xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
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  * $FreeBSD$
22  */
23 
24 /*
25  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
26  * Copyright (c) 2016, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
28  */
29 
30 /*
31  * DTrace - Dynamic Tracing for Solaris
32  *
33  * This is the implementation of the Solaris Dynamic Tracing framework
34  * (DTrace).  The user-visible interface to DTrace is described at length in
35  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
36  * library, the in-kernel DTrace framework, and the DTrace providers are
37  * described in the block comments in the <sys/dtrace.h> header file.  The
38  * internal architecture of DTrace is described in the block comments in the
39  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
40  * implementation very much assume mastery of all of these sources; if one has
41  * an unanswered question about the implementation, one should consult them
42  * first.
43  *
44  * The functions here are ordered roughly as follows:
45  *
46  *   - Probe context functions
47  *   - Probe hashing functions
48  *   - Non-probe context utility functions
49  *   - Matching functions
50  *   - Provider-to-Framework API functions
51  *   - Probe management functions
52  *   - DIF object functions
53  *   - Format functions
54  *   - Predicate functions
55  *   - ECB functions
56  *   - Buffer functions
57  *   - Enabling functions
58  *   - DOF functions
59  *   - Anonymous enabling functions
60  *   - Consumer state functions
61  *   - Helper functions
62  *   - Hook functions
63  *   - Driver cookbook functions
64  *
65  * Each group of functions begins with a block comment labelled the "DTrace
66  * [Group] Functions", allowing one to find each block by searching forward
67  * on capital-f functions.
68  */
69 #include <sys/errno.h>
70 #include <sys/param.h>
71 #include <sys/types.h>
72 #ifndef illumos
73 #include <sys/time.h>
74 #endif
75 #include <sys/stat.h>
76 #include <sys/conf.h>
77 #include <sys/systm.h>
78 #include <sys/endian.h>
79 #ifdef illumos
80 #include <sys/ddi.h>
81 #include <sys/sunddi.h>
82 #endif
83 #include <sys/cpuvar.h>
84 #include <sys/kmem.h>
85 #ifdef illumos
86 #include <sys/strsubr.h>
87 #endif
88 #include <sys/sysmacros.h>
89 #include <sys/dtrace_impl.h>
90 #include <sys/atomic.h>
91 #include <sys/cmn_err.h>
92 #ifdef illumos
93 #include <sys/mutex_impl.h>
94 #include <sys/rwlock_impl.h>
95 #endif
96 #include <sys/ctf_api.h>
97 #ifdef illumos
98 #include <sys/panic.h>
99 #include <sys/priv_impl.h>
100 #endif
101 #ifdef illumos
102 #include <sys/cred_impl.h>
103 #include <sys/procfs_isa.h>
104 #endif
105 #include <sys/taskq.h>
106 #ifdef illumos
107 #include <sys/mkdev.h>
108 #include <sys/kdi.h>
109 #endif
110 #include <sys/zone.h>
111 #include <sys/socket.h>
112 #include <netinet/in.h>
113 #include "strtolctype.h"
114 
115 /* FreeBSD includes: */
116 #ifndef illumos
117 #include <sys/callout.h>
118 #include <sys/ctype.h>
119 #include <sys/eventhandler.h>
120 #include <sys/limits.h>
121 #include <sys/linker.h>
122 #include <sys/kdb.h>
123 #include <sys/jail.h>
124 #include <sys/kernel.h>
125 #include <sys/malloc.h>
126 #include <sys/lock.h>
127 #include <sys/mutex.h>
128 #include <sys/ptrace.h>
129 #include <sys/random.h>
130 #include <sys/rwlock.h>
131 #include <sys/sx.h>
132 #include <sys/sysctl.h>
133 
134 
135 #include <sys/mount.h>
136 #undef AT_UID
137 #undef AT_GID
138 #include <sys/vnode.h>
139 #include <sys/cred.h>
140 
141 #include <sys/dtrace_bsd.h>
142 
143 #include <netinet/in.h>
144 
145 #include "dtrace_cddl.h"
146 #include "dtrace_debug.c"
147 #endif
148 
149 #include "dtrace_xoroshiro128_plus.h"
150 
151 /*
152  * DTrace Tunable Variables
153  *
154  * The following variables may be tuned by adding a line to /etc/system that
155  * includes both the name of the DTrace module ("dtrace") and the name of the
156  * variable.  For example:
157  *
158  *   set dtrace:dtrace_destructive_disallow = 1
159  *
160  * In general, the only variables that one should be tuning this way are those
161  * that affect system-wide DTrace behavior, and for which the default behavior
162  * is undesirable.  Most of these variables are tunable on a per-consumer
163  * basis using DTrace options, and need not be tuned on a system-wide basis.
164  * When tuning these variables, avoid pathological values; while some attempt
165  * is made to verify the integrity of these variables, they are not considered
166  * part of the supported interface to DTrace, and they are therefore not
167  * checked comprehensively.  Further, these variables should not be tuned
168  * dynamically via "mdb -kw" or other means; they should only be tuned via
169  * /etc/system.
170  */
171 int		dtrace_destructive_disallow = 0;
172 #ifndef illumos
173 /* Positive logic version of dtrace_destructive_disallow for loader tunable */
174 int		dtrace_allow_destructive = 1;
175 #endif
176 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
177 size_t		dtrace_difo_maxsize = (256 * 1024);
178 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
179 size_t		dtrace_statvar_maxsize = (16 * 1024);
180 size_t		dtrace_actions_max = (16 * 1024);
181 size_t		dtrace_retain_max = 1024;
182 dtrace_optval_t	dtrace_helper_actions_max = 128;
183 dtrace_optval_t	dtrace_helper_providers_max = 32;
184 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
185 size_t		dtrace_strsize_default = 256;
186 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
187 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
188 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
189 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
190 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
191 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
192 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
193 dtrace_optval_t	dtrace_nspec_default = 1;
194 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
195 dtrace_optval_t dtrace_stackframes_default = 20;
196 dtrace_optval_t dtrace_ustackframes_default = 20;
197 dtrace_optval_t dtrace_jstackframes_default = 50;
198 dtrace_optval_t dtrace_jstackstrsize_default = 512;
199 int		dtrace_msgdsize_max = 128;
200 hrtime_t	dtrace_chill_max = MSEC2NSEC(500);		/* 500 ms */
201 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
202 int		dtrace_devdepth_max = 32;
203 int		dtrace_err_verbose;
204 hrtime_t	dtrace_deadman_interval = NANOSEC;
205 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
206 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
207 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
208 #ifndef illumos
209 int		dtrace_memstr_max = 4096;
210 int		dtrace_bufsize_max_frac = 128;
211 #endif
212 
213 /*
214  * DTrace External Variables
215  *
216  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
217  * available to DTrace consumers via the backtick (`) syntax.  One of these,
218  * dtrace_zero, is made deliberately so:  it is provided as a source of
219  * well-known, zero-filled memory.  While this variable is not documented,
220  * it is used by some translators as an implementation detail.
221  */
222 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
223 
224 /*
225  * DTrace Internal Variables
226  */
227 #ifdef illumos
228 static dev_info_t	*dtrace_devi;		/* device info */
229 #endif
230 #ifdef illumos
231 static vmem_t		*dtrace_arena;		/* probe ID arena */
232 static vmem_t		*dtrace_minor;		/* minor number arena */
233 #else
234 static taskq_t		*dtrace_taskq;		/* task queue */
235 static struct unrhdr	*dtrace_arena;		/* Probe ID number.     */
236 #endif
237 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
238 static int		dtrace_nprobes;		/* number of probes */
239 static dtrace_provider_t *dtrace_provider;	/* provider list */
240 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
241 static int		dtrace_opens;		/* number of opens */
242 static int		dtrace_helpers;		/* number of helpers */
243 static int		dtrace_getf;		/* number of unpriv getf()s */
244 #ifdef illumos
245 static void		*dtrace_softstate;	/* softstate pointer */
246 #endif
247 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
248 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
249 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
250 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
251 static int		dtrace_toxranges;	/* number of toxic ranges */
252 static int		dtrace_toxranges_max;	/* size of toxic range array */
253 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
254 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
255 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
256 static kthread_t	*dtrace_panicked;	/* panicking thread */
257 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
258 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
259 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
260 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
261 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
262 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
263 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
264 #ifndef illumos
265 static struct mtx	dtrace_unr_mtx;
266 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
267 static eventhandler_tag	dtrace_kld_load_tag;
268 static eventhandler_tag	dtrace_kld_unload_try_tag;
269 #endif
270 
271 /*
272  * DTrace Locking
273  * DTrace is protected by three (relatively coarse-grained) locks:
274  *
275  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
276  *     including enabling state, probes, ECBs, consumer state, helper state,
277  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
278  *     probe context is lock-free -- synchronization is handled via the
279  *     dtrace_sync() cross call mechanism.
280  *
281  * (2) dtrace_provider_lock is required when manipulating provider state, or
282  *     when provider state must be held constant.
283  *
284  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
285  *     when meta provider state must be held constant.
286  *
287  * The lock ordering between these three locks is dtrace_meta_lock before
288  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
289  * several places where dtrace_provider_lock is held by the framework as it
290  * calls into the providers -- which then call back into the framework,
291  * grabbing dtrace_lock.)
292  *
293  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
294  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
295  * role as a coarse-grained lock; it is acquired before both of these locks.
296  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
297  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
298  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
299  * acquired _between_ dtrace_provider_lock and dtrace_lock.
300  */
301 static kmutex_t		dtrace_lock;		/* probe state lock */
302 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
303 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
304 
305 #ifndef illumos
306 /* XXX FreeBSD hacks. */
307 #define cr_suid		cr_svuid
308 #define cr_sgid		cr_svgid
309 #define	ipaddr_t	in_addr_t
310 #define mod_modname	pathname
311 #define vuprintf	vprintf
312 #ifndef crgetzoneid
313 #define crgetzoneid(_a)        0
314 #endif
315 #define ttoproc(_a)	((_a)->td_proc)
316 #define SNOCD		0
317 #define CPU_ON_INTR(_a)	0
318 
319 #define PRIV_EFFECTIVE		(1 << 0)
320 #define PRIV_DTRACE_KERNEL	(1 << 1)
321 #define PRIV_DTRACE_PROC	(1 << 2)
322 #define PRIV_DTRACE_USER	(1 << 3)
323 #define PRIV_PROC_OWNER		(1 << 4)
324 #define PRIV_PROC_ZONE		(1 << 5)
325 #define PRIV_ALL		~0
326 
327 SYSCTL_DECL(_debug_dtrace);
328 SYSCTL_DECL(_kern_dtrace);
329 #endif
330 
331 #ifdef illumos
332 #define curcpu	CPU->cpu_id
333 #endif
334 
335 
336 /*
337  * DTrace Provider Variables
338  *
339  * These are the variables relating to DTrace as a provider (that is, the
340  * provider of the BEGIN, END, and ERROR probes).
341  */
342 static dtrace_pattr_t	dtrace_provider_attr = {
343 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
344 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
345 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
346 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
347 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
348 };
349 
350 static void
351 dtrace_nullop(void)
352 {}
353 
354 static dtrace_pops_t dtrace_provider_ops = {
355 	.dtps_provide =	(void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
356 	.dtps_provide_module =	(void (*)(void *, modctl_t *))dtrace_nullop,
357 	.dtps_enable =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
358 	.dtps_disable =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
359 	.dtps_suspend =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
360 	.dtps_resume =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
361 	.dtps_getargdesc =	NULL,
362 	.dtps_getargval =	NULL,
363 	.dtps_usermode =	NULL,
364 	.dtps_destroy =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
365 };
366 
367 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
368 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
369 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
370 
371 /*
372  * DTrace Helper Tracing Variables
373  *
374  * These variables should be set dynamically to enable helper tracing.  The
375  * only variables that should be set are dtrace_helptrace_enable (which should
376  * be set to a non-zero value to allocate helper tracing buffers on the next
377  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
378  * non-zero value to deallocate helper tracing buffers on the next close of
379  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
380  * buffer size may also be set via dtrace_helptrace_bufsize.
381  */
382 int			dtrace_helptrace_enable = 0;
383 int			dtrace_helptrace_disable = 0;
384 int			dtrace_helptrace_bufsize = 16 * 1024 * 1024;
385 uint32_t		dtrace_helptrace_nlocals;
386 static dtrace_helptrace_t *dtrace_helptrace_buffer;
387 static uint32_t		dtrace_helptrace_next = 0;
388 static int		dtrace_helptrace_wrapped = 0;
389 
390 /*
391  * DTrace Error Hashing
392  *
393  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
394  * table.  This is very useful for checking coverage of tests that are
395  * expected to induce DIF or DOF processing errors, and may be useful for
396  * debugging problems in the DIF code generator or in DOF generation .  The
397  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
398  */
399 #ifdef DEBUG
400 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
401 static const char *dtrace_errlast;
402 static kthread_t *dtrace_errthread;
403 static kmutex_t dtrace_errlock;
404 #endif
405 
406 /*
407  * DTrace Macros and Constants
408  *
409  * These are various macros that are useful in various spots in the
410  * implementation, along with a few random constants that have no meaning
411  * outside of the implementation.  There is no real structure to this cpp
412  * mishmash -- but is there ever?
413  */
414 #define	DTRACE_HASHSTR(hash, probe)	\
415 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
416 
417 #define	DTRACE_HASHNEXT(hash, probe)	\
418 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
419 
420 #define	DTRACE_HASHPREV(hash, probe)	\
421 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
422 
423 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
424 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
425 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
426 
427 #define	DTRACE_AGGHASHSIZE_SLEW		17
428 
429 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
430 
431 /*
432  * The key for a thread-local variable consists of the lower 61 bits of the
433  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
434  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
435  * equal to a variable identifier.  This is necessary (but not sufficient) to
436  * assure that global associative arrays never collide with thread-local
437  * variables.  To guarantee that they cannot collide, we must also define the
438  * order for keying dynamic variables.  That order is:
439  *
440  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
441  *
442  * Because the variable-key and the tls-key are in orthogonal spaces, there is
443  * no way for a global variable key signature to match a thread-local key
444  * signature.
445  */
446 #ifdef illumos
447 #define	DTRACE_TLS_THRKEY(where) { \
448 	uint_t intr = 0; \
449 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
450 	for (; actv; actv >>= 1) \
451 		intr++; \
452 	ASSERT(intr < (1 << 3)); \
453 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
454 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
455 }
456 #else
457 #define	DTRACE_TLS_THRKEY(where) { \
458 	solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
459 	uint_t intr = 0; \
460 	uint_t actv = _c->cpu_intr_actv; \
461 	for (; actv; actv >>= 1) \
462 		intr++; \
463 	ASSERT(intr < (1 << 3)); \
464 	(where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
465 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
466 }
467 #endif
468 
469 #define	DT_BSWAP_8(x)	((x) & 0xff)
470 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
471 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
472 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
473 
474 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
475 
476 #define	DTRACE_STORE(type, tomax, offset, what) \
477 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
478 
479 #if !defined(__x86) && !defined(__aarch64__)
480 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
481 	if (addr & (size - 1)) {					\
482 		*flags |= CPU_DTRACE_BADALIGN;				\
483 		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
484 		return (0);						\
485 	}
486 #else
487 #define	DTRACE_ALIGNCHECK(addr, size, flags)
488 #endif
489 
490 /*
491  * Test whether a range of memory starting at testaddr of size testsz falls
492  * within the range of memory described by addr, sz.  We take care to avoid
493  * problems with overflow and underflow of the unsigned quantities, and
494  * disallow all negative sizes.  Ranges of size 0 are allowed.
495  */
496 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
497 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
498 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
499 	(testaddr) + (testsz) >= (testaddr))
500 
501 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
502 do {									\
503 	if ((remp) != NULL) {						\
504 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
505 	}								\
506 } while (0)
507 
508 
509 /*
510  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
511  * alloc_sz on the righthand side of the comparison in order to avoid overflow
512  * or underflow in the comparison with it.  This is simpler than the INRANGE
513  * check above, because we know that the dtms_scratch_ptr is valid in the
514  * range.  Allocations of size zero are allowed.
515  */
516 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
517 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
518 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
519 
520 #define	DTRACE_LOADFUNC(bits)						\
521 /*CSTYLED*/								\
522 uint##bits##_t								\
523 dtrace_load##bits(uintptr_t addr)					\
524 {									\
525 	size_t size = bits / NBBY;					\
526 	/*CSTYLED*/							\
527 	uint##bits##_t rval;						\
528 	int i;								\
529 	volatile uint16_t *flags = (volatile uint16_t *)		\
530 	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
531 									\
532 	DTRACE_ALIGNCHECK(addr, size, flags);				\
533 									\
534 	for (i = 0; i < dtrace_toxranges; i++) {			\
535 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
536 			continue;					\
537 									\
538 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
539 			continue;					\
540 									\
541 		/*							\
542 		 * This address falls within a toxic region; return 0.	\
543 		 */							\
544 		*flags |= CPU_DTRACE_BADADDR;				\
545 		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
546 		return (0);						\
547 	}								\
548 									\
549 	*flags |= CPU_DTRACE_NOFAULT;					\
550 	/*CSTYLED*/							\
551 	rval = *((volatile uint##bits##_t *)addr);			\
552 	*flags &= ~CPU_DTRACE_NOFAULT;					\
553 									\
554 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
555 }
556 
557 #ifdef _LP64
558 #define	dtrace_loadptr	dtrace_load64
559 #else
560 #define	dtrace_loadptr	dtrace_load32
561 #endif
562 
563 #define	DTRACE_DYNHASH_FREE	0
564 #define	DTRACE_DYNHASH_SINK	1
565 #define	DTRACE_DYNHASH_VALID	2
566 
567 #define	DTRACE_MATCH_NEXT	0
568 #define	DTRACE_MATCH_DONE	1
569 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
570 #define	DTRACE_STATE_ALIGN	64
571 
572 #define	DTRACE_FLAGS2FLT(flags)						\
573 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
574 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
575 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
576 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
577 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
578 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
579 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
580 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
581 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
582 	DTRACEFLT_UNKNOWN)
583 
584 #define	DTRACEACT_ISSTRING(act)						\
585 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
586 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
587 
588 /* Function prototype definitions: */
589 static size_t dtrace_strlen(const char *, size_t);
590 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
591 static void dtrace_enabling_provide(dtrace_provider_t *);
592 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
593 static void dtrace_enabling_matchall(void);
594 static void dtrace_enabling_reap(void);
595 static dtrace_state_t *dtrace_anon_grab(void);
596 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
597     dtrace_state_t *, uint64_t, uint64_t);
598 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
599 static void dtrace_buffer_drop(dtrace_buffer_t *);
600 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
601 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
602     dtrace_state_t *, dtrace_mstate_t *);
603 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
604     dtrace_optval_t);
605 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
606 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
607 uint16_t dtrace_load16(uintptr_t);
608 uint32_t dtrace_load32(uintptr_t);
609 uint64_t dtrace_load64(uintptr_t);
610 uint8_t dtrace_load8(uintptr_t);
611 void dtrace_dynvar_clean(dtrace_dstate_t *);
612 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
613     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
614 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
615 static int dtrace_priv_proc(dtrace_state_t *);
616 static void dtrace_getf_barrier(void);
617 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
618     dtrace_mstate_t *, dtrace_vstate_t *);
619 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
620     dtrace_mstate_t *, dtrace_vstate_t *);
621 
622 /*
623  * DTrace Probe Context Functions
624  *
625  * These functions are called from probe context.  Because probe context is
626  * any context in which C may be called, arbitrarily locks may be held,
627  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
628  * As a result, functions called from probe context may only call other DTrace
629  * support functions -- they may not interact at all with the system at large.
630  * (Note that the ASSERT macro is made probe-context safe by redefining it in
631  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
632  * loads are to be performed from probe context, they _must_ be in terms of
633  * the safe dtrace_load*() variants.
634  *
635  * Some functions in this block are not actually called from probe context;
636  * for these functions, there will be a comment above the function reading
637  * "Note:  not called from probe context."
638  */
639 void
640 dtrace_panic(const char *format, ...)
641 {
642 	va_list alist;
643 
644 	va_start(alist, format);
645 #ifdef __FreeBSD__
646 	vpanic(format, alist);
647 #else
648 	dtrace_vpanic(format, alist);
649 #endif
650 	va_end(alist);
651 }
652 
653 int
654 dtrace_assfail(const char *a, const char *f, int l)
655 {
656 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
657 
658 	/*
659 	 * We just need something here that even the most clever compiler
660 	 * cannot optimize away.
661 	 */
662 	return (a[(uintptr_t)f]);
663 }
664 
665 /*
666  * Atomically increment a specified error counter from probe context.
667  */
668 static void
669 dtrace_error(uint32_t *counter)
670 {
671 	/*
672 	 * Most counters stored to in probe context are per-CPU counters.
673 	 * However, there are some error conditions that are sufficiently
674 	 * arcane that they don't merit per-CPU storage.  If these counters
675 	 * are incremented concurrently on different CPUs, scalability will be
676 	 * adversely affected -- but we don't expect them to be white-hot in a
677 	 * correctly constructed enabling...
678 	 */
679 	uint32_t oval, nval;
680 
681 	do {
682 		oval = *counter;
683 
684 		if ((nval = oval + 1) == 0) {
685 			/*
686 			 * If the counter would wrap, set it to 1 -- assuring
687 			 * that the counter is never zero when we have seen
688 			 * errors.  (The counter must be 32-bits because we
689 			 * aren't guaranteed a 64-bit compare&swap operation.)
690 			 * To save this code both the infamy of being fingered
691 			 * by a priggish news story and the indignity of being
692 			 * the target of a neo-puritan witch trial, we're
693 			 * carefully avoiding any colorful description of the
694 			 * likelihood of this condition -- but suffice it to
695 			 * say that it is only slightly more likely than the
696 			 * overflow of predicate cache IDs, as discussed in
697 			 * dtrace_predicate_create().
698 			 */
699 			nval = 1;
700 		}
701 	} while (dtrace_cas32(counter, oval, nval) != oval);
702 }
703 
704 /*
705  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
706  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
707  */
708 /* BEGIN CSTYLED */
709 DTRACE_LOADFUNC(8)
710 DTRACE_LOADFUNC(16)
711 DTRACE_LOADFUNC(32)
712 DTRACE_LOADFUNC(64)
713 /* END CSTYLED */
714 
715 static int
716 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
717 {
718 	if (dest < mstate->dtms_scratch_base)
719 		return (0);
720 
721 	if (dest + size < dest)
722 		return (0);
723 
724 	if (dest + size > mstate->dtms_scratch_ptr)
725 		return (0);
726 
727 	return (1);
728 }
729 
730 static int
731 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
732     dtrace_statvar_t **svars, int nsvars)
733 {
734 	int i;
735 	size_t maxglobalsize, maxlocalsize;
736 
737 	if (nsvars == 0)
738 		return (0);
739 
740 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
741 	maxlocalsize = maxglobalsize * NCPU;
742 
743 	for (i = 0; i < nsvars; i++) {
744 		dtrace_statvar_t *svar = svars[i];
745 		uint8_t scope;
746 		size_t size;
747 
748 		if (svar == NULL || (size = svar->dtsv_size) == 0)
749 			continue;
750 
751 		scope = svar->dtsv_var.dtdv_scope;
752 
753 		/*
754 		 * We verify that our size is valid in the spirit of providing
755 		 * defense in depth:  we want to prevent attackers from using
756 		 * DTrace to escalate an orthogonal kernel heap corruption bug
757 		 * into the ability to store to arbitrary locations in memory.
758 		 */
759 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
760 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
761 
762 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
763 		    svar->dtsv_size)) {
764 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
765 			    svar->dtsv_size);
766 			return (1);
767 		}
768 	}
769 
770 	return (0);
771 }
772 
773 /*
774  * Check to see if the address is within a memory region to which a store may
775  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
776  * region.  The caller of dtrace_canstore() is responsible for performing any
777  * alignment checks that are needed before stores are actually executed.
778  */
779 static int
780 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
781     dtrace_vstate_t *vstate)
782 {
783 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
784 }
785 
786 /*
787  * Implementation of dtrace_canstore which communicates the upper bound of the
788  * allowed memory region.
789  */
790 static int
791 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
792     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
793 {
794 	/*
795 	 * First, check to see if the address is in scratch space...
796 	 */
797 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
798 	    mstate->dtms_scratch_size)) {
799 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
800 		    mstate->dtms_scratch_size);
801 		return (1);
802 	}
803 
804 	/*
805 	 * Now check to see if it's a dynamic variable.  This check will pick
806 	 * up both thread-local variables and any global dynamically-allocated
807 	 * variables.
808 	 */
809 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
810 	    vstate->dtvs_dynvars.dtds_size)) {
811 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
812 		uintptr_t base = (uintptr_t)dstate->dtds_base +
813 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
814 		uintptr_t chunkoffs;
815 		dtrace_dynvar_t *dvar;
816 
817 		/*
818 		 * Before we assume that we can store here, we need to make
819 		 * sure that it isn't in our metadata -- storing to our
820 		 * dynamic variable metadata would corrupt our state.  For
821 		 * the range to not include any dynamic variable metadata,
822 		 * it must:
823 		 *
824 		 *	(1) Start above the hash table that is at the base of
825 		 *	the dynamic variable space
826 		 *
827 		 *	(2) Have a starting chunk offset that is beyond the
828 		 *	dtrace_dynvar_t that is at the base of every chunk
829 		 *
830 		 *	(3) Not span a chunk boundary
831 		 *
832 		 *	(4) Not be in the tuple space of a dynamic variable
833 		 *
834 		 */
835 		if (addr < base)
836 			return (0);
837 
838 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
839 
840 		if (chunkoffs < sizeof (dtrace_dynvar_t))
841 			return (0);
842 
843 		if (chunkoffs + sz > dstate->dtds_chunksize)
844 			return (0);
845 
846 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
847 
848 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
849 			return (0);
850 
851 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
852 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
853 			return (0);
854 
855 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
856 		return (1);
857 	}
858 
859 	/*
860 	 * Finally, check the static local and global variables.  These checks
861 	 * take the longest, so we perform them last.
862 	 */
863 	if (dtrace_canstore_statvar(addr, sz, remain,
864 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
865 		return (1);
866 
867 	if (dtrace_canstore_statvar(addr, sz, remain,
868 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
869 		return (1);
870 
871 	return (0);
872 }
873 
874 
875 /*
876  * Convenience routine to check to see if the address is within a memory
877  * region in which a load may be issued given the user's privilege level;
878  * if not, it sets the appropriate error flags and loads 'addr' into the
879  * illegal value slot.
880  *
881  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
882  * appropriate memory access protection.
883  */
884 static int
885 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
886     dtrace_vstate_t *vstate)
887 {
888 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
889 }
890 
891 /*
892  * Implementation of dtrace_canload which communicates the uppoer bound of the
893  * allowed memory region.
894  */
895 static int
896 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
897     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
898 {
899 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
900 	file_t *fp;
901 
902 	/*
903 	 * If we hold the privilege to read from kernel memory, then
904 	 * everything is readable.
905 	 */
906 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
907 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
908 		return (1);
909 	}
910 
911 	/*
912 	 * You can obviously read that which you can store.
913 	 */
914 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
915 		return (1);
916 
917 	/*
918 	 * We're allowed to read from our own string table.
919 	 */
920 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
921 	    mstate->dtms_difo->dtdo_strlen)) {
922 		DTRACE_RANGE_REMAIN(remain, addr,
923 		    mstate->dtms_difo->dtdo_strtab,
924 		    mstate->dtms_difo->dtdo_strlen);
925 		return (1);
926 	}
927 
928 	if (vstate->dtvs_state != NULL &&
929 	    dtrace_priv_proc(vstate->dtvs_state)) {
930 		proc_t *p;
931 
932 		/*
933 		 * When we have privileges to the current process, there are
934 		 * several context-related kernel structures that are safe to
935 		 * read, even absent the privilege to read from kernel memory.
936 		 * These reads are safe because these structures contain only
937 		 * state that (1) we're permitted to read, (2) is harmless or
938 		 * (3) contains pointers to additional kernel state that we're
939 		 * not permitted to read (and as such, do not present an
940 		 * opportunity for privilege escalation).  Finally (and
941 		 * critically), because of the nature of their relation with
942 		 * the current thread context, the memory associated with these
943 		 * structures cannot change over the duration of probe context,
944 		 * and it is therefore impossible for this memory to be
945 		 * deallocated and reallocated as something else while it's
946 		 * being operated upon.
947 		 */
948 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
949 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
950 			    sizeof (kthread_t));
951 			return (1);
952 		}
953 
954 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
955 		    sz, curthread->t_procp, sizeof (proc_t))) {
956 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
957 			    sizeof (proc_t));
958 			return (1);
959 		}
960 
961 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
962 		    curthread->t_cred, sizeof (cred_t))) {
963 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
964 			    sizeof (cred_t));
965 			return (1);
966 		}
967 
968 #ifdef illumos
969 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
970 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
971 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
972 			    sizeof (pid_t));
973 			return (1);
974 		}
975 
976 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
977 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
978 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
979 			    offsetof(cpu_t, cpu_pause_thread));
980 			return (1);
981 		}
982 #endif
983 	}
984 
985 	if ((fp = mstate->dtms_getf) != NULL) {
986 		uintptr_t psz = sizeof (void *);
987 		vnode_t *vp;
988 		vnodeops_t *op;
989 
990 		/*
991 		 * When getf() returns a file_t, the enabling is implicitly
992 		 * granted the (transient) right to read the returned file_t
993 		 * as well as the v_path and v_op->vnop_name of the underlying
994 		 * vnode.  These accesses are allowed after a successful
995 		 * getf() because the members that they refer to cannot change
996 		 * once set -- and the barrier logic in the kernel's closef()
997 		 * path assures that the file_t and its referenced vode_t
998 		 * cannot themselves be stale (that is, it impossible for
999 		 * either dtms_getf itself or its f_vnode member to reference
1000 		 * freed memory).
1001 		 */
1002 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1003 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1004 			return (1);
1005 		}
1006 
1007 		if ((vp = fp->f_vnode) != NULL) {
1008 			size_t slen;
1009 #ifdef illumos
1010 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1011 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1012 				    psz);
1013 				return (1);
1014 			}
1015 			slen = strlen(vp->v_path) + 1;
1016 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1017 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1018 				    slen);
1019 				return (1);
1020 			}
1021 #endif
1022 
1023 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1024 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1025 				    psz);
1026 				return (1);
1027 			}
1028 
1029 #ifdef illumos
1030 			if ((op = vp->v_op) != NULL &&
1031 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1032 				DTRACE_RANGE_REMAIN(remain, addr,
1033 				    &op->vnop_name, psz);
1034 				return (1);
1035 			}
1036 
1037 			if (op != NULL && op->vnop_name != NULL &&
1038 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
1039 			    (slen = strlen(op->vnop_name) + 1))) {
1040 				DTRACE_RANGE_REMAIN(remain, addr,
1041 				    op->vnop_name, slen);
1042 				return (1);
1043 			}
1044 #endif
1045 		}
1046 	}
1047 
1048 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1049 	*illval = addr;
1050 	return (0);
1051 }
1052 
1053 /*
1054  * Convenience routine to check to see if a given string is within a memory
1055  * region in which a load may be issued given the user's privilege level;
1056  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1057  * calls in the event that the user has all privileges.
1058  */
1059 static int
1060 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1061     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1062 {
1063 	size_t rsize;
1064 
1065 	/*
1066 	 * If we hold the privilege to read from kernel memory, then
1067 	 * everything is readable.
1068 	 */
1069 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1070 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1071 		return (1);
1072 	}
1073 
1074 	/*
1075 	 * Even if the caller is uninterested in querying the remaining valid
1076 	 * range, it is required to ensure that the access is allowed.
1077 	 */
1078 	if (remain == NULL) {
1079 		remain = &rsize;
1080 	}
1081 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1082 		size_t strsz;
1083 		/*
1084 		 * Perform the strlen after determining the length of the
1085 		 * memory region which is accessible.  This prevents timing
1086 		 * information from being used to find NULs in memory which is
1087 		 * not accessible to the caller.
1088 		 */
1089 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1090 		    MIN(sz, *remain));
1091 		if (strsz <= *remain) {
1092 			return (1);
1093 		}
1094 	}
1095 
1096 	return (0);
1097 }
1098 
1099 /*
1100  * Convenience routine to check to see if a given variable is within a memory
1101  * region in which a load may be issued given the user's privilege level.
1102  */
1103 static int
1104 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1105     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1106 {
1107 	size_t sz;
1108 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1109 
1110 	/*
1111 	 * Calculate the max size before performing any checks since even
1112 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1113 	 * return the max length via 'remain'.
1114 	 */
1115 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1116 		dtrace_state_t *state = vstate->dtvs_state;
1117 
1118 		if (state != NULL) {
1119 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1120 		} else {
1121 			/*
1122 			 * In helper context, we have a NULL state; fall back
1123 			 * to using the system-wide default for the string size
1124 			 * in this case.
1125 			 */
1126 			sz = dtrace_strsize_default;
1127 		}
1128 	} else {
1129 		sz = type->dtdt_size;
1130 	}
1131 
1132 	/*
1133 	 * If we hold the privilege to read from kernel memory, then
1134 	 * everything is readable.
1135 	 */
1136 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1137 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1138 		return (1);
1139 	}
1140 
1141 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1142 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1143 		    vstate));
1144 	}
1145 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1146 	    vstate));
1147 }
1148 
1149 /*
1150  * Convert a string to a signed integer using safe loads.
1151  *
1152  * NOTE: This function uses various macros from strtolctype.h to manipulate
1153  * digit values, etc -- these have all been checked to ensure they make
1154  * no additional function calls.
1155  */
1156 static int64_t
1157 dtrace_strtoll(char *input, int base, size_t limit)
1158 {
1159 	uintptr_t pos = (uintptr_t)input;
1160 	int64_t val = 0;
1161 	int x;
1162 	boolean_t neg = B_FALSE;
1163 	char c, cc, ccc;
1164 	uintptr_t end = pos + limit;
1165 
1166 	/*
1167 	 * Consume any whitespace preceding digits.
1168 	 */
1169 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1170 		pos++;
1171 
1172 	/*
1173 	 * Handle an explicit sign if one is present.
1174 	 */
1175 	if (c == '-' || c == '+') {
1176 		if (c == '-')
1177 			neg = B_TRUE;
1178 		c = dtrace_load8(++pos);
1179 	}
1180 
1181 	/*
1182 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1183 	 * if present.
1184 	 */
1185 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1186 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1187 		pos += 2;
1188 		c = ccc;
1189 	}
1190 
1191 	/*
1192 	 * Read in contiguous digits until the first non-digit character.
1193 	 */
1194 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1195 	    c = dtrace_load8(++pos))
1196 		val = val * base + x;
1197 
1198 	return (neg ? -val : val);
1199 }
1200 
1201 /*
1202  * Compare two strings using safe loads.
1203  */
1204 static int
1205 dtrace_strncmp(char *s1, char *s2, size_t limit)
1206 {
1207 	uint8_t c1, c2;
1208 	volatile uint16_t *flags;
1209 
1210 	if (s1 == s2 || limit == 0)
1211 		return (0);
1212 
1213 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1214 
1215 	do {
1216 		if (s1 == NULL) {
1217 			c1 = '\0';
1218 		} else {
1219 			c1 = dtrace_load8((uintptr_t)s1++);
1220 		}
1221 
1222 		if (s2 == NULL) {
1223 			c2 = '\0';
1224 		} else {
1225 			c2 = dtrace_load8((uintptr_t)s2++);
1226 		}
1227 
1228 		if (c1 != c2)
1229 			return (c1 - c2);
1230 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1231 
1232 	return (0);
1233 }
1234 
1235 /*
1236  * Compute strlen(s) for a string using safe memory accesses.  The additional
1237  * len parameter is used to specify a maximum length to ensure completion.
1238  */
1239 static size_t
1240 dtrace_strlen(const char *s, size_t lim)
1241 {
1242 	uint_t len;
1243 
1244 	for (len = 0; len != lim; len++) {
1245 		if (dtrace_load8((uintptr_t)s++) == '\0')
1246 			break;
1247 	}
1248 
1249 	return (len);
1250 }
1251 
1252 /*
1253  * Check if an address falls within a toxic region.
1254  */
1255 static int
1256 dtrace_istoxic(uintptr_t kaddr, size_t size)
1257 {
1258 	uintptr_t taddr, tsize;
1259 	int i;
1260 
1261 	for (i = 0; i < dtrace_toxranges; i++) {
1262 		taddr = dtrace_toxrange[i].dtt_base;
1263 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1264 
1265 		if (kaddr - taddr < tsize) {
1266 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1267 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1268 			return (1);
1269 		}
1270 
1271 		if (taddr - kaddr < size) {
1272 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1273 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1274 			return (1);
1275 		}
1276 	}
1277 
1278 	return (0);
1279 }
1280 
1281 /*
1282  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1283  * memory specified by the DIF program.  The dst is assumed to be safe memory
1284  * that we can store to directly because it is managed by DTrace.  As with
1285  * standard bcopy, overlapping copies are handled properly.
1286  */
1287 static void
1288 dtrace_bcopy(const void *src, void *dst, size_t len)
1289 {
1290 	if (len != 0) {
1291 		uint8_t *s1 = dst;
1292 		const uint8_t *s2 = src;
1293 
1294 		if (s1 <= s2) {
1295 			do {
1296 				*s1++ = dtrace_load8((uintptr_t)s2++);
1297 			} while (--len != 0);
1298 		} else {
1299 			s2 += len;
1300 			s1 += len;
1301 
1302 			do {
1303 				*--s1 = dtrace_load8((uintptr_t)--s2);
1304 			} while (--len != 0);
1305 		}
1306 	}
1307 }
1308 
1309 /*
1310  * Copy src to dst using safe memory accesses, up to either the specified
1311  * length, or the point that a nul byte is encountered.  The src is assumed to
1312  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1313  * safe memory that we can store to directly because it is managed by DTrace.
1314  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1315  */
1316 static void
1317 dtrace_strcpy(const void *src, void *dst, size_t len)
1318 {
1319 	if (len != 0) {
1320 		uint8_t *s1 = dst, c;
1321 		const uint8_t *s2 = src;
1322 
1323 		do {
1324 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1325 		} while (--len != 0 && c != '\0');
1326 	}
1327 }
1328 
1329 /*
1330  * Copy src to dst, deriving the size and type from the specified (BYREF)
1331  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1332  * program.  The dst is assumed to be DTrace variable memory that is of the
1333  * specified type; we assume that we can store to directly.
1334  */
1335 static void
1336 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1337 {
1338 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1339 
1340 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1341 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1342 	} else {
1343 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1344 	}
1345 }
1346 
1347 /*
1348  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1349  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1350  * safe memory that we can access directly because it is managed by DTrace.
1351  */
1352 static int
1353 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1354 {
1355 	volatile uint16_t *flags;
1356 
1357 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1358 
1359 	if (s1 == s2)
1360 		return (0);
1361 
1362 	if (s1 == NULL || s2 == NULL)
1363 		return (1);
1364 
1365 	if (s1 != s2 && len != 0) {
1366 		const uint8_t *ps1 = s1;
1367 		const uint8_t *ps2 = s2;
1368 
1369 		do {
1370 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1371 				return (1);
1372 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1373 	}
1374 	return (0);
1375 }
1376 
1377 /*
1378  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1379  * is for safe DTrace-managed memory only.
1380  */
1381 static void
1382 dtrace_bzero(void *dst, size_t len)
1383 {
1384 	uchar_t *cp;
1385 
1386 	for (cp = dst; len != 0; len--)
1387 		*cp++ = 0;
1388 }
1389 
1390 static void
1391 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1392 {
1393 	uint64_t result[2];
1394 
1395 	result[0] = addend1[0] + addend2[0];
1396 	result[1] = addend1[1] + addend2[1] +
1397 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1398 
1399 	sum[0] = result[0];
1400 	sum[1] = result[1];
1401 }
1402 
1403 /*
1404  * Shift the 128-bit value in a by b. If b is positive, shift left.
1405  * If b is negative, shift right.
1406  */
1407 static void
1408 dtrace_shift_128(uint64_t *a, int b)
1409 {
1410 	uint64_t mask;
1411 
1412 	if (b == 0)
1413 		return;
1414 
1415 	if (b < 0) {
1416 		b = -b;
1417 		if (b >= 64) {
1418 			a[0] = a[1] >> (b - 64);
1419 			a[1] = 0;
1420 		} else {
1421 			a[0] >>= b;
1422 			mask = 1LL << (64 - b);
1423 			mask -= 1;
1424 			a[0] |= ((a[1] & mask) << (64 - b));
1425 			a[1] >>= b;
1426 		}
1427 	} else {
1428 		if (b >= 64) {
1429 			a[1] = a[0] << (b - 64);
1430 			a[0] = 0;
1431 		} else {
1432 			a[1] <<= b;
1433 			mask = a[0] >> (64 - b);
1434 			a[1] |= mask;
1435 			a[0] <<= b;
1436 		}
1437 	}
1438 }
1439 
1440 /*
1441  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1442  * use native multiplication on those, and then re-combine into the
1443  * resulting 128-bit value.
1444  *
1445  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1446  *     hi1 * hi2 << 64 +
1447  *     hi1 * lo2 << 32 +
1448  *     hi2 * lo1 << 32 +
1449  *     lo1 * lo2
1450  */
1451 static void
1452 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1453 {
1454 	uint64_t hi1, hi2, lo1, lo2;
1455 	uint64_t tmp[2];
1456 
1457 	hi1 = factor1 >> 32;
1458 	hi2 = factor2 >> 32;
1459 
1460 	lo1 = factor1 & DT_MASK_LO;
1461 	lo2 = factor2 & DT_MASK_LO;
1462 
1463 	product[0] = lo1 * lo2;
1464 	product[1] = hi1 * hi2;
1465 
1466 	tmp[0] = hi1 * lo2;
1467 	tmp[1] = 0;
1468 	dtrace_shift_128(tmp, 32);
1469 	dtrace_add_128(product, tmp, product);
1470 
1471 	tmp[0] = hi2 * lo1;
1472 	tmp[1] = 0;
1473 	dtrace_shift_128(tmp, 32);
1474 	dtrace_add_128(product, tmp, product);
1475 }
1476 
1477 /*
1478  * This privilege check should be used by actions and subroutines to
1479  * verify that the user credentials of the process that enabled the
1480  * invoking ECB match the target credentials
1481  */
1482 static int
1483 dtrace_priv_proc_common_user(dtrace_state_t *state)
1484 {
1485 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1486 
1487 	/*
1488 	 * We should always have a non-NULL state cred here, since if cred
1489 	 * is null (anonymous tracing), we fast-path bypass this routine.
1490 	 */
1491 	ASSERT(s_cr != NULL);
1492 
1493 	if ((cr = CRED()) != NULL &&
1494 	    s_cr->cr_uid == cr->cr_uid &&
1495 	    s_cr->cr_uid == cr->cr_ruid &&
1496 	    s_cr->cr_uid == cr->cr_suid &&
1497 	    s_cr->cr_gid == cr->cr_gid &&
1498 	    s_cr->cr_gid == cr->cr_rgid &&
1499 	    s_cr->cr_gid == cr->cr_sgid)
1500 		return (1);
1501 
1502 	return (0);
1503 }
1504 
1505 /*
1506  * This privilege check should be used by actions and subroutines to
1507  * verify that the zone of the process that enabled the invoking ECB
1508  * matches the target credentials
1509  */
1510 static int
1511 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1512 {
1513 #ifdef illumos
1514 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1515 
1516 	/*
1517 	 * We should always have a non-NULL state cred here, since if cred
1518 	 * is null (anonymous tracing), we fast-path bypass this routine.
1519 	 */
1520 	ASSERT(s_cr != NULL);
1521 
1522 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1523 		return (1);
1524 
1525 	return (0);
1526 #else
1527 	return (1);
1528 #endif
1529 }
1530 
1531 /*
1532  * This privilege check should be used by actions and subroutines to
1533  * verify that the process has not setuid or changed credentials.
1534  */
1535 static int
1536 dtrace_priv_proc_common_nocd(void)
1537 {
1538 	proc_t *proc;
1539 
1540 	if ((proc = ttoproc(curthread)) != NULL &&
1541 	    !(proc->p_flag & SNOCD))
1542 		return (1);
1543 
1544 	return (0);
1545 }
1546 
1547 static int
1548 dtrace_priv_proc_destructive(dtrace_state_t *state)
1549 {
1550 	int action = state->dts_cred.dcr_action;
1551 
1552 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1553 	    dtrace_priv_proc_common_zone(state) == 0)
1554 		goto bad;
1555 
1556 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1557 	    dtrace_priv_proc_common_user(state) == 0)
1558 		goto bad;
1559 
1560 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1561 	    dtrace_priv_proc_common_nocd() == 0)
1562 		goto bad;
1563 
1564 	return (1);
1565 
1566 bad:
1567 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1568 
1569 	return (0);
1570 }
1571 
1572 static int
1573 dtrace_priv_proc_control(dtrace_state_t *state)
1574 {
1575 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1576 		return (1);
1577 
1578 	if (dtrace_priv_proc_common_zone(state) &&
1579 	    dtrace_priv_proc_common_user(state) &&
1580 	    dtrace_priv_proc_common_nocd())
1581 		return (1);
1582 
1583 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1584 
1585 	return (0);
1586 }
1587 
1588 static int
1589 dtrace_priv_proc(dtrace_state_t *state)
1590 {
1591 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1592 		return (1);
1593 
1594 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1595 
1596 	return (0);
1597 }
1598 
1599 static int
1600 dtrace_priv_kernel(dtrace_state_t *state)
1601 {
1602 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1603 		return (1);
1604 
1605 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1606 
1607 	return (0);
1608 }
1609 
1610 static int
1611 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1612 {
1613 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1614 		return (1);
1615 
1616 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1617 
1618 	return (0);
1619 }
1620 
1621 /*
1622  * Determine if the dte_cond of the specified ECB allows for processing of
1623  * the current probe to continue.  Note that this routine may allow continued
1624  * processing, but with access(es) stripped from the mstate's dtms_access
1625  * field.
1626  */
1627 static int
1628 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1629     dtrace_ecb_t *ecb)
1630 {
1631 	dtrace_probe_t *probe = ecb->dte_probe;
1632 	dtrace_provider_t *prov = probe->dtpr_provider;
1633 	dtrace_pops_t *pops = &prov->dtpv_pops;
1634 	int mode = DTRACE_MODE_NOPRIV_DROP;
1635 
1636 	ASSERT(ecb->dte_cond);
1637 
1638 #ifdef illumos
1639 	if (pops->dtps_mode != NULL) {
1640 		mode = pops->dtps_mode(prov->dtpv_arg,
1641 		    probe->dtpr_id, probe->dtpr_arg);
1642 
1643 		ASSERT((mode & DTRACE_MODE_USER) ||
1644 		    (mode & DTRACE_MODE_KERNEL));
1645 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1646 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1647 	}
1648 
1649 	/*
1650 	 * If the dte_cond bits indicate that this consumer is only allowed to
1651 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1652 	 * entry point to check that the probe was fired while in a user
1653 	 * context.  If that's not the case, use the policy specified by the
1654 	 * provider to determine if we drop the probe or merely restrict
1655 	 * operation.
1656 	 */
1657 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1658 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1659 
1660 		if (!(mode & DTRACE_MODE_USER)) {
1661 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1662 				return (0);
1663 
1664 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1665 		}
1666 	}
1667 #endif
1668 
1669 	/*
1670 	 * This is more subtle than it looks. We have to be absolutely certain
1671 	 * that CRED() isn't going to change out from under us so it's only
1672 	 * legit to examine that structure if we're in constrained situations.
1673 	 * Currently, the only times we'll this check is if a non-super-user
1674 	 * has enabled the profile or syscall providers -- providers that
1675 	 * allow visibility of all processes. For the profile case, the check
1676 	 * above will ensure that we're examining a user context.
1677 	 */
1678 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1679 		cred_t *cr;
1680 		cred_t *s_cr = state->dts_cred.dcr_cred;
1681 		proc_t *proc;
1682 
1683 		ASSERT(s_cr != NULL);
1684 
1685 		if ((cr = CRED()) == NULL ||
1686 		    s_cr->cr_uid != cr->cr_uid ||
1687 		    s_cr->cr_uid != cr->cr_ruid ||
1688 		    s_cr->cr_uid != cr->cr_suid ||
1689 		    s_cr->cr_gid != cr->cr_gid ||
1690 		    s_cr->cr_gid != cr->cr_rgid ||
1691 		    s_cr->cr_gid != cr->cr_sgid ||
1692 		    (proc = ttoproc(curthread)) == NULL ||
1693 		    (proc->p_flag & SNOCD)) {
1694 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1695 				return (0);
1696 
1697 #ifdef illumos
1698 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1699 #endif
1700 		}
1701 	}
1702 
1703 #ifdef illumos
1704 	/*
1705 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1706 	 * in our zone, check to see if our mode policy is to restrict rather
1707 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1708 	 * and DTRACE_ACCESS_ARGS
1709 	 */
1710 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1711 		cred_t *cr;
1712 		cred_t *s_cr = state->dts_cred.dcr_cred;
1713 
1714 		ASSERT(s_cr != NULL);
1715 
1716 		if ((cr = CRED()) == NULL ||
1717 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1718 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1719 				return (0);
1720 
1721 			mstate->dtms_access &=
1722 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1723 		}
1724 	}
1725 #endif
1726 
1727 	return (1);
1728 }
1729 
1730 /*
1731  * Note:  not called from probe context.  This function is called
1732  * asynchronously (and at a regular interval) from outside of probe context to
1733  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1734  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1735  */
1736 void
1737 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1738 {
1739 	dtrace_dynvar_t *dirty;
1740 	dtrace_dstate_percpu_t *dcpu;
1741 	dtrace_dynvar_t **rinsep;
1742 	int i, j, work = 0;
1743 
1744 	for (i = 0; i < NCPU; i++) {
1745 		dcpu = &dstate->dtds_percpu[i];
1746 		rinsep = &dcpu->dtdsc_rinsing;
1747 
1748 		/*
1749 		 * If the dirty list is NULL, there is no dirty work to do.
1750 		 */
1751 		if (dcpu->dtdsc_dirty == NULL)
1752 			continue;
1753 
1754 		if (dcpu->dtdsc_rinsing != NULL) {
1755 			/*
1756 			 * If the rinsing list is non-NULL, then it is because
1757 			 * this CPU was selected to accept another CPU's
1758 			 * dirty list -- and since that time, dirty buffers
1759 			 * have accumulated.  This is a highly unlikely
1760 			 * condition, but we choose to ignore the dirty
1761 			 * buffers -- they'll be picked up a future cleanse.
1762 			 */
1763 			continue;
1764 		}
1765 
1766 		if (dcpu->dtdsc_clean != NULL) {
1767 			/*
1768 			 * If the clean list is non-NULL, then we're in a
1769 			 * situation where a CPU has done deallocations (we
1770 			 * have a non-NULL dirty list) but no allocations (we
1771 			 * also have a non-NULL clean list).  We can't simply
1772 			 * move the dirty list into the clean list on this
1773 			 * CPU, yet we also don't want to allow this condition
1774 			 * to persist, lest a short clean list prevent a
1775 			 * massive dirty list from being cleaned (which in
1776 			 * turn could lead to otherwise avoidable dynamic
1777 			 * drops).  To deal with this, we look for some CPU
1778 			 * with a NULL clean list, NULL dirty list, and NULL
1779 			 * rinsing list -- and then we borrow this CPU to
1780 			 * rinse our dirty list.
1781 			 */
1782 			for (j = 0; j < NCPU; j++) {
1783 				dtrace_dstate_percpu_t *rinser;
1784 
1785 				rinser = &dstate->dtds_percpu[j];
1786 
1787 				if (rinser->dtdsc_rinsing != NULL)
1788 					continue;
1789 
1790 				if (rinser->dtdsc_dirty != NULL)
1791 					continue;
1792 
1793 				if (rinser->dtdsc_clean != NULL)
1794 					continue;
1795 
1796 				rinsep = &rinser->dtdsc_rinsing;
1797 				break;
1798 			}
1799 
1800 			if (j == NCPU) {
1801 				/*
1802 				 * We were unable to find another CPU that
1803 				 * could accept this dirty list -- we are
1804 				 * therefore unable to clean it now.
1805 				 */
1806 				dtrace_dynvar_failclean++;
1807 				continue;
1808 			}
1809 		}
1810 
1811 		work = 1;
1812 
1813 		/*
1814 		 * Atomically move the dirty list aside.
1815 		 */
1816 		do {
1817 			dirty = dcpu->dtdsc_dirty;
1818 
1819 			/*
1820 			 * Before we zap the dirty list, set the rinsing list.
1821 			 * (This allows for a potential assertion in
1822 			 * dtrace_dynvar():  if a free dynamic variable appears
1823 			 * on a hash chain, either the dirty list or the
1824 			 * rinsing list for some CPU must be non-NULL.)
1825 			 */
1826 			*rinsep = dirty;
1827 			dtrace_membar_producer();
1828 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1829 		    dirty, NULL) != dirty);
1830 	}
1831 
1832 	if (!work) {
1833 		/*
1834 		 * We have no work to do; we can simply return.
1835 		 */
1836 		return;
1837 	}
1838 
1839 	dtrace_sync();
1840 
1841 	for (i = 0; i < NCPU; i++) {
1842 		dcpu = &dstate->dtds_percpu[i];
1843 
1844 		if (dcpu->dtdsc_rinsing == NULL)
1845 			continue;
1846 
1847 		/*
1848 		 * We are now guaranteed that no hash chain contains a pointer
1849 		 * into this dirty list; we can make it clean.
1850 		 */
1851 		ASSERT(dcpu->dtdsc_clean == NULL);
1852 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1853 		dcpu->dtdsc_rinsing = NULL;
1854 	}
1855 
1856 	/*
1857 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1858 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1859 	 * This prevents a race whereby a CPU incorrectly decides that
1860 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1861 	 * after dtrace_dynvar_clean() has completed.
1862 	 */
1863 	dtrace_sync();
1864 
1865 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1866 }
1867 
1868 /*
1869  * Depending on the value of the op parameter, this function looks-up,
1870  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1871  * allocation is requested, this function will return a pointer to a
1872  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1873  * variable can be allocated.  If NULL is returned, the appropriate counter
1874  * will be incremented.
1875  */
1876 dtrace_dynvar_t *
1877 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1878     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1879     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1880 {
1881 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1882 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1883 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1884 	processorid_t me = curcpu, cpu = me;
1885 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1886 	size_t bucket, ksize;
1887 	size_t chunksize = dstate->dtds_chunksize;
1888 	uintptr_t kdata, lock, nstate;
1889 	uint_t i;
1890 
1891 	ASSERT(nkeys != 0);
1892 
1893 	/*
1894 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1895 	 * algorithm.  For the by-value portions, we perform the algorithm in
1896 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1897 	 * bit, and seems to have only a minute effect on distribution.  For
1898 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1899 	 * over each referenced byte.  It's painful to do this, but it's much
1900 	 * better than pathological hash distribution.  The efficacy of the
1901 	 * hashing algorithm (and a comparison with other algorithms) may be
1902 	 * found by running the ::dtrace_dynstat MDB dcmd.
1903 	 */
1904 	for (i = 0; i < nkeys; i++) {
1905 		if (key[i].dttk_size == 0) {
1906 			uint64_t val = key[i].dttk_value;
1907 
1908 			hashval += (val >> 48) & 0xffff;
1909 			hashval += (hashval << 10);
1910 			hashval ^= (hashval >> 6);
1911 
1912 			hashval += (val >> 32) & 0xffff;
1913 			hashval += (hashval << 10);
1914 			hashval ^= (hashval >> 6);
1915 
1916 			hashval += (val >> 16) & 0xffff;
1917 			hashval += (hashval << 10);
1918 			hashval ^= (hashval >> 6);
1919 
1920 			hashval += val & 0xffff;
1921 			hashval += (hashval << 10);
1922 			hashval ^= (hashval >> 6);
1923 		} else {
1924 			/*
1925 			 * This is incredibly painful, but it beats the hell
1926 			 * out of the alternative.
1927 			 */
1928 			uint64_t j, size = key[i].dttk_size;
1929 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1930 
1931 			if (!dtrace_canload(base, size, mstate, vstate))
1932 				break;
1933 
1934 			for (j = 0; j < size; j++) {
1935 				hashval += dtrace_load8(base + j);
1936 				hashval += (hashval << 10);
1937 				hashval ^= (hashval >> 6);
1938 			}
1939 		}
1940 	}
1941 
1942 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1943 		return (NULL);
1944 
1945 	hashval += (hashval << 3);
1946 	hashval ^= (hashval >> 11);
1947 	hashval += (hashval << 15);
1948 
1949 	/*
1950 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1951 	 * comes out to be one of our two sentinel hash values.  If this
1952 	 * actually happens, we set the hashval to be a value known to be a
1953 	 * non-sentinel value.
1954 	 */
1955 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1956 		hashval = DTRACE_DYNHASH_VALID;
1957 
1958 	/*
1959 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1960 	 * important here, tricks can be pulled to reduce it.  (However, it's
1961 	 * critical that hash collisions be kept to an absolute minimum;
1962 	 * they're much more painful than a divide.)  It's better to have a
1963 	 * solution that generates few collisions and still keeps things
1964 	 * relatively simple.
1965 	 */
1966 	bucket = hashval % dstate->dtds_hashsize;
1967 
1968 	if (op == DTRACE_DYNVAR_DEALLOC) {
1969 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1970 
1971 		for (;;) {
1972 			while ((lock = *lockp) & 1)
1973 				continue;
1974 
1975 			if (dtrace_casptr((volatile void *)lockp,
1976 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1977 				break;
1978 		}
1979 
1980 		dtrace_membar_producer();
1981 	}
1982 
1983 top:
1984 	prev = NULL;
1985 	lock = hash[bucket].dtdh_lock;
1986 
1987 	dtrace_membar_consumer();
1988 
1989 	start = hash[bucket].dtdh_chain;
1990 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1991 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1992 	    op != DTRACE_DYNVAR_DEALLOC));
1993 
1994 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1995 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1996 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1997 
1998 		if (dvar->dtdv_hashval != hashval) {
1999 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
2000 				/*
2001 				 * We've reached the sink, and therefore the
2002 				 * end of the hash chain; we can kick out of
2003 				 * the loop knowing that we have seen a valid
2004 				 * snapshot of state.
2005 				 */
2006 				ASSERT(dvar->dtdv_next == NULL);
2007 				ASSERT(dvar == &dtrace_dynhash_sink);
2008 				break;
2009 			}
2010 
2011 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2012 				/*
2013 				 * We've gone off the rails:  somewhere along
2014 				 * the line, one of the members of this hash
2015 				 * chain was deleted.  Note that we could also
2016 				 * detect this by simply letting this loop run
2017 				 * to completion, as we would eventually hit
2018 				 * the end of the dirty list.  However, we
2019 				 * want to avoid running the length of the
2020 				 * dirty list unnecessarily (it might be quite
2021 				 * long), so we catch this as early as
2022 				 * possible by detecting the hash marker.  In
2023 				 * this case, we simply set dvar to NULL and
2024 				 * break; the conditional after the loop will
2025 				 * send us back to top.
2026 				 */
2027 				dvar = NULL;
2028 				break;
2029 			}
2030 
2031 			goto next;
2032 		}
2033 
2034 		if (dtuple->dtt_nkeys != nkeys)
2035 			goto next;
2036 
2037 		for (i = 0; i < nkeys; i++, dkey++) {
2038 			if (dkey->dttk_size != key[i].dttk_size)
2039 				goto next; /* size or type mismatch */
2040 
2041 			if (dkey->dttk_size != 0) {
2042 				if (dtrace_bcmp(
2043 				    (void *)(uintptr_t)key[i].dttk_value,
2044 				    (void *)(uintptr_t)dkey->dttk_value,
2045 				    dkey->dttk_size))
2046 					goto next;
2047 			} else {
2048 				if (dkey->dttk_value != key[i].dttk_value)
2049 					goto next;
2050 			}
2051 		}
2052 
2053 		if (op != DTRACE_DYNVAR_DEALLOC)
2054 			return (dvar);
2055 
2056 		ASSERT(dvar->dtdv_next == NULL ||
2057 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2058 
2059 		if (prev != NULL) {
2060 			ASSERT(hash[bucket].dtdh_chain != dvar);
2061 			ASSERT(start != dvar);
2062 			ASSERT(prev->dtdv_next == dvar);
2063 			prev->dtdv_next = dvar->dtdv_next;
2064 		} else {
2065 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2066 			    start, dvar->dtdv_next) != start) {
2067 				/*
2068 				 * We have failed to atomically swing the
2069 				 * hash table head pointer, presumably because
2070 				 * of a conflicting allocation on another CPU.
2071 				 * We need to reread the hash chain and try
2072 				 * again.
2073 				 */
2074 				goto top;
2075 			}
2076 		}
2077 
2078 		dtrace_membar_producer();
2079 
2080 		/*
2081 		 * Now set the hash value to indicate that it's free.
2082 		 */
2083 		ASSERT(hash[bucket].dtdh_chain != dvar);
2084 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2085 
2086 		dtrace_membar_producer();
2087 
2088 		/*
2089 		 * Set the next pointer to point at the dirty list, and
2090 		 * atomically swing the dirty pointer to the newly freed dvar.
2091 		 */
2092 		do {
2093 			next = dcpu->dtdsc_dirty;
2094 			dvar->dtdv_next = next;
2095 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2096 
2097 		/*
2098 		 * Finally, unlock this hash bucket.
2099 		 */
2100 		ASSERT(hash[bucket].dtdh_lock == lock);
2101 		ASSERT(lock & 1);
2102 		hash[bucket].dtdh_lock++;
2103 
2104 		return (NULL);
2105 next:
2106 		prev = dvar;
2107 		continue;
2108 	}
2109 
2110 	if (dvar == NULL) {
2111 		/*
2112 		 * If dvar is NULL, it is because we went off the rails:
2113 		 * one of the elements that we traversed in the hash chain
2114 		 * was deleted while we were traversing it.  In this case,
2115 		 * we assert that we aren't doing a dealloc (deallocs lock
2116 		 * the hash bucket to prevent themselves from racing with
2117 		 * one another), and retry the hash chain traversal.
2118 		 */
2119 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2120 		goto top;
2121 	}
2122 
2123 	if (op != DTRACE_DYNVAR_ALLOC) {
2124 		/*
2125 		 * If we are not to allocate a new variable, we want to
2126 		 * return NULL now.  Before we return, check that the value
2127 		 * of the lock word hasn't changed.  If it has, we may have
2128 		 * seen an inconsistent snapshot.
2129 		 */
2130 		if (op == DTRACE_DYNVAR_NOALLOC) {
2131 			if (hash[bucket].dtdh_lock != lock)
2132 				goto top;
2133 		} else {
2134 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2135 			ASSERT(hash[bucket].dtdh_lock == lock);
2136 			ASSERT(lock & 1);
2137 			hash[bucket].dtdh_lock++;
2138 		}
2139 
2140 		return (NULL);
2141 	}
2142 
2143 	/*
2144 	 * We need to allocate a new dynamic variable.  The size we need is the
2145 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2146 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2147 	 * the size of any referred-to data (dsize).  We then round the final
2148 	 * size up to the chunksize for allocation.
2149 	 */
2150 	for (ksize = 0, i = 0; i < nkeys; i++)
2151 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2152 
2153 	/*
2154 	 * This should be pretty much impossible, but could happen if, say,
2155 	 * strange DIF specified the tuple.  Ideally, this should be an
2156 	 * assertion and not an error condition -- but that requires that the
2157 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2158 	 * bullet-proof.  (That is, it must not be able to be fooled by
2159 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2160 	 * solving this would presumably not amount to solving the Halting
2161 	 * Problem -- but it still seems awfully hard.
2162 	 */
2163 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2164 	    ksize + dsize > chunksize) {
2165 		dcpu->dtdsc_drops++;
2166 		return (NULL);
2167 	}
2168 
2169 	nstate = DTRACE_DSTATE_EMPTY;
2170 
2171 	do {
2172 retry:
2173 		free = dcpu->dtdsc_free;
2174 
2175 		if (free == NULL) {
2176 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2177 			void *rval;
2178 
2179 			if (clean == NULL) {
2180 				/*
2181 				 * We're out of dynamic variable space on
2182 				 * this CPU.  Unless we have tried all CPUs,
2183 				 * we'll try to allocate from a different
2184 				 * CPU.
2185 				 */
2186 				switch (dstate->dtds_state) {
2187 				case DTRACE_DSTATE_CLEAN: {
2188 					void *sp = &dstate->dtds_state;
2189 
2190 					if (++cpu >= NCPU)
2191 						cpu = 0;
2192 
2193 					if (dcpu->dtdsc_dirty != NULL &&
2194 					    nstate == DTRACE_DSTATE_EMPTY)
2195 						nstate = DTRACE_DSTATE_DIRTY;
2196 
2197 					if (dcpu->dtdsc_rinsing != NULL)
2198 						nstate = DTRACE_DSTATE_RINSING;
2199 
2200 					dcpu = &dstate->dtds_percpu[cpu];
2201 
2202 					if (cpu != me)
2203 						goto retry;
2204 
2205 					(void) dtrace_cas32(sp,
2206 					    DTRACE_DSTATE_CLEAN, nstate);
2207 
2208 					/*
2209 					 * To increment the correct bean
2210 					 * counter, take another lap.
2211 					 */
2212 					goto retry;
2213 				}
2214 
2215 				case DTRACE_DSTATE_DIRTY:
2216 					dcpu->dtdsc_dirty_drops++;
2217 					break;
2218 
2219 				case DTRACE_DSTATE_RINSING:
2220 					dcpu->dtdsc_rinsing_drops++;
2221 					break;
2222 
2223 				case DTRACE_DSTATE_EMPTY:
2224 					dcpu->dtdsc_drops++;
2225 					break;
2226 				}
2227 
2228 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2229 				return (NULL);
2230 			}
2231 
2232 			/*
2233 			 * The clean list appears to be non-empty.  We want to
2234 			 * move the clean list to the free list; we start by
2235 			 * moving the clean pointer aside.
2236 			 */
2237 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2238 			    clean, NULL) != clean) {
2239 				/*
2240 				 * We are in one of two situations:
2241 				 *
2242 				 *  (a)	The clean list was switched to the
2243 				 *	free list by another CPU.
2244 				 *
2245 				 *  (b)	The clean list was added to by the
2246 				 *	cleansing cyclic.
2247 				 *
2248 				 * In either of these situations, we can
2249 				 * just reattempt the free list allocation.
2250 				 */
2251 				goto retry;
2252 			}
2253 
2254 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2255 
2256 			/*
2257 			 * Now we'll move the clean list to our free list.
2258 			 * It's impossible for this to fail:  the only way
2259 			 * the free list can be updated is through this
2260 			 * code path, and only one CPU can own the clean list.
2261 			 * Thus, it would only be possible for this to fail if
2262 			 * this code were racing with dtrace_dynvar_clean().
2263 			 * (That is, if dtrace_dynvar_clean() updated the clean
2264 			 * list, and we ended up racing to update the free
2265 			 * list.)  This race is prevented by the dtrace_sync()
2266 			 * in dtrace_dynvar_clean() -- which flushes the
2267 			 * owners of the clean lists out before resetting
2268 			 * the clean lists.
2269 			 */
2270 			dcpu = &dstate->dtds_percpu[me];
2271 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2272 			ASSERT(rval == NULL);
2273 			goto retry;
2274 		}
2275 
2276 		dvar = free;
2277 		new_free = dvar->dtdv_next;
2278 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2279 
2280 	/*
2281 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2282 	 * tuple array and copy any referenced key data into the data space
2283 	 * following the tuple array.  As we do this, we relocate dttk_value
2284 	 * in the final tuple to point to the key data address in the chunk.
2285 	 */
2286 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2287 	dvar->dtdv_data = (void *)(kdata + ksize);
2288 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2289 
2290 	for (i = 0; i < nkeys; i++) {
2291 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2292 		size_t kesize = key[i].dttk_size;
2293 
2294 		if (kesize != 0) {
2295 			dtrace_bcopy(
2296 			    (const void *)(uintptr_t)key[i].dttk_value,
2297 			    (void *)kdata, kesize);
2298 			dkey->dttk_value = kdata;
2299 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2300 		} else {
2301 			dkey->dttk_value = key[i].dttk_value;
2302 		}
2303 
2304 		dkey->dttk_size = kesize;
2305 	}
2306 
2307 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2308 	dvar->dtdv_hashval = hashval;
2309 	dvar->dtdv_next = start;
2310 
2311 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2312 		return (dvar);
2313 
2314 	/*
2315 	 * The cas has failed.  Either another CPU is adding an element to
2316 	 * this hash chain, or another CPU is deleting an element from this
2317 	 * hash chain.  The simplest way to deal with both of these cases
2318 	 * (though not necessarily the most efficient) is to free our
2319 	 * allocated block and re-attempt it all.  Note that the free is
2320 	 * to the dirty list and _not_ to the free list.  This is to prevent
2321 	 * races with allocators, above.
2322 	 */
2323 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2324 
2325 	dtrace_membar_producer();
2326 
2327 	do {
2328 		free = dcpu->dtdsc_dirty;
2329 		dvar->dtdv_next = free;
2330 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2331 
2332 	goto top;
2333 }
2334 
2335 /*ARGSUSED*/
2336 static void
2337 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2338 {
2339 	if ((int64_t)nval < (int64_t)*oval)
2340 		*oval = nval;
2341 }
2342 
2343 /*ARGSUSED*/
2344 static void
2345 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2346 {
2347 	if ((int64_t)nval > (int64_t)*oval)
2348 		*oval = nval;
2349 }
2350 
2351 static void
2352 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2353 {
2354 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2355 	int64_t val = (int64_t)nval;
2356 
2357 	if (val < 0) {
2358 		for (i = 0; i < zero; i++) {
2359 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2360 				quanta[i] += incr;
2361 				return;
2362 			}
2363 		}
2364 	} else {
2365 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2366 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2367 				quanta[i - 1] += incr;
2368 				return;
2369 			}
2370 		}
2371 
2372 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2373 		return;
2374 	}
2375 
2376 	ASSERT(0);
2377 }
2378 
2379 static void
2380 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2381 {
2382 	uint64_t arg = *lquanta++;
2383 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2384 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2385 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2386 	int32_t val = (int32_t)nval, level;
2387 
2388 	ASSERT(step != 0);
2389 	ASSERT(levels != 0);
2390 
2391 	if (val < base) {
2392 		/*
2393 		 * This is an underflow.
2394 		 */
2395 		lquanta[0] += incr;
2396 		return;
2397 	}
2398 
2399 	level = (val - base) / step;
2400 
2401 	if (level < levels) {
2402 		lquanta[level + 1] += incr;
2403 		return;
2404 	}
2405 
2406 	/*
2407 	 * This is an overflow.
2408 	 */
2409 	lquanta[levels + 1] += incr;
2410 }
2411 
2412 static int
2413 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2414     uint16_t high, uint16_t nsteps, int64_t value)
2415 {
2416 	int64_t this = 1, last, next;
2417 	int base = 1, order;
2418 
2419 	ASSERT(factor <= nsteps);
2420 	ASSERT(nsteps % factor == 0);
2421 
2422 	for (order = 0; order < low; order++)
2423 		this *= factor;
2424 
2425 	/*
2426 	 * If our value is less than our factor taken to the power of the
2427 	 * low order of magnitude, it goes into the zeroth bucket.
2428 	 */
2429 	if (value < (last = this))
2430 		return (0);
2431 
2432 	for (this *= factor; order <= high; order++) {
2433 		int nbuckets = this > nsteps ? nsteps : this;
2434 
2435 		if ((next = this * factor) < this) {
2436 			/*
2437 			 * We should not generally get log/linear quantizations
2438 			 * with a high magnitude that allows 64-bits to
2439 			 * overflow, but we nonetheless protect against this
2440 			 * by explicitly checking for overflow, and clamping
2441 			 * our value accordingly.
2442 			 */
2443 			value = this - 1;
2444 		}
2445 
2446 		if (value < this) {
2447 			/*
2448 			 * If our value lies within this order of magnitude,
2449 			 * determine its position by taking the offset within
2450 			 * the order of magnitude, dividing by the bucket
2451 			 * width, and adding to our (accumulated) base.
2452 			 */
2453 			return (base + (value - last) / (this / nbuckets));
2454 		}
2455 
2456 		base += nbuckets - (nbuckets / factor);
2457 		last = this;
2458 		this = next;
2459 	}
2460 
2461 	/*
2462 	 * Our value is greater than or equal to our factor taken to the
2463 	 * power of one plus the high magnitude -- return the top bucket.
2464 	 */
2465 	return (base);
2466 }
2467 
2468 static void
2469 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2470 {
2471 	uint64_t arg = *llquanta++;
2472 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2473 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2474 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2475 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2476 
2477 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2478 	    low, high, nsteps, nval)] += incr;
2479 }
2480 
2481 /*ARGSUSED*/
2482 static void
2483 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2484 {
2485 	data[0]++;
2486 	data[1] += nval;
2487 }
2488 
2489 /*ARGSUSED*/
2490 static void
2491 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2492 {
2493 	int64_t snval = (int64_t)nval;
2494 	uint64_t tmp[2];
2495 
2496 	data[0]++;
2497 	data[1] += nval;
2498 
2499 	/*
2500 	 * What we want to say here is:
2501 	 *
2502 	 * data[2] += nval * nval;
2503 	 *
2504 	 * But given that nval is 64-bit, we could easily overflow, so
2505 	 * we do this as 128-bit arithmetic.
2506 	 */
2507 	if (snval < 0)
2508 		snval = -snval;
2509 
2510 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2511 	dtrace_add_128(data + 2, tmp, data + 2);
2512 }
2513 
2514 /*ARGSUSED*/
2515 static void
2516 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2517 {
2518 	*oval = *oval + 1;
2519 }
2520 
2521 /*ARGSUSED*/
2522 static void
2523 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2524 {
2525 	*oval += nval;
2526 }
2527 
2528 /*
2529  * Aggregate given the tuple in the principal data buffer, and the aggregating
2530  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2531  * buffer is specified as the buf parameter.  This routine does not return
2532  * failure; if there is no space in the aggregation buffer, the data will be
2533  * dropped, and a corresponding counter incremented.
2534  */
2535 static void
2536 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2537     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2538 {
2539 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2540 	uint32_t i, ndx, size, fsize;
2541 	uint32_t align = sizeof (uint64_t) - 1;
2542 	dtrace_aggbuffer_t *agb;
2543 	dtrace_aggkey_t *key;
2544 	uint32_t hashval = 0, limit, isstr;
2545 	caddr_t tomax, data, kdata;
2546 	dtrace_actkind_t action;
2547 	dtrace_action_t *act;
2548 	uintptr_t offs;
2549 
2550 	if (buf == NULL)
2551 		return;
2552 
2553 	if (!agg->dtag_hasarg) {
2554 		/*
2555 		 * Currently, only quantize() and lquantize() take additional
2556 		 * arguments, and they have the same semantics:  an increment
2557 		 * value that defaults to 1 when not present.  If additional
2558 		 * aggregating actions take arguments, the setting of the
2559 		 * default argument value will presumably have to become more
2560 		 * sophisticated...
2561 		 */
2562 		arg = 1;
2563 	}
2564 
2565 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2566 	size = rec->dtrd_offset - agg->dtag_base;
2567 	fsize = size + rec->dtrd_size;
2568 
2569 	ASSERT(dbuf->dtb_tomax != NULL);
2570 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2571 
2572 	if ((tomax = buf->dtb_tomax) == NULL) {
2573 		dtrace_buffer_drop(buf);
2574 		return;
2575 	}
2576 
2577 	/*
2578 	 * The metastructure is always at the bottom of the buffer.
2579 	 */
2580 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2581 	    sizeof (dtrace_aggbuffer_t));
2582 
2583 	if (buf->dtb_offset == 0) {
2584 		/*
2585 		 * We just kludge up approximately 1/8th of the size to be
2586 		 * buckets.  If this guess ends up being routinely
2587 		 * off-the-mark, we may need to dynamically readjust this
2588 		 * based on past performance.
2589 		 */
2590 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2591 
2592 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2593 		    (uintptr_t)tomax || hashsize == 0) {
2594 			/*
2595 			 * We've been given a ludicrously small buffer;
2596 			 * increment our drop count and leave.
2597 			 */
2598 			dtrace_buffer_drop(buf);
2599 			return;
2600 		}
2601 
2602 		/*
2603 		 * And now, a pathetic attempt to try to get a an odd (or
2604 		 * perchance, a prime) hash size for better hash distribution.
2605 		 */
2606 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2607 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2608 
2609 		agb->dtagb_hashsize = hashsize;
2610 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2611 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2612 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2613 
2614 		for (i = 0; i < agb->dtagb_hashsize; i++)
2615 			agb->dtagb_hash[i] = NULL;
2616 	}
2617 
2618 	ASSERT(agg->dtag_first != NULL);
2619 	ASSERT(agg->dtag_first->dta_intuple);
2620 
2621 	/*
2622 	 * Calculate the hash value based on the key.  Note that we _don't_
2623 	 * include the aggid in the hashing (but we will store it as part of
2624 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2625 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2626 	 * gets good distribution in practice.  The efficacy of the hashing
2627 	 * algorithm (and a comparison with other algorithms) may be found by
2628 	 * running the ::dtrace_aggstat MDB dcmd.
2629 	 */
2630 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2631 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2632 		limit = i + act->dta_rec.dtrd_size;
2633 		ASSERT(limit <= size);
2634 		isstr = DTRACEACT_ISSTRING(act);
2635 
2636 		for (; i < limit; i++) {
2637 			hashval += data[i];
2638 			hashval += (hashval << 10);
2639 			hashval ^= (hashval >> 6);
2640 
2641 			if (isstr && data[i] == '\0')
2642 				break;
2643 		}
2644 	}
2645 
2646 	hashval += (hashval << 3);
2647 	hashval ^= (hashval >> 11);
2648 	hashval += (hashval << 15);
2649 
2650 	/*
2651 	 * Yes, the divide here is expensive -- but it's generally the least
2652 	 * of the performance issues given the amount of data that we iterate
2653 	 * over to compute hash values, compare data, etc.
2654 	 */
2655 	ndx = hashval % agb->dtagb_hashsize;
2656 
2657 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2658 		ASSERT((caddr_t)key >= tomax);
2659 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2660 
2661 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2662 			continue;
2663 
2664 		kdata = key->dtak_data;
2665 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2666 
2667 		for (act = agg->dtag_first; act->dta_intuple;
2668 		    act = act->dta_next) {
2669 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2670 			limit = i + act->dta_rec.dtrd_size;
2671 			ASSERT(limit <= size);
2672 			isstr = DTRACEACT_ISSTRING(act);
2673 
2674 			for (; i < limit; i++) {
2675 				if (kdata[i] != data[i])
2676 					goto next;
2677 
2678 				if (isstr && data[i] == '\0')
2679 					break;
2680 			}
2681 		}
2682 
2683 		if (action != key->dtak_action) {
2684 			/*
2685 			 * We are aggregating on the same value in the same
2686 			 * aggregation with two different aggregating actions.
2687 			 * (This should have been picked up in the compiler,
2688 			 * so we may be dealing with errant or devious DIF.)
2689 			 * This is an error condition; we indicate as much,
2690 			 * and return.
2691 			 */
2692 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2693 			return;
2694 		}
2695 
2696 		/*
2697 		 * This is a hit:  we need to apply the aggregator to
2698 		 * the value at this key.
2699 		 */
2700 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2701 		return;
2702 next:
2703 		continue;
2704 	}
2705 
2706 	/*
2707 	 * We didn't find it.  We need to allocate some zero-filled space,
2708 	 * link it into the hash table appropriately, and apply the aggregator
2709 	 * to the (zero-filled) value.
2710 	 */
2711 	offs = buf->dtb_offset;
2712 	while (offs & (align - 1))
2713 		offs += sizeof (uint32_t);
2714 
2715 	/*
2716 	 * If we don't have enough room to both allocate a new key _and_
2717 	 * its associated data, increment the drop count and return.
2718 	 */
2719 	if ((uintptr_t)tomax + offs + fsize >
2720 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2721 		dtrace_buffer_drop(buf);
2722 		return;
2723 	}
2724 
2725 	/*CONSTCOND*/
2726 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2727 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2728 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2729 
2730 	key->dtak_data = kdata = tomax + offs;
2731 	buf->dtb_offset = offs + fsize;
2732 
2733 	/*
2734 	 * Now copy the data across.
2735 	 */
2736 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2737 
2738 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2739 		kdata[i] = data[i];
2740 
2741 	/*
2742 	 * Because strings are not zeroed out by default, we need to iterate
2743 	 * looking for actions that store strings, and we need to explicitly
2744 	 * pad these strings out with zeroes.
2745 	 */
2746 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2747 		int nul;
2748 
2749 		if (!DTRACEACT_ISSTRING(act))
2750 			continue;
2751 
2752 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2753 		limit = i + act->dta_rec.dtrd_size;
2754 		ASSERT(limit <= size);
2755 
2756 		for (nul = 0; i < limit; i++) {
2757 			if (nul) {
2758 				kdata[i] = '\0';
2759 				continue;
2760 			}
2761 
2762 			if (data[i] != '\0')
2763 				continue;
2764 
2765 			nul = 1;
2766 		}
2767 	}
2768 
2769 	for (i = size; i < fsize; i++)
2770 		kdata[i] = 0;
2771 
2772 	key->dtak_hashval = hashval;
2773 	key->dtak_size = size;
2774 	key->dtak_action = action;
2775 	key->dtak_next = agb->dtagb_hash[ndx];
2776 	agb->dtagb_hash[ndx] = key;
2777 
2778 	/*
2779 	 * Finally, apply the aggregator.
2780 	 */
2781 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2782 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2783 }
2784 
2785 /*
2786  * Given consumer state, this routine finds a speculation in the INACTIVE
2787  * state and transitions it into the ACTIVE state.  If there is no speculation
2788  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2789  * incremented -- it is up to the caller to take appropriate action.
2790  */
2791 static int
2792 dtrace_speculation(dtrace_state_t *state)
2793 {
2794 	int i = 0;
2795 	dtrace_speculation_state_t curstate;
2796 	uint32_t *stat = &state->dts_speculations_unavail, count;
2797 
2798 	while (i < state->dts_nspeculations) {
2799 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2800 
2801 		curstate = spec->dtsp_state;
2802 
2803 		if (curstate != DTRACESPEC_INACTIVE) {
2804 			if (curstate == DTRACESPEC_COMMITTINGMANY ||
2805 			    curstate == DTRACESPEC_COMMITTING ||
2806 			    curstate == DTRACESPEC_DISCARDING)
2807 				stat = &state->dts_speculations_busy;
2808 			i++;
2809 			continue;
2810 		}
2811 
2812 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2813 		    curstate, DTRACESPEC_ACTIVE) == curstate)
2814 			return (i + 1);
2815 	}
2816 
2817 	/*
2818 	 * We couldn't find a speculation.  If we found as much as a single
2819 	 * busy speculation buffer, we'll attribute this failure as "busy"
2820 	 * instead of "unavail".
2821 	 */
2822 	do {
2823 		count = *stat;
2824 	} while (dtrace_cas32(stat, count, count + 1) != count);
2825 
2826 	return (0);
2827 }
2828 
2829 /*
2830  * This routine commits an active speculation.  If the specified speculation
2831  * is not in a valid state to perform a commit(), this routine will silently do
2832  * nothing.  The state of the specified speculation is transitioned according
2833  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2834  */
2835 static void
2836 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2837     dtrace_specid_t which)
2838 {
2839 	dtrace_speculation_t *spec;
2840 	dtrace_buffer_t *src, *dest;
2841 	uintptr_t daddr, saddr, dlimit, slimit;
2842 	dtrace_speculation_state_t curstate, new = 0;
2843 	intptr_t offs;
2844 	uint64_t timestamp;
2845 
2846 	if (which == 0)
2847 		return;
2848 
2849 	if (which > state->dts_nspeculations) {
2850 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2851 		return;
2852 	}
2853 
2854 	spec = &state->dts_speculations[which - 1];
2855 	src = &spec->dtsp_buffer[cpu];
2856 	dest = &state->dts_buffer[cpu];
2857 
2858 	do {
2859 		curstate = spec->dtsp_state;
2860 
2861 		if (curstate == DTRACESPEC_COMMITTINGMANY)
2862 			break;
2863 
2864 		switch (curstate) {
2865 		case DTRACESPEC_INACTIVE:
2866 		case DTRACESPEC_DISCARDING:
2867 			return;
2868 
2869 		case DTRACESPEC_COMMITTING:
2870 			/*
2871 			 * This is only possible if we are (a) commit()'ing
2872 			 * without having done a prior speculate() on this CPU
2873 			 * and (b) racing with another commit() on a different
2874 			 * CPU.  There's nothing to do -- we just assert that
2875 			 * our offset is 0.
2876 			 */
2877 			ASSERT(src->dtb_offset == 0);
2878 			return;
2879 
2880 		case DTRACESPEC_ACTIVE:
2881 			new = DTRACESPEC_COMMITTING;
2882 			break;
2883 
2884 		case DTRACESPEC_ACTIVEONE:
2885 			/*
2886 			 * This speculation is active on one CPU.  If our
2887 			 * buffer offset is non-zero, we know that the one CPU
2888 			 * must be us.  Otherwise, we are committing on a
2889 			 * different CPU from the speculate(), and we must
2890 			 * rely on being asynchronously cleaned.
2891 			 */
2892 			if (src->dtb_offset != 0) {
2893 				new = DTRACESPEC_COMMITTING;
2894 				break;
2895 			}
2896 			/*FALLTHROUGH*/
2897 
2898 		case DTRACESPEC_ACTIVEMANY:
2899 			new = DTRACESPEC_COMMITTINGMANY;
2900 			break;
2901 
2902 		default:
2903 			ASSERT(0);
2904 		}
2905 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2906 	    curstate, new) != curstate);
2907 
2908 	/*
2909 	 * We have set the state to indicate that we are committing this
2910 	 * speculation.  Now reserve the necessary space in the destination
2911 	 * buffer.
2912 	 */
2913 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2914 	    sizeof (uint64_t), state, NULL)) < 0) {
2915 		dtrace_buffer_drop(dest);
2916 		goto out;
2917 	}
2918 
2919 	/*
2920 	 * We have sufficient space to copy the speculative buffer into the
2921 	 * primary buffer.  First, modify the speculative buffer, filling
2922 	 * in the timestamp of all entries with the curstate time.  The data
2923 	 * must have the commit() time rather than the time it was traced,
2924 	 * so that all entries in the primary buffer are in timestamp order.
2925 	 */
2926 	timestamp = dtrace_gethrtime();
2927 	saddr = (uintptr_t)src->dtb_tomax;
2928 	slimit = saddr + src->dtb_offset;
2929 	while (saddr < slimit) {
2930 		size_t size;
2931 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2932 
2933 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2934 			saddr += sizeof (dtrace_epid_t);
2935 			continue;
2936 		}
2937 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2938 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2939 
2940 		ASSERT3U(saddr + size, <=, slimit);
2941 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2942 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2943 
2944 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2945 
2946 		saddr += size;
2947 	}
2948 
2949 	/*
2950 	 * Copy the buffer across.  (Note that this is a
2951 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2952 	 * a serious performance issue, a high-performance DTrace-specific
2953 	 * bcopy() should obviously be invented.)
2954 	 */
2955 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2956 	dlimit = daddr + src->dtb_offset;
2957 	saddr = (uintptr_t)src->dtb_tomax;
2958 
2959 	/*
2960 	 * First, the aligned portion.
2961 	 */
2962 	while (dlimit - daddr >= sizeof (uint64_t)) {
2963 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2964 
2965 		daddr += sizeof (uint64_t);
2966 		saddr += sizeof (uint64_t);
2967 	}
2968 
2969 	/*
2970 	 * Now any left-over bit...
2971 	 */
2972 	while (dlimit - daddr)
2973 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2974 
2975 	/*
2976 	 * Finally, commit the reserved space in the destination buffer.
2977 	 */
2978 	dest->dtb_offset = offs + src->dtb_offset;
2979 
2980 out:
2981 	/*
2982 	 * If we're lucky enough to be the only active CPU on this speculation
2983 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2984 	 */
2985 	if (curstate == DTRACESPEC_ACTIVE ||
2986 	    (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2987 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2988 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2989 
2990 		ASSERT(rval == DTRACESPEC_COMMITTING);
2991 	}
2992 
2993 	src->dtb_offset = 0;
2994 	src->dtb_xamot_drops += src->dtb_drops;
2995 	src->dtb_drops = 0;
2996 }
2997 
2998 /*
2999  * This routine discards an active speculation.  If the specified speculation
3000  * is not in a valid state to perform a discard(), this routine will silently
3001  * do nothing.  The state of the specified speculation is transitioned
3002  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3003  */
3004 static void
3005 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3006     dtrace_specid_t which)
3007 {
3008 	dtrace_speculation_t *spec;
3009 	dtrace_speculation_state_t curstate, new = 0;
3010 	dtrace_buffer_t *buf;
3011 
3012 	if (which == 0)
3013 		return;
3014 
3015 	if (which > state->dts_nspeculations) {
3016 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3017 		return;
3018 	}
3019 
3020 	spec = &state->dts_speculations[which - 1];
3021 	buf = &spec->dtsp_buffer[cpu];
3022 
3023 	do {
3024 		curstate = spec->dtsp_state;
3025 
3026 		switch (curstate) {
3027 		case DTRACESPEC_INACTIVE:
3028 		case DTRACESPEC_COMMITTINGMANY:
3029 		case DTRACESPEC_COMMITTING:
3030 		case DTRACESPEC_DISCARDING:
3031 			return;
3032 
3033 		case DTRACESPEC_ACTIVE:
3034 		case DTRACESPEC_ACTIVEMANY:
3035 			new = DTRACESPEC_DISCARDING;
3036 			break;
3037 
3038 		case DTRACESPEC_ACTIVEONE:
3039 			if (buf->dtb_offset != 0) {
3040 				new = DTRACESPEC_INACTIVE;
3041 			} else {
3042 				new = DTRACESPEC_DISCARDING;
3043 			}
3044 			break;
3045 
3046 		default:
3047 			ASSERT(0);
3048 		}
3049 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3050 	    curstate, new) != curstate);
3051 
3052 	buf->dtb_offset = 0;
3053 	buf->dtb_drops = 0;
3054 }
3055 
3056 /*
3057  * Note:  not called from probe context.  This function is called
3058  * asynchronously from cross call context to clean any speculations that are
3059  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3060  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3061  * speculation.
3062  */
3063 static void
3064 dtrace_speculation_clean_here(dtrace_state_t *state)
3065 {
3066 	dtrace_icookie_t cookie;
3067 	processorid_t cpu = curcpu;
3068 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3069 	dtrace_specid_t i;
3070 
3071 	cookie = dtrace_interrupt_disable();
3072 
3073 	if (dest->dtb_tomax == NULL) {
3074 		dtrace_interrupt_enable(cookie);
3075 		return;
3076 	}
3077 
3078 	for (i = 0; i < state->dts_nspeculations; i++) {
3079 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3080 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3081 
3082 		if (src->dtb_tomax == NULL)
3083 			continue;
3084 
3085 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3086 			src->dtb_offset = 0;
3087 			continue;
3088 		}
3089 
3090 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3091 			continue;
3092 
3093 		if (src->dtb_offset == 0)
3094 			continue;
3095 
3096 		dtrace_speculation_commit(state, cpu, i + 1);
3097 	}
3098 
3099 	dtrace_interrupt_enable(cookie);
3100 }
3101 
3102 /*
3103  * Note:  not called from probe context.  This function is called
3104  * asynchronously (and at a regular interval) to clean any speculations that
3105  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3106  * is work to be done, it cross calls all CPUs to perform that work;
3107  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3108  * INACTIVE state until they have been cleaned by all CPUs.
3109  */
3110 static void
3111 dtrace_speculation_clean(dtrace_state_t *state)
3112 {
3113 	int work = 0, rv;
3114 	dtrace_specid_t i;
3115 
3116 	for (i = 0; i < state->dts_nspeculations; i++) {
3117 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3118 
3119 		ASSERT(!spec->dtsp_cleaning);
3120 
3121 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3122 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3123 			continue;
3124 
3125 		work++;
3126 		spec->dtsp_cleaning = 1;
3127 	}
3128 
3129 	if (!work)
3130 		return;
3131 
3132 	dtrace_xcall(DTRACE_CPUALL,
3133 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3134 
3135 	/*
3136 	 * We now know that all CPUs have committed or discarded their
3137 	 * speculation buffers, as appropriate.  We can now set the state
3138 	 * to inactive.
3139 	 */
3140 	for (i = 0; i < state->dts_nspeculations; i++) {
3141 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3142 		dtrace_speculation_state_t curstate, new;
3143 
3144 		if (!spec->dtsp_cleaning)
3145 			continue;
3146 
3147 		curstate = spec->dtsp_state;
3148 		ASSERT(curstate == DTRACESPEC_DISCARDING ||
3149 		    curstate == DTRACESPEC_COMMITTINGMANY);
3150 
3151 		new = DTRACESPEC_INACTIVE;
3152 
3153 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3154 		ASSERT(rv == curstate);
3155 		spec->dtsp_cleaning = 0;
3156 	}
3157 }
3158 
3159 /*
3160  * Called as part of a speculate() to get the speculative buffer associated
3161  * with a given speculation.  Returns NULL if the specified speculation is not
3162  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3163  * the active CPU is not the specified CPU -- the speculation will be
3164  * atomically transitioned into the ACTIVEMANY state.
3165  */
3166 static dtrace_buffer_t *
3167 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3168     dtrace_specid_t which)
3169 {
3170 	dtrace_speculation_t *spec;
3171 	dtrace_speculation_state_t curstate, new = 0;
3172 	dtrace_buffer_t *buf;
3173 
3174 	if (which == 0)
3175 		return (NULL);
3176 
3177 	if (which > state->dts_nspeculations) {
3178 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3179 		return (NULL);
3180 	}
3181 
3182 	spec = &state->dts_speculations[which - 1];
3183 	buf = &spec->dtsp_buffer[cpuid];
3184 
3185 	do {
3186 		curstate = spec->dtsp_state;
3187 
3188 		switch (curstate) {
3189 		case DTRACESPEC_INACTIVE:
3190 		case DTRACESPEC_COMMITTINGMANY:
3191 		case DTRACESPEC_DISCARDING:
3192 			return (NULL);
3193 
3194 		case DTRACESPEC_COMMITTING:
3195 			ASSERT(buf->dtb_offset == 0);
3196 			return (NULL);
3197 
3198 		case DTRACESPEC_ACTIVEONE:
3199 			/*
3200 			 * This speculation is currently active on one CPU.
3201 			 * Check the offset in the buffer; if it's non-zero,
3202 			 * that CPU must be us (and we leave the state alone).
3203 			 * If it's zero, assume that we're starting on a new
3204 			 * CPU -- and change the state to indicate that the
3205 			 * speculation is active on more than one CPU.
3206 			 */
3207 			if (buf->dtb_offset != 0)
3208 				return (buf);
3209 
3210 			new = DTRACESPEC_ACTIVEMANY;
3211 			break;
3212 
3213 		case DTRACESPEC_ACTIVEMANY:
3214 			return (buf);
3215 
3216 		case DTRACESPEC_ACTIVE:
3217 			new = DTRACESPEC_ACTIVEONE;
3218 			break;
3219 
3220 		default:
3221 			ASSERT(0);
3222 		}
3223 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3224 	    curstate, new) != curstate);
3225 
3226 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3227 	return (buf);
3228 }
3229 
3230 /*
3231  * Return a string.  In the event that the user lacks the privilege to access
3232  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3233  * don't fail access checking.
3234  *
3235  * dtrace_dif_variable() uses this routine as a helper for various
3236  * builtin values such as 'execname' and 'probefunc.'
3237  */
3238 uintptr_t
3239 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3240     dtrace_mstate_t *mstate)
3241 {
3242 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3243 	uintptr_t ret;
3244 	size_t strsz;
3245 
3246 	/*
3247 	 * The easy case: this probe is allowed to read all of memory, so
3248 	 * we can just return this as a vanilla pointer.
3249 	 */
3250 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3251 		return (addr);
3252 
3253 	/*
3254 	 * This is the tougher case: we copy the string in question from
3255 	 * kernel memory into scratch memory and return it that way: this
3256 	 * ensures that we won't trip up when access checking tests the
3257 	 * BYREF return value.
3258 	 */
3259 	strsz = dtrace_strlen((char *)addr, size) + 1;
3260 
3261 	if (mstate->dtms_scratch_ptr + strsz >
3262 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3263 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3264 		return (0);
3265 	}
3266 
3267 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3268 	    strsz);
3269 	ret = mstate->dtms_scratch_ptr;
3270 	mstate->dtms_scratch_ptr += strsz;
3271 	return (ret);
3272 }
3273 
3274 /*
3275  * Return a string from a memoy address which is known to have one or
3276  * more concatenated, individually zero terminated, sub-strings.
3277  * In the event that the user lacks the privilege to access
3278  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3279  * don't fail access checking.
3280  *
3281  * dtrace_dif_variable() uses this routine as a helper for various
3282  * builtin values such as 'execargs'.
3283  */
3284 static uintptr_t
3285 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3286     dtrace_mstate_t *mstate)
3287 {
3288 	char *p;
3289 	size_t i;
3290 	uintptr_t ret;
3291 
3292 	if (mstate->dtms_scratch_ptr + strsz >
3293 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3294 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3295 		return (0);
3296 	}
3297 
3298 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3299 	    strsz);
3300 
3301 	/* Replace sub-string termination characters with a space. */
3302 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3303 	    p++, i++)
3304 		if (*p == '\0')
3305 			*p = ' ';
3306 
3307 	ret = mstate->dtms_scratch_ptr;
3308 	mstate->dtms_scratch_ptr += strsz;
3309 	return (ret);
3310 }
3311 
3312 /*
3313  * This function implements the DIF emulator's variable lookups.  The emulator
3314  * passes a reserved variable identifier and optional built-in array index.
3315  */
3316 static uint64_t
3317 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3318     uint64_t ndx)
3319 {
3320 	/*
3321 	 * If we're accessing one of the uncached arguments, we'll turn this
3322 	 * into a reference in the args array.
3323 	 */
3324 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3325 		ndx = v - DIF_VAR_ARG0;
3326 		v = DIF_VAR_ARGS;
3327 	}
3328 
3329 	switch (v) {
3330 	case DIF_VAR_ARGS:
3331 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3332 		if (ndx >= sizeof (mstate->dtms_arg) /
3333 		    sizeof (mstate->dtms_arg[0])) {
3334 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3335 			dtrace_provider_t *pv;
3336 			uint64_t val;
3337 
3338 			pv = mstate->dtms_probe->dtpr_provider;
3339 			if (pv->dtpv_pops.dtps_getargval != NULL)
3340 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3341 				    mstate->dtms_probe->dtpr_id,
3342 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3343 			else
3344 				val = dtrace_getarg(ndx, aframes);
3345 
3346 			/*
3347 			 * This is regrettably required to keep the compiler
3348 			 * from tail-optimizing the call to dtrace_getarg().
3349 			 * The condition always evaluates to true, but the
3350 			 * compiler has no way of figuring that out a priori.
3351 			 * (None of this would be necessary if the compiler
3352 			 * could be relied upon to _always_ tail-optimize
3353 			 * the call to dtrace_getarg() -- but it can't.)
3354 			 */
3355 			if (mstate->dtms_probe != NULL)
3356 				return (val);
3357 
3358 			ASSERT(0);
3359 		}
3360 
3361 		return (mstate->dtms_arg[ndx]);
3362 
3363 #ifdef illumos
3364 	case DIF_VAR_UREGS: {
3365 		klwp_t *lwp;
3366 
3367 		if (!dtrace_priv_proc(state))
3368 			return (0);
3369 
3370 		if ((lwp = curthread->t_lwp) == NULL) {
3371 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3372 			cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3373 			return (0);
3374 		}
3375 
3376 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3377 		return (0);
3378 	}
3379 #else
3380 	case DIF_VAR_UREGS: {
3381 		struct trapframe *tframe;
3382 
3383 		if (!dtrace_priv_proc(state))
3384 			return (0);
3385 
3386 		if ((tframe = curthread->td_frame) == NULL) {
3387 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3388 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3389 			return (0);
3390 		}
3391 
3392 		return (dtrace_getreg(tframe, ndx));
3393 	}
3394 #endif
3395 
3396 	case DIF_VAR_CURTHREAD:
3397 		if (!dtrace_priv_proc(state))
3398 			return (0);
3399 		return ((uint64_t)(uintptr_t)curthread);
3400 
3401 	case DIF_VAR_TIMESTAMP:
3402 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3403 			mstate->dtms_timestamp = dtrace_gethrtime();
3404 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3405 		}
3406 		return (mstate->dtms_timestamp);
3407 
3408 	case DIF_VAR_VTIMESTAMP:
3409 		ASSERT(dtrace_vtime_references != 0);
3410 		return (curthread->t_dtrace_vtime);
3411 
3412 	case DIF_VAR_WALLTIMESTAMP:
3413 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3414 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3415 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3416 		}
3417 		return (mstate->dtms_walltimestamp);
3418 
3419 #ifdef illumos
3420 	case DIF_VAR_IPL:
3421 		if (!dtrace_priv_kernel(state))
3422 			return (0);
3423 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3424 			mstate->dtms_ipl = dtrace_getipl();
3425 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3426 		}
3427 		return (mstate->dtms_ipl);
3428 #endif
3429 
3430 	case DIF_VAR_EPID:
3431 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3432 		return (mstate->dtms_epid);
3433 
3434 	case DIF_VAR_ID:
3435 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3436 		return (mstate->dtms_probe->dtpr_id);
3437 
3438 	case DIF_VAR_STACKDEPTH:
3439 		if (!dtrace_priv_kernel(state))
3440 			return (0);
3441 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3442 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3443 
3444 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3445 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3446 		}
3447 		return (mstate->dtms_stackdepth);
3448 
3449 	case DIF_VAR_USTACKDEPTH:
3450 		if (!dtrace_priv_proc(state))
3451 			return (0);
3452 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3453 			/*
3454 			 * See comment in DIF_VAR_PID.
3455 			 */
3456 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3457 			    CPU_ON_INTR(CPU)) {
3458 				mstate->dtms_ustackdepth = 0;
3459 			} else {
3460 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3461 				mstate->dtms_ustackdepth =
3462 				    dtrace_getustackdepth();
3463 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3464 			}
3465 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3466 		}
3467 		return (mstate->dtms_ustackdepth);
3468 
3469 	case DIF_VAR_CALLER:
3470 		if (!dtrace_priv_kernel(state))
3471 			return (0);
3472 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3473 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3474 
3475 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3476 				/*
3477 				 * If this is an unanchored probe, we are
3478 				 * required to go through the slow path:
3479 				 * dtrace_caller() only guarantees correct
3480 				 * results for anchored probes.
3481 				 */
3482 				pc_t caller[2] = {0, 0};
3483 
3484 				dtrace_getpcstack(caller, 2, aframes,
3485 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3486 				mstate->dtms_caller = caller[1];
3487 			} else if ((mstate->dtms_caller =
3488 			    dtrace_caller(aframes)) == -1) {
3489 				/*
3490 				 * We have failed to do this the quick way;
3491 				 * we must resort to the slower approach of
3492 				 * calling dtrace_getpcstack().
3493 				 */
3494 				pc_t caller = 0;
3495 
3496 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3497 				mstate->dtms_caller = caller;
3498 			}
3499 
3500 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3501 		}
3502 		return (mstate->dtms_caller);
3503 
3504 	case DIF_VAR_UCALLER:
3505 		if (!dtrace_priv_proc(state))
3506 			return (0);
3507 
3508 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3509 			uint64_t ustack[3];
3510 
3511 			/*
3512 			 * dtrace_getupcstack() fills in the first uint64_t
3513 			 * with the current PID.  The second uint64_t will
3514 			 * be the program counter at user-level.  The third
3515 			 * uint64_t will contain the caller, which is what
3516 			 * we're after.
3517 			 */
3518 			ustack[2] = 0;
3519 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3520 			dtrace_getupcstack(ustack, 3);
3521 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3522 			mstate->dtms_ucaller = ustack[2];
3523 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3524 		}
3525 
3526 		return (mstate->dtms_ucaller);
3527 
3528 	case DIF_VAR_PROBEPROV:
3529 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3530 		return (dtrace_dif_varstr(
3531 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3532 		    state, mstate));
3533 
3534 	case DIF_VAR_PROBEMOD:
3535 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3536 		return (dtrace_dif_varstr(
3537 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3538 		    state, mstate));
3539 
3540 	case DIF_VAR_PROBEFUNC:
3541 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3542 		return (dtrace_dif_varstr(
3543 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3544 		    state, mstate));
3545 
3546 	case DIF_VAR_PROBENAME:
3547 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3548 		return (dtrace_dif_varstr(
3549 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3550 		    state, mstate));
3551 
3552 	case DIF_VAR_PID:
3553 		if (!dtrace_priv_proc(state))
3554 			return (0);
3555 
3556 #ifdef illumos
3557 		/*
3558 		 * Note that we are assuming that an unanchored probe is
3559 		 * always due to a high-level interrupt.  (And we're assuming
3560 		 * that there is only a single high level interrupt.)
3561 		 */
3562 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3563 			return (pid0.pid_id);
3564 
3565 		/*
3566 		 * It is always safe to dereference one's own t_procp pointer:
3567 		 * it always points to a valid, allocated proc structure.
3568 		 * Further, it is always safe to dereference the p_pidp member
3569 		 * of one's own proc structure.  (These are truisms becuase
3570 		 * threads and processes don't clean up their own state --
3571 		 * they leave that task to whomever reaps them.)
3572 		 */
3573 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3574 #else
3575 		return ((uint64_t)curproc->p_pid);
3576 #endif
3577 
3578 	case DIF_VAR_PPID:
3579 		if (!dtrace_priv_proc(state))
3580 			return (0);
3581 
3582 #ifdef illumos
3583 		/*
3584 		 * See comment in DIF_VAR_PID.
3585 		 */
3586 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3587 			return (pid0.pid_id);
3588 
3589 		/*
3590 		 * It is always safe to dereference one's own t_procp pointer:
3591 		 * it always points to a valid, allocated proc structure.
3592 		 * (This is true because threads don't clean up their own
3593 		 * state -- they leave that task to whomever reaps them.)
3594 		 */
3595 		return ((uint64_t)curthread->t_procp->p_ppid);
3596 #else
3597 		if (curproc->p_pid == proc0.p_pid)
3598 			return (curproc->p_pid);
3599 		else
3600 			return (curproc->p_pptr->p_pid);
3601 #endif
3602 
3603 	case DIF_VAR_TID:
3604 #ifdef illumos
3605 		/*
3606 		 * See comment in DIF_VAR_PID.
3607 		 */
3608 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3609 			return (0);
3610 #endif
3611 
3612 		return ((uint64_t)curthread->t_tid);
3613 
3614 	case DIF_VAR_EXECARGS: {
3615 		struct pargs *p_args = curthread->td_proc->p_args;
3616 
3617 		if (p_args == NULL)
3618 			return(0);
3619 
3620 		return (dtrace_dif_varstrz(
3621 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3622 	}
3623 
3624 	case DIF_VAR_EXECNAME:
3625 #ifdef illumos
3626 		if (!dtrace_priv_proc(state))
3627 			return (0);
3628 
3629 		/*
3630 		 * See comment in DIF_VAR_PID.
3631 		 */
3632 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3633 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3634 
3635 		/*
3636 		 * It is always safe to dereference one's own t_procp pointer:
3637 		 * it always points to a valid, allocated proc structure.
3638 		 * (This is true because threads don't clean up their own
3639 		 * state -- they leave that task to whomever reaps them.)
3640 		 */
3641 		return (dtrace_dif_varstr(
3642 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3643 		    state, mstate));
3644 #else
3645 		return (dtrace_dif_varstr(
3646 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3647 #endif
3648 
3649 	case DIF_VAR_ZONENAME:
3650 #ifdef illumos
3651 		if (!dtrace_priv_proc(state))
3652 			return (0);
3653 
3654 		/*
3655 		 * See comment in DIF_VAR_PID.
3656 		 */
3657 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3658 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3659 
3660 		/*
3661 		 * It is always safe to dereference one's own t_procp pointer:
3662 		 * it always points to a valid, allocated proc structure.
3663 		 * (This is true because threads don't clean up their own
3664 		 * state -- they leave that task to whomever reaps them.)
3665 		 */
3666 		return (dtrace_dif_varstr(
3667 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3668 		    state, mstate));
3669 #elif defined(__FreeBSD__)
3670 	/*
3671 	 * On FreeBSD, we introduce compatibility to zonename by falling through
3672 	 * into jailname.
3673 	 */
3674 	case DIF_VAR_JAILNAME:
3675 		if (!dtrace_priv_kernel(state))
3676 			return (0);
3677 
3678 		return (dtrace_dif_varstr(
3679 		    (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3680 		    state, mstate));
3681 
3682 	case DIF_VAR_JID:
3683 		if (!dtrace_priv_kernel(state))
3684 			return (0);
3685 
3686 		return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3687 #else
3688 		return (0);
3689 #endif
3690 
3691 	case DIF_VAR_UID:
3692 		if (!dtrace_priv_proc(state))
3693 			return (0);
3694 
3695 #ifdef illumos
3696 		/*
3697 		 * See comment in DIF_VAR_PID.
3698 		 */
3699 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3700 			return ((uint64_t)p0.p_cred->cr_uid);
3701 
3702 		/*
3703 		 * It is always safe to dereference one's own t_procp pointer:
3704 		 * it always points to a valid, allocated proc structure.
3705 		 * (This is true because threads don't clean up their own
3706 		 * state -- they leave that task to whomever reaps them.)
3707 		 *
3708 		 * Additionally, it is safe to dereference one's own process
3709 		 * credential, since this is never NULL after process birth.
3710 		 */
3711 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3712 #else
3713 		return ((uint64_t)curthread->td_ucred->cr_uid);
3714 #endif
3715 
3716 	case DIF_VAR_GID:
3717 		if (!dtrace_priv_proc(state))
3718 			return (0);
3719 
3720 #ifdef illumos
3721 		/*
3722 		 * See comment in DIF_VAR_PID.
3723 		 */
3724 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3725 			return ((uint64_t)p0.p_cred->cr_gid);
3726 
3727 		/*
3728 		 * It is always safe to dereference one's own t_procp pointer:
3729 		 * it always points to a valid, allocated proc structure.
3730 		 * (This is true because threads don't clean up their own
3731 		 * state -- they leave that task to whomever reaps them.)
3732 		 *
3733 		 * Additionally, it is safe to dereference one's own process
3734 		 * credential, since this is never NULL after process birth.
3735 		 */
3736 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3737 #else
3738 		return ((uint64_t)curthread->td_ucred->cr_gid);
3739 #endif
3740 
3741 	case DIF_VAR_ERRNO: {
3742 #ifdef illumos
3743 		klwp_t *lwp;
3744 		if (!dtrace_priv_proc(state))
3745 			return (0);
3746 
3747 		/*
3748 		 * See comment in DIF_VAR_PID.
3749 		 */
3750 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3751 			return (0);
3752 
3753 		/*
3754 		 * It is always safe to dereference one's own t_lwp pointer in
3755 		 * the event that this pointer is non-NULL.  (This is true
3756 		 * because threads and lwps don't clean up their own state --
3757 		 * they leave that task to whomever reaps them.)
3758 		 */
3759 		if ((lwp = curthread->t_lwp) == NULL)
3760 			return (0);
3761 
3762 		return ((uint64_t)lwp->lwp_errno);
3763 #else
3764 		return (curthread->td_errno);
3765 #endif
3766 	}
3767 #ifndef illumos
3768 	case DIF_VAR_CPU: {
3769 		return curcpu;
3770 	}
3771 #endif
3772 	default:
3773 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3774 		return (0);
3775 	}
3776 }
3777 
3778 
3779 typedef enum dtrace_json_state {
3780 	DTRACE_JSON_REST = 1,
3781 	DTRACE_JSON_OBJECT,
3782 	DTRACE_JSON_STRING,
3783 	DTRACE_JSON_STRING_ESCAPE,
3784 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3785 	DTRACE_JSON_COLON,
3786 	DTRACE_JSON_COMMA,
3787 	DTRACE_JSON_VALUE,
3788 	DTRACE_JSON_IDENTIFIER,
3789 	DTRACE_JSON_NUMBER,
3790 	DTRACE_JSON_NUMBER_FRAC,
3791 	DTRACE_JSON_NUMBER_EXP,
3792 	DTRACE_JSON_COLLECT_OBJECT
3793 } dtrace_json_state_t;
3794 
3795 /*
3796  * This function possesses just enough knowledge about JSON to extract a single
3797  * value from a JSON string and store it in the scratch buffer.  It is able
3798  * to extract nested object values, and members of arrays by index.
3799  *
3800  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3801  * be looked up as we descend into the object tree.  e.g.
3802  *
3803  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3804  *       with nelems = 5.
3805  *
3806  * The run time of this function must be bounded above by strsize to limit the
3807  * amount of work done in probe context.  As such, it is implemented as a
3808  * simple state machine, reading one character at a time using safe loads
3809  * until we find the requested element, hit a parsing error or run off the
3810  * end of the object or string.
3811  *
3812  * As there is no way for a subroutine to return an error without interrupting
3813  * clause execution, we simply return NULL in the event of a missing key or any
3814  * other error condition.  Each NULL return in this function is commented with
3815  * the error condition it represents -- parsing or otherwise.
3816  *
3817  * The set of states for the state machine closely matches the JSON
3818  * specification (http://json.org/).  Briefly:
3819  *
3820  *   DTRACE_JSON_REST:
3821  *     Skip whitespace until we find either a top-level Object, moving
3822  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3823  *
3824  *   DTRACE_JSON_OBJECT:
3825  *     Locate the next key String in an Object.  Sets a flag to denote
3826  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3827  *
3828  *   DTRACE_JSON_COLON:
3829  *     Skip whitespace until we find the colon that separates key Strings
3830  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3831  *
3832  *   DTRACE_JSON_VALUE:
3833  *     Detects the type of the next value (String, Number, Identifier, Object
3834  *     or Array) and routes to the states that process that type.  Here we also
3835  *     deal with the element selector list if we are requested to traverse down
3836  *     into the object tree.
3837  *
3838  *   DTRACE_JSON_COMMA:
3839  *     Skip whitespace until we find the comma that separates key-value pairs
3840  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3841  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3842  *     states return to this state at the end of their value, unless otherwise
3843  *     noted.
3844  *
3845  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3846  *     Processes a Number literal from the JSON, including any exponent
3847  *     component that may be present.  Numbers are returned as strings, which
3848  *     may be passed to strtoll() if an integer is required.
3849  *
3850  *   DTRACE_JSON_IDENTIFIER:
3851  *     Processes a "true", "false" or "null" literal in the JSON.
3852  *
3853  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3854  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3855  *     Processes a String literal from the JSON, whether the String denotes
3856  *     a key, a value or part of a larger Object.  Handles all escape sequences
3857  *     present in the specification, including four-digit unicode characters,
3858  *     but merely includes the escape sequence without converting it to the
3859  *     actual escaped character.  If the String is flagged as a key, we
3860  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3861  *
3862  *   DTRACE_JSON_COLLECT_OBJECT:
3863  *     This state collects an entire Object (or Array), correctly handling
3864  *     embedded strings.  If the full element selector list matches this nested
3865  *     object, we return the Object in full as a string.  If not, we use this
3866  *     state to skip to the next value at this level and continue processing.
3867  *
3868  * NOTE: This function uses various macros from strtolctype.h to manipulate
3869  * digit values, etc -- these have all been checked to ensure they make
3870  * no additional function calls.
3871  */
3872 static char *
3873 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3874     char *dest)
3875 {
3876 	dtrace_json_state_t state = DTRACE_JSON_REST;
3877 	int64_t array_elem = INT64_MIN;
3878 	int64_t array_pos = 0;
3879 	uint8_t escape_unicount = 0;
3880 	boolean_t string_is_key = B_FALSE;
3881 	boolean_t collect_object = B_FALSE;
3882 	boolean_t found_key = B_FALSE;
3883 	boolean_t in_array = B_FALSE;
3884 	uint32_t braces = 0, brackets = 0;
3885 	char *elem = elemlist;
3886 	char *dd = dest;
3887 	uintptr_t cur;
3888 
3889 	for (cur = json; cur < json + size; cur++) {
3890 		char cc = dtrace_load8(cur);
3891 		if (cc == '\0')
3892 			return (NULL);
3893 
3894 		switch (state) {
3895 		case DTRACE_JSON_REST:
3896 			if (isspace(cc))
3897 				break;
3898 
3899 			if (cc == '{') {
3900 				state = DTRACE_JSON_OBJECT;
3901 				break;
3902 			}
3903 
3904 			if (cc == '[') {
3905 				in_array = B_TRUE;
3906 				array_pos = 0;
3907 				array_elem = dtrace_strtoll(elem, 10, size);
3908 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3909 				state = DTRACE_JSON_VALUE;
3910 				break;
3911 			}
3912 
3913 			/*
3914 			 * ERROR: expected to find a top-level object or array.
3915 			 */
3916 			return (NULL);
3917 		case DTRACE_JSON_OBJECT:
3918 			if (isspace(cc))
3919 				break;
3920 
3921 			if (cc == '"') {
3922 				state = DTRACE_JSON_STRING;
3923 				string_is_key = B_TRUE;
3924 				break;
3925 			}
3926 
3927 			/*
3928 			 * ERROR: either the object did not start with a key
3929 			 * string, or we've run off the end of the object
3930 			 * without finding the requested key.
3931 			 */
3932 			return (NULL);
3933 		case DTRACE_JSON_STRING:
3934 			if (cc == '\\') {
3935 				*dd++ = '\\';
3936 				state = DTRACE_JSON_STRING_ESCAPE;
3937 				break;
3938 			}
3939 
3940 			if (cc == '"') {
3941 				if (collect_object) {
3942 					/*
3943 					 * We don't reset the dest here, as
3944 					 * the string is part of a larger
3945 					 * object being collected.
3946 					 */
3947 					*dd++ = cc;
3948 					collect_object = B_FALSE;
3949 					state = DTRACE_JSON_COLLECT_OBJECT;
3950 					break;
3951 				}
3952 				*dd = '\0';
3953 				dd = dest; /* reset string buffer */
3954 				if (string_is_key) {
3955 					if (dtrace_strncmp(dest, elem,
3956 					    size) == 0)
3957 						found_key = B_TRUE;
3958 				} else if (found_key) {
3959 					if (nelems > 1) {
3960 						/*
3961 						 * We expected an object, not
3962 						 * this string.
3963 						 */
3964 						return (NULL);
3965 					}
3966 					return (dest);
3967 				}
3968 				state = string_is_key ? DTRACE_JSON_COLON :
3969 				    DTRACE_JSON_COMMA;
3970 				string_is_key = B_FALSE;
3971 				break;
3972 			}
3973 
3974 			*dd++ = cc;
3975 			break;
3976 		case DTRACE_JSON_STRING_ESCAPE:
3977 			*dd++ = cc;
3978 			if (cc == 'u') {
3979 				escape_unicount = 0;
3980 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3981 			} else {
3982 				state = DTRACE_JSON_STRING;
3983 			}
3984 			break;
3985 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3986 			if (!isxdigit(cc)) {
3987 				/*
3988 				 * ERROR: invalid unicode escape, expected
3989 				 * four valid hexidecimal digits.
3990 				 */
3991 				return (NULL);
3992 			}
3993 
3994 			*dd++ = cc;
3995 			if (++escape_unicount == 4)
3996 				state = DTRACE_JSON_STRING;
3997 			break;
3998 		case DTRACE_JSON_COLON:
3999 			if (isspace(cc))
4000 				break;
4001 
4002 			if (cc == ':') {
4003 				state = DTRACE_JSON_VALUE;
4004 				break;
4005 			}
4006 
4007 			/*
4008 			 * ERROR: expected a colon.
4009 			 */
4010 			return (NULL);
4011 		case DTRACE_JSON_COMMA:
4012 			if (isspace(cc))
4013 				break;
4014 
4015 			if (cc == ',') {
4016 				if (in_array) {
4017 					state = DTRACE_JSON_VALUE;
4018 					if (++array_pos == array_elem)
4019 						found_key = B_TRUE;
4020 				} else {
4021 					state = DTRACE_JSON_OBJECT;
4022 				}
4023 				break;
4024 			}
4025 
4026 			/*
4027 			 * ERROR: either we hit an unexpected character, or
4028 			 * we reached the end of the object or array without
4029 			 * finding the requested key.
4030 			 */
4031 			return (NULL);
4032 		case DTRACE_JSON_IDENTIFIER:
4033 			if (islower(cc)) {
4034 				*dd++ = cc;
4035 				break;
4036 			}
4037 
4038 			*dd = '\0';
4039 			dd = dest; /* reset string buffer */
4040 
4041 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
4042 			    dtrace_strncmp(dest, "false", 6) == 0 ||
4043 			    dtrace_strncmp(dest, "null", 5) == 0) {
4044 				if (found_key) {
4045 					if (nelems > 1) {
4046 						/*
4047 						 * ERROR: We expected an object,
4048 						 * not this identifier.
4049 						 */
4050 						return (NULL);
4051 					}
4052 					return (dest);
4053 				} else {
4054 					cur--;
4055 					state = DTRACE_JSON_COMMA;
4056 					break;
4057 				}
4058 			}
4059 
4060 			/*
4061 			 * ERROR: we did not recognise the identifier as one
4062 			 * of those in the JSON specification.
4063 			 */
4064 			return (NULL);
4065 		case DTRACE_JSON_NUMBER:
4066 			if (cc == '.') {
4067 				*dd++ = cc;
4068 				state = DTRACE_JSON_NUMBER_FRAC;
4069 				break;
4070 			}
4071 
4072 			if (cc == 'x' || cc == 'X') {
4073 				/*
4074 				 * ERROR: specification explicitly excludes
4075 				 * hexidecimal or octal numbers.
4076 				 */
4077 				return (NULL);
4078 			}
4079 
4080 			/* FALLTHRU */
4081 		case DTRACE_JSON_NUMBER_FRAC:
4082 			if (cc == 'e' || cc == 'E') {
4083 				*dd++ = cc;
4084 				state = DTRACE_JSON_NUMBER_EXP;
4085 				break;
4086 			}
4087 
4088 			if (cc == '+' || cc == '-') {
4089 				/*
4090 				 * ERROR: expect sign as part of exponent only.
4091 				 */
4092 				return (NULL);
4093 			}
4094 			/* FALLTHRU */
4095 		case DTRACE_JSON_NUMBER_EXP:
4096 			if (isdigit(cc) || cc == '+' || cc == '-') {
4097 				*dd++ = cc;
4098 				break;
4099 			}
4100 
4101 			*dd = '\0';
4102 			dd = dest; /* reset string buffer */
4103 			if (found_key) {
4104 				if (nelems > 1) {
4105 					/*
4106 					 * ERROR: We expected an object, not
4107 					 * this number.
4108 					 */
4109 					return (NULL);
4110 				}
4111 				return (dest);
4112 			}
4113 
4114 			cur--;
4115 			state = DTRACE_JSON_COMMA;
4116 			break;
4117 		case DTRACE_JSON_VALUE:
4118 			if (isspace(cc))
4119 				break;
4120 
4121 			if (cc == '{' || cc == '[') {
4122 				if (nelems > 1 && found_key) {
4123 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4124 					/*
4125 					 * If our element selector directs us
4126 					 * to descend into this nested object,
4127 					 * then move to the next selector
4128 					 * element in the list and restart the
4129 					 * state machine.
4130 					 */
4131 					while (*elem != '\0')
4132 						elem++;
4133 					elem++; /* skip the inter-element NUL */
4134 					nelems--;
4135 					dd = dest;
4136 					if (in_array) {
4137 						state = DTRACE_JSON_VALUE;
4138 						array_pos = 0;
4139 						array_elem = dtrace_strtoll(
4140 						    elem, 10, size);
4141 						found_key = array_elem == 0 ?
4142 						    B_TRUE : B_FALSE;
4143 					} else {
4144 						found_key = B_FALSE;
4145 						state = DTRACE_JSON_OBJECT;
4146 					}
4147 					break;
4148 				}
4149 
4150 				/*
4151 				 * Otherwise, we wish to either skip this
4152 				 * nested object or return it in full.
4153 				 */
4154 				if (cc == '[')
4155 					brackets = 1;
4156 				else
4157 					braces = 1;
4158 				*dd++ = cc;
4159 				state = DTRACE_JSON_COLLECT_OBJECT;
4160 				break;
4161 			}
4162 
4163 			if (cc == '"') {
4164 				state = DTRACE_JSON_STRING;
4165 				break;
4166 			}
4167 
4168 			if (islower(cc)) {
4169 				/*
4170 				 * Here we deal with true, false and null.
4171 				 */
4172 				*dd++ = cc;
4173 				state = DTRACE_JSON_IDENTIFIER;
4174 				break;
4175 			}
4176 
4177 			if (cc == '-' || isdigit(cc)) {
4178 				*dd++ = cc;
4179 				state = DTRACE_JSON_NUMBER;
4180 				break;
4181 			}
4182 
4183 			/*
4184 			 * ERROR: unexpected character at start of value.
4185 			 */
4186 			return (NULL);
4187 		case DTRACE_JSON_COLLECT_OBJECT:
4188 			if (cc == '\0')
4189 				/*
4190 				 * ERROR: unexpected end of input.
4191 				 */
4192 				return (NULL);
4193 
4194 			*dd++ = cc;
4195 			if (cc == '"') {
4196 				collect_object = B_TRUE;
4197 				state = DTRACE_JSON_STRING;
4198 				break;
4199 			}
4200 
4201 			if (cc == ']') {
4202 				if (brackets-- == 0) {
4203 					/*
4204 					 * ERROR: unbalanced brackets.
4205 					 */
4206 					return (NULL);
4207 				}
4208 			} else if (cc == '}') {
4209 				if (braces-- == 0) {
4210 					/*
4211 					 * ERROR: unbalanced braces.
4212 					 */
4213 					return (NULL);
4214 				}
4215 			} else if (cc == '{') {
4216 				braces++;
4217 			} else if (cc == '[') {
4218 				brackets++;
4219 			}
4220 
4221 			if (brackets == 0 && braces == 0) {
4222 				if (found_key) {
4223 					*dd = '\0';
4224 					return (dest);
4225 				}
4226 				dd = dest; /* reset string buffer */
4227 				state = DTRACE_JSON_COMMA;
4228 			}
4229 			break;
4230 		}
4231 	}
4232 	return (NULL);
4233 }
4234 
4235 /*
4236  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4237  * Notice that we don't bother validating the proper number of arguments or
4238  * their types in the tuple stack.  This isn't needed because all argument
4239  * interpretation is safe because of our load safety -- the worst that can
4240  * happen is that a bogus program can obtain bogus results.
4241  */
4242 static void
4243 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4244     dtrace_key_t *tupregs, int nargs,
4245     dtrace_mstate_t *mstate, dtrace_state_t *state)
4246 {
4247 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4248 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4249 	dtrace_vstate_t *vstate = &state->dts_vstate;
4250 
4251 #ifdef illumos
4252 	union {
4253 		mutex_impl_t mi;
4254 		uint64_t mx;
4255 	} m;
4256 
4257 	union {
4258 		krwlock_t ri;
4259 		uintptr_t rw;
4260 	} r;
4261 #else
4262 	struct thread *lowner;
4263 	union {
4264 		struct lock_object *li;
4265 		uintptr_t lx;
4266 	} l;
4267 #endif
4268 
4269 	switch (subr) {
4270 	case DIF_SUBR_RAND:
4271 		regs[rd] = dtrace_xoroshiro128_plus_next(
4272 		    state->dts_rstate[curcpu]);
4273 		break;
4274 
4275 #ifdef illumos
4276 	case DIF_SUBR_MUTEX_OWNED:
4277 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4278 		    mstate, vstate)) {
4279 			regs[rd] = 0;
4280 			break;
4281 		}
4282 
4283 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4284 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4285 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4286 		else
4287 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4288 		break;
4289 
4290 	case DIF_SUBR_MUTEX_OWNER:
4291 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4292 		    mstate, vstate)) {
4293 			regs[rd] = 0;
4294 			break;
4295 		}
4296 
4297 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4298 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4299 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4300 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4301 		else
4302 			regs[rd] = 0;
4303 		break;
4304 
4305 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4306 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4307 		    mstate, vstate)) {
4308 			regs[rd] = 0;
4309 			break;
4310 		}
4311 
4312 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4313 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4314 		break;
4315 
4316 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4317 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4318 		    mstate, vstate)) {
4319 			regs[rd] = 0;
4320 			break;
4321 		}
4322 
4323 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4324 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4325 		break;
4326 
4327 	case DIF_SUBR_RW_READ_HELD: {
4328 		uintptr_t tmp;
4329 
4330 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4331 		    mstate, vstate)) {
4332 			regs[rd] = 0;
4333 			break;
4334 		}
4335 
4336 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4337 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4338 		break;
4339 	}
4340 
4341 	case DIF_SUBR_RW_WRITE_HELD:
4342 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4343 		    mstate, vstate)) {
4344 			regs[rd] = 0;
4345 			break;
4346 		}
4347 
4348 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4349 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4350 		break;
4351 
4352 	case DIF_SUBR_RW_ISWRITER:
4353 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4354 		    mstate, vstate)) {
4355 			regs[rd] = 0;
4356 			break;
4357 		}
4358 
4359 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4360 		regs[rd] = _RW_ISWRITER(&r.ri);
4361 		break;
4362 
4363 #else /* !illumos */
4364 	case DIF_SUBR_MUTEX_OWNED:
4365 		if (!dtrace_canload(tupregs[0].dttk_value,
4366 			sizeof (struct lock_object), mstate, vstate)) {
4367 			regs[rd] = 0;
4368 			break;
4369 		}
4370 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4371 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4372 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4373 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4374 		break;
4375 
4376 	case DIF_SUBR_MUTEX_OWNER:
4377 		if (!dtrace_canload(tupregs[0].dttk_value,
4378 			sizeof (struct lock_object), mstate, vstate)) {
4379 			regs[rd] = 0;
4380 			break;
4381 		}
4382 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4383 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4384 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4385 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4386 		regs[rd] = (uintptr_t)lowner;
4387 		break;
4388 
4389 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4390 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4391 		    mstate, vstate)) {
4392 			regs[rd] = 0;
4393 			break;
4394 		}
4395 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4396 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4397 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4398 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4399 		break;
4400 
4401 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4402 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4403 		    mstate, vstate)) {
4404 			regs[rd] = 0;
4405 			break;
4406 		}
4407 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4408 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4409 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4410 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4411 		break;
4412 
4413 	case DIF_SUBR_RW_READ_HELD:
4414 	case DIF_SUBR_SX_SHARED_HELD:
4415 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4416 		    mstate, vstate)) {
4417 			regs[rd] = 0;
4418 			break;
4419 		}
4420 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4421 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4422 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4423 		    lowner == NULL;
4424 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4425 		break;
4426 
4427 	case DIF_SUBR_RW_WRITE_HELD:
4428 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
4429 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4430 		    mstate, vstate)) {
4431 			regs[rd] = 0;
4432 			break;
4433 		}
4434 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4435 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4436 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4437 		    lowner != NULL;
4438 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4439 		break;
4440 
4441 	case DIF_SUBR_RW_ISWRITER:
4442 	case DIF_SUBR_SX_ISEXCLUSIVE:
4443 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4444 		    mstate, vstate)) {
4445 			regs[rd] = 0;
4446 			break;
4447 		}
4448 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4449 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4450 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4451 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4452 		regs[rd] = (lowner == curthread);
4453 		break;
4454 #endif /* illumos */
4455 
4456 	case DIF_SUBR_BCOPY: {
4457 		/*
4458 		 * We need to be sure that the destination is in the scratch
4459 		 * region -- no other region is allowed.
4460 		 */
4461 		uintptr_t src = tupregs[0].dttk_value;
4462 		uintptr_t dest = tupregs[1].dttk_value;
4463 		size_t size = tupregs[2].dttk_value;
4464 
4465 		if (!dtrace_inscratch(dest, size, mstate)) {
4466 			*flags |= CPU_DTRACE_BADADDR;
4467 			*illval = regs[rd];
4468 			break;
4469 		}
4470 
4471 		if (!dtrace_canload(src, size, mstate, vstate)) {
4472 			regs[rd] = 0;
4473 			break;
4474 		}
4475 
4476 		dtrace_bcopy((void *)src, (void *)dest, size);
4477 		break;
4478 	}
4479 
4480 	case DIF_SUBR_ALLOCA:
4481 	case DIF_SUBR_COPYIN: {
4482 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4483 		uint64_t size =
4484 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4485 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4486 
4487 		/*
4488 		 * This action doesn't require any credential checks since
4489 		 * probes will not activate in user contexts to which the
4490 		 * enabling user does not have permissions.
4491 		 */
4492 
4493 		/*
4494 		 * Rounding up the user allocation size could have overflowed
4495 		 * a large, bogus allocation (like -1ULL) to 0.
4496 		 */
4497 		if (scratch_size < size ||
4498 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4499 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4500 			regs[rd] = 0;
4501 			break;
4502 		}
4503 
4504 		if (subr == DIF_SUBR_COPYIN) {
4505 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4506 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4507 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4508 		}
4509 
4510 		mstate->dtms_scratch_ptr += scratch_size;
4511 		regs[rd] = dest;
4512 		break;
4513 	}
4514 
4515 	case DIF_SUBR_COPYINTO: {
4516 		uint64_t size = tupregs[1].dttk_value;
4517 		uintptr_t dest = tupregs[2].dttk_value;
4518 
4519 		/*
4520 		 * This action doesn't require any credential checks since
4521 		 * probes will not activate in user contexts to which the
4522 		 * enabling user does not have permissions.
4523 		 */
4524 		if (!dtrace_inscratch(dest, size, mstate)) {
4525 			*flags |= CPU_DTRACE_BADADDR;
4526 			*illval = regs[rd];
4527 			break;
4528 		}
4529 
4530 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4531 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4532 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4533 		break;
4534 	}
4535 
4536 	case DIF_SUBR_COPYINSTR: {
4537 		uintptr_t dest = mstate->dtms_scratch_ptr;
4538 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4539 
4540 		if (nargs > 1 && tupregs[1].dttk_value < size)
4541 			size = tupregs[1].dttk_value + 1;
4542 
4543 		/*
4544 		 * This action doesn't require any credential checks since
4545 		 * probes will not activate in user contexts to which the
4546 		 * enabling user does not have permissions.
4547 		 */
4548 		if (!DTRACE_INSCRATCH(mstate, size)) {
4549 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4550 			regs[rd] = 0;
4551 			break;
4552 		}
4553 
4554 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4555 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4556 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4557 
4558 		((char *)dest)[size - 1] = '\0';
4559 		mstate->dtms_scratch_ptr += size;
4560 		regs[rd] = dest;
4561 		break;
4562 	}
4563 
4564 #ifdef illumos
4565 	case DIF_SUBR_MSGSIZE:
4566 	case DIF_SUBR_MSGDSIZE: {
4567 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4568 		uintptr_t wptr, rptr;
4569 		size_t count = 0;
4570 		int cont = 0;
4571 
4572 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4573 
4574 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4575 			    vstate)) {
4576 				regs[rd] = 0;
4577 				break;
4578 			}
4579 
4580 			wptr = dtrace_loadptr(baddr +
4581 			    offsetof(mblk_t, b_wptr));
4582 
4583 			rptr = dtrace_loadptr(baddr +
4584 			    offsetof(mblk_t, b_rptr));
4585 
4586 			if (wptr < rptr) {
4587 				*flags |= CPU_DTRACE_BADADDR;
4588 				*illval = tupregs[0].dttk_value;
4589 				break;
4590 			}
4591 
4592 			daddr = dtrace_loadptr(baddr +
4593 			    offsetof(mblk_t, b_datap));
4594 
4595 			baddr = dtrace_loadptr(baddr +
4596 			    offsetof(mblk_t, b_cont));
4597 
4598 			/*
4599 			 * We want to prevent against denial-of-service here,
4600 			 * so we're only going to search the list for
4601 			 * dtrace_msgdsize_max mblks.
4602 			 */
4603 			if (cont++ > dtrace_msgdsize_max) {
4604 				*flags |= CPU_DTRACE_ILLOP;
4605 				break;
4606 			}
4607 
4608 			if (subr == DIF_SUBR_MSGDSIZE) {
4609 				if (dtrace_load8(daddr +
4610 				    offsetof(dblk_t, db_type)) != M_DATA)
4611 					continue;
4612 			}
4613 
4614 			count += wptr - rptr;
4615 		}
4616 
4617 		if (!(*flags & CPU_DTRACE_FAULT))
4618 			regs[rd] = count;
4619 
4620 		break;
4621 	}
4622 #endif
4623 
4624 	case DIF_SUBR_PROGENYOF: {
4625 		pid_t pid = tupregs[0].dttk_value;
4626 		proc_t *p;
4627 		int rval = 0;
4628 
4629 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4630 
4631 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4632 #ifdef illumos
4633 			if (p->p_pidp->pid_id == pid) {
4634 #else
4635 			if (p->p_pid == pid) {
4636 #endif
4637 				rval = 1;
4638 				break;
4639 			}
4640 		}
4641 
4642 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4643 
4644 		regs[rd] = rval;
4645 		break;
4646 	}
4647 
4648 	case DIF_SUBR_SPECULATION:
4649 		regs[rd] = dtrace_speculation(state);
4650 		break;
4651 
4652 	case DIF_SUBR_COPYOUT: {
4653 		uintptr_t kaddr = tupregs[0].dttk_value;
4654 		uintptr_t uaddr = tupregs[1].dttk_value;
4655 		uint64_t size = tupregs[2].dttk_value;
4656 
4657 		if (!dtrace_destructive_disallow &&
4658 		    dtrace_priv_proc_control(state) &&
4659 		    !dtrace_istoxic(kaddr, size) &&
4660 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4661 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4662 			dtrace_copyout(kaddr, uaddr, size, flags);
4663 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4664 		}
4665 		break;
4666 	}
4667 
4668 	case DIF_SUBR_COPYOUTSTR: {
4669 		uintptr_t kaddr = tupregs[0].dttk_value;
4670 		uintptr_t uaddr = tupregs[1].dttk_value;
4671 		uint64_t size = tupregs[2].dttk_value;
4672 		size_t lim;
4673 
4674 		if (!dtrace_destructive_disallow &&
4675 		    dtrace_priv_proc_control(state) &&
4676 		    !dtrace_istoxic(kaddr, size) &&
4677 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4678 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4679 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4680 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4681 		}
4682 		break;
4683 	}
4684 
4685 	case DIF_SUBR_STRLEN: {
4686 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4687 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4688 		size_t lim;
4689 
4690 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4691 			regs[rd] = 0;
4692 			break;
4693 		}
4694 
4695 		regs[rd] = dtrace_strlen((char *)addr, lim);
4696 		break;
4697 	}
4698 
4699 	case DIF_SUBR_STRCHR:
4700 	case DIF_SUBR_STRRCHR: {
4701 		/*
4702 		 * We're going to iterate over the string looking for the
4703 		 * specified character.  We will iterate until we have reached
4704 		 * the string length or we have found the character.  If this
4705 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4706 		 * of the specified character instead of the first.
4707 		 */
4708 		uintptr_t addr = tupregs[0].dttk_value;
4709 		uintptr_t addr_limit;
4710 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4711 		size_t lim;
4712 		char c, target = (char)tupregs[1].dttk_value;
4713 
4714 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4715 			regs[rd] = 0;
4716 			break;
4717 		}
4718 		addr_limit = addr + lim;
4719 
4720 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4721 			if ((c = dtrace_load8(addr)) == target) {
4722 				regs[rd] = addr;
4723 
4724 				if (subr == DIF_SUBR_STRCHR)
4725 					break;
4726 			}
4727 
4728 			if (c == '\0')
4729 				break;
4730 		}
4731 		break;
4732 	}
4733 
4734 	case DIF_SUBR_STRSTR:
4735 	case DIF_SUBR_INDEX:
4736 	case DIF_SUBR_RINDEX: {
4737 		/*
4738 		 * We're going to iterate over the string looking for the
4739 		 * specified string.  We will iterate until we have reached
4740 		 * the string length or we have found the string.  (Yes, this
4741 		 * is done in the most naive way possible -- but considering
4742 		 * that the string we're searching for is likely to be
4743 		 * relatively short, the complexity of Rabin-Karp or similar
4744 		 * hardly seems merited.)
4745 		 */
4746 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4747 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4748 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4749 		size_t len = dtrace_strlen(addr, size);
4750 		size_t sublen = dtrace_strlen(substr, size);
4751 		char *limit = addr + len, *orig = addr;
4752 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4753 		int inc = 1;
4754 
4755 		regs[rd] = notfound;
4756 
4757 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4758 			regs[rd] = 0;
4759 			break;
4760 		}
4761 
4762 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4763 		    vstate)) {
4764 			regs[rd] = 0;
4765 			break;
4766 		}
4767 
4768 		/*
4769 		 * strstr() and index()/rindex() have similar semantics if
4770 		 * both strings are the empty string: strstr() returns a
4771 		 * pointer to the (empty) string, and index() and rindex()
4772 		 * both return index 0 (regardless of any position argument).
4773 		 */
4774 		if (sublen == 0 && len == 0) {
4775 			if (subr == DIF_SUBR_STRSTR)
4776 				regs[rd] = (uintptr_t)addr;
4777 			else
4778 				regs[rd] = 0;
4779 			break;
4780 		}
4781 
4782 		if (subr != DIF_SUBR_STRSTR) {
4783 			if (subr == DIF_SUBR_RINDEX) {
4784 				limit = orig - 1;
4785 				addr += len;
4786 				inc = -1;
4787 			}
4788 
4789 			/*
4790 			 * Both index() and rindex() take an optional position
4791 			 * argument that denotes the starting position.
4792 			 */
4793 			if (nargs == 3) {
4794 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4795 
4796 				/*
4797 				 * If the position argument to index() is
4798 				 * negative, Perl implicitly clamps it at
4799 				 * zero.  This semantic is a little surprising
4800 				 * given the special meaning of negative
4801 				 * positions to similar Perl functions like
4802 				 * substr(), but it appears to reflect a
4803 				 * notion that index() can start from a
4804 				 * negative index and increment its way up to
4805 				 * the string.  Given this notion, Perl's
4806 				 * rindex() is at least self-consistent in
4807 				 * that it implicitly clamps positions greater
4808 				 * than the string length to be the string
4809 				 * length.  Where Perl completely loses
4810 				 * coherence, however, is when the specified
4811 				 * substring is the empty string ("").  In
4812 				 * this case, even if the position is
4813 				 * negative, rindex() returns 0 -- and even if
4814 				 * the position is greater than the length,
4815 				 * index() returns the string length.  These
4816 				 * semantics violate the notion that index()
4817 				 * should never return a value less than the
4818 				 * specified position and that rindex() should
4819 				 * never return a value greater than the
4820 				 * specified position.  (One assumes that
4821 				 * these semantics are artifacts of Perl's
4822 				 * implementation and not the results of
4823 				 * deliberate design -- it beggars belief that
4824 				 * even Larry Wall could desire such oddness.)
4825 				 * While in the abstract one would wish for
4826 				 * consistent position semantics across
4827 				 * substr(), index() and rindex() -- or at the
4828 				 * very least self-consistent position
4829 				 * semantics for index() and rindex() -- we
4830 				 * instead opt to keep with the extant Perl
4831 				 * semantics, in all their broken glory.  (Do
4832 				 * we have more desire to maintain Perl's
4833 				 * semantics than Perl does?  Probably.)
4834 				 */
4835 				if (subr == DIF_SUBR_RINDEX) {
4836 					if (pos < 0) {
4837 						if (sublen == 0)
4838 							regs[rd] = 0;
4839 						break;
4840 					}
4841 
4842 					if (pos > len)
4843 						pos = len;
4844 				} else {
4845 					if (pos < 0)
4846 						pos = 0;
4847 
4848 					if (pos >= len) {
4849 						if (sublen == 0)
4850 							regs[rd] = len;
4851 						break;
4852 					}
4853 				}
4854 
4855 				addr = orig + pos;
4856 			}
4857 		}
4858 
4859 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4860 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4861 				if (subr != DIF_SUBR_STRSTR) {
4862 					/*
4863 					 * As D index() and rindex() are
4864 					 * modeled on Perl (and not on awk),
4865 					 * we return a zero-based (and not a
4866 					 * one-based) index.  (For you Perl
4867 					 * weenies: no, we're not going to add
4868 					 * $[ -- and shouldn't you be at a con
4869 					 * or something?)
4870 					 */
4871 					regs[rd] = (uintptr_t)(addr - orig);
4872 					break;
4873 				}
4874 
4875 				ASSERT(subr == DIF_SUBR_STRSTR);
4876 				regs[rd] = (uintptr_t)addr;
4877 				break;
4878 			}
4879 		}
4880 
4881 		break;
4882 	}
4883 
4884 	case DIF_SUBR_STRTOK: {
4885 		uintptr_t addr = tupregs[0].dttk_value;
4886 		uintptr_t tokaddr = tupregs[1].dttk_value;
4887 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4888 		uintptr_t limit, toklimit;
4889 		size_t clim;
4890 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4891 		char *dest = (char *)mstate->dtms_scratch_ptr;
4892 		int i;
4893 
4894 		/*
4895 		 * Check both the token buffer and (later) the input buffer,
4896 		 * since both could be non-scratch addresses.
4897 		 */
4898 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4899 			regs[rd] = 0;
4900 			break;
4901 		}
4902 		toklimit = tokaddr + clim;
4903 
4904 		if (!DTRACE_INSCRATCH(mstate, size)) {
4905 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4906 			regs[rd] = 0;
4907 			break;
4908 		}
4909 
4910 		if (addr == 0) {
4911 			/*
4912 			 * If the address specified is NULL, we use our saved
4913 			 * strtok pointer from the mstate.  Note that this
4914 			 * means that the saved strtok pointer is _only_
4915 			 * valid within multiple enablings of the same probe --
4916 			 * it behaves like an implicit clause-local variable.
4917 			 */
4918 			addr = mstate->dtms_strtok;
4919 			limit = mstate->dtms_strtok_limit;
4920 		} else {
4921 			/*
4922 			 * If the user-specified address is non-NULL we must
4923 			 * access check it.  This is the only time we have
4924 			 * a chance to do so, since this address may reside
4925 			 * in the string table of this clause-- future calls
4926 			 * (when we fetch addr from mstate->dtms_strtok)
4927 			 * would fail this access check.
4928 			 */
4929 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4930 			    vstate)) {
4931 				regs[rd] = 0;
4932 				break;
4933 			}
4934 			limit = addr + clim;
4935 		}
4936 
4937 		/*
4938 		 * First, zero the token map, and then process the token
4939 		 * string -- setting a bit in the map for every character
4940 		 * found in the token string.
4941 		 */
4942 		for (i = 0; i < sizeof (tokmap); i++)
4943 			tokmap[i] = 0;
4944 
4945 		for (; tokaddr < toklimit; tokaddr++) {
4946 			if ((c = dtrace_load8(tokaddr)) == '\0')
4947 				break;
4948 
4949 			ASSERT((c >> 3) < sizeof (tokmap));
4950 			tokmap[c >> 3] |= (1 << (c & 0x7));
4951 		}
4952 
4953 		for (; addr < limit; addr++) {
4954 			/*
4955 			 * We're looking for a character that is _not_
4956 			 * contained in the token string.
4957 			 */
4958 			if ((c = dtrace_load8(addr)) == '\0')
4959 				break;
4960 
4961 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4962 				break;
4963 		}
4964 
4965 		if (c == '\0') {
4966 			/*
4967 			 * We reached the end of the string without finding
4968 			 * any character that was not in the token string.
4969 			 * We return NULL in this case, and we set the saved
4970 			 * address to NULL as well.
4971 			 */
4972 			regs[rd] = 0;
4973 			mstate->dtms_strtok = 0;
4974 			mstate->dtms_strtok_limit = 0;
4975 			break;
4976 		}
4977 
4978 		/*
4979 		 * From here on, we're copying into the destination string.
4980 		 */
4981 		for (i = 0; addr < limit && i < size - 1; addr++) {
4982 			if ((c = dtrace_load8(addr)) == '\0')
4983 				break;
4984 
4985 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4986 				break;
4987 
4988 			ASSERT(i < size);
4989 			dest[i++] = c;
4990 		}
4991 
4992 		ASSERT(i < size);
4993 		dest[i] = '\0';
4994 		regs[rd] = (uintptr_t)dest;
4995 		mstate->dtms_scratch_ptr += size;
4996 		mstate->dtms_strtok = addr;
4997 		mstate->dtms_strtok_limit = limit;
4998 		break;
4999 	}
5000 
5001 	case DIF_SUBR_SUBSTR: {
5002 		uintptr_t s = tupregs[0].dttk_value;
5003 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5004 		char *d = (char *)mstate->dtms_scratch_ptr;
5005 		int64_t index = (int64_t)tupregs[1].dttk_value;
5006 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
5007 		size_t len = dtrace_strlen((char *)s, size);
5008 		int64_t i;
5009 
5010 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5011 			regs[rd] = 0;
5012 			break;
5013 		}
5014 
5015 		if (!DTRACE_INSCRATCH(mstate, size)) {
5016 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5017 			regs[rd] = 0;
5018 			break;
5019 		}
5020 
5021 		if (nargs <= 2)
5022 			remaining = (int64_t)size;
5023 
5024 		if (index < 0) {
5025 			index += len;
5026 
5027 			if (index < 0 && index + remaining > 0) {
5028 				remaining += index;
5029 				index = 0;
5030 			}
5031 		}
5032 
5033 		if (index >= len || index < 0) {
5034 			remaining = 0;
5035 		} else if (remaining < 0) {
5036 			remaining += len - index;
5037 		} else if (index + remaining > size) {
5038 			remaining = size - index;
5039 		}
5040 
5041 		for (i = 0; i < remaining; i++) {
5042 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5043 				break;
5044 		}
5045 
5046 		d[i] = '\0';
5047 
5048 		mstate->dtms_scratch_ptr += size;
5049 		regs[rd] = (uintptr_t)d;
5050 		break;
5051 	}
5052 
5053 	case DIF_SUBR_JSON: {
5054 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5055 		uintptr_t json = tupregs[0].dttk_value;
5056 		size_t jsonlen = dtrace_strlen((char *)json, size);
5057 		uintptr_t elem = tupregs[1].dttk_value;
5058 		size_t elemlen = dtrace_strlen((char *)elem, size);
5059 
5060 		char *dest = (char *)mstate->dtms_scratch_ptr;
5061 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5062 		char *ee = elemlist;
5063 		int nelems = 1;
5064 		uintptr_t cur;
5065 
5066 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5067 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5068 			regs[rd] = 0;
5069 			break;
5070 		}
5071 
5072 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5073 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5074 			regs[rd] = 0;
5075 			break;
5076 		}
5077 
5078 		/*
5079 		 * Read the element selector and split it up into a packed list
5080 		 * of strings.
5081 		 */
5082 		for (cur = elem; cur < elem + elemlen; cur++) {
5083 			char cc = dtrace_load8(cur);
5084 
5085 			if (cur == elem && cc == '[') {
5086 				/*
5087 				 * If the first element selector key is
5088 				 * actually an array index then ignore the
5089 				 * bracket.
5090 				 */
5091 				continue;
5092 			}
5093 
5094 			if (cc == ']')
5095 				continue;
5096 
5097 			if (cc == '.' || cc == '[') {
5098 				nelems++;
5099 				cc = '\0';
5100 			}
5101 
5102 			*ee++ = cc;
5103 		}
5104 		*ee++ = '\0';
5105 
5106 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5107 		    nelems, dest)) != 0)
5108 			mstate->dtms_scratch_ptr += jsonlen + 1;
5109 		break;
5110 	}
5111 
5112 	case DIF_SUBR_TOUPPER:
5113 	case DIF_SUBR_TOLOWER: {
5114 		uintptr_t s = tupregs[0].dttk_value;
5115 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5116 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5117 		size_t len = dtrace_strlen((char *)s, size);
5118 		char lower, upper, convert;
5119 		int64_t i;
5120 
5121 		if (subr == DIF_SUBR_TOUPPER) {
5122 			lower = 'a';
5123 			upper = 'z';
5124 			convert = 'A';
5125 		} else {
5126 			lower = 'A';
5127 			upper = 'Z';
5128 			convert = 'a';
5129 		}
5130 
5131 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5132 			regs[rd] = 0;
5133 			break;
5134 		}
5135 
5136 		if (!DTRACE_INSCRATCH(mstate, size)) {
5137 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5138 			regs[rd] = 0;
5139 			break;
5140 		}
5141 
5142 		for (i = 0; i < size - 1; i++) {
5143 			if ((c = dtrace_load8(s + i)) == '\0')
5144 				break;
5145 
5146 			if (c >= lower && c <= upper)
5147 				c = convert + (c - lower);
5148 
5149 			dest[i] = c;
5150 		}
5151 
5152 		ASSERT(i < size);
5153 		dest[i] = '\0';
5154 		regs[rd] = (uintptr_t)dest;
5155 		mstate->dtms_scratch_ptr += size;
5156 		break;
5157 	}
5158 
5159 #ifdef illumos
5160 	case DIF_SUBR_GETMAJOR:
5161 #ifdef _LP64
5162 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5163 #else
5164 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5165 #endif
5166 		break;
5167 
5168 	case DIF_SUBR_GETMINOR:
5169 #ifdef _LP64
5170 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5171 #else
5172 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
5173 #endif
5174 		break;
5175 
5176 	case DIF_SUBR_DDI_PATHNAME: {
5177 		/*
5178 		 * This one is a galactic mess.  We are going to roughly
5179 		 * emulate ddi_pathname(), but it's made more complicated
5180 		 * by the fact that we (a) want to include the minor name and
5181 		 * (b) must proceed iteratively instead of recursively.
5182 		 */
5183 		uintptr_t dest = mstate->dtms_scratch_ptr;
5184 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5185 		char *start = (char *)dest, *end = start + size - 1;
5186 		uintptr_t daddr = tupregs[0].dttk_value;
5187 		int64_t minor = (int64_t)tupregs[1].dttk_value;
5188 		char *s;
5189 		int i, len, depth = 0;
5190 
5191 		/*
5192 		 * Due to all the pointer jumping we do and context we must
5193 		 * rely upon, we just mandate that the user must have kernel
5194 		 * read privileges to use this routine.
5195 		 */
5196 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5197 			*flags |= CPU_DTRACE_KPRIV;
5198 			*illval = daddr;
5199 			regs[rd] = 0;
5200 		}
5201 
5202 		if (!DTRACE_INSCRATCH(mstate, size)) {
5203 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5204 			regs[rd] = 0;
5205 			break;
5206 		}
5207 
5208 		*end = '\0';
5209 
5210 		/*
5211 		 * We want to have a name for the minor.  In order to do this,
5212 		 * we need to walk the minor list from the devinfo.  We want
5213 		 * to be sure that we don't infinitely walk a circular list,
5214 		 * so we check for circularity by sending a scout pointer
5215 		 * ahead two elements for every element that we iterate over;
5216 		 * if the list is circular, these will ultimately point to the
5217 		 * same element.  You may recognize this little trick as the
5218 		 * answer to a stupid interview question -- one that always
5219 		 * seems to be asked by those who had to have it laboriously
5220 		 * explained to them, and who can't even concisely describe
5221 		 * the conditions under which one would be forced to resort to
5222 		 * this technique.  Needless to say, those conditions are
5223 		 * found here -- and probably only here.  Is this the only use
5224 		 * of this infamous trick in shipping, production code?  If it
5225 		 * isn't, it probably should be...
5226 		 */
5227 		if (minor != -1) {
5228 			uintptr_t maddr = dtrace_loadptr(daddr +
5229 			    offsetof(struct dev_info, devi_minor));
5230 
5231 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5232 			uintptr_t name = offsetof(struct ddi_minor_data,
5233 			    d_minor) + offsetof(struct ddi_minor, name);
5234 			uintptr_t dev = offsetof(struct ddi_minor_data,
5235 			    d_minor) + offsetof(struct ddi_minor, dev);
5236 			uintptr_t scout;
5237 
5238 			if (maddr != NULL)
5239 				scout = dtrace_loadptr(maddr + next);
5240 
5241 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5242 				uint64_t m;
5243 #ifdef _LP64
5244 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5245 #else
5246 				m = dtrace_load32(maddr + dev) & MAXMIN;
5247 #endif
5248 				if (m != minor) {
5249 					maddr = dtrace_loadptr(maddr + next);
5250 
5251 					if (scout == NULL)
5252 						continue;
5253 
5254 					scout = dtrace_loadptr(scout + next);
5255 
5256 					if (scout == NULL)
5257 						continue;
5258 
5259 					scout = dtrace_loadptr(scout + next);
5260 
5261 					if (scout == NULL)
5262 						continue;
5263 
5264 					if (scout == maddr) {
5265 						*flags |= CPU_DTRACE_ILLOP;
5266 						break;
5267 					}
5268 
5269 					continue;
5270 				}
5271 
5272 				/*
5273 				 * We have the minor data.  Now we need to
5274 				 * copy the minor's name into the end of the
5275 				 * pathname.
5276 				 */
5277 				s = (char *)dtrace_loadptr(maddr + name);
5278 				len = dtrace_strlen(s, size);
5279 
5280 				if (*flags & CPU_DTRACE_FAULT)
5281 					break;
5282 
5283 				if (len != 0) {
5284 					if ((end -= (len + 1)) < start)
5285 						break;
5286 
5287 					*end = ':';
5288 				}
5289 
5290 				for (i = 1; i <= len; i++)
5291 					end[i] = dtrace_load8((uintptr_t)s++);
5292 				break;
5293 			}
5294 		}
5295 
5296 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5297 			ddi_node_state_t devi_state;
5298 
5299 			devi_state = dtrace_load32(daddr +
5300 			    offsetof(struct dev_info, devi_node_state));
5301 
5302 			if (*flags & CPU_DTRACE_FAULT)
5303 				break;
5304 
5305 			if (devi_state >= DS_INITIALIZED) {
5306 				s = (char *)dtrace_loadptr(daddr +
5307 				    offsetof(struct dev_info, devi_addr));
5308 				len = dtrace_strlen(s, size);
5309 
5310 				if (*flags & CPU_DTRACE_FAULT)
5311 					break;
5312 
5313 				if (len != 0) {
5314 					if ((end -= (len + 1)) < start)
5315 						break;
5316 
5317 					*end = '@';
5318 				}
5319 
5320 				for (i = 1; i <= len; i++)
5321 					end[i] = dtrace_load8((uintptr_t)s++);
5322 			}
5323 
5324 			/*
5325 			 * Now for the node name...
5326 			 */
5327 			s = (char *)dtrace_loadptr(daddr +
5328 			    offsetof(struct dev_info, devi_node_name));
5329 
5330 			daddr = dtrace_loadptr(daddr +
5331 			    offsetof(struct dev_info, devi_parent));
5332 
5333 			/*
5334 			 * If our parent is NULL (that is, if we're the root
5335 			 * node), we're going to use the special path
5336 			 * "devices".
5337 			 */
5338 			if (daddr == 0)
5339 				s = "devices";
5340 
5341 			len = dtrace_strlen(s, size);
5342 			if (*flags & CPU_DTRACE_FAULT)
5343 				break;
5344 
5345 			if ((end -= (len + 1)) < start)
5346 				break;
5347 
5348 			for (i = 1; i <= len; i++)
5349 				end[i] = dtrace_load8((uintptr_t)s++);
5350 			*end = '/';
5351 
5352 			if (depth++ > dtrace_devdepth_max) {
5353 				*flags |= CPU_DTRACE_ILLOP;
5354 				break;
5355 			}
5356 		}
5357 
5358 		if (end < start)
5359 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5360 
5361 		if (daddr == 0) {
5362 			regs[rd] = (uintptr_t)end;
5363 			mstate->dtms_scratch_ptr += size;
5364 		}
5365 
5366 		break;
5367 	}
5368 #endif
5369 
5370 	case DIF_SUBR_STRJOIN: {
5371 		char *d = (char *)mstate->dtms_scratch_ptr;
5372 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5373 		uintptr_t s1 = tupregs[0].dttk_value;
5374 		uintptr_t s2 = tupregs[1].dttk_value;
5375 		int i = 0, j = 0;
5376 		size_t lim1, lim2;
5377 		char c;
5378 
5379 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5380 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5381 			regs[rd] = 0;
5382 			break;
5383 		}
5384 
5385 		if (!DTRACE_INSCRATCH(mstate, size)) {
5386 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5387 			regs[rd] = 0;
5388 			break;
5389 		}
5390 
5391 		for (;;) {
5392 			if (i >= size) {
5393 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5394 				regs[rd] = 0;
5395 				break;
5396 			}
5397 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5398 			if ((d[i++] = c) == '\0') {
5399 				i--;
5400 				break;
5401 			}
5402 		}
5403 
5404 		for (;;) {
5405 			if (i >= size) {
5406 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5407 				regs[rd] = 0;
5408 				break;
5409 			}
5410 
5411 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5412 			if ((d[i++] = c) == '\0')
5413 				break;
5414 		}
5415 
5416 		if (i < size) {
5417 			mstate->dtms_scratch_ptr += i;
5418 			regs[rd] = (uintptr_t)d;
5419 		}
5420 
5421 		break;
5422 	}
5423 
5424 	case DIF_SUBR_STRTOLL: {
5425 		uintptr_t s = tupregs[0].dttk_value;
5426 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5427 		size_t lim;
5428 		int base = 10;
5429 
5430 		if (nargs > 1) {
5431 			if ((base = tupregs[1].dttk_value) <= 1 ||
5432 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5433 				*flags |= CPU_DTRACE_ILLOP;
5434 				break;
5435 			}
5436 		}
5437 
5438 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5439 			regs[rd] = INT64_MIN;
5440 			break;
5441 		}
5442 
5443 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5444 		break;
5445 	}
5446 
5447 	case DIF_SUBR_LLTOSTR: {
5448 		int64_t i = (int64_t)tupregs[0].dttk_value;
5449 		uint64_t val, digit;
5450 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5451 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5452 		int base = 10;
5453 
5454 		if (nargs > 1) {
5455 			if ((base = tupregs[1].dttk_value) <= 1 ||
5456 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5457 				*flags |= CPU_DTRACE_ILLOP;
5458 				break;
5459 			}
5460 		}
5461 
5462 		val = (base == 10 && i < 0) ? i * -1 : i;
5463 
5464 		if (!DTRACE_INSCRATCH(mstate, size)) {
5465 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5466 			regs[rd] = 0;
5467 			break;
5468 		}
5469 
5470 		for (*end-- = '\0'; val; val /= base) {
5471 			if ((digit = val % base) <= '9' - '0') {
5472 				*end-- = '0' + digit;
5473 			} else {
5474 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5475 			}
5476 		}
5477 
5478 		if (i == 0 && base == 16)
5479 			*end-- = '0';
5480 
5481 		if (base == 16)
5482 			*end-- = 'x';
5483 
5484 		if (i == 0 || base == 8 || base == 16)
5485 			*end-- = '0';
5486 
5487 		if (i < 0 && base == 10)
5488 			*end-- = '-';
5489 
5490 		regs[rd] = (uintptr_t)end + 1;
5491 		mstate->dtms_scratch_ptr += size;
5492 		break;
5493 	}
5494 
5495 	case DIF_SUBR_HTONS:
5496 	case DIF_SUBR_NTOHS:
5497 #if BYTE_ORDER == BIG_ENDIAN
5498 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5499 #else
5500 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5501 #endif
5502 		break;
5503 
5504 
5505 	case DIF_SUBR_HTONL:
5506 	case DIF_SUBR_NTOHL:
5507 #if BYTE_ORDER == BIG_ENDIAN
5508 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5509 #else
5510 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5511 #endif
5512 		break;
5513 
5514 
5515 	case DIF_SUBR_HTONLL:
5516 	case DIF_SUBR_NTOHLL:
5517 #if BYTE_ORDER == BIG_ENDIAN
5518 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5519 #else
5520 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5521 #endif
5522 		break;
5523 
5524 
5525 	case DIF_SUBR_DIRNAME:
5526 	case DIF_SUBR_BASENAME: {
5527 		char *dest = (char *)mstate->dtms_scratch_ptr;
5528 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5529 		uintptr_t src = tupregs[0].dttk_value;
5530 		int i, j, len = dtrace_strlen((char *)src, size);
5531 		int lastbase = -1, firstbase = -1, lastdir = -1;
5532 		int start, end;
5533 
5534 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5535 			regs[rd] = 0;
5536 			break;
5537 		}
5538 
5539 		if (!DTRACE_INSCRATCH(mstate, size)) {
5540 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5541 			regs[rd] = 0;
5542 			break;
5543 		}
5544 
5545 		/*
5546 		 * The basename and dirname for a zero-length string is
5547 		 * defined to be "."
5548 		 */
5549 		if (len == 0) {
5550 			len = 1;
5551 			src = (uintptr_t)".";
5552 		}
5553 
5554 		/*
5555 		 * Start from the back of the string, moving back toward the
5556 		 * front until we see a character that isn't a slash.  That
5557 		 * character is the last character in the basename.
5558 		 */
5559 		for (i = len - 1; i >= 0; i--) {
5560 			if (dtrace_load8(src + i) != '/')
5561 				break;
5562 		}
5563 
5564 		if (i >= 0)
5565 			lastbase = i;
5566 
5567 		/*
5568 		 * Starting from the last character in the basename, move
5569 		 * towards the front until we find a slash.  The character
5570 		 * that we processed immediately before that is the first
5571 		 * character in the basename.
5572 		 */
5573 		for (; i >= 0; i--) {
5574 			if (dtrace_load8(src + i) == '/')
5575 				break;
5576 		}
5577 
5578 		if (i >= 0)
5579 			firstbase = i + 1;
5580 
5581 		/*
5582 		 * Now keep going until we find a non-slash character.  That
5583 		 * character is the last character in the dirname.
5584 		 */
5585 		for (; i >= 0; i--) {
5586 			if (dtrace_load8(src + i) != '/')
5587 				break;
5588 		}
5589 
5590 		if (i >= 0)
5591 			lastdir = i;
5592 
5593 		ASSERT(!(lastbase == -1 && firstbase != -1));
5594 		ASSERT(!(firstbase == -1 && lastdir != -1));
5595 
5596 		if (lastbase == -1) {
5597 			/*
5598 			 * We didn't find a non-slash character.  We know that
5599 			 * the length is non-zero, so the whole string must be
5600 			 * slashes.  In either the dirname or the basename
5601 			 * case, we return '/'.
5602 			 */
5603 			ASSERT(firstbase == -1);
5604 			firstbase = lastbase = lastdir = 0;
5605 		}
5606 
5607 		if (firstbase == -1) {
5608 			/*
5609 			 * The entire string consists only of a basename
5610 			 * component.  If we're looking for dirname, we need
5611 			 * to change our string to be just "."; if we're
5612 			 * looking for a basename, we'll just set the first
5613 			 * character of the basename to be 0.
5614 			 */
5615 			if (subr == DIF_SUBR_DIRNAME) {
5616 				ASSERT(lastdir == -1);
5617 				src = (uintptr_t)".";
5618 				lastdir = 0;
5619 			} else {
5620 				firstbase = 0;
5621 			}
5622 		}
5623 
5624 		if (subr == DIF_SUBR_DIRNAME) {
5625 			if (lastdir == -1) {
5626 				/*
5627 				 * We know that we have a slash in the name --
5628 				 * or lastdir would be set to 0, above.  And
5629 				 * because lastdir is -1, we know that this
5630 				 * slash must be the first character.  (That
5631 				 * is, the full string must be of the form
5632 				 * "/basename".)  In this case, the last
5633 				 * character of the directory name is 0.
5634 				 */
5635 				lastdir = 0;
5636 			}
5637 
5638 			start = 0;
5639 			end = lastdir;
5640 		} else {
5641 			ASSERT(subr == DIF_SUBR_BASENAME);
5642 			ASSERT(firstbase != -1 && lastbase != -1);
5643 			start = firstbase;
5644 			end = lastbase;
5645 		}
5646 
5647 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5648 			dest[j] = dtrace_load8(src + i);
5649 
5650 		dest[j] = '\0';
5651 		regs[rd] = (uintptr_t)dest;
5652 		mstate->dtms_scratch_ptr += size;
5653 		break;
5654 	}
5655 
5656 	case DIF_SUBR_GETF: {
5657 		uintptr_t fd = tupregs[0].dttk_value;
5658 		struct filedesc *fdp;
5659 		file_t *fp;
5660 
5661 		if (!dtrace_priv_proc(state)) {
5662 			regs[rd] = 0;
5663 			break;
5664 		}
5665 		fdp = curproc->p_fd;
5666 		FILEDESC_SLOCK(fdp);
5667 		fp = fget_locked(fdp, fd);
5668 		mstate->dtms_getf = fp;
5669 		regs[rd] = (uintptr_t)fp;
5670 		FILEDESC_SUNLOCK(fdp);
5671 		break;
5672 	}
5673 
5674 	case DIF_SUBR_CLEANPATH: {
5675 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5676 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5677 		uintptr_t src = tupregs[0].dttk_value;
5678 		size_t lim;
5679 		int i = 0, j = 0;
5680 #ifdef illumos
5681 		zone_t *z;
5682 #endif
5683 
5684 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5685 			regs[rd] = 0;
5686 			break;
5687 		}
5688 
5689 		if (!DTRACE_INSCRATCH(mstate, size)) {
5690 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5691 			regs[rd] = 0;
5692 			break;
5693 		}
5694 
5695 		/*
5696 		 * Move forward, loading each character.
5697 		 */
5698 		do {
5699 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5700 next:
5701 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5702 				break;
5703 
5704 			if (c != '/') {
5705 				dest[j++] = c;
5706 				continue;
5707 			}
5708 
5709 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5710 
5711 			if (c == '/') {
5712 				/*
5713 				 * We have two slashes -- we can just advance
5714 				 * to the next character.
5715 				 */
5716 				goto next;
5717 			}
5718 
5719 			if (c != '.') {
5720 				/*
5721 				 * This is not "." and it's not ".." -- we can
5722 				 * just store the "/" and this character and
5723 				 * drive on.
5724 				 */
5725 				dest[j++] = '/';
5726 				dest[j++] = c;
5727 				continue;
5728 			}
5729 
5730 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5731 
5732 			if (c == '/') {
5733 				/*
5734 				 * This is a "/./" component.  We're not going
5735 				 * to store anything in the destination buffer;
5736 				 * we're just going to go to the next component.
5737 				 */
5738 				goto next;
5739 			}
5740 
5741 			if (c != '.') {
5742 				/*
5743 				 * This is not ".." -- we can just store the
5744 				 * "/." and this character and continue
5745 				 * processing.
5746 				 */
5747 				dest[j++] = '/';
5748 				dest[j++] = '.';
5749 				dest[j++] = c;
5750 				continue;
5751 			}
5752 
5753 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5754 
5755 			if (c != '/' && c != '\0') {
5756 				/*
5757 				 * This is not ".." -- it's "..[mumble]".
5758 				 * We'll store the "/.." and this character
5759 				 * and continue processing.
5760 				 */
5761 				dest[j++] = '/';
5762 				dest[j++] = '.';
5763 				dest[j++] = '.';
5764 				dest[j++] = c;
5765 				continue;
5766 			}
5767 
5768 			/*
5769 			 * This is "/../" or "/..\0".  We need to back up
5770 			 * our destination pointer until we find a "/".
5771 			 */
5772 			i--;
5773 			while (j != 0 && dest[--j] != '/')
5774 				continue;
5775 
5776 			if (c == '\0')
5777 				dest[++j] = '/';
5778 		} while (c != '\0');
5779 
5780 		dest[j] = '\0';
5781 
5782 #ifdef illumos
5783 		if (mstate->dtms_getf != NULL &&
5784 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5785 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5786 			/*
5787 			 * If we've done a getf() as a part of this ECB and we
5788 			 * don't have kernel access (and we're not in the global
5789 			 * zone), check if the path we cleaned up begins with
5790 			 * the zone's root path, and trim it off if so.  Note
5791 			 * that this is an output cleanliness issue, not a
5792 			 * security issue: knowing one's zone root path does
5793 			 * not enable privilege escalation.
5794 			 */
5795 			if (strstr(dest, z->zone_rootpath) == dest)
5796 				dest += strlen(z->zone_rootpath) - 1;
5797 		}
5798 #endif
5799 
5800 		regs[rd] = (uintptr_t)dest;
5801 		mstate->dtms_scratch_ptr += size;
5802 		break;
5803 	}
5804 
5805 	case DIF_SUBR_INET_NTOA:
5806 	case DIF_SUBR_INET_NTOA6:
5807 	case DIF_SUBR_INET_NTOP: {
5808 		size_t size;
5809 		int af, argi, i;
5810 		char *base, *end;
5811 
5812 		if (subr == DIF_SUBR_INET_NTOP) {
5813 			af = (int)tupregs[0].dttk_value;
5814 			argi = 1;
5815 		} else {
5816 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5817 			argi = 0;
5818 		}
5819 
5820 		if (af == AF_INET) {
5821 			ipaddr_t ip4;
5822 			uint8_t *ptr8, val;
5823 
5824 			if (!dtrace_canload(tupregs[argi].dttk_value,
5825 			    sizeof (ipaddr_t), mstate, vstate)) {
5826 				regs[rd] = 0;
5827 				break;
5828 			}
5829 
5830 			/*
5831 			 * Safely load the IPv4 address.
5832 			 */
5833 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5834 
5835 			/*
5836 			 * Check an IPv4 string will fit in scratch.
5837 			 */
5838 			size = INET_ADDRSTRLEN;
5839 			if (!DTRACE_INSCRATCH(mstate, size)) {
5840 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5841 				regs[rd] = 0;
5842 				break;
5843 			}
5844 			base = (char *)mstate->dtms_scratch_ptr;
5845 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5846 
5847 			/*
5848 			 * Stringify as a dotted decimal quad.
5849 			 */
5850 			*end-- = '\0';
5851 			ptr8 = (uint8_t *)&ip4;
5852 			for (i = 3; i >= 0; i--) {
5853 				val = ptr8[i];
5854 
5855 				if (val == 0) {
5856 					*end-- = '0';
5857 				} else {
5858 					for (; val; val /= 10) {
5859 						*end-- = '0' + (val % 10);
5860 					}
5861 				}
5862 
5863 				if (i > 0)
5864 					*end-- = '.';
5865 			}
5866 			ASSERT(end + 1 >= base);
5867 
5868 		} else if (af == AF_INET6) {
5869 			struct in6_addr ip6;
5870 			int firstzero, tryzero, numzero, v6end;
5871 			uint16_t val;
5872 			const char digits[] = "0123456789abcdef";
5873 
5874 			/*
5875 			 * Stringify using RFC 1884 convention 2 - 16 bit
5876 			 * hexadecimal values with a zero-run compression.
5877 			 * Lower case hexadecimal digits are used.
5878 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5879 			 * The IPv4 embedded form is returned for inet_ntop,
5880 			 * just the IPv4 string is returned for inet_ntoa6.
5881 			 */
5882 
5883 			if (!dtrace_canload(tupregs[argi].dttk_value,
5884 			    sizeof (struct in6_addr), mstate, vstate)) {
5885 				regs[rd] = 0;
5886 				break;
5887 			}
5888 
5889 			/*
5890 			 * Safely load the IPv6 address.
5891 			 */
5892 			dtrace_bcopy(
5893 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5894 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5895 
5896 			/*
5897 			 * Check an IPv6 string will fit in scratch.
5898 			 */
5899 			size = INET6_ADDRSTRLEN;
5900 			if (!DTRACE_INSCRATCH(mstate, size)) {
5901 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5902 				regs[rd] = 0;
5903 				break;
5904 			}
5905 			base = (char *)mstate->dtms_scratch_ptr;
5906 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5907 			*end-- = '\0';
5908 
5909 			/*
5910 			 * Find the longest run of 16 bit zero values
5911 			 * for the single allowed zero compression - "::".
5912 			 */
5913 			firstzero = -1;
5914 			tryzero = -1;
5915 			numzero = 1;
5916 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5917 #ifdef illumos
5918 				if (ip6._S6_un._S6_u8[i] == 0 &&
5919 #else
5920 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5921 #endif
5922 				    tryzero == -1 && i % 2 == 0) {
5923 					tryzero = i;
5924 					continue;
5925 				}
5926 
5927 				if (tryzero != -1 &&
5928 #ifdef illumos
5929 				    (ip6._S6_un._S6_u8[i] != 0 ||
5930 #else
5931 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5932 #endif
5933 				    i == sizeof (struct in6_addr) - 1)) {
5934 
5935 					if (i - tryzero <= numzero) {
5936 						tryzero = -1;
5937 						continue;
5938 					}
5939 
5940 					firstzero = tryzero;
5941 					numzero = i - i % 2 - tryzero;
5942 					tryzero = -1;
5943 
5944 #ifdef illumos
5945 					if (ip6._S6_un._S6_u8[i] == 0 &&
5946 #else
5947 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5948 #endif
5949 					    i == sizeof (struct in6_addr) - 1)
5950 						numzero += 2;
5951 				}
5952 			}
5953 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5954 
5955 			/*
5956 			 * Check for an IPv4 embedded address.
5957 			 */
5958 			v6end = sizeof (struct in6_addr) - 2;
5959 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5960 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5961 				for (i = sizeof (struct in6_addr) - 1;
5962 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5963 					ASSERT(end >= base);
5964 
5965 #ifdef illumos
5966 					val = ip6._S6_un._S6_u8[i];
5967 #else
5968 					val = ip6.__u6_addr.__u6_addr8[i];
5969 #endif
5970 
5971 					if (val == 0) {
5972 						*end-- = '0';
5973 					} else {
5974 						for (; val; val /= 10) {
5975 							*end-- = '0' + val % 10;
5976 						}
5977 					}
5978 
5979 					if (i > DTRACE_V4MAPPED_OFFSET)
5980 						*end-- = '.';
5981 				}
5982 
5983 				if (subr == DIF_SUBR_INET_NTOA6)
5984 					goto inetout;
5985 
5986 				/*
5987 				 * Set v6end to skip the IPv4 address that
5988 				 * we have already stringified.
5989 				 */
5990 				v6end = 10;
5991 			}
5992 
5993 			/*
5994 			 * Build the IPv6 string by working through the
5995 			 * address in reverse.
5996 			 */
5997 			for (i = v6end; i >= 0; i -= 2) {
5998 				ASSERT(end >= base);
5999 
6000 				if (i == firstzero + numzero - 2) {
6001 					*end-- = ':';
6002 					*end-- = ':';
6003 					i -= numzero - 2;
6004 					continue;
6005 				}
6006 
6007 				if (i < 14 && i != firstzero - 2)
6008 					*end-- = ':';
6009 
6010 #ifdef illumos
6011 				val = (ip6._S6_un._S6_u8[i] << 8) +
6012 				    ip6._S6_un._S6_u8[i + 1];
6013 #else
6014 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6015 				    ip6.__u6_addr.__u6_addr8[i + 1];
6016 #endif
6017 
6018 				if (val == 0) {
6019 					*end-- = '0';
6020 				} else {
6021 					for (; val; val /= 16) {
6022 						*end-- = digits[val % 16];
6023 					}
6024 				}
6025 			}
6026 			ASSERT(end + 1 >= base);
6027 
6028 		} else {
6029 			/*
6030 			 * The user didn't use AH_INET or AH_INET6.
6031 			 */
6032 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6033 			regs[rd] = 0;
6034 			break;
6035 		}
6036 
6037 inetout:	regs[rd] = (uintptr_t)end + 1;
6038 		mstate->dtms_scratch_ptr += size;
6039 		break;
6040 	}
6041 
6042 	case DIF_SUBR_MEMREF: {
6043 		uintptr_t size = 2 * sizeof(uintptr_t);
6044 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6045 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6046 
6047 		/* address and length */
6048 		memref[0] = tupregs[0].dttk_value;
6049 		memref[1] = tupregs[1].dttk_value;
6050 
6051 		regs[rd] = (uintptr_t) memref;
6052 		mstate->dtms_scratch_ptr += scratch_size;
6053 		break;
6054 	}
6055 
6056 #ifndef illumos
6057 	case DIF_SUBR_MEMSTR: {
6058 		char *str = (char *)mstate->dtms_scratch_ptr;
6059 		uintptr_t mem = tupregs[0].dttk_value;
6060 		char c = tupregs[1].dttk_value;
6061 		size_t size = tupregs[2].dttk_value;
6062 		uint8_t n;
6063 		int i;
6064 
6065 		regs[rd] = 0;
6066 
6067 		if (size == 0)
6068 			break;
6069 
6070 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6071 			break;
6072 
6073 		if (!DTRACE_INSCRATCH(mstate, size)) {
6074 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6075 			break;
6076 		}
6077 
6078 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6079 			*flags |= CPU_DTRACE_ILLOP;
6080 			break;
6081 		}
6082 
6083 		for (i = 0; i < size - 1; i++) {
6084 			n = dtrace_load8(mem++);
6085 			str[i] = (n == 0) ? c : n;
6086 		}
6087 		str[size - 1] = 0;
6088 
6089 		regs[rd] = (uintptr_t)str;
6090 		mstate->dtms_scratch_ptr += size;
6091 		break;
6092 	}
6093 #endif
6094 	}
6095 }
6096 
6097 /*
6098  * Emulate the execution of DTrace IR instructions specified by the given
6099  * DIF object.  This function is deliberately void of assertions as all of
6100  * the necessary checks are handled by a call to dtrace_difo_validate().
6101  */
6102 static uint64_t
6103 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6104     dtrace_vstate_t *vstate, dtrace_state_t *state)
6105 {
6106 	const dif_instr_t *text = difo->dtdo_buf;
6107 	const uint_t textlen = difo->dtdo_len;
6108 	const char *strtab = difo->dtdo_strtab;
6109 	const uint64_t *inttab = difo->dtdo_inttab;
6110 
6111 	uint64_t rval = 0;
6112 	dtrace_statvar_t *svar;
6113 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6114 	dtrace_difv_t *v;
6115 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6116 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6117 
6118 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6119 	uint64_t regs[DIF_DIR_NREGS];
6120 	uint64_t *tmp;
6121 
6122 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6123 	int64_t cc_r;
6124 	uint_t pc = 0, id, opc = 0;
6125 	uint8_t ttop = 0;
6126 	dif_instr_t instr;
6127 	uint_t r1, r2, rd;
6128 
6129 	/*
6130 	 * We stash the current DIF object into the machine state: we need it
6131 	 * for subsequent access checking.
6132 	 */
6133 	mstate->dtms_difo = difo;
6134 
6135 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6136 
6137 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6138 		opc = pc;
6139 
6140 		instr = text[pc++];
6141 		r1 = DIF_INSTR_R1(instr);
6142 		r2 = DIF_INSTR_R2(instr);
6143 		rd = DIF_INSTR_RD(instr);
6144 
6145 		switch (DIF_INSTR_OP(instr)) {
6146 		case DIF_OP_OR:
6147 			regs[rd] = regs[r1] | regs[r2];
6148 			break;
6149 		case DIF_OP_XOR:
6150 			regs[rd] = regs[r1] ^ regs[r2];
6151 			break;
6152 		case DIF_OP_AND:
6153 			regs[rd] = regs[r1] & regs[r2];
6154 			break;
6155 		case DIF_OP_SLL:
6156 			regs[rd] = regs[r1] << regs[r2];
6157 			break;
6158 		case DIF_OP_SRL:
6159 			regs[rd] = regs[r1] >> regs[r2];
6160 			break;
6161 		case DIF_OP_SUB:
6162 			regs[rd] = regs[r1] - regs[r2];
6163 			break;
6164 		case DIF_OP_ADD:
6165 			regs[rd] = regs[r1] + regs[r2];
6166 			break;
6167 		case DIF_OP_MUL:
6168 			regs[rd] = regs[r1] * regs[r2];
6169 			break;
6170 		case DIF_OP_SDIV:
6171 			if (regs[r2] == 0) {
6172 				regs[rd] = 0;
6173 				*flags |= CPU_DTRACE_DIVZERO;
6174 			} else {
6175 				regs[rd] = (int64_t)regs[r1] /
6176 				    (int64_t)regs[r2];
6177 			}
6178 			break;
6179 
6180 		case DIF_OP_UDIV:
6181 			if (regs[r2] == 0) {
6182 				regs[rd] = 0;
6183 				*flags |= CPU_DTRACE_DIVZERO;
6184 			} else {
6185 				regs[rd] = regs[r1] / regs[r2];
6186 			}
6187 			break;
6188 
6189 		case DIF_OP_SREM:
6190 			if (regs[r2] == 0) {
6191 				regs[rd] = 0;
6192 				*flags |= CPU_DTRACE_DIVZERO;
6193 			} else {
6194 				regs[rd] = (int64_t)regs[r1] %
6195 				    (int64_t)regs[r2];
6196 			}
6197 			break;
6198 
6199 		case DIF_OP_UREM:
6200 			if (regs[r2] == 0) {
6201 				regs[rd] = 0;
6202 				*flags |= CPU_DTRACE_DIVZERO;
6203 			} else {
6204 				regs[rd] = regs[r1] % regs[r2];
6205 			}
6206 			break;
6207 
6208 		case DIF_OP_NOT:
6209 			regs[rd] = ~regs[r1];
6210 			break;
6211 		case DIF_OP_MOV:
6212 			regs[rd] = regs[r1];
6213 			break;
6214 		case DIF_OP_CMP:
6215 			cc_r = regs[r1] - regs[r2];
6216 			cc_n = cc_r < 0;
6217 			cc_z = cc_r == 0;
6218 			cc_v = 0;
6219 			cc_c = regs[r1] < regs[r2];
6220 			break;
6221 		case DIF_OP_TST:
6222 			cc_n = cc_v = cc_c = 0;
6223 			cc_z = regs[r1] == 0;
6224 			break;
6225 		case DIF_OP_BA:
6226 			pc = DIF_INSTR_LABEL(instr);
6227 			break;
6228 		case DIF_OP_BE:
6229 			if (cc_z)
6230 				pc = DIF_INSTR_LABEL(instr);
6231 			break;
6232 		case DIF_OP_BNE:
6233 			if (cc_z == 0)
6234 				pc = DIF_INSTR_LABEL(instr);
6235 			break;
6236 		case DIF_OP_BG:
6237 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6238 				pc = DIF_INSTR_LABEL(instr);
6239 			break;
6240 		case DIF_OP_BGU:
6241 			if ((cc_c | cc_z) == 0)
6242 				pc = DIF_INSTR_LABEL(instr);
6243 			break;
6244 		case DIF_OP_BGE:
6245 			if ((cc_n ^ cc_v) == 0)
6246 				pc = DIF_INSTR_LABEL(instr);
6247 			break;
6248 		case DIF_OP_BGEU:
6249 			if (cc_c == 0)
6250 				pc = DIF_INSTR_LABEL(instr);
6251 			break;
6252 		case DIF_OP_BL:
6253 			if (cc_n ^ cc_v)
6254 				pc = DIF_INSTR_LABEL(instr);
6255 			break;
6256 		case DIF_OP_BLU:
6257 			if (cc_c)
6258 				pc = DIF_INSTR_LABEL(instr);
6259 			break;
6260 		case DIF_OP_BLE:
6261 			if (cc_z | (cc_n ^ cc_v))
6262 				pc = DIF_INSTR_LABEL(instr);
6263 			break;
6264 		case DIF_OP_BLEU:
6265 			if (cc_c | cc_z)
6266 				pc = DIF_INSTR_LABEL(instr);
6267 			break;
6268 		case DIF_OP_RLDSB:
6269 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6270 				break;
6271 			/*FALLTHROUGH*/
6272 		case DIF_OP_LDSB:
6273 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6274 			break;
6275 		case DIF_OP_RLDSH:
6276 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6277 				break;
6278 			/*FALLTHROUGH*/
6279 		case DIF_OP_LDSH:
6280 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6281 			break;
6282 		case DIF_OP_RLDSW:
6283 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6284 				break;
6285 			/*FALLTHROUGH*/
6286 		case DIF_OP_LDSW:
6287 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6288 			break;
6289 		case DIF_OP_RLDUB:
6290 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6291 				break;
6292 			/*FALLTHROUGH*/
6293 		case DIF_OP_LDUB:
6294 			regs[rd] = dtrace_load8(regs[r1]);
6295 			break;
6296 		case DIF_OP_RLDUH:
6297 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6298 				break;
6299 			/*FALLTHROUGH*/
6300 		case DIF_OP_LDUH:
6301 			regs[rd] = dtrace_load16(regs[r1]);
6302 			break;
6303 		case DIF_OP_RLDUW:
6304 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6305 				break;
6306 			/*FALLTHROUGH*/
6307 		case DIF_OP_LDUW:
6308 			regs[rd] = dtrace_load32(regs[r1]);
6309 			break;
6310 		case DIF_OP_RLDX:
6311 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6312 				break;
6313 			/*FALLTHROUGH*/
6314 		case DIF_OP_LDX:
6315 			regs[rd] = dtrace_load64(regs[r1]);
6316 			break;
6317 		case DIF_OP_ULDSB:
6318 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6319 			regs[rd] = (int8_t)
6320 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6321 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6322 			break;
6323 		case DIF_OP_ULDSH:
6324 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6325 			regs[rd] = (int16_t)
6326 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6327 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6328 			break;
6329 		case DIF_OP_ULDSW:
6330 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6331 			regs[rd] = (int32_t)
6332 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6333 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6334 			break;
6335 		case DIF_OP_ULDUB:
6336 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6337 			regs[rd] =
6338 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6339 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6340 			break;
6341 		case DIF_OP_ULDUH:
6342 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6343 			regs[rd] =
6344 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6345 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6346 			break;
6347 		case DIF_OP_ULDUW:
6348 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6349 			regs[rd] =
6350 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6351 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6352 			break;
6353 		case DIF_OP_ULDX:
6354 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6355 			regs[rd] =
6356 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6357 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6358 			break;
6359 		case DIF_OP_RET:
6360 			rval = regs[rd];
6361 			pc = textlen;
6362 			break;
6363 		case DIF_OP_NOP:
6364 			break;
6365 		case DIF_OP_SETX:
6366 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6367 			break;
6368 		case DIF_OP_SETS:
6369 			regs[rd] = (uint64_t)(uintptr_t)
6370 			    (strtab + DIF_INSTR_STRING(instr));
6371 			break;
6372 		case DIF_OP_SCMP: {
6373 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6374 			uintptr_t s1 = regs[r1];
6375 			uintptr_t s2 = regs[r2];
6376 			size_t lim1, lim2;
6377 
6378 			/*
6379 			 * If one of the strings is NULL then the limit becomes
6380 			 * 0 which compares 0 characters in dtrace_strncmp()
6381 			 * resulting in a false positive.  dtrace_strncmp()
6382 			 * treats a NULL as an empty 1-char string.
6383 			 */
6384 			lim1 = lim2 = 1;
6385 
6386 			if (s1 != 0 &&
6387 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6388 				break;
6389 			if (s2 != 0 &&
6390 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6391 				break;
6392 
6393 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6394 			    MIN(lim1, lim2));
6395 
6396 			cc_n = cc_r < 0;
6397 			cc_z = cc_r == 0;
6398 			cc_v = cc_c = 0;
6399 			break;
6400 		}
6401 		case DIF_OP_LDGA:
6402 			regs[rd] = dtrace_dif_variable(mstate, state,
6403 			    r1, regs[r2]);
6404 			break;
6405 		case DIF_OP_LDGS:
6406 			id = DIF_INSTR_VAR(instr);
6407 
6408 			if (id >= DIF_VAR_OTHER_UBASE) {
6409 				uintptr_t a;
6410 
6411 				id -= DIF_VAR_OTHER_UBASE;
6412 				svar = vstate->dtvs_globals[id];
6413 				ASSERT(svar != NULL);
6414 				v = &svar->dtsv_var;
6415 
6416 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6417 					regs[rd] = svar->dtsv_data;
6418 					break;
6419 				}
6420 
6421 				a = (uintptr_t)svar->dtsv_data;
6422 
6423 				if (*(uint8_t *)a == UINT8_MAX) {
6424 					/*
6425 					 * If the 0th byte is set to UINT8_MAX
6426 					 * then this is to be treated as a
6427 					 * reference to a NULL variable.
6428 					 */
6429 					regs[rd] = 0;
6430 				} else {
6431 					regs[rd] = a + sizeof (uint64_t);
6432 				}
6433 
6434 				break;
6435 			}
6436 
6437 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6438 			break;
6439 
6440 		case DIF_OP_STGS:
6441 			id = DIF_INSTR_VAR(instr);
6442 
6443 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6444 			id -= DIF_VAR_OTHER_UBASE;
6445 
6446 			VERIFY(id < vstate->dtvs_nglobals);
6447 			svar = vstate->dtvs_globals[id];
6448 			ASSERT(svar != NULL);
6449 			v = &svar->dtsv_var;
6450 
6451 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6452 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6453 				size_t lim;
6454 
6455 				ASSERT(a != 0);
6456 				ASSERT(svar->dtsv_size != 0);
6457 
6458 				if (regs[rd] == 0) {
6459 					*(uint8_t *)a = UINT8_MAX;
6460 					break;
6461 				} else {
6462 					*(uint8_t *)a = 0;
6463 					a += sizeof (uint64_t);
6464 				}
6465 				if (!dtrace_vcanload(
6466 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6467 				    &lim, mstate, vstate))
6468 					break;
6469 
6470 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6471 				    (void *)a, &v->dtdv_type, lim);
6472 				break;
6473 			}
6474 
6475 			svar->dtsv_data = regs[rd];
6476 			break;
6477 
6478 		case DIF_OP_LDTA:
6479 			/*
6480 			 * There are no DTrace built-in thread-local arrays at
6481 			 * present.  This opcode is saved for future work.
6482 			 */
6483 			*flags |= CPU_DTRACE_ILLOP;
6484 			regs[rd] = 0;
6485 			break;
6486 
6487 		case DIF_OP_LDLS:
6488 			id = DIF_INSTR_VAR(instr);
6489 
6490 			if (id < DIF_VAR_OTHER_UBASE) {
6491 				/*
6492 				 * For now, this has no meaning.
6493 				 */
6494 				regs[rd] = 0;
6495 				break;
6496 			}
6497 
6498 			id -= DIF_VAR_OTHER_UBASE;
6499 
6500 			ASSERT(id < vstate->dtvs_nlocals);
6501 			ASSERT(vstate->dtvs_locals != NULL);
6502 
6503 			svar = vstate->dtvs_locals[id];
6504 			ASSERT(svar != NULL);
6505 			v = &svar->dtsv_var;
6506 
6507 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6508 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6509 				size_t sz = v->dtdv_type.dtdt_size;
6510 				size_t lim;
6511 
6512 				sz += sizeof (uint64_t);
6513 				ASSERT(svar->dtsv_size == NCPU * sz);
6514 				a += curcpu * sz;
6515 
6516 				if (*(uint8_t *)a == UINT8_MAX) {
6517 					/*
6518 					 * If the 0th byte is set to UINT8_MAX
6519 					 * then this is to be treated as a
6520 					 * reference to a NULL variable.
6521 					 */
6522 					regs[rd] = 0;
6523 				} else {
6524 					regs[rd] = a + sizeof (uint64_t);
6525 				}
6526 
6527 				break;
6528 			}
6529 
6530 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6531 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6532 			regs[rd] = tmp[curcpu];
6533 			break;
6534 
6535 		case DIF_OP_STLS:
6536 			id = DIF_INSTR_VAR(instr);
6537 
6538 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6539 			id -= DIF_VAR_OTHER_UBASE;
6540 			VERIFY(id < vstate->dtvs_nlocals);
6541 
6542 			ASSERT(vstate->dtvs_locals != NULL);
6543 			svar = vstate->dtvs_locals[id];
6544 			ASSERT(svar != NULL);
6545 			v = &svar->dtsv_var;
6546 
6547 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6548 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6549 				size_t sz = v->dtdv_type.dtdt_size;
6550 				size_t lim;
6551 
6552 				sz += sizeof (uint64_t);
6553 				ASSERT(svar->dtsv_size == NCPU * sz);
6554 				a += curcpu * sz;
6555 
6556 				if (regs[rd] == 0) {
6557 					*(uint8_t *)a = UINT8_MAX;
6558 					break;
6559 				} else {
6560 					*(uint8_t *)a = 0;
6561 					a += sizeof (uint64_t);
6562 				}
6563 
6564 				if (!dtrace_vcanload(
6565 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6566 				    &lim, mstate, vstate))
6567 					break;
6568 
6569 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6570 				    (void *)a, &v->dtdv_type, lim);
6571 				break;
6572 			}
6573 
6574 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6575 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6576 			tmp[curcpu] = regs[rd];
6577 			break;
6578 
6579 		case DIF_OP_LDTS: {
6580 			dtrace_dynvar_t *dvar;
6581 			dtrace_key_t *key;
6582 
6583 			id = DIF_INSTR_VAR(instr);
6584 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6585 			id -= DIF_VAR_OTHER_UBASE;
6586 			v = &vstate->dtvs_tlocals[id];
6587 
6588 			key = &tupregs[DIF_DTR_NREGS];
6589 			key[0].dttk_value = (uint64_t)id;
6590 			key[0].dttk_size = 0;
6591 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6592 			key[1].dttk_size = 0;
6593 
6594 			dvar = dtrace_dynvar(dstate, 2, key,
6595 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6596 			    mstate, vstate);
6597 
6598 			if (dvar == NULL) {
6599 				regs[rd] = 0;
6600 				break;
6601 			}
6602 
6603 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6604 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6605 			} else {
6606 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6607 			}
6608 
6609 			break;
6610 		}
6611 
6612 		case DIF_OP_STTS: {
6613 			dtrace_dynvar_t *dvar;
6614 			dtrace_key_t *key;
6615 
6616 			id = DIF_INSTR_VAR(instr);
6617 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6618 			id -= DIF_VAR_OTHER_UBASE;
6619 			VERIFY(id < vstate->dtvs_ntlocals);
6620 
6621 			key = &tupregs[DIF_DTR_NREGS];
6622 			key[0].dttk_value = (uint64_t)id;
6623 			key[0].dttk_size = 0;
6624 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6625 			key[1].dttk_size = 0;
6626 			v = &vstate->dtvs_tlocals[id];
6627 
6628 			dvar = dtrace_dynvar(dstate, 2, key,
6629 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6630 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6631 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6632 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6633 
6634 			/*
6635 			 * Given that we're storing to thread-local data,
6636 			 * we need to flush our predicate cache.
6637 			 */
6638 			curthread->t_predcache = 0;
6639 
6640 			if (dvar == NULL)
6641 				break;
6642 
6643 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6644 				size_t lim;
6645 
6646 				if (!dtrace_vcanload(
6647 				    (void *)(uintptr_t)regs[rd],
6648 				    &v->dtdv_type, &lim, mstate, vstate))
6649 					break;
6650 
6651 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6652 				    dvar->dtdv_data, &v->dtdv_type, lim);
6653 			} else {
6654 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6655 			}
6656 
6657 			break;
6658 		}
6659 
6660 		case DIF_OP_SRA:
6661 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6662 			break;
6663 
6664 		case DIF_OP_CALL:
6665 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6666 			    regs, tupregs, ttop, mstate, state);
6667 			break;
6668 
6669 		case DIF_OP_PUSHTR:
6670 			if (ttop == DIF_DTR_NREGS) {
6671 				*flags |= CPU_DTRACE_TUPOFLOW;
6672 				break;
6673 			}
6674 
6675 			if (r1 == DIF_TYPE_STRING) {
6676 				/*
6677 				 * If this is a string type and the size is 0,
6678 				 * we'll use the system-wide default string
6679 				 * size.  Note that we are _not_ looking at
6680 				 * the value of the DTRACEOPT_STRSIZE option;
6681 				 * had this been set, we would expect to have
6682 				 * a non-zero size value in the "pushtr".
6683 				 */
6684 				tupregs[ttop].dttk_size =
6685 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6686 				    regs[r2] ? regs[r2] :
6687 				    dtrace_strsize_default) + 1;
6688 			} else {
6689 				if (regs[r2] > LONG_MAX) {
6690 					*flags |= CPU_DTRACE_ILLOP;
6691 					break;
6692 				}
6693 
6694 				tupregs[ttop].dttk_size = regs[r2];
6695 			}
6696 
6697 			tupregs[ttop++].dttk_value = regs[rd];
6698 			break;
6699 
6700 		case DIF_OP_PUSHTV:
6701 			if (ttop == DIF_DTR_NREGS) {
6702 				*flags |= CPU_DTRACE_TUPOFLOW;
6703 				break;
6704 			}
6705 
6706 			tupregs[ttop].dttk_value = regs[rd];
6707 			tupregs[ttop++].dttk_size = 0;
6708 			break;
6709 
6710 		case DIF_OP_POPTS:
6711 			if (ttop != 0)
6712 				ttop--;
6713 			break;
6714 
6715 		case DIF_OP_FLUSHTS:
6716 			ttop = 0;
6717 			break;
6718 
6719 		case DIF_OP_LDGAA:
6720 		case DIF_OP_LDTAA: {
6721 			dtrace_dynvar_t *dvar;
6722 			dtrace_key_t *key = tupregs;
6723 			uint_t nkeys = ttop;
6724 
6725 			id = DIF_INSTR_VAR(instr);
6726 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6727 			id -= DIF_VAR_OTHER_UBASE;
6728 
6729 			key[nkeys].dttk_value = (uint64_t)id;
6730 			key[nkeys++].dttk_size = 0;
6731 
6732 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6733 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6734 				key[nkeys++].dttk_size = 0;
6735 				VERIFY(id < vstate->dtvs_ntlocals);
6736 				v = &vstate->dtvs_tlocals[id];
6737 			} else {
6738 				VERIFY(id < vstate->dtvs_nglobals);
6739 				v = &vstate->dtvs_globals[id]->dtsv_var;
6740 			}
6741 
6742 			dvar = dtrace_dynvar(dstate, nkeys, key,
6743 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6744 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6745 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6746 
6747 			if (dvar == NULL) {
6748 				regs[rd] = 0;
6749 				break;
6750 			}
6751 
6752 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6753 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6754 			} else {
6755 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6756 			}
6757 
6758 			break;
6759 		}
6760 
6761 		case DIF_OP_STGAA:
6762 		case DIF_OP_STTAA: {
6763 			dtrace_dynvar_t *dvar;
6764 			dtrace_key_t *key = tupregs;
6765 			uint_t nkeys = ttop;
6766 
6767 			id = DIF_INSTR_VAR(instr);
6768 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6769 			id -= DIF_VAR_OTHER_UBASE;
6770 
6771 			key[nkeys].dttk_value = (uint64_t)id;
6772 			key[nkeys++].dttk_size = 0;
6773 
6774 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6775 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6776 				key[nkeys++].dttk_size = 0;
6777 				VERIFY(id < vstate->dtvs_ntlocals);
6778 				v = &vstate->dtvs_tlocals[id];
6779 			} else {
6780 				VERIFY(id < vstate->dtvs_nglobals);
6781 				v = &vstate->dtvs_globals[id]->dtsv_var;
6782 			}
6783 
6784 			dvar = dtrace_dynvar(dstate, nkeys, key,
6785 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6786 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6787 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6788 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6789 
6790 			if (dvar == NULL)
6791 				break;
6792 
6793 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6794 				size_t lim;
6795 
6796 				if (!dtrace_vcanload(
6797 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6798 				    &lim, mstate, vstate))
6799 					break;
6800 
6801 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6802 				    dvar->dtdv_data, &v->dtdv_type, lim);
6803 			} else {
6804 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6805 			}
6806 
6807 			break;
6808 		}
6809 
6810 		case DIF_OP_ALLOCS: {
6811 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6812 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6813 
6814 			/*
6815 			 * Rounding up the user allocation size could have
6816 			 * overflowed large, bogus allocations (like -1ULL) to
6817 			 * 0.
6818 			 */
6819 			if (size < regs[r1] ||
6820 			    !DTRACE_INSCRATCH(mstate, size)) {
6821 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6822 				regs[rd] = 0;
6823 				break;
6824 			}
6825 
6826 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6827 			mstate->dtms_scratch_ptr += size;
6828 			regs[rd] = ptr;
6829 			break;
6830 		}
6831 
6832 		case DIF_OP_COPYS:
6833 			if (!dtrace_canstore(regs[rd], regs[r2],
6834 			    mstate, vstate)) {
6835 				*flags |= CPU_DTRACE_BADADDR;
6836 				*illval = regs[rd];
6837 				break;
6838 			}
6839 
6840 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6841 				break;
6842 
6843 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6844 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6845 			break;
6846 
6847 		case DIF_OP_STB:
6848 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6849 				*flags |= CPU_DTRACE_BADADDR;
6850 				*illval = regs[rd];
6851 				break;
6852 			}
6853 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6854 			break;
6855 
6856 		case DIF_OP_STH:
6857 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6858 				*flags |= CPU_DTRACE_BADADDR;
6859 				*illval = regs[rd];
6860 				break;
6861 			}
6862 			if (regs[rd] & 1) {
6863 				*flags |= CPU_DTRACE_BADALIGN;
6864 				*illval = regs[rd];
6865 				break;
6866 			}
6867 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6868 			break;
6869 
6870 		case DIF_OP_STW:
6871 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6872 				*flags |= CPU_DTRACE_BADADDR;
6873 				*illval = regs[rd];
6874 				break;
6875 			}
6876 			if (regs[rd] & 3) {
6877 				*flags |= CPU_DTRACE_BADALIGN;
6878 				*illval = regs[rd];
6879 				break;
6880 			}
6881 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6882 			break;
6883 
6884 		case DIF_OP_STX:
6885 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6886 				*flags |= CPU_DTRACE_BADADDR;
6887 				*illval = regs[rd];
6888 				break;
6889 			}
6890 			if (regs[rd] & 7) {
6891 				*flags |= CPU_DTRACE_BADALIGN;
6892 				*illval = regs[rd];
6893 				break;
6894 			}
6895 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6896 			break;
6897 		}
6898 	}
6899 
6900 	if (!(*flags & CPU_DTRACE_FAULT))
6901 		return (rval);
6902 
6903 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6904 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6905 
6906 	return (0);
6907 }
6908 
6909 static void
6910 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6911 {
6912 	dtrace_probe_t *probe = ecb->dte_probe;
6913 	dtrace_provider_t *prov = probe->dtpr_provider;
6914 	char c[DTRACE_FULLNAMELEN + 80], *str;
6915 	char *msg = "dtrace: breakpoint action at probe ";
6916 	char *ecbmsg = " (ecb ";
6917 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6918 	uintptr_t val = (uintptr_t)ecb;
6919 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6920 
6921 	if (dtrace_destructive_disallow)
6922 		return;
6923 
6924 	/*
6925 	 * It's impossible to be taking action on the NULL probe.
6926 	 */
6927 	ASSERT(probe != NULL);
6928 
6929 	/*
6930 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6931 	 * print the provider name, module name, function name and name of
6932 	 * the probe, along with the hex address of the ECB with the breakpoint
6933 	 * action -- all of which we must place in the character buffer by
6934 	 * hand.
6935 	 */
6936 	while (*msg != '\0')
6937 		c[i++] = *msg++;
6938 
6939 	for (str = prov->dtpv_name; *str != '\0'; str++)
6940 		c[i++] = *str;
6941 	c[i++] = ':';
6942 
6943 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6944 		c[i++] = *str;
6945 	c[i++] = ':';
6946 
6947 	for (str = probe->dtpr_func; *str != '\0'; str++)
6948 		c[i++] = *str;
6949 	c[i++] = ':';
6950 
6951 	for (str = probe->dtpr_name; *str != '\0'; str++)
6952 		c[i++] = *str;
6953 
6954 	while (*ecbmsg != '\0')
6955 		c[i++] = *ecbmsg++;
6956 
6957 	while (shift >= 0) {
6958 		mask = (uintptr_t)0xf << shift;
6959 
6960 		if (val >= ((uintptr_t)1 << shift))
6961 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6962 		shift -= 4;
6963 	}
6964 
6965 	c[i++] = ')';
6966 	c[i] = '\0';
6967 
6968 #ifdef illumos
6969 	debug_enter(c);
6970 #else
6971 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6972 #endif
6973 }
6974 
6975 static void
6976 dtrace_action_panic(dtrace_ecb_t *ecb)
6977 {
6978 	dtrace_probe_t *probe = ecb->dte_probe;
6979 
6980 	/*
6981 	 * It's impossible to be taking action on the NULL probe.
6982 	 */
6983 	ASSERT(probe != NULL);
6984 
6985 	if (dtrace_destructive_disallow)
6986 		return;
6987 
6988 	if (dtrace_panicked != NULL)
6989 		return;
6990 
6991 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6992 		return;
6993 
6994 	/*
6995 	 * We won the right to panic.  (We want to be sure that only one
6996 	 * thread calls panic() from dtrace_probe(), and that panic() is
6997 	 * called exactly once.)
6998 	 */
6999 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
7000 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
7001 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
7002 }
7003 
7004 static void
7005 dtrace_action_raise(uint64_t sig)
7006 {
7007 	if (dtrace_destructive_disallow)
7008 		return;
7009 
7010 	if (sig >= NSIG) {
7011 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7012 		return;
7013 	}
7014 
7015 #ifdef illumos
7016 	/*
7017 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7018 	 * invocations of the raise() action.
7019 	 */
7020 	if (curthread->t_dtrace_sig == 0)
7021 		curthread->t_dtrace_sig = (uint8_t)sig;
7022 
7023 	curthread->t_sig_check = 1;
7024 	aston(curthread);
7025 #else
7026 	struct proc *p = curproc;
7027 	PROC_LOCK(p);
7028 	kern_psignal(p, sig);
7029 	PROC_UNLOCK(p);
7030 #endif
7031 }
7032 
7033 static void
7034 dtrace_action_stop(void)
7035 {
7036 	if (dtrace_destructive_disallow)
7037 		return;
7038 
7039 #ifdef illumos
7040 	if (!curthread->t_dtrace_stop) {
7041 		curthread->t_dtrace_stop = 1;
7042 		curthread->t_sig_check = 1;
7043 		aston(curthread);
7044 	}
7045 #else
7046 	struct proc *p = curproc;
7047 	PROC_LOCK(p);
7048 	kern_psignal(p, SIGSTOP);
7049 	PROC_UNLOCK(p);
7050 #endif
7051 }
7052 
7053 static void
7054 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7055 {
7056 	hrtime_t now;
7057 	volatile uint16_t *flags;
7058 #ifdef illumos
7059 	cpu_t *cpu = CPU;
7060 #else
7061 	cpu_t *cpu = &solaris_cpu[curcpu];
7062 #endif
7063 
7064 	if (dtrace_destructive_disallow)
7065 		return;
7066 
7067 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7068 
7069 	now = dtrace_gethrtime();
7070 
7071 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7072 		/*
7073 		 * We need to advance the mark to the current time.
7074 		 */
7075 		cpu->cpu_dtrace_chillmark = now;
7076 		cpu->cpu_dtrace_chilled = 0;
7077 	}
7078 
7079 	/*
7080 	 * Now check to see if the requested chill time would take us over
7081 	 * the maximum amount of time allowed in the chill interval.  (Or
7082 	 * worse, if the calculation itself induces overflow.)
7083 	 */
7084 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7085 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7086 		*flags |= CPU_DTRACE_ILLOP;
7087 		return;
7088 	}
7089 
7090 	while (dtrace_gethrtime() - now < val)
7091 		continue;
7092 
7093 	/*
7094 	 * Normally, we assure that the value of the variable "timestamp" does
7095 	 * not change within an ECB.  The presence of chill() represents an
7096 	 * exception to this rule, however.
7097 	 */
7098 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7099 	cpu->cpu_dtrace_chilled += val;
7100 }
7101 
7102 static void
7103 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7104     uint64_t *buf, uint64_t arg)
7105 {
7106 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7107 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7108 	uint64_t *pcs = &buf[1], *fps;
7109 	char *str = (char *)&pcs[nframes];
7110 	int size, offs = 0, i, j;
7111 	size_t rem;
7112 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7113 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7114 	char *sym;
7115 
7116 	/*
7117 	 * Should be taking a faster path if string space has not been
7118 	 * allocated.
7119 	 */
7120 	ASSERT(strsize != 0);
7121 
7122 	/*
7123 	 * We will first allocate some temporary space for the frame pointers.
7124 	 */
7125 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7126 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7127 	    (nframes * sizeof (uint64_t));
7128 
7129 	if (!DTRACE_INSCRATCH(mstate, size)) {
7130 		/*
7131 		 * Not enough room for our frame pointers -- need to indicate
7132 		 * that we ran out of scratch space.
7133 		 */
7134 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7135 		return;
7136 	}
7137 
7138 	mstate->dtms_scratch_ptr += size;
7139 	saved = mstate->dtms_scratch_ptr;
7140 
7141 	/*
7142 	 * Now get a stack with both program counters and frame pointers.
7143 	 */
7144 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7145 	dtrace_getufpstack(buf, fps, nframes + 1);
7146 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7147 
7148 	/*
7149 	 * If that faulted, we're cooked.
7150 	 */
7151 	if (*flags & CPU_DTRACE_FAULT)
7152 		goto out;
7153 
7154 	/*
7155 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7156 	 * each iteration, we restore the scratch pointer.
7157 	 */
7158 	for (i = 0; i < nframes; i++) {
7159 		mstate->dtms_scratch_ptr = saved;
7160 
7161 		if (offs >= strsize)
7162 			break;
7163 
7164 		sym = (char *)(uintptr_t)dtrace_helper(
7165 		    DTRACE_HELPER_ACTION_USTACK,
7166 		    mstate, state, pcs[i], fps[i]);
7167 
7168 		/*
7169 		 * If we faulted while running the helper, we're going to
7170 		 * clear the fault and null out the corresponding string.
7171 		 */
7172 		if (*flags & CPU_DTRACE_FAULT) {
7173 			*flags &= ~CPU_DTRACE_FAULT;
7174 			str[offs++] = '\0';
7175 			continue;
7176 		}
7177 
7178 		if (sym == NULL) {
7179 			str[offs++] = '\0';
7180 			continue;
7181 		}
7182 
7183 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7184 		    &(state->dts_vstate))) {
7185 			str[offs++] = '\0';
7186 			continue;
7187 		}
7188 
7189 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7190 
7191 		/*
7192 		 * Now copy in the string that the helper returned to us.
7193 		 */
7194 		for (j = 0; offs + j < strsize && j < rem; j++) {
7195 			if ((str[offs + j] = sym[j]) == '\0')
7196 				break;
7197 		}
7198 
7199 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7200 
7201 		offs += j + 1;
7202 	}
7203 
7204 	if (offs >= strsize) {
7205 		/*
7206 		 * If we didn't have room for all of the strings, we don't
7207 		 * abort processing -- this needn't be a fatal error -- but we
7208 		 * still want to increment a counter (dts_stkstroverflows) to
7209 		 * allow this condition to be warned about.  (If this is from
7210 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7211 		 */
7212 		dtrace_error(&state->dts_stkstroverflows);
7213 	}
7214 
7215 	while (offs < strsize)
7216 		str[offs++] = '\0';
7217 
7218 out:
7219 	mstate->dtms_scratch_ptr = old;
7220 }
7221 
7222 static void
7223 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7224     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7225 {
7226 	volatile uint16_t *flags;
7227 	uint64_t val = *valp;
7228 	size_t valoffs = *valoffsp;
7229 
7230 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7231 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7232 
7233 	/*
7234 	 * If this is a string, we're going to only load until we find the zero
7235 	 * byte -- after which we'll store zero bytes.
7236 	 */
7237 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7238 		char c = '\0' + 1;
7239 		size_t s;
7240 
7241 		for (s = 0; s < size; s++) {
7242 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7243 				c = dtrace_load8(val++);
7244 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7245 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7246 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7247 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7248 				if (*flags & CPU_DTRACE_FAULT)
7249 					break;
7250 			}
7251 
7252 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7253 
7254 			if (c == '\0' && intuple)
7255 				break;
7256 		}
7257 	} else {
7258 		uint8_t c;
7259 		while (valoffs < end) {
7260 			if (dtkind == DIF_TF_BYREF) {
7261 				c = dtrace_load8(val++);
7262 			} else if (dtkind == DIF_TF_BYUREF) {
7263 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7264 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7265 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7266 				if (*flags & CPU_DTRACE_FAULT)
7267 					break;
7268 			}
7269 
7270 			DTRACE_STORE(uint8_t, tomax,
7271 			    valoffs++, c);
7272 		}
7273 	}
7274 
7275 	*valp = val;
7276 	*valoffsp = valoffs;
7277 }
7278 
7279 /*
7280  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7281  * defined, we also assert that we are not recursing unless the probe ID is an
7282  * error probe.
7283  */
7284 static dtrace_icookie_t
7285 dtrace_probe_enter(dtrace_id_t id)
7286 {
7287 	dtrace_icookie_t cookie;
7288 
7289 	cookie = dtrace_interrupt_disable();
7290 
7291 	/*
7292 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7293 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7294 	 * function is instrumented that should not have been instrumented or
7295 	 * that the ordering guarantee of the records will be violated,
7296 	 * resulting in unexpected output. If there is an exception to this
7297 	 * assertion, a new case should be added.
7298 	 */
7299 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7300 	    id == dtrace_probeid_error);
7301 	curthread->t_dtrace_inprobe = 1;
7302 
7303 	return (cookie);
7304 }
7305 
7306 /*
7307  * Clears the per-thread inprobe flag and enables interrupts.
7308  */
7309 static void
7310 dtrace_probe_exit(dtrace_icookie_t cookie)
7311 {
7312 
7313 	curthread->t_dtrace_inprobe = 0;
7314 	dtrace_interrupt_enable(cookie);
7315 }
7316 
7317 /*
7318  * If you're looking for the epicenter of DTrace, you just found it.  This
7319  * is the function called by the provider to fire a probe -- from which all
7320  * subsequent probe-context DTrace activity emanates.
7321  */
7322 void
7323 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7324     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7325 {
7326 	processorid_t cpuid;
7327 	dtrace_icookie_t cookie;
7328 	dtrace_probe_t *probe;
7329 	dtrace_mstate_t mstate;
7330 	dtrace_ecb_t *ecb;
7331 	dtrace_action_t *act;
7332 	intptr_t offs;
7333 	size_t size;
7334 	int vtime, onintr;
7335 	volatile uint16_t *flags;
7336 	hrtime_t now;
7337 
7338 	if (panicstr != NULL)
7339 		return;
7340 
7341 #ifdef illumos
7342 	/*
7343 	 * Kick out immediately if this CPU is still being born (in which case
7344 	 * curthread will be set to -1) or the current thread can't allow
7345 	 * probes in its current context.
7346 	 */
7347 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7348 		return;
7349 #endif
7350 
7351 	cookie = dtrace_probe_enter(id);
7352 	probe = dtrace_probes[id - 1];
7353 	cpuid = curcpu;
7354 	onintr = CPU_ON_INTR(CPU);
7355 
7356 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7357 	    probe->dtpr_predcache == curthread->t_predcache) {
7358 		/*
7359 		 * We have hit in the predicate cache; we know that
7360 		 * this predicate would evaluate to be false.
7361 		 */
7362 		dtrace_probe_exit(cookie);
7363 		return;
7364 	}
7365 
7366 #ifdef illumos
7367 	if (panic_quiesce) {
7368 #else
7369 	if (panicstr != NULL) {
7370 #endif
7371 		/*
7372 		 * We don't trace anything if we're panicking.
7373 		 */
7374 		dtrace_probe_exit(cookie);
7375 		return;
7376 	}
7377 
7378 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7379 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7380 	vtime = dtrace_vtime_references != 0;
7381 
7382 	if (vtime && curthread->t_dtrace_start)
7383 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7384 
7385 	mstate.dtms_difo = NULL;
7386 	mstate.dtms_probe = probe;
7387 	mstate.dtms_strtok = 0;
7388 	mstate.dtms_arg[0] = arg0;
7389 	mstate.dtms_arg[1] = arg1;
7390 	mstate.dtms_arg[2] = arg2;
7391 	mstate.dtms_arg[3] = arg3;
7392 	mstate.dtms_arg[4] = arg4;
7393 
7394 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7395 
7396 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7397 		dtrace_predicate_t *pred = ecb->dte_predicate;
7398 		dtrace_state_t *state = ecb->dte_state;
7399 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7400 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7401 		dtrace_vstate_t *vstate = &state->dts_vstate;
7402 		dtrace_provider_t *prov = probe->dtpr_provider;
7403 		uint64_t tracememsize = 0;
7404 		int committed = 0;
7405 		caddr_t tomax;
7406 
7407 		/*
7408 		 * A little subtlety with the following (seemingly innocuous)
7409 		 * declaration of the automatic 'val':  by looking at the
7410 		 * code, you might think that it could be declared in the
7411 		 * action processing loop, below.  (That is, it's only used in
7412 		 * the action processing loop.)  However, it must be declared
7413 		 * out of that scope because in the case of DIF expression
7414 		 * arguments to aggregating actions, one iteration of the
7415 		 * action loop will use the last iteration's value.
7416 		 */
7417 		uint64_t val = 0;
7418 
7419 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7420 		mstate.dtms_getf = NULL;
7421 
7422 		*flags &= ~CPU_DTRACE_ERROR;
7423 
7424 		if (prov == dtrace_provider) {
7425 			/*
7426 			 * If dtrace itself is the provider of this probe,
7427 			 * we're only going to continue processing the ECB if
7428 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7429 			 * creating state.  (This prevents disjoint consumers
7430 			 * from seeing one another's metaprobes.)
7431 			 */
7432 			if (arg0 != (uint64_t)(uintptr_t)state)
7433 				continue;
7434 		}
7435 
7436 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7437 			/*
7438 			 * We're not currently active.  If our provider isn't
7439 			 * the dtrace pseudo provider, we're not interested.
7440 			 */
7441 			if (prov != dtrace_provider)
7442 				continue;
7443 
7444 			/*
7445 			 * Now we must further check if we are in the BEGIN
7446 			 * probe.  If we are, we will only continue processing
7447 			 * if we're still in WARMUP -- if one BEGIN enabling
7448 			 * has invoked the exit() action, we don't want to
7449 			 * evaluate subsequent BEGIN enablings.
7450 			 */
7451 			if (probe->dtpr_id == dtrace_probeid_begin &&
7452 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7453 				ASSERT(state->dts_activity ==
7454 				    DTRACE_ACTIVITY_DRAINING);
7455 				continue;
7456 			}
7457 		}
7458 
7459 		if (ecb->dte_cond) {
7460 			/*
7461 			 * If the dte_cond bits indicate that this
7462 			 * consumer is only allowed to see user-mode firings
7463 			 * of this probe, call the provider's dtps_usermode()
7464 			 * entry point to check that the probe was fired
7465 			 * while in a user context. Skip this ECB if that's
7466 			 * not the case.
7467 			 */
7468 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7469 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7470 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7471 				continue;
7472 
7473 #ifdef illumos
7474 			/*
7475 			 * This is more subtle than it looks. We have to be
7476 			 * absolutely certain that CRED() isn't going to
7477 			 * change out from under us so it's only legit to
7478 			 * examine that structure if we're in constrained
7479 			 * situations. Currently, the only times we'll this
7480 			 * check is if a non-super-user has enabled the
7481 			 * profile or syscall providers -- providers that
7482 			 * allow visibility of all processes. For the
7483 			 * profile case, the check above will ensure that
7484 			 * we're examining a user context.
7485 			 */
7486 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7487 				cred_t *cr;
7488 				cred_t *s_cr =
7489 				    ecb->dte_state->dts_cred.dcr_cred;
7490 				proc_t *proc;
7491 
7492 				ASSERT(s_cr != NULL);
7493 
7494 				if ((cr = CRED()) == NULL ||
7495 				    s_cr->cr_uid != cr->cr_uid ||
7496 				    s_cr->cr_uid != cr->cr_ruid ||
7497 				    s_cr->cr_uid != cr->cr_suid ||
7498 				    s_cr->cr_gid != cr->cr_gid ||
7499 				    s_cr->cr_gid != cr->cr_rgid ||
7500 				    s_cr->cr_gid != cr->cr_sgid ||
7501 				    (proc = ttoproc(curthread)) == NULL ||
7502 				    (proc->p_flag & SNOCD))
7503 					continue;
7504 			}
7505 
7506 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7507 				cred_t *cr;
7508 				cred_t *s_cr =
7509 				    ecb->dte_state->dts_cred.dcr_cred;
7510 
7511 				ASSERT(s_cr != NULL);
7512 
7513 				if ((cr = CRED()) == NULL ||
7514 				    s_cr->cr_zone->zone_id !=
7515 				    cr->cr_zone->zone_id)
7516 					continue;
7517 			}
7518 #endif
7519 		}
7520 
7521 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7522 			/*
7523 			 * We seem to be dead.  Unless we (a) have kernel
7524 			 * destructive permissions (b) have explicitly enabled
7525 			 * destructive actions and (c) destructive actions have
7526 			 * not been disabled, we're going to transition into
7527 			 * the KILLED state, from which no further processing
7528 			 * on this state will be performed.
7529 			 */
7530 			if (!dtrace_priv_kernel_destructive(state) ||
7531 			    !state->dts_cred.dcr_destructive ||
7532 			    dtrace_destructive_disallow) {
7533 				void *activity = &state->dts_activity;
7534 				dtrace_activity_t curstate;
7535 
7536 				do {
7537 					curstate = state->dts_activity;
7538 				} while (dtrace_cas32(activity, curstate,
7539 				    DTRACE_ACTIVITY_KILLED) != curstate);
7540 
7541 				continue;
7542 			}
7543 		}
7544 
7545 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7546 		    ecb->dte_alignment, state, &mstate)) < 0)
7547 			continue;
7548 
7549 		tomax = buf->dtb_tomax;
7550 		ASSERT(tomax != NULL);
7551 
7552 		if (ecb->dte_size != 0) {
7553 			dtrace_rechdr_t dtrh;
7554 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7555 				mstate.dtms_timestamp = dtrace_gethrtime();
7556 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7557 			}
7558 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7559 			dtrh.dtrh_epid = ecb->dte_epid;
7560 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7561 			    mstate.dtms_timestamp);
7562 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7563 		}
7564 
7565 		mstate.dtms_epid = ecb->dte_epid;
7566 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7567 
7568 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7569 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7570 		else
7571 			mstate.dtms_access = 0;
7572 
7573 		if (pred != NULL) {
7574 			dtrace_difo_t *dp = pred->dtp_difo;
7575 			uint64_t rval;
7576 
7577 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7578 
7579 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7580 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7581 
7582 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7583 					/*
7584 					 * Update the predicate cache...
7585 					 */
7586 					ASSERT(cid == pred->dtp_cacheid);
7587 					curthread->t_predcache = cid;
7588 				}
7589 
7590 				continue;
7591 			}
7592 		}
7593 
7594 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7595 		    act != NULL; act = act->dta_next) {
7596 			size_t valoffs;
7597 			dtrace_difo_t *dp;
7598 			dtrace_recdesc_t *rec = &act->dta_rec;
7599 
7600 			size = rec->dtrd_size;
7601 			valoffs = offs + rec->dtrd_offset;
7602 
7603 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7604 				uint64_t v = 0xbad;
7605 				dtrace_aggregation_t *agg;
7606 
7607 				agg = (dtrace_aggregation_t *)act;
7608 
7609 				if ((dp = act->dta_difo) != NULL)
7610 					v = dtrace_dif_emulate(dp,
7611 					    &mstate, vstate, state);
7612 
7613 				if (*flags & CPU_DTRACE_ERROR)
7614 					continue;
7615 
7616 				/*
7617 				 * Note that we always pass the expression
7618 				 * value from the previous iteration of the
7619 				 * action loop.  This value will only be used
7620 				 * if there is an expression argument to the
7621 				 * aggregating action, denoted by the
7622 				 * dtag_hasarg field.
7623 				 */
7624 				dtrace_aggregate(agg, buf,
7625 				    offs, aggbuf, v, val);
7626 				continue;
7627 			}
7628 
7629 			switch (act->dta_kind) {
7630 			case DTRACEACT_STOP:
7631 				if (dtrace_priv_proc_destructive(state))
7632 					dtrace_action_stop();
7633 				continue;
7634 
7635 			case DTRACEACT_BREAKPOINT:
7636 				if (dtrace_priv_kernel_destructive(state))
7637 					dtrace_action_breakpoint(ecb);
7638 				continue;
7639 
7640 			case DTRACEACT_PANIC:
7641 				if (dtrace_priv_kernel_destructive(state))
7642 					dtrace_action_panic(ecb);
7643 				continue;
7644 
7645 			case DTRACEACT_STACK:
7646 				if (!dtrace_priv_kernel(state))
7647 					continue;
7648 
7649 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7650 				    size / sizeof (pc_t), probe->dtpr_aframes,
7651 				    DTRACE_ANCHORED(probe) ? NULL :
7652 				    (uint32_t *)arg0);
7653 				continue;
7654 
7655 			case DTRACEACT_JSTACK:
7656 			case DTRACEACT_USTACK:
7657 				if (!dtrace_priv_proc(state))
7658 					continue;
7659 
7660 				/*
7661 				 * See comment in DIF_VAR_PID.
7662 				 */
7663 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7664 				    CPU_ON_INTR(CPU)) {
7665 					int depth = DTRACE_USTACK_NFRAMES(
7666 					    rec->dtrd_arg) + 1;
7667 
7668 					dtrace_bzero((void *)(tomax + valoffs),
7669 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7670 					    + depth * sizeof (uint64_t));
7671 
7672 					continue;
7673 				}
7674 
7675 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7676 				    curproc->p_dtrace_helpers != NULL) {
7677 					/*
7678 					 * This is the slow path -- we have
7679 					 * allocated string space, and we're
7680 					 * getting the stack of a process that
7681 					 * has helpers.  Call into a separate
7682 					 * routine to perform this processing.
7683 					 */
7684 					dtrace_action_ustack(&mstate, state,
7685 					    (uint64_t *)(tomax + valoffs),
7686 					    rec->dtrd_arg);
7687 					continue;
7688 				}
7689 
7690 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7691 				dtrace_getupcstack((uint64_t *)
7692 				    (tomax + valoffs),
7693 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7694 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7695 				continue;
7696 
7697 			default:
7698 				break;
7699 			}
7700 
7701 			dp = act->dta_difo;
7702 			ASSERT(dp != NULL);
7703 
7704 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7705 
7706 			if (*flags & CPU_DTRACE_ERROR)
7707 				continue;
7708 
7709 			switch (act->dta_kind) {
7710 			case DTRACEACT_SPECULATE: {
7711 				dtrace_rechdr_t *dtrh;
7712 
7713 				ASSERT(buf == &state->dts_buffer[cpuid]);
7714 				buf = dtrace_speculation_buffer(state,
7715 				    cpuid, val);
7716 
7717 				if (buf == NULL) {
7718 					*flags |= CPU_DTRACE_DROP;
7719 					continue;
7720 				}
7721 
7722 				offs = dtrace_buffer_reserve(buf,
7723 				    ecb->dte_needed, ecb->dte_alignment,
7724 				    state, NULL);
7725 
7726 				if (offs < 0) {
7727 					*flags |= CPU_DTRACE_DROP;
7728 					continue;
7729 				}
7730 
7731 				tomax = buf->dtb_tomax;
7732 				ASSERT(tomax != NULL);
7733 
7734 				if (ecb->dte_size == 0)
7735 					continue;
7736 
7737 				ASSERT3U(ecb->dte_size, >=,
7738 				    sizeof (dtrace_rechdr_t));
7739 				dtrh = ((void *)(tomax + offs));
7740 				dtrh->dtrh_epid = ecb->dte_epid;
7741 				/*
7742 				 * When the speculation is committed, all of
7743 				 * the records in the speculative buffer will
7744 				 * have their timestamps set to the commit
7745 				 * time.  Until then, it is set to a sentinel
7746 				 * value, for debugability.
7747 				 */
7748 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7749 				continue;
7750 			}
7751 
7752 			case DTRACEACT_PRINTM: {
7753 				/* The DIF returns a 'memref'. */
7754 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7755 
7756 				/* Get the size from the memref. */
7757 				size = memref[1];
7758 
7759 				/*
7760 				 * Check if the size exceeds the allocated
7761 				 * buffer size.
7762 				 */
7763 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7764 					/* Flag a drop! */
7765 					*flags |= CPU_DTRACE_DROP;
7766 					continue;
7767 				}
7768 
7769 				/* Store the size in the buffer first. */
7770 				DTRACE_STORE(uintptr_t, tomax,
7771 				    valoffs, size);
7772 
7773 				/*
7774 				 * Offset the buffer address to the start
7775 				 * of the data.
7776 				 */
7777 				valoffs += sizeof(uintptr_t);
7778 
7779 				/*
7780 				 * Reset to the memory address rather than
7781 				 * the memref array, then let the BYREF
7782 				 * code below do the work to store the
7783 				 * memory data in the buffer.
7784 				 */
7785 				val = memref[0];
7786 				break;
7787 			}
7788 
7789 			case DTRACEACT_CHILL:
7790 				if (dtrace_priv_kernel_destructive(state))
7791 					dtrace_action_chill(&mstate, val);
7792 				continue;
7793 
7794 			case DTRACEACT_RAISE:
7795 				if (dtrace_priv_proc_destructive(state))
7796 					dtrace_action_raise(val);
7797 				continue;
7798 
7799 			case DTRACEACT_COMMIT:
7800 				ASSERT(!committed);
7801 
7802 				/*
7803 				 * We need to commit our buffer state.
7804 				 */
7805 				if (ecb->dte_size)
7806 					buf->dtb_offset = offs + ecb->dte_size;
7807 				buf = &state->dts_buffer[cpuid];
7808 				dtrace_speculation_commit(state, cpuid, val);
7809 				committed = 1;
7810 				continue;
7811 
7812 			case DTRACEACT_DISCARD:
7813 				dtrace_speculation_discard(state, cpuid, val);
7814 				continue;
7815 
7816 			case DTRACEACT_DIFEXPR:
7817 			case DTRACEACT_LIBACT:
7818 			case DTRACEACT_PRINTF:
7819 			case DTRACEACT_PRINTA:
7820 			case DTRACEACT_SYSTEM:
7821 			case DTRACEACT_FREOPEN:
7822 			case DTRACEACT_TRACEMEM:
7823 				break;
7824 
7825 			case DTRACEACT_TRACEMEM_DYNSIZE:
7826 				tracememsize = val;
7827 				break;
7828 
7829 			case DTRACEACT_SYM:
7830 			case DTRACEACT_MOD:
7831 				if (!dtrace_priv_kernel(state))
7832 					continue;
7833 				break;
7834 
7835 			case DTRACEACT_USYM:
7836 			case DTRACEACT_UMOD:
7837 			case DTRACEACT_UADDR: {
7838 #ifdef illumos
7839 				struct pid *pid = curthread->t_procp->p_pidp;
7840 #endif
7841 
7842 				if (!dtrace_priv_proc(state))
7843 					continue;
7844 
7845 				DTRACE_STORE(uint64_t, tomax,
7846 #ifdef illumos
7847 				    valoffs, (uint64_t)pid->pid_id);
7848 #else
7849 				    valoffs, (uint64_t) curproc->p_pid);
7850 #endif
7851 				DTRACE_STORE(uint64_t, tomax,
7852 				    valoffs + sizeof (uint64_t), val);
7853 
7854 				continue;
7855 			}
7856 
7857 			case DTRACEACT_EXIT: {
7858 				/*
7859 				 * For the exit action, we are going to attempt
7860 				 * to atomically set our activity to be
7861 				 * draining.  If this fails (either because
7862 				 * another CPU has beat us to the exit action,
7863 				 * or because our current activity is something
7864 				 * other than ACTIVE or WARMUP), we will
7865 				 * continue.  This assures that the exit action
7866 				 * can be successfully recorded at most once
7867 				 * when we're in the ACTIVE state.  If we're
7868 				 * encountering the exit() action while in
7869 				 * COOLDOWN, however, we want to honor the new
7870 				 * status code.  (We know that we're the only
7871 				 * thread in COOLDOWN, so there is no race.)
7872 				 */
7873 				void *activity = &state->dts_activity;
7874 				dtrace_activity_t curstate = state->dts_activity;
7875 
7876 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7877 					break;
7878 
7879 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7880 					curstate = DTRACE_ACTIVITY_ACTIVE;
7881 
7882 				if (dtrace_cas32(activity, curstate,
7883 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7884 					*flags |= CPU_DTRACE_DROP;
7885 					continue;
7886 				}
7887 
7888 				break;
7889 			}
7890 
7891 			default:
7892 				ASSERT(0);
7893 			}
7894 
7895 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7896 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7897 				uintptr_t end = valoffs + size;
7898 
7899 				if (tracememsize != 0 &&
7900 				    valoffs + tracememsize < end) {
7901 					end = valoffs + tracememsize;
7902 					tracememsize = 0;
7903 				}
7904 
7905 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7906 				    !dtrace_vcanload((void *)(uintptr_t)val,
7907 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7908 					continue;
7909 
7910 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7911 				    &val, end, act->dta_intuple,
7912 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7913 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7914 				continue;
7915 			}
7916 
7917 			switch (size) {
7918 			case 0:
7919 				break;
7920 
7921 			case sizeof (uint8_t):
7922 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7923 				break;
7924 			case sizeof (uint16_t):
7925 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7926 				break;
7927 			case sizeof (uint32_t):
7928 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7929 				break;
7930 			case sizeof (uint64_t):
7931 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7932 				break;
7933 			default:
7934 				/*
7935 				 * Any other size should have been returned by
7936 				 * reference, not by value.
7937 				 */
7938 				ASSERT(0);
7939 				break;
7940 			}
7941 		}
7942 
7943 		if (*flags & CPU_DTRACE_DROP)
7944 			continue;
7945 
7946 		if (*flags & CPU_DTRACE_FAULT) {
7947 			int ndx;
7948 			dtrace_action_t *err;
7949 
7950 			buf->dtb_errors++;
7951 
7952 			if (probe->dtpr_id == dtrace_probeid_error) {
7953 				/*
7954 				 * There's nothing we can do -- we had an
7955 				 * error on the error probe.  We bump an
7956 				 * error counter to at least indicate that
7957 				 * this condition happened.
7958 				 */
7959 				dtrace_error(&state->dts_dblerrors);
7960 				continue;
7961 			}
7962 
7963 			if (vtime) {
7964 				/*
7965 				 * Before recursing on dtrace_probe(), we
7966 				 * need to explicitly clear out our start
7967 				 * time to prevent it from being accumulated
7968 				 * into t_dtrace_vtime.
7969 				 */
7970 				curthread->t_dtrace_start = 0;
7971 			}
7972 
7973 			/*
7974 			 * Iterate over the actions to figure out which action
7975 			 * we were processing when we experienced the error.
7976 			 * Note that act points _past_ the faulting action; if
7977 			 * act is ecb->dte_action, the fault was in the
7978 			 * predicate, if it's ecb->dte_action->dta_next it's
7979 			 * in action #1, and so on.
7980 			 */
7981 			for (err = ecb->dte_action, ndx = 0;
7982 			    err != act; err = err->dta_next, ndx++)
7983 				continue;
7984 
7985 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7986 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7987 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7988 			    cpu_core[cpuid].cpuc_dtrace_illval);
7989 
7990 			continue;
7991 		}
7992 
7993 		if (!committed)
7994 			buf->dtb_offset = offs + ecb->dte_size;
7995 	}
7996 
7997 	if (vtime)
7998 		curthread->t_dtrace_start = dtrace_gethrtime();
7999 
8000 	dtrace_probe_exit(cookie);
8001 }
8002 
8003 /*
8004  * DTrace Probe Hashing Functions
8005  *
8006  * The functions in this section (and indeed, the functions in remaining
8007  * sections) are not _called_ from probe context.  (Any exceptions to this are
8008  * marked with a "Note:".)  Rather, they are called from elsewhere in the
8009  * DTrace framework to look-up probes in, add probes to and remove probes from
8010  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8011  * probe tuple -- allowing for fast lookups, regardless of what was
8012  * specified.)
8013  */
8014 static uint_t
8015 dtrace_hash_str(const char *p)
8016 {
8017 	unsigned int g;
8018 	uint_t hval = 0;
8019 
8020 	while (*p) {
8021 		hval = (hval << 4) + *p++;
8022 		if ((g = (hval & 0xf0000000)) != 0)
8023 			hval ^= g >> 24;
8024 		hval &= ~g;
8025 	}
8026 	return (hval);
8027 }
8028 
8029 static dtrace_hash_t *
8030 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
8031 {
8032 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8033 
8034 	hash->dth_stroffs = stroffs;
8035 	hash->dth_nextoffs = nextoffs;
8036 	hash->dth_prevoffs = prevoffs;
8037 
8038 	hash->dth_size = 1;
8039 	hash->dth_mask = hash->dth_size - 1;
8040 
8041 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8042 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8043 
8044 	return (hash);
8045 }
8046 
8047 static void
8048 dtrace_hash_destroy(dtrace_hash_t *hash)
8049 {
8050 #ifdef DEBUG
8051 	int i;
8052 
8053 	for (i = 0; i < hash->dth_size; i++)
8054 		ASSERT(hash->dth_tab[i] == NULL);
8055 #endif
8056 
8057 	kmem_free(hash->dth_tab,
8058 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8059 	kmem_free(hash, sizeof (dtrace_hash_t));
8060 }
8061 
8062 static void
8063 dtrace_hash_resize(dtrace_hash_t *hash)
8064 {
8065 	int size = hash->dth_size, i, ndx;
8066 	int new_size = hash->dth_size << 1;
8067 	int new_mask = new_size - 1;
8068 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8069 
8070 	ASSERT((new_size & new_mask) == 0);
8071 
8072 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8073 
8074 	for (i = 0; i < size; i++) {
8075 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8076 			dtrace_probe_t *probe = bucket->dthb_chain;
8077 
8078 			ASSERT(probe != NULL);
8079 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8080 
8081 			next = bucket->dthb_next;
8082 			bucket->dthb_next = new_tab[ndx];
8083 			new_tab[ndx] = bucket;
8084 		}
8085 	}
8086 
8087 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8088 	hash->dth_tab = new_tab;
8089 	hash->dth_size = new_size;
8090 	hash->dth_mask = new_mask;
8091 }
8092 
8093 static void
8094 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8095 {
8096 	int hashval = DTRACE_HASHSTR(hash, new);
8097 	int ndx = hashval & hash->dth_mask;
8098 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8099 	dtrace_probe_t **nextp, **prevp;
8100 
8101 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8102 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8103 			goto add;
8104 	}
8105 
8106 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8107 		dtrace_hash_resize(hash);
8108 		dtrace_hash_add(hash, new);
8109 		return;
8110 	}
8111 
8112 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8113 	bucket->dthb_next = hash->dth_tab[ndx];
8114 	hash->dth_tab[ndx] = bucket;
8115 	hash->dth_nbuckets++;
8116 
8117 add:
8118 	nextp = DTRACE_HASHNEXT(hash, new);
8119 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8120 	*nextp = bucket->dthb_chain;
8121 
8122 	if (bucket->dthb_chain != NULL) {
8123 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8124 		ASSERT(*prevp == NULL);
8125 		*prevp = new;
8126 	}
8127 
8128 	bucket->dthb_chain = new;
8129 	bucket->dthb_len++;
8130 }
8131 
8132 static dtrace_probe_t *
8133 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8134 {
8135 	int hashval = DTRACE_HASHSTR(hash, template);
8136 	int ndx = hashval & hash->dth_mask;
8137 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8138 
8139 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8140 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8141 			return (bucket->dthb_chain);
8142 	}
8143 
8144 	return (NULL);
8145 }
8146 
8147 static int
8148 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8149 {
8150 	int hashval = DTRACE_HASHSTR(hash, template);
8151 	int ndx = hashval & hash->dth_mask;
8152 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8153 
8154 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8155 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8156 			return (bucket->dthb_len);
8157 	}
8158 
8159 	return (0);
8160 }
8161 
8162 static void
8163 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8164 {
8165 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8166 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8167 
8168 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8169 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8170 
8171 	/*
8172 	 * Find the bucket that we're removing this probe from.
8173 	 */
8174 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8175 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8176 			break;
8177 	}
8178 
8179 	ASSERT(bucket != NULL);
8180 
8181 	if (*prevp == NULL) {
8182 		if (*nextp == NULL) {
8183 			/*
8184 			 * The removed probe was the only probe on this
8185 			 * bucket; we need to remove the bucket.
8186 			 */
8187 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8188 
8189 			ASSERT(bucket->dthb_chain == probe);
8190 			ASSERT(b != NULL);
8191 
8192 			if (b == bucket) {
8193 				hash->dth_tab[ndx] = bucket->dthb_next;
8194 			} else {
8195 				while (b->dthb_next != bucket)
8196 					b = b->dthb_next;
8197 				b->dthb_next = bucket->dthb_next;
8198 			}
8199 
8200 			ASSERT(hash->dth_nbuckets > 0);
8201 			hash->dth_nbuckets--;
8202 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8203 			return;
8204 		}
8205 
8206 		bucket->dthb_chain = *nextp;
8207 	} else {
8208 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8209 	}
8210 
8211 	if (*nextp != NULL)
8212 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8213 }
8214 
8215 /*
8216  * DTrace Utility Functions
8217  *
8218  * These are random utility functions that are _not_ called from probe context.
8219  */
8220 static int
8221 dtrace_badattr(const dtrace_attribute_t *a)
8222 {
8223 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8224 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8225 	    a->dtat_class > DTRACE_CLASS_MAX);
8226 }
8227 
8228 /*
8229  * Return a duplicate copy of a string.  If the specified string is NULL,
8230  * this function returns a zero-length string.
8231  */
8232 static char *
8233 dtrace_strdup(const char *str)
8234 {
8235 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8236 
8237 	if (str != NULL)
8238 		(void) strcpy(new, str);
8239 
8240 	return (new);
8241 }
8242 
8243 #define	DTRACE_ISALPHA(c)	\
8244 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8245 
8246 static int
8247 dtrace_badname(const char *s)
8248 {
8249 	char c;
8250 
8251 	if (s == NULL || (c = *s++) == '\0')
8252 		return (0);
8253 
8254 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8255 		return (1);
8256 
8257 	while ((c = *s++) != '\0') {
8258 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8259 		    c != '-' && c != '_' && c != '.' && c != '`')
8260 			return (1);
8261 	}
8262 
8263 	return (0);
8264 }
8265 
8266 static void
8267 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8268 {
8269 	uint32_t priv;
8270 
8271 #ifdef illumos
8272 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8273 		/*
8274 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8275 		 */
8276 		priv = DTRACE_PRIV_ALL;
8277 	} else {
8278 		*uidp = crgetuid(cr);
8279 		*zoneidp = crgetzoneid(cr);
8280 
8281 		priv = 0;
8282 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8283 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8284 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8285 			priv |= DTRACE_PRIV_USER;
8286 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8287 			priv |= DTRACE_PRIV_PROC;
8288 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8289 			priv |= DTRACE_PRIV_OWNER;
8290 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8291 			priv |= DTRACE_PRIV_ZONEOWNER;
8292 	}
8293 #else
8294 	priv = DTRACE_PRIV_ALL;
8295 #endif
8296 
8297 	*privp = priv;
8298 }
8299 
8300 #ifdef DTRACE_ERRDEBUG
8301 static void
8302 dtrace_errdebug(const char *str)
8303 {
8304 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8305 	int occupied = 0;
8306 
8307 	mutex_enter(&dtrace_errlock);
8308 	dtrace_errlast = str;
8309 	dtrace_errthread = curthread;
8310 
8311 	while (occupied++ < DTRACE_ERRHASHSZ) {
8312 		if (dtrace_errhash[hval].dter_msg == str) {
8313 			dtrace_errhash[hval].dter_count++;
8314 			goto out;
8315 		}
8316 
8317 		if (dtrace_errhash[hval].dter_msg != NULL) {
8318 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8319 			continue;
8320 		}
8321 
8322 		dtrace_errhash[hval].dter_msg = str;
8323 		dtrace_errhash[hval].dter_count = 1;
8324 		goto out;
8325 	}
8326 
8327 	panic("dtrace: undersized error hash");
8328 out:
8329 	mutex_exit(&dtrace_errlock);
8330 }
8331 #endif
8332 
8333 /*
8334  * DTrace Matching Functions
8335  *
8336  * These functions are used to match groups of probes, given some elements of
8337  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8338  */
8339 static int
8340 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8341     zoneid_t zoneid)
8342 {
8343 	if (priv != DTRACE_PRIV_ALL) {
8344 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8345 		uint32_t match = priv & ppriv;
8346 
8347 		/*
8348 		 * No PRIV_DTRACE_* privileges...
8349 		 */
8350 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8351 		    DTRACE_PRIV_KERNEL)) == 0)
8352 			return (0);
8353 
8354 		/*
8355 		 * No matching bits, but there were bits to match...
8356 		 */
8357 		if (match == 0 && ppriv != 0)
8358 			return (0);
8359 
8360 		/*
8361 		 * Need to have permissions to the process, but don't...
8362 		 */
8363 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8364 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8365 			return (0);
8366 		}
8367 
8368 		/*
8369 		 * Need to be in the same zone unless we possess the
8370 		 * privilege to examine all zones.
8371 		 */
8372 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8373 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8374 			return (0);
8375 		}
8376 	}
8377 
8378 	return (1);
8379 }
8380 
8381 /*
8382  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8383  * consists of input pattern strings and an ops-vector to evaluate them.
8384  * This function returns >0 for match, 0 for no match, and <0 for error.
8385  */
8386 static int
8387 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8388     uint32_t priv, uid_t uid, zoneid_t zoneid)
8389 {
8390 	dtrace_provider_t *pvp = prp->dtpr_provider;
8391 	int rv;
8392 
8393 	if (pvp->dtpv_defunct)
8394 		return (0);
8395 
8396 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8397 		return (rv);
8398 
8399 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8400 		return (rv);
8401 
8402 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8403 		return (rv);
8404 
8405 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8406 		return (rv);
8407 
8408 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8409 		return (0);
8410 
8411 	return (rv);
8412 }
8413 
8414 /*
8415  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8416  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8417  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8418  * In addition, all of the recursion cases except for '*' matching have been
8419  * unwound.  For '*', we still implement recursive evaluation, but a depth
8420  * counter is maintained and matching is aborted if we recurse too deep.
8421  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8422  */
8423 static int
8424 dtrace_match_glob(const char *s, const char *p, int depth)
8425 {
8426 	const char *olds;
8427 	char s1, c;
8428 	int gs;
8429 
8430 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8431 		return (-1);
8432 
8433 	if (s == NULL)
8434 		s = ""; /* treat NULL as empty string */
8435 
8436 top:
8437 	olds = s;
8438 	s1 = *s++;
8439 
8440 	if (p == NULL)
8441 		return (0);
8442 
8443 	if ((c = *p++) == '\0')
8444 		return (s1 == '\0');
8445 
8446 	switch (c) {
8447 	case '[': {
8448 		int ok = 0, notflag = 0;
8449 		char lc = '\0';
8450 
8451 		if (s1 == '\0')
8452 			return (0);
8453 
8454 		if (*p == '!') {
8455 			notflag = 1;
8456 			p++;
8457 		}
8458 
8459 		if ((c = *p++) == '\0')
8460 			return (0);
8461 
8462 		do {
8463 			if (c == '-' && lc != '\0' && *p != ']') {
8464 				if ((c = *p++) == '\0')
8465 					return (0);
8466 				if (c == '\\' && (c = *p++) == '\0')
8467 					return (0);
8468 
8469 				if (notflag) {
8470 					if (s1 < lc || s1 > c)
8471 						ok++;
8472 					else
8473 						return (0);
8474 				} else if (lc <= s1 && s1 <= c)
8475 					ok++;
8476 
8477 			} else if (c == '\\' && (c = *p++) == '\0')
8478 				return (0);
8479 
8480 			lc = c; /* save left-hand 'c' for next iteration */
8481 
8482 			if (notflag) {
8483 				if (s1 != c)
8484 					ok++;
8485 				else
8486 					return (0);
8487 			} else if (s1 == c)
8488 				ok++;
8489 
8490 			if ((c = *p++) == '\0')
8491 				return (0);
8492 
8493 		} while (c != ']');
8494 
8495 		if (ok)
8496 			goto top;
8497 
8498 		return (0);
8499 	}
8500 
8501 	case '\\':
8502 		if ((c = *p++) == '\0')
8503 			return (0);
8504 		/*FALLTHRU*/
8505 
8506 	default:
8507 		if (c != s1)
8508 			return (0);
8509 		/*FALLTHRU*/
8510 
8511 	case '?':
8512 		if (s1 != '\0')
8513 			goto top;
8514 		return (0);
8515 
8516 	case '*':
8517 		while (*p == '*')
8518 			p++; /* consecutive *'s are identical to a single one */
8519 
8520 		if (*p == '\0')
8521 			return (1);
8522 
8523 		for (s = olds; *s != '\0'; s++) {
8524 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8525 				return (gs);
8526 		}
8527 
8528 		return (0);
8529 	}
8530 }
8531 
8532 /*ARGSUSED*/
8533 static int
8534 dtrace_match_string(const char *s, const char *p, int depth)
8535 {
8536 	return (s != NULL && strcmp(s, p) == 0);
8537 }
8538 
8539 /*ARGSUSED*/
8540 static int
8541 dtrace_match_nul(const char *s, const char *p, int depth)
8542 {
8543 	return (1); /* always match the empty pattern */
8544 }
8545 
8546 /*ARGSUSED*/
8547 static int
8548 dtrace_match_nonzero(const char *s, const char *p, int depth)
8549 {
8550 	return (s != NULL && s[0] != '\0');
8551 }
8552 
8553 static int
8554 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8555     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8556 {
8557 	dtrace_probe_t template, *probe;
8558 	dtrace_hash_t *hash = NULL;
8559 	int len, best = INT_MAX, nmatched = 0;
8560 	dtrace_id_t i;
8561 
8562 	ASSERT(MUTEX_HELD(&dtrace_lock));
8563 
8564 	/*
8565 	 * If the probe ID is specified in the key, just lookup by ID and
8566 	 * invoke the match callback once if a matching probe is found.
8567 	 */
8568 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8569 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8570 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8571 			(void) (*matched)(probe, arg);
8572 			nmatched++;
8573 		}
8574 		return (nmatched);
8575 	}
8576 
8577 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8578 	template.dtpr_func = (char *)pkp->dtpk_func;
8579 	template.dtpr_name = (char *)pkp->dtpk_name;
8580 
8581 	/*
8582 	 * We want to find the most distinct of the module name, function
8583 	 * name, and name.  So for each one that is not a glob pattern or
8584 	 * empty string, we perform a lookup in the corresponding hash and
8585 	 * use the hash table with the fewest collisions to do our search.
8586 	 */
8587 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8588 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8589 		best = len;
8590 		hash = dtrace_bymod;
8591 	}
8592 
8593 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8594 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8595 		best = len;
8596 		hash = dtrace_byfunc;
8597 	}
8598 
8599 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8600 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8601 		best = len;
8602 		hash = dtrace_byname;
8603 	}
8604 
8605 	/*
8606 	 * If we did not select a hash table, iterate over every probe and
8607 	 * invoke our callback for each one that matches our input probe key.
8608 	 */
8609 	if (hash == NULL) {
8610 		for (i = 0; i < dtrace_nprobes; i++) {
8611 			if ((probe = dtrace_probes[i]) == NULL ||
8612 			    dtrace_match_probe(probe, pkp, priv, uid,
8613 			    zoneid) <= 0)
8614 				continue;
8615 
8616 			nmatched++;
8617 
8618 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8619 				break;
8620 		}
8621 
8622 		return (nmatched);
8623 	}
8624 
8625 	/*
8626 	 * If we selected a hash table, iterate over each probe of the same key
8627 	 * name and invoke the callback for every probe that matches the other
8628 	 * attributes of our input probe key.
8629 	 */
8630 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8631 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8632 
8633 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8634 			continue;
8635 
8636 		nmatched++;
8637 
8638 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8639 			break;
8640 	}
8641 
8642 	return (nmatched);
8643 }
8644 
8645 /*
8646  * Return the function pointer dtrace_probecmp() should use to compare the
8647  * specified pattern with a string.  For NULL or empty patterns, we select
8648  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8649  * For non-empty non-glob strings, we use dtrace_match_string().
8650  */
8651 static dtrace_probekey_f *
8652 dtrace_probekey_func(const char *p)
8653 {
8654 	char c;
8655 
8656 	if (p == NULL || *p == '\0')
8657 		return (&dtrace_match_nul);
8658 
8659 	while ((c = *p++) != '\0') {
8660 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8661 			return (&dtrace_match_glob);
8662 	}
8663 
8664 	return (&dtrace_match_string);
8665 }
8666 
8667 /*
8668  * Build a probe comparison key for use with dtrace_match_probe() from the
8669  * given probe description.  By convention, a null key only matches anchored
8670  * probes: if each field is the empty string, reset dtpk_fmatch to
8671  * dtrace_match_nonzero().
8672  */
8673 static void
8674 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8675 {
8676 	pkp->dtpk_prov = pdp->dtpd_provider;
8677 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8678 
8679 	pkp->dtpk_mod = pdp->dtpd_mod;
8680 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8681 
8682 	pkp->dtpk_func = pdp->dtpd_func;
8683 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8684 
8685 	pkp->dtpk_name = pdp->dtpd_name;
8686 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8687 
8688 	pkp->dtpk_id = pdp->dtpd_id;
8689 
8690 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8691 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8692 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8693 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8694 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8695 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8696 }
8697 
8698 /*
8699  * DTrace Provider-to-Framework API Functions
8700  *
8701  * These functions implement much of the Provider-to-Framework API, as
8702  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8703  * the functions in the API for probe management (found below), and
8704  * dtrace_probe() itself (found above).
8705  */
8706 
8707 /*
8708  * Register the calling provider with the DTrace framework.  This should
8709  * generally be called by DTrace providers in their attach(9E) entry point.
8710  */
8711 int
8712 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8713     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8714 {
8715 	dtrace_provider_t *provider;
8716 
8717 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8718 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8719 		    "arguments", name ? name : "<NULL>");
8720 		return (EINVAL);
8721 	}
8722 
8723 	if (name[0] == '\0' || dtrace_badname(name)) {
8724 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8725 		    "provider name", name);
8726 		return (EINVAL);
8727 	}
8728 
8729 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8730 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8731 	    pops->dtps_destroy == NULL ||
8732 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8733 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8734 		    "provider ops", name);
8735 		return (EINVAL);
8736 	}
8737 
8738 	if (dtrace_badattr(&pap->dtpa_provider) ||
8739 	    dtrace_badattr(&pap->dtpa_mod) ||
8740 	    dtrace_badattr(&pap->dtpa_func) ||
8741 	    dtrace_badattr(&pap->dtpa_name) ||
8742 	    dtrace_badattr(&pap->dtpa_args)) {
8743 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8744 		    "provider attributes", name);
8745 		return (EINVAL);
8746 	}
8747 
8748 	if (priv & ~DTRACE_PRIV_ALL) {
8749 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8750 		    "privilege attributes", name);
8751 		return (EINVAL);
8752 	}
8753 
8754 	if ((priv & DTRACE_PRIV_KERNEL) &&
8755 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8756 	    pops->dtps_usermode == NULL) {
8757 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8758 		    "dtps_usermode() op for given privilege attributes", name);
8759 		return (EINVAL);
8760 	}
8761 
8762 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8763 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8764 	(void) strcpy(provider->dtpv_name, name);
8765 
8766 	provider->dtpv_attr = *pap;
8767 	provider->dtpv_priv.dtpp_flags = priv;
8768 	if (cr != NULL) {
8769 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8770 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8771 	}
8772 	provider->dtpv_pops = *pops;
8773 
8774 	if (pops->dtps_provide == NULL) {
8775 		ASSERT(pops->dtps_provide_module != NULL);
8776 		provider->dtpv_pops.dtps_provide =
8777 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8778 	}
8779 
8780 	if (pops->dtps_provide_module == NULL) {
8781 		ASSERT(pops->dtps_provide != NULL);
8782 		provider->dtpv_pops.dtps_provide_module =
8783 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8784 	}
8785 
8786 	if (pops->dtps_suspend == NULL) {
8787 		ASSERT(pops->dtps_resume == NULL);
8788 		provider->dtpv_pops.dtps_suspend =
8789 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8790 		provider->dtpv_pops.dtps_resume =
8791 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8792 	}
8793 
8794 	provider->dtpv_arg = arg;
8795 	*idp = (dtrace_provider_id_t)provider;
8796 
8797 	if (pops == &dtrace_provider_ops) {
8798 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8799 		ASSERT(MUTEX_HELD(&dtrace_lock));
8800 		ASSERT(dtrace_anon.dta_enabling == NULL);
8801 
8802 		/*
8803 		 * We make sure that the DTrace provider is at the head of
8804 		 * the provider chain.
8805 		 */
8806 		provider->dtpv_next = dtrace_provider;
8807 		dtrace_provider = provider;
8808 		return (0);
8809 	}
8810 
8811 	mutex_enter(&dtrace_provider_lock);
8812 	mutex_enter(&dtrace_lock);
8813 
8814 	/*
8815 	 * If there is at least one provider registered, we'll add this
8816 	 * provider after the first provider.
8817 	 */
8818 	if (dtrace_provider != NULL) {
8819 		provider->dtpv_next = dtrace_provider->dtpv_next;
8820 		dtrace_provider->dtpv_next = provider;
8821 	} else {
8822 		dtrace_provider = provider;
8823 	}
8824 
8825 	if (dtrace_retained != NULL) {
8826 		dtrace_enabling_provide(provider);
8827 
8828 		/*
8829 		 * Now we need to call dtrace_enabling_matchall() -- which
8830 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8831 		 * to drop all of our locks before calling into it...
8832 		 */
8833 		mutex_exit(&dtrace_lock);
8834 		mutex_exit(&dtrace_provider_lock);
8835 		dtrace_enabling_matchall();
8836 
8837 		return (0);
8838 	}
8839 
8840 	mutex_exit(&dtrace_lock);
8841 	mutex_exit(&dtrace_provider_lock);
8842 
8843 	return (0);
8844 }
8845 
8846 /*
8847  * Unregister the specified provider from the DTrace framework.  This should
8848  * generally be called by DTrace providers in their detach(9E) entry point.
8849  */
8850 int
8851 dtrace_unregister(dtrace_provider_id_t id)
8852 {
8853 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8854 	dtrace_provider_t *prev = NULL;
8855 	int i, self = 0, noreap = 0;
8856 	dtrace_probe_t *probe, *first = NULL;
8857 
8858 	if (old->dtpv_pops.dtps_enable ==
8859 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8860 		/*
8861 		 * If DTrace itself is the provider, we're called with locks
8862 		 * already held.
8863 		 */
8864 		ASSERT(old == dtrace_provider);
8865 #ifdef illumos
8866 		ASSERT(dtrace_devi != NULL);
8867 #endif
8868 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8869 		ASSERT(MUTEX_HELD(&dtrace_lock));
8870 		self = 1;
8871 
8872 		if (dtrace_provider->dtpv_next != NULL) {
8873 			/*
8874 			 * There's another provider here; return failure.
8875 			 */
8876 			return (EBUSY);
8877 		}
8878 	} else {
8879 		mutex_enter(&dtrace_provider_lock);
8880 #ifdef illumos
8881 		mutex_enter(&mod_lock);
8882 #endif
8883 		mutex_enter(&dtrace_lock);
8884 	}
8885 
8886 	/*
8887 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8888 	 * probes, we refuse to let providers slither away, unless this
8889 	 * provider has already been explicitly invalidated.
8890 	 */
8891 	if (!old->dtpv_defunct &&
8892 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8893 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8894 		if (!self) {
8895 			mutex_exit(&dtrace_lock);
8896 #ifdef illumos
8897 			mutex_exit(&mod_lock);
8898 #endif
8899 			mutex_exit(&dtrace_provider_lock);
8900 		}
8901 		return (EBUSY);
8902 	}
8903 
8904 	/*
8905 	 * Attempt to destroy the probes associated with this provider.
8906 	 */
8907 	for (i = 0; i < dtrace_nprobes; i++) {
8908 		if ((probe = dtrace_probes[i]) == NULL)
8909 			continue;
8910 
8911 		if (probe->dtpr_provider != old)
8912 			continue;
8913 
8914 		if (probe->dtpr_ecb == NULL)
8915 			continue;
8916 
8917 		/*
8918 		 * If we are trying to unregister a defunct provider, and the
8919 		 * provider was made defunct within the interval dictated by
8920 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8921 		 * attempt to reap our enablings.  To denote that the provider
8922 		 * should reattempt to unregister itself at some point in the
8923 		 * future, we will return a differentiable error code (EAGAIN
8924 		 * instead of EBUSY) in this case.
8925 		 */
8926 		if (dtrace_gethrtime() - old->dtpv_defunct >
8927 		    dtrace_unregister_defunct_reap)
8928 			noreap = 1;
8929 
8930 		if (!self) {
8931 			mutex_exit(&dtrace_lock);
8932 #ifdef illumos
8933 			mutex_exit(&mod_lock);
8934 #endif
8935 			mutex_exit(&dtrace_provider_lock);
8936 		}
8937 
8938 		if (noreap)
8939 			return (EBUSY);
8940 
8941 		(void) taskq_dispatch(dtrace_taskq,
8942 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8943 
8944 		return (EAGAIN);
8945 	}
8946 
8947 	/*
8948 	 * All of the probes for this provider are disabled; we can safely
8949 	 * remove all of them from their hash chains and from the probe array.
8950 	 */
8951 	for (i = 0; i < dtrace_nprobes; i++) {
8952 		if ((probe = dtrace_probes[i]) == NULL)
8953 			continue;
8954 
8955 		if (probe->dtpr_provider != old)
8956 			continue;
8957 
8958 		dtrace_probes[i] = NULL;
8959 
8960 		dtrace_hash_remove(dtrace_bymod, probe);
8961 		dtrace_hash_remove(dtrace_byfunc, probe);
8962 		dtrace_hash_remove(dtrace_byname, probe);
8963 
8964 		if (first == NULL) {
8965 			first = probe;
8966 			probe->dtpr_nextmod = NULL;
8967 		} else {
8968 			probe->dtpr_nextmod = first;
8969 			first = probe;
8970 		}
8971 	}
8972 
8973 	/*
8974 	 * The provider's probes have been removed from the hash chains and
8975 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8976 	 * everyone has cleared out from any probe array processing.
8977 	 */
8978 	dtrace_sync();
8979 
8980 	for (probe = first; probe != NULL; probe = first) {
8981 		first = probe->dtpr_nextmod;
8982 
8983 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8984 		    probe->dtpr_arg);
8985 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8986 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8987 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8988 #ifdef illumos
8989 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8990 #else
8991 		free_unr(dtrace_arena, probe->dtpr_id);
8992 #endif
8993 		kmem_free(probe, sizeof (dtrace_probe_t));
8994 	}
8995 
8996 	if ((prev = dtrace_provider) == old) {
8997 #ifdef illumos
8998 		ASSERT(self || dtrace_devi == NULL);
8999 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9000 #endif
9001 		dtrace_provider = old->dtpv_next;
9002 	} else {
9003 		while (prev != NULL && prev->dtpv_next != old)
9004 			prev = prev->dtpv_next;
9005 
9006 		if (prev == NULL) {
9007 			panic("attempt to unregister non-existent "
9008 			    "dtrace provider %p\n", (void *)id);
9009 		}
9010 
9011 		prev->dtpv_next = old->dtpv_next;
9012 	}
9013 
9014 	if (!self) {
9015 		mutex_exit(&dtrace_lock);
9016 #ifdef illumos
9017 		mutex_exit(&mod_lock);
9018 #endif
9019 		mutex_exit(&dtrace_provider_lock);
9020 	}
9021 
9022 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9023 	kmem_free(old, sizeof (dtrace_provider_t));
9024 
9025 	return (0);
9026 }
9027 
9028 /*
9029  * Invalidate the specified provider.  All subsequent probe lookups for the
9030  * specified provider will fail, but its probes will not be removed.
9031  */
9032 void
9033 dtrace_invalidate(dtrace_provider_id_t id)
9034 {
9035 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9036 
9037 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9038 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9039 
9040 	mutex_enter(&dtrace_provider_lock);
9041 	mutex_enter(&dtrace_lock);
9042 
9043 	pvp->dtpv_defunct = dtrace_gethrtime();
9044 
9045 	mutex_exit(&dtrace_lock);
9046 	mutex_exit(&dtrace_provider_lock);
9047 }
9048 
9049 /*
9050  * Indicate whether or not DTrace has attached.
9051  */
9052 int
9053 dtrace_attached(void)
9054 {
9055 	/*
9056 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9057 	 * attached.  (It's non-NULL because DTrace is always itself a
9058 	 * provider.)
9059 	 */
9060 	return (dtrace_provider != NULL);
9061 }
9062 
9063 /*
9064  * Remove all the unenabled probes for the given provider.  This function is
9065  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9066  * -- just as many of its associated probes as it can.
9067  */
9068 int
9069 dtrace_condense(dtrace_provider_id_t id)
9070 {
9071 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9072 	int i;
9073 	dtrace_probe_t *probe;
9074 
9075 	/*
9076 	 * Make sure this isn't the dtrace provider itself.
9077 	 */
9078 	ASSERT(prov->dtpv_pops.dtps_enable !=
9079 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9080 
9081 	mutex_enter(&dtrace_provider_lock);
9082 	mutex_enter(&dtrace_lock);
9083 
9084 	/*
9085 	 * Attempt to destroy the probes associated with this provider.
9086 	 */
9087 	for (i = 0; i < dtrace_nprobes; i++) {
9088 		if ((probe = dtrace_probes[i]) == NULL)
9089 			continue;
9090 
9091 		if (probe->dtpr_provider != prov)
9092 			continue;
9093 
9094 		if (probe->dtpr_ecb != NULL)
9095 			continue;
9096 
9097 		dtrace_probes[i] = NULL;
9098 
9099 		dtrace_hash_remove(dtrace_bymod, probe);
9100 		dtrace_hash_remove(dtrace_byfunc, probe);
9101 		dtrace_hash_remove(dtrace_byname, probe);
9102 
9103 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9104 		    probe->dtpr_arg);
9105 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9106 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9107 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9108 		kmem_free(probe, sizeof (dtrace_probe_t));
9109 #ifdef illumos
9110 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9111 #else
9112 		free_unr(dtrace_arena, i + 1);
9113 #endif
9114 	}
9115 
9116 	mutex_exit(&dtrace_lock);
9117 	mutex_exit(&dtrace_provider_lock);
9118 
9119 	return (0);
9120 }
9121 
9122 /*
9123  * DTrace Probe Management Functions
9124  *
9125  * The functions in this section perform the DTrace probe management,
9126  * including functions to create probes, look-up probes, and call into the
9127  * providers to request that probes be provided.  Some of these functions are
9128  * in the Provider-to-Framework API; these functions can be identified by the
9129  * fact that they are not declared "static".
9130  */
9131 
9132 /*
9133  * Create a probe with the specified module name, function name, and name.
9134  */
9135 dtrace_id_t
9136 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9137     const char *func, const char *name, int aframes, void *arg)
9138 {
9139 	dtrace_probe_t *probe, **probes;
9140 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9141 	dtrace_id_t id;
9142 
9143 	if (provider == dtrace_provider) {
9144 		ASSERT(MUTEX_HELD(&dtrace_lock));
9145 	} else {
9146 		mutex_enter(&dtrace_lock);
9147 	}
9148 
9149 #ifdef illumos
9150 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9151 	    VM_BESTFIT | VM_SLEEP);
9152 #else
9153 	id = alloc_unr(dtrace_arena);
9154 #endif
9155 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9156 
9157 	probe->dtpr_id = id;
9158 	probe->dtpr_gen = dtrace_probegen++;
9159 	probe->dtpr_mod = dtrace_strdup(mod);
9160 	probe->dtpr_func = dtrace_strdup(func);
9161 	probe->dtpr_name = dtrace_strdup(name);
9162 	probe->dtpr_arg = arg;
9163 	probe->dtpr_aframes = aframes;
9164 	probe->dtpr_provider = provider;
9165 
9166 	dtrace_hash_add(dtrace_bymod, probe);
9167 	dtrace_hash_add(dtrace_byfunc, probe);
9168 	dtrace_hash_add(dtrace_byname, probe);
9169 
9170 	if (id - 1 >= dtrace_nprobes) {
9171 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9172 		size_t nsize = osize << 1;
9173 
9174 		if (nsize == 0) {
9175 			ASSERT(osize == 0);
9176 			ASSERT(dtrace_probes == NULL);
9177 			nsize = sizeof (dtrace_probe_t *);
9178 		}
9179 
9180 		probes = kmem_zalloc(nsize, KM_SLEEP);
9181 
9182 		if (dtrace_probes == NULL) {
9183 			ASSERT(osize == 0);
9184 			dtrace_probes = probes;
9185 			dtrace_nprobes = 1;
9186 		} else {
9187 			dtrace_probe_t **oprobes = dtrace_probes;
9188 
9189 			bcopy(oprobes, probes, osize);
9190 			dtrace_membar_producer();
9191 			dtrace_probes = probes;
9192 
9193 			dtrace_sync();
9194 
9195 			/*
9196 			 * All CPUs are now seeing the new probes array; we can
9197 			 * safely free the old array.
9198 			 */
9199 			kmem_free(oprobes, osize);
9200 			dtrace_nprobes <<= 1;
9201 		}
9202 
9203 		ASSERT(id - 1 < dtrace_nprobes);
9204 	}
9205 
9206 	ASSERT(dtrace_probes[id - 1] == NULL);
9207 	dtrace_probes[id - 1] = probe;
9208 
9209 	if (provider != dtrace_provider)
9210 		mutex_exit(&dtrace_lock);
9211 
9212 	return (id);
9213 }
9214 
9215 static dtrace_probe_t *
9216 dtrace_probe_lookup_id(dtrace_id_t id)
9217 {
9218 	ASSERT(MUTEX_HELD(&dtrace_lock));
9219 
9220 	if (id == 0 || id > dtrace_nprobes)
9221 		return (NULL);
9222 
9223 	return (dtrace_probes[id - 1]);
9224 }
9225 
9226 static int
9227 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9228 {
9229 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9230 
9231 	return (DTRACE_MATCH_DONE);
9232 }
9233 
9234 /*
9235  * Look up a probe based on provider and one or more of module name, function
9236  * name and probe name.
9237  */
9238 dtrace_id_t
9239 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9240     char *func, char *name)
9241 {
9242 	dtrace_probekey_t pkey;
9243 	dtrace_id_t id;
9244 	int match;
9245 
9246 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9247 	pkey.dtpk_pmatch = &dtrace_match_string;
9248 	pkey.dtpk_mod = mod;
9249 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9250 	pkey.dtpk_func = func;
9251 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9252 	pkey.dtpk_name = name;
9253 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9254 	pkey.dtpk_id = DTRACE_IDNONE;
9255 
9256 	mutex_enter(&dtrace_lock);
9257 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9258 	    dtrace_probe_lookup_match, &id);
9259 	mutex_exit(&dtrace_lock);
9260 
9261 	ASSERT(match == 1 || match == 0);
9262 	return (match ? id : 0);
9263 }
9264 
9265 /*
9266  * Returns the probe argument associated with the specified probe.
9267  */
9268 void *
9269 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9270 {
9271 	dtrace_probe_t *probe;
9272 	void *rval = NULL;
9273 
9274 	mutex_enter(&dtrace_lock);
9275 
9276 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9277 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9278 		rval = probe->dtpr_arg;
9279 
9280 	mutex_exit(&dtrace_lock);
9281 
9282 	return (rval);
9283 }
9284 
9285 /*
9286  * Copy a probe into a probe description.
9287  */
9288 static void
9289 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9290 {
9291 	bzero(pdp, sizeof (dtrace_probedesc_t));
9292 	pdp->dtpd_id = prp->dtpr_id;
9293 
9294 	(void) strncpy(pdp->dtpd_provider,
9295 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9296 
9297 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9298 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9299 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9300 }
9301 
9302 /*
9303  * Called to indicate that a probe -- or probes -- should be provided by a
9304  * specfied provider.  If the specified description is NULL, the provider will
9305  * be told to provide all of its probes.  (This is done whenever a new
9306  * consumer comes along, or whenever a retained enabling is to be matched.) If
9307  * the specified description is non-NULL, the provider is given the
9308  * opportunity to dynamically provide the specified probe, allowing providers
9309  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9310  * probes.)  If the provider is NULL, the operations will be applied to all
9311  * providers; if the provider is non-NULL the operations will only be applied
9312  * to the specified provider.  The dtrace_provider_lock must be held, and the
9313  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9314  * will need to grab the dtrace_lock when it reenters the framework through
9315  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9316  */
9317 static void
9318 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9319 {
9320 #ifdef illumos
9321 	modctl_t *ctl;
9322 #endif
9323 	int all = 0;
9324 
9325 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9326 
9327 	if (prv == NULL) {
9328 		all = 1;
9329 		prv = dtrace_provider;
9330 	}
9331 
9332 	do {
9333 		/*
9334 		 * First, call the blanket provide operation.
9335 		 */
9336 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9337 
9338 #ifdef illumos
9339 		/*
9340 		 * Now call the per-module provide operation.  We will grab
9341 		 * mod_lock to prevent the list from being modified.  Note
9342 		 * that this also prevents the mod_busy bits from changing.
9343 		 * (mod_busy can only be changed with mod_lock held.)
9344 		 */
9345 		mutex_enter(&mod_lock);
9346 
9347 		ctl = &modules;
9348 		do {
9349 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9350 				continue;
9351 
9352 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9353 
9354 		} while ((ctl = ctl->mod_next) != &modules);
9355 
9356 		mutex_exit(&mod_lock);
9357 #endif
9358 	} while (all && (prv = prv->dtpv_next) != NULL);
9359 }
9360 
9361 #ifdef illumos
9362 /*
9363  * Iterate over each probe, and call the Framework-to-Provider API function
9364  * denoted by offs.
9365  */
9366 static void
9367 dtrace_probe_foreach(uintptr_t offs)
9368 {
9369 	dtrace_provider_t *prov;
9370 	void (*func)(void *, dtrace_id_t, void *);
9371 	dtrace_probe_t *probe;
9372 	dtrace_icookie_t cookie;
9373 	int i;
9374 
9375 	/*
9376 	 * We disable interrupts to walk through the probe array.  This is
9377 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9378 	 * won't see stale data.
9379 	 */
9380 	cookie = dtrace_interrupt_disable();
9381 
9382 	for (i = 0; i < dtrace_nprobes; i++) {
9383 		if ((probe = dtrace_probes[i]) == NULL)
9384 			continue;
9385 
9386 		if (probe->dtpr_ecb == NULL) {
9387 			/*
9388 			 * This probe isn't enabled -- don't call the function.
9389 			 */
9390 			continue;
9391 		}
9392 
9393 		prov = probe->dtpr_provider;
9394 		func = *((void(**)(void *, dtrace_id_t, void *))
9395 		    ((uintptr_t)&prov->dtpv_pops + offs));
9396 
9397 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9398 	}
9399 
9400 	dtrace_interrupt_enable(cookie);
9401 }
9402 #endif
9403 
9404 static int
9405 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9406 {
9407 	dtrace_probekey_t pkey;
9408 	uint32_t priv;
9409 	uid_t uid;
9410 	zoneid_t zoneid;
9411 
9412 	ASSERT(MUTEX_HELD(&dtrace_lock));
9413 	dtrace_ecb_create_cache = NULL;
9414 
9415 	if (desc == NULL) {
9416 		/*
9417 		 * If we're passed a NULL description, we're being asked to
9418 		 * create an ECB with a NULL probe.
9419 		 */
9420 		(void) dtrace_ecb_create_enable(NULL, enab);
9421 		return (0);
9422 	}
9423 
9424 	dtrace_probekey(desc, &pkey);
9425 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9426 	    &priv, &uid, &zoneid);
9427 
9428 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9429 	    enab));
9430 }
9431 
9432 /*
9433  * DTrace Helper Provider Functions
9434  */
9435 static void
9436 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9437 {
9438 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9439 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9440 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9441 }
9442 
9443 static void
9444 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9445     const dof_provider_t *dofprov, char *strtab)
9446 {
9447 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9448 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9449 	    dofprov->dofpv_provattr);
9450 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9451 	    dofprov->dofpv_modattr);
9452 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9453 	    dofprov->dofpv_funcattr);
9454 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9455 	    dofprov->dofpv_nameattr);
9456 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9457 	    dofprov->dofpv_argsattr);
9458 }
9459 
9460 static void
9461 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9462 {
9463 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9464 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9465 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9466 	dof_provider_t *provider;
9467 	dof_probe_t *probe;
9468 	uint32_t *off, *enoff;
9469 	uint8_t *arg;
9470 	char *strtab;
9471 	uint_t i, nprobes;
9472 	dtrace_helper_provdesc_t dhpv;
9473 	dtrace_helper_probedesc_t dhpb;
9474 	dtrace_meta_t *meta = dtrace_meta_pid;
9475 	dtrace_mops_t *mops = &meta->dtm_mops;
9476 	void *parg;
9477 
9478 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9479 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9480 	    provider->dofpv_strtab * dof->dofh_secsize);
9481 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9482 	    provider->dofpv_probes * dof->dofh_secsize);
9483 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9484 	    provider->dofpv_prargs * dof->dofh_secsize);
9485 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9486 	    provider->dofpv_proffs * dof->dofh_secsize);
9487 
9488 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9489 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9490 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9491 	enoff = NULL;
9492 
9493 	/*
9494 	 * See dtrace_helper_provider_validate().
9495 	 */
9496 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9497 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9498 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9499 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9500 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9501 	}
9502 
9503 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9504 
9505 	/*
9506 	 * Create the provider.
9507 	 */
9508 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9509 
9510 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9511 		return;
9512 
9513 	meta->dtm_count++;
9514 
9515 	/*
9516 	 * Create the probes.
9517 	 */
9518 	for (i = 0; i < nprobes; i++) {
9519 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9520 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9521 
9522 		/* See the check in dtrace_helper_provider_validate(). */
9523 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9524 			continue;
9525 
9526 		dhpb.dthpb_mod = dhp->dofhp_mod;
9527 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9528 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9529 		dhpb.dthpb_base = probe->dofpr_addr;
9530 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9531 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9532 		if (enoff != NULL) {
9533 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9534 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9535 		} else {
9536 			dhpb.dthpb_enoffs = NULL;
9537 			dhpb.dthpb_nenoffs = 0;
9538 		}
9539 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9540 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9541 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9542 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9543 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9544 
9545 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9546 	}
9547 }
9548 
9549 static void
9550 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9551 {
9552 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9553 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9554 	int i;
9555 
9556 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9557 
9558 	for (i = 0; i < dof->dofh_secnum; i++) {
9559 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9560 		    dof->dofh_secoff + i * dof->dofh_secsize);
9561 
9562 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9563 			continue;
9564 
9565 		dtrace_helper_provide_one(dhp, sec, pid);
9566 	}
9567 
9568 	/*
9569 	 * We may have just created probes, so we must now rematch against
9570 	 * any retained enablings.  Note that this call will acquire both
9571 	 * cpu_lock and dtrace_lock; the fact that we are holding
9572 	 * dtrace_meta_lock now is what defines the ordering with respect to
9573 	 * these three locks.
9574 	 */
9575 	dtrace_enabling_matchall();
9576 }
9577 
9578 static void
9579 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9580 {
9581 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9582 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9583 	dof_sec_t *str_sec;
9584 	dof_provider_t *provider;
9585 	char *strtab;
9586 	dtrace_helper_provdesc_t dhpv;
9587 	dtrace_meta_t *meta = dtrace_meta_pid;
9588 	dtrace_mops_t *mops = &meta->dtm_mops;
9589 
9590 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9591 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9592 	    provider->dofpv_strtab * dof->dofh_secsize);
9593 
9594 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9595 
9596 	/*
9597 	 * Create the provider.
9598 	 */
9599 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9600 
9601 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9602 
9603 	meta->dtm_count--;
9604 }
9605 
9606 static void
9607 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9608 {
9609 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9610 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9611 	int i;
9612 
9613 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9614 
9615 	for (i = 0; i < dof->dofh_secnum; i++) {
9616 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9617 		    dof->dofh_secoff + i * dof->dofh_secsize);
9618 
9619 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9620 			continue;
9621 
9622 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9623 	}
9624 }
9625 
9626 /*
9627  * DTrace Meta Provider-to-Framework API Functions
9628  *
9629  * These functions implement the Meta Provider-to-Framework API, as described
9630  * in <sys/dtrace.h>.
9631  */
9632 int
9633 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9634     dtrace_meta_provider_id_t *idp)
9635 {
9636 	dtrace_meta_t *meta;
9637 	dtrace_helpers_t *help, *next;
9638 	int i;
9639 
9640 	*idp = DTRACE_METAPROVNONE;
9641 
9642 	/*
9643 	 * We strictly don't need the name, but we hold onto it for
9644 	 * debuggability. All hail error queues!
9645 	 */
9646 	if (name == NULL) {
9647 		cmn_err(CE_WARN, "failed to register meta-provider: "
9648 		    "invalid name");
9649 		return (EINVAL);
9650 	}
9651 
9652 	if (mops == NULL ||
9653 	    mops->dtms_create_probe == NULL ||
9654 	    mops->dtms_provide_pid == NULL ||
9655 	    mops->dtms_remove_pid == NULL) {
9656 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9657 		    "invalid ops", name);
9658 		return (EINVAL);
9659 	}
9660 
9661 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9662 	meta->dtm_mops = *mops;
9663 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9664 	(void) strcpy(meta->dtm_name, name);
9665 	meta->dtm_arg = arg;
9666 
9667 	mutex_enter(&dtrace_meta_lock);
9668 	mutex_enter(&dtrace_lock);
9669 
9670 	if (dtrace_meta_pid != NULL) {
9671 		mutex_exit(&dtrace_lock);
9672 		mutex_exit(&dtrace_meta_lock);
9673 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9674 		    "user-land meta-provider exists", name);
9675 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9676 		kmem_free(meta, sizeof (dtrace_meta_t));
9677 		return (EINVAL);
9678 	}
9679 
9680 	dtrace_meta_pid = meta;
9681 	*idp = (dtrace_meta_provider_id_t)meta;
9682 
9683 	/*
9684 	 * If there are providers and probes ready to go, pass them
9685 	 * off to the new meta provider now.
9686 	 */
9687 
9688 	help = dtrace_deferred_pid;
9689 	dtrace_deferred_pid = NULL;
9690 
9691 	mutex_exit(&dtrace_lock);
9692 
9693 	while (help != NULL) {
9694 		for (i = 0; i < help->dthps_nprovs; i++) {
9695 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9696 			    help->dthps_pid);
9697 		}
9698 
9699 		next = help->dthps_next;
9700 		help->dthps_next = NULL;
9701 		help->dthps_prev = NULL;
9702 		help->dthps_deferred = 0;
9703 		help = next;
9704 	}
9705 
9706 	mutex_exit(&dtrace_meta_lock);
9707 
9708 	return (0);
9709 }
9710 
9711 int
9712 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9713 {
9714 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9715 
9716 	mutex_enter(&dtrace_meta_lock);
9717 	mutex_enter(&dtrace_lock);
9718 
9719 	if (old == dtrace_meta_pid) {
9720 		pp = &dtrace_meta_pid;
9721 	} else {
9722 		panic("attempt to unregister non-existent "
9723 		    "dtrace meta-provider %p\n", (void *)old);
9724 	}
9725 
9726 	if (old->dtm_count != 0) {
9727 		mutex_exit(&dtrace_lock);
9728 		mutex_exit(&dtrace_meta_lock);
9729 		return (EBUSY);
9730 	}
9731 
9732 	*pp = NULL;
9733 
9734 	mutex_exit(&dtrace_lock);
9735 	mutex_exit(&dtrace_meta_lock);
9736 
9737 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9738 	kmem_free(old, sizeof (dtrace_meta_t));
9739 
9740 	return (0);
9741 }
9742 
9743 
9744 /*
9745  * DTrace DIF Object Functions
9746  */
9747 static int
9748 dtrace_difo_err(uint_t pc, const char *format, ...)
9749 {
9750 	if (dtrace_err_verbose) {
9751 		va_list alist;
9752 
9753 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9754 		va_start(alist, format);
9755 		(void) vuprintf(format, alist);
9756 		va_end(alist);
9757 	}
9758 
9759 #ifdef DTRACE_ERRDEBUG
9760 	dtrace_errdebug(format);
9761 #endif
9762 	return (1);
9763 }
9764 
9765 /*
9766  * Validate a DTrace DIF object by checking the IR instructions.  The following
9767  * rules are currently enforced by dtrace_difo_validate():
9768  *
9769  * 1. Each instruction must have a valid opcode
9770  * 2. Each register, string, variable, or subroutine reference must be valid
9771  * 3. No instruction can modify register %r0 (must be zero)
9772  * 4. All instruction reserved bits must be set to zero
9773  * 5. The last instruction must be a "ret" instruction
9774  * 6. All branch targets must reference a valid instruction _after_ the branch
9775  */
9776 static int
9777 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9778     cred_t *cr)
9779 {
9780 	int err = 0, i;
9781 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9782 	int kcheckload;
9783 	uint_t pc;
9784 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9785 
9786 	kcheckload = cr == NULL ||
9787 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9788 
9789 	dp->dtdo_destructive = 0;
9790 
9791 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9792 		dif_instr_t instr = dp->dtdo_buf[pc];
9793 
9794 		uint_t r1 = DIF_INSTR_R1(instr);
9795 		uint_t r2 = DIF_INSTR_R2(instr);
9796 		uint_t rd = DIF_INSTR_RD(instr);
9797 		uint_t rs = DIF_INSTR_RS(instr);
9798 		uint_t label = DIF_INSTR_LABEL(instr);
9799 		uint_t v = DIF_INSTR_VAR(instr);
9800 		uint_t subr = DIF_INSTR_SUBR(instr);
9801 		uint_t type = DIF_INSTR_TYPE(instr);
9802 		uint_t op = DIF_INSTR_OP(instr);
9803 
9804 		switch (op) {
9805 		case DIF_OP_OR:
9806 		case DIF_OP_XOR:
9807 		case DIF_OP_AND:
9808 		case DIF_OP_SLL:
9809 		case DIF_OP_SRL:
9810 		case DIF_OP_SRA:
9811 		case DIF_OP_SUB:
9812 		case DIF_OP_ADD:
9813 		case DIF_OP_MUL:
9814 		case DIF_OP_SDIV:
9815 		case DIF_OP_UDIV:
9816 		case DIF_OP_SREM:
9817 		case DIF_OP_UREM:
9818 		case DIF_OP_COPYS:
9819 			if (r1 >= nregs)
9820 				err += efunc(pc, "invalid register %u\n", r1);
9821 			if (r2 >= nregs)
9822 				err += efunc(pc, "invalid register %u\n", r2);
9823 			if (rd >= nregs)
9824 				err += efunc(pc, "invalid register %u\n", rd);
9825 			if (rd == 0)
9826 				err += efunc(pc, "cannot write to %r0\n");
9827 			break;
9828 		case DIF_OP_NOT:
9829 		case DIF_OP_MOV:
9830 		case DIF_OP_ALLOCS:
9831 			if (r1 >= nregs)
9832 				err += efunc(pc, "invalid register %u\n", r1);
9833 			if (r2 != 0)
9834 				err += efunc(pc, "non-zero reserved bits\n");
9835 			if (rd >= nregs)
9836 				err += efunc(pc, "invalid register %u\n", rd);
9837 			if (rd == 0)
9838 				err += efunc(pc, "cannot write to %r0\n");
9839 			break;
9840 		case DIF_OP_LDSB:
9841 		case DIF_OP_LDSH:
9842 		case DIF_OP_LDSW:
9843 		case DIF_OP_LDUB:
9844 		case DIF_OP_LDUH:
9845 		case DIF_OP_LDUW:
9846 		case DIF_OP_LDX:
9847 			if (r1 >= nregs)
9848 				err += efunc(pc, "invalid register %u\n", r1);
9849 			if (r2 != 0)
9850 				err += efunc(pc, "non-zero reserved bits\n");
9851 			if (rd >= nregs)
9852 				err += efunc(pc, "invalid register %u\n", rd);
9853 			if (rd == 0)
9854 				err += efunc(pc, "cannot write to %r0\n");
9855 			if (kcheckload)
9856 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9857 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9858 			break;
9859 		case DIF_OP_RLDSB:
9860 		case DIF_OP_RLDSH:
9861 		case DIF_OP_RLDSW:
9862 		case DIF_OP_RLDUB:
9863 		case DIF_OP_RLDUH:
9864 		case DIF_OP_RLDUW:
9865 		case DIF_OP_RLDX:
9866 			if (r1 >= nregs)
9867 				err += efunc(pc, "invalid register %u\n", r1);
9868 			if (r2 != 0)
9869 				err += efunc(pc, "non-zero reserved bits\n");
9870 			if (rd >= nregs)
9871 				err += efunc(pc, "invalid register %u\n", rd);
9872 			if (rd == 0)
9873 				err += efunc(pc, "cannot write to %r0\n");
9874 			break;
9875 		case DIF_OP_ULDSB:
9876 		case DIF_OP_ULDSH:
9877 		case DIF_OP_ULDSW:
9878 		case DIF_OP_ULDUB:
9879 		case DIF_OP_ULDUH:
9880 		case DIF_OP_ULDUW:
9881 		case DIF_OP_ULDX:
9882 			if (r1 >= nregs)
9883 				err += efunc(pc, "invalid register %u\n", r1);
9884 			if (r2 != 0)
9885 				err += efunc(pc, "non-zero reserved bits\n");
9886 			if (rd >= nregs)
9887 				err += efunc(pc, "invalid register %u\n", rd);
9888 			if (rd == 0)
9889 				err += efunc(pc, "cannot write to %r0\n");
9890 			break;
9891 		case DIF_OP_STB:
9892 		case DIF_OP_STH:
9893 		case DIF_OP_STW:
9894 		case DIF_OP_STX:
9895 			if (r1 >= nregs)
9896 				err += efunc(pc, "invalid register %u\n", r1);
9897 			if (r2 != 0)
9898 				err += efunc(pc, "non-zero reserved bits\n");
9899 			if (rd >= nregs)
9900 				err += efunc(pc, "invalid register %u\n", rd);
9901 			if (rd == 0)
9902 				err += efunc(pc, "cannot write to 0 address\n");
9903 			break;
9904 		case DIF_OP_CMP:
9905 		case DIF_OP_SCMP:
9906 			if (r1 >= nregs)
9907 				err += efunc(pc, "invalid register %u\n", r1);
9908 			if (r2 >= nregs)
9909 				err += efunc(pc, "invalid register %u\n", r2);
9910 			if (rd != 0)
9911 				err += efunc(pc, "non-zero reserved bits\n");
9912 			break;
9913 		case DIF_OP_TST:
9914 			if (r1 >= nregs)
9915 				err += efunc(pc, "invalid register %u\n", r1);
9916 			if (r2 != 0 || rd != 0)
9917 				err += efunc(pc, "non-zero reserved bits\n");
9918 			break;
9919 		case DIF_OP_BA:
9920 		case DIF_OP_BE:
9921 		case DIF_OP_BNE:
9922 		case DIF_OP_BG:
9923 		case DIF_OP_BGU:
9924 		case DIF_OP_BGE:
9925 		case DIF_OP_BGEU:
9926 		case DIF_OP_BL:
9927 		case DIF_OP_BLU:
9928 		case DIF_OP_BLE:
9929 		case DIF_OP_BLEU:
9930 			if (label >= dp->dtdo_len) {
9931 				err += efunc(pc, "invalid branch target %u\n",
9932 				    label);
9933 			}
9934 			if (label <= pc) {
9935 				err += efunc(pc, "backward branch to %u\n",
9936 				    label);
9937 			}
9938 			break;
9939 		case DIF_OP_RET:
9940 			if (r1 != 0 || r2 != 0)
9941 				err += efunc(pc, "non-zero reserved bits\n");
9942 			if (rd >= nregs)
9943 				err += efunc(pc, "invalid register %u\n", rd);
9944 			break;
9945 		case DIF_OP_NOP:
9946 		case DIF_OP_POPTS:
9947 		case DIF_OP_FLUSHTS:
9948 			if (r1 != 0 || r2 != 0 || rd != 0)
9949 				err += efunc(pc, "non-zero reserved bits\n");
9950 			break;
9951 		case DIF_OP_SETX:
9952 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9953 				err += efunc(pc, "invalid integer ref %u\n",
9954 				    DIF_INSTR_INTEGER(instr));
9955 			}
9956 			if (rd >= nregs)
9957 				err += efunc(pc, "invalid register %u\n", rd);
9958 			if (rd == 0)
9959 				err += efunc(pc, "cannot write to %r0\n");
9960 			break;
9961 		case DIF_OP_SETS:
9962 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9963 				err += efunc(pc, "invalid string ref %u\n",
9964 				    DIF_INSTR_STRING(instr));
9965 			}
9966 			if (rd >= nregs)
9967 				err += efunc(pc, "invalid register %u\n", rd);
9968 			if (rd == 0)
9969 				err += efunc(pc, "cannot write to %r0\n");
9970 			break;
9971 		case DIF_OP_LDGA:
9972 		case DIF_OP_LDTA:
9973 			if (r1 > DIF_VAR_ARRAY_MAX)
9974 				err += efunc(pc, "invalid array %u\n", r1);
9975 			if (r2 >= nregs)
9976 				err += efunc(pc, "invalid register %u\n", r2);
9977 			if (rd >= nregs)
9978 				err += efunc(pc, "invalid register %u\n", rd);
9979 			if (rd == 0)
9980 				err += efunc(pc, "cannot write to %r0\n");
9981 			break;
9982 		case DIF_OP_LDGS:
9983 		case DIF_OP_LDTS:
9984 		case DIF_OP_LDLS:
9985 		case DIF_OP_LDGAA:
9986 		case DIF_OP_LDTAA:
9987 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9988 				err += efunc(pc, "invalid variable %u\n", v);
9989 			if (rd >= nregs)
9990 				err += efunc(pc, "invalid register %u\n", rd);
9991 			if (rd == 0)
9992 				err += efunc(pc, "cannot write to %r0\n");
9993 			break;
9994 		case DIF_OP_STGS:
9995 		case DIF_OP_STTS:
9996 		case DIF_OP_STLS:
9997 		case DIF_OP_STGAA:
9998 		case DIF_OP_STTAA:
9999 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
10000 				err += efunc(pc, "invalid variable %u\n", v);
10001 			if (rs >= nregs)
10002 				err += efunc(pc, "invalid register %u\n", rd);
10003 			break;
10004 		case DIF_OP_CALL:
10005 			if (subr > DIF_SUBR_MAX)
10006 				err += efunc(pc, "invalid subr %u\n", subr);
10007 			if (rd >= nregs)
10008 				err += efunc(pc, "invalid register %u\n", rd);
10009 			if (rd == 0)
10010 				err += efunc(pc, "cannot write to %r0\n");
10011 
10012 			if (subr == DIF_SUBR_COPYOUT ||
10013 			    subr == DIF_SUBR_COPYOUTSTR) {
10014 				dp->dtdo_destructive = 1;
10015 			}
10016 
10017 			if (subr == DIF_SUBR_GETF) {
10018 #ifdef __FreeBSD__
10019 				err += efunc(pc, "getf() not supported");
10020 #else
10021 				/*
10022 				 * If we have a getf() we need to record that
10023 				 * in our state.  Note that our state can be
10024 				 * NULL if this is a helper -- but in that
10025 				 * case, the call to getf() is itself illegal,
10026 				 * and will be caught (slightly later) when
10027 				 * the helper is validated.
10028 				 */
10029 				if (vstate->dtvs_state != NULL)
10030 					vstate->dtvs_state->dts_getf++;
10031 #endif
10032 			}
10033 
10034 			break;
10035 		case DIF_OP_PUSHTR:
10036 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10037 				err += efunc(pc, "invalid ref type %u\n", type);
10038 			if (r2 >= nregs)
10039 				err += efunc(pc, "invalid register %u\n", r2);
10040 			if (rs >= nregs)
10041 				err += efunc(pc, "invalid register %u\n", rs);
10042 			break;
10043 		case DIF_OP_PUSHTV:
10044 			if (type != DIF_TYPE_CTF)
10045 				err += efunc(pc, "invalid val type %u\n", type);
10046 			if (r2 >= nregs)
10047 				err += efunc(pc, "invalid register %u\n", r2);
10048 			if (rs >= nregs)
10049 				err += efunc(pc, "invalid register %u\n", rs);
10050 			break;
10051 		default:
10052 			err += efunc(pc, "invalid opcode %u\n",
10053 			    DIF_INSTR_OP(instr));
10054 		}
10055 	}
10056 
10057 	if (dp->dtdo_len != 0 &&
10058 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10059 		err += efunc(dp->dtdo_len - 1,
10060 		    "expected 'ret' as last DIF instruction\n");
10061 	}
10062 
10063 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10064 		/*
10065 		 * If we're not returning by reference, the size must be either
10066 		 * 0 or the size of one of the base types.
10067 		 */
10068 		switch (dp->dtdo_rtype.dtdt_size) {
10069 		case 0:
10070 		case sizeof (uint8_t):
10071 		case sizeof (uint16_t):
10072 		case sizeof (uint32_t):
10073 		case sizeof (uint64_t):
10074 			break;
10075 
10076 		default:
10077 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10078 		}
10079 	}
10080 
10081 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10082 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10083 		dtrace_diftype_t *vt, *et;
10084 		uint_t id, ndx;
10085 
10086 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10087 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10088 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10089 			err += efunc(i, "unrecognized variable scope %d\n",
10090 			    v->dtdv_scope);
10091 			break;
10092 		}
10093 
10094 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10095 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10096 			err += efunc(i, "unrecognized variable type %d\n",
10097 			    v->dtdv_kind);
10098 			break;
10099 		}
10100 
10101 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10102 			err += efunc(i, "%d exceeds variable id limit\n", id);
10103 			break;
10104 		}
10105 
10106 		if (id < DIF_VAR_OTHER_UBASE)
10107 			continue;
10108 
10109 		/*
10110 		 * For user-defined variables, we need to check that this
10111 		 * definition is identical to any previous definition that we
10112 		 * encountered.
10113 		 */
10114 		ndx = id - DIF_VAR_OTHER_UBASE;
10115 
10116 		switch (v->dtdv_scope) {
10117 		case DIFV_SCOPE_GLOBAL:
10118 			if (maxglobal == -1 || ndx > maxglobal)
10119 				maxglobal = ndx;
10120 
10121 			if (ndx < vstate->dtvs_nglobals) {
10122 				dtrace_statvar_t *svar;
10123 
10124 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10125 					existing = &svar->dtsv_var;
10126 			}
10127 
10128 			break;
10129 
10130 		case DIFV_SCOPE_THREAD:
10131 			if (maxtlocal == -1 || ndx > maxtlocal)
10132 				maxtlocal = ndx;
10133 
10134 			if (ndx < vstate->dtvs_ntlocals)
10135 				existing = &vstate->dtvs_tlocals[ndx];
10136 			break;
10137 
10138 		case DIFV_SCOPE_LOCAL:
10139 			if (maxlocal == -1 || ndx > maxlocal)
10140 				maxlocal = ndx;
10141 
10142 			if (ndx < vstate->dtvs_nlocals) {
10143 				dtrace_statvar_t *svar;
10144 
10145 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10146 					existing = &svar->dtsv_var;
10147 			}
10148 
10149 			break;
10150 		}
10151 
10152 		vt = &v->dtdv_type;
10153 
10154 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10155 			if (vt->dtdt_size == 0) {
10156 				err += efunc(i, "zero-sized variable\n");
10157 				break;
10158 			}
10159 
10160 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10161 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10162 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10163 				err += efunc(i, "oversized by-ref static\n");
10164 				break;
10165 			}
10166 		}
10167 
10168 		if (existing == NULL || existing->dtdv_id == 0)
10169 			continue;
10170 
10171 		ASSERT(existing->dtdv_id == v->dtdv_id);
10172 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10173 
10174 		if (existing->dtdv_kind != v->dtdv_kind)
10175 			err += efunc(i, "%d changed variable kind\n", id);
10176 
10177 		et = &existing->dtdv_type;
10178 
10179 		if (vt->dtdt_flags != et->dtdt_flags) {
10180 			err += efunc(i, "%d changed variable type flags\n", id);
10181 			break;
10182 		}
10183 
10184 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10185 			err += efunc(i, "%d changed variable type size\n", id);
10186 			break;
10187 		}
10188 	}
10189 
10190 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10191 		dif_instr_t instr = dp->dtdo_buf[pc];
10192 
10193 		uint_t v = DIF_INSTR_VAR(instr);
10194 		uint_t op = DIF_INSTR_OP(instr);
10195 
10196 		switch (op) {
10197 		case DIF_OP_LDGS:
10198 		case DIF_OP_LDGAA:
10199 		case DIF_OP_STGS:
10200 		case DIF_OP_STGAA:
10201 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10202 				err += efunc(pc, "invalid variable %u\n", v);
10203 			break;
10204 		case DIF_OP_LDTS:
10205 		case DIF_OP_LDTAA:
10206 		case DIF_OP_STTS:
10207 		case DIF_OP_STTAA:
10208 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10209 				err += efunc(pc, "invalid variable %u\n", v);
10210 			break;
10211 		case DIF_OP_LDLS:
10212 		case DIF_OP_STLS:
10213 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10214 				err += efunc(pc, "invalid variable %u\n", v);
10215 			break;
10216 		default:
10217 			break;
10218 		}
10219 	}
10220 
10221 	return (err);
10222 }
10223 
10224 /*
10225  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10226  * are much more constrained than normal DIFOs.  Specifically, they may
10227  * not:
10228  *
10229  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10230  *    miscellaneous string routines
10231  * 2. Access DTrace variables other than the args[] array, and the
10232  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10233  * 3. Have thread-local variables.
10234  * 4. Have dynamic variables.
10235  */
10236 static int
10237 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10238 {
10239 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10240 	int err = 0;
10241 	uint_t pc;
10242 
10243 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10244 		dif_instr_t instr = dp->dtdo_buf[pc];
10245 
10246 		uint_t v = DIF_INSTR_VAR(instr);
10247 		uint_t subr = DIF_INSTR_SUBR(instr);
10248 		uint_t op = DIF_INSTR_OP(instr);
10249 
10250 		switch (op) {
10251 		case DIF_OP_OR:
10252 		case DIF_OP_XOR:
10253 		case DIF_OP_AND:
10254 		case DIF_OP_SLL:
10255 		case DIF_OP_SRL:
10256 		case DIF_OP_SRA:
10257 		case DIF_OP_SUB:
10258 		case DIF_OP_ADD:
10259 		case DIF_OP_MUL:
10260 		case DIF_OP_SDIV:
10261 		case DIF_OP_UDIV:
10262 		case DIF_OP_SREM:
10263 		case DIF_OP_UREM:
10264 		case DIF_OP_COPYS:
10265 		case DIF_OP_NOT:
10266 		case DIF_OP_MOV:
10267 		case DIF_OP_RLDSB:
10268 		case DIF_OP_RLDSH:
10269 		case DIF_OP_RLDSW:
10270 		case DIF_OP_RLDUB:
10271 		case DIF_OP_RLDUH:
10272 		case DIF_OP_RLDUW:
10273 		case DIF_OP_RLDX:
10274 		case DIF_OP_ULDSB:
10275 		case DIF_OP_ULDSH:
10276 		case DIF_OP_ULDSW:
10277 		case DIF_OP_ULDUB:
10278 		case DIF_OP_ULDUH:
10279 		case DIF_OP_ULDUW:
10280 		case DIF_OP_ULDX:
10281 		case DIF_OP_STB:
10282 		case DIF_OP_STH:
10283 		case DIF_OP_STW:
10284 		case DIF_OP_STX:
10285 		case DIF_OP_ALLOCS:
10286 		case DIF_OP_CMP:
10287 		case DIF_OP_SCMP:
10288 		case DIF_OP_TST:
10289 		case DIF_OP_BA:
10290 		case DIF_OP_BE:
10291 		case DIF_OP_BNE:
10292 		case DIF_OP_BG:
10293 		case DIF_OP_BGU:
10294 		case DIF_OP_BGE:
10295 		case DIF_OP_BGEU:
10296 		case DIF_OP_BL:
10297 		case DIF_OP_BLU:
10298 		case DIF_OP_BLE:
10299 		case DIF_OP_BLEU:
10300 		case DIF_OP_RET:
10301 		case DIF_OP_NOP:
10302 		case DIF_OP_POPTS:
10303 		case DIF_OP_FLUSHTS:
10304 		case DIF_OP_SETX:
10305 		case DIF_OP_SETS:
10306 		case DIF_OP_LDGA:
10307 		case DIF_OP_LDLS:
10308 		case DIF_OP_STGS:
10309 		case DIF_OP_STLS:
10310 		case DIF_OP_PUSHTR:
10311 		case DIF_OP_PUSHTV:
10312 			break;
10313 
10314 		case DIF_OP_LDGS:
10315 			if (v >= DIF_VAR_OTHER_UBASE)
10316 				break;
10317 
10318 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10319 				break;
10320 
10321 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10322 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10323 			    v == DIF_VAR_EXECARGS ||
10324 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10325 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10326 				break;
10327 
10328 			err += efunc(pc, "illegal variable %u\n", v);
10329 			break;
10330 
10331 		case DIF_OP_LDTA:
10332 		case DIF_OP_LDTS:
10333 		case DIF_OP_LDGAA:
10334 		case DIF_OP_LDTAA:
10335 			err += efunc(pc, "illegal dynamic variable load\n");
10336 			break;
10337 
10338 		case DIF_OP_STTS:
10339 		case DIF_OP_STGAA:
10340 		case DIF_OP_STTAA:
10341 			err += efunc(pc, "illegal dynamic variable store\n");
10342 			break;
10343 
10344 		case DIF_OP_CALL:
10345 			if (subr == DIF_SUBR_ALLOCA ||
10346 			    subr == DIF_SUBR_BCOPY ||
10347 			    subr == DIF_SUBR_COPYIN ||
10348 			    subr == DIF_SUBR_COPYINTO ||
10349 			    subr == DIF_SUBR_COPYINSTR ||
10350 			    subr == DIF_SUBR_INDEX ||
10351 			    subr == DIF_SUBR_INET_NTOA ||
10352 			    subr == DIF_SUBR_INET_NTOA6 ||
10353 			    subr == DIF_SUBR_INET_NTOP ||
10354 			    subr == DIF_SUBR_JSON ||
10355 			    subr == DIF_SUBR_LLTOSTR ||
10356 			    subr == DIF_SUBR_STRTOLL ||
10357 			    subr == DIF_SUBR_RINDEX ||
10358 			    subr == DIF_SUBR_STRCHR ||
10359 			    subr == DIF_SUBR_STRJOIN ||
10360 			    subr == DIF_SUBR_STRRCHR ||
10361 			    subr == DIF_SUBR_STRSTR ||
10362 			    subr == DIF_SUBR_HTONS ||
10363 			    subr == DIF_SUBR_HTONL ||
10364 			    subr == DIF_SUBR_HTONLL ||
10365 			    subr == DIF_SUBR_NTOHS ||
10366 			    subr == DIF_SUBR_NTOHL ||
10367 			    subr == DIF_SUBR_NTOHLL ||
10368 			    subr == DIF_SUBR_MEMREF)
10369 				break;
10370 #ifdef __FreeBSD__
10371 			if (subr == DIF_SUBR_MEMSTR)
10372 				break;
10373 #endif
10374 
10375 			err += efunc(pc, "invalid subr %u\n", subr);
10376 			break;
10377 
10378 		default:
10379 			err += efunc(pc, "invalid opcode %u\n",
10380 			    DIF_INSTR_OP(instr));
10381 		}
10382 	}
10383 
10384 	return (err);
10385 }
10386 
10387 /*
10388  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10389  * basis; 0 if not.
10390  */
10391 static int
10392 dtrace_difo_cacheable(dtrace_difo_t *dp)
10393 {
10394 	int i;
10395 
10396 	if (dp == NULL)
10397 		return (0);
10398 
10399 	for (i = 0; i < dp->dtdo_varlen; i++) {
10400 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10401 
10402 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10403 			continue;
10404 
10405 		switch (v->dtdv_id) {
10406 		case DIF_VAR_CURTHREAD:
10407 		case DIF_VAR_PID:
10408 		case DIF_VAR_TID:
10409 		case DIF_VAR_EXECARGS:
10410 		case DIF_VAR_EXECNAME:
10411 		case DIF_VAR_ZONENAME:
10412 			break;
10413 
10414 		default:
10415 			return (0);
10416 		}
10417 	}
10418 
10419 	/*
10420 	 * This DIF object may be cacheable.  Now we need to look for any
10421 	 * array loading instructions, any memory loading instructions, or
10422 	 * any stores to thread-local variables.
10423 	 */
10424 	for (i = 0; i < dp->dtdo_len; i++) {
10425 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10426 
10427 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10428 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10429 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10430 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10431 			return (0);
10432 	}
10433 
10434 	return (1);
10435 }
10436 
10437 static void
10438 dtrace_difo_hold(dtrace_difo_t *dp)
10439 {
10440 	int i;
10441 
10442 	ASSERT(MUTEX_HELD(&dtrace_lock));
10443 
10444 	dp->dtdo_refcnt++;
10445 	ASSERT(dp->dtdo_refcnt != 0);
10446 
10447 	/*
10448 	 * We need to check this DIF object for references to the variable
10449 	 * DIF_VAR_VTIMESTAMP.
10450 	 */
10451 	for (i = 0; i < dp->dtdo_varlen; i++) {
10452 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10453 
10454 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10455 			continue;
10456 
10457 		if (dtrace_vtime_references++ == 0)
10458 			dtrace_vtime_enable();
10459 	}
10460 }
10461 
10462 /*
10463  * This routine calculates the dynamic variable chunksize for a given DIF
10464  * object.  The calculation is not fool-proof, and can probably be tricked by
10465  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10466  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10467  * if a dynamic variable size exceeds the chunksize.
10468  */
10469 static void
10470 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10471 {
10472 	uint64_t sval = 0;
10473 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10474 	const dif_instr_t *text = dp->dtdo_buf;
10475 	uint_t pc, srd = 0;
10476 	uint_t ttop = 0;
10477 	size_t size, ksize;
10478 	uint_t id, i;
10479 
10480 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10481 		dif_instr_t instr = text[pc];
10482 		uint_t op = DIF_INSTR_OP(instr);
10483 		uint_t rd = DIF_INSTR_RD(instr);
10484 		uint_t r1 = DIF_INSTR_R1(instr);
10485 		uint_t nkeys = 0;
10486 		uchar_t scope = 0;
10487 
10488 		dtrace_key_t *key = tupregs;
10489 
10490 		switch (op) {
10491 		case DIF_OP_SETX:
10492 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10493 			srd = rd;
10494 			continue;
10495 
10496 		case DIF_OP_STTS:
10497 			key = &tupregs[DIF_DTR_NREGS];
10498 			key[0].dttk_size = 0;
10499 			key[1].dttk_size = 0;
10500 			nkeys = 2;
10501 			scope = DIFV_SCOPE_THREAD;
10502 			break;
10503 
10504 		case DIF_OP_STGAA:
10505 		case DIF_OP_STTAA:
10506 			nkeys = ttop;
10507 
10508 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10509 				key[nkeys++].dttk_size = 0;
10510 
10511 			key[nkeys++].dttk_size = 0;
10512 
10513 			if (op == DIF_OP_STTAA) {
10514 				scope = DIFV_SCOPE_THREAD;
10515 			} else {
10516 				scope = DIFV_SCOPE_GLOBAL;
10517 			}
10518 
10519 			break;
10520 
10521 		case DIF_OP_PUSHTR:
10522 			if (ttop == DIF_DTR_NREGS)
10523 				return;
10524 
10525 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10526 				/*
10527 				 * If the register for the size of the "pushtr"
10528 				 * is %r0 (or the value is 0) and the type is
10529 				 * a string, we'll use the system-wide default
10530 				 * string size.
10531 				 */
10532 				tupregs[ttop++].dttk_size =
10533 				    dtrace_strsize_default;
10534 			} else {
10535 				if (srd == 0)
10536 					return;
10537 
10538 				if (sval > LONG_MAX)
10539 					return;
10540 
10541 				tupregs[ttop++].dttk_size = sval;
10542 			}
10543 
10544 			break;
10545 
10546 		case DIF_OP_PUSHTV:
10547 			if (ttop == DIF_DTR_NREGS)
10548 				return;
10549 
10550 			tupregs[ttop++].dttk_size = 0;
10551 			break;
10552 
10553 		case DIF_OP_FLUSHTS:
10554 			ttop = 0;
10555 			break;
10556 
10557 		case DIF_OP_POPTS:
10558 			if (ttop != 0)
10559 				ttop--;
10560 			break;
10561 		}
10562 
10563 		sval = 0;
10564 		srd = 0;
10565 
10566 		if (nkeys == 0)
10567 			continue;
10568 
10569 		/*
10570 		 * We have a dynamic variable allocation; calculate its size.
10571 		 */
10572 		for (ksize = 0, i = 0; i < nkeys; i++)
10573 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10574 
10575 		size = sizeof (dtrace_dynvar_t);
10576 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10577 		size += ksize;
10578 
10579 		/*
10580 		 * Now we need to determine the size of the stored data.
10581 		 */
10582 		id = DIF_INSTR_VAR(instr);
10583 
10584 		for (i = 0; i < dp->dtdo_varlen; i++) {
10585 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10586 
10587 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10588 				size += v->dtdv_type.dtdt_size;
10589 				break;
10590 			}
10591 		}
10592 
10593 		if (i == dp->dtdo_varlen)
10594 			return;
10595 
10596 		/*
10597 		 * We have the size.  If this is larger than the chunk size
10598 		 * for our dynamic variable state, reset the chunk size.
10599 		 */
10600 		size = P2ROUNDUP(size, sizeof (uint64_t));
10601 
10602 		/*
10603 		 * Before setting the chunk size, check that we're not going
10604 		 * to set it to a negative value...
10605 		 */
10606 		if (size > LONG_MAX)
10607 			return;
10608 
10609 		/*
10610 		 * ...and make certain that we didn't badly overflow.
10611 		 */
10612 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10613 			return;
10614 
10615 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10616 			vstate->dtvs_dynvars.dtds_chunksize = size;
10617 	}
10618 }
10619 
10620 static void
10621 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10622 {
10623 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10624 	uint_t id;
10625 
10626 	ASSERT(MUTEX_HELD(&dtrace_lock));
10627 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10628 
10629 	for (i = 0; i < dp->dtdo_varlen; i++) {
10630 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10631 		dtrace_statvar_t *svar, ***svarp = NULL;
10632 		size_t dsize = 0;
10633 		uint8_t scope = v->dtdv_scope;
10634 		int *np = NULL;
10635 
10636 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10637 			continue;
10638 
10639 		id -= DIF_VAR_OTHER_UBASE;
10640 
10641 		switch (scope) {
10642 		case DIFV_SCOPE_THREAD:
10643 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10644 				dtrace_difv_t *tlocals;
10645 
10646 				if ((ntlocals = (otlocals << 1)) == 0)
10647 					ntlocals = 1;
10648 
10649 				osz = otlocals * sizeof (dtrace_difv_t);
10650 				nsz = ntlocals * sizeof (dtrace_difv_t);
10651 
10652 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10653 
10654 				if (osz != 0) {
10655 					bcopy(vstate->dtvs_tlocals,
10656 					    tlocals, osz);
10657 					kmem_free(vstate->dtvs_tlocals, osz);
10658 				}
10659 
10660 				vstate->dtvs_tlocals = tlocals;
10661 				vstate->dtvs_ntlocals = ntlocals;
10662 			}
10663 
10664 			vstate->dtvs_tlocals[id] = *v;
10665 			continue;
10666 
10667 		case DIFV_SCOPE_LOCAL:
10668 			np = &vstate->dtvs_nlocals;
10669 			svarp = &vstate->dtvs_locals;
10670 
10671 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10672 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10673 				    sizeof (uint64_t));
10674 			else
10675 				dsize = NCPU * sizeof (uint64_t);
10676 
10677 			break;
10678 
10679 		case DIFV_SCOPE_GLOBAL:
10680 			np = &vstate->dtvs_nglobals;
10681 			svarp = &vstate->dtvs_globals;
10682 
10683 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10684 				dsize = v->dtdv_type.dtdt_size +
10685 				    sizeof (uint64_t);
10686 
10687 			break;
10688 
10689 		default:
10690 			ASSERT(0);
10691 		}
10692 
10693 		while (id >= (oldsvars = *np)) {
10694 			dtrace_statvar_t **statics;
10695 			int newsvars, oldsize, newsize;
10696 
10697 			if ((newsvars = (oldsvars << 1)) == 0)
10698 				newsvars = 1;
10699 
10700 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10701 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10702 
10703 			statics = kmem_zalloc(newsize, KM_SLEEP);
10704 
10705 			if (oldsize != 0) {
10706 				bcopy(*svarp, statics, oldsize);
10707 				kmem_free(*svarp, oldsize);
10708 			}
10709 
10710 			*svarp = statics;
10711 			*np = newsvars;
10712 		}
10713 
10714 		if ((svar = (*svarp)[id]) == NULL) {
10715 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10716 			svar->dtsv_var = *v;
10717 
10718 			if ((svar->dtsv_size = dsize) != 0) {
10719 				svar->dtsv_data = (uint64_t)(uintptr_t)
10720 				    kmem_zalloc(dsize, KM_SLEEP);
10721 			}
10722 
10723 			(*svarp)[id] = svar;
10724 		}
10725 
10726 		svar->dtsv_refcnt++;
10727 	}
10728 
10729 	dtrace_difo_chunksize(dp, vstate);
10730 	dtrace_difo_hold(dp);
10731 }
10732 
10733 static dtrace_difo_t *
10734 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10735 {
10736 	dtrace_difo_t *new;
10737 	size_t sz;
10738 
10739 	ASSERT(dp->dtdo_buf != NULL);
10740 	ASSERT(dp->dtdo_refcnt != 0);
10741 
10742 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10743 
10744 	ASSERT(dp->dtdo_buf != NULL);
10745 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10746 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10747 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10748 	new->dtdo_len = dp->dtdo_len;
10749 
10750 	if (dp->dtdo_strtab != NULL) {
10751 		ASSERT(dp->dtdo_strlen != 0);
10752 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10753 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10754 		new->dtdo_strlen = dp->dtdo_strlen;
10755 	}
10756 
10757 	if (dp->dtdo_inttab != NULL) {
10758 		ASSERT(dp->dtdo_intlen != 0);
10759 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10760 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10761 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10762 		new->dtdo_intlen = dp->dtdo_intlen;
10763 	}
10764 
10765 	if (dp->dtdo_vartab != NULL) {
10766 		ASSERT(dp->dtdo_varlen != 0);
10767 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10768 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10769 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10770 		new->dtdo_varlen = dp->dtdo_varlen;
10771 	}
10772 
10773 	dtrace_difo_init(new, vstate);
10774 	return (new);
10775 }
10776 
10777 static void
10778 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10779 {
10780 	int i;
10781 
10782 	ASSERT(dp->dtdo_refcnt == 0);
10783 
10784 	for (i = 0; i < dp->dtdo_varlen; i++) {
10785 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10786 		dtrace_statvar_t *svar, **svarp = NULL;
10787 		uint_t id;
10788 		uint8_t scope = v->dtdv_scope;
10789 		int *np = NULL;
10790 
10791 		switch (scope) {
10792 		case DIFV_SCOPE_THREAD:
10793 			continue;
10794 
10795 		case DIFV_SCOPE_LOCAL:
10796 			np = &vstate->dtvs_nlocals;
10797 			svarp = vstate->dtvs_locals;
10798 			break;
10799 
10800 		case DIFV_SCOPE_GLOBAL:
10801 			np = &vstate->dtvs_nglobals;
10802 			svarp = vstate->dtvs_globals;
10803 			break;
10804 
10805 		default:
10806 			ASSERT(0);
10807 		}
10808 
10809 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10810 			continue;
10811 
10812 		id -= DIF_VAR_OTHER_UBASE;
10813 		ASSERT(id < *np);
10814 
10815 		svar = svarp[id];
10816 		ASSERT(svar != NULL);
10817 		ASSERT(svar->dtsv_refcnt > 0);
10818 
10819 		if (--svar->dtsv_refcnt > 0)
10820 			continue;
10821 
10822 		if (svar->dtsv_size != 0) {
10823 			ASSERT(svar->dtsv_data != 0);
10824 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10825 			    svar->dtsv_size);
10826 		}
10827 
10828 		kmem_free(svar, sizeof (dtrace_statvar_t));
10829 		svarp[id] = NULL;
10830 	}
10831 
10832 	if (dp->dtdo_buf != NULL)
10833 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10834 	if (dp->dtdo_inttab != NULL)
10835 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10836 	if (dp->dtdo_strtab != NULL)
10837 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10838 	if (dp->dtdo_vartab != NULL)
10839 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10840 
10841 	kmem_free(dp, sizeof (dtrace_difo_t));
10842 }
10843 
10844 static void
10845 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10846 {
10847 	int i;
10848 
10849 	ASSERT(MUTEX_HELD(&dtrace_lock));
10850 	ASSERT(dp->dtdo_refcnt != 0);
10851 
10852 	for (i = 0; i < dp->dtdo_varlen; i++) {
10853 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10854 
10855 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10856 			continue;
10857 
10858 		ASSERT(dtrace_vtime_references > 0);
10859 		if (--dtrace_vtime_references == 0)
10860 			dtrace_vtime_disable();
10861 	}
10862 
10863 	if (--dp->dtdo_refcnt == 0)
10864 		dtrace_difo_destroy(dp, vstate);
10865 }
10866 
10867 /*
10868  * DTrace Format Functions
10869  */
10870 static uint16_t
10871 dtrace_format_add(dtrace_state_t *state, char *str)
10872 {
10873 	char *fmt, **new;
10874 	uint16_t ndx, len = strlen(str) + 1;
10875 
10876 	fmt = kmem_zalloc(len, KM_SLEEP);
10877 	bcopy(str, fmt, len);
10878 
10879 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10880 		if (state->dts_formats[ndx] == NULL) {
10881 			state->dts_formats[ndx] = fmt;
10882 			return (ndx + 1);
10883 		}
10884 	}
10885 
10886 	if (state->dts_nformats == USHRT_MAX) {
10887 		/*
10888 		 * This is only likely if a denial-of-service attack is being
10889 		 * attempted.  As such, it's okay to fail silently here.
10890 		 */
10891 		kmem_free(fmt, len);
10892 		return (0);
10893 	}
10894 
10895 	/*
10896 	 * For simplicity, we always resize the formats array to be exactly the
10897 	 * number of formats.
10898 	 */
10899 	ndx = state->dts_nformats++;
10900 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10901 
10902 	if (state->dts_formats != NULL) {
10903 		ASSERT(ndx != 0);
10904 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10905 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10906 	}
10907 
10908 	state->dts_formats = new;
10909 	state->dts_formats[ndx] = fmt;
10910 
10911 	return (ndx + 1);
10912 }
10913 
10914 static void
10915 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10916 {
10917 	char *fmt;
10918 
10919 	ASSERT(state->dts_formats != NULL);
10920 	ASSERT(format <= state->dts_nformats);
10921 	ASSERT(state->dts_formats[format - 1] != NULL);
10922 
10923 	fmt = state->dts_formats[format - 1];
10924 	kmem_free(fmt, strlen(fmt) + 1);
10925 	state->dts_formats[format - 1] = NULL;
10926 }
10927 
10928 static void
10929 dtrace_format_destroy(dtrace_state_t *state)
10930 {
10931 	int i;
10932 
10933 	if (state->dts_nformats == 0) {
10934 		ASSERT(state->dts_formats == NULL);
10935 		return;
10936 	}
10937 
10938 	ASSERT(state->dts_formats != NULL);
10939 
10940 	for (i = 0; i < state->dts_nformats; i++) {
10941 		char *fmt = state->dts_formats[i];
10942 
10943 		if (fmt == NULL)
10944 			continue;
10945 
10946 		kmem_free(fmt, strlen(fmt) + 1);
10947 	}
10948 
10949 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10950 	state->dts_nformats = 0;
10951 	state->dts_formats = NULL;
10952 }
10953 
10954 /*
10955  * DTrace Predicate Functions
10956  */
10957 static dtrace_predicate_t *
10958 dtrace_predicate_create(dtrace_difo_t *dp)
10959 {
10960 	dtrace_predicate_t *pred;
10961 
10962 	ASSERT(MUTEX_HELD(&dtrace_lock));
10963 	ASSERT(dp->dtdo_refcnt != 0);
10964 
10965 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10966 	pred->dtp_difo = dp;
10967 	pred->dtp_refcnt = 1;
10968 
10969 	if (!dtrace_difo_cacheable(dp))
10970 		return (pred);
10971 
10972 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10973 		/*
10974 		 * This is only theoretically possible -- we have had 2^32
10975 		 * cacheable predicates on this machine.  We cannot allow any
10976 		 * more predicates to become cacheable:  as unlikely as it is,
10977 		 * there may be a thread caching a (now stale) predicate cache
10978 		 * ID. (N.B.: the temptation is being successfully resisted to
10979 		 * have this cmn_err() "Holy shit -- we executed this code!")
10980 		 */
10981 		return (pred);
10982 	}
10983 
10984 	pred->dtp_cacheid = dtrace_predcache_id++;
10985 
10986 	return (pred);
10987 }
10988 
10989 static void
10990 dtrace_predicate_hold(dtrace_predicate_t *pred)
10991 {
10992 	ASSERT(MUTEX_HELD(&dtrace_lock));
10993 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10994 	ASSERT(pred->dtp_refcnt > 0);
10995 
10996 	pred->dtp_refcnt++;
10997 }
10998 
10999 static void
11000 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
11001 {
11002 	dtrace_difo_t *dp = pred->dtp_difo;
11003 
11004 	ASSERT(MUTEX_HELD(&dtrace_lock));
11005 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11006 	ASSERT(pred->dtp_refcnt > 0);
11007 
11008 	if (--pred->dtp_refcnt == 0) {
11009 		dtrace_difo_release(pred->dtp_difo, vstate);
11010 		kmem_free(pred, sizeof (dtrace_predicate_t));
11011 	}
11012 }
11013 
11014 /*
11015  * DTrace Action Description Functions
11016  */
11017 static dtrace_actdesc_t *
11018 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11019     uint64_t uarg, uint64_t arg)
11020 {
11021 	dtrace_actdesc_t *act;
11022 
11023 #ifdef illumos
11024 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11025 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11026 #endif
11027 
11028 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11029 	act->dtad_kind = kind;
11030 	act->dtad_ntuple = ntuple;
11031 	act->dtad_uarg = uarg;
11032 	act->dtad_arg = arg;
11033 	act->dtad_refcnt = 1;
11034 
11035 	return (act);
11036 }
11037 
11038 static void
11039 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11040 {
11041 	ASSERT(act->dtad_refcnt >= 1);
11042 	act->dtad_refcnt++;
11043 }
11044 
11045 static void
11046 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11047 {
11048 	dtrace_actkind_t kind = act->dtad_kind;
11049 	dtrace_difo_t *dp;
11050 
11051 	ASSERT(act->dtad_refcnt >= 1);
11052 
11053 	if (--act->dtad_refcnt != 0)
11054 		return;
11055 
11056 	if ((dp = act->dtad_difo) != NULL)
11057 		dtrace_difo_release(dp, vstate);
11058 
11059 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11060 		char *str = (char *)(uintptr_t)act->dtad_arg;
11061 
11062 #ifdef illumos
11063 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11064 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11065 #endif
11066 
11067 		if (str != NULL)
11068 			kmem_free(str, strlen(str) + 1);
11069 	}
11070 
11071 	kmem_free(act, sizeof (dtrace_actdesc_t));
11072 }
11073 
11074 /*
11075  * DTrace ECB Functions
11076  */
11077 static dtrace_ecb_t *
11078 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11079 {
11080 	dtrace_ecb_t *ecb;
11081 	dtrace_epid_t epid;
11082 
11083 	ASSERT(MUTEX_HELD(&dtrace_lock));
11084 
11085 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11086 	ecb->dte_predicate = NULL;
11087 	ecb->dte_probe = probe;
11088 
11089 	/*
11090 	 * The default size is the size of the default action: recording
11091 	 * the header.
11092 	 */
11093 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11094 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11095 
11096 	epid = state->dts_epid++;
11097 
11098 	if (epid - 1 >= state->dts_necbs) {
11099 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11100 		int necbs = state->dts_necbs << 1;
11101 
11102 		ASSERT(epid == state->dts_necbs + 1);
11103 
11104 		if (necbs == 0) {
11105 			ASSERT(oecbs == NULL);
11106 			necbs = 1;
11107 		}
11108 
11109 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11110 
11111 		if (oecbs != NULL)
11112 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11113 
11114 		dtrace_membar_producer();
11115 		state->dts_ecbs = ecbs;
11116 
11117 		if (oecbs != NULL) {
11118 			/*
11119 			 * If this state is active, we must dtrace_sync()
11120 			 * before we can free the old dts_ecbs array:  we're
11121 			 * coming in hot, and there may be active ring
11122 			 * buffer processing (which indexes into the dts_ecbs
11123 			 * array) on another CPU.
11124 			 */
11125 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11126 				dtrace_sync();
11127 
11128 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11129 		}
11130 
11131 		dtrace_membar_producer();
11132 		state->dts_necbs = necbs;
11133 	}
11134 
11135 	ecb->dte_state = state;
11136 
11137 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11138 	dtrace_membar_producer();
11139 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11140 
11141 	return (ecb);
11142 }
11143 
11144 static void
11145 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11146 {
11147 	dtrace_probe_t *probe = ecb->dte_probe;
11148 
11149 	ASSERT(MUTEX_HELD(&cpu_lock));
11150 	ASSERT(MUTEX_HELD(&dtrace_lock));
11151 	ASSERT(ecb->dte_next == NULL);
11152 
11153 	if (probe == NULL) {
11154 		/*
11155 		 * This is the NULL probe -- there's nothing to do.
11156 		 */
11157 		return;
11158 	}
11159 
11160 	if (probe->dtpr_ecb == NULL) {
11161 		dtrace_provider_t *prov = probe->dtpr_provider;
11162 
11163 		/*
11164 		 * We're the first ECB on this probe.
11165 		 */
11166 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11167 
11168 		if (ecb->dte_predicate != NULL)
11169 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11170 
11171 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11172 		    probe->dtpr_id, probe->dtpr_arg);
11173 	} else {
11174 		/*
11175 		 * This probe is already active.  Swing the last pointer to
11176 		 * point to the new ECB, and issue a dtrace_sync() to assure
11177 		 * that all CPUs have seen the change.
11178 		 */
11179 		ASSERT(probe->dtpr_ecb_last != NULL);
11180 		probe->dtpr_ecb_last->dte_next = ecb;
11181 		probe->dtpr_ecb_last = ecb;
11182 		probe->dtpr_predcache = 0;
11183 
11184 		dtrace_sync();
11185 	}
11186 }
11187 
11188 static int
11189 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11190 {
11191 	dtrace_action_t *act;
11192 	uint32_t curneeded = UINT32_MAX;
11193 	uint32_t aggbase = UINT32_MAX;
11194 
11195 	/*
11196 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11197 	 * we always record it first.)
11198 	 */
11199 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11200 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11201 
11202 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11203 		dtrace_recdesc_t *rec = &act->dta_rec;
11204 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11205 
11206 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11207 		    rec->dtrd_alignment);
11208 
11209 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11210 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11211 
11212 			ASSERT(rec->dtrd_size != 0);
11213 			ASSERT(agg->dtag_first != NULL);
11214 			ASSERT(act->dta_prev->dta_intuple);
11215 			ASSERT(aggbase != UINT32_MAX);
11216 			ASSERT(curneeded != UINT32_MAX);
11217 
11218 			agg->dtag_base = aggbase;
11219 
11220 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11221 			rec->dtrd_offset = curneeded;
11222 			if (curneeded + rec->dtrd_size < curneeded)
11223 				return (EINVAL);
11224 			curneeded += rec->dtrd_size;
11225 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11226 
11227 			aggbase = UINT32_MAX;
11228 			curneeded = UINT32_MAX;
11229 		} else if (act->dta_intuple) {
11230 			if (curneeded == UINT32_MAX) {
11231 				/*
11232 				 * This is the first record in a tuple.  Align
11233 				 * curneeded to be at offset 4 in an 8-byte
11234 				 * aligned block.
11235 				 */
11236 				ASSERT(act->dta_prev == NULL ||
11237 				    !act->dta_prev->dta_intuple);
11238 				ASSERT3U(aggbase, ==, UINT32_MAX);
11239 				curneeded = P2PHASEUP(ecb->dte_size,
11240 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11241 
11242 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11243 				ASSERT(IS_P2ALIGNED(aggbase,
11244 				    sizeof (uint64_t)));
11245 			}
11246 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11247 			rec->dtrd_offset = curneeded;
11248 			if (curneeded + rec->dtrd_size < curneeded)
11249 				return (EINVAL);
11250 			curneeded += rec->dtrd_size;
11251 		} else {
11252 			/* tuples must be followed by an aggregation */
11253 			ASSERT(act->dta_prev == NULL ||
11254 			    !act->dta_prev->dta_intuple);
11255 
11256 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11257 			    rec->dtrd_alignment);
11258 			rec->dtrd_offset = ecb->dte_size;
11259 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11260 				return (EINVAL);
11261 			ecb->dte_size += rec->dtrd_size;
11262 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11263 		}
11264 	}
11265 
11266 	if ((act = ecb->dte_action) != NULL &&
11267 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11268 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11269 		/*
11270 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11271 		 * actions store no data; set the size to 0.
11272 		 */
11273 		ecb->dte_size = 0;
11274 	}
11275 
11276 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11277 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11278 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11279 	    ecb->dte_needed);
11280 	return (0);
11281 }
11282 
11283 static dtrace_action_t *
11284 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11285 {
11286 	dtrace_aggregation_t *agg;
11287 	size_t size = sizeof (uint64_t);
11288 	int ntuple = desc->dtad_ntuple;
11289 	dtrace_action_t *act;
11290 	dtrace_recdesc_t *frec;
11291 	dtrace_aggid_t aggid;
11292 	dtrace_state_t *state = ecb->dte_state;
11293 
11294 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11295 	agg->dtag_ecb = ecb;
11296 
11297 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11298 
11299 	switch (desc->dtad_kind) {
11300 	case DTRACEAGG_MIN:
11301 		agg->dtag_initial = INT64_MAX;
11302 		agg->dtag_aggregate = dtrace_aggregate_min;
11303 		break;
11304 
11305 	case DTRACEAGG_MAX:
11306 		agg->dtag_initial = INT64_MIN;
11307 		agg->dtag_aggregate = dtrace_aggregate_max;
11308 		break;
11309 
11310 	case DTRACEAGG_COUNT:
11311 		agg->dtag_aggregate = dtrace_aggregate_count;
11312 		break;
11313 
11314 	case DTRACEAGG_QUANTIZE:
11315 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11316 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11317 		    sizeof (uint64_t);
11318 		break;
11319 
11320 	case DTRACEAGG_LQUANTIZE: {
11321 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11322 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11323 
11324 		agg->dtag_initial = desc->dtad_arg;
11325 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11326 
11327 		if (step == 0 || levels == 0)
11328 			goto err;
11329 
11330 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11331 		break;
11332 	}
11333 
11334 	case DTRACEAGG_LLQUANTIZE: {
11335 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11336 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11337 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11338 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11339 		int64_t v;
11340 
11341 		agg->dtag_initial = desc->dtad_arg;
11342 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11343 
11344 		if (factor < 2 || low >= high || nsteps < factor)
11345 			goto err;
11346 
11347 		/*
11348 		 * Now check that the number of steps evenly divides a power
11349 		 * of the factor.  (This assures both integer bucket size and
11350 		 * linearity within each magnitude.)
11351 		 */
11352 		for (v = factor; v < nsteps; v *= factor)
11353 			continue;
11354 
11355 		if ((v % nsteps) || (nsteps % factor))
11356 			goto err;
11357 
11358 		size = (dtrace_aggregate_llquantize_bucket(factor,
11359 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11360 		break;
11361 	}
11362 
11363 	case DTRACEAGG_AVG:
11364 		agg->dtag_aggregate = dtrace_aggregate_avg;
11365 		size = sizeof (uint64_t) * 2;
11366 		break;
11367 
11368 	case DTRACEAGG_STDDEV:
11369 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11370 		size = sizeof (uint64_t) * 4;
11371 		break;
11372 
11373 	case DTRACEAGG_SUM:
11374 		agg->dtag_aggregate = dtrace_aggregate_sum;
11375 		break;
11376 
11377 	default:
11378 		goto err;
11379 	}
11380 
11381 	agg->dtag_action.dta_rec.dtrd_size = size;
11382 
11383 	if (ntuple == 0)
11384 		goto err;
11385 
11386 	/*
11387 	 * We must make sure that we have enough actions for the n-tuple.
11388 	 */
11389 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11390 		if (DTRACEACT_ISAGG(act->dta_kind))
11391 			break;
11392 
11393 		if (--ntuple == 0) {
11394 			/*
11395 			 * This is the action with which our n-tuple begins.
11396 			 */
11397 			agg->dtag_first = act;
11398 			goto success;
11399 		}
11400 	}
11401 
11402 	/*
11403 	 * This n-tuple is short by ntuple elements.  Return failure.
11404 	 */
11405 	ASSERT(ntuple != 0);
11406 err:
11407 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11408 	return (NULL);
11409 
11410 success:
11411 	/*
11412 	 * If the last action in the tuple has a size of zero, it's actually
11413 	 * an expression argument for the aggregating action.
11414 	 */
11415 	ASSERT(ecb->dte_action_last != NULL);
11416 	act = ecb->dte_action_last;
11417 
11418 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11419 		ASSERT(act->dta_difo != NULL);
11420 
11421 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11422 			agg->dtag_hasarg = 1;
11423 	}
11424 
11425 	/*
11426 	 * We need to allocate an id for this aggregation.
11427 	 */
11428 #ifdef illumos
11429 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11430 	    VM_BESTFIT | VM_SLEEP);
11431 #else
11432 	aggid = alloc_unr(state->dts_aggid_arena);
11433 #endif
11434 
11435 	if (aggid - 1 >= state->dts_naggregations) {
11436 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11437 		dtrace_aggregation_t **aggs;
11438 		int naggs = state->dts_naggregations << 1;
11439 		int onaggs = state->dts_naggregations;
11440 
11441 		ASSERT(aggid == state->dts_naggregations + 1);
11442 
11443 		if (naggs == 0) {
11444 			ASSERT(oaggs == NULL);
11445 			naggs = 1;
11446 		}
11447 
11448 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11449 
11450 		if (oaggs != NULL) {
11451 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11452 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11453 		}
11454 
11455 		state->dts_aggregations = aggs;
11456 		state->dts_naggregations = naggs;
11457 	}
11458 
11459 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11460 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11461 
11462 	frec = &agg->dtag_first->dta_rec;
11463 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11464 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11465 
11466 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11467 		ASSERT(!act->dta_intuple);
11468 		act->dta_intuple = 1;
11469 	}
11470 
11471 	return (&agg->dtag_action);
11472 }
11473 
11474 static void
11475 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11476 {
11477 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11478 	dtrace_state_t *state = ecb->dte_state;
11479 	dtrace_aggid_t aggid = agg->dtag_id;
11480 
11481 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11482 #ifdef illumos
11483 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11484 #else
11485 	free_unr(state->dts_aggid_arena, aggid);
11486 #endif
11487 
11488 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11489 	state->dts_aggregations[aggid - 1] = NULL;
11490 
11491 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11492 }
11493 
11494 static int
11495 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11496 {
11497 	dtrace_action_t *action, *last;
11498 	dtrace_difo_t *dp = desc->dtad_difo;
11499 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11500 	uint16_t format = 0;
11501 	dtrace_recdesc_t *rec;
11502 	dtrace_state_t *state = ecb->dte_state;
11503 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11504 	uint64_t arg = desc->dtad_arg;
11505 
11506 	ASSERT(MUTEX_HELD(&dtrace_lock));
11507 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11508 
11509 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11510 		/*
11511 		 * If this is an aggregating action, there must be neither
11512 		 * a speculate nor a commit on the action chain.
11513 		 */
11514 		dtrace_action_t *act;
11515 
11516 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11517 			if (act->dta_kind == DTRACEACT_COMMIT)
11518 				return (EINVAL);
11519 
11520 			if (act->dta_kind == DTRACEACT_SPECULATE)
11521 				return (EINVAL);
11522 		}
11523 
11524 		action = dtrace_ecb_aggregation_create(ecb, desc);
11525 
11526 		if (action == NULL)
11527 			return (EINVAL);
11528 	} else {
11529 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11530 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11531 		    dp != NULL && dp->dtdo_destructive)) {
11532 			state->dts_destructive = 1;
11533 		}
11534 
11535 		switch (desc->dtad_kind) {
11536 		case DTRACEACT_PRINTF:
11537 		case DTRACEACT_PRINTA:
11538 		case DTRACEACT_SYSTEM:
11539 		case DTRACEACT_FREOPEN:
11540 		case DTRACEACT_DIFEXPR:
11541 			/*
11542 			 * We know that our arg is a string -- turn it into a
11543 			 * format.
11544 			 */
11545 			if (arg == 0) {
11546 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11547 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11548 				format = 0;
11549 			} else {
11550 				ASSERT(arg != 0);
11551 #ifdef illumos
11552 				ASSERT(arg > KERNELBASE);
11553 #endif
11554 				format = dtrace_format_add(state,
11555 				    (char *)(uintptr_t)arg);
11556 			}
11557 
11558 			/*FALLTHROUGH*/
11559 		case DTRACEACT_LIBACT:
11560 		case DTRACEACT_TRACEMEM:
11561 		case DTRACEACT_TRACEMEM_DYNSIZE:
11562 			if (dp == NULL)
11563 				return (EINVAL);
11564 
11565 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11566 				break;
11567 
11568 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11569 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11570 					return (EINVAL);
11571 
11572 				size = opt[DTRACEOPT_STRSIZE];
11573 			}
11574 
11575 			break;
11576 
11577 		case DTRACEACT_STACK:
11578 			if ((nframes = arg) == 0) {
11579 				nframes = opt[DTRACEOPT_STACKFRAMES];
11580 				ASSERT(nframes > 0);
11581 				arg = nframes;
11582 			}
11583 
11584 			size = nframes * sizeof (pc_t);
11585 			break;
11586 
11587 		case DTRACEACT_JSTACK:
11588 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11589 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11590 
11591 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11592 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11593 
11594 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11595 
11596 			/*FALLTHROUGH*/
11597 		case DTRACEACT_USTACK:
11598 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11599 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11600 				strsize = DTRACE_USTACK_STRSIZE(arg);
11601 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11602 				ASSERT(nframes > 0);
11603 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11604 			}
11605 
11606 			/*
11607 			 * Save a slot for the pid.
11608 			 */
11609 			size = (nframes + 1) * sizeof (uint64_t);
11610 			size += DTRACE_USTACK_STRSIZE(arg);
11611 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11612 
11613 			break;
11614 
11615 		case DTRACEACT_SYM:
11616 		case DTRACEACT_MOD:
11617 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11618 			    sizeof (uint64_t)) ||
11619 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11620 				return (EINVAL);
11621 			break;
11622 
11623 		case DTRACEACT_USYM:
11624 		case DTRACEACT_UMOD:
11625 		case DTRACEACT_UADDR:
11626 			if (dp == NULL ||
11627 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11628 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11629 				return (EINVAL);
11630 
11631 			/*
11632 			 * We have a slot for the pid, plus a slot for the
11633 			 * argument.  To keep things simple (aligned with
11634 			 * bitness-neutral sizing), we store each as a 64-bit
11635 			 * quantity.
11636 			 */
11637 			size = 2 * sizeof (uint64_t);
11638 			break;
11639 
11640 		case DTRACEACT_STOP:
11641 		case DTRACEACT_BREAKPOINT:
11642 		case DTRACEACT_PANIC:
11643 			break;
11644 
11645 		case DTRACEACT_CHILL:
11646 		case DTRACEACT_DISCARD:
11647 		case DTRACEACT_RAISE:
11648 			if (dp == NULL)
11649 				return (EINVAL);
11650 			break;
11651 
11652 		case DTRACEACT_EXIT:
11653 			if (dp == NULL ||
11654 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11655 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11656 				return (EINVAL);
11657 			break;
11658 
11659 		case DTRACEACT_SPECULATE:
11660 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11661 				return (EINVAL);
11662 
11663 			if (dp == NULL)
11664 				return (EINVAL);
11665 
11666 			state->dts_speculates = 1;
11667 			break;
11668 
11669 		case DTRACEACT_PRINTM:
11670 		    	size = dp->dtdo_rtype.dtdt_size;
11671 			break;
11672 
11673 		case DTRACEACT_COMMIT: {
11674 			dtrace_action_t *act = ecb->dte_action;
11675 
11676 			for (; act != NULL; act = act->dta_next) {
11677 				if (act->dta_kind == DTRACEACT_COMMIT)
11678 					return (EINVAL);
11679 			}
11680 
11681 			if (dp == NULL)
11682 				return (EINVAL);
11683 			break;
11684 		}
11685 
11686 		default:
11687 			return (EINVAL);
11688 		}
11689 
11690 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11691 			/*
11692 			 * If this is a data-storing action or a speculate,
11693 			 * we must be sure that there isn't a commit on the
11694 			 * action chain.
11695 			 */
11696 			dtrace_action_t *act = ecb->dte_action;
11697 
11698 			for (; act != NULL; act = act->dta_next) {
11699 				if (act->dta_kind == DTRACEACT_COMMIT)
11700 					return (EINVAL);
11701 			}
11702 		}
11703 
11704 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11705 		action->dta_rec.dtrd_size = size;
11706 	}
11707 
11708 	action->dta_refcnt = 1;
11709 	rec = &action->dta_rec;
11710 	size = rec->dtrd_size;
11711 
11712 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11713 		if (!(size & mask)) {
11714 			align = mask + 1;
11715 			break;
11716 		}
11717 	}
11718 
11719 	action->dta_kind = desc->dtad_kind;
11720 
11721 	if ((action->dta_difo = dp) != NULL)
11722 		dtrace_difo_hold(dp);
11723 
11724 	rec->dtrd_action = action->dta_kind;
11725 	rec->dtrd_arg = arg;
11726 	rec->dtrd_uarg = desc->dtad_uarg;
11727 	rec->dtrd_alignment = (uint16_t)align;
11728 	rec->dtrd_format = format;
11729 
11730 	if ((last = ecb->dte_action_last) != NULL) {
11731 		ASSERT(ecb->dte_action != NULL);
11732 		action->dta_prev = last;
11733 		last->dta_next = action;
11734 	} else {
11735 		ASSERT(ecb->dte_action == NULL);
11736 		ecb->dte_action = action;
11737 	}
11738 
11739 	ecb->dte_action_last = action;
11740 
11741 	return (0);
11742 }
11743 
11744 static void
11745 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11746 {
11747 	dtrace_action_t *act = ecb->dte_action, *next;
11748 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11749 	dtrace_difo_t *dp;
11750 	uint16_t format;
11751 
11752 	if (act != NULL && act->dta_refcnt > 1) {
11753 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11754 		act->dta_refcnt--;
11755 	} else {
11756 		for (; act != NULL; act = next) {
11757 			next = act->dta_next;
11758 			ASSERT(next != NULL || act == ecb->dte_action_last);
11759 			ASSERT(act->dta_refcnt == 1);
11760 
11761 			if ((format = act->dta_rec.dtrd_format) != 0)
11762 				dtrace_format_remove(ecb->dte_state, format);
11763 
11764 			if ((dp = act->dta_difo) != NULL)
11765 				dtrace_difo_release(dp, vstate);
11766 
11767 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11768 				dtrace_ecb_aggregation_destroy(ecb, act);
11769 			} else {
11770 				kmem_free(act, sizeof (dtrace_action_t));
11771 			}
11772 		}
11773 	}
11774 
11775 	ecb->dte_action = NULL;
11776 	ecb->dte_action_last = NULL;
11777 	ecb->dte_size = 0;
11778 }
11779 
11780 static void
11781 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11782 {
11783 	/*
11784 	 * We disable the ECB by removing it from its probe.
11785 	 */
11786 	dtrace_ecb_t *pecb, *prev = NULL;
11787 	dtrace_probe_t *probe = ecb->dte_probe;
11788 
11789 	ASSERT(MUTEX_HELD(&dtrace_lock));
11790 
11791 	if (probe == NULL) {
11792 		/*
11793 		 * This is the NULL probe; there is nothing to disable.
11794 		 */
11795 		return;
11796 	}
11797 
11798 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11799 		if (pecb == ecb)
11800 			break;
11801 		prev = pecb;
11802 	}
11803 
11804 	ASSERT(pecb != NULL);
11805 
11806 	if (prev == NULL) {
11807 		probe->dtpr_ecb = ecb->dte_next;
11808 	} else {
11809 		prev->dte_next = ecb->dte_next;
11810 	}
11811 
11812 	if (ecb == probe->dtpr_ecb_last) {
11813 		ASSERT(ecb->dte_next == NULL);
11814 		probe->dtpr_ecb_last = prev;
11815 	}
11816 
11817 	/*
11818 	 * The ECB has been disconnected from the probe; now sync to assure
11819 	 * that all CPUs have seen the change before returning.
11820 	 */
11821 	dtrace_sync();
11822 
11823 	if (probe->dtpr_ecb == NULL) {
11824 		/*
11825 		 * That was the last ECB on the probe; clear the predicate
11826 		 * cache ID for the probe, disable it and sync one more time
11827 		 * to assure that we'll never hit it again.
11828 		 */
11829 		dtrace_provider_t *prov = probe->dtpr_provider;
11830 
11831 		ASSERT(ecb->dte_next == NULL);
11832 		ASSERT(probe->dtpr_ecb_last == NULL);
11833 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11834 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11835 		    probe->dtpr_id, probe->dtpr_arg);
11836 		dtrace_sync();
11837 	} else {
11838 		/*
11839 		 * There is at least one ECB remaining on the probe.  If there
11840 		 * is _exactly_ one, set the probe's predicate cache ID to be
11841 		 * the predicate cache ID of the remaining ECB.
11842 		 */
11843 		ASSERT(probe->dtpr_ecb_last != NULL);
11844 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11845 
11846 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11847 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11848 
11849 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11850 
11851 			if (p != NULL)
11852 				probe->dtpr_predcache = p->dtp_cacheid;
11853 		}
11854 
11855 		ecb->dte_next = NULL;
11856 	}
11857 }
11858 
11859 static void
11860 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11861 {
11862 	dtrace_state_t *state = ecb->dte_state;
11863 	dtrace_vstate_t *vstate = &state->dts_vstate;
11864 	dtrace_predicate_t *pred;
11865 	dtrace_epid_t epid = ecb->dte_epid;
11866 
11867 	ASSERT(MUTEX_HELD(&dtrace_lock));
11868 	ASSERT(ecb->dte_next == NULL);
11869 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11870 
11871 	if ((pred = ecb->dte_predicate) != NULL)
11872 		dtrace_predicate_release(pred, vstate);
11873 
11874 	dtrace_ecb_action_remove(ecb);
11875 
11876 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11877 	state->dts_ecbs[epid - 1] = NULL;
11878 
11879 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11880 }
11881 
11882 static dtrace_ecb_t *
11883 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11884     dtrace_enabling_t *enab)
11885 {
11886 	dtrace_ecb_t *ecb;
11887 	dtrace_predicate_t *pred;
11888 	dtrace_actdesc_t *act;
11889 	dtrace_provider_t *prov;
11890 	dtrace_ecbdesc_t *desc = enab->dten_current;
11891 
11892 	ASSERT(MUTEX_HELD(&dtrace_lock));
11893 	ASSERT(state != NULL);
11894 
11895 	ecb = dtrace_ecb_add(state, probe);
11896 	ecb->dte_uarg = desc->dted_uarg;
11897 
11898 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11899 		dtrace_predicate_hold(pred);
11900 		ecb->dte_predicate = pred;
11901 	}
11902 
11903 	if (probe != NULL) {
11904 		/*
11905 		 * If the provider shows more leg than the consumer is old
11906 		 * enough to see, we need to enable the appropriate implicit
11907 		 * predicate bits to prevent the ecb from activating at
11908 		 * revealing times.
11909 		 *
11910 		 * Providers specifying DTRACE_PRIV_USER at register time
11911 		 * are stating that they need the /proc-style privilege
11912 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11913 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11914 		 */
11915 		prov = probe->dtpr_provider;
11916 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11917 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11918 			ecb->dte_cond |= DTRACE_COND_OWNER;
11919 
11920 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11921 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11922 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11923 
11924 		/*
11925 		 * If the provider shows us kernel innards and the user
11926 		 * is lacking sufficient privilege, enable the
11927 		 * DTRACE_COND_USERMODE implicit predicate.
11928 		 */
11929 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11930 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11931 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11932 	}
11933 
11934 	if (dtrace_ecb_create_cache != NULL) {
11935 		/*
11936 		 * If we have a cached ecb, we'll use its action list instead
11937 		 * of creating our own (saving both time and space).
11938 		 */
11939 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11940 		dtrace_action_t *act = cached->dte_action;
11941 
11942 		if (act != NULL) {
11943 			ASSERT(act->dta_refcnt > 0);
11944 			act->dta_refcnt++;
11945 			ecb->dte_action = act;
11946 			ecb->dte_action_last = cached->dte_action_last;
11947 			ecb->dte_needed = cached->dte_needed;
11948 			ecb->dte_size = cached->dte_size;
11949 			ecb->dte_alignment = cached->dte_alignment;
11950 		}
11951 
11952 		return (ecb);
11953 	}
11954 
11955 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11956 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11957 			dtrace_ecb_destroy(ecb);
11958 			return (NULL);
11959 		}
11960 	}
11961 
11962 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11963 		dtrace_ecb_destroy(ecb);
11964 		return (NULL);
11965 	}
11966 
11967 	return (dtrace_ecb_create_cache = ecb);
11968 }
11969 
11970 static int
11971 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11972 {
11973 	dtrace_ecb_t *ecb;
11974 	dtrace_enabling_t *enab = arg;
11975 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11976 
11977 	ASSERT(state != NULL);
11978 
11979 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11980 		/*
11981 		 * This probe was created in a generation for which this
11982 		 * enabling has previously created ECBs; we don't want to
11983 		 * enable it again, so just kick out.
11984 		 */
11985 		return (DTRACE_MATCH_NEXT);
11986 	}
11987 
11988 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11989 		return (DTRACE_MATCH_DONE);
11990 
11991 	dtrace_ecb_enable(ecb);
11992 	return (DTRACE_MATCH_NEXT);
11993 }
11994 
11995 static dtrace_ecb_t *
11996 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11997 {
11998 	dtrace_ecb_t *ecb;
11999 
12000 	ASSERT(MUTEX_HELD(&dtrace_lock));
12001 
12002 	if (id == 0 || id > state->dts_necbs)
12003 		return (NULL);
12004 
12005 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12006 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12007 
12008 	return (state->dts_ecbs[id - 1]);
12009 }
12010 
12011 static dtrace_aggregation_t *
12012 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12013 {
12014 	dtrace_aggregation_t *agg;
12015 
12016 	ASSERT(MUTEX_HELD(&dtrace_lock));
12017 
12018 	if (id == 0 || id > state->dts_naggregations)
12019 		return (NULL);
12020 
12021 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12022 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12023 	    agg->dtag_id == id);
12024 
12025 	return (state->dts_aggregations[id - 1]);
12026 }
12027 
12028 /*
12029  * DTrace Buffer Functions
12030  *
12031  * The following functions manipulate DTrace buffers.  Most of these functions
12032  * are called in the context of establishing or processing consumer state;
12033  * exceptions are explicitly noted.
12034  */
12035 
12036 /*
12037  * Note:  called from cross call context.  This function switches the two
12038  * buffers on a given CPU.  The atomicity of this operation is assured by
12039  * disabling interrupts while the actual switch takes place; the disabling of
12040  * interrupts serializes the execution with any execution of dtrace_probe() on
12041  * the same CPU.
12042  */
12043 static void
12044 dtrace_buffer_switch(dtrace_buffer_t *buf)
12045 {
12046 	caddr_t tomax = buf->dtb_tomax;
12047 	caddr_t xamot = buf->dtb_xamot;
12048 	dtrace_icookie_t cookie;
12049 	hrtime_t now;
12050 
12051 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12052 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12053 
12054 	cookie = dtrace_interrupt_disable();
12055 	now = dtrace_gethrtime();
12056 	buf->dtb_tomax = xamot;
12057 	buf->dtb_xamot = tomax;
12058 	buf->dtb_xamot_drops = buf->dtb_drops;
12059 	buf->dtb_xamot_offset = buf->dtb_offset;
12060 	buf->dtb_xamot_errors = buf->dtb_errors;
12061 	buf->dtb_xamot_flags = buf->dtb_flags;
12062 	buf->dtb_offset = 0;
12063 	buf->dtb_drops = 0;
12064 	buf->dtb_errors = 0;
12065 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12066 	buf->dtb_interval = now - buf->dtb_switched;
12067 	buf->dtb_switched = now;
12068 	dtrace_interrupt_enable(cookie);
12069 }
12070 
12071 /*
12072  * Note:  called from cross call context.  This function activates a buffer
12073  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12074  * is guaranteed by the disabling of interrupts.
12075  */
12076 static void
12077 dtrace_buffer_activate(dtrace_state_t *state)
12078 {
12079 	dtrace_buffer_t *buf;
12080 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12081 
12082 	buf = &state->dts_buffer[curcpu];
12083 
12084 	if (buf->dtb_tomax != NULL) {
12085 		/*
12086 		 * We might like to assert that the buffer is marked inactive,
12087 		 * but this isn't necessarily true:  the buffer for the CPU
12088 		 * that processes the BEGIN probe has its buffer activated
12089 		 * manually.  In this case, we take the (harmless) action
12090 		 * re-clearing the bit INACTIVE bit.
12091 		 */
12092 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12093 	}
12094 
12095 	dtrace_interrupt_enable(cookie);
12096 }
12097 
12098 #ifdef __FreeBSD__
12099 /*
12100  * Activate the specified per-CPU buffer.  This is used instead of
12101  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12102  * activating anonymous state.
12103  */
12104 static void
12105 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12106 {
12107 
12108 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12109 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12110 }
12111 #endif
12112 
12113 static int
12114 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12115     processorid_t cpu, int *factor)
12116 {
12117 #ifdef illumos
12118 	cpu_t *cp;
12119 #endif
12120 	dtrace_buffer_t *buf;
12121 	int allocated = 0, desired = 0;
12122 
12123 #ifdef illumos
12124 	ASSERT(MUTEX_HELD(&cpu_lock));
12125 	ASSERT(MUTEX_HELD(&dtrace_lock));
12126 
12127 	*factor = 1;
12128 
12129 	if (size > dtrace_nonroot_maxsize &&
12130 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12131 		return (EFBIG);
12132 
12133 	cp = cpu_list;
12134 
12135 	do {
12136 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12137 			continue;
12138 
12139 		buf = &bufs[cp->cpu_id];
12140 
12141 		/*
12142 		 * If there is already a buffer allocated for this CPU, it
12143 		 * is only possible that this is a DR event.  In this case,
12144 		 */
12145 		if (buf->dtb_tomax != NULL) {
12146 			ASSERT(buf->dtb_size == size);
12147 			continue;
12148 		}
12149 
12150 		ASSERT(buf->dtb_xamot == NULL);
12151 
12152 		if ((buf->dtb_tomax = kmem_zalloc(size,
12153 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12154 			goto err;
12155 
12156 		buf->dtb_size = size;
12157 		buf->dtb_flags = flags;
12158 		buf->dtb_offset = 0;
12159 		buf->dtb_drops = 0;
12160 
12161 		if (flags & DTRACEBUF_NOSWITCH)
12162 			continue;
12163 
12164 		if ((buf->dtb_xamot = kmem_zalloc(size,
12165 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12166 			goto err;
12167 	} while ((cp = cp->cpu_next) != cpu_list);
12168 
12169 	return (0);
12170 
12171 err:
12172 	cp = cpu_list;
12173 
12174 	do {
12175 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12176 			continue;
12177 
12178 		buf = &bufs[cp->cpu_id];
12179 		desired += 2;
12180 
12181 		if (buf->dtb_xamot != NULL) {
12182 			ASSERT(buf->dtb_tomax != NULL);
12183 			ASSERT(buf->dtb_size == size);
12184 			kmem_free(buf->dtb_xamot, size);
12185 			allocated++;
12186 		}
12187 
12188 		if (buf->dtb_tomax != NULL) {
12189 			ASSERT(buf->dtb_size == size);
12190 			kmem_free(buf->dtb_tomax, size);
12191 			allocated++;
12192 		}
12193 
12194 		buf->dtb_tomax = NULL;
12195 		buf->dtb_xamot = NULL;
12196 		buf->dtb_size = 0;
12197 	} while ((cp = cp->cpu_next) != cpu_list);
12198 #else
12199 	int i;
12200 
12201 	*factor = 1;
12202 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12203     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12204 	/*
12205 	 * FreeBSD isn't good at limiting the amount of memory we
12206 	 * ask to malloc, so let's place a limit here before trying
12207 	 * to do something that might well end in tears at bedtime.
12208 	 */
12209 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12210 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12211 		return (ENOMEM);
12212 #endif
12213 
12214 	ASSERT(MUTEX_HELD(&dtrace_lock));
12215 	CPU_FOREACH(i) {
12216 		if (cpu != DTRACE_CPUALL && cpu != i)
12217 			continue;
12218 
12219 		buf = &bufs[i];
12220 
12221 		/*
12222 		 * If there is already a buffer allocated for this CPU, it
12223 		 * is only possible that this is a DR event.  In this case,
12224 		 * the buffer size must match our specified size.
12225 		 */
12226 		if (buf->dtb_tomax != NULL) {
12227 			ASSERT(buf->dtb_size == size);
12228 			continue;
12229 		}
12230 
12231 		ASSERT(buf->dtb_xamot == NULL);
12232 
12233 		if ((buf->dtb_tomax = kmem_zalloc(size,
12234 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12235 			goto err;
12236 
12237 		buf->dtb_size = size;
12238 		buf->dtb_flags = flags;
12239 		buf->dtb_offset = 0;
12240 		buf->dtb_drops = 0;
12241 
12242 		if (flags & DTRACEBUF_NOSWITCH)
12243 			continue;
12244 
12245 		if ((buf->dtb_xamot = kmem_zalloc(size,
12246 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12247 			goto err;
12248 	}
12249 
12250 	return (0);
12251 
12252 err:
12253 	/*
12254 	 * Error allocating memory, so free the buffers that were
12255 	 * allocated before the failed allocation.
12256 	 */
12257 	CPU_FOREACH(i) {
12258 		if (cpu != DTRACE_CPUALL && cpu != i)
12259 			continue;
12260 
12261 		buf = &bufs[i];
12262 		desired += 2;
12263 
12264 		if (buf->dtb_xamot != NULL) {
12265 			ASSERT(buf->dtb_tomax != NULL);
12266 			ASSERT(buf->dtb_size == size);
12267 			kmem_free(buf->dtb_xamot, size);
12268 			allocated++;
12269 		}
12270 
12271 		if (buf->dtb_tomax != NULL) {
12272 			ASSERT(buf->dtb_size == size);
12273 			kmem_free(buf->dtb_tomax, size);
12274 			allocated++;
12275 		}
12276 
12277 		buf->dtb_tomax = NULL;
12278 		buf->dtb_xamot = NULL;
12279 		buf->dtb_size = 0;
12280 
12281 	}
12282 #endif
12283 	*factor = desired / (allocated > 0 ? allocated : 1);
12284 
12285 	return (ENOMEM);
12286 }
12287 
12288 /*
12289  * Note:  called from probe context.  This function just increments the drop
12290  * count on a buffer.  It has been made a function to allow for the
12291  * possibility of understanding the source of mysterious drop counts.  (A
12292  * problem for which one may be particularly disappointed that DTrace cannot
12293  * be used to understand DTrace.)
12294  */
12295 static void
12296 dtrace_buffer_drop(dtrace_buffer_t *buf)
12297 {
12298 	buf->dtb_drops++;
12299 }
12300 
12301 /*
12302  * Note:  called from probe context.  This function is called to reserve space
12303  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12304  * mstate.  Returns the new offset in the buffer, or a negative value if an
12305  * error has occurred.
12306  */
12307 static intptr_t
12308 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12309     dtrace_state_t *state, dtrace_mstate_t *mstate)
12310 {
12311 	intptr_t offs = buf->dtb_offset, soffs;
12312 	intptr_t woffs;
12313 	caddr_t tomax;
12314 	size_t total;
12315 
12316 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12317 		return (-1);
12318 
12319 	if ((tomax = buf->dtb_tomax) == NULL) {
12320 		dtrace_buffer_drop(buf);
12321 		return (-1);
12322 	}
12323 
12324 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12325 		while (offs & (align - 1)) {
12326 			/*
12327 			 * Assert that our alignment is off by a number which
12328 			 * is itself sizeof (uint32_t) aligned.
12329 			 */
12330 			ASSERT(!((align - (offs & (align - 1))) &
12331 			    (sizeof (uint32_t) - 1)));
12332 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12333 			offs += sizeof (uint32_t);
12334 		}
12335 
12336 		if ((soffs = offs + needed) > buf->dtb_size) {
12337 			dtrace_buffer_drop(buf);
12338 			return (-1);
12339 		}
12340 
12341 		if (mstate == NULL)
12342 			return (offs);
12343 
12344 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12345 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12346 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12347 
12348 		return (offs);
12349 	}
12350 
12351 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12352 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12353 		    (buf->dtb_flags & DTRACEBUF_FULL))
12354 			return (-1);
12355 		goto out;
12356 	}
12357 
12358 	total = needed + (offs & (align - 1));
12359 
12360 	/*
12361 	 * For a ring buffer, life is quite a bit more complicated.  Before
12362 	 * we can store any padding, we need to adjust our wrapping offset.
12363 	 * (If we've never before wrapped or we're not about to, no adjustment
12364 	 * is required.)
12365 	 */
12366 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12367 	    offs + total > buf->dtb_size) {
12368 		woffs = buf->dtb_xamot_offset;
12369 
12370 		if (offs + total > buf->dtb_size) {
12371 			/*
12372 			 * We can't fit in the end of the buffer.  First, a
12373 			 * sanity check that we can fit in the buffer at all.
12374 			 */
12375 			if (total > buf->dtb_size) {
12376 				dtrace_buffer_drop(buf);
12377 				return (-1);
12378 			}
12379 
12380 			/*
12381 			 * We're going to be storing at the top of the buffer,
12382 			 * so now we need to deal with the wrapped offset.  We
12383 			 * only reset our wrapped offset to 0 if it is
12384 			 * currently greater than the current offset.  If it
12385 			 * is less than the current offset, it is because a
12386 			 * previous allocation induced a wrap -- but the
12387 			 * allocation didn't subsequently take the space due
12388 			 * to an error or false predicate evaluation.  In this
12389 			 * case, we'll just leave the wrapped offset alone: if
12390 			 * the wrapped offset hasn't been advanced far enough
12391 			 * for this allocation, it will be adjusted in the
12392 			 * lower loop.
12393 			 */
12394 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12395 				if (woffs >= offs)
12396 					woffs = 0;
12397 			} else {
12398 				woffs = 0;
12399 			}
12400 
12401 			/*
12402 			 * Now we know that we're going to be storing to the
12403 			 * top of the buffer and that there is room for us
12404 			 * there.  We need to clear the buffer from the current
12405 			 * offset to the end (there may be old gunk there).
12406 			 */
12407 			while (offs < buf->dtb_size)
12408 				tomax[offs++] = 0;
12409 
12410 			/*
12411 			 * We need to set our offset to zero.  And because we
12412 			 * are wrapping, we need to set the bit indicating as
12413 			 * much.  We can also adjust our needed space back
12414 			 * down to the space required by the ECB -- we know
12415 			 * that the top of the buffer is aligned.
12416 			 */
12417 			offs = 0;
12418 			total = needed;
12419 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12420 		} else {
12421 			/*
12422 			 * There is room for us in the buffer, so we simply
12423 			 * need to check the wrapped offset.
12424 			 */
12425 			if (woffs < offs) {
12426 				/*
12427 				 * The wrapped offset is less than the offset.
12428 				 * This can happen if we allocated buffer space
12429 				 * that induced a wrap, but then we didn't
12430 				 * subsequently take the space due to an error
12431 				 * or false predicate evaluation.  This is
12432 				 * okay; we know that _this_ allocation isn't
12433 				 * going to induce a wrap.  We still can't
12434 				 * reset the wrapped offset to be zero,
12435 				 * however: the space may have been trashed in
12436 				 * the previous failed probe attempt.  But at
12437 				 * least the wrapped offset doesn't need to
12438 				 * be adjusted at all...
12439 				 */
12440 				goto out;
12441 			}
12442 		}
12443 
12444 		while (offs + total > woffs) {
12445 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12446 			size_t size;
12447 
12448 			if (epid == DTRACE_EPIDNONE) {
12449 				size = sizeof (uint32_t);
12450 			} else {
12451 				ASSERT3U(epid, <=, state->dts_necbs);
12452 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12453 
12454 				size = state->dts_ecbs[epid - 1]->dte_size;
12455 			}
12456 
12457 			ASSERT(woffs + size <= buf->dtb_size);
12458 			ASSERT(size != 0);
12459 
12460 			if (woffs + size == buf->dtb_size) {
12461 				/*
12462 				 * We've reached the end of the buffer; we want
12463 				 * to set the wrapped offset to 0 and break
12464 				 * out.  However, if the offs is 0, then we're
12465 				 * in a strange edge-condition:  the amount of
12466 				 * space that we want to reserve plus the size
12467 				 * of the record that we're overwriting is
12468 				 * greater than the size of the buffer.  This
12469 				 * is problematic because if we reserve the
12470 				 * space but subsequently don't consume it (due
12471 				 * to a failed predicate or error) the wrapped
12472 				 * offset will be 0 -- yet the EPID at offset 0
12473 				 * will not be committed.  This situation is
12474 				 * relatively easy to deal with:  if we're in
12475 				 * this case, the buffer is indistinguishable
12476 				 * from one that hasn't wrapped; we need only
12477 				 * finish the job by clearing the wrapped bit,
12478 				 * explicitly setting the offset to be 0, and
12479 				 * zero'ing out the old data in the buffer.
12480 				 */
12481 				if (offs == 0) {
12482 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12483 					buf->dtb_offset = 0;
12484 					woffs = total;
12485 
12486 					while (woffs < buf->dtb_size)
12487 						tomax[woffs++] = 0;
12488 				}
12489 
12490 				woffs = 0;
12491 				break;
12492 			}
12493 
12494 			woffs += size;
12495 		}
12496 
12497 		/*
12498 		 * We have a wrapped offset.  It may be that the wrapped offset
12499 		 * has become zero -- that's okay.
12500 		 */
12501 		buf->dtb_xamot_offset = woffs;
12502 	}
12503 
12504 out:
12505 	/*
12506 	 * Now we can plow the buffer with any necessary padding.
12507 	 */
12508 	while (offs & (align - 1)) {
12509 		/*
12510 		 * Assert that our alignment is off by a number which
12511 		 * is itself sizeof (uint32_t) aligned.
12512 		 */
12513 		ASSERT(!((align - (offs & (align - 1))) &
12514 		    (sizeof (uint32_t) - 1)));
12515 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12516 		offs += sizeof (uint32_t);
12517 	}
12518 
12519 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12520 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12521 			buf->dtb_flags |= DTRACEBUF_FULL;
12522 			return (-1);
12523 		}
12524 	}
12525 
12526 	if (mstate == NULL)
12527 		return (offs);
12528 
12529 	/*
12530 	 * For ring buffers and fill buffers, the scratch space is always
12531 	 * the inactive buffer.
12532 	 */
12533 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12534 	mstate->dtms_scratch_size = buf->dtb_size;
12535 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12536 
12537 	return (offs);
12538 }
12539 
12540 static void
12541 dtrace_buffer_polish(dtrace_buffer_t *buf)
12542 {
12543 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12544 	ASSERT(MUTEX_HELD(&dtrace_lock));
12545 
12546 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12547 		return;
12548 
12549 	/*
12550 	 * We need to polish the ring buffer.  There are three cases:
12551 	 *
12552 	 * - The first (and presumably most common) is that there is no gap
12553 	 *   between the buffer offset and the wrapped offset.  In this case,
12554 	 *   there is nothing in the buffer that isn't valid data; we can
12555 	 *   mark the buffer as polished and return.
12556 	 *
12557 	 * - The second (less common than the first but still more common
12558 	 *   than the third) is that there is a gap between the buffer offset
12559 	 *   and the wrapped offset, and the wrapped offset is larger than the
12560 	 *   buffer offset.  This can happen because of an alignment issue, or
12561 	 *   can happen because of a call to dtrace_buffer_reserve() that
12562 	 *   didn't subsequently consume the buffer space.  In this case,
12563 	 *   we need to zero the data from the buffer offset to the wrapped
12564 	 *   offset.
12565 	 *
12566 	 * - The third (and least common) is that there is a gap between the
12567 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12568 	 *   _less_ than the buffer offset.  This can only happen because a
12569 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12570 	 *   was not subsequently consumed.  In this case, we need to zero the
12571 	 *   space from the offset to the end of the buffer _and_ from the
12572 	 *   top of the buffer to the wrapped offset.
12573 	 */
12574 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12575 		bzero(buf->dtb_tomax + buf->dtb_offset,
12576 		    buf->dtb_xamot_offset - buf->dtb_offset);
12577 	}
12578 
12579 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12580 		bzero(buf->dtb_tomax + buf->dtb_offset,
12581 		    buf->dtb_size - buf->dtb_offset);
12582 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12583 	}
12584 }
12585 
12586 /*
12587  * This routine determines if data generated at the specified time has likely
12588  * been entirely consumed at user-level.  This routine is called to determine
12589  * if an ECB on a defunct probe (but for an active enabling) can be safely
12590  * disabled and destroyed.
12591  */
12592 static int
12593 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12594 {
12595 	int i;
12596 
12597 	for (i = 0; i < NCPU; i++) {
12598 		dtrace_buffer_t *buf = &bufs[i];
12599 
12600 		if (buf->dtb_size == 0)
12601 			continue;
12602 
12603 		if (buf->dtb_flags & DTRACEBUF_RING)
12604 			return (0);
12605 
12606 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12607 			return (0);
12608 
12609 		if (buf->dtb_switched - buf->dtb_interval < when)
12610 			return (0);
12611 	}
12612 
12613 	return (1);
12614 }
12615 
12616 static void
12617 dtrace_buffer_free(dtrace_buffer_t *bufs)
12618 {
12619 	int i;
12620 
12621 	for (i = 0; i < NCPU; i++) {
12622 		dtrace_buffer_t *buf = &bufs[i];
12623 
12624 		if (buf->dtb_tomax == NULL) {
12625 			ASSERT(buf->dtb_xamot == NULL);
12626 			ASSERT(buf->dtb_size == 0);
12627 			continue;
12628 		}
12629 
12630 		if (buf->dtb_xamot != NULL) {
12631 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12632 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12633 		}
12634 
12635 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12636 		buf->dtb_size = 0;
12637 		buf->dtb_tomax = NULL;
12638 		buf->dtb_xamot = NULL;
12639 	}
12640 }
12641 
12642 /*
12643  * DTrace Enabling Functions
12644  */
12645 static dtrace_enabling_t *
12646 dtrace_enabling_create(dtrace_vstate_t *vstate)
12647 {
12648 	dtrace_enabling_t *enab;
12649 
12650 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12651 	enab->dten_vstate = vstate;
12652 
12653 	return (enab);
12654 }
12655 
12656 static void
12657 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12658 {
12659 	dtrace_ecbdesc_t **ndesc;
12660 	size_t osize, nsize;
12661 
12662 	/*
12663 	 * We can't add to enablings after we've enabled them, or after we've
12664 	 * retained them.
12665 	 */
12666 	ASSERT(enab->dten_probegen == 0);
12667 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12668 
12669 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12670 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12671 		return;
12672 	}
12673 
12674 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12675 
12676 	if (enab->dten_maxdesc == 0) {
12677 		enab->dten_maxdesc = 1;
12678 	} else {
12679 		enab->dten_maxdesc <<= 1;
12680 	}
12681 
12682 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12683 
12684 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12685 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12686 	bcopy(enab->dten_desc, ndesc, osize);
12687 	if (enab->dten_desc != NULL)
12688 		kmem_free(enab->dten_desc, osize);
12689 
12690 	enab->dten_desc = ndesc;
12691 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12692 }
12693 
12694 static void
12695 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12696     dtrace_probedesc_t *pd)
12697 {
12698 	dtrace_ecbdesc_t *new;
12699 	dtrace_predicate_t *pred;
12700 	dtrace_actdesc_t *act;
12701 
12702 	/*
12703 	 * We're going to create a new ECB description that matches the
12704 	 * specified ECB in every way, but has the specified probe description.
12705 	 */
12706 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12707 
12708 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12709 		dtrace_predicate_hold(pred);
12710 
12711 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12712 		dtrace_actdesc_hold(act);
12713 
12714 	new->dted_action = ecb->dted_action;
12715 	new->dted_pred = ecb->dted_pred;
12716 	new->dted_probe = *pd;
12717 	new->dted_uarg = ecb->dted_uarg;
12718 
12719 	dtrace_enabling_add(enab, new);
12720 }
12721 
12722 static void
12723 dtrace_enabling_dump(dtrace_enabling_t *enab)
12724 {
12725 	int i;
12726 
12727 	for (i = 0; i < enab->dten_ndesc; i++) {
12728 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12729 
12730 #ifdef __FreeBSD__
12731 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12732 		    desc->dtpd_provider, desc->dtpd_mod,
12733 		    desc->dtpd_func, desc->dtpd_name);
12734 #else
12735 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12736 		    desc->dtpd_provider, desc->dtpd_mod,
12737 		    desc->dtpd_func, desc->dtpd_name);
12738 #endif
12739 	}
12740 }
12741 
12742 static void
12743 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12744 {
12745 	int i;
12746 	dtrace_ecbdesc_t *ep;
12747 	dtrace_vstate_t *vstate = enab->dten_vstate;
12748 
12749 	ASSERT(MUTEX_HELD(&dtrace_lock));
12750 
12751 	for (i = 0; i < enab->dten_ndesc; i++) {
12752 		dtrace_actdesc_t *act, *next;
12753 		dtrace_predicate_t *pred;
12754 
12755 		ep = enab->dten_desc[i];
12756 
12757 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12758 			dtrace_predicate_release(pred, vstate);
12759 
12760 		for (act = ep->dted_action; act != NULL; act = next) {
12761 			next = act->dtad_next;
12762 			dtrace_actdesc_release(act, vstate);
12763 		}
12764 
12765 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12766 	}
12767 
12768 	if (enab->dten_desc != NULL)
12769 		kmem_free(enab->dten_desc,
12770 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12771 
12772 	/*
12773 	 * If this was a retained enabling, decrement the dts_nretained count
12774 	 * and take it off of the dtrace_retained list.
12775 	 */
12776 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12777 	    dtrace_retained == enab) {
12778 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12779 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12780 		enab->dten_vstate->dtvs_state->dts_nretained--;
12781 		dtrace_retained_gen++;
12782 	}
12783 
12784 	if (enab->dten_prev == NULL) {
12785 		if (dtrace_retained == enab) {
12786 			dtrace_retained = enab->dten_next;
12787 
12788 			if (dtrace_retained != NULL)
12789 				dtrace_retained->dten_prev = NULL;
12790 		}
12791 	} else {
12792 		ASSERT(enab != dtrace_retained);
12793 		ASSERT(dtrace_retained != NULL);
12794 		enab->dten_prev->dten_next = enab->dten_next;
12795 	}
12796 
12797 	if (enab->dten_next != NULL) {
12798 		ASSERT(dtrace_retained != NULL);
12799 		enab->dten_next->dten_prev = enab->dten_prev;
12800 	}
12801 
12802 	kmem_free(enab, sizeof (dtrace_enabling_t));
12803 }
12804 
12805 static int
12806 dtrace_enabling_retain(dtrace_enabling_t *enab)
12807 {
12808 	dtrace_state_t *state;
12809 
12810 	ASSERT(MUTEX_HELD(&dtrace_lock));
12811 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12812 	ASSERT(enab->dten_vstate != NULL);
12813 
12814 	state = enab->dten_vstate->dtvs_state;
12815 	ASSERT(state != NULL);
12816 
12817 	/*
12818 	 * We only allow each state to retain dtrace_retain_max enablings.
12819 	 */
12820 	if (state->dts_nretained >= dtrace_retain_max)
12821 		return (ENOSPC);
12822 
12823 	state->dts_nretained++;
12824 	dtrace_retained_gen++;
12825 
12826 	if (dtrace_retained == NULL) {
12827 		dtrace_retained = enab;
12828 		return (0);
12829 	}
12830 
12831 	enab->dten_next = dtrace_retained;
12832 	dtrace_retained->dten_prev = enab;
12833 	dtrace_retained = enab;
12834 
12835 	return (0);
12836 }
12837 
12838 static int
12839 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12840     dtrace_probedesc_t *create)
12841 {
12842 	dtrace_enabling_t *new, *enab;
12843 	int found = 0, err = ENOENT;
12844 
12845 	ASSERT(MUTEX_HELD(&dtrace_lock));
12846 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12847 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12848 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12849 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12850 
12851 	new = dtrace_enabling_create(&state->dts_vstate);
12852 
12853 	/*
12854 	 * Iterate over all retained enablings, looking for enablings that
12855 	 * match the specified state.
12856 	 */
12857 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12858 		int i;
12859 
12860 		/*
12861 		 * dtvs_state can only be NULL for helper enablings -- and
12862 		 * helper enablings can't be retained.
12863 		 */
12864 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12865 
12866 		if (enab->dten_vstate->dtvs_state != state)
12867 			continue;
12868 
12869 		/*
12870 		 * Now iterate over each probe description; we're looking for
12871 		 * an exact match to the specified probe description.
12872 		 */
12873 		for (i = 0; i < enab->dten_ndesc; i++) {
12874 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12875 			dtrace_probedesc_t *pd = &ep->dted_probe;
12876 
12877 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12878 				continue;
12879 
12880 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12881 				continue;
12882 
12883 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12884 				continue;
12885 
12886 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12887 				continue;
12888 
12889 			/*
12890 			 * We have a winning probe!  Add it to our growing
12891 			 * enabling.
12892 			 */
12893 			found = 1;
12894 			dtrace_enabling_addlike(new, ep, create);
12895 		}
12896 	}
12897 
12898 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12899 		dtrace_enabling_destroy(new);
12900 		return (err);
12901 	}
12902 
12903 	return (0);
12904 }
12905 
12906 static void
12907 dtrace_enabling_retract(dtrace_state_t *state)
12908 {
12909 	dtrace_enabling_t *enab, *next;
12910 
12911 	ASSERT(MUTEX_HELD(&dtrace_lock));
12912 
12913 	/*
12914 	 * Iterate over all retained enablings, destroy the enablings retained
12915 	 * for the specified state.
12916 	 */
12917 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12918 		next = enab->dten_next;
12919 
12920 		/*
12921 		 * dtvs_state can only be NULL for helper enablings -- and
12922 		 * helper enablings can't be retained.
12923 		 */
12924 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12925 
12926 		if (enab->dten_vstate->dtvs_state == state) {
12927 			ASSERT(state->dts_nretained > 0);
12928 			dtrace_enabling_destroy(enab);
12929 		}
12930 	}
12931 
12932 	ASSERT(state->dts_nretained == 0);
12933 }
12934 
12935 static int
12936 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12937 {
12938 	int i = 0;
12939 	int matched = 0;
12940 
12941 	ASSERT(MUTEX_HELD(&cpu_lock));
12942 	ASSERT(MUTEX_HELD(&dtrace_lock));
12943 
12944 	for (i = 0; i < enab->dten_ndesc; i++) {
12945 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12946 
12947 		enab->dten_current = ep;
12948 		enab->dten_error = 0;
12949 
12950 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12951 
12952 		if (enab->dten_error != 0) {
12953 			/*
12954 			 * If we get an error half-way through enabling the
12955 			 * probes, we kick out -- perhaps with some number of
12956 			 * them enabled.  Leaving enabled probes enabled may
12957 			 * be slightly confusing for user-level, but we expect
12958 			 * that no one will attempt to actually drive on in
12959 			 * the face of such errors.  If this is an anonymous
12960 			 * enabling (indicated with a NULL nmatched pointer),
12961 			 * we cmn_err() a message.  We aren't expecting to
12962 			 * get such an error -- such as it can exist at all,
12963 			 * it would be a result of corrupted DOF in the driver
12964 			 * properties.
12965 			 */
12966 			if (nmatched == NULL) {
12967 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12968 				    "error on %p: %d", (void *)ep,
12969 				    enab->dten_error);
12970 			}
12971 
12972 			return (enab->dten_error);
12973 		}
12974 	}
12975 
12976 	enab->dten_probegen = dtrace_probegen;
12977 	if (nmatched != NULL)
12978 		*nmatched = matched;
12979 
12980 	return (0);
12981 }
12982 
12983 static void
12984 dtrace_enabling_matchall(void)
12985 {
12986 	dtrace_enabling_t *enab;
12987 
12988 	mutex_enter(&cpu_lock);
12989 	mutex_enter(&dtrace_lock);
12990 
12991 	/*
12992 	 * Iterate over all retained enablings to see if any probes match
12993 	 * against them.  We only perform this operation on enablings for which
12994 	 * we have sufficient permissions by virtue of being in the global zone
12995 	 * or in the same zone as the DTrace client.  Because we can be called
12996 	 * after dtrace_detach() has been called, we cannot assert that there
12997 	 * are retained enablings.  We can safely load from dtrace_retained,
12998 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12999 	 * block pending our completion.
13000 	 */
13001 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13002 #ifdef illumos
13003 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
13004 
13005 		if (INGLOBALZONE(curproc) ||
13006 		    cr != NULL && getzoneid() == crgetzoneid(cr))
13007 #endif
13008 			(void) dtrace_enabling_match(enab, NULL);
13009 	}
13010 
13011 	mutex_exit(&dtrace_lock);
13012 	mutex_exit(&cpu_lock);
13013 }
13014 
13015 /*
13016  * If an enabling is to be enabled without having matched probes (that is, if
13017  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13018  * enabling must be _primed_ by creating an ECB for every ECB description.
13019  * This must be done to assure that we know the number of speculations, the
13020  * number of aggregations, the minimum buffer size needed, etc. before we
13021  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13022  * enabling any probes, we create ECBs for every ECB decription, but with a
13023  * NULL probe -- which is exactly what this function does.
13024  */
13025 static void
13026 dtrace_enabling_prime(dtrace_state_t *state)
13027 {
13028 	dtrace_enabling_t *enab;
13029 	int i;
13030 
13031 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13032 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13033 
13034 		if (enab->dten_vstate->dtvs_state != state)
13035 			continue;
13036 
13037 		/*
13038 		 * We don't want to prime an enabling more than once, lest
13039 		 * we allow a malicious user to induce resource exhaustion.
13040 		 * (The ECBs that result from priming an enabling aren't
13041 		 * leaked -- but they also aren't deallocated until the
13042 		 * consumer state is destroyed.)
13043 		 */
13044 		if (enab->dten_primed)
13045 			continue;
13046 
13047 		for (i = 0; i < enab->dten_ndesc; i++) {
13048 			enab->dten_current = enab->dten_desc[i];
13049 			(void) dtrace_probe_enable(NULL, enab);
13050 		}
13051 
13052 		enab->dten_primed = 1;
13053 	}
13054 }
13055 
13056 /*
13057  * Called to indicate that probes should be provided due to retained
13058  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13059  * must take an initial lap through the enabling calling the dtps_provide()
13060  * entry point explicitly to allow for autocreated probes.
13061  */
13062 static void
13063 dtrace_enabling_provide(dtrace_provider_t *prv)
13064 {
13065 	int i, all = 0;
13066 	dtrace_probedesc_t desc;
13067 	dtrace_genid_t gen;
13068 
13069 	ASSERT(MUTEX_HELD(&dtrace_lock));
13070 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13071 
13072 	if (prv == NULL) {
13073 		all = 1;
13074 		prv = dtrace_provider;
13075 	}
13076 
13077 	do {
13078 		dtrace_enabling_t *enab;
13079 		void *parg = prv->dtpv_arg;
13080 
13081 retry:
13082 		gen = dtrace_retained_gen;
13083 		for (enab = dtrace_retained; enab != NULL;
13084 		    enab = enab->dten_next) {
13085 			for (i = 0; i < enab->dten_ndesc; i++) {
13086 				desc = enab->dten_desc[i]->dted_probe;
13087 				mutex_exit(&dtrace_lock);
13088 				prv->dtpv_pops.dtps_provide(parg, &desc);
13089 				mutex_enter(&dtrace_lock);
13090 				/*
13091 				 * Process the retained enablings again if
13092 				 * they have changed while we weren't holding
13093 				 * dtrace_lock.
13094 				 */
13095 				if (gen != dtrace_retained_gen)
13096 					goto retry;
13097 			}
13098 		}
13099 	} while (all && (prv = prv->dtpv_next) != NULL);
13100 
13101 	mutex_exit(&dtrace_lock);
13102 	dtrace_probe_provide(NULL, all ? NULL : prv);
13103 	mutex_enter(&dtrace_lock);
13104 }
13105 
13106 /*
13107  * Called to reap ECBs that are attached to probes from defunct providers.
13108  */
13109 static void
13110 dtrace_enabling_reap(void)
13111 {
13112 	dtrace_provider_t *prov;
13113 	dtrace_probe_t *probe;
13114 	dtrace_ecb_t *ecb;
13115 	hrtime_t when;
13116 	int i;
13117 
13118 	mutex_enter(&cpu_lock);
13119 	mutex_enter(&dtrace_lock);
13120 
13121 	for (i = 0; i < dtrace_nprobes; i++) {
13122 		if ((probe = dtrace_probes[i]) == NULL)
13123 			continue;
13124 
13125 		if (probe->dtpr_ecb == NULL)
13126 			continue;
13127 
13128 		prov = probe->dtpr_provider;
13129 
13130 		if ((when = prov->dtpv_defunct) == 0)
13131 			continue;
13132 
13133 		/*
13134 		 * We have ECBs on a defunct provider:  we want to reap these
13135 		 * ECBs to allow the provider to unregister.  The destruction
13136 		 * of these ECBs must be done carefully:  if we destroy the ECB
13137 		 * and the consumer later wishes to consume an EPID that
13138 		 * corresponds to the destroyed ECB (and if the EPID metadata
13139 		 * has not been previously consumed), the consumer will abort
13140 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13141 		 * eliminate) the possibility of this, we will only destroy an
13142 		 * ECB for a defunct provider if, for the state that
13143 		 * corresponds to the ECB:
13144 		 *
13145 		 *  (a)	There is no speculative tracing (which can effectively
13146 		 *	cache an EPID for an arbitrary amount of time).
13147 		 *
13148 		 *  (b)	The principal buffers have been switched twice since the
13149 		 *	provider became defunct.
13150 		 *
13151 		 *  (c)	The aggregation buffers are of zero size or have been
13152 		 *	switched twice since the provider became defunct.
13153 		 *
13154 		 * We use dts_speculates to determine (a) and call a function
13155 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13156 		 * that as soon as we've been unable to destroy one of the ECBs
13157 		 * associated with the probe, we quit trying -- reaping is only
13158 		 * fruitful in as much as we can destroy all ECBs associated
13159 		 * with the defunct provider's probes.
13160 		 */
13161 		while ((ecb = probe->dtpr_ecb) != NULL) {
13162 			dtrace_state_t *state = ecb->dte_state;
13163 			dtrace_buffer_t *buf = state->dts_buffer;
13164 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13165 
13166 			if (state->dts_speculates)
13167 				break;
13168 
13169 			if (!dtrace_buffer_consumed(buf, when))
13170 				break;
13171 
13172 			if (!dtrace_buffer_consumed(aggbuf, when))
13173 				break;
13174 
13175 			dtrace_ecb_disable(ecb);
13176 			ASSERT(probe->dtpr_ecb != ecb);
13177 			dtrace_ecb_destroy(ecb);
13178 		}
13179 	}
13180 
13181 	mutex_exit(&dtrace_lock);
13182 	mutex_exit(&cpu_lock);
13183 }
13184 
13185 /*
13186  * DTrace DOF Functions
13187  */
13188 /*ARGSUSED*/
13189 static void
13190 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13191 {
13192 	if (dtrace_err_verbose)
13193 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13194 
13195 #ifdef DTRACE_ERRDEBUG
13196 	dtrace_errdebug(str);
13197 #endif
13198 }
13199 
13200 /*
13201  * Create DOF out of a currently enabled state.  Right now, we only create
13202  * DOF containing the run-time options -- but this could be expanded to create
13203  * complete DOF representing the enabled state.
13204  */
13205 static dof_hdr_t *
13206 dtrace_dof_create(dtrace_state_t *state)
13207 {
13208 	dof_hdr_t *dof;
13209 	dof_sec_t *sec;
13210 	dof_optdesc_t *opt;
13211 	int i, len = sizeof (dof_hdr_t) +
13212 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13213 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13214 
13215 	ASSERT(MUTEX_HELD(&dtrace_lock));
13216 
13217 	dof = kmem_zalloc(len, KM_SLEEP);
13218 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13219 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13220 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13221 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13222 
13223 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13224 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13225 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13226 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13227 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13228 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13229 
13230 	dof->dofh_flags = 0;
13231 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13232 	dof->dofh_secsize = sizeof (dof_sec_t);
13233 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13234 	dof->dofh_secoff = sizeof (dof_hdr_t);
13235 	dof->dofh_loadsz = len;
13236 	dof->dofh_filesz = len;
13237 	dof->dofh_pad = 0;
13238 
13239 	/*
13240 	 * Fill in the option section header...
13241 	 */
13242 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13243 	sec->dofs_type = DOF_SECT_OPTDESC;
13244 	sec->dofs_align = sizeof (uint64_t);
13245 	sec->dofs_flags = DOF_SECF_LOAD;
13246 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13247 
13248 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13249 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13250 
13251 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13252 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13253 
13254 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13255 		opt[i].dofo_option = i;
13256 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13257 		opt[i].dofo_value = state->dts_options[i];
13258 	}
13259 
13260 	return (dof);
13261 }
13262 
13263 static dof_hdr_t *
13264 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13265 {
13266 	dof_hdr_t hdr, *dof;
13267 
13268 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13269 
13270 	/*
13271 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13272 	 */
13273 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13274 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13275 		*errp = EFAULT;
13276 		return (NULL);
13277 	}
13278 
13279 	/*
13280 	 * Now we'll allocate the entire DOF and copy it in -- provided
13281 	 * that the length isn't outrageous.
13282 	 */
13283 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13284 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13285 		*errp = E2BIG;
13286 		return (NULL);
13287 	}
13288 
13289 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13290 		dtrace_dof_error(&hdr, "invalid load size");
13291 		*errp = EINVAL;
13292 		return (NULL);
13293 	}
13294 
13295 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13296 
13297 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13298 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13299 		kmem_free(dof, hdr.dofh_loadsz);
13300 		*errp = EFAULT;
13301 		return (NULL);
13302 	}
13303 
13304 	return (dof);
13305 }
13306 
13307 #ifdef __FreeBSD__
13308 static dof_hdr_t *
13309 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13310 {
13311 	dof_hdr_t hdr, *dof;
13312 	struct thread *td;
13313 	size_t loadsz;
13314 
13315 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13316 
13317 	td = curthread;
13318 
13319 	/*
13320 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13321 	 */
13322 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13323 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13324 		*errp = EFAULT;
13325 		return (NULL);
13326 	}
13327 
13328 	/*
13329 	 * Now we'll allocate the entire DOF and copy it in -- provided
13330 	 * that the length isn't outrageous.
13331 	 */
13332 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13333 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13334 		*errp = E2BIG;
13335 		return (NULL);
13336 	}
13337 	loadsz = (size_t)hdr.dofh_loadsz;
13338 
13339 	if (loadsz < sizeof (hdr)) {
13340 		dtrace_dof_error(&hdr, "invalid load size");
13341 		*errp = EINVAL;
13342 		return (NULL);
13343 	}
13344 
13345 	dof = kmem_alloc(loadsz, KM_SLEEP);
13346 
13347 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13348 	    dof->dofh_loadsz != loadsz) {
13349 		kmem_free(dof, hdr.dofh_loadsz);
13350 		*errp = EFAULT;
13351 		return (NULL);
13352 	}
13353 
13354 	return (dof);
13355 }
13356 
13357 static __inline uchar_t
13358 dtrace_dof_char(char c)
13359 {
13360 
13361 	switch (c) {
13362 	case '0':
13363 	case '1':
13364 	case '2':
13365 	case '3':
13366 	case '4':
13367 	case '5':
13368 	case '6':
13369 	case '7':
13370 	case '8':
13371 	case '9':
13372 		return (c - '0');
13373 	case 'A':
13374 	case 'B':
13375 	case 'C':
13376 	case 'D':
13377 	case 'E':
13378 	case 'F':
13379 		return (c - 'A' + 10);
13380 	case 'a':
13381 	case 'b':
13382 	case 'c':
13383 	case 'd':
13384 	case 'e':
13385 	case 'f':
13386 		return (c - 'a' + 10);
13387 	}
13388 	/* Should not reach here. */
13389 	return (UCHAR_MAX);
13390 }
13391 #endif /* __FreeBSD__ */
13392 
13393 static dof_hdr_t *
13394 dtrace_dof_property(const char *name)
13395 {
13396 #ifdef __FreeBSD__
13397 	uint8_t *dofbuf;
13398 	u_char *data, *eol;
13399 	caddr_t doffile;
13400 	size_t bytes, len, i;
13401 	dof_hdr_t *dof;
13402 	u_char c1, c2;
13403 
13404 	dof = NULL;
13405 
13406 	doffile = preload_search_by_type("dtrace_dof");
13407 	if (doffile == NULL)
13408 		return (NULL);
13409 
13410 	data = preload_fetch_addr(doffile);
13411 	len = preload_fetch_size(doffile);
13412 	for (;;) {
13413 		/* Look for the end of the line. All lines end in a newline. */
13414 		eol = memchr(data, '\n', len);
13415 		if (eol == NULL)
13416 			return (NULL);
13417 
13418 		if (strncmp(name, data, strlen(name)) == 0)
13419 			break;
13420 
13421 		eol++; /* skip past the newline */
13422 		len -= eol - data;
13423 		data = eol;
13424 	}
13425 
13426 	/* We've found the data corresponding to the specified key. */
13427 
13428 	data += strlen(name) + 1; /* skip past the '=' */
13429 	len = eol - data;
13430 	if (len % 2 != 0) {
13431 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13432 		goto doferr;
13433 	}
13434 	bytes = len / 2;
13435 	if (bytes < sizeof(dof_hdr_t)) {
13436 		dtrace_dof_error(NULL, "truncated header");
13437 		goto doferr;
13438 	}
13439 
13440 	/*
13441 	 * Each byte is represented by the two ASCII characters in its hex
13442 	 * representation.
13443 	 */
13444 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13445 	for (i = 0; i < bytes; i++) {
13446 		c1 = dtrace_dof_char(data[i * 2]);
13447 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13448 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13449 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13450 			goto doferr;
13451 		}
13452 		dofbuf[i] = c1 * 16 + c2;
13453 	}
13454 
13455 	dof = (dof_hdr_t *)dofbuf;
13456 	if (bytes < dof->dofh_loadsz) {
13457 		dtrace_dof_error(NULL, "truncated DOF");
13458 		goto doferr;
13459 	}
13460 
13461 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13462 		dtrace_dof_error(NULL, "oversized DOF");
13463 		goto doferr;
13464 	}
13465 
13466 	return (dof);
13467 
13468 doferr:
13469 	free(dof, M_SOLARIS);
13470 	return (NULL);
13471 #else /* __FreeBSD__ */
13472 	uchar_t *buf;
13473 	uint64_t loadsz;
13474 	unsigned int len, i;
13475 	dof_hdr_t *dof;
13476 
13477 	/*
13478 	 * Unfortunately, array of values in .conf files are always (and
13479 	 * only) interpreted to be integer arrays.  We must read our DOF
13480 	 * as an integer array, and then squeeze it into a byte array.
13481 	 */
13482 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13483 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13484 		return (NULL);
13485 
13486 	for (i = 0; i < len; i++)
13487 		buf[i] = (uchar_t)(((int *)buf)[i]);
13488 
13489 	if (len < sizeof (dof_hdr_t)) {
13490 		ddi_prop_free(buf);
13491 		dtrace_dof_error(NULL, "truncated header");
13492 		return (NULL);
13493 	}
13494 
13495 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13496 		ddi_prop_free(buf);
13497 		dtrace_dof_error(NULL, "truncated DOF");
13498 		return (NULL);
13499 	}
13500 
13501 	if (loadsz >= dtrace_dof_maxsize) {
13502 		ddi_prop_free(buf);
13503 		dtrace_dof_error(NULL, "oversized DOF");
13504 		return (NULL);
13505 	}
13506 
13507 	dof = kmem_alloc(loadsz, KM_SLEEP);
13508 	bcopy(buf, dof, loadsz);
13509 	ddi_prop_free(buf);
13510 
13511 	return (dof);
13512 #endif /* !__FreeBSD__ */
13513 }
13514 
13515 static void
13516 dtrace_dof_destroy(dof_hdr_t *dof)
13517 {
13518 	kmem_free(dof, dof->dofh_loadsz);
13519 }
13520 
13521 /*
13522  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13523  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13524  * a type other than DOF_SECT_NONE is specified, the header is checked against
13525  * this type and NULL is returned if the types do not match.
13526  */
13527 static dof_sec_t *
13528 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13529 {
13530 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13531 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13532 
13533 	if (i >= dof->dofh_secnum) {
13534 		dtrace_dof_error(dof, "referenced section index is invalid");
13535 		return (NULL);
13536 	}
13537 
13538 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13539 		dtrace_dof_error(dof, "referenced section is not loadable");
13540 		return (NULL);
13541 	}
13542 
13543 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13544 		dtrace_dof_error(dof, "referenced section is the wrong type");
13545 		return (NULL);
13546 	}
13547 
13548 	return (sec);
13549 }
13550 
13551 static dtrace_probedesc_t *
13552 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13553 {
13554 	dof_probedesc_t *probe;
13555 	dof_sec_t *strtab;
13556 	uintptr_t daddr = (uintptr_t)dof;
13557 	uintptr_t str;
13558 	size_t size;
13559 
13560 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13561 		dtrace_dof_error(dof, "invalid probe section");
13562 		return (NULL);
13563 	}
13564 
13565 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13566 		dtrace_dof_error(dof, "bad alignment in probe description");
13567 		return (NULL);
13568 	}
13569 
13570 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13571 		dtrace_dof_error(dof, "truncated probe description");
13572 		return (NULL);
13573 	}
13574 
13575 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13576 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13577 
13578 	if (strtab == NULL)
13579 		return (NULL);
13580 
13581 	str = daddr + strtab->dofs_offset;
13582 	size = strtab->dofs_size;
13583 
13584 	if (probe->dofp_provider >= strtab->dofs_size) {
13585 		dtrace_dof_error(dof, "corrupt probe provider");
13586 		return (NULL);
13587 	}
13588 
13589 	(void) strncpy(desc->dtpd_provider,
13590 	    (char *)(str + probe->dofp_provider),
13591 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13592 
13593 	if (probe->dofp_mod >= strtab->dofs_size) {
13594 		dtrace_dof_error(dof, "corrupt probe module");
13595 		return (NULL);
13596 	}
13597 
13598 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13599 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13600 
13601 	if (probe->dofp_func >= strtab->dofs_size) {
13602 		dtrace_dof_error(dof, "corrupt probe function");
13603 		return (NULL);
13604 	}
13605 
13606 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13607 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13608 
13609 	if (probe->dofp_name >= strtab->dofs_size) {
13610 		dtrace_dof_error(dof, "corrupt probe name");
13611 		return (NULL);
13612 	}
13613 
13614 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13615 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13616 
13617 	return (desc);
13618 }
13619 
13620 static dtrace_difo_t *
13621 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13622     cred_t *cr)
13623 {
13624 	dtrace_difo_t *dp;
13625 	size_t ttl = 0;
13626 	dof_difohdr_t *dofd;
13627 	uintptr_t daddr = (uintptr_t)dof;
13628 	size_t max = dtrace_difo_maxsize;
13629 	int i, l, n;
13630 
13631 	static const struct {
13632 		int section;
13633 		int bufoffs;
13634 		int lenoffs;
13635 		int entsize;
13636 		int align;
13637 		const char *msg;
13638 	} difo[] = {
13639 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13640 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13641 		sizeof (dif_instr_t), "multiple DIF sections" },
13642 
13643 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13644 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13645 		sizeof (uint64_t), "multiple integer tables" },
13646 
13647 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13648 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13649 		sizeof (char), "multiple string tables" },
13650 
13651 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13652 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13653 		sizeof (uint_t), "multiple variable tables" },
13654 
13655 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13656 	};
13657 
13658 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13659 		dtrace_dof_error(dof, "invalid DIFO header section");
13660 		return (NULL);
13661 	}
13662 
13663 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13664 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13665 		return (NULL);
13666 	}
13667 
13668 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13669 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13670 		dtrace_dof_error(dof, "bad size in DIFO header");
13671 		return (NULL);
13672 	}
13673 
13674 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13675 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13676 
13677 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13678 	dp->dtdo_rtype = dofd->dofd_rtype;
13679 
13680 	for (l = 0; l < n; l++) {
13681 		dof_sec_t *subsec;
13682 		void **bufp;
13683 		uint32_t *lenp;
13684 
13685 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13686 		    dofd->dofd_links[l])) == NULL)
13687 			goto err; /* invalid section link */
13688 
13689 		if (ttl + subsec->dofs_size > max) {
13690 			dtrace_dof_error(dof, "exceeds maximum size");
13691 			goto err;
13692 		}
13693 
13694 		ttl += subsec->dofs_size;
13695 
13696 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13697 			if (subsec->dofs_type != difo[i].section)
13698 				continue;
13699 
13700 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13701 				dtrace_dof_error(dof, "section not loaded");
13702 				goto err;
13703 			}
13704 
13705 			if (subsec->dofs_align != difo[i].align) {
13706 				dtrace_dof_error(dof, "bad alignment");
13707 				goto err;
13708 			}
13709 
13710 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13711 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13712 
13713 			if (*bufp != NULL) {
13714 				dtrace_dof_error(dof, difo[i].msg);
13715 				goto err;
13716 			}
13717 
13718 			if (difo[i].entsize != subsec->dofs_entsize) {
13719 				dtrace_dof_error(dof, "entry size mismatch");
13720 				goto err;
13721 			}
13722 
13723 			if (subsec->dofs_entsize != 0 &&
13724 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13725 				dtrace_dof_error(dof, "corrupt entry size");
13726 				goto err;
13727 			}
13728 
13729 			*lenp = subsec->dofs_size;
13730 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13731 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13732 			    *bufp, subsec->dofs_size);
13733 
13734 			if (subsec->dofs_entsize != 0)
13735 				*lenp /= subsec->dofs_entsize;
13736 
13737 			break;
13738 		}
13739 
13740 		/*
13741 		 * If we encounter a loadable DIFO sub-section that is not
13742 		 * known to us, assume this is a broken program and fail.
13743 		 */
13744 		if (difo[i].section == DOF_SECT_NONE &&
13745 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13746 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13747 			goto err;
13748 		}
13749 	}
13750 
13751 	if (dp->dtdo_buf == NULL) {
13752 		/*
13753 		 * We can't have a DIF object without DIF text.
13754 		 */
13755 		dtrace_dof_error(dof, "missing DIF text");
13756 		goto err;
13757 	}
13758 
13759 	/*
13760 	 * Before we validate the DIF object, run through the variable table
13761 	 * looking for the strings -- if any of their size are under, we'll set
13762 	 * their size to be the system-wide default string size.  Note that
13763 	 * this should _not_ happen if the "strsize" option has been set --
13764 	 * in this case, the compiler should have set the size to reflect the
13765 	 * setting of the option.
13766 	 */
13767 	for (i = 0; i < dp->dtdo_varlen; i++) {
13768 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13769 		dtrace_diftype_t *t = &v->dtdv_type;
13770 
13771 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13772 			continue;
13773 
13774 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13775 			t->dtdt_size = dtrace_strsize_default;
13776 	}
13777 
13778 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13779 		goto err;
13780 
13781 	dtrace_difo_init(dp, vstate);
13782 	return (dp);
13783 
13784 err:
13785 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13786 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13787 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13788 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13789 
13790 	kmem_free(dp, sizeof (dtrace_difo_t));
13791 	return (NULL);
13792 }
13793 
13794 static dtrace_predicate_t *
13795 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13796     cred_t *cr)
13797 {
13798 	dtrace_difo_t *dp;
13799 
13800 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13801 		return (NULL);
13802 
13803 	return (dtrace_predicate_create(dp));
13804 }
13805 
13806 static dtrace_actdesc_t *
13807 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13808     cred_t *cr)
13809 {
13810 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13811 	dof_actdesc_t *desc;
13812 	dof_sec_t *difosec;
13813 	size_t offs;
13814 	uintptr_t daddr = (uintptr_t)dof;
13815 	uint64_t arg;
13816 	dtrace_actkind_t kind;
13817 
13818 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13819 		dtrace_dof_error(dof, "invalid action section");
13820 		return (NULL);
13821 	}
13822 
13823 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13824 		dtrace_dof_error(dof, "truncated action description");
13825 		return (NULL);
13826 	}
13827 
13828 	if (sec->dofs_align != sizeof (uint64_t)) {
13829 		dtrace_dof_error(dof, "bad alignment in action description");
13830 		return (NULL);
13831 	}
13832 
13833 	if (sec->dofs_size < sec->dofs_entsize) {
13834 		dtrace_dof_error(dof, "section entry size exceeds total size");
13835 		return (NULL);
13836 	}
13837 
13838 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13839 		dtrace_dof_error(dof, "bad entry size in action description");
13840 		return (NULL);
13841 	}
13842 
13843 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13844 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13845 		return (NULL);
13846 	}
13847 
13848 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13849 		desc = (dof_actdesc_t *)(daddr +
13850 		    (uintptr_t)sec->dofs_offset + offs);
13851 		kind = (dtrace_actkind_t)desc->dofa_kind;
13852 
13853 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13854 		    (kind != DTRACEACT_PRINTA ||
13855 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13856 		    (kind == DTRACEACT_DIFEXPR &&
13857 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13858 			dof_sec_t *strtab;
13859 			char *str, *fmt;
13860 			uint64_t i;
13861 
13862 			/*
13863 			 * The argument to these actions is an index into the
13864 			 * DOF string table.  For printf()-like actions, this
13865 			 * is the format string.  For print(), this is the
13866 			 * CTF type of the expression result.
13867 			 */
13868 			if ((strtab = dtrace_dof_sect(dof,
13869 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13870 				goto err;
13871 
13872 			str = (char *)((uintptr_t)dof +
13873 			    (uintptr_t)strtab->dofs_offset);
13874 
13875 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13876 				if (str[i] == '\0')
13877 					break;
13878 			}
13879 
13880 			if (i >= strtab->dofs_size) {
13881 				dtrace_dof_error(dof, "bogus format string");
13882 				goto err;
13883 			}
13884 
13885 			if (i == desc->dofa_arg) {
13886 				dtrace_dof_error(dof, "empty format string");
13887 				goto err;
13888 			}
13889 
13890 			i -= desc->dofa_arg;
13891 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13892 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13893 			arg = (uint64_t)(uintptr_t)fmt;
13894 		} else {
13895 			if (kind == DTRACEACT_PRINTA) {
13896 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13897 				arg = 0;
13898 			} else {
13899 				arg = desc->dofa_arg;
13900 			}
13901 		}
13902 
13903 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13904 		    desc->dofa_uarg, arg);
13905 
13906 		if (last != NULL) {
13907 			last->dtad_next = act;
13908 		} else {
13909 			first = act;
13910 		}
13911 
13912 		last = act;
13913 
13914 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13915 			continue;
13916 
13917 		if ((difosec = dtrace_dof_sect(dof,
13918 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13919 			goto err;
13920 
13921 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13922 
13923 		if (act->dtad_difo == NULL)
13924 			goto err;
13925 	}
13926 
13927 	ASSERT(first != NULL);
13928 	return (first);
13929 
13930 err:
13931 	for (act = first; act != NULL; act = next) {
13932 		next = act->dtad_next;
13933 		dtrace_actdesc_release(act, vstate);
13934 	}
13935 
13936 	return (NULL);
13937 }
13938 
13939 static dtrace_ecbdesc_t *
13940 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13941     cred_t *cr)
13942 {
13943 	dtrace_ecbdesc_t *ep;
13944 	dof_ecbdesc_t *ecb;
13945 	dtrace_probedesc_t *desc;
13946 	dtrace_predicate_t *pred = NULL;
13947 
13948 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13949 		dtrace_dof_error(dof, "truncated ECB description");
13950 		return (NULL);
13951 	}
13952 
13953 	if (sec->dofs_align != sizeof (uint64_t)) {
13954 		dtrace_dof_error(dof, "bad alignment in ECB description");
13955 		return (NULL);
13956 	}
13957 
13958 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13959 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13960 
13961 	if (sec == NULL)
13962 		return (NULL);
13963 
13964 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13965 	ep->dted_uarg = ecb->dofe_uarg;
13966 	desc = &ep->dted_probe;
13967 
13968 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13969 		goto err;
13970 
13971 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13972 		if ((sec = dtrace_dof_sect(dof,
13973 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13974 			goto err;
13975 
13976 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13977 			goto err;
13978 
13979 		ep->dted_pred.dtpdd_predicate = pred;
13980 	}
13981 
13982 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13983 		if ((sec = dtrace_dof_sect(dof,
13984 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13985 			goto err;
13986 
13987 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13988 
13989 		if (ep->dted_action == NULL)
13990 			goto err;
13991 	}
13992 
13993 	return (ep);
13994 
13995 err:
13996 	if (pred != NULL)
13997 		dtrace_predicate_release(pred, vstate);
13998 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13999 	return (NULL);
14000 }
14001 
14002 /*
14003  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
14004  * specified DOF.  SETX relocations are computed using 'ubase', the base load
14005  * address of the object containing the DOF, and DOFREL relocations are relative
14006  * to the relocation offset within the DOF.
14007  */
14008 static int
14009 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14010     uint64_t udaddr)
14011 {
14012 	uintptr_t daddr = (uintptr_t)dof;
14013 	uintptr_t ts_end;
14014 	dof_relohdr_t *dofr =
14015 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14016 	dof_sec_t *ss, *rs, *ts;
14017 	dof_relodesc_t *r;
14018 	uint_t i, n;
14019 
14020 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14021 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14022 		dtrace_dof_error(dof, "invalid relocation header");
14023 		return (-1);
14024 	}
14025 
14026 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14027 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14028 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14029 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14030 
14031 	if (ss == NULL || rs == NULL || ts == NULL)
14032 		return (-1); /* dtrace_dof_error() has been called already */
14033 
14034 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14035 	    rs->dofs_align != sizeof (uint64_t)) {
14036 		dtrace_dof_error(dof, "invalid relocation section");
14037 		return (-1);
14038 	}
14039 
14040 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14041 	n = rs->dofs_size / rs->dofs_entsize;
14042 
14043 	for (i = 0; i < n; i++) {
14044 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14045 
14046 		switch (r->dofr_type) {
14047 		case DOF_RELO_NONE:
14048 			break;
14049 		case DOF_RELO_SETX:
14050 		case DOF_RELO_DOFREL:
14051 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14052 			    sizeof (uint64_t) > ts->dofs_size) {
14053 				dtrace_dof_error(dof, "bad relocation offset");
14054 				return (-1);
14055 			}
14056 
14057 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14058 				dtrace_dof_error(dof, "bad relocation offset");
14059 				return (-1);
14060 			}
14061 
14062 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14063 				dtrace_dof_error(dof, "misaligned setx relo");
14064 				return (-1);
14065 			}
14066 
14067 			if (r->dofr_type == DOF_RELO_SETX)
14068 				*(uint64_t *)taddr += ubase;
14069 			else
14070 				*(uint64_t *)taddr +=
14071 				    udaddr + ts->dofs_offset + r->dofr_offset;
14072 			break;
14073 		default:
14074 			dtrace_dof_error(dof, "invalid relocation type");
14075 			return (-1);
14076 		}
14077 
14078 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14079 	}
14080 
14081 	return (0);
14082 }
14083 
14084 /*
14085  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14086  * header:  it should be at the front of a memory region that is at least
14087  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14088  * size.  It need not be validated in any other way.
14089  */
14090 static int
14091 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14092     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14093 {
14094 	uint64_t len = dof->dofh_loadsz, seclen;
14095 	uintptr_t daddr = (uintptr_t)dof;
14096 	dtrace_ecbdesc_t *ep;
14097 	dtrace_enabling_t *enab;
14098 	uint_t i;
14099 
14100 	ASSERT(MUTEX_HELD(&dtrace_lock));
14101 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14102 
14103 	/*
14104 	 * Check the DOF header identification bytes.  In addition to checking
14105 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14106 	 * we can use them later without fear of regressing existing binaries.
14107 	 */
14108 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14109 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14110 		dtrace_dof_error(dof, "DOF magic string mismatch");
14111 		return (-1);
14112 	}
14113 
14114 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14115 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14116 		dtrace_dof_error(dof, "DOF has invalid data model");
14117 		return (-1);
14118 	}
14119 
14120 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14121 		dtrace_dof_error(dof, "DOF encoding mismatch");
14122 		return (-1);
14123 	}
14124 
14125 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14126 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14127 		dtrace_dof_error(dof, "DOF version mismatch");
14128 		return (-1);
14129 	}
14130 
14131 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14132 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14133 		return (-1);
14134 	}
14135 
14136 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14137 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14138 		return (-1);
14139 	}
14140 
14141 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14142 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14143 		return (-1);
14144 	}
14145 
14146 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14147 		if (dof->dofh_ident[i] != 0) {
14148 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14149 			return (-1);
14150 		}
14151 	}
14152 
14153 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14154 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14155 		return (-1);
14156 	}
14157 
14158 	if (dof->dofh_secsize == 0) {
14159 		dtrace_dof_error(dof, "zero section header size");
14160 		return (-1);
14161 	}
14162 
14163 	/*
14164 	 * Check that the section headers don't exceed the amount of DOF
14165 	 * data.  Note that we cast the section size and number of sections
14166 	 * to uint64_t's to prevent possible overflow in the multiplication.
14167 	 */
14168 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14169 
14170 	if (dof->dofh_secoff > len || seclen > len ||
14171 	    dof->dofh_secoff + seclen > len) {
14172 		dtrace_dof_error(dof, "truncated section headers");
14173 		return (-1);
14174 	}
14175 
14176 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14177 		dtrace_dof_error(dof, "misaligned section headers");
14178 		return (-1);
14179 	}
14180 
14181 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14182 		dtrace_dof_error(dof, "misaligned section size");
14183 		return (-1);
14184 	}
14185 
14186 	/*
14187 	 * Take an initial pass through the section headers to be sure that
14188 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14189 	 * set, do not permit sections relating to providers, probes, or args.
14190 	 */
14191 	for (i = 0; i < dof->dofh_secnum; i++) {
14192 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14193 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14194 
14195 		if (noprobes) {
14196 			switch (sec->dofs_type) {
14197 			case DOF_SECT_PROVIDER:
14198 			case DOF_SECT_PROBES:
14199 			case DOF_SECT_PRARGS:
14200 			case DOF_SECT_PROFFS:
14201 				dtrace_dof_error(dof, "illegal sections "
14202 				    "for enabling");
14203 				return (-1);
14204 			}
14205 		}
14206 
14207 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14208 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14209 			dtrace_dof_error(dof, "loadable section with load "
14210 			    "flag unset");
14211 			return (-1);
14212 		}
14213 
14214 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14215 			continue; /* just ignore non-loadable sections */
14216 
14217 		if (!ISP2(sec->dofs_align)) {
14218 			dtrace_dof_error(dof, "bad section alignment");
14219 			return (-1);
14220 		}
14221 
14222 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14223 			dtrace_dof_error(dof, "misaligned section");
14224 			return (-1);
14225 		}
14226 
14227 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14228 		    sec->dofs_offset + sec->dofs_size > len) {
14229 			dtrace_dof_error(dof, "corrupt section header");
14230 			return (-1);
14231 		}
14232 
14233 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14234 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14235 			dtrace_dof_error(dof, "non-terminating string table");
14236 			return (-1);
14237 		}
14238 	}
14239 
14240 	/*
14241 	 * Take a second pass through the sections and locate and perform any
14242 	 * relocations that are present.  We do this after the first pass to
14243 	 * be sure that all sections have had their headers validated.
14244 	 */
14245 	for (i = 0; i < dof->dofh_secnum; i++) {
14246 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14247 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14248 
14249 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14250 			continue; /* skip sections that are not loadable */
14251 
14252 		switch (sec->dofs_type) {
14253 		case DOF_SECT_URELHDR:
14254 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14255 				return (-1);
14256 			break;
14257 		}
14258 	}
14259 
14260 	if ((enab = *enabp) == NULL)
14261 		enab = *enabp = dtrace_enabling_create(vstate);
14262 
14263 	for (i = 0; i < dof->dofh_secnum; i++) {
14264 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14265 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14266 
14267 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14268 			continue;
14269 
14270 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14271 			dtrace_enabling_destroy(enab);
14272 			*enabp = NULL;
14273 			return (-1);
14274 		}
14275 
14276 		dtrace_enabling_add(enab, ep);
14277 	}
14278 
14279 	return (0);
14280 }
14281 
14282 /*
14283  * Process DOF for any options.  This routine assumes that the DOF has been
14284  * at least processed by dtrace_dof_slurp().
14285  */
14286 static int
14287 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14288 {
14289 	int i, rval;
14290 	uint32_t entsize;
14291 	size_t offs;
14292 	dof_optdesc_t *desc;
14293 
14294 	for (i = 0; i < dof->dofh_secnum; i++) {
14295 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14296 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14297 
14298 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14299 			continue;
14300 
14301 		if (sec->dofs_align != sizeof (uint64_t)) {
14302 			dtrace_dof_error(dof, "bad alignment in "
14303 			    "option description");
14304 			return (EINVAL);
14305 		}
14306 
14307 		if ((entsize = sec->dofs_entsize) == 0) {
14308 			dtrace_dof_error(dof, "zeroed option entry size");
14309 			return (EINVAL);
14310 		}
14311 
14312 		if (entsize < sizeof (dof_optdesc_t)) {
14313 			dtrace_dof_error(dof, "bad option entry size");
14314 			return (EINVAL);
14315 		}
14316 
14317 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14318 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14319 			    (uintptr_t)sec->dofs_offset + offs);
14320 
14321 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14322 				dtrace_dof_error(dof, "non-zero option string");
14323 				return (EINVAL);
14324 			}
14325 
14326 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14327 				dtrace_dof_error(dof, "unset option");
14328 				return (EINVAL);
14329 			}
14330 
14331 			if ((rval = dtrace_state_option(state,
14332 			    desc->dofo_option, desc->dofo_value)) != 0) {
14333 				dtrace_dof_error(dof, "rejected option");
14334 				return (rval);
14335 			}
14336 		}
14337 	}
14338 
14339 	return (0);
14340 }
14341 
14342 /*
14343  * DTrace Consumer State Functions
14344  */
14345 static int
14346 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14347 {
14348 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14349 	void *base;
14350 	uintptr_t limit;
14351 	dtrace_dynvar_t *dvar, *next, *start;
14352 	int i;
14353 
14354 	ASSERT(MUTEX_HELD(&dtrace_lock));
14355 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14356 
14357 	bzero(dstate, sizeof (dtrace_dstate_t));
14358 
14359 	if ((dstate->dtds_chunksize = chunksize) == 0)
14360 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14361 
14362 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14363 
14364 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14365 		size = min;
14366 
14367 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14368 		return (ENOMEM);
14369 
14370 	dstate->dtds_size = size;
14371 	dstate->dtds_base = base;
14372 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14373 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14374 
14375 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14376 
14377 	if (hashsize != 1 && (hashsize & 1))
14378 		hashsize--;
14379 
14380 	dstate->dtds_hashsize = hashsize;
14381 	dstate->dtds_hash = dstate->dtds_base;
14382 
14383 	/*
14384 	 * Set all of our hash buckets to point to the single sink, and (if
14385 	 * it hasn't already been set), set the sink's hash value to be the
14386 	 * sink sentinel value.  The sink is needed for dynamic variable
14387 	 * lookups to know that they have iterated over an entire, valid hash
14388 	 * chain.
14389 	 */
14390 	for (i = 0; i < hashsize; i++)
14391 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14392 
14393 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14394 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14395 
14396 	/*
14397 	 * Determine number of active CPUs.  Divide free list evenly among
14398 	 * active CPUs.
14399 	 */
14400 	start = (dtrace_dynvar_t *)
14401 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14402 	limit = (uintptr_t)base + size;
14403 
14404 	VERIFY((uintptr_t)start < limit);
14405 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14406 
14407 	maxper = (limit - (uintptr_t)start) / NCPU;
14408 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14409 
14410 #ifndef illumos
14411 	CPU_FOREACH(i) {
14412 #else
14413 	for (i = 0; i < NCPU; i++) {
14414 #endif
14415 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14416 
14417 		/*
14418 		 * If we don't even have enough chunks to make it once through
14419 		 * NCPUs, we're just going to allocate everything to the first
14420 		 * CPU.  And if we're on the last CPU, we're going to allocate
14421 		 * whatever is left over.  In either case, we set the limit to
14422 		 * be the limit of the dynamic variable space.
14423 		 */
14424 		if (maxper == 0 || i == NCPU - 1) {
14425 			limit = (uintptr_t)base + size;
14426 			start = NULL;
14427 		} else {
14428 			limit = (uintptr_t)start + maxper;
14429 			start = (dtrace_dynvar_t *)limit;
14430 		}
14431 
14432 		VERIFY(limit <= (uintptr_t)base + size);
14433 
14434 		for (;;) {
14435 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14436 			    dstate->dtds_chunksize);
14437 
14438 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14439 				break;
14440 
14441 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14442 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14443 			dvar->dtdv_next = next;
14444 			dvar = next;
14445 		}
14446 
14447 		if (maxper == 0)
14448 			break;
14449 	}
14450 
14451 	return (0);
14452 }
14453 
14454 static void
14455 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14456 {
14457 	ASSERT(MUTEX_HELD(&cpu_lock));
14458 
14459 	if (dstate->dtds_base == NULL)
14460 		return;
14461 
14462 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14463 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14464 }
14465 
14466 static void
14467 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14468 {
14469 	/*
14470 	 * Logical XOR, where are you?
14471 	 */
14472 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14473 
14474 	if (vstate->dtvs_nglobals > 0) {
14475 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14476 		    sizeof (dtrace_statvar_t *));
14477 	}
14478 
14479 	if (vstate->dtvs_ntlocals > 0) {
14480 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14481 		    sizeof (dtrace_difv_t));
14482 	}
14483 
14484 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14485 
14486 	if (vstate->dtvs_nlocals > 0) {
14487 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14488 		    sizeof (dtrace_statvar_t *));
14489 	}
14490 }
14491 
14492 #ifdef illumos
14493 static void
14494 dtrace_state_clean(dtrace_state_t *state)
14495 {
14496 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14497 		return;
14498 
14499 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14500 	dtrace_speculation_clean(state);
14501 }
14502 
14503 static void
14504 dtrace_state_deadman(dtrace_state_t *state)
14505 {
14506 	hrtime_t now;
14507 
14508 	dtrace_sync();
14509 
14510 	now = dtrace_gethrtime();
14511 
14512 	if (state != dtrace_anon.dta_state &&
14513 	    now - state->dts_laststatus >= dtrace_deadman_user)
14514 		return;
14515 
14516 	/*
14517 	 * We must be sure that dts_alive never appears to be less than the
14518 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14519 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14520 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14521 	 * the new value.  This assures that dts_alive never appears to be
14522 	 * less than its true value, regardless of the order in which the
14523 	 * stores to the underlying storage are issued.
14524 	 */
14525 	state->dts_alive = INT64_MAX;
14526 	dtrace_membar_producer();
14527 	state->dts_alive = now;
14528 }
14529 #else	/* !illumos */
14530 static void
14531 dtrace_state_clean(void *arg)
14532 {
14533 	dtrace_state_t *state = arg;
14534 	dtrace_optval_t *opt = state->dts_options;
14535 
14536 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14537 		return;
14538 
14539 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14540 	dtrace_speculation_clean(state);
14541 
14542 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14543 	    dtrace_state_clean, state);
14544 }
14545 
14546 static void
14547 dtrace_state_deadman(void *arg)
14548 {
14549 	dtrace_state_t *state = arg;
14550 	hrtime_t now;
14551 
14552 	dtrace_sync();
14553 
14554 	dtrace_debug_output();
14555 
14556 	now = dtrace_gethrtime();
14557 
14558 	if (state != dtrace_anon.dta_state &&
14559 	    now - state->dts_laststatus >= dtrace_deadman_user)
14560 		return;
14561 
14562 	/*
14563 	 * We must be sure that dts_alive never appears to be less than the
14564 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14565 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14566 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14567 	 * the new value.  This assures that dts_alive never appears to be
14568 	 * less than its true value, regardless of the order in which the
14569 	 * stores to the underlying storage are issued.
14570 	 */
14571 	state->dts_alive = INT64_MAX;
14572 	dtrace_membar_producer();
14573 	state->dts_alive = now;
14574 
14575 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14576 	    dtrace_state_deadman, state);
14577 }
14578 #endif	/* illumos */
14579 
14580 static dtrace_state_t *
14581 #ifdef illumos
14582 dtrace_state_create(dev_t *devp, cred_t *cr)
14583 #else
14584 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14585 #endif
14586 {
14587 #ifdef illumos
14588 	minor_t minor;
14589 	major_t major;
14590 #else
14591 	cred_t *cr = NULL;
14592 	int m = 0;
14593 #endif
14594 	char c[30];
14595 	dtrace_state_t *state;
14596 	dtrace_optval_t *opt;
14597 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14598 	int cpu_it;
14599 
14600 	ASSERT(MUTEX_HELD(&dtrace_lock));
14601 	ASSERT(MUTEX_HELD(&cpu_lock));
14602 
14603 #ifdef illumos
14604 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14605 	    VM_BESTFIT | VM_SLEEP);
14606 
14607 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14608 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14609 		return (NULL);
14610 	}
14611 
14612 	state = ddi_get_soft_state(dtrace_softstate, minor);
14613 #else
14614 	if (dev != NULL) {
14615 		cr = dev->si_cred;
14616 		m = dev2unit(dev);
14617 	}
14618 
14619 	/* Allocate memory for the state. */
14620 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14621 #endif
14622 
14623 	state->dts_epid = DTRACE_EPIDNONE + 1;
14624 
14625 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14626 #ifdef illumos
14627 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14628 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14629 
14630 	if (devp != NULL) {
14631 		major = getemajor(*devp);
14632 	} else {
14633 		major = ddi_driver_major(dtrace_devi);
14634 	}
14635 
14636 	state->dts_dev = makedevice(major, minor);
14637 
14638 	if (devp != NULL)
14639 		*devp = state->dts_dev;
14640 #else
14641 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14642 	state->dts_dev = dev;
14643 #endif
14644 
14645 	/*
14646 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14647 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14648 	 * other hand, it saves an additional memory reference in the probe
14649 	 * path.
14650 	 */
14651 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14652 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14653 
14654 	/*
14655          * Allocate and initialise the per-process per-CPU random state.
14656 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14657          * assumed to be seeded at this point (if from Fortuna seed file).
14658 	 */
14659 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14660 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14661 		/*
14662 		 * Each CPU is assigned a 2^64 period, non-overlapping
14663 		 * subsequence.
14664 		 */
14665 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14666 		    state->dts_rstate[cpu_it]);
14667 	}
14668 
14669 #ifdef illumos
14670 	state->dts_cleaner = CYCLIC_NONE;
14671 	state->dts_deadman = CYCLIC_NONE;
14672 #else
14673 	callout_init(&state->dts_cleaner, 1);
14674 	callout_init(&state->dts_deadman, 1);
14675 #endif
14676 	state->dts_vstate.dtvs_state = state;
14677 
14678 	for (i = 0; i < DTRACEOPT_MAX; i++)
14679 		state->dts_options[i] = DTRACEOPT_UNSET;
14680 
14681 	/*
14682 	 * Set the default options.
14683 	 */
14684 	opt = state->dts_options;
14685 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14686 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14687 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14688 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14689 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14690 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14691 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14692 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14693 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14694 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14695 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14696 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14697 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14698 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14699 
14700 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14701 
14702 	/*
14703 	 * Depending on the user credentials, we set flag bits which alter probe
14704 	 * visibility or the amount of destructiveness allowed.  In the case of
14705 	 * actual anonymous tracing, or the possession of all privileges, all of
14706 	 * the normal checks are bypassed.
14707 	 */
14708 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14709 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14710 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14711 	} else {
14712 		/*
14713 		 * Set up the credentials for this instantiation.  We take a
14714 		 * hold on the credential to prevent it from disappearing on
14715 		 * us; this in turn prevents the zone_t referenced by this
14716 		 * credential from disappearing.  This means that we can
14717 		 * examine the credential and the zone from probe context.
14718 		 */
14719 		crhold(cr);
14720 		state->dts_cred.dcr_cred = cr;
14721 
14722 		/*
14723 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14724 		 * unlocks the use of variables like pid, zonename, etc.
14725 		 */
14726 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14727 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14728 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14729 		}
14730 
14731 		/*
14732 		 * dtrace_user allows use of syscall and profile providers.
14733 		 * If the user also has proc_owner and/or proc_zone, we
14734 		 * extend the scope to include additional visibility and
14735 		 * destructive power.
14736 		 */
14737 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14738 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14739 				state->dts_cred.dcr_visible |=
14740 				    DTRACE_CRV_ALLPROC;
14741 
14742 				state->dts_cred.dcr_action |=
14743 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14744 			}
14745 
14746 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14747 				state->dts_cred.dcr_visible |=
14748 				    DTRACE_CRV_ALLZONE;
14749 
14750 				state->dts_cred.dcr_action |=
14751 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14752 			}
14753 
14754 			/*
14755 			 * If we have all privs in whatever zone this is,
14756 			 * we can do destructive things to processes which
14757 			 * have altered credentials.
14758 			 */
14759 #ifdef illumos
14760 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14761 			    cr->cr_zone->zone_privset)) {
14762 				state->dts_cred.dcr_action |=
14763 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14764 			}
14765 #endif
14766 		}
14767 
14768 		/*
14769 		 * Holding the dtrace_kernel privilege also implies that
14770 		 * the user has the dtrace_user privilege from a visibility
14771 		 * perspective.  But without further privileges, some
14772 		 * destructive actions are not available.
14773 		 */
14774 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14775 			/*
14776 			 * Make all probes in all zones visible.  However,
14777 			 * this doesn't mean that all actions become available
14778 			 * to all zones.
14779 			 */
14780 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14781 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14782 
14783 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14784 			    DTRACE_CRA_PROC;
14785 			/*
14786 			 * Holding proc_owner means that destructive actions
14787 			 * for *this* zone are allowed.
14788 			 */
14789 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14790 				state->dts_cred.dcr_action |=
14791 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14792 
14793 			/*
14794 			 * Holding proc_zone means that destructive actions
14795 			 * for this user/group ID in all zones is allowed.
14796 			 */
14797 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14798 				state->dts_cred.dcr_action |=
14799 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14800 
14801 #ifdef illumos
14802 			/*
14803 			 * If we have all privs in whatever zone this is,
14804 			 * we can do destructive things to processes which
14805 			 * have altered credentials.
14806 			 */
14807 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14808 			    cr->cr_zone->zone_privset)) {
14809 				state->dts_cred.dcr_action |=
14810 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14811 			}
14812 #endif
14813 		}
14814 
14815 		/*
14816 		 * Holding the dtrace_proc privilege gives control over fasttrap
14817 		 * and pid providers.  We need to grant wider destructive
14818 		 * privileges in the event that the user has proc_owner and/or
14819 		 * proc_zone.
14820 		 */
14821 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14822 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14823 				state->dts_cred.dcr_action |=
14824 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14825 
14826 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14827 				state->dts_cred.dcr_action |=
14828 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14829 		}
14830 	}
14831 
14832 	return (state);
14833 }
14834 
14835 static int
14836 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14837 {
14838 	dtrace_optval_t *opt = state->dts_options, size;
14839 	processorid_t cpu = 0;
14840 	int flags = 0, rval, factor, divisor = 1;
14841 
14842 	ASSERT(MUTEX_HELD(&dtrace_lock));
14843 	ASSERT(MUTEX_HELD(&cpu_lock));
14844 	ASSERT(which < DTRACEOPT_MAX);
14845 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14846 	    (state == dtrace_anon.dta_state &&
14847 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14848 
14849 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14850 		return (0);
14851 
14852 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14853 		cpu = opt[DTRACEOPT_CPU];
14854 
14855 	if (which == DTRACEOPT_SPECSIZE)
14856 		flags |= DTRACEBUF_NOSWITCH;
14857 
14858 	if (which == DTRACEOPT_BUFSIZE) {
14859 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14860 			flags |= DTRACEBUF_RING;
14861 
14862 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14863 			flags |= DTRACEBUF_FILL;
14864 
14865 		if (state != dtrace_anon.dta_state ||
14866 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14867 			flags |= DTRACEBUF_INACTIVE;
14868 	}
14869 
14870 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14871 		/*
14872 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14873 		 * aligned, drop it down by the difference.
14874 		 */
14875 		if (size & (sizeof (uint64_t) - 1))
14876 			size -= size & (sizeof (uint64_t) - 1);
14877 
14878 		if (size < state->dts_reserve) {
14879 			/*
14880 			 * Buffers always must be large enough to accommodate
14881 			 * their prereserved space.  We return E2BIG instead
14882 			 * of ENOMEM in this case to allow for user-level
14883 			 * software to differentiate the cases.
14884 			 */
14885 			return (E2BIG);
14886 		}
14887 
14888 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14889 
14890 		if (rval != ENOMEM) {
14891 			opt[which] = size;
14892 			return (rval);
14893 		}
14894 
14895 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14896 			return (rval);
14897 
14898 		for (divisor = 2; divisor < factor; divisor <<= 1)
14899 			continue;
14900 	}
14901 
14902 	return (ENOMEM);
14903 }
14904 
14905 static int
14906 dtrace_state_buffers(dtrace_state_t *state)
14907 {
14908 	dtrace_speculation_t *spec = state->dts_speculations;
14909 	int rval, i;
14910 
14911 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14912 	    DTRACEOPT_BUFSIZE)) != 0)
14913 		return (rval);
14914 
14915 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14916 	    DTRACEOPT_AGGSIZE)) != 0)
14917 		return (rval);
14918 
14919 	for (i = 0; i < state->dts_nspeculations; i++) {
14920 		if ((rval = dtrace_state_buffer(state,
14921 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14922 			return (rval);
14923 	}
14924 
14925 	return (0);
14926 }
14927 
14928 static void
14929 dtrace_state_prereserve(dtrace_state_t *state)
14930 {
14931 	dtrace_ecb_t *ecb;
14932 	dtrace_probe_t *probe;
14933 
14934 	state->dts_reserve = 0;
14935 
14936 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14937 		return;
14938 
14939 	/*
14940 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14941 	 * prereserved space to be the space required by the END probes.
14942 	 */
14943 	probe = dtrace_probes[dtrace_probeid_end - 1];
14944 	ASSERT(probe != NULL);
14945 
14946 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14947 		if (ecb->dte_state != state)
14948 			continue;
14949 
14950 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14951 	}
14952 }
14953 
14954 static int
14955 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14956 {
14957 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14958 	dtrace_speculation_t *spec;
14959 	dtrace_buffer_t *buf;
14960 #ifdef illumos
14961 	cyc_handler_t hdlr;
14962 	cyc_time_t when;
14963 #endif
14964 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14965 	dtrace_icookie_t cookie;
14966 
14967 	mutex_enter(&cpu_lock);
14968 	mutex_enter(&dtrace_lock);
14969 
14970 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14971 		rval = EBUSY;
14972 		goto out;
14973 	}
14974 
14975 	/*
14976 	 * Before we can perform any checks, we must prime all of the
14977 	 * retained enablings that correspond to this state.
14978 	 */
14979 	dtrace_enabling_prime(state);
14980 
14981 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14982 		rval = EACCES;
14983 		goto out;
14984 	}
14985 
14986 	dtrace_state_prereserve(state);
14987 
14988 	/*
14989 	 * Now we want to do is try to allocate our speculations.
14990 	 * We do not automatically resize the number of speculations; if
14991 	 * this fails, we will fail the operation.
14992 	 */
14993 	nspec = opt[DTRACEOPT_NSPEC];
14994 	ASSERT(nspec != DTRACEOPT_UNSET);
14995 
14996 	if (nspec > INT_MAX) {
14997 		rval = ENOMEM;
14998 		goto out;
14999 	}
15000 
15001 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
15002 	    KM_NOSLEEP | KM_NORMALPRI);
15003 
15004 	if (spec == NULL) {
15005 		rval = ENOMEM;
15006 		goto out;
15007 	}
15008 
15009 	state->dts_speculations = spec;
15010 	state->dts_nspeculations = (int)nspec;
15011 
15012 	for (i = 0; i < nspec; i++) {
15013 		if ((buf = kmem_zalloc(bufsize,
15014 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15015 			rval = ENOMEM;
15016 			goto err;
15017 		}
15018 
15019 		spec[i].dtsp_buffer = buf;
15020 	}
15021 
15022 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15023 		if (dtrace_anon.dta_state == NULL) {
15024 			rval = ENOENT;
15025 			goto out;
15026 		}
15027 
15028 		if (state->dts_necbs != 0) {
15029 			rval = EALREADY;
15030 			goto out;
15031 		}
15032 
15033 		state->dts_anon = dtrace_anon_grab();
15034 		ASSERT(state->dts_anon != NULL);
15035 		state = state->dts_anon;
15036 
15037 		/*
15038 		 * We want "grabanon" to be set in the grabbed state, so we'll
15039 		 * copy that option value from the grabbing state into the
15040 		 * grabbed state.
15041 		 */
15042 		state->dts_options[DTRACEOPT_GRABANON] =
15043 		    opt[DTRACEOPT_GRABANON];
15044 
15045 		*cpu = dtrace_anon.dta_beganon;
15046 
15047 		/*
15048 		 * If the anonymous state is active (as it almost certainly
15049 		 * is if the anonymous enabling ultimately matched anything),
15050 		 * we don't allow any further option processing -- but we
15051 		 * don't return failure.
15052 		 */
15053 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15054 			goto out;
15055 	}
15056 
15057 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15058 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15059 		if (state->dts_aggregations == NULL) {
15060 			/*
15061 			 * We're not going to create an aggregation buffer
15062 			 * because we don't have any ECBs that contain
15063 			 * aggregations -- set this option to 0.
15064 			 */
15065 			opt[DTRACEOPT_AGGSIZE] = 0;
15066 		} else {
15067 			/*
15068 			 * If we have an aggregation buffer, we must also have
15069 			 * a buffer to use as scratch.
15070 			 */
15071 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15072 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15073 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15074 			}
15075 		}
15076 	}
15077 
15078 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15079 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15080 		if (!state->dts_speculates) {
15081 			/*
15082 			 * We're not going to create speculation buffers
15083 			 * because we don't have any ECBs that actually
15084 			 * speculate -- set the speculation size to 0.
15085 			 */
15086 			opt[DTRACEOPT_SPECSIZE] = 0;
15087 		}
15088 	}
15089 
15090 	/*
15091 	 * The bare minimum size for any buffer that we're actually going to
15092 	 * do anything to is sizeof (uint64_t).
15093 	 */
15094 	sz = sizeof (uint64_t);
15095 
15096 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15097 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15098 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15099 		/*
15100 		 * A buffer size has been explicitly set to 0 (or to a size
15101 		 * that will be adjusted to 0) and we need the space -- we
15102 		 * need to return failure.  We return ENOSPC to differentiate
15103 		 * it from failing to allocate a buffer due to failure to meet
15104 		 * the reserve (for which we return E2BIG).
15105 		 */
15106 		rval = ENOSPC;
15107 		goto out;
15108 	}
15109 
15110 	if ((rval = dtrace_state_buffers(state)) != 0)
15111 		goto err;
15112 
15113 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15114 		sz = dtrace_dstate_defsize;
15115 
15116 	do {
15117 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15118 
15119 		if (rval == 0)
15120 			break;
15121 
15122 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15123 			goto err;
15124 	} while (sz >>= 1);
15125 
15126 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15127 
15128 	if (rval != 0)
15129 		goto err;
15130 
15131 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15132 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15133 
15134 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15135 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15136 
15137 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15138 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15139 
15140 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15141 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15142 
15143 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15144 #ifdef illumos
15145 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15146 	hdlr.cyh_arg = state;
15147 	hdlr.cyh_level = CY_LOW_LEVEL;
15148 
15149 	when.cyt_when = 0;
15150 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15151 
15152 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15153 
15154 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15155 	hdlr.cyh_arg = state;
15156 	hdlr.cyh_level = CY_LOW_LEVEL;
15157 
15158 	when.cyt_when = 0;
15159 	when.cyt_interval = dtrace_deadman_interval;
15160 
15161 	state->dts_deadman = cyclic_add(&hdlr, &when);
15162 #else
15163 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15164 	    dtrace_state_clean, state);
15165 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15166 	    dtrace_state_deadman, state);
15167 #endif
15168 
15169 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15170 
15171 #ifdef illumos
15172 	if (state->dts_getf != 0 &&
15173 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15174 		/*
15175 		 * We don't have kernel privs but we have at least one call
15176 		 * to getf(); we need to bump our zone's count, and (if
15177 		 * this is the first enabling to have an unprivileged call
15178 		 * to getf()) we need to hook into closef().
15179 		 */
15180 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15181 
15182 		if (dtrace_getf++ == 0) {
15183 			ASSERT(dtrace_closef == NULL);
15184 			dtrace_closef = dtrace_getf_barrier;
15185 		}
15186 	}
15187 #endif
15188 
15189 	/*
15190 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15191 	 * interrupts here both to record the CPU on which we fired the BEGIN
15192 	 * probe (the data from this CPU will be processed first at user
15193 	 * level) and to manually activate the buffer for this CPU.
15194 	 */
15195 	cookie = dtrace_interrupt_disable();
15196 	*cpu = curcpu;
15197 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15198 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15199 
15200 	dtrace_probe(dtrace_probeid_begin,
15201 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15202 	dtrace_interrupt_enable(cookie);
15203 	/*
15204 	 * We may have had an exit action from a BEGIN probe; only change our
15205 	 * state to ACTIVE if we're still in WARMUP.
15206 	 */
15207 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15208 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15209 
15210 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15211 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15212 
15213 #ifdef __FreeBSD__
15214 	/*
15215 	 * We enable anonymous tracing before APs are started, so we must
15216 	 * activate buffers using the current CPU.
15217 	 */
15218 	if (state == dtrace_anon.dta_state)
15219 		for (int i = 0; i < NCPU; i++)
15220 			dtrace_buffer_activate_cpu(state, i);
15221 	else
15222 		dtrace_xcall(DTRACE_CPUALL,
15223 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15224 #else
15225 	/*
15226 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15227 	 * want each CPU to transition its principal buffer out of the
15228 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15229 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15230 	 * atomically transition from processing none of a state's ECBs to
15231 	 * processing all of them.
15232 	 */
15233 	dtrace_xcall(DTRACE_CPUALL,
15234 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15235 #endif
15236 	goto out;
15237 
15238 err:
15239 	dtrace_buffer_free(state->dts_buffer);
15240 	dtrace_buffer_free(state->dts_aggbuffer);
15241 
15242 	if ((nspec = state->dts_nspeculations) == 0) {
15243 		ASSERT(state->dts_speculations == NULL);
15244 		goto out;
15245 	}
15246 
15247 	spec = state->dts_speculations;
15248 	ASSERT(spec != NULL);
15249 
15250 	for (i = 0; i < state->dts_nspeculations; i++) {
15251 		if ((buf = spec[i].dtsp_buffer) == NULL)
15252 			break;
15253 
15254 		dtrace_buffer_free(buf);
15255 		kmem_free(buf, bufsize);
15256 	}
15257 
15258 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15259 	state->dts_nspeculations = 0;
15260 	state->dts_speculations = NULL;
15261 
15262 out:
15263 	mutex_exit(&dtrace_lock);
15264 	mutex_exit(&cpu_lock);
15265 
15266 	return (rval);
15267 }
15268 
15269 static int
15270 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15271 {
15272 	dtrace_icookie_t cookie;
15273 
15274 	ASSERT(MUTEX_HELD(&dtrace_lock));
15275 
15276 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15277 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15278 		return (EINVAL);
15279 
15280 	/*
15281 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15282 	 * to be sure that every CPU has seen it.  See below for the details
15283 	 * on why this is done.
15284 	 */
15285 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15286 	dtrace_sync();
15287 
15288 	/*
15289 	 * By this point, it is impossible for any CPU to be still processing
15290 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15291 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15292 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15293 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15294 	 * iff we're in the END probe.
15295 	 */
15296 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15297 	dtrace_sync();
15298 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15299 
15300 	/*
15301 	 * Finally, we can release the reserve and call the END probe.  We
15302 	 * disable interrupts across calling the END probe to allow us to
15303 	 * return the CPU on which we actually called the END probe.  This
15304 	 * allows user-land to be sure that this CPU's principal buffer is
15305 	 * processed last.
15306 	 */
15307 	state->dts_reserve = 0;
15308 
15309 	cookie = dtrace_interrupt_disable();
15310 	*cpu = curcpu;
15311 	dtrace_probe(dtrace_probeid_end,
15312 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15313 	dtrace_interrupt_enable(cookie);
15314 
15315 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15316 	dtrace_sync();
15317 
15318 #ifdef illumos
15319 	if (state->dts_getf != 0 &&
15320 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15321 		/*
15322 		 * We don't have kernel privs but we have at least one call
15323 		 * to getf(); we need to lower our zone's count, and (if
15324 		 * this is the last enabling to have an unprivileged call
15325 		 * to getf()) we need to clear the closef() hook.
15326 		 */
15327 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15328 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15329 		ASSERT(dtrace_getf > 0);
15330 
15331 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15332 
15333 		if (--dtrace_getf == 0)
15334 			dtrace_closef = NULL;
15335 	}
15336 #endif
15337 
15338 	return (0);
15339 }
15340 
15341 static int
15342 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15343     dtrace_optval_t val)
15344 {
15345 	ASSERT(MUTEX_HELD(&dtrace_lock));
15346 
15347 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15348 		return (EBUSY);
15349 
15350 	if (option >= DTRACEOPT_MAX)
15351 		return (EINVAL);
15352 
15353 	if (option != DTRACEOPT_CPU && val < 0)
15354 		return (EINVAL);
15355 
15356 	switch (option) {
15357 	case DTRACEOPT_DESTRUCTIVE:
15358 		if (dtrace_destructive_disallow)
15359 			return (EACCES);
15360 
15361 		state->dts_cred.dcr_destructive = 1;
15362 		break;
15363 
15364 	case DTRACEOPT_BUFSIZE:
15365 	case DTRACEOPT_DYNVARSIZE:
15366 	case DTRACEOPT_AGGSIZE:
15367 	case DTRACEOPT_SPECSIZE:
15368 	case DTRACEOPT_STRSIZE:
15369 		if (val < 0)
15370 			return (EINVAL);
15371 
15372 		if (val >= LONG_MAX) {
15373 			/*
15374 			 * If this is an otherwise negative value, set it to
15375 			 * the highest multiple of 128m less than LONG_MAX.
15376 			 * Technically, we're adjusting the size without
15377 			 * regard to the buffer resizing policy, but in fact,
15378 			 * this has no effect -- if we set the buffer size to
15379 			 * ~LONG_MAX and the buffer policy is ultimately set to
15380 			 * be "manual", the buffer allocation is guaranteed to
15381 			 * fail, if only because the allocation requires two
15382 			 * buffers.  (We set the the size to the highest
15383 			 * multiple of 128m because it ensures that the size
15384 			 * will remain a multiple of a megabyte when
15385 			 * repeatedly halved -- all the way down to 15m.)
15386 			 */
15387 			val = LONG_MAX - (1 << 27) + 1;
15388 		}
15389 	}
15390 
15391 	state->dts_options[option] = val;
15392 
15393 	return (0);
15394 }
15395 
15396 static void
15397 dtrace_state_destroy(dtrace_state_t *state)
15398 {
15399 	dtrace_ecb_t *ecb;
15400 	dtrace_vstate_t *vstate = &state->dts_vstate;
15401 #ifdef illumos
15402 	minor_t minor = getminor(state->dts_dev);
15403 #endif
15404 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15405 	dtrace_speculation_t *spec = state->dts_speculations;
15406 	int nspec = state->dts_nspeculations;
15407 	uint32_t match;
15408 
15409 	ASSERT(MUTEX_HELD(&dtrace_lock));
15410 	ASSERT(MUTEX_HELD(&cpu_lock));
15411 
15412 	/*
15413 	 * First, retract any retained enablings for this state.
15414 	 */
15415 	dtrace_enabling_retract(state);
15416 	ASSERT(state->dts_nretained == 0);
15417 
15418 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15419 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15420 		/*
15421 		 * We have managed to come into dtrace_state_destroy() on a
15422 		 * hot enabling -- almost certainly because of a disorderly
15423 		 * shutdown of a consumer.  (That is, a consumer that is
15424 		 * exiting without having called dtrace_stop().) In this case,
15425 		 * we're going to set our activity to be KILLED, and then
15426 		 * issue a sync to be sure that everyone is out of probe
15427 		 * context before we start blowing away ECBs.
15428 		 */
15429 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15430 		dtrace_sync();
15431 	}
15432 
15433 	/*
15434 	 * Release the credential hold we took in dtrace_state_create().
15435 	 */
15436 	if (state->dts_cred.dcr_cred != NULL)
15437 		crfree(state->dts_cred.dcr_cred);
15438 
15439 	/*
15440 	 * Now we can safely disable and destroy any enabled probes.  Because
15441 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15442 	 * (especially if they're all enabled), we take two passes through the
15443 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15444 	 * in the second we disable whatever is left over.
15445 	 */
15446 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15447 		for (i = 0; i < state->dts_necbs; i++) {
15448 			if ((ecb = state->dts_ecbs[i]) == NULL)
15449 				continue;
15450 
15451 			if (match && ecb->dte_probe != NULL) {
15452 				dtrace_probe_t *probe = ecb->dte_probe;
15453 				dtrace_provider_t *prov = probe->dtpr_provider;
15454 
15455 				if (!(prov->dtpv_priv.dtpp_flags & match))
15456 					continue;
15457 			}
15458 
15459 			dtrace_ecb_disable(ecb);
15460 			dtrace_ecb_destroy(ecb);
15461 		}
15462 
15463 		if (!match)
15464 			break;
15465 	}
15466 
15467 	/*
15468 	 * Before we free the buffers, perform one more sync to assure that
15469 	 * every CPU is out of probe context.
15470 	 */
15471 	dtrace_sync();
15472 
15473 	dtrace_buffer_free(state->dts_buffer);
15474 	dtrace_buffer_free(state->dts_aggbuffer);
15475 
15476 	for (i = 0; i < nspec; i++)
15477 		dtrace_buffer_free(spec[i].dtsp_buffer);
15478 
15479 #ifdef illumos
15480 	if (state->dts_cleaner != CYCLIC_NONE)
15481 		cyclic_remove(state->dts_cleaner);
15482 
15483 	if (state->dts_deadman != CYCLIC_NONE)
15484 		cyclic_remove(state->dts_deadman);
15485 #else
15486 	callout_stop(&state->dts_cleaner);
15487 	callout_drain(&state->dts_cleaner);
15488 	callout_stop(&state->dts_deadman);
15489 	callout_drain(&state->dts_deadman);
15490 #endif
15491 
15492 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15493 	dtrace_vstate_fini(vstate);
15494 	if (state->dts_ecbs != NULL)
15495 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15496 
15497 	if (state->dts_aggregations != NULL) {
15498 #ifdef DEBUG
15499 		for (i = 0; i < state->dts_naggregations; i++)
15500 			ASSERT(state->dts_aggregations[i] == NULL);
15501 #endif
15502 		ASSERT(state->dts_naggregations > 0);
15503 		kmem_free(state->dts_aggregations,
15504 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15505 	}
15506 
15507 	kmem_free(state->dts_buffer, bufsize);
15508 	kmem_free(state->dts_aggbuffer, bufsize);
15509 
15510 	for (i = 0; i < nspec; i++)
15511 		kmem_free(spec[i].dtsp_buffer, bufsize);
15512 
15513 	if (spec != NULL)
15514 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15515 
15516 	dtrace_format_destroy(state);
15517 
15518 	if (state->dts_aggid_arena != NULL) {
15519 #ifdef illumos
15520 		vmem_destroy(state->dts_aggid_arena);
15521 #else
15522 		delete_unrhdr(state->dts_aggid_arena);
15523 #endif
15524 		state->dts_aggid_arena = NULL;
15525 	}
15526 #ifdef illumos
15527 	ddi_soft_state_free(dtrace_softstate, minor);
15528 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15529 #endif
15530 }
15531 
15532 /*
15533  * DTrace Anonymous Enabling Functions
15534  */
15535 static dtrace_state_t *
15536 dtrace_anon_grab(void)
15537 {
15538 	dtrace_state_t *state;
15539 
15540 	ASSERT(MUTEX_HELD(&dtrace_lock));
15541 
15542 	if ((state = dtrace_anon.dta_state) == NULL) {
15543 		ASSERT(dtrace_anon.dta_enabling == NULL);
15544 		return (NULL);
15545 	}
15546 
15547 	ASSERT(dtrace_anon.dta_enabling != NULL);
15548 	ASSERT(dtrace_retained != NULL);
15549 
15550 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15551 	dtrace_anon.dta_enabling = NULL;
15552 	dtrace_anon.dta_state = NULL;
15553 
15554 	return (state);
15555 }
15556 
15557 static void
15558 dtrace_anon_property(void)
15559 {
15560 	int i, rv;
15561 	dtrace_state_t *state;
15562 	dof_hdr_t *dof;
15563 	char c[32];		/* enough for "dof-data-" + digits */
15564 
15565 	ASSERT(MUTEX_HELD(&dtrace_lock));
15566 	ASSERT(MUTEX_HELD(&cpu_lock));
15567 
15568 	for (i = 0; ; i++) {
15569 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15570 
15571 		dtrace_err_verbose = 1;
15572 
15573 		if ((dof = dtrace_dof_property(c)) == NULL) {
15574 			dtrace_err_verbose = 0;
15575 			break;
15576 		}
15577 
15578 #ifdef illumos
15579 		/*
15580 		 * We want to create anonymous state, so we need to transition
15581 		 * the kernel debugger to indicate that DTrace is active.  If
15582 		 * this fails (e.g. because the debugger has modified text in
15583 		 * some way), we won't continue with the processing.
15584 		 */
15585 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15586 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15587 			    "enabling ignored.");
15588 			dtrace_dof_destroy(dof);
15589 			break;
15590 		}
15591 #endif
15592 
15593 		/*
15594 		 * If we haven't allocated an anonymous state, we'll do so now.
15595 		 */
15596 		if ((state = dtrace_anon.dta_state) == NULL) {
15597 			state = dtrace_state_create(NULL, NULL);
15598 			dtrace_anon.dta_state = state;
15599 
15600 			if (state == NULL) {
15601 				/*
15602 				 * This basically shouldn't happen:  the only
15603 				 * failure mode from dtrace_state_create() is a
15604 				 * failure of ddi_soft_state_zalloc() that
15605 				 * itself should never happen.  Still, the
15606 				 * interface allows for a failure mode, and
15607 				 * we want to fail as gracefully as possible:
15608 				 * we'll emit an error message and cease
15609 				 * processing anonymous state in this case.
15610 				 */
15611 				cmn_err(CE_WARN, "failed to create "
15612 				    "anonymous state");
15613 				dtrace_dof_destroy(dof);
15614 				break;
15615 			}
15616 		}
15617 
15618 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15619 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15620 
15621 		if (rv == 0)
15622 			rv = dtrace_dof_options(dof, state);
15623 
15624 		dtrace_err_verbose = 0;
15625 		dtrace_dof_destroy(dof);
15626 
15627 		if (rv != 0) {
15628 			/*
15629 			 * This is malformed DOF; chuck any anonymous state
15630 			 * that we created.
15631 			 */
15632 			ASSERT(dtrace_anon.dta_enabling == NULL);
15633 			dtrace_state_destroy(state);
15634 			dtrace_anon.dta_state = NULL;
15635 			break;
15636 		}
15637 
15638 		ASSERT(dtrace_anon.dta_enabling != NULL);
15639 	}
15640 
15641 	if (dtrace_anon.dta_enabling != NULL) {
15642 		int rval;
15643 
15644 		/*
15645 		 * dtrace_enabling_retain() can only fail because we are
15646 		 * trying to retain more enablings than are allowed -- but
15647 		 * we only have one anonymous enabling, and we are guaranteed
15648 		 * to be allowed at least one retained enabling; we assert
15649 		 * that dtrace_enabling_retain() returns success.
15650 		 */
15651 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15652 		ASSERT(rval == 0);
15653 
15654 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15655 	}
15656 }
15657 
15658 /*
15659  * DTrace Helper Functions
15660  */
15661 static void
15662 dtrace_helper_trace(dtrace_helper_action_t *helper,
15663     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15664 {
15665 	uint32_t size, next, nnext, i;
15666 	dtrace_helptrace_t *ent, *buffer;
15667 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15668 
15669 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15670 		return;
15671 
15672 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15673 
15674 	/*
15675 	 * What would a tracing framework be without its own tracing
15676 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15677 	 */
15678 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15679 	    sizeof (uint64_t) - sizeof (uint64_t);
15680 
15681 	/*
15682 	 * Iterate until we can allocate a slot in the trace buffer.
15683 	 */
15684 	do {
15685 		next = dtrace_helptrace_next;
15686 
15687 		if (next + size < dtrace_helptrace_bufsize) {
15688 			nnext = next + size;
15689 		} else {
15690 			nnext = size;
15691 		}
15692 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15693 
15694 	/*
15695 	 * We have our slot; fill it in.
15696 	 */
15697 	if (nnext == size) {
15698 		dtrace_helptrace_wrapped++;
15699 		next = 0;
15700 	}
15701 
15702 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15703 	ent->dtht_helper = helper;
15704 	ent->dtht_where = where;
15705 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15706 
15707 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15708 	    mstate->dtms_fltoffs : -1;
15709 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15710 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15711 
15712 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15713 		dtrace_statvar_t *svar;
15714 
15715 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15716 			continue;
15717 
15718 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15719 		ent->dtht_locals[i] =
15720 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15721 	}
15722 }
15723 
15724 static uint64_t
15725 dtrace_helper(int which, dtrace_mstate_t *mstate,
15726     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15727 {
15728 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15729 	uint64_t sarg0 = mstate->dtms_arg[0];
15730 	uint64_t sarg1 = mstate->dtms_arg[1];
15731 	uint64_t rval = 0;
15732 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15733 	dtrace_helper_action_t *helper;
15734 	dtrace_vstate_t *vstate;
15735 	dtrace_difo_t *pred;
15736 	int i, trace = dtrace_helptrace_buffer != NULL;
15737 
15738 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15739 
15740 	if (helpers == NULL)
15741 		return (0);
15742 
15743 	if ((helper = helpers->dthps_actions[which]) == NULL)
15744 		return (0);
15745 
15746 	vstate = &helpers->dthps_vstate;
15747 	mstate->dtms_arg[0] = arg0;
15748 	mstate->dtms_arg[1] = arg1;
15749 
15750 	/*
15751 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15752 	 * we'll call the corresponding actions.  Note that the below calls
15753 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15754 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15755 	 * the stored DIF offset with its own (which is the desired behavior).
15756 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15757 	 * from machine state; this is okay, too.
15758 	 */
15759 	for (; helper != NULL; helper = helper->dtha_next) {
15760 		if ((pred = helper->dtha_predicate) != NULL) {
15761 			if (trace)
15762 				dtrace_helper_trace(helper, mstate, vstate, 0);
15763 
15764 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15765 				goto next;
15766 
15767 			if (*flags & CPU_DTRACE_FAULT)
15768 				goto err;
15769 		}
15770 
15771 		for (i = 0; i < helper->dtha_nactions; i++) {
15772 			if (trace)
15773 				dtrace_helper_trace(helper,
15774 				    mstate, vstate, i + 1);
15775 
15776 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15777 			    mstate, vstate, state);
15778 
15779 			if (*flags & CPU_DTRACE_FAULT)
15780 				goto err;
15781 		}
15782 
15783 next:
15784 		if (trace)
15785 			dtrace_helper_trace(helper, mstate, vstate,
15786 			    DTRACE_HELPTRACE_NEXT);
15787 	}
15788 
15789 	if (trace)
15790 		dtrace_helper_trace(helper, mstate, vstate,
15791 		    DTRACE_HELPTRACE_DONE);
15792 
15793 	/*
15794 	 * Restore the arg0 that we saved upon entry.
15795 	 */
15796 	mstate->dtms_arg[0] = sarg0;
15797 	mstate->dtms_arg[1] = sarg1;
15798 
15799 	return (rval);
15800 
15801 err:
15802 	if (trace)
15803 		dtrace_helper_trace(helper, mstate, vstate,
15804 		    DTRACE_HELPTRACE_ERR);
15805 
15806 	/*
15807 	 * Restore the arg0 that we saved upon entry.
15808 	 */
15809 	mstate->dtms_arg[0] = sarg0;
15810 	mstate->dtms_arg[1] = sarg1;
15811 
15812 	return (0);
15813 }
15814 
15815 static void
15816 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15817     dtrace_vstate_t *vstate)
15818 {
15819 	int i;
15820 
15821 	if (helper->dtha_predicate != NULL)
15822 		dtrace_difo_release(helper->dtha_predicate, vstate);
15823 
15824 	for (i = 0; i < helper->dtha_nactions; i++) {
15825 		ASSERT(helper->dtha_actions[i] != NULL);
15826 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15827 	}
15828 
15829 	kmem_free(helper->dtha_actions,
15830 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15831 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15832 }
15833 
15834 static int
15835 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15836 {
15837 	proc_t *p = curproc;
15838 	dtrace_vstate_t *vstate;
15839 	int i;
15840 
15841 	if (help == NULL)
15842 		help = p->p_dtrace_helpers;
15843 
15844 	ASSERT(MUTEX_HELD(&dtrace_lock));
15845 
15846 	if (help == NULL || gen > help->dthps_generation)
15847 		return (EINVAL);
15848 
15849 	vstate = &help->dthps_vstate;
15850 
15851 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15852 		dtrace_helper_action_t *last = NULL, *h, *next;
15853 
15854 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15855 			next = h->dtha_next;
15856 
15857 			if (h->dtha_generation == gen) {
15858 				if (last != NULL) {
15859 					last->dtha_next = next;
15860 				} else {
15861 					help->dthps_actions[i] = next;
15862 				}
15863 
15864 				dtrace_helper_action_destroy(h, vstate);
15865 			} else {
15866 				last = h;
15867 			}
15868 		}
15869 	}
15870 
15871 	/*
15872 	 * Interate until we've cleared out all helper providers with the
15873 	 * given generation number.
15874 	 */
15875 	for (;;) {
15876 		dtrace_helper_provider_t *prov;
15877 
15878 		/*
15879 		 * Look for a helper provider with the right generation. We
15880 		 * have to start back at the beginning of the list each time
15881 		 * because we drop dtrace_lock. It's unlikely that we'll make
15882 		 * more than two passes.
15883 		 */
15884 		for (i = 0; i < help->dthps_nprovs; i++) {
15885 			prov = help->dthps_provs[i];
15886 
15887 			if (prov->dthp_generation == gen)
15888 				break;
15889 		}
15890 
15891 		/*
15892 		 * If there were no matches, we're done.
15893 		 */
15894 		if (i == help->dthps_nprovs)
15895 			break;
15896 
15897 		/*
15898 		 * Move the last helper provider into this slot.
15899 		 */
15900 		help->dthps_nprovs--;
15901 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15902 		help->dthps_provs[help->dthps_nprovs] = NULL;
15903 
15904 		mutex_exit(&dtrace_lock);
15905 
15906 		/*
15907 		 * If we have a meta provider, remove this helper provider.
15908 		 */
15909 		mutex_enter(&dtrace_meta_lock);
15910 		if (dtrace_meta_pid != NULL) {
15911 			ASSERT(dtrace_deferred_pid == NULL);
15912 			dtrace_helper_provider_remove(&prov->dthp_prov,
15913 			    p->p_pid);
15914 		}
15915 		mutex_exit(&dtrace_meta_lock);
15916 
15917 		dtrace_helper_provider_destroy(prov);
15918 
15919 		mutex_enter(&dtrace_lock);
15920 	}
15921 
15922 	return (0);
15923 }
15924 
15925 static int
15926 dtrace_helper_validate(dtrace_helper_action_t *helper)
15927 {
15928 	int err = 0, i;
15929 	dtrace_difo_t *dp;
15930 
15931 	if ((dp = helper->dtha_predicate) != NULL)
15932 		err += dtrace_difo_validate_helper(dp);
15933 
15934 	for (i = 0; i < helper->dtha_nactions; i++)
15935 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15936 
15937 	return (err == 0);
15938 }
15939 
15940 static int
15941 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15942     dtrace_helpers_t *help)
15943 {
15944 	dtrace_helper_action_t *helper, *last;
15945 	dtrace_actdesc_t *act;
15946 	dtrace_vstate_t *vstate;
15947 	dtrace_predicate_t *pred;
15948 	int count = 0, nactions = 0, i;
15949 
15950 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15951 		return (EINVAL);
15952 
15953 	last = help->dthps_actions[which];
15954 	vstate = &help->dthps_vstate;
15955 
15956 	for (count = 0; last != NULL; last = last->dtha_next) {
15957 		count++;
15958 		if (last->dtha_next == NULL)
15959 			break;
15960 	}
15961 
15962 	/*
15963 	 * If we already have dtrace_helper_actions_max helper actions for this
15964 	 * helper action type, we'll refuse to add a new one.
15965 	 */
15966 	if (count >= dtrace_helper_actions_max)
15967 		return (ENOSPC);
15968 
15969 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15970 	helper->dtha_generation = help->dthps_generation;
15971 
15972 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15973 		ASSERT(pred->dtp_difo != NULL);
15974 		dtrace_difo_hold(pred->dtp_difo);
15975 		helper->dtha_predicate = pred->dtp_difo;
15976 	}
15977 
15978 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15979 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15980 			goto err;
15981 
15982 		if (act->dtad_difo == NULL)
15983 			goto err;
15984 
15985 		nactions++;
15986 	}
15987 
15988 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15989 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15990 
15991 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15992 		dtrace_difo_hold(act->dtad_difo);
15993 		helper->dtha_actions[i++] = act->dtad_difo;
15994 	}
15995 
15996 	if (!dtrace_helper_validate(helper))
15997 		goto err;
15998 
15999 	if (last == NULL) {
16000 		help->dthps_actions[which] = helper;
16001 	} else {
16002 		last->dtha_next = helper;
16003 	}
16004 
16005 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16006 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16007 		dtrace_helptrace_next = 0;
16008 	}
16009 
16010 	return (0);
16011 err:
16012 	dtrace_helper_action_destroy(helper, vstate);
16013 	return (EINVAL);
16014 }
16015 
16016 static void
16017 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16018     dof_helper_t *dofhp)
16019 {
16020 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16021 
16022 	mutex_enter(&dtrace_meta_lock);
16023 	mutex_enter(&dtrace_lock);
16024 
16025 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16026 		/*
16027 		 * If the dtrace module is loaded but not attached, or if
16028 		 * there aren't isn't a meta provider registered to deal with
16029 		 * these provider descriptions, we need to postpone creating
16030 		 * the actual providers until later.
16031 		 */
16032 
16033 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16034 		    dtrace_deferred_pid != help) {
16035 			help->dthps_deferred = 1;
16036 			help->dthps_pid = p->p_pid;
16037 			help->dthps_next = dtrace_deferred_pid;
16038 			help->dthps_prev = NULL;
16039 			if (dtrace_deferred_pid != NULL)
16040 				dtrace_deferred_pid->dthps_prev = help;
16041 			dtrace_deferred_pid = help;
16042 		}
16043 
16044 		mutex_exit(&dtrace_lock);
16045 
16046 	} else if (dofhp != NULL) {
16047 		/*
16048 		 * If the dtrace module is loaded and we have a particular
16049 		 * helper provider description, pass that off to the
16050 		 * meta provider.
16051 		 */
16052 
16053 		mutex_exit(&dtrace_lock);
16054 
16055 		dtrace_helper_provide(dofhp, p->p_pid);
16056 
16057 	} else {
16058 		/*
16059 		 * Otherwise, just pass all the helper provider descriptions
16060 		 * off to the meta provider.
16061 		 */
16062 
16063 		int i;
16064 		mutex_exit(&dtrace_lock);
16065 
16066 		for (i = 0; i < help->dthps_nprovs; i++) {
16067 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16068 			    p->p_pid);
16069 		}
16070 	}
16071 
16072 	mutex_exit(&dtrace_meta_lock);
16073 }
16074 
16075 static int
16076 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16077 {
16078 	dtrace_helper_provider_t *hprov, **tmp_provs;
16079 	uint_t tmp_maxprovs, i;
16080 
16081 	ASSERT(MUTEX_HELD(&dtrace_lock));
16082 	ASSERT(help != NULL);
16083 
16084 	/*
16085 	 * If we already have dtrace_helper_providers_max helper providers,
16086 	 * we're refuse to add a new one.
16087 	 */
16088 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16089 		return (ENOSPC);
16090 
16091 	/*
16092 	 * Check to make sure this isn't a duplicate.
16093 	 */
16094 	for (i = 0; i < help->dthps_nprovs; i++) {
16095 		if (dofhp->dofhp_addr ==
16096 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16097 			return (EALREADY);
16098 	}
16099 
16100 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16101 	hprov->dthp_prov = *dofhp;
16102 	hprov->dthp_ref = 1;
16103 	hprov->dthp_generation = gen;
16104 
16105 	/*
16106 	 * Allocate a bigger table for helper providers if it's already full.
16107 	 */
16108 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16109 		tmp_maxprovs = help->dthps_maxprovs;
16110 		tmp_provs = help->dthps_provs;
16111 
16112 		if (help->dthps_maxprovs == 0)
16113 			help->dthps_maxprovs = 2;
16114 		else
16115 			help->dthps_maxprovs *= 2;
16116 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16117 			help->dthps_maxprovs = dtrace_helper_providers_max;
16118 
16119 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16120 
16121 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16122 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16123 
16124 		if (tmp_provs != NULL) {
16125 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16126 			    sizeof (dtrace_helper_provider_t *));
16127 			kmem_free(tmp_provs, tmp_maxprovs *
16128 			    sizeof (dtrace_helper_provider_t *));
16129 		}
16130 	}
16131 
16132 	help->dthps_provs[help->dthps_nprovs] = hprov;
16133 	help->dthps_nprovs++;
16134 
16135 	return (0);
16136 }
16137 
16138 static void
16139 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16140 {
16141 	mutex_enter(&dtrace_lock);
16142 
16143 	if (--hprov->dthp_ref == 0) {
16144 		dof_hdr_t *dof;
16145 		mutex_exit(&dtrace_lock);
16146 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16147 		dtrace_dof_destroy(dof);
16148 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16149 	} else {
16150 		mutex_exit(&dtrace_lock);
16151 	}
16152 }
16153 
16154 static int
16155 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16156 {
16157 	uintptr_t daddr = (uintptr_t)dof;
16158 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16159 	dof_provider_t *provider;
16160 	dof_probe_t *probe;
16161 	uint8_t *arg;
16162 	char *strtab, *typestr;
16163 	dof_stridx_t typeidx;
16164 	size_t typesz;
16165 	uint_t nprobes, j, k;
16166 
16167 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16168 
16169 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16170 		dtrace_dof_error(dof, "misaligned section offset");
16171 		return (-1);
16172 	}
16173 
16174 	/*
16175 	 * The section needs to be large enough to contain the DOF provider
16176 	 * structure appropriate for the given version.
16177 	 */
16178 	if (sec->dofs_size <
16179 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16180 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16181 	    sizeof (dof_provider_t))) {
16182 		dtrace_dof_error(dof, "provider section too small");
16183 		return (-1);
16184 	}
16185 
16186 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16187 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16188 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16189 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16190 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16191 
16192 	if (str_sec == NULL || prb_sec == NULL ||
16193 	    arg_sec == NULL || off_sec == NULL)
16194 		return (-1);
16195 
16196 	enoff_sec = NULL;
16197 
16198 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16199 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16200 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16201 	    provider->dofpv_prenoffs)) == NULL)
16202 		return (-1);
16203 
16204 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16205 
16206 	if (provider->dofpv_name >= str_sec->dofs_size ||
16207 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16208 		dtrace_dof_error(dof, "invalid provider name");
16209 		return (-1);
16210 	}
16211 
16212 	if (prb_sec->dofs_entsize == 0 ||
16213 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16214 		dtrace_dof_error(dof, "invalid entry size");
16215 		return (-1);
16216 	}
16217 
16218 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16219 		dtrace_dof_error(dof, "misaligned entry size");
16220 		return (-1);
16221 	}
16222 
16223 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16224 		dtrace_dof_error(dof, "invalid entry size");
16225 		return (-1);
16226 	}
16227 
16228 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16229 		dtrace_dof_error(dof, "misaligned section offset");
16230 		return (-1);
16231 	}
16232 
16233 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16234 		dtrace_dof_error(dof, "invalid entry size");
16235 		return (-1);
16236 	}
16237 
16238 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16239 
16240 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16241 
16242 	/*
16243 	 * Take a pass through the probes to check for errors.
16244 	 */
16245 	for (j = 0; j < nprobes; j++) {
16246 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16247 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16248 
16249 		if (probe->dofpr_func >= str_sec->dofs_size) {
16250 			dtrace_dof_error(dof, "invalid function name");
16251 			return (-1);
16252 		}
16253 
16254 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16255 			dtrace_dof_error(dof, "function name too long");
16256 			/*
16257 			 * Keep going if the function name is too long.
16258 			 * Unlike provider and probe names, we cannot reasonably
16259 			 * impose restrictions on function names, since they're
16260 			 * a property of the code being instrumented. We will
16261 			 * skip this probe in dtrace_helper_provide_one().
16262 			 */
16263 		}
16264 
16265 		if (probe->dofpr_name >= str_sec->dofs_size ||
16266 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16267 			dtrace_dof_error(dof, "invalid probe name");
16268 			return (-1);
16269 		}
16270 
16271 		/*
16272 		 * The offset count must not wrap the index, and the offsets
16273 		 * must also not overflow the section's data.
16274 		 */
16275 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16276 		    probe->dofpr_offidx ||
16277 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16278 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16279 			dtrace_dof_error(dof, "invalid probe offset");
16280 			return (-1);
16281 		}
16282 
16283 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16284 			/*
16285 			 * If there's no is-enabled offset section, make sure
16286 			 * there aren't any is-enabled offsets. Otherwise
16287 			 * perform the same checks as for probe offsets
16288 			 * (immediately above).
16289 			 */
16290 			if (enoff_sec == NULL) {
16291 				if (probe->dofpr_enoffidx != 0 ||
16292 				    probe->dofpr_nenoffs != 0) {
16293 					dtrace_dof_error(dof, "is-enabled "
16294 					    "offsets with null section");
16295 					return (-1);
16296 				}
16297 			} else if (probe->dofpr_enoffidx +
16298 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16299 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16300 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16301 				dtrace_dof_error(dof, "invalid is-enabled "
16302 				    "offset");
16303 				return (-1);
16304 			}
16305 
16306 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16307 				dtrace_dof_error(dof, "zero probe and "
16308 				    "is-enabled offsets");
16309 				return (-1);
16310 			}
16311 		} else if (probe->dofpr_noffs == 0) {
16312 			dtrace_dof_error(dof, "zero probe offsets");
16313 			return (-1);
16314 		}
16315 
16316 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16317 		    probe->dofpr_argidx ||
16318 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16319 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16320 			dtrace_dof_error(dof, "invalid args");
16321 			return (-1);
16322 		}
16323 
16324 		typeidx = probe->dofpr_nargv;
16325 		typestr = strtab + probe->dofpr_nargv;
16326 		for (k = 0; k < probe->dofpr_nargc; k++) {
16327 			if (typeidx >= str_sec->dofs_size) {
16328 				dtrace_dof_error(dof, "bad "
16329 				    "native argument type");
16330 				return (-1);
16331 			}
16332 
16333 			typesz = strlen(typestr) + 1;
16334 			if (typesz > DTRACE_ARGTYPELEN) {
16335 				dtrace_dof_error(dof, "native "
16336 				    "argument type too long");
16337 				return (-1);
16338 			}
16339 			typeidx += typesz;
16340 			typestr += typesz;
16341 		}
16342 
16343 		typeidx = probe->dofpr_xargv;
16344 		typestr = strtab + probe->dofpr_xargv;
16345 		for (k = 0; k < probe->dofpr_xargc; k++) {
16346 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16347 				dtrace_dof_error(dof, "bad "
16348 				    "native argument index");
16349 				return (-1);
16350 			}
16351 
16352 			if (typeidx >= str_sec->dofs_size) {
16353 				dtrace_dof_error(dof, "bad "
16354 				    "translated argument type");
16355 				return (-1);
16356 			}
16357 
16358 			typesz = strlen(typestr) + 1;
16359 			if (typesz > DTRACE_ARGTYPELEN) {
16360 				dtrace_dof_error(dof, "translated argument "
16361 				    "type too long");
16362 				return (-1);
16363 			}
16364 
16365 			typeidx += typesz;
16366 			typestr += typesz;
16367 		}
16368 	}
16369 
16370 	return (0);
16371 }
16372 
16373 static int
16374 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16375 {
16376 	dtrace_helpers_t *help;
16377 	dtrace_vstate_t *vstate;
16378 	dtrace_enabling_t *enab = NULL;
16379 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16380 	uintptr_t daddr = (uintptr_t)dof;
16381 
16382 	ASSERT(MUTEX_HELD(&dtrace_lock));
16383 
16384 	if ((help = p->p_dtrace_helpers) == NULL)
16385 		help = dtrace_helpers_create(p);
16386 
16387 	vstate = &help->dthps_vstate;
16388 
16389 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16390 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16391 		dtrace_dof_destroy(dof);
16392 		return (rv);
16393 	}
16394 
16395 	/*
16396 	 * Look for helper providers and validate their descriptions.
16397 	 */
16398 	for (i = 0; i < dof->dofh_secnum; i++) {
16399 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16400 		    dof->dofh_secoff + i * dof->dofh_secsize);
16401 
16402 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16403 			continue;
16404 
16405 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16406 			dtrace_enabling_destroy(enab);
16407 			dtrace_dof_destroy(dof);
16408 			return (-1);
16409 		}
16410 
16411 		nprovs++;
16412 	}
16413 
16414 	/*
16415 	 * Now we need to walk through the ECB descriptions in the enabling.
16416 	 */
16417 	for (i = 0; i < enab->dten_ndesc; i++) {
16418 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16419 		dtrace_probedesc_t *desc = &ep->dted_probe;
16420 
16421 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16422 			continue;
16423 
16424 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16425 			continue;
16426 
16427 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16428 			continue;
16429 
16430 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16431 		    ep, help)) != 0) {
16432 			/*
16433 			 * Adding this helper action failed -- we are now going
16434 			 * to rip out the entire generation and return failure.
16435 			 */
16436 			(void) dtrace_helper_destroygen(help,
16437 			    help->dthps_generation);
16438 			dtrace_enabling_destroy(enab);
16439 			dtrace_dof_destroy(dof);
16440 			return (-1);
16441 		}
16442 
16443 		nhelpers++;
16444 	}
16445 
16446 	if (nhelpers < enab->dten_ndesc)
16447 		dtrace_dof_error(dof, "unmatched helpers");
16448 
16449 	gen = help->dthps_generation++;
16450 	dtrace_enabling_destroy(enab);
16451 
16452 	if (nprovs > 0) {
16453 		/*
16454 		 * Now that this is in-kernel, we change the sense of the
16455 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16456 		 * and dofhp_addr denotes the address at user-level.
16457 		 */
16458 		dhp->dofhp_addr = dhp->dofhp_dof;
16459 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16460 
16461 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16462 			mutex_exit(&dtrace_lock);
16463 			dtrace_helper_provider_register(p, help, dhp);
16464 			mutex_enter(&dtrace_lock);
16465 
16466 			destroy = 0;
16467 		}
16468 	}
16469 
16470 	if (destroy)
16471 		dtrace_dof_destroy(dof);
16472 
16473 	return (gen);
16474 }
16475 
16476 static dtrace_helpers_t *
16477 dtrace_helpers_create(proc_t *p)
16478 {
16479 	dtrace_helpers_t *help;
16480 
16481 	ASSERT(MUTEX_HELD(&dtrace_lock));
16482 	ASSERT(p->p_dtrace_helpers == NULL);
16483 
16484 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16485 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16486 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16487 
16488 	p->p_dtrace_helpers = help;
16489 	dtrace_helpers++;
16490 
16491 	return (help);
16492 }
16493 
16494 #ifdef illumos
16495 static
16496 #endif
16497 void
16498 dtrace_helpers_destroy(proc_t *p)
16499 {
16500 	dtrace_helpers_t *help;
16501 	dtrace_vstate_t *vstate;
16502 #ifdef illumos
16503 	proc_t *p = curproc;
16504 #endif
16505 	int i;
16506 
16507 	mutex_enter(&dtrace_lock);
16508 
16509 	ASSERT(p->p_dtrace_helpers != NULL);
16510 	ASSERT(dtrace_helpers > 0);
16511 
16512 	help = p->p_dtrace_helpers;
16513 	vstate = &help->dthps_vstate;
16514 
16515 	/*
16516 	 * We're now going to lose the help from this process.
16517 	 */
16518 	p->p_dtrace_helpers = NULL;
16519 	dtrace_sync();
16520 
16521 	/*
16522 	 * Destory the helper actions.
16523 	 */
16524 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16525 		dtrace_helper_action_t *h, *next;
16526 
16527 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16528 			next = h->dtha_next;
16529 			dtrace_helper_action_destroy(h, vstate);
16530 			h = next;
16531 		}
16532 	}
16533 
16534 	mutex_exit(&dtrace_lock);
16535 
16536 	/*
16537 	 * Destroy the helper providers.
16538 	 */
16539 	if (help->dthps_maxprovs > 0) {
16540 		mutex_enter(&dtrace_meta_lock);
16541 		if (dtrace_meta_pid != NULL) {
16542 			ASSERT(dtrace_deferred_pid == NULL);
16543 
16544 			for (i = 0; i < help->dthps_nprovs; i++) {
16545 				dtrace_helper_provider_remove(
16546 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16547 			}
16548 		} else {
16549 			mutex_enter(&dtrace_lock);
16550 			ASSERT(help->dthps_deferred == 0 ||
16551 			    help->dthps_next != NULL ||
16552 			    help->dthps_prev != NULL ||
16553 			    help == dtrace_deferred_pid);
16554 
16555 			/*
16556 			 * Remove the helper from the deferred list.
16557 			 */
16558 			if (help->dthps_next != NULL)
16559 				help->dthps_next->dthps_prev = help->dthps_prev;
16560 			if (help->dthps_prev != NULL)
16561 				help->dthps_prev->dthps_next = help->dthps_next;
16562 			if (dtrace_deferred_pid == help) {
16563 				dtrace_deferred_pid = help->dthps_next;
16564 				ASSERT(help->dthps_prev == NULL);
16565 			}
16566 
16567 			mutex_exit(&dtrace_lock);
16568 		}
16569 
16570 		mutex_exit(&dtrace_meta_lock);
16571 
16572 		for (i = 0; i < help->dthps_nprovs; i++) {
16573 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16574 		}
16575 
16576 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16577 		    sizeof (dtrace_helper_provider_t *));
16578 	}
16579 
16580 	mutex_enter(&dtrace_lock);
16581 
16582 	dtrace_vstate_fini(&help->dthps_vstate);
16583 	kmem_free(help->dthps_actions,
16584 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16585 	kmem_free(help, sizeof (dtrace_helpers_t));
16586 
16587 	--dtrace_helpers;
16588 	mutex_exit(&dtrace_lock);
16589 }
16590 
16591 #ifdef illumos
16592 static
16593 #endif
16594 void
16595 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16596 {
16597 	dtrace_helpers_t *help, *newhelp;
16598 	dtrace_helper_action_t *helper, *new, *last;
16599 	dtrace_difo_t *dp;
16600 	dtrace_vstate_t *vstate;
16601 	int i, j, sz, hasprovs = 0;
16602 
16603 	mutex_enter(&dtrace_lock);
16604 	ASSERT(from->p_dtrace_helpers != NULL);
16605 	ASSERT(dtrace_helpers > 0);
16606 
16607 	help = from->p_dtrace_helpers;
16608 	newhelp = dtrace_helpers_create(to);
16609 	ASSERT(to->p_dtrace_helpers != NULL);
16610 
16611 	newhelp->dthps_generation = help->dthps_generation;
16612 	vstate = &newhelp->dthps_vstate;
16613 
16614 	/*
16615 	 * Duplicate the helper actions.
16616 	 */
16617 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16618 		if ((helper = help->dthps_actions[i]) == NULL)
16619 			continue;
16620 
16621 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16622 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16623 			    KM_SLEEP);
16624 			new->dtha_generation = helper->dtha_generation;
16625 
16626 			if ((dp = helper->dtha_predicate) != NULL) {
16627 				dp = dtrace_difo_duplicate(dp, vstate);
16628 				new->dtha_predicate = dp;
16629 			}
16630 
16631 			new->dtha_nactions = helper->dtha_nactions;
16632 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16633 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16634 
16635 			for (j = 0; j < new->dtha_nactions; j++) {
16636 				dtrace_difo_t *dp = helper->dtha_actions[j];
16637 
16638 				ASSERT(dp != NULL);
16639 				dp = dtrace_difo_duplicate(dp, vstate);
16640 				new->dtha_actions[j] = dp;
16641 			}
16642 
16643 			if (last != NULL) {
16644 				last->dtha_next = new;
16645 			} else {
16646 				newhelp->dthps_actions[i] = new;
16647 			}
16648 
16649 			last = new;
16650 		}
16651 	}
16652 
16653 	/*
16654 	 * Duplicate the helper providers and register them with the
16655 	 * DTrace framework.
16656 	 */
16657 	if (help->dthps_nprovs > 0) {
16658 		newhelp->dthps_nprovs = help->dthps_nprovs;
16659 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16660 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16661 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16662 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16663 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16664 			newhelp->dthps_provs[i]->dthp_ref++;
16665 		}
16666 
16667 		hasprovs = 1;
16668 	}
16669 
16670 	mutex_exit(&dtrace_lock);
16671 
16672 	if (hasprovs)
16673 		dtrace_helper_provider_register(to, newhelp, NULL);
16674 }
16675 
16676 /*
16677  * DTrace Hook Functions
16678  */
16679 static void
16680 dtrace_module_loaded(modctl_t *ctl)
16681 {
16682 	dtrace_provider_t *prv;
16683 
16684 	mutex_enter(&dtrace_provider_lock);
16685 #ifdef illumos
16686 	mutex_enter(&mod_lock);
16687 #endif
16688 
16689 #ifdef illumos
16690 	ASSERT(ctl->mod_busy);
16691 #endif
16692 
16693 	/*
16694 	 * We're going to call each providers per-module provide operation
16695 	 * specifying only this module.
16696 	 */
16697 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16698 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16699 
16700 #ifdef illumos
16701 	mutex_exit(&mod_lock);
16702 #endif
16703 	mutex_exit(&dtrace_provider_lock);
16704 
16705 	/*
16706 	 * If we have any retained enablings, we need to match against them.
16707 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16708 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16709 	 * module.  (In particular, this happens when loading scheduling
16710 	 * classes.)  So if we have any retained enablings, we need to dispatch
16711 	 * our task queue to do the match for us.
16712 	 */
16713 	mutex_enter(&dtrace_lock);
16714 
16715 	if (dtrace_retained == NULL) {
16716 		mutex_exit(&dtrace_lock);
16717 		return;
16718 	}
16719 
16720 	(void) taskq_dispatch(dtrace_taskq,
16721 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16722 
16723 	mutex_exit(&dtrace_lock);
16724 
16725 	/*
16726 	 * And now, for a little heuristic sleaze:  in general, we want to
16727 	 * match modules as soon as they load.  However, we cannot guarantee
16728 	 * this, because it would lead us to the lock ordering violation
16729 	 * outlined above.  The common case, of course, is that cpu_lock is
16730 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16731 	 * long enough for the task queue to do its work.  If it's not, it's
16732 	 * not a serious problem -- it just means that the module that we
16733 	 * just loaded may not be immediately instrumentable.
16734 	 */
16735 	delay(1);
16736 }
16737 
16738 static void
16739 #ifdef illumos
16740 dtrace_module_unloaded(modctl_t *ctl)
16741 #else
16742 dtrace_module_unloaded(modctl_t *ctl, int *error)
16743 #endif
16744 {
16745 	dtrace_probe_t template, *probe, *first, *next;
16746 	dtrace_provider_t *prov;
16747 #ifndef illumos
16748 	char modname[DTRACE_MODNAMELEN];
16749 	size_t len;
16750 #endif
16751 
16752 #ifdef illumos
16753 	template.dtpr_mod = ctl->mod_modname;
16754 #else
16755 	/* Handle the fact that ctl->filename may end in ".ko". */
16756 	strlcpy(modname, ctl->filename, sizeof(modname));
16757 	len = strlen(ctl->filename);
16758 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16759 		modname[len - 3] = '\0';
16760 	template.dtpr_mod = modname;
16761 #endif
16762 
16763 	mutex_enter(&dtrace_provider_lock);
16764 #ifdef illumos
16765 	mutex_enter(&mod_lock);
16766 #endif
16767 	mutex_enter(&dtrace_lock);
16768 
16769 #ifndef illumos
16770 	if (ctl->nenabled > 0) {
16771 		/* Don't allow unloads if a probe is enabled. */
16772 		mutex_exit(&dtrace_provider_lock);
16773 		mutex_exit(&dtrace_lock);
16774 		*error = -1;
16775 		printf(
16776 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16777 		return;
16778 	}
16779 #endif
16780 
16781 	if (dtrace_bymod == NULL) {
16782 		/*
16783 		 * The DTrace module is loaded (obviously) but not attached;
16784 		 * we don't have any work to do.
16785 		 */
16786 		mutex_exit(&dtrace_provider_lock);
16787 #ifdef illumos
16788 		mutex_exit(&mod_lock);
16789 #endif
16790 		mutex_exit(&dtrace_lock);
16791 		return;
16792 	}
16793 
16794 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16795 	    probe != NULL; probe = probe->dtpr_nextmod) {
16796 		if (probe->dtpr_ecb != NULL) {
16797 			mutex_exit(&dtrace_provider_lock);
16798 #ifdef illumos
16799 			mutex_exit(&mod_lock);
16800 #endif
16801 			mutex_exit(&dtrace_lock);
16802 
16803 			/*
16804 			 * This shouldn't _actually_ be possible -- we're
16805 			 * unloading a module that has an enabled probe in it.
16806 			 * (It's normally up to the provider to make sure that
16807 			 * this can't happen.)  However, because dtps_enable()
16808 			 * doesn't have a failure mode, there can be an
16809 			 * enable/unload race.  Upshot:  we don't want to
16810 			 * assert, but we're not going to disable the
16811 			 * probe, either.
16812 			 */
16813 			if (dtrace_err_verbose) {
16814 #ifdef illumos
16815 				cmn_err(CE_WARN, "unloaded module '%s' had "
16816 				    "enabled probes", ctl->mod_modname);
16817 #else
16818 				cmn_err(CE_WARN, "unloaded module '%s' had "
16819 				    "enabled probes", modname);
16820 #endif
16821 			}
16822 
16823 			return;
16824 		}
16825 	}
16826 
16827 	probe = first;
16828 
16829 	for (first = NULL; probe != NULL; probe = next) {
16830 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16831 
16832 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16833 
16834 		next = probe->dtpr_nextmod;
16835 		dtrace_hash_remove(dtrace_bymod, probe);
16836 		dtrace_hash_remove(dtrace_byfunc, probe);
16837 		dtrace_hash_remove(dtrace_byname, probe);
16838 
16839 		if (first == NULL) {
16840 			first = probe;
16841 			probe->dtpr_nextmod = NULL;
16842 		} else {
16843 			probe->dtpr_nextmod = first;
16844 			first = probe;
16845 		}
16846 	}
16847 
16848 	/*
16849 	 * We've removed all of the module's probes from the hash chains and
16850 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16851 	 * everyone has cleared out from any probe array processing.
16852 	 */
16853 	dtrace_sync();
16854 
16855 	for (probe = first; probe != NULL; probe = first) {
16856 		first = probe->dtpr_nextmod;
16857 		prov = probe->dtpr_provider;
16858 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16859 		    probe->dtpr_arg);
16860 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16861 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16862 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16863 #ifdef illumos
16864 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16865 #else
16866 		free_unr(dtrace_arena, probe->dtpr_id);
16867 #endif
16868 		kmem_free(probe, sizeof (dtrace_probe_t));
16869 	}
16870 
16871 	mutex_exit(&dtrace_lock);
16872 #ifdef illumos
16873 	mutex_exit(&mod_lock);
16874 #endif
16875 	mutex_exit(&dtrace_provider_lock);
16876 }
16877 
16878 #ifndef illumos
16879 static void
16880 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16881 {
16882 
16883 	dtrace_module_loaded(lf);
16884 }
16885 
16886 static void
16887 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16888 {
16889 
16890 	if (*error != 0)
16891 		/* We already have an error, so don't do anything. */
16892 		return;
16893 	dtrace_module_unloaded(lf, error);
16894 }
16895 #endif
16896 
16897 #ifdef illumos
16898 static void
16899 dtrace_suspend(void)
16900 {
16901 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16902 }
16903 
16904 static void
16905 dtrace_resume(void)
16906 {
16907 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16908 }
16909 #endif
16910 
16911 static int
16912 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16913 {
16914 	ASSERT(MUTEX_HELD(&cpu_lock));
16915 	mutex_enter(&dtrace_lock);
16916 
16917 	switch (what) {
16918 	case CPU_CONFIG: {
16919 		dtrace_state_t *state;
16920 		dtrace_optval_t *opt, rs, c;
16921 
16922 		/*
16923 		 * For now, we only allocate a new buffer for anonymous state.
16924 		 */
16925 		if ((state = dtrace_anon.dta_state) == NULL)
16926 			break;
16927 
16928 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16929 			break;
16930 
16931 		opt = state->dts_options;
16932 		c = opt[DTRACEOPT_CPU];
16933 
16934 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16935 			break;
16936 
16937 		/*
16938 		 * Regardless of what the actual policy is, we're going to
16939 		 * temporarily set our resize policy to be manual.  We're
16940 		 * also going to temporarily set our CPU option to denote
16941 		 * the newly configured CPU.
16942 		 */
16943 		rs = opt[DTRACEOPT_BUFRESIZE];
16944 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16945 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16946 
16947 		(void) dtrace_state_buffers(state);
16948 
16949 		opt[DTRACEOPT_BUFRESIZE] = rs;
16950 		opt[DTRACEOPT_CPU] = c;
16951 
16952 		break;
16953 	}
16954 
16955 	case CPU_UNCONFIG:
16956 		/*
16957 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16958 		 * buffer will be freed when the consumer exits.)
16959 		 */
16960 		break;
16961 
16962 	default:
16963 		break;
16964 	}
16965 
16966 	mutex_exit(&dtrace_lock);
16967 	return (0);
16968 }
16969 
16970 #ifdef illumos
16971 static void
16972 dtrace_cpu_setup_initial(processorid_t cpu)
16973 {
16974 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16975 }
16976 #endif
16977 
16978 static void
16979 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16980 {
16981 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16982 		int osize, nsize;
16983 		dtrace_toxrange_t *range;
16984 
16985 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16986 
16987 		if (osize == 0) {
16988 			ASSERT(dtrace_toxrange == NULL);
16989 			ASSERT(dtrace_toxranges_max == 0);
16990 			dtrace_toxranges_max = 1;
16991 		} else {
16992 			dtrace_toxranges_max <<= 1;
16993 		}
16994 
16995 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16996 		range = kmem_zalloc(nsize, KM_SLEEP);
16997 
16998 		if (dtrace_toxrange != NULL) {
16999 			ASSERT(osize != 0);
17000 			bcopy(dtrace_toxrange, range, osize);
17001 			kmem_free(dtrace_toxrange, osize);
17002 		}
17003 
17004 		dtrace_toxrange = range;
17005 	}
17006 
17007 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17008 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17009 
17010 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17011 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17012 	dtrace_toxranges++;
17013 }
17014 
17015 static void
17016 dtrace_getf_barrier()
17017 {
17018 #ifdef illumos
17019 	/*
17020 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17021 	 * that contain calls to getf(), this routine will be called on every
17022 	 * closef() before either the underlying vnode is released or the
17023 	 * file_t itself is freed.  By the time we are here, it is essential
17024 	 * that the file_t can no longer be accessed from a call to getf()
17025 	 * in probe context -- that assures that a dtrace_sync() can be used
17026 	 * to clear out any enablings referring to the old structures.
17027 	 */
17028 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17029 	    kcred->cr_zone->zone_dtrace_getf != 0)
17030 		dtrace_sync();
17031 #endif
17032 }
17033 
17034 /*
17035  * DTrace Driver Cookbook Functions
17036  */
17037 #ifdef illumos
17038 /*ARGSUSED*/
17039 static int
17040 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17041 {
17042 	dtrace_provider_id_t id;
17043 	dtrace_state_t *state = NULL;
17044 	dtrace_enabling_t *enab;
17045 
17046 	mutex_enter(&cpu_lock);
17047 	mutex_enter(&dtrace_provider_lock);
17048 	mutex_enter(&dtrace_lock);
17049 
17050 	if (ddi_soft_state_init(&dtrace_softstate,
17051 	    sizeof (dtrace_state_t), 0) != 0) {
17052 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17053 		mutex_exit(&cpu_lock);
17054 		mutex_exit(&dtrace_provider_lock);
17055 		mutex_exit(&dtrace_lock);
17056 		return (DDI_FAILURE);
17057 	}
17058 
17059 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17060 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17061 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17062 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17063 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17064 		ddi_remove_minor_node(devi, NULL);
17065 		ddi_soft_state_fini(&dtrace_softstate);
17066 		mutex_exit(&cpu_lock);
17067 		mutex_exit(&dtrace_provider_lock);
17068 		mutex_exit(&dtrace_lock);
17069 		return (DDI_FAILURE);
17070 	}
17071 
17072 	ddi_report_dev(devi);
17073 	dtrace_devi = devi;
17074 
17075 	dtrace_modload = dtrace_module_loaded;
17076 	dtrace_modunload = dtrace_module_unloaded;
17077 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17078 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17079 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17080 	dtrace_cpustart_init = dtrace_suspend;
17081 	dtrace_cpustart_fini = dtrace_resume;
17082 	dtrace_debugger_init = dtrace_suspend;
17083 	dtrace_debugger_fini = dtrace_resume;
17084 
17085 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17086 
17087 	ASSERT(MUTEX_HELD(&cpu_lock));
17088 
17089 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17090 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17091 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17092 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17093 	    VM_SLEEP | VMC_IDENTIFIER);
17094 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17095 	    1, INT_MAX, 0);
17096 
17097 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17098 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17099 	    NULL, NULL, NULL, NULL, NULL, 0);
17100 
17101 	ASSERT(MUTEX_HELD(&cpu_lock));
17102 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17103 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17104 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17105 
17106 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17107 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17108 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17109 
17110 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17111 	    offsetof(dtrace_probe_t, dtpr_nextname),
17112 	    offsetof(dtrace_probe_t, dtpr_prevname));
17113 
17114 	if (dtrace_retain_max < 1) {
17115 		cmn_err(CE_WARN, "illegal value (%zu) for dtrace_retain_max; "
17116 		    "setting to 1", dtrace_retain_max);
17117 		dtrace_retain_max = 1;
17118 	}
17119 
17120 	/*
17121 	 * Now discover our toxic ranges.
17122 	 */
17123 	dtrace_toxic_ranges(dtrace_toxrange_add);
17124 
17125 	/*
17126 	 * Before we register ourselves as a provider to our own framework,
17127 	 * we would like to assert that dtrace_provider is NULL -- but that's
17128 	 * not true if we were loaded as a dependency of a DTrace provider.
17129 	 * Once we've registered, we can assert that dtrace_provider is our
17130 	 * pseudo provider.
17131 	 */
17132 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17133 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17134 
17135 	ASSERT(dtrace_provider != NULL);
17136 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17137 
17138 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17139 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17140 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17141 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17142 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17143 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17144 
17145 	dtrace_anon_property();
17146 	mutex_exit(&cpu_lock);
17147 
17148 	/*
17149 	 * If there are already providers, we must ask them to provide their
17150 	 * probes, and then match any anonymous enabling against them.  Note
17151 	 * that there should be no other retained enablings at this time:
17152 	 * the only retained enablings at this time should be the anonymous
17153 	 * enabling.
17154 	 */
17155 	if (dtrace_anon.dta_enabling != NULL) {
17156 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17157 
17158 		dtrace_enabling_provide(NULL);
17159 		state = dtrace_anon.dta_state;
17160 
17161 		/*
17162 		 * We couldn't hold cpu_lock across the above call to
17163 		 * dtrace_enabling_provide(), but we must hold it to actually
17164 		 * enable the probes.  We have to drop all of our locks, pick
17165 		 * up cpu_lock, and regain our locks before matching the
17166 		 * retained anonymous enabling.
17167 		 */
17168 		mutex_exit(&dtrace_lock);
17169 		mutex_exit(&dtrace_provider_lock);
17170 
17171 		mutex_enter(&cpu_lock);
17172 		mutex_enter(&dtrace_provider_lock);
17173 		mutex_enter(&dtrace_lock);
17174 
17175 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17176 			(void) dtrace_enabling_match(enab, NULL);
17177 
17178 		mutex_exit(&cpu_lock);
17179 	}
17180 
17181 	mutex_exit(&dtrace_lock);
17182 	mutex_exit(&dtrace_provider_lock);
17183 
17184 	if (state != NULL) {
17185 		/*
17186 		 * If we created any anonymous state, set it going now.
17187 		 */
17188 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17189 	}
17190 
17191 	return (DDI_SUCCESS);
17192 }
17193 #endif	/* illumos */
17194 
17195 #ifndef illumos
17196 static void dtrace_dtr(void *);
17197 #endif
17198 
17199 /*ARGSUSED*/
17200 static int
17201 #ifdef illumos
17202 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17203 #else
17204 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17205 #endif
17206 {
17207 	dtrace_state_t *state;
17208 	uint32_t priv;
17209 	uid_t uid;
17210 	zoneid_t zoneid;
17211 
17212 #ifdef illumos
17213 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17214 		return (0);
17215 
17216 	/*
17217 	 * If this wasn't an open with the "helper" minor, then it must be
17218 	 * the "dtrace" minor.
17219 	 */
17220 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17221 		return (ENXIO);
17222 #else
17223 	cred_t *cred_p = NULL;
17224 	cred_p = dev->si_cred;
17225 
17226 	/*
17227 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17228 	 * caller lacks sufficient permission to do anything with DTrace.
17229 	 */
17230 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17231 	if (priv == DTRACE_PRIV_NONE) {
17232 #endif
17233 
17234 		return (EACCES);
17235 	}
17236 
17237 	/*
17238 	 * Ask all providers to provide all their probes.
17239 	 */
17240 	mutex_enter(&dtrace_provider_lock);
17241 	dtrace_probe_provide(NULL, NULL);
17242 	mutex_exit(&dtrace_provider_lock);
17243 
17244 	mutex_enter(&cpu_lock);
17245 	mutex_enter(&dtrace_lock);
17246 	dtrace_opens++;
17247 	dtrace_membar_producer();
17248 
17249 #ifdef illumos
17250 	/*
17251 	 * If the kernel debugger is active (that is, if the kernel debugger
17252 	 * modified text in some way), we won't allow the open.
17253 	 */
17254 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17255 		dtrace_opens--;
17256 		mutex_exit(&cpu_lock);
17257 		mutex_exit(&dtrace_lock);
17258 		return (EBUSY);
17259 	}
17260 
17261 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17262 		/*
17263 		 * If DTrace helper tracing is enabled, we need to allocate the
17264 		 * trace buffer and initialize the values.
17265 		 */
17266 		dtrace_helptrace_buffer =
17267 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17268 		dtrace_helptrace_next = 0;
17269 		dtrace_helptrace_wrapped = 0;
17270 		dtrace_helptrace_enable = 0;
17271 	}
17272 
17273 	state = dtrace_state_create(devp, cred_p);
17274 #else
17275 	state = dtrace_state_create(dev, NULL);
17276 	devfs_set_cdevpriv(state, dtrace_dtr);
17277 #endif
17278 
17279 	mutex_exit(&cpu_lock);
17280 
17281 	if (state == NULL) {
17282 #ifdef illumos
17283 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17284 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17285 #else
17286 		--dtrace_opens;
17287 #endif
17288 		mutex_exit(&dtrace_lock);
17289 		return (EAGAIN);
17290 	}
17291 
17292 	mutex_exit(&dtrace_lock);
17293 
17294 	return (0);
17295 }
17296 
17297 /*ARGSUSED*/
17298 #ifdef illumos
17299 static int
17300 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17301 #else
17302 static void
17303 dtrace_dtr(void *data)
17304 #endif
17305 {
17306 #ifdef illumos
17307 	minor_t minor = getminor(dev);
17308 	dtrace_state_t *state;
17309 #endif
17310 	dtrace_helptrace_t *buf = NULL;
17311 
17312 #ifdef illumos
17313 	if (minor == DTRACEMNRN_HELPER)
17314 		return (0);
17315 
17316 	state = ddi_get_soft_state(dtrace_softstate, minor);
17317 #else
17318 	dtrace_state_t *state = data;
17319 #endif
17320 
17321 	mutex_enter(&cpu_lock);
17322 	mutex_enter(&dtrace_lock);
17323 
17324 #ifdef illumos
17325 	if (state->dts_anon)
17326 #else
17327 	if (state != NULL && state->dts_anon)
17328 #endif
17329 	{
17330 		/*
17331 		 * There is anonymous state. Destroy that first.
17332 		 */
17333 		ASSERT(dtrace_anon.dta_state == NULL);
17334 		dtrace_state_destroy(state->dts_anon);
17335 	}
17336 
17337 	if (dtrace_helptrace_disable) {
17338 		/*
17339 		 * If we have been told to disable helper tracing, set the
17340 		 * buffer to NULL before calling into dtrace_state_destroy();
17341 		 * we take advantage of its dtrace_sync() to know that no
17342 		 * CPU is in probe context with enabled helper tracing
17343 		 * after it returns.
17344 		 */
17345 		buf = dtrace_helptrace_buffer;
17346 		dtrace_helptrace_buffer = NULL;
17347 	}
17348 
17349 #ifdef illumos
17350 	dtrace_state_destroy(state);
17351 #else
17352 	if (state != NULL) {
17353 		dtrace_state_destroy(state);
17354 		kmem_free(state, 0);
17355 	}
17356 #endif
17357 	ASSERT(dtrace_opens > 0);
17358 
17359 #ifdef illumos
17360 	/*
17361 	 * Only relinquish control of the kernel debugger interface when there
17362 	 * are no consumers and no anonymous enablings.
17363 	 */
17364 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17365 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17366 #else
17367 	--dtrace_opens;
17368 #endif
17369 
17370 	if (buf != NULL) {
17371 		kmem_free(buf, dtrace_helptrace_bufsize);
17372 		dtrace_helptrace_disable = 0;
17373 	}
17374 
17375 	mutex_exit(&dtrace_lock);
17376 	mutex_exit(&cpu_lock);
17377 
17378 #ifdef illumos
17379 	return (0);
17380 #endif
17381 }
17382 
17383 #ifdef illumos
17384 /*ARGSUSED*/
17385 static int
17386 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17387 {
17388 	int rval;
17389 	dof_helper_t help, *dhp = NULL;
17390 
17391 	switch (cmd) {
17392 	case DTRACEHIOC_ADDDOF:
17393 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17394 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17395 			return (EFAULT);
17396 		}
17397 
17398 		dhp = &help;
17399 		arg = (intptr_t)help.dofhp_dof;
17400 		/*FALLTHROUGH*/
17401 
17402 	case DTRACEHIOC_ADD: {
17403 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17404 
17405 		if (dof == NULL)
17406 			return (rval);
17407 
17408 		mutex_enter(&dtrace_lock);
17409 
17410 		/*
17411 		 * dtrace_helper_slurp() takes responsibility for the dof --
17412 		 * it may free it now or it may save it and free it later.
17413 		 */
17414 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17415 			*rv = rval;
17416 			rval = 0;
17417 		} else {
17418 			rval = EINVAL;
17419 		}
17420 
17421 		mutex_exit(&dtrace_lock);
17422 		return (rval);
17423 	}
17424 
17425 	case DTRACEHIOC_REMOVE: {
17426 		mutex_enter(&dtrace_lock);
17427 		rval = dtrace_helper_destroygen(NULL, arg);
17428 		mutex_exit(&dtrace_lock);
17429 
17430 		return (rval);
17431 	}
17432 
17433 	default:
17434 		break;
17435 	}
17436 
17437 	return (ENOTTY);
17438 }
17439 
17440 /*ARGSUSED*/
17441 static int
17442 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17443 {
17444 	minor_t minor = getminor(dev);
17445 	dtrace_state_t *state;
17446 	int rval;
17447 
17448 	if (minor == DTRACEMNRN_HELPER)
17449 		return (dtrace_ioctl_helper(cmd, arg, rv));
17450 
17451 	state = ddi_get_soft_state(dtrace_softstate, minor);
17452 
17453 	if (state->dts_anon) {
17454 		ASSERT(dtrace_anon.dta_state == NULL);
17455 		state = state->dts_anon;
17456 	}
17457 
17458 	switch (cmd) {
17459 	case DTRACEIOC_PROVIDER: {
17460 		dtrace_providerdesc_t pvd;
17461 		dtrace_provider_t *pvp;
17462 
17463 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17464 			return (EFAULT);
17465 
17466 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17467 		mutex_enter(&dtrace_provider_lock);
17468 
17469 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17470 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17471 				break;
17472 		}
17473 
17474 		mutex_exit(&dtrace_provider_lock);
17475 
17476 		if (pvp == NULL)
17477 			return (ESRCH);
17478 
17479 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17480 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17481 
17482 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17483 			return (EFAULT);
17484 
17485 		return (0);
17486 	}
17487 
17488 	case DTRACEIOC_EPROBE: {
17489 		dtrace_eprobedesc_t epdesc;
17490 		dtrace_ecb_t *ecb;
17491 		dtrace_action_t *act;
17492 		void *buf;
17493 		size_t size;
17494 		uintptr_t dest;
17495 		int nrecs;
17496 
17497 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17498 			return (EFAULT);
17499 
17500 		mutex_enter(&dtrace_lock);
17501 
17502 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17503 			mutex_exit(&dtrace_lock);
17504 			return (EINVAL);
17505 		}
17506 
17507 		if (ecb->dte_probe == NULL) {
17508 			mutex_exit(&dtrace_lock);
17509 			return (EINVAL);
17510 		}
17511 
17512 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17513 		epdesc.dtepd_uarg = ecb->dte_uarg;
17514 		epdesc.dtepd_size = ecb->dte_size;
17515 
17516 		nrecs = epdesc.dtepd_nrecs;
17517 		epdesc.dtepd_nrecs = 0;
17518 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17519 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17520 				continue;
17521 
17522 			epdesc.dtepd_nrecs++;
17523 		}
17524 
17525 		/*
17526 		 * Now that we have the size, we need to allocate a temporary
17527 		 * buffer in which to store the complete description.  We need
17528 		 * the temporary buffer to be able to drop dtrace_lock()
17529 		 * across the copyout(), below.
17530 		 */
17531 		size = sizeof (dtrace_eprobedesc_t) +
17532 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17533 
17534 		buf = kmem_alloc(size, KM_SLEEP);
17535 		dest = (uintptr_t)buf;
17536 
17537 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17538 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17539 
17540 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17541 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17542 				continue;
17543 
17544 			if (nrecs-- == 0)
17545 				break;
17546 
17547 			bcopy(&act->dta_rec, (void *)dest,
17548 			    sizeof (dtrace_recdesc_t));
17549 			dest += sizeof (dtrace_recdesc_t);
17550 		}
17551 
17552 		mutex_exit(&dtrace_lock);
17553 
17554 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17555 			kmem_free(buf, size);
17556 			return (EFAULT);
17557 		}
17558 
17559 		kmem_free(buf, size);
17560 		return (0);
17561 	}
17562 
17563 	case DTRACEIOC_AGGDESC: {
17564 		dtrace_aggdesc_t aggdesc;
17565 		dtrace_action_t *act;
17566 		dtrace_aggregation_t *agg;
17567 		int nrecs;
17568 		uint32_t offs;
17569 		dtrace_recdesc_t *lrec;
17570 		void *buf;
17571 		size_t size;
17572 		uintptr_t dest;
17573 
17574 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17575 			return (EFAULT);
17576 
17577 		mutex_enter(&dtrace_lock);
17578 
17579 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17580 			mutex_exit(&dtrace_lock);
17581 			return (EINVAL);
17582 		}
17583 
17584 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17585 
17586 		nrecs = aggdesc.dtagd_nrecs;
17587 		aggdesc.dtagd_nrecs = 0;
17588 
17589 		offs = agg->dtag_base;
17590 		lrec = &agg->dtag_action.dta_rec;
17591 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17592 
17593 		for (act = agg->dtag_first; ; act = act->dta_next) {
17594 			ASSERT(act->dta_intuple ||
17595 			    DTRACEACT_ISAGG(act->dta_kind));
17596 
17597 			/*
17598 			 * If this action has a record size of zero, it
17599 			 * denotes an argument to the aggregating action.
17600 			 * Because the presence of this record doesn't (or
17601 			 * shouldn't) affect the way the data is interpreted,
17602 			 * we don't copy it out to save user-level the
17603 			 * confusion of dealing with a zero-length record.
17604 			 */
17605 			if (act->dta_rec.dtrd_size == 0) {
17606 				ASSERT(agg->dtag_hasarg);
17607 				continue;
17608 			}
17609 
17610 			aggdesc.dtagd_nrecs++;
17611 
17612 			if (act == &agg->dtag_action)
17613 				break;
17614 		}
17615 
17616 		/*
17617 		 * Now that we have the size, we need to allocate a temporary
17618 		 * buffer in which to store the complete description.  We need
17619 		 * the temporary buffer to be able to drop dtrace_lock()
17620 		 * across the copyout(), below.
17621 		 */
17622 		size = sizeof (dtrace_aggdesc_t) +
17623 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17624 
17625 		buf = kmem_alloc(size, KM_SLEEP);
17626 		dest = (uintptr_t)buf;
17627 
17628 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17629 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17630 
17631 		for (act = agg->dtag_first; ; act = act->dta_next) {
17632 			dtrace_recdesc_t rec = act->dta_rec;
17633 
17634 			/*
17635 			 * See the comment in the above loop for why we pass
17636 			 * over zero-length records.
17637 			 */
17638 			if (rec.dtrd_size == 0) {
17639 				ASSERT(agg->dtag_hasarg);
17640 				continue;
17641 			}
17642 
17643 			if (nrecs-- == 0)
17644 				break;
17645 
17646 			rec.dtrd_offset -= offs;
17647 			bcopy(&rec, (void *)dest, sizeof (rec));
17648 			dest += sizeof (dtrace_recdesc_t);
17649 
17650 			if (act == &agg->dtag_action)
17651 				break;
17652 		}
17653 
17654 		mutex_exit(&dtrace_lock);
17655 
17656 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17657 			kmem_free(buf, size);
17658 			return (EFAULT);
17659 		}
17660 
17661 		kmem_free(buf, size);
17662 		return (0);
17663 	}
17664 
17665 	case DTRACEIOC_ENABLE: {
17666 		dof_hdr_t *dof;
17667 		dtrace_enabling_t *enab = NULL;
17668 		dtrace_vstate_t *vstate;
17669 		int err = 0;
17670 
17671 		*rv = 0;
17672 
17673 		/*
17674 		 * If a NULL argument has been passed, we take this as our
17675 		 * cue to reevaluate our enablings.
17676 		 */
17677 		if (arg == NULL) {
17678 			dtrace_enabling_matchall();
17679 
17680 			return (0);
17681 		}
17682 
17683 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17684 			return (rval);
17685 
17686 		mutex_enter(&cpu_lock);
17687 		mutex_enter(&dtrace_lock);
17688 		vstate = &state->dts_vstate;
17689 
17690 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17691 			mutex_exit(&dtrace_lock);
17692 			mutex_exit(&cpu_lock);
17693 			dtrace_dof_destroy(dof);
17694 			return (EBUSY);
17695 		}
17696 
17697 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17698 			mutex_exit(&dtrace_lock);
17699 			mutex_exit(&cpu_lock);
17700 			dtrace_dof_destroy(dof);
17701 			return (EINVAL);
17702 		}
17703 
17704 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17705 			dtrace_enabling_destroy(enab);
17706 			mutex_exit(&dtrace_lock);
17707 			mutex_exit(&cpu_lock);
17708 			dtrace_dof_destroy(dof);
17709 			return (rval);
17710 		}
17711 
17712 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17713 			err = dtrace_enabling_retain(enab);
17714 		} else {
17715 			dtrace_enabling_destroy(enab);
17716 		}
17717 
17718 		mutex_exit(&cpu_lock);
17719 		mutex_exit(&dtrace_lock);
17720 		dtrace_dof_destroy(dof);
17721 
17722 		return (err);
17723 	}
17724 
17725 	case DTRACEIOC_REPLICATE: {
17726 		dtrace_repldesc_t desc;
17727 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17728 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17729 		int err;
17730 
17731 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17732 			return (EFAULT);
17733 
17734 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17735 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17736 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17737 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17738 
17739 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17740 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17741 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17742 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17743 
17744 		mutex_enter(&dtrace_lock);
17745 		err = dtrace_enabling_replicate(state, match, create);
17746 		mutex_exit(&dtrace_lock);
17747 
17748 		return (err);
17749 	}
17750 
17751 	case DTRACEIOC_PROBEMATCH:
17752 	case DTRACEIOC_PROBES: {
17753 		dtrace_probe_t *probe = NULL;
17754 		dtrace_probedesc_t desc;
17755 		dtrace_probekey_t pkey;
17756 		dtrace_id_t i;
17757 		int m = 0;
17758 		uint32_t priv;
17759 		uid_t uid;
17760 		zoneid_t zoneid;
17761 
17762 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17763 			return (EFAULT);
17764 
17765 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17766 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17767 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17768 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17769 
17770 		/*
17771 		 * Before we attempt to match this probe, we want to give
17772 		 * all providers the opportunity to provide it.
17773 		 */
17774 		if (desc.dtpd_id == DTRACE_IDNONE) {
17775 			mutex_enter(&dtrace_provider_lock);
17776 			dtrace_probe_provide(&desc, NULL);
17777 			mutex_exit(&dtrace_provider_lock);
17778 			desc.dtpd_id++;
17779 		}
17780 
17781 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17782 			dtrace_probekey(&desc, &pkey);
17783 			pkey.dtpk_id = DTRACE_IDNONE;
17784 		}
17785 
17786 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17787 
17788 		mutex_enter(&dtrace_lock);
17789 
17790 		if (cmd == DTRACEIOC_PROBEMATCH) {
17791 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17792 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17793 				    (m = dtrace_match_probe(probe, &pkey,
17794 				    priv, uid, zoneid)) != 0)
17795 					break;
17796 			}
17797 
17798 			if (m < 0) {
17799 				mutex_exit(&dtrace_lock);
17800 				return (EINVAL);
17801 			}
17802 
17803 		} else {
17804 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17805 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17806 				    dtrace_match_priv(probe, priv, uid, zoneid))
17807 					break;
17808 			}
17809 		}
17810 
17811 		if (probe == NULL) {
17812 			mutex_exit(&dtrace_lock);
17813 			return (ESRCH);
17814 		}
17815 
17816 		dtrace_probe_description(probe, &desc);
17817 		mutex_exit(&dtrace_lock);
17818 
17819 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17820 			return (EFAULT);
17821 
17822 		return (0);
17823 	}
17824 
17825 	case DTRACEIOC_PROBEARG: {
17826 		dtrace_argdesc_t desc;
17827 		dtrace_probe_t *probe;
17828 		dtrace_provider_t *prov;
17829 
17830 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17831 			return (EFAULT);
17832 
17833 		if (desc.dtargd_id == DTRACE_IDNONE)
17834 			return (EINVAL);
17835 
17836 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17837 			return (EINVAL);
17838 
17839 		mutex_enter(&dtrace_provider_lock);
17840 		mutex_enter(&mod_lock);
17841 		mutex_enter(&dtrace_lock);
17842 
17843 		if (desc.dtargd_id > dtrace_nprobes) {
17844 			mutex_exit(&dtrace_lock);
17845 			mutex_exit(&mod_lock);
17846 			mutex_exit(&dtrace_provider_lock);
17847 			return (EINVAL);
17848 		}
17849 
17850 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17851 			mutex_exit(&dtrace_lock);
17852 			mutex_exit(&mod_lock);
17853 			mutex_exit(&dtrace_provider_lock);
17854 			return (EINVAL);
17855 		}
17856 
17857 		mutex_exit(&dtrace_lock);
17858 
17859 		prov = probe->dtpr_provider;
17860 
17861 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17862 			/*
17863 			 * There isn't any typed information for this probe.
17864 			 * Set the argument number to DTRACE_ARGNONE.
17865 			 */
17866 			desc.dtargd_ndx = DTRACE_ARGNONE;
17867 		} else {
17868 			desc.dtargd_native[0] = '\0';
17869 			desc.dtargd_xlate[0] = '\0';
17870 			desc.dtargd_mapping = desc.dtargd_ndx;
17871 
17872 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17873 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17874 		}
17875 
17876 		mutex_exit(&mod_lock);
17877 		mutex_exit(&dtrace_provider_lock);
17878 
17879 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17880 			return (EFAULT);
17881 
17882 		return (0);
17883 	}
17884 
17885 	case DTRACEIOC_GO: {
17886 		processorid_t cpuid;
17887 		rval = dtrace_state_go(state, &cpuid);
17888 
17889 		if (rval != 0)
17890 			return (rval);
17891 
17892 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17893 			return (EFAULT);
17894 
17895 		return (0);
17896 	}
17897 
17898 	case DTRACEIOC_STOP: {
17899 		processorid_t cpuid;
17900 
17901 		mutex_enter(&dtrace_lock);
17902 		rval = dtrace_state_stop(state, &cpuid);
17903 		mutex_exit(&dtrace_lock);
17904 
17905 		if (rval != 0)
17906 			return (rval);
17907 
17908 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17909 			return (EFAULT);
17910 
17911 		return (0);
17912 	}
17913 
17914 	case DTRACEIOC_DOFGET: {
17915 		dof_hdr_t hdr, *dof;
17916 		uint64_t len;
17917 
17918 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17919 			return (EFAULT);
17920 
17921 		mutex_enter(&dtrace_lock);
17922 		dof = dtrace_dof_create(state);
17923 		mutex_exit(&dtrace_lock);
17924 
17925 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17926 		rval = copyout(dof, (void *)arg, len);
17927 		dtrace_dof_destroy(dof);
17928 
17929 		return (rval == 0 ? 0 : EFAULT);
17930 	}
17931 
17932 	case DTRACEIOC_AGGSNAP:
17933 	case DTRACEIOC_BUFSNAP: {
17934 		dtrace_bufdesc_t desc;
17935 		caddr_t cached;
17936 		dtrace_buffer_t *buf;
17937 
17938 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17939 			return (EFAULT);
17940 
17941 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17942 			return (EINVAL);
17943 
17944 		mutex_enter(&dtrace_lock);
17945 
17946 		if (cmd == DTRACEIOC_BUFSNAP) {
17947 			buf = &state->dts_buffer[desc.dtbd_cpu];
17948 		} else {
17949 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17950 		}
17951 
17952 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17953 			size_t sz = buf->dtb_offset;
17954 
17955 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17956 				mutex_exit(&dtrace_lock);
17957 				return (EBUSY);
17958 			}
17959 
17960 			/*
17961 			 * If this buffer has already been consumed, we're
17962 			 * going to indicate that there's nothing left here
17963 			 * to consume.
17964 			 */
17965 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17966 				mutex_exit(&dtrace_lock);
17967 
17968 				desc.dtbd_size = 0;
17969 				desc.dtbd_drops = 0;
17970 				desc.dtbd_errors = 0;
17971 				desc.dtbd_oldest = 0;
17972 				sz = sizeof (desc);
17973 
17974 				if (copyout(&desc, (void *)arg, sz) != 0)
17975 					return (EFAULT);
17976 
17977 				return (0);
17978 			}
17979 
17980 			/*
17981 			 * If this is a ring buffer that has wrapped, we want
17982 			 * to copy the whole thing out.
17983 			 */
17984 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17985 				dtrace_buffer_polish(buf);
17986 				sz = buf->dtb_size;
17987 			}
17988 
17989 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17990 				mutex_exit(&dtrace_lock);
17991 				return (EFAULT);
17992 			}
17993 
17994 			desc.dtbd_size = sz;
17995 			desc.dtbd_drops = buf->dtb_drops;
17996 			desc.dtbd_errors = buf->dtb_errors;
17997 			desc.dtbd_oldest = buf->dtb_xamot_offset;
17998 			desc.dtbd_timestamp = dtrace_gethrtime();
17999 
18000 			mutex_exit(&dtrace_lock);
18001 
18002 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18003 				return (EFAULT);
18004 
18005 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18006 
18007 			return (0);
18008 		}
18009 
18010 		if (buf->dtb_tomax == NULL) {
18011 			ASSERT(buf->dtb_xamot == NULL);
18012 			mutex_exit(&dtrace_lock);
18013 			return (ENOENT);
18014 		}
18015 
18016 		cached = buf->dtb_tomax;
18017 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18018 
18019 		dtrace_xcall(desc.dtbd_cpu,
18020 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18021 
18022 		state->dts_errors += buf->dtb_xamot_errors;
18023 
18024 		/*
18025 		 * If the buffers did not actually switch, then the cross call
18026 		 * did not take place -- presumably because the given CPU is
18027 		 * not in the ready set.  If this is the case, we'll return
18028 		 * ENOENT.
18029 		 */
18030 		if (buf->dtb_tomax == cached) {
18031 			ASSERT(buf->dtb_xamot != cached);
18032 			mutex_exit(&dtrace_lock);
18033 			return (ENOENT);
18034 		}
18035 
18036 		ASSERT(cached == buf->dtb_xamot);
18037 
18038 		/*
18039 		 * We have our snapshot; now copy it out.
18040 		 */
18041 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18042 		    buf->dtb_xamot_offset) != 0) {
18043 			mutex_exit(&dtrace_lock);
18044 			return (EFAULT);
18045 		}
18046 
18047 		desc.dtbd_size = buf->dtb_xamot_offset;
18048 		desc.dtbd_drops = buf->dtb_xamot_drops;
18049 		desc.dtbd_errors = buf->dtb_xamot_errors;
18050 		desc.dtbd_oldest = 0;
18051 		desc.dtbd_timestamp = buf->dtb_switched;
18052 
18053 		mutex_exit(&dtrace_lock);
18054 
18055 		/*
18056 		 * Finally, copy out the buffer description.
18057 		 */
18058 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18059 			return (EFAULT);
18060 
18061 		return (0);
18062 	}
18063 
18064 	case DTRACEIOC_CONF: {
18065 		dtrace_conf_t conf;
18066 
18067 		bzero(&conf, sizeof (conf));
18068 		conf.dtc_difversion = DIF_VERSION;
18069 		conf.dtc_difintregs = DIF_DIR_NREGS;
18070 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18071 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18072 
18073 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18074 			return (EFAULT);
18075 
18076 		return (0);
18077 	}
18078 
18079 	case DTRACEIOC_STATUS: {
18080 		dtrace_status_t stat;
18081 		dtrace_dstate_t *dstate;
18082 		int i, j;
18083 		uint64_t nerrs;
18084 
18085 		/*
18086 		 * See the comment in dtrace_state_deadman() for the reason
18087 		 * for setting dts_laststatus to INT64_MAX before setting
18088 		 * it to the correct value.
18089 		 */
18090 		state->dts_laststatus = INT64_MAX;
18091 		dtrace_membar_producer();
18092 		state->dts_laststatus = dtrace_gethrtime();
18093 
18094 		bzero(&stat, sizeof (stat));
18095 
18096 		mutex_enter(&dtrace_lock);
18097 
18098 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18099 			mutex_exit(&dtrace_lock);
18100 			return (ENOENT);
18101 		}
18102 
18103 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18104 			stat.dtst_exiting = 1;
18105 
18106 		nerrs = state->dts_errors;
18107 		dstate = &state->dts_vstate.dtvs_dynvars;
18108 
18109 		for (i = 0; i < NCPU; i++) {
18110 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18111 
18112 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18113 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18114 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18115 
18116 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18117 				stat.dtst_filled++;
18118 
18119 			nerrs += state->dts_buffer[i].dtb_errors;
18120 
18121 			for (j = 0; j < state->dts_nspeculations; j++) {
18122 				dtrace_speculation_t *spec;
18123 				dtrace_buffer_t *buf;
18124 
18125 				spec = &state->dts_speculations[j];
18126 				buf = &spec->dtsp_buffer[i];
18127 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18128 			}
18129 		}
18130 
18131 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18132 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18133 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18134 		stat.dtst_dblerrors = state->dts_dblerrors;
18135 		stat.dtst_killed =
18136 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18137 		stat.dtst_errors = nerrs;
18138 
18139 		mutex_exit(&dtrace_lock);
18140 
18141 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18142 			return (EFAULT);
18143 
18144 		return (0);
18145 	}
18146 
18147 	case DTRACEIOC_FORMAT: {
18148 		dtrace_fmtdesc_t fmt;
18149 		char *str;
18150 		int len;
18151 
18152 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18153 			return (EFAULT);
18154 
18155 		mutex_enter(&dtrace_lock);
18156 
18157 		if (fmt.dtfd_format == 0 ||
18158 		    fmt.dtfd_format > state->dts_nformats) {
18159 			mutex_exit(&dtrace_lock);
18160 			return (EINVAL);
18161 		}
18162 
18163 		/*
18164 		 * Format strings are allocated contiguously and they are
18165 		 * never freed; if a format index is less than the number
18166 		 * of formats, we can assert that the format map is non-NULL
18167 		 * and that the format for the specified index is non-NULL.
18168 		 */
18169 		ASSERT(state->dts_formats != NULL);
18170 		str = state->dts_formats[fmt.dtfd_format - 1];
18171 		ASSERT(str != NULL);
18172 
18173 		len = strlen(str) + 1;
18174 
18175 		if (len > fmt.dtfd_length) {
18176 			fmt.dtfd_length = len;
18177 
18178 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18179 				mutex_exit(&dtrace_lock);
18180 				return (EINVAL);
18181 			}
18182 		} else {
18183 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18184 				mutex_exit(&dtrace_lock);
18185 				return (EINVAL);
18186 			}
18187 		}
18188 
18189 		mutex_exit(&dtrace_lock);
18190 		return (0);
18191 	}
18192 
18193 	default:
18194 		break;
18195 	}
18196 
18197 	return (ENOTTY);
18198 }
18199 
18200 /*ARGSUSED*/
18201 static int
18202 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18203 {
18204 	dtrace_state_t *state;
18205 
18206 	switch (cmd) {
18207 	case DDI_DETACH:
18208 		break;
18209 
18210 	case DDI_SUSPEND:
18211 		return (DDI_SUCCESS);
18212 
18213 	default:
18214 		return (DDI_FAILURE);
18215 	}
18216 
18217 	mutex_enter(&cpu_lock);
18218 	mutex_enter(&dtrace_provider_lock);
18219 	mutex_enter(&dtrace_lock);
18220 
18221 	ASSERT(dtrace_opens == 0);
18222 
18223 	if (dtrace_helpers > 0) {
18224 		mutex_exit(&dtrace_provider_lock);
18225 		mutex_exit(&dtrace_lock);
18226 		mutex_exit(&cpu_lock);
18227 		return (DDI_FAILURE);
18228 	}
18229 
18230 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18231 		mutex_exit(&dtrace_provider_lock);
18232 		mutex_exit(&dtrace_lock);
18233 		mutex_exit(&cpu_lock);
18234 		return (DDI_FAILURE);
18235 	}
18236 
18237 	dtrace_provider = NULL;
18238 
18239 	if ((state = dtrace_anon_grab()) != NULL) {
18240 		/*
18241 		 * If there were ECBs on this state, the provider should
18242 		 * have not been allowed to detach; assert that there is
18243 		 * none.
18244 		 */
18245 		ASSERT(state->dts_necbs == 0);
18246 		dtrace_state_destroy(state);
18247 
18248 		/*
18249 		 * If we're being detached with anonymous state, we need to
18250 		 * indicate to the kernel debugger that DTrace is now inactive.
18251 		 */
18252 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18253 	}
18254 
18255 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18256 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18257 	dtrace_cpu_init = NULL;
18258 	dtrace_helpers_cleanup = NULL;
18259 	dtrace_helpers_fork = NULL;
18260 	dtrace_cpustart_init = NULL;
18261 	dtrace_cpustart_fini = NULL;
18262 	dtrace_debugger_init = NULL;
18263 	dtrace_debugger_fini = NULL;
18264 	dtrace_modload = NULL;
18265 	dtrace_modunload = NULL;
18266 
18267 	ASSERT(dtrace_getf == 0);
18268 	ASSERT(dtrace_closef == NULL);
18269 
18270 	mutex_exit(&cpu_lock);
18271 
18272 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18273 	dtrace_probes = NULL;
18274 	dtrace_nprobes = 0;
18275 
18276 	dtrace_hash_destroy(dtrace_bymod);
18277 	dtrace_hash_destroy(dtrace_byfunc);
18278 	dtrace_hash_destroy(dtrace_byname);
18279 	dtrace_bymod = NULL;
18280 	dtrace_byfunc = NULL;
18281 	dtrace_byname = NULL;
18282 
18283 	kmem_cache_destroy(dtrace_state_cache);
18284 	vmem_destroy(dtrace_minor);
18285 	vmem_destroy(dtrace_arena);
18286 
18287 	if (dtrace_toxrange != NULL) {
18288 		kmem_free(dtrace_toxrange,
18289 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18290 		dtrace_toxrange = NULL;
18291 		dtrace_toxranges = 0;
18292 		dtrace_toxranges_max = 0;
18293 	}
18294 
18295 	ddi_remove_minor_node(dtrace_devi, NULL);
18296 	dtrace_devi = NULL;
18297 
18298 	ddi_soft_state_fini(&dtrace_softstate);
18299 
18300 	ASSERT(dtrace_vtime_references == 0);
18301 	ASSERT(dtrace_opens == 0);
18302 	ASSERT(dtrace_retained == NULL);
18303 
18304 	mutex_exit(&dtrace_lock);
18305 	mutex_exit(&dtrace_provider_lock);
18306 
18307 	/*
18308 	 * We don't destroy the task queue until after we have dropped our
18309 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18310 	 * attempting to do work after we have effectively detached but before
18311 	 * the task queue has been destroyed, all tasks dispatched via the
18312 	 * task queue must check that DTrace is still attached before
18313 	 * performing any operation.
18314 	 */
18315 	taskq_destroy(dtrace_taskq);
18316 	dtrace_taskq = NULL;
18317 
18318 	return (DDI_SUCCESS);
18319 }
18320 #endif
18321 
18322 #ifdef illumos
18323 /*ARGSUSED*/
18324 static int
18325 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18326 {
18327 	int error;
18328 
18329 	switch (infocmd) {
18330 	case DDI_INFO_DEVT2DEVINFO:
18331 		*result = (void *)dtrace_devi;
18332 		error = DDI_SUCCESS;
18333 		break;
18334 	case DDI_INFO_DEVT2INSTANCE:
18335 		*result = (void *)0;
18336 		error = DDI_SUCCESS;
18337 		break;
18338 	default:
18339 		error = DDI_FAILURE;
18340 	}
18341 	return (error);
18342 }
18343 #endif
18344 
18345 #ifdef illumos
18346 static struct cb_ops dtrace_cb_ops = {
18347 	dtrace_open,		/* open */
18348 	dtrace_close,		/* close */
18349 	nulldev,		/* strategy */
18350 	nulldev,		/* print */
18351 	nodev,			/* dump */
18352 	nodev,			/* read */
18353 	nodev,			/* write */
18354 	dtrace_ioctl,		/* ioctl */
18355 	nodev,			/* devmap */
18356 	nodev,			/* mmap */
18357 	nodev,			/* segmap */
18358 	nochpoll,		/* poll */
18359 	ddi_prop_op,		/* cb_prop_op */
18360 	0,			/* streamtab  */
18361 	D_NEW | D_MP		/* Driver compatibility flag */
18362 };
18363 
18364 static struct dev_ops dtrace_ops = {
18365 	DEVO_REV,		/* devo_rev */
18366 	0,			/* refcnt */
18367 	dtrace_info,		/* get_dev_info */
18368 	nulldev,		/* identify */
18369 	nulldev,		/* probe */
18370 	dtrace_attach,		/* attach */
18371 	dtrace_detach,		/* detach */
18372 	nodev,			/* reset */
18373 	&dtrace_cb_ops,		/* driver operations */
18374 	NULL,			/* bus operations */
18375 	nodev			/* dev power */
18376 };
18377 
18378 static struct modldrv modldrv = {
18379 	&mod_driverops,		/* module type (this is a pseudo driver) */
18380 	"Dynamic Tracing",	/* name of module */
18381 	&dtrace_ops,		/* driver ops */
18382 };
18383 
18384 static struct modlinkage modlinkage = {
18385 	MODREV_1,
18386 	(void *)&modldrv,
18387 	NULL
18388 };
18389 
18390 int
18391 _init(void)
18392 {
18393 	return (mod_install(&modlinkage));
18394 }
18395 
18396 int
18397 _info(struct modinfo *modinfop)
18398 {
18399 	return (mod_info(&modlinkage, modinfop));
18400 }
18401 
18402 int
18403 _fini(void)
18404 {
18405 	return (mod_remove(&modlinkage));
18406 }
18407 #else
18408 
18409 static d_ioctl_t	dtrace_ioctl;
18410 static d_ioctl_t	dtrace_ioctl_helper;
18411 static void		dtrace_load(void *);
18412 static int		dtrace_unload(void);
18413 static struct cdev	*dtrace_dev;
18414 static struct cdev	*helper_dev;
18415 
18416 void dtrace_invop_init(void);
18417 void dtrace_invop_uninit(void);
18418 
18419 static struct cdevsw dtrace_cdevsw = {
18420 	.d_version	= D_VERSION,
18421 	.d_ioctl	= dtrace_ioctl,
18422 	.d_open		= dtrace_open,
18423 	.d_name		= "dtrace",
18424 };
18425 
18426 static struct cdevsw helper_cdevsw = {
18427 	.d_version	= D_VERSION,
18428 	.d_ioctl	= dtrace_ioctl_helper,
18429 	.d_name		= "helper",
18430 };
18431 
18432 #include <dtrace_anon.c>
18433 #include <dtrace_ioctl.c>
18434 #include <dtrace_load.c>
18435 #include <dtrace_modevent.c>
18436 #include <dtrace_sysctl.c>
18437 #include <dtrace_unload.c>
18438 #include <dtrace_vtime.c>
18439 #include <dtrace_hacks.c>
18440 #include <dtrace_isa.c>
18441 
18442 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18443 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18444 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18445 
18446 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18447 MODULE_VERSION(dtrace, 1);
18448 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18449 #endif
18450