xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision 3078531de10dcae44b253a35125c949ff4235284)
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 		/*
5668 		 * XXXMJG this looks broken as no ref is taken.
5669 		 */
5670 		fp = fget_noref(fdp, fd);
5671 		mstate->dtms_getf = fp;
5672 		regs[rd] = (uintptr_t)fp;
5673 		FILEDESC_SUNLOCK(fdp);
5674 		break;
5675 	}
5676 
5677 	case DIF_SUBR_CLEANPATH: {
5678 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5679 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5680 		uintptr_t src = tupregs[0].dttk_value;
5681 		size_t lim;
5682 		int i = 0, j = 0;
5683 #ifdef illumos
5684 		zone_t *z;
5685 #endif
5686 
5687 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5688 			regs[rd] = 0;
5689 			break;
5690 		}
5691 
5692 		if (!DTRACE_INSCRATCH(mstate, size)) {
5693 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5694 			regs[rd] = 0;
5695 			break;
5696 		}
5697 
5698 		/*
5699 		 * Move forward, loading each character.
5700 		 */
5701 		do {
5702 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5703 next:
5704 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5705 				break;
5706 
5707 			if (c != '/') {
5708 				dest[j++] = c;
5709 				continue;
5710 			}
5711 
5712 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5713 
5714 			if (c == '/') {
5715 				/*
5716 				 * We have two slashes -- we can just advance
5717 				 * to the next character.
5718 				 */
5719 				goto next;
5720 			}
5721 
5722 			if (c != '.') {
5723 				/*
5724 				 * This is not "." and it's not ".." -- we can
5725 				 * just store the "/" and this character and
5726 				 * drive on.
5727 				 */
5728 				dest[j++] = '/';
5729 				dest[j++] = c;
5730 				continue;
5731 			}
5732 
5733 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5734 
5735 			if (c == '/') {
5736 				/*
5737 				 * This is a "/./" component.  We're not going
5738 				 * to store anything in the destination buffer;
5739 				 * we're just going to go to the next component.
5740 				 */
5741 				goto next;
5742 			}
5743 
5744 			if (c != '.') {
5745 				/*
5746 				 * This is not ".." -- we can just store the
5747 				 * "/." and this character and continue
5748 				 * processing.
5749 				 */
5750 				dest[j++] = '/';
5751 				dest[j++] = '.';
5752 				dest[j++] = c;
5753 				continue;
5754 			}
5755 
5756 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5757 
5758 			if (c != '/' && c != '\0') {
5759 				/*
5760 				 * This is not ".." -- it's "..[mumble]".
5761 				 * We'll store the "/.." and this character
5762 				 * and continue processing.
5763 				 */
5764 				dest[j++] = '/';
5765 				dest[j++] = '.';
5766 				dest[j++] = '.';
5767 				dest[j++] = c;
5768 				continue;
5769 			}
5770 
5771 			/*
5772 			 * This is "/../" or "/..\0".  We need to back up
5773 			 * our destination pointer until we find a "/".
5774 			 */
5775 			i--;
5776 			while (j != 0 && dest[--j] != '/')
5777 				continue;
5778 
5779 			if (c == '\0')
5780 				dest[++j] = '/';
5781 		} while (c != '\0');
5782 
5783 		dest[j] = '\0';
5784 
5785 #ifdef illumos
5786 		if (mstate->dtms_getf != NULL &&
5787 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5788 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5789 			/*
5790 			 * If we've done a getf() as a part of this ECB and we
5791 			 * don't have kernel access (and we're not in the global
5792 			 * zone), check if the path we cleaned up begins with
5793 			 * the zone's root path, and trim it off if so.  Note
5794 			 * that this is an output cleanliness issue, not a
5795 			 * security issue: knowing one's zone root path does
5796 			 * not enable privilege escalation.
5797 			 */
5798 			if (strstr(dest, z->zone_rootpath) == dest)
5799 				dest += strlen(z->zone_rootpath) - 1;
5800 		}
5801 #endif
5802 
5803 		regs[rd] = (uintptr_t)dest;
5804 		mstate->dtms_scratch_ptr += size;
5805 		break;
5806 	}
5807 
5808 	case DIF_SUBR_INET_NTOA:
5809 	case DIF_SUBR_INET_NTOA6:
5810 	case DIF_SUBR_INET_NTOP: {
5811 		size_t size;
5812 		int af, argi, i;
5813 		char *base, *end;
5814 
5815 		if (subr == DIF_SUBR_INET_NTOP) {
5816 			af = (int)tupregs[0].dttk_value;
5817 			argi = 1;
5818 		} else {
5819 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5820 			argi = 0;
5821 		}
5822 
5823 		if (af == AF_INET) {
5824 			ipaddr_t ip4;
5825 			uint8_t *ptr8, val;
5826 
5827 			if (!dtrace_canload(tupregs[argi].dttk_value,
5828 			    sizeof (ipaddr_t), mstate, vstate)) {
5829 				regs[rd] = 0;
5830 				break;
5831 			}
5832 
5833 			/*
5834 			 * Safely load the IPv4 address.
5835 			 */
5836 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5837 
5838 			/*
5839 			 * Check an IPv4 string will fit in scratch.
5840 			 */
5841 			size = INET_ADDRSTRLEN;
5842 			if (!DTRACE_INSCRATCH(mstate, size)) {
5843 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5844 				regs[rd] = 0;
5845 				break;
5846 			}
5847 			base = (char *)mstate->dtms_scratch_ptr;
5848 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5849 
5850 			/*
5851 			 * Stringify as a dotted decimal quad.
5852 			 */
5853 			*end-- = '\0';
5854 			ptr8 = (uint8_t *)&ip4;
5855 			for (i = 3; i >= 0; i--) {
5856 				val = ptr8[i];
5857 
5858 				if (val == 0) {
5859 					*end-- = '0';
5860 				} else {
5861 					for (; val; val /= 10) {
5862 						*end-- = '0' + (val % 10);
5863 					}
5864 				}
5865 
5866 				if (i > 0)
5867 					*end-- = '.';
5868 			}
5869 			ASSERT(end + 1 >= base);
5870 
5871 		} else if (af == AF_INET6) {
5872 			struct in6_addr ip6;
5873 			int firstzero, tryzero, numzero, v6end;
5874 			uint16_t val;
5875 			const char digits[] = "0123456789abcdef";
5876 
5877 			/*
5878 			 * Stringify using RFC 1884 convention 2 - 16 bit
5879 			 * hexadecimal values with a zero-run compression.
5880 			 * Lower case hexadecimal digits are used.
5881 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5882 			 * The IPv4 embedded form is returned for inet_ntop,
5883 			 * just the IPv4 string is returned for inet_ntoa6.
5884 			 */
5885 
5886 			if (!dtrace_canload(tupregs[argi].dttk_value,
5887 			    sizeof (struct in6_addr), mstate, vstate)) {
5888 				regs[rd] = 0;
5889 				break;
5890 			}
5891 
5892 			/*
5893 			 * Safely load the IPv6 address.
5894 			 */
5895 			dtrace_bcopy(
5896 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5897 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5898 
5899 			/*
5900 			 * Check an IPv6 string will fit in scratch.
5901 			 */
5902 			size = INET6_ADDRSTRLEN;
5903 			if (!DTRACE_INSCRATCH(mstate, size)) {
5904 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5905 				regs[rd] = 0;
5906 				break;
5907 			}
5908 			base = (char *)mstate->dtms_scratch_ptr;
5909 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5910 			*end-- = '\0';
5911 
5912 			/*
5913 			 * Find the longest run of 16 bit zero values
5914 			 * for the single allowed zero compression - "::".
5915 			 */
5916 			firstzero = -1;
5917 			tryzero = -1;
5918 			numzero = 1;
5919 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5920 #ifdef illumos
5921 				if (ip6._S6_un._S6_u8[i] == 0 &&
5922 #else
5923 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5924 #endif
5925 				    tryzero == -1 && i % 2 == 0) {
5926 					tryzero = i;
5927 					continue;
5928 				}
5929 
5930 				if (tryzero != -1 &&
5931 #ifdef illumos
5932 				    (ip6._S6_un._S6_u8[i] != 0 ||
5933 #else
5934 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5935 #endif
5936 				    i == sizeof (struct in6_addr) - 1)) {
5937 
5938 					if (i - tryzero <= numzero) {
5939 						tryzero = -1;
5940 						continue;
5941 					}
5942 
5943 					firstzero = tryzero;
5944 					numzero = i - i % 2 - tryzero;
5945 					tryzero = -1;
5946 
5947 #ifdef illumos
5948 					if (ip6._S6_un._S6_u8[i] == 0 &&
5949 #else
5950 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5951 #endif
5952 					    i == sizeof (struct in6_addr) - 1)
5953 						numzero += 2;
5954 				}
5955 			}
5956 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5957 
5958 			/*
5959 			 * Check for an IPv4 embedded address.
5960 			 */
5961 			v6end = sizeof (struct in6_addr) - 2;
5962 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5963 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5964 				for (i = sizeof (struct in6_addr) - 1;
5965 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5966 					ASSERT(end >= base);
5967 
5968 #ifdef illumos
5969 					val = ip6._S6_un._S6_u8[i];
5970 #else
5971 					val = ip6.__u6_addr.__u6_addr8[i];
5972 #endif
5973 
5974 					if (val == 0) {
5975 						*end-- = '0';
5976 					} else {
5977 						for (; val; val /= 10) {
5978 							*end-- = '0' + val % 10;
5979 						}
5980 					}
5981 
5982 					if (i > DTRACE_V4MAPPED_OFFSET)
5983 						*end-- = '.';
5984 				}
5985 
5986 				if (subr == DIF_SUBR_INET_NTOA6)
5987 					goto inetout;
5988 
5989 				/*
5990 				 * Set v6end to skip the IPv4 address that
5991 				 * we have already stringified.
5992 				 */
5993 				v6end = 10;
5994 			}
5995 
5996 			/*
5997 			 * Build the IPv6 string by working through the
5998 			 * address in reverse.
5999 			 */
6000 			for (i = v6end; i >= 0; i -= 2) {
6001 				ASSERT(end >= base);
6002 
6003 				if (i == firstzero + numzero - 2) {
6004 					*end-- = ':';
6005 					*end-- = ':';
6006 					i -= numzero - 2;
6007 					continue;
6008 				}
6009 
6010 				if (i < 14 && i != firstzero - 2)
6011 					*end-- = ':';
6012 
6013 #ifdef illumos
6014 				val = (ip6._S6_un._S6_u8[i] << 8) +
6015 				    ip6._S6_un._S6_u8[i + 1];
6016 #else
6017 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6018 				    ip6.__u6_addr.__u6_addr8[i + 1];
6019 #endif
6020 
6021 				if (val == 0) {
6022 					*end-- = '0';
6023 				} else {
6024 					for (; val; val /= 16) {
6025 						*end-- = digits[val % 16];
6026 					}
6027 				}
6028 			}
6029 			ASSERT(end + 1 >= base);
6030 
6031 		} else {
6032 			/*
6033 			 * The user didn't use AH_INET or AH_INET6.
6034 			 */
6035 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6036 			regs[rd] = 0;
6037 			break;
6038 		}
6039 
6040 inetout:	regs[rd] = (uintptr_t)end + 1;
6041 		mstate->dtms_scratch_ptr += size;
6042 		break;
6043 	}
6044 
6045 	case DIF_SUBR_MEMREF: {
6046 		uintptr_t size = 2 * sizeof(uintptr_t);
6047 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6048 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6049 
6050 		/* address and length */
6051 		memref[0] = tupregs[0].dttk_value;
6052 		memref[1] = tupregs[1].dttk_value;
6053 
6054 		regs[rd] = (uintptr_t) memref;
6055 		mstate->dtms_scratch_ptr += scratch_size;
6056 		break;
6057 	}
6058 
6059 #ifndef illumos
6060 	case DIF_SUBR_MEMSTR: {
6061 		char *str = (char *)mstate->dtms_scratch_ptr;
6062 		uintptr_t mem = tupregs[0].dttk_value;
6063 		char c = tupregs[1].dttk_value;
6064 		size_t size = tupregs[2].dttk_value;
6065 		uint8_t n;
6066 		int i;
6067 
6068 		regs[rd] = 0;
6069 
6070 		if (size == 0)
6071 			break;
6072 
6073 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6074 			break;
6075 
6076 		if (!DTRACE_INSCRATCH(mstate, size)) {
6077 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6078 			break;
6079 		}
6080 
6081 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6082 			*flags |= CPU_DTRACE_ILLOP;
6083 			break;
6084 		}
6085 
6086 		for (i = 0; i < size - 1; i++) {
6087 			n = dtrace_load8(mem++);
6088 			str[i] = (n == 0) ? c : n;
6089 		}
6090 		str[size - 1] = 0;
6091 
6092 		regs[rd] = (uintptr_t)str;
6093 		mstate->dtms_scratch_ptr += size;
6094 		break;
6095 	}
6096 #endif
6097 	}
6098 }
6099 
6100 /*
6101  * Emulate the execution of DTrace IR instructions specified by the given
6102  * DIF object.  This function is deliberately void of assertions as all of
6103  * the necessary checks are handled by a call to dtrace_difo_validate().
6104  */
6105 static uint64_t
6106 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6107     dtrace_vstate_t *vstate, dtrace_state_t *state)
6108 {
6109 	const dif_instr_t *text = difo->dtdo_buf;
6110 	const uint_t textlen = difo->dtdo_len;
6111 	const char *strtab = difo->dtdo_strtab;
6112 	const uint64_t *inttab = difo->dtdo_inttab;
6113 
6114 	uint64_t rval = 0;
6115 	dtrace_statvar_t *svar;
6116 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6117 	dtrace_difv_t *v;
6118 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6119 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6120 
6121 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6122 	uint64_t regs[DIF_DIR_NREGS];
6123 	uint64_t *tmp;
6124 
6125 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6126 	int64_t cc_r;
6127 	uint_t pc = 0, id, opc = 0;
6128 	uint8_t ttop = 0;
6129 	dif_instr_t instr;
6130 	uint_t r1, r2, rd;
6131 
6132 	/*
6133 	 * We stash the current DIF object into the machine state: we need it
6134 	 * for subsequent access checking.
6135 	 */
6136 	mstate->dtms_difo = difo;
6137 
6138 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6139 
6140 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6141 		opc = pc;
6142 
6143 		instr = text[pc++];
6144 		r1 = DIF_INSTR_R1(instr);
6145 		r2 = DIF_INSTR_R2(instr);
6146 		rd = DIF_INSTR_RD(instr);
6147 
6148 		switch (DIF_INSTR_OP(instr)) {
6149 		case DIF_OP_OR:
6150 			regs[rd] = regs[r1] | regs[r2];
6151 			break;
6152 		case DIF_OP_XOR:
6153 			regs[rd] = regs[r1] ^ regs[r2];
6154 			break;
6155 		case DIF_OP_AND:
6156 			regs[rd] = regs[r1] & regs[r2];
6157 			break;
6158 		case DIF_OP_SLL:
6159 			regs[rd] = regs[r1] << regs[r2];
6160 			break;
6161 		case DIF_OP_SRL:
6162 			regs[rd] = regs[r1] >> regs[r2];
6163 			break;
6164 		case DIF_OP_SUB:
6165 			regs[rd] = regs[r1] - regs[r2];
6166 			break;
6167 		case DIF_OP_ADD:
6168 			regs[rd] = regs[r1] + regs[r2];
6169 			break;
6170 		case DIF_OP_MUL:
6171 			regs[rd] = regs[r1] * regs[r2];
6172 			break;
6173 		case DIF_OP_SDIV:
6174 			if (regs[r2] == 0) {
6175 				regs[rd] = 0;
6176 				*flags |= CPU_DTRACE_DIVZERO;
6177 			} else {
6178 				regs[rd] = (int64_t)regs[r1] /
6179 				    (int64_t)regs[r2];
6180 			}
6181 			break;
6182 
6183 		case DIF_OP_UDIV:
6184 			if (regs[r2] == 0) {
6185 				regs[rd] = 0;
6186 				*flags |= CPU_DTRACE_DIVZERO;
6187 			} else {
6188 				regs[rd] = regs[r1] / regs[r2];
6189 			}
6190 			break;
6191 
6192 		case DIF_OP_SREM:
6193 			if (regs[r2] == 0) {
6194 				regs[rd] = 0;
6195 				*flags |= CPU_DTRACE_DIVZERO;
6196 			} else {
6197 				regs[rd] = (int64_t)regs[r1] %
6198 				    (int64_t)regs[r2];
6199 			}
6200 			break;
6201 
6202 		case DIF_OP_UREM:
6203 			if (regs[r2] == 0) {
6204 				regs[rd] = 0;
6205 				*flags |= CPU_DTRACE_DIVZERO;
6206 			} else {
6207 				regs[rd] = regs[r1] % regs[r2];
6208 			}
6209 			break;
6210 
6211 		case DIF_OP_NOT:
6212 			regs[rd] = ~regs[r1];
6213 			break;
6214 		case DIF_OP_MOV:
6215 			regs[rd] = regs[r1];
6216 			break;
6217 		case DIF_OP_CMP:
6218 			cc_r = regs[r1] - regs[r2];
6219 			cc_n = cc_r < 0;
6220 			cc_z = cc_r == 0;
6221 			cc_v = 0;
6222 			cc_c = regs[r1] < regs[r2];
6223 			break;
6224 		case DIF_OP_TST:
6225 			cc_n = cc_v = cc_c = 0;
6226 			cc_z = regs[r1] == 0;
6227 			break;
6228 		case DIF_OP_BA:
6229 			pc = DIF_INSTR_LABEL(instr);
6230 			break;
6231 		case DIF_OP_BE:
6232 			if (cc_z)
6233 				pc = DIF_INSTR_LABEL(instr);
6234 			break;
6235 		case DIF_OP_BNE:
6236 			if (cc_z == 0)
6237 				pc = DIF_INSTR_LABEL(instr);
6238 			break;
6239 		case DIF_OP_BG:
6240 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6241 				pc = DIF_INSTR_LABEL(instr);
6242 			break;
6243 		case DIF_OP_BGU:
6244 			if ((cc_c | cc_z) == 0)
6245 				pc = DIF_INSTR_LABEL(instr);
6246 			break;
6247 		case DIF_OP_BGE:
6248 			if ((cc_n ^ cc_v) == 0)
6249 				pc = DIF_INSTR_LABEL(instr);
6250 			break;
6251 		case DIF_OP_BGEU:
6252 			if (cc_c == 0)
6253 				pc = DIF_INSTR_LABEL(instr);
6254 			break;
6255 		case DIF_OP_BL:
6256 			if (cc_n ^ cc_v)
6257 				pc = DIF_INSTR_LABEL(instr);
6258 			break;
6259 		case DIF_OP_BLU:
6260 			if (cc_c)
6261 				pc = DIF_INSTR_LABEL(instr);
6262 			break;
6263 		case DIF_OP_BLE:
6264 			if (cc_z | (cc_n ^ cc_v))
6265 				pc = DIF_INSTR_LABEL(instr);
6266 			break;
6267 		case DIF_OP_BLEU:
6268 			if (cc_c | cc_z)
6269 				pc = DIF_INSTR_LABEL(instr);
6270 			break;
6271 		case DIF_OP_RLDSB:
6272 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6273 				break;
6274 			/*FALLTHROUGH*/
6275 		case DIF_OP_LDSB:
6276 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6277 			break;
6278 		case DIF_OP_RLDSH:
6279 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6280 				break;
6281 			/*FALLTHROUGH*/
6282 		case DIF_OP_LDSH:
6283 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6284 			break;
6285 		case DIF_OP_RLDSW:
6286 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6287 				break;
6288 			/*FALLTHROUGH*/
6289 		case DIF_OP_LDSW:
6290 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6291 			break;
6292 		case DIF_OP_RLDUB:
6293 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6294 				break;
6295 			/*FALLTHROUGH*/
6296 		case DIF_OP_LDUB:
6297 			regs[rd] = dtrace_load8(regs[r1]);
6298 			break;
6299 		case DIF_OP_RLDUH:
6300 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6301 				break;
6302 			/*FALLTHROUGH*/
6303 		case DIF_OP_LDUH:
6304 			regs[rd] = dtrace_load16(regs[r1]);
6305 			break;
6306 		case DIF_OP_RLDUW:
6307 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6308 				break;
6309 			/*FALLTHROUGH*/
6310 		case DIF_OP_LDUW:
6311 			regs[rd] = dtrace_load32(regs[r1]);
6312 			break;
6313 		case DIF_OP_RLDX:
6314 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6315 				break;
6316 			/*FALLTHROUGH*/
6317 		case DIF_OP_LDX:
6318 			regs[rd] = dtrace_load64(regs[r1]);
6319 			break;
6320 		case DIF_OP_ULDSB:
6321 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6322 			regs[rd] = (int8_t)
6323 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6324 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6325 			break;
6326 		case DIF_OP_ULDSH:
6327 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6328 			regs[rd] = (int16_t)
6329 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6330 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6331 			break;
6332 		case DIF_OP_ULDSW:
6333 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6334 			regs[rd] = (int32_t)
6335 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6336 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6337 			break;
6338 		case DIF_OP_ULDUB:
6339 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6340 			regs[rd] =
6341 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6342 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6343 			break;
6344 		case DIF_OP_ULDUH:
6345 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6346 			regs[rd] =
6347 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6348 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6349 			break;
6350 		case DIF_OP_ULDUW:
6351 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6352 			regs[rd] =
6353 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6354 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6355 			break;
6356 		case DIF_OP_ULDX:
6357 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6358 			regs[rd] =
6359 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6360 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6361 			break;
6362 		case DIF_OP_RET:
6363 			rval = regs[rd];
6364 			pc = textlen;
6365 			break;
6366 		case DIF_OP_NOP:
6367 			break;
6368 		case DIF_OP_SETX:
6369 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6370 			break;
6371 		case DIF_OP_SETS:
6372 			regs[rd] = (uint64_t)(uintptr_t)
6373 			    (strtab + DIF_INSTR_STRING(instr));
6374 			break;
6375 		case DIF_OP_SCMP: {
6376 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6377 			uintptr_t s1 = regs[r1];
6378 			uintptr_t s2 = regs[r2];
6379 			size_t lim1, lim2;
6380 
6381 			/*
6382 			 * If one of the strings is NULL then the limit becomes
6383 			 * 0 which compares 0 characters in dtrace_strncmp()
6384 			 * resulting in a false positive.  dtrace_strncmp()
6385 			 * treats a NULL as an empty 1-char string.
6386 			 */
6387 			lim1 = lim2 = 1;
6388 
6389 			if (s1 != 0 &&
6390 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6391 				break;
6392 			if (s2 != 0 &&
6393 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6394 				break;
6395 
6396 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6397 			    MIN(lim1, lim2));
6398 
6399 			cc_n = cc_r < 0;
6400 			cc_z = cc_r == 0;
6401 			cc_v = cc_c = 0;
6402 			break;
6403 		}
6404 		case DIF_OP_LDGA:
6405 			regs[rd] = dtrace_dif_variable(mstate, state,
6406 			    r1, regs[r2]);
6407 			break;
6408 		case DIF_OP_LDGS:
6409 			id = DIF_INSTR_VAR(instr);
6410 
6411 			if (id >= DIF_VAR_OTHER_UBASE) {
6412 				uintptr_t a;
6413 
6414 				id -= DIF_VAR_OTHER_UBASE;
6415 				svar = vstate->dtvs_globals[id];
6416 				ASSERT(svar != NULL);
6417 				v = &svar->dtsv_var;
6418 
6419 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6420 					regs[rd] = svar->dtsv_data;
6421 					break;
6422 				}
6423 
6424 				a = (uintptr_t)svar->dtsv_data;
6425 
6426 				if (*(uint8_t *)a == UINT8_MAX) {
6427 					/*
6428 					 * If the 0th byte is set to UINT8_MAX
6429 					 * then this is to be treated as a
6430 					 * reference to a NULL variable.
6431 					 */
6432 					regs[rd] = 0;
6433 				} else {
6434 					regs[rd] = a + sizeof (uint64_t);
6435 				}
6436 
6437 				break;
6438 			}
6439 
6440 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6441 			break;
6442 
6443 		case DIF_OP_STGS:
6444 			id = DIF_INSTR_VAR(instr);
6445 
6446 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6447 			id -= DIF_VAR_OTHER_UBASE;
6448 
6449 			VERIFY(id < vstate->dtvs_nglobals);
6450 			svar = vstate->dtvs_globals[id];
6451 			ASSERT(svar != NULL);
6452 			v = &svar->dtsv_var;
6453 
6454 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6455 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6456 				size_t lim;
6457 
6458 				ASSERT(a != 0);
6459 				ASSERT(svar->dtsv_size != 0);
6460 
6461 				if (regs[rd] == 0) {
6462 					*(uint8_t *)a = UINT8_MAX;
6463 					break;
6464 				} else {
6465 					*(uint8_t *)a = 0;
6466 					a += sizeof (uint64_t);
6467 				}
6468 				if (!dtrace_vcanload(
6469 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6470 				    &lim, mstate, vstate))
6471 					break;
6472 
6473 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6474 				    (void *)a, &v->dtdv_type, lim);
6475 				break;
6476 			}
6477 
6478 			svar->dtsv_data = regs[rd];
6479 			break;
6480 
6481 		case DIF_OP_LDTA:
6482 			/*
6483 			 * There are no DTrace built-in thread-local arrays at
6484 			 * present.  This opcode is saved for future work.
6485 			 */
6486 			*flags |= CPU_DTRACE_ILLOP;
6487 			regs[rd] = 0;
6488 			break;
6489 
6490 		case DIF_OP_LDLS:
6491 			id = DIF_INSTR_VAR(instr);
6492 
6493 			if (id < DIF_VAR_OTHER_UBASE) {
6494 				/*
6495 				 * For now, this has no meaning.
6496 				 */
6497 				regs[rd] = 0;
6498 				break;
6499 			}
6500 
6501 			id -= DIF_VAR_OTHER_UBASE;
6502 
6503 			ASSERT(id < vstate->dtvs_nlocals);
6504 			ASSERT(vstate->dtvs_locals != NULL);
6505 
6506 			svar = vstate->dtvs_locals[id];
6507 			ASSERT(svar != NULL);
6508 			v = &svar->dtsv_var;
6509 
6510 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6511 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6512 				size_t sz = v->dtdv_type.dtdt_size;
6513 				size_t lim;
6514 
6515 				sz += sizeof (uint64_t);
6516 				ASSERT(svar->dtsv_size == NCPU * sz);
6517 				a += curcpu * sz;
6518 
6519 				if (*(uint8_t *)a == UINT8_MAX) {
6520 					/*
6521 					 * If the 0th byte is set to UINT8_MAX
6522 					 * then this is to be treated as a
6523 					 * reference to a NULL variable.
6524 					 */
6525 					regs[rd] = 0;
6526 				} else {
6527 					regs[rd] = a + sizeof (uint64_t);
6528 				}
6529 
6530 				break;
6531 			}
6532 
6533 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6534 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6535 			regs[rd] = tmp[curcpu];
6536 			break;
6537 
6538 		case DIF_OP_STLS:
6539 			id = DIF_INSTR_VAR(instr);
6540 
6541 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6542 			id -= DIF_VAR_OTHER_UBASE;
6543 			VERIFY(id < vstate->dtvs_nlocals);
6544 
6545 			ASSERT(vstate->dtvs_locals != NULL);
6546 			svar = vstate->dtvs_locals[id];
6547 			ASSERT(svar != NULL);
6548 			v = &svar->dtsv_var;
6549 
6550 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6551 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6552 				size_t sz = v->dtdv_type.dtdt_size;
6553 				size_t lim;
6554 
6555 				sz += sizeof (uint64_t);
6556 				ASSERT(svar->dtsv_size == NCPU * sz);
6557 				a += curcpu * sz;
6558 
6559 				if (regs[rd] == 0) {
6560 					*(uint8_t *)a = UINT8_MAX;
6561 					break;
6562 				} else {
6563 					*(uint8_t *)a = 0;
6564 					a += sizeof (uint64_t);
6565 				}
6566 
6567 				if (!dtrace_vcanload(
6568 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6569 				    &lim, mstate, vstate))
6570 					break;
6571 
6572 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6573 				    (void *)a, &v->dtdv_type, lim);
6574 				break;
6575 			}
6576 
6577 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6578 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6579 			tmp[curcpu] = regs[rd];
6580 			break;
6581 
6582 		case DIF_OP_LDTS: {
6583 			dtrace_dynvar_t *dvar;
6584 			dtrace_key_t *key;
6585 
6586 			id = DIF_INSTR_VAR(instr);
6587 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6588 			id -= DIF_VAR_OTHER_UBASE;
6589 			v = &vstate->dtvs_tlocals[id];
6590 
6591 			key = &tupregs[DIF_DTR_NREGS];
6592 			key[0].dttk_value = (uint64_t)id;
6593 			key[0].dttk_size = 0;
6594 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6595 			key[1].dttk_size = 0;
6596 
6597 			dvar = dtrace_dynvar(dstate, 2, key,
6598 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6599 			    mstate, vstate);
6600 
6601 			if (dvar == NULL) {
6602 				regs[rd] = 0;
6603 				break;
6604 			}
6605 
6606 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6607 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6608 			} else {
6609 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6610 			}
6611 
6612 			break;
6613 		}
6614 
6615 		case DIF_OP_STTS: {
6616 			dtrace_dynvar_t *dvar;
6617 			dtrace_key_t *key;
6618 
6619 			id = DIF_INSTR_VAR(instr);
6620 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6621 			id -= DIF_VAR_OTHER_UBASE;
6622 			VERIFY(id < vstate->dtvs_ntlocals);
6623 
6624 			key = &tupregs[DIF_DTR_NREGS];
6625 			key[0].dttk_value = (uint64_t)id;
6626 			key[0].dttk_size = 0;
6627 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6628 			key[1].dttk_size = 0;
6629 			v = &vstate->dtvs_tlocals[id];
6630 
6631 			dvar = dtrace_dynvar(dstate, 2, key,
6632 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6633 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6634 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6635 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6636 
6637 			/*
6638 			 * Given that we're storing to thread-local data,
6639 			 * we need to flush our predicate cache.
6640 			 */
6641 			curthread->t_predcache = 0;
6642 
6643 			if (dvar == NULL)
6644 				break;
6645 
6646 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6647 				size_t lim;
6648 
6649 				if (!dtrace_vcanload(
6650 				    (void *)(uintptr_t)regs[rd],
6651 				    &v->dtdv_type, &lim, mstate, vstate))
6652 					break;
6653 
6654 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6655 				    dvar->dtdv_data, &v->dtdv_type, lim);
6656 			} else {
6657 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6658 			}
6659 
6660 			break;
6661 		}
6662 
6663 		case DIF_OP_SRA:
6664 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6665 			break;
6666 
6667 		case DIF_OP_CALL:
6668 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6669 			    regs, tupregs, ttop, mstate, state);
6670 			break;
6671 
6672 		case DIF_OP_PUSHTR:
6673 			if (ttop == DIF_DTR_NREGS) {
6674 				*flags |= CPU_DTRACE_TUPOFLOW;
6675 				break;
6676 			}
6677 
6678 			if (r1 == DIF_TYPE_STRING) {
6679 				/*
6680 				 * If this is a string type and the size is 0,
6681 				 * we'll use the system-wide default string
6682 				 * size.  Note that we are _not_ looking at
6683 				 * the value of the DTRACEOPT_STRSIZE option;
6684 				 * had this been set, we would expect to have
6685 				 * a non-zero size value in the "pushtr".
6686 				 */
6687 				tupregs[ttop].dttk_size =
6688 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6689 				    regs[r2] ? regs[r2] :
6690 				    dtrace_strsize_default) + 1;
6691 			} else {
6692 				if (regs[r2] > LONG_MAX) {
6693 					*flags |= CPU_DTRACE_ILLOP;
6694 					break;
6695 				}
6696 
6697 				tupregs[ttop].dttk_size = regs[r2];
6698 			}
6699 
6700 			tupregs[ttop++].dttk_value = regs[rd];
6701 			break;
6702 
6703 		case DIF_OP_PUSHTV:
6704 			if (ttop == DIF_DTR_NREGS) {
6705 				*flags |= CPU_DTRACE_TUPOFLOW;
6706 				break;
6707 			}
6708 
6709 			tupregs[ttop].dttk_value = regs[rd];
6710 			tupregs[ttop++].dttk_size = 0;
6711 			break;
6712 
6713 		case DIF_OP_POPTS:
6714 			if (ttop != 0)
6715 				ttop--;
6716 			break;
6717 
6718 		case DIF_OP_FLUSHTS:
6719 			ttop = 0;
6720 			break;
6721 
6722 		case DIF_OP_LDGAA:
6723 		case DIF_OP_LDTAA: {
6724 			dtrace_dynvar_t *dvar;
6725 			dtrace_key_t *key = tupregs;
6726 			uint_t nkeys = ttop;
6727 
6728 			id = DIF_INSTR_VAR(instr);
6729 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6730 			id -= DIF_VAR_OTHER_UBASE;
6731 
6732 			key[nkeys].dttk_value = (uint64_t)id;
6733 			key[nkeys++].dttk_size = 0;
6734 
6735 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6736 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6737 				key[nkeys++].dttk_size = 0;
6738 				VERIFY(id < vstate->dtvs_ntlocals);
6739 				v = &vstate->dtvs_tlocals[id];
6740 			} else {
6741 				VERIFY(id < vstate->dtvs_nglobals);
6742 				v = &vstate->dtvs_globals[id]->dtsv_var;
6743 			}
6744 
6745 			dvar = dtrace_dynvar(dstate, nkeys, key,
6746 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6747 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6748 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6749 
6750 			if (dvar == NULL) {
6751 				regs[rd] = 0;
6752 				break;
6753 			}
6754 
6755 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6756 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6757 			} else {
6758 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6759 			}
6760 
6761 			break;
6762 		}
6763 
6764 		case DIF_OP_STGAA:
6765 		case DIF_OP_STTAA: {
6766 			dtrace_dynvar_t *dvar;
6767 			dtrace_key_t *key = tupregs;
6768 			uint_t nkeys = ttop;
6769 
6770 			id = DIF_INSTR_VAR(instr);
6771 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6772 			id -= DIF_VAR_OTHER_UBASE;
6773 
6774 			key[nkeys].dttk_value = (uint64_t)id;
6775 			key[nkeys++].dttk_size = 0;
6776 
6777 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6778 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6779 				key[nkeys++].dttk_size = 0;
6780 				VERIFY(id < vstate->dtvs_ntlocals);
6781 				v = &vstate->dtvs_tlocals[id];
6782 			} else {
6783 				VERIFY(id < vstate->dtvs_nglobals);
6784 				v = &vstate->dtvs_globals[id]->dtsv_var;
6785 			}
6786 
6787 			dvar = dtrace_dynvar(dstate, nkeys, key,
6788 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6789 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6790 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6791 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6792 
6793 			if (dvar == NULL)
6794 				break;
6795 
6796 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6797 				size_t lim;
6798 
6799 				if (!dtrace_vcanload(
6800 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6801 				    &lim, mstate, vstate))
6802 					break;
6803 
6804 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6805 				    dvar->dtdv_data, &v->dtdv_type, lim);
6806 			} else {
6807 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6808 			}
6809 
6810 			break;
6811 		}
6812 
6813 		case DIF_OP_ALLOCS: {
6814 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6815 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6816 
6817 			/*
6818 			 * Rounding up the user allocation size could have
6819 			 * overflowed large, bogus allocations (like -1ULL) to
6820 			 * 0.
6821 			 */
6822 			if (size < regs[r1] ||
6823 			    !DTRACE_INSCRATCH(mstate, size)) {
6824 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6825 				regs[rd] = 0;
6826 				break;
6827 			}
6828 
6829 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6830 			mstate->dtms_scratch_ptr += size;
6831 			regs[rd] = ptr;
6832 			break;
6833 		}
6834 
6835 		case DIF_OP_COPYS:
6836 			if (!dtrace_canstore(regs[rd], regs[r2],
6837 			    mstate, vstate)) {
6838 				*flags |= CPU_DTRACE_BADADDR;
6839 				*illval = regs[rd];
6840 				break;
6841 			}
6842 
6843 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6844 				break;
6845 
6846 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6847 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6848 			break;
6849 
6850 		case DIF_OP_STB:
6851 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6852 				*flags |= CPU_DTRACE_BADADDR;
6853 				*illval = regs[rd];
6854 				break;
6855 			}
6856 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6857 			break;
6858 
6859 		case DIF_OP_STH:
6860 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6861 				*flags |= CPU_DTRACE_BADADDR;
6862 				*illval = regs[rd];
6863 				break;
6864 			}
6865 			if (regs[rd] & 1) {
6866 				*flags |= CPU_DTRACE_BADALIGN;
6867 				*illval = regs[rd];
6868 				break;
6869 			}
6870 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6871 			break;
6872 
6873 		case DIF_OP_STW:
6874 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6875 				*flags |= CPU_DTRACE_BADADDR;
6876 				*illval = regs[rd];
6877 				break;
6878 			}
6879 			if (regs[rd] & 3) {
6880 				*flags |= CPU_DTRACE_BADALIGN;
6881 				*illval = regs[rd];
6882 				break;
6883 			}
6884 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6885 			break;
6886 
6887 		case DIF_OP_STX:
6888 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6889 				*flags |= CPU_DTRACE_BADADDR;
6890 				*illval = regs[rd];
6891 				break;
6892 			}
6893 			if (regs[rd] & 7) {
6894 				*flags |= CPU_DTRACE_BADALIGN;
6895 				*illval = regs[rd];
6896 				break;
6897 			}
6898 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6899 			break;
6900 		}
6901 	}
6902 
6903 	if (!(*flags & CPU_DTRACE_FAULT))
6904 		return (rval);
6905 
6906 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6907 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6908 
6909 	return (0);
6910 }
6911 
6912 static void
6913 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6914 {
6915 	dtrace_probe_t *probe = ecb->dte_probe;
6916 	dtrace_provider_t *prov = probe->dtpr_provider;
6917 	char c[DTRACE_FULLNAMELEN + 80], *str;
6918 	char *msg = "dtrace: breakpoint action at probe ";
6919 	char *ecbmsg = " (ecb ";
6920 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6921 	uintptr_t val = (uintptr_t)ecb;
6922 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6923 
6924 	if (dtrace_destructive_disallow)
6925 		return;
6926 
6927 	/*
6928 	 * It's impossible to be taking action on the NULL probe.
6929 	 */
6930 	ASSERT(probe != NULL);
6931 
6932 	/*
6933 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6934 	 * print the provider name, module name, function name and name of
6935 	 * the probe, along with the hex address of the ECB with the breakpoint
6936 	 * action -- all of which we must place in the character buffer by
6937 	 * hand.
6938 	 */
6939 	while (*msg != '\0')
6940 		c[i++] = *msg++;
6941 
6942 	for (str = prov->dtpv_name; *str != '\0'; str++)
6943 		c[i++] = *str;
6944 	c[i++] = ':';
6945 
6946 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6947 		c[i++] = *str;
6948 	c[i++] = ':';
6949 
6950 	for (str = probe->dtpr_func; *str != '\0'; str++)
6951 		c[i++] = *str;
6952 	c[i++] = ':';
6953 
6954 	for (str = probe->dtpr_name; *str != '\0'; str++)
6955 		c[i++] = *str;
6956 
6957 	while (*ecbmsg != '\0')
6958 		c[i++] = *ecbmsg++;
6959 
6960 	while (shift >= 0) {
6961 		mask = (uintptr_t)0xf << shift;
6962 
6963 		if (val >= ((uintptr_t)1 << shift))
6964 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6965 		shift -= 4;
6966 	}
6967 
6968 	c[i++] = ')';
6969 	c[i] = '\0';
6970 
6971 #ifdef illumos
6972 	debug_enter(c);
6973 #else
6974 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6975 #endif
6976 }
6977 
6978 static void
6979 dtrace_action_panic(dtrace_ecb_t *ecb)
6980 {
6981 	dtrace_probe_t *probe = ecb->dte_probe;
6982 
6983 	/*
6984 	 * It's impossible to be taking action on the NULL probe.
6985 	 */
6986 	ASSERT(probe != NULL);
6987 
6988 	if (dtrace_destructive_disallow)
6989 		return;
6990 
6991 	if (dtrace_panicked != NULL)
6992 		return;
6993 
6994 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6995 		return;
6996 
6997 	/*
6998 	 * We won the right to panic.  (We want to be sure that only one
6999 	 * thread calls panic() from dtrace_probe(), and that panic() is
7000 	 * called exactly once.)
7001 	 */
7002 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
7003 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
7004 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
7005 }
7006 
7007 static void
7008 dtrace_action_raise(uint64_t sig)
7009 {
7010 	if (dtrace_destructive_disallow)
7011 		return;
7012 
7013 	if (sig >= NSIG) {
7014 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7015 		return;
7016 	}
7017 
7018 #ifdef illumos
7019 	/*
7020 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7021 	 * invocations of the raise() action.
7022 	 */
7023 	if (curthread->t_dtrace_sig == 0)
7024 		curthread->t_dtrace_sig = (uint8_t)sig;
7025 
7026 	curthread->t_sig_check = 1;
7027 	aston(curthread);
7028 #else
7029 	struct proc *p = curproc;
7030 	PROC_LOCK(p);
7031 	kern_psignal(p, sig);
7032 	PROC_UNLOCK(p);
7033 #endif
7034 }
7035 
7036 static void
7037 dtrace_action_stop(void)
7038 {
7039 	if (dtrace_destructive_disallow)
7040 		return;
7041 
7042 #ifdef illumos
7043 	if (!curthread->t_dtrace_stop) {
7044 		curthread->t_dtrace_stop = 1;
7045 		curthread->t_sig_check = 1;
7046 		aston(curthread);
7047 	}
7048 #else
7049 	struct proc *p = curproc;
7050 	PROC_LOCK(p);
7051 	kern_psignal(p, SIGSTOP);
7052 	PROC_UNLOCK(p);
7053 #endif
7054 }
7055 
7056 static void
7057 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7058 {
7059 	hrtime_t now;
7060 	volatile uint16_t *flags;
7061 #ifdef illumos
7062 	cpu_t *cpu = CPU;
7063 #else
7064 	cpu_t *cpu = &solaris_cpu[curcpu];
7065 #endif
7066 
7067 	if (dtrace_destructive_disallow)
7068 		return;
7069 
7070 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7071 
7072 	now = dtrace_gethrtime();
7073 
7074 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7075 		/*
7076 		 * We need to advance the mark to the current time.
7077 		 */
7078 		cpu->cpu_dtrace_chillmark = now;
7079 		cpu->cpu_dtrace_chilled = 0;
7080 	}
7081 
7082 	/*
7083 	 * Now check to see if the requested chill time would take us over
7084 	 * the maximum amount of time allowed in the chill interval.  (Or
7085 	 * worse, if the calculation itself induces overflow.)
7086 	 */
7087 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7088 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7089 		*flags |= CPU_DTRACE_ILLOP;
7090 		return;
7091 	}
7092 
7093 	while (dtrace_gethrtime() - now < val)
7094 		continue;
7095 
7096 	/*
7097 	 * Normally, we assure that the value of the variable "timestamp" does
7098 	 * not change within an ECB.  The presence of chill() represents an
7099 	 * exception to this rule, however.
7100 	 */
7101 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7102 	cpu->cpu_dtrace_chilled += val;
7103 }
7104 
7105 static void
7106 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7107     uint64_t *buf, uint64_t arg)
7108 {
7109 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7110 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7111 	uint64_t *pcs = &buf[1], *fps;
7112 	char *str = (char *)&pcs[nframes];
7113 	int size, offs = 0, i, j;
7114 	size_t rem;
7115 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7116 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7117 	char *sym;
7118 
7119 	/*
7120 	 * Should be taking a faster path if string space has not been
7121 	 * allocated.
7122 	 */
7123 	ASSERT(strsize != 0);
7124 
7125 	/*
7126 	 * We will first allocate some temporary space for the frame pointers.
7127 	 */
7128 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7129 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7130 	    (nframes * sizeof (uint64_t));
7131 
7132 	if (!DTRACE_INSCRATCH(mstate, size)) {
7133 		/*
7134 		 * Not enough room for our frame pointers -- need to indicate
7135 		 * that we ran out of scratch space.
7136 		 */
7137 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7138 		return;
7139 	}
7140 
7141 	mstate->dtms_scratch_ptr += size;
7142 	saved = mstate->dtms_scratch_ptr;
7143 
7144 	/*
7145 	 * Now get a stack with both program counters and frame pointers.
7146 	 */
7147 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7148 	dtrace_getufpstack(buf, fps, nframes + 1);
7149 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7150 
7151 	/*
7152 	 * If that faulted, we're cooked.
7153 	 */
7154 	if (*flags & CPU_DTRACE_FAULT)
7155 		goto out;
7156 
7157 	/*
7158 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7159 	 * each iteration, we restore the scratch pointer.
7160 	 */
7161 	for (i = 0; i < nframes; i++) {
7162 		mstate->dtms_scratch_ptr = saved;
7163 
7164 		if (offs >= strsize)
7165 			break;
7166 
7167 		sym = (char *)(uintptr_t)dtrace_helper(
7168 		    DTRACE_HELPER_ACTION_USTACK,
7169 		    mstate, state, pcs[i], fps[i]);
7170 
7171 		/*
7172 		 * If we faulted while running the helper, we're going to
7173 		 * clear the fault and null out the corresponding string.
7174 		 */
7175 		if (*flags & CPU_DTRACE_FAULT) {
7176 			*flags &= ~CPU_DTRACE_FAULT;
7177 			str[offs++] = '\0';
7178 			continue;
7179 		}
7180 
7181 		if (sym == NULL) {
7182 			str[offs++] = '\0';
7183 			continue;
7184 		}
7185 
7186 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7187 		    &(state->dts_vstate))) {
7188 			str[offs++] = '\0';
7189 			continue;
7190 		}
7191 
7192 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7193 
7194 		/*
7195 		 * Now copy in the string that the helper returned to us.
7196 		 */
7197 		for (j = 0; offs + j < strsize && j < rem; j++) {
7198 			if ((str[offs + j] = sym[j]) == '\0')
7199 				break;
7200 		}
7201 
7202 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7203 
7204 		offs += j + 1;
7205 	}
7206 
7207 	if (offs >= strsize) {
7208 		/*
7209 		 * If we didn't have room for all of the strings, we don't
7210 		 * abort processing -- this needn't be a fatal error -- but we
7211 		 * still want to increment a counter (dts_stkstroverflows) to
7212 		 * allow this condition to be warned about.  (If this is from
7213 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7214 		 */
7215 		dtrace_error(&state->dts_stkstroverflows);
7216 	}
7217 
7218 	while (offs < strsize)
7219 		str[offs++] = '\0';
7220 
7221 out:
7222 	mstate->dtms_scratch_ptr = old;
7223 }
7224 
7225 static void
7226 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7227     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7228 {
7229 	volatile uint16_t *flags;
7230 	uint64_t val = *valp;
7231 	size_t valoffs = *valoffsp;
7232 
7233 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7234 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7235 
7236 	/*
7237 	 * If this is a string, we're going to only load until we find the zero
7238 	 * byte -- after which we'll store zero bytes.
7239 	 */
7240 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7241 		char c = '\0' + 1;
7242 		size_t s;
7243 
7244 		for (s = 0; s < size; s++) {
7245 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7246 				c = dtrace_load8(val++);
7247 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7248 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7249 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7250 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7251 				if (*flags & CPU_DTRACE_FAULT)
7252 					break;
7253 			}
7254 
7255 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7256 
7257 			if (c == '\0' && intuple)
7258 				break;
7259 		}
7260 	} else {
7261 		uint8_t c;
7262 		while (valoffs < end) {
7263 			if (dtkind == DIF_TF_BYREF) {
7264 				c = dtrace_load8(val++);
7265 			} else if (dtkind == DIF_TF_BYUREF) {
7266 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7267 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7268 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7269 				if (*flags & CPU_DTRACE_FAULT)
7270 					break;
7271 			}
7272 
7273 			DTRACE_STORE(uint8_t, tomax,
7274 			    valoffs++, c);
7275 		}
7276 	}
7277 
7278 	*valp = val;
7279 	*valoffsp = valoffs;
7280 }
7281 
7282 /*
7283  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7284  * defined, we also assert that we are not recursing unless the probe ID is an
7285  * error probe.
7286  */
7287 static dtrace_icookie_t
7288 dtrace_probe_enter(dtrace_id_t id)
7289 {
7290 	dtrace_icookie_t cookie;
7291 
7292 	cookie = dtrace_interrupt_disable();
7293 
7294 	/*
7295 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7296 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7297 	 * function is instrumented that should not have been instrumented or
7298 	 * that the ordering guarantee of the records will be violated,
7299 	 * resulting in unexpected output. If there is an exception to this
7300 	 * assertion, a new case should be added.
7301 	 */
7302 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7303 	    id == dtrace_probeid_error);
7304 	curthread->t_dtrace_inprobe = 1;
7305 
7306 	return (cookie);
7307 }
7308 
7309 /*
7310  * Clears the per-thread inprobe flag and enables interrupts.
7311  */
7312 static void
7313 dtrace_probe_exit(dtrace_icookie_t cookie)
7314 {
7315 
7316 	curthread->t_dtrace_inprobe = 0;
7317 	dtrace_interrupt_enable(cookie);
7318 }
7319 
7320 /*
7321  * If you're looking for the epicenter of DTrace, you just found it.  This
7322  * is the function called by the provider to fire a probe -- from which all
7323  * subsequent probe-context DTrace activity emanates.
7324  */
7325 void
7326 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7327     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7328 {
7329 	processorid_t cpuid;
7330 	dtrace_icookie_t cookie;
7331 	dtrace_probe_t *probe;
7332 	dtrace_mstate_t mstate;
7333 	dtrace_ecb_t *ecb;
7334 	dtrace_action_t *act;
7335 	intptr_t offs;
7336 	size_t size;
7337 	int vtime, onintr;
7338 	volatile uint16_t *flags;
7339 	hrtime_t now;
7340 
7341 	if (KERNEL_PANICKED())
7342 		return;
7343 
7344 #ifdef illumos
7345 	/*
7346 	 * Kick out immediately if this CPU is still being born (in which case
7347 	 * curthread will be set to -1) or the current thread can't allow
7348 	 * probes in its current context.
7349 	 */
7350 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7351 		return;
7352 #endif
7353 
7354 	cookie = dtrace_probe_enter(id);
7355 	probe = dtrace_probes[id - 1];
7356 	cpuid = curcpu;
7357 	onintr = CPU_ON_INTR(CPU);
7358 
7359 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7360 	    probe->dtpr_predcache == curthread->t_predcache) {
7361 		/*
7362 		 * We have hit in the predicate cache; we know that
7363 		 * this predicate would evaluate to be false.
7364 		 */
7365 		dtrace_probe_exit(cookie);
7366 		return;
7367 	}
7368 
7369 #ifdef illumos
7370 	if (panic_quiesce) {
7371 #else
7372 	if (KERNEL_PANICKED()) {
7373 #endif
7374 		/*
7375 		 * We don't trace anything if we're panicking.
7376 		 */
7377 		dtrace_probe_exit(cookie);
7378 		return;
7379 	}
7380 
7381 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7382 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7383 	vtime = dtrace_vtime_references != 0;
7384 
7385 	if (vtime && curthread->t_dtrace_start)
7386 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7387 
7388 	mstate.dtms_difo = NULL;
7389 	mstate.dtms_probe = probe;
7390 	mstate.dtms_strtok = 0;
7391 	mstate.dtms_arg[0] = arg0;
7392 	mstate.dtms_arg[1] = arg1;
7393 	mstate.dtms_arg[2] = arg2;
7394 	mstate.dtms_arg[3] = arg3;
7395 	mstate.dtms_arg[4] = arg4;
7396 
7397 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7398 
7399 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7400 		dtrace_predicate_t *pred = ecb->dte_predicate;
7401 		dtrace_state_t *state = ecb->dte_state;
7402 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7403 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7404 		dtrace_vstate_t *vstate = &state->dts_vstate;
7405 		dtrace_provider_t *prov = probe->dtpr_provider;
7406 		uint64_t tracememsize = 0;
7407 		int committed = 0;
7408 		caddr_t tomax;
7409 
7410 		/*
7411 		 * A little subtlety with the following (seemingly innocuous)
7412 		 * declaration of the automatic 'val':  by looking at the
7413 		 * code, you might think that it could be declared in the
7414 		 * action processing loop, below.  (That is, it's only used in
7415 		 * the action processing loop.)  However, it must be declared
7416 		 * out of that scope because in the case of DIF expression
7417 		 * arguments to aggregating actions, one iteration of the
7418 		 * action loop will use the last iteration's value.
7419 		 */
7420 		uint64_t val = 0;
7421 
7422 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7423 		mstate.dtms_getf = NULL;
7424 
7425 		*flags &= ~CPU_DTRACE_ERROR;
7426 
7427 		if (prov == dtrace_provider) {
7428 			/*
7429 			 * If dtrace itself is the provider of this probe,
7430 			 * we're only going to continue processing the ECB if
7431 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7432 			 * creating state.  (This prevents disjoint consumers
7433 			 * from seeing one another's metaprobes.)
7434 			 */
7435 			if (arg0 != (uint64_t)(uintptr_t)state)
7436 				continue;
7437 		}
7438 
7439 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7440 			/*
7441 			 * We're not currently active.  If our provider isn't
7442 			 * the dtrace pseudo provider, we're not interested.
7443 			 */
7444 			if (prov != dtrace_provider)
7445 				continue;
7446 
7447 			/*
7448 			 * Now we must further check if we are in the BEGIN
7449 			 * probe.  If we are, we will only continue processing
7450 			 * if we're still in WARMUP -- if one BEGIN enabling
7451 			 * has invoked the exit() action, we don't want to
7452 			 * evaluate subsequent BEGIN enablings.
7453 			 */
7454 			if (probe->dtpr_id == dtrace_probeid_begin &&
7455 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7456 				ASSERT(state->dts_activity ==
7457 				    DTRACE_ACTIVITY_DRAINING);
7458 				continue;
7459 			}
7460 		}
7461 
7462 		if (ecb->dte_cond) {
7463 			/*
7464 			 * If the dte_cond bits indicate that this
7465 			 * consumer is only allowed to see user-mode firings
7466 			 * of this probe, call the provider's dtps_usermode()
7467 			 * entry point to check that the probe was fired
7468 			 * while in a user context. Skip this ECB if that's
7469 			 * not the case.
7470 			 */
7471 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7472 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7473 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7474 				continue;
7475 
7476 #ifdef illumos
7477 			/*
7478 			 * This is more subtle than it looks. We have to be
7479 			 * absolutely certain that CRED() isn't going to
7480 			 * change out from under us so it's only legit to
7481 			 * examine that structure if we're in constrained
7482 			 * situations. Currently, the only times we'll this
7483 			 * check is if a non-super-user has enabled the
7484 			 * profile or syscall providers -- providers that
7485 			 * allow visibility of all processes. For the
7486 			 * profile case, the check above will ensure that
7487 			 * we're examining a user context.
7488 			 */
7489 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7490 				cred_t *cr;
7491 				cred_t *s_cr =
7492 				    ecb->dte_state->dts_cred.dcr_cred;
7493 				proc_t *proc;
7494 
7495 				ASSERT(s_cr != NULL);
7496 
7497 				if ((cr = CRED()) == NULL ||
7498 				    s_cr->cr_uid != cr->cr_uid ||
7499 				    s_cr->cr_uid != cr->cr_ruid ||
7500 				    s_cr->cr_uid != cr->cr_suid ||
7501 				    s_cr->cr_gid != cr->cr_gid ||
7502 				    s_cr->cr_gid != cr->cr_rgid ||
7503 				    s_cr->cr_gid != cr->cr_sgid ||
7504 				    (proc = ttoproc(curthread)) == NULL ||
7505 				    (proc->p_flag & SNOCD))
7506 					continue;
7507 			}
7508 
7509 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7510 				cred_t *cr;
7511 				cred_t *s_cr =
7512 				    ecb->dte_state->dts_cred.dcr_cred;
7513 
7514 				ASSERT(s_cr != NULL);
7515 
7516 				if ((cr = CRED()) == NULL ||
7517 				    s_cr->cr_zone->zone_id !=
7518 				    cr->cr_zone->zone_id)
7519 					continue;
7520 			}
7521 #endif
7522 		}
7523 
7524 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7525 			/*
7526 			 * We seem to be dead.  Unless we (a) have kernel
7527 			 * destructive permissions (b) have explicitly enabled
7528 			 * destructive actions and (c) destructive actions have
7529 			 * not been disabled, we're going to transition into
7530 			 * the KILLED state, from which no further processing
7531 			 * on this state will be performed.
7532 			 */
7533 			if (!dtrace_priv_kernel_destructive(state) ||
7534 			    !state->dts_cred.dcr_destructive ||
7535 			    dtrace_destructive_disallow) {
7536 				void *activity = &state->dts_activity;
7537 				dtrace_activity_t curstate;
7538 
7539 				do {
7540 					curstate = state->dts_activity;
7541 				} while (dtrace_cas32(activity, curstate,
7542 				    DTRACE_ACTIVITY_KILLED) != curstate);
7543 
7544 				continue;
7545 			}
7546 		}
7547 
7548 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7549 		    ecb->dte_alignment, state, &mstate)) < 0)
7550 			continue;
7551 
7552 		tomax = buf->dtb_tomax;
7553 		ASSERT(tomax != NULL);
7554 
7555 		if (ecb->dte_size != 0) {
7556 			dtrace_rechdr_t dtrh;
7557 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7558 				mstate.dtms_timestamp = dtrace_gethrtime();
7559 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7560 			}
7561 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7562 			dtrh.dtrh_epid = ecb->dte_epid;
7563 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7564 			    mstate.dtms_timestamp);
7565 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7566 		}
7567 
7568 		mstate.dtms_epid = ecb->dte_epid;
7569 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7570 
7571 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7572 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7573 		else
7574 			mstate.dtms_access = 0;
7575 
7576 		if (pred != NULL) {
7577 			dtrace_difo_t *dp = pred->dtp_difo;
7578 			uint64_t rval;
7579 
7580 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7581 
7582 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7583 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7584 
7585 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7586 					/*
7587 					 * Update the predicate cache...
7588 					 */
7589 					ASSERT(cid == pred->dtp_cacheid);
7590 					curthread->t_predcache = cid;
7591 				}
7592 
7593 				continue;
7594 			}
7595 		}
7596 
7597 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7598 		    act != NULL; act = act->dta_next) {
7599 			size_t valoffs;
7600 			dtrace_difo_t *dp;
7601 			dtrace_recdesc_t *rec = &act->dta_rec;
7602 
7603 			size = rec->dtrd_size;
7604 			valoffs = offs + rec->dtrd_offset;
7605 
7606 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7607 				uint64_t v = 0xbad;
7608 				dtrace_aggregation_t *agg;
7609 
7610 				agg = (dtrace_aggregation_t *)act;
7611 
7612 				if ((dp = act->dta_difo) != NULL)
7613 					v = dtrace_dif_emulate(dp,
7614 					    &mstate, vstate, state);
7615 
7616 				if (*flags & CPU_DTRACE_ERROR)
7617 					continue;
7618 
7619 				/*
7620 				 * Note that we always pass the expression
7621 				 * value from the previous iteration of the
7622 				 * action loop.  This value will only be used
7623 				 * if there is an expression argument to the
7624 				 * aggregating action, denoted by the
7625 				 * dtag_hasarg field.
7626 				 */
7627 				dtrace_aggregate(agg, buf,
7628 				    offs, aggbuf, v, val);
7629 				continue;
7630 			}
7631 
7632 			switch (act->dta_kind) {
7633 			case DTRACEACT_STOP:
7634 				if (dtrace_priv_proc_destructive(state))
7635 					dtrace_action_stop();
7636 				continue;
7637 
7638 			case DTRACEACT_BREAKPOINT:
7639 				if (dtrace_priv_kernel_destructive(state))
7640 					dtrace_action_breakpoint(ecb);
7641 				continue;
7642 
7643 			case DTRACEACT_PANIC:
7644 				if (dtrace_priv_kernel_destructive(state))
7645 					dtrace_action_panic(ecb);
7646 				continue;
7647 
7648 			case DTRACEACT_STACK:
7649 				if (!dtrace_priv_kernel(state))
7650 					continue;
7651 
7652 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7653 				    size / sizeof (pc_t), probe->dtpr_aframes,
7654 				    DTRACE_ANCHORED(probe) ? NULL :
7655 				    (uint32_t *)arg0);
7656 				continue;
7657 
7658 			case DTRACEACT_JSTACK:
7659 			case DTRACEACT_USTACK:
7660 				if (!dtrace_priv_proc(state))
7661 					continue;
7662 
7663 				/*
7664 				 * See comment in DIF_VAR_PID.
7665 				 */
7666 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7667 				    CPU_ON_INTR(CPU)) {
7668 					int depth = DTRACE_USTACK_NFRAMES(
7669 					    rec->dtrd_arg) + 1;
7670 
7671 					dtrace_bzero((void *)(tomax + valoffs),
7672 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7673 					    + depth * sizeof (uint64_t));
7674 
7675 					continue;
7676 				}
7677 
7678 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7679 				    curproc->p_dtrace_helpers != NULL) {
7680 					/*
7681 					 * This is the slow path -- we have
7682 					 * allocated string space, and we're
7683 					 * getting the stack of a process that
7684 					 * has helpers.  Call into a separate
7685 					 * routine to perform this processing.
7686 					 */
7687 					dtrace_action_ustack(&mstate, state,
7688 					    (uint64_t *)(tomax + valoffs),
7689 					    rec->dtrd_arg);
7690 					continue;
7691 				}
7692 
7693 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7694 				dtrace_getupcstack((uint64_t *)
7695 				    (tomax + valoffs),
7696 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7697 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7698 				continue;
7699 
7700 			default:
7701 				break;
7702 			}
7703 
7704 			dp = act->dta_difo;
7705 			ASSERT(dp != NULL);
7706 
7707 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7708 
7709 			if (*flags & CPU_DTRACE_ERROR)
7710 				continue;
7711 
7712 			switch (act->dta_kind) {
7713 			case DTRACEACT_SPECULATE: {
7714 				dtrace_rechdr_t *dtrh;
7715 
7716 				ASSERT(buf == &state->dts_buffer[cpuid]);
7717 				buf = dtrace_speculation_buffer(state,
7718 				    cpuid, val);
7719 
7720 				if (buf == NULL) {
7721 					*flags |= CPU_DTRACE_DROP;
7722 					continue;
7723 				}
7724 
7725 				offs = dtrace_buffer_reserve(buf,
7726 				    ecb->dte_needed, ecb->dte_alignment,
7727 				    state, NULL);
7728 
7729 				if (offs < 0) {
7730 					*flags |= CPU_DTRACE_DROP;
7731 					continue;
7732 				}
7733 
7734 				tomax = buf->dtb_tomax;
7735 				ASSERT(tomax != NULL);
7736 
7737 				if (ecb->dte_size == 0)
7738 					continue;
7739 
7740 				ASSERT3U(ecb->dte_size, >=,
7741 				    sizeof (dtrace_rechdr_t));
7742 				dtrh = ((void *)(tomax + offs));
7743 				dtrh->dtrh_epid = ecb->dte_epid;
7744 				/*
7745 				 * When the speculation is committed, all of
7746 				 * the records in the speculative buffer will
7747 				 * have their timestamps set to the commit
7748 				 * time.  Until then, it is set to a sentinel
7749 				 * value, for debugability.
7750 				 */
7751 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7752 				continue;
7753 			}
7754 
7755 			case DTRACEACT_PRINTM: {
7756 				/* The DIF returns a 'memref'. */
7757 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7758 
7759 				/* Get the size from the memref. */
7760 				size = memref[1];
7761 
7762 				/*
7763 				 * Check if the size exceeds the allocated
7764 				 * buffer size.
7765 				 */
7766 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7767 					/* Flag a drop! */
7768 					*flags |= CPU_DTRACE_DROP;
7769 					continue;
7770 				}
7771 
7772 				/* Store the size in the buffer first. */
7773 				DTRACE_STORE(uintptr_t, tomax,
7774 				    valoffs, size);
7775 
7776 				/*
7777 				 * Offset the buffer address to the start
7778 				 * of the data.
7779 				 */
7780 				valoffs += sizeof(uintptr_t);
7781 
7782 				/*
7783 				 * Reset to the memory address rather than
7784 				 * the memref array, then let the BYREF
7785 				 * code below do the work to store the
7786 				 * memory data in the buffer.
7787 				 */
7788 				val = memref[0];
7789 				break;
7790 			}
7791 
7792 			case DTRACEACT_CHILL:
7793 				if (dtrace_priv_kernel_destructive(state))
7794 					dtrace_action_chill(&mstate, val);
7795 				continue;
7796 
7797 			case DTRACEACT_RAISE:
7798 				if (dtrace_priv_proc_destructive(state))
7799 					dtrace_action_raise(val);
7800 				continue;
7801 
7802 			case DTRACEACT_COMMIT:
7803 				ASSERT(!committed);
7804 
7805 				/*
7806 				 * We need to commit our buffer state.
7807 				 */
7808 				if (ecb->dte_size)
7809 					buf->dtb_offset = offs + ecb->dte_size;
7810 				buf = &state->dts_buffer[cpuid];
7811 				dtrace_speculation_commit(state, cpuid, val);
7812 				committed = 1;
7813 				continue;
7814 
7815 			case DTRACEACT_DISCARD:
7816 				dtrace_speculation_discard(state, cpuid, val);
7817 				continue;
7818 
7819 			case DTRACEACT_DIFEXPR:
7820 			case DTRACEACT_LIBACT:
7821 			case DTRACEACT_PRINTF:
7822 			case DTRACEACT_PRINTA:
7823 			case DTRACEACT_SYSTEM:
7824 			case DTRACEACT_FREOPEN:
7825 			case DTRACEACT_TRACEMEM:
7826 				break;
7827 
7828 			case DTRACEACT_TRACEMEM_DYNSIZE:
7829 				tracememsize = val;
7830 				break;
7831 
7832 			case DTRACEACT_SYM:
7833 			case DTRACEACT_MOD:
7834 				if (!dtrace_priv_kernel(state))
7835 					continue;
7836 				break;
7837 
7838 			case DTRACEACT_USYM:
7839 			case DTRACEACT_UMOD:
7840 			case DTRACEACT_UADDR: {
7841 #ifdef illumos
7842 				struct pid *pid = curthread->t_procp->p_pidp;
7843 #endif
7844 
7845 				if (!dtrace_priv_proc(state))
7846 					continue;
7847 
7848 				DTRACE_STORE(uint64_t, tomax,
7849 #ifdef illumos
7850 				    valoffs, (uint64_t)pid->pid_id);
7851 #else
7852 				    valoffs, (uint64_t) curproc->p_pid);
7853 #endif
7854 				DTRACE_STORE(uint64_t, tomax,
7855 				    valoffs + sizeof (uint64_t), val);
7856 
7857 				continue;
7858 			}
7859 
7860 			case DTRACEACT_EXIT: {
7861 				/*
7862 				 * For the exit action, we are going to attempt
7863 				 * to atomically set our activity to be
7864 				 * draining.  If this fails (either because
7865 				 * another CPU has beat us to the exit action,
7866 				 * or because our current activity is something
7867 				 * other than ACTIVE or WARMUP), we will
7868 				 * continue.  This assures that the exit action
7869 				 * can be successfully recorded at most once
7870 				 * when we're in the ACTIVE state.  If we're
7871 				 * encountering the exit() action while in
7872 				 * COOLDOWN, however, we want to honor the new
7873 				 * status code.  (We know that we're the only
7874 				 * thread in COOLDOWN, so there is no race.)
7875 				 */
7876 				void *activity = &state->dts_activity;
7877 				dtrace_activity_t curstate = state->dts_activity;
7878 
7879 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7880 					break;
7881 
7882 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7883 					curstate = DTRACE_ACTIVITY_ACTIVE;
7884 
7885 				if (dtrace_cas32(activity, curstate,
7886 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7887 					*flags |= CPU_DTRACE_DROP;
7888 					continue;
7889 				}
7890 
7891 				break;
7892 			}
7893 
7894 			default:
7895 				ASSERT(0);
7896 			}
7897 
7898 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7899 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7900 				uintptr_t end = valoffs + size;
7901 
7902 				if (tracememsize != 0 &&
7903 				    valoffs + tracememsize < end) {
7904 					end = valoffs + tracememsize;
7905 					tracememsize = 0;
7906 				}
7907 
7908 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7909 				    !dtrace_vcanload((void *)(uintptr_t)val,
7910 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7911 					continue;
7912 
7913 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7914 				    &val, end, act->dta_intuple,
7915 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7916 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7917 				continue;
7918 			}
7919 
7920 			switch (size) {
7921 			case 0:
7922 				break;
7923 
7924 			case sizeof (uint8_t):
7925 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7926 				break;
7927 			case sizeof (uint16_t):
7928 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7929 				break;
7930 			case sizeof (uint32_t):
7931 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7932 				break;
7933 			case sizeof (uint64_t):
7934 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7935 				break;
7936 			default:
7937 				/*
7938 				 * Any other size should have been returned by
7939 				 * reference, not by value.
7940 				 */
7941 				ASSERT(0);
7942 				break;
7943 			}
7944 		}
7945 
7946 		if (*flags & CPU_DTRACE_DROP)
7947 			continue;
7948 
7949 		if (*flags & CPU_DTRACE_FAULT) {
7950 			int ndx;
7951 			dtrace_action_t *err;
7952 
7953 			buf->dtb_errors++;
7954 
7955 			if (probe->dtpr_id == dtrace_probeid_error) {
7956 				/*
7957 				 * There's nothing we can do -- we had an
7958 				 * error on the error probe.  We bump an
7959 				 * error counter to at least indicate that
7960 				 * this condition happened.
7961 				 */
7962 				dtrace_error(&state->dts_dblerrors);
7963 				continue;
7964 			}
7965 
7966 			if (vtime) {
7967 				/*
7968 				 * Before recursing on dtrace_probe(), we
7969 				 * need to explicitly clear out our start
7970 				 * time to prevent it from being accumulated
7971 				 * into t_dtrace_vtime.
7972 				 */
7973 				curthread->t_dtrace_start = 0;
7974 			}
7975 
7976 			/*
7977 			 * Iterate over the actions to figure out which action
7978 			 * we were processing when we experienced the error.
7979 			 * Note that act points _past_ the faulting action; if
7980 			 * act is ecb->dte_action, the fault was in the
7981 			 * predicate, if it's ecb->dte_action->dta_next it's
7982 			 * in action #1, and so on.
7983 			 */
7984 			for (err = ecb->dte_action, ndx = 0;
7985 			    err != act; err = err->dta_next, ndx++)
7986 				continue;
7987 
7988 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7989 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7990 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7991 			    cpu_core[cpuid].cpuc_dtrace_illval);
7992 
7993 			continue;
7994 		}
7995 
7996 		if (!committed)
7997 			buf->dtb_offset = offs + ecb->dte_size;
7998 	}
7999 
8000 	if (vtime)
8001 		curthread->t_dtrace_start = dtrace_gethrtime();
8002 
8003 	dtrace_probe_exit(cookie);
8004 }
8005 
8006 /*
8007  * DTrace Probe Hashing Functions
8008  *
8009  * The functions in this section (and indeed, the functions in remaining
8010  * sections) are not _called_ from probe context.  (Any exceptions to this are
8011  * marked with a "Note:".)  Rather, they are called from elsewhere in the
8012  * DTrace framework to look-up probes in, add probes to and remove probes from
8013  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8014  * probe tuple -- allowing for fast lookups, regardless of what was
8015  * specified.)
8016  */
8017 static uint_t
8018 dtrace_hash_str(const char *p)
8019 {
8020 	unsigned int g;
8021 	uint_t hval = 0;
8022 
8023 	while (*p) {
8024 		hval = (hval << 4) + *p++;
8025 		if ((g = (hval & 0xf0000000)) != 0)
8026 			hval ^= g >> 24;
8027 		hval &= ~g;
8028 	}
8029 	return (hval);
8030 }
8031 
8032 static dtrace_hash_t *
8033 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
8034 {
8035 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8036 
8037 	hash->dth_stroffs = stroffs;
8038 	hash->dth_nextoffs = nextoffs;
8039 	hash->dth_prevoffs = prevoffs;
8040 
8041 	hash->dth_size = 1;
8042 	hash->dth_mask = hash->dth_size - 1;
8043 
8044 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8045 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8046 
8047 	return (hash);
8048 }
8049 
8050 static void
8051 dtrace_hash_destroy(dtrace_hash_t *hash)
8052 {
8053 #ifdef DEBUG
8054 	int i;
8055 
8056 	for (i = 0; i < hash->dth_size; i++)
8057 		ASSERT(hash->dth_tab[i] == NULL);
8058 #endif
8059 
8060 	kmem_free(hash->dth_tab,
8061 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8062 	kmem_free(hash, sizeof (dtrace_hash_t));
8063 }
8064 
8065 static void
8066 dtrace_hash_resize(dtrace_hash_t *hash)
8067 {
8068 	int size = hash->dth_size, i, ndx;
8069 	int new_size = hash->dth_size << 1;
8070 	int new_mask = new_size - 1;
8071 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8072 
8073 	ASSERT((new_size & new_mask) == 0);
8074 
8075 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8076 
8077 	for (i = 0; i < size; i++) {
8078 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8079 			dtrace_probe_t *probe = bucket->dthb_chain;
8080 
8081 			ASSERT(probe != NULL);
8082 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8083 
8084 			next = bucket->dthb_next;
8085 			bucket->dthb_next = new_tab[ndx];
8086 			new_tab[ndx] = bucket;
8087 		}
8088 	}
8089 
8090 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8091 	hash->dth_tab = new_tab;
8092 	hash->dth_size = new_size;
8093 	hash->dth_mask = new_mask;
8094 }
8095 
8096 static void
8097 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8098 {
8099 	int hashval = DTRACE_HASHSTR(hash, new);
8100 	int ndx = hashval & hash->dth_mask;
8101 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8102 	dtrace_probe_t **nextp, **prevp;
8103 
8104 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8105 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8106 			goto add;
8107 	}
8108 
8109 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8110 		dtrace_hash_resize(hash);
8111 		dtrace_hash_add(hash, new);
8112 		return;
8113 	}
8114 
8115 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8116 	bucket->dthb_next = hash->dth_tab[ndx];
8117 	hash->dth_tab[ndx] = bucket;
8118 	hash->dth_nbuckets++;
8119 
8120 add:
8121 	nextp = DTRACE_HASHNEXT(hash, new);
8122 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8123 	*nextp = bucket->dthb_chain;
8124 
8125 	if (bucket->dthb_chain != NULL) {
8126 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8127 		ASSERT(*prevp == NULL);
8128 		*prevp = new;
8129 	}
8130 
8131 	bucket->dthb_chain = new;
8132 	bucket->dthb_len++;
8133 }
8134 
8135 static dtrace_probe_t *
8136 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8137 {
8138 	int hashval = DTRACE_HASHSTR(hash, template);
8139 	int ndx = hashval & hash->dth_mask;
8140 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8141 
8142 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8143 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8144 			return (bucket->dthb_chain);
8145 	}
8146 
8147 	return (NULL);
8148 }
8149 
8150 static int
8151 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8152 {
8153 	int hashval = DTRACE_HASHSTR(hash, template);
8154 	int ndx = hashval & hash->dth_mask;
8155 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8156 
8157 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8158 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8159 			return (bucket->dthb_len);
8160 	}
8161 
8162 	return (0);
8163 }
8164 
8165 static void
8166 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8167 {
8168 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8169 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8170 
8171 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8172 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8173 
8174 	/*
8175 	 * Find the bucket that we're removing this probe from.
8176 	 */
8177 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8178 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8179 			break;
8180 	}
8181 
8182 	ASSERT(bucket != NULL);
8183 
8184 	if (*prevp == NULL) {
8185 		if (*nextp == NULL) {
8186 			/*
8187 			 * The removed probe was the only probe on this
8188 			 * bucket; we need to remove the bucket.
8189 			 */
8190 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8191 
8192 			ASSERT(bucket->dthb_chain == probe);
8193 			ASSERT(b != NULL);
8194 
8195 			if (b == bucket) {
8196 				hash->dth_tab[ndx] = bucket->dthb_next;
8197 			} else {
8198 				while (b->dthb_next != bucket)
8199 					b = b->dthb_next;
8200 				b->dthb_next = bucket->dthb_next;
8201 			}
8202 
8203 			ASSERT(hash->dth_nbuckets > 0);
8204 			hash->dth_nbuckets--;
8205 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8206 			return;
8207 		}
8208 
8209 		bucket->dthb_chain = *nextp;
8210 	} else {
8211 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8212 	}
8213 
8214 	if (*nextp != NULL)
8215 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8216 }
8217 
8218 /*
8219  * DTrace Utility Functions
8220  *
8221  * These are random utility functions that are _not_ called from probe context.
8222  */
8223 static int
8224 dtrace_badattr(const dtrace_attribute_t *a)
8225 {
8226 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8227 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8228 	    a->dtat_class > DTRACE_CLASS_MAX);
8229 }
8230 
8231 /*
8232  * Return a duplicate copy of a string.  If the specified string is NULL,
8233  * this function returns a zero-length string.
8234  */
8235 static char *
8236 dtrace_strdup(const char *str)
8237 {
8238 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8239 
8240 	if (str != NULL)
8241 		(void) strcpy(new, str);
8242 
8243 	return (new);
8244 }
8245 
8246 #define	DTRACE_ISALPHA(c)	\
8247 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8248 
8249 static int
8250 dtrace_badname(const char *s)
8251 {
8252 	char c;
8253 
8254 	if (s == NULL || (c = *s++) == '\0')
8255 		return (0);
8256 
8257 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8258 		return (1);
8259 
8260 	while ((c = *s++) != '\0') {
8261 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8262 		    c != '-' && c != '_' && c != '.' && c != '`')
8263 			return (1);
8264 	}
8265 
8266 	return (0);
8267 }
8268 
8269 static void
8270 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8271 {
8272 	uint32_t priv;
8273 
8274 #ifdef illumos
8275 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8276 		/*
8277 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8278 		 */
8279 		priv = DTRACE_PRIV_ALL;
8280 	} else {
8281 		*uidp = crgetuid(cr);
8282 		*zoneidp = crgetzoneid(cr);
8283 
8284 		priv = 0;
8285 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8286 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8287 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8288 			priv |= DTRACE_PRIV_USER;
8289 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8290 			priv |= DTRACE_PRIV_PROC;
8291 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8292 			priv |= DTRACE_PRIV_OWNER;
8293 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8294 			priv |= DTRACE_PRIV_ZONEOWNER;
8295 	}
8296 #else
8297 	priv = DTRACE_PRIV_ALL;
8298 #endif
8299 
8300 	*privp = priv;
8301 }
8302 
8303 #ifdef DTRACE_ERRDEBUG
8304 static void
8305 dtrace_errdebug(const char *str)
8306 {
8307 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8308 	int occupied = 0;
8309 
8310 	mutex_enter(&dtrace_errlock);
8311 	dtrace_errlast = str;
8312 	dtrace_errthread = curthread;
8313 
8314 	while (occupied++ < DTRACE_ERRHASHSZ) {
8315 		if (dtrace_errhash[hval].dter_msg == str) {
8316 			dtrace_errhash[hval].dter_count++;
8317 			goto out;
8318 		}
8319 
8320 		if (dtrace_errhash[hval].dter_msg != NULL) {
8321 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8322 			continue;
8323 		}
8324 
8325 		dtrace_errhash[hval].dter_msg = str;
8326 		dtrace_errhash[hval].dter_count = 1;
8327 		goto out;
8328 	}
8329 
8330 	panic("dtrace: undersized error hash");
8331 out:
8332 	mutex_exit(&dtrace_errlock);
8333 }
8334 #endif
8335 
8336 /*
8337  * DTrace Matching Functions
8338  *
8339  * These functions are used to match groups of probes, given some elements of
8340  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8341  */
8342 static int
8343 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8344     zoneid_t zoneid)
8345 {
8346 	if (priv != DTRACE_PRIV_ALL) {
8347 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8348 		uint32_t match = priv & ppriv;
8349 
8350 		/*
8351 		 * No PRIV_DTRACE_* privileges...
8352 		 */
8353 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8354 		    DTRACE_PRIV_KERNEL)) == 0)
8355 			return (0);
8356 
8357 		/*
8358 		 * No matching bits, but there were bits to match...
8359 		 */
8360 		if (match == 0 && ppriv != 0)
8361 			return (0);
8362 
8363 		/*
8364 		 * Need to have permissions to the process, but don't...
8365 		 */
8366 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8367 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8368 			return (0);
8369 		}
8370 
8371 		/*
8372 		 * Need to be in the same zone unless we possess the
8373 		 * privilege to examine all zones.
8374 		 */
8375 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8376 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8377 			return (0);
8378 		}
8379 	}
8380 
8381 	return (1);
8382 }
8383 
8384 /*
8385  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8386  * consists of input pattern strings and an ops-vector to evaluate them.
8387  * This function returns >0 for match, 0 for no match, and <0 for error.
8388  */
8389 static int
8390 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8391     uint32_t priv, uid_t uid, zoneid_t zoneid)
8392 {
8393 	dtrace_provider_t *pvp = prp->dtpr_provider;
8394 	int rv;
8395 
8396 	if (pvp->dtpv_defunct)
8397 		return (0);
8398 
8399 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8400 		return (rv);
8401 
8402 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8403 		return (rv);
8404 
8405 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8406 		return (rv);
8407 
8408 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8409 		return (rv);
8410 
8411 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8412 		return (0);
8413 
8414 	return (rv);
8415 }
8416 
8417 /*
8418  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8419  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8420  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8421  * In addition, all of the recursion cases except for '*' matching have been
8422  * unwound.  For '*', we still implement recursive evaluation, but a depth
8423  * counter is maintained and matching is aborted if we recurse too deep.
8424  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8425  */
8426 static int
8427 dtrace_match_glob(const char *s, const char *p, int depth)
8428 {
8429 	const char *olds;
8430 	char s1, c;
8431 	int gs;
8432 
8433 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8434 		return (-1);
8435 
8436 	if (s == NULL)
8437 		s = ""; /* treat NULL as empty string */
8438 
8439 top:
8440 	olds = s;
8441 	s1 = *s++;
8442 
8443 	if (p == NULL)
8444 		return (0);
8445 
8446 	if ((c = *p++) == '\0')
8447 		return (s1 == '\0');
8448 
8449 	switch (c) {
8450 	case '[': {
8451 		int ok = 0, notflag = 0;
8452 		char lc = '\0';
8453 
8454 		if (s1 == '\0')
8455 			return (0);
8456 
8457 		if (*p == '!') {
8458 			notflag = 1;
8459 			p++;
8460 		}
8461 
8462 		if ((c = *p++) == '\0')
8463 			return (0);
8464 
8465 		do {
8466 			if (c == '-' && lc != '\0' && *p != ']') {
8467 				if ((c = *p++) == '\0')
8468 					return (0);
8469 				if (c == '\\' && (c = *p++) == '\0')
8470 					return (0);
8471 
8472 				if (notflag) {
8473 					if (s1 < lc || s1 > c)
8474 						ok++;
8475 					else
8476 						return (0);
8477 				} else if (lc <= s1 && s1 <= c)
8478 					ok++;
8479 
8480 			} else if (c == '\\' && (c = *p++) == '\0')
8481 				return (0);
8482 
8483 			lc = c; /* save left-hand 'c' for next iteration */
8484 
8485 			if (notflag) {
8486 				if (s1 != c)
8487 					ok++;
8488 				else
8489 					return (0);
8490 			} else if (s1 == c)
8491 				ok++;
8492 
8493 			if ((c = *p++) == '\0')
8494 				return (0);
8495 
8496 		} while (c != ']');
8497 
8498 		if (ok)
8499 			goto top;
8500 
8501 		return (0);
8502 	}
8503 
8504 	case '\\':
8505 		if ((c = *p++) == '\0')
8506 			return (0);
8507 		/*FALLTHRU*/
8508 
8509 	default:
8510 		if (c != s1)
8511 			return (0);
8512 		/*FALLTHRU*/
8513 
8514 	case '?':
8515 		if (s1 != '\0')
8516 			goto top;
8517 		return (0);
8518 
8519 	case '*':
8520 		while (*p == '*')
8521 			p++; /* consecutive *'s are identical to a single one */
8522 
8523 		if (*p == '\0')
8524 			return (1);
8525 
8526 		for (s = olds; *s != '\0'; s++) {
8527 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8528 				return (gs);
8529 		}
8530 
8531 		return (0);
8532 	}
8533 }
8534 
8535 /*ARGSUSED*/
8536 static int
8537 dtrace_match_string(const char *s, const char *p, int depth)
8538 {
8539 	return (s != NULL && strcmp(s, p) == 0);
8540 }
8541 
8542 /*ARGSUSED*/
8543 static int
8544 dtrace_match_nul(const char *s, const char *p, int depth)
8545 {
8546 	return (1); /* always match the empty pattern */
8547 }
8548 
8549 /*ARGSUSED*/
8550 static int
8551 dtrace_match_nonzero(const char *s, const char *p, int depth)
8552 {
8553 	return (s != NULL && s[0] != '\0');
8554 }
8555 
8556 static int
8557 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8558     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8559 {
8560 	dtrace_probe_t template, *probe;
8561 	dtrace_hash_t *hash = NULL;
8562 	int len, best = INT_MAX, nmatched = 0;
8563 	dtrace_id_t i;
8564 
8565 	ASSERT(MUTEX_HELD(&dtrace_lock));
8566 
8567 	/*
8568 	 * If the probe ID is specified in the key, just lookup by ID and
8569 	 * invoke the match callback once if a matching probe is found.
8570 	 */
8571 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8572 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8573 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8574 			(void) (*matched)(probe, arg);
8575 			nmatched++;
8576 		}
8577 		return (nmatched);
8578 	}
8579 
8580 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8581 	template.dtpr_func = (char *)pkp->dtpk_func;
8582 	template.dtpr_name = (char *)pkp->dtpk_name;
8583 
8584 	/*
8585 	 * We want to find the most distinct of the module name, function
8586 	 * name, and name.  So for each one that is not a glob pattern or
8587 	 * empty string, we perform a lookup in the corresponding hash and
8588 	 * use the hash table with the fewest collisions to do our search.
8589 	 */
8590 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8591 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8592 		best = len;
8593 		hash = dtrace_bymod;
8594 	}
8595 
8596 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8597 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8598 		best = len;
8599 		hash = dtrace_byfunc;
8600 	}
8601 
8602 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8603 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8604 		best = len;
8605 		hash = dtrace_byname;
8606 	}
8607 
8608 	/*
8609 	 * If we did not select a hash table, iterate over every probe and
8610 	 * invoke our callback for each one that matches our input probe key.
8611 	 */
8612 	if (hash == NULL) {
8613 		for (i = 0; i < dtrace_nprobes; i++) {
8614 			if ((probe = dtrace_probes[i]) == NULL ||
8615 			    dtrace_match_probe(probe, pkp, priv, uid,
8616 			    zoneid) <= 0)
8617 				continue;
8618 
8619 			nmatched++;
8620 
8621 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8622 				break;
8623 		}
8624 
8625 		return (nmatched);
8626 	}
8627 
8628 	/*
8629 	 * If we selected a hash table, iterate over each probe of the same key
8630 	 * name and invoke the callback for every probe that matches the other
8631 	 * attributes of our input probe key.
8632 	 */
8633 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8634 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8635 
8636 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8637 			continue;
8638 
8639 		nmatched++;
8640 
8641 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8642 			break;
8643 	}
8644 
8645 	return (nmatched);
8646 }
8647 
8648 /*
8649  * Return the function pointer dtrace_probecmp() should use to compare the
8650  * specified pattern with a string.  For NULL or empty patterns, we select
8651  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8652  * For non-empty non-glob strings, we use dtrace_match_string().
8653  */
8654 static dtrace_probekey_f *
8655 dtrace_probekey_func(const char *p)
8656 {
8657 	char c;
8658 
8659 	if (p == NULL || *p == '\0')
8660 		return (&dtrace_match_nul);
8661 
8662 	while ((c = *p++) != '\0') {
8663 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8664 			return (&dtrace_match_glob);
8665 	}
8666 
8667 	return (&dtrace_match_string);
8668 }
8669 
8670 /*
8671  * Build a probe comparison key for use with dtrace_match_probe() from the
8672  * given probe description.  By convention, a null key only matches anchored
8673  * probes: if each field is the empty string, reset dtpk_fmatch to
8674  * dtrace_match_nonzero().
8675  */
8676 static void
8677 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8678 {
8679 	pkp->dtpk_prov = pdp->dtpd_provider;
8680 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8681 
8682 	pkp->dtpk_mod = pdp->dtpd_mod;
8683 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8684 
8685 	pkp->dtpk_func = pdp->dtpd_func;
8686 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8687 
8688 	pkp->dtpk_name = pdp->dtpd_name;
8689 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8690 
8691 	pkp->dtpk_id = pdp->dtpd_id;
8692 
8693 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8694 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8695 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8696 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8697 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8698 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8699 }
8700 
8701 /*
8702  * DTrace Provider-to-Framework API Functions
8703  *
8704  * These functions implement much of the Provider-to-Framework API, as
8705  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8706  * the functions in the API for probe management (found below), and
8707  * dtrace_probe() itself (found above).
8708  */
8709 
8710 /*
8711  * Register the calling provider with the DTrace framework.  This should
8712  * generally be called by DTrace providers in their attach(9E) entry point.
8713  */
8714 int
8715 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8716     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8717 {
8718 	dtrace_provider_t *provider;
8719 
8720 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8721 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8722 		    "arguments", name ? name : "<NULL>");
8723 		return (EINVAL);
8724 	}
8725 
8726 	if (name[0] == '\0' || dtrace_badname(name)) {
8727 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8728 		    "provider name", name);
8729 		return (EINVAL);
8730 	}
8731 
8732 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8733 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8734 	    pops->dtps_destroy == NULL ||
8735 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8736 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8737 		    "provider ops", name);
8738 		return (EINVAL);
8739 	}
8740 
8741 	if (dtrace_badattr(&pap->dtpa_provider) ||
8742 	    dtrace_badattr(&pap->dtpa_mod) ||
8743 	    dtrace_badattr(&pap->dtpa_func) ||
8744 	    dtrace_badattr(&pap->dtpa_name) ||
8745 	    dtrace_badattr(&pap->dtpa_args)) {
8746 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8747 		    "provider attributes", name);
8748 		return (EINVAL);
8749 	}
8750 
8751 	if (priv & ~DTRACE_PRIV_ALL) {
8752 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8753 		    "privilege attributes", name);
8754 		return (EINVAL);
8755 	}
8756 
8757 	if ((priv & DTRACE_PRIV_KERNEL) &&
8758 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8759 	    pops->dtps_usermode == NULL) {
8760 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8761 		    "dtps_usermode() op for given privilege attributes", name);
8762 		return (EINVAL);
8763 	}
8764 
8765 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8766 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8767 	(void) strcpy(provider->dtpv_name, name);
8768 
8769 	provider->dtpv_attr = *pap;
8770 	provider->dtpv_priv.dtpp_flags = priv;
8771 	if (cr != NULL) {
8772 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8773 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8774 	}
8775 	provider->dtpv_pops = *pops;
8776 
8777 	if (pops->dtps_provide == NULL) {
8778 		ASSERT(pops->dtps_provide_module != NULL);
8779 		provider->dtpv_pops.dtps_provide =
8780 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8781 	}
8782 
8783 	if (pops->dtps_provide_module == NULL) {
8784 		ASSERT(pops->dtps_provide != NULL);
8785 		provider->dtpv_pops.dtps_provide_module =
8786 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8787 	}
8788 
8789 	if (pops->dtps_suspend == NULL) {
8790 		ASSERT(pops->dtps_resume == NULL);
8791 		provider->dtpv_pops.dtps_suspend =
8792 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8793 		provider->dtpv_pops.dtps_resume =
8794 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8795 	}
8796 
8797 	provider->dtpv_arg = arg;
8798 	*idp = (dtrace_provider_id_t)provider;
8799 
8800 	if (pops == &dtrace_provider_ops) {
8801 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8802 		ASSERT(MUTEX_HELD(&dtrace_lock));
8803 		ASSERT(dtrace_anon.dta_enabling == NULL);
8804 
8805 		/*
8806 		 * We make sure that the DTrace provider is at the head of
8807 		 * the provider chain.
8808 		 */
8809 		provider->dtpv_next = dtrace_provider;
8810 		dtrace_provider = provider;
8811 		return (0);
8812 	}
8813 
8814 	mutex_enter(&dtrace_provider_lock);
8815 	mutex_enter(&dtrace_lock);
8816 
8817 	/*
8818 	 * If there is at least one provider registered, we'll add this
8819 	 * provider after the first provider.
8820 	 */
8821 	if (dtrace_provider != NULL) {
8822 		provider->dtpv_next = dtrace_provider->dtpv_next;
8823 		dtrace_provider->dtpv_next = provider;
8824 	} else {
8825 		dtrace_provider = provider;
8826 	}
8827 
8828 	if (dtrace_retained != NULL) {
8829 		dtrace_enabling_provide(provider);
8830 
8831 		/*
8832 		 * Now we need to call dtrace_enabling_matchall() -- which
8833 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8834 		 * to drop all of our locks before calling into it...
8835 		 */
8836 		mutex_exit(&dtrace_lock);
8837 		mutex_exit(&dtrace_provider_lock);
8838 		dtrace_enabling_matchall();
8839 
8840 		return (0);
8841 	}
8842 
8843 	mutex_exit(&dtrace_lock);
8844 	mutex_exit(&dtrace_provider_lock);
8845 
8846 	return (0);
8847 }
8848 
8849 /*
8850  * Unregister the specified provider from the DTrace framework.  This should
8851  * generally be called by DTrace providers in their detach(9E) entry point.
8852  */
8853 int
8854 dtrace_unregister(dtrace_provider_id_t id)
8855 {
8856 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8857 	dtrace_provider_t *prev = NULL;
8858 	int i, self = 0, noreap = 0;
8859 	dtrace_probe_t *probe, *first = NULL;
8860 
8861 	if (old->dtpv_pops.dtps_enable ==
8862 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8863 		/*
8864 		 * If DTrace itself is the provider, we're called with locks
8865 		 * already held.
8866 		 */
8867 		ASSERT(old == dtrace_provider);
8868 #ifdef illumos
8869 		ASSERT(dtrace_devi != NULL);
8870 #endif
8871 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8872 		ASSERT(MUTEX_HELD(&dtrace_lock));
8873 		self = 1;
8874 
8875 		if (dtrace_provider->dtpv_next != NULL) {
8876 			/*
8877 			 * There's another provider here; return failure.
8878 			 */
8879 			return (EBUSY);
8880 		}
8881 	} else {
8882 		mutex_enter(&dtrace_provider_lock);
8883 #ifdef illumos
8884 		mutex_enter(&mod_lock);
8885 #endif
8886 		mutex_enter(&dtrace_lock);
8887 	}
8888 
8889 	/*
8890 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8891 	 * probes, we refuse to let providers slither away, unless this
8892 	 * provider has already been explicitly invalidated.
8893 	 */
8894 	if (!old->dtpv_defunct &&
8895 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8896 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8897 		if (!self) {
8898 			mutex_exit(&dtrace_lock);
8899 #ifdef illumos
8900 			mutex_exit(&mod_lock);
8901 #endif
8902 			mutex_exit(&dtrace_provider_lock);
8903 		}
8904 		return (EBUSY);
8905 	}
8906 
8907 	/*
8908 	 * Attempt to destroy the probes associated with this provider.
8909 	 */
8910 	for (i = 0; i < dtrace_nprobes; i++) {
8911 		if ((probe = dtrace_probes[i]) == NULL)
8912 			continue;
8913 
8914 		if (probe->dtpr_provider != old)
8915 			continue;
8916 
8917 		if (probe->dtpr_ecb == NULL)
8918 			continue;
8919 
8920 		/*
8921 		 * If we are trying to unregister a defunct provider, and the
8922 		 * provider was made defunct within the interval dictated by
8923 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8924 		 * attempt to reap our enablings.  To denote that the provider
8925 		 * should reattempt to unregister itself at some point in the
8926 		 * future, we will return a differentiable error code (EAGAIN
8927 		 * instead of EBUSY) in this case.
8928 		 */
8929 		if (dtrace_gethrtime() - old->dtpv_defunct >
8930 		    dtrace_unregister_defunct_reap)
8931 			noreap = 1;
8932 
8933 		if (!self) {
8934 			mutex_exit(&dtrace_lock);
8935 #ifdef illumos
8936 			mutex_exit(&mod_lock);
8937 #endif
8938 			mutex_exit(&dtrace_provider_lock);
8939 		}
8940 
8941 		if (noreap)
8942 			return (EBUSY);
8943 
8944 		(void) taskq_dispatch(dtrace_taskq,
8945 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8946 
8947 		return (EAGAIN);
8948 	}
8949 
8950 	/*
8951 	 * All of the probes for this provider are disabled; we can safely
8952 	 * remove all of them from their hash chains and from the probe array.
8953 	 */
8954 	for (i = 0; i < dtrace_nprobes; i++) {
8955 		if ((probe = dtrace_probes[i]) == NULL)
8956 			continue;
8957 
8958 		if (probe->dtpr_provider != old)
8959 			continue;
8960 
8961 		dtrace_probes[i] = NULL;
8962 
8963 		dtrace_hash_remove(dtrace_bymod, probe);
8964 		dtrace_hash_remove(dtrace_byfunc, probe);
8965 		dtrace_hash_remove(dtrace_byname, probe);
8966 
8967 		if (first == NULL) {
8968 			first = probe;
8969 			probe->dtpr_nextmod = NULL;
8970 		} else {
8971 			probe->dtpr_nextmod = first;
8972 			first = probe;
8973 		}
8974 	}
8975 
8976 	/*
8977 	 * The provider's probes have been removed from the hash chains and
8978 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8979 	 * everyone has cleared out from any probe array processing.
8980 	 */
8981 	dtrace_sync();
8982 
8983 	for (probe = first; probe != NULL; probe = first) {
8984 		first = probe->dtpr_nextmod;
8985 
8986 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8987 		    probe->dtpr_arg);
8988 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8989 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8990 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8991 #ifdef illumos
8992 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8993 #else
8994 		free_unr(dtrace_arena, probe->dtpr_id);
8995 #endif
8996 		kmem_free(probe, sizeof (dtrace_probe_t));
8997 	}
8998 
8999 	if ((prev = dtrace_provider) == old) {
9000 #ifdef illumos
9001 		ASSERT(self || dtrace_devi == NULL);
9002 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9003 #endif
9004 		dtrace_provider = old->dtpv_next;
9005 	} else {
9006 		while (prev != NULL && prev->dtpv_next != old)
9007 			prev = prev->dtpv_next;
9008 
9009 		if (prev == NULL) {
9010 			panic("attempt to unregister non-existent "
9011 			    "dtrace provider %p\n", (void *)id);
9012 		}
9013 
9014 		prev->dtpv_next = old->dtpv_next;
9015 	}
9016 
9017 	if (!self) {
9018 		mutex_exit(&dtrace_lock);
9019 #ifdef illumos
9020 		mutex_exit(&mod_lock);
9021 #endif
9022 		mutex_exit(&dtrace_provider_lock);
9023 	}
9024 
9025 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9026 	kmem_free(old, sizeof (dtrace_provider_t));
9027 
9028 	return (0);
9029 }
9030 
9031 /*
9032  * Invalidate the specified provider.  All subsequent probe lookups for the
9033  * specified provider will fail, but its probes will not be removed.
9034  */
9035 void
9036 dtrace_invalidate(dtrace_provider_id_t id)
9037 {
9038 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9039 
9040 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9041 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9042 
9043 	mutex_enter(&dtrace_provider_lock);
9044 	mutex_enter(&dtrace_lock);
9045 
9046 	pvp->dtpv_defunct = dtrace_gethrtime();
9047 
9048 	mutex_exit(&dtrace_lock);
9049 	mutex_exit(&dtrace_provider_lock);
9050 }
9051 
9052 /*
9053  * Indicate whether or not DTrace has attached.
9054  */
9055 int
9056 dtrace_attached(void)
9057 {
9058 	/*
9059 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9060 	 * attached.  (It's non-NULL because DTrace is always itself a
9061 	 * provider.)
9062 	 */
9063 	return (dtrace_provider != NULL);
9064 }
9065 
9066 /*
9067  * Remove all the unenabled probes for the given provider.  This function is
9068  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9069  * -- just as many of its associated probes as it can.
9070  */
9071 int
9072 dtrace_condense(dtrace_provider_id_t id)
9073 {
9074 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9075 	int i;
9076 	dtrace_probe_t *probe;
9077 
9078 	/*
9079 	 * Make sure this isn't the dtrace provider itself.
9080 	 */
9081 	ASSERT(prov->dtpv_pops.dtps_enable !=
9082 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9083 
9084 	mutex_enter(&dtrace_provider_lock);
9085 	mutex_enter(&dtrace_lock);
9086 
9087 	/*
9088 	 * Attempt to destroy the probes associated with this provider.
9089 	 */
9090 	for (i = 0; i < dtrace_nprobes; i++) {
9091 		if ((probe = dtrace_probes[i]) == NULL)
9092 			continue;
9093 
9094 		if (probe->dtpr_provider != prov)
9095 			continue;
9096 
9097 		if (probe->dtpr_ecb != NULL)
9098 			continue;
9099 
9100 		dtrace_probes[i] = NULL;
9101 
9102 		dtrace_hash_remove(dtrace_bymod, probe);
9103 		dtrace_hash_remove(dtrace_byfunc, probe);
9104 		dtrace_hash_remove(dtrace_byname, probe);
9105 
9106 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9107 		    probe->dtpr_arg);
9108 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9109 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9110 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9111 		kmem_free(probe, sizeof (dtrace_probe_t));
9112 #ifdef illumos
9113 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9114 #else
9115 		free_unr(dtrace_arena, i + 1);
9116 #endif
9117 	}
9118 
9119 	mutex_exit(&dtrace_lock);
9120 	mutex_exit(&dtrace_provider_lock);
9121 
9122 	return (0);
9123 }
9124 
9125 /*
9126  * DTrace Probe Management Functions
9127  *
9128  * The functions in this section perform the DTrace probe management,
9129  * including functions to create probes, look-up probes, and call into the
9130  * providers to request that probes be provided.  Some of these functions are
9131  * in the Provider-to-Framework API; these functions can be identified by the
9132  * fact that they are not declared "static".
9133  */
9134 
9135 /*
9136  * Create a probe with the specified module name, function name, and name.
9137  */
9138 dtrace_id_t
9139 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9140     const char *func, const char *name, int aframes, void *arg)
9141 {
9142 	dtrace_probe_t *probe, **probes;
9143 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9144 	dtrace_id_t id;
9145 
9146 	if (provider == dtrace_provider) {
9147 		ASSERT(MUTEX_HELD(&dtrace_lock));
9148 	} else {
9149 		mutex_enter(&dtrace_lock);
9150 	}
9151 
9152 #ifdef illumos
9153 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9154 	    VM_BESTFIT | VM_SLEEP);
9155 #else
9156 	id = alloc_unr(dtrace_arena);
9157 #endif
9158 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9159 
9160 	probe->dtpr_id = id;
9161 	probe->dtpr_gen = dtrace_probegen++;
9162 	probe->dtpr_mod = dtrace_strdup(mod);
9163 	probe->dtpr_func = dtrace_strdup(func);
9164 	probe->dtpr_name = dtrace_strdup(name);
9165 	probe->dtpr_arg = arg;
9166 	probe->dtpr_aframes = aframes;
9167 	probe->dtpr_provider = provider;
9168 
9169 	dtrace_hash_add(dtrace_bymod, probe);
9170 	dtrace_hash_add(dtrace_byfunc, probe);
9171 	dtrace_hash_add(dtrace_byname, probe);
9172 
9173 	if (id - 1 >= dtrace_nprobes) {
9174 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9175 		size_t nsize = osize << 1;
9176 
9177 		if (nsize == 0) {
9178 			ASSERT(osize == 0);
9179 			ASSERT(dtrace_probes == NULL);
9180 			nsize = sizeof (dtrace_probe_t *);
9181 		}
9182 
9183 		probes = kmem_zalloc(nsize, KM_SLEEP);
9184 
9185 		if (dtrace_probes == NULL) {
9186 			ASSERT(osize == 0);
9187 			dtrace_probes = probes;
9188 			dtrace_nprobes = 1;
9189 		} else {
9190 			dtrace_probe_t **oprobes = dtrace_probes;
9191 
9192 			bcopy(oprobes, probes, osize);
9193 			dtrace_membar_producer();
9194 			dtrace_probes = probes;
9195 
9196 			dtrace_sync();
9197 
9198 			/*
9199 			 * All CPUs are now seeing the new probes array; we can
9200 			 * safely free the old array.
9201 			 */
9202 			kmem_free(oprobes, osize);
9203 			dtrace_nprobes <<= 1;
9204 		}
9205 
9206 		ASSERT(id - 1 < dtrace_nprobes);
9207 	}
9208 
9209 	ASSERT(dtrace_probes[id - 1] == NULL);
9210 	dtrace_probes[id - 1] = probe;
9211 
9212 	if (provider != dtrace_provider)
9213 		mutex_exit(&dtrace_lock);
9214 
9215 	return (id);
9216 }
9217 
9218 static dtrace_probe_t *
9219 dtrace_probe_lookup_id(dtrace_id_t id)
9220 {
9221 	ASSERT(MUTEX_HELD(&dtrace_lock));
9222 
9223 	if (id == 0 || id > dtrace_nprobes)
9224 		return (NULL);
9225 
9226 	return (dtrace_probes[id - 1]);
9227 }
9228 
9229 static int
9230 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9231 {
9232 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9233 
9234 	return (DTRACE_MATCH_DONE);
9235 }
9236 
9237 /*
9238  * Look up a probe based on provider and one or more of module name, function
9239  * name and probe name.
9240  */
9241 dtrace_id_t
9242 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9243     char *func, char *name)
9244 {
9245 	dtrace_probekey_t pkey;
9246 	dtrace_id_t id;
9247 	int match;
9248 
9249 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9250 	pkey.dtpk_pmatch = &dtrace_match_string;
9251 	pkey.dtpk_mod = mod;
9252 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9253 	pkey.dtpk_func = func;
9254 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9255 	pkey.dtpk_name = name;
9256 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9257 	pkey.dtpk_id = DTRACE_IDNONE;
9258 
9259 	mutex_enter(&dtrace_lock);
9260 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9261 	    dtrace_probe_lookup_match, &id);
9262 	mutex_exit(&dtrace_lock);
9263 
9264 	ASSERT(match == 1 || match == 0);
9265 	return (match ? id : 0);
9266 }
9267 
9268 /*
9269  * Returns the probe argument associated with the specified probe.
9270  */
9271 void *
9272 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9273 {
9274 	dtrace_probe_t *probe;
9275 	void *rval = NULL;
9276 
9277 	mutex_enter(&dtrace_lock);
9278 
9279 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9280 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9281 		rval = probe->dtpr_arg;
9282 
9283 	mutex_exit(&dtrace_lock);
9284 
9285 	return (rval);
9286 }
9287 
9288 /*
9289  * Copy a probe into a probe description.
9290  */
9291 static void
9292 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9293 {
9294 	bzero(pdp, sizeof (dtrace_probedesc_t));
9295 	pdp->dtpd_id = prp->dtpr_id;
9296 
9297 	(void) strncpy(pdp->dtpd_provider,
9298 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9299 
9300 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9301 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9302 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9303 }
9304 
9305 /*
9306  * Called to indicate that a probe -- or probes -- should be provided by a
9307  * specfied provider.  If the specified description is NULL, the provider will
9308  * be told to provide all of its probes.  (This is done whenever a new
9309  * consumer comes along, or whenever a retained enabling is to be matched.) If
9310  * the specified description is non-NULL, the provider is given the
9311  * opportunity to dynamically provide the specified probe, allowing providers
9312  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9313  * probes.)  If the provider is NULL, the operations will be applied to all
9314  * providers; if the provider is non-NULL the operations will only be applied
9315  * to the specified provider.  The dtrace_provider_lock must be held, and the
9316  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9317  * will need to grab the dtrace_lock when it reenters the framework through
9318  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9319  */
9320 static void
9321 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9322 {
9323 #ifdef illumos
9324 	modctl_t *ctl;
9325 #endif
9326 	int all = 0;
9327 
9328 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9329 
9330 	if (prv == NULL) {
9331 		all = 1;
9332 		prv = dtrace_provider;
9333 	}
9334 
9335 	do {
9336 		/*
9337 		 * First, call the blanket provide operation.
9338 		 */
9339 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9340 
9341 #ifdef illumos
9342 		/*
9343 		 * Now call the per-module provide operation.  We will grab
9344 		 * mod_lock to prevent the list from being modified.  Note
9345 		 * that this also prevents the mod_busy bits from changing.
9346 		 * (mod_busy can only be changed with mod_lock held.)
9347 		 */
9348 		mutex_enter(&mod_lock);
9349 
9350 		ctl = &modules;
9351 		do {
9352 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9353 				continue;
9354 
9355 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9356 
9357 		} while ((ctl = ctl->mod_next) != &modules);
9358 
9359 		mutex_exit(&mod_lock);
9360 #endif
9361 	} while (all && (prv = prv->dtpv_next) != NULL);
9362 }
9363 
9364 #ifdef illumos
9365 /*
9366  * Iterate over each probe, and call the Framework-to-Provider API function
9367  * denoted by offs.
9368  */
9369 static void
9370 dtrace_probe_foreach(uintptr_t offs)
9371 {
9372 	dtrace_provider_t *prov;
9373 	void (*func)(void *, dtrace_id_t, void *);
9374 	dtrace_probe_t *probe;
9375 	dtrace_icookie_t cookie;
9376 	int i;
9377 
9378 	/*
9379 	 * We disable interrupts to walk through the probe array.  This is
9380 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9381 	 * won't see stale data.
9382 	 */
9383 	cookie = dtrace_interrupt_disable();
9384 
9385 	for (i = 0; i < dtrace_nprobes; i++) {
9386 		if ((probe = dtrace_probes[i]) == NULL)
9387 			continue;
9388 
9389 		if (probe->dtpr_ecb == NULL) {
9390 			/*
9391 			 * This probe isn't enabled -- don't call the function.
9392 			 */
9393 			continue;
9394 		}
9395 
9396 		prov = probe->dtpr_provider;
9397 		func = *((void(**)(void *, dtrace_id_t, void *))
9398 		    ((uintptr_t)&prov->dtpv_pops + offs));
9399 
9400 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9401 	}
9402 
9403 	dtrace_interrupt_enable(cookie);
9404 }
9405 #endif
9406 
9407 static int
9408 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9409 {
9410 	dtrace_probekey_t pkey;
9411 	uint32_t priv;
9412 	uid_t uid;
9413 	zoneid_t zoneid;
9414 
9415 	ASSERT(MUTEX_HELD(&dtrace_lock));
9416 	dtrace_ecb_create_cache = NULL;
9417 
9418 	if (desc == NULL) {
9419 		/*
9420 		 * If we're passed a NULL description, we're being asked to
9421 		 * create an ECB with a NULL probe.
9422 		 */
9423 		(void) dtrace_ecb_create_enable(NULL, enab);
9424 		return (0);
9425 	}
9426 
9427 	dtrace_probekey(desc, &pkey);
9428 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9429 	    &priv, &uid, &zoneid);
9430 
9431 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9432 	    enab));
9433 }
9434 
9435 /*
9436  * DTrace Helper Provider Functions
9437  */
9438 static void
9439 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9440 {
9441 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9442 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9443 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9444 }
9445 
9446 static void
9447 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9448     const dof_provider_t *dofprov, char *strtab)
9449 {
9450 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9451 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9452 	    dofprov->dofpv_provattr);
9453 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9454 	    dofprov->dofpv_modattr);
9455 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9456 	    dofprov->dofpv_funcattr);
9457 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9458 	    dofprov->dofpv_nameattr);
9459 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9460 	    dofprov->dofpv_argsattr);
9461 }
9462 
9463 static void
9464 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9465 {
9466 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9467 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9468 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9469 	dof_provider_t *provider;
9470 	dof_probe_t *probe;
9471 	uint32_t *off, *enoff;
9472 	uint8_t *arg;
9473 	char *strtab;
9474 	uint_t i, nprobes;
9475 	dtrace_helper_provdesc_t dhpv;
9476 	dtrace_helper_probedesc_t dhpb;
9477 	dtrace_meta_t *meta = dtrace_meta_pid;
9478 	dtrace_mops_t *mops = &meta->dtm_mops;
9479 	void *parg;
9480 
9481 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9482 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9483 	    provider->dofpv_strtab * dof->dofh_secsize);
9484 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9485 	    provider->dofpv_probes * dof->dofh_secsize);
9486 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9487 	    provider->dofpv_prargs * dof->dofh_secsize);
9488 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9489 	    provider->dofpv_proffs * dof->dofh_secsize);
9490 
9491 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9492 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9493 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9494 	enoff = NULL;
9495 
9496 	/*
9497 	 * See dtrace_helper_provider_validate().
9498 	 */
9499 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9500 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9501 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9502 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9503 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9504 	}
9505 
9506 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9507 
9508 	/*
9509 	 * Create the provider.
9510 	 */
9511 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9512 
9513 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9514 		return;
9515 
9516 	meta->dtm_count++;
9517 
9518 	/*
9519 	 * Create the probes.
9520 	 */
9521 	for (i = 0; i < nprobes; i++) {
9522 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9523 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9524 
9525 		/* See the check in dtrace_helper_provider_validate(). */
9526 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9527 			continue;
9528 
9529 		dhpb.dthpb_mod = dhp->dofhp_mod;
9530 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9531 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9532 		dhpb.dthpb_base = probe->dofpr_addr;
9533 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9534 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9535 		if (enoff != NULL) {
9536 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9537 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9538 		} else {
9539 			dhpb.dthpb_enoffs = NULL;
9540 			dhpb.dthpb_nenoffs = 0;
9541 		}
9542 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9543 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9544 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9545 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9546 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9547 
9548 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9549 	}
9550 }
9551 
9552 static void
9553 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9554 {
9555 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9556 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9557 	int i;
9558 
9559 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9560 
9561 	for (i = 0; i < dof->dofh_secnum; i++) {
9562 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9563 		    dof->dofh_secoff + i * dof->dofh_secsize);
9564 
9565 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9566 			continue;
9567 
9568 		dtrace_helper_provide_one(dhp, sec, pid);
9569 	}
9570 
9571 	/*
9572 	 * We may have just created probes, so we must now rematch against
9573 	 * any retained enablings.  Note that this call will acquire both
9574 	 * cpu_lock and dtrace_lock; the fact that we are holding
9575 	 * dtrace_meta_lock now is what defines the ordering with respect to
9576 	 * these three locks.
9577 	 */
9578 	dtrace_enabling_matchall();
9579 }
9580 
9581 static void
9582 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9583 {
9584 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9585 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9586 	dof_sec_t *str_sec;
9587 	dof_provider_t *provider;
9588 	char *strtab;
9589 	dtrace_helper_provdesc_t dhpv;
9590 	dtrace_meta_t *meta = dtrace_meta_pid;
9591 	dtrace_mops_t *mops = &meta->dtm_mops;
9592 
9593 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9594 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9595 	    provider->dofpv_strtab * dof->dofh_secsize);
9596 
9597 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9598 
9599 	/*
9600 	 * Create the provider.
9601 	 */
9602 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9603 
9604 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9605 
9606 	meta->dtm_count--;
9607 }
9608 
9609 static void
9610 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9611 {
9612 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9613 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9614 	int i;
9615 
9616 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9617 
9618 	for (i = 0; i < dof->dofh_secnum; i++) {
9619 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9620 		    dof->dofh_secoff + i * dof->dofh_secsize);
9621 
9622 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9623 			continue;
9624 
9625 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9626 	}
9627 }
9628 
9629 /*
9630  * DTrace Meta Provider-to-Framework API Functions
9631  *
9632  * These functions implement the Meta Provider-to-Framework API, as described
9633  * in <sys/dtrace.h>.
9634  */
9635 int
9636 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9637     dtrace_meta_provider_id_t *idp)
9638 {
9639 	dtrace_meta_t *meta;
9640 	dtrace_helpers_t *help, *next;
9641 	int i;
9642 
9643 	*idp = DTRACE_METAPROVNONE;
9644 
9645 	/*
9646 	 * We strictly don't need the name, but we hold onto it for
9647 	 * debuggability. All hail error queues!
9648 	 */
9649 	if (name == NULL) {
9650 		cmn_err(CE_WARN, "failed to register meta-provider: "
9651 		    "invalid name");
9652 		return (EINVAL);
9653 	}
9654 
9655 	if (mops == NULL ||
9656 	    mops->dtms_create_probe == NULL ||
9657 	    mops->dtms_provide_pid == NULL ||
9658 	    mops->dtms_remove_pid == NULL) {
9659 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9660 		    "invalid ops", name);
9661 		return (EINVAL);
9662 	}
9663 
9664 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9665 	meta->dtm_mops = *mops;
9666 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9667 	(void) strcpy(meta->dtm_name, name);
9668 	meta->dtm_arg = arg;
9669 
9670 	mutex_enter(&dtrace_meta_lock);
9671 	mutex_enter(&dtrace_lock);
9672 
9673 	if (dtrace_meta_pid != NULL) {
9674 		mutex_exit(&dtrace_lock);
9675 		mutex_exit(&dtrace_meta_lock);
9676 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9677 		    "user-land meta-provider exists", name);
9678 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9679 		kmem_free(meta, sizeof (dtrace_meta_t));
9680 		return (EINVAL);
9681 	}
9682 
9683 	dtrace_meta_pid = meta;
9684 	*idp = (dtrace_meta_provider_id_t)meta;
9685 
9686 	/*
9687 	 * If there are providers and probes ready to go, pass them
9688 	 * off to the new meta provider now.
9689 	 */
9690 
9691 	help = dtrace_deferred_pid;
9692 	dtrace_deferred_pid = NULL;
9693 
9694 	mutex_exit(&dtrace_lock);
9695 
9696 	while (help != NULL) {
9697 		for (i = 0; i < help->dthps_nprovs; i++) {
9698 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9699 			    help->dthps_pid);
9700 		}
9701 
9702 		next = help->dthps_next;
9703 		help->dthps_next = NULL;
9704 		help->dthps_prev = NULL;
9705 		help->dthps_deferred = 0;
9706 		help = next;
9707 	}
9708 
9709 	mutex_exit(&dtrace_meta_lock);
9710 
9711 	return (0);
9712 }
9713 
9714 int
9715 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9716 {
9717 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9718 
9719 	mutex_enter(&dtrace_meta_lock);
9720 	mutex_enter(&dtrace_lock);
9721 
9722 	if (old == dtrace_meta_pid) {
9723 		pp = &dtrace_meta_pid;
9724 	} else {
9725 		panic("attempt to unregister non-existent "
9726 		    "dtrace meta-provider %p\n", (void *)old);
9727 	}
9728 
9729 	if (old->dtm_count != 0) {
9730 		mutex_exit(&dtrace_lock);
9731 		mutex_exit(&dtrace_meta_lock);
9732 		return (EBUSY);
9733 	}
9734 
9735 	*pp = NULL;
9736 
9737 	mutex_exit(&dtrace_lock);
9738 	mutex_exit(&dtrace_meta_lock);
9739 
9740 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9741 	kmem_free(old, sizeof (dtrace_meta_t));
9742 
9743 	return (0);
9744 }
9745 
9746 
9747 /*
9748  * DTrace DIF Object Functions
9749  */
9750 static int
9751 dtrace_difo_err(uint_t pc, const char *format, ...)
9752 {
9753 	if (dtrace_err_verbose) {
9754 		va_list alist;
9755 
9756 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9757 		va_start(alist, format);
9758 		(void) vuprintf(format, alist);
9759 		va_end(alist);
9760 	}
9761 
9762 #ifdef DTRACE_ERRDEBUG
9763 	dtrace_errdebug(format);
9764 #endif
9765 	return (1);
9766 }
9767 
9768 /*
9769  * Validate a DTrace DIF object by checking the IR instructions.  The following
9770  * rules are currently enforced by dtrace_difo_validate():
9771  *
9772  * 1. Each instruction must have a valid opcode
9773  * 2. Each register, string, variable, or subroutine reference must be valid
9774  * 3. No instruction can modify register %r0 (must be zero)
9775  * 4. All instruction reserved bits must be set to zero
9776  * 5. The last instruction must be a "ret" instruction
9777  * 6. All branch targets must reference a valid instruction _after_ the branch
9778  */
9779 static int
9780 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9781     cred_t *cr)
9782 {
9783 	int err = 0, i;
9784 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9785 	int kcheckload;
9786 	uint_t pc;
9787 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9788 
9789 	kcheckload = cr == NULL ||
9790 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9791 
9792 	dp->dtdo_destructive = 0;
9793 
9794 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9795 		dif_instr_t instr = dp->dtdo_buf[pc];
9796 
9797 		uint_t r1 = DIF_INSTR_R1(instr);
9798 		uint_t r2 = DIF_INSTR_R2(instr);
9799 		uint_t rd = DIF_INSTR_RD(instr);
9800 		uint_t rs = DIF_INSTR_RS(instr);
9801 		uint_t label = DIF_INSTR_LABEL(instr);
9802 		uint_t v = DIF_INSTR_VAR(instr);
9803 		uint_t subr = DIF_INSTR_SUBR(instr);
9804 		uint_t type = DIF_INSTR_TYPE(instr);
9805 		uint_t op = DIF_INSTR_OP(instr);
9806 
9807 		switch (op) {
9808 		case DIF_OP_OR:
9809 		case DIF_OP_XOR:
9810 		case DIF_OP_AND:
9811 		case DIF_OP_SLL:
9812 		case DIF_OP_SRL:
9813 		case DIF_OP_SRA:
9814 		case DIF_OP_SUB:
9815 		case DIF_OP_ADD:
9816 		case DIF_OP_MUL:
9817 		case DIF_OP_SDIV:
9818 		case DIF_OP_UDIV:
9819 		case DIF_OP_SREM:
9820 		case DIF_OP_UREM:
9821 		case DIF_OP_COPYS:
9822 			if (r1 >= nregs)
9823 				err += efunc(pc, "invalid register %u\n", r1);
9824 			if (r2 >= nregs)
9825 				err += efunc(pc, "invalid register %u\n", r2);
9826 			if (rd >= nregs)
9827 				err += efunc(pc, "invalid register %u\n", rd);
9828 			if (rd == 0)
9829 				err += efunc(pc, "cannot write to %r0\n");
9830 			break;
9831 		case DIF_OP_NOT:
9832 		case DIF_OP_MOV:
9833 		case DIF_OP_ALLOCS:
9834 			if (r1 >= nregs)
9835 				err += efunc(pc, "invalid register %u\n", r1);
9836 			if (r2 != 0)
9837 				err += efunc(pc, "non-zero reserved bits\n");
9838 			if (rd >= nregs)
9839 				err += efunc(pc, "invalid register %u\n", rd);
9840 			if (rd == 0)
9841 				err += efunc(pc, "cannot write to %r0\n");
9842 			break;
9843 		case DIF_OP_LDSB:
9844 		case DIF_OP_LDSH:
9845 		case DIF_OP_LDSW:
9846 		case DIF_OP_LDUB:
9847 		case DIF_OP_LDUH:
9848 		case DIF_OP_LDUW:
9849 		case DIF_OP_LDX:
9850 			if (r1 >= nregs)
9851 				err += efunc(pc, "invalid register %u\n", r1);
9852 			if (r2 != 0)
9853 				err += efunc(pc, "non-zero reserved bits\n");
9854 			if (rd >= nregs)
9855 				err += efunc(pc, "invalid register %u\n", rd);
9856 			if (rd == 0)
9857 				err += efunc(pc, "cannot write to %r0\n");
9858 			if (kcheckload)
9859 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9860 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9861 			break;
9862 		case DIF_OP_RLDSB:
9863 		case DIF_OP_RLDSH:
9864 		case DIF_OP_RLDSW:
9865 		case DIF_OP_RLDUB:
9866 		case DIF_OP_RLDUH:
9867 		case DIF_OP_RLDUW:
9868 		case DIF_OP_RLDX:
9869 			if (r1 >= nregs)
9870 				err += efunc(pc, "invalid register %u\n", r1);
9871 			if (r2 != 0)
9872 				err += efunc(pc, "non-zero reserved bits\n");
9873 			if (rd >= nregs)
9874 				err += efunc(pc, "invalid register %u\n", rd);
9875 			if (rd == 0)
9876 				err += efunc(pc, "cannot write to %r0\n");
9877 			break;
9878 		case DIF_OP_ULDSB:
9879 		case DIF_OP_ULDSH:
9880 		case DIF_OP_ULDSW:
9881 		case DIF_OP_ULDUB:
9882 		case DIF_OP_ULDUH:
9883 		case DIF_OP_ULDUW:
9884 		case DIF_OP_ULDX:
9885 			if (r1 >= nregs)
9886 				err += efunc(pc, "invalid register %u\n", r1);
9887 			if (r2 != 0)
9888 				err += efunc(pc, "non-zero reserved bits\n");
9889 			if (rd >= nregs)
9890 				err += efunc(pc, "invalid register %u\n", rd);
9891 			if (rd == 0)
9892 				err += efunc(pc, "cannot write to %r0\n");
9893 			break;
9894 		case DIF_OP_STB:
9895 		case DIF_OP_STH:
9896 		case DIF_OP_STW:
9897 		case DIF_OP_STX:
9898 			if (r1 >= nregs)
9899 				err += efunc(pc, "invalid register %u\n", r1);
9900 			if (r2 != 0)
9901 				err += efunc(pc, "non-zero reserved bits\n");
9902 			if (rd >= nregs)
9903 				err += efunc(pc, "invalid register %u\n", rd);
9904 			if (rd == 0)
9905 				err += efunc(pc, "cannot write to 0 address\n");
9906 			break;
9907 		case DIF_OP_CMP:
9908 		case DIF_OP_SCMP:
9909 			if (r1 >= nregs)
9910 				err += efunc(pc, "invalid register %u\n", r1);
9911 			if (r2 >= nregs)
9912 				err += efunc(pc, "invalid register %u\n", r2);
9913 			if (rd != 0)
9914 				err += efunc(pc, "non-zero reserved bits\n");
9915 			break;
9916 		case DIF_OP_TST:
9917 			if (r1 >= nregs)
9918 				err += efunc(pc, "invalid register %u\n", r1);
9919 			if (r2 != 0 || rd != 0)
9920 				err += efunc(pc, "non-zero reserved bits\n");
9921 			break;
9922 		case DIF_OP_BA:
9923 		case DIF_OP_BE:
9924 		case DIF_OP_BNE:
9925 		case DIF_OP_BG:
9926 		case DIF_OP_BGU:
9927 		case DIF_OP_BGE:
9928 		case DIF_OP_BGEU:
9929 		case DIF_OP_BL:
9930 		case DIF_OP_BLU:
9931 		case DIF_OP_BLE:
9932 		case DIF_OP_BLEU:
9933 			if (label >= dp->dtdo_len) {
9934 				err += efunc(pc, "invalid branch target %u\n",
9935 				    label);
9936 			}
9937 			if (label <= pc) {
9938 				err += efunc(pc, "backward branch to %u\n",
9939 				    label);
9940 			}
9941 			break;
9942 		case DIF_OP_RET:
9943 			if (r1 != 0 || r2 != 0)
9944 				err += efunc(pc, "non-zero reserved bits\n");
9945 			if (rd >= nregs)
9946 				err += efunc(pc, "invalid register %u\n", rd);
9947 			break;
9948 		case DIF_OP_NOP:
9949 		case DIF_OP_POPTS:
9950 		case DIF_OP_FLUSHTS:
9951 			if (r1 != 0 || r2 != 0 || rd != 0)
9952 				err += efunc(pc, "non-zero reserved bits\n");
9953 			break;
9954 		case DIF_OP_SETX:
9955 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9956 				err += efunc(pc, "invalid integer ref %u\n",
9957 				    DIF_INSTR_INTEGER(instr));
9958 			}
9959 			if (rd >= nregs)
9960 				err += efunc(pc, "invalid register %u\n", rd);
9961 			if (rd == 0)
9962 				err += efunc(pc, "cannot write to %r0\n");
9963 			break;
9964 		case DIF_OP_SETS:
9965 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9966 				err += efunc(pc, "invalid string ref %u\n",
9967 				    DIF_INSTR_STRING(instr));
9968 			}
9969 			if (rd >= nregs)
9970 				err += efunc(pc, "invalid register %u\n", rd);
9971 			if (rd == 0)
9972 				err += efunc(pc, "cannot write to %r0\n");
9973 			break;
9974 		case DIF_OP_LDGA:
9975 		case DIF_OP_LDTA:
9976 			if (r1 > DIF_VAR_ARRAY_MAX)
9977 				err += efunc(pc, "invalid array %u\n", r1);
9978 			if (r2 >= nregs)
9979 				err += efunc(pc, "invalid register %u\n", r2);
9980 			if (rd >= nregs)
9981 				err += efunc(pc, "invalid register %u\n", rd);
9982 			if (rd == 0)
9983 				err += efunc(pc, "cannot write to %r0\n");
9984 			break;
9985 		case DIF_OP_LDGS:
9986 		case DIF_OP_LDTS:
9987 		case DIF_OP_LDLS:
9988 		case DIF_OP_LDGAA:
9989 		case DIF_OP_LDTAA:
9990 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9991 				err += efunc(pc, "invalid variable %u\n", v);
9992 			if (rd >= nregs)
9993 				err += efunc(pc, "invalid register %u\n", rd);
9994 			if (rd == 0)
9995 				err += efunc(pc, "cannot write to %r0\n");
9996 			break;
9997 		case DIF_OP_STGS:
9998 		case DIF_OP_STTS:
9999 		case DIF_OP_STLS:
10000 		case DIF_OP_STGAA:
10001 		case DIF_OP_STTAA:
10002 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
10003 				err += efunc(pc, "invalid variable %u\n", v);
10004 			if (rs >= nregs)
10005 				err += efunc(pc, "invalid register %u\n", rd);
10006 			break;
10007 		case DIF_OP_CALL:
10008 			if (subr > DIF_SUBR_MAX)
10009 				err += efunc(pc, "invalid subr %u\n", subr);
10010 			if (rd >= nregs)
10011 				err += efunc(pc, "invalid register %u\n", rd);
10012 			if (rd == 0)
10013 				err += efunc(pc, "cannot write to %r0\n");
10014 
10015 			if (subr == DIF_SUBR_COPYOUT ||
10016 			    subr == DIF_SUBR_COPYOUTSTR) {
10017 				dp->dtdo_destructive = 1;
10018 			}
10019 
10020 			if (subr == DIF_SUBR_GETF) {
10021 #ifdef __FreeBSD__
10022 				err += efunc(pc, "getf() not supported");
10023 #else
10024 				/*
10025 				 * If we have a getf() we need to record that
10026 				 * in our state.  Note that our state can be
10027 				 * NULL if this is a helper -- but in that
10028 				 * case, the call to getf() is itself illegal,
10029 				 * and will be caught (slightly later) when
10030 				 * the helper is validated.
10031 				 */
10032 				if (vstate->dtvs_state != NULL)
10033 					vstate->dtvs_state->dts_getf++;
10034 #endif
10035 			}
10036 
10037 			break;
10038 		case DIF_OP_PUSHTR:
10039 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10040 				err += efunc(pc, "invalid ref type %u\n", type);
10041 			if (r2 >= nregs)
10042 				err += efunc(pc, "invalid register %u\n", r2);
10043 			if (rs >= nregs)
10044 				err += efunc(pc, "invalid register %u\n", rs);
10045 			break;
10046 		case DIF_OP_PUSHTV:
10047 			if (type != DIF_TYPE_CTF)
10048 				err += efunc(pc, "invalid val type %u\n", type);
10049 			if (r2 >= nregs)
10050 				err += efunc(pc, "invalid register %u\n", r2);
10051 			if (rs >= nregs)
10052 				err += efunc(pc, "invalid register %u\n", rs);
10053 			break;
10054 		default:
10055 			err += efunc(pc, "invalid opcode %u\n",
10056 			    DIF_INSTR_OP(instr));
10057 		}
10058 	}
10059 
10060 	if (dp->dtdo_len != 0 &&
10061 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10062 		err += efunc(dp->dtdo_len - 1,
10063 		    "expected 'ret' as last DIF instruction\n");
10064 	}
10065 
10066 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10067 		/*
10068 		 * If we're not returning by reference, the size must be either
10069 		 * 0 or the size of one of the base types.
10070 		 */
10071 		switch (dp->dtdo_rtype.dtdt_size) {
10072 		case 0:
10073 		case sizeof (uint8_t):
10074 		case sizeof (uint16_t):
10075 		case sizeof (uint32_t):
10076 		case sizeof (uint64_t):
10077 			break;
10078 
10079 		default:
10080 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10081 		}
10082 	}
10083 
10084 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10085 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10086 		dtrace_diftype_t *vt, *et;
10087 		uint_t id, ndx;
10088 
10089 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10090 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10091 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10092 			err += efunc(i, "unrecognized variable scope %d\n",
10093 			    v->dtdv_scope);
10094 			break;
10095 		}
10096 
10097 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10098 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10099 			err += efunc(i, "unrecognized variable type %d\n",
10100 			    v->dtdv_kind);
10101 			break;
10102 		}
10103 
10104 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10105 			err += efunc(i, "%d exceeds variable id limit\n", id);
10106 			break;
10107 		}
10108 
10109 		if (id < DIF_VAR_OTHER_UBASE)
10110 			continue;
10111 
10112 		/*
10113 		 * For user-defined variables, we need to check that this
10114 		 * definition is identical to any previous definition that we
10115 		 * encountered.
10116 		 */
10117 		ndx = id - DIF_VAR_OTHER_UBASE;
10118 
10119 		switch (v->dtdv_scope) {
10120 		case DIFV_SCOPE_GLOBAL:
10121 			if (maxglobal == -1 || ndx > maxglobal)
10122 				maxglobal = ndx;
10123 
10124 			if (ndx < vstate->dtvs_nglobals) {
10125 				dtrace_statvar_t *svar;
10126 
10127 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10128 					existing = &svar->dtsv_var;
10129 			}
10130 
10131 			break;
10132 
10133 		case DIFV_SCOPE_THREAD:
10134 			if (maxtlocal == -1 || ndx > maxtlocal)
10135 				maxtlocal = ndx;
10136 
10137 			if (ndx < vstate->dtvs_ntlocals)
10138 				existing = &vstate->dtvs_tlocals[ndx];
10139 			break;
10140 
10141 		case DIFV_SCOPE_LOCAL:
10142 			if (maxlocal == -1 || ndx > maxlocal)
10143 				maxlocal = ndx;
10144 
10145 			if (ndx < vstate->dtvs_nlocals) {
10146 				dtrace_statvar_t *svar;
10147 
10148 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10149 					existing = &svar->dtsv_var;
10150 			}
10151 
10152 			break;
10153 		}
10154 
10155 		vt = &v->dtdv_type;
10156 
10157 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10158 			if (vt->dtdt_size == 0) {
10159 				err += efunc(i, "zero-sized variable\n");
10160 				break;
10161 			}
10162 
10163 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10164 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10165 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10166 				err += efunc(i, "oversized by-ref static\n");
10167 				break;
10168 			}
10169 		}
10170 
10171 		if (existing == NULL || existing->dtdv_id == 0)
10172 			continue;
10173 
10174 		ASSERT(existing->dtdv_id == v->dtdv_id);
10175 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10176 
10177 		if (existing->dtdv_kind != v->dtdv_kind)
10178 			err += efunc(i, "%d changed variable kind\n", id);
10179 
10180 		et = &existing->dtdv_type;
10181 
10182 		if (vt->dtdt_flags != et->dtdt_flags) {
10183 			err += efunc(i, "%d changed variable type flags\n", id);
10184 			break;
10185 		}
10186 
10187 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10188 			err += efunc(i, "%d changed variable type size\n", id);
10189 			break;
10190 		}
10191 	}
10192 
10193 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10194 		dif_instr_t instr = dp->dtdo_buf[pc];
10195 
10196 		uint_t v = DIF_INSTR_VAR(instr);
10197 		uint_t op = DIF_INSTR_OP(instr);
10198 
10199 		switch (op) {
10200 		case DIF_OP_LDGS:
10201 		case DIF_OP_LDGAA:
10202 		case DIF_OP_STGS:
10203 		case DIF_OP_STGAA:
10204 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10205 				err += efunc(pc, "invalid variable %u\n", v);
10206 			break;
10207 		case DIF_OP_LDTS:
10208 		case DIF_OP_LDTAA:
10209 		case DIF_OP_STTS:
10210 		case DIF_OP_STTAA:
10211 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10212 				err += efunc(pc, "invalid variable %u\n", v);
10213 			break;
10214 		case DIF_OP_LDLS:
10215 		case DIF_OP_STLS:
10216 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10217 				err += efunc(pc, "invalid variable %u\n", v);
10218 			break;
10219 		default:
10220 			break;
10221 		}
10222 	}
10223 
10224 	return (err);
10225 }
10226 
10227 /*
10228  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10229  * are much more constrained than normal DIFOs.  Specifically, they may
10230  * not:
10231  *
10232  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10233  *    miscellaneous string routines
10234  * 2. Access DTrace variables other than the args[] array, and the
10235  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10236  * 3. Have thread-local variables.
10237  * 4. Have dynamic variables.
10238  */
10239 static int
10240 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10241 {
10242 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10243 	int err = 0;
10244 	uint_t pc;
10245 
10246 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10247 		dif_instr_t instr = dp->dtdo_buf[pc];
10248 
10249 		uint_t v = DIF_INSTR_VAR(instr);
10250 		uint_t subr = DIF_INSTR_SUBR(instr);
10251 		uint_t op = DIF_INSTR_OP(instr);
10252 
10253 		switch (op) {
10254 		case DIF_OP_OR:
10255 		case DIF_OP_XOR:
10256 		case DIF_OP_AND:
10257 		case DIF_OP_SLL:
10258 		case DIF_OP_SRL:
10259 		case DIF_OP_SRA:
10260 		case DIF_OP_SUB:
10261 		case DIF_OP_ADD:
10262 		case DIF_OP_MUL:
10263 		case DIF_OP_SDIV:
10264 		case DIF_OP_UDIV:
10265 		case DIF_OP_SREM:
10266 		case DIF_OP_UREM:
10267 		case DIF_OP_COPYS:
10268 		case DIF_OP_NOT:
10269 		case DIF_OP_MOV:
10270 		case DIF_OP_RLDSB:
10271 		case DIF_OP_RLDSH:
10272 		case DIF_OP_RLDSW:
10273 		case DIF_OP_RLDUB:
10274 		case DIF_OP_RLDUH:
10275 		case DIF_OP_RLDUW:
10276 		case DIF_OP_RLDX:
10277 		case DIF_OP_ULDSB:
10278 		case DIF_OP_ULDSH:
10279 		case DIF_OP_ULDSW:
10280 		case DIF_OP_ULDUB:
10281 		case DIF_OP_ULDUH:
10282 		case DIF_OP_ULDUW:
10283 		case DIF_OP_ULDX:
10284 		case DIF_OP_STB:
10285 		case DIF_OP_STH:
10286 		case DIF_OP_STW:
10287 		case DIF_OP_STX:
10288 		case DIF_OP_ALLOCS:
10289 		case DIF_OP_CMP:
10290 		case DIF_OP_SCMP:
10291 		case DIF_OP_TST:
10292 		case DIF_OP_BA:
10293 		case DIF_OP_BE:
10294 		case DIF_OP_BNE:
10295 		case DIF_OP_BG:
10296 		case DIF_OP_BGU:
10297 		case DIF_OP_BGE:
10298 		case DIF_OP_BGEU:
10299 		case DIF_OP_BL:
10300 		case DIF_OP_BLU:
10301 		case DIF_OP_BLE:
10302 		case DIF_OP_BLEU:
10303 		case DIF_OP_RET:
10304 		case DIF_OP_NOP:
10305 		case DIF_OP_POPTS:
10306 		case DIF_OP_FLUSHTS:
10307 		case DIF_OP_SETX:
10308 		case DIF_OP_SETS:
10309 		case DIF_OP_LDGA:
10310 		case DIF_OP_LDLS:
10311 		case DIF_OP_STGS:
10312 		case DIF_OP_STLS:
10313 		case DIF_OP_PUSHTR:
10314 		case DIF_OP_PUSHTV:
10315 			break;
10316 
10317 		case DIF_OP_LDGS:
10318 			if (v >= DIF_VAR_OTHER_UBASE)
10319 				break;
10320 
10321 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10322 				break;
10323 
10324 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10325 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10326 			    v == DIF_VAR_EXECARGS ||
10327 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10328 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10329 				break;
10330 
10331 			err += efunc(pc, "illegal variable %u\n", v);
10332 			break;
10333 
10334 		case DIF_OP_LDTA:
10335 		case DIF_OP_LDTS:
10336 		case DIF_OP_LDGAA:
10337 		case DIF_OP_LDTAA:
10338 			err += efunc(pc, "illegal dynamic variable load\n");
10339 			break;
10340 
10341 		case DIF_OP_STTS:
10342 		case DIF_OP_STGAA:
10343 		case DIF_OP_STTAA:
10344 			err += efunc(pc, "illegal dynamic variable store\n");
10345 			break;
10346 
10347 		case DIF_OP_CALL:
10348 			if (subr == DIF_SUBR_ALLOCA ||
10349 			    subr == DIF_SUBR_BCOPY ||
10350 			    subr == DIF_SUBR_COPYIN ||
10351 			    subr == DIF_SUBR_COPYINTO ||
10352 			    subr == DIF_SUBR_COPYINSTR ||
10353 			    subr == DIF_SUBR_INDEX ||
10354 			    subr == DIF_SUBR_INET_NTOA ||
10355 			    subr == DIF_SUBR_INET_NTOA6 ||
10356 			    subr == DIF_SUBR_INET_NTOP ||
10357 			    subr == DIF_SUBR_JSON ||
10358 			    subr == DIF_SUBR_LLTOSTR ||
10359 			    subr == DIF_SUBR_STRTOLL ||
10360 			    subr == DIF_SUBR_RINDEX ||
10361 			    subr == DIF_SUBR_STRCHR ||
10362 			    subr == DIF_SUBR_STRJOIN ||
10363 			    subr == DIF_SUBR_STRRCHR ||
10364 			    subr == DIF_SUBR_STRSTR ||
10365 			    subr == DIF_SUBR_HTONS ||
10366 			    subr == DIF_SUBR_HTONL ||
10367 			    subr == DIF_SUBR_HTONLL ||
10368 			    subr == DIF_SUBR_NTOHS ||
10369 			    subr == DIF_SUBR_NTOHL ||
10370 			    subr == DIF_SUBR_NTOHLL ||
10371 			    subr == DIF_SUBR_MEMREF)
10372 				break;
10373 #ifdef __FreeBSD__
10374 			if (subr == DIF_SUBR_MEMSTR)
10375 				break;
10376 #endif
10377 
10378 			err += efunc(pc, "invalid subr %u\n", subr);
10379 			break;
10380 
10381 		default:
10382 			err += efunc(pc, "invalid opcode %u\n",
10383 			    DIF_INSTR_OP(instr));
10384 		}
10385 	}
10386 
10387 	return (err);
10388 }
10389 
10390 /*
10391  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10392  * basis; 0 if not.
10393  */
10394 static int
10395 dtrace_difo_cacheable(dtrace_difo_t *dp)
10396 {
10397 	int i;
10398 
10399 	if (dp == NULL)
10400 		return (0);
10401 
10402 	for (i = 0; i < dp->dtdo_varlen; i++) {
10403 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10404 
10405 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10406 			continue;
10407 
10408 		switch (v->dtdv_id) {
10409 		case DIF_VAR_CURTHREAD:
10410 		case DIF_VAR_PID:
10411 		case DIF_VAR_TID:
10412 		case DIF_VAR_EXECARGS:
10413 		case DIF_VAR_EXECNAME:
10414 		case DIF_VAR_ZONENAME:
10415 			break;
10416 
10417 		default:
10418 			return (0);
10419 		}
10420 	}
10421 
10422 	/*
10423 	 * This DIF object may be cacheable.  Now we need to look for any
10424 	 * array loading instructions, any memory loading instructions, or
10425 	 * any stores to thread-local variables.
10426 	 */
10427 	for (i = 0; i < dp->dtdo_len; i++) {
10428 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10429 
10430 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10431 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10432 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10433 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10434 			return (0);
10435 	}
10436 
10437 	return (1);
10438 }
10439 
10440 static void
10441 dtrace_difo_hold(dtrace_difo_t *dp)
10442 {
10443 	int i;
10444 
10445 	ASSERT(MUTEX_HELD(&dtrace_lock));
10446 
10447 	dp->dtdo_refcnt++;
10448 	ASSERT(dp->dtdo_refcnt != 0);
10449 
10450 	/*
10451 	 * We need to check this DIF object for references to the variable
10452 	 * DIF_VAR_VTIMESTAMP.
10453 	 */
10454 	for (i = 0; i < dp->dtdo_varlen; i++) {
10455 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10456 
10457 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10458 			continue;
10459 
10460 		if (dtrace_vtime_references++ == 0)
10461 			dtrace_vtime_enable();
10462 	}
10463 }
10464 
10465 /*
10466  * This routine calculates the dynamic variable chunksize for a given DIF
10467  * object.  The calculation is not fool-proof, and can probably be tricked by
10468  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10469  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10470  * if a dynamic variable size exceeds the chunksize.
10471  */
10472 static void
10473 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10474 {
10475 	uint64_t sval = 0;
10476 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10477 	const dif_instr_t *text = dp->dtdo_buf;
10478 	uint_t pc, srd = 0;
10479 	uint_t ttop = 0;
10480 	size_t size, ksize;
10481 	uint_t id, i;
10482 
10483 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10484 		dif_instr_t instr = text[pc];
10485 		uint_t op = DIF_INSTR_OP(instr);
10486 		uint_t rd = DIF_INSTR_RD(instr);
10487 		uint_t r1 = DIF_INSTR_R1(instr);
10488 		uint_t nkeys = 0;
10489 		uchar_t scope = 0;
10490 
10491 		dtrace_key_t *key = tupregs;
10492 
10493 		switch (op) {
10494 		case DIF_OP_SETX:
10495 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10496 			srd = rd;
10497 			continue;
10498 
10499 		case DIF_OP_STTS:
10500 			key = &tupregs[DIF_DTR_NREGS];
10501 			key[0].dttk_size = 0;
10502 			key[1].dttk_size = 0;
10503 			nkeys = 2;
10504 			scope = DIFV_SCOPE_THREAD;
10505 			break;
10506 
10507 		case DIF_OP_STGAA:
10508 		case DIF_OP_STTAA:
10509 			nkeys = ttop;
10510 
10511 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10512 				key[nkeys++].dttk_size = 0;
10513 
10514 			key[nkeys++].dttk_size = 0;
10515 
10516 			if (op == DIF_OP_STTAA) {
10517 				scope = DIFV_SCOPE_THREAD;
10518 			} else {
10519 				scope = DIFV_SCOPE_GLOBAL;
10520 			}
10521 
10522 			break;
10523 
10524 		case DIF_OP_PUSHTR:
10525 			if (ttop == DIF_DTR_NREGS)
10526 				return;
10527 
10528 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10529 				/*
10530 				 * If the register for the size of the "pushtr"
10531 				 * is %r0 (or the value is 0) and the type is
10532 				 * a string, we'll use the system-wide default
10533 				 * string size.
10534 				 */
10535 				tupregs[ttop++].dttk_size =
10536 				    dtrace_strsize_default;
10537 			} else {
10538 				if (srd == 0)
10539 					return;
10540 
10541 				if (sval > LONG_MAX)
10542 					return;
10543 
10544 				tupregs[ttop++].dttk_size = sval;
10545 			}
10546 
10547 			break;
10548 
10549 		case DIF_OP_PUSHTV:
10550 			if (ttop == DIF_DTR_NREGS)
10551 				return;
10552 
10553 			tupregs[ttop++].dttk_size = 0;
10554 			break;
10555 
10556 		case DIF_OP_FLUSHTS:
10557 			ttop = 0;
10558 			break;
10559 
10560 		case DIF_OP_POPTS:
10561 			if (ttop != 0)
10562 				ttop--;
10563 			break;
10564 		}
10565 
10566 		sval = 0;
10567 		srd = 0;
10568 
10569 		if (nkeys == 0)
10570 			continue;
10571 
10572 		/*
10573 		 * We have a dynamic variable allocation; calculate its size.
10574 		 */
10575 		for (ksize = 0, i = 0; i < nkeys; i++)
10576 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10577 
10578 		size = sizeof (dtrace_dynvar_t);
10579 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10580 		size += ksize;
10581 
10582 		/*
10583 		 * Now we need to determine the size of the stored data.
10584 		 */
10585 		id = DIF_INSTR_VAR(instr);
10586 
10587 		for (i = 0; i < dp->dtdo_varlen; i++) {
10588 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10589 
10590 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10591 				size += v->dtdv_type.dtdt_size;
10592 				break;
10593 			}
10594 		}
10595 
10596 		if (i == dp->dtdo_varlen)
10597 			return;
10598 
10599 		/*
10600 		 * We have the size.  If this is larger than the chunk size
10601 		 * for our dynamic variable state, reset the chunk size.
10602 		 */
10603 		size = P2ROUNDUP(size, sizeof (uint64_t));
10604 
10605 		/*
10606 		 * Before setting the chunk size, check that we're not going
10607 		 * to set it to a negative value...
10608 		 */
10609 		if (size > LONG_MAX)
10610 			return;
10611 
10612 		/*
10613 		 * ...and make certain that we didn't badly overflow.
10614 		 */
10615 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10616 			return;
10617 
10618 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10619 			vstate->dtvs_dynvars.dtds_chunksize = size;
10620 	}
10621 }
10622 
10623 static void
10624 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10625 {
10626 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10627 	uint_t id;
10628 
10629 	ASSERT(MUTEX_HELD(&dtrace_lock));
10630 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10631 
10632 	for (i = 0; i < dp->dtdo_varlen; i++) {
10633 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10634 		dtrace_statvar_t *svar, ***svarp = NULL;
10635 		size_t dsize = 0;
10636 		uint8_t scope = v->dtdv_scope;
10637 		int *np = NULL;
10638 
10639 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10640 			continue;
10641 
10642 		id -= DIF_VAR_OTHER_UBASE;
10643 
10644 		switch (scope) {
10645 		case DIFV_SCOPE_THREAD:
10646 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10647 				dtrace_difv_t *tlocals;
10648 
10649 				if ((ntlocals = (otlocals << 1)) == 0)
10650 					ntlocals = 1;
10651 
10652 				osz = otlocals * sizeof (dtrace_difv_t);
10653 				nsz = ntlocals * sizeof (dtrace_difv_t);
10654 
10655 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10656 
10657 				if (osz != 0) {
10658 					bcopy(vstate->dtvs_tlocals,
10659 					    tlocals, osz);
10660 					kmem_free(vstate->dtvs_tlocals, osz);
10661 				}
10662 
10663 				vstate->dtvs_tlocals = tlocals;
10664 				vstate->dtvs_ntlocals = ntlocals;
10665 			}
10666 
10667 			vstate->dtvs_tlocals[id] = *v;
10668 			continue;
10669 
10670 		case DIFV_SCOPE_LOCAL:
10671 			np = &vstate->dtvs_nlocals;
10672 			svarp = &vstate->dtvs_locals;
10673 
10674 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10675 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10676 				    sizeof (uint64_t));
10677 			else
10678 				dsize = NCPU * sizeof (uint64_t);
10679 
10680 			break;
10681 
10682 		case DIFV_SCOPE_GLOBAL:
10683 			np = &vstate->dtvs_nglobals;
10684 			svarp = &vstate->dtvs_globals;
10685 
10686 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10687 				dsize = v->dtdv_type.dtdt_size +
10688 				    sizeof (uint64_t);
10689 
10690 			break;
10691 
10692 		default:
10693 			ASSERT(0);
10694 		}
10695 
10696 		while (id >= (oldsvars = *np)) {
10697 			dtrace_statvar_t **statics;
10698 			int newsvars, oldsize, newsize;
10699 
10700 			if ((newsvars = (oldsvars << 1)) == 0)
10701 				newsvars = 1;
10702 
10703 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10704 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10705 
10706 			statics = kmem_zalloc(newsize, KM_SLEEP);
10707 
10708 			if (oldsize != 0) {
10709 				bcopy(*svarp, statics, oldsize);
10710 				kmem_free(*svarp, oldsize);
10711 			}
10712 
10713 			*svarp = statics;
10714 			*np = newsvars;
10715 		}
10716 
10717 		if ((svar = (*svarp)[id]) == NULL) {
10718 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10719 			svar->dtsv_var = *v;
10720 
10721 			if ((svar->dtsv_size = dsize) != 0) {
10722 				svar->dtsv_data = (uint64_t)(uintptr_t)
10723 				    kmem_zalloc(dsize, KM_SLEEP);
10724 			}
10725 
10726 			(*svarp)[id] = svar;
10727 		}
10728 
10729 		svar->dtsv_refcnt++;
10730 	}
10731 
10732 	dtrace_difo_chunksize(dp, vstate);
10733 	dtrace_difo_hold(dp);
10734 }
10735 
10736 static dtrace_difo_t *
10737 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10738 {
10739 	dtrace_difo_t *new;
10740 	size_t sz;
10741 
10742 	ASSERT(dp->dtdo_buf != NULL);
10743 	ASSERT(dp->dtdo_refcnt != 0);
10744 
10745 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10746 
10747 	ASSERT(dp->dtdo_buf != NULL);
10748 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10749 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10750 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10751 	new->dtdo_len = dp->dtdo_len;
10752 
10753 	if (dp->dtdo_strtab != NULL) {
10754 		ASSERT(dp->dtdo_strlen != 0);
10755 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10756 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10757 		new->dtdo_strlen = dp->dtdo_strlen;
10758 	}
10759 
10760 	if (dp->dtdo_inttab != NULL) {
10761 		ASSERT(dp->dtdo_intlen != 0);
10762 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10763 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10764 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10765 		new->dtdo_intlen = dp->dtdo_intlen;
10766 	}
10767 
10768 	if (dp->dtdo_vartab != NULL) {
10769 		ASSERT(dp->dtdo_varlen != 0);
10770 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10771 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10772 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10773 		new->dtdo_varlen = dp->dtdo_varlen;
10774 	}
10775 
10776 	dtrace_difo_init(new, vstate);
10777 	return (new);
10778 }
10779 
10780 static void
10781 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10782 {
10783 	int i;
10784 
10785 	ASSERT(dp->dtdo_refcnt == 0);
10786 
10787 	for (i = 0; i < dp->dtdo_varlen; i++) {
10788 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10789 		dtrace_statvar_t *svar, **svarp = NULL;
10790 		uint_t id;
10791 		uint8_t scope = v->dtdv_scope;
10792 		int *np = NULL;
10793 
10794 		switch (scope) {
10795 		case DIFV_SCOPE_THREAD:
10796 			continue;
10797 
10798 		case DIFV_SCOPE_LOCAL:
10799 			np = &vstate->dtvs_nlocals;
10800 			svarp = vstate->dtvs_locals;
10801 			break;
10802 
10803 		case DIFV_SCOPE_GLOBAL:
10804 			np = &vstate->dtvs_nglobals;
10805 			svarp = vstate->dtvs_globals;
10806 			break;
10807 
10808 		default:
10809 			ASSERT(0);
10810 		}
10811 
10812 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10813 			continue;
10814 
10815 		id -= DIF_VAR_OTHER_UBASE;
10816 		ASSERT(id < *np);
10817 
10818 		svar = svarp[id];
10819 		ASSERT(svar != NULL);
10820 		ASSERT(svar->dtsv_refcnt > 0);
10821 
10822 		if (--svar->dtsv_refcnt > 0)
10823 			continue;
10824 
10825 		if (svar->dtsv_size != 0) {
10826 			ASSERT(svar->dtsv_data != 0);
10827 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10828 			    svar->dtsv_size);
10829 		}
10830 
10831 		kmem_free(svar, sizeof (dtrace_statvar_t));
10832 		svarp[id] = NULL;
10833 	}
10834 
10835 	if (dp->dtdo_buf != NULL)
10836 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10837 	if (dp->dtdo_inttab != NULL)
10838 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10839 	if (dp->dtdo_strtab != NULL)
10840 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10841 	if (dp->dtdo_vartab != NULL)
10842 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10843 
10844 	kmem_free(dp, sizeof (dtrace_difo_t));
10845 }
10846 
10847 static void
10848 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10849 {
10850 	int i;
10851 
10852 	ASSERT(MUTEX_HELD(&dtrace_lock));
10853 	ASSERT(dp->dtdo_refcnt != 0);
10854 
10855 	for (i = 0; i < dp->dtdo_varlen; i++) {
10856 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10857 
10858 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10859 			continue;
10860 
10861 		ASSERT(dtrace_vtime_references > 0);
10862 		if (--dtrace_vtime_references == 0)
10863 			dtrace_vtime_disable();
10864 	}
10865 
10866 	if (--dp->dtdo_refcnt == 0)
10867 		dtrace_difo_destroy(dp, vstate);
10868 }
10869 
10870 /*
10871  * DTrace Format Functions
10872  */
10873 static uint16_t
10874 dtrace_format_add(dtrace_state_t *state, char *str)
10875 {
10876 	char *fmt, **new;
10877 	uint16_t ndx, len = strlen(str) + 1;
10878 
10879 	fmt = kmem_zalloc(len, KM_SLEEP);
10880 	bcopy(str, fmt, len);
10881 
10882 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10883 		if (state->dts_formats[ndx] == NULL) {
10884 			state->dts_formats[ndx] = fmt;
10885 			return (ndx + 1);
10886 		}
10887 	}
10888 
10889 	if (state->dts_nformats == USHRT_MAX) {
10890 		/*
10891 		 * This is only likely if a denial-of-service attack is being
10892 		 * attempted.  As such, it's okay to fail silently here.
10893 		 */
10894 		kmem_free(fmt, len);
10895 		return (0);
10896 	}
10897 
10898 	/*
10899 	 * For simplicity, we always resize the formats array to be exactly the
10900 	 * number of formats.
10901 	 */
10902 	ndx = state->dts_nformats++;
10903 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10904 
10905 	if (state->dts_formats != NULL) {
10906 		ASSERT(ndx != 0);
10907 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10908 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10909 	}
10910 
10911 	state->dts_formats = new;
10912 	state->dts_formats[ndx] = fmt;
10913 
10914 	return (ndx + 1);
10915 }
10916 
10917 static void
10918 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10919 {
10920 	char *fmt;
10921 
10922 	ASSERT(state->dts_formats != NULL);
10923 	ASSERT(format <= state->dts_nformats);
10924 	ASSERT(state->dts_formats[format - 1] != NULL);
10925 
10926 	fmt = state->dts_formats[format - 1];
10927 	kmem_free(fmt, strlen(fmt) + 1);
10928 	state->dts_formats[format - 1] = NULL;
10929 }
10930 
10931 static void
10932 dtrace_format_destroy(dtrace_state_t *state)
10933 {
10934 	int i;
10935 
10936 	if (state->dts_nformats == 0) {
10937 		ASSERT(state->dts_formats == NULL);
10938 		return;
10939 	}
10940 
10941 	ASSERT(state->dts_formats != NULL);
10942 
10943 	for (i = 0; i < state->dts_nformats; i++) {
10944 		char *fmt = state->dts_formats[i];
10945 
10946 		if (fmt == NULL)
10947 			continue;
10948 
10949 		kmem_free(fmt, strlen(fmt) + 1);
10950 	}
10951 
10952 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10953 	state->dts_nformats = 0;
10954 	state->dts_formats = NULL;
10955 }
10956 
10957 /*
10958  * DTrace Predicate Functions
10959  */
10960 static dtrace_predicate_t *
10961 dtrace_predicate_create(dtrace_difo_t *dp)
10962 {
10963 	dtrace_predicate_t *pred;
10964 
10965 	ASSERT(MUTEX_HELD(&dtrace_lock));
10966 	ASSERT(dp->dtdo_refcnt != 0);
10967 
10968 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10969 	pred->dtp_difo = dp;
10970 	pred->dtp_refcnt = 1;
10971 
10972 	if (!dtrace_difo_cacheable(dp))
10973 		return (pred);
10974 
10975 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10976 		/*
10977 		 * This is only theoretically possible -- we have had 2^32
10978 		 * cacheable predicates on this machine.  We cannot allow any
10979 		 * more predicates to become cacheable:  as unlikely as it is,
10980 		 * there may be a thread caching a (now stale) predicate cache
10981 		 * ID. (N.B.: the temptation is being successfully resisted to
10982 		 * have this cmn_err() "Holy shit -- we executed this code!")
10983 		 */
10984 		return (pred);
10985 	}
10986 
10987 	pred->dtp_cacheid = dtrace_predcache_id++;
10988 
10989 	return (pred);
10990 }
10991 
10992 static void
10993 dtrace_predicate_hold(dtrace_predicate_t *pred)
10994 {
10995 	ASSERT(MUTEX_HELD(&dtrace_lock));
10996 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10997 	ASSERT(pred->dtp_refcnt > 0);
10998 
10999 	pred->dtp_refcnt++;
11000 }
11001 
11002 static void
11003 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
11004 {
11005 	dtrace_difo_t *dp = pred->dtp_difo;
11006 
11007 	ASSERT(MUTEX_HELD(&dtrace_lock));
11008 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11009 	ASSERT(pred->dtp_refcnt > 0);
11010 
11011 	if (--pred->dtp_refcnt == 0) {
11012 		dtrace_difo_release(pred->dtp_difo, vstate);
11013 		kmem_free(pred, sizeof (dtrace_predicate_t));
11014 	}
11015 }
11016 
11017 /*
11018  * DTrace Action Description Functions
11019  */
11020 static dtrace_actdesc_t *
11021 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11022     uint64_t uarg, uint64_t arg)
11023 {
11024 	dtrace_actdesc_t *act;
11025 
11026 #ifdef illumos
11027 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11028 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11029 #endif
11030 
11031 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11032 	act->dtad_kind = kind;
11033 	act->dtad_ntuple = ntuple;
11034 	act->dtad_uarg = uarg;
11035 	act->dtad_arg = arg;
11036 	act->dtad_refcnt = 1;
11037 
11038 	return (act);
11039 }
11040 
11041 static void
11042 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11043 {
11044 	ASSERT(act->dtad_refcnt >= 1);
11045 	act->dtad_refcnt++;
11046 }
11047 
11048 static void
11049 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11050 {
11051 	dtrace_actkind_t kind = act->dtad_kind;
11052 	dtrace_difo_t *dp;
11053 
11054 	ASSERT(act->dtad_refcnt >= 1);
11055 
11056 	if (--act->dtad_refcnt != 0)
11057 		return;
11058 
11059 	if ((dp = act->dtad_difo) != NULL)
11060 		dtrace_difo_release(dp, vstate);
11061 
11062 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11063 		char *str = (char *)(uintptr_t)act->dtad_arg;
11064 
11065 #ifdef illumos
11066 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11067 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11068 #endif
11069 
11070 		if (str != NULL)
11071 			kmem_free(str, strlen(str) + 1);
11072 	}
11073 
11074 	kmem_free(act, sizeof (dtrace_actdesc_t));
11075 }
11076 
11077 /*
11078  * DTrace ECB Functions
11079  */
11080 static dtrace_ecb_t *
11081 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11082 {
11083 	dtrace_ecb_t *ecb;
11084 	dtrace_epid_t epid;
11085 
11086 	ASSERT(MUTEX_HELD(&dtrace_lock));
11087 
11088 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11089 	ecb->dte_predicate = NULL;
11090 	ecb->dte_probe = probe;
11091 
11092 	/*
11093 	 * The default size is the size of the default action: recording
11094 	 * the header.
11095 	 */
11096 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11097 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11098 
11099 	epid = state->dts_epid++;
11100 
11101 	if (epid - 1 >= state->dts_necbs) {
11102 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11103 		int necbs = state->dts_necbs << 1;
11104 
11105 		ASSERT(epid == state->dts_necbs + 1);
11106 
11107 		if (necbs == 0) {
11108 			ASSERT(oecbs == NULL);
11109 			necbs = 1;
11110 		}
11111 
11112 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11113 
11114 		if (oecbs != NULL)
11115 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11116 
11117 		dtrace_membar_producer();
11118 		state->dts_ecbs = ecbs;
11119 
11120 		if (oecbs != NULL) {
11121 			/*
11122 			 * If this state is active, we must dtrace_sync()
11123 			 * before we can free the old dts_ecbs array:  we're
11124 			 * coming in hot, and there may be active ring
11125 			 * buffer processing (which indexes into the dts_ecbs
11126 			 * array) on another CPU.
11127 			 */
11128 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11129 				dtrace_sync();
11130 
11131 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11132 		}
11133 
11134 		dtrace_membar_producer();
11135 		state->dts_necbs = necbs;
11136 	}
11137 
11138 	ecb->dte_state = state;
11139 
11140 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11141 	dtrace_membar_producer();
11142 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11143 
11144 	return (ecb);
11145 }
11146 
11147 static void
11148 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11149 {
11150 	dtrace_probe_t *probe = ecb->dte_probe;
11151 
11152 	ASSERT(MUTEX_HELD(&cpu_lock));
11153 	ASSERT(MUTEX_HELD(&dtrace_lock));
11154 	ASSERT(ecb->dte_next == NULL);
11155 
11156 	if (probe == NULL) {
11157 		/*
11158 		 * This is the NULL probe -- there's nothing to do.
11159 		 */
11160 		return;
11161 	}
11162 
11163 	if (probe->dtpr_ecb == NULL) {
11164 		dtrace_provider_t *prov = probe->dtpr_provider;
11165 
11166 		/*
11167 		 * We're the first ECB on this probe.
11168 		 */
11169 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11170 
11171 		if (ecb->dte_predicate != NULL)
11172 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11173 
11174 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11175 		    probe->dtpr_id, probe->dtpr_arg);
11176 	} else {
11177 		/*
11178 		 * This probe is already active.  Swing the last pointer to
11179 		 * point to the new ECB, and issue a dtrace_sync() to assure
11180 		 * that all CPUs have seen the change.
11181 		 */
11182 		ASSERT(probe->dtpr_ecb_last != NULL);
11183 		probe->dtpr_ecb_last->dte_next = ecb;
11184 		probe->dtpr_ecb_last = ecb;
11185 		probe->dtpr_predcache = 0;
11186 
11187 		dtrace_sync();
11188 	}
11189 }
11190 
11191 static int
11192 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11193 {
11194 	dtrace_action_t *act;
11195 	uint32_t curneeded = UINT32_MAX;
11196 	uint32_t aggbase = UINT32_MAX;
11197 
11198 	/*
11199 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11200 	 * we always record it first.)
11201 	 */
11202 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11203 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11204 
11205 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11206 		dtrace_recdesc_t *rec = &act->dta_rec;
11207 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11208 
11209 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11210 		    rec->dtrd_alignment);
11211 
11212 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11213 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11214 
11215 			ASSERT(rec->dtrd_size != 0);
11216 			ASSERT(agg->dtag_first != NULL);
11217 			ASSERT(act->dta_prev->dta_intuple);
11218 			ASSERT(aggbase != UINT32_MAX);
11219 			ASSERT(curneeded != UINT32_MAX);
11220 
11221 			agg->dtag_base = aggbase;
11222 
11223 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11224 			rec->dtrd_offset = curneeded;
11225 			if (curneeded + rec->dtrd_size < curneeded)
11226 				return (EINVAL);
11227 			curneeded += rec->dtrd_size;
11228 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11229 
11230 			aggbase = UINT32_MAX;
11231 			curneeded = UINT32_MAX;
11232 		} else if (act->dta_intuple) {
11233 			if (curneeded == UINT32_MAX) {
11234 				/*
11235 				 * This is the first record in a tuple.  Align
11236 				 * curneeded to be at offset 4 in an 8-byte
11237 				 * aligned block.
11238 				 */
11239 				ASSERT(act->dta_prev == NULL ||
11240 				    !act->dta_prev->dta_intuple);
11241 				ASSERT3U(aggbase, ==, UINT32_MAX);
11242 				curneeded = P2PHASEUP(ecb->dte_size,
11243 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11244 
11245 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11246 				ASSERT(IS_P2ALIGNED(aggbase,
11247 				    sizeof (uint64_t)));
11248 			}
11249 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11250 			rec->dtrd_offset = curneeded;
11251 			if (curneeded + rec->dtrd_size < curneeded)
11252 				return (EINVAL);
11253 			curneeded += rec->dtrd_size;
11254 		} else {
11255 			/* tuples must be followed by an aggregation */
11256 			ASSERT(act->dta_prev == NULL ||
11257 			    !act->dta_prev->dta_intuple);
11258 
11259 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11260 			    rec->dtrd_alignment);
11261 			rec->dtrd_offset = ecb->dte_size;
11262 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11263 				return (EINVAL);
11264 			ecb->dte_size += rec->dtrd_size;
11265 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11266 		}
11267 	}
11268 
11269 	if ((act = ecb->dte_action) != NULL &&
11270 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11271 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11272 		/*
11273 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11274 		 * actions store no data; set the size to 0.
11275 		 */
11276 		ecb->dte_size = 0;
11277 	}
11278 
11279 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11280 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11281 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11282 	    ecb->dte_needed);
11283 	return (0);
11284 }
11285 
11286 static dtrace_action_t *
11287 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11288 {
11289 	dtrace_aggregation_t *agg;
11290 	size_t size = sizeof (uint64_t);
11291 	int ntuple = desc->dtad_ntuple;
11292 	dtrace_action_t *act;
11293 	dtrace_recdesc_t *frec;
11294 	dtrace_aggid_t aggid;
11295 	dtrace_state_t *state = ecb->dte_state;
11296 
11297 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11298 	agg->dtag_ecb = ecb;
11299 
11300 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11301 
11302 	switch (desc->dtad_kind) {
11303 	case DTRACEAGG_MIN:
11304 		agg->dtag_initial = INT64_MAX;
11305 		agg->dtag_aggregate = dtrace_aggregate_min;
11306 		break;
11307 
11308 	case DTRACEAGG_MAX:
11309 		agg->dtag_initial = INT64_MIN;
11310 		agg->dtag_aggregate = dtrace_aggregate_max;
11311 		break;
11312 
11313 	case DTRACEAGG_COUNT:
11314 		agg->dtag_aggregate = dtrace_aggregate_count;
11315 		break;
11316 
11317 	case DTRACEAGG_QUANTIZE:
11318 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11319 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11320 		    sizeof (uint64_t);
11321 		break;
11322 
11323 	case DTRACEAGG_LQUANTIZE: {
11324 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11325 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11326 
11327 		agg->dtag_initial = desc->dtad_arg;
11328 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11329 
11330 		if (step == 0 || levels == 0)
11331 			goto err;
11332 
11333 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11334 		break;
11335 	}
11336 
11337 	case DTRACEAGG_LLQUANTIZE: {
11338 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11339 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11340 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11341 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11342 		int64_t v;
11343 
11344 		agg->dtag_initial = desc->dtad_arg;
11345 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11346 
11347 		if (factor < 2 || low >= high || nsteps < factor)
11348 			goto err;
11349 
11350 		/*
11351 		 * Now check that the number of steps evenly divides a power
11352 		 * of the factor.  (This assures both integer bucket size and
11353 		 * linearity within each magnitude.)
11354 		 */
11355 		for (v = factor; v < nsteps; v *= factor)
11356 			continue;
11357 
11358 		if ((v % nsteps) || (nsteps % factor))
11359 			goto err;
11360 
11361 		size = (dtrace_aggregate_llquantize_bucket(factor,
11362 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11363 		break;
11364 	}
11365 
11366 	case DTRACEAGG_AVG:
11367 		agg->dtag_aggregate = dtrace_aggregate_avg;
11368 		size = sizeof (uint64_t) * 2;
11369 		break;
11370 
11371 	case DTRACEAGG_STDDEV:
11372 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11373 		size = sizeof (uint64_t) * 4;
11374 		break;
11375 
11376 	case DTRACEAGG_SUM:
11377 		agg->dtag_aggregate = dtrace_aggregate_sum;
11378 		break;
11379 
11380 	default:
11381 		goto err;
11382 	}
11383 
11384 	agg->dtag_action.dta_rec.dtrd_size = size;
11385 
11386 	if (ntuple == 0)
11387 		goto err;
11388 
11389 	/*
11390 	 * We must make sure that we have enough actions for the n-tuple.
11391 	 */
11392 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11393 		if (DTRACEACT_ISAGG(act->dta_kind))
11394 			break;
11395 
11396 		if (--ntuple == 0) {
11397 			/*
11398 			 * This is the action with which our n-tuple begins.
11399 			 */
11400 			agg->dtag_first = act;
11401 			goto success;
11402 		}
11403 	}
11404 
11405 	/*
11406 	 * This n-tuple is short by ntuple elements.  Return failure.
11407 	 */
11408 	ASSERT(ntuple != 0);
11409 err:
11410 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11411 	return (NULL);
11412 
11413 success:
11414 	/*
11415 	 * If the last action in the tuple has a size of zero, it's actually
11416 	 * an expression argument for the aggregating action.
11417 	 */
11418 	ASSERT(ecb->dte_action_last != NULL);
11419 	act = ecb->dte_action_last;
11420 
11421 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11422 		ASSERT(act->dta_difo != NULL);
11423 
11424 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11425 			agg->dtag_hasarg = 1;
11426 	}
11427 
11428 	/*
11429 	 * We need to allocate an id for this aggregation.
11430 	 */
11431 #ifdef illumos
11432 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11433 	    VM_BESTFIT | VM_SLEEP);
11434 #else
11435 	aggid = alloc_unr(state->dts_aggid_arena);
11436 #endif
11437 
11438 	if (aggid - 1 >= state->dts_naggregations) {
11439 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11440 		dtrace_aggregation_t **aggs;
11441 		int naggs = state->dts_naggregations << 1;
11442 		int onaggs = state->dts_naggregations;
11443 
11444 		ASSERT(aggid == state->dts_naggregations + 1);
11445 
11446 		if (naggs == 0) {
11447 			ASSERT(oaggs == NULL);
11448 			naggs = 1;
11449 		}
11450 
11451 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11452 
11453 		if (oaggs != NULL) {
11454 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11455 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11456 		}
11457 
11458 		state->dts_aggregations = aggs;
11459 		state->dts_naggregations = naggs;
11460 	}
11461 
11462 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11463 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11464 
11465 	frec = &agg->dtag_first->dta_rec;
11466 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11467 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11468 
11469 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11470 		ASSERT(!act->dta_intuple);
11471 		act->dta_intuple = 1;
11472 	}
11473 
11474 	return (&agg->dtag_action);
11475 }
11476 
11477 static void
11478 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11479 {
11480 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11481 	dtrace_state_t *state = ecb->dte_state;
11482 	dtrace_aggid_t aggid = agg->dtag_id;
11483 
11484 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11485 #ifdef illumos
11486 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11487 #else
11488 	free_unr(state->dts_aggid_arena, aggid);
11489 #endif
11490 
11491 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11492 	state->dts_aggregations[aggid - 1] = NULL;
11493 
11494 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11495 }
11496 
11497 static int
11498 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11499 {
11500 	dtrace_action_t *action, *last;
11501 	dtrace_difo_t *dp = desc->dtad_difo;
11502 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11503 	uint16_t format = 0;
11504 	dtrace_recdesc_t *rec;
11505 	dtrace_state_t *state = ecb->dte_state;
11506 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11507 	uint64_t arg = desc->dtad_arg;
11508 
11509 	ASSERT(MUTEX_HELD(&dtrace_lock));
11510 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11511 
11512 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11513 		/*
11514 		 * If this is an aggregating action, there must be neither
11515 		 * a speculate nor a commit on the action chain.
11516 		 */
11517 		dtrace_action_t *act;
11518 
11519 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11520 			if (act->dta_kind == DTRACEACT_COMMIT)
11521 				return (EINVAL);
11522 
11523 			if (act->dta_kind == DTRACEACT_SPECULATE)
11524 				return (EINVAL);
11525 		}
11526 
11527 		action = dtrace_ecb_aggregation_create(ecb, desc);
11528 
11529 		if (action == NULL)
11530 			return (EINVAL);
11531 	} else {
11532 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11533 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11534 		    dp != NULL && dp->dtdo_destructive)) {
11535 			state->dts_destructive = 1;
11536 		}
11537 
11538 		switch (desc->dtad_kind) {
11539 		case DTRACEACT_PRINTF:
11540 		case DTRACEACT_PRINTA:
11541 		case DTRACEACT_SYSTEM:
11542 		case DTRACEACT_FREOPEN:
11543 		case DTRACEACT_DIFEXPR:
11544 			/*
11545 			 * We know that our arg is a string -- turn it into a
11546 			 * format.
11547 			 */
11548 			if (arg == 0) {
11549 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11550 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11551 				format = 0;
11552 			} else {
11553 				ASSERT(arg != 0);
11554 #ifdef illumos
11555 				ASSERT(arg > KERNELBASE);
11556 #endif
11557 				format = dtrace_format_add(state,
11558 				    (char *)(uintptr_t)arg);
11559 			}
11560 
11561 			/*FALLTHROUGH*/
11562 		case DTRACEACT_LIBACT:
11563 		case DTRACEACT_TRACEMEM:
11564 		case DTRACEACT_TRACEMEM_DYNSIZE:
11565 			if (dp == NULL)
11566 				return (EINVAL);
11567 
11568 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11569 				break;
11570 
11571 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11572 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11573 					return (EINVAL);
11574 
11575 				size = opt[DTRACEOPT_STRSIZE];
11576 			}
11577 
11578 			break;
11579 
11580 		case DTRACEACT_STACK:
11581 			if ((nframes = arg) == 0) {
11582 				nframes = opt[DTRACEOPT_STACKFRAMES];
11583 				ASSERT(nframes > 0);
11584 				arg = nframes;
11585 			}
11586 
11587 			size = nframes * sizeof (pc_t);
11588 			break;
11589 
11590 		case DTRACEACT_JSTACK:
11591 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11592 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11593 
11594 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11595 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11596 
11597 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11598 
11599 			/*FALLTHROUGH*/
11600 		case DTRACEACT_USTACK:
11601 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11602 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11603 				strsize = DTRACE_USTACK_STRSIZE(arg);
11604 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11605 				ASSERT(nframes > 0);
11606 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11607 			}
11608 
11609 			/*
11610 			 * Save a slot for the pid.
11611 			 */
11612 			size = (nframes + 1) * sizeof (uint64_t);
11613 			size += DTRACE_USTACK_STRSIZE(arg);
11614 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11615 
11616 			break;
11617 
11618 		case DTRACEACT_SYM:
11619 		case DTRACEACT_MOD:
11620 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11621 			    sizeof (uint64_t)) ||
11622 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11623 				return (EINVAL);
11624 			break;
11625 
11626 		case DTRACEACT_USYM:
11627 		case DTRACEACT_UMOD:
11628 		case DTRACEACT_UADDR:
11629 			if (dp == NULL ||
11630 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11631 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11632 				return (EINVAL);
11633 
11634 			/*
11635 			 * We have a slot for the pid, plus a slot for the
11636 			 * argument.  To keep things simple (aligned with
11637 			 * bitness-neutral sizing), we store each as a 64-bit
11638 			 * quantity.
11639 			 */
11640 			size = 2 * sizeof (uint64_t);
11641 			break;
11642 
11643 		case DTRACEACT_STOP:
11644 		case DTRACEACT_BREAKPOINT:
11645 		case DTRACEACT_PANIC:
11646 			break;
11647 
11648 		case DTRACEACT_CHILL:
11649 		case DTRACEACT_DISCARD:
11650 		case DTRACEACT_RAISE:
11651 			if (dp == NULL)
11652 				return (EINVAL);
11653 			break;
11654 
11655 		case DTRACEACT_EXIT:
11656 			if (dp == NULL ||
11657 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11658 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11659 				return (EINVAL);
11660 			break;
11661 
11662 		case DTRACEACT_SPECULATE:
11663 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11664 				return (EINVAL);
11665 
11666 			if (dp == NULL)
11667 				return (EINVAL);
11668 
11669 			state->dts_speculates = 1;
11670 			break;
11671 
11672 		case DTRACEACT_PRINTM:
11673 		    	size = dp->dtdo_rtype.dtdt_size;
11674 			break;
11675 
11676 		case DTRACEACT_COMMIT: {
11677 			dtrace_action_t *act = ecb->dte_action;
11678 
11679 			for (; act != NULL; act = act->dta_next) {
11680 				if (act->dta_kind == DTRACEACT_COMMIT)
11681 					return (EINVAL);
11682 			}
11683 
11684 			if (dp == NULL)
11685 				return (EINVAL);
11686 			break;
11687 		}
11688 
11689 		default:
11690 			return (EINVAL);
11691 		}
11692 
11693 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11694 			/*
11695 			 * If this is a data-storing action or a speculate,
11696 			 * we must be sure that there isn't a commit on the
11697 			 * action chain.
11698 			 */
11699 			dtrace_action_t *act = ecb->dte_action;
11700 
11701 			for (; act != NULL; act = act->dta_next) {
11702 				if (act->dta_kind == DTRACEACT_COMMIT)
11703 					return (EINVAL);
11704 			}
11705 		}
11706 
11707 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11708 		action->dta_rec.dtrd_size = size;
11709 	}
11710 
11711 	action->dta_refcnt = 1;
11712 	rec = &action->dta_rec;
11713 	size = rec->dtrd_size;
11714 
11715 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11716 		if (!(size & mask)) {
11717 			align = mask + 1;
11718 			break;
11719 		}
11720 	}
11721 
11722 	action->dta_kind = desc->dtad_kind;
11723 
11724 	if ((action->dta_difo = dp) != NULL)
11725 		dtrace_difo_hold(dp);
11726 
11727 	rec->dtrd_action = action->dta_kind;
11728 	rec->dtrd_arg = arg;
11729 	rec->dtrd_uarg = desc->dtad_uarg;
11730 	rec->dtrd_alignment = (uint16_t)align;
11731 	rec->dtrd_format = format;
11732 
11733 	if ((last = ecb->dte_action_last) != NULL) {
11734 		ASSERT(ecb->dte_action != NULL);
11735 		action->dta_prev = last;
11736 		last->dta_next = action;
11737 	} else {
11738 		ASSERT(ecb->dte_action == NULL);
11739 		ecb->dte_action = action;
11740 	}
11741 
11742 	ecb->dte_action_last = action;
11743 
11744 	return (0);
11745 }
11746 
11747 static void
11748 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11749 {
11750 	dtrace_action_t *act = ecb->dte_action, *next;
11751 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11752 	dtrace_difo_t *dp;
11753 	uint16_t format;
11754 
11755 	if (act != NULL && act->dta_refcnt > 1) {
11756 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11757 		act->dta_refcnt--;
11758 	} else {
11759 		for (; act != NULL; act = next) {
11760 			next = act->dta_next;
11761 			ASSERT(next != NULL || act == ecb->dte_action_last);
11762 			ASSERT(act->dta_refcnt == 1);
11763 
11764 			if ((format = act->dta_rec.dtrd_format) != 0)
11765 				dtrace_format_remove(ecb->dte_state, format);
11766 
11767 			if ((dp = act->dta_difo) != NULL)
11768 				dtrace_difo_release(dp, vstate);
11769 
11770 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11771 				dtrace_ecb_aggregation_destroy(ecb, act);
11772 			} else {
11773 				kmem_free(act, sizeof (dtrace_action_t));
11774 			}
11775 		}
11776 	}
11777 
11778 	ecb->dte_action = NULL;
11779 	ecb->dte_action_last = NULL;
11780 	ecb->dte_size = 0;
11781 }
11782 
11783 static void
11784 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11785 {
11786 	/*
11787 	 * We disable the ECB by removing it from its probe.
11788 	 */
11789 	dtrace_ecb_t *pecb, *prev = NULL;
11790 	dtrace_probe_t *probe = ecb->dte_probe;
11791 
11792 	ASSERT(MUTEX_HELD(&dtrace_lock));
11793 
11794 	if (probe == NULL) {
11795 		/*
11796 		 * This is the NULL probe; there is nothing to disable.
11797 		 */
11798 		return;
11799 	}
11800 
11801 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11802 		if (pecb == ecb)
11803 			break;
11804 		prev = pecb;
11805 	}
11806 
11807 	ASSERT(pecb != NULL);
11808 
11809 	if (prev == NULL) {
11810 		probe->dtpr_ecb = ecb->dte_next;
11811 	} else {
11812 		prev->dte_next = ecb->dte_next;
11813 	}
11814 
11815 	if (ecb == probe->dtpr_ecb_last) {
11816 		ASSERT(ecb->dte_next == NULL);
11817 		probe->dtpr_ecb_last = prev;
11818 	}
11819 
11820 	/*
11821 	 * The ECB has been disconnected from the probe; now sync to assure
11822 	 * that all CPUs have seen the change before returning.
11823 	 */
11824 	dtrace_sync();
11825 
11826 	if (probe->dtpr_ecb == NULL) {
11827 		/*
11828 		 * That was the last ECB on the probe; clear the predicate
11829 		 * cache ID for the probe, disable it and sync one more time
11830 		 * to assure that we'll never hit it again.
11831 		 */
11832 		dtrace_provider_t *prov = probe->dtpr_provider;
11833 
11834 		ASSERT(ecb->dte_next == NULL);
11835 		ASSERT(probe->dtpr_ecb_last == NULL);
11836 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11837 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11838 		    probe->dtpr_id, probe->dtpr_arg);
11839 		dtrace_sync();
11840 	} else {
11841 		/*
11842 		 * There is at least one ECB remaining on the probe.  If there
11843 		 * is _exactly_ one, set the probe's predicate cache ID to be
11844 		 * the predicate cache ID of the remaining ECB.
11845 		 */
11846 		ASSERT(probe->dtpr_ecb_last != NULL);
11847 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11848 
11849 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11850 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11851 
11852 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11853 
11854 			if (p != NULL)
11855 				probe->dtpr_predcache = p->dtp_cacheid;
11856 		}
11857 
11858 		ecb->dte_next = NULL;
11859 	}
11860 }
11861 
11862 static void
11863 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11864 {
11865 	dtrace_state_t *state = ecb->dte_state;
11866 	dtrace_vstate_t *vstate = &state->dts_vstate;
11867 	dtrace_predicate_t *pred;
11868 	dtrace_epid_t epid = ecb->dte_epid;
11869 
11870 	ASSERT(MUTEX_HELD(&dtrace_lock));
11871 	ASSERT(ecb->dte_next == NULL);
11872 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11873 
11874 	if ((pred = ecb->dte_predicate) != NULL)
11875 		dtrace_predicate_release(pred, vstate);
11876 
11877 	dtrace_ecb_action_remove(ecb);
11878 
11879 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11880 	state->dts_ecbs[epid - 1] = NULL;
11881 
11882 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11883 }
11884 
11885 static dtrace_ecb_t *
11886 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11887     dtrace_enabling_t *enab)
11888 {
11889 	dtrace_ecb_t *ecb;
11890 	dtrace_predicate_t *pred;
11891 	dtrace_actdesc_t *act;
11892 	dtrace_provider_t *prov;
11893 	dtrace_ecbdesc_t *desc = enab->dten_current;
11894 
11895 	ASSERT(MUTEX_HELD(&dtrace_lock));
11896 	ASSERT(state != NULL);
11897 
11898 	ecb = dtrace_ecb_add(state, probe);
11899 	ecb->dte_uarg = desc->dted_uarg;
11900 
11901 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11902 		dtrace_predicate_hold(pred);
11903 		ecb->dte_predicate = pred;
11904 	}
11905 
11906 	if (probe != NULL) {
11907 		/*
11908 		 * If the provider shows more leg than the consumer is old
11909 		 * enough to see, we need to enable the appropriate implicit
11910 		 * predicate bits to prevent the ecb from activating at
11911 		 * revealing times.
11912 		 *
11913 		 * Providers specifying DTRACE_PRIV_USER at register time
11914 		 * are stating that they need the /proc-style privilege
11915 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11916 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11917 		 */
11918 		prov = probe->dtpr_provider;
11919 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11920 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11921 			ecb->dte_cond |= DTRACE_COND_OWNER;
11922 
11923 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11924 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11925 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11926 
11927 		/*
11928 		 * If the provider shows us kernel innards and the user
11929 		 * is lacking sufficient privilege, enable the
11930 		 * DTRACE_COND_USERMODE implicit predicate.
11931 		 */
11932 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11933 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11934 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11935 	}
11936 
11937 	if (dtrace_ecb_create_cache != NULL) {
11938 		/*
11939 		 * If we have a cached ecb, we'll use its action list instead
11940 		 * of creating our own (saving both time and space).
11941 		 */
11942 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11943 		dtrace_action_t *act = cached->dte_action;
11944 
11945 		if (act != NULL) {
11946 			ASSERT(act->dta_refcnt > 0);
11947 			act->dta_refcnt++;
11948 			ecb->dte_action = act;
11949 			ecb->dte_action_last = cached->dte_action_last;
11950 			ecb->dte_needed = cached->dte_needed;
11951 			ecb->dte_size = cached->dte_size;
11952 			ecb->dte_alignment = cached->dte_alignment;
11953 		}
11954 
11955 		return (ecb);
11956 	}
11957 
11958 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11959 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11960 			dtrace_ecb_destroy(ecb);
11961 			return (NULL);
11962 		}
11963 	}
11964 
11965 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11966 		dtrace_ecb_destroy(ecb);
11967 		return (NULL);
11968 	}
11969 
11970 	return (dtrace_ecb_create_cache = ecb);
11971 }
11972 
11973 static int
11974 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11975 {
11976 	dtrace_ecb_t *ecb;
11977 	dtrace_enabling_t *enab = arg;
11978 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11979 
11980 	ASSERT(state != NULL);
11981 
11982 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11983 		/*
11984 		 * This probe was created in a generation for which this
11985 		 * enabling has previously created ECBs; we don't want to
11986 		 * enable it again, so just kick out.
11987 		 */
11988 		return (DTRACE_MATCH_NEXT);
11989 	}
11990 
11991 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11992 		return (DTRACE_MATCH_DONE);
11993 
11994 	dtrace_ecb_enable(ecb);
11995 	return (DTRACE_MATCH_NEXT);
11996 }
11997 
11998 static dtrace_ecb_t *
11999 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
12000 {
12001 	dtrace_ecb_t *ecb;
12002 
12003 	ASSERT(MUTEX_HELD(&dtrace_lock));
12004 
12005 	if (id == 0 || id > state->dts_necbs)
12006 		return (NULL);
12007 
12008 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12009 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12010 
12011 	return (state->dts_ecbs[id - 1]);
12012 }
12013 
12014 static dtrace_aggregation_t *
12015 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12016 {
12017 	dtrace_aggregation_t *agg;
12018 
12019 	ASSERT(MUTEX_HELD(&dtrace_lock));
12020 
12021 	if (id == 0 || id > state->dts_naggregations)
12022 		return (NULL);
12023 
12024 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12025 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12026 	    agg->dtag_id == id);
12027 
12028 	return (state->dts_aggregations[id - 1]);
12029 }
12030 
12031 /*
12032  * DTrace Buffer Functions
12033  *
12034  * The following functions manipulate DTrace buffers.  Most of these functions
12035  * are called in the context of establishing or processing consumer state;
12036  * exceptions are explicitly noted.
12037  */
12038 
12039 /*
12040  * Note:  called from cross call context.  This function switches the two
12041  * buffers on a given CPU.  The atomicity of this operation is assured by
12042  * disabling interrupts while the actual switch takes place; the disabling of
12043  * interrupts serializes the execution with any execution of dtrace_probe() on
12044  * the same CPU.
12045  */
12046 static void
12047 dtrace_buffer_switch(dtrace_buffer_t *buf)
12048 {
12049 	caddr_t tomax = buf->dtb_tomax;
12050 	caddr_t xamot = buf->dtb_xamot;
12051 	dtrace_icookie_t cookie;
12052 	hrtime_t now;
12053 
12054 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12055 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12056 
12057 	cookie = dtrace_interrupt_disable();
12058 	now = dtrace_gethrtime();
12059 	buf->dtb_tomax = xamot;
12060 	buf->dtb_xamot = tomax;
12061 	buf->dtb_xamot_drops = buf->dtb_drops;
12062 	buf->dtb_xamot_offset = buf->dtb_offset;
12063 	buf->dtb_xamot_errors = buf->dtb_errors;
12064 	buf->dtb_xamot_flags = buf->dtb_flags;
12065 	buf->dtb_offset = 0;
12066 	buf->dtb_drops = 0;
12067 	buf->dtb_errors = 0;
12068 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12069 	buf->dtb_interval = now - buf->dtb_switched;
12070 	buf->dtb_switched = now;
12071 	dtrace_interrupt_enable(cookie);
12072 }
12073 
12074 /*
12075  * Note:  called from cross call context.  This function activates a buffer
12076  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12077  * is guaranteed by the disabling of interrupts.
12078  */
12079 static void
12080 dtrace_buffer_activate(dtrace_state_t *state)
12081 {
12082 	dtrace_buffer_t *buf;
12083 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12084 
12085 	buf = &state->dts_buffer[curcpu];
12086 
12087 	if (buf->dtb_tomax != NULL) {
12088 		/*
12089 		 * We might like to assert that the buffer is marked inactive,
12090 		 * but this isn't necessarily true:  the buffer for the CPU
12091 		 * that processes the BEGIN probe has its buffer activated
12092 		 * manually.  In this case, we take the (harmless) action
12093 		 * re-clearing the bit INACTIVE bit.
12094 		 */
12095 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12096 	}
12097 
12098 	dtrace_interrupt_enable(cookie);
12099 }
12100 
12101 #ifdef __FreeBSD__
12102 /*
12103  * Activate the specified per-CPU buffer.  This is used instead of
12104  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12105  * activating anonymous state.
12106  */
12107 static void
12108 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12109 {
12110 
12111 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12112 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12113 }
12114 #endif
12115 
12116 static int
12117 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12118     processorid_t cpu, int *factor)
12119 {
12120 #ifdef illumos
12121 	cpu_t *cp;
12122 #endif
12123 	dtrace_buffer_t *buf;
12124 	int allocated = 0, desired = 0;
12125 
12126 #ifdef illumos
12127 	ASSERT(MUTEX_HELD(&cpu_lock));
12128 	ASSERT(MUTEX_HELD(&dtrace_lock));
12129 
12130 	*factor = 1;
12131 
12132 	if (size > dtrace_nonroot_maxsize &&
12133 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12134 		return (EFBIG);
12135 
12136 	cp = cpu_list;
12137 
12138 	do {
12139 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12140 			continue;
12141 
12142 		buf = &bufs[cp->cpu_id];
12143 
12144 		/*
12145 		 * If there is already a buffer allocated for this CPU, it
12146 		 * is only possible that this is a DR event.  In this case,
12147 		 */
12148 		if (buf->dtb_tomax != NULL) {
12149 			ASSERT(buf->dtb_size == size);
12150 			continue;
12151 		}
12152 
12153 		ASSERT(buf->dtb_xamot == NULL);
12154 
12155 		if ((buf->dtb_tomax = kmem_zalloc(size,
12156 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12157 			goto err;
12158 
12159 		buf->dtb_size = size;
12160 		buf->dtb_flags = flags;
12161 		buf->dtb_offset = 0;
12162 		buf->dtb_drops = 0;
12163 
12164 		if (flags & DTRACEBUF_NOSWITCH)
12165 			continue;
12166 
12167 		if ((buf->dtb_xamot = kmem_zalloc(size,
12168 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12169 			goto err;
12170 	} while ((cp = cp->cpu_next) != cpu_list);
12171 
12172 	return (0);
12173 
12174 err:
12175 	cp = cpu_list;
12176 
12177 	do {
12178 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12179 			continue;
12180 
12181 		buf = &bufs[cp->cpu_id];
12182 		desired += 2;
12183 
12184 		if (buf->dtb_xamot != NULL) {
12185 			ASSERT(buf->dtb_tomax != NULL);
12186 			ASSERT(buf->dtb_size == size);
12187 			kmem_free(buf->dtb_xamot, size);
12188 			allocated++;
12189 		}
12190 
12191 		if (buf->dtb_tomax != NULL) {
12192 			ASSERT(buf->dtb_size == size);
12193 			kmem_free(buf->dtb_tomax, size);
12194 			allocated++;
12195 		}
12196 
12197 		buf->dtb_tomax = NULL;
12198 		buf->dtb_xamot = NULL;
12199 		buf->dtb_size = 0;
12200 	} while ((cp = cp->cpu_next) != cpu_list);
12201 #else
12202 	int i;
12203 
12204 	*factor = 1;
12205 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12206     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12207 	/*
12208 	 * FreeBSD isn't good at limiting the amount of memory we
12209 	 * ask to malloc, so let's place a limit here before trying
12210 	 * to do something that might well end in tears at bedtime.
12211 	 */
12212 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12213 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12214 		return (ENOMEM);
12215 #endif
12216 
12217 	ASSERT(MUTEX_HELD(&dtrace_lock));
12218 	CPU_FOREACH(i) {
12219 		if (cpu != DTRACE_CPUALL && cpu != i)
12220 			continue;
12221 
12222 		buf = &bufs[i];
12223 
12224 		/*
12225 		 * If there is already a buffer allocated for this CPU, it
12226 		 * is only possible that this is a DR event.  In this case,
12227 		 * the buffer size must match our specified size.
12228 		 */
12229 		if (buf->dtb_tomax != NULL) {
12230 			ASSERT(buf->dtb_size == size);
12231 			continue;
12232 		}
12233 
12234 		ASSERT(buf->dtb_xamot == NULL);
12235 
12236 		if ((buf->dtb_tomax = kmem_zalloc(size,
12237 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12238 			goto err;
12239 
12240 		buf->dtb_size = size;
12241 		buf->dtb_flags = flags;
12242 		buf->dtb_offset = 0;
12243 		buf->dtb_drops = 0;
12244 
12245 		if (flags & DTRACEBUF_NOSWITCH)
12246 			continue;
12247 
12248 		if ((buf->dtb_xamot = kmem_zalloc(size,
12249 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12250 			goto err;
12251 	}
12252 
12253 	return (0);
12254 
12255 err:
12256 	/*
12257 	 * Error allocating memory, so free the buffers that were
12258 	 * allocated before the failed allocation.
12259 	 */
12260 	CPU_FOREACH(i) {
12261 		if (cpu != DTRACE_CPUALL && cpu != i)
12262 			continue;
12263 
12264 		buf = &bufs[i];
12265 		desired += 2;
12266 
12267 		if (buf->dtb_xamot != NULL) {
12268 			ASSERT(buf->dtb_tomax != NULL);
12269 			ASSERT(buf->dtb_size == size);
12270 			kmem_free(buf->dtb_xamot, size);
12271 			allocated++;
12272 		}
12273 
12274 		if (buf->dtb_tomax != NULL) {
12275 			ASSERT(buf->dtb_size == size);
12276 			kmem_free(buf->dtb_tomax, size);
12277 			allocated++;
12278 		}
12279 
12280 		buf->dtb_tomax = NULL;
12281 		buf->dtb_xamot = NULL;
12282 		buf->dtb_size = 0;
12283 
12284 	}
12285 #endif
12286 	*factor = desired / (allocated > 0 ? allocated : 1);
12287 
12288 	return (ENOMEM);
12289 }
12290 
12291 /*
12292  * Note:  called from probe context.  This function just increments the drop
12293  * count on a buffer.  It has been made a function to allow for the
12294  * possibility of understanding the source of mysterious drop counts.  (A
12295  * problem for which one may be particularly disappointed that DTrace cannot
12296  * be used to understand DTrace.)
12297  */
12298 static void
12299 dtrace_buffer_drop(dtrace_buffer_t *buf)
12300 {
12301 	buf->dtb_drops++;
12302 }
12303 
12304 /*
12305  * Note:  called from probe context.  This function is called to reserve space
12306  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12307  * mstate.  Returns the new offset in the buffer, or a negative value if an
12308  * error has occurred.
12309  */
12310 static intptr_t
12311 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12312     dtrace_state_t *state, dtrace_mstate_t *mstate)
12313 {
12314 	intptr_t offs = buf->dtb_offset, soffs;
12315 	intptr_t woffs;
12316 	caddr_t tomax;
12317 	size_t total;
12318 
12319 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12320 		return (-1);
12321 
12322 	if ((tomax = buf->dtb_tomax) == NULL) {
12323 		dtrace_buffer_drop(buf);
12324 		return (-1);
12325 	}
12326 
12327 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12328 		while (offs & (align - 1)) {
12329 			/*
12330 			 * Assert that our alignment is off by a number which
12331 			 * is itself sizeof (uint32_t) aligned.
12332 			 */
12333 			ASSERT(!((align - (offs & (align - 1))) &
12334 			    (sizeof (uint32_t) - 1)));
12335 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12336 			offs += sizeof (uint32_t);
12337 		}
12338 
12339 		if ((soffs = offs + needed) > buf->dtb_size) {
12340 			dtrace_buffer_drop(buf);
12341 			return (-1);
12342 		}
12343 
12344 		if (mstate == NULL)
12345 			return (offs);
12346 
12347 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12348 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12349 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12350 
12351 		return (offs);
12352 	}
12353 
12354 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12355 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12356 		    (buf->dtb_flags & DTRACEBUF_FULL))
12357 			return (-1);
12358 		goto out;
12359 	}
12360 
12361 	total = needed + (offs & (align - 1));
12362 
12363 	/*
12364 	 * For a ring buffer, life is quite a bit more complicated.  Before
12365 	 * we can store any padding, we need to adjust our wrapping offset.
12366 	 * (If we've never before wrapped or we're not about to, no adjustment
12367 	 * is required.)
12368 	 */
12369 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12370 	    offs + total > buf->dtb_size) {
12371 		woffs = buf->dtb_xamot_offset;
12372 
12373 		if (offs + total > buf->dtb_size) {
12374 			/*
12375 			 * We can't fit in the end of the buffer.  First, a
12376 			 * sanity check that we can fit in the buffer at all.
12377 			 */
12378 			if (total > buf->dtb_size) {
12379 				dtrace_buffer_drop(buf);
12380 				return (-1);
12381 			}
12382 
12383 			/*
12384 			 * We're going to be storing at the top of the buffer,
12385 			 * so now we need to deal with the wrapped offset.  We
12386 			 * only reset our wrapped offset to 0 if it is
12387 			 * currently greater than the current offset.  If it
12388 			 * is less than the current offset, it is because a
12389 			 * previous allocation induced a wrap -- but the
12390 			 * allocation didn't subsequently take the space due
12391 			 * to an error or false predicate evaluation.  In this
12392 			 * case, we'll just leave the wrapped offset alone: if
12393 			 * the wrapped offset hasn't been advanced far enough
12394 			 * for this allocation, it will be adjusted in the
12395 			 * lower loop.
12396 			 */
12397 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12398 				if (woffs >= offs)
12399 					woffs = 0;
12400 			} else {
12401 				woffs = 0;
12402 			}
12403 
12404 			/*
12405 			 * Now we know that we're going to be storing to the
12406 			 * top of the buffer and that there is room for us
12407 			 * there.  We need to clear the buffer from the current
12408 			 * offset to the end (there may be old gunk there).
12409 			 */
12410 			while (offs < buf->dtb_size)
12411 				tomax[offs++] = 0;
12412 
12413 			/*
12414 			 * We need to set our offset to zero.  And because we
12415 			 * are wrapping, we need to set the bit indicating as
12416 			 * much.  We can also adjust our needed space back
12417 			 * down to the space required by the ECB -- we know
12418 			 * that the top of the buffer is aligned.
12419 			 */
12420 			offs = 0;
12421 			total = needed;
12422 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12423 		} else {
12424 			/*
12425 			 * There is room for us in the buffer, so we simply
12426 			 * need to check the wrapped offset.
12427 			 */
12428 			if (woffs < offs) {
12429 				/*
12430 				 * The wrapped offset is less than the offset.
12431 				 * This can happen if we allocated buffer space
12432 				 * that induced a wrap, but then we didn't
12433 				 * subsequently take the space due to an error
12434 				 * or false predicate evaluation.  This is
12435 				 * okay; we know that _this_ allocation isn't
12436 				 * going to induce a wrap.  We still can't
12437 				 * reset the wrapped offset to be zero,
12438 				 * however: the space may have been trashed in
12439 				 * the previous failed probe attempt.  But at
12440 				 * least the wrapped offset doesn't need to
12441 				 * be adjusted at all...
12442 				 */
12443 				goto out;
12444 			}
12445 		}
12446 
12447 		while (offs + total > woffs) {
12448 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12449 			size_t size;
12450 
12451 			if (epid == DTRACE_EPIDNONE) {
12452 				size = sizeof (uint32_t);
12453 			} else {
12454 				ASSERT3U(epid, <=, state->dts_necbs);
12455 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12456 
12457 				size = state->dts_ecbs[epid - 1]->dte_size;
12458 			}
12459 
12460 			ASSERT(woffs + size <= buf->dtb_size);
12461 			ASSERT(size != 0);
12462 
12463 			if (woffs + size == buf->dtb_size) {
12464 				/*
12465 				 * We've reached the end of the buffer; we want
12466 				 * to set the wrapped offset to 0 and break
12467 				 * out.  However, if the offs is 0, then we're
12468 				 * in a strange edge-condition:  the amount of
12469 				 * space that we want to reserve plus the size
12470 				 * of the record that we're overwriting is
12471 				 * greater than the size of the buffer.  This
12472 				 * is problematic because if we reserve the
12473 				 * space but subsequently don't consume it (due
12474 				 * to a failed predicate or error) the wrapped
12475 				 * offset will be 0 -- yet the EPID at offset 0
12476 				 * will not be committed.  This situation is
12477 				 * relatively easy to deal with:  if we're in
12478 				 * this case, the buffer is indistinguishable
12479 				 * from one that hasn't wrapped; we need only
12480 				 * finish the job by clearing the wrapped bit,
12481 				 * explicitly setting the offset to be 0, and
12482 				 * zero'ing out the old data in the buffer.
12483 				 */
12484 				if (offs == 0) {
12485 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12486 					buf->dtb_offset = 0;
12487 					woffs = total;
12488 
12489 					while (woffs < buf->dtb_size)
12490 						tomax[woffs++] = 0;
12491 				}
12492 
12493 				woffs = 0;
12494 				break;
12495 			}
12496 
12497 			woffs += size;
12498 		}
12499 
12500 		/*
12501 		 * We have a wrapped offset.  It may be that the wrapped offset
12502 		 * has become zero -- that's okay.
12503 		 */
12504 		buf->dtb_xamot_offset = woffs;
12505 	}
12506 
12507 out:
12508 	/*
12509 	 * Now we can plow the buffer with any necessary padding.
12510 	 */
12511 	while (offs & (align - 1)) {
12512 		/*
12513 		 * Assert that our alignment is off by a number which
12514 		 * is itself sizeof (uint32_t) aligned.
12515 		 */
12516 		ASSERT(!((align - (offs & (align - 1))) &
12517 		    (sizeof (uint32_t) - 1)));
12518 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12519 		offs += sizeof (uint32_t);
12520 	}
12521 
12522 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12523 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12524 			buf->dtb_flags |= DTRACEBUF_FULL;
12525 			return (-1);
12526 		}
12527 	}
12528 
12529 	if (mstate == NULL)
12530 		return (offs);
12531 
12532 	/*
12533 	 * For ring buffers and fill buffers, the scratch space is always
12534 	 * the inactive buffer.
12535 	 */
12536 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12537 	mstate->dtms_scratch_size = buf->dtb_size;
12538 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12539 
12540 	return (offs);
12541 }
12542 
12543 static void
12544 dtrace_buffer_polish(dtrace_buffer_t *buf)
12545 {
12546 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12547 	ASSERT(MUTEX_HELD(&dtrace_lock));
12548 
12549 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12550 		return;
12551 
12552 	/*
12553 	 * We need to polish the ring buffer.  There are three cases:
12554 	 *
12555 	 * - The first (and presumably most common) is that there is no gap
12556 	 *   between the buffer offset and the wrapped offset.  In this case,
12557 	 *   there is nothing in the buffer that isn't valid data; we can
12558 	 *   mark the buffer as polished and return.
12559 	 *
12560 	 * - The second (less common than the first but still more common
12561 	 *   than the third) is that there is a gap between the buffer offset
12562 	 *   and the wrapped offset, and the wrapped offset is larger than the
12563 	 *   buffer offset.  This can happen because of an alignment issue, or
12564 	 *   can happen because of a call to dtrace_buffer_reserve() that
12565 	 *   didn't subsequently consume the buffer space.  In this case,
12566 	 *   we need to zero the data from the buffer offset to the wrapped
12567 	 *   offset.
12568 	 *
12569 	 * - The third (and least common) is that there is a gap between the
12570 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12571 	 *   _less_ than the buffer offset.  This can only happen because a
12572 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12573 	 *   was not subsequently consumed.  In this case, we need to zero the
12574 	 *   space from the offset to the end of the buffer _and_ from the
12575 	 *   top of the buffer to the wrapped offset.
12576 	 */
12577 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12578 		bzero(buf->dtb_tomax + buf->dtb_offset,
12579 		    buf->dtb_xamot_offset - buf->dtb_offset);
12580 	}
12581 
12582 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12583 		bzero(buf->dtb_tomax + buf->dtb_offset,
12584 		    buf->dtb_size - buf->dtb_offset);
12585 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12586 	}
12587 }
12588 
12589 /*
12590  * This routine determines if data generated at the specified time has likely
12591  * been entirely consumed at user-level.  This routine is called to determine
12592  * if an ECB on a defunct probe (but for an active enabling) can be safely
12593  * disabled and destroyed.
12594  */
12595 static int
12596 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12597 {
12598 	int i;
12599 
12600 	for (i = 0; i < NCPU; i++) {
12601 		dtrace_buffer_t *buf = &bufs[i];
12602 
12603 		if (buf->dtb_size == 0)
12604 			continue;
12605 
12606 		if (buf->dtb_flags & DTRACEBUF_RING)
12607 			return (0);
12608 
12609 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12610 			return (0);
12611 
12612 		if (buf->dtb_switched - buf->dtb_interval < when)
12613 			return (0);
12614 	}
12615 
12616 	return (1);
12617 }
12618 
12619 static void
12620 dtrace_buffer_free(dtrace_buffer_t *bufs)
12621 {
12622 	int i;
12623 
12624 	for (i = 0; i < NCPU; i++) {
12625 		dtrace_buffer_t *buf = &bufs[i];
12626 
12627 		if (buf->dtb_tomax == NULL) {
12628 			ASSERT(buf->dtb_xamot == NULL);
12629 			ASSERT(buf->dtb_size == 0);
12630 			continue;
12631 		}
12632 
12633 		if (buf->dtb_xamot != NULL) {
12634 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12635 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12636 		}
12637 
12638 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12639 		buf->dtb_size = 0;
12640 		buf->dtb_tomax = NULL;
12641 		buf->dtb_xamot = NULL;
12642 	}
12643 }
12644 
12645 /*
12646  * DTrace Enabling Functions
12647  */
12648 static dtrace_enabling_t *
12649 dtrace_enabling_create(dtrace_vstate_t *vstate)
12650 {
12651 	dtrace_enabling_t *enab;
12652 
12653 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12654 	enab->dten_vstate = vstate;
12655 
12656 	return (enab);
12657 }
12658 
12659 static void
12660 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12661 {
12662 	dtrace_ecbdesc_t **ndesc;
12663 	size_t osize, nsize;
12664 
12665 	/*
12666 	 * We can't add to enablings after we've enabled them, or after we've
12667 	 * retained them.
12668 	 */
12669 	ASSERT(enab->dten_probegen == 0);
12670 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12671 
12672 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12673 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12674 		return;
12675 	}
12676 
12677 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12678 
12679 	if (enab->dten_maxdesc == 0) {
12680 		enab->dten_maxdesc = 1;
12681 	} else {
12682 		enab->dten_maxdesc <<= 1;
12683 	}
12684 
12685 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12686 
12687 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12688 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12689 	bcopy(enab->dten_desc, ndesc, osize);
12690 	if (enab->dten_desc != NULL)
12691 		kmem_free(enab->dten_desc, osize);
12692 
12693 	enab->dten_desc = ndesc;
12694 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12695 }
12696 
12697 static void
12698 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12699     dtrace_probedesc_t *pd)
12700 {
12701 	dtrace_ecbdesc_t *new;
12702 	dtrace_predicate_t *pred;
12703 	dtrace_actdesc_t *act;
12704 
12705 	/*
12706 	 * We're going to create a new ECB description that matches the
12707 	 * specified ECB in every way, but has the specified probe description.
12708 	 */
12709 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12710 
12711 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12712 		dtrace_predicate_hold(pred);
12713 
12714 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12715 		dtrace_actdesc_hold(act);
12716 
12717 	new->dted_action = ecb->dted_action;
12718 	new->dted_pred = ecb->dted_pred;
12719 	new->dted_probe = *pd;
12720 	new->dted_uarg = ecb->dted_uarg;
12721 
12722 	dtrace_enabling_add(enab, new);
12723 }
12724 
12725 static void
12726 dtrace_enabling_dump(dtrace_enabling_t *enab)
12727 {
12728 	int i;
12729 
12730 	for (i = 0; i < enab->dten_ndesc; i++) {
12731 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12732 
12733 #ifdef __FreeBSD__
12734 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12735 		    desc->dtpd_provider, desc->dtpd_mod,
12736 		    desc->dtpd_func, desc->dtpd_name);
12737 #else
12738 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12739 		    desc->dtpd_provider, desc->dtpd_mod,
12740 		    desc->dtpd_func, desc->dtpd_name);
12741 #endif
12742 	}
12743 }
12744 
12745 static void
12746 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12747 {
12748 	int i;
12749 	dtrace_ecbdesc_t *ep;
12750 	dtrace_vstate_t *vstate = enab->dten_vstate;
12751 
12752 	ASSERT(MUTEX_HELD(&dtrace_lock));
12753 
12754 	for (i = 0; i < enab->dten_ndesc; i++) {
12755 		dtrace_actdesc_t *act, *next;
12756 		dtrace_predicate_t *pred;
12757 
12758 		ep = enab->dten_desc[i];
12759 
12760 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12761 			dtrace_predicate_release(pred, vstate);
12762 
12763 		for (act = ep->dted_action; act != NULL; act = next) {
12764 			next = act->dtad_next;
12765 			dtrace_actdesc_release(act, vstate);
12766 		}
12767 
12768 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12769 	}
12770 
12771 	if (enab->dten_desc != NULL)
12772 		kmem_free(enab->dten_desc,
12773 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12774 
12775 	/*
12776 	 * If this was a retained enabling, decrement the dts_nretained count
12777 	 * and take it off of the dtrace_retained list.
12778 	 */
12779 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12780 	    dtrace_retained == enab) {
12781 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12782 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12783 		enab->dten_vstate->dtvs_state->dts_nretained--;
12784 		dtrace_retained_gen++;
12785 	}
12786 
12787 	if (enab->dten_prev == NULL) {
12788 		if (dtrace_retained == enab) {
12789 			dtrace_retained = enab->dten_next;
12790 
12791 			if (dtrace_retained != NULL)
12792 				dtrace_retained->dten_prev = NULL;
12793 		}
12794 	} else {
12795 		ASSERT(enab != dtrace_retained);
12796 		ASSERT(dtrace_retained != NULL);
12797 		enab->dten_prev->dten_next = enab->dten_next;
12798 	}
12799 
12800 	if (enab->dten_next != NULL) {
12801 		ASSERT(dtrace_retained != NULL);
12802 		enab->dten_next->dten_prev = enab->dten_prev;
12803 	}
12804 
12805 	kmem_free(enab, sizeof (dtrace_enabling_t));
12806 }
12807 
12808 static int
12809 dtrace_enabling_retain(dtrace_enabling_t *enab)
12810 {
12811 	dtrace_state_t *state;
12812 
12813 	ASSERT(MUTEX_HELD(&dtrace_lock));
12814 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12815 	ASSERT(enab->dten_vstate != NULL);
12816 
12817 	state = enab->dten_vstate->dtvs_state;
12818 	ASSERT(state != NULL);
12819 
12820 	/*
12821 	 * We only allow each state to retain dtrace_retain_max enablings.
12822 	 */
12823 	if (state->dts_nretained >= dtrace_retain_max)
12824 		return (ENOSPC);
12825 
12826 	state->dts_nretained++;
12827 	dtrace_retained_gen++;
12828 
12829 	if (dtrace_retained == NULL) {
12830 		dtrace_retained = enab;
12831 		return (0);
12832 	}
12833 
12834 	enab->dten_next = dtrace_retained;
12835 	dtrace_retained->dten_prev = enab;
12836 	dtrace_retained = enab;
12837 
12838 	return (0);
12839 }
12840 
12841 static int
12842 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12843     dtrace_probedesc_t *create)
12844 {
12845 	dtrace_enabling_t *new, *enab;
12846 	int found = 0, err = ENOENT;
12847 
12848 	ASSERT(MUTEX_HELD(&dtrace_lock));
12849 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12850 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12851 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12852 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12853 
12854 	new = dtrace_enabling_create(&state->dts_vstate);
12855 
12856 	/*
12857 	 * Iterate over all retained enablings, looking for enablings that
12858 	 * match the specified state.
12859 	 */
12860 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12861 		int i;
12862 
12863 		/*
12864 		 * dtvs_state can only be NULL for helper enablings -- and
12865 		 * helper enablings can't be retained.
12866 		 */
12867 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12868 
12869 		if (enab->dten_vstate->dtvs_state != state)
12870 			continue;
12871 
12872 		/*
12873 		 * Now iterate over each probe description; we're looking for
12874 		 * an exact match to the specified probe description.
12875 		 */
12876 		for (i = 0; i < enab->dten_ndesc; i++) {
12877 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12878 			dtrace_probedesc_t *pd = &ep->dted_probe;
12879 
12880 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12881 				continue;
12882 
12883 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12884 				continue;
12885 
12886 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12887 				continue;
12888 
12889 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12890 				continue;
12891 
12892 			/*
12893 			 * We have a winning probe!  Add it to our growing
12894 			 * enabling.
12895 			 */
12896 			found = 1;
12897 			dtrace_enabling_addlike(new, ep, create);
12898 		}
12899 	}
12900 
12901 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12902 		dtrace_enabling_destroy(new);
12903 		return (err);
12904 	}
12905 
12906 	return (0);
12907 }
12908 
12909 static void
12910 dtrace_enabling_retract(dtrace_state_t *state)
12911 {
12912 	dtrace_enabling_t *enab, *next;
12913 
12914 	ASSERT(MUTEX_HELD(&dtrace_lock));
12915 
12916 	/*
12917 	 * Iterate over all retained enablings, destroy the enablings retained
12918 	 * for the specified state.
12919 	 */
12920 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12921 		next = enab->dten_next;
12922 
12923 		/*
12924 		 * dtvs_state can only be NULL for helper enablings -- and
12925 		 * helper enablings can't be retained.
12926 		 */
12927 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12928 
12929 		if (enab->dten_vstate->dtvs_state == state) {
12930 			ASSERT(state->dts_nretained > 0);
12931 			dtrace_enabling_destroy(enab);
12932 		}
12933 	}
12934 
12935 	ASSERT(state->dts_nretained == 0);
12936 }
12937 
12938 static int
12939 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12940 {
12941 	int i = 0;
12942 	int matched = 0;
12943 
12944 	ASSERT(MUTEX_HELD(&cpu_lock));
12945 	ASSERT(MUTEX_HELD(&dtrace_lock));
12946 
12947 	for (i = 0; i < enab->dten_ndesc; i++) {
12948 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12949 
12950 		enab->dten_current = ep;
12951 		enab->dten_error = 0;
12952 
12953 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12954 
12955 		if (enab->dten_error != 0) {
12956 			/*
12957 			 * If we get an error half-way through enabling the
12958 			 * probes, we kick out -- perhaps with some number of
12959 			 * them enabled.  Leaving enabled probes enabled may
12960 			 * be slightly confusing for user-level, but we expect
12961 			 * that no one will attempt to actually drive on in
12962 			 * the face of such errors.  If this is an anonymous
12963 			 * enabling (indicated with a NULL nmatched pointer),
12964 			 * we cmn_err() a message.  We aren't expecting to
12965 			 * get such an error -- such as it can exist at all,
12966 			 * it would be a result of corrupted DOF in the driver
12967 			 * properties.
12968 			 */
12969 			if (nmatched == NULL) {
12970 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12971 				    "error on %p: %d", (void *)ep,
12972 				    enab->dten_error);
12973 			}
12974 
12975 			return (enab->dten_error);
12976 		}
12977 	}
12978 
12979 	enab->dten_probegen = dtrace_probegen;
12980 	if (nmatched != NULL)
12981 		*nmatched = matched;
12982 
12983 	return (0);
12984 }
12985 
12986 static void
12987 dtrace_enabling_matchall(void)
12988 {
12989 	dtrace_enabling_t *enab;
12990 
12991 	mutex_enter(&cpu_lock);
12992 	mutex_enter(&dtrace_lock);
12993 
12994 	/*
12995 	 * Iterate over all retained enablings to see if any probes match
12996 	 * against them.  We only perform this operation on enablings for which
12997 	 * we have sufficient permissions by virtue of being in the global zone
12998 	 * or in the same zone as the DTrace client.  Because we can be called
12999 	 * after dtrace_detach() has been called, we cannot assert that there
13000 	 * are retained enablings.  We can safely load from dtrace_retained,
13001 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
13002 	 * block pending our completion.
13003 	 */
13004 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13005 #ifdef illumos
13006 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
13007 
13008 		if (INGLOBALZONE(curproc) ||
13009 		    cr != NULL && getzoneid() == crgetzoneid(cr))
13010 #endif
13011 			(void) dtrace_enabling_match(enab, NULL);
13012 	}
13013 
13014 	mutex_exit(&dtrace_lock);
13015 	mutex_exit(&cpu_lock);
13016 }
13017 
13018 /*
13019  * If an enabling is to be enabled without having matched probes (that is, if
13020  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13021  * enabling must be _primed_ by creating an ECB for every ECB description.
13022  * This must be done to assure that we know the number of speculations, the
13023  * number of aggregations, the minimum buffer size needed, etc. before we
13024  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13025  * enabling any probes, we create ECBs for every ECB decription, but with a
13026  * NULL probe -- which is exactly what this function does.
13027  */
13028 static void
13029 dtrace_enabling_prime(dtrace_state_t *state)
13030 {
13031 	dtrace_enabling_t *enab;
13032 	int i;
13033 
13034 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13035 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13036 
13037 		if (enab->dten_vstate->dtvs_state != state)
13038 			continue;
13039 
13040 		/*
13041 		 * We don't want to prime an enabling more than once, lest
13042 		 * we allow a malicious user to induce resource exhaustion.
13043 		 * (The ECBs that result from priming an enabling aren't
13044 		 * leaked -- but they also aren't deallocated until the
13045 		 * consumer state is destroyed.)
13046 		 */
13047 		if (enab->dten_primed)
13048 			continue;
13049 
13050 		for (i = 0; i < enab->dten_ndesc; i++) {
13051 			enab->dten_current = enab->dten_desc[i];
13052 			(void) dtrace_probe_enable(NULL, enab);
13053 		}
13054 
13055 		enab->dten_primed = 1;
13056 	}
13057 }
13058 
13059 /*
13060  * Called to indicate that probes should be provided due to retained
13061  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13062  * must take an initial lap through the enabling calling the dtps_provide()
13063  * entry point explicitly to allow for autocreated probes.
13064  */
13065 static void
13066 dtrace_enabling_provide(dtrace_provider_t *prv)
13067 {
13068 	int i, all = 0;
13069 	dtrace_probedesc_t desc;
13070 	dtrace_genid_t gen;
13071 
13072 	ASSERT(MUTEX_HELD(&dtrace_lock));
13073 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13074 
13075 	if (prv == NULL) {
13076 		all = 1;
13077 		prv = dtrace_provider;
13078 	}
13079 
13080 	do {
13081 		dtrace_enabling_t *enab;
13082 		void *parg = prv->dtpv_arg;
13083 
13084 retry:
13085 		gen = dtrace_retained_gen;
13086 		for (enab = dtrace_retained; enab != NULL;
13087 		    enab = enab->dten_next) {
13088 			for (i = 0; i < enab->dten_ndesc; i++) {
13089 				desc = enab->dten_desc[i]->dted_probe;
13090 				mutex_exit(&dtrace_lock);
13091 				prv->dtpv_pops.dtps_provide(parg, &desc);
13092 				mutex_enter(&dtrace_lock);
13093 				/*
13094 				 * Process the retained enablings again if
13095 				 * they have changed while we weren't holding
13096 				 * dtrace_lock.
13097 				 */
13098 				if (gen != dtrace_retained_gen)
13099 					goto retry;
13100 			}
13101 		}
13102 	} while (all && (prv = prv->dtpv_next) != NULL);
13103 
13104 	mutex_exit(&dtrace_lock);
13105 	dtrace_probe_provide(NULL, all ? NULL : prv);
13106 	mutex_enter(&dtrace_lock);
13107 }
13108 
13109 /*
13110  * Called to reap ECBs that are attached to probes from defunct providers.
13111  */
13112 static void
13113 dtrace_enabling_reap(void)
13114 {
13115 	dtrace_provider_t *prov;
13116 	dtrace_probe_t *probe;
13117 	dtrace_ecb_t *ecb;
13118 	hrtime_t when;
13119 	int i;
13120 
13121 	mutex_enter(&cpu_lock);
13122 	mutex_enter(&dtrace_lock);
13123 
13124 	for (i = 0; i < dtrace_nprobes; i++) {
13125 		if ((probe = dtrace_probes[i]) == NULL)
13126 			continue;
13127 
13128 		if (probe->dtpr_ecb == NULL)
13129 			continue;
13130 
13131 		prov = probe->dtpr_provider;
13132 
13133 		if ((when = prov->dtpv_defunct) == 0)
13134 			continue;
13135 
13136 		/*
13137 		 * We have ECBs on a defunct provider:  we want to reap these
13138 		 * ECBs to allow the provider to unregister.  The destruction
13139 		 * of these ECBs must be done carefully:  if we destroy the ECB
13140 		 * and the consumer later wishes to consume an EPID that
13141 		 * corresponds to the destroyed ECB (and if the EPID metadata
13142 		 * has not been previously consumed), the consumer will abort
13143 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13144 		 * eliminate) the possibility of this, we will only destroy an
13145 		 * ECB for a defunct provider if, for the state that
13146 		 * corresponds to the ECB:
13147 		 *
13148 		 *  (a)	There is no speculative tracing (which can effectively
13149 		 *	cache an EPID for an arbitrary amount of time).
13150 		 *
13151 		 *  (b)	The principal buffers have been switched twice since the
13152 		 *	provider became defunct.
13153 		 *
13154 		 *  (c)	The aggregation buffers are of zero size or have been
13155 		 *	switched twice since the provider became defunct.
13156 		 *
13157 		 * We use dts_speculates to determine (a) and call a function
13158 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13159 		 * that as soon as we've been unable to destroy one of the ECBs
13160 		 * associated with the probe, we quit trying -- reaping is only
13161 		 * fruitful in as much as we can destroy all ECBs associated
13162 		 * with the defunct provider's probes.
13163 		 */
13164 		while ((ecb = probe->dtpr_ecb) != NULL) {
13165 			dtrace_state_t *state = ecb->dte_state;
13166 			dtrace_buffer_t *buf = state->dts_buffer;
13167 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13168 
13169 			if (state->dts_speculates)
13170 				break;
13171 
13172 			if (!dtrace_buffer_consumed(buf, when))
13173 				break;
13174 
13175 			if (!dtrace_buffer_consumed(aggbuf, when))
13176 				break;
13177 
13178 			dtrace_ecb_disable(ecb);
13179 			ASSERT(probe->dtpr_ecb != ecb);
13180 			dtrace_ecb_destroy(ecb);
13181 		}
13182 	}
13183 
13184 	mutex_exit(&dtrace_lock);
13185 	mutex_exit(&cpu_lock);
13186 }
13187 
13188 /*
13189  * DTrace DOF Functions
13190  */
13191 /*ARGSUSED*/
13192 static void
13193 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13194 {
13195 	if (dtrace_err_verbose)
13196 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13197 
13198 #ifdef DTRACE_ERRDEBUG
13199 	dtrace_errdebug(str);
13200 #endif
13201 }
13202 
13203 /*
13204  * Create DOF out of a currently enabled state.  Right now, we only create
13205  * DOF containing the run-time options -- but this could be expanded to create
13206  * complete DOF representing the enabled state.
13207  */
13208 static dof_hdr_t *
13209 dtrace_dof_create(dtrace_state_t *state)
13210 {
13211 	dof_hdr_t *dof;
13212 	dof_sec_t *sec;
13213 	dof_optdesc_t *opt;
13214 	int i, len = sizeof (dof_hdr_t) +
13215 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13216 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13217 
13218 	ASSERT(MUTEX_HELD(&dtrace_lock));
13219 
13220 	dof = kmem_zalloc(len, KM_SLEEP);
13221 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13222 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13223 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13224 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13225 
13226 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13227 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13228 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13229 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13230 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13231 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13232 
13233 	dof->dofh_flags = 0;
13234 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13235 	dof->dofh_secsize = sizeof (dof_sec_t);
13236 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13237 	dof->dofh_secoff = sizeof (dof_hdr_t);
13238 	dof->dofh_loadsz = len;
13239 	dof->dofh_filesz = len;
13240 	dof->dofh_pad = 0;
13241 
13242 	/*
13243 	 * Fill in the option section header...
13244 	 */
13245 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13246 	sec->dofs_type = DOF_SECT_OPTDESC;
13247 	sec->dofs_align = sizeof (uint64_t);
13248 	sec->dofs_flags = DOF_SECF_LOAD;
13249 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13250 
13251 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13252 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13253 
13254 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13255 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13256 
13257 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13258 		opt[i].dofo_option = i;
13259 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13260 		opt[i].dofo_value = state->dts_options[i];
13261 	}
13262 
13263 	return (dof);
13264 }
13265 
13266 static dof_hdr_t *
13267 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13268 {
13269 	dof_hdr_t hdr, *dof;
13270 
13271 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13272 
13273 	/*
13274 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13275 	 */
13276 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13277 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13278 		*errp = EFAULT;
13279 		return (NULL);
13280 	}
13281 
13282 	/*
13283 	 * Now we'll allocate the entire DOF and copy it in -- provided
13284 	 * that the length isn't outrageous.
13285 	 */
13286 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13287 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13288 		*errp = E2BIG;
13289 		return (NULL);
13290 	}
13291 
13292 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13293 		dtrace_dof_error(&hdr, "invalid load size");
13294 		*errp = EINVAL;
13295 		return (NULL);
13296 	}
13297 
13298 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13299 
13300 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13301 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13302 		kmem_free(dof, hdr.dofh_loadsz);
13303 		*errp = EFAULT;
13304 		return (NULL);
13305 	}
13306 
13307 	return (dof);
13308 }
13309 
13310 #ifdef __FreeBSD__
13311 static dof_hdr_t *
13312 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13313 {
13314 	dof_hdr_t hdr, *dof;
13315 	struct thread *td;
13316 	size_t loadsz;
13317 
13318 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13319 
13320 	td = curthread;
13321 
13322 	/*
13323 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13324 	 */
13325 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13326 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13327 		*errp = EFAULT;
13328 		return (NULL);
13329 	}
13330 
13331 	/*
13332 	 * Now we'll allocate the entire DOF and copy it in -- provided
13333 	 * that the length isn't outrageous.
13334 	 */
13335 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13336 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13337 		*errp = E2BIG;
13338 		return (NULL);
13339 	}
13340 	loadsz = (size_t)hdr.dofh_loadsz;
13341 
13342 	if (loadsz < sizeof (hdr)) {
13343 		dtrace_dof_error(&hdr, "invalid load size");
13344 		*errp = EINVAL;
13345 		return (NULL);
13346 	}
13347 
13348 	dof = kmem_alloc(loadsz, KM_SLEEP);
13349 
13350 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13351 	    dof->dofh_loadsz != loadsz) {
13352 		kmem_free(dof, hdr.dofh_loadsz);
13353 		*errp = EFAULT;
13354 		return (NULL);
13355 	}
13356 
13357 	return (dof);
13358 }
13359 
13360 static __inline uchar_t
13361 dtrace_dof_char(char c)
13362 {
13363 
13364 	switch (c) {
13365 	case '0':
13366 	case '1':
13367 	case '2':
13368 	case '3':
13369 	case '4':
13370 	case '5':
13371 	case '6':
13372 	case '7':
13373 	case '8':
13374 	case '9':
13375 		return (c - '0');
13376 	case 'A':
13377 	case 'B':
13378 	case 'C':
13379 	case 'D':
13380 	case 'E':
13381 	case 'F':
13382 		return (c - 'A' + 10);
13383 	case 'a':
13384 	case 'b':
13385 	case 'c':
13386 	case 'd':
13387 	case 'e':
13388 	case 'f':
13389 		return (c - 'a' + 10);
13390 	}
13391 	/* Should not reach here. */
13392 	return (UCHAR_MAX);
13393 }
13394 #endif /* __FreeBSD__ */
13395 
13396 static dof_hdr_t *
13397 dtrace_dof_property(const char *name)
13398 {
13399 #ifdef __FreeBSD__
13400 	uint8_t *dofbuf;
13401 	u_char *data, *eol;
13402 	caddr_t doffile;
13403 	size_t bytes, len, i;
13404 	dof_hdr_t *dof;
13405 	u_char c1, c2;
13406 
13407 	dof = NULL;
13408 
13409 	doffile = preload_search_by_type("dtrace_dof");
13410 	if (doffile == NULL)
13411 		return (NULL);
13412 
13413 	data = preload_fetch_addr(doffile);
13414 	len = preload_fetch_size(doffile);
13415 	for (;;) {
13416 		/* Look for the end of the line. All lines end in a newline. */
13417 		eol = memchr(data, '\n', len);
13418 		if (eol == NULL)
13419 			return (NULL);
13420 
13421 		if (strncmp(name, data, strlen(name)) == 0)
13422 			break;
13423 
13424 		eol++; /* skip past the newline */
13425 		len -= eol - data;
13426 		data = eol;
13427 	}
13428 
13429 	/* We've found the data corresponding to the specified key. */
13430 
13431 	data += strlen(name) + 1; /* skip past the '=' */
13432 	len = eol - data;
13433 	if (len % 2 != 0) {
13434 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13435 		goto doferr;
13436 	}
13437 	bytes = len / 2;
13438 	if (bytes < sizeof(dof_hdr_t)) {
13439 		dtrace_dof_error(NULL, "truncated header");
13440 		goto doferr;
13441 	}
13442 
13443 	/*
13444 	 * Each byte is represented by the two ASCII characters in its hex
13445 	 * representation.
13446 	 */
13447 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13448 	for (i = 0; i < bytes; i++) {
13449 		c1 = dtrace_dof_char(data[i * 2]);
13450 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13451 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13452 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13453 			goto doferr;
13454 		}
13455 		dofbuf[i] = c1 * 16 + c2;
13456 	}
13457 
13458 	dof = (dof_hdr_t *)dofbuf;
13459 	if (bytes < dof->dofh_loadsz) {
13460 		dtrace_dof_error(NULL, "truncated DOF");
13461 		goto doferr;
13462 	}
13463 
13464 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13465 		dtrace_dof_error(NULL, "oversized DOF");
13466 		goto doferr;
13467 	}
13468 
13469 	return (dof);
13470 
13471 doferr:
13472 	free(dof, M_SOLARIS);
13473 	return (NULL);
13474 #else /* __FreeBSD__ */
13475 	uchar_t *buf;
13476 	uint64_t loadsz;
13477 	unsigned int len, i;
13478 	dof_hdr_t *dof;
13479 
13480 	/*
13481 	 * Unfortunately, array of values in .conf files are always (and
13482 	 * only) interpreted to be integer arrays.  We must read our DOF
13483 	 * as an integer array, and then squeeze it into a byte array.
13484 	 */
13485 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13486 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13487 		return (NULL);
13488 
13489 	for (i = 0; i < len; i++)
13490 		buf[i] = (uchar_t)(((int *)buf)[i]);
13491 
13492 	if (len < sizeof (dof_hdr_t)) {
13493 		ddi_prop_free(buf);
13494 		dtrace_dof_error(NULL, "truncated header");
13495 		return (NULL);
13496 	}
13497 
13498 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13499 		ddi_prop_free(buf);
13500 		dtrace_dof_error(NULL, "truncated DOF");
13501 		return (NULL);
13502 	}
13503 
13504 	if (loadsz >= dtrace_dof_maxsize) {
13505 		ddi_prop_free(buf);
13506 		dtrace_dof_error(NULL, "oversized DOF");
13507 		return (NULL);
13508 	}
13509 
13510 	dof = kmem_alloc(loadsz, KM_SLEEP);
13511 	bcopy(buf, dof, loadsz);
13512 	ddi_prop_free(buf);
13513 
13514 	return (dof);
13515 #endif /* !__FreeBSD__ */
13516 }
13517 
13518 static void
13519 dtrace_dof_destroy(dof_hdr_t *dof)
13520 {
13521 	kmem_free(dof, dof->dofh_loadsz);
13522 }
13523 
13524 /*
13525  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13526  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13527  * a type other than DOF_SECT_NONE is specified, the header is checked against
13528  * this type and NULL is returned if the types do not match.
13529  */
13530 static dof_sec_t *
13531 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13532 {
13533 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13534 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13535 
13536 	if (i >= dof->dofh_secnum) {
13537 		dtrace_dof_error(dof, "referenced section index is invalid");
13538 		return (NULL);
13539 	}
13540 
13541 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13542 		dtrace_dof_error(dof, "referenced section is not loadable");
13543 		return (NULL);
13544 	}
13545 
13546 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13547 		dtrace_dof_error(dof, "referenced section is the wrong type");
13548 		return (NULL);
13549 	}
13550 
13551 	return (sec);
13552 }
13553 
13554 static dtrace_probedesc_t *
13555 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13556 {
13557 	dof_probedesc_t *probe;
13558 	dof_sec_t *strtab;
13559 	uintptr_t daddr = (uintptr_t)dof;
13560 	uintptr_t str;
13561 	size_t size;
13562 
13563 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13564 		dtrace_dof_error(dof, "invalid probe section");
13565 		return (NULL);
13566 	}
13567 
13568 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13569 		dtrace_dof_error(dof, "bad alignment in probe description");
13570 		return (NULL);
13571 	}
13572 
13573 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13574 		dtrace_dof_error(dof, "truncated probe description");
13575 		return (NULL);
13576 	}
13577 
13578 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13579 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13580 
13581 	if (strtab == NULL)
13582 		return (NULL);
13583 
13584 	str = daddr + strtab->dofs_offset;
13585 	size = strtab->dofs_size;
13586 
13587 	if (probe->dofp_provider >= strtab->dofs_size) {
13588 		dtrace_dof_error(dof, "corrupt probe provider");
13589 		return (NULL);
13590 	}
13591 
13592 	(void) strncpy(desc->dtpd_provider,
13593 	    (char *)(str + probe->dofp_provider),
13594 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13595 
13596 	if (probe->dofp_mod >= strtab->dofs_size) {
13597 		dtrace_dof_error(dof, "corrupt probe module");
13598 		return (NULL);
13599 	}
13600 
13601 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13602 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13603 
13604 	if (probe->dofp_func >= strtab->dofs_size) {
13605 		dtrace_dof_error(dof, "corrupt probe function");
13606 		return (NULL);
13607 	}
13608 
13609 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13610 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13611 
13612 	if (probe->dofp_name >= strtab->dofs_size) {
13613 		dtrace_dof_error(dof, "corrupt probe name");
13614 		return (NULL);
13615 	}
13616 
13617 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13618 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13619 
13620 	return (desc);
13621 }
13622 
13623 static dtrace_difo_t *
13624 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13625     cred_t *cr)
13626 {
13627 	dtrace_difo_t *dp;
13628 	size_t ttl = 0;
13629 	dof_difohdr_t *dofd;
13630 	uintptr_t daddr = (uintptr_t)dof;
13631 	size_t max = dtrace_difo_maxsize;
13632 	int i, l, n;
13633 
13634 	static const struct {
13635 		int section;
13636 		int bufoffs;
13637 		int lenoffs;
13638 		int entsize;
13639 		int align;
13640 		const char *msg;
13641 	} difo[] = {
13642 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13643 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13644 		sizeof (dif_instr_t), "multiple DIF sections" },
13645 
13646 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13647 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13648 		sizeof (uint64_t), "multiple integer tables" },
13649 
13650 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13651 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13652 		sizeof (char), "multiple string tables" },
13653 
13654 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13655 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13656 		sizeof (uint_t), "multiple variable tables" },
13657 
13658 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13659 	};
13660 
13661 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13662 		dtrace_dof_error(dof, "invalid DIFO header section");
13663 		return (NULL);
13664 	}
13665 
13666 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13667 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13668 		return (NULL);
13669 	}
13670 
13671 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13672 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13673 		dtrace_dof_error(dof, "bad size in DIFO header");
13674 		return (NULL);
13675 	}
13676 
13677 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13678 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13679 
13680 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13681 	dp->dtdo_rtype = dofd->dofd_rtype;
13682 
13683 	for (l = 0; l < n; l++) {
13684 		dof_sec_t *subsec;
13685 		void **bufp;
13686 		uint32_t *lenp;
13687 
13688 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13689 		    dofd->dofd_links[l])) == NULL)
13690 			goto err; /* invalid section link */
13691 
13692 		if (ttl + subsec->dofs_size > max) {
13693 			dtrace_dof_error(dof, "exceeds maximum size");
13694 			goto err;
13695 		}
13696 
13697 		ttl += subsec->dofs_size;
13698 
13699 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13700 			if (subsec->dofs_type != difo[i].section)
13701 				continue;
13702 
13703 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13704 				dtrace_dof_error(dof, "section not loaded");
13705 				goto err;
13706 			}
13707 
13708 			if (subsec->dofs_align != difo[i].align) {
13709 				dtrace_dof_error(dof, "bad alignment");
13710 				goto err;
13711 			}
13712 
13713 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13714 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13715 
13716 			if (*bufp != NULL) {
13717 				dtrace_dof_error(dof, difo[i].msg);
13718 				goto err;
13719 			}
13720 
13721 			if (difo[i].entsize != subsec->dofs_entsize) {
13722 				dtrace_dof_error(dof, "entry size mismatch");
13723 				goto err;
13724 			}
13725 
13726 			if (subsec->dofs_entsize != 0 &&
13727 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13728 				dtrace_dof_error(dof, "corrupt entry size");
13729 				goto err;
13730 			}
13731 
13732 			*lenp = subsec->dofs_size;
13733 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13734 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13735 			    *bufp, subsec->dofs_size);
13736 
13737 			if (subsec->dofs_entsize != 0)
13738 				*lenp /= subsec->dofs_entsize;
13739 
13740 			break;
13741 		}
13742 
13743 		/*
13744 		 * If we encounter a loadable DIFO sub-section that is not
13745 		 * known to us, assume this is a broken program and fail.
13746 		 */
13747 		if (difo[i].section == DOF_SECT_NONE &&
13748 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13749 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13750 			goto err;
13751 		}
13752 	}
13753 
13754 	if (dp->dtdo_buf == NULL) {
13755 		/*
13756 		 * We can't have a DIF object without DIF text.
13757 		 */
13758 		dtrace_dof_error(dof, "missing DIF text");
13759 		goto err;
13760 	}
13761 
13762 	/*
13763 	 * Before we validate the DIF object, run through the variable table
13764 	 * looking for the strings -- if any of their size are under, we'll set
13765 	 * their size to be the system-wide default string size.  Note that
13766 	 * this should _not_ happen if the "strsize" option has been set --
13767 	 * in this case, the compiler should have set the size to reflect the
13768 	 * setting of the option.
13769 	 */
13770 	for (i = 0; i < dp->dtdo_varlen; i++) {
13771 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13772 		dtrace_diftype_t *t = &v->dtdv_type;
13773 
13774 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13775 			continue;
13776 
13777 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13778 			t->dtdt_size = dtrace_strsize_default;
13779 	}
13780 
13781 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13782 		goto err;
13783 
13784 	dtrace_difo_init(dp, vstate);
13785 	return (dp);
13786 
13787 err:
13788 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13789 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13790 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13791 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13792 
13793 	kmem_free(dp, sizeof (dtrace_difo_t));
13794 	return (NULL);
13795 }
13796 
13797 static dtrace_predicate_t *
13798 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13799     cred_t *cr)
13800 {
13801 	dtrace_difo_t *dp;
13802 
13803 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13804 		return (NULL);
13805 
13806 	return (dtrace_predicate_create(dp));
13807 }
13808 
13809 static dtrace_actdesc_t *
13810 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13811     cred_t *cr)
13812 {
13813 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13814 	dof_actdesc_t *desc;
13815 	dof_sec_t *difosec;
13816 	size_t offs;
13817 	uintptr_t daddr = (uintptr_t)dof;
13818 	uint64_t arg;
13819 	dtrace_actkind_t kind;
13820 
13821 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13822 		dtrace_dof_error(dof, "invalid action section");
13823 		return (NULL);
13824 	}
13825 
13826 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13827 		dtrace_dof_error(dof, "truncated action description");
13828 		return (NULL);
13829 	}
13830 
13831 	if (sec->dofs_align != sizeof (uint64_t)) {
13832 		dtrace_dof_error(dof, "bad alignment in action description");
13833 		return (NULL);
13834 	}
13835 
13836 	if (sec->dofs_size < sec->dofs_entsize) {
13837 		dtrace_dof_error(dof, "section entry size exceeds total size");
13838 		return (NULL);
13839 	}
13840 
13841 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13842 		dtrace_dof_error(dof, "bad entry size in action description");
13843 		return (NULL);
13844 	}
13845 
13846 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13847 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13848 		return (NULL);
13849 	}
13850 
13851 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13852 		desc = (dof_actdesc_t *)(daddr +
13853 		    (uintptr_t)sec->dofs_offset + offs);
13854 		kind = (dtrace_actkind_t)desc->dofa_kind;
13855 
13856 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13857 		    (kind != DTRACEACT_PRINTA ||
13858 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13859 		    (kind == DTRACEACT_DIFEXPR &&
13860 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13861 			dof_sec_t *strtab;
13862 			char *str, *fmt;
13863 			uint64_t i;
13864 
13865 			/*
13866 			 * The argument to these actions is an index into the
13867 			 * DOF string table.  For printf()-like actions, this
13868 			 * is the format string.  For print(), this is the
13869 			 * CTF type of the expression result.
13870 			 */
13871 			if ((strtab = dtrace_dof_sect(dof,
13872 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13873 				goto err;
13874 
13875 			str = (char *)((uintptr_t)dof +
13876 			    (uintptr_t)strtab->dofs_offset);
13877 
13878 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13879 				if (str[i] == '\0')
13880 					break;
13881 			}
13882 
13883 			if (i >= strtab->dofs_size) {
13884 				dtrace_dof_error(dof, "bogus format string");
13885 				goto err;
13886 			}
13887 
13888 			if (i == desc->dofa_arg) {
13889 				dtrace_dof_error(dof, "empty format string");
13890 				goto err;
13891 			}
13892 
13893 			i -= desc->dofa_arg;
13894 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13895 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13896 			arg = (uint64_t)(uintptr_t)fmt;
13897 		} else {
13898 			if (kind == DTRACEACT_PRINTA) {
13899 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13900 				arg = 0;
13901 			} else {
13902 				arg = desc->dofa_arg;
13903 			}
13904 		}
13905 
13906 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13907 		    desc->dofa_uarg, arg);
13908 
13909 		if (last != NULL) {
13910 			last->dtad_next = act;
13911 		} else {
13912 			first = act;
13913 		}
13914 
13915 		last = act;
13916 
13917 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13918 			continue;
13919 
13920 		if ((difosec = dtrace_dof_sect(dof,
13921 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13922 			goto err;
13923 
13924 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13925 
13926 		if (act->dtad_difo == NULL)
13927 			goto err;
13928 	}
13929 
13930 	ASSERT(first != NULL);
13931 	return (first);
13932 
13933 err:
13934 	for (act = first; act != NULL; act = next) {
13935 		next = act->dtad_next;
13936 		dtrace_actdesc_release(act, vstate);
13937 	}
13938 
13939 	return (NULL);
13940 }
13941 
13942 static dtrace_ecbdesc_t *
13943 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13944     cred_t *cr)
13945 {
13946 	dtrace_ecbdesc_t *ep;
13947 	dof_ecbdesc_t *ecb;
13948 	dtrace_probedesc_t *desc;
13949 	dtrace_predicate_t *pred = NULL;
13950 
13951 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13952 		dtrace_dof_error(dof, "truncated ECB description");
13953 		return (NULL);
13954 	}
13955 
13956 	if (sec->dofs_align != sizeof (uint64_t)) {
13957 		dtrace_dof_error(dof, "bad alignment in ECB description");
13958 		return (NULL);
13959 	}
13960 
13961 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13962 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13963 
13964 	if (sec == NULL)
13965 		return (NULL);
13966 
13967 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13968 	ep->dted_uarg = ecb->dofe_uarg;
13969 	desc = &ep->dted_probe;
13970 
13971 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13972 		goto err;
13973 
13974 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13975 		if ((sec = dtrace_dof_sect(dof,
13976 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13977 			goto err;
13978 
13979 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13980 			goto err;
13981 
13982 		ep->dted_pred.dtpdd_predicate = pred;
13983 	}
13984 
13985 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13986 		if ((sec = dtrace_dof_sect(dof,
13987 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13988 			goto err;
13989 
13990 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13991 
13992 		if (ep->dted_action == NULL)
13993 			goto err;
13994 	}
13995 
13996 	return (ep);
13997 
13998 err:
13999 	if (pred != NULL)
14000 		dtrace_predicate_release(pred, vstate);
14001 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
14002 	return (NULL);
14003 }
14004 
14005 /*
14006  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
14007  * specified DOF.  SETX relocations are computed using 'ubase', the base load
14008  * address of the object containing the DOF, and DOFREL relocations are relative
14009  * to the relocation offset within the DOF.
14010  */
14011 static int
14012 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14013     uint64_t udaddr)
14014 {
14015 	uintptr_t daddr = (uintptr_t)dof;
14016 	uintptr_t ts_end;
14017 	dof_relohdr_t *dofr =
14018 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14019 	dof_sec_t *ss, *rs, *ts;
14020 	dof_relodesc_t *r;
14021 	uint_t i, n;
14022 
14023 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14024 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14025 		dtrace_dof_error(dof, "invalid relocation header");
14026 		return (-1);
14027 	}
14028 
14029 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14030 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14031 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14032 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14033 
14034 	if (ss == NULL || rs == NULL || ts == NULL)
14035 		return (-1); /* dtrace_dof_error() has been called already */
14036 
14037 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14038 	    rs->dofs_align != sizeof (uint64_t)) {
14039 		dtrace_dof_error(dof, "invalid relocation section");
14040 		return (-1);
14041 	}
14042 
14043 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14044 	n = rs->dofs_size / rs->dofs_entsize;
14045 
14046 	for (i = 0; i < n; i++) {
14047 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14048 
14049 		switch (r->dofr_type) {
14050 		case DOF_RELO_NONE:
14051 			break;
14052 		case DOF_RELO_SETX:
14053 		case DOF_RELO_DOFREL:
14054 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14055 			    sizeof (uint64_t) > ts->dofs_size) {
14056 				dtrace_dof_error(dof, "bad relocation offset");
14057 				return (-1);
14058 			}
14059 
14060 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14061 				dtrace_dof_error(dof, "bad relocation offset");
14062 				return (-1);
14063 			}
14064 
14065 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14066 				dtrace_dof_error(dof, "misaligned setx relo");
14067 				return (-1);
14068 			}
14069 
14070 			if (r->dofr_type == DOF_RELO_SETX)
14071 				*(uint64_t *)taddr += ubase;
14072 			else
14073 				*(uint64_t *)taddr +=
14074 				    udaddr + ts->dofs_offset + r->dofr_offset;
14075 			break;
14076 		default:
14077 			dtrace_dof_error(dof, "invalid relocation type");
14078 			return (-1);
14079 		}
14080 
14081 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14082 	}
14083 
14084 	return (0);
14085 }
14086 
14087 /*
14088  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14089  * header:  it should be at the front of a memory region that is at least
14090  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14091  * size.  It need not be validated in any other way.
14092  */
14093 static int
14094 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14095     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14096 {
14097 	uint64_t len = dof->dofh_loadsz, seclen;
14098 	uintptr_t daddr = (uintptr_t)dof;
14099 	dtrace_ecbdesc_t *ep;
14100 	dtrace_enabling_t *enab;
14101 	uint_t i;
14102 
14103 	ASSERT(MUTEX_HELD(&dtrace_lock));
14104 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14105 
14106 	/*
14107 	 * Check the DOF header identification bytes.  In addition to checking
14108 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14109 	 * we can use them later without fear of regressing existing binaries.
14110 	 */
14111 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14112 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14113 		dtrace_dof_error(dof, "DOF magic string mismatch");
14114 		return (-1);
14115 	}
14116 
14117 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14118 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14119 		dtrace_dof_error(dof, "DOF has invalid data model");
14120 		return (-1);
14121 	}
14122 
14123 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14124 		dtrace_dof_error(dof, "DOF encoding mismatch");
14125 		return (-1);
14126 	}
14127 
14128 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14129 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14130 		dtrace_dof_error(dof, "DOF version mismatch");
14131 		return (-1);
14132 	}
14133 
14134 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14135 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14136 		return (-1);
14137 	}
14138 
14139 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14140 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14141 		return (-1);
14142 	}
14143 
14144 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14145 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14146 		return (-1);
14147 	}
14148 
14149 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14150 		if (dof->dofh_ident[i] != 0) {
14151 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14152 			return (-1);
14153 		}
14154 	}
14155 
14156 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14157 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14158 		return (-1);
14159 	}
14160 
14161 	if (dof->dofh_secsize == 0) {
14162 		dtrace_dof_error(dof, "zero section header size");
14163 		return (-1);
14164 	}
14165 
14166 	/*
14167 	 * Check that the section headers don't exceed the amount of DOF
14168 	 * data.  Note that we cast the section size and number of sections
14169 	 * to uint64_t's to prevent possible overflow in the multiplication.
14170 	 */
14171 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14172 
14173 	if (dof->dofh_secoff > len || seclen > len ||
14174 	    dof->dofh_secoff + seclen > len) {
14175 		dtrace_dof_error(dof, "truncated section headers");
14176 		return (-1);
14177 	}
14178 
14179 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14180 		dtrace_dof_error(dof, "misaligned section headers");
14181 		return (-1);
14182 	}
14183 
14184 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14185 		dtrace_dof_error(dof, "misaligned section size");
14186 		return (-1);
14187 	}
14188 
14189 	/*
14190 	 * Take an initial pass through the section headers to be sure that
14191 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14192 	 * set, do not permit sections relating to providers, probes, or args.
14193 	 */
14194 	for (i = 0; i < dof->dofh_secnum; i++) {
14195 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14196 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14197 
14198 		if (noprobes) {
14199 			switch (sec->dofs_type) {
14200 			case DOF_SECT_PROVIDER:
14201 			case DOF_SECT_PROBES:
14202 			case DOF_SECT_PRARGS:
14203 			case DOF_SECT_PROFFS:
14204 				dtrace_dof_error(dof, "illegal sections "
14205 				    "for enabling");
14206 				return (-1);
14207 			}
14208 		}
14209 
14210 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14211 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14212 			dtrace_dof_error(dof, "loadable section with load "
14213 			    "flag unset");
14214 			return (-1);
14215 		}
14216 
14217 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14218 			continue; /* just ignore non-loadable sections */
14219 
14220 		if (!ISP2(sec->dofs_align)) {
14221 			dtrace_dof_error(dof, "bad section alignment");
14222 			return (-1);
14223 		}
14224 
14225 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14226 			dtrace_dof_error(dof, "misaligned section");
14227 			return (-1);
14228 		}
14229 
14230 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14231 		    sec->dofs_offset + sec->dofs_size > len) {
14232 			dtrace_dof_error(dof, "corrupt section header");
14233 			return (-1);
14234 		}
14235 
14236 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14237 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14238 			dtrace_dof_error(dof, "non-terminating string table");
14239 			return (-1);
14240 		}
14241 	}
14242 
14243 	/*
14244 	 * Take a second pass through the sections and locate and perform any
14245 	 * relocations that are present.  We do this after the first pass to
14246 	 * be sure that all sections have had their headers validated.
14247 	 */
14248 	for (i = 0; i < dof->dofh_secnum; i++) {
14249 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14250 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14251 
14252 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14253 			continue; /* skip sections that are not loadable */
14254 
14255 		switch (sec->dofs_type) {
14256 		case DOF_SECT_URELHDR:
14257 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14258 				return (-1);
14259 			break;
14260 		}
14261 	}
14262 
14263 	if ((enab = *enabp) == NULL)
14264 		enab = *enabp = dtrace_enabling_create(vstate);
14265 
14266 	for (i = 0; i < dof->dofh_secnum; i++) {
14267 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14268 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14269 
14270 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14271 			continue;
14272 
14273 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14274 			dtrace_enabling_destroy(enab);
14275 			*enabp = NULL;
14276 			return (-1);
14277 		}
14278 
14279 		dtrace_enabling_add(enab, ep);
14280 	}
14281 
14282 	return (0);
14283 }
14284 
14285 /*
14286  * Process DOF for any options.  This routine assumes that the DOF has been
14287  * at least processed by dtrace_dof_slurp().
14288  */
14289 static int
14290 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14291 {
14292 	int i, rval;
14293 	uint32_t entsize;
14294 	size_t offs;
14295 	dof_optdesc_t *desc;
14296 
14297 	for (i = 0; i < dof->dofh_secnum; i++) {
14298 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14299 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14300 
14301 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14302 			continue;
14303 
14304 		if (sec->dofs_align != sizeof (uint64_t)) {
14305 			dtrace_dof_error(dof, "bad alignment in "
14306 			    "option description");
14307 			return (EINVAL);
14308 		}
14309 
14310 		if ((entsize = sec->dofs_entsize) == 0) {
14311 			dtrace_dof_error(dof, "zeroed option entry size");
14312 			return (EINVAL);
14313 		}
14314 
14315 		if (entsize < sizeof (dof_optdesc_t)) {
14316 			dtrace_dof_error(dof, "bad option entry size");
14317 			return (EINVAL);
14318 		}
14319 
14320 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14321 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14322 			    (uintptr_t)sec->dofs_offset + offs);
14323 
14324 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14325 				dtrace_dof_error(dof, "non-zero option string");
14326 				return (EINVAL);
14327 			}
14328 
14329 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14330 				dtrace_dof_error(dof, "unset option");
14331 				return (EINVAL);
14332 			}
14333 
14334 			if ((rval = dtrace_state_option(state,
14335 			    desc->dofo_option, desc->dofo_value)) != 0) {
14336 				dtrace_dof_error(dof, "rejected option");
14337 				return (rval);
14338 			}
14339 		}
14340 	}
14341 
14342 	return (0);
14343 }
14344 
14345 /*
14346  * DTrace Consumer State Functions
14347  */
14348 static int
14349 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14350 {
14351 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14352 	void *base;
14353 	uintptr_t limit;
14354 	dtrace_dynvar_t *dvar, *next, *start;
14355 	int i;
14356 
14357 	ASSERT(MUTEX_HELD(&dtrace_lock));
14358 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14359 
14360 	bzero(dstate, sizeof (dtrace_dstate_t));
14361 
14362 	if ((dstate->dtds_chunksize = chunksize) == 0)
14363 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14364 
14365 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14366 
14367 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14368 		size = min;
14369 
14370 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14371 		return (ENOMEM);
14372 
14373 	dstate->dtds_size = size;
14374 	dstate->dtds_base = base;
14375 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14376 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14377 
14378 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14379 
14380 	if (hashsize != 1 && (hashsize & 1))
14381 		hashsize--;
14382 
14383 	dstate->dtds_hashsize = hashsize;
14384 	dstate->dtds_hash = dstate->dtds_base;
14385 
14386 	/*
14387 	 * Set all of our hash buckets to point to the single sink, and (if
14388 	 * it hasn't already been set), set the sink's hash value to be the
14389 	 * sink sentinel value.  The sink is needed for dynamic variable
14390 	 * lookups to know that they have iterated over an entire, valid hash
14391 	 * chain.
14392 	 */
14393 	for (i = 0; i < hashsize; i++)
14394 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14395 
14396 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14397 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14398 
14399 	/*
14400 	 * Determine number of active CPUs.  Divide free list evenly among
14401 	 * active CPUs.
14402 	 */
14403 	start = (dtrace_dynvar_t *)
14404 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14405 	limit = (uintptr_t)base + size;
14406 
14407 	VERIFY((uintptr_t)start < limit);
14408 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14409 
14410 	maxper = (limit - (uintptr_t)start) / NCPU;
14411 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14412 
14413 #ifndef illumos
14414 	CPU_FOREACH(i) {
14415 #else
14416 	for (i = 0; i < NCPU; i++) {
14417 #endif
14418 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14419 
14420 		/*
14421 		 * If we don't even have enough chunks to make it once through
14422 		 * NCPUs, we're just going to allocate everything to the first
14423 		 * CPU.  And if we're on the last CPU, we're going to allocate
14424 		 * whatever is left over.  In either case, we set the limit to
14425 		 * be the limit of the dynamic variable space.
14426 		 */
14427 		if (maxper == 0 || i == NCPU - 1) {
14428 			limit = (uintptr_t)base + size;
14429 			start = NULL;
14430 		} else {
14431 			limit = (uintptr_t)start + maxper;
14432 			start = (dtrace_dynvar_t *)limit;
14433 		}
14434 
14435 		VERIFY(limit <= (uintptr_t)base + size);
14436 
14437 		for (;;) {
14438 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14439 			    dstate->dtds_chunksize);
14440 
14441 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14442 				break;
14443 
14444 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14445 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14446 			dvar->dtdv_next = next;
14447 			dvar = next;
14448 		}
14449 
14450 		if (maxper == 0)
14451 			break;
14452 	}
14453 
14454 	return (0);
14455 }
14456 
14457 static void
14458 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14459 {
14460 	ASSERT(MUTEX_HELD(&cpu_lock));
14461 
14462 	if (dstate->dtds_base == NULL)
14463 		return;
14464 
14465 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14466 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14467 }
14468 
14469 static void
14470 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14471 {
14472 	/*
14473 	 * Logical XOR, where are you?
14474 	 */
14475 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14476 
14477 	if (vstate->dtvs_nglobals > 0) {
14478 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14479 		    sizeof (dtrace_statvar_t *));
14480 	}
14481 
14482 	if (vstate->dtvs_ntlocals > 0) {
14483 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14484 		    sizeof (dtrace_difv_t));
14485 	}
14486 
14487 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14488 
14489 	if (vstate->dtvs_nlocals > 0) {
14490 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14491 		    sizeof (dtrace_statvar_t *));
14492 	}
14493 }
14494 
14495 #ifdef illumos
14496 static void
14497 dtrace_state_clean(dtrace_state_t *state)
14498 {
14499 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14500 		return;
14501 
14502 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14503 	dtrace_speculation_clean(state);
14504 }
14505 
14506 static void
14507 dtrace_state_deadman(dtrace_state_t *state)
14508 {
14509 	hrtime_t now;
14510 
14511 	dtrace_sync();
14512 
14513 	now = dtrace_gethrtime();
14514 
14515 	if (state != dtrace_anon.dta_state &&
14516 	    now - state->dts_laststatus >= dtrace_deadman_user)
14517 		return;
14518 
14519 	/*
14520 	 * We must be sure that dts_alive never appears to be less than the
14521 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14522 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14523 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14524 	 * the new value.  This assures that dts_alive never appears to be
14525 	 * less than its true value, regardless of the order in which the
14526 	 * stores to the underlying storage are issued.
14527 	 */
14528 	state->dts_alive = INT64_MAX;
14529 	dtrace_membar_producer();
14530 	state->dts_alive = now;
14531 }
14532 #else	/* !illumos */
14533 static void
14534 dtrace_state_clean(void *arg)
14535 {
14536 	dtrace_state_t *state = arg;
14537 	dtrace_optval_t *opt = state->dts_options;
14538 
14539 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14540 		return;
14541 
14542 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14543 	dtrace_speculation_clean(state);
14544 
14545 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14546 	    dtrace_state_clean, state);
14547 }
14548 
14549 static void
14550 dtrace_state_deadman(void *arg)
14551 {
14552 	dtrace_state_t *state = arg;
14553 	hrtime_t now;
14554 
14555 	dtrace_sync();
14556 
14557 	dtrace_debug_output();
14558 
14559 	now = dtrace_gethrtime();
14560 
14561 	if (state != dtrace_anon.dta_state &&
14562 	    now - state->dts_laststatus >= dtrace_deadman_user)
14563 		return;
14564 
14565 	/*
14566 	 * We must be sure that dts_alive never appears to be less than the
14567 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14568 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14569 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14570 	 * the new value.  This assures that dts_alive never appears to be
14571 	 * less than its true value, regardless of the order in which the
14572 	 * stores to the underlying storage are issued.
14573 	 */
14574 	state->dts_alive = INT64_MAX;
14575 	dtrace_membar_producer();
14576 	state->dts_alive = now;
14577 
14578 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14579 	    dtrace_state_deadman, state);
14580 }
14581 #endif	/* illumos */
14582 
14583 static dtrace_state_t *
14584 #ifdef illumos
14585 dtrace_state_create(dev_t *devp, cred_t *cr)
14586 #else
14587 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14588 #endif
14589 {
14590 #ifdef illumos
14591 	minor_t minor;
14592 	major_t major;
14593 #else
14594 	cred_t *cr = NULL;
14595 	int m = 0;
14596 #endif
14597 	char c[30];
14598 	dtrace_state_t *state;
14599 	dtrace_optval_t *opt;
14600 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14601 	int cpu_it;
14602 
14603 	ASSERT(MUTEX_HELD(&dtrace_lock));
14604 	ASSERT(MUTEX_HELD(&cpu_lock));
14605 
14606 #ifdef illumos
14607 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14608 	    VM_BESTFIT | VM_SLEEP);
14609 
14610 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14611 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14612 		return (NULL);
14613 	}
14614 
14615 	state = ddi_get_soft_state(dtrace_softstate, minor);
14616 #else
14617 	if (dev != NULL) {
14618 		cr = dev->si_cred;
14619 		m = dev2unit(dev);
14620 	}
14621 
14622 	/* Allocate memory for the state. */
14623 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14624 #endif
14625 
14626 	state->dts_epid = DTRACE_EPIDNONE + 1;
14627 
14628 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14629 #ifdef illumos
14630 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14631 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14632 
14633 	if (devp != NULL) {
14634 		major = getemajor(*devp);
14635 	} else {
14636 		major = ddi_driver_major(dtrace_devi);
14637 	}
14638 
14639 	state->dts_dev = makedevice(major, minor);
14640 
14641 	if (devp != NULL)
14642 		*devp = state->dts_dev;
14643 #else
14644 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14645 	state->dts_dev = dev;
14646 #endif
14647 
14648 	/*
14649 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14650 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14651 	 * other hand, it saves an additional memory reference in the probe
14652 	 * path.
14653 	 */
14654 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14655 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14656 
14657 	/*
14658          * Allocate and initialise the per-process per-CPU random state.
14659 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14660          * assumed to be seeded at this point (if from Fortuna seed file).
14661 	 */
14662 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14663 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14664 		/*
14665 		 * Each CPU is assigned a 2^64 period, non-overlapping
14666 		 * subsequence.
14667 		 */
14668 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14669 		    state->dts_rstate[cpu_it]);
14670 	}
14671 
14672 #ifdef illumos
14673 	state->dts_cleaner = CYCLIC_NONE;
14674 	state->dts_deadman = CYCLIC_NONE;
14675 #else
14676 	callout_init(&state->dts_cleaner, 1);
14677 	callout_init(&state->dts_deadman, 1);
14678 #endif
14679 	state->dts_vstate.dtvs_state = state;
14680 
14681 	for (i = 0; i < DTRACEOPT_MAX; i++)
14682 		state->dts_options[i] = DTRACEOPT_UNSET;
14683 
14684 	/*
14685 	 * Set the default options.
14686 	 */
14687 	opt = state->dts_options;
14688 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14689 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14690 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14691 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14692 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14693 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14694 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14695 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14696 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14697 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14698 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14699 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14700 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14701 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14702 
14703 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14704 
14705 	/*
14706 	 * Depending on the user credentials, we set flag bits which alter probe
14707 	 * visibility or the amount of destructiveness allowed.  In the case of
14708 	 * actual anonymous tracing, or the possession of all privileges, all of
14709 	 * the normal checks are bypassed.
14710 	 */
14711 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14712 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14713 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14714 	} else {
14715 		/*
14716 		 * Set up the credentials for this instantiation.  We take a
14717 		 * hold on the credential to prevent it from disappearing on
14718 		 * us; this in turn prevents the zone_t referenced by this
14719 		 * credential from disappearing.  This means that we can
14720 		 * examine the credential and the zone from probe context.
14721 		 */
14722 		crhold(cr);
14723 		state->dts_cred.dcr_cred = cr;
14724 
14725 		/*
14726 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14727 		 * unlocks the use of variables like pid, zonename, etc.
14728 		 */
14729 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14730 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14731 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14732 		}
14733 
14734 		/*
14735 		 * dtrace_user allows use of syscall and profile providers.
14736 		 * If the user also has proc_owner and/or proc_zone, we
14737 		 * extend the scope to include additional visibility and
14738 		 * destructive power.
14739 		 */
14740 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14741 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14742 				state->dts_cred.dcr_visible |=
14743 				    DTRACE_CRV_ALLPROC;
14744 
14745 				state->dts_cred.dcr_action |=
14746 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14747 			}
14748 
14749 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14750 				state->dts_cred.dcr_visible |=
14751 				    DTRACE_CRV_ALLZONE;
14752 
14753 				state->dts_cred.dcr_action |=
14754 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14755 			}
14756 
14757 			/*
14758 			 * If we have all privs in whatever zone this is,
14759 			 * we can do destructive things to processes which
14760 			 * have altered credentials.
14761 			 */
14762 #ifdef illumos
14763 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14764 			    cr->cr_zone->zone_privset)) {
14765 				state->dts_cred.dcr_action |=
14766 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14767 			}
14768 #endif
14769 		}
14770 
14771 		/*
14772 		 * Holding the dtrace_kernel privilege also implies that
14773 		 * the user has the dtrace_user privilege from a visibility
14774 		 * perspective.  But without further privileges, some
14775 		 * destructive actions are not available.
14776 		 */
14777 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14778 			/*
14779 			 * Make all probes in all zones visible.  However,
14780 			 * this doesn't mean that all actions become available
14781 			 * to all zones.
14782 			 */
14783 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14784 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14785 
14786 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14787 			    DTRACE_CRA_PROC;
14788 			/*
14789 			 * Holding proc_owner means that destructive actions
14790 			 * for *this* zone are allowed.
14791 			 */
14792 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14793 				state->dts_cred.dcr_action |=
14794 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14795 
14796 			/*
14797 			 * Holding proc_zone means that destructive actions
14798 			 * for this user/group ID in all zones is allowed.
14799 			 */
14800 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14801 				state->dts_cred.dcr_action |=
14802 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14803 
14804 #ifdef illumos
14805 			/*
14806 			 * If we have all privs in whatever zone this is,
14807 			 * we can do destructive things to processes which
14808 			 * have altered credentials.
14809 			 */
14810 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14811 			    cr->cr_zone->zone_privset)) {
14812 				state->dts_cred.dcr_action |=
14813 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14814 			}
14815 #endif
14816 		}
14817 
14818 		/*
14819 		 * Holding the dtrace_proc privilege gives control over fasttrap
14820 		 * and pid providers.  We need to grant wider destructive
14821 		 * privileges in the event that the user has proc_owner and/or
14822 		 * proc_zone.
14823 		 */
14824 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14825 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14826 				state->dts_cred.dcr_action |=
14827 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14828 
14829 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14830 				state->dts_cred.dcr_action |=
14831 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14832 		}
14833 	}
14834 
14835 	return (state);
14836 }
14837 
14838 static int
14839 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14840 {
14841 	dtrace_optval_t *opt = state->dts_options, size;
14842 	processorid_t cpu = 0;
14843 	int flags = 0, rval, factor, divisor = 1;
14844 
14845 	ASSERT(MUTEX_HELD(&dtrace_lock));
14846 	ASSERT(MUTEX_HELD(&cpu_lock));
14847 	ASSERT(which < DTRACEOPT_MAX);
14848 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14849 	    (state == dtrace_anon.dta_state &&
14850 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14851 
14852 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14853 		return (0);
14854 
14855 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14856 		cpu = opt[DTRACEOPT_CPU];
14857 
14858 	if (which == DTRACEOPT_SPECSIZE)
14859 		flags |= DTRACEBUF_NOSWITCH;
14860 
14861 	if (which == DTRACEOPT_BUFSIZE) {
14862 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14863 			flags |= DTRACEBUF_RING;
14864 
14865 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14866 			flags |= DTRACEBUF_FILL;
14867 
14868 		if (state != dtrace_anon.dta_state ||
14869 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14870 			flags |= DTRACEBUF_INACTIVE;
14871 	}
14872 
14873 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14874 		/*
14875 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14876 		 * aligned, drop it down by the difference.
14877 		 */
14878 		if (size & (sizeof (uint64_t) - 1))
14879 			size -= size & (sizeof (uint64_t) - 1);
14880 
14881 		if (size < state->dts_reserve) {
14882 			/*
14883 			 * Buffers always must be large enough to accommodate
14884 			 * their prereserved space.  We return E2BIG instead
14885 			 * of ENOMEM in this case to allow for user-level
14886 			 * software to differentiate the cases.
14887 			 */
14888 			return (E2BIG);
14889 		}
14890 
14891 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14892 
14893 		if (rval != ENOMEM) {
14894 			opt[which] = size;
14895 			return (rval);
14896 		}
14897 
14898 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14899 			return (rval);
14900 
14901 		for (divisor = 2; divisor < factor; divisor <<= 1)
14902 			continue;
14903 	}
14904 
14905 	return (ENOMEM);
14906 }
14907 
14908 static int
14909 dtrace_state_buffers(dtrace_state_t *state)
14910 {
14911 	dtrace_speculation_t *spec = state->dts_speculations;
14912 	int rval, i;
14913 
14914 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14915 	    DTRACEOPT_BUFSIZE)) != 0)
14916 		return (rval);
14917 
14918 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14919 	    DTRACEOPT_AGGSIZE)) != 0)
14920 		return (rval);
14921 
14922 	for (i = 0; i < state->dts_nspeculations; i++) {
14923 		if ((rval = dtrace_state_buffer(state,
14924 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14925 			return (rval);
14926 	}
14927 
14928 	return (0);
14929 }
14930 
14931 static void
14932 dtrace_state_prereserve(dtrace_state_t *state)
14933 {
14934 	dtrace_ecb_t *ecb;
14935 	dtrace_probe_t *probe;
14936 
14937 	state->dts_reserve = 0;
14938 
14939 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14940 		return;
14941 
14942 	/*
14943 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14944 	 * prereserved space to be the space required by the END probes.
14945 	 */
14946 	probe = dtrace_probes[dtrace_probeid_end - 1];
14947 	ASSERT(probe != NULL);
14948 
14949 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14950 		if (ecb->dte_state != state)
14951 			continue;
14952 
14953 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14954 	}
14955 }
14956 
14957 static int
14958 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14959 {
14960 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14961 	dtrace_speculation_t *spec;
14962 	dtrace_buffer_t *buf;
14963 #ifdef illumos
14964 	cyc_handler_t hdlr;
14965 	cyc_time_t when;
14966 #endif
14967 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14968 	dtrace_icookie_t cookie;
14969 
14970 	mutex_enter(&cpu_lock);
14971 	mutex_enter(&dtrace_lock);
14972 
14973 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14974 		rval = EBUSY;
14975 		goto out;
14976 	}
14977 
14978 	/*
14979 	 * Before we can perform any checks, we must prime all of the
14980 	 * retained enablings that correspond to this state.
14981 	 */
14982 	dtrace_enabling_prime(state);
14983 
14984 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14985 		rval = EACCES;
14986 		goto out;
14987 	}
14988 
14989 	dtrace_state_prereserve(state);
14990 
14991 	/*
14992 	 * Now we want to do is try to allocate our speculations.
14993 	 * We do not automatically resize the number of speculations; if
14994 	 * this fails, we will fail the operation.
14995 	 */
14996 	nspec = opt[DTRACEOPT_NSPEC];
14997 	ASSERT(nspec != DTRACEOPT_UNSET);
14998 
14999 	if (nspec > INT_MAX) {
15000 		rval = ENOMEM;
15001 		goto out;
15002 	}
15003 
15004 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
15005 	    KM_NOSLEEP | KM_NORMALPRI);
15006 
15007 	if (spec == NULL) {
15008 		rval = ENOMEM;
15009 		goto out;
15010 	}
15011 
15012 	state->dts_speculations = spec;
15013 	state->dts_nspeculations = (int)nspec;
15014 
15015 	for (i = 0; i < nspec; i++) {
15016 		if ((buf = kmem_zalloc(bufsize,
15017 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15018 			rval = ENOMEM;
15019 			goto err;
15020 		}
15021 
15022 		spec[i].dtsp_buffer = buf;
15023 	}
15024 
15025 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15026 		if (dtrace_anon.dta_state == NULL) {
15027 			rval = ENOENT;
15028 			goto out;
15029 		}
15030 
15031 		if (state->dts_necbs != 0) {
15032 			rval = EALREADY;
15033 			goto out;
15034 		}
15035 
15036 		state->dts_anon = dtrace_anon_grab();
15037 		ASSERT(state->dts_anon != NULL);
15038 		state = state->dts_anon;
15039 
15040 		/*
15041 		 * We want "grabanon" to be set in the grabbed state, so we'll
15042 		 * copy that option value from the grabbing state into the
15043 		 * grabbed state.
15044 		 */
15045 		state->dts_options[DTRACEOPT_GRABANON] =
15046 		    opt[DTRACEOPT_GRABANON];
15047 
15048 		*cpu = dtrace_anon.dta_beganon;
15049 
15050 		/*
15051 		 * If the anonymous state is active (as it almost certainly
15052 		 * is if the anonymous enabling ultimately matched anything),
15053 		 * we don't allow any further option processing -- but we
15054 		 * don't return failure.
15055 		 */
15056 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15057 			goto out;
15058 	}
15059 
15060 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15061 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15062 		if (state->dts_aggregations == NULL) {
15063 			/*
15064 			 * We're not going to create an aggregation buffer
15065 			 * because we don't have any ECBs that contain
15066 			 * aggregations -- set this option to 0.
15067 			 */
15068 			opt[DTRACEOPT_AGGSIZE] = 0;
15069 		} else {
15070 			/*
15071 			 * If we have an aggregation buffer, we must also have
15072 			 * a buffer to use as scratch.
15073 			 */
15074 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15075 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15076 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15077 			}
15078 		}
15079 	}
15080 
15081 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15082 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15083 		if (!state->dts_speculates) {
15084 			/*
15085 			 * We're not going to create speculation buffers
15086 			 * because we don't have any ECBs that actually
15087 			 * speculate -- set the speculation size to 0.
15088 			 */
15089 			opt[DTRACEOPT_SPECSIZE] = 0;
15090 		}
15091 	}
15092 
15093 	/*
15094 	 * The bare minimum size for any buffer that we're actually going to
15095 	 * do anything to is sizeof (uint64_t).
15096 	 */
15097 	sz = sizeof (uint64_t);
15098 
15099 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15100 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15101 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15102 		/*
15103 		 * A buffer size has been explicitly set to 0 (or to a size
15104 		 * that will be adjusted to 0) and we need the space -- we
15105 		 * need to return failure.  We return ENOSPC to differentiate
15106 		 * it from failing to allocate a buffer due to failure to meet
15107 		 * the reserve (for which we return E2BIG).
15108 		 */
15109 		rval = ENOSPC;
15110 		goto out;
15111 	}
15112 
15113 	if ((rval = dtrace_state_buffers(state)) != 0)
15114 		goto err;
15115 
15116 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15117 		sz = dtrace_dstate_defsize;
15118 
15119 	do {
15120 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15121 
15122 		if (rval == 0)
15123 			break;
15124 
15125 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15126 			goto err;
15127 	} while (sz >>= 1);
15128 
15129 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15130 
15131 	if (rval != 0)
15132 		goto err;
15133 
15134 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15135 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15136 
15137 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15138 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15139 
15140 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15141 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15142 
15143 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15144 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15145 
15146 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15147 #ifdef illumos
15148 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15149 	hdlr.cyh_arg = state;
15150 	hdlr.cyh_level = CY_LOW_LEVEL;
15151 
15152 	when.cyt_when = 0;
15153 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15154 
15155 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15156 
15157 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15158 	hdlr.cyh_arg = state;
15159 	hdlr.cyh_level = CY_LOW_LEVEL;
15160 
15161 	when.cyt_when = 0;
15162 	when.cyt_interval = dtrace_deadman_interval;
15163 
15164 	state->dts_deadman = cyclic_add(&hdlr, &when);
15165 #else
15166 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15167 	    dtrace_state_clean, state);
15168 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15169 	    dtrace_state_deadman, state);
15170 #endif
15171 
15172 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15173 
15174 #ifdef illumos
15175 	if (state->dts_getf != 0 &&
15176 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15177 		/*
15178 		 * We don't have kernel privs but we have at least one call
15179 		 * to getf(); we need to bump our zone's count, and (if
15180 		 * this is the first enabling to have an unprivileged call
15181 		 * to getf()) we need to hook into closef().
15182 		 */
15183 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15184 
15185 		if (dtrace_getf++ == 0) {
15186 			ASSERT(dtrace_closef == NULL);
15187 			dtrace_closef = dtrace_getf_barrier;
15188 		}
15189 	}
15190 #endif
15191 
15192 	/*
15193 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15194 	 * interrupts here both to record the CPU on which we fired the BEGIN
15195 	 * probe (the data from this CPU will be processed first at user
15196 	 * level) and to manually activate the buffer for this CPU.
15197 	 */
15198 	cookie = dtrace_interrupt_disable();
15199 	*cpu = curcpu;
15200 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15201 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15202 
15203 	dtrace_probe(dtrace_probeid_begin,
15204 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15205 	dtrace_interrupt_enable(cookie);
15206 	/*
15207 	 * We may have had an exit action from a BEGIN probe; only change our
15208 	 * state to ACTIVE if we're still in WARMUP.
15209 	 */
15210 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15211 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15212 
15213 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15214 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15215 
15216 #ifdef __FreeBSD__
15217 	/*
15218 	 * We enable anonymous tracing before APs are started, so we must
15219 	 * activate buffers using the current CPU.
15220 	 */
15221 	if (state == dtrace_anon.dta_state)
15222 		for (int i = 0; i < NCPU; i++)
15223 			dtrace_buffer_activate_cpu(state, i);
15224 	else
15225 		dtrace_xcall(DTRACE_CPUALL,
15226 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15227 #else
15228 	/*
15229 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15230 	 * want each CPU to transition its principal buffer out of the
15231 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15232 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15233 	 * atomically transition from processing none of a state's ECBs to
15234 	 * processing all of them.
15235 	 */
15236 	dtrace_xcall(DTRACE_CPUALL,
15237 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15238 #endif
15239 	goto out;
15240 
15241 err:
15242 	dtrace_buffer_free(state->dts_buffer);
15243 	dtrace_buffer_free(state->dts_aggbuffer);
15244 
15245 	if ((nspec = state->dts_nspeculations) == 0) {
15246 		ASSERT(state->dts_speculations == NULL);
15247 		goto out;
15248 	}
15249 
15250 	spec = state->dts_speculations;
15251 	ASSERT(spec != NULL);
15252 
15253 	for (i = 0; i < state->dts_nspeculations; i++) {
15254 		if ((buf = spec[i].dtsp_buffer) == NULL)
15255 			break;
15256 
15257 		dtrace_buffer_free(buf);
15258 		kmem_free(buf, bufsize);
15259 	}
15260 
15261 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15262 	state->dts_nspeculations = 0;
15263 	state->dts_speculations = NULL;
15264 
15265 out:
15266 	mutex_exit(&dtrace_lock);
15267 	mutex_exit(&cpu_lock);
15268 
15269 	return (rval);
15270 }
15271 
15272 static int
15273 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15274 {
15275 	dtrace_icookie_t cookie;
15276 
15277 	ASSERT(MUTEX_HELD(&dtrace_lock));
15278 
15279 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15280 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15281 		return (EINVAL);
15282 
15283 	/*
15284 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15285 	 * to be sure that every CPU has seen it.  See below for the details
15286 	 * on why this is done.
15287 	 */
15288 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15289 	dtrace_sync();
15290 
15291 	/*
15292 	 * By this point, it is impossible for any CPU to be still processing
15293 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15294 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15295 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15296 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15297 	 * iff we're in the END probe.
15298 	 */
15299 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15300 	dtrace_sync();
15301 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15302 
15303 	/*
15304 	 * Finally, we can release the reserve and call the END probe.  We
15305 	 * disable interrupts across calling the END probe to allow us to
15306 	 * return the CPU on which we actually called the END probe.  This
15307 	 * allows user-land to be sure that this CPU's principal buffer is
15308 	 * processed last.
15309 	 */
15310 	state->dts_reserve = 0;
15311 
15312 	cookie = dtrace_interrupt_disable();
15313 	*cpu = curcpu;
15314 	dtrace_probe(dtrace_probeid_end,
15315 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15316 	dtrace_interrupt_enable(cookie);
15317 
15318 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15319 	dtrace_sync();
15320 
15321 #ifdef illumos
15322 	if (state->dts_getf != 0 &&
15323 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15324 		/*
15325 		 * We don't have kernel privs but we have at least one call
15326 		 * to getf(); we need to lower our zone's count, and (if
15327 		 * this is the last enabling to have an unprivileged call
15328 		 * to getf()) we need to clear the closef() hook.
15329 		 */
15330 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15331 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15332 		ASSERT(dtrace_getf > 0);
15333 
15334 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15335 
15336 		if (--dtrace_getf == 0)
15337 			dtrace_closef = NULL;
15338 	}
15339 #endif
15340 
15341 	return (0);
15342 }
15343 
15344 static int
15345 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15346     dtrace_optval_t val)
15347 {
15348 	ASSERT(MUTEX_HELD(&dtrace_lock));
15349 
15350 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15351 		return (EBUSY);
15352 
15353 	if (option >= DTRACEOPT_MAX)
15354 		return (EINVAL);
15355 
15356 	if (option != DTRACEOPT_CPU && val < 0)
15357 		return (EINVAL);
15358 
15359 	switch (option) {
15360 	case DTRACEOPT_DESTRUCTIVE:
15361 		if (dtrace_destructive_disallow)
15362 			return (EACCES);
15363 
15364 		state->dts_cred.dcr_destructive = 1;
15365 		break;
15366 
15367 	case DTRACEOPT_BUFSIZE:
15368 	case DTRACEOPT_DYNVARSIZE:
15369 	case DTRACEOPT_AGGSIZE:
15370 	case DTRACEOPT_SPECSIZE:
15371 	case DTRACEOPT_STRSIZE:
15372 		if (val < 0)
15373 			return (EINVAL);
15374 
15375 		if (val >= LONG_MAX) {
15376 			/*
15377 			 * If this is an otherwise negative value, set it to
15378 			 * the highest multiple of 128m less than LONG_MAX.
15379 			 * Technically, we're adjusting the size without
15380 			 * regard to the buffer resizing policy, but in fact,
15381 			 * this has no effect -- if we set the buffer size to
15382 			 * ~LONG_MAX and the buffer policy is ultimately set to
15383 			 * be "manual", the buffer allocation is guaranteed to
15384 			 * fail, if only because the allocation requires two
15385 			 * buffers.  (We set the the size to the highest
15386 			 * multiple of 128m because it ensures that the size
15387 			 * will remain a multiple of a megabyte when
15388 			 * repeatedly halved -- all the way down to 15m.)
15389 			 */
15390 			val = LONG_MAX - (1 << 27) + 1;
15391 		}
15392 	}
15393 
15394 	state->dts_options[option] = val;
15395 
15396 	return (0);
15397 }
15398 
15399 static void
15400 dtrace_state_destroy(dtrace_state_t *state)
15401 {
15402 	dtrace_ecb_t *ecb;
15403 	dtrace_vstate_t *vstate = &state->dts_vstate;
15404 #ifdef illumos
15405 	minor_t minor = getminor(state->dts_dev);
15406 #endif
15407 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15408 	dtrace_speculation_t *spec = state->dts_speculations;
15409 	int nspec = state->dts_nspeculations;
15410 	uint32_t match;
15411 
15412 	ASSERT(MUTEX_HELD(&dtrace_lock));
15413 	ASSERT(MUTEX_HELD(&cpu_lock));
15414 
15415 	/*
15416 	 * First, retract any retained enablings for this state.
15417 	 */
15418 	dtrace_enabling_retract(state);
15419 	ASSERT(state->dts_nretained == 0);
15420 
15421 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15422 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15423 		/*
15424 		 * We have managed to come into dtrace_state_destroy() on a
15425 		 * hot enabling -- almost certainly because of a disorderly
15426 		 * shutdown of a consumer.  (That is, a consumer that is
15427 		 * exiting without having called dtrace_stop().) In this case,
15428 		 * we're going to set our activity to be KILLED, and then
15429 		 * issue a sync to be sure that everyone is out of probe
15430 		 * context before we start blowing away ECBs.
15431 		 */
15432 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15433 		dtrace_sync();
15434 	}
15435 
15436 	/*
15437 	 * Release the credential hold we took in dtrace_state_create().
15438 	 */
15439 	if (state->dts_cred.dcr_cred != NULL)
15440 		crfree(state->dts_cred.dcr_cred);
15441 
15442 	/*
15443 	 * Now we can safely disable and destroy any enabled probes.  Because
15444 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15445 	 * (especially if they're all enabled), we take two passes through the
15446 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15447 	 * in the second we disable whatever is left over.
15448 	 */
15449 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15450 		for (i = 0; i < state->dts_necbs; i++) {
15451 			if ((ecb = state->dts_ecbs[i]) == NULL)
15452 				continue;
15453 
15454 			if (match && ecb->dte_probe != NULL) {
15455 				dtrace_probe_t *probe = ecb->dte_probe;
15456 				dtrace_provider_t *prov = probe->dtpr_provider;
15457 
15458 				if (!(prov->dtpv_priv.dtpp_flags & match))
15459 					continue;
15460 			}
15461 
15462 			dtrace_ecb_disable(ecb);
15463 			dtrace_ecb_destroy(ecb);
15464 		}
15465 
15466 		if (!match)
15467 			break;
15468 	}
15469 
15470 	/*
15471 	 * Before we free the buffers, perform one more sync to assure that
15472 	 * every CPU is out of probe context.
15473 	 */
15474 	dtrace_sync();
15475 
15476 	dtrace_buffer_free(state->dts_buffer);
15477 	dtrace_buffer_free(state->dts_aggbuffer);
15478 
15479 	for (i = 0; i < nspec; i++)
15480 		dtrace_buffer_free(spec[i].dtsp_buffer);
15481 
15482 #ifdef illumos
15483 	if (state->dts_cleaner != CYCLIC_NONE)
15484 		cyclic_remove(state->dts_cleaner);
15485 
15486 	if (state->dts_deadman != CYCLIC_NONE)
15487 		cyclic_remove(state->dts_deadman);
15488 #else
15489 	callout_stop(&state->dts_cleaner);
15490 	callout_drain(&state->dts_cleaner);
15491 	callout_stop(&state->dts_deadman);
15492 	callout_drain(&state->dts_deadman);
15493 #endif
15494 
15495 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15496 	dtrace_vstate_fini(vstate);
15497 	if (state->dts_ecbs != NULL)
15498 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15499 
15500 	if (state->dts_aggregations != NULL) {
15501 #ifdef DEBUG
15502 		for (i = 0; i < state->dts_naggregations; i++)
15503 			ASSERT(state->dts_aggregations[i] == NULL);
15504 #endif
15505 		ASSERT(state->dts_naggregations > 0);
15506 		kmem_free(state->dts_aggregations,
15507 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15508 	}
15509 
15510 	kmem_free(state->dts_buffer, bufsize);
15511 	kmem_free(state->dts_aggbuffer, bufsize);
15512 
15513 	for (i = 0; i < nspec; i++)
15514 		kmem_free(spec[i].dtsp_buffer, bufsize);
15515 
15516 	if (spec != NULL)
15517 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15518 
15519 	dtrace_format_destroy(state);
15520 
15521 	if (state->dts_aggid_arena != NULL) {
15522 #ifdef illumos
15523 		vmem_destroy(state->dts_aggid_arena);
15524 #else
15525 		delete_unrhdr(state->dts_aggid_arena);
15526 #endif
15527 		state->dts_aggid_arena = NULL;
15528 	}
15529 #ifdef illumos
15530 	ddi_soft_state_free(dtrace_softstate, minor);
15531 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15532 #endif
15533 }
15534 
15535 /*
15536  * DTrace Anonymous Enabling Functions
15537  */
15538 static dtrace_state_t *
15539 dtrace_anon_grab(void)
15540 {
15541 	dtrace_state_t *state;
15542 
15543 	ASSERT(MUTEX_HELD(&dtrace_lock));
15544 
15545 	if ((state = dtrace_anon.dta_state) == NULL) {
15546 		ASSERT(dtrace_anon.dta_enabling == NULL);
15547 		return (NULL);
15548 	}
15549 
15550 	ASSERT(dtrace_anon.dta_enabling != NULL);
15551 	ASSERT(dtrace_retained != NULL);
15552 
15553 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15554 	dtrace_anon.dta_enabling = NULL;
15555 	dtrace_anon.dta_state = NULL;
15556 
15557 	return (state);
15558 }
15559 
15560 static void
15561 dtrace_anon_property(void)
15562 {
15563 	int i, rv;
15564 	dtrace_state_t *state;
15565 	dof_hdr_t *dof;
15566 	char c[32];		/* enough for "dof-data-" + digits */
15567 
15568 	ASSERT(MUTEX_HELD(&dtrace_lock));
15569 	ASSERT(MUTEX_HELD(&cpu_lock));
15570 
15571 	for (i = 0; ; i++) {
15572 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15573 
15574 		dtrace_err_verbose = 1;
15575 
15576 		if ((dof = dtrace_dof_property(c)) == NULL) {
15577 			dtrace_err_verbose = 0;
15578 			break;
15579 		}
15580 
15581 #ifdef illumos
15582 		/*
15583 		 * We want to create anonymous state, so we need to transition
15584 		 * the kernel debugger to indicate that DTrace is active.  If
15585 		 * this fails (e.g. because the debugger has modified text in
15586 		 * some way), we won't continue with the processing.
15587 		 */
15588 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15589 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15590 			    "enabling ignored.");
15591 			dtrace_dof_destroy(dof);
15592 			break;
15593 		}
15594 #endif
15595 
15596 		/*
15597 		 * If we haven't allocated an anonymous state, we'll do so now.
15598 		 */
15599 		if ((state = dtrace_anon.dta_state) == NULL) {
15600 			state = dtrace_state_create(NULL, NULL);
15601 			dtrace_anon.dta_state = state;
15602 
15603 			if (state == NULL) {
15604 				/*
15605 				 * This basically shouldn't happen:  the only
15606 				 * failure mode from dtrace_state_create() is a
15607 				 * failure of ddi_soft_state_zalloc() that
15608 				 * itself should never happen.  Still, the
15609 				 * interface allows for a failure mode, and
15610 				 * we want to fail as gracefully as possible:
15611 				 * we'll emit an error message and cease
15612 				 * processing anonymous state in this case.
15613 				 */
15614 				cmn_err(CE_WARN, "failed to create "
15615 				    "anonymous state");
15616 				dtrace_dof_destroy(dof);
15617 				break;
15618 			}
15619 		}
15620 
15621 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15622 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15623 
15624 		if (rv == 0)
15625 			rv = dtrace_dof_options(dof, state);
15626 
15627 		dtrace_err_verbose = 0;
15628 		dtrace_dof_destroy(dof);
15629 
15630 		if (rv != 0) {
15631 			/*
15632 			 * This is malformed DOF; chuck any anonymous state
15633 			 * that we created.
15634 			 */
15635 			ASSERT(dtrace_anon.dta_enabling == NULL);
15636 			dtrace_state_destroy(state);
15637 			dtrace_anon.dta_state = NULL;
15638 			break;
15639 		}
15640 
15641 		ASSERT(dtrace_anon.dta_enabling != NULL);
15642 	}
15643 
15644 	if (dtrace_anon.dta_enabling != NULL) {
15645 		int rval;
15646 
15647 		/*
15648 		 * dtrace_enabling_retain() can only fail because we are
15649 		 * trying to retain more enablings than are allowed -- but
15650 		 * we only have one anonymous enabling, and we are guaranteed
15651 		 * to be allowed at least one retained enabling; we assert
15652 		 * that dtrace_enabling_retain() returns success.
15653 		 */
15654 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15655 		ASSERT(rval == 0);
15656 
15657 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15658 	}
15659 }
15660 
15661 /*
15662  * DTrace Helper Functions
15663  */
15664 static void
15665 dtrace_helper_trace(dtrace_helper_action_t *helper,
15666     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15667 {
15668 	uint32_t size, next, nnext, i;
15669 	dtrace_helptrace_t *ent, *buffer;
15670 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15671 
15672 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15673 		return;
15674 
15675 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15676 
15677 	/*
15678 	 * What would a tracing framework be without its own tracing
15679 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15680 	 */
15681 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15682 	    sizeof (uint64_t) - sizeof (uint64_t);
15683 
15684 	/*
15685 	 * Iterate until we can allocate a slot in the trace buffer.
15686 	 */
15687 	do {
15688 		next = dtrace_helptrace_next;
15689 
15690 		if (next + size < dtrace_helptrace_bufsize) {
15691 			nnext = next + size;
15692 		} else {
15693 			nnext = size;
15694 		}
15695 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15696 
15697 	/*
15698 	 * We have our slot; fill it in.
15699 	 */
15700 	if (nnext == size) {
15701 		dtrace_helptrace_wrapped++;
15702 		next = 0;
15703 	}
15704 
15705 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15706 	ent->dtht_helper = helper;
15707 	ent->dtht_where = where;
15708 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15709 
15710 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15711 	    mstate->dtms_fltoffs : -1;
15712 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15713 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15714 
15715 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15716 		dtrace_statvar_t *svar;
15717 
15718 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15719 			continue;
15720 
15721 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15722 		ent->dtht_locals[i] =
15723 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15724 	}
15725 }
15726 
15727 static uint64_t
15728 dtrace_helper(int which, dtrace_mstate_t *mstate,
15729     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15730 {
15731 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15732 	uint64_t sarg0 = mstate->dtms_arg[0];
15733 	uint64_t sarg1 = mstate->dtms_arg[1];
15734 	uint64_t rval = 0;
15735 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15736 	dtrace_helper_action_t *helper;
15737 	dtrace_vstate_t *vstate;
15738 	dtrace_difo_t *pred;
15739 	int i, trace = dtrace_helptrace_buffer != NULL;
15740 
15741 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15742 
15743 	if (helpers == NULL)
15744 		return (0);
15745 
15746 	if ((helper = helpers->dthps_actions[which]) == NULL)
15747 		return (0);
15748 
15749 	vstate = &helpers->dthps_vstate;
15750 	mstate->dtms_arg[0] = arg0;
15751 	mstate->dtms_arg[1] = arg1;
15752 
15753 	/*
15754 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15755 	 * we'll call the corresponding actions.  Note that the below calls
15756 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15757 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15758 	 * the stored DIF offset with its own (which is the desired behavior).
15759 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15760 	 * from machine state; this is okay, too.
15761 	 */
15762 	for (; helper != NULL; helper = helper->dtha_next) {
15763 		if ((pred = helper->dtha_predicate) != NULL) {
15764 			if (trace)
15765 				dtrace_helper_trace(helper, mstate, vstate, 0);
15766 
15767 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15768 				goto next;
15769 
15770 			if (*flags & CPU_DTRACE_FAULT)
15771 				goto err;
15772 		}
15773 
15774 		for (i = 0; i < helper->dtha_nactions; i++) {
15775 			if (trace)
15776 				dtrace_helper_trace(helper,
15777 				    mstate, vstate, i + 1);
15778 
15779 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15780 			    mstate, vstate, state);
15781 
15782 			if (*flags & CPU_DTRACE_FAULT)
15783 				goto err;
15784 		}
15785 
15786 next:
15787 		if (trace)
15788 			dtrace_helper_trace(helper, mstate, vstate,
15789 			    DTRACE_HELPTRACE_NEXT);
15790 	}
15791 
15792 	if (trace)
15793 		dtrace_helper_trace(helper, mstate, vstate,
15794 		    DTRACE_HELPTRACE_DONE);
15795 
15796 	/*
15797 	 * Restore the arg0 that we saved upon entry.
15798 	 */
15799 	mstate->dtms_arg[0] = sarg0;
15800 	mstate->dtms_arg[1] = sarg1;
15801 
15802 	return (rval);
15803 
15804 err:
15805 	if (trace)
15806 		dtrace_helper_trace(helper, mstate, vstate,
15807 		    DTRACE_HELPTRACE_ERR);
15808 
15809 	/*
15810 	 * Restore the arg0 that we saved upon entry.
15811 	 */
15812 	mstate->dtms_arg[0] = sarg0;
15813 	mstate->dtms_arg[1] = sarg1;
15814 
15815 	return (0);
15816 }
15817 
15818 static void
15819 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15820     dtrace_vstate_t *vstate)
15821 {
15822 	int i;
15823 
15824 	if (helper->dtha_predicate != NULL)
15825 		dtrace_difo_release(helper->dtha_predicate, vstate);
15826 
15827 	for (i = 0; i < helper->dtha_nactions; i++) {
15828 		ASSERT(helper->dtha_actions[i] != NULL);
15829 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15830 	}
15831 
15832 	kmem_free(helper->dtha_actions,
15833 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15834 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15835 }
15836 
15837 static int
15838 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15839 {
15840 	proc_t *p = curproc;
15841 	dtrace_vstate_t *vstate;
15842 	int i;
15843 
15844 	if (help == NULL)
15845 		help = p->p_dtrace_helpers;
15846 
15847 	ASSERT(MUTEX_HELD(&dtrace_lock));
15848 
15849 	if (help == NULL || gen > help->dthps_generation)
15850 		return (EINVAL);
15851 
15852 	vstate = &help->dthps_vstate;
15853 
15854 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15855 		dtrace_helper_action_t *last = NULL, *h, *next;
15856 
15857 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15858 			next = h->dtha_next;
15859 
15860 			if (h->dtha_generation == gen) {
15861 				if (last != NULL) {
15862 					last->dtha_next = next;
15863 				} else {
15864 					help->dthps_actions[i] = next;
15865 				}
15866 
15867 				dtrace_helper_action_destroy(h, vstate);
15868 			} else {
15869 				last = h;
15870 			}
15871 		}
15872 	}
15873 
15874 	/*
15875 	 * Interate until we've cleared out all helper providers with the
15876 	 * given generation number.
15877 	 */
15878 	for (;;) {
15879 		dtrace_helper_provider_t *prov;
15880 
15881 		/*
15882 		 * Look for a helper provider with the right generation. We
15883 		 * have to start back at the beginning of the list each time
15884 		 * because we drop dtrace_lock. It's unlikely that we'll make
15885 		 * more than two passes.
15886 		 */
15887 		for (i = 0; i < help->dthps_nprovs; i++) {
15888 			prov = help->dthps_provs[i];
15889 
15890 			if (prov->dthp_generation == gen)
15891 				break;
15892 		}
15893 
15894 		/*
15895 		 * If there were no matches, we're done.
15896 		 */
15897 		if (i == help->dthps_nprovs)
15898 			break;
15899 
15900 		/*
15901 		 * Move the last helper provider into this slot.
15902 		 */
15903 		help->dthps_nprovs--;
15904 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15905 		help->dthps_provs[help->dthps_nprovs] = NULL;
15906 
15907 		mutex_exit(&dtrace_lock);
15908 
15909 		/*
15910 		 * If we have a meta provider, remove this helper provider.
15911 		 */
15912 		mutex_enter(&dtrace_meta_lock);
15913 		if (dtrace_meta_pid != NULL) {
15914 			ASSERT(dtrace_deferred_pid == NULL);
15915 			dtrace_helper_provider_remove(&prov->dthp_prov,
15916 			    p->p_pid);
15917 		}
15918 		mutex_exit(&dtrace_meta_lock);
15919 
15920 		dtrace_helper_provider_destroy(prov);
15921 
15922 		mutex_enter(&dtrace_lock);
15923 	}
15924 
15925 	return (0);
15926 }
15927 
15928 static int
15929 dtrace_helper_validate(dtrace_helper_action_t *helper)
15930 {
15931 	int err = 0, i;
15932 	dtrace_difo_t *dp;
15933 
15934 	if ((dp = helper->dtha_predicate) != NULL)
15935 		err += dtrace_difo_validate_helper(dp);
15936 
15937 	for (i = 0; i < helper->dtha_nactions; i++)
15938 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15939 
15940 	return (err == 0);
15941 }
15942 
15943 static int
15944 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15945     dtrace_helpers_t *help)
15946 {
15947 	dtrace_helper_action_t *helper, *last;
15948 	dtrace_actdesc_t *act;
15949 	dtrace_vstate_t *vstate;
15950 	dtrace_predicate_t *pred;
15951 	int count = 0, nactions = 0, i;
15952 
15953 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15954 		return (EINVAL);
15955 
15956 	last = help->dthps_actions[which];
15957 	vstate = &help->dthps_vstate;
15958 
15959 	for (count = 0; last != NULL; last = last->dtha_next) {
15960 		count++;
15961 		if (last->dtha_next == NULL)
15962 			break;
15963 	}
15964 
15965 	/*
15966 	 * If we already have dtrace_helper_actions_max helper actions for this
15967 	 * helper action type, we'll refuse to add a new one.
15968 	 */
15969 	if (count >= dtrace_helper_actions_max)
15970 		return (ENOSPC);
15971 
15972 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15973 	helper->dtha_generation = help->dthps_generation;
15974 
15975 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15976 		ASSERT(pred->dtp_difo != NULL);
15977 		dtrace_difo_hold(pred->dtp_difo);
15978 		helper->dtha_predicate = pred->dtp_difo;
15979 	}
15980 
15981 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15982 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15983 			goto err;
15984 
15985 		if (act->dtad_difo == NULL)
15986 			goto err;
15987 
15988 		nactions++;
15989 	}
15990 
15991 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15992 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15993 
15994 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15995 		dtrace_difo_hold(act->dtad_difo);
15996 		helper->dtha_actions[i++] = act->dtad_difo;
15997 	}
15998 
15999 	if (!dtrace_helper_validate(helper))
16000 		goto err;
16001 
16002 	if (last == NULL) {
16003 		help->dthps_actions[which] = helper;
16004 	} else {
16005 		last->dtha_next = helper;
16006 	}
16007 
16008 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16009 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16010 		dtrace_helptrace_next = 0;
16011 	}
16012 
16013 	return (0);
16014 err:
16015 	dtrace_helper_action_destroy(helper, vstate);
16016 	return (EINVAL);
16017 }
16018 
16019 static void
16020 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16021     dof_helper_t *dofhp)
16022 {
16023 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16024 
16025 	mutex_enter(&dtrace_meta_lock);
16026 	mutex_enter(&dtrace_lock);
16027 
16028 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16029 		/*
16030 		 * If the dtrace module is loaded but not attached, or if
16031 		 * there aren't isn't a meta provider registered to deal with
16032 		 * these provider descriptions, we need to postpone creating
16033 		 * the actual providers until later.
16034 		 */
16035 
16036 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16037 		    dtrace_deferred_pid != help) {
16038 			help->dthps_deferred = 1;
16039 			help->dthps_pid = p->p_pid;
16040 			help->dthps_next = dtrace_deferred_pid;
16041 			help->dthps_prev = NULL;
16042 			if (dtrace_deferred_pid != NULL)
16043 				dtrace_deferred_pid->dthps_prev = help;
16044 			dtrace_deferred_pid = help;
16045 		}
16046 
16047 		mutex_exit(&dtrace_lock);
16048 
16049 	} else if (dofhp != NULL) {
16050 		/*
16051 		 * If the dtrace module is loaded and we have a particular
16052 		 * helper provider description, pass that off to the
16053 		 * meta provider.
16054 		 */
16055 
16056 		mutex_exit(&dtrace_lock);
16057 
16058 		dtrace_helper_provide(dofhp, p->p_pid);
16059 
16060 	} else {
16061 		/*
16062 		 * Otherwise, just pass all the helper provider descriptions
16063 		 * off to the meta provider.
16064 		 */
16065 
16066 		int i;
16067 		mutex_exit(&dtrace_lock);
16068 
16069 		for (i = 0; i < help->dthps_nprovs; i++) {
16070 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16071 			    p->p_pid);
16072 		}
16073 	}
16074 
16075 	mutex_exit(&dtrace_meta_lock);
16076 }
16077 
16078 static int
16079 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16080 {
16081 	dtrace_helper_provider_t *hprov, **tmp_provs;
16082 	uint_t tmp_maxprovs, i;
16083 
16084 	ASSERT(MUTEX_HELD(&dtrace_lock));
16085 	ASSERT(help != NULL);
16086 
16087 	/*
16088 	 * If we already have dtrace_helper_providers_max helper providers,
16089 	 * we're refuse to add a new one.
16090 	 */
16091 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16092 		return (ENOSPC);
16093 
16094 	/*
16095 	 * Check to make sure this isn't a duplicate.
16096 	 */
16097 	for (i = 0; i < help->dthps_nprovs; i++) {
16098 		if (dofhp->dofhp_addr ==
16099 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16100 			return (EALREADY);
16101 	}
16102 
16103 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16104 	hprov->dthp_prov = *dofhp;
16105 	hprov->dthp_ref = 1;
16106 	hprov->dthp_generation = gen;
16107 
16108 	/*
16109 	 * Allocate a bigger table for helper providers if it's already full.
16110 	 */
16111 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16112 		tmp_maxprovs = help->dthps_maxprovs;
16113 		tmp_provs = help->dthps_provs;
16114 
16115 		if (help->dthps_maxprovs == 0)
16116 			help->dthps_maxprovs = 2;
16117 		else
16118 			help->dthps_maxprovs *= 2;
16119 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16120 			help->dthps_maxprovs = dtrace_helper_providers_max;
16121 
16122 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16123 
16124 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16125 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16126 
16127 		if (tmp_provs != NULL) {
16128 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16129 			    sizeof (dtrace_helper_provider_t *));
16130 			kmem_free(tmp_provs, tmp_maxprovs *
16131 			    sizeof (dtrace_helper_provider_t *));
16132 		}
16133 	}
16134 
16135 	help->dthps_provs[help->dthps_nprovs] = hprov;
16136 	help->dthps_nprovs++;
16137 
16138 	return (0);
16139 }
16140 
16141 static void
16142 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16143 {
16144 	mutex_enter(&dtrace_lock);
16145 
16146 	if (--hprov->dthp_ref == 0) {
16147 		dof_hdr_t *dof;
16148 		mutex_exit(&dtrace_lock);
16149 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16150 		dtrace_dof_destroy(dof);
16151 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16152 	} else {
16153 		mutex_exit(&dtrace_lock);
16154 	}
16155 }
16156 
16157 static int
16158 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16159 {
16160 	uintptr_t daddr = (uintptr_t)dof;
16161 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16162 	dof_provider_t *provider;
16163 	dof_probe_t *probe;
16164 	uint8_t *arg;
16165 	char *strtab, *typestr;
16166 	dof_stridx_t typeidx;
16167 	size_t typesz;
16168 	uint_t nprobes, j, k;
16169 
16170 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16171 
16172 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16173 		dtrace_dof_error(dof, "misaligned section offset");
16174 		return (-1);
16175 	}
16176 
16177 	/*
16178 	 * The section needs to be large enough to contain the DOF provider
16179 	 * structure appropriate for the given version.
16180 	 */
16181 	if (sec->dofs_size <
16182 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16183 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16184 	    sizeof (dof_provider_t))) {
16185 		dtrace_dof_error(dof, "provider section too small");
16186 		return (-1);
16187 	}
16188 
16189 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16190 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16191 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16192 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16193 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16194 
16195 	if (str_sec == NULL || prb_sec == NULL ||
16196 	    arg_sec == NULL || off_sec == NULL)
16197 		return (-1);
16198 
16199 	enoff_sec = NULL;
16200 
16201 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16202 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16203 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16204 	    provider->dofpv_prenoffs)) == NULL)
16205 		return (-1);
16206 
16207 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16208 
16209 	if (provider->dofpv_name >= str_sec->dofs_size ||
16210 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16211 		dtrace_dof_error(dof, "invalid provider name");
16212 		return (-1);
16213 	}
16214 
16215 	if (prb_sec->dofs_entsize == 0 ||
16216 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16217 		dtrace_dof_error(dof, "invalid entry size");
16218 		return (-1);
16219 	}
16220 
16221 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16222 		dtrace_dof_error(dof, "misaligned entry size");
16223 		return (-1);
16224 	}
16225 
16226 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16227 		dtrace_dof_error(dof, "invalid entry size");
16228 		return (-1);
16229 	}
16230 
16231 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16232 		dtrace_dof_error(dof, "misaligned section offset");
16233 		return (-1);
16234 	}
16235 
16236 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16237 		dtrace_dof_error(dof, "invalid entry size");
16238 		return (-1);
16239 	}
16240 
16241 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16242 
16243 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16244 
16245 	/*
16246 	 * Take a pass through the probes to check for errors.
16247 	 */
16248 	for (j = 0; j < nprobes; j++) {
16249 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16250 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16251 
16252 		if (probe->dofpr_func >= str_sec->dofs_size) {
16253 			dtrace_dof_error(dof, "invalid function name");
16254 			return (-1);
16255 		}
16256 
16257 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16258 			dtrace_dof_error(dof, "function name too long");
16259 			/*
16260 			 * Keep going if the function name is too long.
16261 			 * Unlike provider and probe names, we cannot reasonably
16262 			 * impose restrictions on function names, since they're
16263 			 * a property of the code being instrumented. We will
16264 			 * skip this probe in dtrace_helper_provide_one().
16265 			 */
16266 		}
16267 
16268 		if (probe->dofpr_name >= str_sec->dofs_size ||
16269 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16270 			dtrace_dof_error(dof, "invalid probe name");
16271 			return (-1);
16272 		}
16273 
16274 		/*
16275 		 * The offset count must not wrap the index, and the offsets
16276 		 * must also not overflow the section's data.
16277 		 */
16278 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16279 		    probe->dofpr_offidx ||
16280 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16281 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16282 			dtrace_dof_error(dof, "invalid probe offset");
16283 			return (-1);
16284 		}
16285 
16286 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16287 			/*
16288 			 * If there's no is-enabled offset section, make sure
16289 			 * there aren't any is-enabled offsets. Otherwise
16290 			 * perform the same checks as for probe offsets
16291 			 * (immediately above).
16292 			 */
16293 			if (enoff_sec == NULL) {
16294 				if (probe->dofpr_enoffidx != 0 ||
16295 				    probe->dofpr_nenoffs != 0) {
16296 					dtrace_dof_error(dof, "is-enabled "
16297 					    "offsets with null section");
16298 					return (-1);
16299 				}
16300 			} else if (probe->dofpr_enoffidx +
16301 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16302 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16303 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16304 				dtrace_dof_error(dof, "invalid is-enabled "
16305 				    "offset");
16306 				return (-1);
16307 			}
16308 
16309 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16310 				dtrace_dof_error(dof, "zero probe and "
16311 				    "is-enabled offsets");
16312 				return (-1);
16313 			}
16314 		} else if (probe->dofpr_noffs == 0) {
16315 			dtrace_dof_error(dof, "zero probe offsets");
16316 			return (-1);
16317 		}
16318 
16319 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16320 		    probe->dofpr_argidx ||
16321 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16322 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16323 			dtrace_dof_error(dof, "invalid args");
16324 			return (-1);
16325 		}
16326 
16327 		typeidx = probe->dofpr_nargv;
16328 		typestr = strtab + probe->dofpr_nargv;
16329 		for (k = 0; k < probe->dofpr_nargc; k++) {
16330 			if (typeidx >= str_sec->dofs_size) {
16331 				dtrace_dof_error(dof, "bad "
16332 				    "native argument type");
16333 				return (-1);
16334 			}
16335 
16336 			typesz = strlen(typestr) + 1;
16337 			if (typesz > DTRACE_ARGTYPELEN) {
16338 				dtrace_dof_error(dof, "native "
16339 				    "argument type too long");
16340 				return (-1);
16341 			}
16342 			typeidx += typesz;
16343 			typestr += typesz;
16344 		}
16345 
16346 		typeidx = probe->dofpr_xargv;
16347 		typestr = strtab + probe->dofpr_xargv;
16348 		for (k = 0; k < probe->dofpr_xargc; k++) {
16349 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16350 				dtrace_dof_error(dof, "bad "
16351 				    "native argument index");
16352 				return (-1);
16353 			}
16354 
16355 			if (typeidx >= str_sec->dofs_size) {
16356 				dtrace_dof_error(dof, "bad "
16357 				    "translated argument type");
16358 				return (-1);
16359 			}
16360 
16361 			typesz = strlen(typestr) + 1;
16362 			if (typesz > DTRACE_ARGTYPELEN) {
16363 				dtrace_dof_error(dof, "translated argument "
16364 				    "type too long");
16365 				return (-1);
16366 			}
16367 
16368 			typeidx += typesz;
16369 			typestr += typesz;
16370 		}
16371 	}
16372 
16373 	return (0);
16374 }
16375 
16376 static int
16377 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16378 {
16379 	dtrace_helpers_t *help;
16380 	dtrace_vstate_t *vstate;
16381 	dtrace_enabling_t *enab = NULL;
16382 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16383 	uintptr_t daddr = (uintptr_t)dof;
16384 
16385 	ASSERT(MUTEX_HELD(&dtrace_lock));
16386 
16387 	if ((help = p->p_dtrace_helpers) == NULL)
16388 		help = dtrace_helpers_create(p);
16389 
16390 	vstate = &help->dthps_vstate;
16391 
16392 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16393 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16394 		dtrace_dof_destroy(dof);
16395 		return (rv);
16396 	}
16397 
16398 	/*
16399 	 * Look for helper providers and validate their descriptions.
16400 	 */
16401 	for (i = 0; i < dof->dofh_secnum; i++) {
16402 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16403 		    dof->dofh_secoff + i * dof->dofh_secsize);
16404 
16405 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16406 			continue;
16407 
16408 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16409 			dtrace_enabling_destroy(enab);
16410 			dtrace_dof_destroy(dof);
16411 			return (-1);
16412 		}
16413 
16414 		nprovs++;
16415 	}
16416 
16417 	/*
16418 	 * Now we need to walk through the ECB descriptions in the enabling.
16419 	 */
16420 	for (i = 0; i < enab->dten_ndesc; i++) {
16421 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16422 		dtrace_probedesc_t *desc = &ep->dted_probe;
16423 
16424 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16425 			continue;
16426 
16427 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16428 			continue;
16429 
16430 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16431 			continue;
16432 
16433 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16434 		    ep, help)) != 0) {
16435 			/*
16436 			 * Adding this helper action failed -- we are now going
16437 			 * to rip out the entire generation and return failure.
16438 			 */
16439 			(void) dtrace_helper_destroygen(help,
16440 			    help->dthps_generation);
16441 			dtrace_enabling_destroy(enab);
16442 			dtrace_dof_destroy(dof);
16443 			return (-1);
16444 		}
16445 
16446 		nhelpers++;
16447 	}
16448 
16449 	if (nhelpers < enab->dten_ndesc)
16450 		dtrace_dof_error(dof, "unmatched helpers");
16451 
16452 	gen = help->dthps_generation++;
16453 	dtrace_enabling_destroy(enab);
16454 
16455 	if (nprovs > 0) {
16456 		/*
16457 		 * Now that this is in-kernel, we change the sense of the
16458 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16459 		 * and dofhp_addr denotes the address at user-level.
16460 		 */
16461 		dhp->dofhp_addr = dhp->dofhp_dof;
16462 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16463 
16464 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16465 			mutex_exit(&dtrace_lock);
16466 			dtrace_helper_provider_register(p, help, dhp);
16467 			mutex_enter(&dtrace_lock);
16468 
16469 			destroy = 0;
16470 		}
16471 	}
16472 
16473 	if (destroy)
16474 		dtrace_dof_destroy(dof);
16475 
16476 	return (gen);
16477 }
16478 
16479 static dtrace_helpers_t *
16480 dtrace_helpers_create(proc_t *p)
16481 {
16482 	dtrace_helpers_t *help;
16483 
16484 	ASSERT(MUTEX_HELD(&dtrace_lock));
16485 	ASSERT(p->p_dtrace_helpers == NULL);
16486 
16487 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16488 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16489 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16490 
16491 	p->p_dtrace_helpers = help;
16492 	dtrace_helpers++;
16493 
16494 	return (help);
16495 }
16496 
16497 #ifdef illumos
16498 static
16499 #endif
16500 void
16501 dtrace_helpers_destroy(proc_t *p)
16502 {
16503 	dtrace_helpers_t *help;
16504 	dtrace_vstate_t *vstate;
16505 #ifdef illumos
16506 	proc_t *p = curproc;
16507 #endif
16508 	int i;
16509 
16510 	mutex_enter(&dtrace_lock);
16511 
16512 	ASSERT(p->p_dtrace_helpers != NULL);
16513 	ASSERT(dtrace_helpers > 0);
16514 
16515 	help = p->p_dtrace_helpers;
16516 	vstate = &help->dthps_vstate;
16517 
16518 	/*
16519 	 * We're now going to lose the help from this process.
16520 	 */
16521 	p->p_dtrace_helpers = NULL;
16522 	dtrace_sync();
16523 
16524 	/*
16525 	 * Destory the helper actions.
16526 	 */
16527 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16528 		dtrace_helper_action_t *h, *next;
16529 
16530 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16531 			next = h->dtha_next;
16532 			dtrace_helper_action_destroy(h, vstate);
16533 			h = next;
16534 		}
16535 	}
16536 
16537 	mutex_exit(&dtrace_lock);
16538 
16539 	/*
16540 	 * Destroy the helper providers.
16541 	 */
16542 	if (help->dthps_maxprovs > 0) {
16543 		mutex_enter(&dtrace_meta_lock);
16544 		if (dtrace_meta_pid != NULL) {
16545 			ASSERT(dtrace_deferred_pid == NULL);
16546 
16547 			for (i = 0; i < help->dthps_nprovs; i++) {
16548 				dtrace_helper_provider_remove(
16549 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16550 			}
16551 		} else {
16552 			mutex_enter(&dtrace_lock);
16553 			ASSERT(help->dthps_deferred == 0 ||
16554 			    help->dthps_next != NULL ||
16555 			    help->dthps_prev != NULL ||
16556 			    help == dtrace_deferred_pid);
16557 
16558 			/*
16559 			 * Remove the helper from the deferred list.
16560 			 */
16561 			if (help->dthps_next != NULL)
16562 				help->dthps_next->dthps_prev = help->dthps_prev;
16563 			if (help->dthps_prev != NULL)
16564 				help->dthps_prev->dthps_next = help->dthps_next;
16565 			if (dtrace_deferred_pid == help) {
16566 				dtrace_deferred_pid = help->dthps_next;
16567 				ASSERT(help->dthps_prev == NULL);
16568 			}
16569 
16570 			mutex_exit(&dtrace_lock);
16571 		}
16572 
16573 		mutex_exit(&dtrace_meta_lock);
16574 
16575 		for (i = 0; i < help->dthps_nprovs; i++) {
16576 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16577 		}
16578 
16579 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16580 		    sizeof (dtrace_helper_provider_t *));
16581 	}
16582 
16583 	mutex_enter(&dtrace_lock);
16584 
16585 	dtrace_vstate_fini(&help->dthps_vstate);
16586 	kmem_free(help->dthps_actions,
16587 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16588 	kmem_free(help, sizeof (dtrace_helpers_t));
16589 
16590 	--dtrace_helpers;
16591 	mutex_exit(&dtrace_lock);
16592 }
16593 
16594 #ifdef illumos
16595 static
16596 #endif
16597 void
16598 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16599 {
16600 	dtrace_helpers_t *help, *newhelp;
16601 	dtrace_helper_action_t *helper, *new, *last;
16602 	dtrace_difo_t *dp;
16603 	dtrace_vstate_t *vstate;
16604 	int i, j, sz, hasprovs = 0;
16605 
16606 	mutex_enter(&dtrace_lock);
16607 	ASSERT(from->p_dtrace_helpers != NULL);
16608 	ASSERT(dtrace_helpers > 0);
16609 
16610 	help = from->p_dtrace_helpers;
16611 	newhelp = dtrace_helpers_create(to);
16612 	ASSERT(to->p_dtrace_helpers != NULL);
16613 
16614 	newhelp->dthps_generation = help->dthps_generation;
16615 	vstate = &newhelp->dthps_vstate;
16616 
16617 	/*
16618 	 * Duplicate the helper actions.
16619 	 */
16620 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16621 		if ((helper = help->dthps_actions[i]) == NULL)
16622 			continue;
16623 
16624 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16625 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16626 			    KM_SLEEP);
16627 			new->dtha_generation = helper->dtha_generation;
16628 
16629 			if ((dp = helper->dtha_predicate) != NULL) {
16630 				dp = dtrace_difo_duplicate(dp, vstate);
16631 				new->dtha_predicate = dp;
16632 			}
16633 
16634 			new->dtha_nactions = helper->dtha_nactions;
16635 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16636 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16637 
16638 			for (j = 0; j < new->dtha_nactions; j++) {
16639 				dtrace_difo_t *dp = helper->dtha_actions[j];
16640 
16641 				ASSERT(dp != NULL);
16642 				dp = dtrace_difo_duplicate(dp, vstate);
16643 				new->dtha_actions[j] = dp;
16644 			}
16645 
16646 			if (last != NULL) {
16647 				last->dtha_next = new;
16648 			} else {
16649 				newhelp->dthps_actions[i] = new;
16650 			}
16651 
16652 			last = new;
16653 		}
16654 	}
16655 
16656 	/*
16657 	 * Duplicate the helper providers and register them with the
16658 	 * DTrace framework.
16659 	 */
16660 	if (help->dthps_nprovs > 0) {
16661 		newhelp->dthps_nprovs = help->dthps_nprovs;
16662 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16663 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16664 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16665 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16666 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16667 			newhelp->dthps_provs[i]->dthp_ref++;
16668 		}
16669 
16670 		hasprovs = 1;
16671 	}
16672 
16673 	mutex_exit(&dtrace_lock);
16674 
16675 	if (hasprovs)
16676 		dtrace_helper_provider_register(to, newhelp, NULL);
16677 }
16678 
16679 /*
16680  * DTrace Hook Functions
16681  */
16682 static void
16683 dtrace_module_loaded(modctl_t *ctl)
16684 {
16685 	dtrace_provider_t *prv;
16686 
16687 	mutex_enter(&dtrace_provider_lock);
16688 #ifdef illumos
16689 	mutex_enter(&mod_lock);
16690 #endif
16691 
16692 #ifdef illumos
16693 	ASSERT(ctl->mod_busy);
16694 #endif
16695 
16696 	/*
16697 	 * We're going to call each providers per-module provide operation
16698 	 * specifying only this module.
16699 	 */
16700 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16701 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16702 
16703 #ifdef illumos
16704 	mutex_exit(&mod_lock);
16705 #endif
16706 	mutex_exit(&dtrace_provider_lock);
16707 
16708 	/*
16709 	 * If we have any retained enablings, we need to match against them.
16710 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16711 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16712 	 * module.  (In particular, this happens when loading scheduling
16713 	 * classes.)  So if we have any retained enablings, we need to dispatch
16714 	 * our task queue to do the match for us.
16715 	 */
16716 	mutex_enter(&dtrace_lock);
16717 
16718 	if (dtrace_retained == NULL) {
16719 		mutex_exit(&dtrace_lock);
16720 		return;
16721 	}
16722 
16723 	(void) taskq_dispatch(dtrace_taskq,
16724 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16725 
16726 	mutex_exit(&dtrace_lock);
16727 
16728 	/*
16729 	 * And now, for a little heuristic sleaze:  in general, we want to
16730 	 * match modules as soon as they load.  However, we cannot guarantee
16731 	 * this, because it would lead us to the lock ordering violation
16732 	 * outlined above.  The common case, of course, is that cpu_lock is
16733 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16734 	 * long enough for the task queue to do its work.  If it's not, it's
16735 	 * not a serious problem -- it just means that the module that we
16736 	 * just loaded may not be immediately instrumentable.
16737 	 */
16738 	delay(1);
16739 }
16740 
16741 static void
16742 #ifdef illumos
16743 dtrace_module_unloaded(modctl_t *ctl)
16744 #else
16745 dtrace_module_unloaded(modctl_t *ctl, int *error)
16746 #endif
16747 {
16748 	dtrace_probe_t template, *probe, *first, *next;
16749 	dtrace_provider_t *prov;
16750 #ifndef illumos
16751 	char modname[DTRACE_MODNAMELEN];
16752 	size_t len;
16753 #endif
16754 
16755 #ifdef illumos
16756 	template.dtpr_mod = ctl->mod_modname;
16757 #else
16758 	/* Handle the fact that ctl->filename may end in ".ko". */
16759 	strlcpy(modname, ctl->filename, sizeof(modname));
16760 	len = strlen(ctl->filename);
16761 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16762 		modname[len - 3] = '\0';
16763 	template.dtpr_mod = modname;
16764 #endif
16765 
16766 	mutex_enter(&dtrace_provider_lock);
16767 #ifdef illumos
16768 	mutex_enter(&mod_lock);
16769 #endif
16770 	mutex_enter(&dtrace_lock);
16771 
16772 #ifndef illumos
16773 	if (ctl->nenabled > 0) {
16774 		/* Don't allow unloads if a probe is enabled. */
16775 		mutex_exit(&dtrace_provider_lock);
16776 		mutex_exit(&dtrace_lock);
16777 		*error = -1;
16778 		printf(
16779 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16780 		return;
16781 	}
16782 #endif
16783 
16784 	if (dtrace_bymod == NULL) {
16785 		/*
16786 		 * The DTrace module is loaded (obviously) but not attached;
16787 		 * we don't have any work to do.
16788 		 */
16789 		mutex_exit(&dtrace_provider_lock);
16790 #ifdef illumos
16791 		mutex_exit(&mod_lock);
16792 #endif
16793 		mutex_exit(&dtrace_lock);
16794 		return;
16795 	}
16796 
16797 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16798 	    probe != NULL; probe = probe->dtpr_nextmod) {
16799 		if (probe->dtpr_ecb != NULL) {
16800 			mutex_exit(&dtrace_provider_lock);
16801 #ifdef illumos
16802 			mutex_exit(&mod_lock);
16803 #endif
16804 			mutex_exit(&dtrace_lock);
16805 
16806 			/*
16807 			 * This shouldn't _actually_ be possible -- we're
16808 			 * unloading a module that has an enabled probe in it.
16809 			 * (It's normally up to the provider to make sure that
16810 			 * this can't happen.)  However, because dtps_enable()
16811 			 * doesn't have a failure mode, there can be an
16812 			 * enable/unload race.  Upshot:  we don't want to
16813 			 * assert, but we're not going to disable the
16814 			 * probe, either.
16815 			 */
16816 			if (dtrace_err_verbose) {
16817 #ifdef illumos
16818 				cmn_err(CE_WARN, "unloaded module '%s' had "
16819 				    "enabled probes", ctl->mod_modname);
16820 #else
16821 				cmn_err(CE_WARN, "unloaded module '%s' had "
16822 				    "enabled probes", modname);
16823 #endif
16824 			}
16825 
16826 			return;
16827 		}
16828 	}
16829 
16830 	probe = first;
16831 
16832 	for (first = NULL; probe != NULL; probe = next) {
16833 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16834 
16835 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16836 
16837 		next = probe->dtpr_nextmod;
16838 		dtrace_hash_remove(dtrace_bymod, probe);
16839 		dtrace_hash_remove(dtrace_byfunc, probe);
16840 		dtrace_hash_remove(dtrace_byname, probe);
16841 
16842 		if (first == NULL) {
16843 			first = probe;
16844 			probe->dtpr_nextmod = NULL;
16845 		} else {
16846 			probe->dtpr_nextmod = first;
16847 			first = probe;
16848 		}
16849 	}
16850 
16851 	/*
16852 	 * We've removed all of the module's probes from the hash chains and
16853 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16854 	 * everyone has cleared out from any probe array processing.
16855 	 */
16856 	dtrace_sync();
16857 
16858 	for (probe = first; probe != NULL; probe = first) {
16859 		first = probe->dtpr_nextmod;
16860 		prov = probe->dtpr_provider;
16861 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16862 		    probe->dtpr_arg);
16863 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16864 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16865 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16866 #ifdef illumos
16867 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16868 #else
16869 		free_unr(dtrace_arena, probe->dtpr_id);
16870 #endif
16871 		kmem_free(probe, sizeof (dtrace_probe_t));
16872 	}
16873 
16874 	mutex_exit(&dtrace_lock);
16875 #ifdef illumos
16876 	mutex_exit(&mod_lock);
16877 #endif
16878 	mutex_exit(&dtrace_provider_lock);
16879 }
16880 
16881 #ifndef illumos
16882 static void
16883 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16884 {
16885 
16886 	dtrace_module_loaded(lf);
16887 }
16888 
16889 static void
16890 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16891 {
16892 
16893 	if (*error != 0)
16894 		/* We already have an error, so don't do anything. */
16895 		return;
16896 	dtrace_module_unloaded(lf, error);
16897 }
16898 #endif
16899 
16900 #ifdef illumos
16901 static void
16902 dtrace_suspend(void)
16903 {
16904 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16905 }
16906 
16907 static void
16908 dtrace_resume(void)
16909 {
16910 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16911 }
16912 #endif
16913 
16914 static int
16915 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16916 {
16917 	ASSERT(MUTEX_HELD(&cpu_lock));
16918 	mutex_enter(&dtrace_lock);
16919 
16920 	switch (what) {
16921 	case CPU_CONFIG: {
16922 		dtrace_state_t *state;
16923 		dtrace_optval_t *opt, rs, c;
16924 
16925 		/*
16926 		 * For now, we only allocate a new buffer for anonymous state.
16927 		 */
16928 		if ((state = dtrace_anon.dta_state) == NULL)
16929 			break;
16930 
16931 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16932 			break;
16933 
16934 		opt = state->dts_options;
16935 		c = opt[DTRACEOPT_CPU];
16936 
16937 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16938 			break;
16939 
16940 		/*
16941 		 * Regardless of what the actual policy is, we're going to
16942 		 * temporarily set our resize policy to be manual.  We're
16943 		 * also going to temporarily set our CPU option to denote
16944 		 * the newly configured CPU.
16945 		 */
16946 		rs = opt[DTRACEOPT_BUFRESIZE];
16947 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16948 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16949 
16950 		(void) dtrace_state_buffers(state);
16951 
16952 		opt[DTRACEOPT_BUFRESIZE] = rs;
16953 		opt[DTRACEOPT_CPU] = c;
16954 
16955 		break;
16956 	}
16957 
16958 	case CPU_UNCONFIG:
16959 		/*
16960 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16961 		 * buffer will be freed when the consumer exits.)
16962 		 */
16963 		break;
16964 
16965 	default:
16966 		break;
16967 	}
16968 
16969 	mutex_exit(&dtrace_lock);
16970 	return (0);
16971 }
16972 
16973 #ifdef illumos
16974 static void
16975 dtrace_cpu_setup_initial(processorid_t cpu)
16976 {
16977 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16978 }
16979 #endif
16980 
16981 static void
16982 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16983 {
16984 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16985 		int osize, nsize;
16986 		dtrace_toxrange_t *range;
16987 
16988 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16989 
16990 		if (osize == 0) {
16991 			ASSERT(dtrace_toxrange == NULL);
16992 			ASSERT(dtrace_toxranges_max == 0);
16993 			dtrace_toxranges_max = 1;
16994 		} else {
16995 			dtrace_toxranges_max <<= 1;
16996 		}
16997 
16998 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16999 		range = kmem_zalloc(nsize, KM_SLEEP);
17000 
17001 		if (dtrace_toxrange != NULL) {
17002 			ASSERT(osize != 0);
17003 			bcopy(dtrace_toxrange, range, osize);
17004 			kmem_free(dtrace_toxrange, osize);
17005 		}
17006 
17007 		dtrace_toxrange = range;
17008 	}
17009 
17010 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17011 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17012 
17013 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17014 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17015 	dtrace_toxranges++;
17016 }
17017 
17018 static void
17019 dtrace_getf_barrier(void)
17020 {
17021 #ifdef illumos
17022 	/*
17023 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17024 	 * that contain calls to getf(), this routine will be called on every
17025 	 * closef() before either the underlying vnode is released or the
17026 	 * file_t itself is freed.  By the time we are here, it is essential
17027 	 * that the file_t can no longer be accessed from a call to getf()
17028 	 * in probe context -- that assures that a dtrace_sync() can be used
17029 	 * to clear out any enablings referring to the old structures.
17030 	 */
17031 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17032 	    kcred->cr_zone->zone_dtrace_getf != 0)
17033 		dtrace_sync();
17034 #endif
17035 }
17036 
17037 /*
17038  * DTrace Driver Cookbook Functions
17039  */
17040 #ifdef illumos
17041 /*ARGSUSED*/
17042 static int
17043 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17044 {
17045 	dtrace_provider_id_t id;
17046 	dtrace_state_t *state = NULL;
17047 	dtrace_enabling_t *enab;
17048 
17049 	mutex_enter(&cpu_lock);
17050 	mutex_enter(&dtrace_provider_lock);
17051 	mutex_enter(&dtrace_lock);
17052 
17053 	if (ddi_soft_state_init(&dtrace_softstate,
17054 	    sizeof (dtrace_state_t), 0) != 0) {
17055 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17056 		mutex_exit(&cpu_lock);
17057 		mutex_exit(&dtrace_provider_lock);
17058 		mutex_exit(&dtrace_lock);
17059 		return (DDI_FAILURE);
17060 	}
17061 
17062 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17063 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17064 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17065 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17066 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17067 		ddi_remove_minor_node(devi, NULL);
17068 		ddi_soft_state_fini(&dtrace_softstate);
17069 		mutex_exit(&cpu_lock);
17070 		mutex_exit(&dtrace_provider_lock);
17071 		mutex_exit(&dtrace_lock);
17072 		return (DDI_FAILURE);
17073 	}
17074 
17075 	ddi_report_dev(devi);
17076 	dtrace_devi = devi;
17077 
17078 	dtrace_modload = dtrace_module_loaded;
17079 	dtrace_modunload = dtrace_module_unloaded;
17080 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17081 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17082 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17083 	dtrace_cpustart_init = dtrace_suspend;
17084 	dtrace_cpustart_fini = dtrace_resume;
17085 	dtrace_debugger_init = dtrace_suspend;
17086 	dtrace_debugger_fini = dtrace_resume;
17087 
17088 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17089 
17090 	ASSERT(MUTEX_HELD(&cpu_lock));
17091 
17092 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17093 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17094 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17095 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17096 	    VM_SLEEP | VMC_IDENTIFIER);
17097 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17098 	    1, INT_MAX, 0);
17099 
17100 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17101 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17102 	    NULL, NULL, NULL, NULL, NULL, 0);
17103 
17104 	ASSERT(MUTEX_HELD(&cpu_lock));
17105 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17106 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17107 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17108 
17109 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17110 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17111 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17112 
17113 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17114 	    offsetof(dtrace_probe_t, dtpr_nextname),
17115 	    offsetof(dtrace_probe_t, dtpr_prevname));
17116 
17117 	if (dtrace_retain_max < 1) {
17118 		cmn_err(CE_WARN, "illegal value (%zu) for dtrace_retain_max; "
17119 		    "setting to 1", dtrace_retain_max);
17120 		dtrace_retain_max = 1;
17121 	}
17122 
17123 	/*
17124 	 * Now discover our toxic ranges.
17125 	 */
17126 	dtrace_toxic_ranges(dtrace_toxrange_add);
17127 
17128 	/*
17129 	 * Before we register ourselves as a provider to our own framework,
17130 	 * we would like to assert that dtrace_provider is NULL -- but that's
17131 	 * not true if we were loaded as a dependency of a DTrace provider.
17132 	 * Once we've registered, we can assert that dtrace_provider is our
17133 	 * pseudo provider.
17134 	 */
17135 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17136 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17137 
17138 	ASSERT(dtrace_provider != NULL);
17139 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17140 
17141 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17142 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17143 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17144 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17145 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17146 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17147 
17148 	dtrace_anon_property();
17149 	mutex_exit(&cpu_lock);
17150 
17151 	/*
17152 	 * If there are already providers, we must ask them to provide their
17153 	 * probes, and then match any anonymous enabling against them.  Note
17154 	 * that there should be no other retained enablings at this time:
17155 	 * the only retained enablings at this time should be the anonymous
17156 	 * enabling.
17157 	 */
17158 	if (dtrace_anon.dta_enabling != NULL) {
17159 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17160 
17161 		dtrace_enabling_provide(NULL);
17162 		state = dtrace_anon.dta_state;
17163 
17164 		/*
17165 		 * We couldn't hold cpu_lock across the above call to
17166 		 * dtrace_enabling_provide(), but we must hold it to actually
17167 		 * enable the probes.  We have to drop all of our locks, pick
17168 		 * up cpu_lock, and regain our locks before matching the
17169 		 * retained anonymous enabling.
17170 		 */
17171 		mutex_exit(&dtrace_lock);
17172 		mutex_exit(&dtrace_provider_lock);
17173 
17174 		mutex_enter(&cpu_lock);
17175 		mutex_enter(&dtrace_provider_lock);
17176 		mutex_enter(&dtrace_lock);
17177 
17178 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17179 			(void) dtrace_enabling_match(enab, NULL);
17180 
17181 		mutex_exit(&cpu_lock);
17182 	}
17183 
17184 	mutex_exit(&dtrace_lock);
17185 	mutex_exit(&dtrace_provider_lock);
17186 
17187 	if (state != NULL) {
17188 		/*
17189 		 * If we created any anonymous state, set it going now.
17190 		 */
17191 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17192 	}
17193 
17194 	return (DDI_SUCCESS);
17195 }
17196 #endif	/* illumos */
17197 
17198 #ifndef illumos
17199 static void dtrace_dtr(void *);
17200 #endif
17201 
17202 /*ARGSUSED*/
17203 static int
17204 #ifdef illumos
17205 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17206 #else
17207 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17208 #endif
17209 {
17210 	dtrace_state_t *state;
17211 	uint32_t priv;
17212 	uid_t uid;
17213 	zoneid_t zoneid;
17214 
17215 #ifdef illumos
17216 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17217 		return (0);
17218 
17219 	/*
17220 	 * If this wasn't an open with the "helper" minor, then it must be
17221 	 * the "dtrace" minor.
17222 	 */
17223 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17224 		return (ENXIO);
17225 #else
17226 	cred_t *cred_p = NULL;
17227 	cred_p = dev->si_cred;
17228 
17229 	/*
17230 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17231 	 * caller lacks sufficient permission to do anything with DTrace.
17232 	 */
17233 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17234 	if (priv == DTRACE_PRIV_NONE) {
17235 #endif
17236 
17237 		return (EACCES);
17238 	}
17239 
17240 	/*
17241 	 * Ask all providers to provide all their probes.
17242 	 */
17243 	mutex_enter(&dtrace_provider_lock);
17244 	dtrace_probe_provide(NULL, NULL);
17245 	mutex_exit(&dtrace_provider_lock);
17246 
17247 	mutex_enter(&cpu_lock);
17248 	mutex_enter(&dtrace_lock);
17249 	dtrace_opens++;
17250 	dtrace_membar_producer();
17251 
17252 #ifdef illumos
17253 	/*
17254 	 * If the kernel debugger is active (that is, if the kernel debugger
17255 	 * modified text in some way), we won't allow the open.
17256 	 */
17257 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17258 		dtrace_opens--;
17259 		mutex_exit(&cpu_lock);
17260 		mutex_exit(&dtrace_lock);
17261 		return (EBUSY);
17262 	}
17263 
17264 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17265 		/*
17266 		 * If DTrace helper tracing is enabled, we need to allocate the
17267 		 * trace buffer and initialize the values.
17268 		 */
17269 		dtrace_helptrace_buffer =
17270 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17271 		dtrace_helptrace_next = 0;
17272 		dtrace_helptrace_wrapped = 0;
17273 		dtrace_helptrace_enable = 0;
17274 	}
17275 
17276 	state = dtrace_state_create(devp, cred_p);
17277 #else
17278 	state = dtrace_state_create(dev, NULL);
17279 	devfs_set_cdevpriv(state, dtrace_dtr);
17280 #endif
17281 
17282 	mutex_exit(&cpu_lock);
17283 
17284 	if (state == NULL) {
17285 #ifdef illumos
17286 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17287 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17288 #else
17289 		--dtrace_opens;
17290 #endif
17291 		mutex_exit(&dtrace_lock);
17292 		return (EAGAIN);
17293 	}
17294 
17295 	mutex_exit(&dtrace_lock);
17296 
17297 	return (0);
17298 }
17299 
17300 /*ARGSUSED*/
17301 #ifdef illumos
17302 static int
17303 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17304 #else
17305 static void
17306 dtrace_dtr(void *data)
17307 #endif
17308 {
17309 #ifdef illumos
17310 	minor_t minor = getminor(dev);
17311 	dtrace_state_t *state;
17312 #endif
17313 	dtrace_helptrace_t *buf = NULL;
17314 
17315 #ifdef illumos
17316 	if (minor == DTRACEMNRN_HELPER)
17317 		return (0);
17318 
17319 	state = ddi_get_soft_state(dtrace_softstate, minor);
17320 #else
17321 	dtrace_state_t *state = data;
17322 #endif
17323 
17324 	mutex_enter(&cpu_lock);
17325 	mutex_enter(&dtrace_lock);
17326 
17327 #ifdef illumos
17328 	if (state->dts_anon)
17329 #else
17330 	if (state != NULL && state->dts_anon)
17331 #endif
17332 	{
17333 		/*
17334 		 * There is anonymous state. Destroy that first.
17335 		 */
17336 		ASSERT(dtrace_anon.dta_state == NULL);
17337 		dtrace_state_destroy(state->dts_anon);
17338 	}
17339 
17340 	if (dtrace_helptrace_disable) {
17341 		/*
17342 		 * If we have been told to disable helper tracing, set the
17343 		 * buffer to NULL before calling into dtrace_state_destroy();
17344 		 * we take advantage of its dtrace_sync() to know that no
17345 		 * CPU is in probe context with enabled helper tracing
17346 		 * after it returns.
17347 		 */
17348 		buf = dtrace_helptrace_buffer;
17349 		dtrace_helptrace_buffer = NULL;
17350 	}
17351 
17352 #ifdef illumos
17353 	dtrace_state_destroy(state);
17354 #else
17355 	if (state != NULL) {
17356 		dtrace_state_destroy(state);
17357 		kmem_free(state, 0);
17358 	}
17359 #endif
17360 	ASSERT(dtrace_opens > 0);
17361 
17362 #ifdef illumos
17363 	/*
17364 	 * Only relinquish control of the kernel debugger interface when there
17365 	 * are no consumers and no anonymous enablings.
17366 	 */
17367 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17368 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17369 #else
17370 	--dtrace_opens;
17371 #endif
17372 
17373 	if (buf != NULL) {
17374 		kmem_free(buf, dtrace_helptrace_bufsize);
17375 		dtrace_helptrace_disable = 0;
17376 	}
17377 
17378 	mutex_exit(&dtrace_lock);
17379 	mutex_exit(&cpu_lock);
17380 
17381 #ifdef illumos
17382 	return (0);
17383 #endif
17384 }
17385 
17386 #ifdef illumos
17387 /*ARGSUSED*/
17388 static int
17389 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17390 {
17391 	int rval;
17392 	dof_helper_t help, *dhp = NULL;
17393 
17394 	switch (cmd) {
17395 	case DTRACEHIOC_ADDDOF:
17396 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17397 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17398 			return (EFAULT);
17399 		}
17400 
17401 		dhp = &help;
17402 		arg = (intptr_t)help.dofhp_dof;
17403 		/*FALLTHROUGH*/
17404 
17405 	case DTRACEHIOC_ADD: {
17406 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17407 
17408 		if (dof == NULL)
17409 			return (rval);
17410 
17411 		mutex_enter(&dtrace_lock);
17412 
17413 		/*
17414 		 * dtrace_helper_slurp() takes responsibility for the dof --
17415 		 * it may free it now or it may save it and free it later.
17416 		 */
17417 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17418 			*rv = rval;
17419 			rval = 0;
17420 		} else {
17421 			rval = EINVAL;
17422 		}
17423 
17424 		mutex_exit(&dtrace_lock);
17425 		return (rval);
17426 	}
17427 
17428 	case DTRACEHIOC_REMOVE: {
17429 		mutex_enter(&dtrace_lock);
17430 		rval = dtrace_helper_destroygen(NULL, arg);
17431 		mutex_exit(&dtrace_lock);
17432 
17433 		return (rval);
17434 	}
17435 
17436 	default:
17437 		break;
17438 	}
17439 
17440 	return (ENOTTY);
17441 }
17442 
17443 /*ARGSUSED*/
17444 static int
17445 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17446 {
17447 	minor_t minor = getminor(dev);
17448 	dtrace_state_t *state;
17449 	int rval;
17450 
17451 	if (minor == DTRACEMNRN_HELPER)
17452 		return (dtrace_ioctl_helper(cmd, arg, rv));
17453 
17454 	state = ddi_get_soft_state(dtrace_softstate, minor);
17455 
17456 	if (state->dts_anon) {
17457 		ASSERT(dtrace_anon.dta_state == NULL);
17458 		state = state->dts_anon;
17459 	}
17460 
17461 	switch (cmd) {
17462 	case DTRACEIOC_PROVIDER: {
17463 		dtrace_providerdesc_t pvd;
17464 		dtrace_provider_t *pvp;
17465 
17466 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17467 			return (EFAULT);
17468 
17469 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17470 		mutex_enter(&dtrace_provider_lock);
17471 
17472 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17473 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17474 				break;
17475 		}
17476 
17477 		mutex_exit(&dtrace_provider_lock);
17478 
17479 		if (pvp == NULL)
17480 			return (ESRCH);
17481 
17482 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17483 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17484 
17485 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17486 			return (EFAULT);
17487 
17488 		return (0);
17489 	}
17490 
17491 	case DTRACEIOC_EPROBE: {
17492 		dtrace_eprobedesc_t epdesc;
17493 		dtrace_ecb_t *ecb;
17494 		dtrace_action_t *act;
17495 		void *buf;
17496 		size_t size;
17497 		uintptr_t dest;
17498 		int nrecs;
17499 
17500 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17501 			return (EFAULT);
17502 
17503 		mutex_enter(&dtrace_lock);
17504 
17505 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17506 			mutex_exit(&dtrace_lock);
17507 			return (EINVAL);
17508 		}
17509 
17510 		if (ecb->dte_probe == NULL) {
17511 			mutex_exit(&dtrace_lock);
17512 			return (EINVAL);
17513 		}
17514 
17515 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17516 		epdesc.dtepd_uarg = ecb->dte_uarg;
17517 		epdesc.dtepd_size = ecb->dte_size;
17518 
17519 		nrecs = epdesc.dtepd_nrecs;
17520 		epdesc.dtepd_nrecs = 0;
17521 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17522 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17523 				continue;
17524 
17525 			epdesc.dtepd_nrecs++;
17526 		}
17527 
17528 		/*
17529 		 * Now that we have the size, we need to allocate a temporary
17530 		 * buffer in which to store the complete description.  We need
17531 		 * the temporary buffer to be able to drop dtrace_lock()
17532 		 * across the copyout(), below.
17533 		 */
17534 		size = sizeof (dtrace_eprobedesc_t) +
17535 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17536 
17537 		buf = kmem_alloc(size, KM_SLEEP);
17538 		dest = (uintptr_t)buf;
17539 
17540 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17541 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17542 
17543 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17544 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17545 				continue;
17546 
17547 			if (nrecs-- == 0)
17548 				break;
17549 
17550 			bcopy(&act->dta_rec, (void *)dest,
17551 			    sizeof (dtrace_recdesc_t));
17552 			dest += sizeof (dtrace_recdesc_t);
17553 		}
17554 
17555 		mutex_exit(&dtrace_lock);
17556 
17557 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17558 			kmem_free(buf, size);
17559 			return (EFAULT);
17560 		}
17561 
17562 		kmem_free(buf, size);
17563 		return (0);
17564 	}
17565 
17566 	case DTRACEIOC_AGGDESC: {
17567 		dtrace_aggdesc_t aggdesc;
17568 		dtrace_action_t *act;
17569 		dtrace_aggregation_t *agg;
17570 		int nrecs;
17571 		uint32_t offs;
17572 		dtrace_recdesc_t *lrec;
17573 		void *buf;
17574 		size_t size;
17575 		uintptr_t dest;
17576 
17577 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17578 			return (EFAULT);
17579 
17580 		mutex_enter(&dtrace_lock);
17581 
17582 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17583 			mutex_exit(&dtrace_lock);
17584 			return (EINVAL);
17585 		}
17586 
17587 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17588 
17589 		nrecs = aggdesc.dtagd_nrecs;
17590 		aggdesc.dtagd_nrecs = 0;
17591 
17592 		offs = agg->dtag_base;
17593 		lrec = &agg->dtag_action.dta_rec;
17594 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17595 
17596 		for (act = agg->dtag_first; ; act = act->dta_next) {
17597 			ASSERT(act->dta_intuple ||
17598 			    DTRACEACT_ISAGG(act->dta_kind));
17599 
17600 			/*
17601 			 * If this action has a record size of zero, it
17602 			 * denotes an argument to the aggregating action.
17603 			 * Because the presence of this record doesn't (or
17604 			 * shouldn't) affect the way the data is interpreted,
17605 			 * we don't copy it out to save user-level the
17606 			 * confusion of dealing with a zero-length record.
17607 			 */
17608 			if (act->dta_rec.dtrd_size == 0) {
17609 				ASSERT(agg->dtag_hasarg);
17610 				continue;
17611 			}
17612 
17613 			aggdesc.dtagd_nrecs++;
17614 
17615 			if (act == &agg->dtag_action)
17616 				break;
17617 		}
17618 
17619 		/*
17620 		 * Now that we have the size, we need to allocate a temporary
17621 		 * buffer in which to store the complete description.  We need
17622 		 * the temporary buffer to be able to drop dtrace_lock()
17623 		 * across the copyout(), below.
17624 		 */
17625 		size = sizeof (dtrace_aggdesc_t) +
17626 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17627 
17628 		buf = kmem_alloc(size, KM_SLEEP);
17629 		dest = (uintptr_t)buf;
17630 
17631 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17632 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17633 
17634 		for (act = agg->dtag_first; ; act = act->dta_next) {
17635 			dtrace_recdesc_t rec = act->dta_rec;
17636 
17637 			/*
17638 			 * See the comment in the above loop for why we pass
17639 			 * over zero-length records.
17640 			 */
17641 			if (rec.dtrd_size == 0) {
17642 				ASSERT(agg->dtag_hasarg);
17643 				continue;
17644 			}
17645 
17646 			if (nrecs-- == 0)
17647 				break;
17648 
17649 			rec.dtrd_offset -= offs;
17650 			bcopy(&rec, (void *)dest, sizeof (rec));
17651 			dest += sizeof (dtrace_recdesc_t);
17652 
17653 			if (act == &agg->dtag_action)
17654 				break;
17655 		}
17656 
17657 		mutex_exit(&dtrace_lock);
17658 
17659 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17660 			kmem_free(buf, size);
17661 			return (EFAULT);
17662 		}
17663 
17664 		kmem_free(buf, size);
17665 		return (0);
17666 	}
17667 
17668 	case DTRACEIOC_ENABLE: {
17669 		dof_hdr_t *dof;
17670 		dtrace_enabling_t *enab = NULL;
17671 		dtrace_vstate_t *vstate;
17672 		int err = 0;
17673 
17674 		*rv = 0;
17675 
17676 		/*
17677 		 * If a NULL argument has been passed, we take this as our
17678 		 * cue to reevaluate our enablings.
17679 		 */
17680 		if (arg == NULL) {
17681 			dtrace_enabling_matchall();
17682 
17683 			return (0);
17684 		}
17685 
17686 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17687 			return (rval);
17688 
17689 		mutex_enter(&cpu_lock);
17690 		mutex_enter(&dtrace_lock);
17691 		vstate = &state->dts_vstate;
17692 
17693 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17694 			mutex_exit(&dtrace_lock);
17695 			mutex_exit(&cpu_lock);
17696 			dtrace_dof_destroy(dof);
17697 			return (EBUSY);
17698 		}
17699 
17700 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17701 			mutex_exit(&dtrace_lock);
17702 			mutex_exit(&cpu_lock);
17703 			dtrace_dof_destroy(dof);
17704 			return (EINVAL);
17705 		}
17706 
17707 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17708 			dtrace_enabling_destroy(enab);
17709 			mutex_exit(&dtrace_lock);
17710 			mutex_exit(&cpu_lock);
17711 			dtrace_dof_destroy(dof);
17712 			return (rval);
17713 		}
17714 
17715 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17716 			err = dtrace_enabling_retain(enab);
17717 		} else {
17718 			dtrace_enabling_destroy(enab);
17719 		}
17720 
17721 		mutex_exit(&cpu_lock);
17722 		mutex_exit(&dtrace_lock);
17723 		dtrace_dof_destroy(dof);
17724 
17725 		return (err);
17726 	}
17727 
17728 	case DTRACEIOC_REPLICATE: {
17729 		dtrace_repldesc_t desc;
17730 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17731 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17732 		int err;
17733 
17734 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17735 			return (EFAULT);
17736 
17737 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17738 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17739 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17740 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17741 
17742 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17743 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17744 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17745 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17746 
17747 		mutex_enter(&dtrace_lock);
17748 		err = dtrace_enabling_replicate(state, match, create);
17749 		mutex_exit(&dtrace_lock);
17750 
17751 		return (err);
17752 	}
17753 
17754 	case DTRACEIOC_PROBEMATCH:
17755 	case DTRACEIOC_PROBES: {
17756 		dtrace_probe_t *probe = NULL;
17757 		dtrace_probedesc_t desc;
17758 		dtrace_probekey_t pkey;
17759 		dtrace_id_t i;
17760 		int m = 0;
17761 		uint32_t priv;
17762 		uid_t uid;
17763 		zoneid_t zoneid;
17764 
17765 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17766 			return (EFAULT);
17767 
17768 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17769 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17770 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17771 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17772 
17773 		/*
17774 		 * Before we attempt to match this probe, we want to give
17775 		 * all providers the opportunity to provide it.
17776 		 */
17777 		if (desc.dtpd_id == DTRACE_IDNONE) {
17778 			mutex_enter(&dtrace_provider_lock);
17779 			dtrace_probe_provide(&desc, NULL);
17780 			mutex_exit(&dtrace_provider_lock);
17781 			desc.dtpd_id++;
17782 		}
17783 
17784 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17785 			dtrace_probekey(&desc, &pkey);
17786 			pkey.dtpk_id = DTRACE_IDNONE;
17787 		}
17788 
17789 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17790 
17791 		mutex_enter(&dtrace_lock);
17792 
17793 		if (cmd == DTRACEIOC_PROBEMATCH) {
17794 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17795 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17796 				    (m = dtrace_match_probe(probe, &pkey,
17797 				    priv, uid, zoneid)) != 0)
17798 					break;
17799 			}
17800 
17801 			if (m < 0) {
17802 				mutex_exit(&dtrace_lock);
17803 				return (EINVAL);
17804 			}
17805 
17806 		} else {
17807 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17808 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17809 				    dtrace_match_priv(probe, priv, uid, zoneid))
17810 					break;
17811 			}
17812 		}
17813 
17814 		if (probe == NULL) {
17815 			mutex_exit(&dtrace_lock);
17816 			return (ESRCH);
17817 		}
17818 
17819 		dtrace_probe_description(probe, &desc);
17820 		mutex_exit(&dtrace_lock);
17821 
17822 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17823 			return (EFAULT);
17824 
17825 		return (0);
17826 	}
17827 
17828 	case DTRACEIOC_PROBEARG: {
17829 		dtrace_argdesc_t desc;
17830 		dtrace_probe_t *probe;
17831 		dtrace_provider_t *prov;
17832 
17833 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17834 			return (EFAULT);
17835 
17836 		if (desc.dtargd_id == DTRACE_IDNONE)
17837 			return (EINVAL);
17838 
17839 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17840 			return (EINVAL);
17841 
17842 		mutex_enter(&dtrace_provider_lock);
17843 		mutex_enter(&mod_lock);
17844 		mutex_enter(&dtrace_lock);
17845 
17846 		if (desc.dtargd_id > dtrace_nprobes) {
17847 			mutex_exit(&dtrace_lock);
17848 			mutex_exit(&mod_lock);
17849 			mutex_exit(&dtrace_provider_lock);
17850 			return (EINVAL);
17851 		}
17852 
17853 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17854 			mutex_exit(&dtrace_lock);
17855 			mutex_exit(&mod_lock);
17856 			mutex_exit(&dtrace_provider_lock);
17857 			return (EINVAL);
17858 		}
17859 
17860 		mutex_exit(&dtrace_lock);
17861 
17862 		prov = probe->dtpr_provider;
17863 
17864 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17865 			/*
17866 			 * There isn't any typed information for this probe.
17867 			 * Set the argument number to DTRACE_ARGNONE.
17868 			 */
17869 			desc.dtargd_ndx = DTRACE_ARGNONE;
17870 		} else {
17871 			desc.dtargd_native[0] = '\0';
17872 			desc.dtargd_xlate[0] = '\0';
17873 			desc.dtargd_mapping = desc.dtargd_ndx;
17874 
17875 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17876 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17877 		}
17878 
17879 		mutex_exit(&mod_lock);
17880 		mutex_exit(&dtrace_provider_lock);
17881 
17882 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17883 			return (EFAULT);
17884 
17885 		return (0);
17886 	}
17887 
17888 	case DTRACEIOC_GO: {
17889 		processorid_t cpuid;
17890 		rval = dtrace_state_go(state, &cpuid);
17891 
17892 		if (rval != 0)
17893 			return (rval);
17894 
17895 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17896 			return (EFAULT);
17897 
17898 		return (0);
17899 	}
17900 
17901 	case DTRACEIOC_STOP: {
17902 		processorid_t cpuid;
17903 
17904 		mutex_enter(&dtrace_lock);
17905 		rval = dtrace_state_stop(state, &cpuid);
17906 		mutex_exit(&dtrace_lock);
17907 
17908 		if (rval != 0)
17909 			return (rval);
17910 
17911 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17912 			return (EFAULT);
17913 
17914 		return (0);
17915 	}
17916 
17917 	case DTRACEIOC_DOFGET: {
17918 		dof_hdr_t hdr, *dof;
17919 		uint64_t len;
17920 
17921 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17922 			return (EFAULT);
17923 
17924 		mutex_enter(&dtrace_lock);
17925 		dof = dtrace_dof_create(state);
17926 		mutex_exit(&dtrace_lock);
17927 
17928 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17929 		rval = copyout(dof, (void *)arg, len);
17930 		dtrace_dof_destroy(dof);
17931 
17932 		return (rval == 0 ? 0 : EFAULT);
17933 	}
17934 
17935 	case DTRACEIOC_AGGSNAP:
17936 	case DTRACEIOC_BUFSNAP: {
17937 		dtrace_bufdesc_t desc;
17938 		caddr_t cached;
17939 		dtrace_buffer_t *buf;
17940 
17941 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17942 			return (EFAULT);
17943 
17944 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17945 			return (EINVAL);
17946 
17947 		mutex_enter(&dtrace_lock);
17948 
17949 		if (cmd == DTRACEIOC_BUFSNAP) {
17950 			buf = &state->dts_buffer[desc.dtbd_cpu];
17951 		} else {
17952 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17953 		}
17954 
17955 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17956 			size_t sz = buf->dtb_offset;
17957 
17958 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17959 				mutex_exit(&dtrace_lock);
17960 				return (EBUSY);
17961 			}
17962 
17963 			/*
17964 			 * If this buffer has already been consumed, we're
17965 			 * going to indicate that there's nothing left here
17966 			 * to consume.
17967 			 */
17968 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17969 				mutex_exit(&dtrace_lock);
17970 
17971 				desc.dtbd_size = 0;
17972 				desc.dtbd_drops = 0;
17973 				desc.dtbd_errors = 0;
17974 				desc.dtbd_oldest = 0;
17975 				sz = sizeof (desc);
17976 
17977 				if (copyout(&desc, (void *)arg, sz) != 0)
17978 					return (EFAULT);
17979 
17980 				return (0);
17981 			}
17982 
17983 			/*
17984 			 * If this is a ring buffer that has wrapped, we want
17985 			 * to copy the whole thing out.
17986 			 */
17987 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17988 				dtrace_buffer_polish(buf);
17989 				sz = buf->dtb_size;
17990 			}
17991 
17992 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17993 				mutex_exit(&dtrace_lock);
17994 				return (EFAULT);
17995 			}
17996 
17997 			desc.dtbd_size = sz;
17998 			desc.dtbd_drops = buf->dtb_drops;
17999 			desc.dtbd_errors = buf->dtb_errors;
18000 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18001 			desc.dtbd_timestamp = dtrace_gethrtime();
18002 
18003 			mutex_exit(&dtrace_lock);
18004 
18005 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18006 				return (EFAULT);
18007 
18008 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18009 
18010 			return (0);
18011 		}
18012 
18013 		if (buf->dtb_tomax == NULL) {
18014 			ASSERT(buf->dtb_xamot == NULL);
18015 			mutex_exit(&dtrace_lock);
18016 			return (ENOENT);
18017 		}
18018 
18019 		cached = buf->dtb_tomax;
18020 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18021 
18022 		dtrace_xcall(desc.dtbd_cpu,
18023 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18024 
18025 		state->dts_errors += buf->dtb_xamot_errors;
18026 
18027 		/*
18028 		 * If the buffers did not actually switch, then the cross call
18029 		 * did not take place -- presumably because the given CPU is
18030 		 * not in the ready set.  If this is the case, we'll return
18031 		 * ENOENT.
18032 		 */
18033 		if (buf->dtb_tomax == cached) {
18034 			ASSERT(buf->dtb_xamot != cached);
18035 			mutex_exit(&dtrace_lock);
18036 			return (ENOENT);
18037 		}
18038 
18039 		ASSERT(cached == buf->dtb_xamot);
18040 
18041 		/*
18042 		 * We have our snapshot; now copy it out.
18043 		 */
18044 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18045 		    buf->dtb_xamot_offset) != 0) {
18046 			mutex_exit(&dtrace_lock);
18047 			return (EFAULT);
18048 		}
18049 
18050 		desc.dtbd_size = buf->dtb_xamot_offset;
18051 		desc.dtbd_drops = buf->dtb_xamot_drops;
18052 		desc.dtbd_errors = buf->dtb_xamot_errors;
18053 		desc.dtbd_oldest = 0;
18054 		desc.dtbd_timestamp = buf->dtb_switched;
18055 
18056 		mutex_exit(&dtrace_lock);
18057 
18058 		/*
18059 		 * Finally, copy out the buffer description.
18060 		 */
18061 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18062 			return (EFAULT);
18063 
18064 		return (0);
18065 	}
18066 
18067 	case DTRACEIOC_CONF: {
18068 		dtrace_conf_t conf;
18069 
18070 		bzero(&conf, sizeof (conf));
18071 		conf.dtc_difversion = DIF_VERSION;
18072 		conf.dtc_difintregs = DIF_DIR_NREGS;
18073 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18074 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18075 
18076 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18077 			return (EFAULT);
18078 
18079 		return (0);
18080 	}
18081 
18082 	case DTRACEIOC_STATUS: {
18083 		dtrace_status_t stat;
18084 		dtrace_dstate_t *dstate;
18085 		int i, j;
18086 		uint64_t nerrs;
18087 
18088 		/*
18089 		 * See the comment in dtrace_state_deadman() for the reason
18090 		 * for setting dts_laststatus to INT64_MAX before setting
18091 		 * it to the correct value.
18092 		 */
18093 		state->dts_laststatus = INT64_MAX;
18094 		dtrace_membar_producer();
18095 		state->dts_laststatus = dtrace_gethrtime();
18096 
18097 		bzero(&stat, sizeof (stat));
18098 
18099 		mutex_enter(&dtrace_lock);
18100 
18101 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18102 			mutex_exit(&dtrace_lock);
18103 			return (ENOENT);
18104 		}
18105 
18106 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18107 			stat.dtst_exiting = 1;
18108 
18109 		nerrs = state->dts_errors;
18110 		dstate = &state->dts_vstate.dtvs_dynvars;
18111 
18112 		for (i = 0; i < NCPU; i++) {
18113 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18114 
18115 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18116 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18117 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18118 
18119 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18120 				stat.dtst_filled++;
18121 
18122 			nerrs += state->dts_buffer[i].dtb_errors;
18123 
18124 			for (j = 0; j < state->dts_nspeculations; j++) {
18125 				dtrace_speculation_t *spec;
18126 				dtrace_buffer_t *buf;
18127 
18128 				spec = &state->dts_speculations[j];
18129 				buf = &spec->dtsp_buffer[i];
18130 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18131 			}
18132 		}
18133 
18134 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18135 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18136 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18137 		stat.dtst_dblerrors = state->dts_dblerrors;
18138 		stat.dtst_killed =
18139 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18140 		stat.dtst_errors = nerrs;
18141 
18142 		mutex_exit(&dtrace_lock);
18143 
18144 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18145 			return (EFAULT);
18146 
18147 		return (0);
18148 	}
18149 
18150 	case DTRACEIOC_FORMAT: {
18151 		dtrace_fmtdesc_t fmt;
18152 		char *str;
18153 		int len;
18154 
18155 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18156 			return (EFAULT);
18157 
18158 		mutex_enter(&dtrace_lock);
18159 
18160 		if (fmt.dtfd_format == 0 ||
18161 		    fmt.dtfd_format > state->dts_nformats) {
18162 			mutex_exit(&dtrace_lock);
18163 			return (EINVAL);
18164 		}
18165 
18166 		/*
18167 		 * Format strings are allocated contiguously and they are
18168 		 * never freed; if a format index is less than the number
18169 		 * of formats, we can assert that the format map is non-NULL
18170 		 * and that the format for the specified index is non-NULL.
18171 		 */
18172 		ASSERT(state->dts_formats != NULL);
18173 		str = state->dts_formats[fmt.dtfd_format - 1];
18174 		ASSERT(str != NULL);
18175 
18176 		len = strlen(str) + 1;
18177 
18178 		if (len > fmt.dtfd_length) {
18179 			fmt.dtfd_length = len;
18180 
18181 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18182 				mutex_exit(&dtrace_lock);
18183 				return (EINVAL);
18184 			}
18185 		} else {
18186 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18187 				mutex_exit(&dtrace_lock);
18188 				return (EINVAL);
18189 			}
18190 		}
18191 
18192 		mutex_exit(&dtrace_lock);
18193 		return (0);
18194 	}
18195 
18196 	default:
18197 		break;
18198 	}
18199 
18200 	return (ENOTTY);
18201 }
18202 
18203 /*ARGSUSED*/
18204 static int
18205 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18206 {
18207 	dtrace_state_t *state;
18208 
18209 	switch (cmd) {
18210 	case DDI_DETACH:
18211 		break;
18212 
18213 	case DDI_SUSPEND:
18214 		return (DDI_SUCCESS);
18215 
18216 	default:
18217 		return (DDI_FAILURE);
18218 	}
18219 
18220 	mutex_enter(&cpu_lock);
18221 	mutex_enter(&dtrace_provider_lock);
18222 	mutex_enter(&dtrace_lock);
18223 
18224 	ASSERT(dtrace_opens == 0);
18225 
18226 	if (dtrace_helpers > 0) {
18227 		mutex_exit(&dtrace_provider_lock);
18228 		mutex_exit(&dtrace_lock);
18229 		mutex_exit(&cpu_lock);
18230 		return (DDI_FAILURE);
18231 	}
18232 
18233 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18234 		mutex_exit(&dtrace_provider_lock);
18235 		mutex_exit(&dtrace_lock);
18236 		mutex_exit(&cpu_lock);
18237 		return (DDI_FAILURE);
18238 	}
18239 
18240 	dtrace_provider = NULL;
18241 
18242 	if ((state = dtrace_anon_grab()) != NULL) {
18243 		/*
18244 		 * If there were ECBs on this state, the provider should
18245 		 * have not been allowed to detach; assert that there is
18246 		 * none.
18247 		 */
18248 		ASSERT(state->dts_necbs == 0);
18249 		dtrace_state_destroy(state);
18250 
18251 		/*
18252 		 * If we're being detached with anonymous state, we need to
18253 		 * indicate to the kernel debugger that DTrace is now inactive.
18254 		 */
18255 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18256 	}
18257 
18258 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18259 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18260 	dtrace_cpu_init = NULL;
18261 	dtrace_helpers_cleanup = NULL;
18262 	dtrace_helpers_fork = NULL;
18263 	dtrace_cpustart_init = NULL;
18264 	dtrace_cpustart_fini = NULL;
18265 	dtrace_debugger_init = NULL;
18266 	dtrace_debugger_fini = NULL;
18267 	dtrace_modload = NULL;
18268 	dtrace_modunload = NULL;
18269 
18270 	ASSERT(dtrace_getf == 0);
18271 	ASSERT(dtrace_closef == NULL);
18272 
18273 	mutex_exit(&cpu_lock);
18274 
18275 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18276 	dtrace_probes = NULL;
18277 	dtrace_nprobes = 0;
18278 
18279 	dtrace_hash_destroy(dtrace_bymod);
18280 	dtrace_hash_destroy(dtrace_byfunc);
18281 	dtrace_hash_destroy(dtrace_byname);
18282 	dtrace_bymod = NULL;
18283 	dtrace_byfunc = NULL;
18284 	dtrace_byname = NULL;
18285 
18286 	kmem_cache_destroy(dtrace_state_cache);
18287 	vmem_destroy(dtrace_minor);
18288 	vmem_destroy(dtrace_arena);
18289 
18290 	if (dtrace_toxrange != NULL) {
18291 		kmem_free(dtrace_toxrange,
18292 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18293 		dtrace_toxrange = NULL;
18294 		dtrace_toxranges = 0;
18295 		dtrace_toxranges_max = 0;
18296 	}
18297 
18298 	ddi_remove_minor_node(dtrace_devi, NULL);
18299 	dtrace_devi = NULL;
18300 
18301 	ddi_soft_state_fini(&dtrace_softstate);
18302 
18303 	ASSERT(dtrace_vtime_references == 0);
18304 	ASSERT(dtrace_opens == 0);
18305 	ASSERT(dtrace_retained == NULL);
18306 
18307 	mutex_exit(&dtrace_lock);
18308 	mutex_exit(&dtrace_provider_lock);
18309 
18310 	/*
18311 	 * We don't destroy the task queue until after we have dropped our
18312 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18313 	 * attempting to do work after we have effectively detached but before
18314 	 * the task queue has been destroyed, all tasks dispatched via the
18315 	 * task queue must check that DTrace is still attached before
18316 	 * performing any operation.
18317 	 */
18318 	taskq_destroy(dtrace_taskq);
18319 	dtrace_taskq = NULL;
18320 
18321 	return (DDI_SUCCESS);
18322 }
18323 #endif
18324 
18325 #ifdef illumos
18326 /*ARGSUSED*/
18327 static int
18328 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18329 {
18330 	int error;
18331 
18332 	switch (infocmd) {
18333 	case DDI_INFO_DEVT2DEVINFO:
18334 		*result = (void *)dtrace_devi;
18335 		error = DDI_SUCCESS;
18336 		break;
18337 	case DDI_INFO_DEVT2INSTANCE:
18338 		*result = (void *)0;
18339 		error = DDI_SUCCESS;
18340 		break;
18341 	default:
18342 		error = DDI_FAILURE;
18343 	}
18344 	return (error);
18345 }
18346 #endif
18347 
18348 #ifdef illumos
18349 static struct cb_ops dtrace_cb_ops = {
18350 	dtrace_open,		/* open */
18351 	dtrace_close,		/* close */
18352 	nulldev,		/* strategy */
18353 	nulldev,		/* print */
18354 	nodev,			/* dump */
18355 	nodev,			/* read */
18356 	nodev,			/* write */
18357 	dtrace_ioctl,		/* ioctl */
18358 	nodev,			/* devmap */
18359 	nodev,			/* mmap */
18360 	nodev,			/* segmap */
18361 	nochpoll,		/* poll */
18362 	ddi_prop_op,		/* cb_prop_op */
18363 	0,			/* streamtab  */
18364 	D_NEW | D_MP		/* Driver compatibility flag */
18365 };
18366 
18367 static struct dev_ops dtrace_ops = {
18368 	DEVO_REV,		/* devo_rev */
18369 	0,			/* refcnt */
18370 	dtrace_info,		/* get_dev_info */
18371 	nulldev,		/* identify */
18372 	nulldev,		/* probe */
18373 	dtrace_attach,		/* attach */
18374 	dtrace_detach,		/* detach */
18375 	nodev,			/* reset */
18376 	&dtrace_cb_ops,		/* driver operations */
18377 	NULL,			/* bus operations */
18378 	nodev			/* dev power */
18379 };
18380 
18381 static struct modldrv modldrv = {
18382 	&mod_driverops,		/* module type (this is a pseudo driver) */
18383 	"Dynamic Tracing",	/* name of module */
18384 	&dtrace_ops,		/* driver ops */
18385 };
18386 
18387 static struct modlinkage modlinkage = {
18388 	MODREV_1,
18389 	(void *)&modldrv,
18390 	NULL
18391 };
18392 
18393 int
18394 _init(void)
18395 {
18396 	return (mod_install(&modlinkage));
18397 }
18398 
18399 int
18400 _info(struct modinfo *modinfop)
18401 {
18402 	return (mod_info(&modlinkage, modinfop));
18403 }
18404 
18405 int
18406 _fini(void)
18407 {
18408 	return (mod_remove(&modlinkage));
18409 }
18410 #else
18411 
18412 static d_ioctl_t	dtrace_ioctl;
18413 static d_ioctl_t	dtrace_ioctl_helper;
18414 static void		dtrace_load(void *);
18415 static int		dtrace_unload(void);
18416 static struct cdev	*dtrace_dev;
18417 static struct cdev	*helper_dev;
18418 
18419 void dtrace_invop_init(void);
18420 void dtrace_invop_uninit(void);
18421 
18422 static struct cdevsw dtrace_cdevsw = {
18423 	.d_version	= D_VERSION,
18424 	.d_ioctl	= dtrace_ioctl,
18425 	.d_open		= dtrace_open,
18426 	.d_name		= "dtrace",
18427 };
18428 
18429 static struct cdevsw helper_cdevsw = {
18430 	.d_version	= D_VERSION,
18431 	.d_ioctl	= dtrace_ioctl_helper,
18432 	.d_name		= "helper",
18433 };
18434 
18435 #include <dtrace_anon.c>
18436 #include <dtrace_ioctl.c>
18437 #include <dtrace_load.c>
18438 #include <dtrace_modevent.c>
18439 #include <dtrace_sysctl.c>
18440 #include <dtrace_unload.c>
18441 #include <dtrace_vtime.c>
18442 #include <dtrace_hacks.c>
18443 #include <dtrace_isa.c>
18444 
18445 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18446 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18447 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18448 
18449 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18450 MODULE_VERSION(dtrace, 1);
18451 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18452 #endif
18453