1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2016, Joyent, Inc. All rights reserved.
25  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
26  */
27 
28 /*
29  * DTrace - Dynamic Tracing for Solaris
30  *
31  * This is the implementation of the Solaris Dynamic Tracing framework
32  * (DTrace).  The user-visible interface to DTrace is described at length in
33  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
34  * library, the in-kernel DTrace framework, and the DTrace providers are
35  * described in the block comments in the <sys/dtrace.h> header file.  The
36  * internal architecture of DTrace is described in the block comments in the
37  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
38  * implementation very much assume mastery of all of these sources; if one has
39  * an unanswered question about the implementation, one should consult them
40  * first.
41  *
42  * The functions here are ordered roughly as follows:
43  *
44  *   - Probe context functions
45  *   - Probe hashing functions
46  *   - Non-probe context utility functions
47  *   - Matching functions
48  *   - Provider-to-Framework API functions
49  *   - Probe management functions
50  *   - DIF object functions
51  *   - Format functions
52  *   - Predicate functions
53  *   - ECB functions
54  *   - Buffer functions
55  *   - Enabling functions
56  *   - DOF functions
57  *   - Anonymous enabling functions
58  *   - Consumer state functions
59  *   - Helper functions
60  *   - Hook functions
61  *   - Driver cookbook functions
62  *
63  * Each group of functions begins with a block comment labelled the "DTrace
64  * [Group] Functions", allowing one to find each block by searching forward
65  * on capital-f functions.
66  */
67 #include <sys/errno.h>
68 #include <sys/param.h>
69 #include <sys/types.h>
70 #ifndef illumos
71 #include <sys/time.h>
72 #endif
73 #include <sys/stat.h>
74 #include <sys/conf.h>
75 #include <sys/systm.h>
76 #include <sys/endian.h>
77 #ifdef illumos
78 #include <sys/ddi.h>
79 #include <sys/sunddi.h>
80 #endif
81 #include <sys/cpuvar.h>
82 #include <sys/kmem.h>
83 #ifdef illumos
84 #include <sys/strsubr.h>
85 #endif
86 #include <sys/sysmacros.h>
87 #include <sys/dtrace_impl.h>
88 #include <sys/atomic.h>
89 #include <sys/cmn_err.h>
90 #ifdef illumos
91 #include <sys/mutex_impl.h>
92 #include <sys/rwlock_impl.h>
93 #endif
94 #include <sys/ctf_api.h>
95 #ifdef illumos
96 #include <sys/panic.h>
97 #include <sys/priv_impl.h>
98 #endif
99 #ifdef illumos
100 #include <sys/cred_impl.h>
101 #include <sys/procfs_isa.h>
102 #endif
103 #include <sys/taskq.h>
104 #ifdef illumos
105 #include <sys/mkdev.h>
106 #include <sys/kdi.h>
107 #endif
108 #include <sys/zone.h>
109 #include <sys/socket.h>
110 #include <netinet/in.h>
111 #include "strtolctype.h"
112 
113 /* FreeBSD includes: */
114 #ifndef illumos
115 #include <sys/callout.h>
116 #include <sys/ctype.h>
117 #include <sys/eventhandler.h>
118 #include <sys/limits.h>
119 #include <sys/linker.h>
120 #include <sys/kdb.h>
121 #include <sys/jail.h>
122 #include <sys/kernel.h>
123 #include <sys/malloc.h>
124 #include <sys/lock.h>
125 #include <sys/mutex.h>
126 #include <sys/ptrace.h>
127 #include <sys/random.h>
128 #include <sys/rwlock.h>
129 #include <sys/sx.h>
130 #include <sys/sysctl.h>
131 
132 
133 #include <sys/mount.h>
134 #undef AT_UID
135 #undef AT_GID
136 #include <sys/vnode.h>
137 #include <sys/cred.h>
138 
139 #include <sys/dtrace_bsd.h>
140 
141 #include <netinet/in.h>
142 
143 #include "dtrace_cddl.h"
144 #include "dtrace_debug.c"
145 #endif
146 
147 #include "dtrace_xoroshiro128_plus.h"
148 
149 /*
150  * DTrace Tunable Variables
151  *
152  * The following variables may be tuned by adding a line to /etc/system that
153  * includes both the name of the DTrace module ("dtrace") and the name of the
154  * variable.  For example:
155  *
156  *   set dtrace:dtrace_destructive_disallow = 1
157  *
158  * In general, the only variables that one should be tuning this way are those
159  * that affect system-wide DTrace behavior, and for which the default behavior
160  * is undesirable.  Most of these variables are tunable on a per-consumer
161  * basis using DTrace options, and need not be tuned on a system-wide basis.
162  * When tuning these variables, avoid pathological values; while some attempt
163  * is made to verify the integrity of these variables, they are not considered
164  * part of the supported interface to DTrace, and they are therefore not
165  * checked comprehensively.  Further, these variables should not be tuned
166  * dynamically via "mdb -kw" or other means; they should only be tuned via
167  * /etc/system.
168  */
169 int		dtrace_destructive_disallow = 0;
170 #ifndef illumos
171 /* Positive logic version of dtrace_destructive_disallow for loader tunable */
172 int		dtrace_allow_destructive = 1;
173 #endif
174 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
175 size_t		dtrace_difo_maxsize = (256 * 1024);
176 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
177 size_t		dtrace_statvar_maxsize = (16 * 1024);
178 size_t		dtrace_actions_max = (16 * 1024);
179 size_t		dtrace_retain_max = 1024;
180 dtrace_optval_t	dtrace_helper_actions_max = 128;
181 dtrace_optval_t	dtrace_helper_providers_max = 32;
182 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
183 size_t		dtrace_strsize_default = 256;
184 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
185 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
186 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
187 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
188 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
189 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
190 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
191 dtrace_optval_t	dtrace_nspec_default = 1;
192 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
193 dtrace_optval_t dtrace_stackframes_default = 20;
194 dtrace_optval_t dtrace_ustackframes_default = 20;
195 dtrace_optval_t dtrace_jstackframes_default = 50;
196 dtrace_optval_t dtrace_jstackstrsize_default = 512;
197 int		dtrace_msgdsize_max = 128;
198 hrtime_t	dtrace_chill_max = MSEC2NSEC(500);		/* 500 ms */
199 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
200 int		dtrace_devdepth_max = 32;
201 int		dtrace_err_verbose;
202 hrtime_t	dtrace_deadman_interval = NANOSEC;
203 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
204 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
205 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
206 #ifndef illumos
207 int		dtrace_memstr_max = 4096;
208 int		dtrace_bufsize_max_frac = 128;
209 #endif
210 
211 /*
212  * DTrace External Variables
213  *
214  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
215  * available to DTrace consumers via the backtick (`) syntax.  One of these,
216  * dtrace_zero, is made deliberately so:  it is provided as a source of
217  * well-known, zero-filled memory.  While this variable is not documented,
218  * it is used by some translators as an implementation detail.
219  */
220 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
221 
222 /*
223  * DTrace Internal Variables
224  */
225 #ifdef illumos
226 static dev_info_t	*dtrace_devi;		/* device info */
227 #endif
228 #ifdef illumos
229 static vmem_t		*dtrace_arena;		/* probe ID arena */
230 static vmem_t		*dtrace_minor;		/* minor number arena */
231 #else
232 static taskq_t		*dtrace_taskq;		/* task queue */
233 static struct unrhdr	*dtrace_arena;		/* Probe ID number.     */
234 #endif
235 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
236 static int		dtrace_nprobes;		/* number of probes */
237 static dtrace_provider_t *dtrace_provider;	/* provider list */
238 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
239 static int		dtrace_opens;		/* number of opens */
240 static int		dtrace_helpers;		/* number of helpers */
241 static int		dtrace_getf;		/* number of unpriv getf()s */
242 #ifdef illumos
243 static void		*dtrace_softstate;	/* softstate pointer */
244 #endif
245 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
246 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
247 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
248 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
249 static int		dtrace_toxranges;	/* number of toxic ranges */
250 static int		dtrace_toxranges_max;	/* size of toxic range array */
251 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
252 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
253 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
254 static kthread_t	*dtrace_panicked;	/* panicking thread */
255 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
256 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
257 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
258 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
259 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
260 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
261 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
262 #ifndef illumos
263 static struct mtx	dtrace_unr_mtx;
264 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
265 static eventhandler_tag	dtrace_kld_load_tag;
266 static eventhandler_tag	dtrace_kld_unload_try_tag;
267 #endif
268 
269 /*
270  * DTrace Locking
271  * DTrace is protected by three (relatively coarse-grained) locks:
272  *
273  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
274  *     including enabling state, probes, ECBs, consumer state, helper state,
275  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
276  *     probe context is lock-free -- synchronization is handled via the
277  *     dtrace_sync() cross call mechanism.
278  *
279  * (2) dtrace_provider_lock is required when manipulating provider state, or
280  *     when provider state must be held constant.
281  *
282  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
283  *     when meta provider state must be held constant.
284  *
285  * The lock ordering between these three locks is dtrace_meta_lock before
286  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
287  * several places where dtrace_provider_lock is held by the framework as it
288  * calls into the providers -- which then call back into the framework,
289  * grabbing dtrace_lock.)
290  *
291  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
292  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
293  * role as a coarse-grained lock; it is acquired before both of these locks.
294  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
295  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
296  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
297  * acquired _between_ dtrace_provider_lock and dtrace_lock.
298  */
299 static kmutex_t		dtrace_lock;		/* probe state lock */
300 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
301 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
302 
303 #ifndef illumos
304 /* XXX FreeBSD hacks. */
305 #define cr_suid		cr_svuid
306 #define cr_sgid		cr_svgid
307 #define	ipaddr_t	in_addr_t
308 #define mod_modname	pathname
309 #define vuprintf	vprintf
310 #ifndef crgetzoneid
311 #define crgetzoneid(_a)        0
312 #endif
313 #define ttoproc(_a)	((_a)->td_proc)
314 #define SNOCD		0
315 #define CPU_ON_INTR(_a)	0
316 
317 #define PRIV_EFFECTIVE		(1 << 0)
318 #define PRIV_DTRACE_KERNEL	(1 << 1)
319 #define PRIV_DTRACE_PROC	(1 << 2)
320 #define PRIV_DTRACE_USER	(1 << 3)
321 #define PRIV_PROC_OWNER		(1 << 4)
322 #define PRIV_PROC_ZONE		(1 << 5)
323 #define PRIV_ALL		~0
324 
325 SYSCTL_DECL(_debug_dtrace);
326 SYSCTL_DECL(_kern_dtrace);
327 #endif
328 
329 #ifdef illumos
330 #define curcpu	CPU->cpu_id
331 #endif
332 
333 
334 /*
335  * DTrace Provider Variables
336  *
337  * These are the variables relating to DTrace as a provider (that is, the
338  * provider of the BEGIN, END, and ERROR probes).
339  */
340 static dtrace_pattr_t	dtrace_provider_attr = {
341 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
342 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
343 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
344 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
345 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
346 };
347 
348 static void
349 dtrace_nullop(void)
350 {}
351 
352 static dtrace_pops_t dtrace_provider_ops = {
353 	.dtps_provide =	(void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
354 	.dtps_provide_module =	(void (*)(void *, modctl_t *))dtrace_nullop,
355 	.dtps_enable =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
356 	.dtps_disable =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
357 	.dtps_suspend =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
358 	.dtps_resume =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
359 	.dtps_getargdesc =	NULL,
360 	.dtps_getargval =	NULL,
361 	.dtps_usermode =	NULL,
362 	.dtps_destroy =	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
363 };
364 
365 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
366 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
367 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
368 
369 /*
370  * DTrace Helper Tracing Variables
371  *
372  * These variables should be set dynamically to enable helper tracing.  The
373  * only variables that should be set are dtrace_helptrace_enable (which should
374  * be set to a non-zero value to allocate helper tracing buffers on the next
375  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
376  * non-zero value to deallocate helper tracing buffers on the next close of
377  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
378  * buffer size may also be set via dtrace_helptrace_bufsize.
379  */
380 int			dtrace_helptrace_enable = 0;
381 int			dtrace_helptrace_disable = 0;
382 int			dtrace_helptrace_bufsize = 16 * 1024 * 1024;
383 uint32_t		dtrace_helptrace_nlocals;
384 static dtrace_helptrace_t *dtrace_helptrace_buffer;
385 static uint32_t		dtrace_helptrace_next = 0;
386 static int		dtrace_helptrace_wrapped = 0;
387 
388 /*
389  * DTrace Error Hashing
390  *
391  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
392  * table.  This is very useful for checking coverage of tests that are
393  * expected to induce DIF or DOF processing errors, and may be useful for
394  * debugging problems in the DIF code generator or in DOF generation .  The
395  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
396  */
397 #ifdef DEBUG
398 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
399 static const char *dtrace_errlast;
400 static kthread_t *dtrace_errthread;
401 static kmutex_t dtrace_errlock;
402 #endif
403 
404 /*
405  * DTrace Macros and Constants
406  *
407  * These are various macros that are useful in various spots in the
408  * implementation, along with a few random constants that have no meaning
409  * outside of the implementation.  There is no real structure to this cpp
410  * mishmash -- but is there ever?
411  */
412 #define	DTRACE_HASHSTR(hash, probe)	\
413 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
414 
415 #define	DTRACE_HASHNEXT(hash, probe)	\
416 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
417 
418 #define	DTRACE_HASHPREV(hash, probe)	\
419 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
420 
421 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
422 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
423 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
424 
425 #define	DTRACE_AGGHASHSIZE_SLEW		17
426 
427 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
428 
429 /*
430  * The key for a thread-local variable consists of the lower 61 bits of the
431  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
432  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
433  * equal to a variable identifier.  This is necessary (but not sufficient) to
434  * assure that global associative arrays never collide with thread-local
435  * variables.  To guarantee that they cannot collide, we must also define the
436  * order for keying dynamic variables.  That order is:
437  *
438  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
439  *
440  * Because the variable-key and the tls-key are in orthogonal spaces, there is
441  * no way for a global variable key signature to match a thread-local key
442  * signature.
443  */
444 #ifdef illumos
445 #define	DTRACE_TLS_THRKEY(where) { \
446 	uint_t intr = 0; \
447 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
448 	for (; actv; actv >>= 1) \
449 		intr++; \
450 	ASSERT(intr < (1 << 3)); \
451 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
452 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
453 }
454 #else
455 #define	DTRACE_TLS_THRKEY(where) { \
456 	solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
457 	uint_t intr = 0; \
458 	uint_t actv = _c->cpu_intr_actv; \
459 	for (; actv; actv >>= 1) \
460 		intr++; \
461 	ASSERT(intr < (1 << 3)); \
462 	(where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
463 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
464 }
465 #endif
466 
467 #define	DT_BSWAP_8(x)	((x) & 0xff)
468 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
469 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
470 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
471 
472 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
473 
474 #define	DTRACE_STORE(type, tomax, offset, what) \
475 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
476 
477 #if !defined(__x86) && !defined(__aarch64__)
478 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
479 	if (addr & (size - 1)) {					\
480 		*flags |= CPU_DTRACE_BADALIGN;				\
481 		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
482 		return (0);						\
483 	}
484 #else
485 #define	DTRACE_ALIGNCHECK(addr, size, flags)
486 #endif
487 
488 /*
489  * Test whether a range of memory starting at testaddr of size testsz falls
490  * within the range of memory described by addr, sz.  We take care to avoid
491  * problems with overflow and underflow of the unsigned quantities, and
492  * disallow all negative sizes.  Ranges of size 0 are allowed.
493  */
494 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
495 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
496 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
497 	(testaddr) + (testsz) >= (testaddr))
498 
499 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
500 do {									\
501 	if ((remp) != NULL) {						\
502 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
503 	}								\
504 } while (0)
505 
506 
507 /*
508  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
509  * alloc_sz on the righthand side of the comparison in order to avoid overflow
510  * or underflow in the comparison with it.  This is simpler than the INRANGE
511  * check above, because we know that the dtms_scratch_ptr is valid in the
512  * range.  Allocations of size zero are allowed.
513  */
514 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
515 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
516 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
517 
518 #define	DTRACE_LOADFUNC(bits)						\
519 /*CSTYLED*/								\
520 uint##bits##_t								\
521 dtrace_load##bits(uintptr_t addr)					\
522 {									\
523 	size_t size = bits / NBBY;					\
524 	/*CSTYLED*/							\
525 	uint##bits##_t rval;						\
526 	int i;								\
527 	volatile uint16_t *flags = (volatile uint16_t *)		\
528 	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
529 									\
530 	DTRACE_ALIGNCHECK(addr, size, flags);				\
531 									\
532 	for (i = 0; i < dtrace_toxranges; i++) {			\
533 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
534 			continue;					\
535 									\
536 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
537 			continue;					\
538 									\
539 		/*							\
540 		 * This address falls within a toxic region; return 0.	\
541 		 */							\
542 		*flags |= CPU_DTRACE_BADADDR;				\
543 		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
544 		return (0);						\
545 	}								\
546 									\
547 	*flags |= CPU_DTRACE_NOFAULT;					\
548 	/*CSTYLED*/							\
549 	rval = *((volatile uint##bits##_t *)addr);			\
550 	*flags &= ~CPU_DTRACE_NOFAULT;					\
551 									\
552 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
553 }
554 
555 #ifdef _LP64
556 #define	dtrace_loadptr	dtrace_load64
557 #else
558 #define	dtrace_loadptr	dtrace_load32
559 #endif
560 
561 #define	DTRACE_DYNHASH_FREE	0
562 #define	DTRACE_DYNHASH_SINK	1
563 #define	DTRACE_DYNHASH_VALID	2
564 
565 #define	DTRACE_MATCH_NEXT	0
566 #define	DTRACE_MATCH_DONE	1
567 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
568 #define	DTRACE_STATE_ALIGN	64
569 
570 #define	DTRACE_FLAGS2FLT(flags)						\
571 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
572 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
573 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
574 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
575 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
576 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
577 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
578 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
579 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
580 	DTRACEFLT_UNKNOWN)
581 
582 #define	DTRACEACT_ISSTRING(act)						\
583 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
584 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
585 
586 /* Function prototype definitions: */
587 static size_t dtrace_strlen(const char *, size_t);
588 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
589 static void dtrace_enabling_provide(dtrace_provider_t *);
590 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
591 static void dtrace_enabling_matchall(void);
592 static void dtrace_enabling_reap(void);
593 static dtrace_state_t *dtrace_anon_grab(void);
594 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
595     dtrace_state_t *, uint64_t, uint64_t);
596 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
597 static void dtrace_buffer_drop(dtrace_buffer_t *);
598 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
599 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
600     dtrace_state_t *, dtrace_mstate_t *);
601 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
602     dtrace_optval_t);
603 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
604 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
605 uint16_t dtrace_load16(uintptr_t);
606 uint32_t dtrace_load32(uintptr_t);
607 uint64_t dtrace_load64(uintptr_t);
608 uint8_t dtrace_load8(uintptr_t);
609 void dtrace_dynvar_clean(dtrace_dstate_t *);
610 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
611     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
612 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
613 static int dtrace_priv_proc(dtrace_state_t *);
614 static void dtrace_getf_barrier(void);
615 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
616     dtrace_mstate_t *, dtrace_vstate_t *);
617 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
618     dtrace_mstate_t *, dtrace_vstate_t *);
619 
620 /*
621  * DTrace Probe Context Functions
622  *
623  * These functions are called from probe context.  Because probe context is
624  * any context in which C may be called, arbitrarily locks may be held,
625  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
626  * As a result, functions called from probe context may only call other DTrace
627  * support functions -- they may not interact at all with the system at large.
628  * (Note that the ASSERT macro is made probe-context safe by redefining it in
629  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
630  * loads are to be performed from probe context, they _must_ be in terms of
631  * the safe dtrace_load*() variants.
632  *
633  * Some functions in this block are not actually called from probe context;
634  * for these functions, there will be a comment above the function reading
635  * "Note:  not called from probe context."
636  */
637 void
638 dtrace_panic(const char *format, ...)
639 {
640 	va_list alist;
641 
642 	va_start(alist, format);
643 #ifdef __FreeBSD__
644 	vpanic(format, alist);
645 #else
646 	dtrace_vpanic(format, alist);
647 #endif
648 	va_end(alist);
649 }
650 
651 int
652 dtrace_assfail(const char *a, const char *f, int l)
653 {
654 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
655 
656 	/*
657 	 * We just need something here that even the most clever compiler
658 	 * cannot optimize away.
659 	 */
660 	return (a[(uintptr_t)f]);
661 }
662 
663 /*
664  * Atomically increment a specified error counter from probe context.
665  */
666 static void
667 dtrace_error(uint32_t *counter)
668 {
669 	/*
670 	 * Most counters stored to in probe context are per-CPU counters.
671 	 * However, there are some error conditions that are sufficiently
672 	 * arcane that they don't merit per-CPU storage.  If these counters
673 	 * are incremented concurrently on different CPUs, scalability will be
674 	 * adversely affected -- but we don't expect them to be white-hot in a
675 	 * correctly constructed enabling...
676 	 */
677 	uint32_t oval, nval;
678 
679 	do {
680 		oval = *counter;
681 
682 		if ((nval = oval + 1) == 0) {
683 			/*
684 			 * If the counter would wrap, set it to 1 -- assuring
685 			 * that the counter is never zero when we have seen
686 			 * errors.  (The counter must be 32-bits because we
687 			 * aren't guaranteed a 64-bit compare&swap operation.)
688 			 * To save this code both the infamy of being fingered
689 			 * by a priggish news story and the indignity of being
690 			 * the target of a neo-puritan witch trial, we're
691 			 * carefully avoiding any colorful description of the
692 			 * likelihood of this condition -- but suffice it to
693 			 * say that it is only slightly more likely than the
694 			 * overflow of predicate cache IDs, as discussed in
695 			 * dtrace_predicate_create().
696 			 */
697 			nval = 1;
698 		}
699 	} while (dtrace_cas32(counter, oval, nval) != oval);
700 }
701 
702 /*
703  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
704  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
705  */
706 /* BEGIN CSTYLED */
707 DTRACE_LOADFUNC(8)
708 DTRACE_LOADFUNC(16)
709 DTRACE_LOADFUNC(32)
710 DTRACE_LOADFUNC(64)
711 /* END CSTYLED */
712 
713 static int
714 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
715 {
716 	if (dest < mstate->dtms_scratch_base)
717 		return (0);
718 
719 	if (dest + size < dest)
720 		return (0);
721 
722 	if (dest + size > mstate->dtms_scratch_ptr)
723 		return (0);
724 
725 	return (1);
726 }
727 
728 static int
729 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
730     dtrace_statvar_t **svars, int nsvars)
731 {
732 	int i;
733 	size_t maxglobalsize, maxlocalsize;
734 
735 	if (nsvars == 0)
736 		return (0);
737 
738 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
739 	maxlocalsize = maxglobalsize * NCPU;
740 
741 	for (i = 0; i < nsvars; i++) {
742 		dtrace_statvar_t *svar = svars[i];
743 		uint8_t scope;
744 		size_t size;
745 
746 		if (svar == NULL || (size = svar->dtsv_size) == 0)
747 			continue;
748 
749 		scope = svar->dtsv_var.dtdv_scope;
750 
751 		/*
752 		 * We verify that our size is valid in the spirit of providing
753 		 * defense in depth:  we want to prevent attackers from using
754 		 * DTrace to escalate an orthogonal kernel heap corruption bug
755 		 * into the ability to store to arbitrary locations in memory.
756 		 */
757 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
758 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
759 
760 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
761 		    svar->dtsv_size)) {
762 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
763 			    svar->dtsv_size);
764 			return (1);
765 		}
766 	}
767 
768 	return (0);
769 }
770 
771 /*
772  * Check to see if the address is within a memory region to which a store may
773  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
774  * region.  The caller of dtrace_canstore() is responsible for performing any
775  * alignment checks that are needed before stores are actually executed.
776  */
777 static int
778 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
779     dtrace_vstate_t *vstate)
780 {
781 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
782 }
783 
784 /*
785  * Implementation of dtrace_canstore which communicates the upper bound of the
786  * allowed memory region.
787  */
788 static int
789 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
790     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
791 {
792 	/*
793 	 * First, check to see if the address is in scratch space...
794 	 */
795 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
796 	    mstate->dtms_scratch_size)) {
797 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
798 		    mstate->dtms_scratch_size);
799 		return (1);
800 	}
801 
802 	/*
803 	 * Now check to see if it's a dynamic variable.  This check will pick
804 	 * up both thread-local variables and any global dynamically-allocated
805 	 * variables.
806 	 */
807 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
808 	    vstate->dtvs_dynvars.dtds_size)) {
809 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
810 		uintptr_t base = (uintptr_t)dstate->dtds_base +
811 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
812 		uintptr_t chunkoffs;
813 		dtrace_dynvar_t *dvar;
814 
815 		/*
816 		 * Before we assume that we can store here, we need to make
817 		 * sure that it isn't in our metadata -- storing to our
818 		 * dynamic variable metadata would corrupt our state.  For
819 		 * the range to not include any dynamic variable metadata,
820 		 * it must:
821 		 *
822 		 *	(1) Start above the hash table that is at the base of
823 		 *	the dynamic variable space
824 		 *
825 		 *	(2) Have a starting chunk offset that is beyond the
826 		 *	dtrace_dynvar_t that is at the base of every chunk
827 		 *
828 		 *	(3) Not span a chunk boundary
829 		 *
830 		 *	(4) Not be in the tuple space of a dynamic variable
831 		 *
832 		 */
833 		if (addr < base)
834 			return (0);
835 
836 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
837 
838 		if (chunkoffs < sizeof (dtrace_dynvar_t))
839 			return (0);
840 
841 		if (chunkoffs + sz > dstate->dtds_chunksize)
842 			return (0);
843 
844 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
845 
846 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
847 			return (0);
848 
849 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
850 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
851 			return (0);
852 
853 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
854 		return (1);
855 	}
856 
857 	/*
858 	 * Finally, check the static local and global variables.  These checks
859 	 * take the longest, so we perform them last.
860 	 */
861 	if (dtrace_canstore_statvar(addr, sz, remain,
862 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
863 		return (1);
864 
865 	if (dtrace_canstore_statvar(addr, sz, remain,
866 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
867 		return (1);
868 
869 	return (0);
870 }
871 
872 
873 /*
874  * Convenience routine to check to see if the address is within a memory
875  * region in which a load may be issued given the user's privilege level;
876  * if not, it sets the appropriate error flags and loads 'addr' into the
877  * illegal value slot.
878  *
879  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
880  * appropriate memory access protection.
881  */
882 static int
883 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
884     dtrace_vstate_t *vstate)
885 {
886 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
887 }
888 
889 /*
890  * Implementation of dtrace_canload which communicates the uppoer bound of the
891  * allowed memory region.
892  */
893 static int
894 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
895     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
896 {
897 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
898 	file_t *fp;
899 
900 	/*
901 	 * If we hold the privilege to read from kernel memory, then
902 	 * everything is readable.
903 	 */
904 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
905 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
906 		return (1);
907 	}
908 
909 	/*
910 	 * You can obviously read that which you can store.
911 	 */
912 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
913 		return (1);
914 
915 	/*
916 	 * We're allowed to read from our own string table.
917 	 */
918 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
919 	    mstate->dtms_difo->dtdo_strlen)) {
920 		DTRACE_RANGE_REMAIN(remain, addr,
921 		    mstate->dtms_difo->dtdo_strtab,
922 		    mstate->dtms_difo->dtdo_strlen);
923 		return (1);
924 	}
925 
926 	if (vstate->dtvs_state != NULL &&
927 	    dtrace_priv_proc(vstate->dtvs_state)) {
928 		proc_t *p;
929 
930 		/*
931 		 * When we have privileges to the current process, there are
932 		 * several context-related kernel structures that are safe to
933 		 * read, even absent the privilege to read from kernel memory.
934 		 * These reads are safe because these structures contain only
935 		 * state that (1) we're permitted to read, (2) is harmless or
936 		 * (3) contains pointers to additional kernel state that we're
937 		 * not permitted to read (and as such, do not present an
938 		 * opportunity for privilege escalation).  Finally (and
939 		 * critically), because of the nature of their relation with
940 		 * the current thread context, the memory associated with these
941 		 * structures cannot change over the duration of probe context,
942 		 * and it is therefore impossible for this memory to be
943 		 * deallocated and reallocated as something else while it's
944 		 * being operated upon.
945 		 */
946 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
947 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
948 			    sizeof (kthread_t));
949 			return (1);
950 		}
951 
952 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
953 		    sz, curthread->t_procp, sizeof (proc_t))) {
954 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
955 			    sizeof (proc_t));
956 			return (1);
957 		}
958 
959 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
960 		    curthread->t_cred, sizeof (cred_t))) {
961 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
962 			    sizeof (cred_t));
963 			return (1);
964 		}
965 
966 #ifdef illumos
967 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
968 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
969 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
970 			    sizeof (pid_t));
971 			return (1);
972 		}
973 
974 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
975 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
976 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
977 			    offsetof(cpu_t, cpu_pause_thread));
978 			return (1);
979 		}
980 #endif
981 	}
982 
983 	if ((fp = mstate->dtms_getf) != NULL) {
984 		uintptr_t psz = sizeof (void *);
985 		vnode_t *vp;
986 		vnodeops_t *op;
987 
988 		/*
989 		 * When getf() returns a file_t, the enabling is implicitly
990 		 * granted the (transient) right to read the returned file_t
991 		 * as well as the v_path and v_op->vnop_name of the underlying
992 		 * vnode.  These accesses are allowed after a successful
993 		 * getf() because the members that they refer to cannot change
994 		 * once set -- and the barrier logic in the kernel's closef()
995 		 * path assures that the file_t and its referenced vode_t
996 		 * cannot themselves be stale (that is, it impossible for
997 		 * either dtms_getf itself or its f_vnode member to reference
998 		 * freed memory).
999 		 */
1000 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1001 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1002 			return (1);
1003 		}
1004 
1005 		if ((vp = fp->f_vnode) != NULL) {
1006 			size_t slen;
1007 #ifdef illumos
1008 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1009 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1010 				    psz);
1011 				return (1);
1012 			}
1013 			slen = strlen(vp->v_path) + 1;
1014 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1015 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1016 				    slen);
1017 				return (1);
1018 			}
1019 #endif
1020 
1021 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1022 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1023 				    psz);
1024 				return (1);
1025 			}
1026 
1027 #ifdef illumos
1028 			if ((op = vp->v_op) != NULL &&
1029 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1030 				DTRACE_RANGE_REMAIN(remain, addr,
1031 				    &op->vnop_name, psz);
1032 				return (1);
1033 			}
1034 
1035 			if (op != NULL && op->vnop_name != NULL &&
1036 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
1037 			    (slen = strlen(op->vnop_name) + 1))) {
1038 				DTRACE_RANGE_REMAIN(remain, addr,
1039 				    op->vnop_name, slen);
1040 				return (1);
1041 			}
1042 #endif
1043 		}
1044 	}
1045 
1046 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1047 	*illval = addr;
1048 	return (0);
1049 }
1050 
1051 /*
1052  * Convenience routine to check to see if a given string is within a memory
1053  * region in which a load may be issued given the user's privilege level;
1054  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1055  * calls in the event that the user has all privileges.
1056  */
1057 static int
1058 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1059     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1060 {
1061 	size_t rsize;
1062 
1063 	/*
1064 	 * If we hold the privilege to read from kernel memory, then
1065 	 * everything is readable.
1066 	 */
1067 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1068 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1069 		return (1);
1070 	}
1071 
1072 	/*
1073 	 * Even if the caller is uninterested in querying the remaining valid
1074 	 * range, it is required to ensure that the access is allowed.
1075 	 */
1076 	if (remain == NULL) {
1077 		remain = &rsize;
1078 	}
1079 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1080 		size_t strsz;
1081 		/*
1082 		 * Perform the strlen after determining the length of the
1083 		 * memory region which is accessible.  This prevents timing
1084 		 * information from being used to find NULs in memory which is
1085 		 * not accessible to the caller.
1086 		 */
1087 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1088 		    MIN(sz, *remain));
1089 		if (strsz <= *remain) {
1090 			return (1);
1091 		}
1092 	}
1093 
1094 	return (0);
1095 }
1096 
1097 /*
1098  * Convenience routine to check to see if a given variable is within a memory
1099  * region in which a load may be issued given the user's privilege level.
1100  */
1101 static int
1102 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1103     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1104 {
1105 	size_t sz;
1106 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1107 
1108 	/*
1109 	 * Calculate the max size before performing any checks since even
1110 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1111 	 * return the max length via 'remain'.
1112 	 */
1113 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1114 		dtrace_state_t *state = vstate->dtvs_state;
1115 
1116 		if (state != NULL) {
1117 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1118 		} else {
1119 			/*
1120 			 * In helper context, we have a NULL state; fall back
1121 			 * to using the system-wide default for the string size
1122 			 * in this case.
1123 			 */
1124 			sz = dtrace_strsize_default;
1125 		}
1126 	} else {
1127 		sz = type->dtdt_size;
1128 	}
1129 
1130 	/*
1131 	 * If we hold the privilege to read from kernel memory, then
1132 	 * everything is readable.
1133 	 */
1134 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1135 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1136 		return (1);
1137 	}
1138 
1139 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1140 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1141 		    vstate));
1142 	}
1143 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1144 	    vstate));
1145 }
1146 
1147 /*
1148  * Convert a string to a signed integer using safe loads.
1149  *
1150  * NOTE: This function uses various macros from strtolctype.h to manipulate
1151  * digit values, etc -- these have all been checked to ensure they make
1152  * no additional function calls.
1153  */
1154 static int64_t
1155 dtrace_strtoll(char *input, int base, size_t limit)
1156 {
1157 	uintptr_t pos = (uintptr_t)input;
1158 	int64_t val = 0;
1159 	int x;
1160 	boolean_t neg = B_FALSE;
1161 	char c, cc, ccc;
1162 	uintptr_t end = pos + limit;
1163 
1164 	/*
1165 	 * Consume any whitespace preceding digits.
1166 	 */
1167 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1168 		pos++;
1169 
1170 	/*
1171 	 * Handle an explicit sign if one is present.
1172 	 */
1173 	if (c == '-' || c == '+') {
1174 		if (c == '-')
1175 			neg = B_TRUE;
1176 		c = dtrace_load8(++pos);
1177 	}
1178 
1179 	/*
1180 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1181 	 * if present.
1182 	 */
1183 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1184 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1185 		pos += 2;
1186 		c = ccc;
1187 	}
1188 
1189 	/*
1190 	 * Read in contiguous digits until the first non-digit character.
1191 	 */
1192 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1193 	    c = dtrace_load8(++pos))
1194 		val = val * base + x;
1195 
1196 	return (neg ? -val : val);
1197 }
1198 
1199 /*
1200  * Compare two strings using safe loads.
1201  */
1202 static int
1203 dtrace_strncmp(char *s1, char *s2, size_t limit)
1204 {
1205 	uint8_t c1, c2;
1206 	volatile uint16_t *flags;
1207 
1208 	if (s1 == s2 || limit == 0)
1209 		return (0);
1210 
1211 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1212 
1213 	do {
1214 		if (s1 == NULL) {
1215 			c1 = '\0';
1216 		} else {
1217 			c1 = dtrace_load8((uintptr_t)s1++);
1218 		}
1219 
1220 		if (s2 == NULL) {
1221 			c2 = '\0';
1222 		} else {
1223 			c2 = dtrace_load8((uintptr_t)s2++);
1224 		}
1225 
1226 		if (c1 != c2)
1227 			return (c1 - c2);
1228 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1229 
1230 	return (0);
1231 }
1232 
1233 /*
1234  * Compute strlen(s) for a string using safe memory accesses.  The additional
1235  * len parameter is used to specify a maximum length to ensure completion.
1236  */
1237 static size_t
1238 dtrace_strlen(const char *s, size_t lim)
1239 {
1240 	uint_t len;
1241 
1242 	for (len = 0; len != lim; len++) {
1243 		if (dtrace_load8((uintptr_t)s++) == '\0')
1244 			break;
1245 	}
1246 
1247 	return (len);
1248 }
1249 
1250 /*
1251  * Check if an address falls within a toxic region.
1252  */
1253 static int
1254 dtrace_istoxic(uintptr_t kaddr, size_t size)
1255 {
1256 	uintptr_t taddr, tsize;
1257 	int i;
1258 
1259 	for (i = 0; i < dtrace_toxranges; i++) {
1260 		taddr = dtrace_toxrange[i].dtt_base;
1261 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1262 
1263 		if (kaddr - taddr < tsize) {
1264 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1265 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1266 			return (1);
1267 		}
1268 
1269 		if (taddr - kaddr < size) {
1270 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1271 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1272 			return (1);
1273 		}
1274 	}
1275 
1276 	return (0);
1277 }
1278 
1279 /*
1280  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1281  * memory specified by the DIF program.  The dst is assumed to be safe memory
1282  * that we can store to directly because it is managed by DTrace.  As with
1283  * standard bcopy, overlapping copies are handled properly.
1284  */
1285 static void
1286 dtrace_bcopy(const void *src, void *dst, size_t len)
1287 {
1288 	if (len != 0) {
1289 		uint8_t *s1 = dst;
1290 		const uint8_t *s2 = src;
1291 
1292 		if (s1 <= s2) {
1293 			do {
1294 				*s1++ = dtrace_load8((uintptr_t)s2++);
1295 			} while (--len != 0);
1296 		} else {
1297 			s2 += len;
1298 			s1 += len;
1299 
1300 			do {
1301 				*--s1 = dtrace_load8((uintptr_t)--s2);
1302 			} while (--len != 0);
1303 		}
1304 	}
1305 }
1306 
1307 /*
1308  * Copy src to dst using safe memory accesses, up to either the specified
1309  * length, or the point that a nul byte is encountered.  The src is assumed to
1310  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1311  * safe memory that we can store to directly because it is managed by DTrace.
1312  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1313  */
1314 static void
1315 dtrace_strcpy(const void *src, void *dst, size_t len)
1316 {
1317 	if (len != 0) {
1318 		uint8_t *s1 = dst, c;
1319 		const uint8_t *s2 = src;
1320 
1321 		do {
1322 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1323 		} while (--len != 0 && c != '\0');
1324 	}
1325 }
1326 
1327 /*
1328  * Copy src to dst, deriving the size and type from the specified (BYREF)
1329  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1330  * program.  The dst is assumed to be DTrace variable memory that is of the
1331  * specified type; we assume that we can store to directly.
1332  */
1333 static void
1334 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1335 {
1336 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1337 
1338 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1339 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1340 	} else {
1341 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1342 	}
1343 }
1344 
1345 /*
1346  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1347  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1348  * safe memory that we can access directly because it is managed by DTrace.
1349  */
1350 static int
1351 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1352 {
1353 	volatile uint16_t *flags;
1354 
1355 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1356 
1357 	if (s1 == s2)
1358 		return (0);
1359 
1360 	if (s1 == NULL || s2 == NULL)
1361 		return (1);
1362 
1363 	if (s1 != s2 && len != 0) {
1364 		const uint8_t *ps1 = s1;
1365 		const uint8_t *ps2 = s2;
1366 
1367 		do {
1368 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1369 				return (1);
1370 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1371 	}
1372 	return (0);
1373 }
1374 
1375 /*
1376  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1377  * is for safe DTrace-managed memory only.
1378  */
1379 static void
1380 dtrace_bzero(void *dst, size_t len)
1381 {
1382 	uchar_t *cp;
1383 
1384 	for (cp = dst; len != 0; len--)
1385 		*cp++ = 0;
1386 }
1387 
1388 static void
1389 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1390 {
1391 	uint64_t result[2];
1392 
1393 	result[0] = addend1[0] + addend2[0];
1394 	result[1] = addend1[1] + addend2[1] +
1395 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1396 
1397 	sum[0] = result[0];
1398 	sum[1] = result[1];
1399 }
1400 
1401 /*
1402  * Shift the 128-bit value in a by b. If b is positive, shift left.
1403  * If b is negative, shift right.
1404  */
1405 static void
1406 dtrace_shift_128(uint64_t *a, int b)
1407 {
1408 	uint64_t mask;
1409 
1410 	if (b == 0)
1411 		return;
1412 
1413 	if (b < 0) {
1414 		b = -b;
1415 		if (b >= 64) {
1416 			a[0] = a[1] >> (b - 64);
1417 			a[1] = 0;
1418 		} else {
1419 			a[0] >>= b;
1420 			mask = 1LL << (64 - b);
1421 			mask -= 1;
1422 			a[0] |= ((a[1] & mask) << (64 - b));
1423 			a[1] >>= b;
1424 		}
1425 	} else {
1426 		if (b >= 64) {
1427 			a[1] = a[0] << (b - 64);
1428 			a[0] = 0;
1429 		} else {
1430 			a[1] <<= b;
1431 			mask = a[0] >> (64 - b);
1432 			a[1] |= mask;
1433 			a[0] <<= b;
1434 		}
1435 	}
1436 }
1437 
1438 /*
1439  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1440  * use native multiplication on those, and then re-combine into the
1441  * resulting 128-bit value.
1442  *
1443  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1444  *     hi1 * hi2 << 64 +
1445  *     hi1 * lo2 << 32 +
1446  *     hi2 * lo1 << 32 +
1447  *     lo1 * lo2
1448  */
1449 static void
1450 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1451 {
1452 	uint64_t hi1, hi2, lo1, lo2;
1453 	uint64_t tmp[2];
1454 
1455 	hi1 = factor1 >> 32;
1456 	hi2 = factor2 >> 32;
1457 
1458 	lo1 = factor1 & DT_MASK_LO;
1459 	lo2 = factor2 & DT_MASK_LO;
1460 
1461 	product[0] = lo1 * lo2;
1462 	product[1] = hi1 * hi2;
1463 
1464 	tmp[0] = hi1 * lo2;
1465 	tmp[1] = 0;
1466 	dtrace_shift_128(tmp, 32);
1467 	dtrace_add_128(product, tmp, product);
1468 
1469 	tmp[0] = hi2 * lo1;
1470 	tmp[1] = 0;
1471 	dtrace_shift_128(tmp, 32);
1472 	dtrace_add_128(product, tmp, product);
1473 }
1474 
1475 /*
1476  * This privilege check should be used by actions and subroutines to
1477  * verify that the user credentials of the process that enabled the
1478  * invoking ECB match the target credentials
1479  */
1480 static int
1481 dtrace_priv_proc_common_user(dtrace_state_t *state)
1482 {
1483 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1484 
1485 	/*
1486 	 * We should always have a non-NULL state cred here, since if cred
1487 	 * is null (anonymous tracing), we fast-path bypass this routine.
1488 	 */
1489 	ASSERT(s_cr != NULL);
1490 
1491 	if ((cr = CRED()) != NULL &&
1492 	    s_cr->cr_uid == cr->cr_uid &&
1493 	    s_cr->cr_uid == cr->cr_ruid &&
1494 	    s_cr->cr_uid == cr->cr_suid &&
1495 	    s_cr->cr_gid == cr->cr_gid &&
1496 	    s_cr->cr_gid == cr->cr_rgid &&
1497 	    s_cr->cr_gid == cr->cr_sgid)
1498 		return (1);
1499 
1500 	return (0);
1501 }
1502 
1503 /*
1504  * This privilege check should be used by actions and subroutines to
1505  * verify that the zone of the process that enabled the invoking ECB
1506  * matches the target credentials
1507  */
1508 static int
1509 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1510 {
1511 #ifdef illumos
1512 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1513 
1514 	/*
1515 	 * We should always have a non-NULL state cred here, since if cred
1516 	 * is null (anonymous tracing), we fast-path bypass this routine.
1517 	 */
1518 	ASSERT(s_cr != NULL);
1519 
1520 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1521 		return (1);
1522 
1523 	return (0);
1524 #else
1525 	return (1);
1526 #endif
1527 }
1528 
1529 /*
1530  * This privilege check should be used by actions and subroutines to
1531  * verify that the process has not setuid or changed credentials.
1532  */
1533 static int
1534 dtrace_priv_proc_common_nocd(void)
1535 {
1536 	proc_t *proc;
1537 
1538 	if ((proc = ttoproc(curthread)) != NULL &&
1539 	    !(proc->p_flag & SNOCD))
1540 		return (1);
1541 
1542 	return (0);
1543 }
1544 
1545 static int
1546 dtrace_priv_proc_destructive(dtrace_state_t *state)
1547 {
1548 	int action = state->dts_cred.dcr_action;
1549 
1550 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1551 	    dtrace_priv_proc_common_zone(state) == 0)
1552 		goto bad;
1553 
1554 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1555 	    dtrace_priv_proc_common_user(state) == 0)
1556 		goto bad;
1557 
1558 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1559 	    dtrace_priv_proc_common_nocd() == 0)
1560 		goto bad;
1561 
1562 	return (1);
1563 
1564 bad:
1565 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1566 
1567 	return (0);
1568 }
1569 
1570 static int
1571 dtrace_priv_proc_control(dtrace_state_t *state)
1572 {
1573 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1574 		return (1);
1575 
1576 	if (dtrace_priv_proc_common_zone(state) &&
1577 	    dtrace_priv_proc_common_user(state) &&
1578 	    dtrace_priv_proc_common_nocd())
1579 		return (1);
1580 
1581 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1582 
1583 	return (0);
1584 }
1585 
1586 static int
1587 dtrace_priv_proc(dtrace_state_t *state)
1588 {
1589 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1590 		return (1);
1591 
1592 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1593 
1594 	return (0);
1595 }
1596 
1597 static int
1598 dtrace_priv_kernel(dtrace_state_t *state)
1599 {
1600 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1601 		return (1);
1602 
1603 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1604 
1605 	return (0);
1606 }
1607 
1608 static int
1609 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1610 {
1611 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1612 		return (1);
1613 
1614 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1615 
1616 	return (0);
1617 }
1618 
1619 /*
1620  * Determine if the dte_cond of the specified ECB allows for processing of
1621  * the current probe to continue.  Note that this routine may allow continued
1622  * processing, but with access(es) stripped from the mstate's dtms_access
1623  * field.
1624  */
1625 static int
1626 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1627     dtrace_ecb_t *ecb)
1628 {
1629 	dtrace_probe_t *probe = ecb->dte_probe;
1630 	dtrace_provider_t *prov = probe->dtpr_provider;
1631 	dtrace_pops_t *pops = &prov->dtpv_pops;
1632 	int mode = DTRACE_MODE_NOPRIV_DROP;
1633 
1634 	ASSERT(ecb->dte_cond);
1635 
1636 #ifdef illumos
1637 	if (pops->dtps_mode != NULL) {
1638 		mode = pops->dtps_mode(prov->dtpv_arg,
1639 		    probe->dtpr_id, probe->dtpr_arg);
1640 
1641 		ASSERT((mode & DTRACE_MODE_USER) ||
1642 		    (mode & DTRACE_MODE_KERNEL));
1643 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1644 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1645 	}
1646 
1647 	/*
1648 	 * If the dte_cond bits indicate that this consumer is only allowed to
1649 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1650 	 * entry point to check that the probe was fired while in a user
1651 	 * context.  If that's not the case, use the policy specified by the
1652 	 * provider to determine if we drop the probe or merely restrict
1653 	 * operation.
1654 	 */
1655 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1656 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1657 
1658 		if (!(mode & DTRACE_MODE_USER)) {
1659 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1660 				return (0);
1661 
1662 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1663 		}
1664 	}
1665 #endif
1666 
1667 	/*
1668 	 * This is more subtle than it looks. We have to be absolutely certain
1669 	 * that CRED() isn't going to change out from under us so it's only
1670 	 * legit to examine that structure if we're in constrained situations.
1671 	 * Currently, the only times we'll this check is if a non-super-user
1672 	 * has enabled the profile or syscall providers -- providers that
1673 	 * allow visibility of all processes. For the profile case, the check
1674 	 * above will ensure that we're examining a user context.
1675 	 */
1676 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1677 		cred_t *cr;
1678 		cred_t *s_cr = state->dts_cred.dcr_cred;
1679 		proc_t *proc;
1680 
1681 		ASSERT(s_cr != NULL);
1682 
1683 		if ((cr = CRED()) == NULL ||
1684 		    s_cr->cr_uid != cr->cr_uid ||
1685 		    s_cr->cr_uid != cr->cr_ruid ||
1686 		    s_cr->cr_uid != cr->cr_suid ||
1687 		    s_cr->cr_gid != cr->cr_gid ||
1688 		    s_cr->cr_gid != cr->cr_rgid ||
1689 		    s_cr->cr_gid != cr->cr_sgid ||
1690 		    (proc = ttoproc(curthread)) == NULL ||
1691 		    (proc->p_flag & SNOCD)) {
1692 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1693 				return (0);
1694 
1695 #ifdef illumos
1696 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1697 #endif
1698 		}
1699 	}
1700 
1701 #ifdef illumos
1702 	/*
1703 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1704 	 * in our zone, check to see if our mode policy is to restrict rather
1705 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1706 	 * and DTRACE_ACCESS_ARGS
1707 	 */
1708 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1709 		cred_t *cr;
1710 		cred_t *s_cr = state->dts_cred.dcr_cred;
1711 
1712 		ASSERT(s_cr != NULL);
1713 
1714 		if ((cr = CRED()) == NULL ||
1715 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1716 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1717 				return (0);
1718 
1719 			mstate->dtms_access &=
1720 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1721 		}
1722 	}
1723 #endif
1724 
1725 	return (1);
1726 }
1727 
1728 /*
1729  * Note:  not called from probe context.  This function is called
1730  * asynchronously (and at a regular interval) from outside of probe context to
1731  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1732  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1733  */
1734 void
1735 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1736 {
1737 	dtrace_dynvar_t *dirty;
1738 	dtrace_dstate_percpu_t *dcpu;
1739 	dtrace_dynvar_t **rinsep;
1740 	int i, j, work = 0;
1741 
1742 	for (i = 0; i < NCPU; i++) {
1743 		dcpu = &dstate->dtds_percpu[i];
1744 		rinsep = &dcpu->dtdsc_rinsing;
1745 
1746 		/*
1747 		 * If the dirty list is NULL, there is no dirty work to do.
1748 		 */
1749 		if (dcpu->dtdsc_dirty == NULL)
1750 			continue;
1751 
1752 		if (dcpu->dtdsc_rinsing != NULL) {
1753 			/*
1754 			 * If the rinsing list is non-NULL, then it is because
1755 			 * this CPU was selected to accept another CPU's
1756 			 * dirty list -- and since that time, dirty buffers
1757 			 * have accumulated.  This is a highly unlikely
1758 			 * condition, but we choose to ignore the dirty
1759 			 * buffers -- they'll be picked up a future cleanse.
1760 			 */
1761 			continue;
1762 		}
1763 
1764 		if (dcpu->dtdsc_clean != NULL) {
1765 			/*
1766 			 * If the clean list is non-NULL, then we're in a
1767 			 * situation where a CPU has done deallocations (we
1768 			 * have a non-NULL dirty list) but no allocations (we
1769 			 * also have a non-NULL clean list).  We can't simply
1770 			 * move the dirty list into the clean list on this
1771 			 * CPU, yet we also don't want to allow this condition
1772 			 * to persist, lest a short clean list prevent a
1773 			 * massive dirty list from being cleaned (which in
1774 			 * turn could lead to otherwise avoidable dynamic
1775 			 * drops).  To deal with this, we look for some CPU
1776 			 * with a NULL clean list, NULL dirty list, and NULL
1777 			 * rinsing list -- and then we borrow this CPU to
1778 			 * rinse our dirty list.
1779 			 */
1780 			for (j = 0; j < NCPU; j++) {
1781 				dtrace_dstate_percpu_t *rinser;
1782 
1783 				rinser = &dstate->dtds_percpu[j];
1784 
1785 				if (rinser->dtdsc_rinsing != NULL)
1786 					continue;
1787 
1788 				if (rinser->dtdsc_dirty != NULL)
1789 					continue;
1790 
1791 				if (rinser->dtdsc_clean != NULL)
1792 					continue;
1793 
1794 				rinsep = &rinser->dtdsc_rinsing;
1795 				break;
1796 			}
1797 
1798 			if (j == NCPU) {
1799 				/*
1800 				 * We were unable to find another CPU that
1801 				 * could accept this dirty list -- we are
1802 				 * therefore unable to clean it now.
1803 				 */
1804 				dtrace_dynvar_failclean++;
1805 				continue;
1806 			}
1807 		}
1808 
1809 		work = 1;
1810 
1811 		/*
1812 		 * Atomically move the dirty list aside.
1813 		 */
1814 		do {
1815 			dirty = dcpu->dtdsc_dirty;
1816 
1817 			/*
1818 			 * Before we zap the dirty list, set the rinsing list.
1819 			 * (This allows for a potential assertion in
1820 			 * dtrace_dynvar():  if a free dynamic variable appears
1821 			 * on a hash chain, either the dirty list or the
1822 			 * rinsing list for some CPU must be non-NULL.)
1823 			 */
1824 			*rinsep = dirty;
1825 			dtrace_membar_producer();
1826 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1827 		    dirty, NULL) != dirty);
1828 	}
1829 
1830 	if (!work) {
1831 		/*
1832 		 * We have no work to do; we can simply return.
1833 		 */
1834 		return;
1835 	}
1836 
1837 	dtrace_sync();
1838 
1839 	for (i = 0; i < NCPU; i++) {
1840 		dcpu = &dstate->dtds_percpu[i];
1841 
1842 		if (dcpu->dtdsc_rinsing == NULL)
1843 			continue;
1844 
1845 		/*
1846 		 * We are now guaranteed that no hash chain contains a pointer
1847 		 * into this dirty list; we can make it clean.
1848 		 */
1849 		ASSERT(dcpu->dtdsc_clean == NULL);
1850 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1851 		dcpu->dtdsc_rinsing = NULL;
1852 	}
1853 
1854 	/*
1855 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1856 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1857 	 * This prevents a race whereby a CPU incorrectly decides that
1858 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1859 	 * after dtrace_dynvar_clean() has completed.
1860 	 */
1861 	dtrace_sync();
1862 
1863 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1864 }
1865 
1866 /*
1867  * Depending on the value of the op parameter, this function looks-up,
1868  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1869  * allocation is requested, this function will return a pointer to a
1870  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1871  * variable can be allocated.  If NULL is returned, the appropriate counter
1872  * will be incremented.
1873  */
1874 dtrace_dynvar_t *
1875 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1876     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1877     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1878 {
1879 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1880 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1881 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1882 	processorid_t me = curcpu, cpu = me;
1883 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1884 	size_t bucket, ksize;
1885 	size_t chunksize = dstate->dtds_chunksize;
1886 	uintptr_t kdata, lock, nstate;
1887 	uint_t i;
1888 
1889 	ASSERT(nkeys != 0);
1890 
1891 	/*
1892 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1893 	 * algorithm.  For the by-value portions, we perform the algorithm in
1894 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1895 	 * bit, and seems to have only a minute effect on distribution.  For
1896 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1897 	 * over each referenced byte.  It's painful to do this, but it's much
1898 	 * better than pathological hash distribution.  The efficacy of the
1899 	 * hashing algorithm (and a comparison with other algorithms) may be
1900 	 * found by running the ::dtrace_dynstat MDB dcmd.
1901 	 */
1902 	for (i = 0; i < nkeys; i++) {
1903 		if (key[i].dttk_size == 0) {
1904 			uint64_t val = key[i].dttk_value;
1905 
1906 			hashval += (val >> 48) & 0xffff;
1907 			hashval += (hashval << 10);
1908 			hashval ^= (hashval >> 6);
1909 
1910 			hashval += (val >> 32) & 0xffff;
1911 			hashval += (hashval << 10);
1912 			hashval ^= (hashval >> 6);
1913 
1914 			hashval += (val >> 16) & 0xffff;
1915 			hashval += (hashval << 10);
1916 			hashval ^= (hashval >> 6);
1917 
1918 			hashval += val & 0xffff;
1919 			hashval += (hashval << 10);
1920 			hashval ^= (hashval >> 6);
1921 		} else {
1922 			/*
1923 			 * This is incredibly painful, but it beats the hell
1924 			 * out of the alternative.
1925 			 */
1926 			uint64_t j, size = key[i].dttk_size;
1927 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1928 
1929 			if (!dtrace_canload(base, size, mstate, vstate))
1930 				break;
1931 
1932 			for (j = 0; j < size; j++) {
1933 				hashval += dtrace_load8(base + j);
1934 				hashval += (hashval << 10);
1935 				hashval ^= (hashval >> 6);
1936 			}
1937 		}
1938 	}
1939 
1940 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1941 		return (NULL);
1942 
1943 	hashval += (hashval << 3);
1944 	hashval ^= (hashval >> 11);
1945 	hashval += (hashval << 15);
1946 
1947 	/*
1948 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1949 	 * comes out to be one of our two sentinel hash values.  If this
1950 	 * actually happens, we set the hashval to be a value known to be a
1951 	 * non-sentinel value.
1952 	 */
1953 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1954 		hashval = DTRACE_DYNHASH_VALID;
1955 
1956 	/*
1957 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1958 	 * important here, tricks can be pulled to reduce it.  (However, it's
1959 	 * critical that hash collisions be kept to an absolute minimum;
1960 	 * they're much more painful than a divide.)  It's better to have a
1961 	 * solution that generates few collisions and still keeps things
1962 	 * relatively simple.
1963 	 */
1964 	bucket = hashval % dstate->dtds_hashsize;
1965 
1966 	if (op == DTRACE_DYNVAR_DEALLOC) {
1967 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1968 
1969 		for (;;) {
1970 			while ((lock = *lockp) & 1)
1971 				continue;
1972 
1973 			if (dtrace_casptr((volatile void *)lockp,
1974 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1975 				break;
1976 		}
1977 
1978 		dtrace_membar_producer();
1979 	}
1980 
1981 top:
1982 	prev = NULL;
1983 	lock = hash[bucket].dtdh_lock;
1984 
1985 	dtrace_membar_consumer();
1986 
1987 	start = hash[bucket].dtdh_chain;
1988 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1989 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1990 	    op != DTRACE_DYNVAR_DEALLOC));
1991 
1992 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1993 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1994 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1995 
1996 		if (dvar->dtdv_hashval != hashval) {
1997 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1998 				/*
1999 				 * We've reached the sink, and therefore the
2000 				 * end of the hash chain; we can kick out of
2001 				 * the loop knowing that we have seen a valid
2002 				 * snapshot of state.
2003 				 */
2004 				ASSERT(dvar->dtdv_next == NULL);
2005 				ASSERT(dvar == &dtrace_dynhash_sink);
2006 				break;
2007 			}
2008 
2009 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2010 				/*
2011 				 * We've gone off the rails:  somewhere along
2012 				 * the line, one of the members of this hash
2013 				 * chain was deleted.  Note that we could also
2014 				 * detect this by simply letting this loop run
2015 				 * to completion, as we would eventually hit
2016 				 * the end of the dirty list.  However, we
2017 				 * want to avoid running the length of the
2018 				 * dirty list unnecessarily (it might be quite
2019 				 * long), so we catch this as early as
2020 				 * possible by detecting the hash marker.  In
2021 				 * this case, we simply set dvar to NULL and
2022 				 * break; the conditional after the loop will
2023 				 * send us back to top.
2024 				 */
2025 				dvar = NULL;
2026 				break;
2027 			}
2028 
2029 			goto next;
2030 		}
2031 
2032 		if (dtuple->dtt_nkeys != nkeys)
2033 			goto next;
2034 
2035 		for (i = 0; i < nkeys; i++, dkey++) {
2036 			if (dkey->dttk_size != key[i].dttk_size)
2037 				goto next; /* size or type mismatch */
2038 
2039 			if (dkey->dttk_size != 0) {
2040 				if (dtrace_bcmp(
2041 				    (void *)(uintptr_t)key[i].dttk_value,
2042 				    (void *)(uintptr_t)dkey->dttk_value,
2043 				    dkey->dttk_size))
2044 					goto next;
2045 			} else {
2046 				if (dkey->dttk_value != key[i].dttk_value)
2047 					goto next;
2048 			}
2049 		}
2050 
2051 		if (op != DTRACE_DYNVAR_DEALLOC)
2052 			return (dvar);
2053 
2054 		ASSERT(dvar->dtdv_next == NULL ||
2055 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2056 
2057 		if (prev != NULL) {
2058 			ASSERT(hash[bucket].dtdh_chain != dvar);
2059 			ASSERT(start != dvar);
2060 			ASSERT(prev->dtdv_next == dvar);
2061 			prev->dtdv_next = dvar->dtdv_next;
2062 		} else {
2063 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2064 			    start, dvar->dtdv_next) != start) {
2065 				/*
2066 				 * We have failed to atomically swing the
2067 				 * hash table head pointer, presumably because
2068 				 * of a conflicting allocation on another CPU.
2069 				 * We need to reread the hash chain and try
2070 				 * again.
2071 				 */
2072 				goto top;
2073 			}
2074 		}
2075 
2076 		dtrace_membar_producer();
2077 
2078 		/*
2079 		 * Now set the hash value to indicate that it's free.
2080 		 */
2081 		ASSERT(hash[bucket].dtdh_chain != dvar);
2082 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2083 
2084 		dtrace_membar_producer();
2085 
2086 		/*
2087 		 * Set the next pointer to point at the dirty list, and
2088 		 * atomically swing the dirty pointer to the newly freed dvar.
2089 		 */
2090 		do {
2091 			next = dcpu->dtdsc_dirty;
2092 			dvar->dtdv_next = next;
2093 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2094 
2095 		/*
2096 		 * Finally, unlock this hash bucket.
2097 		 */
2098 		ASSERT(hash[bucket].dtdh_lock == lock);
2099 		ASSERT(lock & 1);
2100 		hash[bucket].dtdh_lock++;
2101 
2102 		return (NULL);
2103 next:
2104 		prev = dvar;
2105 		continue;
2106 	}
2107 
2108 	if (dvar == NULL) {
2109 		/*
2110 		 * If dvar is NULL, it is because we went off the rails:
2111 		 * one of the elements that we traversed in the hash chain
2112 		 * was deleted while we were traversing it.  In this case,
2113 		 * we assert that we aren't doing a dealloc (deallocs lock
2114 		 * the hash bucket to prevent themselves from racing with
2115 		 * one another), and retry the hash chain traversal.
2116 		 */
2117 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2118 		goto top;
2119 	}
2120 
2121 	if (op != DTRACE_DYNVAR_ALLOC) {
2122 		/*
2123 		 * If we are not to allocate a new variable, we want to
2124 		 * return NULL now.  Before we return, check that the value
2125 		 * of the lock word hasn't changed.  If it has, we may have
2126 		 * seen an inconsistent snapshot.
2127 		 */
2128 		if (op == DTRACE_DYNVAR_NOALLOC) {
2129 			if (hash[bucket].dtdh_lock != lock)
2130 				goto top;
2131 		} else {
2132 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2133 			ASSERT(hash[bucket].dtdh_lock == lock);
2134 			ASSERT(lock & 1);
2135 			hash[bucket].dtdh_lock++;
2136 		}
2137 
2138 		return (NULL);
2139 	}
2140 
2141 	/*
2142 	 * We need to allocate a new dynamic variable.  The size we need is the
2143 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2144 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2145 	 * the size of any referred-to data (dsize).  We then round the final
2146 	 * size up to the chunksize for allocation.
2147 	 */
2148 	for (ksize = 0, i = 0; i < nkeys; i++)
2149 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2150 
2151 	/*
2152 	 * This should be pretty much impossible, but could happen if, say,
2153 	 * strange DIF specified the tuple.  Ideally, this should be an
2154 	 * assertion and not an error condition -- but that requires that the
2155 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2156 	 * bullet-proof.  (That is, it must not be able to be fooled by
2157 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2158 	 * solving this would presumably not amount to solving the Halting
2159 	 * Problem -- but it still seems awfully hard.
2160 	 */
2161 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2162 	    ksize + dsize > chunksize) {
2163 		dcpu->dtdsc_drops++;
2164 		return (NULL);
2165 	}
2166 
2167 	nstate = DTRACE_DSTATE_EMPTY;
2168 
2169 	do {
2170 retry:
2171 		free = dcpu->dtdsc_free;
2172 
2173 		if (free == NULL) {
2174 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2175 			void *rval;
2176 
2177 			if (clean == NULL) {
2178 				/*
2179 				 * We're out of dynamic variable space on
2180 				 * this CPU.  Unless we have tried all CPUs,
2181 				 * we'll try to allocate from a different
2182 				 * CPU.
2183 				 */
2184 				switch (dstate->dtds_state) {
2185 				case DTRACE_DSTATE_CLEAN: {
2186 					void *sp = &dstate->dtds_state;
2187 
2188 					if (++cpu >= NCPU)
2189 						cpu = 0;
2190 
2191 					if (dcpu->dtdsc_dirty != NULL &&
2192 					    nstate == DTRACE_DSTATE_EMPTY)
2193 						nstate = DTRACE_DSTATE_DIRTY;
2194 
2195 					if (dcpu->dtdsc_rinsing != NULL)
2196 						nstate = DTRACE_DSTATE_RINSING;
2197 
2198 					dcpu = &dstate->dtds_percpu[cpu];
2199 
2200 					if (cpu != me)
2201 						goto retry;
2202 
2203 					(void) dtrace_cas32(sp,
2204 					    DTRACE_DSTATE_CLEAN, nstate);
2205 
2206 					/*
2207 					 * To increment the correct bean
2208 					 * counter, take another lap.
2209 					 */
2210 					goto retry;
2211 				}
2212 
2213 				case DTRACE_DSTATE_DIRTY:
2214 					dcpu->dtdsc_dirty_drops++;
2215 					break;
2216 
2217 				case DTRACE_DSTATE_RINSING:
2218 					dcpu->dtdsc_rinsing_drops++;
2219 					break;
2220 
2221 				case DTRACE_DSTATE_EMPTY:
2222 					dcpu->dtdsc_drops++;
2223 					break;
2224 				}
2225 
2226 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2227 				return (NULL);
2228 			}
2229 
2230 			/*
2231 			 * The clean list appears to be non-empty.  We want to
2232 			 * move the clean list to the free list; we start by
2233 			 * moving the clean pointer aside.
2234 			 */
2235 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2236 			    clean, NULL) != clean) {
2237 				/*
2238 				 * We are in one of two situations:
2239 				 *
2240 				 *  (a)	The clean list was switched to the
2241 				 *	free list by another CPU.
2242 				 *
2243 				 *  (b)	The clean list was added to by the
2244 				 *	cleansing cyclic.
2245 				 *
2246 				 * In either of these situations, we can
2247 				 * just reattempt the free list allocation.
2248 				 */
2249 				goto retry;
2250 			}
2251 
2252 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2253 
2254 			/*
2255 			 * Now we'll move the clean list to our free list.
2256 			 * It's impossible for this to fail:  the only way
2257 			 * the free list can be updated is through this
2258 			 * code path, and only one CPU can own the clean list.
2259 			 * Thus, it would only be possible for this to fail if
2260 			 * this code were racing with dtrace_dynvar_clean().
2261 			 * (That is, if dtrace_dynvar_clean() updated the clean
2262 			 * list, and we ended up racing to update the free
2263 			 * list.)  This race is prevented by the dtrace_sync()
2264 			 * in dtrace_dynvar_clean() -- which flushes the
2265 			 * owners of the clean lists out before resetting
2266 			 * the clean lists.
2267 			 */
2268 			dcpu = &dstate->dtds_percpu[me];
2269 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2270 			ASSERT(rval == NULL);
2271 			goto retry;
2272 		}
2273 
2274 		dvar = free;
2275 		new_free = dvar->dtdv_next;
2276 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2277 
2278 	/*
2279 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2280 	 * tuple array and copy any referenced key data into the data space
2281 	 * following the tuple array.  As we do this, we relocate dttk_value
2282 	 * in the final tuple to point to the key data address in the chunk.
2283 	 */
2284 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2285 	dvar->dtdv_data = (void *)(kdata + ksize);
2286 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2287 
2288 	for (i = 0; i < nkeys; i++) {
2289 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2290 		size_t kesize = key[i].dttk_size;
2291 
2292 		if (kesize != 0) {
2293 			dtrace_bcopy(
2294 			    (const void *)(uintptr_t)key[i].dttk_value,
2295 			    (void *)kdata, kesize);
2296 			dkey->dttk_value = kdata;
2297 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2298 		} else {
2299 			dkey->dttk_value = key[i].dttk_value;
2300 		}
2301 
2302 		dkey->dttk_size = kesize;
2303 	}
2304 
2305 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2306 	dvar->dtdv_hashval = hashval;
2307 	dvar->dtdv_next = start;
2308 
2309 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2310 		return (dvar);
2311 
2312 	/*
2313 	 * The cas has failed.  Either another CPU is adding an element to
2314 	 * this hash chain, or another CPU is deleting an element from this
2315 	 * hash chain.  The simplest way to deal with both of these cases
2316 	 * (though not necessarily the most efficient) is to free our
2317 	 * allocated block and re-attempt it all.  Note that the free is
2318 	 * to the dirty list and _not_ to the free list.  This is to prevent
2319 	 * races with allocators, above.
2320 	 */
2321 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2322 
2323 	dtrace_membar_producer();
2324 
2325 	do {
2326 		free = dcpu->dtdsc_dirty;
2327 		dvar->dtdv_next = free;
2328 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2329 
2330 	goto top;
2331 }
2332 
2333 /*ARGSUSED*/
2334 static void
2335 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2336 {
2337 	if ((int64_t)nval < (int64_t)*oval)
2338 		*oval = nval;
2339 }
2340 
2341 /*ARGSUSED*/
2342 static void
2343 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2344 {
2345 	if ((int64_t)nval > (int64_t)*oval)
2346 		*oval = nval;
2347 }
2348 
2349 static void
2350 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2351 {
2352 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2353 	int64_t val = (int64_t)nval;
2354 
2355 	if (val < 0) {
2356 		for (i = 0; i < zero; i++) {
2357 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2358 				quanta[i] += incr;
2359 				return;
2360 			}
2361 		}
2362 	} else {
2363 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2364 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2365 				quanta[i - 1] += incr;
2366 				return;
2367 			}
2368 		}
2369 
2370 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2371 		return;
2372 	}
2373 
2374 	ASSERT(0);
2375 }
2376 
2377 static void
2378 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2379 {
2380 	uint64_t arg = *lquanta++;
2381 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2382 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2383 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2384 	int32_t val = (int32_t)nval, level;
2385 
2386 	ASSERT(step != 0);
2387 	ASSERT(levels != 0);
2388 
2389 	if (val < base) {
2390 		/*
2391 		 * This is an underflow.
2392 		 */
2393 		lquanta[0] += incr;
2394 		return;
2395 	}
2396 
2397 	level = (val - base) / step;
2398 
2399 	if (level < levels) {
2400 		lquanta[level + 1] += incr;
2401 		return;
2402 	}
2403 
2404 	/*
2405 	 * This is an overflow.
2406 	 */
2407 	lquanta[levels + 1] += incr;
2408 }
2409 
2410 static int
2411 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2412     uint16_t high, uint16_t nsteps, int64_t value)
2413 {
2414 	int64_t this = 1, last, next;
2415 	int base = 1, order;
2416 
2417 	ASSERT(factor <= nsteps);
2418 	ASSERT(nsteps % factor == 0);
2419 
2420 	for (order = 0; order < low; order++)
2421 		this *= factor;
2422 
2423 	/*
2424 	 * If our value is less than our factor taken to the power of the
2425 	 * low order of magnitude, it goes into the zeroth bucket.
2426 	 */
2427 	if (value < (last = this))
2428 		return (0);
2429 
2430 	for (this *= factor; order <= high; order++) {
2431 		int nbuckets = this > nsteps ? nsteps : this;
2432 
2433 		if ((next = this * factor) < this) {
2434 			/*
2435 			 * We should not generally get log/linear quantizations
2436 			 * with a high magnitude that allows 64-bits to
2437 			 * overflow, but we nonetheless protect against this
2438 			 * by explicitly checking for overflow, and clamping
2439 			 * our value accordingly.
2440 			 */
2441 			value = this - 1;
2442 		}
2443 
2444 		if (value < this) {
2445 			/*
2446 			 * If our value lies within this order of magnitude,
2447 			 * determine its position by taking the offset within
2448 			 * the order of magnitude, dividing by the bucket
2449 			 * width, and adding to our (accumulated) base.
2450 			 */
2451 			return (base + (value - last) / (this / nbuckets));
2452 		}
2453 
2454 		base += nbuckets - (nbuckets / factor);
2455 		last = this;
2456 		this = next;
2457 	}
2458 
2459 	/*
2460 	 * Our value is greater than or equal to our factor taken to the
2461 	 * power of one plus the high magnitude -- return the top bucket.
2462 	 */
2463 	return (base);
2464 }
2465 
2466 static void
2467 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2468 {
2469 	uint64_t arg = *llquanta++;
2470 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2471 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2472 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2473 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2474 
2475 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2476 	    low, high, nsteps, nval)] += incr;
2477 }
2478 
2479 /*ARGSUSED*/
2480 static void
2481 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2482 {
2483 	data[0]++;
2484 	data[1] += nval;
2485 }
2486 
2487 /*ARGSUSED*/
2488 static void
2489 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2490 {
2491 	int64_t snval = (int64_t)nval;
2492 	uint64_t tmp[2];
2493 
2494 	data[0]++;
2495 	data[1] += nval;
2496 
2497 	/*
2498 	 * What we want to say here is:
2499 	 *
2500 	 * data[2] += nval * nval;
2501 	 *
2502 	 * But given that nval is 64-bit, we could easily overflow, so
2503 	 * we do this as 128-bit arithmetic.
2504 	 */
2505 	if (snval < 0)
2506 		snval = -snval;
2507 
2508 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2509 	dtrace_add_128(data + 2, tmp, data + 2);
2510 }
2511 
2512 /*ARGSUSED*/
2513 static void
2514 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2515 {
2516 	*oval = *oval + 1;
2517 }
2518 
2519 /*ARGSUSED*/
2520 static void
2521 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2522 {
2523 	*oval += nval;
2524 }
2525 
2526 /*
2527  * Aggregate given the tuple in the principal data buffer, and the aggregating
2528  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2529  * buffer is specified as the buf parameter.  This routine does not return
2530  * failure; if there is no space in the aggregation buffer, the data will be
2531  * dropped, and a corresponding counter incremented.
2532  */
2533 static void
2534 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2535     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2536 {
2537 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2538 	uint32_t i, ndx, size, fsize;
2539 	uint32_t align = sizeof (uint64_t) - 1;
2540 	dtrace_aggbuffer_t *agb;
2541 	dtrace_aggkey_t *key;
2542 	uint32_t hashval = 0, limit, isstr;
2543 	caddr_t tomax, data, kdata;
2544 	dtrace_actkind_t action;
2545 	dtrace_action_t *act;
2546 	uintptr_t offs;
2547 
2548 	if (buf == NULL)
2549 		return;
2550 
2551 	if (!agg->dtag_hasarg) {
2552 		/*
2553 		 * Currently, only quantize() and lquantize() take additional
2554 		 * arguments, and they have the same semantics:  an increment
2555 		 * value that defaults to 1 when not present.  If additional
2556 		 * aggregating actions take arguments, the setting of the
2557 		 * default argument value will presumably have to become more
2558 		 * sophisticated...
2559 		 */
2560 		arg = 1;
2561 	}
2562 
2563 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2564 	size = rec->dtrd_offset - agg->dtag_base;
2565 	fsize = size + rec->dtrd_size;
2566 
2567 	ASSERT(dbuf->dtb_tomax != NULL);
2568 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2569 
2570 	if ((tomax = buf->dtb_tomax) == NULL) {
2571 		dtrace_buffer_drop(buf);
2572 		return;
2573 	}
2574 
2575 	/*
2576 	 * The metastructure is always at the bottom of the buffer.
2577 	 */
2578 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2579 	    sizeof (dtrace_aggbuffer_t));
2580 
2581 	if (buf->dtb_offset == 0) {
2582 		/*
2583 		 * We just kludge up approximately 1/8th of the size to be
2584 		 * buckets.  If this guess ends up being routinely
2585 		 * off-the-mark, we may need to dynamically readjust this
2586 		 * based on past performance.
2587 		 */
2588 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2589 
2590 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2591 		    (uintptr_t)tomax || hashsize == 0) {
2592 			/*
2593 			 * We've been given a ludicrously small buffer;
2594 			 * increment our drop count and leave.
2595 			 */
2596 			dtrace_buffer_drop(buf);
2597 			return;
2598 		}
2599 
2600 		/*
2601 		 * And now, a pathetic attempt to try to get a an odd (or
2602 		 * perchance, a prime) hash size for better hash distribution.
2603 		 */
2604 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2605 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2606 
2607 		agb->dtagb_hashsize = hashsize;
2608 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2609 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2610 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2611 
2612 		for (i = 0; i < agb->dtagb_hashsize; i++)
2613 			agb->dtagb_hash[i] = NULL;
2614 	}
2615 
2616 	ASSERT(agg->dtag_first != NULL);
2617 	ASSERT(agg->dtag_first->dta_intuple);
2618 
2619 	/*
2620 	 * Calculate the hash value based on the key.  Note that we _don't_
2621 	 * include the aggid in the hashing (but we will store it as part of
2622 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2623 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2624 	 * gets good distribution in practice.  The efficacy of the hashing
2625 	 * algorithm (and a comparison with other algorithms) may be found by
2626 	 * running the ::dtrace_aggstat MDB dcmd.
2627 	 */
2628 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2629 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2630 		limit = i + act->dta_rec.dtrd_size;
2631 		ASSERT(limit <= size);
2632 		isstr = DTRACEACT_ISSTRING(act);
2633 
2634 		for (; i < limit; i++) {
2635 			hashval += data[i];
2636 			hashval += (hashval << 10);
2637 			hashval ^= (hashval >> 6);
2638 
2639 			if (isstr && data[i] == '\0')
2640 				break;
2641 		}
2642 	}
2643 
2644 	hashval += (hashval << 3);
2645 	hashval ^= (hashval >> 11);
2646 	hashval += (hashval << 15);
2647 
2648 	/*
2649 	 * Yes, the divide here is expensive -- but it's generally the least
2650 	 * of the performance issues given the amount of data that we iterate
2651 	 * over to compute hash values, compare data, etc.
2652 	 */
2653 	ndx = hashval % agb->dtagb_hashsize;
2654 
2655 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2656 		ASSERT((caddr_t)key >= tomax);
2657 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2658 
2659 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2660 			continue;
2661 
2662 		kdata = key->dtak_data;
2663 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2664 
2665 		for (act = agg->dtag_first; act->dta_intuple;
2666 		    act = act->dta_next) {
2667 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2668 			limit = i + act->dta_rec.dtrd_size;
2669 			ASSERT(limit <= size);
2670 			isstr = DTRACEACT_ISSTRING(act);
2671 
2672 			for (; i < limit; i++) {
2673 				if (kdata[i] != data[i])
2674 					goto next;
2675 
2676 				if (isstr && data[i] == '\0')
2677 					break;
2678 			}
2679 		}
2680 
2681 		if (action != key->dtak_action) {
2682 			/*
2683 			 * We are aggregating on the same value in the same
2684 			 * aggregation with two different aggregating actions.
2685 			 * (This should have been picked up in the compiler,
2686 			 * so we may be dealing with errant or devious DIF.)
2687 			 * This is an error condition; we indicate as much,
2688 			 * and return.
2689 			 */
2690 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2691 			return;
2692 		}
2693 
2694 		/*
2695 		 * This is a hit:  we need to apply the aggregator to
2696 		 * the value at this key.
2697 		 */
2698 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2699 		return;
2700 next:
2701 		continue;
2702 	}
2703 
2704 	/*
2705 	 * We didn't find it.  We need to allocate some zero-filled space,
2706 	 * link it into the hash table appropriately, and apply the aggregator
2707 	 * to the (zero-filled) value.
2708 	 */
2709 	offs = buf->dtb_offset;
2710 	while (offs & (align - 1))
2711 		offs += sizeof (uint32_t);
2712 
2713 	/*
2714 	 * If we don't have enough room to both allocate a new key _and_
2715 	 * its associated data, increment the drop count and return.
2716 	 */
2717 	if ((uintptr_t)tomax + offs + fsize >
2718 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2719 		dtrace_buffer_drop(buf);
2720 		return;
2721 	}
2722 
2723 	/*CONSTCOND*/
2724 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2725 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2726 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2727 
2728 	key->dtak_data = kdata = tomax + offs;
2729 	buf->dtb_offset = offs + fsize;
2730 
2731 	/*
2732 	 * Now copy the data across.
2733 	 */
2734 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2735 
2736 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2737 		kdata[i] = data[i];
2738 
2739 	/*
2740 	 * Because strings are not zeroed out by default, we need to iterate
2741 	 * looking for actions that store strings, and we need to explicitly
2742 	 * pad these strings out with zeroes.
2743 	 */
2744 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2745 		int nul;
2746 
2747 		if (!DTRACEACT_ISSTRING(act))
2748 			continue;
2749 
2750 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2751 		limit = i + act->dta_rec.dtrd_size;
2752 		ASSERT(limit <= size);
2753 
2754 		for (nul = 0; i < limit; i++) {
2755 			if (nul) {
2756 				kdata[i] = '\0';
2757 				continue;
2758 			}
2759 
2760 			if (data[i] != '\0')
2761 				continue;
2762 
2763 			nul = 1;
2764 		}
2765 	}
2766 
2767 	for (i = size; i < fsize; i++)
2768 		kdata[i] = 0;
2769 
2770 	key->dtak_hashval = hashval;
2771 	key->dtak_size = size;
2772 	key->dtak_action = action;
2773 	key->dtak_next = agb->dtagb_hash[ndx];
2774 	agb->dtagb_hash[ndx] = key;
2775 
2776 	/*
2777 	 * Finally, apply the aggregator.
2778 	 */
2779 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2780 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2781 }
2782 
2783 /*
2784  * Given consumer state, this routine finds a speculation in the INACTIVE
2785  * state and transitions it into the ACTIVE state.  If there is no speculation
2786  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2787  * incremented -- it is up to the caller to take appropriate action.
2788  */
2789 static int
2790 dtrace_speculation(dtrace_state_t *state)
2791 {
2792 	int i = 0;
2793 	dtrace_speculation_state_t curstate;
2794 	uint32_t *stat = &state->dts_speculations_unavail, count;
2795 
2796 	while (i < state->dts_nspeculations) {
2797 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2798 
2799 		curstate = spec->dtsp_state;
2800 
2801 		if (curstate != DTRACESPEC_INACTIVE) {
2802 			if (curstate == DTRACESPEC_COMMITTINGMANY ||
2803 			    curstate == DTRACESPEC_COMMITTING ||
2804 			    curstate == DTRACESPEC_DISCARDING)
2805 				stat = &state->dts_speculations_busy;
2806 			i++;
2807 			continue;
2808 		}
2809 
2810 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2811 		    curstate, DTRACESPEC_ACTIVE) == curstate)
2812 			return (i + 1);
2813 	}
2814 
2815 	/*
2816 	 * We couldn't find a speculation.  If we found as much as a single
2817 	 * busy speculation buffer, we'll attribute this failure as "busy"
2818 	 * instead of "unavail".
2819 	 */
2820 	do {
2821 		count = *stat;
2822 	} while (dtrace_cas32(stat, count, count + 1) != count);
2823 
2824 	return (0);
2825 }
2826 
2827 /*
2828  * This routine commits an active speculation.  If the specified speculation
2829  * is not in a valid state to perform a commit(), this routine will silently do
2830  * nothing.  The state of the specified speculation is transitioned according
2831  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2832  */
2833 static void
2834 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2835     dtrace_specid_t which)
2836 {
2837 	dtrace_speculation_t *spec;
2838 	dtrace_buffer_t *src, *dest;
2839 	uintptr_t daddr, saddr, dlimit, slimit;
2840 	dtrace_speculation_state_t curstate, new = 0;
2841 	intptr_t offs;
2842 	uint64_t timestamp;
2843 
2844 	if (which == 0)
2845 		return;
2846 
2847 	if (which > state->dts_nspeculations) {
2848 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2849 		return;
2850 	}
2851 
2852 	spec = &state->dts_speculations[which - 1];
2853 	src = &spec->dtsp_buffer[cpu];
2854 	dest = &state->dts_buffer[cpu];
2855 
2856 	do {
2857 		curstate = spec->dtsp_state;
2858 
2859 		if (curstate == DTRACESPEC_COMMITTINGMANY)
2860 			break;
2861 
2862 		switch (curstate) {
2863 		case DTRACESPEC_INACTIVE:
2864 		case DTRACESPEC_DISCARDING:
2865 			return;
2866 
2867 		case DTRACESPEC_COMMITTING:
2868 			/*
2869 			 * This is only possible if we are (a) commit()'ing
2870 			 * without having done a prior speculate() on this CPU
2871 			 * and (b) racing with another commit() on a different
2872 			 * CPU.  There's nothing to do -- we just assert that
2873 			 * our offset is 0.
2874 			 */
2875 			ASSERT(src->dtb_offset == 0);
2876 			return;
2877 
2878 		case DTRACESPEC_ACTIVE:
2879 			new = DTRACESPEC_COMMITTING;
2880 			break;
2881 
2882 		case DTRACESPEC_ACTIVEONE:
2883 			/*
2884 			 * This speculation is active on one CPU.  If our
2885 			 * buffer offset is non-zero, we know that the one CPU
2886 			 * must be us.  Otherwise, we are committing on a
2887 			 * different CPU from the speculate(), and we must
2888 			 * rely on being asynchronously cleaned.
2889 			 */
2890 			if (src->dtb_offset != 0) {
2891 				new = DTRACESPEC_COMMITTING;
2892 				break;
2893 			}
2894 			/*FALLTHROUGH*/
2895 
2896 		case DTRACESPEC_ACTIVEMANY:
2897 			new = DTRACESPEC_COMMITTINGMANY;
2898 			break;
2899 
2900 		default:
2901 			ASSERT(0);
2902 		}
2903 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2904 	    curstate, new) != curstate);
2905 
2906 	/*
2907 	 * We have set the state to indicate that we are committing this
2908 	 * speculation.  Now reserve the necessary space in the destination
2909 	 * buffer.
2910 	 */
2911 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2912 	    sizeof (uint64_t), state, NULL)) < 0) {
2913 		dtrace_buffer_drop(dest);
2914 		goto out;
2915 	}
2916 
2917 	/*
2918 	 * We have sufficient space to copy the speculative buffer into the
2919 	 * primary buffer.  First, modify the speculative buffer, filling
2920 	 * in the timestamp of all entries with the curstate time.  The data
2921 	 * must have the commit() time rather than the time it was traced,
2922 	 * so that all entries in the primary buffer are in timestamp order.
2923 	 */
2924 	timestamp = dtrace_gethrtime();
2925 	saddr = (uintptr_t)src->dtb_tomax;
2926 	slimit = saddr + src->dtb_offset;
2927 	while (saddr < slimit) {
2928 		size_t size;
2929 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2930 
2931 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2932 			saddr += sizeof (dtrace_epid_t);
2933 			continue;
2934 		}
2935 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2936 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2937 
2938 		ASSERT3U(saddr + size, <=, slimit);
2939 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2940 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2941 
2942 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2943 
2944 		saddr += size;
2945 	}
2946 
2947 	/*
2948 	 * Copy the buffer across.  (Note that this is a
2949 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2950 	 * a serious performance issue, a high-performance DTrace-specific
2951 	 * bcopy() should obviously be invented.)
2952 	 */
2953 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2954 	dlimit = daddr + src->dtb_offset;
2955 	saddr = (uintptr_t)src->dtb_tomax;
2956 
2957 	/*
2958 	 * First, the aligned portion.
2959 	 */
2960 	while (dlimit - daddr >= sizeof (uint64_t)) {
2961 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2962 
2963 		daddr += sizeof (uint64_t);
2964 		saddr += sizeof (uint64_t);
2965 	}
2966 
2967 	/*
2968 	 * Now any left-over bit...
2969 	 */
2970 	while (dlimit - daddr)
2971 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2972 
2973 	/*
2974 	 * Finally, commit the reserved space in the destination buffer.
2975 	 */
2976 	dest->dtb_offset = offs + src->dtb_offset;
2977 
2978 out:
2979 	/*
2980 	 * If we're lucky enough to be the only active CPU on this speculation
2981 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2982 	 */
2983 	if (curstate == DTRACESPEC_ACTIVE ||
2984 	    (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2985 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2986 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2987 
2988 		ASSERT(rval == DTRACESPEC_COMMITTING);
2989 	}
2990 
2991 	src->dtb_offset = 0;
2992 	src->dtb_xamot_drops += src->dtb_drops;
2993 	src->dtb_drops = 0;
2994 }
2995 
2996 /*
2997  * This routine discards an active speculation.  If the specified speculation
2998  * is not in a valid state to perform a discard(), this routine will silently
2999  * do nothing.  The state of the specified speculation is transitioned
3000  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3001  */
3002 static void
3003 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3004     dtrace_specid_t which)
3005 {
3006 	dtrace_speculation_t *spec;
3007 	dtrace_speculation_state_t curstate, new = 0;
3008 	dtrace_buffer_t *buf;
3009 
3010 	if (which == 0)
3011 		return;
3012 
3013 	if (which > state->dts_nspeculations) {
3014 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3015 		return;
3016 	}
3017 
3018 	spec = &state->dts_speculations[which - 1];
3019 	buf = &spec->dtsp_buffer[cpu];
3020 
3021 	do {
3022 		curstate = spec->dtsp_state;
3023 
3024 		switch (curstate) {
3025 		case DTRACESPEC_INACTIVE:
3026 		case DTRACESPEC_COMMITTINGMANY:
3027 		case DTRACESPEC_COMMITTING:
3028 		case DTRACESPEC_DISCARDING:
3029 			return;
3030 
3031 		case DTRACESPEC_ACTIVE:
3032 		case DTRACESPEC_ACTIVEMANY:
3033 			new = DTRACESPEC_DISCARDING;
3034 			break;
3035 
3036 		case DTRACESPEC_ACTIVEONE:
3037 			if (buf->dtb_offset != 0) {
3038 				new = DTRACESPEC_INACTIVE;
3039 			} else {
3040 				new = DTRACESPEC_DISCARDING;
3041 			}
3042 			break;
3043 
3044 		default:
3045 			ASSERT(0);
3046 		}
3047 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3048 	    curstate, new) != curstate);
3049 
3050 	buf->dtb_offset = 0;
3051 	buf->dtb_drops = 0;
3052 }
3053 
3054 /*
3055  * Note:  not called from probe context.  This function is called
3056  * asynchronously from cross call context to clean any speculations that are
3057  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3058  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3059  * speculation.
3060  */
3061 static void
3062 dtrace_speculation_clean_here(dtrace_state_t *state)
3063 {
3064 	dtrace_icookie_t cookie;
3065 	processorid_t cpu = curcpu;
3066 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3067 	dtrace_specid_t i;
3068 
3069 	cookie = dtrace_interrupt_disable();
3070 
3071 	if (dest->dtb_tomax == NULL) {
3072 		dtrace_interrupt_enable(cookie);
3073 		return;
3074 	}
3075 
3076 	for (i = 0; i < state->dts_nspeculations; i++) {
3077 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3078 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3079 
3080 		if (src->dtb_tomax == NULL)
3081 			continue;
3082 
3083 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3084 			src->dtb_offset = 0;
3085 			continue;
3086 		}
3087 
3088 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3089 			continue;
3090 
3091 		if (src->dtb_offset == 0)
3092 			continue;
3093 
3094 		dtrace_speculation_commit(state, cpu, i + 1);
3095 	}
3096 
3097 	dtrace_interrupt_enable(cookie);
3098 }
3099 
3100 /*
3101  * Note:  not called from probe context.  This function is called
3102  * asynchronously (and at a regular interval) to clean any speculations that
3103  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3104  * is work to be done, it cross calls all CPUs to perform that work;
3105  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3106  * INACTIVE state until they have been cleaned by all CPUs.
3107  */
3108 static void
3109 dtrace_speculation_clean(dtrace_state_t *state)
3110 {
3111 	int work = 0, rv;
3112 	dtrace_specid_t i;
3113 
3114 	for (i = 0; i < state->dts_nspeculations; i++) {
3115 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3116 
3117 		ASSERT(!spec->dtsp_cleaning);
3118 
3119 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3120 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3121 			continue;
3122 
3123 		work++;
3124 		spec->dtsp_cleaning = 1;
3125 	}
3126 
3127 	if (!work)
3128 		return;
3129 
3130 	dtrace_xcall(DTRACE_CPUALL,
3131 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3132 
3133 	/*
3134 	 * We now know that all CPUs have committed or discarded their
3135 	 * speculation buffers, as appropriate.  We can now set the state
3136 	 * to inactive.
3137 	 */
3138 	for (i = 0; i < state->dts_nspeculations; i++) {
3139 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3140 		dtrace_speculation_state_t curstate, new;
3141 
3142 		if (!spec->dtsp_cleaning)
3143 			continue;
3144 
3145 		curstate = spec->dtsp_state;
3146 		ASSERT(curstate == DTRACESPEC_DISCARDING ||
3147 		    curstate == DTRACESPEC_COMMITTINGMANY);
3148 
3149 		new = DTRACESPEC_INACTIVE;
3150 
3151 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3152 		ASSERT(rv == curstate);
3153 		spec->dtsp_cleaning = 0;
3154 	}
3155 }
3156 
3157 /*
3158  * Called as part of a speculate() to get the speculative buffer associated
3159  * with a given speculation.  Returns NULL if the specified speculation is not
3160  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3161  * the active CPU is not the specified CPU -- the speculation will be
3162  * atomically transitioned into the ACTIVEMANY state.
3163  */
3164 static dtrace_buffer_t *
3165 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3166     dtrace_specid_t which)
3167 {
3168 	dtrace_speculation_t *spec;
3169 	dtrace_speculation_state_t curstate, new = 0;
3170 	dtrace_buffer_t *buf;
3171 
3172 	if (which == 0)
3173 		return (NULL);
3174 
3175 	if (which > state->dts_nspeculations) {
3176 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3177 		return (NULL);
3178 	}
3179 
3180 	spec = &state->dts_speculations[which - 1];
3181 	buf = &spec->dtsp_buffer[cpuid];
3182 
3183 	do {
3184 		curstate = spec->dtsp_state;
3185 
3186 		switch (curstate) {
3187 		case DTRACESPEC_INACTIVE:
3188 		case DTRACESPEC_COMMITTINGMANY:
3189 		case DTRACESPEC_DISCARDING:
3190 			return (NULL);
3191 
3192 		case DTRACESPEC_COMMITTING:
3193 			ASSERT(buf->dtb_offset == 0);
3194 			return (NULL);
3195 
3196 		case DTRACESPEC_ACTIVEONE:
3197 			/*
3198 			 * This speculation is currently active on one CPU.
3199 			 * Check the offset in the buffer; if it's non-zero,
3200 			 * that CPU must be us (and we leave the state alone).
3201 			 * If it's zero, assume that we're starting on a new
3202 			 * CPU -- and change the state to indicate that the
3203 			 * speculation is active on more than one CPU.
3204 			 */
3205 			if (buf->dtb_offset != 0)
3206 				return (buf);
3207 
3208 			new = DTRACESPEC_ACTIVEMANY;
3209 			break;
3210 
3211 		case DTRACESPEC_ACTIVEMANY:
3212 			return (buf);
3213 
3214 		case DTRACESPEC_ACTIVE:
3215 			new = DTRACESPEC_ACTIVEONE;
3216 			break;
3217 
3218 		default:
3219 			ASSERT(0);
3220 		}
3221 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3222 	    curstate, new) != curstate);
3223 
3224 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3225 	return (buf);
3226 }
3227 
3228 /*
3229  * Return a string.  In the event that the user lacks the privilege to access
3230  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3231  * don't fail access checking.
3232  *
3233  * dtrace_dif_variable() uses this routine as a helper for various
3234  * builtin values such as 'execname' and 'probefunc.'
3235  */
3236 uintptr_t
3237 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3238     dtrace_mstate_t *mstate)
3239 {
3240 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3241 	uintptr_t ret;
3242 	size_t strsz;
3243 
3244 	/*
3245 	 * The easy case: this probe is allowed to read all of memory, so
3246 	 * we can just return this as a vanilla pointer.
3247 	 */
3248 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3249 		return (addr);
3250 
3251 	/*
3252 	 * This is the tougher case: we copy the string in question from
3253 	 * kernel memory into scratch memory and return it that way: this
3254 	 * ensures that we won't trip up when access checking tests the
3255 	 * BYREF return value.
3256 	 */
3257 	strsz = dtrace_strlen((char *)addr, size) + 1;
3258 
3259 	if (mstate->dtms_scratch_ptr + strsz >
3260 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3261 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3262 		return (0);
3263 	}
3264 
3265 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3266 	    strsz);
3267 	ret = mstate->dtms_scratch_ptr;
3268 	mstate->dtms_scratch_ptr += strsz;
3269 	return (ret);
3270 }
3271 
3272 /*
3273  * Return a string from a memoy address which is known to have one or
3274  * more concatenated, individually zero terminated, sub-strings.
3275  * In the event that the user lacks the privilege to access
3276  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3277  * don't fail access checking.
3278  *
3279  * dtrace_dif_variable() uses this routine as a helper for various
3280  * builtin values such as 'execargs'.
3281  */
3282 static uintptr_t
3283 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3284     dtrace_mstate_t *mstate)
3285 {
3286 	char *p;
3287 	size_t i;
3288 	uintptr_t ret;
3289 
3290 	if (mstate->dtms_scratch_ptr + strsz >
3291 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3292 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3293 		return (0);
3294 	}
3295 
3296 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3297 	    strsz);
3298 
3299 	/* Replace sub-string termination characters with a space. */
3300 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3301 	    p++, i++)
3302 		if (*p == '\0')
3303 			*p = ' ';
3304 
3305 	ret = mstate->dtms_scratch_ptr;
3306 	mstate->dtms_scratch_ptr += strsz;
3307 	return (ret);
3308 }
3309 
3310 /*
3311  * This function implements the DIF emulator's variable lookups.  The emulator
3312  * passes a reserved variable identifier and optional built-in array index.
3313  */
3314 static uint64_t
3315 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3316     uint64_t ndx)
3317 {
3318 	/*
3319 	 * If we're accessing one of the uncached arguments, we'll turn this
3320 	 * into a reference in the args array.
3321 	 */
3322 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3323 		ndx = v - DIF_VAR_ARG0;
3324 		v = DIF_VAR_ARGS;
3325 	}
3326 
3327 	switch (v) {
3328 	case DIF_VAR_ARGS:
3329 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3330 		if (ndx >= sizeof (mstate->dtms_arg) /
3331 		    sizeof (mstate->dtms_arg[0])) {
3332 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3333 			dtrace_provider_t *pv;
3334 			uint64_t val;
3335 
3336 			pv = mstate->dtms_probe->dtpr_provider;
3337 			if (pv->dtpv_pops.dtps_getargval != NULL)
3338 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3339 				    mstate->dtms_probe->dtpr_id,
3340 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3341 			else
3342 				val = dtrace_getarg(ndx, aframes);
3343 
3344 			/*
3345 			 * This is regrettably required to keep the compiler
3346 			 * from tail-optimizing the call to dtrace_getarg().
3347 			 * The condition always evaluates to true, but the
3348 			 * compiler has no way of figuring that out a priori.
3349 			 * (None of this would be necessary if the compiler
3350 			 * could be relied upon to _always_ tail-optimize
3351 			 * the call to dtrace_getarg() -- but it can't.)
3352 			 */
3353 			if (mstate->dtms_probe != NULL)
3354 				return (val);
3355 
3356 			ASSERT(0);
3357 		}
3358 
3359 		return (mstate->dtms_arg[ndx]);
3360 
3361 	case DIF_VAR_REGS:
3362 	case DIF_VAR_UREGS: {
3363 		struct trapframe *tframe;
3364 
3365 		if (!dtrace_priv_proc(state))
3366 			return (0);
3367 
3368 		if (v == DIF_VAR_REGS)
3369 			tframe = curthread->t_dtrace_trapframe;
3370 		else
3371 			tframe = curthread->td_frame;
3372 
3373 		if (tframe == NULL) {
3374 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3375 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3376 			return (0);
3377 		}
3378 
3379 		return (dtrace_getreg(tframe, ndx));
3380 	}
3381 
3382 	case DIF_VAR_CURTHREAD:
3383 		if (!dtrace_priv_proc(state))
3384 			return (0);
3385 		return ((uint64_t)(uintptr_t)curthread);
3386 
3387 	case DIF_VAR_TIMESTAMP:
3388 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3389 			mstate->dtms_timestamp = dtrace_gethrtime();
3390 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3391 		}
3392 		return (mstate->dtms_timestamp);
3393 
3394 	case DIF_VAR_VTIMESTAMP:
3395 		ASSERT(dtrace_vtime_references != 0);
3396 		return (curthread->t_dtrace_vtime);
3397 
3398 	case DIF_VAR_WALLTIMESTAMP:
3399 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3400 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3401 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3402 		}
3403 		return (mstate->dtms_walltimestamp);
3404 
3405 #ifdef illumos
3406 	case DIF_VAR_IPL:
3407 		if (!dtrace_priv_kernel(state))
3408 			return (0);
3409 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3410 			mstate->dtms_ipl = dtrace_getipl();
3411 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3412 		}
3413 		return (mstate->dtms_ipl);
3414 #endif
3415 
3416 	case DIF_VAR_EPID:
3417 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3418 		return (mstate->dtms_epid);
3419 
3420 	case DIF_VAR_ID:
3421 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3422 		return (mstate->dtms_probe->dtpr_id);
3423 
3424 	case DIF_VAR_STACKDEPTH:
3425 		if (!dtrace_priv_kernel(state))
3426 			return (0);
3427 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3428 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3429 
3430 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3431 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3432 		}
3433 		return (mstate->dtms_stackdepth);
3434 
3435 	case DIF_VAR_USTACKDEPTH:
3436 		if (!dtrace_priv_proc(state))
3437 			return (0);
3438 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3439 			/*
3440 			 * See comment in DIF_VAR_PID.
3441 			 */
3442 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3443 			    CPU_ON_INTR(CPU)) {
3444 				mstate->dtms_ustackdepth = 0;
3445 			} else {
3446 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3447 				mstate->dtms_ustackdepth =
3448 				    dtrace_getustackdepth();
3449 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3450 			}
3451 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3452 		}
3453 		return (mstate->dtms_ustackdepth);
3454 
3455 	case DIF_VAR_CALLER:
3456 		if (!dtrace_priv_kernel(state))
3457 			return (0);
3458 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3459 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3460 
3461 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3462 				/*
3463 				 * If this is an unanchored probe, we are
3464 				 * required to go through the slow path:
3465 				 * dtrace_caller() only guarantees correct
3466 				 * results for anchored probes.
3467 				 */
3468 				pc_t caller[2] = {0, 0};
3469 
3470 				dtrace_getpcstack(caller, 2, aframes,
3471 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3472 				mstate->dtms_caller = caller[1];
3473 			} else if ((mstate->dtms_caller =
3474 			    dtrace_caller(aframes)) == -1) {
3475 				/*
3476 				 * We have failed to do this the quick way;
3477 				 * we must resort to the slower approach of
3478 				 * calling dtrace_getpcstack().
3479 				 */
3480 				pc_t caller = 0;
3481 
3482 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3483 				mstate->dtms_caller = caller;
3484 			}
3485 
3486 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3487 		}
3488 		return (mstate->dtms_caller);
3489 
3490 	case DIF_VAR_UCALLER:
3491 		if (!dtrace_priv_proc(state))
3492 			return (0);
3493 
3494 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3495 			uint64_t ustack[3];
3496 
3497 			/*
3498 			 * dtrace_getupcstack() fills in the first uint64_t
3499 			 * with the current PID.  The second uint64_t will
3500 			 * be the program counter at user-level.  The third
3501 			 * uint64_t will contain the caller, which is what
3502 			 * we're after.
3503 			 */
3504 			ustack[2] = 0;
3505 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3506 			dtrace_getupcstack(ustack, 3);
3507 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3508 			mstate->dtms_ucaller = ustack[2];
3509 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3510 		}
3511 
3512 		return (mstate->dtms_ucaller);
3513 
3514 	case DIF_VAR_PROBEPROV:
3515 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3516 		return (dtrace_dif_varstr(
3517 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3518 		    state, mstate));
3519 
3520 	case DIF_VAR_PROBEMOD:
3521 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3522 		return (dtrace_dif_varstr(
3523 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3524 		    state, mstate));
3525 
3526 	case DIF_VAR_PROBEFUNC:
3527 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3528 		return (dtrace_dif_varstr(
3529 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3530 		    state, mstate));
3531 
3532 	case DIF_VAR_PROBENAME:
3533 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3534 		return (dtrace_dif_varstr(
3535 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3536 		    state, mstate));
3537 
3538 	case DIF_VAR_PID:
3539 		if (!dtrace_priv_proc(state))
3540 			return (0);
3541 
3542 #ifdef illumos
3543 		/*
3544 		 * Note that we are assuming that an unanchored probe is
3545 		 * always due to a high-level interrupt.  (And we're assuming
3546 		 * that there is only a single high level interrupt.)
3547 		 */
3548 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3549 			return (pid0.pid_id);
3550 
3551 		/*
3552 		 * It is always safe to dereference one's own t_procp pointer:
3553 		 * it always points to a valid, allocated proc structure.
3554 		 * Further, it is always safe to dereference the p_pidp member
3555 		 * of one's own proc structure.  (These are truisms becuase
3556 		 * threads and processes don't clean up their own state --
3557 		 * they leave that task to whomever reaps them.)
3558 		 */
3559 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3560 #else
3561 		return ((uint64_t)curproc->p_pid);
3562 #endif
3563 
3564 	case DIF_VAR_PPID:
3565 		if (!dtrace_priv_proc(state))
3566 			return (0);
3567 
3568 #ifdef illumos
3569 		/*
3570 		 * See comment in DIF_VAR_PID.
3571 		 */
3572 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3573 			return (pid0.pid_id);
3574 
3575 		/*
3576 		 * It is always safe to dereference one's own t_procp pointer:
3577 		 * it always points to a valid, allocated proc structure.
3578 		 * (This is true because threads don't clean up their own
3579 		 * state -- they leave that task to whomever reaps them.)
3580 		 */
3581 		return ((uint64_t)curthread->t_procp->p_ppid);
3582 #else
3583 		if (curproc->p_pid == proc0.p_pid)
3584 			return (curproc->p_pid);
3585 		else
3586 			return (curproc->p_pptr->p_pid);
3587 #endif
3588 
3589 	case DIF_VAR_TID:
3590 #ifdef illumos
3591 		/*
3592 		 * See comment in DIF_VAR_PID.
3593 		 */
3594 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3595 			return (0);
3596 #endif
3597 
3598 		return ((uint64_t)curthread->t_tid);
3599 
3600 	case DIF_VAR_EXECARGS: {
3601 		struct pargs *p_args = curthread->td_proc->p_args;
3602 
3603 		if (p_args == NULL)
3604 			return(0);
3605 
3606 		return (dtrace_dif_varstrz(
3607 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3608 	}
3609 
3610 	case DIF_VAR_EXECNAME:
3611 #ifdef illumos
3612 		if (!dtrace_priv_proc(state))
3613 			return (0);
3614 
3615 		/*
3616 		 * See comment in DIF_VAR_PID.
3617 		 */
3618 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3619 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3620 
3621 		/*
3622 		 * It is always safe to dereference one's own t_procp pointer:
3623 		 * it always points to a valid, allocated proc structure.
3624 		 * (This is true because threads don't clean up their own
3625 		 * state -- they leave that task to whomever reaps them.)
3626 		 */
3627 		return (dtrace_dif_varstr(
3628 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3629 		    state, mstate));
3630 #else
3631 		return (dtrace_dif_varstr(
3632 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3633 #endif
3634 
3635 	case DIF_VAR_ZONENAME:
3636 #ifdef illumos
3637 		if (!dtrace_priv_proc(state))
3638 			return (0);
3639 
3640 		/*
3641 		 * See comment in DIF_VAR_PID.
3642 		 */
3643 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3644 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3645 
3646 		/*
3647 		 * It is always safe to dereference one's own t_procp pointer:
3648 		 * it always points to a valid, allocated proc structure.
3649 		 * (This is true because threads don't clean up their own
3650 		 * state -- they leave that task to whomever reaps them.)
3651 		 */
3652 		return (dtrace_dif_varstr(
3653 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3654 		    state, mstate));
3655 #elif defined(__FreeBSD__)
3656 	/*
3657 	 * On FreeBSD, we introduce compatibility to zonename by falling through
3658 	 * into jailname.
3659 	 */
3660 	case DIF_VAR_JAILNAME:
3661 		if (!dtrace_priv_kernel(state))
3662 			return (0);
3663 
3664 		return (dtrace_dif_varstr(
3665 		    (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3666 		    state, mstate));
3667 
3668 	case DIF_VAR_JID:
3669 		if (!dtrace_priv_kernel(state))
3670 			return (0);
3671 
3672 		return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3673 #else
3674 		return (0);
3675 #endif
3676 
3677 	case DIF_VAR_UID:
3678 		if (!dtrace_priv_proc(state))
3679 			return (0);
3680 
3681 #ifdef illumos
3682 		/*
3683 		 * See comment in DIF_VAR_PID.
3684 		 */
3685 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3686 			return ((uint64_t)p0.p_cred->cr_uid);
3687 
3688 		/*
3689 		 * It is always safe to dereference one's own t_procp pointer:
3690 		 * it always points to a valid, allocated proc structure.
3691 		 * (This is true because threads don't clean up their own
3692 		 * state -- they leave that task to whomever reaps them.)
3693 		 *
3694 		 * Additionally, it is safe to dereference one's own process
3695 		 * credential, since this is never NULL after process birth.
3696 		 */
3697 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3698 #else
3699 		return ((uint64_t)curthread->td_ucred->cr_uid);
3700 #endif
3701 
3702 	case DIF_VAR_GID:
3703 		if (!dtrace_priv_proc(state))
3704 			return (0);
3705 
3706 #ifdef illumos
3707 		/*
3708 		 * See comment in DIF_VAR_PID.
3709 		 */
3710 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3711 			return ((uint64_t)p0.p_cred->cr_gid);
3712 
3713 		/*
3714 		 * It is always safe to dereference one's own t_procp pointer:
3715 		 * it always points to a valid, allocated proc structure.
3716 		 * (This is true because threads don't clean up their own
3717 		 * state -- they leave that task to whomever reaps them.)
3718 		 *
3719 		 * Additionally, it is safe to dereference one's own process
3720 		 * credential, since this is never NULL after process birth.
3721 		 */
3722 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3723 #else
3724 		return ((uint64_t)curthread->td_ucred->cr_gid);
3725 #endif
3726 
3727 	case DIF_VAR_ERRNO: {
3728 #ifdef illumos
3729 		klwp_t *lwp;
3730 		if (!dtrace_priv_proc(state))
3731 			return (0);
3732 
3733 		/*
3734 		 * See comment in DIF_VAR_PID.
3735 		 */
3736 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3737 			return (0);
3738 
3739 		/*
3740 		 * It is always safe to dereference one's own t_lwp pointer in
3741 		 * the event that this pointer is non-NULL.  (This is true
3742 		 * because threads and lwps don't clean up their own state --
3743 		 * they leave that task to whomever reaps them.)
3744 		 */
3745 		if ((lwp = curthread->t_lwp) == NULL)
3746 			return (0);
3747 
3748 		return ((uint64_t)lwp->lwp_errno);
3749 #else
3750 		return (curthread->td_errno);
3751 #endif
3752 	}
3753 #ifndef illumos
3754 	case DIF_VAR_CPU: {
3755 		return curcpu;
3756 	}
3757 #endif
3758 	default:
3759 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3760 		return (0);
3761 	}
3762 }
3763 
3764 
3765 typedef enum dtrace_json_state {
3766 	DTRACE_JSON_REST = 1,
3767 	DTRACE_JSON_OBJECT,
3768 	DTRACE_JSON_STRING,
3769 	DTRACE_JSON_STRING_ESCAPE,
3770 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3771 	DTRACE_JSON_COLON,
3772 	DTRACE_JSON_COMMA,
3773 	DTRACE_JSON_VALUE,
3774 	DTRACE_JSON_IDENTIFIER,
3775 	DTRACE_JSON_NUMBER,
3776 	DTRACE_JSON_NUMBER_FRAC,
3777 	DTRACE_JSON_NUMBER_EXP,
3778 	DTRACE_JSON_COLLECT_OBJECT
3779 } dtrace_json_state_t;
3780 
3781 /*
3782  * This function possesses just enough knowledge about JSON to extract a single
3783  * value from a JSON string and store it in the scratch buffer.  It is able
3784  * to extract nested object values, and members of arrays by index.
3785  *
3786  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3787  * be looked up as we descend into the object tree.  e.g.
3788  *
3789  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3790  *       with nelems = 5.
3791  *
3792  * The run time of this function must be bounded above by strsize to limit the
3793  * amount of work done in probe context.  As such, it is implemented as a
3794  * simple state machine, reading one character at a time using safe loads
3795  * until we find the requested element, hit a parsing error or run off the
3796  * end of the object or string.
3797  *
3798  * As there is no way for a subroutine to return an error without interrupting
3799  * clause execution, we simply return NULL in the event of a missing key or any
3800  * other error condition.  Each NULL return in this function is commented with
3801  * the error condition it represents -- parsing or otherwise.
3802  *
3803  * The set of states for the state machine closely matches the JSON
3804  * specification (http://json.org/).  Briefly:
3805  *
3806  *   DTRACE_JSON_REST:
3807  *     Skip whitespace until we find either a top-level Object, moving
3808  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3809  *
3810  *   DTRACE_JSON_OBJECT:
3811  *     Locate the next key String in an Object.  Sets a flag to denote
3812  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3813  *
3814  *   DTRACE_JSON_COLON:
3815  *     Skip whitespace until we find the colon that separates key Strings
3816  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3817  *
3818  *   DTRACE_JSON_VALUE:
3819  *     Detects the type of the next value (String, Number, Identifier, Object
3820  *     or Array) and routes to the states that process that type.  Here we also
3821  *     deal with the element selector list if we are requested to traverse down
3822  *     into the object tree.
3823  *
3824  *   DTRACE_JSON_COMMA:
3825  *     Skip whitespace until we find the comma that separates key-value pairs
3826  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3827  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3828  *     states return to this state at the end of their value, unless otherwise
3829  *     noted.
3830  *
3831  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3832  *     Processes a Number literal from the JSON, including any exponent
3833  *     component that may be present.  Numbers are returned as strings, which
3834  *     may be passed to strtoll() if an integer is required.
3835  *
3836  *   DTRACE_JSON_IDENTIFIER:
3837  *     Processes a "true", "false" or "null" literal in the JSON.
3838  *
3839  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3840  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3841  *     Processes a String literal from the JSON, whether the String denotes
3842  *     a key, a value or part of a larger Object.  Handles all escape sequences
3843  *     present in the specification, including four-digit unicode characters,
3844  *     but merely includes the escape sequence without converting it to the
3845  *     actual escaped character.  If the String is flagged as a key, we
3846  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3847  *
3848  *   DTRACE_JSON_COLLECT_OBJECT:
3849  *     This state collects an entire Object (or Array), correctly handling
3850  *     embedded strings.  If the full element selector list matches this nested
3851  *     object, we return the Object in full as a string.  If not, we use this
3852  *     state to skip to the next value at this level and continue processing.
3853  *
3854  * NOTE: This function uses various macros from strtolctype.h to manipulate
3855  * digit values, etc -- these have all been checked to ensure they make
3856  * no additional function calls.
3857  */
3858 static char *
3859 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3860     char *dest)
3861 {
3862 	dtrace_json_state_t state = DTRACE_JSON_REST;
3863 	int64_t array_elem = INT64_MIN;
3864 	int64_t array_pos = 0;
3865 	uint8_t escape_unicount = 0;
3866 	boolean_t string_is_key = B_FALSE;
3867 	boolean_t collect_object = B_FALSE;
3868 	boolean_t found_key = B_FALSE;
3869 	boolean_t in_array = B_FALSE;
3870 	uint32_t braces = 0, brackets = 0;
3871 	char *elem = elemlist;
3872 	char *dd = dest;
3873 	uintptr_t cur;
3874 
3875 	for (cur = json; cur < json + size; cur++) {
3876 		char cc = dtrace_load8(cur);
3877 		if (cc == '\0')
3878 			return (NULL);
3879 
3880 		switch (state) {
3881 		case DTRACE_JSON_REST:
3882 			if (isspace(cc))
3883 				break;
3884 
3885 			if (cc == '{') {
3886 				state = DTRACE_JSON_OBJECT;
3887 				break;
3888 			}
3889 
3890 			if (cc == '[') {
3891 				in_array = B_TRUE;
3892 				array_pos = 0;
3893 				array_elem = dtrace_strtoll(elem, 10, size);
3894 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3895 				state = DTRACE_JSON_VALUE;
3896 				break;
3897 			}
3898 
3899 			/*
3900 			 * ERROR: expected to find a top-level object or array.
3901 			 */
3902 			return (NULL);
3903 		case DTRACE_JSON_OBJECT:
3904 			if (isspace(cc))
3905 				break;
3906 
3907 			if (cc == '"') {
3908 				state = DTRACE_JSON_STRING;
3909 				string_is_key = B_TRUE;
3910 				break;
3911 			}
3912 
3913 			/*
3914 			 * ERROR: either the object did not start with a key
3915 			 * string, or we've run off the end of the object
3916 			 * without finding the requested key.
3917 			 */
3918 			return (NULL);
3919 		case DTRACE_JSON_STRING:
3920 			if (cc == '\\') {
3921 				*dd++ = '\\';
3922 				state = DTRACE_JSON_STRING_ESCAPE;
3923 				break;
3924 			}
3925 
3926 			if (cc == '"') {
3927 				if (collect_object) {
3928 					/*
3929 					 * We don't reset the dest here, as
3930 					 * the string is part of a larger
3931 					 * object being collected.
3932 					 */
3933 					*dd++ = cc;
3934 					collect_object = B_FALSE;
3935 					state = DTRACE_JSON_COLLECT_OBJECT;
3936 					break;
3937 				}
3938 				*dd = '\0';
3939 				dd = dest; /* reset string buffer */
3940 				if (string_is_key) {
3941 					if (dtrace_strncmp(dest, elem,
3942 					    size) == 0)
3943 						found_key = B_TRUE;
3944 				} else if (found_key) {
3945 					if (nelems > 1) {
3946 						/*
3947 						 * We expected an object, not
3948 						 * this string.
3949 						 */
3950 						return (NULL);
3951 					}
3952 					return (dest);
3953 				}
3954 				state = string_is_key ? DTRACE_JSON_COLON :
3955 				    DTRACE_JSON_COMMA;
3956 				string_is_key = B_FALSE;
3957 				break;
3958 			}
3959 
3960 			*dd++ = cc;
3961 			break;
3962 		case DTRACE_JSON_STRING_ESCAPE:
3963 			*dd++ = cc;
3964 			if (cc == 'u') {
3965 				escape_unicount = 0;
3966 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3967 			} else {
3968 				state = DTRACE_JSON_STRING;
3969 			}
3970 			break;
3971 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3972 			if (!isxdigit(cc)) {
3973 				/*
3974 				 * ERROR: invalid unicode escape, expected
3975 				 * four valid hexidecimal digits.
3976 				 */
3977 				return (NULL);
3978 			}
3979 
3980 			*dd++ = cc;
3981 			if (++escape_unicount == 4)
3982 				state = DTRACE_JSON_STRING;
3983 			break;
3984 		case DTRACE_JSON_COLON:
3985 			if (isspace(cc))
3986 				break;
3987 
3988 			if (cc == ':') {
3989 				state = DTRACE_JSON_VALUE;
3990 				break;
3991 			}
3992 
3993 			/*
3994 			 * ERROR: expected a colon.
3995 			 */
3996 			return (NULL);
3997 		case DTRACE_JSON_COMMA:
3998 			if (isspace(cc))
3999 				break;
4000 
4001 			if (cc == ',') {
4002 				if (in_array) {
4003 					state = DTRACE_JSON_VALUE;
4004 					if (++array_pos == array_elem)
4005 						found_key = B_TRUE;
4006 				} else {
4007 					state = DTRACE_JSON_OBJECT;
4008 				}
4009 				break;
4010 			}
4011 
4012 			/*
4013 			 * ERROR: either we hit an unexpected character, or
4014 			 * we reached the end of the object or array without
4015 			 * finding the requested key.
4016 			 */
4017 			return (NULL);
4018 		case DTRACE_JSON_IDENTIFIER:
4019 			if (islower(cc)) {
4020 				*dd++ = cc;
4021 				break;
4022 			}
4023 
4024 			*dd = '\0';
4025 			dd = dest; /* reset string buffer */
4026 
4027 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
4028 			    dtrace_strncmp(dest, "false", 6) == 0 ||
4029 			    dtrace_strncmp(dest, "null", 5) == 0) {
4030 				if (found_key) {
4031 					if (nelems > 1) {
4032 						/*
4033 						 * ERROR: We expected an object,
4034 						 * not this identifier.
4035 						 */
4036 						return (NULL);
4037 					}
4038 					return (dest);
4039 				} else {
4040 					cur--;
4041 					state = DTRACE_JSON_COMMA;
4042 					break;
4043 				}
4044 			}
4045 
4046 			/*
4047 			 * ERROR: we did not recognise the identifier as one
4048 			 * of those in the JSON specification.
4049 			 */
4050 			return (NULL);
4051 		case DTRACE_JSON_NUMBER:
4052 			if (cc == '.') {
4053 				*dd++ = cc;
4054 				state = DTRACE_JSON_NUMBER_FRAC;
4055 				break;
4056 			}
4057 
4058 			if (cc == 'x' || cc == 'X') {
4059 				/*
4060 				 * ERROR: specification explicitly excludes
4061 				 * hexidecimal or octal numbers.
4062 				 */
4063 				return (NULL);
4064 			}
4065 
4066 			/* FALLTHRU */
4067 		case DTRACE_JSON_NUMBER_FRAC:
4068 			if (cc == 'e' || cc == 'E') {
4069 				*dd++ = cc;
4070 				state = DTRACE_JSON_NUMBER_EXP;
4071 				break;
4072 			}
4073 
4074 			if (cc == '+' || cc == '-') {
4075 				/*
4076 				 * ERROR: expect sign as part of exponent only.
4077 				 */
4078 				return (NULL);
4079 			}
4080 			/* FALLTHRU */
4081 		case DTRACE_JSON_NUMBER_EXP:
4082 			if (isdigit(cc) || cc == '+' || cc == '-') {
4083 				*dd++ = cc;
4084 				break;
4085 			}
4086 
4087 			*dd = '\0';
4088 			dd = dest; /* reset string buffer */
4089 			if (found_key) {
4090 				if (nelems > 1) {
4091 					/*
4092 					 * ERROR: We expected an object, not
4093 					 * this number.
4094 					 */
4095 					return (NULL);
4096 				}
4097 				return (dest);
4098 			}
4099 
4100 			cur--;
4101 			state = DTRACE_JSON_COMMA;
4102 			break;
4103 		case DTRACE_JSON_VALUE:
4104 			if (isspace(cc))
4105 				break;
4106 
4107 			if (cc == '{' || cc == '[') {
4108 				if (nelems > 1 && found_key) {
4109 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4110 					/*
4111 					 * If our element selector directs us
4112 					 * to descend into this nested object,
4113 					 * then move to the next selector
4114 					 * element in the list and restart the
4115 					 * state machine.
4116 					 */
4117 					while (*elem != '\0')
4118 						elem++;
4119 					elem++; /* skip the inter-element NUL */
4120 					nelems--;
4121 					dd = dest;
4122 					if (in_array) {
4123 						state = DTRACE_JSON_VALUE;
4124 						array_pos = 0;
4125 						array_elem = dtrace_strtoll(
4126 						    elem, 10, size);
4127 						found_key = array_elem == 0 ?
4128 						    B_TRUE : B_FALSE;
4129 					} else {
4130 						found_key = B_FALSE;
4131 						state = DTRACE_JSON_OBJECT;
4132 					}
4133 					break;
4134 				}
4135 
4136 				/*
4137 				 * Otherwise, we wish to either skip this
4138 				 * nested object or return it in full.
4139 				 */
4140 				if (cc == '[')
4141 					brackets = 1;
4142 				else
4143 					braces = 1;
4144 				*dd++ = cc;
4145 				state = DTRACE_JSON_COLLECT_OBJECT;
4146 				break;
4147 			}
4148 
4149 			if (cc == '"') {
4150 				state = DTRACE_JSON_STRING;
4151 				break;
4152 			}
4153 
4154 			if (islower(cc)) {
4155 				/*
4156 				 * Here we deal with true, false and null.
4157 				 */
4158 				*dd++ = cc;
4159 				state = DTRACE_JSON_IDENTIFIER;
4160 				break;
4161 			}
4162 
4163 			if (cc == '-' || isdigit(cc)) {
4164 				*dd++ = cc;
4165 				state = DTRACE_JSON_NUMBER;
4166 				break;
4167 			}
4168 
4169 			/*
4170 			 * ERROR: unexpected character at start of value.
4171 			 */
4172 			return (NULL);
4173 		case DTRACE_JSON_COLLECT_OBJECT:
4174 			if (cc == '\0')
4175 				/*
4176 				 * ERROR: unexpected end of input.
4177 				 */
4178 				return (NULL);
4179 
4180 			*dd++ = cc;
4181 			if (cc == '"') {
4182 				collect_object = B_TRUE;
4183 				state = DTRACE_JSON_STRING;
4184 				break;
4185 			}
4186 
4187 			if (cc == ']') {
4188 				if (brackets-- == 0) {
4189 					/*
4190 					 * ERROR: unbalanced brackets.
4191 					 */
4192 					return (NULL);
4193 				}
4194 			} else if (cc == '}') {
4195 				if (braces-- == 0) {
4196 					/*
4197 					 * ERROR: unbalanced braces.
4198 					 */
4199 					return (NULL);
4200 				}
4201 			} else if (cc == '{') {
4202 				braces++;
4203 			} else if (cc == '[') {
4204 				brackets++;
4205 			}
4206 
4207 			if (brackets == 0 && braces == 0) {
4208 				if (found_key) {
4209 					*dd = '\0';
4210 					return (dest);
4211 				}
4212 				dd = dest; /* reset string buffer */
4213 				state = DTRACE_JSON_COMMA;
4214 			}
4215 			break;
4216 		}
4217 	}
4218 	return (NULL);
4219 }
4220 
4221 /*
4222  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4223  * Notice that we don't bother validating the proper number of arguments or
4224  * their types in the tuple stack.  This isn't needed because all argument
4225  * interpretation is safe because of our load safety -- the worst that can
4226  * happen is that a bogus program can obtain bogus results.
4227  */
4228 static void
4229 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4230     dtrace_key_t *tupregs, int nargs,
4231     dtrace_mstate_t *mstate, dtrace_state_t *state)
4232 {
4233 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4234 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4235 	dtrace_vstate_t *vstate = &state->dts_vstate;
4236 
4237 #ifdef illumos
4238 	union {
4239 		mutex_impl_t mi;
4240 		uint64_t mx;
4241 	} m;
4242 
4243 	union {
4244 		krwlock_t ri;
4245 		uintptr_t rw;
4246 	} r;
4247 #else
4248 	struct thread *lowner;
4249 	union {
4250 		struct lock_object *li;
4251 		uintptr_t lx;
4252 	} l;
4253 #endif
4254 
4255 	switch (subr) {
4256 	case DIF_SUBR_RAND:
4257 		regs[rd] = dtrace_xoroshiro128_plus_next(
4258 		    state->dts_rstate[curcpu]);
4259 		break;
4260 
4261 #ifdef illumos
4262 	case DIF_SUBR_MUTEX_OWNED:
4263 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4264 		    mstate, vstate)) {
4265 			regs[rd] = 0;
4266 			break;
4267 		}
4268 
4269 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4270 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4271 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4272 		else
4273 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4274 		break;
4275 
4276 	case DIF_SUBR_MUTEX_OWNER:
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 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4286 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4287 		else
4288 			regs[rd] = 0;
4289 		break;
4290 
4291 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4292 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4293 		    mstate, vstate)) {
4294 			regs[rd] = 0;
4295 			break;
4296 		}
4297 
4298 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4299 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4300 		break;
4301 
4302 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4303 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4304 		    mstate, vstate)) {
4305 			regs[rd] = 0;
4306 			break;
4307 		}
4308 
4309 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4310 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4311 		break;
4312 
4313 	case DIF_SUBR_RW_READ_HELD: {
4314 		uintptr_t tmp;
4315 
4316 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4317 		    mstate, vstate)) {
4318 			regs[rd] = 0;
4319 			break;
4320 		}
4321 
4322 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4323 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4324 		break;
4325 	}
4326 
4327 	case DIF_SUBR_RW_WRITE_HELD:
4328 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4329 		    mstate, vstate)) {
4330 			regs[rd] = 0;
4331 			break;
4332 		}
4333 
4334 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4335 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4336 		break;
4337 
4338 	case DIF_SUBR_RW_ISWRITER:
4339 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4340 		    mstate, vstate)) {
4341 			regs[rd] = 0;
4342 			break;
4343 		}
4344 
4345 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4346 		regs[rd] = _RW_ISWRITER(&r.ri);
4347 		break;
4348 
4349 #else /* !illumos */
4350 	case DIF_SUBR_MUTEX_OWNED:
4351 		if (!dtrace_canload(tupregs[0].dttk_value,
4352 			sizeof (struct lock_object), mstate, vstate)) {
4353 			regs[rd] = 0;
4354 			break;
4355 		}
4356 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4357 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4358 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4359 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4360 		break;
4361 
4362 	case DIF_SUBR_MUTEX_OWNER:
4363 		if (!dtrace_canload(tupregs[0].dttk_value,
4364 			sizeof (struct lock_object), mstate, vstate)) {
4365 			regs[rd] = 0;
4366 			break;
4367 		}
4368 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4369 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4370 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4371 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4372 		regs[rd] = (uintptr_t)lowner;
4373 		break;
4374 
4375 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4376 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4377 		    mstate, vstate)) {
4378 			regs[rd] = 0;
4379 			break;
4380 		}
4381 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4382 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4383 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4384 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4385 		break;
4386 
4387 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4388 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4389 		    mstate, vstate)) {
4390 			regs[rd] = 0;
4391 			break;
4392 		}
4393 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4394 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4395 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4396 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4397 		break;
4398 
4399 	case DIF_SUBR_RW_READ_HELD:
4400 	case DIF_SUBR_SX_SHARED_HELD:
4401 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4402 		    mstate, vstate)) {
4403 			regs[rd] = 0;
4404 			break;
4405 		}
4406 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4407 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4408 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4409 		    lowner == NULL;
4410 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4411 		break;
4412 
4413 	case DIF_SUBR_RW_WRITE_HELD:
4414 	case DIF_SUBR_SX_EXCLUSIVE_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(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_ISWRITER:
4428 	case DIF_SUBR_SX_ISEXCLUSIVE:
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 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4437 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4438 		regs[rd] = (lowner == curthread);
4439 		break;
4440 #endif /* illumos */
4441 
4442 	case DIF_SUBR_BCOPY: {
4443 		/*
4444 		 * We need to be sure that the destination is in the scratch
4445 		 * region -- no other region is allowed.
4446 		 */
4447 		uintptr_t src = tupregs[0].dttk_value;
4448 		uintptr_t dest = tupregs[1].dttk_value;
4449 		size_t size = tupregs[2].dttk_value;
4450 
4451 		if (!dtrace_inscratch(dest, size, mstate)) {
4452 			*flags |= CPU_DTRACE_BADADDR;
4453 			*illval = regs[rd];
4454 			break;
4455 		}
4456 
4457 		if (!dtrace_canload(src, size, mstate, vstate)) {
4458 			regs[rd] = 0;
4459 			break;
4460 		}
4461 
4462 		dtrace_bcopy((void *)src, (void *)dest, size);
4463 		break;
4464 	}
4465 
4466 	case DIF_SUBR_ALLOCA:
4467 	case DIF_SUBR_COPYIN: {
4468 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4469 		uint64_t size =
4470 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4471 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4472 
4473 		/*
4474 		 * This action doesn't require any credential checks since
4475 		 * probes will not activate in user contexts to which the
4476 		 * enabling user does not have permissions.
4477 		 */
4478 
4479 		/*
4480 		 * Rounding up the user allocation size could have overflowed
4481 		 * a large, bogus allocation (like -1ULL) to 0.
4482 		 */
4483 		if (scratch_size < size ||
4484 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4485 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4486 			regs[rd] = 0;
4487 			break;
4488 		}
4489 
4490 		if (subr == DIF_SUBR_COPYIN) {
4491 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4492 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4493 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4494 		}
4495 
4496 		mstate->dtms_scratch_ptr += scratch_size;
4497 		regs[rd] = dest;
4498 		break;
4499 	}
4500 
4501 	case DIF_SUBR_COPYINTO: {
4502 		uint64_t size = tupregs[1].dttk_value;
4503 		uintptr_t dest = tupregs[2].dttk_value;
4504 
4505 		/*
4506 		 * This action doesn't require any credential checks since
4507 		 * probes will not activate in user contexts to which the
4508 		 * enabling user does not have permissions.
4509 		 */
4510 		if (!dtrace_inscratch(dest, size, mstate)) {
4511 			*flags |= CPU_DTRACE_BADADDR;
4512 			*illval = regs[rd];
4513 			break;
4514 		}
4515 
4516 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4517 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4518 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4519 		break;
4520 	}
4521 
4522 	case DIF_SUBR_COPYINSTR: {
4523 		uintptr_t dest = mstate->dtms_scratch_ptr;
4524 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4525 
4526 		if (nargs > 1 && tupregs[1].dttk_value < size)
4527 			size = tupregs[1].dttk_value + 1;
4528 
4529 		/*
4530 		 * This action doesn't require any credential checks since
4531 		 * probes will not activate in user contexts to which the
4532 		 * enabling user does not have permissions.
4533 		 */
4534 		if (!DTRACE_INSCRATCH(mstate, size)) {
4535 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4536 			regs[rd] = 0;
4537 			break;
4538 		}
4539 
4540 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4541 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4542 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4543 
4544 		((char *)dest)[size - 1] = '\0';
4545 		mstate->dtms_scratch_ptr += size;
4546 		regs[rd] = dest;
4547 		break;
4548 	}
4549 
4550 #ifdef illumos
4551 	case DIF_SUBR_MSGSIZE:
4552 	case DIF_SUBR_MSGDSIZE: {
4553 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4554 		uintptr_t wptr, rptr;
4555 		size_t count = 0;
4556 		int cont = 0;
4557 
4558 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4559 
4560 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4561 			    vstate)) {
4562 				regs[rd] = 0;
4563 				break;
4564 			}
4565 
4566 			wptr = dtrace_loadptr(baddr +
4567 			    offsetof(mblk_t, b_wptr));
4568 
4569 			rptr = dtrace_loadptr(baddr +
4570 			    offsetof(mblk_t, b_rptr));
4571 
4572 			if (wptr < rptr) {
4573 				*flags |= CPU_DTRACE_BADADDR;
4574 				*illval = tupregs[0].dttk_value;
4575 				break;
4576 			}
4577 
4578 			daddr = dtrace_loadptr(baddr +
4579 			    offsetof(mblk_t, b_datap));
4580 
4581 			baddr = dtrace_loadptr(baddr +
4582 			    offsetof(mblk_t, b_cont));
4583 
4584 			/*
4585 			 * We want to prevent against denial-of-service here,
4586 			 * so we're only going to search the list for
4587 			 * dtrace_msgdsize_max mblks.
4588 			 */
4589 			if (cont++ > dtrace_msgdsize_max) {
4590 				*flags |= CPU_DTRACE_ILLOP;
4591 				break;
4592 			}
4593 
4594 			if (subr == DIF_SUBR_MSGDSIZE) {
4595 				if (dtrace_load8(daddr +
4596 				    offsetof(dblk_t, db_type)) != M_DATA)
4597 					continue;
4598 			}
4599 
4600 			count += wptr - rptr;
4601 		}
4602 
4603 		if (!(*flags & CPU_DTRACE_FAULT))
4604 			regs[rd] = count;
4605 
4606 		break;
4607 	}
4608 #endif
4609 
4610 	case DIF_SUBR_PROGENYOF: {
4611 		pid_t pid = tupregs[0].dttk_value;
4612 		proc_t *p;
4613 		int rval = 0;
4614 
4615 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4616 
4617 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4618 #ifdef illumos
4619 			if (p->p_pidp->pid_id == pid) {
4620 #else
4621 			if (p->p_pid == pid) {
4622 #endif
4623 				rval = 1;
4624 				break;
4625 			}
4626 		}
4627 
4628 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4629 
4630 		regs[rd] = rval;
4631 		break;
4632 	}
4633 
4634 	case DIF_SUBR_SPECULATION:
4635 		regs[rd] = dtrace_speculation(state);
4636 		break;
4637 
4638 	case DIF_SUBR_COPYOUT: {
4639 		uintptr_t kaddr = tupregs[0].dttk_value;
4640 		uintptr_t uaddr = tupregs[1].dttk_value;
4641 		uint64_t size = tupregs[2].dttk_value;
4642 
4643 		if (!dtrace_destructive_disallow &&
4644 		    dtrace_priv_proc_control(state) &&
4645 		    !dtrace_istoxic(kaddr, size) &&
4646 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4647 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4648 			dtrace_copyout(kaddr, uaddr, size, flags);
4649 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4650 		}
4651 		break;
4652 	}
4653 
4654 	case DIF_SUBR_COPYOUTSTR: {
4655 		uintptr_t kaddr = tupregs[0].dttk_value;
4656 		uintptr_t uaddr = tupregs[1].dttk_value;
4657 		uint64_t size = tupregs[2].dttk_value;
4658 		size_t lim;
4659 
4660 		if (!dtrace_destructive_disallow &&
4661 		    dtrace_priv_proc_control(state) &&
4662 		    !dtrace_istoxic(kaddr, size) &&
4663 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4664 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4665 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4666 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4667 		}
4668 		break;
4669 	}
4670 
4671 	case DIF_SUBR_STRLEN: {
4672 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4673 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4674 		size_t lim;
4675 
4676 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4677 			regs[rd] = 0;
4678 			break;
4679 		}
4680 
4681 		regs[rd] = dtrace_strlen((char *)addr, lim);
4682 		break;
4683 	}
4684 
4685 	case DIF_SUBR_STRCHR:
4686 	case DIF_SUBR_STRRCHR: {
4687 		/*
4688 		 * We're going to iterate over the string looking for the
4689 		 * specified character.  We will iterate until we have reached
4690 		 * the string length or we have found the character.  If this
4691 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4692 		 * of the specified character instead of the first.
4693 		 */
4694 		uintptr_t addr = tupregs[0].dttk_value;
4695 		uintptr_t addr_limit;
4696 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4697 		size_t lim;
4698 		char c, target = (char)tupregs[1].dttk_value;
4699 
4700 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4701 			regs[rd] = 0;
4702 			break;
4703 		}
4704 		addr_limit = addr + lim;
4705 
4706 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4707 			if ((c = dtrace_load8(addr)) == target) {
4708 				regs[rd] = addr;
4709 
4710 				if (subr == DIF_SUBR_STRCHR)
4711 					break;
4712 			}
4713 
4714 			if (c == '\0')
4715 				break;
4716 		}
4717 		break;
4718 	}
4719 
4720 	case DIF_SUBR_STRSTR:
4721 	case DIF_SUBR_INDEX:
4722 	case DIF_SUBR_RINDEX: {
4723 		/*
4724 		 * We're going to iterate over the string looking for the
4725 		 * specified string.  We will iterate until we have reached
4726 		 * the string length or we have found the string.  (Yes, this
4727 		 * is done in the most naive way possible -- but considering
4728 		 * that the string we're searching for is likely to be
4729 		 * relatively short, the complexity of Rabin-Karp or similar
4730 		 * hardly seems merited.)
4731 		 */
4732 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4733 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4734 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4735 		size_t len = dtrace_strlen(addr, size);
4736 		size_t sublen = dtrace_strlen(substr, size);
4737 		char *limit = addr + len, *orig = addr;
4738 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4739 		int inc = 1;
4740 
4741 		regs[rd] = notfound;
4742 
4743 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4744 			regs[rd] = 0;
4745 			break;
4746 		}
4747 
4748 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4749 		    vstate)) {
4750 			regs[rd] = 0;
4751 			break;
4752 		}
4753 
4754 		/*
4755 		 * strstr() and index()/rindex() have similar semantics if
4756 		 * both strings are the empty string: strstr() returns a
4757 		 * pointer to the (empty) string, and index() and rindex()
4758 		 * both return index 0 (regardless of any position argument).
4759 		 */
4760 		if (sublen == 0 && len == 0) {
4761 			if (subr == DIF_SUBR_STRSTR)
4762 				regs[rd] = (uintptr_t)addr;
4763 			else
4764 				regs[rd] = 0;
4765 			break;
4766 		}
4767 
4768 		if (subr != DIF_SUBR_STRSTR) {
4769 			if (subr == DIF_SUBR_RINDEX) {
4770 				limit = orig - 1;
4771 				addr += len;
4772 				inc = -1;
4773 			}
4774 
4775 			/*
4776 			 * Both index() and rindex() take an optional position
4777 			 * argument that denotes the starting position.
4778 			 */
4779 			if (nargs == 3) {
4780 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4781 
4782 				/*
4783 				 * If the position argument to index() is
4784 				 * negative, Perl implicitly clamps it at
4785 				 * zero.  This semantic is a little surprising
4786 				 * given the special meaning of negative
4787 				 * positions to similar Perl functions like
4788 				 * substr(), but it appears to reflect a
4789 				 * notion that index() can start from a
4790 				 * negative index and increment its way up to
4791 				 * the string.  Given this notion, Perl's
4792 				 * rindex() is at least self-consistent in
4793 				 * that it implicitly clamps positions greater
4794 				 * than the string length to be the string
4795 				 * length.  Where Perl completely loses
4796 				 * coherence, however, is when the specified
4797 				 * substring is the empty string ("").  In
4798 				 * this case, even if the position is
4799 				 * negative, rindex() returns 0 -- and even if
4800 				 * the position is greater than the length,
4801 				 * index() returns the string length.  These
4802 				 * semantics violate the notion that index()
4803 				 * should never return a value less than the
4804 				 * specified position and that rindex() should
4805 				 * never return a value greater than the
4806 				 * specified position.  (One assumes that
4807 				 * these semantics are artifacts of Perl's
4808 				 * implementation and not the results of
4809 				 * deliberate design -- it beggars belief that
4810 				 * even Larry Wall could desire such oddness.)
4811 				 * While in the abstract one would wish for
4812 				 * consistent position semantics across
4813 				 * substr(), index() and rindex() -- or at the
4814 				 * very least self-consistent position
4815 				 * semantics for index() and rindex() -- we
4816 				 * instead opt to keep with the extant Perl
4817 				 * semantics, in all their broken glory.  (Do
4818 				 * we have more desire to maintain Perl's
4819 				 * semantics than Perl does?  Probably.)
4820 				 */
4821 				if (subr == DIF_SUBR_RINDEX) {
4822 					if (pos < 0) {
4823 						if (sublen == 0)
4824 							regs[rd] = 0;
4825 						break;
4826 					}
4827 
4828 					if (pos > len)
4829 						pos = len;
4830 				} else {
4831 					if (pos < 0)
4832 						pos = 0;
4833 
4834 					if (pos >= len) {
4835 						if (sublen == 0)
4836 							regs[rd] = len;
4837 						break;
4838 					}
4839 				}
4840 
4841 				addr = orig + pos;
4842 			}
4843 		}
4844 
4845 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4846 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4847 				if (subr != DIF_SUBR_STRSTR) {
4848 					/*
4849 					 * As D index() and rindex() are
4850 					 * modeled on Perl (and not on awk),
4851 					 * we return a zero-based (and not a
4852 					 * one-based) index.  (For you Perl
4853 					 * weenies: no, we're not going to add
4854 					 * $[ -- and shouldn't you be at a con
4855 					 * or something?)
4856 					 */
4857 					regs[rd] = (uintptr_t)(addr - orig);
4858 					break;
4859 				}
4860 
4861 				ASSERT(subr == DIF_SUBR_STRSTR);
4862 				regs[rd] = (uintptr_t)addr;
4863 				break;
4864 			}
4865 		}
4866 
4867 		break;
4868 	}
4869 
4870 	case DIF_SUBR_STRTOK: {
4871 		uintptr_t addr = tupregs[0].dttk_value;
4872 		uintptr_t tokaddr = tupregs[1].dttk_value;
4873 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4874 		uintptr_t limit, toklimit;
4875 		size_t clim;
4876 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4877 		char *dest = (char *)mstate->dtms_scratch_ptr;
4878 		int i;
4879 
4880 		/*
4881 		 * Check both the token buffer and (later) the input buffer,
4882 		 * since both could be non-scratch addresses.
4883 		 */
4884 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4885 			regs[rd] = 0;
4886 			break;
4887 		}
4888 		toklimit = tokaddr + clim;
4889 
4890 		if (!DTRACE_INSCRATCH(mstate, size)) {
4891 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4892 			regs[rd] = 0;
4893 			break;
4894 		}
4895 
4896 		if (addr == 0) {
4897 			/*
4898 			 * If the address specified is NULL, we use our saved
4899 			 * strtok pointer from the mstate.  Note that this
4900 			 * means that the saved strtok pointer is _only_
4901 			 * valid within multiple enablings of the same probe --
4902 			 * it behaves like an implicit clause-local variable.
4903 			 */
4904 			addr = mstate->dtms_strtok;
4905 			limit = mstate->dtms_strtok_limit;
4906 		} else {
4907 			/*
4908 			 * If the user-specified address is non-NULL we must
4909 			 * access check it.  This is the only time we have
4910 			 * a chance to do so, since this address may reside
4911 			 * in the string table of this clause-- future calls
4912 			 * (when we fetch addr from mstate->dtms_strtok)
4913 			 * would fail this access check.
4914 			 */
4915 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4916 			    vstate)) {
4917 				regs[rd] = 0;
4918 				break;
4919 			}
4920 			limit = addr + clim;
4921 		}
4922 
4923 		/*
4924 		 * First, zero the token map, and then process the token
4925 		 * string -- setting a bit in the map for every character
4926 		 * found in the token string.
4927 		 */
4928 		for (i = 0; i < sizeof (tokmap); i++)
4929 			tokmap[i] = 0;
4930 
4931 		for (; tokaddr < toklimit; tokaddr++) {
4932 			if ((c = dtrace_load8(tokaddr)) == '\0')
4933 				break;
4934 
4935 			ASSERT((c >> 3) < sizeof (tokmap));
4936 			tokmap[c >> 3] |= (1 << (c & 0x7));
4937 		}
4938 
4939 		for (; addr < limit; addr++) {
4940 			/*
4941 			 * We're looking for a character that is _not_
4942 			 * contained in the token string.
4943 			 */
4944 			if ((c = dtrace_load8(addr)) == '\0')
4945 				break;
4946 
4947 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4948 				break;
4949 		}
4950 
4951 		if (c == '\0') {
4952 			/*
4953 			 * We reached the end of the string without finding
4954 			 * any character that was not in the token string.
4955 			 * We return NULL in this case, and we set the saved
4956 			 * address to NULL as well.
4957 			 */
4958 			regs[rd] = 0;
4959 			mstate->dtms_strtok = 0;
4960 			mstate->dtms_strtok_limit = 0;
4961 			break;
4962 		}
4963 
4964 		/*
4965 		 * From here on, we're copying into the destination string.
4966 		 */
4967 		for (i = 0; addr < limit && i < size - 1; addr++) {
4968 			if ((c = dtrace_load8(addr)) == '\0')
4969 				break;
4970 
4971 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4972 				break;
4973 
4974 			ASSERT(i < size);
4975 			dest[i++] = c;
4976 		}
4977 
4978 		ASSERT(i < size);
4979 		dest[i] = '\0';
4980 		regs[rd] = (uintptr_t)dest;
4981 		mstate->dtms_scratch_ptr += size;
4982 		mstate->dtms_strtok = addr;
4983 		mstate->dtms_strtok_limit = limit;
4984 		break;
4985 	}
4986 
4987 	case DIF_SUBR_SUBSTR: {
4988 		uintptr_t s = tupregs[0].dttk_value;
4989 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4990 		char *d = (char *)mstate->dtms_scratch_ptr;
4991 		int64_t index = (int64_t)tupregs[1].dttk_value;
4992 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4993 		size_t len = dtrace_strlen((char *)s, size);
4994 		int64_t i;
4995 
4996 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4997 			regs[rd] = 0;
4998 			break;
4999 		}
5000 
5001 		if (!DTRACE_INSCRATCH(mstate, size)) {
5002 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5003 			regs[rd] = 0;
5004 			break;
5005 		}
5006 
5007 		if (nargs <= 2)
5008 			remaining = (int64_t)size;
5009 
5010 		if (index < 0) {
5011 			index += len;
5012 
5013 			if (index < 0 && index + remaining > 0) {
5014 				remaining += index;
5015 				index = 0;
5016 			}
5017 		}
5018 
5019 		if (index >= len || index < 0) {
5020 			remaining = 0;
5021 		} else if (remaining < 0) {
5022 			remaining += len - index;
5023 		} else if (index + remaining > size) {
5024 			remaining = size - index;
5025 		}
5026 
5027 		for (i = 0; i < remaining; i++) {
5028 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5029 				break;
5030 		}
5031 
5032 		d[i] = '\0';
5033 
5034 		mstate->dtms_scratch_ptr += size;
5035 		regs[rd] = (uintptr_t)d;
5036 		break;
5037 	}
5038 
5039 	case DIF_SUBR_JSON: {
5040 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5041 		uintptr_t json = tupregs[0].dttk_value;
5042 		size_t jsonlen = dtrace_strlen((char *)json, size);
5043 		uintptr_t elem = tupregs[1].dttk_value;
5044 		size_t elemlen = dtrace_strlen((char *)elem, size);
5045 
5046 		char *dest = (char *)mstate->dtms_scratch_ptr;
5047 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5048 		char *ee = elemlist;
5049 		int nelems = 1;
5050 		uintptr_t cur;
5051 
5052 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5053 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5054 			regs[rd] = 0;
5055 			break;
5056 		}
5057 
5058 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5059 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5060 			regs[rd] = 0;
5061 			break;
5062 		}
5063 
5064 		/*
5065 		 * Read the element selector and split it up into a packed list
5066 		 * of strings.
5067 		 */
5068 		for (cur = elem; cur < elem + elemlen; cur++) {
5069 			char cc = dtrace_load8(cur);
5070 
5071 			if (cur == elem && cc == '[') {
5072 				/*
5073 				 * If the first element selector key is
5074 				 * actually an array index then ignore the
5075 				 * bracket.
5076 				 */
5077 				continue;
5078 			}
5079 
5080 			if (cc == ']')
5081 				continue;
5082 
5083 			if (cc == '.' || cc == '[') {
5084 				nelems++;
5085 				cc = '\0';
5086 			}
5087 
5088 			*ee++ = cc;
5089 		}
5090 		*ee++ = '\0';
5091 
5092 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5093 		    nelems, dest)) != 0)
5094 			mstate->dtms_scratch_ptr += jsonlen + 1;
5095 		break;
5096 	}
5097 
5098 	case DIF_SUBR_TOUPPER:
5099 	case DIF_SUBR_TOLOWER: {
5100 		uintptr_t s = tupregs[0].dttk_value;
5101 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5102 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5103 		size_t len = dtrace_strlen((char *)s, size);
5104 		char lower, upper, convert;
5105 		int64_t i;
5106 
5107 		if (subr == DIF_SUBR_TOUPPER) {
5108 			lower = 'a';
5109 			upper = 'z';
5110 			convert = 'A';
5111 		} else {
5112 			lower = 'A';
5113 			upper = 'Z';
5114 			convert = 'a';
5115 		}
5116 
5117 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5118 			regs[rd] = 0;
5119 			break;
5120 		}
5121 
5122 		if (!DTRACE_INSCRATCH(mstate, size)) {
5123 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5124 			regs[rd] = 0;
5125 			break;
5126 		}
5127 
5128 		for (i = 0; i < size - 1; i++) {
5129 			if ((c = dtrace_load8(s + i)) == '\0')
5130 				break;
5131 
5132 			if (c >= lower && c <= upper)
5133 				c = convert + (c - lower);
5134 
5135 			dest[i] = c;
5136 		}
5137 
5138 		ASSERT(i < size);
5139 		dest[i] = '\0';
5140 		regs[rd] = (uintptr_t)dest;
5141 		mstate->dtms_scratch_ptr += size;
5142 		break;
5143 	}
5144 
5145 #ifdef illumos
5146 	case DIF_SUBR_GETMAJOR:
5147 #ifdef _LP64
5148 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5149 #else
5150 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5151 #endif
5152 		break;
5153 
5154 	case DIF_SUBR_GETMINOR:
5155 #ifdef _LP64
5156 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5157 #else
5158 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
5159 #endif
5160 		break;
5161 
5162 	case DIF_SUBR_DDI_PATHNAME: {
5163 		/*
5164 		 * This one is a galactic mess.  We are going to roughly
5165 		 * emulate ddi_pathname(), but it's made more complicated
5166 		 * by the fact that we (a) want to include the minor name and
5167 		 * (b) must proceed iteratively instead of recursively.
5168 		 */
5169 		uintptr_t dest = mstate->dtms_scratch_ptr;
5170 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5171 		char *start = (char *)dest, *end = start + size - 1;
5172 		uintptr_t daddr = tupregs[0].dttk_value;
5173 		int64_t minor = (int64_t)tupregs[1].dttk_value;
5174 		char *s;
5175 		int i, len, depth = 0;
5176 
5177 		/*
5178 		 * Due to all the pointer jumping we do and context we must
5179 		 * rely upon, we just mandate that the user must have kernel
5180 		 * read privileges to use this routine.
5181 		 */
5182 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5183 			*flags |= CPU_DTRACE_KPRIV;
5184 			*illval = daddr;
5185 			regs[rd] = 0;
5186 		}
5187 
5188 		if (!DTRACE_INSCRATCH(mstate, size)) {
5189 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5190 			regs[rd] = 0;
5191 			break;
5192 		}
5193 
5194 		*end = '\0';
5195 
5196 		/*
5197 		 * We want to have a name for the minor.  In order to do this,
5198 		 * we need to walk the minor list from the devinfo.  We want
5199 		 * to be sure that we don't infinitely walk a circular list,
5200 		 * so we check for circularity by sending a scout pointer
5201 		 * ahead two elements for every element that we iterate over;
5202 		 * if the list is circular, these will ultimately point to the
5203 		 * same element.  You may recognize this little trick as the
5204 		 * answer to a stupid interview question -- one that always
5205 		 * seems to be asked by those who had to have it laboriously
5206 		 * explained to them, and who can't even concisely describe
5207 		 * the conditions under which one would be forced to resort to
5208 		 * this technique.  Needless to say, those conditions are
5209 		 * found here -- and probably only here.  Is this the only use
5210 		 * of this infamous trick in shipping, production code?  If it
5211 		 * isn't, it probably should be...
5212 		 */
5213 		if (minor != -1) {
5214 			uintptr_t maddr = dtrace_loadptr(daddr +
5215 			    offsetof(struct dev_info, devi_minor));
5216 
5217 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5218 			uintptr_t name = offsetof(struct ddi_minor_data,
5219 			    d_minor) + offsetof(struct ddi_minor, name);
5220 			uintptr_t dev = offsetof(struct ddi_minor_data,
5221 			    d_minor) + offsetof(struct ddi_minor, dev);
5222 			uintptr_t scout;
5223 
5224 			if (maddr != NULL)
5225 				scout = dtrace_loadptr(maddr + next);
5226 
5227 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5228 				uint64_t m;
5229 #ifdef _LP64
5230 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5231 #else
5232 				m = dtrace_load32(maddr + dev) & MAXMIN;
5233 #endif
5234 				if (m != minor) {
5235 					maddr = dtrace_loadptr(maddr + next);
5236 
5237 					if (scout == NULL)
5238 						continue;
5239 
5240 					scout = dtrace_loadptr(scout + next);
5241 
5242 					if (scout == NULL)
5243 						continue;
5244 
5245 					scout = dtrace_loadptr(scout + next);
5246 
5247 					if (scout == NULL)
5248 						continue;
5249 
5250 					if (scout == maddr) {
5251 						*flags |= CPU_DTRACE_ILLOP;
5252 						break;
5253 					}
5254 
5255 					continue;
5256 				}
5257 
5258 				/*
5259 				 * We have the minor data.  Now we need to
5260 				 * copy the minor's name into the end of the
5261 				 * pathname.
5262 				 */
5263 				s = (char *)dtrace_loadptr(maddr + name);
5264 				len = dtrace_strlen(s, size);
5265 
5266 				if (*flags & CPU_DTRACE_FAULT)
5267 					break;
5268 
5269 				if (len != 0) {
5270 					if ((end -= (len + 1)) < start)
5271 						break;
5272 
5273 					*end = ':';
5274 				}
5275 
5276 				for (i = 1; i <= len; i++)
5277 					end[i] = dtrace_load8((uintptr_t)s++);
5278 				break;
5279 			}
5280 		}
5281 
5282 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5283 			ddi_node_state_t devi_state;
5284 
5285 			devi_state = dtrace_load32(daddr +
5286 			    offsetof(struct dev_info, devi_node_state));
5287 
5288 			if (*flags & CPU_DTRACE_FAULT)
5289 				break;
5290 
5291 			if (devi_state >= DS_INITIALIZED) {
5292 				s = (char *)dtrace_loadptr(daddr +
5293 				    offsetof(struct dev_info, devi_addr));
5294 				len = dtrace_strlen(s, size);
5295 
5296 				if (*flags & CPU_DTRACE_FAULT)
5297 					break;
5298 
5299 				if (len != 0) {
5300 					if ((end -= (len + 1)) < start)
5301 						break;
5302 
5303 					*end = '@';
5304 				}
5305 
5306 				for (i = 1; i <= len; i++)
5307 					end[i] = dtrace_load8((uintptr_t)s++);
5308 			}
5309 
5310 			/*
5311 			 * Now for the node name...
5312 			 */
5313 			s = (char *)dtrace_loadptr(daddr +
5314 			    offsetof(struct dev_info, devi_node_name));
5315 
5316 			daddr = dtrace_loadptr(daddr +
5317 			    offsetof(struct dev_info, devi_parent));
5318 
5319 			/*
5320 			 * If our parent is NULL (that is, if we're the root
5321 			 * node), we're going to use the special path
5322 			 * "devices".
5323 			 */
5324 			if (daddr == 0)
5325 				s = "devices";
5326 
5327 			len = dtrace_strlen(s, size);
5328 			if (*flags & CPU_DTRACE_FAULT)
5329 				break;
5330 
5331 			if ((end -= (len + 1)) < start)
5332 				break;
5333 
5334 			for (i = 1; i <= len; i++)
5335 				end[i] = dtrace_load8((uintptr_t)s++);
5336 			*end = '/';
5337 
5338 			if (depth++ > dtrace_devdepth_max) {
5339 				*flags |= CPU_DTRACE_ILLOP;
5340 				break;
5341 			}
5342 		}
5343 
5344 		if (end < start)
5345 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5346 
5347 		if (daddr == 0) {
5348 			regs[rd] = (uintptr_t)end;
5349 			mstate->dtms_scratch_ptr += size;
5350 		}
5351 
5352 		break;
5353 	}
5354 #endif
5355 
5356 	case DIF_SUBR_STRJOIN: {
5357 		char *d = (char *)mstate->dtms_scratch_ptr;
5358 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5359 		uintptr_t s1 = tupregs[0].dttk_value;
5360 		uintptr_t s2 = tupregs[1].dttk_value;
5361 		int i = 0, j = 0;
5362 		size_t lim1, lim2;
5363 		char c;
5364 
5365 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5366 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5367 			regs[rd] = 0;
5368 			break;
5369 		}
5370 
5371 		if (!DTRACE_INSCRATCH(mstate, size)) {
5372 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5373 			regs[rd] = 0;
5374 			break;
5375 		}
5376 
5377 		for (;;) {
5378 			if (i >= size) {
5379 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5380 				regs[rd] = 0;
5381 				break;
5382 			}
5383 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5384 			if ((d[i++] = c) == '\0') {
5385 				i--;
5386 				break;
5387 			}
5388 		}
5389 
5390 		for (;;) {
5391 			if (i >= size) {
5392 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5393 				regs[rd] = 0;
5394 				break;
5395 			}
5396 
5397 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5398 			if ((d[i++] = c) == '\0')
5399 				break;
5400 		}
5401 
5402 		if (i < size) {
5403 			mstate->dtms_scratch_ptr += i;
5404 			regs[rd] = (uintptr_t)d;
5405 		}
5406 
5407 		break;
5408 	}
5409 
5410 	case DIF_SUBR_STRTOLL: {
5411 		uintptr_t s = tupregs[0].dttk_value;
5412 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5413 		size_t lim;
5414 		int base = 10;
5415 
5416 		if (nargs > 1) {
5417 			if ((base = tupregs[1].dttk_value) <= 1 ||
5418 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5419 				*flags |= CPU_DTRACE_ILLOP;
5420 				break;
5421 			}
5422 		}
5423 
5424 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5425 			regs[rd] = INT64_MIN;
5426 			break;
5427 		}
5428 
5429 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5430 		break;
5431 	}
5432 
5433 	case DIF_SUBR_LLTOSTR: {
5434 		int64_t i = (int64_t)tupregs[0].dttk_value;
5435 		uint64_t val, digit;
5436 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5437 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5438 		int base = 10;
5439 
5440 		if (nargs > 1) {
5441 			if ((base = tupregs[1].dttk_value) <= 1 ||
5442 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5443 				*flags |= CPU_DTRACE_ILLOP;
5444 				break;
5445 			}
5446 		}
5447 
5448 		val = (base == 10 && i < 0) ? i * -1 : i;
5449 
5450 		if (!DTRACE_INSCRATCH(mstate, size)) {
5451 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5452 			regs[rd] = 0;
5453 			break;
5454 		}
5455 
5456 		for (*end-- = '\0'; val; val /= base) {
5457 			if ((digit = val % base) <= '9' - '0') {
5458 				*end-- = '0' + digit;
5459 			} else {
5460 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5461 			}
5462 		}
5463 
5464 		if (i == 0 && base == 16)
5465 			*end-- = '0';
5466 
5467 		if (base == 16)
5468 			*end-- = 'x';
5469 
5470 		if (i == 0 || base == 8 || base == 16)
5471 			*end-- = '0';
5472 
5473 		if (i < 0 && base == 10)
5474 			*end-- = '-';
5475 
5476 		regs[rd] = (uintptr_t)end + 1;
5477 		mstate->dtms_scratch_ptr += size;
5478 		break;
5479 	}
5480 
5481 	case DIF_SUBR_HTONS:
5482 	case DIF_SUBR_NTOHS:
5483 #if BYTE_ORDER == BIG_ENDIAN
5484 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5485 #else
5486 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5487 #endif
5488 		break;
5489 
5490 
5491 	case DIF_SUBR_HTONL:
5492 	case DIF_SUBR_NTOHL:
5493 #if BYTE_ORDER == BIG_ENDIAN
5494 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5495 #else
5496 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5497 #endif
5498 		break;
5499 
5500 
5501 	case DIF_SUBR_HTONLL:
5502 	case DIF_SUBR_NTOHLL:
5503 #if BYTE_ORDER == BIG_ENDIAN
5504 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5505 #else
5506 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5507 #endif
5508 		break;
5509 
5510 
5511 	case DIF_SUBR_DIRNAME:
5512 	case DIF_SUBR_BASENAME: {
5513 		char *dest = (char *)mstate->dtms_scratch_ptr;
5514 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5515 		uintptr_t src = tupregs[0].dttk_value;
5516 		int i, j, len = dtrace_strlen((char *)src, size);
5517 		int lastbase = -1, firstbase = -1, lastdir = -1;
5518 		int start, end;
5519 
5520 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5521 			regs[rd] = 0;
5522 			break;
5523 		}
5524 
5525 		if (!DTRACE_INSCRATCH(mstate, size)) {
5526 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5527 			regs[rd] = 0;
5528 			break;
5529 		}
5530 
5531 		/*
5532 		 * The basename and dirname for a zero-length string is
5533 		 * defined to be "."
5534 		 */
5535 		if (len == 0) {
5536 			len = 1;
5537 			src = (uintptr_t)".";
5538 		}
5539 
5540 		/*
5541 		 * Start from the back of the string, moving back toward the
5542 		 * front until we see a character that isn't a slash.  That
5543 		 * character is the last character in the basename.
5544 		 */
5545 		for (i = len - 1; i >= 0; i--) {
5546 			if (dtrace_load8(src + i) != '/')
5547 				break;
5548 		}
5549 
5550 		if (i >= 0)
5551 			lastbase = i;
5552 
5553 		/*
5554 		 * Starting from the last character in the basename, move
5555 		 * towards the front until we find a slash.  The character
5556 		 * that we processed immediately before that is the first
5557 		 * character in the basename.
5558 		 */
5559 		for (; i >= 0; i--) {
5560 			if (dtrace_load8(src + i) == '/')
5561 				break;
5562 		}
5563 
5564 		if (i >= 0)
5565 			firstbase = i + 1;
5566 
5567 		/*
5568 		 * Now keep going until we find a non-slash character.  That
5569 		 * character is the last character in the dirname.
5570 		 */
5571 		for (; i >= 0; i--) {
5572 			if (dtrace_load8(src + i) != '/')
5573 				break;
5574 		}
5575 
5576 		if (i >= 0)
5577 			lastdir = i;
5578 
5579 		ASSERT(!(lastbase == -1 && firstbase != -1));
5580 		ASSERT(!(firstbase == -1 && lastdir != -1));
5581 
5582 		if (lastbase == -1) {
5583 			/*
5584 			 * We didn't find a non-slash character.  We know that
5585 			 * the length is non-zero, so the whole string must be
5586 			 * slashes.  In either the dirname or the basename
5587 			 * case, we return '/'.
5588 			 */
5589 			ASSERT(firstbase == -1);
5590 			firstbase = lastbase = lastdir = 0;
5591 		}
5592 
5593 		if (firstbase == -1) {
5594 			/*
5595 			 * The entire string consists only of a basename
5596 			 * component.  If we're looking for dirname, we need
5597 			 * to change our string to be just "."; if we're
5598 			 * looking for a basename, we'll just set the first
5599 			 * character of the basename to be 0.
5600 			 */
5601 			if (subr == DIF_SUBR_DIRNAME) {
5602 				ASSERT(lastdir == -1);
5603 				src = (uintptr_t)".";
5604 				lastdir = 0;
5605 			} else {
5606 				firstbase = 0;
5607 			}
5608 		}
5609 
5610 		if (subr == DIF_SUBR_DIRNAME) {
5611 			if (lastdir == -1) {
5612 				/*
5613 				 * We know that we have a slash in the name --
5614 				 * or lastdir would be set to 0, above.  And
5615 				 * because lastdir is -1, we know that this
5616 				 * slash must be the first character.  (That
5617 				 * is, the full string must be of the form
5618 				 * "/basename".)  In this case, the last
5619 				 * character of the directory name is 0.
5620 				 */
5621 				lastdir = 0;
5622 			}
5623 
5624 			start = 0;
5625 			end = lastdir;
5626 		} else {
5627 			ASSERT(subr == DIF_SUBR_BASENAME);
5628 			ASSERT(firstbase != -1 && lastbase != -1);
5629 			start = firstbase;
5630 			end = lastbase;
5631 		}
5632 
5633 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5634 			dest[j] = dtrace_load8(src + i);
5635 
5636 		dest[j] = '\0';
5637 		regs[rd] = (uintptr_t)dest;
5638 		mstate->dtms_scratch_ptr += size;
5639 		break;
5640 	}
5641 
5642 	case DIF_SUBR_GETF: {
5643 		uintptr_t fd = tupregs[0].dttk_value;
5644 		struct filedesc *fdp;
5645 		file_t *fp;
5646 
5647 		if (!dtrace_priv_proc(state)) {
5648 			regs[rd] = 0;
5649 			break;
5650 		}
5651 		fdp = curproc->p_fd;
5652 		FILEDESC_SLOCK(fdp);
5653 		/*
5654 		 * XXXMJG this looks broken as no ref is taken.
5655 		 */
5656 		fp = fget_noref(fdp, fd);
5657 		mstate->dtms_getf = fp;
5658 		regs[rd] = (uintptr_t)fp;
5659 		FILEDESC_SUNLOCK(fdp);
5660 		break;
5661 	}
5662 
5663 	case DIF_SUBR_CLEANPATH: {
5664 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5665 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5666 		uintptr_t src = tupregs[0].dttk_value;
5667 		size_t lim;
5668 		int i = 0, j = 0;
5669 #ifdef illumos
5670 		zone_t *z;
5671 #endif
5672 
5673 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5674 			regs[rd] = 0;
5675 			break;
5676 		}
5677 
5678 		if (!DTRACE_INSCRATCH(mstate, size)) {
5679 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5680 			regs[rd] = 0;
5681 			break;
5682 		}
5683 
5684 		/*
5685 		 * Move forward, loading each character.
5686 		 */
5687 		do {
5688 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5689 next:
5690 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5691 				break;
5692 
5693 			if (c != '/') {
5694 				dest[j++] = c;
5695 				continue;
5696 			}
5697 
5698 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5699 
5700 			if (c == '/') {
5701 				/*
5702 				 * We have two slashes -- we can just advance
5703 				 * to the next character.
5704 				 */
5705 				goto next;
5706 			}
5707 
5708 			if (c != '.') {
5709 				/*
5710 				 * This is not "." and it's not ".." -- we can
5711 				 * just store the "/" and this character and
5712 				 * drive on.
5713 				 */
5714 				dest[j++] = '/';
5715 				dest[j++] = c;
5716 				continue;
5717 			}
5718 
5719 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5720 
5721 			if (c == '/') {
5722 				/*
5723 				 * This is a "/./" component.  We're not going
5724 				 * to store anything in the destination buffer;
5725 				 * we're just going to go to the next component.
5726 				 */
5727 				goto next;
5728 			}
5729 
5730 			if (c != '.') {
5731 				/*
5732 				 * This is not ".." -- we can just store the
5733 				 * "/." and this character and continue
5734 				 * processing.
5735 				 */
5736 				dest[j++] = '/';
5737 				dest[j++] = '.';
5738 				dest[j++] = c;
5739 				continue;
5740 			}
5741 
5742 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5743 
5744 			if (c != '/' && c != '\0') {
5745 				/*
5746 				 * This is not ".." -- it's "..[mumble]".
5747 				 * We'll store the "/.." and this character
5748 				 * and continue processing.
5749 				 */
5750 				dest[j++] = '/';
5751 				dest[j++] = '.';
5752 				dest[j++] = '.';
5753 				dest[j++] = c;
5754 				continue;
5755 			}
5756 
5757 			/*
5758 			 * This is "/../" or "/..\0".  We need to back up
5759 			 * our destination pointer until we find a "/".
5760 			 */
5761 			i--;
5762 			while (j != 0 && dest[--j] != '/')
5763 				continue;
5764 
5765 			if (c == '\0')
5766 				dest[++j] = '/';
5767 		} while (c != '\0');
5768 
5769 		dest[j] = '\0';
5770 
5771 #ifdef illumos
5772 		if (mstate->dtms_getf != NULL &&
5773 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5774 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5775 			/*
5776 			 * If we've done a getf() as a part of this ECB and we
5777 			 * don't have kernel access (and we're not in the global
5778 			 * zone), check if the path we cleaned up begins with
5779 			 * the zone's root path, and trim it off if so.  Note
5780 			 * that this is an output cleanliness issue, not a
5781 			 * security issue: knowing one's zone root path does
5782 			 * not enable privilege escalation.
5783 			 */
5784 			if (strstr(dest, z->zone_rootpath) == dest)
5785 				dest += strlen(z->zone_rootpath) - 1;
5786 		}
5787 #endif
5788 
5789 		regs[rd] = (uintptr_t)dest;
5790 		mstate->dtms_scratch_ptr += size;
5791 		break;
5792 	}
5793 
5794 	case DIF_SUBR_INET_NTOA:
5795 	case DIF_SUBR_INET_NTOA6:
5796 	case DIF_SUBR_INET_NTOP: {
5797 		size_t size;
5798 		int af, argi, i;
5799 		char *base, *end;
5800 
5801 		if (subr == DIF_SUBR_INET_NTOP) {
5802 			af = (int)tupregs[0].dttk_value;
5803 			argi = 1;
5804 		} else {
5805 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5806 			argi = 0;
5807 		}
5808 
5809 		if (af == AF_INET) {
5810 			ipaddr_t ip4;
5811 			uint8_t *ptr8, val;
5812 
5813 			if (!dtrace_canload(tupregs[argi].dttk_value,
5814 			    sizeof (ipaddr_t), mstate, vstate)) {
5815 				regs[rd] = 0;
5816 				break;
5817 			}
5818 
5819 			/*
5820 			 * Safely load the IPv4 address.
5821 			 */
5822 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5823 
5824 			/*
5825 			 * Check an IPv4 string will fit in scratch.
5826 			 */
5827 			size = INET_ADDRSTRLEN;
5828 			if (!DTRACE_INSCRATCH(mstate, size)) {
5829 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5830 				regs[rd] = 0;
5831 				break;
5832 			}
5833 			base = (char *)mstate->dtms_scratch_ptr;
5834 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5835 
5836 			/*
5837 			 * Stringify as a dotted decimal quad.
5838 			 */
5839 			*end-- = '\0';
5840 			ptr8 = (uint8_t *)&ip4;
5841 			for (i = 3; i >= 0; i--) {
5842 				val = ptr8[i];
5843 
5844 				if (val == 0) {
5845 					*end-- = '0';
5846 				} else {
5847 					for (; val; val /= 10) {
5848 						*end-- = '0' + (val % 10);
5849 					}
5850 				}
5851 
5852 				if (i > 0)
5853 					*end-- = '.';
5854 			}
5855 			ASSERT(end + 1 >= base);
5856 
5857 		} else if (af == AF_INET6) {
5858 			struct in6_addr ip6;
5859 			int firstzero, tryzero, numzero, v6end;
5860 			uint16_t val;
5861 			const char digits[] = "0123456789abcdef";
5862 
5863 			/*
5864 			 * Stringify using RFC 1884 convention 2 - 16 bit
5865 			 * hexadecimal values with a zero-run compression.
5866 			 * Lower case hexadecimal digits are used.
5867 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5868 			 * The IPv4 embedded form is returned for inet_ntop,
5869 			 * just the IPv4 string is returned for inet_ntoa6.
5870 			 */
5871 
5872 			if (!dtrace_canload(tupregs[argi].dttk_value,
5873 			    sizeof (struct in6_addr), mstate, vstate)) {
5874 				regs[rd] = 0;
5875 				break;
5876 			}
5877 
5878 			/*
5879 			 * Safely load the IPv6 address.
5880 			 */
5881 			dtrace_bcopy(
5882 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5883 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5884 
5885 			/*
5886 			 * Check an IPv6 string will fit in scratch.
5887 			 */
5888 			size = INET6_ADDRSTRLEN;
5889 			if (!DTRACE_INSCRATCH(mstate, size)) {
5890 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5891 				regs[rd] = 0;
5892 				break;
5893 			}
5894 			base = (char *)mstate->dtms_scratch_ptr;
5895 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5896 			*end-- = '\0';
5897 
5898 			/*
5899 			 * Find the longest run of 16 bit zero values
5900 			 * for the single allowed zero compression - "::".
5901 			 */
5902 			firstzero = -1;
5903 			tryzero = -1;
5904 			numzero = 1;
5905 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5906 #ifdef illumos
5907 				if (ip6._S6_un._S6_u8[i] == 0 &&
5908 #else
5909 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5910 #endif
5911 				    tryzero == -1 && i % 2 == 0) {
5912 					tryzero = i;
5913 					continue;
5914 				}
5915 
5916 				if (tryzero != -1 &&
5917 #ifdef illumos
5918 				    (ip6._S6_un._S6_u8[i] != 0 ||
5919 #else
5920 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5921 #endif
5922 				    i == sizeof (struct in6_addr) - 1)) {
5923 
5924 					if (i - tryzero <= numzero) {
5925 						tryzero = -1;
5926 						continue;
5927 					}
5928 
5929 					firstzero = tryzero;
5930 					numzero = i - i % 2 - tryzero;
5931 					tryzero = -1;
5932 
5933 #ifdef illumos
5934 					if (ip6._S6_un._S6_u8[i] == 0 &&
5935 #else
5936 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5937 #endif
5938 					    i == sizeof (struct in6_addr) - 1)
5939 						numzero += 2;
5940 				}
5941 			}
5942 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5943 
5944 			/*
5945 			 * Check for an IPv4 embedded address.
5946 			 */
5947 			v6end = sizeof (struct in6_addr) - 2;
5948 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5949 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5950 				for (i = sizeof (struct in6_addr) - 1;
5951 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5952 					ASSERT(end >= base);
5953 
5954 #ifdef illumos
5955 					val = ip6._S6_un._S6_u8[i];
5956 #else
5957 					val = ip6.__u6_addr.__u6_addr8[i];
5958 #endif
5959 
5960 					if (val == 0) {
5961 						*end-- = '0';
5962 					} else {
5963 						for (; val; val /= 10) {
5964 							*end-- = '0' + val % 10;
5965 						}
5966 					}
5967 
5968 					if (i > DTRACE_V4MAPPED_OFFSET)
5969 						*end-- = '.';
5970 				}
5971 
5972 				if (subr == DIF_SUBR_INET_NTOA6)
5973 					goto inetout;
5974 
5975 				/*
5976 				 * Set v6end to skip the IPv4 address that
5977 				 * we have already stringified.
5978 				 */
5979 				v6end = 10;
5980 			}
5981 
5982 			/*
5983 			 * Build the IPv6 string by working through the
5984 			 * address in reverse.
5985 			 */
5986 			for (i = v6end; i >= 0; i -= 2) {
5987 				ASSERT(end >= base);
5988 
5989 				if (i == firstzero + numzero - 2) {
5990 					*end-- = ':';
5991 					*end-- = ':';
5992 					i -= numzero - 2;
5993 					continue;
5994 				}
5995 
5996 				if (i < 14 && i != firstzero - 2)
5997 					*end-- = ':';
5998 
5999 #ifdef illumos
6000 				val = (ip6._S6_un._S6_u8[i] << 8) +
6001 				    ip6._S6_un._S6_u8[i + 1];
6002 #else
6003 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6004 				    ip6.__u6_addr.__u6_addr8[i + 1];
6005 #endif
6006 
6007 				if (val == 0) {
6008 					*end-- = '0';
6009 				} else {
6010 					for (; val; val /= 16) {
6011 						*end-- = digits[val % 16];
6012 					}
6013 				}
6014 			}
6015 			ASSERT(end + 1 >= base);
6016 
6017 		} else {
6018 			/*
6019 			 * The user didn't use AH_INET or AH_INET6.
6020 			 */
6021 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6022 			regs[rd] = 0;
6023 			break;
6024 		}
6025 
6026 inetout:	regs[rd] = (uintptr_t)end + 1;
6027 		mstate->dtms_scratch_ptr += size;
6028 		break;
6029 	}
6030 
6031 	case DIF_SUBR_MEMREF: {
6032 		uintptr_t size = 2 * sizeof(uintptr_t);
6033 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6034 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6035 
6036 		/* address and length */
6037 		memref[0] = tupregs[0].dttk_value;
6038 		memref[1] = tupregs[1].dttk_value;
6039 
6040 		regs[rd] = (uintptr_t) memref;
6041 		mstate->dtms_scratch_ptr += scratch_size;
6042 		break;
6043 	}
6044 
6045 #ifndef illumos
6046 	case DIF_SUBR_MEMSTR: {
6047 		char *str = (char *)mstate->dtms_scratch_ptr;
6048 		uintptr_t mem = tupregs[0].dttk_value;
6049 		char c = tupregs[1].dttk_value;
6050 		size_t size = tupregs[2].dttk_value;
6051 		uint8_t n;
6052 		int i;
6053 
6054 		regs[rd] = 0;
6055 
6056 		if (size == 0)
6057 			break;
6058 
6059 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6060 			break;
6061 
6062 		if (!DTRACE_INSCRATCH(mstate, size)) {
6063 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6064 			break;
6065 		}
6066 
6067 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6068 			*flags |= CPU_DTRACE_ILLOP;
6069 			break;
6070 		}
6071 
6072 		for (i = 0; i < size - 1; i++) {
6073 			n = dtrace_load8(mem++);
6074 			str[i] = (n == 0) ? c : n;
6075 		}
6076 		str[size - 1] = 0;
6077 
6078 		regs[rd] = (uintptr_t)str;
6079 		mstate->dtms_scratch_ptr += size;
6080 		break;
6081 	}
6082 #endif
6083 	}
6084 }
6085 
6086 /*
6087  * Emulate the execution of DTrace IR instructions specified by the given
6088  * DIF object.  This function is deliberately void of assertions as all of
6089  * the necessary checks are handled by a call to dtrace_difo_validate().
6090  */
6091 static uint64_t
6092 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6093     dtrace_vstate_t *vstate, dtrace_state_t *state)
6094 {
6095 	const dif_instr_t *text = difo->dtdo_buf;
6096 	const uint_t textlen = difo->dtdo_len;
6097 	const char *strtab = difo->dtdo_strtab;
6098 	const uint64_t *inttab = difo->dtdo_inttab;
6099 
6100 	uint64_t rval = 0;
6101 	dtrace_statvar_t *svar;
6102 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6103 	dtrace_difv_t *v;
6104 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6105 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6106 
6107 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6108 	uint64_t regs[DIF_DIR_NREGS];
6109 	uint64_t *tmp;
6110 
6111 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6112 	int64_t cc_r;
6113 	uint_t pc = 0, id, opc = 0;
6114 	uint8_t ttop = 0;
6115 	dif_instr_t instr;
6116 	uint_t r1, r2, rd;
6117 
6118 	/*
6119 	 * We stash the current DIF object into the machine state: we need it
6120 	 * for subsequent access checking.
6121 	 */
6122 	mstate->dtms_difo = difo;
6123 
6124 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6125 
6126 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6127 		opc = pc;
6128 
6129 		instr = text[pc++];
6130 		r1 = DIF_INSTR_R1(instr);
6131 		r2 = DIF_INSTR_R2(instr);
6132 		rd = DIF_INSTR_RD(instr);
6133 
6134 		switch (DIF_INSTR_OP(instr)) {
6135 		case DIF_OP_OR:
6136 			regs[rd] = regs[r1] | regs[r2];
6137 			break;
6138 		case DIF_OP_XOR:
6139 			regs[rd] = regs[r1] ^ regs[r2];
6140 			break;
6141 		case DIF_OP_AND:
6142 			regs[rd] = regs[r1] & regs[r2];
6143 			break;
6144 		case DIF_OP_SLL:
6145 			regs[rd] = regs[r1] << regs[r2];
6146 			break;
6147 		case DIF_OP_SRL:
6148 			regs[rd] = regs[r1] >> regs[r2];
6149 			break;
6150 		case DIF_OP_SUB:
6151 			regs[rd] = regs[r1] - regs[r2];
6152 			break;
6153 		case DIF_OP_ADD:
6154 			regs[rd] = regs[r1] + regs[r2];
6155 			break;
6156 		case DIF_OP_MUL:
6157 			regs[rd] = regs[r1] * regs[r2];
6158 			break;
6159 		case DIF_OP_SDIV:
6160 			if (regs[r2] == 0) {
6161 				regs[rd] = 0;
6162 				*flags |= CPU_DTRACE_DIVZERO;
6163 			} else {
6164 				regs[rd] = (int64_t)regs[r1] /
6165 				    (int64_t)regs[r2];
6166 			}
6167 			break;
6168 
6169 		case DIF_OP_UDIV:
6170 			if (regs[r2] == 0) {
6171 				regs[rd] = 0;
6172 				*flags |= CPU_DTRACE_DIVZERO;
6173 			} else {
6174 				regs[rd] = regs[r1] / regs[r2];
6175 			}
6176 			break;
6177 
6178 		case DIF_OP_SREM:
6179 			if (regs[r2] == 0) {
6180 				regs[rd] = 0;
6181 				*flags |= CPU_DTRACE_DIVZERO;
6182 			} else {
6183 				regs[rd] = (int64_t)regs[r1] %
6184 				    (int64_t)regs[r2];
6185 			}
6186 			break;
6187 
6188 		case DIF_OP_UREM:
6189 			if (regs[r2] == 0) {
6190 				regs[rd] = 0;
6191 				*flags |= CPU_DTRACE_DIVZERO;
6192 			} else {
6193 				regs[rd] = regs[r1] % regs[r2];
6194 			}
6195 			break;
6196 
6197 		case DIF_OP_NOT:
6198 			regs[rd] = ~regs[r1];
6199 			break;
6200 		case DIF_OP_MOV:
6201 			regs[rd] = regs[r1];
6202 			break;
6203 		case DIF_OP_CMP:
6204 			cc_r = regs[r1] - regs[r2];
6205 			cc_n = cc_r < 0;
6206 			cc_z = cc_r == 0;
6207 			cc_v = 0;
6208 			cc_c = regs[r1] < regs[r2];
6209 			break;
6210 		case DIF_OP_TST:
6211 			cc_n = cc_v = cc_c = 0;
6212 			cc_z = regs[r1] == 0;
6213 			break;
6214 		case DIF_OP_BA:
6215 			pc = DIF_INSTR_LABEL(instr);
6216 			break;
6217 		case DIF_OP_BE:
6218 			if (cc_z)
6219 				pc = DIF_INSTR_LABEL(instr);
6220 			break;
6221 		case DIF_OP_BNE:
6222 			if (cc_z == 0)
6223 				pc = DIF_INSTR_LABEL(instr);
6224 			break;
6225 		case DIF_OP_BG:
6226 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6227 				pc = DIF_INSTR_LABEL(instr);
6228 			break;
6229 		case DIF_OP_BGU:
6230 			if ((cc_c | cc_z) == 0)
6231 				pc = DIF_INSTR_LABEL(instr);
6232 			break;
6233 		case DIF_OP_BGE:
6234 			if ((cc_n ^ cc_v) == 0)
6235 				pc = DIF_INSTR_LABEL(instr);
6236 			break;
6237 		case DIF_OP_BGEU:
6238 			if (cc_c == 0)
6239 				pc = DIF_INSTR_LABEL(instr);
6240 			break;
6241 		case DIF_OP_BL:
6242 			if (cc_n ^ cc_v)
6243 				pc = DIF_INSTR_LABEL(instr);
6244 			break;
6245 		case DIF_OP_BLU:
6246 			if (cc_c)
6247 				pc = DIF_INSTR_LABEL(instr);
6248 			break;
6249 		case DIF_OP_BLE:
6250 			if (cc_z | (cc_n ^ cc_v))
6251 				pc = DIF_INSTR_LABEL(instr);
6252 			break;
6253 		case DIF_OP_BLEU:
6254 			if (cc_c | cc_z)
6255 				pc = DIF_INSTR_LABEL(instr);
6256 			break;
6257 		case DIF_OP_RLDSB:
6258 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6259 				break;
6260 			/*FALLTHROUGH*/
6261 		case DIF_OP_LDSB:
6262 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6263 			break;
6264 		case DIF_OP_RLDSH:
6265 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6266 				break;
6267 			/*FALLTHROUGH*/
6268 		case DIF_OP_LDSH:
6269 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6270 			break;
6271 		case DIF_OP_RLDSW:
6272 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6273 				break;
6274 			/*FALLTHROUGH*/
6275 		case DIF_OP_LDSW:
6276 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6277 			break;
6278 		case DIF_OP_RLDUB:
6279 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6280 				break;
6281 			/*FALLTHROUGH*/
6282 		case DIF_OP_LDUB:
6283 			regs[rd] = dtrace_load8(regs[r1]);
6284 			break;
6285 		case DIF_OP_RLDUH:
6286 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6287 				break;
6288 			/*FALLTHROUGH*/
6289 		case DIF_OP_LDUH:
6290 			regs[rd] = dtrace_load16(regs[r1]);
6291 			break;
6292 		case DIF_OP_RLDUW:
6293 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6294 				break;
6295 			/*FALLTHROUGH*/
6296 		case DIF_OP_LDUW:
6297 			regs[rd] = dtrace_load32(regs[r1]);
6298 			break;
6299 		case DIF_OP_RLDX:
6300 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6301 				break;
6302 			/*FALLTHROUGH*/
6303 		case DIF_OP_LDX:
6304 			regs[rd] = dtrace_load64(regs[r1]);
6305 			break;
6306 		case DIF_OP_ULDSB:
6307 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6308 			regs[rd] = (int8_t)
6309 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6310 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6311 			break;
6312 		case DIF_OP_ULDSH:
6313 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6314 			regs[rd] = (int16_t)
6315 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6316 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6317 			break;
6318 		case DIF_OP_ULDSW:
6319 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6320 			regs[rd] = (int32_t)
6321 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6322 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6323 			break;
6324 		case DIF_OP_ULDUB:
6325 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6326 			regs[rd] =
6327 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6328 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6329 			break;
6330 		case DIF_OP_ULDUH:
6331 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6332 			regs[rd] =
6333 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6334 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6335 			break;
6336 		case DIF_OP_ULDUW:
6337 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6338 			regs[rd] =
6339 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6340 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6341 			break;
6342 		case DIF_OP_ULDX:
6343 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6344 			regs[rd] =
6345 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6346 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6347 			break;
6348 		case DIF_OP_RET:
6349 			rval = regs[rd];
6350 			pc = textlen;
6351 			break;
6352 		case DIF_OP_NOP:
6353 			break;
6354 		case DIF_OP_SETX:
6355 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6356 			break;
6357 		case DIF_OP_SETS:
6358 			regs[rd] = (uint64_t)(uintptr_t)
6359 			    (strtab + DIF_INSTR_STRING(instr));
6360 			break;
6361 		case DIF_OP_SCMP: {
6362 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6363 			uintptr_t s1 = regs[r1];
6364 			uintptr_t s2 = regs[r2];
6365 			size_t lim1, lim2;
6366 
6367 			/*
6368 			 * If one of the strings is NULL then the limit becomes
6369 			 * 0 which compares 0 characters in dtrace_strncmp()
6370 			 * resulting in a false positive.  dtrace_strncmp()
6371 			 * treats a NULL as an empty 1-char string.
6372 			 */
6373 			lim1 = lim2 = 1;
6374 
6375 			if (s1 != 0 &&
6376 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6377 				break;
6378 			if (s2 != 0 &&
6379 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6380 				break;
6381 
6382 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6383 			    MIN(lim1, lim2));
6384 
6385 			cc_n = cc_r < 0;
6386 			cc_z = cc_r == 0;
6387 			cc_v = cc_c = 0;
6388 			break;
6389 		}
6390 		case DIF_OP_LDGA:
6391 			regs[rd] = dtrace_dif_variable(mstate, state,
6392 			    r1, regs[r2]);
6393 			break;
6394 		case DIF_OP_LDGS:
6395 			id = DIF_INSTR_VAR(instr);
6396 
6397 			if (id >= DIF_VAR_OTHER_UBASE) {
6398 				uintptr_t a;
6399 
6400 				id -= DIF_VAR_OTHER_UBASE;
6401 				svar = vstate->dtvs_globals[id];
6402 				ASSERT(svar != NULL);
6403 				v = &svar->dtsv_var;
6404 
6405 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6406 					regs[rd] = svar->dtsv_data;
6407 					break;
6408 				}
6409 
6410 				a = (uintptr_t)svar->dtsv_data;
6411 
6412 				if (*(uint8_t *)a == UINT8_MAX) {
6413 					/*
6414 					 * If the 0th byte is set to UINT8_MAX
6415 					 * then this is to be treated as a
6416 					 * reference to a NULL variable.
6417 					 */
6418 					regs[rd] = 0;
6419 				} else {
6420 					regs[rd] = a + sizeof (uint64_t);
6421 				}
6422 
6423 				break;
6424 			}
6425 
6426 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6427 			break;
6428 
6429 		case DIF_OP_STGS:
6430 			id = DIF_INSTR_VAR(instr);
6431 
6432 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6433 			id -= DIF_VAR_OTHER_UBASE;
6434 
6435 			VERIFY(id < vstate->dtvs_nglobals);
6436 			svar = vstate->dtvs_globals[id];
6437 			ASSERT(svar != NULL);
6438 			v = &svar->dtsv_var;
6439 
6440 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6441 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6442 				size_t lim;
6443 
6444 				ASSERT(a != 0);
6445 				ASSERT(svar->dtsv_size != 0);
6446 
6447 				if (regs[rd] == 0) {
6448 					*(uint8_t *)a = UINT8_MAX;
6449 					break;
6450 				} else {
6451 					*(uint8_t *)a = 0;
6452 					a += sizeof (uint64_t);
6453 				}
6454 				if (!dtrace_vcanload(
6455 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6456 				    &lim, mstate, vstate))
6457 					break;
6458 
6459 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6460 				    (void *)a, &v->dtdv_type, lim);
6461 				break;
6462 			}
6463 
6464 			svar->dtsv_data = regs[rd];
6465 			break;
6466 
6467 		case DIF_OP_LDTA:
6468 			/*
6469 			 * There are no DTrace built-in thread-local arrays at
6470 			 * present.  This opcode is saved for future work.
6471 			 */
6472 			*flags |= CPU_DTRACE_ILLOP;
6473 			regs[rd] = 0;
6474 			break;
6475 
6476 		case DIF_OP_LDLS:
6477 			id = DIF_INSTR_VAR(instr);
6478 
6479 			if (id < DIF_VAR_OTHER_UBASE) {
6480 				/*
6481 				 * For now, this has no meaning.
6482 				 */
6483 				regs[rd] = 0;
6484 				break;
6485 			}
6486 
6487 			id -= DIF_VAR_OTHER_UBASE;
6488 
6489 			ASSERT(id < vstate->dtvs_nlocals);
6490 			ASSERT(vstate->dtvs_locals != NULL);
6491 
6492 			svar = vstate->dtvs_locals[id];
6493 			ASSERT(svar != NULL);
6494 			v = &svar->dtsv_var;
6495 
6496 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6497 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6498 				size_t sz = v->dtdv_type.dtdt_size;
6499 				size_t lim;
6500 
6501 				sz += sizeof (uint64_t);
6502 				ASSERT(svar->dtsv_size == NCPU * sz);
6503 				a += curcpu * sz;
6504 
6505 				if (*(uint8_t *)a == UINT8_MAX) {
6506 					/*
6507 					 * If the 0th byte is set to UINT8_MAX
6508 					 * then this is to be treated as a
6509 					 * reference to a NULL variable.
6510 					 */
6511 					regs[rd] = 0;
6512 				} else {
6513 					regs[rd] = a + sizeof (uint64_t);
6514 				}
6515 
6516 				break;
6517 			}
6518 
6519 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6520 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6521 			regs[rd] = tmp[curcpu];
6522 			break;
6523 
6524 		case DIF_OP_STLS:
6525 			id = DIF_INSTR_VAR(instr);
6526 
6527 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6528 			id -= DIF_VAR_OTHER_UBASE;
6529 			VERIFY(id < vstate->dtvs_nlocals);
6530 
6531 			ASSERT(vstate->dtvs_locals != NULL);
6532 			svar = vstate->dtvs_locals[id];
6533 			ASSERT(svar != NULL);
6534 			v = &svar->dtsv_var;
6535 
6536 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6537 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6538 				size_t sz = v->dtdv_type.dtdt_size;
6539 				size_t lim;
6540 
6541 				sz += sizeof (uint64_t);
6542 				ASSERT(svar->dtsv_size == NCPU * sz);
6543 				a += curcpu * sz;
6544 
6545 				if (regs[rd] == 0) {
6546 					*(uint8_t *)a = UINT8_MAX;
6547 					break;
6548 				} else {
6549 					*(uint8_t *)a = 0;
6550 					a += sizeof (uint64_t);
6551 				}
6552 
6553 				if (!dtrace_vcanload(
6554 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6555 				    &lim, mstate, vstate))
6556 					break;
6557 
6558 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6559 				    (void *)a, &v->dtdv_type, lim);
6560 				break;
6561 			}
6562 
6563 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6564 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6565 			tmp[curcpu] = regs[rd];
6566 			break;
6567 
6568 		case DIF_OP_LDTS: {
6569 			dtrace_dynvar_t *dvar;
6570 			dtrace_key_t *key;
6571 
6572 			id = DIF_INSTR_VAR(instr);
6573 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6574 			id -= DIF_VAR_OTHER_UBASE;
6575 			v = &vstate->dtvs_tlocals[id];
6576 
6577 			key = &tupregs[DIF_DTR_NREGS];
6578 			key[0].dttk_value = (uint64_t)id;
6579 			key[0].dttk_size = 0;
6580 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6581 			key[1].dttk_size = 0;
6582 
6583 			dvar = dtrace_dynvar(dstate, 2, key,
6584 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6585 			    mstate, vstate);
6586 
6587 			if (dvar == NULL) {
6588 				regs[rd] = 0;
6589 				break;
6590 			}
6591 
6592 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6593 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6594 			} else {
6595 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6596 			}
6597 
6598 			break;
6599 		}
6600 
6601 		case DIF_OP_STTS: {
6602 			dtrace_dynvar_t *dvar;
6603 			dtrace_key_t *key;
6604 
6605 			id = DIF_INSTR_VAR(instr);
6606 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6607 			id -= DIF_VAR_OTHER_UBASE;
6608 			VERIFY(id < vstate->dtvs_ntlocals);
6609 
6610 			key = &tupregs[DIF_DTR_NREGS];
6611 			key[0].dttk_value = (uint64_t)id;
6612 			key[0].dttk_size = 0;
6613 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6614 			key[1].dttk_size = 0;
6615 			v = &vstate->dtvs_tlocals[id];
6616 
6617 			dvar = dtrace_dynvar(dstate, 2, key,
6618 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6619 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6620 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6621 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6622 
6623 			/*
6624 			 * Given that we're storing to thread-local data,
6625 			 * we need to flush our predicate cache.
6626 			 */
6627 			curthread->t_predcache = 0;
6628 
6629 			if (dvar == NULL)
6630 				break;
6631 
6632 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6633 				size_t lim;
6634 
6635 				if (!dtrace_vcanload(
6636 				    (void *)(uintptr_t)regs[rd],
6637 				    &v->dtdv_type, &lim, mstate, vstate))
6638 					break;
6639 
6640 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6641 				    dvar->dtdv_data, &v->dtdv_type, lim);
6642 			} else {
6643 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6644 			}
6645 
6646 			break;
6647 		}
6648 
6649 		case DIF_OP_SRA:
6650 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6651 			break;
6652 
6653 		case DIF_OP_CALL:
6654 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6655 			    regs, tupregs, ttop, mstate, state);
6656 			break;
6657 
6658 		case DIF_OP_PUSHTR:
6659 			if (ttop == DIF_DTR_NREGS) {
6660 				*flags |= CPU_DTRACE_TUPOFLOW;
6661 				break;
6662 			}
6663 
6664 			if (r1 == DIF_TYPE_STRING) {
6665 				/*
6666 				 * If this is a string type and the size is 0,
6667 				 * we'll use the system-wide default string
6668 				 * size.  Note that we are _not_ looking at
6669 				 * the value of the DTRACEOPT_STRSIZE option;
6670 				 * had this been set, we would expect to have
6671 				 * a non-zero size value in the "pushtr".
6672 				 */
6673 				tupregs[ttop].dttk_size =
6674 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6675 				    regs[r2] ? regs[r2] :
6676 				    dtrace_strsize_default) + 1;
6677 			} else {
6678 				if (regs[r2] > LONG_MAX) {
6679 					*flags |= CPU_DTRACE_ILLOP;
6680 					break;
6681 				}
6682 
6683 				tupregs[ttop].dttk_size = regs[r2];
6684 			}
6685 
6686 			tupregs[ttop++].dttk_value = regs[rd];
6687 			break;
6688 
6689 		case DIF_OP_PUSHTV:
6690 			if (ttop == DIF_DTR_NREGS) {
6691 				*flags |= CPU_DTRACE_TUPOFLOW;
6692 				break;
6693 			}
6694 
6695 			tupregs[ttop].dttk_value = regs[rd];
6696 			tupregs[ttop++].dttk_size = 0;
6697 			break;
6698 
6699 		case DIF_OP_POPTS:
6700 			if (ttop != 0)
6701 				ttop--;
6702 			break;
6703 
6704 		case DIF_OP_FLUSHTS:
6705 			ttop = 0;
6706 			break;
6707 
6708 		case DIF_OP_LDGAA:
6709 		case DIF_OP_LDTAA: {
6710 			dtrace_dynvar_t *dvar;
6711 			dtrace_key_t *key = tupregs;
6712 			uint_t nkeys = ttop;
6713 
6714 			id = DIF_INSTR_VAR(instr);
6715 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6716 			id -= DIF_VAR_OTHER_UBASE;
6717 
6718 			key[nkeys].dttk_value = (uint64_t)id;
6719 			key[nkeys++].dttk_size = 0;
6720 
6721 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6722 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6723 				key[nkeys++].dttk_size = 0;
6724 				VERIFY(id < vstate->dtvs_ntlocals);
6725 				v = &vstate->dtvs_tlocals[id];
6726 			} else {
6727 				VERIFY(id < vstate->dtvs_nglobals);
6728 				v = &vstate->dtvs_globals[id]->dtsv_var;
6729 			}
6730 
6731 			dvar = dtrace_dynvar(dstate, nkeys, key,
6732 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6733 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6734 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6735 
6736 			if (dvar == NULL) {
6737 				regs[rd] = 0;
6738 				break;
6739 			}
6740 
6741 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6742 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6743 			} else {
6744 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6745 			}
6746 
6747 			break;
6748 		}
6749 
6750 		case DIF_OP_STGAA:
6751 		case DIF_OP_STTAA: {
6752 			dtrace_dynvar_t *dvar;
6753 			dtrace_key_t *key = tupregs;
6754 			uint_t nkeys = ttop;
6755 
6756 			id = DIF_INSTR_VAR(instr);
6757 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6758 			id -= DIF_VAR_OTHER_UBASE;
6759 
6760 			key[nkeys].dttk_value = (uint64_t)id;
6761 			key[nkeys++].dttk_size = 0;
6762 
6763 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6764 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6765 				key[nkeys++].dttk_size = 0;
6766 				VERIFY(id < vstate->dtvs_ntlocals);
6767 				v = &vstate->dtvs_tlocals[id];
6768 			} else {
6769 				VERIFY(id < vstate->dtvs_nglobals);
6770 				v = &vstate->dtvs_globals[id]->dtsv_var;
6771 			}
6772 
6773 			dvar = dtrace_dynvar(dstate, nkeys, key,
6774 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6775 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6776 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6777 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6778 
6779 			if (dvar == NULL)
6780 				break;
6781 
6782 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6783 				size_t lim;
6784 
6785 				if (!dtrace_vcanload(
6786 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6787 				    &lim, mstate, vstate))
6788 					break;
6789 
6790 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6791 				    dvar->dtdv_data, &v->dtdv_type, lim);
6792 			} else {
6793 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6794 			}
6795 
6796 			break;
6797 		}
6798 
6799 		case DIF_OP_ALLOCS: {
6800 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6801 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6802 
6803 			/*
6804 			 * Rounding up the user allocation size could have
6805 			 * overflowed large, bogus allocations (like -1ULL) to
6806 			 * 0.
6807 			 */
6808 			if (size < regs[r1] ||
6809 			    !DTRACE_INSCRATCH(mstate, size)) {
6810 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6811 				regs[rd] = 0;
6812 				break;
6813 			}
6814 
6815 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6816 			mstate->dtms_scratch_ptr += size;
6817 			regs[rd] = ptr;
6818 			break;
6819 		}
6820 
6821 		case DIF_OP_COPYS:
6822 			if (!dtrace_canstore(regs[rd], regs[r2],
6823 			    mstate, vstate)) {
6824 				*flags |= CPU_DTRACE_BADADDR;
6825 				*illval = regs[rd];
6826 				break;
6827 			}
6828 
6829 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6830 				break;
6831 
6832 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6833 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6834 			break;
6835 
6836 		case DIF_OP_STB:
6837 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6838 				*flags |= CPU_DTRACE_BADADDR;
6839 				*illval = regs[rd];
6840 				break;
6841 			}
6842 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6843 			break;
6844 
6845 		case DIF_OP_STH:
6846 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6847 				*flags |= CPU_DTRACE_BADADDR;
6848 				*illval = regs[rd];
6849 				break;
6850 			}
6851 			if (regs[rd] & 1) {
6852 				*flags |= CPU_DTRACE_BADALIGN;
6853 				*illval = regs[rd];
6854 				break;
6855 			}
6856 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6857 			break;
6858 
6859 		case DIF_OP_STW:
6860 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6861 				*flags |= CPU_DTRACE_BADADDR;
6862 				*illval = regs[rd];
6863 				break;
6864 			}
6865 			if (regs[rd] & 3) {
6866 				*flags |= CPU_DTRACE_BADALIGN;
6867 				*illval = regs[rd];
6868 				break;
6869 			}
6870 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6871 			break;
6872 
6873 		case DIF_OP_STX:
6874 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6875 				*flags |= CPU_DTRACE_BADADDR;
6876 				*illval = regs[rd];
6877 				break;
6878 			}
6879 			if (regs[rd] & 7) {
6880 				*flags |= CPU_DTRACE_BADALIGN;
6881 				*illval = regs[rd];
6882 				break;
6883 			}
6884 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6885 			break;
6886 		}
6887 	}
6888 
6889 	if (!(*flags & CPU_DTRACE_FAULT))
6890 		return (rval);
6891 
6892 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6893 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6894 
6895 	return (0);
6896 }
6897 
6898 static void
6899 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6900 {
6901 	dtrace_probe_t *probe = ecb->dte_probe;
6902 	dtrace_provider_t *prov = probe->dtpr_provider;
6903 	char c[DTRACE_FULLNAMELEN + 80], *str;
6904 	char *msg = "dtrace: breakpoint action at probe ";
6905 	char *ecbmsg = " (ecb ";
6906 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6907 	uintptr_t val = (uintptr_t)ecb;
6908 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6909 
6910 	if (dtrace_destructive_disallow)
6911 		return;
6912 
6913 	/*
6914 	 * It's impossible to be taking action on the NULL probe.
6915 	 */
6916 	ASSERT(probe != NULL);
6917 
6918 	/*
6919 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6920 	 * print the provider name, module name, function name and name of
6921 	 * the probe, along with the hex address of the ECB with the breakpoint
6922 	 * action -- all of which we must place in the character buffer by
6923 	 * hand.
6924 	 */
6925 	while (*msg != '\0')
6926 		c[i++] = *msg++;
6927 
6928 	for (str = prov->dtpv_name; *str != '\0'; str++)
6929 		c[i++] = *str;
6930 	c[i++] = ':';
6931 
6932 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6933 		c[i++] = *str;
6934 	c[i++] = ':';
6935 
6936 	for (str = probe->dtpr_func; *str != '\0'; str++)
6937 		c[i++] = *str;
6938 	c[i++] = ':';
6939 
6940 	for (str = probe->dtpr_name; *str != '\0'; str++)
6941 		c[i++] = *str;
6942 
6943 	while (*ecbmsg != '\0')
6944 		c[i++] = *ecbmsg++;
6945 
6946 	while (shift >= 0) {
6947 		mask = (uintptr_t)0xf << shift;
6948 
6949 		if (val >= ((uintptr_t)1 << shift))
6950 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6951 		shift -= 4;
6952 	}
6953 
6954 	c[i++] = ')';
6955 	c[i] = '\0';
6956 
6957 #ifdef illumos
6958 	debug_enter(c);
6959 #else
6960 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6961 #endif
6962 }
6963 
6964 static void
6965 dtrace_action_panic(dtrace_ecb_t *ecb)
6966 {
6967 	dtrace_probe_t *probe = ecb->dte_probe;
6968 
6969 	/*
6970 	 * It's impossible to be taking action on the NULL probe.
6971 	 */
6972 	ASSERT(probe != NULL);
6973 
6974 	if (dtrace_destructive_disallow)
6975 		return;
6976 
6977 	if (dtrace_panicked != NULL)
6978 		return;
6979 
6980 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6981 		return;
6982 
6983 	/*
6984 	 * We won the right to panic.  (We want to be sure that only one
6985 	 * thread calls panic() from dtrace_probe(), and that panic() is
6986 	 * called exactly once.)
6987 	 */
6988 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6989 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6990 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6991 }
6992 
6993 static void
6994 dtrace_action_raise(uint64_t sig)
6995 {
6996 	if (dtrace_destructive_disallow)
6997 		return;
6998 
6999 	if (sig >= NSIG) {
7000 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7001 		return;
7002 	}
7003 
7004 #ifdef illumos
7005 	/*
7006 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7007 	 * invocations of the raise() action.
7008 	 */
7009 	if (curthread->t_dtrace_sig == 0)
7010 		curthread->t_dtrace_sig = (uint8_t)sig;
7011 
7012 	curthread->t_sig_check = 1;
7013 	aston(curthread);
7014 #else
7015 	struct proc *p = curproc;
7016 	PROC_LOCK(p);
7017 	kern_psignal(p, sig);
7018 	PROC_UNLOCK(p);
7019 #endif
7020 }
7021 
7022 static void
7023 dtrace_action_stop(void)
7024 {
7025 	if (dtrace_destructive_disallow)
7026 		return;
7027 
7028 #ifdef illumos
7029 	if (!curthread->t_dtrace_stop) {
7030 		curthread->t_dtrace_stop = 1;
7031 		curthread->t_sig_check = 1;
7032 		aston(curthread);
7033 	}
7034 #else
7035 	struct proc *p = curproc;
7036 	PROC_LOCK(p);
7037 	kern_psignal(p, SIGSTOP);
7038 	PROC_UNLOCK(p);
7039 #endif
7040 }
7041 
7042 static void
7043 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7044 {
7045 	hrtime_t now;
7046 	volatile uint16_t *flags;
7047 #ifdef illumos
7048 	cpu_t *cpu = CPU;
7049 #else
7050 	cpu_t *cpu = &solaris_cpu[curcpu];
7051 #endif
7052 
7053 	if (dtrace_destructive_disallow)
7054 		return;
7055 
7056 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7057 
7058 	now = dtrace_gethrtime();
7059 
7060 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7061 		/*
7062 		 * We need to advance the mark to the current time.
7063 		 */
7064 		cpu->cpu_dtrace_chillmark = now;
7065 		cpu->cpu_dtrace_chilled = 0;
7066 	}
7067 
7068 	/*
7069 	 * Now check to see if the requested chill time would take us over
7070 	 * the maximum amount of time allowed in the chill interval.  (Or
7071 	 * worse, if the calculation itself induces overflow.)
7072 	 */
7073 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7074 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7075 		*flags |= CPU_DTRACE_ILLOP;
7076 		return;
7077 	}
7078 
7079 	while (dtrace_gethrtime() - now < val)
7080 		continue;
7081 
7082 	/*
7083 	 * Normally, we assure that the value of the variable "timestamp" does
7084 	 * not change within an ECB.  The presence of chill() represents an
7085 	 * exception to this rule, however.
7086 	 */
7087 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7088 	cpu->cpu_dtrace_chilled += val;
7089 }
7090 
7091 static void
7092 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7093     uint64_t *buf, uint64_t arg)
7094 {
7095 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7096 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7097 	uint64_t *pcs = &buf[1], *fps;
7098 	char *str = (char *)&pcs[nframes];
7099 	int size, offs = 0, i, j;
7100 	size_t rem;
7101 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7102 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7103 	char *sym;
7104 
7105 	/*
7106 	 * Should be taking a faster path if string space has not been
7107 	 * allocated.
7108 	 */
7109 	ASSERT(strsize != 0);
7110 
7111 	/*
7112 	 * We will first allocate some temporary space for the frame pointers.
7113 	 */
7114 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7115 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7116 	    (nframes * sizeof (uint64_t));
7117 
7118 	if (!DTRACE_INSCRATCH(mstate, size)) {
7119 		/*
7120 		 * Not enough room for our frame pointers -- need to indicate
7121 		 * that we ran out of scratch space.
7122 		 */
7123 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7124 		return;
7125 	}
7126 
7127 	mstate->dtms_scratch_ptr += size;
7128 	saved = mstate->dtms_scratch_ptr;
7129 
7130 	/*
7131 	 * Now get a stack with both program counters and frame pointers.
7132 	 */
7133 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7134 	dtrace_getufpstack(buf, fps, nframes + 1);
7135 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7136 
7137 	/*
7138 	 * If that faulted, we're cooked.
7139 	 */
7140 	if (*flags & CPU_DTRACE_FAULT)
7141 		goto out;
7142 
7143 	/*
7144 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7145 	 * each iteration, we restore the scratch pointer.
7146 	 */
7147 	for (i = 0; i < nframes; i++) {
7148 		mstate->dtms_scratch_ptr = saved;
7149 
7150 		if (offs >= strsize)
7151 			break;
7152 
7153 		sym = (char *)(uintptr_t)dtrace_helper(
7154 		    DTRACE_HELPER_ACTION_USTACK,
7155 		    mstate, state, pcs[i], fps[i]);
7156 
7157 		/*
7158 		 * If we faulted while running the helper, we're going to
7159 		 * clear the fault and null out the corresponding string.
7160 		 */
7161 		if (*flags & CPU_DTRACE_FAULT) {
7162 			*flags &= ~CPU_DTRACE_FAULT;
7163 			str[offs++] = '\0';
7164 			continue;
7165 		}
7166 
7167 		if (sym == NULL) {
7168 			str[offs++] = '\0';
7169 			continue;
7170 		}
7171 
7172 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7173 		    &(state->dts_vstate))) {
7174 			str[offs++] = '\0';
7175 			continue;
7176 		}
7177 
7178 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7179 
7180 		/*
7181 		 * Now copy in the string that the helper returned to us.
7182 		 */
7183 		for (j = 0; offs + j < strsize && j < rem; j++) {
7184 			if ((str[offs + j] = sym[j]) == '\0')
7185 				break;
7186 		}
7187 
7188 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7189 
7190 		offs += j + 1;
7191 	}
7192 
7193 	if (offs >= strsize) {
7194 		/*
7195 		 * If we didn't have room for all of the strings, we don't
7196 		 * abort processing -- this needn't be a fatal error -- but we
7197 		 * still want to increment a counter (dts_stkstroverflows) to
7198 		 * allow this condition to be warned about.  (If this is from
7199 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7200 		 */
7201 		dtrace_error(&state->dts_stkstroverflows);
7202 	}
7203 
7204 	while (offs < strsize)
7205 		str[offs++] = '\0';
7206 
7207 out:
7208 	mstate->dtms_scratch_ptr = old;
7209 }
7210 
7211 static void
7212 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7213     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7214 {
7215 	volatile uint16_t *flags;
7216 	uint64_t val = *valp;
7217 	size_t valoffs = *valoffsp;
7218 
7219 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7220 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7221 
7222 	/*
7223 	 * If this is a string, we're going to only load until we find the zero
7224 	 * byte -- after which we'll store zero bytes.
7225 	 */
7226 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7227 		char c = '\0' + 1;
7228 		size_t s;
7229 
7230 		for (s = 0; s < size; s++) {
7231 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7232 				c = dtrace_load8(val++);
7233 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7234 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7235 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7236 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7237 				if (*flags & CPU_DTRACE_FAULT)
7238 					break;
7239 			}
7240 
7241 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7242 
7243 			if (c == '\0' && intuple)
7244 				break;
7245 		}
7246 	} else {
7247 		uint8_t c;
7248 		while (valoffs < end) {
7249 			if (dtkind == DIF_TF_BYREF) {
7250 				c = dtrace_load8(val++);
7251 			} else if (dtkind == DIF_TF_BYUREF) {
7252 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7253 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7254 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7255 				if (*flags & CPU_DTRACE_FAULT)
7256 					break;
7257 			}
7258 
7259 			DTRACE_STORE(uint8_t, tomax,
7260 			    valoffs++, c);
7261 		}
7262 	}
7263 
7264 	*valp = val;
7265 	*valoffsp = valoffs;
7266 }
7267 
7268 /*
7269  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7270  * defined, we also assert that we are not recursing unless the probe ID is an
7271  * error probe.
7272  */
7273 static dtrace_icookie_t
7274 dtrace_probe_enter(dtrace_id_t id)
7275 {
7276 	dtrace_icookie_t cookie;
7277 
7278 	cookie = dtrace_interrupt_disable();
7279 
7280 	/*
7281 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7282 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7283 	 * function is instrumented that should not have been instrumented or
7284 	 * that the ordering guarantee of the records will be violated,
7285 	 * resulting in unexpected output. If there is an exception to this
7286 	 * assertion, a new case should be added.
7287 	 */
7288 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7289 	    id == dtrace_probeid_error);
7290 	curthread->t_dtrace_inprobe = 1;
7291 
7292 	return (cookie);
7293 }
7294 
7295 /*
7296  * Clears the per-thread inprobe flag and enables interrupts.
7297  */
7298 static void
7299 dtrace_probe_exit(dtrace_icookie_t cookie)
7300 {
7301 
7302 	curthread->t_dtrace_inprobe = 0;
7303 	dtrace_interrupt_enable(cookie);
7304 }
7305 
7306 /*
7307  * If you're looking for the epicenter of DTrace, you just found it.  This
7308  * is the function called by the provider to fire a probe -- from which all
7309  * subsequent probe-context DTrace activity emanates.
7310  */
7311 void
7312 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7313     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7314 {
7315 	processorid_t cpuid;
7316 	dtrace_icookie_t cookie;
7317 	dtrace_probe_t *probe;
7318 	dtrace_mstate_t mstate;
7319 	dtrace_ecb_t *ecb;
7320 	dtrace_action_t *act;
7321 	intptr_t offs;
7322 	size_t size;
7323 	int vtime, onintr;
7324 	volatile uint16_t *flags;
7325 	hrtime_t now;
7326 
7327 	if (KERNEL_PANICKED())
7328 		return;
7329 
7330 #ifdef illumos
7331 	/*
7332 	 * Kick out immediately if this CPU is still being born (in which case
7333 	 * curthread will be set to -1) or the current thread can't allow
7334 	 * probes in its current context.
7335 	 */
7336 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7337 		return;
7338 #endif
7339 
7340 	cookie = dtrace_probe_enter(id);
7341 	probe = dtrace_probes[id - 1];
7342 	cpuid = curcpu;
7343 	onintr = CPU_ON_INTR(CPU);
7344 
7345 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7346 	    probe->dtpr_predcache == curthread->t_predcache) {
7347 		/*
7348 		 * We have hit in the predicate cache; we know that
7349 		 * this predicate would evaluate to be false.
7350 		 */
7351 		dtrace_probe_exit(cookie);
7352 		return;
7353 	}
7354 
7355 #ifdef illumos
7356 	if (panic_quiesce) {
7357 #else
7358 	if (KERNEL_PANICKED()) {
7359 #endif
7360 		/*
7361 		 * We don't trace anything if we're panicking.
7362 		 */
7363 		dtrace_probe_exit(cookie);
7364 		return;
7365 	}
7366 
7367 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7368 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7369 	vtime = dtrace_vtime_references != 0;
7370 
7371 	if (vtime && curthread->t_dtrace_start)
7372 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7373 
7374 	mstate.dtms_difo = NULL;
7375 	mstate.dtms_probe = probe;
7376 	mstate.dtms_strtok = 0;
7377 	mstate.dtms_arg[0] = arg0;
7378 	mstate.dtms_arg[1] = arg1;
7379 	mstate.dtms_arg[2] = arg2;
7380 	mstate.dtms_arg[3] = arg3;
7381 	mstate.dtms_arg[4] = arg4;
7382 
7383 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7384 
7385 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7386 		dtrace_predicate_t *pred = ecb->dte_predicate;
7387 		dtrace_state_t *state = ecb->dte_state;
7388 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7389 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7390 		dtrace_vstate_t *vstate = &state->dts_vstate;
7391 		dtrace_provider_t *prov = probe->dtpr_provider;
7392 		uint64_t tracememsize = 0;
7393 		int committed = 0;
7394 		caddr_t tomax;
7395 
7396 		/*
7397 		 * A little subtlety with the following (seemingly innocuous)
7398 		 * declaration of the automatic 'val':  by looking at the
7399 		 * code, you might think that it could be declared in the
7400 		 * action processing loop, below.  (That is, it's only used in
7401 		 * the action processing loop.)  However, it must be declared
7402 		 * out of that scope because in the case of DIF expression
7403 		 * arguments to aggregating actions, one iteration of the
7404 		 * action loop will use the last iteration's value.
7405 		 */
7406 		uint64_t val = 0;
7407 
7408 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7409 		mstate.dtms_getf = NULL;
7410 
7411 		*flags &= ~CPU_DTRACE_ERROR;
7412 
7413 		if (prov == dtrace_provider) {
7414 			/*
7415 			 * If dtrace itself is the provider of this probe,
7416 			 * we're only going to continue processing the ECB if
7417 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7418 			 * creating state.  (This prevents disjoint consumers
7419 			 * from seeing one another's metaprobes.)
7420 			 */
7421 			if (arg0 != (uint64_t)(uintptr_t)state)
7422 				continue;
7423 		}
7424 
7425 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7426 			/*
7427 			 * We're not currently active.  If our provider isn't
7428 			 * the dtrace pseudo provider, we're not interested.
7429 			 */
7430 			if (prov != dtrace_provider)
7431 				continue;
7432 
7433 			/*
7434 			 * Now we must further check if we are in the BEGIN
7435 			 * probe.  If we are, we will only continue processing
7436 			 * if we're still in WARMUP -- if one BEGIN enabling
7437 			 * has invoked the exit() action, we don't want to
7438 			 * evaluate subsequent BEGIN enablings.
7439 			 */
7440 			if (probe->dtpr_id == dtrace_probeid_begin &&
7441 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7442 				ASSERT(state->dts_activity ==
7443 				    DTRACE_ACTIVITY_DRAINING);
7444 				continue;
7445 			}
7446 		}
7447 
7448 		if (ecb->dte_cond) {
7449 			/*
7450 			 * If the dte_cond bits indicate that this
7451 			 * consumer is only allowed to see user-mode firings
7452 			 * of this probe, call the provider's dtps_usermode()
7453 			 * entry point to check that the probe was fired
7454 			 * while in a user context. Skip this ECB if that's
7455 			 * not the case.
7456 			 */
7457 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7458 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7459 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7460 				continue;
7461 
7462 #ifdef illumos
7463 			/*
7464 			 * This is more subtle than it looks. We have to be
7465 			 * absolutely certain that CRED() isn't going to
7466 			 * change out from under us so it's only legit to
7467 			 * examine that structure if we're in constrained
7468 			 * situations. Currently, the only times we'll this
7469 			 * check is if a non-super-user has enabled the
7470 			 * profile or syscall providers -- providers that
7471 			 * allow visibility of all processes. For the
7472 			 * profile case, the check above will ensure that
7473 			 * we're examining a user context.
7474 			 */
7475 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7476 				cred_t *cr;
7477 				cred_t *s_cr =
7478 				    ecb->dte_state->dts_cred.dcr_cred;
7479 				proc_t *proc;
7480 
7481 				ASSERT(s_cr != NULL);
7482 
7483 				if ((cr = CRED()) == NULL ||
7484 				    s_cr->cr_uid != cr->cr_uid ||
7485 				    s_cr->cr_uid != cr->cr_ruid ||
7486 				    s_cr->cr_uid != cr->cr_suid ||
7487 				    s_cr->cr_gid != cr->cr_gid ||
7488 				    s_cr->cr_gid != cr->cr_rgid ||
7489 				    s_cr->cr_gid != cr->cr_sgid ||
7490 				    (proc = ttoproc(curthread)) == NULL ||
7491 				    (proc->p_flag & SNOCD))
7492 					continue;
7493 			}
7494 
7495 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7496 				cred_t *cr;
7497 				cred_t *s_cr =
7498 				    ecb->dte_state->dts_cred.dcr_cred;
7499 
7500 				ASSERT(s_cr != NULL);
7501 
7502 				if ((cr = CRED()) == NULL ||
7503 				    s_cr->cr_zone->zone_id !=
7504 				    cr->cr_zone->zone_id)
7505 					continue;
7506 			}
7507 #endif
7508 		}
7509 
7510 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7511 			/*
7512 			 * We seem to be dead.  Unless we (a) have kernel
7513 			 * destructive permissions (b) have explicitly enabled
7514 			 * destructive actions and (c) destructive actions have
7515 			 * not been disabled, we're going to transition into
7516 			 * the KILLED state, from which no further processing
7517 			 * on this state will be performed.
7518 			 */
7519 			if (!dtrace_priv_kernel_destructive(state) ||
7520 			    !state->dts_cred.dcr_destructive ||
7521 			    dtrace_destructive_disallow) {
7522 				void *activity = &state->dts_activity;
7523 				dtrace_activity_t curstate;
7524 
7525 				do {
7526 					curstate = state->dts_activity;
7527 				} while (dtrace_cas32(activity, curstate,
7528 				    DTRACE_ACTIVITY_KILLED) != curstate);
7529 
7530 				continue;
7531 			}
7532 		}
7533 
7534 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7535 		    ecb->dte_alignment, state, &mstate)) < 0)
7536 			continue;
7537 
7538 		tomax = buf->dtb_tomax;
7539 		ASSERT(tomax != NULL);
7540 
7541 		if (ecb->dte_size != 0) {
7542 			dtrace_rechdr_t dtrh;
7543 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7544 				mstate.dtms_timestamp = dtrace_gethrtime();
7545 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7546 			}
7547 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7548 			dtrh.dtrh_epid = ecb->dte_epid;
7549 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7550 			    mstate.dtms_timestamp);
7551 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7552 		}
7553 
7554 		mstate.dtms_epid = ecb->dte_epid;
7555 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7556 
7557 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7558 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7559 		else
7560 			mstate.dtms_access = 0;
7561 
7562 		if (pred != NULL) {
7563 			dtrace_difo_t *dp = pred->dtp_difo;
7564 			uint64_t rval;
7565 
7566 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7567 
7568 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7569 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7570 
7571 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7572 					/*
7573 					 * Update the predicate cache...
7574 					 */
7575 					ASSERT(cid == pred->dtp_cacheid);
7576 					curthread->t_predcache = cid;
7577 				}
7578 
7579 				continue;
7580 			}
7581 		}
7582 
7583 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7584 		    act != NULL; act = act->dta_next) {
7585 			size_t valoffs;
7586 			dtrace_difo_t *dp;
7587 			dtrace_recdesc_t *rec = &act->dta_rec;
7588 
7589 			size = rec->dtrd_size;
7590 			valoffs = offs + rec->dtrd_offset;
7591 
7592 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7593 				uint64_t v = 0xbad;
7594 				dtrace_aggregation_t *agg;
7595 
7596 				agg = (dtrace_aggregation_t *)act;
7597 
7598 				if ((dp = act->dta_difo) != NULL)
7599 					v = dtrace_dif_emulate(dp,
7600 					    &mstate, vstate, state);
7601 
7602 				if (*flags & CPU_DTRACE_ERROR)
7603 					continue;
7604 
7605 				/*
7606 				 * Note that we always pass the expression
7607 				 * value from the previous iteration of the
7608 				 * action loop.  This value will only be used
7609 				 * if there is an expression argument to the
7610 				 * aggregating action, denoted by the
7611 				 * dtag_hasarg field.
7612 				 */
7613 				dtrace_aggregate(agg, buf,
7614 				    offs, aggbuf, v, val);
7615 				continue;
7616 			}
7617 
7618 			switch (act->dta_kind) {
7619 			case DTRACEACT_STOP:
7620 				if (dtrace_priv_proc_destructive(state))
7621 					dtrace_action_stop();
7622 				continue;
7623 
7624 			case DTRACEACT_BREAKPOINT:
7625 				if (dtrace_priv_kernel_destructive(state))
7626 					dtrace_action_breakpoint(ecb);
7627 				continue;
7628 
7629 			case DTRACEACT_PANIC:
7630 				if (dtrace_priv_kernel_destructive(state))
7631 					dtrace_action_panic(ecb);
7632 				continue;
7633 
7634 			case DTRACEACT_STACK:
7635 				if (!dtrace_priv_kernel(state))
7636 					continue;
7637 
7638 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7639 				    size / sizeof (pc_t), probe->dtpr_aframes,
7640 				    DTRACE_ANCHORED(probe) ? NULL :
7641 				    (uint32_t *)arg0);
7642 				continue;
7643 
7644 			case DTRACEACT_JSTACK:
7645 			case DTRACEACT_USTACK:
7646 				if (!dtrace_priv_proc(state))
7647 					continue;
7648 
7649 				/*
7650 				 * See comment in DIF_VAR_PID.
7651 				 */
7652 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7653 				    CPU_ON_INTR(CPU)) {
7654 					int depth = DTRACE_USTACK_NFRAMES(
7655 					    rec->dtrd_arg) + 1;
7656 
7657 					dtrace_bzero((void *)(tomax + valoffs),
7658 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7659 					    + depth * sizeof (uint64_t));
7660 
7661 					continue;
7662 				}
7663 
7664 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7665 				    curproc->p_dtrace_helpers != NULL) {
7666 					/*
7667 					 * This is the slow path -- we have
7668 					 * allocated string space, and we're
7669 					 * getting the stack of a process that
7670 					 * has helpers.  Call into a separate
7671 					 * routine to perform this processing.
7672 					 */
7673 					dtrace_action_ustack(&mstate, state,
7674 					    (uint64_t *)(tomax + valoffs),
7675 					    rec->dtrd_arg);
7676 					continue;
7677 				}
7678 
7679 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7680 				dtrace_getupcstack((uint64_t *)
7681 				    (tomax + valoffs),
7682 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7683 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7684 				continue;
7685 
7686 			default:
7687 				break;
7688 			}
7689 
7690 			dp = act->dta_difo;
7691 			ASSERT(dp != NULL);
7692 
7693 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7694 
7695 			if (*flags & CPU_DTRACE_ERROR)
7696 				continue;
7697 
7698 			switch (act->dta_kind) {
7699 			case DTRACEACT_SPECULATE: {
7700 				dtrace_rechdr_t *dtrh;
7701 
7702 				ASSERT(buf == &state->dts_buffer[cpuid]);
7703 				buf = dtrace_speculation_buffer(state,
7704 				    cpuid, val);
7705 
7706 				if (buf == NULL) {
7707 					*flags |= CPU_DTRACE_DROP;
7708 					continue;
7709 				}
7710 
7711 				offs = dtrace_buffer_reserve(buf,
7712 				    ecb->dte_needed, ecb->dte_alignment,
7713 				    state, NULL);
7714 
7715 				if (offs < 0) {
7716 					*flags |= CPU_DTRACE_DROP;
7717 					continue;
7718 				}
7719 
7720 				tomax = buf->dtb_tomax;
7721 				ASSERT(tomax != NULL);
7722 
7723 				if (ecb->dte_size == 0)
7724 					continue;
7725 
7726 				ASSERT3U(ecb->dte_size, >=,
7727 				    sizeof (dtrace_rechdr_t));
7728 				dtrh = ((void *)(tomax + offs));
7729 				dtrh->dtrh_epid = ecb->dte_epid;
7730 				/*
7731 				 * When the speculation is committed, all of
7732 				 * the records in the speculative buffer will
7733 				 * have their timestamps set to the commit
7734 				 * time.  Until then, it is set to a sentinel
7735 				 * value, for debugability.
7736 				 */
7737 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7738 				continue;
7739 			}
7740 
7741 			case DTRACEACT_PRINTM: {
7742 				/* The DIF returns a 'memref'. */
7743 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7744 
7745 				/* Get the size from the memref. */
7746 				size = memref[1];
7747 
7748 				/*
7749 				 * Check if the size exceeds the allocated
7750 				 * buffer size.
7751 				 */
7752 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7753 					/* Flag a drop! */
7754 					*flags |= CPU_DTRACE_DROP;
7755 					continue;
7756 				}
7757 
7758 				/* Store the size in the buffer first. */
7759 				DTRACE_STORE(uintptr_t, tomax,
7760 				    valoffs, size);
7761 
7762 				/*
7763 				 * Offset the buffer address to the start
7764 				 * of the data.
7765 				 */
7766 				valoffs += sizeof(uintptr_t);
7767 
7768 				/*
7769 				 * Reset to the memory address rather than
7770 				 * the memref array, then let the BYREF
7771 				 * code below do the work to store the
7772 				 * memory data in the buffer.
7773 				 */
7774 				val = memref[0];
7775 				break;
7776 			}
7777 
7778 			case DTRACEACT_CHILL:
7779 				if (dtrace_priv_kernel_destructive(state))
7780 					dtrace_action_chill(&mstate, val);
7781 				continue;
7782 
7783 			case DTRACEACT_RAISE:
7784 				if (dtrace_priv_proc_destructive(state))
7785 					dtrace_action_raise(val);
7786 				continue;
7787 
7788 			case DTRACEACT_COMMIT:
7789 				ASSERT(!committed);
7790 
7791 				/*
7792 				 * We need to commit our buffer state.
7793 				 */
7794 				if (ecb->dte_size)
7795 					buf->dtb_offset = offs + ecb->dte_size;
7796 				buf = &state->dts_buffer[cpuid];
7797 				dtrace_speculation_commit(state, cpuid, val);
7798 				committed = 1;
7799 				continue;
7800 
7801 			case DTRACEACT_DISCARD:
7802 				dtrace_speculation_discard(state, cpuid, val);
7803 				continue;
7804 
7805 			case DTRACEACT_DIFEXPR:
7806 			case DTRACEACT_LIBACT:
7807 			case DTRACEACT_PRINTF:
7808 			case DTRACEACT_PRINTA:
7809 			case DTRACEACT_SYSTEM:
7810 			case DTRACEACT_FREOPEN:
7811 			case DTRACEACT_TRACEMEM:
7812 				break;
7813 
7814 			case DTRACEACT_TRACEMEM_DYNSIZE:
7815 				tracememsize = val;
7816 				break;
7817 
7818 			case DTRACEACT_SYM:
7819 			case DTRACEACT_MOD:
7820 				if (!dtrace_priv_kernel(state))
7821 					continue;
7822 				break;
7823 
7824 			case DTRACEACT_USYM:
7825 			case DTRACEACT_UMOD:
7826 			case DTRACEACT_UADDR: {
7827 #ifdef illumos
7828 				struct pid *pid = curthread->t_procp->p_pidp;
7829 #endif
7830 
7831 				if (!dtrace_priv_proc(state))
7832 					continue;
7833 
7834 				DTRACE_STORE(uint64_t, tomax,
7835 #ifdef illumos
7836 				    valoffs, (uint64_t)pid->pid_id);
7837 #else
7838 				    valoffs, (uint64_t) curproc->p_pid);
7839 #endif
7840 				DTRACE_STORE(uint64_t, tomax,
7841 				    valoffs + sizeof (uint64_t), val);
7842 
7843 				continue;
7844 			}
7845 
7846 			case DTRACEACT_EXIT: {
7847 				/*
7848 				 * For the exit action, we are going to attempt
7849 				 * to atomically set our activity to be
7850 				 * draining.  If this fails (either because
7851 				 * another CPU has beat us to the exit action,
7852 				 * or because our current activity is something
7853 				 * other than ACTIVE or WARMUP), we will
7854 				 * continue.  This assures that the exit action
7855 				 * can be successfully recorded at most once
7856 				 * when we're in the ACTIVE state.  If we're
7857 				 * encountering the exit() action while in
7858 				 * COOLDOWN, however, we want to honor the new
7859 				 * status code.  (We know that we're the only
7860 				 * thread in COOLDOWN, so there is no race.)
7861 				 */
7862 				void *activity = &state->dts_activity;
7863 				dtrace_activity_t curstate = state->dts_activity;
7864 
7865 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7866 					break;
7867 
7868 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7869 					curstate = DTRACE_ACTIVITY_ACTIVE;
7870 
7871 				if (dtrace_cas32(activity, curstate,
7872 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7873 					*flags |= CPU_DTRACE_DROP;
7874 					continue;
7875 				}
7876 
7877 				break;
7878 			}
7879 
7880 			default:
7881 				ASSERT(0);
7882 			}
7883 
7884 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7885 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7886 				uintptr_t end = valoffs + size;
7887 
7888 				if (tracememsize != 0 &&
7889 				    valoffs + tracememsize < end) {
7890 					end = valoffs + tracememsize;
7891 					tracememsize = 0;
7892 				}
7893 
7894 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7895 				    !dtrace_vcanload((void *)(uintptr_t)val,
7896 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7897 					continue;
7898 
7899 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7900 				    &val, end, act->dta_intuple,
7901 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7902 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7903 				continue;
7904 			}
7905 
7906 			switch (size) {
7907 			case 0:
7908 				break;
7909 
7910 			case sizeof (uint8_t):
7911 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7912 				break;
7913 			case sizeof (uint16_t):
7914 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7915 				break;
7916 			case sizeof (uint32_t):
7917 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7918 				break;
7919 			case sizeof (uint64_t):
7920 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7921 				break;
7922 			default:
7923 				/*
7924 				 * Any other size should have been returned by
7925 				 * reference, not by value.
7926 				 */
7927 				ASSERT(0);
7928 				break;
7929 			}
7930 		}
7931 
7932 		if (*flags & CPU_DTRACE_DROP)
7933 			continue;
7934 
7935 		if (*flags & CPU_DTRACE_FAULT) {
7936 			int ndx;
7937 			dtrace_action_t *err;
7938 
7939 			buf->dtb_errors++;
7940 
7941 			if (probe->dtpr_id == dtrace_probeid_error) {
7942 				/*
7943 				 * There's nothing we can do -- we had an
7944 				 * error on the error probe.  We bump an
7945 				 * error counter to at least indicate that
7946 				 * this condition happened.
7947 				 */
7948 				dtrace_error(&state->dts_dblerrors);
7949 				continue;
7950 			}
7951 
7952 			if (vtime) {
7953 				/*
7954 				 * Before recursing on dtrace_probe(), we
7955 				 * need to explicitly clear out our start
7956 				 * time to prevent it from being accumulated
7957 				 * into t_dtrace_vtime.
7958 				 */
7959 				curthread->t_dtrace_start = 0;
7960 			}
7961 
7962 			/*
7963 			 * Iterate over the actions to figure out which action
7964 			 * we were processing when we experienced the error.
7965 			 * Note that act points _past_ the faulting action; if
7966 			 * act is ecb->dte_action, the fault was in the
7967 			 * predicate, if it's ecb->dte_action->dta_next it's
7968 			 * in action #1, and so on.
7969 			 */
7970 			for (err = ecb->dte_action, ndx = 0;
7971 			    err != act; err = err->dta_next, ndx++)
7972 				continue;
7973 
7974 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7975 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7976 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7977 			    cpu_core[cpuid].cpuc_dtrace_illval);
7978 
7979 			continue;
7980 		}
7981 
7982 		if (!committed)
7983 			buf->dtb_offset = offs + ecb->dte_size;
7984 	}
7985 
7986 	if (vtime)
7987 		curthread->t_dtrace_start = dtrace_gethrtime();
7988 
7989 	dtrace_probe_exit(cookie);
7990 }
7991 
7992 /*
7993  * DTrace Probe Hashing Functions
7994  *
7995  * The functions in this section (and indeed, the functions in remaining
7996  * sections) are not _called_ from probe context.  (Any exceptions to this are
7997  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7998  * DTrace framework to look-up probes in, add probes to and remove probes from
7999  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8000  * probe tuple -- allowing for fast lookups, regardless of what was
8001  * specified.)
8002  */
8003 static uint_t
8004 dtrace_hash_str(const char *p)
8005 {
8006 	unsigned int g;
8007 	uint_t hval = 0;
8008 
8009 	while (*p) {
8010 		hval = (hval << 4) + *p++;
8011 		if ((g = (hval & 0xf0000000)) != 0)
8012 			hval ^= g >> 24;
8013 		hval &= ~g;
8014 	}
8015 	return (hval);
8016 }
8017 
8018 static dtrace_hash_t *
8019 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
8020 {
8021 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8022 
8023 	hash->dth_stroffs = stroffs;
8024 	hash->dth_nextoffs = nextoffs;
8025 	hash->dth_prevoffs = prevoffs;
8026 
8027 	hash->dth_size = 1;
8028 	hash->dth_mask = hash->dth_size - 1;
8029 
8030 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8031 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8032 
8033 	return (hash);
8034 }
8035 
8036 static void
8037 dtrace_hash_destroy(dtrace_hash_t *hash)
8038 {
8039 #ifdef DEBUG
8040 	int i;
8041 
8042 	for (i = 0; i < hash->dth_size; i++)
8043 		ASSERT(hash->dth_tab[i] == NULL);
8044 #endif
8045 
8046 	kmem_free(hash->dth_tab,
8047 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8048 	kmem_free(hash, sizeof (dtrace_hash_t));
8049 }
8050 
8051 static void
8052 dtrace_hash_resize(dtrace_hash_t *hash)
8053 {
8054 	int size = hash->dth_size, i, ndx;
8055 	int new_size = hash->dth_size << 1;
8056 	int new_mask = new_size - 1;
8057 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8058 
8059 	ASSERT((new_size & new_mask) == 0);
8060 
8061 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8062 
8063 	for (i = 0; i < size; i++) {
8064 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8065 			dtrace_probe_t *probe = bucket->dthb_chain;
8066 
8067 			ASSERT(probe != NULL);
8068 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8069 
8070 			next = bucket->dthb_next;
8071 			bucket->dthb_next = new_tab[ndx];
8072 			new_tab[ndx] = bucket;
8073 		}
8074 	}
8075 
8076 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8077 	hash->dth_tab = new_tab;
8078 	hash->dth_size = new_size;
8079 	hash->dth_mask = new_mask;
8080 }
8081 
8082 static void
8083 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8084 {
8085 	int hashval = DTRACE_HASHSTR(hash, new);
8086 	int ndx = hashval & hash->dth_mask;
8087 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8088 	dtrace_probe_t **nextp, **prevp;
8089 
8090 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8091 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8092 			goto add;
8093 	}
8094 
8095 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8096 		dtrace_hash_resize(hash);
8097 		dtrace_hash_add(hash, new);
8098 		return;
8099 	}
8100 
8101 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8102 	bucket->dthb_next = hash->dth_tab[ndx];
8103 	hash->dth_tab[ndx] = bucket;
8104 	hash->dth_nbuckets++;
8105 
8106 add:
8107 	nextp = DTRACE_HASHNEXT(hash, new);
8108 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8109 	*nextp = bucket->dthb_chain;
8110 
8111 	if (bucket->dthb_chain != NULL) {
8112 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8113 		ASSERT(*prevp == NULL);
8114 		*prevp = new;
8115 	}
8116 
8117 	bucket->dthb_chain = new;
8118 	bucket->dthb_len++;
8119 }
8120 
8121 static dtrace_probe_t *
8122 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8123 {
8124 	int hashval = DTRACE_HASHSTR(hash, template);
8125 	int ndx = hashval & hash->dth_mask;
8126 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8127 
8128 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8129 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8130 			return (bucket->dthb_chain);
8131 	}
8132 
8133 	return (NULL);
8134 }
8135 
8136 static int
8137 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8138 {
8139 	int hashval = DTRACE_HASHSTR(hash, template);
8140 	int ndx = hashval & hash->dth_mask;
8141 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8142 
8143 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8144 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8145 			return (bucket->dthb_len);
8146 	}
8147 
8148 	return (0);
8149 }
8150 
8151 static void
8152 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8153 {
8154 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8155 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8156 
8157 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8158 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8159 
8160 	/*
8161 	 * Find the bucket that we're removing this probe from.
8162 	 */
8163 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8164 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8165 			break;
8166 	}
8167 
8168 	ASSERT(bucket != NULL);
8169 
8170 	if (*prevp == NULL) {
8171 		if (*nextp == NULL) {
8172 			/*
8173 			 * The removed probe was the only probe on this
8174 			 * bucket; we need to remove the bucket.
8175 			 */
8176 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8177 
8178 			ASSERT(bucket->dthb_chain == probe);
8179 			ASSERT(b != NULL);
8180 
8181 			if (b == bucket) {
8182 				hash->dth_tab[ndx] = bucket->dthb_next;
8183 			} else {
8184 				while (b->dthb_next != bucket)
8185 					b = b->dthb_next;
8186 				b->dthb_next = bucket->dthb_next;
8187 			}
8188 
8189 			ASSERT(hash->dth_nbuckets > 0);
8190 			hash->dth_nbuckets--;
8191 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8192 			return;
8193 		}
8194 
8195 		bucket->dthb_chain = *nextp;
8196 	} else {
8197 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8198 	}
8199 
8200 	if (*nextp != NULL)
8201 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8202 }
8203 
8204 /*
8205  * DTrace Utility Functions
8206  *
8207  * These are random utility functions that are _not_ called from probe context.
8208  */
8209 static int
8210 dtrace_badattr(const dtrace_attribute_t *a)
8211 {
8212 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8213 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8214 	    a->dtat_class > DTRACE_CLASS_MAX);
8215 }
8216 
8217 /*
8218  * Return a duplicate copy of a string.  If the specified string is NULL,
8219  * this function returns a zero-length string.
8220  */
8221 static char *
8222 dtrace_strdup(const char *str)
8223 {
8224 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8225 
8226 	if (str != NULL)
8227 		(void) strcpy(new, str);
8228 
8229 	return (new);
8230 }
8231 
8232 #define	DTRACE_ISALPHA(c)	\
8233 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8234 
8235 static int
8236 dtrace_badname(const char *s)
8237 {
8238 	char c;
8239 
8240 	if (s == NULL || (c = *s++) == '\0')
8241 		return (0);
8242 
8243 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8244 		return (1);
8245 
8246 	while ((c = *s++) != '\0') {
8247 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8248 		    c != '-' && c != '_' && c != '.' && c != '`')
8249 			return (1);
8250 	}
8251 
8252 	return (0);
8253 }
8254 
8255 static void
8256 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8257 {
8258 	uint32_t priv;
8259 
8260 #ifdef illumos
8261 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8262 		/*
8263 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8264 		 */
8265 		priv = DTRACE_PRIV_ALL;
8266 	} else {
8267 		*uidp = crgetuid(cr);
8268 		*zoneidp = crgetzoneid(cr);
8269 
8270 		priv = 0;
8271 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8272 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8273 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8274 			priv |= DTRACE_PRIV_USER;
8275 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8276 			priv |= DTRACE_PRIV_PROC;
8277 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8278 			priv |= DTRACE_PRIV_OWNER;
8279 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8280 			priv |= DTRACE_PRIV_ZONEOWNER;
8281 	}
8282 #else
8283 	priv = DTRACE_PRIV_ALL;
8284 #endif
8285 
8286 	*privp = priv;
8287 }
8288 
8289 #ifdef DTRACE_ERRDEBUG
8290 static void
8291 dtrace_errdebug(const char *str)
8292 {
8293 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8294 	int occupied = 0;
8295 
8296 	mutex_enter(&dtrace_errlock);
8297 	dtrace_errlast = str;
8298 	dtrace_errthread = curthread;
8299 
8300 	while (occupied++ < DTRACE_ERRHASHSZ) {
8301 		if (dtrace_errhash[hval].dter_msg == str) {
8302 			dtrace_errhash[hval].dter_count++;
8303 			goto out;
8304 		}
8305 
8306 		if (dtrace_errhash[hval].dter_msg != NULL) {
8307 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8308 			continue;
8309 		}
8310 
8311 		dtrace_errhash[hval].dter_msg = str;
8312 		dtrace_errhash[hval].dter_count = 1;
8313 		goto out;
8314 	}
8315 
8316 	panic("dtrace: undersized error hash");
8317 out:
8318 	mutex_exit(&dtrace_errlock);
8319 }
8320 #endif
8321 
8322 /*
8323  * DTrace Matching Functions
8324  *
8325  * These functions are used to match groups of probes, given some elements of
8326  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8327  */
8328 static int
8329 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8330     zoneid_t zoneid)
8331 {
8332 	if (priv != DTRACE_PRIV_ALL) {
8333 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8334 		uint32_t match = priv & ppriv;
8335 
8336 		/*
8337 		 * No PRIV_DTRACE_* privileges...
8338 		 */
8339 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8340 		    DTRACE_PRIV_KERNEL)) == 0)
8341 			return (0);
8342 
8343 		/*
8344 		 * No matching bits, but there were bits to match...
8345 		 */
8346 		if (match == 0 && ppriv != 0)
8347 			return (0);
8348 
8349 		/*
8350 		 * Need to have permissions to the process, but don't...
8351 		 */
8352 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8353 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8354 			return (0);
8355 		}
8356 
8357 		/*
8358 		 * Need to be in the same zone unless we possess the
8359 		 * privilege to examine all zones.
8360 		 */
8361 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8362 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8363 			return (0);
8364 		}
8365 	}
8366 
8367 	return (1);
8368 }
8369 
8370 /*
8371  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8372  * consists of input pattern strings and an ops-vector to evaluate them.
8373  * This function returns >0 for match, 0 for no match, and <0 for error.
8374  */
8375 static int
8376 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8377     uint32_t priv, uid_t uid, zoneid_t zoneid)
8378 {
8379 	dtrace_provider_t *pvp = prp->dtpr_provider;
8380 	int rv;
8381 
8382 	if (pvp->dtpv_defunct)
8383 		return (0);
8384 
8385 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8386 		return (rv);
8387 
8388 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8389 		return (rv);
8390 
8391 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8392 		return (rv);
8393 
8394 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8395 		return (rv);
8396 
8397 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8398 		return (0);
8399 
8400 	return (rv);
8401 }
8402 
8403 /*
8404  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8405  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8406  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8407  * In addition, all of the recursion cases except for '*' matching have been
8408  * unwound.  For '*', we still implement recursive evaluation, but a depth
8409  * counter is maintained and matching is aborted if we recurse too deep.
8410  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8411  */
8412 static int
8413 dtrace_match_glob(const char *s, const char *p, int depth)
8414 {
8415 	const char *olds;
8416 	char s1, c;
8417 	int gs;
8418 
8419 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8420 		return (-1);
8421 
8422 	if (s == NULL)
8423 		s = ""; /* treat NULL as empty string */
8424 
8425 top:
8426 	olds = s;
8427 	s1 = *s++;
8428 
8429 	if (p == NULL)
8430 		return (0);
8431 
8432 	if ((c = *p++) == '\0')
8433 		return (s1 == '\0');
8434 
8435 	switch (c) {
8436 	case '[': {
8437 		int ok = 0, notflag = 0;
8438 		char lc = '\0';
8439 
8440 		if (s1 == '\0')
8441 			return (0);
8442 
8443 		if (*p == '!') {
8444 			notflag = 1;
8445 			p++;
8446 		}
8447 
8448 		if ((c = *p++) == '\0')
8449 			return (0);
8450 
8451 		do {
8452 			if (c == '-' && lc != '\0' && *p != ']') {
8453 				if ((c = *p++) == '\0')
8454 					return (0);
8455 				if (c == '\\' && (c = *p++) == '\0')
8456 					return (0);
8457 
8458 				if (notflag) {
8459 					if (s1 < lc || s1 > c)
8460 						ok++;
8461 					else
8462 						return (0);
8463 				} else if (lc <= s1 && s1 <= c)
8464 					ok++;
8465 
8466 			} else if (c == '\\' && (c = *p++) == '\0')
8467 				return (0);
8468 
8469 			lc = c; /* save left-hand 'c' for next iteration */
8470 
8471 			if (notflag) {
8472 				if (s1 != c)
8473 					ok++;
8474 				else
8475 					return (0);
8476 			} else if (s1 == c)
8477 				ok++;
8478 
8479 			if ((c = *p++) == '\0')
8480 				return (0);
8481 
8482 		} while (c != ']');
8483 
8484 		if (ok)
8485 			goto top;
8486 
8487 		return (0);
8488 	}
8489 
8490 	case '\\':
8491 		if ((c = *p++) == '\0')
8492 			return (0);
8493 		/*FALLTHRU*/
8494 
8495 	default:
8496 		if (c != s1)
8497 			return (0);
8498 		/*FALLTHRU*/
8499 
8500 	case '?':
8501 		if (s1 != '\0')
8502 			goto top;
8503 		return (0);
8504 
8505 	case '*':
8506 		while (*p == '*')
8507 			p++; /* consecutive *'s are identical to a single one */
8508 
8509 		if (*p == '\0')
8510 			return (1);
8511 
8512 		for (s = olds; *s != '\0'; s++) {
8513 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8514 				return (gs);
8515 		}
8516 
8517 		return (0);
8518 	}
8519 }
8520 
8521 /*ARGSUSED*/
8522 static int
8523 dtrace_match_string(const char *s, const char *p, int depth)
8524 {
8525 	return (s != NULL && strcmp(s, p) == 0);
8526 }
8527 
8528 /*ARGSUSED*/
8529 static int
8530 dtrace_match_nul(const char *s, const char *p, int depth)
8531 {
8532 	return (1); /* always match the empty pattern */
8533 }
8534 
8535 /*ARGSUSED*/
8536 static int
8537 dtrace_match_nonzero(const char *s, const char *p, int depth)
8538 {
8539 	return (s != NULL && s[0] != '\0');
8540 }
8541 
8542 static int
8543 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8544     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8545 {
8546 	dtrace_probe_t template, *probe;
8547 	dtrace_hash_t *hash = NULL;
8548 	int len, best = INT_MAX, nmatched = 0;
8549 	dtrace_id_t i;
8550 
8551 	ASSERT(MUTEX_HELD(&dtrace_lock));
8552 
8553 	/*
8554 	 * If the probe ID is specified in the key, just lookup by ID and
8555 	 * invoke the match callback once if a matching probe is found.
8556 	 */
8557 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8558 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8559 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8560 			(void) (*matched)(probe, arg);
8561 			nmatched++;
8562 		}
8563 		return (nmatched);
8564 	}
8565 
8566 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8567 	template.dtpr_func = (char *)pkp->dtpk_func;
8568 	template.dtpr_name = (char *)pkp->dtpk_name;
8569 
8570 	/*
8571 	 * We want to find the most distinct of the module name, function
8572 	 * name, and name.  So for each one that is not a glob pattern or
8573 	 * empty string, we perform a lookup in the corresponding hash and
8574 	 * use the hash table with the fewest collisions to do our search.
8575 	 */
8576 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8577 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8578 		best = len;
8579 		hash = dtrace_bymod;
8580 	}
8581 
8582 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8583 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8584 		best = len;
8585 		hash = dtrace_byfunc;
8586 	}
8587 
8588 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8589 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8590 		best = len;
8591 		hash = dtrace_byname;
8592 	}
8593 
8594 	/*
8595 	 * If we did not select a hash table, iterate over every probe and
8596 	 * invoke our callback for each one that matches our input probe key.
8597 	 */
8598 	if (hash == NULL) {
8599 		for (i = 0; i < dtrace_nprobes; i++) {
8600 			if ((probe = dtrace_probes[i]) == NULL ||
8601 			    dtrace_match_probe(probe, pkp, priv, uid,
8602 			    zoneid) <= 0)
8603 				continue;
8604 
8605 			nmatched++;
8606 
8607 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8608 				break;
8609 		}
8610 
8611 		return (nmatched);
8612 	}
8613 
8614 	/*
8615 	 * If we selected a hash table, iterate over each probe of the same key
8616 	 * name and invoke the callback for every probe that matches the other
8617 	 * attributes of our input probe key.
8618 	 */
8619 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8620 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8621 
8622 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8623 			continue;
8624 
8625 		nmatched++;
8626 
8627 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8628 			break;
8629 	}
8630 
8631 	return (nmatched);
8632 }
8633 
8634 /*
8635  * Return the function pointer dtrace_probecmp() should use to compare the
8636  * specified pattern with a string.  For NULL or empty patterns, we select
8637  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8638  * For non-empty non-glob strings, we use dtrace_match_string().
8639  */
8640 static dtrace_probekey_f *
8641 dtrace_probekey_func(const char *p)
8642 {
8643 	char c;
8644 
8645 	if (p == NULL || *p == '\0')
8646 		return (&dtrace_match_nul);
8647 
8648 	while ((c = *p++) != '\0') {
8649 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8650 			return (&dtrace_match_glob);
8651 	}
8652 
8653 	return (&dtrace_match_string);
8654 }
8655 
8656 /*
8657  * Build a probe comparison key for use with dtrace_match_probe() from the
8658  * given probe description.  By convention, a null key only matches anchored
8659  * probes: if each field is the empty string, reset dtpk_fmatch to
8660  * dtrace_match_nonzero().
8661  */
8662 static void
8663 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8664 {
8665 	pkp->dtpk_prov = pdp->dtpd_provider;
8666 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8667 
8668 	pkp->dtpk_mod = pdp->dtpd_mod;
8669 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8670 
8671 	pkp->dtpk_func = pdp->dtpd_func;
8672 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8673 
8674 	pkp->dtpk_name = pdp->dtpd_name;
8675 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8676 
8677 	pkp->dtpk_id = pdp->dtpd_id;
8678 
8679 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8680 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8681 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8682 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8683 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8684 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8685 }
8686 
8687 /*
8688  * DTrace Provider-to-Framework API Functions
8689  *
8690  * These functions implement much of the Provider-to-Framework API, as
8691  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8692  * the functions in the API for probe management (found below), and
8693  * dtrace_probe() itself (found above).
8694  */
8695 
8696 /*
8697  * Register the calling provider with the DTrace framework.  This should
8698  * generally be called by DTrace providers in their attach(9E) entry point.
8699  */
8700 int
8701 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8702     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8703 {
8704 	dtrace_provider_t *provider;
8705 
8706 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8707 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8708 		    "arguments", name ? name : "<NULL>");
8709 		return (EINVAL);
8710 	}
8711 
8712 	if (name[0] == '\0' || dtrace_badname(name)) {
8713 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8714 		    "provider name", name);
8715 		return (EINVAL);
8716 	}
8717 
8718 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8719 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8720 	    pops->dtps_destroy == NULL ||
8721 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8722 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8723 		    "provider ops", name);
8724 		return (EINVAL);
8725 	}
8726 
8727 	if (dtrace_badattr(&pap->dtpa_provider) ||
8728 	    dtrace_badattr(&pap->dtpa_mod) ||
8729 	    dtrace_badattr(&pap->dtpa_func) ||
8730 	    dtrace_badattr(&pap->dtpa_name) ||
8731 	    dtrace_badattr(&pap->dtpa_args)) {
8732 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8733 		    "provider attributes", name);
8734 		return (EINVAL);
8735 	}
8736 
8737 	if (priv & ~DTRACE_PRIV_ALL) {
8738 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8739 		    "privilege attributes", name);
8740 		return (EINVAL);
8741 	}
8742 
8743 	if ((priv & DTRACE_PRIV_KERNEL) &&
8744 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8745 	    pops->dtps_usermode == NULL) {
8746 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8747 		    "dtps_usermode() op for given privilege attributes", name);
8748 		return (EINVAL);
8749 	}
8750 
8751 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8752 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8753 	(void) strcpy(provider->dtpv_name, name);
8754 
8755 	provider->dtpv_attr = *pap;
8756 	provider->dtpv_priv.dtpp_flags = priv;
8757 	if (cr != NULL) {
8758 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8759 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8760 	}
8761 	provider->dtpv_pops = *pops;
8762 
8763 	if (pops->dtps_provide == NULL) {
8764 		ASSERT(pops->dtps_provide_module != NULL);
8765 		provider->dtpv_pops.dtps_provide =
8766 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8767 	}
8768 
8769 	if (pops->dtps_provide_module == NULL) {
8770 		ASSERT(pops->dtps_provide != NULL);
8771 		provider->dtpv_pops.dtps_provide_module =
8772 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8773 	}
8774 
8775 	if (pops->dtps_suspend == NULL) {
8776 		ASSERT(pops->dtps_resume == NULL);
8777 		provider->dtpv_pops.dtps_suspend =
8778 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8779 		provider->dtpv_pops.dtps_resume =
8780 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8781 	}
8782 
8783 	provider->dtpv_arg = arg;
8784 	*idp = (dtrace_provider_id_t)provider;
8785 
8786 	if (pops == &dtrace_provider_ops) {
8787 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8788 		ASSERT(MUTEX_HELD(&dtrace_lock));
8789 		ASSERT(dtrace_anon.dta_enabling == NULL);
8790 
8791 		/*
8792 		 * We make sure that the DTrace provider is at the head of
8793 		 * the provider chain.
8794 		 */
8795 		provider->dtpv_next = dtrace_provider;
8796 		dtrace_provider = provider;
8797 		return (0);
8798 	}
8799 
8800 	mutex_enter(&dtrace_provider_lock);
8801 	mutex_enter(&dtrace_lock);
8802 
8803 	/*
8804 	 * If there is at least one provider registered, we'll add this
8805 	 * provider after the first provider.
8806 	 */
8807 	if (dtrace_provider != NULL) {
8808 		provider->dtpv_next = dtrace_provider->dtpv_next;
8809 		dtrace_provider->dtpv_next = provider;
8810 	} else {
8811 		dtrace_provider = provider;
8812 	}
8813 
8814 	if (dtrace_retained != NULL) {
8815 		dtrace_enabling_provide(provider);
8816 
8817 		/*
8818 		 * Now we need to call dtrace_enabling_matchall() -- which
8819 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8820 		 * to drop all of our locks before calling into it...
8821 		 */
8822 		mutex_exit(&dtrace_lock);
8823 		mutex_exit(&dtrace_provider_lock);
8824 		dtrace_enabling_matchall();
8825 
8826 		return (0);
8827 	}
8828 
8829 	mutex_exit(&dtrace_lock);
8830 	mutex_exit(&dtrace_provider_lock);
8831 
8832 	return (0);
8833 }
8834 
8835 /*
8836  * Unregister the specified provider from the DTrace framework.  This should
8837  * generally be called by DTrace providers in their detach(9E) entry point.
8838  */
8839 int
8840 dtrace_unregister(dtrace_provider_id_t id)
8841 {
8842 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8843 	dtrace_provider_t *prev = NULL;
8844 	int i, self = 0, noreap = 0;
8845 	dtrace_probe_t *probe, *first = NULL;
8846 
8847 	if (old->dtpv_pops.dtps_enable ==
8848 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8849 		/*
8850 		 * If DTrace itself is the provider, we're called with locks
8851 		 * already held.
8852 		 */
8853 		ASSERT(old == dtrace_provider);
8854 #ifdef illumos
8855 		ASSERT(dtrace_devi != NULL);
8856 #endif
8857 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8858 		ASSERT(MUTEX_HELD(&dtrace_lock));
8859 		self = 1;
8860 
8861 		if (dtrace_provider->dtpv_next != NULL) {
8862 			/*
8863 			 * There's another provider here; return failure.
8864 			 */
8865 			return (EBUSY);
8866 		}
8867 	} else {
8868 		mutex_enter(&dtrace_provider_lock);
8869 #ifdef illumos
8870 		mutex_enter(&mod_lock);
8871 #endif
8872 		mutex_enter(&dtrace_lock);
8873 	}
8874 
8875 	/*
8876 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8877 	 * probes, we refuse to let providers slither away, unless this
8878 	 * provider has already been explicitly invalidated.
8879 	 */
8880 	if (!old->dtpv_defunct &&
8881 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8882 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8883 		if (!self) {
8884 			mutex_exit(&dtrace_lock);
8885 #ifdef illumos
8886 			mutex_exit(&mod_lock);
8887 #endif
8888 			mutex_exit(&dtrace_provider_lock);
8889 		}
8890 		return (EBUSY);
8891 	}
8892 
8893 	/*
8894 	 * Attempt to destroy the probes associated with this provider.
8895 	 */
8896 	for (i = 0; i < dtrace_nprobes; i++) {
8897 		if ((probe = dtrace_probes[i]) == NULL)
8898 			continue;
8899 
8900 		if (probe->dtpr_provider != old)
8901 			continue;
8902 
8903 		if (probe->dtpr_ecb == NULL)
8904 			continue;
8905 
8906 		/*
8907 		 * If we are trying to unregister a defunct provider, and the
8908 		 * provider was made defunct within the interval dictated by
8909 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8910 		 * attempt to reap our enablings.  To denote that the provider
8911 		 * should reattempt to unregister itself at some point in the
8912 		 * future, we will return a differentiable error code (EAGAIN
8913 		 * instead of EBUSY) in this case.
8914 		 */
8915 		if (dtrace_gethrtime() - old->dtpv_defunct >
8916 		    dtrace_unregister_defunct_reap)
8917 			noreap = 1;
8918 
8919 		if (!self) {
8920 			mutex_exit(&dtrace_lock);
8921 #ifdef illumos
8922 			mutex_exit(&mod_lock);
8923 #endif
8924 			mutex_exit(&dtrace_provider_lock);
8925 		}
8926 
8927 		if (noreap)
8928 			return (EBUSY);
8929 
8930 		(void) taskq_dispatch(dtrace_taskq,
8931 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8932 
8933 		return (EAGAIN);
8934 	}
8935 
8936 	/*
8937 	 * All of the probes for this provider are disabled; we can safely
8938 	 * remove all of them from their hash chains and from the probe array.
8939 	 */
8940 	for (i = 0; i < dtrace_nprobes; i++) {
8941 		if ((probe = dtrace_probes[i]) == NULL)
8942 			continue;
8943 
8944 		if (probe->dtpr_provider != old)
8945 			continue;
8946 
8947 		dtrace_probes[i] = NULL;
8948 
8949 		dtrace_hash_remove(dtrace_bymod, probe);
8950 		dtrace_hash_remove(dtrace_byfunc, probe);
8951 		dtrace_hash_remove(dtrace_byname, probe);
8952 
8953 		if (first == NULL) {
8954 			first = probe;
8955 			probe->dtpr_nextmod = NULL;
8956 		} else {
8957 			probe->dtpr_nextmod = first;
8958 			first = probe;
8959 		}
8960 	}
8961 
8962 	/*
8963 	 * The provider's probes have been removed from the hash chains and
8964 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8965 	 * everyone has cleared out from any probe array processing.
8966 	 */
8967 	dtrace_sync();
8968 
8969 	for (probe = first; probe != NULL; probe = first) {
8970 		first = probe->dtpr_nextmod;
8971 
8972 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8973 		    probe->dtpr_arg);
8974 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8975 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8976 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8977 #ifdef illumos
8978 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8979 #else
8980 		free_unr(dtrace_arena, probe->dtpr_id);
8981 #endif
8982 		kmem_free(probe, sizeof (dtrace_probe_t));
8983 	}
8984 
8985 	if ((prev = dtrace_provider) == old) {
8986 #ifdef illumos
8987 		ASSERT(self || dtrace_devi == NULL);
8988 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8989 #endif
8990 		dtrace_provider = old->dtpv_next;
8991 	} else {
8992 		while (prev != NULL && prev->dtpv_next != old)
8993 			prev = prev->dtpv_next;
8994 
8995 		if (prev == NULL) {
8996 			panic("attempt to unregister non-existent "
8997 			    "dtrace provider %p\n", (void *)id);
8998 		}
8999 
9000 		prev->dtpv_next = old->dtpv_next;
9001 	}
9002 
9003 	if (!self) {
9004 		mutex_exit(&dtrace_lock);
9005 #ifdef illumos
9006 		mutex_exit(&mod_lock);
9007 #endif
9008 		mutex_exit(&dtrace_provider_lock);
9009 	}
9010 
9011 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9012 	kmem_free(old, sizeof (dtrace_provider_t));
9013 
9014 	return (0);
9015 }
9016 
9017 /*
9018  * Invalidate the specified provider.  All subsequent probe lookups for the
9019  * specified provider will fail, but its probes will not be removed.
9020  */
9021 void
9022 dtrace_invalidate(dtrace_provider_id_t id)
9023 {
9024 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9025 
9026 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9027 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9028 
9029 	mutex_enter(&dtrace_provider_lock);
9030 	mutex_enter(&dtrace_lock);
9031 
9032 	pvp->dtpv_defunct = dtrace_gethrtime();
9033 
9034 	mutex_exit(&dtrace_lock);
9035 	mutex_exit(&dtrace_provider_lock);
9036 }
9037 
9038 /*
9039  * Indicate whether or not DTrace has attached.
9040  */
9041 int
9042 dtrace_attached(void)
9043 {
9044 	/*
9045 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9046 	 * attached.  (It's non-NULL because DTrace is always itself a
9047 	 * provider.)
9048 	 */
9049 	return (dtrace_provider != NULL);
9050 }
9051 
9052 /*
9053  * Remove all the unenabled probes for the given provider.  This function is
9054  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9055  * -- just as many of its associated probes as it can.
9056  */
9057 int
9058 dtrace_condense(dtrace_provider_id_t id)
9059 {
9060 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9061 	int i;
9062 	dtrace_probe_t *probe;
9063 
9064 	/*
9065 	 * Make sure this isn't the dtrace provider itself.
9066 	 */
9067 	ASSERT(prov->dtpv_pops.dtps_enable !=
9068 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9069 
9070 	mutex_enter(&dtrace_provider_lock);
9071 	mutex_enter(&dtrace_lock);
9072 
9073 	/*
9074 	 * Attempt to destroy the probes associated with this provider.
9075 	 */
9076 	for (i = 0; i < dtrace_nprobes; i++) {
9077 		if ((probe = dtrace_probes[i]) == NULL)
9078 			continue;
9079 
9080 		if (probe->dtpr_provider != prov)
9081 			continue;
9082 
9083 		if (probe->dtpr_ecb != NULL)
9084 			continue;
9085 
9086 		dtrace_probes[i] = NULL;
9087 
9088 		dtrace_hash_remove(dtrace_bymod, probe);
9089 		dtrace_hash_remove(dtrace_byfunc, probe);
9090 		dtrace_hash_remove(dtrace_byname, probe);
9091 
9092 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9093 		    probe->dtpr_arg);
9094 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9095 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9096 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9097 		kmem_free(probe, sizeof (dtrace_probe_t));
9098 #ifdef illumos
9099 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9100 #else
9101 		free_unr(dtrace_arena, i + 1);
9102 #endif
9103 	}
9104 
9105 	mutex_exit(&dtrace_lock);
9106 	mutex_exit(&dtrace_provider_lock);
9107 
9108 	return (0);
9109 }
9110 
9111 /*
9112  * DTrace Probe Management Functions
9113  *
9114  * The functions in this section perform the DTrace probe management,
9115  * including functions to create probes, look-up probes, and call into the
9116  * providers to request that probes be provided.  Some of these functions are
9117  * in the Provider-to-Framework API; these functions can be identified by the
9118  * fact that they are not declared "static".
9119  */
9120 
9121 /*
9122  * Create a probe with the specified module name, function name, and name.
9123  */
9124 dtrace_id_t
9125 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9126     const char *func, const char *name, int aframes, void *arg)
9127 {
9128 	dtrace_probe_t *probe, **probes;
9129 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9130 	dtrace_id_t id;
9131 
9132 	if (provider == dtrace_provider) {
9133 		ASSERT(MUTEX_HELD(&dtrace_lock));
9134 	} else {
9135 		mutex_enter(&dtrace_lock);
9136 	}
9137 
9138 #ifdef illumos
9139 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9140 	    VM_BESTFIT | VM_SLEEP);
9141 #else
9142 	id = alloc_unr(dtrace_arena);
9143 #endif
9144 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9145 
9146 	probe->dtpr_id = id;
9147 	probe->dtpr_gen = dtrace_probegen++;
9148 	probe->dtpr_mod = dtrace_strdup(mod);
9149 	probe->dtpr_func = dtrace_strdup(func);
9150 	probe->dtpr_name = dtrace_strdup(name);
9151 	probe->dtpr_arg = arg;
9152 	probe->dtpr_aframes = aframes;
9153 	probe->dtpr_provider = provider;
9154 
9155 	dtrace_hash_add(dtrace_bymod, probe);
9156 	dtrace_hash_add(dtrace_byfunc, probe);
9157 	dtrace_hash_add(dtrace_byname, probe);
9158 
9159 	if (id - 1 >= dtrace_nprobes) {
9160 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9161 		size_t nsize = osize << 1;
9162 
9163 		if (nsize == 0) {
9164 			ASSERT(osize == 0);
9165 			ASSERT(dtrace_probes == NULL);
9166 			nsize = sizeof (dtrace_probe_t *);
9167 		}
9168 
9169 		probes = kmem_zalloc(nsize, KM_SLEEP);
9170 
9171 		if (dtrace_probes == NULL) {
9172 			ASSERT(osize == 0);
9173 			dtrace_probes = probes;
9174 			dtrace_nprobes = 1;
9175 		} else {
9176 			dtrace_probe_t **oprobes = dtrace_probes;
9177 
9178 			bcopy(oprobes, probes, osize);
9179 			dtrace_membar_producer();
9180 			dtrace_probes = probes;
9181 
9182 			dtrace_sync();
9183 
9184 			/*
9185 			 * All CPUs are now seeing the new probes array; we can
9186 			 * safely free the old array.
9187 			 */
9188 			kmem_free(oprobes, osize);
9189 			dtrace_nprobes <<= 1;
9190 		}
9191 
9192 		ASSERT(id - 1 < dtrace_nprobes);
9193 	}
9194 
9195 	ASSERT(dtrace_probes[id - 1] == NULL);
9196 	dtrace_probes[id - 1] = probe;
9197 
9198 	if (provider != dtrace_provider)
9199 		mutex_exit(&dtrace_lock);
9200 
9201 	return (id);
9202 }
9203 
9204 static dtrace_probe_t *
9205 dtrace_probe_lookup_id(dtrace_id_t id)
9206 {
9207 	ASSERT(MUTEX_HELD(&dtrace_lock));
9208 
9209 	if (id == 0 || id > dtrace_nprobes)
9210 		return (NULL);
9211 
9212 	return (dtrace_probes[id - 1]);
9213 }
9214 
9215 static int
9216 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9217 {
9218 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9219 
9220 	return (DTRACE_MATCH_DONE);
9221 }
9222 
9223 /*
9224  * Look up a probe based on provider and one or more of module name, function
9225  * name and probe name.
9226  */
9227 dtrace_id_t
9228 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9229     char *func, char *name)
9230 {
9231 	dtrace_probekey_t pkey;
9232 	dtrace_id_t id;
9233 	int match;
9234 
9235 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9236 	pkey.dtpk_pmatch = &dtrace_match_string;
9237 	pkey.dtpk_mod = mod;
9238 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9239 	pkey.dtpk_func = func;
9240 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9241 	pkey.dtpk_name = name;
9242 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9243 	pkey.dtpk_id = DTRACE_IDNONE;
9244 
9245 	mutex_enter(&dtrace_lock);
9246 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9247 	    dtrace_probe_lookup_match, &id);
9248 	mutex_exit(&dtrace_lock);
9249 
9250 	ASSERT(match == 1 || match == 0);
9251 	return (match ? id : 0);
9252 }
9253 
9254 /*
9255  * Returns the probe argument associated with the specified probe.
9256  */
9257 void *
9258 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9259 {
9260 	dtrace_probe_t *probe;
9261 	void *rval = NULL;
9262 
9263 	mutex_enter(&dtrace_lock);
9264 
9265 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9266 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9267 		rval = probe->dtpr_arg;
9268 
9269 	mutex_exit(&dtrace_lock);
9270 
9271 	return (rval);
9272 }
9273 
9274 /*
9275  * Copy a probe into a probe description.
9276  */
9277 static void
9278 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9279 {
9280 	bzero(pdp, sizeof (dtrace_probedesc_t));
9281 	pdp->dtpd_id = prp->dtpr_id;
9282 
9283 	(void) strncpy(pdp->dtpd_provider,
9284 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9285 
9286 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9287 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9288 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9289 }
9290 
9291 /*
9292  * Called to indicate that a probe -- or probes -- should be provided by a
9293  * specfied provider.  If the specified description is NULL, the provider will
9294  * be told to provide all of its probes.  (This is done whenever a new
9295  * consumer comes along, or whenever a retained enabling is to be matched.) If
9296  * the specified description is non-NULL, the provider is given the
9297  * opportunity to dynamically provide the specified probe, allowing providers
9298  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9299  * probes.)  If the provider is NULL, the operations will be applied to all
9300  * providers; if the provider is non-NULL the operations will only be applied
9301  * to the specified provider.  The dtrace_provider_lock must be held, and the
9302  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9303  * will need to grab the dtrace_lock when it reenters the framework through
9304  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9305  */
9306 static void
9307 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9308 {
9309 #ifdef illumos
9310 	modctl_t *ctl;
9311 #endif
9312 	int all = 0;
9313 
9314 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9315 
9316 	if (prv == NULL) {
9317 		all = 1;
9318 		prv = dtrace_provider;
9319 	}
9320 
9321 	do {
9322 		/*
9323 		 * First, call the blanket provide operation.
9324 		 */
9325 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9326 
9327 #ifdef illumos
9328 		/*
9329 		 * Now call the per-module provide operation.  We will grab
9330 		 * mod_lock to prevent the list from being modified.  Note
9331 		 * that this also prevents the mod_busy bits from changing.
9332 		 * (mod_busy can only be changed with mod_lock held.)
9333 		 */
9334 		mutex_enter(&mod_lock);
9335 
9336 		ctl = &modules;
9337 		do {
9338 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9339 				continue;
9340 
9341 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9342 
9343 		} while ((ctl = ctl->mod_next) != &modules);
9344 
9345 		mutex_exit(&mod_lock);
9346 #endif
9347 	} while (all && (prv = prv->dtpv_next) != NULL);
9348 }
9349 
9350 #ifdef illumos
9351 /*
9352  * Iterate over each probe, and call the Framework-to-Provider API function
9353  * denoted by offs.
9354  */
9355 static void
9356 dtrace_probe_foreach(uintptr_t offs)
9357 {
9358 	dtrace_provider_t *prov;
9359 	void (*func)(void *, dtrace_id_t, void *);
9360 	dtrace_probe_t *probe;
9361 	dtrace_icookie_t cookie;
9362 	int i;
9363 
9364 	/*
9365 	 * We disable interrupts to walk through the probe array.  This is
9366 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9367 	 * won't see stale data.
9368 	 */
9369 	cookie = dtrace_interrupt_disable();
9370 
9371 	for (i = 0; i < dtrace_nprobes; i++) {
9372 		if ((probe = dtrace_probes[i]) == NULL)
9373 			continue;
9374 
9375 		if (probe->dtpr_ecb == NULL) {
9376 			/*
9377 			 * This probe isn't enabled -- don't call the function.
9378 			 */
9379 			continue;
9380 		}
9381 
9382 		prov = probe->dtpr_provider;
9383 		func = *((void(**)(void *, dtrace_id_t, void *))
9384 		    ((uintptr_t)&prov->dtpv_pops + offs));
9385 
9386 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9387 	}
9388 
9389 	dtrace_interrupt_enable(cookie);
9390 }
9391 #endif
9392 
9393 static int
9394 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9395 {
9396 	dtrace_probekey_t pkey;
9397 	uint32_t priv;
9398 	uid_t uid;
9399 	zoneid_t zoneid;
9400 
9401 	ASSERT(MUTEX_HELD(&dtrace_lock));
9402 	dtrace_ecb_create_cache = NULL;
9403 
9404 	if (desc == NULL) {
9405 		/*
9406 		 * If we're passed a NULL description, we're being asked to
9407 		 * create an ECB with a NULL probe.
9408 		 */
9409 		(void) dtrace_ecb_create_enable(NULL, enab);
9410 		return (0);
9411 	}
9412 
9413 	dtrace_probekey(desc, &pkey);
9414 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9415 	    &priv, &uid, &zoneid);
9416 
9417 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9418 	    enab));
9419 }
9420 
9421 /*
9422  * DTrace Helper Provider Functions
9423  */
9424 static void
9425 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9426 {
9427 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9428 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9429 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9430 }
9431 
9432 static void
9433 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9434     const dof_provider_t *dofprov, char *strtab)
9435 {
9436 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9437 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9438 	    dofprov->dofpv_provattr);
9439 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9440 	    dofprov->dofpv_modattr);
9441 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9442 	    dofprov->dofpv_funcattr);
9443 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9444 	    dofprov->dofpv_nameattr);
9445 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9446 	    dofprov->dofpv_argsattr);
9447 }
9448 
9449 static void
9450 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9451 {
9452 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9453 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9454 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9455 	dof_provider_t *provider;
9456 	dof_probe_t *probe;
9457 	uint32_t *off, *enoff;
9458 	uint8_t *arg;
9459 	char *strtab;
9460 	uint_t i, nprobes;
9461 	dtrace_helper_provdesc_t dhpv;
9462 	dtrace_helper_probedesc_t dhpb;
9463 	dtrace_meta_t *meta = dtrace_meta_pid;
9464 	dtrace_mops_t *mops = &meta->dtm_mops;
9465 	void *parg;
9466 
9467 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9468 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9469 	    provider->dofpv_strtab * dof->dofh_secsize);
9470 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9471 	    provider->dofpv_probes * dof->dofh_secsize);
9472 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9473 	    provider->dofpv_prargs * dof->dofh_secsize);
9474 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9475 	    provider->dofpv_proffs * dof->dofh_secsize);
9476 
9477 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9478 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9479 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9480 	enoff = NULL;
9481 
9482 	/*
9483 	 * See dtrace_helper_provider_validate().
9484 	 */
9485 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9486 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9487 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9488 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9489 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9490 	}
9491 
9492 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9493 
9494 	/*
9495 	 * Create the provider.
9496 	 */
9497 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9498 
9499 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9500 		return;
9501 
9502 	meta->dtm_count++;
9503 
9504 	/*
9505 	 * Create the probes.
9506 	 */
9507 	for (i = 0; i < nprobes; i++) {
9508 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9509 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9510 
9511 		/* See the check in dtrace_helper_provider_validate(). */
9512 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9513 			continue;
9514 
9515 		dhpb.dthpb_mod = dhp->dofhp_mod;
9516 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9517 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9518 		dhpb.dthpb_base = probe->dofpr_addr;
9519 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9520 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9521 		if (enoff != NULL) {
9522 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9523 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9524 		} else {
9525 			dhpb.dthpb_enoffs = NULL;
9526 			dhpb.dthpb_nenoffs = 0;
9527 		}
9528 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9529 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9530 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9531 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9532 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9533 
9534 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9535 	}
9536 }
9537 
9538 static void
9539 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9540 {
9541 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9542 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9543 	int i;
9544 
9545 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9546 
9547 	for (i = 0; i < dof->dofh_secnum; i++) {
9548 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9549 		    dof->dofh_secoff + i * dof->dofh_secsize);
9550 
9551 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9552 			continue;
9553 
9554 		dtrace_helper_provide_one(dhp, sec, pid);
9555 	}
9556 
9557 	/*
9558 	 * We may have just created probes, so we must now rematch against
9559 	 * any retained enablings.  Note that this call will acquire both
9560 	 * cpu_lock and dtrace_lock; the fact that we are holding
9561 	 * dtrace_meta_lock now is what defines the ordering with respect to
9562 	 * these three locks.
9563 	 */
9564 	dtrace_enabling_matchall();
9565 }
9566 
9567 static void
9568 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9569 {
9570 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9571 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9572 	dof_sec_t *str_sec;
9573 	dof_provider_t *provider;
9574 	char *strtab;
9575 	dtrace_helper_provdesc_t dhpv;
9576 	dtrace_meta_t *meta = dtrace_meta_pid;
9577 	dtrace_mops_t *mops = &meta->dtm_mops;
9578 
9579 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9580 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9581 	    provider->dofpv_strtab * dof->dofh_secsize);
9582 
9583 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9584 
9585 	/*
9586 	 * Create the provider.
9587 	 */
9588 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9589 
9590 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9591 
9592 	meta->dtm_count--;
9593 }
9594 
9595 static void
9596 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9597 {
9598 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9599 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9600 	int i;
9601 
9602 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9603 
9604 	for (i = 0; i < dof->dofh_secnum; i++) {
9605 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9606 		    dof->dofh_secoff + i * dof->dofh_secsize);
9607 
9608 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9609 			continue;
9610 
9611 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9612 	}
9613 }
9614 
9615 /*
9616  * DTrace Meta Provider-to-Framework API Functions
9617  *
9618  * These functions implement the Meta Provider-to-Framework API, as described
9619  * in <sys/dtrace.h>.
9620  */
9621 int
9622 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9623     dtrace_meta_provider_id_t *idp)
9624 {
9625 	dtrace_meta_t *meta;
9626 	dtrace_helpers_t *help, *next;
9627 	int i;
9628 
9629 	*idp = DTRACE_METAPROVNONE;
9630 
9631 	/*
9632 	 * We strictly don't need the name, but we hold onto it for
9633 	 * debuggability. All hail error queues!
9634 	 */
9635 	if (name == NULL) {
9636 		cmn_err(CE_WARN, "failed to register meta-provider: "
9637 		    "invalid name");
9638 		return (EINVAL);
9639 	}
9640 
9641 	if (mops == NULL ||
9642 	    mops->dtms_create_probe == NULL ||
9643 	    mops->dtms_provide_pid == NULL ||
9644 	    mops->dtms_remove_pid == NULL) {
9645 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9646 		    "invalid ops", name);
9647 		return (EINVAL);
9648 	}
9649 
9650 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9651 	meta->dtm_mops = *mops;
9652 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9653 	(void) strcpy(meta->dtm_name, name);
9654 	meta->dtm_arg = arg;
9655 
9656 	mutex_enter(&dtrace_meta_lock);
9657 	mutex_enter(&dtrace_lock);
9658 
9659 	if (dtrace_meta_pid != NULL) {
9660 		mutex_exit(&dtrace_lock);
9661 		mutex_exit(&dtrace_meta_lock);
9662 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9663 		    "user-land meta-provider exists", name);
9664 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9665 		kmem_free(meta, sizeof (dtrace_meta_t));
9666 		return (EINVAL);
9667 	}
9668 
9669 	dtrace_meta_pid = meta;
9670 	*idp = (dtrace_meta_provider_id_t)meta;
9671 
9672 	/*
9673 	 * If there are providers and probes ready to go, pass them
9674 	 * off to the new meta provider now.
9675 	 */
9676 
9677 	help = dtrace_deferred_pid;
9678 	dtrace_deferred_pid = NULL;
9679 
9680 	mutex_exit(&dtrace_lock);
9681 
9682 	while (help != NULL) {
9683 		for (i = 0; i < help->dthps_nprovs; i++) {
9684 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9685 			    help->dthps_pid);
9686 		}
9687 
9688 		next = help->dthps_next;
9689 		help->dthps_next = NULL;
9690 		help->dthps_prev = NULL;
9691 		help->dthps_deferred = 0;
9692 		help = next;
9693 	}
9694 
9695 	mutex_exit(&dtrace_meta_lock);
9696 
9697 	return (0);
9698 }
9699 
9700 int
9701 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9702 {
9703 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9704 
9705 	mutex_enter(&dtrace_meta_lock);
9706 	mutex_enter(&dtrace_lock);
9707 
9708 	if (old == dtrace_meta_pid) {
9709 		pp = &dtrace_meta_pid;
9710 	} else {
9711 		panic("attempt to unregister non-existent "
9712 		    "dtrace meta-provider %p\n", (void *)old);
9713 	}
9714 
9715 	if (old->dtm_count != 0) {
9716 		mutex_exit(&dtrace_lock);
9717 		mutex_exit(&dtrace_meta_lock);
9718 		return (EBUSY);
9719 	}
9720 
9721 	*pp = NULL;
9722 
9723 	mutex_exit(&dtrace_lock);
9724 	mutex_exit(&dtrace_meta_lock);
9725 
9726 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9727 	kmem_free(old, sizeof (dtrace_meta_t));
9728 
9729 	return (0);
9730 }
9731 
9732 
9733 /*
9734  * DTrace DIF Object Functions
9735  */
9736 static int
9737 dtrace_difo_err(uint_t pc, const char *format, ...)
9738 {
9739 	if (dtrace_err_verbose) {
9740 		va_list alist;
9741 
9742 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9743 		va_start(alist, format);
9744 		(void) vuprintf(format, alist);
9745 		va_end(alist);
9746 	}
9747 
9748 #ifdef DTRACE_ERRDEBUG
9749 	dtrace_errdebug(format);
9750 #endif
9751 	return (1);
9752 }
9753 
9754 /*
9755  * Validate a DTrace DIF object by checking the IR instructions.  The following
9756  * rules are currently enforced by dtrace_difo_validate():
9757  *
9758  * 1. Each instruction must have a valid opcode
9759  * 2. Each register, string, variable, or subroutine reference must be valid
9760  * 3. No instruction can modify register %r0 (must be zero)
9761  * 4. All instruction reserved bits must be set to zero
9762  * 5. The last instruction must be a "ret" instruction
9763  * 6. All branch targets must reference a valid instruction _after_ the branch
9764  */
9765 static int
9766 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9767     cred_t *cr)
9768 {
9769 	int err = 0, i;
9770 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9771 	int kcheckload;
9772 	uint_t pc;
9773 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9774 
9775 	kcheckload = cr == NULL ||
9776 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9777 
9778 	dp->dtdo_destructive = 0;
9779 
9780 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9781 		dif_instr_t instr = dp->dtdo_buf[pc];
9782 
9783 		uint_t r1 = DIF_INSTR_R1(instr);
9784 		uint_t r2 = DIF_INSTR_R2(instr);
9785 		uint_t rd = DIF_INSTR_RD(instr);
9786 		uint_t rs = DIF_INSTR_RS(instr);
9787 		uint_t label = DIF_INSTR_LABEL(instr);
9788 		uint_t v = DIF_INSTR_VAR(instr);
9789 		uint_t subr = DIF_INSTR_SUBR(instr);
9790 		uint_t type = DIF_INSTR_TYPE(instr);
9791 		uint_t op = DIF_INSTR_OP(instr);
9792 
9793 		switch (op) {
9794 		case DIF_OP_OR:
9795 		case DIF_OP_XOR:
9796 		case DIF_OP_AND:
9797 		case DIF_OP_SLL:
9798 		case DIF_OP_SRL:
9799 		case DIF_OP_SRA:
9800 		case DIF_OP_SUB:
9801 		case DIF_OP_ADD:
9802 		case DIF_OP_MUL:
9803 		case DIF_OP_SDIV:
9804 		case DIF_OP_UDIV:
9805 		case DIF_OP_SREM:
9806 		case DIF_OP_UREM:
9807 		case DIF_OP_COPYS:
9808 			if (r1 >= nregs)
9809 				err += efunc(pc, "invalid register %u\n", r1);
9810 			if (r2 >= nregs)
9811 				err += efunc(pc, "invalid register %u\n", r2);
9812 			if (rd >= nregs)
9813 				err += efunc(pc, "invalid register %u\n", rd);
9814 			if (rd == 0)
9815 				err += efunc(pc, "cannot write to %%r0\n");
9816 			break;
9817 		case DIF_OP_NOT:
9818 		case DIF_OP_MOV:
9819 		case DIF_OP_ALLOCS:
9820 			if (r1 >= nregs)
9821 				err += efunc(pc, "invalid register %u\n", r1);
9822 			if (r2 != 0)
9823 				err += efunc(pc, "non-zero reserved bits\n");
9824 			if (rd >= nregs)
9825 				err += efunc(pc, "invalid register %u\n", rd);
9826 			if (rd == 0)
9827 				err += efunc(pc, "cannot write to %%r0\n");
9828 			break;
9829 		case DIF_OP_LDSB:
9830 		case DIF_OP_LDSH:
9831 		case DIF_OP_LDSW:
9832 		case DIF_OP_LDUB:
9833 		case DIF_OP_LDUH:
9834 		case DIF_OP_LDUW:
9835 		case DIF_OP_LDX:
9836 			if (r1 >= nregs)
9837 				err += efunc(pc, "invalid register %u\n", r1);
9838 			if (r2 != 0)
9839 				err += efunc(pc, "non-zero reserved bits\n");
9840 			if (rd >= nregs)
9841 				err += efunc(pc, "invalid register %u\n", rd);
9842 			if (rd == 0)
9843 				err += efunc(pc, "cannot write to %%r0\n");
9844 			if (kcheckload)
9845 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9846 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9847 			break;
9848 		case DIF_OP_RLDSB:
9849 		case DIF_OP_RLDSH:
9850 		case DIF_OP_RLDSW:
9851 		case DIF_OP_RLDUB:
9852 		case DIF_OP_RLDUH:
9853 		case DIF_OP_RLDUW:
9854 		case DIF_OP_RLDX:
9855 			if (r1 >= nregs)
9856 				err += efunc(pc, "invalid register %u\n", r1);
9857 			if (r2 != 0)
9858 				err += efunc(pc, "non-zero reserved bits\n");
9859 			if (rd >= nregs)
9860 				err += efunc(pc, "invalid register %u\n", rd);
9861 			if (rd == 0)
9862 				err += efunc(pc, "cannot write to %%r0\n");
9863 			break;
9864 		case DIF_OP_ULDSB:
9865 		case DIF_OP_ULDSH:
9866 		case DIF_OP_ULDSW:
9867 		case DIF_OP_ULDUB:
9868 		case DIF_OP_ULDUH:
9869 		case DIF_OP_ULDUW:
9870 		case DIF_OP_ULDX:
9871 			if (r1 >= nregs)
9872 				err += efunc(pc, "invalid register %u\n", r1);
9873 			if (r2 != 0)
9874 				err += efunc(pc, "non-zero reserved bits\n");
9875 			if (rd >= nregs)
9876 				err += efunc(pc, "invalid register %u\n", rd);
9877 			if (rd == 0)
9878 				err += efunc(pc, "cannot write to %%r0\n");
9879 			break;
9880 		case DIF_OP_STB:
9881 		case DIF_OP_STH:
9882 		case DIF_OP_STW:
9883 		case DIF_OP_STX:
9884 			if (r1 >= nregs)
9885 				err += efunc(pc, "invalid register %u\n", r1);
9886 			if (r2 != 0)
9887 				err += efunc(pc, "non-zero reserved bits\n");
9888 			if (rd >= nregs)
9889 				err += efunc(pc, "invalid register %u\n", rd);
9890 			if (rd == 0)
9891 				err += efunc(pc, "cannot write to 0 address\n");
9892 			break;
9893 		case DIF_OP_CMP:
9894 		case DIF_OP_SCMP:
9895 			if (r1 >= nregs)
9896 				err += efunc(pc, "invalid register %u\n", r1);
9897 			if (r2 >= nregs)
9898 				err += efunc(pc, "invalid register %u\n", r2);
9899 			if (rd != 0)
9900 				err += efunc(pc, "non-zero reserved bits\n");
9901 			break;
9902 		case DIF_OP_TST:
9903 			if (r1 >= nregs)
9904 				err += efunc(pc, "invalid register %u\n", r1);
9905 			if (r2 != 0 || rd != 0)
9906 				err += efunc(pc, "non-zero reserved bits\n");
9907 			break;
9908 		case DIF_OP_BA:
9909 		case DIF_OP_BE:
9910 		case DIF_OP_BNE:
9911 		case DIF_OP_BG:
9912 		case DIF_OP_BGU:
9913 		case DIF_OP_BGE:
9914 		case DIF_OP_BGEU:
9915 		case DIF_OP_BL:
9916 		case DIF_OP_BLU:
9917 		case DIF_OP_BLE:
9918 		case DIF_OP_BLEU:
9919 			if (label >= dp->dtdo_len) {
9920 				err += efunc(pc, "invalid branch target %u\n",
9921 				    label);
9922 			}
9923 			if (label <= pc) {
9924 				err += efunc(pc, "backward branch to %u\n",
9925 				    label);
9926 			}
9927 			break;
9928 		case DIF_OP_RET:
9929 			if (r1 != 0 || r2 != 0)
9930 				err += efunc(pc, "non-zero reserved bits\n");
9931 			if (rd >= nregs)
9932 				err += efunc(pc, "invalid register %u\n", rd);
9933 			break;
9934 		case DIF_OP_NOP:
9935 		case DIF_OP_POPTS:
9936 		case DIF_OP_FLUSHTS:
9937 			if (r1 != 0 || r2 != 0 || rd != 0)
9938 				err += efunc(pc, "non-zero reserved bits\n");
9939 			break;
9940 		case DIF_OP_SETX:
9941 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9942 				err += efunc(pc, "invalid integer ref %u\n",
9943 				    DIF_INSTR_INTEGER(instr));
9944 			}
9945 			if (rd >= nregs)
9946 				err += efunc(pc, "invalid register %u\n", rd);
9947 			if (rd == 0)
9948 				err += efunc(pc, "cannot write to %%r0\n");
9949 			break;
9950 		case DIF_OP_SETS:
9951 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9952 				err += efunc(pc, "invalid string ref %u\n",
9953 				    DIF_INSTR_STRING(instr));
9954 			}
9955 			if (rd >= nregs)
9956 				err += efunc(pc, "invalid register %u\n", rd);
9957 			if (rd == 0)
9958 				err += efunc(pc, "cannot write to %%r0\n");
9959 			break;
9960 		case DIF_OP_LDGA:
9961 		case DIF_OP_LDTA:
9962 			if (r1 > DIF_VAR_ARRAY_MAX)
9963 				err += efunc(pc, "invalid array %u\n", r1);
9964 			if (r2 >= nregs)
9965 				err += efunc(pc, "invalid register %u\n", r2);
9966 			if (rd >= nregs)
9967 				err += efunc(pc, "invalid register %u\n", rd);
9968 			if (rd == 0)
9969 				err += efunc(pc, "cannot write to %%r0\n");
9970 			break;
9971 		case DIF_OP_LDGS:
9972 		case DIF_OP_LDTS:
9973 		case DIF_OP_LDLS:
9974 		case DIF_OP_LDGAA:
9975 		case DIF_OP_LDTAA:
9976 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9977 				err += efunc(pc, "invalid variable %u\n", v);
9978 			if (rd >= nregs)
9979 				err += efunc(pc, "invalid register %u\n", rd);
9980 			if (rd == 0)
9981 				err += efunc(pc, "cannot write to %%r0\n");
9982 			break;
9983 		case DIF_OP_STGS:
9984 		case DIF_OP_STTS:
9985 		case DIF_OP_STLS:
9986 		case DIF_OP_STGAA:
9987 		case DIF_OP_STTAA:
9988 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9989 				err += efunc(pc, "invalid variable %u\n", v);
9990 			if (rs >= nregs)
9991 				err += efunc(pc, "invalid register %u\n", rd);
9992 			break;
9993 		case DIF_OP_CALL:
9994 			if (subr > DIF_SUBR_MAX)
9995 				err += efunc(pc, "invalid subr %u\n", subr);
9996 			if (rd >= nregs)
9997 				err += efunc(pc, "invalid register %u\n", rd);
9998 			if (rd == 0)
9999 				err += efunc(pc, "cannot write to %%r0\n");
10000 
10001 			if (subr == DIF_SUBR_COPYOUT ||
10002 			    subr == DIF_SUBR_COPYOUTSTR) {
10003 				dp->dtdo_destructive = 1;
10004 			}
10005 
10006 			if (subr == DIF_SUBR_GETF) {
10007 #ifdef __FreeBSD__
10008 				err += efunc(pc, "getf() not supported");
10009 #else
10010 				/*
10011 				 * If we have a getf() we need to record that
10012 				 * in our state.  Note that our state can be
10013 				 * NULL if this is a helper -- but in that
10014 				 * case, the call to getf() is itself illegal,
10015 				 * and will be caught (slightly later) when
10016 				 * the helper is validated.
10017 				 */
10018 				if (vstate->dtvs_state != NULL)
10019 					vstate->dtvs_state->dts_getf++;
10020 #endif
10021 			}
10022 
10023 			break;
10024 		case DIF_OP_PUSHTR:
10025 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10026 				err += efunc(pc, "invalid ref type %u\n", type);
10027 			if (r2 >= nregs)
10028 				err += efunc(pc, "invalid register %u\n", r2);
10029 			if (rs >= nregs)
10030 				err += efunc(pc, "invalid register %u\n", rs);
10031 			break;
10032 		case DIF_OP_PUSHTV:
10033 			if (type != DIF_TYPE_CTF)
10034 				err += efunc(pc, "invalid val type %u\n", type);
10035 			if (r2 >= nregs)
10036 				err += efunc(pc, "invalid register %u\n", r2);
10037 			if (rs >= nregs)
10038 				err += efunc(pc, "invalid register %u\n", rs);
10039 			break;
10040 		default:
10041 			err += efunc(pc, "invalid opcode %u\n",
10042 			    DIF_INSTR_OP(instr));
10043 		}
10044 	}
10045 
10046 	if (dp->dtdo_len != 0 &&
10047 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10048 		err += efunc(dp->dtdo_len - 1,
10049 		    "expected 'ret' as last DIF instruction\n");
10050 	}
10051 
10052 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10053 		/*
10054 		 * If we're not returning by reference, the size must be either
10055 		 * 0 or the size of one of the base types.
10056 		 */
10057 		switch (dp->dtdo_rtype.dtdt_size) {
10058 		case 0:
10059 		case sizeof (uint8_t):
10060 		case sizeof (uint16_t):
10061 		case sizeof (uint32_t):
10062 		case sizeof (uint64_t):
10063 			break;
10064 
10065 		default:
10066 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10067 		}
10068 	}
10069 
10070 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10071 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10072 		dtrace_diftype_t *vt, *et;
10073 		uint_t id, ndx;
10074 
10075 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10076 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10077 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10078 			err += efunc(i, "unrecognized variable scope %d\n",
10079 			    v->dtdv_scope);
10080 			break;
10081 		}
10082 
10083 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10084 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10085 			err += efunc(i, "unrecognized variable type %d\n",
10086 			    v->dtdv_kind);
10087 			break;
10088 		}
10089 
10090 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10091 			err += efunc(i, "%d exceeds variable id limit\n", id);
10092 			break;
10093 		}
10094 
10095 		if (id < DIF_VAR_OTHER_UBASE)
10096 			continue;
10097 
10098 		/*
10099 		 * For user-defined variables, we need to check that this
10100 		 * definition is identical to any previous definition that we
10101 		 * encountered.
10102 		 */
10103 		ndx = id - DIF_VAR_OTHER_UBASE;
10104 
10105 		switch (v->dtdv_scope) {
10106 		case DIFV_SCOPE_GLOBAL:
10107 			if (maxglobal == -1 || ndx > maxglobal)
10108 				maxglobal = ndx;
10109 
10110 			if (ndx < vstate->dtvs_nglobals) {
10111 				dtrace_statvar_t *svar;
10112 
10113 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10114 					existing = &svar->dtsv_var;
10115 			}
10116 
10117 			break;
10118 
10119 		case DIFV_SCOPE_THREAD:
10120 			if (maxtlocal == -1 || ndx > maxtlocal)
10121 				maxtlocal = ndx;
10122 
10123 			if (ndx < vstate->dtvs_ntlocals)
10124 				existing = &vstate->dtvs_tlocals[ndx];
10125 			break;
10126 
10127 		case DIFV_SCOPE_LOCAL:
10128 			if (maxlocal == -1 || ndx > maxlocal)
10129 				maxlocal = ndx;
10130 
10131 			if (ndx < vstate->dtvs_nlocals) {
10132 				dtrace_statvar_t *svar;
10133 
10134 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10135 					existing = &svar->dtsv_var;
10136 			}
10137 
10138 			break;
10139 		}
10140 
10141 		vt = &v->dtdv_type;
10142 
10143 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10144 			if (vt->dtdt_size == 0) {
10145 				err += efunc(i, "zero-sized variable\n");
10146 				break;
10147 			}
10148 
10149 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10150 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10151 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10152 				err += efunc(i, "oversized by-ref static\n");
10153 				break;
10154 			}
10155 		}
10156 
10157 		if (existing == NULL || existing->dtdv_id == 0)
10158 			continue;
10159 
10160 		ASSERT(existing->dtdv_id == v->dtdv_id);
10161 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10162 
10163 		if (existing->dtdv_kind != v->dtdv_kind)
10164 			err += efunc(i, "%d changed variable kind\n", id);
10165 
10166 		et = &existing->dtdv_type;
10167 
10168 		if (vt->dtdt_flags != et->dtdt_flags) {
10169 			err += efunc(i, "%d changed variable type flags\n", id);
10170 			break;
10171 		}
10172 
10173 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10174 			err += efunc(i, "%d changed variable type size\n", id);
10175 			break;
10176 		}
10177 	}
10178 
10179 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10180 		dif_instr_t instr = dp->dtdo_buf[pc];
10181 
10182 		uint_t v = DIF_INSTR_VAR(instr);
10183 		uint_t op = DIF_INSTR_OP(instr);
10184 
10185 		switch (op) {
10186 		case DIF_OP_LDGS:
10187 		case DIF_OP_LDGAA:
10188 		case DIF_OP_STGS:
10189 		case DIF_OP_STGAA:
10190 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10191 				err += efunc(pc, "invalid variable %u\n", v);
10192 			break;
10193 		case DIF_OP_LDTS:
10194 		case DIF_OP_LDTAA:
10195 		case DIF_OP_STTS:
10196 		case DIF_OP_STTAA:
10197 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10198 				err += efunc(pc, "invalid variable %u\n", v);
10199 			break;
10200 		case DIF_OP_LDLS:
10201 		case DIF_OP_STLS:
10202 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10203 				err += efunc(pc, "invalid variable %u\n", v);
10204 			break;
10205 		default:
10206 			break;
10207 		}
10208 	}
10209 
10210 	return (err);
10211 }
10212 
10213 /*
10214  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10215  * are much more constrained than normal DIFOs.  Specifically, they may
10216  * not:
10217  *
10218  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10219  *    miscellaneous string routines
10220  * 2. Access DTrace variables other than the args[] array, and the
10221  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10222  * 3. Have thread-local variables.
10223  * 4. Have dynamic variables.
10224  */
10225 static int
10226 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10227 {
10228 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10229 	int err = 0;
10230 	uint_t pc;
10231 
10232 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10233 		dif_instr_t instr = dp->dtdo_buf[pc];
10234 
10235 		uint_t v = DIF_INSTR_VAR(instr);
10236 		uint_t subr = DIF_INSTR_SUBR(instr);
10237 		uint_t op = DIF_INSTR_OP(instr);
10238 
10239 		switch (op) {
10240 		case DIF_OP_OR:
10241 		case DIF_OP_XOR:
10242 		case DIF_OP_AND:
10243 		case DIF_OP_SLL:
10244 		case DIF_OP_SRL:
10245 		case DIF_OP_SRA:
10246 		case DIF_OP_SUB:
10247 		case DIF_OP_ADD:
10248 		case DIF_OP_MUL:
10249 		case DIF_OP_SDIV:
10250 		case DIF_OP_UDIV:
10251 		case DIF_OP_SREM:
10252 		case DIF_OP_UREM:
10253 		case DIF_OP_COPYS:
10254 		case DIF_OP_NOT:
10255 		case DIF_OP_MOV:
10256 		case DIF_OP_RLDSB:
10257 		case DIF_OP_RLDSH:
10258 		case DIF_OP_RLDSW:
10259 		case DIF_OP_RLDUB:
10260 		case DIF_OP_RLDUH:
10261 		case DIF_OP_RLDUW:
10262 		case DIF_OP_RLDX:
10263 		case DIF_OP_ULDSB:
10264 		case DIF_OP_ULDSH:
10265 		case DIF_OP_ULDSW:
10266 		case DIF_OP_ULDUB:
10267 		case DIF_OP_ULDUH:
10268 		case DIF_OP_ULDUW:
10269 		case DIF_OP_ULDX:
10270 		case DIF_OP_STB:
10271 		case DIF_OP_STH:
10272 		case DIF_OP_STW:
10273 		case DIF_OP_STX:
10274 		case DIF_OP_ALLOCS:
10275 		case DIF_OP_CMP:
10276 		case DIF_OP_SCMP:
10277 		case DIF_OP_TST:
10278 		case DIF_OP_BA:
10279 		case DIF_OP_BE:
10280 		case DIF_OP_BNE:
10281 		case DIF_OP_BG:
10282 		case DIF_OP_BGU:
10283 		case DIF_OP_BGE:
10284 		case DIF_OP_BGEU:
10285 		case DIF_OP_BL:
10286 		case DIF_OP_BLU:
10287 		case DIF_OP_BLE:
10288 		case DIF_OP_BLEU:
10289 		case DIF_OP_RET:
10290 		case DIF_OP_NOP:
10291 		case DIF_OP_POPTS:
10292 		case DIF_OP_FLUSHTS:
10293 		case DIF_OP_SETX:
10294 		case DIF_OP_SETS:
10295 		case DIF_OP_LDGA:
10296 		case DIF_OP_LDLS:
10297 		case DIF_OP_STGS:
10298 		case DIF_OP_STLS:
10299 		case DIF_OP_PUSHTR:
10300 		case DIF_OP_PUSHTV:
10301 			break;
10302 
10303 		case DIF_OP_LDGS:
10304 			if (v >= DIF_VAR_OTHER_UBASE)
10305 				break;
10306 
10307 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10308 				break;
10309 
10310 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10311 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10312 			    v == DIF_VAR_EXECARGS ||
10313 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10314 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10315 				break;
10316 
10317 			err += efunc(pc, "illegal variable %u\n", v);
10318 			break;
10319 
10320 		case DIF_OP_LDTA:
10321 		case DIF_OP_LDTS:
10322 		case DIF_OP_LDGAA:
10323 		case DIF_OP_LDTAA:
10324 			err += efunc(pc, "illegal dynamic variable load\n");
10325 			break;
10326 
10327 		case DIF_OP_STTS:
10328 		case DIF_OP_STGAA:
10329 		case DIF_OP_STTAA:
10330 			err += efunc(pc, "illegal dynamic variable store\n");
10331 			break;
10332 
10333 		case DIF_OP_CALL:
10334 			if (subr == DIF_SUBR_ALLOCA ||
10335 			    subr == DIF_SUBR_BCOPY ||
10336 			    subr == DIF_SUBR_COPYIN ||
10337 			    subr == DIF_SUBR_COPYINTO ||
10338 			    subr == DIF_SUBR_COPYINSTR ||
10339 			    subr == DIF_SUBR_INDEX ||
10340 			    subr == DIF_SUBR_INET_NTOA ||
10341 			    subr == DIF_SUBR_INET_NTOA6 ||
10342 			    subr == DIF_SUBR_INET_NTOP ||
10343 			    subr == DIF_SUBR_JSON ||
10344 			    subr == DIF_SUBR_LLTOSTR ||
10345 			    subr == DIF_SUBR_STRTOLL ||
10346 			    subr == DIF_SUBR_RINDEX ||
10347 			    subr == DIF_SUBR_STRCHR ||
10348 			    subr == DIF_SUBR_STRJOIN ||
10349 			    subr == DIF_SUBR_STRRCHR ||
10350 			    subr == DIF_SUBR_STRSTR ||
10351 			    subr == DIF_SUBR_HTONS ||
10352 			    subr == DIF_SUBR_HTONL ||
10353 			    subr == DIF_SUBR_HTONLL ||
10354 			    subr == DIF_SUBR_NTOHS ||
10355 			    subr == DIF_SUBR_NTOHL ||
10356 			    subr == DIF_SUBR_NTOHLL ||
10357 			    subr == DIF_SUBR_MEMREF)
10358 				break;
10359 #ifdef __FreeBSD__
10360 			if (subr == DIF_SUBR_MEMSTR)
10361 				break;
10362 #endif
10363 
10364 			err += efunc(pc, "invalid subr %u\n", subr);
10365 			break;
10366 
10367 		default:
10368 			err += efunc(pc, "invalid opcode %u\n",
10369 			    DIF_INSTR_OP(instr));
10370 		}
10371 	}
10372 
10373 	return (err);
10374 }
10375 
10376 /*
10377  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10378  * basis; 0 if not.
10379  */
10380 static int
10381 dtrace_difo_cacheable(dtrace_difo_t *dp)
10382 {
10383 	int i;
10384 
10385 	if (dp == NULL)
10386 		return (0);
10387 
10388 	for (i = 0; i < dp->dtdo_varlen; i++) {
10389 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10390 
10391 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10392 			continue;
10393 
10394 		switch (v->dtdv_id) {
10395 		case DIF_VAR_CURTHREAD:
10396 		case DIF_VAR_PID:
10397 		case DIF_VAR_TID:
10398 		case DIF_VAR_EXECARGS:
10399 		case DIF_VAR_EXECNAME:
10400 		case DIF_VAR_ZONENAME:
10401 			break;
10402 
10403 		default:
10404 			return (0);
10405 		}
10406 	}
10407 
10408 	/*
10409 	 * This DIF object may be cacheable.  Now we need to look for any
10410 	 * array loading instructions, any memory loading instructions, or
10411 	 * any stores to thread-local variables.
10412 	 */
10413 	for (i = 0; i < dp->dtdo_len; i++) {
10414 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10415 
10416 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10417 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10418 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10419 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10420 			return (0);
10421 	}
10422 
10423 	return (1);
10424 }
10425 
10426 static void
10427 dtrace_difo_hold(dtrace_difo_t *dp)
10428 {
10429 	int i;
10430 
10431 	ASSERT(MUTEX_HELD(&dtrace_lock));
10432 
10433 	dp->dtdo_refcnt++;
10434 	ASSERT(dp->dtdo_refcnt != 0);
10435 
10436 	/*
10437 	 * We need to check this DIF object for references to the variable
10438 	 * DIF_VAR_VTIMESTAMP.
10439 	 */
10440 	for (i = 0; i < dp->dtdo_varlen; i++) {
10441 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10442 
10443 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10444 			continue;
10445 
10446 		if (dtrace_vtime_references++ == 0)
10447 			dtrace_vtime_enable();
10448 	}
10449 }
10450 
10451 /*
10452  * This routine calculates the dynamic variable chunksize for a given DIF
10453  * object.  The calculation is not fool-proof, and can probably be tricked by
10454  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10455  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10456  * if a dynamic variable size exceeds the chunksize.
10457  */
10458 static void
10459 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10460 {
10461 	uint64_t sval = 0;
10462 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10463 	const dif_instr_t *text = dp->dtdo_buf;
10464 	uint_t pc, srd = 0;
10465 	uint_t ttop = 0;
10466 	size_t size, ksize;
10467 	uint_t id, i;
10468 
10469 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10470 		dif_instr_t instr = text[pc];
10471 		uint_t op = DIF_INSTR_OP(instr);
10472 		uint_t rd = DIF_INSTR_RD(instr);
10473 		uint_t r1 = DIF_INSTR_R1(instr);
10474 		uint_t nkeys = 0;
10475 		uchar_t scope = 0;
10476 
10477 		dtrace_key_t *key = tupregs;
10478 
10479 		switch (op) {
10480 		case DIF_OP_SETX:
10481 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10482 			srd = rd;
10483 			continue;
10484 
10485 		case DIF_OP_STTS:
10486 			key = &tupregs[DIF_DTR_NREGS];
10487 			key[0].dttk_size = 0;
10488 			key[1].dttk_size = 0;
10489 			nkeys = 2;
10490 			scope = DIFV_SCOPE_THREAD;
10491 			break;
10492 
10493 		case DIF_OP_STGAA:
10494 		case DIF_OP_STTAA:
10495 			nkeys = ttop;
10496 
10497 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10498 				key[nkeys++].dttk_size = 0;
10499 
10500 			key[nkeys++].dttk_size = 0;
10501 
10502 			if (op == DIF_OP_STTAA) {
10503 				scope = DIFV_SCOPE_THREAD;
10504 			} else {
10505 				scope = DIFV_SCOPE_GLOBAL;
10506 			}
10507 
10508 			break;
10509 
10510 		case DIF_OP_PUSHTR:
10511 			if (ttop == DIF_DTR_NREGS)
10512 				return;
10513 
10514 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10515 				/*
10516 				 * If the register for the size of the "pushtr"
10517 				 * is %r0 (or the value is 0) and the type is
10518 				 * a string, we'll use the system-wide default
10519 				 * string size.
10520 				 */
10521 				tupregs[ttop++].dttk_size =
10522 				    dtrace_strsize_default;
10523 			} else {
10524 				if (srd == 0)
10525 					return;
10526 
10527 				if (sval > LONG_MAX)
10528 					return;
10529 
10530 				tupregs[ttop++].dttk_size = sval;
10531 			}
10532 
10533 			break;
10534 
10535 		case DIF_OP_PUSHTV:
10536 			if (ttop == DIF_DTR_NREGS)
10537 				return;
10538 
10539 			tupregs[ttop++].dttk_size = 0;
10540 			break;
10541 
10542 		case DIF_OP_FLUSHTS:
10543 			ttop = 0;
10544 			break;
10545 
10546 		case DIF_OP_POPTS:
10547 			if (ttop != 0)
10548 				ttop--;
10549 			break;
10550 		}
10551 
10552 		sval = 0;
10553 		srd = 0;
10554 
10555 		if (nkeys == 0)
10556 			continue;
10557 
10558 		/*
10559 		 * We have a dynamic variable allocation; calculate its size.
10560 		 */
10561 		for (ksize = 0, i = 0; i < nkeys; i++)
10562 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10563 
10564 		size = sizeof (dtrace_dynvar_t);
10565 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10566 		size += ksize;
10567 
10568 		/*
10569 		 * Now we need to determine the size of the stored data.
10570 		 */
10571 		id = DIF_INSTR_VAR(instr);
10572 
10573 		for (i = 0; i < dp->dtdo_varlen; i++) {
10574 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10575 
10576 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10577 				size += v->dtdv_type.dtdt_size;
10578 				break;
10579 			}
10580 		}
10581 
10582 		if (i == dp->dtdo_varlen)
10583 			return;
10584 
10585 		/*
10586 		 * We have the size.  If this is larger than the chunk size
10587 		 * for our dynamic variable state, reset the chunk size.
10588 		 */
10589 		size = P2ROUNDUP(size, sizeof (uint64_t));
10590 
10591 		/*
10592 		 * Before setting the chunk size, check that we're not going
10593 		 * to set it to a negative value...
10594 		 */
10595 		if (size > LONG_MAX)
10596 			return;
10597 
10598 		/*
10599 		 * ...and make certain that we didn't badly overflow.
10600 		 */
10601 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10602 			return;
10603 
10604 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10605 			vstate->dtvs_dynvars.dtds_chunksize = size;
10606 	}
10607 }
10608 
10609 static void
10610 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10611 {
10612 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10613 	uint_t id;
10614 
10615 	ASSERT(MUTEX_HELD(&dtrace_lock));
10616 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10617 
10618 	for (i = 0; i < dp->dtdo_varlen; i++) {
10619 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10620 		dtrace_statvar_t *svar, ***svarp = NULL;
10621 		size_t dsize = 0;
10622 		uint8_t scope = v->dtdv_scope;
10623 		int *np = NULL;
10624 
10625 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10626 			continue;
10627 
10628 		id -= DIF_VAR_OTHER_UBASE;
10629 
10630 		switch (scope) {
10631 		case DIFV_SCOPE_THREAD:
10632 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10633 				dtrace_difv_t *tlocals;
10634 
10635 				if ((ntlocals = (otlocals << 1)) == 0)
10636 					ntlocals = 1;
10637 
10638 				osz = otlocals * sizeof (dtrace_difv_t);
10639 				nsz = ntlocals * sizeof (dtrace_difv_t);
10640 
10641 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10642 
10643 				if (osz != 0) {
10644 					bcopy(vstate->dtvs_tlocals,
10645 					    tlocals, osz);
10646 					kmem_free(vstate->dtvs_tlocals, osz);
10647 				}
10648 
10649 				vstate->dtvs_tlocals = tlocals;
10650 				vstate->dtvs_ntlocals = ntlocals;
10651 			}
10652 
10653 			vstate->dtvs_tlocals[id] = *v;
10654 			continue;
10655 
10656 		case DIFV_SCOPE_LOCAL:
10657 			np = &vstate->dtvs_nlocals;
10658 			svarp = &vstate->dtvs_locals;
10659 
10660 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10661 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10662 				    sizeof (uint64_t));
10663 			else
10664 				dsize = NCPU * sizeof (uint64_t);
10665 
10666 			break;
10667 
10668 		case DIFV_SCOPE_GLOBAL:
10669 			np = &vstate->dtvs_nglobals;
10670 			svarp = &vstate->dtvs_globals;
10671 
10672 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10673 				dsize = v->dtdv_type.dtdt_size +
10674 				    sizeof (uint64_t);
10675 
10676 			break;
10677 
10678 		default:
10679 			ASSERT(0);
10680 		}
10681 
10682 		while (id >= (oldsvars = *np)) {
10683 			dtrace_statvar_t **statics;
10684 			int newsvars, oldsize, newsize;
10685 
10686 			if ((newsvars = (oldsvars << 1)) == 0)
10687 				newsvars = 1;
10688 
10689 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10690 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10691 
10692 			statics = kmem_zalloc(newsize, KM_SLEEP);
10693 
10694 			if (oldsize != 0) {
10695 				bcopy(*svarp, statics, oldsize);
10696 				kmem_free(*svarp, oldsize);
10697 			}
10698 
10699 			*svarp = statics;
10700 			*np = newsvars;
10701 		}
10702 
10703 		if ((svar = (*svarp)[id]) == NULL) {
10704 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10705 			svar->dtsv_var = *v;
10706 
10707 			if ((svar->dtsv_size = dsize) != 0) {
10708 				svar->dtsv_data = (uint64_t)(uintptr_t)
10709 				    kmem_zalloc(dsize, KM_SLEEP);
10710 			}
10711 
10712 			(*svarp)[id] = svar;
10713 		}
10714 
10715 		svar->dtsv_refcnt++;
10716 	}
10717 
10718 	dtrace_difo_chunksize(dp, vstate);
10719 	dtrace_difo_hold(dp);
10720 }
10721 
10722 static dtrace_difo_t *
10723 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10724 {
10725 	dtrace_difo_t *new;
10726 	size_t sz;
10727 
10728 	ASSERT(dp->dtdo_buf != NULL);
10729 	ASSERT(dp->dtdo_refcnt != 0);
10730 
10731 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10732 
10733 	ASSERT(dp->dtdo_buf != NULL);
10734 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10735 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10736 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10737 	new->dtdo_len = dp->dtdo_len;
10738 
10739 	if (dp->dtdo_strtab != NULL) {
10740 		ASSERT(dp->dtdo_strlen != 0);
10741 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10742 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10743 		new->dtdo_strlen = dp->dtdo_strlen;
10744 	}
10745 
10746 	if (dp->dtdo_inttab != NULL) {
10747 		ASSERT(dp->dtdo_intlen != 0);
10748 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10749 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10750 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10751 		new->dtdo_intlen = dp->dtdo_intlen;
10752 	}
10753 
10754 	if (dp->dtdo_vartab != NULL) {
10755 		ASSERT(dp->dtdo_varlen != 0);
10756 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10757 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10758 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10759 		new->dtdo_varlen = dp->dtdo_varlen;
10760 	}
10761 
10762 	dtrace_difo_init(new, vstate);
10763 	return (new);
10764 }
10765 
10766 static void
10767 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10768 {
10769 	int i;
10770 
10771 	ASSERT(dp->dtdo_refcnt == 0);
10772 
10773 	for (i = 0; i < dp->dtdo_varlen; i++) {
10774 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10775 		dtrace_statvar_t *svar, **svarp = NULL;
10776 		uint_t id;
10777 		uint8_t scope = v->dtdv_scope;
10778 		int *np = NULL;
10779 
10780 		switch (scope) {
10781 		case DIFV_SCOPE_THREAD:
10782 			continue;
10783 
10784 		case DIFV_SCOPE_LOCAL:
10785 			np = &vstate->dtvs_nlocals;
10786 			svarp = vstate->dtvs_locals;
10787 			break;
10788 
10789 		case DIFV_SCOPE_GLOBAL:
10790 			np = &vstate->dtvs_nglobals;
10791 			svarp = vstate->dtvs_globals;
10792 			break;
10793 
10794 		default:
10795 			ASSERT(0);
10796 		}
10797 
10798 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10799 			continue;
10800 
10801 		id -= DIF_VAR_OTHER_UBASE;
10802 		ASSERT(id < *np);
10803 
10804 		svar = svarp[id];
10805 		ASSERT(svar != NULL);
10806 		ASSERT(svar->dtsv_refcnt > 0);
10807 
10808 		if (--svar->dtsv_refcnt > 0)
10809 			continue;
10810 
10811 		if (svar->dtsv_size != 0) {
10812 			ASSERT(svar->dtsv_data != 0);
10813 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10814 			    svar->dtsv_size);
10815 		}
10816 
10817 		kmem_free(svar, sizeof (dtrace_statvar_t));
10818 		svarp[id] = NULL;
10819 	}
10820 
10821 	if (dp->dtdo_buf != NULL)
10822 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10823 	if (dp->dtdo_inttab != NULL)
10824 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10825 	if (dp->dtdo_strtab != NULL)
10826 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10827 	if (dp->dtdo_vartab != NULL)
10828 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10829 
10830 	kmem_free(dp, sizeof (dtrace_difo_t));
10831 }
10832 
10833 static void
10834 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10835 {
10836 	int i;
10837 
10838 	ASSERT(MUTEX_HELD(&dtrace_lock));
10839 	ASSERT(dp->dtdo_refcnt != 0);
10840 
10841 	for (i = 0; i < dp->dtdo_varlen; i++) {
10842 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10843 
10844 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10845 			continue;
10846 
10847 		ASSERT(dtrace_vtime_references > 0);
10848 		if (--dtrace_vtime_references == 0)
10849 			dtrace_vtime_disable();
10850 	}
10851 
10852 	if (--dp->dtdo_refcnt == 0)
10853 		dtrace_difo_destroy(dp, vstate);
10854 }
10855 
10856 /*
10857  * DTrace Format Functions
10858  */
10859 static uint16_t
10860 dtrace_format_add(dtrace_state_t *state, char *str)
10861 {
10862 	char *fmt, **new;
10863 	uint16_t ndx, len = strlen(str) + 1;
10864 
10865 	fmt = kmem_zalloc(len, KM_SLEEP);
10866 	bcopy(str, fmt, len);
10867 
10868 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10869 		if (state->dts_formats[ndx] == NULL) {
10870 			state->dts_formats[ndx] = fmt;
10871 			return (ndx + 1);
10872 		}
10873 	}
10874 
10875 	if (state->dts_nformats == USHRT_MAX) {
10876 		/*
10877 		 * This is only likely if a denial-of-service attack is being
10878 		 * attempted.  As such, it's okay to fail silently here.
10879 		 */
10880 		kmem_free(fmt, len);
10881 		return (0);
10882 	}
10883 
10884 	/*
10885 	 * For simplicity, we always resize the formats array to be exactly the
10886 	 * number of formats.
10887 	 */
10888 	ndx = state->dts_nformats++;
10889 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10890 
10891 	if (state->dts_formats != NULL) {
10892 		ASSERT(ndx != 0);
10893 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10894 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10895 	}
10896 
10897 	state->dts_formats = new;
10898 	state->dts_formats[ndx] = fmt;
10899 
10900 	return (ndx + 1);
10901 }
10902 
10903 static void
10904 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10905 {
10906 	char *fmt;
10907 
10908 	ASSERT(state->dts_formats != NULL);
10909 	ASSERT(format <= state->dts_nformats);
10910 	ASSERT(state->dts_formats[format - 1] != NULL);
10911 
10912 	fmt = state->dts_formats[format - 1];
10913 	kmem_free(fmt, strlen(fmt) + 1);
10914 	state->dts_formats[format - 1] = NULL;
10915 }
10916 
10917 static void
10918 dtrace_format_destroy(dtrace_state_t *state)
10919 {
10920 	int i;
10921 
10922 	if (state->dts_nformats == 0) {
10923 		ASSERT(state->dts_formats == NULL);
10924 		return;
10925 	}
10926 
10927 	ASSERT(state->dts_formats != NULL);
10928 
10929 	for (i = 0; i < state->dts_nformats; i++) {
10930 		char *fmt = state->dts_formats[i];
10931 
10932 		if (fmt == NULL)
10933 			continue;
10934 
10935 		kmem_free(fmt, strlen(fmt) + 1);
10936 	}
10937 
10938 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10939 	state->dts_nformats = 0;
10940 	state->dts_formats = NULL;
10941 }
10942 
10943 /*
10944  * DTrace Predicate Functions
10945  */
10946 static dtrace_predicate_t *
10947 dtrace_predicate_create(dtrace_difo_t *dp)
10948 {
10949 	dtrace_predicate_t *pred;
10950 
10951 	ASSERT(MUTEX_HELD(&dtrace_lock));
10952 	ASSERT(dp->dtdo_refcnt != 0);
10953 
10954 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10955 	pred->dtp_difo = dp;
10956 	pred->dtp_refcnt = 1;
10957 
10958 	if (!dtrace_difo_cacheable(dp))
10959 		return (pred);
10960 
10961 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10962 		/*
10963 		 * This is only theoretically possible -- we have had 2^32
10964 		 * cacheable predicates on this machine.  We cannot allow any
10965 		 * more predicates to become cacheable:  as unlikely as it is,
10966 		 * there may be a thread caching a (now stale) predicate cache
10967 		 * ID. (N.B.: the temptation is being successfully resisted to
10968 		 * have this cmn_err() "Holy shit -- we executed this code!")
10969 		 */
10970 		return (pred);
10971 	}
10972 
10973 	pred->dtp_cacheid = dtrace_predcache_id++;
10974 
10975 	return (pred);
10976 }
10977 
10978 static void
10979 dtrace_predicate_hold(dtrace_predicate_t *pred)
10980 {
10981 	ASSERT(MUTEX_HELD(&dtrace_lock));
10982 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10983 	ASSERT(pred->dtp_refcnt > 0);
10984 
10985 	pred->dtp_refcnt++;
10986 }
10987 
10988 static void
10989 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10990 {
10991 	dtrace_difo_t *dp = pred->dtp_difo;
10992 
10993 	ASSERT(MUTEX_HELD(&dtrace_lock));
10994 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10995 	ASSERT(pred->dtp_refcnt > 0);
10996 
10997 	if (--pred->dtp_refcnt == 0) {
10998 		dtrace_difo_release(pred->dtp_difo, vstate);
10999 		kmem_free(pred, sizeof (dtrace_predicate_t));
11000 	}
11001 }
11002 
11003 /*
11004  * DTrace Action Description Functions
11005  */
11006 static dtrace_actdesc_t *
11007 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11008     uint64_t uarg, uint64_t arg)
11009 {
11010 	dtrace_actdesc_t *act;
11011 
11012 #ifdef illumos
11013 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11014 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11015 #endif
11016 
11017 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11018 	act->dtad_kind = kind;
11019 	act->dtad_ntuple = ntuple;
11020 	act->dtad_uarg = uarg;
11021 	act->dtad_arg = arg;
11022 	act->dtad_refcnt = 1;
11023 
11024 	return (act);
11025 }
11026 
11027 static void
11028 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11029 {
11030 	ASSERT(act->dtad_refcnt >= 1);
11031 	act->dtad_refcnt++;
11032 }
11033 
11034 static void
11035 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11036 {
11037 	dtrace_actkind_t kind = act->dtad_kind;
11038 	dtrace_difo_t *dp;
11039 
11040 	ASSERT(act->dtad_refcnt >= 1);
11041 
11042 	if (--act->dtad_refcnt != 0)
11043 		return;
11044 
11045 	if ((dp = act->dtad_difo) != NULL)
11046 		dtrace_difo_release(dp, vstate);
11047 
11048 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11049 		char *str = (char *)(uintptr_t)act->dtad_arg;
11050 
11051 #ifdef illumos
11052 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11053 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11054 #endif
11055 
11056 		if (str != NULL)
11057 			kmem_free(str, strlen(str) + 1);
11058 	}
11059 
11060 	kmem_free(act, sizeof (dtrace_actdesc_t));
11061 }
11062 
11063 /*
11064  * DTrace ECB Functions
11065  */
11066 static dtrace_ecb_t *
11067 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11068 {
11069 	dtrace_ecb_t *ecb;
11070 	dtrace_epid_t epid;
11071 
11072 	ASSERT(MUTEX_HELD(&dtrace_lock));
11073 
11074 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11075 	ecb->dte_predicate = NULL;
11076 	ecb->dte_probe = probe;
11077 
11078 	/*
11079 	 * The default size is the size of the default action: recording
11080 	 * the header.
11081 	 */
11082 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11083 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11084 
11085 	epid = state->dts_epid++;
11086 
11087 	if (epid - 1 >= state->dts_necbs) {
11088 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11089 		int necbs = state->dts_necbs << 1;
11090 
11091 		ASSERT(epid == state->dts_necbs + 1);
11092 
11093 		if (necbs == 0) {
11094 			ASSERT(oecbs == NULL);
11095 			necbs = 1;
11096 		}
11097 
11098 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11099 
11100 		if (oecbs != NULL)
11101 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11102 
11103 		dtrace_membar_producer();
11104 		state->dts_ecbs = ecbs;
11105 
11106 		if (oecbs != NULL) {
11107 			/*
11108 			 * If this state is active, we must dtrace_sync()
11109 			 * before we can free the old dts_ecbs array:  we're
11110 			 * coming in hot, and there may be active ring
11111 			 * buffer processing (which indexes into the dts_ecbs
11112 			 * array) on another CPU.
11113 			 */
11114 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11115 				dtrace_sync();
11116 
11117 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11118 		}
11119 
11120 		dtrace_membar_producer();
11121 		state->dts_necbs = necbs;
11122 	}
11123 
11124 	ecb->dte_state = state;
11125 
11126 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11127 	dtrace_membar_producer();
11128 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11129 
11130 	return (ecb);
11131 }
11132 
11133 static void
11134 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11135 {
11136 	dtrace_probe_t *probe = ecb->dte_probe;
11137 
11138 	ASSERT(MUTEX_HELD(&cpu_lock));
11139 	ASSERT(MUTEX_HELD(&dtrace_lock));
11140 	ASSERT(ecb->dte_next == NULL);
11141 
11142 	if (probe == NULL) {
11143 		/*
11144 		 * This is the NULL probe -- there's nothing to do.
11145 		 */
11146 		return;
11147 	}
11148 
11149 	if (probe->dtpr_ecb == NULL) {
11150 		dtrace_provider_t *prov = probe->dtpr_provider;
11151 
11152 		/*
11153 		 * We're the first ECB on this probe.
11154 		 */
11155 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11156 
11157 		if (ecb->dte_predicate != NULL)
11158 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11159 
11160 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11161 		    probe->dtpr_id, probe->dtpr_arg);
11162 	} else {
11163 		/*
11164 		 * This probe is already active.  Swing the last pointer to
11165 		 * point to the new ECB, and issue a dtrace_sync() to assure
11166 		 * that all CPUs have seen the change.
11167 		 */
11168 		ASSERT(probe->dtpr_ecb_last != NULL);
11169 		probe->dtpr_ecb_last->dte_next = ecb;
11170 		probe->dtpr_ecb_last = ecb;
11171 		probe->dtpr_predcache = 0;
11172 
11173 		dtrace_sync();
11174 	}
11175 }
11176 
11177 static int
11178 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11179 {
11180 	dtrace_action_t *act;
11181 	uint32_t curneeded = UINT32_MAX;
11182 	uint32_t aggbase = UINT32_MAX;
11183 
11184 	/*
11185 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11186 	 * we always record it first.)
11187 	 */
11188 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11189 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11190 
11191 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11192 		dtrace_recdesc_t *rec = &act->dta_rec;
11193 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11194 
11195 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11196 		    rec->dtrd_alignment);
11197 
11198 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11199 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11200 
11201 			ASSERT(rec->dtrd_size != 0);
11202 			ASSERT(agg->dtag_first != NULL);
11203 			ASSERT(act->dta_prev->dta_intuple);
11204 			ASSERT(aggbase != UINT32_MAX);
11205 			ASSERT(curneeded != UINT32_MAX);
11206 
11207 			agg->dtag_base = aggbase;
11208 
11209 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11210 			rec->dtrd_offset = curneeded;
11211 			if (curneeded + rec->dtrd_size < curneeded)
11212 				return (EINVAL);
11213 			curneeded += rec->dtrd_size;
11214 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11215 
11216 			aggbase = UINT32_MAX;
11217 			curneeded = UINT32_MAX;
11218 		} else if (act->dta_intuple) {
11219 			if (curneeded == UINT32_MAX) {
11220 				/*
11221 				 * This is the first record in a tuple.  Align
11222 				 * curneeded to be at offset 4 in an 8-byte
11223 				 * aligned block.
11224 				 */
11225 				ASSERT(act->dta_prev == NULL ||
11226 				    !act->dta_prev->dta_intuple);
11227 				ASSERT3U(aggbase, ==, UINT32_MAX);
11228 				curneeded = P2PHASEUP(ecb->dte_size,
11229 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11230 
11231 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11232 				ASSERT(IS_P2ALIGNED(aggbase,
11233 				    sizeof (uint64_t)));
11234 			}
11235 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11236 			rec->dtrd_offset = curneeded;
11237 			if (curneeded + rec->dtrd_size < curneeded)
11238 				return (EINVAL);
11239 			curneeded += rec->dtrd_size;
11240 		} else {
11241 			/* tuples must be followed by an aggregation */
11242 			ASSERT(act->dta_prev == NULL ||
11243 			    !act->dta_prev->dta_intuple);
11244 
11245 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11246 			    rec->dtrd_alignment);
11247 			rec->dtrd_offset = ecb->dte_size;
11248 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11249 				return (EINVAL);
11250 			ecb->dte_size += rec->dtrd_size;
11251 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11252 		}
11253 	}
11254 
11255 	if ((act = ecb->dte_action) != NULL &&
11256 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11257 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11258 		/*
11259 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11260 		 * actions store no data; set the size to 0.
11261 		 */
11262 		ecb->dte_size = 0;
11263 	}
11264 
11265 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11266 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11267 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11268 	    ecb->dte_needed);
11269 	return (0);
11270 }
11271 
11272 static dtrace_action_t *
11273 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11274 {
11275 	dtrace_aggregation_t *agg;
11276 	size_t size = sizeof (uint64_t);
11277 	int ntuple = desc->dtad_ntuple;
11278 	dtrace_action_t *act;
11279 	dtrace_recdesc_t *frec;
11280 	dtrace_aggid_t aggid;
11281 	dtrace_state_t *state = ecb->dte_state;
11282 
11283 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11284 	agg->dtag_ecb = ecb;
11285 
11286 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11287 
11288 	switch (desc->dtad_kind) {
11289 	case DTRACEAGG_MIN:
11290 		agg->dtag_initial = INT64_MAX;
11291 		agg->dtag_aggregate = dtrace_aggregate_min;
11292 		break;
11293 
11294 	case DTRACEAGG_MAX:
11295 		agg->dtag_initial = INT64_MIN;
11296 		agg->dtag_aggregate = dtrace_aggregate_max;
11297 		break;
11298 
11299 	case DTRACEAGG_COUNT:
11300 		agg->dtag_aggregate = dtrace_aggregate_count;
11301 		break;
11302 
11303 	case DTRACEAGG_QUANTIZE:
11304 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11305 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11306 		    sizeof (uint64_t);
11307 		break;
11308 
11309 	case DTRACEAGG_LQUANTIZE: {
11310 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11311 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11312 
11313 		agg->dtag_initial = desc->dtad_arg;
11314 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11315 
11316 		if (step == 0 || levels == 0)
11317 			goto err;
11318 
11319 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11320 		break;
11321 	}
11322 
11323 	case DTRACEAGG_LLQUANTIZE: {
11324 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11325 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11326 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11327 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11328 		int64_t v;
11329 
11330 		agg->dtag_initial = desc->dtad_arg;
11331 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11332 
11333 		if (factor < 2 || low >= high || nsteps < factor)
11334 			goto err;
11335 
11336 		/*
11337 		 * Now check that the number of steps evenly divides a power
11338 		 * of the factor.  (This assures both integer bucket size and
11339 		 * linearity within each magnitude.)
11340 		 */
11341 		for (v = factor; v < nsteps; v *= factor)
11342 			continue;
11343 
11344 		if ((v % nsteps) || (nsteps % factor))
11345 			goto err;
11346 
11347 		size = (dtrace_aggregate_llquantize_bucket(factor,
11348 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11349 		break;
11350 	}
11351 
11352 	case DTRACEAGG_AVG:
11353 		agg->dtag_aggregate = dtrace_aggregate_avg;
11354 		size = sizeof (uint64_t) * 2;
11355 		break;
11356 
11357 	case DTRACEAGG_STDDEV:
11358 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11359 		size = sizeof (uint64_t) * 4;
11360 		break;
11361 
11362 	case DTRACEAGG_SUM:
11363 		agg->dtag_aggregate = dtrace_aggregate_sum;
11364 		break;
11365 
11366 	default:
11367 		goto err;
11368 	}
11369 
11370 	agg->dtag_action.dta_rec.dtrd_size = size;
11371 
11372 	if (ntuple == 0)
11373 		goto err;
11374 
11375 	/*
11376 	 * We must make sure that we have enough actions for the n-tuple.
11377 	 */
11378 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11379 		if (DTRACEACT_ISAGG(act->dta_kind))
11380 			break;
11381 
11382 		if (--ntuple == 0) {
11383 			/*
11384 			 * This is the action with which our n-tuple begins.
11385 			 */
11386 			agg->dtag_first = act;
11387 			goto success;
11388 		}
11389 	}
11390 
11391 	/*
11392 	 * This n-tuple is short by ntuple elements.  Return failure.
11393 	 */
11394 	ASSERT(ntuple != 0);
11395 err:
11396 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11397 	return (NULL);
11398 
11399 success:
11400 	/*
11401 	 * If the last action in the tuple has a size of zero, it's actually
11402 	 * an expression argument for the aggregating action.
11403 	 */
11404 	ASSERT(ecb->dte_action_last != NULL);
11405 	act = ecb->dte_action_last;
11406 
11407 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11408 		ASSERT(act->dta_difo != NULL);
11409 
11410 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11411 			agg->dtag_hasarg = 1;
11412 	}
11413 
11414 	/*
11415 	 * We need to allocate an id for this aggregation.
11416 	 */
11417 #ifdef illumos
11418 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11419 	    VM_BESTFIT | VM_SLEEP);
11420 #else
11421 	aggid = alloc_unr(state->dts_aggid_arena);
11422 #endif
11423 
11424 	if (aggid - 1 >= state->dts_naggregations) {
11425 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11426 		dtrace_aggregation_t **aggs;
11427 		int naggs = state->dts_naggregations << 1;
11428 		int onaggs = state->dts_naggregations;
11429 
11430 		ASSERT(aggid == state->dts_naggregations + 1);
11431 
11432 		if (naggs == 0) {
11433 			ASSERT(oaggs == NULL);
11434 			naggs = 1;
11435 		}
11436 
11437 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11438 
11439 		if (oaggs != NULL) {
11440 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11441 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11442 		}
11443 
11444 		state->dts_aggregations = aggs;
11445 		state->dts_naggregations = naggs;
11446 	}
11447 
11448 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11449 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11450 
11451 	frec = &agg->dtag_first->dta_rec;
11452 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11453 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11454 
11455 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11456 		ASSERT(!act->dta_intuple);
11457 		act->dta_intuple = 1;
11458 	}
11459 
11460 	return (&agg->dtag_action);
11461 }
11462 
11463 static void
11464 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11465 {
11466 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11467 	dtrace_state_t *state = ecb->dte_state;
11468 	dtrace_aggid_t aggid = agg->dtag_id;
11469 
11470 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11471 #ifdef illumos
11472 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11473 #else
11474 	free_unr(state->dts_aggid_arena, aggid);
11475 #endif
11476 
11477 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11478 	state->dts_aggregations[aggid - 1] = NULL;
11479 
11480 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11481 }
11482 
11483 static int
11484 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11485 {
11486 	dtrace_action_t *action, *last;
11487 	dtrace_difo_t *dp = desc->dtad_difo;
11488 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11489 	uint16_t format = 0;
11490 	dtrace_recdesc_t *rec;
11491 	dtrace_state_t *state = ecb->dte_state;
11492 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11493 	uint64_t arg = desc->dtad_arg;
11494 
11495 	ASSERT(MUTEX_HELD(&dtrace_lock));
11496 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11497 
11498 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11499 		/*
11500 		 * If this is an aggregating action, there must be neither
11501 		 * a speculate nor a commit on the action chain.
11502 		 */
11503 		dtrace_action_t *act;
11504 
11505 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11506 			if (act->dta_kind == DTRACEACT_COMMIT)
11507 				return (EINVAL);
11508 
11509 			if (act->dta_kind == DTRACEACT_SPECULATE)
11510 				return (EINVAL);
11511 		}
11512 
11513 		action = dtrace_ecb_aggregation_create(ecb, desc);
11514 
11515 		if (action == NULL)
11516 			return (EINVAL);
11517 	} else {
11518 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11519 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11520 		    dp != NULL && dp->dtdo_destructive)) {
11521 			state->dts_destructive = 1;
11522 		}
11523 
11524 		switch (desc->dtad_kind) {
11525 		case DTRACEACT_PRINTF:
11526 		case DTRACEACT_PRINTA:
11527 		case DTRACEACT_SYSTEM:
11528 		case DTRACEACT_FREOPEN:
11529 		case DTRACEACT_DIFEXPR:
11530 			/*
11531 			 * We know that our arg is a string -- turn it into a
11532 			 * format.
11533 			 */
11534 			if (arg == 0) {
11535 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11536 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11537 				format = 0;
11538 			} else {
11539 				ASSERT(arg != 0);
11540 #ifdef illumos
11541 				ASSERT(arg > KERNELBASE);
11542 #endif
11543 				format = dtrace_format_add(state,
11544 				    (char *)(uintptr_t)arg);
11545 			}
11546 
11547 			/*FALLTHROUGH*/
11548 		case DTRACEACT_LIBACT:
11549 		case DTRACEACT_TRACEMEM:
11550 		case DTRACEACT_TRACEMEM_DYNSIZE:
11551 			if (dp == NULL)
11552 				return (EINVAL);
11553 
11554 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11555 				break;
11556 
11557 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11558 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11559 					return (EINVAL);
11560 
11561 				size = opt[DTRACEOPT_STRSIZE];
11562 			}
11563 
11564 			break;
11565 
11566 		case DTRACEACT_STACK:
11567 			if ((nframes = arg) == 0) {
11568 				nframes = opt[DTRACEOPT_STACKFRAMES];
11569 				ASSERT(nframes > 0);
11570 				arg = nframes;
11571 			}
11572 
11573 			size = nframes * sizeof (pc_t);
11574 			break;
11575 
11576 		case DTRACEACT_JSTACK:
11577 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11578 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11579 
11580 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11581 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11582 
11583 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11584 
11585 			/*FALLTHROUGH*/
11586 		case DTRACEACT_USTACK:
11587 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11588 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11589 				strsize = DTRACE_USTACK_STRSIZE(arg);
11590 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11591 				ASSERT(nframes > 0);
11592 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11593 			}
11594 
11595 			/*
11596 			 * Save a slot for the pid.
11597 			 */
11598 			size = (nframes + 1) * sizeof (uint64_t);
11599 			size += DTRACE_USTACK_STRSIZE(arg);
11600 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11601 
11602 			break;
11603 
11604 		case DTRACEACT_SYM:
11605 		case DTRACEACT_MOD:
11606 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11607 			    sizeof (uint64_t)) ||
11608 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11609 				return (EINVAL);
11610 			break;
11611 
11612 		case DTRACEACT_USYM:
11613 		case DTRACEACT_UMOD:
11614 		case DTRACEACT_UADDR:
11615 			if (dp == NULL ||
11616 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11617 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11618 				return (EINVAL);
11619 
11620 			/*
11621 			 * We have a slot for the pid, plus a slot for the
11622 			 * argument.  To keep things simple (aligned with
11623 			 * bitness-neutral sizing), we store each as a 64-bit
11624 			 * quantity.
11625 			 */
11626 			size = 2 * sizeof (uint64_t);
11627 			break;
11628 
11629 		case DTRACEACT_STOP:
11630 		case DTRACEACT_BREAKPOINT:
11631 		case DTRACEACT_PANIC:
11632 			break;
11633 
11634 		case DTRACEACT_CHILL:
11635 		case DTRACEACT_DISCARD:
11636 		case DTRACEACT_RAISE:
11637 			if (dp == NULL)
11638 				return (EINVAL);
11639 			break;
11640 
11641 		case DTRACEACT_EXIT:
11642 			if (dp == NULL ||
11643 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11644 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11645 				return (EINVAL);
11646 			break;
11647 
11648 		case DTRACEACT_SPECULATE:
11649 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11650 				return (EINVAL);
11651 
11652 			if (dp == NULL)
11653 				return (EINVAL);
11654 
11655 			state->dts_speculates = 1;
11656 			break;
11657 
11658 		case DTRACEACT_PRINTM:
11659 		    	size = dp->dtdo_rtype.dtdt_size;
11660 			break;
11661 
11662 		case DTRACEACT_COMMIT: {
11663 			dtrace_action_t *act = ecb->dte_action;
11664 
11665 			for (; act != NULL; act = act->dta_next) {
11666 				if (act->dta_kind == DTRACEACT_COMMIT)
11667 					return (EINVAL);
11668 			}
11669 
11670 			if (dp == NULL)
11671 				return (EINVAL);
11672 			break;
11673 		}
11674 
11675 		default:
11676 			return (EINVAL);
11677 		}
11678 
11679 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11680 			/*
11681 			 * If this is a data-storing action or a speculate,
11682 			 * we must be sure that there isn't a commit on the
11683 			 * action chain.
11684 			 */
11685 			dtrace_action_t *act = ecb->dte_action;
11686 
11687 			for (; act != NULL; act = act->dta_next) {
11688 				if (act->dta_kind == DTRACEACT_COMMIT)
11689 					return (EINVAL);
11690 			}
11691 		}
11692 
11693 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11694 		action->dta_rec.dtrd_size = size;
11695 	}
11696 
11697 	action->dta_refcnt = 1;
11698 	rec = &action->dta_rec;
11699 	size = rec->dtrd_size;
11700 
11701 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11702 		if (!(size & mask)) {
11703 			align = mask + 1;
11704 			break;
11705 		}
11706 	}
11707 
11708 	action->dta_kind = desc->dtad_kind;
11709 
11710 	if ((action->dta_difo = dp) != NULL)
11711 		dtrace_difo_hold(dp);
11712 
11713 	rec->dtrd_action = action->dta_kind;
11714 	rec->dtrd_arg = arg;
11715 	rec->dtrd_uarg = desc->dtad_uarg;
11716 	rec->dtrd_alignment = (uint16_t)align;
11717 	rec->dtrd_format = format;
11718 
11719 	if ((last = ecb->dte_action_last) != NULL) {
11720 		ASSERT(ecb->dte_action != NULL);
11721 		action->dta_prev = last;
11722 		last->dta_next = action;
11723 	} else {
11724 		ASSERT(ecb->dte_action == NULL);
11725 		ecb->dte_action = action;
11726 	}
11727 
11728 	ecb->dte_action_last = action;
11729 
11730 	return (0);
11731 }
11732 
11733 static void
11734 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11735 {
11736 	dtrace_action_t *act = ecb->dte_action, *next;
11737 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11738 	dtrace_difo_t *dp;
11739 	uint16_t format;
11740 
11741 	if (act != NULL && act->dta_refcnt > 1) {
11742 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11743 		act->dta_refcnt--;
11744 	} else {
11745 		for (; act != NULL; act = next) {
11746 			next = act->dta_next;
11747 			ASSERT(next != NULL || act == ecb->dte_action_last);
11748 			ASSERT(act->dta_refcnt == 1);
11749 
11750 			if ((format = act->dta_rec.dtrd_format) != 0)
11751 				dtrace_format_remove(ecb->dte_state, format);
11752 
11753 			if ((dp = act->dta_difo) != NULL)
11754 				dtrace_difo_release(dp, vstate);
11755 
11756 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11757 				dtrace_ecb_aggregation_destroy(ecb, act);
11758 			} else {
11759 				kmem_free(act, sizeof (dtrace_action_t));
11760 			}
11761 		}
11762 	}
11763 
11764 	ecb->dte_action = NULL;
11765 	ecb->dte_action_last = NULL;
11766 	ecb->dte_size = 0;
11767 }
11768 
11769 static void
11770 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11771 {
11772 	/*
11773 	 * We disable the ECB by removing it from its probe.
11774 	 */
11775 	dtrace_ecb_t *pecb, *prev = NULL;
11776 	dtrace_probe_t *probe = ecb->dte_probe;
11777 
11778 	ASSERT(MUTEX_HELD(&dtrace_lock));
11779 
11780 	if (probe == NULL) {
11781 		/*
11782 		 * This is the NULL probe; there is nothing to disable.
11783 		 */
11784 		return;
11785 	}
11786 
11787 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11788 		if (pecb == ecb)
11789 			break;
11790 		prev = pecb;
11791 	}
11792 
11793 	ASSERT(pecb != NULL);
11794 
11795 	if (prev == NULL) {
11796 		probe->dtpr_ecb = ecb->dte_next;
11797 	} else {
11798 		prev->dte_next = ecb->dte_next;
11799 	}
11800 
11801 	if (ecb == probe->dtpr_ecb_last) {
11802 		ASSERT(ecb->dte_next == NULL);
11803 		probe->dtpr_ecb_last = prev;
11804 	}
11805 
11806 	/*
11807 	 * The ECB has been disconnected from the probe; now sync to assure
11808 	 * that all CPUs have seen the change before returning.
11809 	 */
11810 	dtrace_sync();
11811 
11812 	if (probe->dtpr_ecb == NULL) {
11813 		/*
11814 		 * That was the last ECB on the probe; clear the predicate
11815 		 * cache ID for the probe, disable it and sync one more time
11816 		 * to assure that we'll never hit it again.
11817 		 */
11818 		dtrace_provider_t *prov = probe->dtpr_provider;
11819 
11820 		ASSERT(ecb->dte_next == NULL);
11821 		ASSERT(probe->dtpr_ecb_last == NULL);
11822 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11823 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11824 		    probe->dtpr_id, probe->dtpr_arg);
11825 		dtrace_sync();
11826 	} else {
11827 		/*
11828 		 * There is at least one ECB remaining on the probe.  If there
11829 		 * is _exactly_ one, set the probe's predicate cache ID to be
11830 		 * the predicate cache ID of the remaining ECB.
11831 		 */
11832 		ASSERT(probe->dtpr_ecb_last != NULL);
11833 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11834 
11835 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11836 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11837 
11838 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11839 
11840 			if (p != NULL)
11841 				probe->dtpr_predcache = p->dtp_cacheid;
11842 		}
11843 
11844 		ecb->dte_next = NULL;
11845 	}
11846 }
11847 
11848 static void
11849 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11850 {
11851 	dtrace_state_t *state = ecb->dte_state;
11852 	dtrace_vstate_t *vstate = &state->dts_vstate;
11853 	dtrace_predicate_t *pred;
11854 	dtrace_epid_t epid = ecb->dte_epid;
11855 
11856 	ASSERT(MUTEX_HELD(&dtrace_lock));
11857 	ASSERT(ecb->dte_next == NULL);
11858 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11859 
11860 	if ((pred = ecb->dte_predicate) != NULL)
11861 		dtrace_predicate_release(pred, vstate);
11862 
11863 	dtrace_ecb_action_remove(ecb);
11864 
11865 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11866 	state->dts_ecbs[epid - 1] = NULL;
11867 
11868 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11869 }
11870 
11871 static dtrace_ecb_t *
11872 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11873     dtrace_enabling_t *enab)
11874 {
11875 	dtrace_ecb_t *ecb;
11876 	dtrace_predicate_t *pred;
11877 	dtrace_actdesc_t *act;
11878 	dtrace_provider_t *prov;
11879 	dtrace_ecbdesc_t *desc = enab->dten_current;
11880 
11881 	ASSERT(MUTEX_HELD(&dtrace_lock));
11882 	ASSERT(state != NULL);
11883 
11884 	ecb = dtrace_ecb_add(state, probe);
11885 	ecb->dte_uarg = desc->dted_uarg;
11886 
11887 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11888 		dtrace_predicate_hold(pred);
11889 		ecb->dte_predicate = pred;
11890 	}
11891 
11892 	if (probe != NULL) {
11893 		/*
11894 		 * If the provider shows more leg than the consumer is old
11895 		 * enough to see, we need to enable the appropriate implicit
11896 		 * predicate bits to prevent the ecb from activating at
11897 		 * revealing times.
11898 		 *
11899 		 * Providers specifying DTRACE_PRIV_USER at register time
11900 		 * are stating that they need the /proc-style privilege
11901 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11902 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11903 		 */
11904 		prov = probe->dtpr_provider;
11905 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11906 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11907 			ecb->dte_cond |= DTRACE_COND_OWNER;
11908 
11909 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11910 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11911 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11912 
11913 		/*
11914 		 * If the provider shows us kernel innards and the user
11915 		 * is lacking sufficient privilege, enable the
11916 		 * DTRACE_COND_USERMODE implicit predicate.
11917 		 */
11918 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11919 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11920 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11921 	}
11922 
11923 	if (dtrace_ecb_create_cache != NULL) {
11924 		/*
11925 		 * If we have a cached ecb, we'll use its action list instead
11926 		 * of creating our own (saving both time and space).
11927 		 */
11928 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11929 		dtrace_action_t *act = cached->dte_action;
11930 
11931 		if (act != NULL) {
11932 			ASSERT(act->dta_refcnt > 0);
11933 			act->dta_refcnt++;
11934 			ecb->dte_action = act;
11935 			ecb->dte_action_last = cached->dte_action_last;
11936 			ecb->dte_needed = cached->dte_needed;
11937 			ecb->dte_size = cached->dte_size;
11938 			ecb->dte_alignment = cached->dte_alignment;
11939 		}
11940 
11941 		return (ecb);
11942 	}
11943 
11944 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11945 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11946 			dtrace_ecb_destroy(ecb);
11947 			return (NULL);
11948 		}
11949 	}
11950 
11951 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11952 		dtrace_ecb_destroy(ecb);
11953 		return (NULL);
11954 	}
11955 
11956 	return (dtrace_ecb_create_cache = ecb);
11957 }
11958 
11959 static int
11960 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11961 {
11962 	dtrace_ecb_t *ecb;
11963 	dtrace_enabling_t *enab = arg;
11964 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11965 
11966 	ASSERT(state != NULL);
11967 
11968 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11969 		/*
11970 		 * This probe was created in a generation for which this
11971 		 * enabling has previously created ECBs; we don't want to
11972 		 * enable it again, so just kick out.
11973 		 */
11974 		return (DTRACE_MATCH_NEXT);
11975 	}
11976 
11977 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11978 		return (DTRACE_MATCH_DONE);
11979 
11980 	dtrace_ecb_enable(ecb);
11981 	return (DTRACE_MATCH_NEXT);
11982 }
11983 
11984 static dtrace_ecb_t *
11985 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11986 {
11987 	dtrace_ecb_t *ecb;
11988 
11989 	ASSERT(MUTEX_HELD(&dtrace_lock));
11990 
11991 	if (id == 0 || id > state->dts_necbs)
11992 		return (NULL);
11993 
11994 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11995 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11996 
11997 	return (state->dts_ecbs[id - 1]);
11998 }
11999 
12000 static dtrace_aggregation_t *
12001 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12002 {
12003 	dtrace_aggregation_t *agg;
12004 
12005 	ASSERT(MUTEX_HELD(&dtrace_lock));
12006 
12007 	if (id == 0 || id > state->dts_naggregations)
12008 		return (NULL);
12009 
12010 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12011 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12012 	    agg->dtag_id == id);
12013 
12014 	return (state->dts_aggregations[id - 1]);
12015 }
12016 
12017 /*
12018  * DTrace Buffer Functions
12019  *
12020  * The following functions manipulate DTrace buffers.  Most of these functions
12021  * are called in the context of establishing or processing consumer state;
12022  * exceptions are explicitly noted.
12023  */
12024 
12025 /*
12026  * Note:  called from cross call context.  This function switches the two
12027  * buffers on a given CPU.  The atomicity of this operation is assured by
12028  * disabling interrupts while the actual switch takes place; the disabling of
12029  * interrupts serializes the execution with any execution of dtrace_probe() on
12030  * the same CPU.
12031  */
12032 static void
12033 dtrace_buffer_switch(dtrace_buffer_t *buf)
12034 {
12035 	caddr_t tomax = buf->dtb_tomax;
12036 	caddr_t xamot = buf->dtb_xamot;
12037 	dtrace_icookie_t cookie;
12038 	hrtime_t now;
12039 
12040 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12041 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12042 
12043 	cookie = dtrace_interrupt_disable();
12044 	now = dtrace_gethrtime();
12045 	buf->dtb_tomax = xamot;
12046 	buf->dtb_xamot = tomax;
12047 	buf->dtb_xamot_drops = buf->dtb_drops;
12048 	buf->dtb_xamot_offset = buf->dtb_offset;
12049 	buf->dtb_xamot_errors = buf->dtb_errors;
12050 	buf->dtb_xamot_flags = buf->dtb_flags;
12051 	buf->dtb_offset = 0;
12052 	buf->dtb_drops = 0;
12053 	buf->dtb_errors = 0;
12054 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12055 	buf->dtb_interval = now - buf->dtb_switched;
12056 	buf->dtb_switched = now;
12057 	dtrace_interrupt_enable(cookie);
12058 }
12059 
12060 /*
12061  * Note:  called from cross call context.  This function activates a buffer
12062  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12063  * is guaranteed by the disabling of interrupts.
12064  */
12065 static void
12066 dtrace_buffer_activate(dtrace_state_t *state)
12067 {
12068 	dtrace_buffer_t *buf;
12069 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12070 
12071 	buf = &state->dts_buffer[curcpu];
12072 
12073 	if (buf->dtb_tomax != NULL) {
12074 		/*
12075 		 * We might like to assert that the buffer is marked inactive,
12076 		 * but this isn't necessarily true:  the buffer for the CPU
12077 		 * that processes the BEGIN probe has its buffer activated
12078 		 * manually.  In this case, we take the (harmless) action
12079 		 * re-clearing the bit INACTIVE bit.
12080 		 */
12081 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12082 	}
12083 
12084 	dtrace_interrupt_enable(cookie);
12085 }
12086 
12087 #ifdef __FreeBSD__
12088 /*
12089  * Activate the specified per-CPU buffer.  This is used instead of
12090  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12091  * activating anonymous state.
12092  */
12093 static void
12094 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12095 {
12096 
12097 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12098 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12099 }
12100 #endif
12101 
12102 static int
12103 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12104     processorid_t cpu, int *factor)
12105 {
12106 #ifdef illumos
12107 	cpu_t *cp;
12108 #endif
12109 	dtrace_buffer_t *buf;
12110 	int allocated = 0, desired = 0;
12111 
12112 #ifdef illumos
12113 	ASSERT(MUTEX_HELD(&cpu_lock));
12114 	ASSERT(MUTEX_HELD(&dtrace_lock));
12115 
12116 	*factor = 1;
12117 
12118 	if (size > dtrace_nonroot_maxsize &&
12119 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12120 		return (EFBIG);
12121 
12122 	cp = cpu_list;
12123 
12124 	do {
12125 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12126 			continue;
12127 
12128 		buf = &bufs[cp->cpu_id];
12129 
12130 		/*
12131 		 * If there is already a buffer allocated for this CPU, it
12132 		 * is only possible that this is a DR event.  In this case,
12133 		 */
12134 		if (buf->dtb_tomax != NULL) {
12135 			ASSERT(buf->dtb_size == size);
12136 			continue;
12137 		}
12138 
12139 		ASSERT(buf->dtb_xamot == NULL);
12140 
12141 		if ((buf->dtb_tomax = kmem_zalloc(size,
12142 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12143 			goto err;
12144 
12145 		buf->dtb_size = size;
12146 		buf->dtb_flags = flags;
12147 		buf->dtb_offset = 0;
12148 		buf->dtb_drops = 0;
12149 
12150 		if (flags & DTRACEBUF_NOSWITCH)
12151 			continue;
12152 
12153 		if ((buf->dtb_xamot = kmem_zalloc(size,
12154 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12155 			goto err;
12156 	} while ((cp = cp->cpu_next) != cpu_list);
12157 
12158 	return (0);
12159 
12160 err:
12161 	cp = cpu_list;
12162 
12163 	do {
12164 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12165 			continue;
12166 
12167 		buf = &bufs[cp->cpu_id];
12168 		desired += 2;
12169 
12170 		if (buf->dtb_xamot != NULL) {
12171 			ASSERT(buf->dtb_tomax != NULL);
12172 			ASSERT(buf->dtb_size == size);
12173 			kmem_free(buf->dtb_xamot, size);
12174 			allocated++;
12175 		}
12176 
12177 		if (buf->dtb_tomax != NULL) {
12178 			ASSERT(buf->dtb_size == size);
12179 			kmem_free(buf->dtb_tomax, size);
12180 			allocated++;
12181 		}
12182 
12183 		buf->dtb_tomax = NULL;
12184 		buf->dtb_xamot = NULL;
12185 		buf->dtb_size = 0;
12186 	} while ((cp = cp->cpu_next) != cpu_list);
12187 #else
12188 	int i;
12189 
12190 	*factor = 1;
12191 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12192     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12193 	/*
12194 	 * FreeBSD isn't good at limiting the amount of memory we
12195 	 * ask to malloc, so let's place a limit here before trying
12196 	 * to do something that might well end in tears at bedtime.
12197 	 */
12198 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12199 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12200 		return (ENOMEM);
12201 #endif
12202 
12203 	ASSERT(MUTEX_HELD(&dtrace_lock));
12204 	CPU_FOREACH(i) {
12205 		if (cpu != DTRACE_CPUALL && cpu != i)
12206 			continue;
12207 
12208 		buf = &bufs[i];
12209 
12210 		/*
12211 		 * If there is already a buffer allocated for this CPU, it
12212 		 * is only possible that this is a DR event.  In this case,
12213 		 * the buffer size must match our specified size.
12214 		 */
12215 		if (buf->dtb_tomax != NULL) {
12216 			ASSERT(buf->dtb_size == size);
12217 			continue;
12218 		}
12219 
12220 		ASSERT(buf->dtb_xamot == NULL);
12221 
12222 		if ((buf->dtb_tomax = kmem_zalloc(size,
12223 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12224 			goto err;
12225 
12226 		buf->dtb_size = size;
12227 		buf->dtb_flags = flags;
12228 		buf->dtb_offset = 0;
12229 		buf->dtb_drops = 0;
12230 
12231 		if (flags & DTRACEBUF_NOSWITCH)
12232 			continue;
12233 
12234 		if ((buf->dtb_xamot = kmem_zalloc(size,
12235 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12236 			goto err;
12237 	}
12238 
12239 	return (0);
12240 
12241 err:
12242 	/*
12243 	 * Error allocating memory, so free the buffers that were
12244 	 * allocated before the failed allocation.
12245 	 */
12246 	CPU_FOREACH(i) {
12247 		if (cpu != DTRACE_CPUALL && cpu != i)
12248 			continue;
12249 
12250 		buf = &bufs[i];
12251 		desired += 2;
12252 
12253 		if (buf->dtb_xamot != NULL) {
12254 			ASSERT(buf->dtb_tomax != NULL);
12255 			ASSERT(buf->dtb_size == size);
12256 			kmem_free(buf->dtb_xamot, size);
12257 			allocated++;
12258 		}
12259 
12260 		if (buf->dtb_tomax != NULL) {
12261 			ASSERT(buf->dtb_size == size);
12262 			kmem_free(buf->dtb_tomax, size);
12263 			allocated++;
12264 		}
12265 
12266 		buf->dtb_tomax = NULL;
12267 		buf->dtb_xamot = NULL;
12268 		buf->dtb_size = 0;
12269 
12270 	}
12271 #endif
12272 	*factor = desired / (allocated > 0 ? allocated : 1);
12273 
12274 	return (ENOMEM);
12275 }
12276 
12277 /*
12278  * Note:  called from probe context.  This function just increments the drop
12279  * count on a buffer.  It has been made a function to allow for the
12280  * possibility of understanding the source of mysterious drop counts.  (A
12281  * problem for which one may be particularly disappointed that DTrace cannot
12282  * be used to understand DTrace.)
12283  */
12284 static void
12285 dtrace_buffer_drop(dtrace_buffer_t *buf)
12286 {
12287 	buf->dtb_drops++;
12288 }
12289 
12290 /*
12291  * Note:  called from probe context.  This function is called to reserve space
12292  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12293  * mstate.  Returns the new offset in the buffer, or a negative value if an
12294  * error has occurred.
12295  */
12296 static intptr_t
12297 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12298     dtrace_state_t *state, dtrace_mstate_t *mstate)
12299 {
12300 	intptr_t offs = buf->dtb_offset, soffs;
12301 	intptr_t woffs;
12302 	caddr_t tomax;
12303 	size_t total;
12304 
12305 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12306 		return (-1);
12307 
12308 	if ((tomax = buf->dtb_tomax) == NULL) {
12309 		dtrace_buffer_drop(buf);
12310 		return (-1);
12311 	}
12312 
12313 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12314 		while (offs & (align - 1)) {
12315 			/*
12316 			 * Assert that our alignment is off by a number which
12317 			 * is itself sizeof (uint32_t) aligned.
12318 			 */
12319 			ASSERT(!((align - (offs & (align - 1))) &
12320 			    (sizeof (uint32_t) - 1)));
12321 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12322 			offs += sizeof (uint32_t);
12323 		}
12324 
12325 		if ((soffs = offs + needed) > buf->dtb_size) {
12326 			dtrace_buffer_drop(buf);
12327 			return (-1);
12328 		}
12329 
12330 		if (mstate == NULL)
12331 			return (offs);
12332 
12333 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12334 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12335 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12336 
12337 		return (offs);
12338 	}
12339 
12340 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12341 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12342 		    (buf->dtb_flags & DTRACEBUF_FULL))
12343 			return (-1);
12344 		goto out;
12345 	}
12346 
12347 	total = needed + (offs & (align - 1));
12348 
12349 	/*
12350 	 * For a ring buffer, life is quite a bit more complicated.  Before
12351 	 * we can store any padding, we need to adjust our wrapping offset.
12352 	 * (If we've never before wrapped or we're not about to, no adjustment
12353 	 * is required.)
12354 	 */
12355 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12356 	    offs + total > buf->dtb_size) {
12357 		woffs = buf->dtb_xamot_offset;
12358 
12359 		if (offs + total > buf->dtb_size) {
12360 			/*
12361 			 * We can't fit in the end of the buffer.  First, a
12362 			 * sanity check that we can fit in the buffer at all.
12363 			 */
12364 			if (total > buf->dtb_size) {
12365 				dtrace_buffer_drop(buf);
12366 				return (-1);
12367 			}
12368 
12369 			/*
12370 			 * We're going to be storing at the top of the buffer,
12371 			 * so now we need to deal with the wrapped offset.  We
12372 			 * only reset our wrapped offset to 0 if it is
12373 			 * currently greater than the current offset.  If it
12374 			 * is less than the current offset, it is because a
12375 			 * previous allocation induced a wrap -- but the
12376 			 * allocation didn't subsequently take the space due
12377 			 * to an error or false predicate evaluation.  In this
12378 			 * case, we'll just leave the wrapped offset alone: if
12379 			 * the wrapped offset hasn't been advanced far enough
12380 			 * for this allocation, it will be adjusted in the
12381 			 * lower loop.
12382 			 */
12383 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12384 				if (woffs >= offs)
12385 					woffs = 0;
12386 			} else {
12387 				woffs = 0;
12388 			}
12389 
12390 			/*
12391 			 * Now we know that we're going to be storing to the
12392 			 * top of the buffer and that there is room for us
12393 			 * there.  We need to clear the buffer from the current
12394 			 * offset to the end (there may be old gunk there).
12395 			 */
12396 			while (offs < buf->dtb_size)
12397 				tomax[offs++] = 0;
12398 
12399 			/*
12400 			 * We need to set our offset to zero.  And because we
12401 			 * are wrapping, we need to set the bit indicating as
12402 			 * much.  We can also adjust our needed space back
12403 			 * down to the space required by the ECB -- we know
12404 			 * that the top of the buffer is aligned.
12405 			 */
12406 			offs = 0;
12407 			total = needed;
12408 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12409 		} else {
12410 			/*
12411 			 * There is room for us in the buffer, so we simply
12412 			 * need to check the wrapped offset.
12413 			 */
12414 			if (woffs < offs) {
12415 				/*
12416 				 * The wrapped offset is less than the offset.
12417 				 * This can happen if we allocated buffer space
12418 				 * that induced a wrap, but then we didn't
12419 				 * subsequently take the space due to an error
12420 				 * or false predicate evaluation.  This is
12421 				 * okay; we know that _this_ allocation isn't
12422 				 * going to induce a wrap.  We still can't
12423 				 * reset the wrapped offset to be zero,
12424 				 * however: the space may have been trashed in
12425 				 * the previous failed probe attempt.  But at
12426 				 * least the wrapped offset doesn't need to
12427 				 * be adjusted at all...
12428 				 */
12429 				goto out;
12430 			}
12431 		}
12432 
12433 		while (offs + total > woffs) {
12434 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12435 			size_t size;
12436 
12437 			if (epid == DTRACE_EPIDNONE) {
12438 				size = sizeof (uint32_t);
12439 			} else {
12440 				ASSERT3U(epid, <=, state->dts_necbs);
12441 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12442 
12443 				size = state->dts_ecbs[epid - 1]->dte_size;
12444 			}
12445 
12446 			ASSERT(woffs + size <= buf->dtb_size);
12447 			ASSERT(size != 0);
12448 
12449 			if (woffs + size == buf->dtb_size) {
12450 				/*
12451 				 * We've reached the end of the buffer; we want
12452 				 * to set the wrapped offset to 0 and break
12453 				 * out.  However, if the offs is 0, then we're
12454 				 * in a strange edge-condition:  the amount of
12455 				 * space that we want to reserve plus the size
12456 				 * of the record that we're overwriting is
12457 				 * greater than the size of the buffer.  This
12458 				 * is problematic because if we reserve the
12459 				 * space but subsequently don't consume it (due
12460 				 * to a failed predicate or error) the wrapped
12461 				 * offset will be 0 -- yet the EPID at offset 0
12462 				 * will not be committed.  This situation is
12463 				 * relatively easy to deal with:  if we're in
12464 				 * this case, the buffer is indistinguishable
12465 				 * from one that hasn't wrapped; we need only
12466 				 * finish the job by clearing the wrapped bit,
12467 				 * explicitly setting the offset to be 0, and
12468 				 * zero'ing out the old data in the buffer.
12469 				 */
12470 				if (offs == 0) {
12471 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12472 					buf->dtb_offset = 0;
12473 					woffs = total;
12474 
12475 					while (woffs < buf->dtb_size)
12476 						tomax[woffs++] = 0;
12477 				}
12478 
12479 				woffs = 0;
12480 				break;
12481 			}
12482 
12483 			woffs += size;
12484 		}
12485 
12486 		/*
12487 		 * We have a wrapped offset.  It may be that the wrapped offset
12488 		 * has become zero -- that's okay.
12489 		 */
12490 		buf->dtb_xamot_offset = woffs;
12491 	}
12492 
12493 out:
12494 	/*
12495 	 * Now we can plow the buffer with any necessary padding.
12496 	 */
12497 	while (offs & (align - 1)) {
12498 		/*
12499 		 * Assert that our alignment is off by a number which
12500 		 * is itself sizeof (uint32_t) aligned.
12501 		 */
12502 		ASSERT(!((align - (offs & (align - 1))) &
12503 		    (sizeof (uint32_t) - 1)));
12504 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12505 		offs += sizeof (uint32_t);
12506 	}
12507 
12508 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12509 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12510 			buf->dtb_flags |= DTRACEBUF_FULL;
12511 			return (-1);
12512 		}
12513 	}
12514 
12515 	if (mstate == NULL)
12516 		return (offs);
12517 
12518 	/*
12519 	 * For ring buffers and fill buffers, the scratch space is always
12520 	 * the inactive buffer.
12521 	 */
12522 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12523 	mstate->dtms_scratch_size = buf->dtb_size;
12524 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12525 
12526 	return (offs);
12527 }
12528 
12529 static void
12530 dtrace_buffer_polish(dtrace_buffer_t *buf)
12531 {
12532 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12533 	ASSERT(MUTEX_HELD(&dtrace_lock));
12534 
12535 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12536 		return;
12537 
12538 	/*
12539 	 * We need to polish the ring buffer.  There are three cases:
12540 	 *
12541 	 * - The first (and presumably most common) is that there is no gap
12542 	 *   between the buffer offset and the wrapped offset.  In this case,
12543 	 *   there is nothing in the buffer that isn't valid data; we can
12544 	 *   mark the buffer as polished and return.
12545 	 *
12546 	 * - The second (less common than the first but still more common
12547 	 *   than the third) is that there is a gap between the buffer offset
12548 	 *   and the wrapped offset, and the wrapped offset is larger than the
12549 	 *   buffer offset.  This can happen because of an alignment issue, or
12550 	 *   can happen because of a call to dtrace_buffer_reserve() that
12551 	 *   didn't subsequently consume the buffer space.  In this case,
12552 	 *   we need to zero the data from the buffer offset to the wrapped
12553 	 *   offset.
12554 	 *
12555 	 * - The third (and least common) is that there is a gap between the
12556 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12557 	 *   _less_ than the buffer offset.  This can only happen because a
12558 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12559 	 *   was not subsequently consumed.  In this case, we need to zero the
12560 	 *   space from the offset to the end of the buffer _and_ from the
12561 	 *   top of the buffer to the wrapped offset.
12562 	 */
12563 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12564 		bzero(buf->dtb_tomax + buf->dtb_offset,
12565 		    buf->dtb_xamot_offset - buf->dtb_offset);
12566 	}
12567 
12568 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12569 		bzero(buf->dtb_tomax + buf->dtb_offset,
12570 		    buf->dtb_size - buf->dtb_offset);
12571 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12572 	}
12573 }
12574 
12575 /*
12576  * This routine determines if data generated at the specified time has likely
12577  * been entirely consumed at user-level.  This routine is called to determine
12578  * if an ECB on a defunct probe (but for an active enabling) can be safely
12579  * disabled and destroyed.
12580  */
12581 static int
12582 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12583 {
12584 	int i;
12585 
12586 	for (i = 0; i < NCPU; i++) {
12587 		dtrace_buffer_t *buf = &bufs[i];
12588 
12589 		if (buf->dtb_size == 0)
12590 			continue;
12591 
12592 		if (buf->dtb_flags & DTRACEBUF_RING)
12593 			return (0);
12594 
12595 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12596 			return (0);
12597 
12598 		if (buf->dtb_switched - buf->dtb_interval < when)
12599 			return (0);
12600 	}
12601 
12602 	return (1);
12603 }
12604 
12605 static void
12606 dtrace_buffer_free(dtrace_buffer_t *bufs)
12607 {
12608 	int i;
12609 
12610 	for (i = 0; i < NCPU; i++) {
12611 		dtrace_buffer_t *buf = &bufs[i];
12612 
12613 		if (buf->dtb_tomax == NULL) {
12614 			ASSERT(buf->dtb_xamot == NULL);
12615 			ASSERT(buf->dtb_size == 0);
12616 			continue;
12617 		}
12618 
12619 		if (buf->dtb_xamot != NULL) {
12620 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12621 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12622 		}
12623 
12624 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12625 		buf->dtb_size = 0;
12626 		buf->dtb_tomax = NULL;
12627 		buf->dtb_xamot = NULL;
12628 	}
12629 }
12630 
12631 /*
12632  * DTrace Enabling Functions
12633  */
12634 static dtrace_enabling_t *
12635 dtrace_enabling_create(dtrace_vstate_t *vstate)
12636 {
12637 	dtrace_enabling_t *enab;
12638 
12639 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12640 	enab->dten_vstate = vstate;
12641 
12642 	return (enab);
12643 }
12644 
12645 static void
12646 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12647 {
12648 	dtrace_ecbdesc_t **ndesc;
12649 	size_t osize, nsize;
12650 
12651 	/*
12652 	 * We can't add to enablings after we've enabled them, or after we've
12653 	 * retained them.
12654 	 */
12655 	ASSERT(enab->dten_probegen == 0);
12656 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12657 
12658 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12659 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12660 		return;
12661 	}
12662 
12663 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12664 
12665 	if (enab->dten_maxdesc == 0) {
12666 		enab->dten_maxdesc = 1;
12667 	} else {
12668 		enab->dten_maxdesc <<= 1;
12669 	}
12670 
12671 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12672 
12673 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12674 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12675 	bcopy(enab->dten_desc, ndesc, osize);
12676 	if (enab->dten_desc != NULL)
12677 		kmem_free(enab->dten_desc, osize);
12678 
12679 	enab->dten_desc = ndesc;
12680 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12681 }
12682 
12683 static void
12684 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12685     dtrace_probedesc_t *pd)
12686 {
12687 	dtrace_ecbdesc_t *new;
12688 	dtrace_predicate_t *pred;
12689 	dtrace_actdesc_t *act;
12690 
12691 	/*
12692 	 * We're going to create a new ECB description that matches the
12693 	 * specified ECB in every way, but has the specified probe description.
12694 	 */
12695 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12696 
12697 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12698 		dtrace_predicate_hold(pred);
12699 
12700 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12701 		dtrace_actdesc_hold(act);
12702 
12703 	new->dted_action = ecb->dted_action;
12704 	new->dted_pred = ecb->dted_pred;
12705 	new->dted_probe = *pd;
12706 	new->dted_uarg = ecb->dted_uarg;
12707 
12708 	dtrace_enabling_add(enab, new);
12709 }
12710 
12711 static void
12712 dtrace_enabling_dump(dtrace_enabling_t *enab)
12713 {
12714 	int i;
12715 
12716 	for (i = 0; i < enab->dten_ndesc; i++) {
12717 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12718 
12719 #ifdef __FreeBSD__
12720 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12721 		    desc->dtpd_provider, desc->dtpd_mod,
12722 		    desc->dtpd_func, desc->dtpd_name);
12723 #else
12724 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12725 		    desc->dtpd_provider, desc->dtpd_mod,
12726 		    desc->dtpd_func, desc->dtpd_name);
12727 #endif
12728 	}
12729 }
12730 
12731 static void
12732 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12733 {
12734 	int i;
12735 	dtrace_ecbdesc_t *ep;
12736 	dtrace_vstate_t *vstate = enab->dten_vstate;
12737 
12738 	ASSERT(MUTEX_HELD(&dtrace_lock));
12739 
12740 	for (i = 0; i < enab->dten_ndesc; i++) {
12741 		dtrace_actdesc_t *act, *next;
12742 		dtrace_predicate_t *pred;
12743 
12744 		ep = enab->dten_desc[i];
12745 
12746 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12747 			dtrace_predicate_release(pred, vstate);
12748 
12749 		for (act = ep->dted_action; act != NULL; act = next) {
12750 			next = act->dtad_next;
12751 			dtrace_actdesc_release(act, vstate);
12752 		}
12753 
12754 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12755 	}
12756 
12757 	if (enab->dten_desc != NULL)
12758 		kmem_free(enab->dten_desc,
12759 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12760 
12761 	/*
12762 	 * If this was a retained enabling, decrement the dts_nretained count
12763 	 * and take it off of the dtrace_retained list.
12764 	 */
12765 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12766 	    dtrace_retained == enab) {
12767 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12768 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12769 		enab->dten_vstate->dtvs_state->dts_nretained--;
12770 		dtrace_retained_gen++;
12771 	}
12772 
12773 	if (enab->dten_prev == NULL) {
12774 		if (dtrace_retained == enab) {
12775 			dtrace_retained = enab->dten_next;
12776 
12777 			if (dtrace_retained != NULL)
12778 				dtrace_retained->dten_prev = NULL;
12779 		}
12780 	} else {
12781 		ASSERT(enab != dtrace_retained);
12782 		ASSERT(dtrace_retained != NULL);
12783 		enab->dten_prev->dten_next = enab->dten_next;
12784 	}
12785 
12786 	if (enab->dten_next != NULL) {
12787 		ASSERT(dtrace_retained != NULL);
12788 		enab->dten_next->dten_prev = enab->dten_prev;
12789 	}
12790 
12791 	kmem_free(enab, sizeof (dtrace_enabling_t));
12792 }
12793 
12794 static int
12795 dtrace_enabling_retain(dtrace_enabling_t *enab)
12796 {
12797 	dtrace_state_t *state;
12798 
12799 	ASSERT(MUTEX_HELD(&dtrace_lock));
12800 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12801 	ASSERT(enab->dten_vstate != NULL);
12802 
12803 	state = enab->dten_vstate->dtvs_state;
12804 	ASSERT(state != NULL);
12805 
12806 	/*
12807 	 * We only allow each state to retain dtrace_retain_max enablings.
12808 	 */
12809 	if (state->dts_nretained >= dtrace_retain_max)
12810 		return (ENOSPC);
12811 
12812 	state->dts_nretained++;
12813 	dtrace_retained_gen++;
12814 
12815 	if (dtrace_retained == NULL) {
12816 		dtrace_retained = enab;
12817 		return (0);
12818 	}
12819 
12820 	enab->dten_next = dtrace_retained;
12821 	dtrace_retained->dten_prev = enab;
12822 	dtrace_retained = enab;
12823 
12824 	return (0);
12825 }
12826 
12827 static int
12828 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12829     dtrace_probedesc_t *create)
12830 {
12831 	dtrace_enabling_t *new, *enab;
12832 	int found = 0, err = ENOENT;
12833 
12834 	ASSERT(MUTEX_HELD(&dtrace_lock));
12835 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12836 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12837 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12838 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12839 
12840 	new = dtrace_enabling_create(&state->dts_vstate);
12841 
12842 	/*
12843 	 * Iterate over all retained enablings, looking for enablings that
12844 	 * match the specified state.
12845 	 */
12846 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12847 		int i;
12848 
12849 		/*
12850 		 * dtvs_state can only be NULL for helper enablings -- and
12851 		 * helper enablings can't be retained.
12852 		 */
12853 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12854 
12855 		if (enab->dten_vstate->dtvs_state != state)
12856 			continue;
12857 
12858 		/*
12859 		 * Now iterate over each probe description; we're looking for
12860 		 * an exact match to the specified probe description.
12861 		 */
12862 		for (i = 0; i < enab->dten_ndesc; i++) {
12863 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12864 			dtrace_probedesc_t *pd = &ep->dted_probe;
12865 
12866 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12867 				continue;
12868 
12869 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12870 				continue;
12871 
12872 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12873 				continue;
12874 
12875 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12876 				continue;
12877 
12878 			/*
12879 			 * We have a winning probe!  Add it to our growing
12880 			 * enabling.
12881 			 */
12882 			found = 1;
12883 			dtrace_enabling_addlike(new, ep, create);
12884 		}
12885 	}
12886 
12887 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12888 		dtrace_enabling_destroy(new);
12889 		return (err);
12890 	}
12891 
12892 	return (0);
12893 }
12894 
12895 static void
12896 dtrace_enabling_retract(dtrace_state_t *state)
12897 {
12898 	dtrace_enabling_t *enab, *next;
12899 
12900 	ASSERT(MUTEX_HELD(&dtrace_lock));
12901 
12902 	/*
12903 	 * Iterate over all retained enablings, destroy the enablings retained
12904 	 * for the specified state.
12905 	 */
12906 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12907 		next = enab->dten_next;
12908 
12909 		/*
12910 		 * dtvs_state can only be NULL for helper enablings -- and
12911 		 * helper enablings can't be retained.
12912 		 */
12913 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12914 
12915 		if (enab->dten_vstate->dtvs_state == state) {
12916 			ASSERT(state->dts_nretained > 0);
12917 			dtrace_enabling_destroy(enab);
12918 		}
12919 	}
12920 
12921 	ASSERT(state->dts_nretained == 0);
12922 }
12923 
12924 static int
12925 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12926 {
12927 	int i = 0;
12928 	int matched = 0;
12929 
12930 	ASSERT(MUTEX_HELD(&cpu_lock));
12931 	ASSERT(MUTEX_HELD(&dtrace_lock));
12932 
12933 	for (i = 0; i < enab->dten_ndesc; i++) {
12934 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12935 
12936 		enab->dten_current = ep;
12937 		enab->dten_error = 0;
12938 
12939 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12940 
12941 		if (enab->dten_error != 0) {
12942 			/*
12943 			 * If we get an error half-way through enabling the
12944 			 * probes, we kick out -- perhaps with some number of
12945 			 * them enabled.  Leaving enabled probes enabled may
12946 			 * be slightly confusing for user-level, but we expect
12947 			 * that no one will attempt to actually drive on in
12948 			 * the face of such errors.  If this is an anonymous
12949 			 * enabling (indicated with a NULL nmatched pointer),
12950 			 * we cmn_err() a message.  We aren't expecting to
12951 			 * get such an error -- such as it can exist at all,
12952 			 * it would be a result of corrupted DOF in the driver
12953 			 * properties.
12954 			 */
12955 			if (nmatched == NULL) {
12956 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12957 				    "error on %p: %d", (void *)ep,
12958 				    enab->dten_error);
12959 			}
12960 
12961 			return (enab->dten_error);
12962 		}
12963 	}
12964 
12965 	enab->dten_probegen = dtrace_probegen;
12966 	if (nmatched != NULL)
12967 		*nmatched = matched;
12968 
12969 	return (0);
12970 }
12971 
12972 static void
12973 dtrace_enabling_matchall(void)
12974 {
12975 	dtrace_enabling_t *enab;
12976 
12977 	mutex_enter(&cpu_lock);
12978 	mutex_enter(&dtrace_lock);
12979 
12980 	/*
12981 	 * Iterate over all retained enablings to see if any probes match
12982 	 * against them.  We only perform this operation on enablings for which
12983 	 * we have sufficient permissions by virtue of being in the global zone
12984 	 * or in the same zone as the DTrace client.  Because we can be called
12985 	 * after dtrace_detach() has been called, we cannot assert that there
12986 	 * are retained enablings.  We can safely load from dtrace_retained,
12987 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12988 	 * block pending our completion.
12989 	 */
12990 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12991 #ifdef illumos
12992 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12993 
12994 		if (INGLOBALZONE(curproc) ||
12995 		    cr != NULL && getzoneid() == crgetzoneid(cr))
12996 #endif
12997 			(void) dtrace_enabling_match(enab, NULL);
12998 	}
12999 
13000 	mutex_exit(&dtrace_lock);
13001 	mutex_exit(&cpu_lock);
13002 }
13003 
13004 /*
13005  * If an enabling is to be enabled without having matched probes (that is, if
13006  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13007  * enabling must be _primed_ by creating an ECB for every ECB description.
13008  * This must be done to assure that we know the number of speculations, the
13009  * number of aggregations, the minimum buffer size needed, etc. before we
13010  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13011  * enabling any probes, we create ECBs for every ECB decription, but with a
13012  * NULL probe -- which is exactly what this function does.
13013  */
13014 static void
13015 dtrace_enabling_prime(dtrace_state_t *state)
13016 {
13017 	dtrace_enabling_t *enab;
13018 	int i;
13019 
13020 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13021 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13022 
13023 		if (enab->dten_vstate->dtvs_state != state)
13024 			continue;
13025 
13026 		/*
13027 		 * We don't want to prime an enabling more than once, lest
13028 		 * we allow a malicious user to induce resource exhaustion.
13029 		 * (The ECBs that result from priming an enabling aren't
13030 		 * leaked -- but they also aren't deallocated until the
13031 		 * consumer state is destroyed.)
13032 		 */
13033 		if (enab->dten_primed)
13034 			continue;
13035 
13036 		for (i = 0; i < enab->dten_ndesc; i++) {
13037 			enab->dten_current = enab->dten_desc[i];
13038 			(void) dtrace_probe_enable(NULL, enab);
13039 		}
13040 
13041 		enab->dten_primed = 1;
13042 	}
13043 }
13044 
13045 /*
13046  * Called to indicate that probes should be provided due to retained
13047  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13048  * must take an initial lap through the enabling calling the dtps_provide()
13049  * entry point explicitly to allow for autocreated probes.
13050  */
13051 static void
13052 dtrace_enabling_provide(dtrace_provider_t *prv)
13053 {
13054 	int i, all = 0;
13055 	dtrace_probedesc_t desc;
13056 	dtrace_genid_t gen;
13057 
13058 	ASSERT(MUTEX_HELD(&dtrace_lock));
13059 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13060 
13061 	if (prv == NULL) {
13062 		all = 1;
13063 		prv = dtrace_provider;
13064 	}
13065 
13066 	do {
13067 		dtrace_enabling_t *enab;
13068 		void *parg = prv->dtpv_arg;
13069 
13070 retry:
13071 		gen = dtrace_retained_gen;
13072 		for (enab = dtrace_retained; enab != NULL;
13073 		    enab = enab->dten_next) {
13074 			for (i = 0; i < enab->dten_ndesc; i++) {
13075 				desc = enab->dten_desc[i]->dted_probe;
13076 				mutex_exit(&dtrace_lock);
13077 				prv->dtpv_pops.dtps_provide(parg, &desc);
13078 				mutex_enter(&dtrace_lock);
13079 				/*
13080 				 * Process the retained enablings again if
13081 				 * they have changed while we weren't holding
13082 				 * dtrace_lock.
13083 				 */
13084 				if (gen != dtrace_retained_gen)
13085 					goto retry;
13086 			}
13087 		}
13088 	} while (all && (prv = prv->dtpv_next) != NULL);
13089 
13090 	mutex_exit(&dtrace_lock);
13091 	dtrace_probe_provide(NULL, all ? NULL : prv);
13092 	mutex_enter(&dtrace_lock);
13093 }
13094 
13095 /*
13096  * Called to reap ECBs that are attached to probes from defunct providers.
13097  */
13098 static void
13099 dtrace_enabling_reap(void)
13100 {
13101 	dtrace_provider_t *prov;
13102 	dtrace_probe_t *probe;
13103 	dtrace_ecb_t *ecb;
13104 	hrtime_t when;
13105 	int i;
13106 
13107 	mutex_enter(&cpu_lock);
13108 	mutex_enter(&dtrace_lock);
13109 
13110 	for (i = 0; i < dtrace_nprobes; i++) {
13111 		if ((probe = dtrace_probes[i]) == NULL)
13112 			continue;
13113 
13114 		if (probe->dtpr_ecb == NULL)
13115 			continue;
13116 
13117 		prov = probe->dtpr_provider;
13118 
13119 		if ((when = prov->dtpv_defunct) == 0)
13120 			continue;
13121 
13122 		/*
13123 		 * We have ECBs on a defunct provider:  we want to reap these
13124 		 * ECBs to allow the provider to unregister.  The destruction
13125 		 * of these ECBs must be done carefully:  if we destroy the ECB
13126 		 * and the consumer later wishes to consume an EPID that
13127 		 * corresponds to the destroyed ECB (and if the EPID metadata
13128 		 * has not been previously consumed), the consumer will abort
13129 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13130 		 * eliminate) the possibility of this, we will only destroy an
13131 		 * ECB for a defunct provider if, for the state that
13132 		 * corresponds to the ECB:
13133 		 *
13134 		 *  (a)	There is no speculative tracing (which can effectively
13135 		 *	cache an EPID for an arbitrary amount of time).
13136 		 *
13137 		 *  (b)	The principal buffers have been switched twice since the
13138 		 *	provider became defunct.
13139 		 *
13140 		 *  (c)	The aggregation buffers are of zero size or have been
13141 		 *	switched twice since the provider became defunct.
13142 		 *
13143 		 * We use dts_speculates to determine (a) and call a function
13144 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13145 		 * that as soon as we've been unable to destroy one of the ECBs
13146 		 * associated with the probe, we quit trying -- reaping is only
13147 		 * fruitful in as much as we can destroy all ECBs associated
13148 		 * with the defunct provider's probes.
13149 		 */
13150 		while ((ecb = probe->dtpr_ecb) != NULL) {
13151 			dtrace_state_t *state = ecb->dte_state;
13152 			dtrace_buffer_t *buf = state->dts_buffer;
13153 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13154 
13155 			if (state->dts_speculates)
13156 				break;
13157 
13158 			if (!dtrace_buffer_consumed(buf, when))
13159 				break;
13160 
13161 			if (!dtrace_buffer_consumed(aggbuf, when))
13162 				break;
13163 
13164 			dtrace_ecb_disable(ecb);
13165 			ASSERT(probe->dtpr_ecb != ecb);
13166 			dtrace_ecb_destroy(ecb);
13167 		}
13168 	}
13169 
13170 	mutex_exit(&dtrace_lock);
13171 	mutex_exit(&cpu_lock);
13172 }
13173 
13174 /*
13175  * DTrace DOF Functions
13176  */
13177 /*ARGSUSED*/
13178 static void
13179 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13180 {
13181 	if (dtrace_err_verbose)
13182 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13183 
13184 #ifdef DTRACE_ERRDEBUG
13185 	dtrace_errdebug(str);
13186 #endif
13187 }
13188 
13189 /*
13190  * Create DOF out of a currently enabled state.  Right now, we only create
13191  * DOF containing the run-time options -- but this could be expanded to create
13192  * complete DOF representing the enabled state.
13193  */
13194 static dof_hdr_t *
13195 dtrace_dof_create(dtrace_state_t *state)
13196 {
13197 	dof_hdr_t *dof;
13198 	dof_sec_t *sec;
13199 	dof_optdesc_t *opt;
13200 	int i, len = sizeof (dof_hdr_t) +
13201 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13202 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13203 
13204 	ASSERT(MUTEX_HELD(&dtrace_lock));
13205 
13206 	dof = kmem_zalloc(len, KM_SLEEP);
13207 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13208 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13209 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13210 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13211 
13212 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13213 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13214 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13215 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13216 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13217 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13218 
13219 	dof->dofh_flags = 0;
13220 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13221 	dof->dofh_secsize = sizeof (dof_sec_t);
13222 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13223 	dof->dofh_secoff = sizeof (dof_hdr_t);
13224 	dof->dofh_loadsz = len;
13225 	dof->dofh_filesz = len;
13226 	dof->dofh_pad = 0;
13227 
13228 	/*
13229 	 * Fill in the option section header...
13230 	 */
13231 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13232 	sec->dofs_type = DOF_SECT_OPTDESC;
13233 	sec->dofs_align = sizeof (uint64_t);
13234 	sec->dofs_flags = DOF_SECF_LOAD;
13235 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13236 
13237 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13238 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13239 
13240 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13241 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13242 
13243 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13244 		opt[i].dofo_option = i;
13245 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13246 		opt[i].dofo_value = state->dts_options[i];
13247 	}
13248 
13249 	return (dof);
13250 }
13251 
13252 static dof_hdr_t *
13253 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13254 {
13255 	dof_hdr_t hdr, *dof;
13256 
13257 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13258 
13259 	/*
13260 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13261 	 */
13262 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13263 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13264 		*errp = EFAULT;
13265 		return (NULL);
13266 	}
13267 
13268 	/*
13269 	 * Now we'll allocate the entire DOF and copy it in -- provided
13270 	 * that the length isn't outrageous.
13271 	 */
13272 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13273 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13274 		*errp = E2BIG;
13275 		return (NULL);
13276 	}
13277 
13278 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13279 		dtrace_dof_error(&hdr, "invalid load size");
13280 		*errp = EINVAL;
13281 		return (NULL);
13282 	}
13283 
13284 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13285 
13286 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13287 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13288 		kmem_free(dof, hdr.dofh_loadsz);
13289 		*errp = EFAULT;
13290 		return (NULL);
13291 	}
13292 
13293 	return (dof);
13294 }
13295 
13296 #ifdef __FreeBSD__
13297 static dof_hdr_t *
13298 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13299 {
13300 	dof_hdr_t hdr, *dof;
13301 	struct thread *td;
13302 	size_t loadsz;
13303 
13304 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13305 
13306 	td = curthread;
13307 
13308 	/*
13309 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13310 	 */
13311 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13312 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13313 		*errp = EFAULT;
13314 		return (NULL);
13315 	}
13316 
13317 	/*
13318 	 * Now we'll allocate the entire DOF and copy it in -- provided
13319 	 * that the length isn't outrageous.
13320 	 */
13321 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13322 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13323 		*errp = E2BIG;
13324 		return (NULL);
13325 	}
13326 	loadsz = (size_t)hdr.dofh_loadsz;
13327 
13328 	if (loadsz < sizeof (hdr)) {
13329 		dtrace_dof_error(&hdr, "invalid load size");
13330 		*errp = EINVAL;
13331 		return (NULL);
13332 	}
13333 
13334 	dof = kmem_alloc(loadsz, KM_SLEEP);
13335 
13336 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13337 	    dof->dofh_loadsz != loadsz) {
13338 		kmem_free(dof, hdr.dofh_loadsz);
13339 		*errp = EFAULT;
13340 		return (NULL);
13341 	}
13342 
13343 	return (dof);
13344 }
13345 
13346 static __inline uchar_t
13347 dtrace_dof_char(char c)
13348 {
13349 
13350 	switch (c) {
13351 	case '0':
13352 	case '1':
13353 	case '2':
13354 	case '3':
13355 	case '4':
13356 	case '5':
13357 	case '6':
13358 	case '7':
13359 	case '8':
13360 	case '9':
13361 		return (c - '0');
13362 	case 'A':
13363 	case 'B':
13364 	case 'C':
13365 	case 'D':
13366 	case 'E':
13367 	case 'F':
13368 		return (c - 'A' + 10);
13369 	case 'a':
13370 	case 'b':
13371 	case 'c':
13372 	case 'd':
13373 	case 'e':
13374 	case 'f':
13375 		return (c - 'a' + 10);
13376 	}
13377 	/* Should not reach here. */
13378 	return (UCHAR_MAX);
13379 }
13380 #endif /* __FreeBSD__ */
13381 
13382 static dof_hdr_t *
13383 dtrace_dof_property(const char *name)
13384 {
13385 #ifdef __FreeBSD__
13386 	uint8_t *dofbuf;
13387 	u_char *data, *eol;
13388 	caddr_t doffile;
13389 	size_t bytes, len, i;
13390 	dof_hdr_t *dof;
13391 	u_char c1, c2;
13392 
13393 	dof = NULL;
13394 
13395 	doffile = preload_search_by_type("dtrace_dof");
13396 	if (doffile == NULL)
13397 		return (NULL);
13398 
13399 	data = preload_fetch_addr(doffile);
13400 	len = preload_fetch_size(doffile);
13401 	for (;;) {
13402 		/* Look for the end of the line. All lines end in a newline. */
13403 		eol = memchr(data, '\n', len);
13404 		if (eol == NULL)
13405 			return (NULL);
13406 
13407 		if (strncmp(name, data, strlen(name)) == 0)
13408 			break;
13409 
13410 		eol++; /* skip past the newline */
13411 		len -= eol - data;
13412 		data = eol;
13413 	}
13414 
13415 	/* We've found the data corresponding to the specified key. */
13416 
13417 	data += strlen(name) + 1; /* skip past the '=' */
13418 	len = eol - data;
13419 	if (len % 2 != 0) {
13420 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13421 		goto doferr;
13422 	}
13423 	bytes = len / 2;
13424 	if (bytes < sizeof(dof_hdr_t)) {
13425 		dtrace_dof_error(NULL, "truncated header");
13426 		goto doferr;
13427 	}
13428 
13429 	/*
13430 	 * Each byte is represented by the two ASCII characters in its hex
13431 	 * representation.
13432 	 */
13433 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13434 	for (i = 0; i < bytes; i++) {
13435 		c1 = dtrace_dof_char(data[i * 2]);
13436 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13437 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13438 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13439 			goto doferr;
13440 		}
13441 		dofbuf[i] = c1 * 16 + c2;
13442 	}
13443 
13444 	dof = (dof_hdr_t *)dofbuf;
13445 	if (bytes < dof->dofh_loadsz) {
13446 		dtrace_dof_error(NULL, "truncated DOF");
13447 		goto doferr;
13448 	}
13449 
13450 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13451 		dtrace_dof_error(NULL, "oversized DOF");
13452 		goto doferr;
13453 	}
13454 
13455 	return (dof);
13456 
13457 doferr:
13458 	free(dof, M_SOLARIS);
13459 	return (NULL);
13460 #else /* __FreeBSD__ */
13461 	uchar_t *buf;
13462 	uint64_t loadsz;
13463 	unsigned int len, i;
13464 	dof_hdr_t *dof;
13465 
13466 	/*
13467 	 * Unfortunately, array of values in .conf files are always (and
13468 	 * only) interpreted to be integer arrays.  We must read our DOF
13469 	 * as an integer array, and then squeeze it into a byte array.
13470 	 */
13471 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13472 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13473 		return (NULL);
13474 
13475 	for (i = 0; i < len; i++)
13476 		buf[i] = (uchar_t)(((int *)buf)[i]);
13477 
13478 	if (len < sizeof (dof_hdr_t)) {
13479 		ddi_prop_free(buf);
13480 		dtrace_dof_error(NULL, "truncated header");
13481 		return (NULL);
13482 	}
13483 
13484 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13485 		ddi_prop_free(buf);
13486 		dtrace_dof_error(NULL, "truncated DOF");
13487 		return (NULL);
13488 	}
13489 
13490 	if (loadsz >= dtrace_dof_maxsize) {
13491 		ddi_prop_free(buf);
13492 		dtrace_dof_error(NULL, "oversized DOF");
13493 		return (NULL);
13494 	}
13495 
13496 	dof = kmem_alloc(loadsz, KM_SLEEP);
13497 	bcopy(buf, dof, loadsz);
13498 	ddi_prop_free(buf);
13499 
13500 	return (dof);
13501 #endif /* !__FreeBSD__ */
13502 }
13503 
13504 static void
13505 dtrace_dof_destroy(dof_hdr_t *dof)
13506 {
13507 	kmem_free(dof, dof->dofh_loadsz);
13508 }
13509 
13510 /*
13511  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13512  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13513  * a type other than DOF_SECT_NONE is specified, the header is checked against
13514  * this type and NULL is returned if the types do not match.
13515  */
13516 static dof_sec_t *
13517 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13518 {
13519 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13520 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13521 
13522 	if (i >= dof->dofh_secnum) {
13523 		dtrace_dof_error(dof, "referenced section index is invalid");
13524 		return (NULL);
13525 	}
13526 
13527 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13528 		dtrace_dof_error(dof, "referenced section is not loadable");
13529 		return (NULL);
13530 	}
13531 
13532 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13533 		dtrace_dof_error(dof, "referenced section is the wrong type");
13534 		return (NULL);
13535 	}
13536 
13537 	return (sec);
13538 }
13539 
13540 static dtrace_probedesc_t *
13541 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13542 {
13543 	dof_probedesc_t *probe;
13544 	dof_sec_t *strtab;
13545 	uintptr_t daddr = (uintptr_t)dof;
13546 	uintptr_t str;
13547 	size_t size;
13548 
13549 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13550 		dtrace_dof_error(dof, "invalid probe section");
13551 		return (NULL);
13552 	}
13553 
13554 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13555 		dtrace_dof_error(dof, "bad alignment in probe description");
13556 		return (NULL);
13557 	}
13558 
13559 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13560 		dtrace_dof_error(dof, "truncated probe description");
13561 		return (NULL);
13562 	}
13563 
13564 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13565 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13566 
13567 	if (strtab == NULL)
13568 		return (NULL);
13569 
13570 	str = daddr + strtab->dofs_offset;
13571 	size = strtab->dofs_size;
13572 
13573 	if (probe->dofp_provider >= strtab->dofs_size) {
13574 		dtrace_dof_error(dof, "corrupt probe provider");
13575 		return (NULL);
13576 	}
13577 
13578 	(void) strncpy(desc->dtpd_provider,
13579 	    (char *)(str + probe->dofp_provider),
13580 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13581 
13582 	if (probe->dofp_mod >= strtab->dofs_size) {
13583 		dtrace_dof_error(dof, "corrupt probe module");
13584 		return (NULL);
13585 	}
13586 
13587 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13588 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13589 
13590 	if (probe->dofp_func >= strtab->dofs_size) {
13591 		dtrace_dof_error(dof, "corrupt probe function");
13592 		return (NULL);
13593 	}
13594 
13595 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13596 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13597 
13598 	if (probe->dofp_name >= strtab->dofs_size) {
13599 		dtrace_dof_error(dof, "corrupt probe name");
13600 		return (NULL);
13601 	}
13602 
13603 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13604 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13605 
13606 	return (desc);
13607 }
13608 
13609 static dtrace_difo_t *
13610 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13611     cred_t *cr)
13612 {
13613 	dtrace_difo_t *dp;
13614 	size_t ttl = 0;
13615 	dof_difohdr_t *dofd;
13616 	uintptr_t daddr = (uintptr_t)dof;
13617 	size_t max = dtrace_difo_maxsize;
13618 	int i, l, n;
13619 
13620 	static const struct {
13621 		int section;
13622 		int bufoffs;
13623 		int lenoffs;
13624 		int entsize;
13625 		int align;
13626 		const char *msg;
13627 	} difo[] = {
13628 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13629 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13630 		sizeof (dif_instr_t), "multiple DIF sections" },
13631 
13632 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13633 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13634 		sizeof (uint64_t), "multiple integer tables" },
13635 
13636 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13637 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13638 		sizeof (char), "multiple string tables" },
13639 
13640 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13641 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13642 		sizeof (uint_t), "multiple variable tables" },
13643 
13644 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13645 	};
13646 
13647 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13648 		dtrace_dof_error(dof, "invalid DIFO header section");
13649 		return (NULL);
13650 	}
13651 
13652 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13653 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13654 		return (NULL);
13655 	}
13656 
13657 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13658 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13659 		dtrace_dof_error(dof, "bad size in DIFO header");
13660 		return (NULL);
13661 	}
13662 
13663 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13664 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13665 
13666 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13667 	dp->dtdo_rtype = dofd->dofd_rtype;
13668 
13669 	for (l = 0; l < n; l++) {
13670 		dof_sec_t *subsec;
13671 		void **bufp;
13672 		uint32_t *lenp;
13673 
13674 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13675 		    dofd->dofd_links[l])) == NULL)
13676 			goto err; /* invalid section link */
13677 
13678 		if (ttl + subsec->dofs_size > max) {
13679 			dtrace_dof_error(dof, "exceeds maximum size");
13680 			goto err;
13681 		}
13682 
13683 		ttl += subsec->dofs_size;
13684 
13685 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13686 			if (subsec->dofs_type != difo[i].section)
13687 				continue;
13688 
13689 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13690 				dtrace_dof_error(dof, "section not loaded");
13691 				goto err;
13692 			}
13693 
13694 			if (subsec->dofs_align != difo[i].align) {
13695 				dtrace_dof_error(dof, "bad alignment");
13696 				goto err;
13697 			}
13698 
13699 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13700 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13701 
13702 			if (*bufp != NULL) {
13703 				dtrace_dof_error(dof, difo[i].msg);
13704 				goto err;
13705 			}
13706 
13707 			if (difo[i].entsize != subsec->dofs_entsize) {
13708 				dtrace_dof_error(dof, "entry size mismatch");
13709 				goto err;
13710 			}
13711 
13712 			if (subsec->dofs_entsize != 0 &&
13713 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13714 				dtrace_dof_error(dof, "corrupt entry size");
13715 				goto err;
13716 			}
13717 
13718 			*lenp = subsec->dofs_size;
13719 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13720 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13721 			    *bufp, subsec->dofs_size);
13722 
13723 			if (subsec->dofs_entsize != 0)
13724 				*lenp /= subsec->dofs_entsize;
13725 
13726 			break;
13727 		}
13728 
13729 		/*
13730 		 * If we encounter a loadable DIFO sub-section that is not
13731 		 * known to us, assume this is a broken program and fail.
13732 		 */
13733 		if (difo[i].section == DOF_SECT_NONE &&
13734 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13735 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13736 			goto err;
13737 		}
13738 	}
13739 
13740 	if (dp->dtdo_buf == NULL) {
13741 		/*
13742 		 * We can't have a DIF object without DIF text.
13743 		 */
13744 		dtrace_dof_error(dof, "missing DIF text");
13745 		goto err;
13746 	}
13747 
13748 	/*
13749 	 * Before we validate the DIF object, run through the variable table
13750 	 * looking for the strings -- if any of their size are under, we'll set
13751 	 * their size to be the system-wide default string size.  Note that
13752 	 * this should _not_ happen if the "strsize" option has been set --
13753 	 * in this case, the compiler should have set the size to reflect the
13754 	 * setting of the option.
13755 	 */
13756 	for (i = 0; i < dp->dtdo_varlen; i++) {
13757 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13758 		dtrace_diftype_t *t = &v->dtdv_type;
13759 
13760 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13761 			continue;
13762 
13763 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13764 			t->dtdt_size = dtrace_strsize_default;
13765 	}
13766 
13767 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13768 		goto err;
13769 
13770 	dtrace_difo_init(dp, vstate);
13771 	return (dp);
13772 
13773 err:
13774 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13775 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13776 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13777 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13778 
13779 	kmem_free(dp, sizeof (dtrace_difo_t));
13780 	return (NULL);
13781 }
13782 
13783 static dtrace_predicate_t *
13784 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13785     cred_t *cr)
13786 {
13787 	dtrace_difo_t *dp;
13788 
13789 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13790 		return (NULL);
13791 
13792 	return (dtrace_predicate_create(dp));
13793 }
13794 
13795 static dtrace_actdesc_t *
13796 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13797     cred_t *cr)
13798 {
13799 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13800 	dof_actdesc_t *desc;
13801 	dof_sec_t *difosec;
13802 	size_t offs;
13803 	uintptr_t daddr = (uintptr_t)dof;
13804 	uint64_t arg;
13805 	dtrace_actkind_t kind;
13806 
13807 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13808 		dtrace_dof_error(dof, "invalid action section");
13809 		return (NULL);
13810 	}
13811 
13812 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13813 		dtrace_dof_error(dof, "truncated action description");
13814 		return (NULL);
13815 	}
13816 
13817 	if (sec->dofs_align != sizeof (uint64_t)) {
13818 		dtrace_dof_error(dof, "bad alignment in action description");
13819 		return (NULL);
13820 	}
13821 
13822 	if (sec->dofs_size < sec->dofs_entsize) {
13823 		dtrace_dof_error(dof, "section entry size exceeds total size");
13824 		return (NULL);
13825 	}
13826 
13827 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13828 		dtrace_dof_error(dof, "bad entry size in action description");
13829 		return (NULL);
13830 	}
13831 
13832 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13833 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13834 		return (NULL);
13835 	}
13836 
13837 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13838 		desc = (dof_actdesc_t *)(daddr +
13839 		    (uintptr_t)sec->dofs_offset + offs);
13840 		kind = (dtrace_actkind_t)desc->dofa_kind;
13841 
13842 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13843 		    (kind != DTRACEACT_PRINTA ||
13844 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13845 		    (kind == DTRACEACT_DIFEXPR &&
13846 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13847 			dof_sec_t *strtab;
13848 			char *str, *fmt;
13849 			uint64_t i;
13850 
13851 			/*
13852 			 * The argument to these actions is an index into the
13853 			 * DOF string table.  For printf()-like actions, this
13854 			 * is the format string.  For print(), this is the
13855 			 * CTF type of the expression result.
13856 			 */
13857 			if ((strtab = dtrace_dof_sect(dof,
13858 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13859 				goto err;
13860 
13861 			str = (char *)((uintptr_t)dof +
13862 			    (uintptr_t)strtab->dofs_offset);
13863 
13864 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13865 				if (str[i] == '\0')
13866 					break;
13867 			}
13868 
13869 			if (i >= strtab->dofs_size) {
13870 				dtrace_dof_error(dof, "bogus format string");
13871 				goto err;
13872 			}
13873 
13874 			if (i == desc->dofa_arg) {
13875 				dtrace_dof_error(dof, "empty format string");
13876 				goto err;
13877 			}
13878 
13879 			i -= desc->dofa_arg;
13880 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13881 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13882 			arg = (uint64_t)(uintptr_t)fmt;
13883 		} else {
13884 			if (kind == DTRACEACT_PRINTA) {
13885 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13886 				arg = 0;
13887 			} else {
13888 				arg = desc->dofa_arg;
13889 			}
13890 		}
13891 
13892 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13893 		    desc->dofa_uarg, arg);
13894 
13895 		if (last != NULL) {
13896 			last->dtad_next = act;
13897 		} else {
13898 			first = act;
13899 		}
13900 
13901 		last = act;
13902 
13903 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13904 			continue;
13905 
13906 		if ((difosec = dtrace_dof_sect(dof,
13907 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13908 			goto err;
13909 
13910 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13911 
13912 		if (act->dtad_difo == NULL)
13913 			goto err;
13914 	}
13915 
13916 	ASSERT(first != NULL);
13917 	return (first);
13918 
13919 err:
13920 	for (act = first; act != NULL; act = next) {
13921 		next = act->dtad_next;
13922 		dtrace_actdesc_release(act, vstate);
13923 	}
13924 
13925 	return (NULL);
13926 }
13927 
13928 static dtrace_ecbdesc_t *
13929 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13930     cred_t *cr)
13931 {
13932 	dtrace_ecbdesc_t *ep;
13933 	dof_ecbdesc_t *ecb;
13934 	dtrace_probedesc_t *desc;
13935 	dtrace_predicate_t *pred = NULL;
13936 
13937 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13938 		dtrace_dof_error(dof, "truncated ECB description");
13939 		return (NULL);
13940 	}
13941 
13942 	if (sec->dofs_align != sizeof (uint64_t)) {
13943 		dtrace_dof_error(dof, "bad alignment in ECB description");
13944 		return (NULL);
13945 	}
13946 
13947 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13948 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13949 
13950 	if (sec == NULL)
13951 		return (NULL);
13952 
13953 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13954 	ep->dted_uarg = ecb->dofe_uarg;
13955 	desc = &ep->dted_probe;
13956 
13957 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13958 		goto err;
13959 
13960 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13961 		if ((sec = dtrace_dof_sect(dof,
13962 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13963 			goto err;
13964 
13965 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13966 			goto err;
13967 
13968 		ep->dted_pred.dtpdd_predicate = pred;
13969 	}
13970 
13971 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13972 		if ((sec = dtrace_dof_sect(dof,
13973 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13974 			goto err;
13975 
13976 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13977 
13978 		if (ep->dted_action == NULL)
13979 			goto err;
13980 	}
13981 
13982 	return (ep);
13983 
13984 err:
13985 	if (pred != NULL)
13986 		dtrace_predicate_release(pred, vstate);
13987 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13988 	return (NULL);
13989 }
13990 
13991 /*
13992  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13993  * specified DOF.  SETX relocations are computed using 'ubase', the base load
13994  * address of the object containing the DOF, and DOFREL relocations are relative
13995  * to the relocation offset within the DOF.
13996  */
13997 static int
13998 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
13999     uint64_t udaddr)
14000 {
14001 	uintptr_t daddr = (uintptr_t)dof;
14002 	uintptr_t ts_end;
14003 	dof_relohdr_t *dofr =
14004 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14005 	dof_sec_t *ss, *rs, *ts;
14006 	dof_relodesc_t *r;
14007 	uint_t i, n;
14008 
14009 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14010 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14011 		dtrace_dof_error(dof, "invalid relocation header");
14012 		return (-1);
14013 	}
14014 
14015 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14016 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14017 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14018 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14019 
14020 	if (ss == NULL || rs == NULL || ts == NULL)
14021 		return (-1); /* dtrace_dof_error() has been called already */
14022 
14023 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14024 	    rs->dofs_align != sizeof (uint64_t)) {
14025 		dtrace_dof_error(dof, "invalid relocation section");
14026 		return (-1);
14027 	}
14028 
14029 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14030 	n = rs->dofs_size / rs->dofs_entsize;
14031 
14032 	for (i = 0; i < n; i++) {
14033 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14034 
14035 		switch (r->dofr_type) {
14036 		case DOF_RELO_NONE:
14037 			break;
14038 		case DOF_RELO_SETX:
14039 		case DOF_RELO_DOFREL:
14040 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14041 			    sizeof (uint64_t) > ts->dofs_size) {
14042 				dtrace_dof_error(dof, "bad relocation offset");
14043 				return (-1);
14044 			}
14045 
14046 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14047 				dtrace_dof_error(dof, "bad relocation offset");
14048 				return (-1);
14049 			}
14050 
14051 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14052 				dtrace_dof_error(dof, "misaligned setx relo");
14053 				return (-1);
14054 			}
14055 
14056 			if (r->dofr_type == DOF_RELO_SETX)
14057 				*(uint64_t *)taddr += ubase;
14058 			else
14059 				*(uint64_t *)taddr +=
14060 				    udaddr + ts->dofs_offset + r->dofr_offset;
14061 			break;
14062 		default:
14063 			dtrace_dof_error(dof, "invalid relocation type");
14064 			return (-1);
14065 		}
14066 
14067 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14068 	}
14069 
14070 	return (0);
14071 }
14072 
14073 /*
14074  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14075  * header:  it should be at the front of a memory region that is at least
14076  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14077  * size.  It need not be validated in any other way.
14078  */
14079 static int
14080 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14081     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14082 {
14083 	uint64_t len = dof->dofh_loadsz, seclen;
14084 	uintptr_t daddr = (uintptr_t)dof;
14085 	dtrace_ecbdesc_t *ep;
14086 	dtrace_enabling_t *enab;
14087 	uint_t i;
14088 
14089 	ASSERT(MUTEX_HELD(&dtrace_lock));
14090 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14091 
14092 	/*
14093 	 * Check the DOF header identification bytes.  In addition to checking
14094 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14095 	 * we can use them later without fear of regressing existing binaries.
14096 	 */
14097 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14098 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14099 		dtrace_dof_error(dof, "DOF magic string mismatch");
14100 		return (-1);
14101 	}
14102 
14103 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14104 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14105 		dtrace_dof_error(dof, "DOF has invalid data model");
14106 		return (-1);
14107 	}
14108 
14109 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14110 		dtrace_dof_error(dof, "DOF encoding mismatch");
14111 		return (-1);
14112 	}
14113 
14114 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14115 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14116 		dtrace_dof_error(dof, "DOF version mismatch");
14117 		return (-1);
14118 	}
14119 
14120 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14121 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14122 		return (-1);
14123 	}
14124 
14125 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14126 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14127 		return (-1);
14128 	}
14129 
14130 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14131 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14132 		return (-1);
14133 	}
14134 
14135 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14136 		if (dof->dofh_ident[i] != 0) {
14137 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14138 			return (-1);
14139 		}
14140 	}
14141 
14142 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14143 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14144 		return (-1);
14145 	}
14146 
14147 	if (dof->dofh_secsize == 0) {
14148 		dtrace_dof_error(dof, "zero section header size");
14149 		return (-1);
14150 	}
14151 
14152 	/*
14153 	 * Check that the section headers don't exceed the amount of DOF
14154 	 * data.  Note that we cast the section size and number of sections
14155 	 * to uint64_t's to prevent possible overflow in the multiplication.
14156 	 */
14157 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14158 
14159 	if (dof->dofh_secoff > len || seclen > len ||
14160 	    dof->dofh_secoff + seclen > len) {
14161 		dtrace_dof_error(dof, "truncated section headers");
14162 		return (-1);
14163 	}
14164 
14165 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14166 		dtrace_dof_error(dof, "misaligned section headers");
14167 		return (-1);
14168 	}
14169 
14170 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14171 		dtrace_dof_error(dof, "misaligned section size");
14172 		return (-1);
14173 	}
14174 
14175 	/*
14176 	 * Take an initial pass through the section headers to be sure that
14177 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14178 	 * set, do not permit sections relating to providers, probes, or args.
14179 	 */
14180 	for (i = 0; i < dof->dofh_secnum; i++) {
14181 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14182 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14183 
14184 		if (noprobes) {
14185 			switch (sec->dofs_type) {
14186 			case DOF_SECT_PROVIDER:
14187 			case DOF_SECT_PROBES:
14188 			case DOF_SECT_PRARGS:
14189 			case DOF_SECT_PROFFS:
14190 				dtrace_dof_error(dof, "illegal sections "
14191 				    "for enabling");
14192 				return (-1);
14193 			}
14194 		}
14195 
14196 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14197 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14198 			dtrace_dof_error(dof, "loadable section with load "
14199 			    "flag unset");
14200 			return (-1);
14201 		}
14202 
14203 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14204 			continue; /* just ignore non-loadable sections */
14205 
14206 		if (!ISP2(sec->dofs_align)) {
14207 			dtrace_dof_error(dof, "bad section alignment");
14208 			return (-1);
14209 		}
14210 
14211 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14212 			dtrace_dof_error(dof, "misaligned section");
14213 			return (-1);
14214 		}
14215 
14216 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14217 		    sec->dofs_offset + sec->dofs_size > len) {
14218 			dtrace_dof_error(dof, "corrupt section header");
14219 			return (-1);
14220 		}
14221 
14222 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14223 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14224 			dtrace_dof_error(dof, "non-terminating string table");
14225 			return (-1);
14226 		}
14227 	}
14228 
14229 	/*
14230 	 * Take a second pass through the sections and locate and perform any
14231 	 * relocations that are present.  We do this after the first pass to
14232 	 * be sure that all sections have had their headers validated.
14233 	 */
14234 	for (i = 0; i < dof->dofh_secnum; i++) {
14235 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14236 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14237 
14238 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14239 			continue; /* skip sections that are not loadable */
14240 
14241 		switch (sec->dofs_type) {
14242 		case DOF_SECT_URELHDR:
14243 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14244 				return (-1);
14245 			break;
14246 		}
14247 	}
14248 
14249 	if ((enab = *enabp) == NULL)
14250 		enab = *enabp = dtrace_enabling_create(vstate);
14251 
14252 	for (i = 0; i < dof->dofh_secnum; i++) {
14253 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14254 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14255 
14256 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14257 			continue;
14258 
14259 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14260 			dtrace_enabling_destroy(enab);
14261 			*enabp = NULL;
14262 			return (-1);
14263 		}
14264 
14265 		dtrace_enabling_add(enab, ep);
14266 	}
14267 
14268 	return (0);
14269 }
14270 
14271 /*
14272  * Process DOF for any options.  This routine assumes that the DOF has been
14273  * at least processed by dtrace_dof_slurp().
14274  */
14275 static int
14276 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14277 {
14278 	int i, rval;
14279 	uint32_t entsize;
14280 	size_t offs;
14281 	dof_optdesc_t *desc;
14282 
14283 	for (i = 0; i < dof->dofh_secnum; i++) {
14284 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14285 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14286 
14287 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14288 			continue;
14289 
14290 		if (sec->dofs_align != sizeof (uint64_t)) {
14291 			dtrace_dof_error(dof, "bad alignment in "
14292 			    "option description");
14293 			return (EINVAL);
14294 		}
14295 
14296 		if ((entsize = sec->dofs_entsize) == 0) {
14297 			dtrace_dof_error(dof, "zeroed option entry size");
14298 			return (EINVAL);
14299 		}
14300 
14301 		if (entsize < sizeof (dof_optdesc_t)) {
14302 			dtrace_dof_error(dof, "bad option entry size");
14303 			return (EINVAL);
14304 		}
14305 
14306 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14307 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14308 			    (uintptr_t)sec->dofs_offset + offs);
14309 
14310 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14311 				dtrace_dof_error(dof, "non-zero option string");
14312 				return (EINVAL);
14313 			}
14314 
14315 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14316 				dtrace_dof_error(dof, "unset option");
14317 				return (EINVAL);
14318 			}
14319 
14320 			if ((rval = dtrace_state_option(state,
14321 			    desc->dofo_option, desc->dofo_value)) != 0) {
14322 				dtrace_dof_error(dof, "rejected option");
14323 				return (rval);
14324 			}
14325 		}
14326 	}
14327 
14328 	return (0);
14329 }
14330 
14331 /*
14332  * DTrace Consumer State Functions
14333  */
14334 static int
14335 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14336 {
14337 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14338 	void *base;
14339 	uintptr_t limit;
14340 	dtrace_dynvar_t *dvar, *next, *start;
14341 	int i;
14342 
14343 	ASSERT(MUTEX_HELD(&dtrace_lock));
14344 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14345 
14346 	bzero(dstate, sizeof (dtrace_dstate_t));
14347 
14348 	if ((dstate->dtds_chunksize = chunksize) == 0)
14349 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14350 
14351 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14352 
14353 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14354 		size = min;
14355 
14356 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14357 		return (ENOMEM);
14358 
14359 	dstate->dtds_size = size;
14360 	dstate->dtds_base = base;
14361 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14362 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14363 
14364 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14365 
14366 	if (hashsize != 1 && (hashsize & 1))
14367 		hashsize--;
14368 
14369 	dstate->dtds_hashsize = hashsize;
14370 	dstate->dtds_hash = dstate->dtds_base;
14371 
14372 	/*
14373 	 * Set all of our hash buckets to point to the single sink, and (if
14374 	 * it hasn't already been set), set the sink's hash value to be the
14375 	 * sink sentinel value.  The sink is needed for dynamic variable
14376 	 * lookups to know that they have iterated over an entire, valid hash
14377 	 * chain.
14378 	 */
14379 	for (i = 0; i < hashsize; i++)
14380 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14381 
14382 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14383 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14384 
14385 	/*
14386 	 * Determine number of active CPUs.  Divide free list evenly among
14387 	 * active CPUs.
14388 	 */
14389 	start = (dtrace_dynvar_t *)
14390 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14391 	limit = (uintptr_t)base + size;
14392 
14393 	VERIFY((uintptr_t)start < limit);
14394 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14395 
14396 	maxper = (limit - (uintptr_t)start) / NCPU;
14397 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14398 
14399 #ifndef illumos
14400 	CPU_FOREACH(i) {
14401 #else
14402 	for (i = 0; i < NCPU; i++) {
14403 #endif
14404 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14405 
14406 		/*
14407 		 * If we don't even have enough chunks to make it once through
14408 		 * NCPUs, we're just going to allocate everything to the first
14409 		 * CPU.  And if we're on the last CPU, we're going to allocate
14410 		 * whatever is left over.  In either case, we set the limit to
14411 		 * be the limit of the dynamic variable space.
14412 		 */
14413 		if (maxper == 0 || i == NCPU - 1) {
14414 			limit = (uintptr_t)base + size;
14415 			start = NULL;
14416 		} else {
14417 			limit = (uintptr_t)start + maxper;
14418 			start = (dtrace_dynvar_t *)limit;
14419 		}
14420 
14421 		VERIFY(limit <= (uintptr_t)base + size);
14422 
14423 		for (;;) {
14424 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14425 			    dstate->dtds_chunksize);
14426 
14427 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14428 				break;
14429 
14430 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14431 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14432 			dvar->dtdv_next = next;
14433 			dvar = next;
14434 		}
14435 
14436 		if (maxper == 0)
14437 			break;
14438 	}
14439 
14440 	return (0);
14441 }
14442 
14443 static void
14444 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14445 {
14446 	ASSERT(MUTEX_HELD(&cpu_lock));
14447 
14448 	if (dstate->dtds_base == NULL)
14449 		return;
14450 
14451 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14452 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14453 }
14454 
14455 static void
14456 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14457 {
14458 	/*
14459 	 * Logical XOR, where are you?
14460 	 */
14461 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14462 
14463 	if (vstate->dtvs_nglobals > 0) {
14464 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14465 		    sizeof (dtrace_statvar_t *));
14466 	}
14467 
14468 	if (vstate->dtvs_ntlocals > 0) {
14469 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14470 		    sizeof (dtrace_difv_t));
14471 	}
14472 
14473 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14474 
14475 	if (vstate->dtvs_nlocals > 0) {
14476 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14477 		    sizeof (dtrace_statvar_t *));
14478 	}
14479 }
14480 
14481 #ifdef illumos
14482 static void
14483 dtrace_state_clean(dtrace_state_t *state)
14484 {
14485 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14486 		return;
14487 
14488 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14489 	dtrace_speculation_clean(state);
14490 }
14491 
14492 static void
14493 dtrace_state_deadman(dtrace_state_t *state)
14494 {
14495 	hrtime_t now;
14496 
14497 	dtrace_sync();
14498 
14499 	now = dtrace_gethrtime();
14500 
14501 	if (state != dtrace_anon.dta_state &&
14502 	    now - state->dts_laststatus >= dtrace_deadman_user)
14503 		return;
14504 
14505 	/*
14506 	 * We must be sure that dts_alive never appears to be less than the
14507 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14508 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14509 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14510 	 * the new value.  This assures that dts_alive never appears to be
14511 	 * less than its true value, regardless of the order in which the
14512 	 * stores to the underlying storage are issued.
14513 	 */
14514 	state->dts_alive = INT64_MAX;
14515 	dtrace_membar_producer();
14516 	state->dts_alive = now;
14517 }
14518 #else	/* !illumos */
14519 static void
14520 dtrace_state_clean(void *arg)
14521 {
14522 	dtrace_state_t *state = arg;
14523 	dtrace_optval_t *opt = state->dts_options;
14524 
14525 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14526 		return;
14527 
14528 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14529 	dtrace_speculation_clean(state);
14530 
14531 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14532 	    dtrace_state_clean, state);
14533 }
14534 
14535 static void
14536 dtrace_state_deadman(void *arg)
14537 {
14538 	dtrace_state_t *state = arg;
14539 	hrtime_t now;
14540 
14541 	dtrace_sync();
14542 
14543 	dtrace_debug_output();
14544 
14545 	now = dtrace_gethrtime();
14546 
14547 	if (state != dtrace_anon.dta_state &&
14548 	    now - state->dts_laststatus >= dtrace_deadman_user)
14549 		return;
14550 
14551 	/*
14552 	 * We must be sure that dts_alive never appears to be less than the
14553 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14554 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14555 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14556 	 * the new value.  This assures that dts_alive never appears to be
14557 	 * less than its true value, regardless of the order in which the
14558 	 * stores to the underlying storage are issued.
14559 	 */
14560 	state->dts_alive = INT64_MAX;
14561 	dtrace_membar_producer();
14562 	state->dts_alive = now;
14563 
14564 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14565 	    dtrace_state_deadman, state);
14566 }
14567 #endif	/* illumos */
14568 
14569 static dtrace_state_t *
14570 #ifdef illumos
14571 dtrace_state_create(dev_t *devp, cred_t *cr)
14572 #else
14573 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14574 #endif
14575 {
14576 #ifdef illumos
14577 	minor_t minor;
14578 	major_t major;
14579 #else
14580 	cred_t *cr = NULL;
14581 	int m = 0;
14582 #endif
14583 	char c[30];
14584 	dtrace_state_t *state;
14585 	dtrace_optval_t *opt;
14586 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14587 	int cpu_it;
14588 
14589 	ASSERT(MUTEX_HELD(&dtrace_lock));
14590 	ASSERT(MUTEX_HELD(&cpu_lock));
14591 
14592 #ifdef illumos
14593 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14594 	    VM_BESTFIT | VM_SLEEP);
14595 
14596 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14597 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14598 		return (NULL);
14599 	}
14600 
14601 	state = ddi_get_soft_state(dtrace_softstate, minor);
14602 #else
14603 	if (dev != NULL) {
14604 		cr = dev->si_cred;
14605 		m = dev2unit(dev);
14606 	}
14607 
14608 	/* Allocate memory for the state. */
14609 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14610 #endif
14611 
14612 	state->dts_epid = DTRACE_EPIDNONE + 1;
14613 
14614 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14615 #ifdef illumos
14616 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14617 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14618 
14619 	if (devp != NULL) {
14620 		major = getemajor(*devp);
14621 	} else {
14622 		major = ddi_driver_major(dtrace_devi);
14623 	}
14624 
14625 	state->dts_dev = makedevice(major, minor);
14626 
14627 	if (devp != NULL)
14628 		*devp = state->dts_dev;
14629 #else
14630 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14631 	state->dts_dev = dev;
14632 #endif
14633 
14634 	/*
14635 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14636 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14637 	 * other hand, it saves an additional memory reference in the probe
14638 	 * path.
14639 	 */
14640 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14641 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14642 
14643 	/*
14644          * Allocate and initialise the per-process per-CPU random state.
14645 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14646          * assumed to be seeded at this point (if from Fortuna seed file).
14647 	 */
14648 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14649 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14650 		/*
14651 		 * Each CPU is assigned a 2^64 period, non-overlapping
14652 		 * subsequence.
14653 		 */
14654 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14655 		    state->dts_rstate[cpu_it]);
14656 	}
14657 
14658 #ifdef illumos
14659 	state->dts_cleaner = CYCLIC_NONE;
14660 	state->dts_deadman = CYCLIC_NONE;
14661 #else
14662 	callout_init(&state->dts_cleaner, 1);
14663 	callout_init(&state->dts_deadman, 1);
14664 #endif
14665 	state->dts_vstate.dtvs_state = state;
14666 
14667 	for (i = 0; i < DTRACEOPT_MAX; i++)
14668 		state->dts_options[i] = DTRACEOPT_UNSET;
14669 
14670 	/*
14671 	 * Set the default options.
14672 	 */
14673 	opt = state->dts_options;
14674 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14675 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14676 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14677 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14678 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14679 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14680 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14681 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14682 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14683 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14684 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14685 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14686 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14687 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14688 
14689 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14690 
14691 	/*
14692 	 * Depending on the user credentials, we set flag bits which alter probe
14693 	 * visibility or the amount of destructiveness allowed.  In the case of
14694 	 * actual anonymous tracing, or the possession of all privileges, all of
14695 	 * the normal checks are bypassed.
14696 	 */
14697 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14698 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14699 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14700 	} else {
14701 		/*
14702 		 * Set up the credentials for this instantiation.  We take a
14703 		 * hold on the credential to prevent it from disappearing on
14704 		 * us; this in turn prevents the zone_t referenced by this
14705 		 * credential from disappearing.  This means that we can
14706 		 * examine the credential and the zone from probe context.
14707 		 */
14708 		crhold(cr);
14709 		state->dts_cred.dcr_cred = cr;
14710 
14711 		/*
14712 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14713 		 * unlocks the use of variables like pid, zonename, etc.
14714 		 */
14715 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14716 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14717 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14718 		}
14719 
14720 		/*
14721 		 * dtrace_user allows use of syscall and profile providers.
14722 		 * If the user also has proc_owner and/or proc_zone, we
14723 		 * extend the scope to include additional visibility and
14724 		 * destructive power.
14725 		 */
14726 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14727 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14728 				state->dts_cred.dcr_visible |=
14729 				    DTRACE_CRV_ALLPROC;
14730 
14731 				state->dts_cred.dcr_action |=
14732 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14733 			}
14734 
14735 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14736 				state->dts_cred.dcr_visible |=
14737 				    DTRACE_CRV_ALLZONE;
14738 
14739 				state->dts_cred.dcr_action |=
14740 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14741 			}
14742 
14743 			/*
14744 			 * If we have all privs in whatever zone this is,
14745 			 * we can do destructive things to processes which
14746 			 * have altered credentials.
14747 			 */
14748 #ifdef illumos
14749 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14750 			    cr->cr_zone->zone_privset)) {
14751 				state->dts_cred.dcr_action |=
14752 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14753 			}
14754 #endif
14755 		}
14756 
14757 		/*
14758 		 * Holding the dtrace_kernel privilege also implies that
14759 		 * the user has the dtrace_user privilege from a visibility
14760 		 * perspective.  But without further privileges, some
14761 		 * destructive actions are not available.
14762 		 */
14763 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14764 			/*
14765 			 * Make all probes in all zones visible.  However,
14766 			 * this doesn't mean that all actions become available
14767 			 * to all zones.
14768 			 */
14769 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14770 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14771 
14772 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14773 			    DTRACE_CRA_PROC;
14774 			/*
14775 			 * Holding proc_owner means that destructive actions
14776 			 * for *this* zone are allowed.
14777 			 */
14778 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14779 				state->dts_cred.dcr_action |=
14780 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14781 
14782 			/*
14783 			 * Holding proc_zone means that destructive actions
14784 			 * for this user/group ID in all zones is allowed.
14785 			 */
14786 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14787 				state->dts_cred.dcr_action |=
14788 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14789 
14790 #ifdef illumos
14791 			/*
14792 			 * If we have all privs in whatever zone this is,
14793 			 * we can do destructive things to processes which
14794 			 * have altered credentials.
14795 			 */
14796 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14797 			    cr->cr_zone->zone_privset)) {
14798 				state->dts_cred.dcr_action |=
14799 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14800 			}
14801 #endif
14802 		}
14803 
14804 		/*
14805 		 * Holding the dtrace_proc privilege gives control over fasttrap
14806 		 * and pid providers.  We need to grant wider destructive
14807 		 * privileges in the event that the user has proc_owner and/or
14808 		 * proc_zone.
14809 		 */
14810 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14811 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14812 				state->dts_cred.dcr_action |=
14813 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14814 
14815 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14816 				state->dts_cred.dcr_action |=
14817 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14818 		}
14819 	}
14820 
14821 	return (state);
14822 }
14823 
14824 static int
14825 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14826 {
14827 	dtrace_optval_t *opt = state->dts_options, size;
14828 	processorid_t cpu = 0;
14829 	int flags = 0, rval, factor, divisor = 1;
14830 
14831 	ASSERT(MUTEX_HELD(&dtrace_lock));
14832 	ASSERT(MUTEX_HELD(&cpu_lock));
14833 	ASSERT(which < DTRACEOPT_MAX);
14834 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14835 	    (state == dtrace_anon.dta_state &&
14836 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14837 
14838 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14839 		return (0);
14840 
14841 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14842 		cpu = opt[DTRACEOPT_CPU];
14843 
14844 	if (which == DTRACEOPT_SPECSIZE)
14845 		flags |= DTRACEBUF_NOSWITCH;
14846 
14847 	if (which == DTRACEOPT_BUFSIZE) {
14848 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14849 			flags |= DTRACEBUF_RING;
14850 
14851 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14852 			flags |= DTRACEBUF_FILL;
14853 
14854 		if (state != dtrace_anon.dta_state ||
14855 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14856 			flags |= DTRACEBUF_INACTIVE;
14857 	}
14858 
14859 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14860 		/*
14861 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14862 		 * aligned, drop it down by the difference.
14863 		 */
14864 		if (size & (sizeof (uint64_t) - 1))
14865 			size -= size & (sizeof (uint64_t) - 1);
14866 
14867 		if (size < state->dts_reserve) {
14868 			/*
14869 			 * Buffers always must be large enough to accommodate
14870 			 * their prereserved space.  We return E2BIG instead
14871 			 * of ENOMEM in this case to allow for user-level
14872 			 * software to differentiate the cases.
14873 			 */
14874 			return (E2BIG);
14875 		}
14876 
14877 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14878 
14879 		if (rval != ENOMEM) {
14880 			opt[which] = size;
14881 			return (rval);
14882 		}
14883 
14884 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14885 			return (rval);
14886 
14887 		for (divisor = 2; divisor < factor; divisor <<= 1)
14888 			continue;
14889 	}
14890 
14891 	return (ENOMEM);
14892 }
14893 
14894 static int
14895 dtrace_state_buffers(dtrace_state_t *state)
14896 {
14897 	dtrace_speculation_t *spec = state->dts_speculations;
14898 	int rval, i;
14899 
14900 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14901 	    DTRACEOPT_BUFSIZE)) != 0)
14902 		return (rval);
14903 
14904 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14905 	    DTRACEOPT_AGGSIZE)) != 0)
14906 		return (rval);
14907 
14908 	for (i = 0; i < state->dts_nspeculations; i++) {
14909 		if ((rval = dtrace_state_buffer(state,
14910 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14911 			return (rval);
14912 	}
14913 
14914 	return (0);
14915 }
14916 
14917 static void
14918 dtrace_state_prereserve(dtrace_state_t *state)
14919 {
14920 	dtrace_ecb_t *ecb;
14921 	dtrace_probe_t *probe;
14922 
14923 	state->dts_reserve = 0;
14924 
14925 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14926 		return;
14927 
14928 	/*
14929 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14930 	 * prereserved space to be the space required by the END probes.
14931 	 */
14932 	probe = dtrace_probes[dtrace_probeid_end - 1];
14933 	ASSERT(probe != NULL);
14934 
14935 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14936 		if (ecb->dte_state != state)
14937 			continue;
14938 
14939 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14940 	}
14941 }
14942 
14943 static int
14944 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14945 {
14946 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14947 	dtrace_speculation_t *spec;
14948 	dtrace_buffer_t *buf;
14949 #ifdef illumos
14950 	cyc_handler_t hdlr;
14951 	cyc_time_t when;
14952 #endif
14953 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14954 	dtrace_icookie_t cookie;
14955 
14956 	mutex_enter(&cpu_lock);
14957 	mutex_enter(&dtrace_lock);
14958 
14959 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14960 		rval = EBUSY;
14961 		goto out;
14962 	}
14963 
14964 	/*
14965 	 * Before we can perform any checks, we must prime all of the
14966 	 * retained enablings that correspond to this state.
14967 	 */
14968 	dtrace_enabling_prime(state);
14969 
14970 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14971 		rval = EACCES;
14972 		goto out;
14973 	}
14974 
14975 	dtrace_state_prereserve(state);
14976 
14977 	/*
14978 	 * Now we want to do is try to allocate our speculations.
14979 	 * We do not automatically resize the number of speculations; if
14980 	 * this fails, we will fail the operation.
14981 	 */
14982 	nspec = opt[DTRACEOPT_NSPEC];
14983 	ASSERT(nspec != DTRACEOPT_UNSET);
14984 
14985 	if (nspec > INT_MAX) {
14986 		rval = ENOMEM;
14987 		goto out;
14988 	}
14989 
14990 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14991 	    KM_NOSLEEP | KM_NORMALPRI);
14992 
14993 	if (spec == NULL) {
14994 		rval = ENOMEM;
14995 		goto out;
14996 	}
14997 
14998 	state->dts_speculations = spec;
14999 	state->dts_nspeculations = (int)nspec;
15000 
15001 	for (i = 0; i < nspec; i++) {
15002 		if ((buf = kmem_zalloc(bufsize,
15003 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15004 			rval = ENOMEM;
15005 			goto err;
15006 		}
15007 
15008 		spec[i].dtsp_buffer = buf;
15009 	}
15010 
15011 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15012 		if (dtrace_anon.dta_state == NULL) {
15013 			rval = ENOENT;
15014 			goto out;
15015 		}
15016 
15017 		if (state->dts_necbs != 0) {
15018 			rval = EALREADY;
15019 			goto out;
15020 		}
15021 
15022 		state->dts_anon = dtrace_anon_grab();
15023 		ASSERT(state->dts_anon != NULL);
15024 		state = state->dts_anon;
15025 
15026 		/*
15027 		 * We want "grabanon" to be set in the grabbed state, so we'll
15028 		 * copy that option value from the grabbing state into the
15029 		 * grabbed state.
15030 		 */
15031 		state->dts_options[DTRACEOPT_GRABANON] =
15032 		    opt[DTRACEOPT_GRABANON];
15033 
15034 		*cpu = dtrace_anon.dta_beganon;
15035 
15036 		/*
15037 		 * If the anonymous state is active (as it almost certainly
15038 		 * is if the anonymous enabling ultimately matched anything),
15039 		 * we don't allow any further option processing -- but we
15040 		 * don't return failure.
15041 		 */
15042 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15043 			goto out;
15044 	}
15045 
15046 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15047 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15048 		if (state->dts_aggregations == NULL) {
15049 			/*
15050 			 * We're not going to create an aggregation buffer
15051 			 * because we don't have any ECBs that contain
15052 			 * aggregations -- set this option to 0.
15053 			 */
15054 			opt[DTRACEOPT_AGGSIZE] = 0;
15055 		} else {
15056 			/*
15057 			 * If we have an aggregation buffer, we must also have
15058 			 * a buffer to use as scratch.
15059 			 */
15060 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15061 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15062 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15063 			}
15064 		}
15065 	}
15066 
15067 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15068 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15069 		if (!state->dts_speculates) {
15070 			/*
15071 			 * We're not going to create speculation buffers
15072 			 * because we don't have any ECBs that actually
15073 			 * speculate -- set the speculation size to 0.
15074 			 */
15075 			opt[DTRACEOPT_SPECSIZE] = 0;
15076 		}
15077 	}
15078 
15079 	/*
15080 	 * The bare minimum size for any buffer that we're actually going to
15081 	 * do anything to is sizeof (uint64_t).
15082 	 */
15083 	sz = sizeof (uint64_t);
15084 
15085 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15086 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15087 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15088 		/*
15089 		 * A buffer size has been explicitly set to 0 (or to a size
15090 		 * that will be adjusted to 0) and we need the space -- we
15091 		 * need to return failure.  We return ENOSPC to differentiate
15092 		 * it from failing to allocate a buffer due to failure to meet
15093 		 * the reserve (for which we return E2BIG).
15094 		 */
15095 		rval = ENOSPC;
15096 		goto out;
15097 	}
15098 
15099 	if ((rval = dtrace_state_buffers(state)) != 0)
15100 		goto err;
15101 
15102 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15103 		sz = dtrace_dstate_defsize;
15104 
15105 	do {
15106 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15107 
15108 		if (rval == 0)
15109 			break;
15110 
15111 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15112 			goto err;
15113 	} while (sz >>= 1);
15114 
15115 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15116 
15117 	if (rval != 0)
15118 		goto err;
15119 
15120 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15121 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15122 
15123 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15124 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15125 
15126 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15127 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15128 
15129 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15130 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15131 
15132 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15133 #ifdef illumos
15134 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15135 	hdlr.cyh_arg = state;
15136 	hdlr.cyh_level = CY_LOW_LEVEL;
15137 
15138 	when.cyt_when = 0;
15139 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15140 
15141 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15142 
15143 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15144 	hdlr.cyh_arg = state;
15145 	hdlr.cyh_level = CY_LOW_LEVEL;
15146 
15147 	when.cyt_when = 0;
15148 	when.cyt_interval = dtrace_deadman_interval;
15149 
15150 	state->dts_deadman = cyclic_add(&hdlr, &when);
15151 #else
15152 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15153 	    dtrace_state_clean, state);
15154 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15155 	    dtrace_state_deadman, state);
15156 #endif
15157 
15158 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15159 
15160 #ifdef illumos
15161 	if (state->dts_getf != 0 &&
15162 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15163 		/*
15164 		 * We don't have kernel privs but we have at least one call
15165 		 * to getf(); we need to bump our zone's count, and (if
15166 		 * this is the first enabling to have an unprivileged call
15167 		 * to getf()) we need to hook into closef().
15168 		 */
15169 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15170 
15171 		if (dtrace_getf++ == 0) {
15172 			ASSERT(dtrace_closef == NULL);
15173 			dtrace_closef = dtrace_getf_barrier;
15174 		}
15175 	}
15176 #endif
15177 
15178 	/*
15179 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15180 	 * interrupts here both to record the CPU on which we fired the BEGIN
15181 	 * probe (the data from this CPU will be processed first at user
15182 	 * level) and to manually activate the buffer for this CPU.
15183 	 */
15184 	cookie = dtrace_interrupt_disable();
15185 	*cpu = curcpu;
15186 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15187 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15188 
15189 	dtrace_probe(dtrace_probeid_begin,
15190 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15191 	dtrace_interrupt_enable(cookie);
15192 	/*
15193 	 * We may have had an exit action from a BEGIN probe; only change our
15194 	 * state to ACTIVE if we're still in WARMUP.
15195 	 */
15196 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15197 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15198 
15199 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15200 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15201 
15202 #ifdef __FreeBSD__
15203 	/*
15204 	 * We enable anonymous tracing before APs are started, so we must
15205 	 * activate buffers using the current CPU.
15206 	 */
15207 	if (state == dtrace_anon.dta_state)
15208 		for (int i = 0; i < NCPU; i++)
15209 			dtrace_buffer_activate_cpu(state, i);
15210 	else
15211 		dtrace_xcall(DTRACE_CPUALL,
15212 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15213 #else
15214 	/*
15215 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15216 	 * want each CPU to transition its principal buffer out of the
15217 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15218 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15219 	 * atomically transition from processing none of a state's ECBs to
15220 	 * processing all of them.
15221 	 */
15222 	dtrace_xcall(DTRACE_CPUALL,
15223 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15224 #endif
15225 	goto out;
15226 
15227 err:
15228 	dtrace_buffer_free(state->dts_buffer);
15229 	dtrace_buffer_free(state->dts_aggbuffer);
15230 
15231 	if ((nspec = state->dts_nspeculations) == 0) {
15232 		ASSERT(state->dts_speculations == NULL);
15233 		goto out;
15234 	}
15235 
15236 	spec = state->dts_speculations;
15237 	ASSERT(spec != NULL);
15238 
15239 	for (i = 0; i < state->dts_nspeculations; i++) {
15240 		if ((buf = spec[i].dtsp_buffer) == NULL)
15241 			break;
15242 
15243 		dtrace_buffer_free(buf);
15244 		kmem_free(buf, bufsize);
15245 	}
15246 
15247 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15248 	state->dts_nspeculations = 0;
15249 	state->dts_speculations = NULL;
15250 
15251 out:
15252 	mutex_exit(&dtrace_lock);
15253 	mutex_exit(&cpu_lock);
15254 
15255 	return (rval);
15256 }
15257 
15258 static int
15259 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15260 {
15261 	dtrace_icookie_t cookie;
15262 
15263 	ASSERT(MUTEX_HELD(&dtrace_lock));
15264 
15265 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15266 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15267 		return (EINVAL);
15268 
15269 	/*
15270 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15271 	 * to be sure that every CPU has seen it.  See below for the details
15272 	 * on why this is done.
15273 	 */
15274 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15275 	dtrace_sync();
15276 
15277 	/*
15278 	 * By this point, it is impossible for any CPU to be still processing
15279 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15280 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15281 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15282 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15283 	 * iff we're in the END probe.
15284 	 */
15285 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15286 	dtrace_sync();
15287 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15288 
15289 	/*
15290 	 * Finally, we can release the reserve and call the END probe.  We
15291 	 * disable interrupts across calling the END probe to allow us to
15292 	 * return the CPU on which we actually called the END probe.  This
15293 	 * allows user-land to be sure that this CPU's principal buffer is
15294 	 * processed last.
15295 	 */
15296 	state->dts_reserve = 0;
15297 
15298 	cookie = dtrace_interrupt_disable();
15299 	*cpu = curcpu;
15300 	dtrace_probe(dtrace_probeid_end,
15301 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15302 	dtrace_interrupt_enable(cookie);
15303 
15304 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15305 	dtrace_sync();
15306 
15307 #ifdef illumos
15308 	if (state->dts_getf != 0 &&
15309 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15310 		/*
15311 		 * We don't have kernel privs but we have at least one call
15312 		 * to getf(); we need to lower our zone's count, and (if
15313 		 * this is the last enabling to have an unprivileged call
15314 		 * to getf()) we need to clear the closef() hook.
15315 		 */
15316 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15317 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15318 		ASSERT(dtrace_getf > 0);
15319 
15320 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15321 
15322 		if (--dtrace_getf == 0)
15323 			dtrace_closef = NULL;
15324 	}
15325 #endif
15326 
15327 	return (0);
15328 }
15329 
15330 static int
15331 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15332     dtrace_optval_t val)
15333 {
15334 	ASSERT(MUTEX_HELD(&dtrace_lock));
15335 
15336 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15337 		return (EBUSY);
15338 
15339 	if (option >= DTRACEOPT_MAX)
15340 		return (EINVAL);
15341 
15342 	if (option != DTRACEOPT_CPU && val < 0)
15343 		return (EINVAL);
15344 
15345 	switch (option) {
15346 	case DTRACEOPT_DESTRUCTIVE:
15347 		if (dtrace_destructive_disallow)
15348 			return (EACCES);
15349 
15350 		state->dts_cred.dcr_destructive = 1;
15351 		break;
15352 
15353 	case DTRACEOPT_BUFSIZE:
15354 	case DTRACEOPT_DYNVARSIZE:
15355 	case DTRACEOPT_AGGSIZE:
15356 	case DTRACEOPT_SPECSIZE:
15357 	case DTRACEOPT_STRSIZE:
15358 		if (val < 0)
15359 			return (EINVAL);
15360 
15361 		if (val >= LONG_MAX) {
15362 			/*
15363 			 * If this is an otherwise negative value, set it to
15364 			 * the highest multiple of 128m less than LONG_MAX.
15365 			 * Technically, we're adjusting the size without
15366 			 * regard to the buffer resizing policy, but in fact,
15367 			 * this has no effect -- if we set the buffer size to
15368 			 * ~LONG_MAX and the buffer policy is ultimately set to
15369 			 * be "manual", the buffer allocation is guaranteed to
15370 			 * fail, if only because the allocation requires two
15371 			 * buffers.  (We set the the size to the highest
15372 			 * multiple of 128m because it ensures that the size
15373 			 * will remain a multiple of a megabyte when
15374 			 * repeatedly halved -- all the way down to 15m.)
15375 			 */
15376 			val = LONG_MAX - (1 << 27) + 1;
15377 		}
15378 	}
15379 
15380 	state->dts_options[option] = val;
15381 
15382 	return (0);
15383 }
15384 
15385 static void
15386 dtrace_state_destroy(dtrace_state_t *state)
15387 {
15388 	dtrace_ecb_t *ecb;
15389 	dtrace_vstate_t *vstate = &state->dts_vstate;
15390 #ifdef illumos
15391 	minor_t minor = getminor(state->dts_dev);
15392 #endif
15393 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15394 	dtrace_speculation_t *spec = state->dts_speculations;
15395 	int nspec = state->dts_nspeculations;
15396 	uint32_t match;
15397 
15398 	ASSERT(MUTEX_HELD(&dtrace_lock));
15399 	ASSERT(MUTEX_HELD(&cpu_lock));
15400 
15401 	/*
15402 	 * First, retract any retained enablings for this state.
15403 	 */
15404 	dtrace_enabling_retract(state);
15405 	ASSERT(state->dts_nretained == 0);
15406 
15407 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15408 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15409 		/*
15410 		 * We have managed to come into dtrace_state_destroy() on a
15411 		 * hot enabling -- almost certainly because of a disorderly
15412 		 * shutdown of a consumer.  (That is, a consumer that is
15413 		 * exiting without having called dtrace_stop().) In this case,
15414 		 * we're going to set our activity to be KILLED, and then
15415 		 * issue a sync to be sure that everyone is out of probe
15416 		 * context before we start blowing away ECBs.
15417 		 */
15418 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15419 		dtrace_sync();
15420 	}
15421 
15422 	/*
15423 	 * Release the credential hold we took in dtrace_state_create().
15424 	 */
15425 	if (state->dts_cred.dcr_cred != NULL)
15426 		crfree(state->dts_cred.dcr_cred);
15427 
15428 	/*
15429 	 * Now we can safely disable and destroy any enabled probes.  Because
15430 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15431 	 * (especially if they're all enabled), we take two passes through the
15432 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15433 	 * in the second we disable whatever is left over.
15434 	 */
15435 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15436 		for (i = 0; i < state->dts_necbs; i++) {
15437 			if ((ecb = state->dts_ecbs[i]) == NULL)
15438 				continue;
15439 
15440 			if (match && ecb->dte_probe != NULL) {
15441 				dtrace_probe_t *probe = ecb->dte_probe;
15442 				dtrace_provider_t *prov = probe->dtpr_provider;
15443 
15444 				if (!(prov->dtpv_priv.dtpp_flags & match))
15445 					continue;
15446 			}
15447 
15448 			dtrace_ecb_disable(ecb);
15449 			dtrace_ecb_destroy(ecb);
15450 		}
15451 
15452 		if (!match)
15453 			break;
15454 	}
15455 
15456 	/*
15457 	 * Before we free the buffers, perform one more sync to assure that
15458 	 * every CPU is out of probe context.
15459 	 */
15460 	dtrace_sync();
15461 
15462 	dtrace_buffer_free(state->dts_buffer);
15463 	dtrace_buffer_free(state->dts_aggbuffer);
15464 
15465 	for (i = 0; i < nspec; i++)
15466 		dtrace_buffer_free(spec[i].dtsp_buffer);
15467 
15468 #ifdef illumos
15469 	if (state->dts_cleaner != CYCLIC_NONE)
15470 		cyclic_remove(state->dts_cleaner);
15471 
15472 	if (state->dts_deadman != CYCLIC_NONE)
15473 		cyclic_remove(state->dts_deadman);
15474 #else
15475 	callout_stop(&state->dts_cleaner);
15476 	callout_drain(&state->dts_cleaner);
15477 	callout_stop(&state->dts_deadman);
15478 	callout_drain(&state->dts_deadman);
15479 #endif
15480 
15481 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15482 	dtrace_vstate_fini(vstate);
15483 	if (state->dts_ecbs != NULL)
15484 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15485 
15486 	if (state->dts_aggregations != NULL) {
15487 #ifdef DEBUG
15488 		for (i = 0; i < state->dts_naggregations; i++)
15489 			ASSERT(state->dts_aggregations[i] == NULL);
15490 #endif
15491 		ASSERT(state->dts_naggregations > 0);
15492 		kmem_free(state->dts_aggregations,
15493 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15494 	}
15495 
15496 	kmem_free(state->dts_buffer, bufsize);
15497 	kmem_free(state->dts_aggbuffer, bufsize);
15498 
15499 	for (i = 0; i < nspec; i++)
15500 		kmem_free(spec[i].dtsp_buffer, bufsize);
15501 
15502 	if (spec != NULL)
15503 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15504 
15505 	dtrace_format_destroy(state);
15506 
15507 	if (state->dts_aggid_arena != NULL) {
15508 #ifdef illumos
15509 		vmem_destroy(state->dts_aggid_arena);
15510 #else
15511 		delete_unrhdr(state->dts_aggid_arena);
15512 #endif
15513 		state->dts_aggid_arena = NULL;
15514 	}
15515 #ifdef illumos
15516 	ddi_soft_state_free(dtrace_softstate, minor);
15517 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15518 #endif
15519 }
15520 
15521 /*
15522  * DTrace Anonymous Enabling Functions
15523  */
15524 static dtrace_state_t *
15525 dtrace_anon_grab(void)
15526 {
15527 	dtrace_state_t *state;
15528 
15529 	ASSERT(MUTEX_HELD(&dtrace_lock));
15530 
15531 	if ((state = dtrace_anon.dta_state) == NULL) {
15532 		ASSERT(dtrace_anon.dta_enabling == NULL);
15533 		return (NULL);
15534 	}
15535 
15536 	ASSERT(dtrace_anon.dta_enabling != NULL);
15537 	ASSERT(dtrace_retained != NULL);
15538 
15539 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15540 	dtrace_anon.dta_enabling = NULL;
15541 	dtrace_anon.dta_state = NULL;
15542 
15543 	return (state);
15544 }
15545 
15546 static void
15547 dtrace_anon_property(void)
15548 {
15549 	int i, rv;
15550 	dtrace_state_t *state;
15551 	dof_hdr_t *dof;
15552 	char c[32];		/* enough for "dof-data-" + digits */
15553 
15554 	ASSERT(MUTEX_HELD(&dtrace_lock));
15555 	ASSERT(MUTEX_HELD(&cpu_lock));
15556 
15557 	for (i = 0; ; i++) {
15558 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15559 
15560 		dtrace_err_verbose = 1;
15561 
15562 		if ((dof = dtrace_dof_property(c)) == NULL) {
15563 			dtrace_err_verbose = 0;
15564 			break;
15565 		}
15566 
15567 #ifdef illumos
15568 		/*
15569 		 * We want to create anonymous state, so we need to transition
15570 		 * the kernel debugger to indicate that DTrace is active.  If
15571 		 * this fails (e.g. because the debugger has modified text in
15572 		 * some way), we won't continue with the processing.
15573 		 */
15574 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15575 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15576 			    "enabling ignored.");
15577 			dtrace_dof_destroy(dof);
15578 			break;
15579 		}
15580 #endif
15581 
15582 		/*
15583 		 * If we haven't allocated an anonymous state, we'll do so now.
15584 		 */
15585 		if ((state = dtrace_anon.dta_state) == NULL) {
15586 			state = dtrace_state_create(NULL, NULL);
15587 			dtrace_anon.dta_state = state;
15588 
15589 			if (state == NULL) {
15590 				/*
15591 				 * This basically shouldn't happen:  the only
15592 				 * failure mode from dtrace_state_create() is a
15593 				 * failure of ddi_soft_state_zalloc() that
15594 				 * itself should never happen.  Still, the
15595 				 * interface allows for a failure mode, and
15596 				 * we want to fail as gracefully as possible:
15597 				 * we'll emit an error message and cease
15598 				 * processing anonymous state in this case.
15599 				 */
15600 				cmn_err(CE_WARN, "failed to create "
15601 				    "anonymous state");
15602 				dtrace_dof_destroy(dof);
15603 				break;
15604 			}
15605 		}
15606 
15607 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15608 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15609 
15610 		if (rv == 0)
15611 			rv = dtrace_dof_options(dof, state);
15612 
15613 		dtrace_err_verbose = 0;
15614 		dtrace_dof_destroy(dof);
15615 
15616 		if (rv != 0) {
15617 			/*
15618 			 * This is malformed DOF; chuck any anonymous state
15619 			 * that we created.
15620 			 */
15621 			ASSERT(dtrace_anon.dta_enabling == NULL);
15622 			dtrace_state_destroy(state);
15623 			dtrace_anon.dta_state = NULL;
15624 			break;
15625 		}
15626 
15627 		ASSERT(dtrace_anon.dta_enabling != NULL);
15628 	}
15629 
15630 	if (dtrace_anon.dta_enabling != NULL) {
15631 		int rval;
15632 
15633 		/*
15634 		 * dtrace_enabling_retain() can only fail because we are
15635 		 * trying to retain more enablings than are allowed -- but
15636 		 * we only have one anonymous enabling, and we are guaranteed
15637 		 * to be allowed at least one retained enabling; we assert
15638 		 * that dtrace_enabling_retain() returns success.
15639 		 */
15640 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15641 		ASSERT(rval == 0);
15642 
15643 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15644 	}
15645 }
15646 
15647 /*
15648  * DTrace Helper Functions
15649  */
15650 static void
15651 dtrace_helper_trace(dtrace_helper_action_t *helper,
15652     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15653 {
15654 	uint32_t size, next, nnext, i;
15655 	dtrace_helptrace_t *ent, *buffer;
15656 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15657 
15658 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15659 		return;
15660 
15661 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15662 
15663 	/*
15664 	 * What would a tracing framework be without its own tracing
15665 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15666 	 */
15667 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15668 	    sizeof (uint64_t) - sizeof (uint64_t);
15669 
15670 	/*
15671 	 * Iterate until we can allocate a slot in the trace buffer.
15672 	 */
15673 	do {
15674 		next = dtrace_helptrace_next;
15675 
15676 		if (next + size < dtrace_helptrace_bufsize) {
15677 			nnext = next + size;
15678 		} else {
15679 			nnext = size;
15680 		}
15681 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15682 
15683 	/*
15684 	 * We have our slot; fill it in.
15685 	 */
15686 	if (nnext == size) {
15687 		dtrace_helptrace_wrapped++;
15688 		next = 0;
15689 	}
15690 
15691 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15692 	ent->dtht_helper = helper;
15693 	ent->dtht_where = where;
15694 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15695 
15696 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15697 	    mstate->dtms_fltoffs : -1;
15698 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15699 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15700 
15701 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15702 		dtrace_statvar_t *svar;
15703 
15704 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15705 			continue;
15706 
15707 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15708 		ent->dtht_locals[i] =
15709 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15710 	}
15711 }
15712 
15713 static uint64_t
15714 dtrace_helper(int which, dtrace_mstate_t *mstate,
15715     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15716 {
15717 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15718 	uint64_t sarg0 = mstate->dtms_arg[0];
15719 	uint64_t sarg1 = mstate->dtms_arg[1];
15720 	uint64_t rval = 0;
15721 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15722 	dtrace_helper_action_t *helper;
15723 	dtrace_vstate_t *vstate;
15724 	dtrace_difo_t *pred;
15725 	int i, trace = dtrace_helptrace_buffer != NULL;
15726 
15727 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15728 
15729 	if (helpers == NULL)
15730 		return (0);
15731 
15732 	if ((helper = helpers->dthps_actions[which]) == NULL)
15733 		return (0);
15734 
15735 	vstate = &helpers->dthps_vstate;
15736 	mstate->dtms_arg[0] = arg0;
15737 	mstate->dtms_arg[1] = arg1;
15738 
15739 	/*
15740 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15741 	 * we'll call the corresponding actions.  Note that the below calls
15742 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15743 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15744 	 * the stored DIF offset with its own (which is the desired behavior).
15745 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15746 	 * from machine state; this is okay, too.
15747 	 */
15748 	for (; helper != NULL; helper = helper->dtha_next) {
15749 		if ((pred = helper->dtha_predicate) != NULL) {
15750 			if (trace)
15751 				dtrace_helper_trace(helper, mstate, vstate, 0);
15752 
15753 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15754 				goto next;
15755 
15756 			if (*flags & CPU_DTRACE_FAULT)
15757 				goto err;
15758 		}
15759 
15760 		for (i = 0; i < helper->dtha_nactions; i++) {
15761 			if (trace)
15762 				dtrace_helper_trace(helper,
15763 				    mstate, vstate, i + 1);
15764 
15765 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15766 			    mstate, vstate, state);
15767 
15768 			if (*flags & CPU_DTRACE_FAULT)
15769 				goto err;
15770 		}
15771 
15772 next:
15773 		if (trace)
15774 			dtrace_helper_trace(helper, mstate, vstate,
15775 			    DTRACE_HELPTRACE_NEXT);
15776 	}
15777 
15778 	if (trace)
15779 		dtrace_helper_trace(helper, mstate, vstate,
15780 		    DTRACE_HELPTRACE_DONE);
15781 
15782 	/*
15783 	 * Restore the arg0 that we saved upon entry.
15784 	 */
15785 	mstate->dtms_arg[0] = sarg0;
15786 	mstate->dtms_arg[1] = sarg1;
15787 
15788 	return (rval);
15789 
15790 err:
15791 	if (trace)
15792 		dtrace_helper_trace(helper, mstate, vstate,
15793 		    DTRACE_HELPTRACE_ERR);
15794 
15795 	/*
15796 	 * Restore the arg0 that we saved upon entry.
15797 	 */
15798 	mstate->dtms_arg[0] = sarg0;
15799 	mstate->dtms_arg[1] = sarg1;
15800 
15801 	return (0);
15802 }
15803 
15804 static void
15805 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15806     dtrace_vstate_t *vstate)
15807 {
15808 	int i;
15809 
15810 	if (helper->dtha_predicate != NULL)
15811 		dtrace_difo_release(helper->dtha_predicate, vstate);
15812 
15813 	for (i = 0; i < helper->dtha_nactions; i++) {
15814 		ASSERT(helper->dtha_actions[i] != NULL);
15815 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15816 	}
15817 
15818 	kmem_free(helper->dtha_actions,
15819 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15820 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15821 }
15822 
15823 static int
15824 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15825 {
15826 	proc_t *p = curproc;
15827 	dtrace_vstate_t *vstate;
15828 	int i;
15829 
15830 	if (help == NULL)
15831 		help = p->p_dtrace_helpers;
15832 
15833 	ASSERT(MUTEX_HELD(&dtrace_lock));
15834 
15835 	if (help == NULL || gen > help->dthps_generation)
15836 		return (EINVAL);
15837 
15838 	vstate = &help->dthps_vstate;
15839 
15840 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15841 		dtrace_helper_action_t *last = NULL, *h, *next;
15842 
15843 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15844 			next = h->dtha_next;
15845 
15846 			if (h->dtha_generation == gen) {
15847 				if (last != NULL) {
15848 					last->dtha_next = next;
15849 				} else {
15850 					help->dthps_actions[i] = next;
15851 				}
15852 
15853 				dtrace_helper_action_destroy(h, vstate);
15854 			} else {
15855 				last = h;
15856 			}
15857 		}
15858 	}
15859 
15860 	/*
15861 	 * Interate until we've cleared out all helper providers with the
15862 	 * given generation number.
15863 	 */
15864 	for (;;) {
15865 		dtrace_helper_provider_t *prov;
15866 
15867 		/*
15868 		 * Look for a helper provider with the right generation. We
15869 		 * have to start back at the beginning of the list each time
15870 		 * because we drop dtrace_lock. It's unlikely that we'll make
15871 		 * more than two passes.
15872 		 */
15873 		for (i = 0; i < help->dthps_nprovs; i++) {
15874 			prov = help->dthps_provs[i];
15875 
15876 			if (prov->dthp_generation == gen)
15877 				break;
15878 		}
15879 
15880 		/*
15881 		 * If there were no matches, we're done.
15882 		 */
15883 		if (i == help->dthps_nprovs)
15884 			break;
15885 
15886 		/*
15887 		 * Move the last helper provider into this slot.
15888 		 */
15889 		help->dthps_nprovs--;
15890 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15891 		help->dthps_provs[help->dthps_nprovs] = NULL;
15892 
15893 		mutex_exit(&dtrace_lock);
15894 
15895 		/*
15896 		 * If we have a meta provider, remove this helper provider.
15897 		 */
15898 		mutex_enter(&dtrace_meta_lock);
15899 		if (dtrace_meta_pid != NULL) {
15900 			ASSERT(dtrace_deferred_pid == NULL);
15901 			dtrace_helper_provider_remove(&prov->dthp_prov,
15902 			    p->p_pid);
15903 		}
15904 		mutex_exit(&dtrace_meta_lock);
15905 
15906 		dtrace_helper_provider_destroy(prov);
15907 
15908 		mutex_enter(&dtrace_lock);
15909 	}
15910 
15911 	return (0);
15912 }
15913 
15914 static int
15915 dtrace_helper_validate(dtrace_helper_action_t *helper)
15916 {
15917 	int err = 0, i;
15918 	dtrace_difo_t *dp;
15919 
15920 	if ((dp = helper->dtha_predicate) != NULL)
15921 		err += dtrace_difo_validate_helper(dp);
15922 
15923 	for (i = 0; i < helper->dtha_nactions; i++)
15924 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15925 
15926 	return (err == 0);
15927 }
15928 
15929 static int
15930 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15931     dtrace_helpers_t *help)
15932 {
15933 	dtrace_helper_action_t *helper, *last;
15934 	dtrace_actdesc_t *act;
15935 	dtrace_vstate_t *vstate;
15936 	dtrace_predicate_t *pred;
15937 	int count = 0, nactions = 0, i;
15938 
15939 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15940 		return (EINVAL);
15941 
15942 	last = help->dthps_actions[which];
15943 	vstate = &help->dthps_vstate;
15944 
15945 	for (count = 0; last != NULL; last = last->dtha_next) {
15946 		count++;
15947 		if (last->dtha_next == NULL)
15948 			break;
15949 	}
15950 
15951 	/*
15952 	 * If we already have dtrace_helper_actions_max helper actions for this
15953 	 * helper action type, we'll refuse to add a new one.
15954 	 */
15955 	if (count >= dtrace_helper_actions_max)
15956 		return (ENOSPC);
15957 
15958 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15959 	helper->dtha_generation = help->dthps_generation;
15960 
15961 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15962 		ASSERT(pred->dtp_difo != NULL);
15963 		dtrace_difo_hold(pred->dtp_difo);
15964 		helper->dtha_predicate = pred->dtp_difo;
15965 	}
15966 
15967 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15968 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15969 			goto err;
15970 
15971 		if (act->dtad_difo == NULL)
15972 			goto err;
15973 
15974 		nactions++;
15975 	}
15976 
15977 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15978 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15979 
15980 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15981 		dtrace_difo_hold(act->dtad_difo);
15982 		helper->dtha_actions[i++] = act->dtad_difo;
15983 	}
15984 
15985 	if (!dtrace_helper_validate(helper))
15986 		goto err;
15987 
15988 	if (last == NULL) {
15989 		help->dthps_actions[which] = helper;
15990 	} else {
15991 		last->dtha_next = helper;
15992 	}
15993 
15994 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15995 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15996 		dtrace_helptrace_next = 0;
15997 	}
15998 
15999 	return (0);
16000 err:
16001 	dtrace_helper_action_destroy(helper, vstate);
16002 	return (EINVAL);
16003 }
16004 
16005 static void
16006 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16007     dof_helper_t *dofhp)
16008 {
16009 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16010 
16011 	mutex_enter(&dtrace_meta_lock);
16012 	mutex_enter(&dtrace_lock);
16013 
16014 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16015 		/*
16016 		 * If the dtrace module is loaded but not attached, or if
16017 		 * there aren't isn't a meta provider registered to deal with
16018 		 * these provider descriptions, we need to postpone creating
16019 		 * the actual providers until later.
16020 		 */
16021 
16022 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16023 		    dtrace_deferred_pid != help) {
16024 			help->dthps_deferred = 1;
16025 			help->dthps_pid = p->p_pid;
16026 			help->dthps_next = dtrace_deferred_pid;
16027 			help->dthps_prev = NULL;
16028 			if (dtrace_deferred_pid != NULL)
16029 				dtrace_deferred_pid->dthps_prev = help;
16030 			dtrace_deferred_pid = help;
16031 		}
16032 
16033 		mutex_exit(&dtrace_lock);
16034 
16035 	} else if (dofhp != NULL) {
16036 		/*
16037 		 * If the dtrace module is loaded and we have a particular
16038 		 * helper provider description, pass that off to the
16039 		 * meta provider.
16040 		 */
16041 
16042 		mutex_exit(&dtrace_lock);
16043 
16044 		dtrace_helper_provide(dofhp, p->p_pid);
16045 
16046 	} else {
16047 		/*
16048 		 * Otherwise, just pass all the helper provider descriptions
16049 		 * off to the meta provider.
16050 		 */
16051 
16052 		int i;
16053 		mutex_exit(&dtrace_lock);
16054 
16055 		for (i = 0; i < help->dthps_nprovs; i++) {
16056 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16057 			    p->p_pid);
16058 		}
16059 	}
16060 
16061 	mutex_exit(&dtrace_meta_lock);
16062 }
16063 
16064 static int
16065 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16066 {
16067 	dtrace_helper_provider_t *hprov, **tmp_provs;
16068 	uint_t tmp_maxprovs, i;
16069 
16070 	ASSERT(MUTEX_HELD(&dtrace_lock));
16071 	ASSERT(help != NULL);
16072 
16073 	/*
16074 	 * If we already have dtrace_helper_providers_max helper providers,
16075 	 * we're refuse to add a new one.
16076 	 */
16077 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16078 		return (ENOSPC);
16079 
16080 	/*
16081 	 * Check to make sure this isn't a duplicate.
16082 	 */
16083 	for (i = 0; i < help->dthps_nprovs; i++) {
16084 		if (dofhp->dofhp_addr ==
16085 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16086 			return (EALREADY);
16087 	}
16088 
16089 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16090 	hprov->dthp_prov = *dofhp;
16091 	hprov->dthp_ref = 1;
16092 	hprov->dthp_generation = gen;
16093 
16094 	/*
16095 	 * Allocate a bigger table for helper providers if it's already full.
16096 	 */
16097 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16098 		tmp_maxprovs = help->dthps_maxprovs;
16099 		tmp_provs = help->dthps_provs;
16100 
16101 		if (help->dthps_maxprovs == 0)
16102 			help->dthps_maxprovs = 2;
16103 		else
16104 			help->dthps_maxprovs *= 2;
16105 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16106 			help->dthps_maxprovs = dtrace_helper_providers_max;
16107 
16108 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16109 
16110 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16111 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16112 
16113 		if (tmp_provs != NULL) {
16114 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16115 			    sizeof (dtrace_helper_provider_t *));
16116 			kmem_free(tmp_provs, tmp_maxprovs *
16117 			    sizeof (dtrace_helper_provider_t *));
16118 		}
16119 	}
16120 
16121 	help->dthps_provs[help->dthps_nprovs] = hprov;
16122 	help->dthps_nprovs++;
16123 
16124 	return (0);
16125 }
16126 
16127 static void
16128 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16129 {
16130 	mutex_enter(&dtrace_lock);
16131 
16132 	if (--hprov->dthp_ref == 0) {
16133 		dof_hdr_t *dof;
16134 		mutex_exit(&dtrace_lock);
16135 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16136 		dtrace_dof_destroy(dof);
16137 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16138 	} else {
16139 		mutex_exit(&dtrace_lock);
16140 	}
16141 }
16142 
16143 static int
16144 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16145 {
16146 	uintptr_t daddr = (uintptr_t)dof;
16147 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16148 	dof_provider_t *provider;
16149 	dof_probe_t *probe;
16150 	uint8_t *arg;
16151 	char *strtab, *typestr;
16152 	dof_stridx_t typeidx;
16153 	size_t typesz;
16154 	uint_t nprobes, j, k;
16155 
16156 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16157 
16158 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16159 		dtrace_dof_error(dof, "misaligned section offset");
16160 		return (-1);
16161 	}
16162 
16163 	/*
16164 	 * The section needs to be large enough to contain the DOF provider
16165 	 * structure appropriate for the given version.
16166 	 */
16167 	if (sec->dofs_size <
16168 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16169 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16170 	    sizeof (dof_provider_t))) {
16171 		dtrace_dof_error(dof, "provider section too small");
16172 		return (-1);
16173 	}
16174 
16175 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16176 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16177 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16178 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16179 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16180 
16181 	if (str_sec == NULL || prb_sec == NULL ||
16182 	    arg_sec == NULL || off_sec == NULL)
16183 		return (-1);
16184 
16185 	enoff_sec = NULL;
16186 
16187 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16188 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16189 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16190 	    provider->dofpv_prenoffs)) == NULL)
16191 		return (-1);
16192 
16193 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16194 
16195 	if (provider->dofpv_name >= str_sec->dofs_size ||
16196 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16197 		dtrace_dof_error(dof, "invalid provider name");
16198 		return (-1);
16199 	}
16200 
16201 	if (prb_sec->dofs_entsize == 0 ||
16202 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16203 		dtrace_dof_error(dof, "invalid entry size");
16204 		return (-1);
16205 	}
16206 
16207 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16208 		dtrace_dof_error(dof, "misaligned entry size");
16209 		return (-1);
16210 	}
16211 
16212 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16213 		dtrace_dof_error(dof, "invalid entry size");
16214 		return (-1);
16215 	}
16216 
16217 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16218 		dtrace_dof_error(dof, "misaligned section offset");
16219 		return (-1);
16220 	}
16221 
16222 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16223 		dtrace_dof_error(dof, "invalid entry size");
16224 		return (-1);
16225 	}
16226 
16227 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16228 
16229 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16230 
16231 	/*
16232 	 * Take a pass through the probes to check for errors.
16233 	 */
16234 	for (j = 0; j < nprobes; j++) {
16235 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16236 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16237 
16238 		if (probe->dofpr_func >= str_sec->dofs_size) {
16239 			dtrace_dof_error(dof, "invalid function name");
16240 			return (-1);
16241 		}
16242 
16243 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16244 			dtrace_dof_error(dof, "function name too long");
16245 			/*
16246 			 * Keep going if the function name is too long.
16247 			 * Unlike provider and probe names, we cannot reasonably
16248 			 * impose restrictions on function names, since they're
16249 			 * a property of the code being instrumented. We will
16250 			 * skip this probe in dtrace_helper_provide_one().
16251 			 */
16252 		}
16253 
16254 		if (probe->dofpr_name >= str_sec->dofs_size ||
16255 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16256 			dtrace_dof_error(dof, "invalid probe name");
16257 			return (-1);
16258 		}
16259 
16260 		/*
16261 		 * The offset count must not wrap the index, and the offsets
16262 		 * must also not overflow the section's data.
16263 		 */
16264 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16265 		    probe->dofpr_offidx ||
16266 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16267 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16268 			dtrace_dof_error(dof, "invalid probe offset");
16269 			return (-1);
16270 		}
16271 
16272 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16273 			/*
16274 			 * If there's no is-enabled offset section, make sure
16275 			 * there aren't any is-enabled offsets. Otherwise
16276 			 * perform the same checks as for probe offsets
16277 			 * (immediately above).
16278 			 */
16279 			if (enoff_sec == NULL) {
16280 				if (probe->dofpr_enoffidx != 0 ||
16281 				    probe->dofpr_nenoffs != 0) {
16282 					dtrace_dof_error(dof, "is-enabled "
16283 					    "offsets with null section");
16284 					return (-1);
16285 				}
16286 			} else if (probe->dofpr_enoffidx +
16287 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16288 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16289 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16290 				dtrace_dof_error(dof, "invalid is-enabled "
16291 				    "offset");
16292 				return (-1);
16293 			}
16294 
16295 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16296 				dtrace_dof_error(dof, "zero probe and "
16297 				    "is-enabled offsets");
16298 				return (-1);
16299 			}
16300 		} else if (probe->dofpr_noffs == 0) {
16301 			dtrace_dof_error(dof, "zero probe offsets");
16302 			return (-1);
16303 		}
16304 
16305 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16306 		    probe->dofpr_argidx ||
16307 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16308 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16309 			dtrace_dof_error(dof, "invalid args");
16310 			return (-1);
16311 		}
16312 
16313 		typeidx = probe->dofpr_nargv;
16314 		typestr = strtab + probe->dofpr_nargv;
16315 		for (k = 0; k < probe->dofpr_nargc; k++) {
16316 			if (typeidx >= str_sec->dofs_size) {
16317 				dtrace_dof_error(dof, "bad "
16318 				    "native argument type");
16319 				return (-1);
16320 			}
16321 
16322 			typesz = strlen(typestr) + 1;
16323 			if (typesz > DTRACE_ARGTYPELEN) {
16324 				dtrace_dof_error(dof, "native "
16325 				    "argument type too long");
16326 				return (-1);
16327 			}
16328 			typeidx += typesz;
16329 			typestr += typesz;
16330 		}
16331 
16332 		typeidx = probe->dofpr_xargv;
16333 		typestr = strtab + probe->dofpr_xargv;
16334 		for (k = 0; k < probe->dofpr_xargc; k++) {
16335 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16336 				dtrace_dof_error(dof, "bad "
16337 				    "native argument index");
16338 				return (-1);
16339 			}
16340 
16341 			if (typeidx >= str_sec->dofs_size) {
16342 				dtrace_dof_error(dof, "bad "
16343 				    "translated argument type");
16344 				return (-1);
16345 			}
16346 
16347 			typesz = strlen(typestr) + 1;
16348 			if (typesz > DTRACE_ARGTYPELEN) {
16349 				dtrace_dof_error(dof, "translated argument "
16350 				    "type too long");
16351 				return (-1);
16352 			}
16353 
16354 			typeidx += typesz;
16355 			typestr += typesz;
16356 		}
16357 	}
16358 
16359 	return (0);
16360 }
16361 
16362 static int
16363 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16364 {
16365 	dtrace_helpers_t *help;
16366 	dtrace_vstate_t *vstate;
16367 	dtrace_enabling_t *enab = NULL;
16368 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16369 	uintptr_t daddr = (uintptr_t)dof;
16370 
16371 	ASSERT(MUTEX_HELD(&dtrace_lock));
16372 
16373 	if ((help = p->p_dtrace_helpers) == NULL)
16374 		help = dtrace_helpers_create(p);
16375 
16376 	vstate = &help->dthps_vstate;
16377 
16378 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16379 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16380 		dtrace_dof_destroy(dof);
16381 		return (rv);
16382 	}
16383 
16384 	/*
16385 	 * Look for helper providers and validate their descriptions.
16386 	 */
16387 	for (i = 0; i < dof->dofh_secnum; i++) {
16388 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16389 		    dof->dofh_secoff + i * dof->dofh_secsize);
16390 
16391 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16392 			continue;
16393 
16394 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16395 			dtrace_enabling_destroy(enab);
16396 			dtrace_dof_destroy(dof);
16397 			return (-1);
16398 		}
16399 
16400 		nprovs++;
16401 	}
16402 
16403 	/*
16404 	 * Now we need to walk through the ECB descriptions in the enabling.
16405 	 */
16406 	for (i = 0; i < enab->dten_ndesc; i++) {
16407 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16408 		dtrace_probedesc_t *desc = &ep->dted_probe;
16409 
16410 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16411 			continue;
16412 
16413 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16414 			continue;
16415 
16416 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16417 			continue;
16418 
16419 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16420 		    ep, help)) != 0) {
16421 			/*
16422 			 * Adding this helper action failed -- we are now going
16423 			 * to rip out the entire generation and return failure.
16424 			 */
16425 			(void) dtrace_helper_destroygen(help,
16426 			    help->dthps_generation);
16427 			dtrace_enabling_destroy(enab);
16428 			dtrace_dof_destroy(dof);
16429 			return (-1);
16430 		}
16431 
16432 		nhelpers++;
16433 	}
16434 
16435 	if (nhelpers < enab->dten_ndesc)
16436 		dtrace_dof_error(dof, "unmatched helpers");
16437 
16438 	gen = help->dthps_generation++;
16439 	dtrace_enabling_destroy(enab);
16440 
16441 	if (nprovs > 0) {
16442 		/*
16443 		 * Now that this is in-kernel, we change the sense of the
16444 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16445 		 * and dofhp_addr denotes the address at user-level.
16446 		 */
16447 		dhp->dofhp_addr = dhp->dofhp_dof;
16448 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16449 
16450 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16451 			mutex_exit(&dtrace_lock);
16452 			dtrace_helper_provider_register(p, help, dhp);
16453 			mutex_enter(&dtrace_lock);
16454 
16455 			destroy = 0;
16456 		}
16457 	}
16458 
16459 	if (destroy)
16460 		dtrace_dof_destroy(dof);
16461 
16462 	return (gen);
16463 }
16464 
16465 static dtrace_helpers_t *
16466 dtrace_helpers_create(proc_t *p)
16467 {
16468 	dtrace_helpers_t *help;
16469 
16470 	ASSERT(MUTEX_HELD(&dtrace_lock));
16471 	ASSERT(p->p_dtrace_helpers == NULL);
16472 
16473 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16474 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16475 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16476 
16477 	p->p_dtrace_helpers = help;
16478 	dtrace_helpers++;
16479 
16480 	return (help);
16481 }
16482 
16483 #ifdef illumos
16484 static
16485 #endif
16486 void
16487 dtrace_helpers_destroy(proc_t *p)
16488 {
16489 	dtrace_helpers_t *help;
16490 	dtrace_vstate_t *vstate;
16491 #ifdef illumos
16492 	proc_t *p = curproc;
16493 #endif
16494 	int i;
16495 
16496 	mutex_enter(&dtrace_lock);
16497 
16498 	ASSERT(p->p_dtrace_helpers != NULL);
16499 	ASSERT(dtrace_helpers > 0);
16500 
16501 	help = p->p_dtrace_helpers;
16502 	vstate = &help->dthps_vstate;
16503 
16504 	/*
16505 	 * We're now going to lose the help from this process.
16506 	 */
16507 	p->p_dtrace_helpers = NULL;
16508 	dtrace_sync();
16509 
16510 	/*
16511 	 * Destory the helper actions.
16512 	 */
16513 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16514 		dtrace_helper_action_t *h, *next;
16515 
16516 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16517 			next = h->dtha_next;
16518 			dtrace_helper_action_destroy(h, vstate);
16519 			h = next;
16520 		}
16521 	}
16522 
16523 	mutex_exit(&dtrace_lock);
16524 
16525 	/*
16526 	 * Destroy the helper providers.
16527 	 */
16528 	if (help->dthps_maxprovs > 0) {
16529 		mutex_enter(&dtrace_meta_lock);
16530 		if (dtrace_meta_pid != NULL) {
16531 			ASSERT(dtrace_deferred_pid == NULL);
16532 
16533 			for (i = 0; i < help->dthps_nprovs; i++) {
16534 				dtrace_helper_provider_remove(
16535 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16536 			}
16537 		} else {
16538 			mutex_enter(&dtrace_lock);
16539 			ASSERT(help->dthps_deferred == 0 ||
16540 			    help->dthps_next != NULL ||
16541 			    help->dthps_prev != NULL ||
16542 			    help == dtrace_deferred_pid);
16543 
16544 			/*
16545 			 * Remove the helper from the deferred list.
16546 			 */
16547 			if (help->dthps_next != NULL)
16548 				help->dthps_next->dthps_prev = help->dthps_prev;
16549 			if (help->dthps_prev != NULL)
16550 				help->dthps_prev->dthps_next = help->dthps_next;
16551 			if (dtrace_deferred_pid == help) {
16552 				dtrace_deferred_pid = help->dthps_next;
16553 				ASSERT(help->dthps_prev == NULL);
16554 			}
16555 
16556 			mutex_exit(&dtrace_lock);
16557 		}
16558 
16559 		mutex_exit(&dtrace_meta_lock);
16560 
16561 		for (i = 0; i < help->dthps_nprovs; i++) {
16562 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16563 		}
16564 
16565 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16566 		    sizeof (dtrace_helper_provider_t *));
16567 	}
16568 
16569 	mutex_enter(&dtrace_lock);
16570 
16571 	dtrace_vstate_fini(&help->dthps_vstate);
16572 	kmem_free(help->dthps_actions,
16573 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16574 	kmem_free(help, sizeof (dtrace_helpers_t));
16575 
16576 	--dtrace_helpers;
16577 	mutex_exit(&dtrace_lock);
16578 }
16579 
16580 #ifdef illumos
16581 static
16582 #endif
16583 void
16584 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16585 {
16586 	dtrace_helpers_t *help, *newhelp;
16587 	dtrace_helper_action_t *helper, *new, *last;
16588 	dtrace_difo_t *dp;
16589 	dtrace_vstate_t *vstate;
16590 	int i, j, sz, hasprovs = 0;
16591 
16592 	mutex_enter(&dtrace_lock);
16593 	ASSERT(from->p_dtrace_helpers != NULL);
16594 	ASSERT(dtrace_helpers > 0);
16595 
16596 	help = from->p_dtrace_helpers;
16597 	newhelp = dtrace_helpers_create(to);
16598 	ASSERT(to->p_dtrace_helpers != NULL);
16599 
16600 	newhelp->dthps_generation = help->dthps_generation;
16601 	vstate = &newhelp->dthps_vstate;
16602 
16603 	/*
16604 	 * Duplicate the helper actions.
16605 	 */
16606 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16607 		if ((helper = help->dthps_actions[i]) == NULL)
16608 			continue;
16609 
16610 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16611 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16612 			    KM_SLEEP);
16613 			new->dtha_generation = helper->dtha_generation;
16614 
16615 			if ((dp = helper->dtha_predicate) != NULL) {
16616 				dp = dtrace_difo_duplicate(dp, vstate);
16617 				new->dtha_predicate = dp;
16618 			}
16619 
16620 			new->dtha_nactions = helper->dtha_nactions;
16621 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16622 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16623 
16624 			for (j = 0; j < new->dtha_nactions; j++) {
16625 				dtrace_difo_t *dp = helper->dtha_actions[j];
16626 
16627 				ASSERT(dp != NULL);
16628 				dp = dtrace_difo_duplicate(dp, vstate);
16629 				new->dtha_actions[j] = dp;
16630 			}
16631 
16632 			if (last != NULL) {
16633 				last->dtha_next = new;
16634 			} else {
16635 				newhelp->dthps_actions[i] = new;
16636 			}
16637 
16638 			last = new;
16639 		}
16640 	}
16641 
16642 	/*
16643 	 * Duplicate the helper providers and register them with the
16644 	 * DTrace framework.
16645 	 */
16646 	if (help->dthps_nprovs > 0) {
16647 		newhelp->dthps_nprovs = help->dthps_nprovs;
16648 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16649 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16650 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16651 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16652 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16653 			newhelp->dthps_provs[i]->dthp_ref++;
16654 		}
16655 
16656 		hasprovs = 1;
16657 	}
16658 
16659 	mutex_exit(&dtrace_lock);
16660 
16661 	if (hasprovs)
16662 		dtrace_helper_provider_register(to, newhelp, NULL);
16663 }
16664 
16665 /*
16666  * DTrace Hook Functions
16667  */
16668 static void
16669 dtrace_module_loaded(modctl_t *ctl)
16670 {
16671 	dtrace_provider_t *prv;
16672 
16673 	mutex_enter(&dtrace_provider_lock);
16674 #ifdef illumos
16675 	mutex_enter(&mod_lock);
16676 #endif
16677 
16678 #ifdef illumos
16679 	ASSERT(ctl->mod_busy);
16680 #endif
16681 
16682 	/*
16683 	 * We're going to call each providers per-module provide operation
16684 	 * specifying only this module.
16685 	 */
16686 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16687 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16688 
16689 #ifdef illumos
16690 	mutex_exit(&mod_lock);
16691 #endif
16692 	mutex_exit(&dtrace_provider_lock);
16693 
16694 	/*
16695 	 * If we have any retained enablings, we need to match against them.
16696 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16697 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16698 	 * module.  (In particular, this happens when loading scheduling
16699 	 * classes.)  So if we have any retained enablings, we need to dispatch
16700 	 * our task queue to do the match for us.
16701 	 */
16702 	mutex_enter(&dtrace_lock);
16703 
16704 	if (dtrace_retained == NULL) {
16705 		mutex_exit(&dtrace_lock);
16706 		return;
16707 	}
16708 
16709 	(void) taskq_dispatch(dtrace_taskq,
16710 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16711 
16712 	mutex_exit(&dtrace_lock);
16713 
16714 	/*
16715 	 * And now, for a little heuristic sleaze:  in general, we want to
16716 	 * match modules as soon as they load.  However, we cannot guarantee
16717 	 * this, because it would lead us to the lock ordering violation
16718 	 * outlined above.  The common case, of course, is that cpu_lock is
16719 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16720 	 * long enough for the task queue to do its work.  If it's not, it's
16721 	 * not a serious problem -- it just means that the module that we
16722 	 * just loaded may not be immediately instrumentable.
16723 	 */
16724 	delay(1);
16725 }
16726 
16727 static void
16728 #ifdef illumos
16729 dtrace_module_unloaded(modctl_t *ctl)
16730 #else
16731 dtrace_module_unloaded(modctl_t *ctl, int *error)
16732 #endif
16733 {
16734 	dtrace_probe_t template, *probe, *first, *next;
16735 	dtrace_provider_t *prov;
16736 #ifndef illumos
16737 	char modname[DTRACE_MODNAMELEN];
16738 	size_t len;
16739 #endif
16740 
16741 #ifdef illumos
16742 	template.dtpr_mod = ctl->mod_modname;
16743 #else
16744 	/* Handle the fact that ctl->filename may end in ".ko". */
16745 	strlcpy(modname, ctl->filename, sizeof(modname));
16746 	len = strlen(ctl->filename);
16747 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16748 		modname[len - 3] = '\0';
16749 	template.dtpr_mod = modname;
16750 #endif
16751 
16752 	mutex_enter(&dtrace_provider_lock);
16753 #ifdef illumos
16754 	mutex_enter(&mod_lock);
16755 #endif
16756 	mutex_enter(&dtrace_lock);
16757 
16758 #ifndef illumos
16759 	if (ctl->nenabled > 0) {
16760 		/* Don't allow unloads if a probe is enabled. */
16761 		mutex_exit(&dtrace_provider_lock);
16762 		mutex_exit(&dtrace_lock);
16763 		*error = -1;
16764 		printf(
16765 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16766 		return;
16767 	}
16768 #endif
16769 
16770 	if (dtrace_bymod == NULL) {
16771 		/*
16772 		 * The DTrace module is loaded (obviously) but not attached;
16773 		 * we don't have any work to do.
16774 		 */
16775 		mutex_exit(&dtrace_provider_lock);
16776 #ifdef illumos
16777 		mutex_exit(&mod_lock);
16778 #endif
16779 		mutex_exit(&dtrace_lock);
16780 		return;
16781 	}
16782 
16783 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16784 	    probe != NULL; probe = probe->dtpr_nextmod) {
16785 		if (probe->dtpr_ecb != NULL) {
16786 			mutex_exit(&dtrace_provider_lock);
16787 #ifdef illumos
16788 			mutex_exit(&mod_lock);
16789 #endif
16790 			mutex_exit(&dtrace_lock);
16791 
16792 			/*
16793 			 * This shouldn't _actually_ be possible -- we're
16794 			 * unloading a module that has an enabled probe in it.
16795 			 * (It's normally up to the provider to make sure that
16796 			 * this can't happen.)  However, because dtps_enable()
16797 			 * doesn't have a failure mode, there can be an
16798 			 * enable/unload race.  Upshot:  we don't want to
16799 			 * assert, but we're not going to disable the
16800 			 * probe, either.
16801 			 */
16802 			if (dtrace_err_verbose) {
16803 #ifdef illumos
16804 				cmn_err(CE_WARN, "unloaded module '%s' had "
16805 				    "enabled probes", ctl->mod_modname);
16806 #else
16807 				cmn_err(CE_WARN, "unloaded module '%s' had "
16808 				    "enabled probes", modname);
16809 #endif
16810 			}
16811 
16812 			return;
16813 		}
16814 	}
16815 
16816 	probe = first;
16817 
16818 	for (first = NULL; probe != NULL; probe = next) {
16819 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16820 
16821 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16822 
16823 		next = probe->dtpr_nextmod;
16824 		dtrace_hash_remove(dtrace_bymod, probe);
16825 		dtrace_hash_remove(dtrace_byfunc, probe);
16826 		dtrace_hash_remove(dtrace_byname, probe);
16827 
16828 		if (first == NULL) {
16829 			first = probe;
16830 			probe->dtpr_nextmod = NULL;
16831 		} else {
16832 			probe->dtpr_nextmod = first;
16833 			first = probe;
16834 		}
16835 	}
16836 
16837 	/*
16838 	 * We've removed all of the module's probes from the hash chains and
16839 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16840 	 * everyone has cleared out from any probe array processing.
16841 	 */
16842 	dtrace_sync();
16843 
16844 	for (probe = first; probe != NULL; probe = first) {
16845 		first = probe->dtpr_nextmod;
16846 		prov = probe->dtpr_provider;
16847 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16848 		    probe->dtpr_arg);
16849 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16850 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16851 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16852 #ifdef illumos
16853 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16854 #else
16855 		free_unr(dtrace_arena, probe->dtpr_id);
16856 #endif
16857 		kmem_free(probe, sizeof (dtrace_probe_t));
16858 	}
16859 
16860 	mutex_exit(&dtrace_lock);
16861 #ifdef illumos
16862 	mutex_exit(&mod_lock);
16863 #endif
16864 	mutex_exit(&dtrace_provider_lock);
16865 }
16866 
16867 #ifndef illumos
16868 static void
16869 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16870 {
16871 
16872 	dtrace_module_loaded(lf);
16873 }
16874 
16875 static void
16876 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16877 {
16878 
16879 	if (*error != 0)
16880 		/* We already have an error, so don't do anything. */
16881 		return;
16882 	dtrace_module_unloaded(lf, error);
16883 }
16884 #endif
16885 
16886 #ifdef illumos
16887 static void
16888 dtrace_suspend(void)
16889 {
16890 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16891 }
16892 
16893 static void
16894 dtrace_resume(void)
16895 {
16896 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16897 }
16898 #endif
16899 
16900 static int
16901 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16902 {
16903 	ASSERT(MUTEX_HELD(&cpu_lock));
16904 	mutex_enter(&dtrace_lock);
16905 
16906 	switch (what) {
16907 	case CPU_CONFIG: {
16908 		dtrace_state_t *state;
16909 		dtrace_optval_t *opt, rs, c;
16910 
16911 		/*
16912 		 * For now, we only allocate a new buffer for anonymous state.
16913 		 */
16914 		if ((state = dtrace_anon.dta_state) == NULL)
16915 			break;
16916 
16917 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16918 			break;
16919 
16920 		opt = state->dts_options;
16921 		c = opt[DTRACEOPT_CPU];
16922 
16923 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16924 			break;
16925 
16926 		/*
16927 		 * Regardless of what the actual policy is, we're going to
16928 		 * temporarily set our resize policy to be manual.  We're
16929 		 * also going to temporarily set our CPU option to denote
16930 		 * the newly configured CPU.
16931 		 */
16932 		rs = opt[DTRACEOPT_BUFRESIZE];
16933 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16934 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16935 
16936 		(void) dtrace_state_buffers(state);
16937 
16938 		opt[DTRACEOPT_BUFRESIZE] = rs;
16939 		opt[DTRACEOPT_CPU] = c;
16940 
16941 		break;
16942 	}
16943 
16944 	case CPU_UNCONFIG:
16945 		/*
16946 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16947 		 * buffer will be freed when the consumer exits.)
16948 		 */
16949 		break;
16950 
16951 	default:
16952 		break;
16953 	}
16954 
16955 	mutex_exit(&dtrace_lock);
16956 	return (0);
16957 }
16958 
16959 #ifdef illumos
16960 static void
16961 dtrace_cpu_setup_initial(processorid_t cpu)
16962 {
16963 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16964 }
16965 #endif
16966 
16967 static void
16968 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16969 {
16970 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16971 		int osize, nsize;
16972 		dtrace_toxrange_t *range;
16973 
16974 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16975 
16976 		if (osize == 0) {
16977 			ASSERT(dtrace_toxrange == NULL);
16978 			ASSERT(dtrace_toxranges_max == 0);
16979 			dtrace_toxranges_max = 1;
16980 		} else {
16981 			dtrace_toxranges_max <<= 1;
16982 		}
16983 
16984 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16985 		range = kmem_zalloc(nsize, KM_SLEEP);
16986 
16987 		if (dtrace_toxrange != NULL) {
16988 			ASSERT(osize != 0);
16989 			bcopy(dtrace_toxrange, range, osize);
16990 			kmem_free(dtrace_toxrange, osize);
16991 		}
16992 
16993 		dtrace_toxrange = range;
16994 	}
16995 
16996 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16997 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16998 
16999 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17000 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17001 	dtrace_toxranges++;
17002 }
17003 
17004 static void
17005 dtrace_getf_barrier(void)
17006 {
17007 #ifdef illumos
17008 	/*
17009 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17010 	 * that contain calls to getf(), this routine will be called on every
17011 	 * closef() before either the underlying vnode is released or the
17012 	 * file_t itself is freed.  By the time we are here, it is essential
17013 	 * that the file_t can no longer be accessed from a call to getf()
17014 	 * in probe context -- that assures that a dtrace_sync() can be used
17015 	 * to clear out any enablings referring to the old structures.
17016 	 */
17017 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17018 	    kcred->cr_zone->zone_dtrace_getf != 0)
17019 		dtrace_sync();
17020 #endif
17021 }
17022 
17023 /*
17024  * DTrace Driver Cookbook Functions
17025  */
17026 #ifdef illumos
17027 /*ARGSUSED*/
17028 static int
17029 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17030 {
17031 	dtrace_provider_id_t id;
17032 	dtrace_state_t *state = NULL;
17033 	dtrace_enabling_t *enab;
17034 
17035 	mutex_enter(&cpu_lock);
17036 	mutex_enter(&dtrace_provider_lock);
17037 	mutex_enter(&dtrace_lock);
17038 
17039 	if (ddi_soft_state_init(&dtrace_softstate,
17040 	    sizeof (dtrace_state_t), 0) != 0) {
17041 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17042 		mutex_exit(&cpu_lock);
17043 		mutex_exit(&dtrace_provider_lock);
17044 		mutex_exit(&dtrace_lock);
17045 		return (DDI_FAILURE);
17046 	}
17047 
17048 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17049 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17050 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17051 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17052 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17053 		ddi_remove_minor_node(devi, NULL);
17054 		ddi_soft_state_fini(&dtrace_softstate);
17055 		mutex_exit(&cpu_lock);
17056 		mutex_exit(&dtrace_provider_lock);
17057 		mutex_exit(&dtrace_lock);
17058 		return (DDI_FAILURE);
17059 	}
17060 
17061 	ddi_report_dev(devi);
17062 	dtrace_devi = devi;
17063 
17064 	dtrace_modload = dtrace_module_loaded;
17065 	dtrace_modunload = dtrace_module_unloaded;
17066 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17067 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17068 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17069 	dtrace_cpustart_init = dtrace_suspend;
17070 	dtrace_cpustart_fini = dtrace_resume;
17071 	dtrace_debugger_init = dtrace_suspend;
17072 	dtrace_debugger_fini = dtrace_resume;
17073 
17074 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17075 
17076 	ASSERT(MUTEX_HELD(&cpu_lock));
17077 
17078 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17079 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17080 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17081 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17082 	    VM_SLEEP | VMC_IDENTIFIER);
17083 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17084 	    1, INT_MAX, 0);
17085 
17086 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17087 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17088 	    NULL, NULL, NULL, NULL, NULL, 0);
17089 
17090 	ASSERT(MUTEX_HELD(&cpu_lock));
17091 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17092 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17093 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17094 
17095 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17096 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17097 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17098 
17099 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17100 	    offsetof(dtrace_probe_t, dtpr_nextname),
17101 	    offsetof(dtrace_probe_t, dtpr_prevname));
17102 
17103 	if (dtrace_retain_max < 1) {
17104 		cmn_err(CE_WARN, "illegal value (%zu) for dtrace_retain_max; "
17105 		    "setting to 1", dtrace_retain_max);
17106 		dtrace_retain_max = 1;
17107 	}
17108 
17109 	/*
17110 	 * Now discover our toxic ranges.
17111 	 */
17112 	dtrace_toxic_ranges(dtrace_toxrange_add);
17113 
17114 	/*
17115 	 * Before we register ourselves as a provider to our own framework,
17116 	 * we would like to assert that dtrace_provider is NULL -- but that's
17117 	 * not true if we were loaded as a dependency of a DTrace provider.
17118 	 * Once we've registered, we can assert that dtrace_provider is our
17119 	 * pseudo provider.
17120 	 */
17121 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17122 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17123 
17124 	ASSERT(dtrace_provider != NULL);
17125 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17126 
17127 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17128 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17129 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17130 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17131 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17132 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17133 
17134 	dtrace_anon_property();
17135 	mutex_exit(&cpu_lock);
17136 
17137 	/*
17138 	 * If there are already providers, we must ask them to provide their
17139 	 * probes, and then match any anonymous enabling against them.  Note
17140 	 * that there should be no other retained enablings at this time:
17141 	 * the only retained enablings at this time should be the anonymous
17142 	 * enabling.
17143 	 */
17144 	if (dtrace_anon.dta_enabling != NULL) {
17145 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17146 
17147 		dtrace_enabling_provide(NULL);
17148 		state = dtrace_anon.dta_state;
17149 
17150 		/*
17151 		 * We couldn't hold cpu_lock across the above call to
17152 		 * dtrace_enabling_provide(), but we must hold it to actually
17153 		 * enable the probes.  We have to drop all of our locks, pick
17154 		 * up cpu_lock, and regain our locks before matching the
17155 		 * retained anonymous enabling.
17156 		 */
17157 		mutex_exit(&dtrace_lock);
17158 		mutex_exit(&dtrace_provider_lock);
17159 
17160 		mutex_enter(&cpu_lock);
17161 		mutex_enter(&dtrace_provider_lock);
17162 		mutex_enter(&dtrace_lock);
17163 
17164 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17165 			(void) dtrace_enabling_match(enab, NULL);
17166 
17167 		mutex_exit(&cpu_lock);
17168 	}
17169 
17170 	mutex_exit(&dtrace_lock);
17171 	mutex_exit(&dtrace_provider_lock);
17172 
17173 	if (state != NULL) {
17174 		/*
17175 		 * If we created any anonymous state, set it going now.
17176 		 */
17177 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17178 	}
17179 
17180 	return (DDI_SUCCESS);
17181 }
17182 #endif	/* illumos */
17183 
17184 #ifndef illumos
17185 static void dtrace_dtr(void *);
17186 #endif
17187 
17188 /*ARGSUSED*/
17189 static int
17190 #ifdef illumos
17191 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17192 #else
17193 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17194 #endif
17195 {
17196 	dtrace_state_t *state;
17197 	uint32_t priv;
17198 	uid_t uid;
17199 	zoneid_t zoneid;
17200 
17201 #ifdef illumos
17202 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17203 		return (0);
17204 
17205 	/*
17206 	 * If this wasn't an open with the "helper" minor, then it must be
17207 	 * the "dtrace" minor.
17208 	 */
17209 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17210 		return (ENXIO);
17211 #else
17212 	cred_t *cred_p = NULL;
17213 	cred_p = dev->si_cred;
17214 
17215 	/*
17216 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17217 	 * caller lacks sufficient permission to do anything with DTrace.
17218 	 */
17219 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17220 	if (priv == DTRACE_PRIV_NONE) {
17221 #endif
17222 
17223 		return (EACCES);
17224 	}
17225 
17226 	/*
17227 	 * Ask all providers to provide all their probes.
17228 	 */
17229 	mutex_enter(&dtrace_provider_lock);
17230 	dtrace_probe_provide(NULL, NULL);
17231 	mutex_exit(&dtrace_provider_lock);
17232 
17233 	mutex_enter(&cpu_lock);
17234 	mutex_enter(&dtrace_lock);
17235 	dtrace_opens++;
17236 	dtrace_membar_producer();
17237 
17238 #ifdef illumos
17239 	/*
17240 	 * If the kernel debugger is active (that is, if the kernel debugger
17241 	 * modified text in some way), we won't allow the open.
17242 	 */
17243 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17244 		dtrace_opens--;
17245 		mutex_exit(&cpu_lock);
17246 		mutex_exit(&dtrace_lock);
17247 		return (EBUSY);
17248 	}
17249 
17250 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17251 		/*
17252 		 * If DTrace helper tracing is enabled, we need to allocate the
17253 		 * trace buffer and initialize the values.
17254 		 */
17255 		dtrace_helptrace_buffer =
17256 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17257 		dtrace_helptrace_next = 0;
17258 		dtrace_helptrace_wrapped = 0;
17259 		dtrace_helptrace_enable = 0;
17260 	}
17261 
17262 	state = dtrace_state_create(devp, cred_p);
17263 #else
17264 	state = dtrace_state_create(dev, NULL);
17265 	devfs_set_cdevpriv(state, dtrace_dtr);
17266 #endif
17267 
17268 	mutex_exit(&cpu_lock);
17269 
17270 	if (state == NULL) {
17271 #ifdef illumos
17272 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17273 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17274 #else
17275 		--dtrace_opens;
17276 #endif
17277 		mutex_exit(&dtrace_lock);
17278 		return (EAGAIN);
17279 	}
17280 
17281 	mutex_exit(&dtrace_lock);
17282 
17283 	return (0);
17284 }
17285 
17286 /*ARGSUSED*/
17287 #ifdef illumos
17288 static int
17289 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17290 #else
17291 static void
17292 dtrace_dtr(void *data)
17293 #endif
17294 {
17295 #ifdef illumos
17296 	minor_t minor = getminor(dev);
17297 	dtrace_state_t *state;
17298 #endif
17299 	dtrace_helptrace_t *buf = NULL;
17300 
17301 #ifdef illumos
17302 	if (minor == DTRACEMNRN_HELPER)
17303 		return (0);
17304 
17305 	state = ddi_get_soft_state(dtrace_softstate, minor);
17306 #else
17307 	dtrace_state_t *state = data;
17308 #endif
17309 
17310 	mutex_enter(&cpu_lock);
17311 	mutex_enter(&dtrace_lock);
17312 
17313 #ifdef illumos
17314 	if (state->dts_anon)
17315 #else
17316 	if (state != NULL && state->dts_anon)
17317 #endif
17318 	{
17319 		/*
17320 		 * There is anonymous state. Destroy that first.
17321 		 */
17322 		ASSERT(dtrace_anon.dta_state == NULL);
17323 		dtrace_state_destroy(state->dts_anon);
17324 	}
17325 
17326 	if (dtrace_helptrace_disable) {
17327 		/*
17328 		 * If we have been told to disable helper tracing, set the
17329 		 * buffer to NULL before calling into dtrace_state_destroy();
17330 		 * we take advantage of its dtrace_sync() to know that no
17331 		 * CPU is in probe context with enabled helper tracing
17332 		 * after it returns.
17333 		 */
17334 		buf = dtrace_helptrace_buffer;
17335 		dtrace_helptrace_buffer = NULL;
17336 	}
17337 
17338 #ifdef illumos
17339 	dtrace_state_destroy(state);
17340 #else
17341 	if (state != NULL) {
17342 		dtrace_state_destroy(state);
17343 		kmem_free(state, 0);
17344 	}
17345 #endif
17346 	ASSERT(dtrace_opens > 0);
17347 
17348 #ifdef illumos
17349 	/*
17350 	 * Only relinquish control of the kernel debugger interface when there
17351 	 * are no consumers and no anonymous enablings.
17352 	 */
17353 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17354 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17355 #else
17356 	--dtrace_opens;
17357 #endif
17358 
17359 	if (buf != NULL) {
17360 		kmem_free(buf, dtrace_helptrace_bufsize);
17361 		dtrace_helptrace_disable = 0;
17362 	}
17363 
17364 	mutex_exit(&dtrace_lock);
17365 	mutex_exit(&cpu_lock);
17366 
17367 #ifdef illumos
17368 	return (0);
17369 #endif
17370 }
17371 
17372 #ifdef illumos
17373 /*ARGSUSED*/
17374 static int
17375 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17376 {
17377 	int rval;
17378 	dof_helper_t help, *dhp = NULL;
17379 
17380 	switch (cmd) {
17381 	case DTRACEHIOC_ADDDOF:
17382 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17383 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17384 			return (EFAULT);
17385 		}
17386 
17387 		dhp = &help;
17388 		arg = (intptr_t)help.dofhp_dof;
17389 		/*FALLTHROUGH*/
17390 
17391 	case DTRACEHIOC_ADD: {
17392 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17393 
17394 		if (dof == NULL)
17395 			return (rval);
17396 
17397 		mutex_enter(&dtrace_lock);
17398 
17399 		/*
17400 		 * dtrace_helper_slurp() takes responsibility for the dof --
17401 		 * it may free it now or it may save it and free it later.
17402 		 */
17403 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17404 			*rv = rval;
17405 			rval = 0;
17406 		} else {
17407 			rval = EINVAL;
17408 		}
17409 
17410 		mutex_exit(&dtrace_lock);
17411 		return (rval);
17412 	}
17413 
17414 	case DTRACEHIOC_REMOVE: {
17415 		mutex_enter(&dtrace_lock);
17416 		rval = dtrace_helper_destroygen(NULL, arg);
17417 		mutex_exit(&dtrace_lock);
17418 
17419 		return (rval);
17420 	}
17421 
17422 	default:
17423 		break;
17424 	}
17425 
17426 	return (ENOTTY);
17427 }
17428 
17429 /*ARGSUSED*/
17430 static int
17431 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17432 {
17433 	minor_t minor = getminor(dev);
17434 	dtrace_state_t *state;
17435 	int rval;
17436 
17437 	if (minor == DTRACEMNRN_HELPER)
17438 		return (dtrace_ioctl_helper(cmd, arg, rv));
17439 
17440 	state = ddi_get_soft_state(dtrace_softstate, minor);
17441 
17442 	if (state->dts_anon) {
17443 		ASSERT(dtrace_anon.dta_state == NULL);
17444 		state = state->dts_anon;
17445 	}
17446 
17447 	switch (cmd) {
17448 	case DTRACEIOC_PROVIDER: {
17449 		dtrace_providerdesc_t pvd;
17450 		dtrace_provider_t *pvp;
17451 
17452 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17453 			return (EFAULT);
17454 
17455 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17456 		mutex_enter(&dtrace_provider_lock);
17457 
17458 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17459 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17460 				break;
17461 		}
17462 
17463 		mutex_exit(&dtrace_provider_lock);
17464 
17465 		if (pvp == NULL)
17466 			return (ESRCH);
17467 
17468 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17469 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17470 
17471 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17472 			return (EFAULT);
17473 
17474 		return (0);
17475 	}
17476 
17477 	case DTRACEIOC_EPROBE: {
17478 		dtrace_eprobedesc_t epdesc;
17479 		dtrace_ecb_t *ecb;
17480 		dtrace_action_t *act;
17481 		void *buf;
17482 		size_t size;
17483 		uintptr_t dest;
17484 		int nrecs;
17485 
17486 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17487 			return (EFAULT);
17488 
17489 		mutex_enter(&dtrace_lock);
17490 
17491 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17492 			mutex_exit(&dtrace_lock);
17493 			return (EINVAL);
17494 		}
17495 
17496 		if (ecb->dte_probe == NULL) {
17497 			mutex_exit(&dtrace_lock);
17498 			return (EINVAL);
17499 		}
17500 
17501 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17502 		epdesc.dtepd_uarg = ecb->dte_uarg;
17503 		epdesc.dtepd_size = ecb->dte_size;
17504 
17505 		nrecs = epdesc.dtepd_nrecs;
17506 		epdesc.dtepd_nrecs = 0;
17507 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17508 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17509 				continue;
17510 
17511 			epdesc.dtepd_nrecs++;
17512 		}
17513 
17514 		/*
17515 		 * Now that we have the size, we need to allocate a temporary
17516 		 * buffer in which to store the complete description.  We need
17517 		 * the temporary buffer to be able to drop dtrace_lock()
17518 		 * across the copyout(), below.
17519 		 */
17520 		size = sizeof (dtrace_eprobedesc_t) +
17521 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17522 
17523 		buf = kmem_alloc(size, KM_SLEEP);
17524 		dest = (uintptr_t)buf;
17525 
17526 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17527 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17528 
17529 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17530 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17531 				continue;
17532 
17533 			if (nrecs-- == 0)
17534 				break;
17535 
17536 			bcopy(&act->dta_rec, (void *)dest,
17537 			    sizeof (dtrace_recdesc_t));
17538 			dest += sizeof (dtrace_recdesc_t);
17539 		}
17540 
17541 		mutex_exit(&dtrace_lock);
17542 
17543 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17544 			kmem_free(buf, size);
17545 			return (EFAULT);
17546 		}
17547 
17548 		kmem_free(buf, size);
17549 		return (0);
17550 	}
17551 
17552 	case DTRACEIOC_AGGDESC: {
17553 		dtrace_aggdesc_t aggdesc;
17554 		dtrace_action_t *act;
17555 		dtrace_aggregation_t *agg;
17556 		int nrecs;
17557 		uint32_t offs;
17558 		dtrace_recdesc_t *lrec;
17559 		void *buf;
17560 		size_t size;
17561 		uintptr_t dest;
17562 
17563 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17564 			return (EFAULT);
17565 
17566 		mutex_enter(&dtrace_lock);
17567 
17568 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17569 			mutex_exit(&dtrace_lock);
17570 			return (EINVAL);
17571 		}
17572 
17573 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17574 
17575 		nrecs = aggdesc.dtagd_nrecs;
17576 		aggdesc.dtagd_nrecs = 0;
17577 
17578 		offs = agg->dtag_base;
17579 		lrec = &agg->dtag_action.dta_rec;
17580 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17581 
17582 		for (act = agg->dtag_first; ; act = act->dta_next) {
17583 			ASSERT(act->dta_intuple ||
17584 			    DTRACEACT_ISAGG(act->dta_kind));
17585 
17586 			/*
17587 			 * If this action has a record size of zero, it
17588 			 * denotes an argument to the aggregating action.
17589 			 * Because the presence of this record doesn't (or
17590 			 * shouldn't) affect the way the data is interpreted,
17591 			 * we don't copy it out to save user-level the
17592 			 * confusion of dealing with a zero-length record.
17593 			 */
17594 			if (act->dta_rec.dtrd_size == 0) {
17595 				ASSERT(agg->dtag_hasarg);
17596 				continue;
17597 			}
17598 
17599 			aggdesc.dtagd_nrecs++;
17600 
17601 			if (act == &agg->dtag_action)
17602 				break;
17603 		}
17604 
17605 		/*
17606 		 * Now that we have the size, we need to allocate a temporary
17607 		 * buffer in which to store the complete description.  We need
17608 		 * the temporary buffer to be able to drop dtrace_lock()
17609 		 * across the copyout(), below.
17610 		 */
17611 		size = sizeof (dtrace_aggdesc_t) +
17612 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17613 
17614 		buf = kmem_alloc(size, KM_SLEEP);
17615 		dest = (uintptr_t)buf;
17616 
17617 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17618 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17619 
17620 		for (act = agg->dtag_first; ; act = act->dta_next) {
17621 			dtrace_recdesc_t rec = act->dta_rec;
17622 
17623 			/*
17624 			 * See the comment in the above loop for why we pass
17625 			 * over zero-length records.
17626 			 */
17627 			if (rec.dtrd_size == 0) {
17628 				ASSERT(agg->dtag_hasarg);
17629 				continue;
17630 			}
17631 
17632 			if (nrecs-- == 0)
17633 				break;
17634 
17635 			rec.dtrd_offset -= offs;
17636 			bcopy(&rec, (void *)dest, sizeof (rec));
17637 			dest += sizeof (dtrace_recdesc_t);
17638 
17639 			if (act == &agg->dtag_action)
17640 				break;
17641 		}
17642 
17643 		mutex_exit(&dtrace_lock);
17644 
17645 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17646 			kmem_free(buf, size);
17647 			return (EFAULT);
17648 		}
17649 
17650 		kmem_free(buf, size);
17651 		return (0);
17652 	}
17653 
17654 	case DTRACEIOC_ENABLE: {
17655 		dof_hdr_t *dof;
17656 		dtrace_enabling_t *enab = NULL;
17657 		dtrace_vstate_t *vstate;
17658 		int err = 0;
17659 
17660 		*rv = 0;
17661 
17662 		/*
17663 		 * If a NULL argument has been passed, we take this as our
17664 		 * cue to reevaluate our enablings.
17665 		 */
17666 		if (arg == NULL) {
17667 			dtrace_enabling_matchall();
17668 
17669 			return (0);
17670 		}
17671 
17672 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17673 			return (rval);
17674 
17675 		mutex_enter(&cpu_lock);
17676 		mutex_enter(&dtrace_lock);
17677 		vstate = &state->dts_vstate;
17678 
17679 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17680 			mutex_exit(&dtrace_lock);
17681 			mutex_exit(&cpu_lock);
17682 			dtrace_dof_destroy(dof);
17683 			return (EBUSY);
17684 		}
17685 
17686 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17687 			mutex_exit(&dtrace_lock);
17688 			mutex_exit(&cpu_lock);
17689 			dtrace_dof_destroy(dof);
17690 			return (EINVAL);
17691 		}
17692 
17693 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17694 			dtrace_enabling_destroy(enab);
17695 			mutex_exit(&dtrace_lock);
17696 			mutex_exit(&cpu_lock);
17697 			dtrace_dof_destroy(dof);
17698 			return (rval);
17699 		}
17700 
17701 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17702 			err = dtrace_enabling_retain(enab);
17703 		} else {
17704 			dtrace_enabling_destroy(enab);
17705 		}
17706 
17707 		mutex_exit(&cpu_lock);
17708 		mutex_exit(&dtrace_lock);
17709 		dtrace_dof_destroy(dof);
17710 
17711 		return (err);
17712 	}
17713 
17714 	case DTRACEIOC_REPLICATE: {
17715 		dtrace_repldesc_t desc;
17716 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17717 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17718 		int err;
17719 
17720 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17721 			return (EFAULT);
17722 
17723 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17724 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17725 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17726 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17727 
17728 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17729 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17730 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17731 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17732 
17733 		mutex_enter(&dtrace_lock);
17734 		err = dtrace_enabling_replicate(state, match, create);
17735 		mutex_exit(&dtrace_lock);
17736 
17737 		return (err);
17738 	}
17739 
17740 	case DTRACEIOC_PROBEMATCH:
17741 	case DTRACEIOC_PROBES: {
17742 		dtrace_probe_t *probe = NULL;
17743 		dtrace_probedesc_t desc;
17744 		dtrace_probekey_t pkey;
17745 		dtrace_id_t i;
17746 		int m = 0;
17747 		uint32_t priv;
17748 		uid_t uid;
17749 		zoneid_t zoneid;
17750 
17751 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17752 			return (EFAULT);
17753 
17754 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17755 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17756 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17757 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17758 
17759 		/*
17760 		 * Before we attempt to match this probe, we want to give
17761 		 * all providers the opportunity to provide it.
17762 		 */
17763 		if (desc.dtpd_id == DTRACE_IDNONE) {
17764 			mutex_enter(&dtrace_provider_lock);
17765 			dtrace_probe_provide(&desc, NULL);
17766 			mutex_exit(&dtrace_provider_lock);
17767 			desc.dtpd_id++;
17768 		}
17769 
17770 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17771 			dtrace_probekey(&desc, &pkey);
17772 			pkey.dtpk_id = DTRACE_IDNONE;
17773 		}
17774 
17775 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17776 
17777 		mutex_enter(&dtrace_lock);
17778 
17779 		if (cmd == DTRACEIOC_PROBEMATCH) {
17780 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17781 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17782 				    (m = dtrace_match_probe(probe, &pkey,
17783 				    priv, uid, zoneid)) != 0)
17784 					break;
17785 			}
17786 
17787 			if (m < 0) {
17788 				mutex_exit(&dtrace_lock);
17789 				return (EINVAL);
17790 			}
17791 
17792 		} else {
17793 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17794 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17795 				    dtrace_match_priv(probe, priv, uid, zoneid))
17796 					break;
17797 			}
17798 		}
17799 
17800 		if (probe == NULL) {
17801 			mutex_exit(&dtrace_lock);
17802 			return (ESRCH);
17803 		}
17804 
17805 		dtrace_probe_description(probe, &desc);
17806 		mutex_exit(&dtrace_lock);
17807 
17808 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17809 			return (EFAULT);
17810 
17811 		return (0);
17812 	}
17813 
17814 	case DTRACEIOC_PROBEARG: {
17815 		dtrace_argdesc_t desc;
17816 		dtrace_probe_t *probe;
17817 		dtrace_provider_t *prov;
17818 
17819 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17820 			return (EFAULT);
17821 
17822 		if (desc.dtargd_id == DTRACE_IDNONE)
17823 			return (EINVAL);
17824 
17825 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17826 			return (EINVAL);
17827 
17828 		mutex_enter(&dtrace_provider_lock);
17829 		mutex_enter(&mod_lock);
17830 		mutex_enter(&dtrace_lock);
17831 
17832 		if (desc.dtargd_id > dtrace_nprobes) {
17833 			mutex_exit(&dtrace_lock);
17834 			mutex_exit(&mod_lock);
17835 			mutex_exit(&dtrace_provider_lock);
17836 			return (EINVAL);
17837 		}
17838 
17839 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17840 			mutex_exit(&dtrace_lock);
17841 			mutex_exit(&mod_lock);
17842 			mutex_exit(&dtrace_provider_lock);
17843 			return (EINVAL);
17844 		}
17845 
17846 		mutex_exit(&dtrace_lock);
17847 
17848 		prov = probe->dtpr_provider;
17849 
17850 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17851 			/*
17852 			 * There isn't any typed information for this probe.
17853 			 * Set the argument number to DTRACE_ARGNONE.
17854 			 */
17855 			desc.dtargd_ndx = DTRACE_ARGNONE;
17856 		} else {
17857 			desc.dtargd_native[0] = '\0';
17858 			desc.dtargd_xlate[0] = '\0';
17859 			desc.dtargd_mapping = desc.dtargd_ndx;
17860 
17861 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17862 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17863 		}
17864 
17865 		mutex_exit(&mod_lock);
17866 		mutex_exit(&dtrace_provider_lock);
17867 
17868 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17869 			return (EFAULT);
17870 
17871 		return (0);
17872 	}
17873 
17874 	case DTRACEIOC_GO: {
17875 		processorid_t cpuid;
17876 		rval = dtrace_state_go(state, &cpuid);
17877 
17878 		if (rval != 0)
17879 			return (rval);
17880 
17881 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17882 			return (EFAULT);
17883 
17884 		return (0);
17885 	}
17886 
17887 	case DTRACEIOC_STOP: {
17888 		processorid_t cpuid;
17889 
17890 		mutex_enter(&dtrace_lock);
17891 		rval = dtrace_state_stop(state, &cpuid);
17892 		mutex_exit(&dtrace_lock);
17893 
17894 		if (rval != 0)
17895 			return (rval);
17896 
17897 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17898 			return (EFAULT);
17899 
17900 		return (0);
17901 	}
17902 
17903 	case DTRACEIOC_DOFGET: {
17904 		dof_hdr_t hdr, *dof;
17905 		uint64_t len;
17906 
17907 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17908 			return (EFAULT);
17909 
17910 		mutex_enter(&dtrace_lock);
17911 		dof = dtrace_dof_create(state);
17912 		mutex_exit(&dtrace_lock);
17913 
17914 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17915 		rval = copyout(dof, (void *)arg, len);
17916 		dtrace_dof_destroy(dof);
17917 
17918 		return (rval == 0 ? 0 : EFAULT);
17919 	}
17920 
17921 	case DTRACEIOC_AGGSNAP:
17922 	case DTRACEIOC_BUFSNAP: {
17923 		dtrace_bufdesc_t desc;
17924 		caddr_t cached;
17925 		dtrace_buffer_t *buf;
17926 
17927 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17928 			return (EFAULT);
17929 
17930 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17931 			return (EINVAL);
17932 
17933 		mutex_enter(&dtrace_lock);
17934 
17935 		if (cmd == DTRACEIOC_BUFSNAP) {
17936 			buf = &state->dts_buffer[desc.dtbd_cpu];
17937 		} else {
17938 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17939 		}
17940 
17941 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17942 			size_t sz = buf->dtb_offset;
17943 
17944 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17945 				mutex_exit(&dtrace_lock);
17946 				return (EBUSY);
17947 			}
17948 
17949 			/*
17950 			 * If this buffer has already been consumed, we're
17951 			 * going to indicate that there's nothing left here
17952 			 * to consume.
17953 			 */
17954 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17955 				mutex_exit(&dtrace_lock);
17956 
17957 				desc.dtbd_size = 0;
17958 				desc.dtbd_drops = 0;
17959 				desc.dtbd_errors = 0;
17960 				desc.dtbd_oldest = 0;
17961 				sz = sizeof (desc);
17962 
17963 				if (copyout(&desc, (void *)arg, sz) != 0)
17964 					return (EFAULT);
17965 
17966 				return (0);
17967 			}
17968 
17969 			/*
17970 			 * If this is a ring buffer that has wrapped, we want
17971 			 * to copy the whole thing out.
17972 			 */
17973 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17974 				dtrace_buffer_polish(buf);
17975 				sz = buf->dtb_size;
17976 			}
17977 
17978 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17979 				mutex_exit(&dtrace_lock);
17980 				return (EFAULT);
17981 			}
17982 
17983 			desc.dtbd_size = sz;
17984 			desc.dtbd_drops = buf->dtb_drops;
17985 			desc.dtbd_errors = buf->dtb_errors;
17986 			desc.dtbd_oldest = buf->dtb_xamot_offset;
17987 			desc.dtbd_timestamp = dtrace_gethrtime();
17988 
17989 			mutex_exit(&dtrace_lock);
17990 
17991 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17992 				return (EFAULT);
17993 
17994 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
17995 
17996 			return (0);
17997 		}
17998 
17999 		if (buf->dtb_tomax == NULL) {
18000 			ASSERT(buf->dtb_xamot == NULL);
18001 			mutex_exit(&dtrace_lock);
18002 			return (ENOENT);
18003 		}
18004 
18005 		cached = buf->dtb_tomax;
18006 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18007 
18008 		dtrace_xcall(desc.dtbd_cpu,
18009 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18010 
18011 		state->dts_errors += buf->dtb_xamot_errors;
18012 
18013 		/*
18014 		 * If the buffers did not actually switch, then the cross call
18015 		 * did not take place -- presumably because the given CPU is
18016 		 * not in the ready set.  If this is the case, we'll return
18017 		 * ENOENT.
18018 		 */
18019 		if (buf->dtb_tomax == cached) {
18020 			ASSERT(buf->dtb_xamot != cached);
18021 			mutex_exit(&dtrace_lock);
18022 			return (ENOENT);
18023 		}
18024 
18025 		ASSERT(cached == buf->dtb_xamot);
18026 
18027 		/*
18028 		 * We have our snapshot; now copy it out.
18029 		 */
18030 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18031 		    buf->dtb_xamot_offset) != 0) {
18032 			mutex_exit(&dtrace_lock);
18033 			return (EFAULT);
18034 		}
18035 
18036 		desc.dtbd_size = buf->dtb_xamot_offset;
18037 		desc.dtbd_drops = buf->dtb_xamot_drops;
18038 		desc.dtbd_errors = buf->dtb_xamot_errors;
18039 		desc.dtbd_oldest = 0;
18040 		desc.dtbd_timestamp = buf->dtb_switched;
18041 
18042 		mutex_exit(&dtrace_lock);
18043 
18044 		/*
18045 		 * Finally, copy out the buffer description.
18046 		 */
18047 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18048 			return (EFAULT);
18049 
18050 		return (0);
18051 	}
18052 
18053 	case DTRACEIOC_CONF: {
18054 		dtrace_conf_t conf;
18055 
18056 		bzero(&conf, sizeof (conf));
18057 		conf.dtc_difversion = DIF_VERSION;
18058 		conf.dtc_difintregs = DIF_DIR_NREGS;
18059 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18060 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18061 
18062 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18063 			return (EFAULT);
18064 
18065 		return (0);
18066 	}
18067 
18068 	case DTRACEIOC_STATUS: {
18069 		dtrace_status_t stat;
18070 		dtrace_dstate_t *dstate;
18071 		int i, j;
18072 		uint64_t nerrs;
18073 
18074 		/*
18075 		 * See the comment in dtrace_state_deadman() for the reason
18076 		 * for setting dts_laststatus to INT64_MAX before setting
18077 		 * it to the correct value.
18078 		 */
18079 		state->dts_laststatus = INT64_MAX;
18080 		dtrace_membar_producer();
18081 		state->dts_laststatus = dtrace_gethrtime();
18082 
18083 		bzero(&stat, sizeof (stat));
18084 
18085 		mutex_enter(&dtrace_lock);
18086 
18087 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18088 			mutex_exit(&dtrace_lock);
18089 			return (ENOENT);
18090 		}
18091 
18092 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18093 			stat.dtst_exiting = 1;
18094 
18095 		nerrs = state->dts_errors;
18096 		dstate = &state->dts_vstate.dtvs_dynvars;
18097 
18098 		for (i = 0; i < NCPU; i++) {
18099 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18100 
18101 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18102 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18103 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18104 
18105 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18106 				stat.dtst_filled++;
18107 
18108 			nerrs += state->dts_buffer[i].dtb_errors;
18109 
18110 			for (j = 0; j < state->dts_nspeculations; j++) {
18111 				dtrace_speculation_t *spec;
18112 				dtrace_buffer_t *buf;
18113 
18114 				spec = &state->dts_speculations[j];
18115 				buf = &spec->dtsp_buffer[i];
18116 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18117 			}
18118 		}
18119 
18120 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18121 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18122 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18123 		stat.dtst_dblerrors = state->dts_dblerrors;
18124 		stat.dtst_killed =
18125 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18126 		stat.dtst_errors = nerrs;
18127 
18128 		mutex_exit(&dtrace_lock);
18129 
18130 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18131 			return (EFAULT);
18132 
18133 		return (0);
18134 	}
18135 
18136 	case DTRACEIOC_FORMAT: {
18137 		dtrace_fmtdesc_t fmt;
18138 		char *str;
18139 		int len;
18140 
18141 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18142 			return (EFAULT);
18143 
18144 		mutex_enter(&dtrace_lock);
18145 
18146 		if (fmt.dtfd_format == 0 ||
18147 		    fmt.dtfd_format > state->dts_nformats) {
18148 			mutex_exit(&dtrace_lock);
18149 			return (EINVAL);
18150 		}
18151 
18152 		/*
18153 		 * Format strings are allocated contiguously and they are
18154 		 * never freed; if a format index is less than the number
18155 		 * of formats, we can assert that the format map is non-NULL
18156 		 * and that the format for the specified index is non-NULL.
18157 		 */
18158 		ASSERT(state->dts_formats != NULL);
18159 		str = state->dts_formats[fmt.dtfd_format - 1];
18160 		ASSERT(str != NULL);
18161 
18162 		len = strlen(str) + 1;
18163 
18164 		if (len > fmt.dtfd_length) {
18165 			fmt.dtfd_length = len;
18166 
18167 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18168 				mutex_exit(&dtrace_lock);
18169 				return (EINVAL);
18170 			}
18171 		} else {
18172 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18173 				mutex_exit(&dtrace_lock);
18174 				return (EINVAL);
18175 			}
18176 		}
18177 
18178 		mutex_exit(&dtrace_lock);
18179 		return (0);
18180 	}
18181 
18182 	default:
18183 		break;
18184 	}
18185 
18186 	return (ENOTTY);
18187 }
18188 
18189 /*ARGSUSED*/
18190 static int
18191 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18192 {
18193 	dtrace_state_t *state;
18194 
18195 	switch (cmd) {
18196 	case DDI_DETACH:
18197 		break;
18198 
18199 	case DDI_SUSPEND:
18200 		return (DDI_SUCCESS);
18201 
18202 	default:
18203 		return (DDI_FAILURE);
18204 	}
18205 
18206 	mutex_enter(&cpu_lock);
18207 	mutex_enter(&dtrace_provider_lock);
18208 	mutex_enter(&dtrace_lock);
18209 
18210 	ASSERT(dtrace_opens == 0);
18211 
18212 	if (dtrace_helpers > 0) {
18213 		mutex_exit(&dtrace_provider_lock);
18214 		mutex_exit(&dtrace_lock);
18215 		mutex_exit(&cpu_lock);
18216 		return (DDI_FAILURE);
18217 	}
18218 
18219 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18220 		mutex_exit(&dtrace_provider_lock);
18221 		mutex_exit(&dtrace_lock);
18222 		mutex_exit(&cpu_lock);
18223 		return (DDI_FAILURE);
18224 	}
18225 
18226 	dtrace_provider = NULL;
18227 
18228 	if ((state = dtrace_anon_grab()) != NULL) {
18229 		/*
18230 		 * If there were ECBs on this state, the provider should
18231 		 * have not been allowed to detach; assert that there is
18232 		 * none.
18233 		 */
18234 		ASSERT(state->dts_necbs == 0);
18235 		dtrace_state_destroy(state);
18236 
18237 		/*
18238 		 * If we're being detached with anonymous state, we need to
18239 		 * indicate to the kernel debugger that DTrace is now inactive.
18240 		 */
18241 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18242 	}
18243 
18244 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18245 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18246 	dtrace_cpu_init = NULL;
18247 	dtrace_helpers_cleanup = NULL;
18248 	dtrace_helpers_fork = NULL;
18249 	dtrace_cpustart_init = NULL;
18250 	dtrace_cpustart_fini = NULL;
18251 	dtrace_debugger_init = NULL;
18252 	dtrace_debugger_fini = NULL;
18253 	dtrace_modload = NULL;
18254 	dtrace_modunload = NULL;
18255 
18256 	ASSERT(dtrace_getf == 0);
18257 	ASSERT(dtrace_closef == NULL);
18258 
18259 	mutex_exit(&cpu_lock);
18260 
18261 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18262 	dtrace_probes = NULL;
18263 	dtrace_nprobes = 0;
18264 
18265 	dtrace_hash_destroy(dtrace_bymod);
18266 	dtrace_hash_destroy(dtrace_byfunc);
18267 	dtrace_hash_destroy(dtrace_byname);
18268 	dtrace_bymod = NULL;
18269 	dtrace_byfunc = NULL;
18270 	dtrace_byname = NULL;
18271 
18272 	kmem_cache_destroy(dtrace_state_cache);
18273 	vmem_destroy(dtrace_minor);
18274 	vmem_destroy(dtrace_arena);
18275 
18276 	if (dtrace_toxrange != NULL) {
18277 		kmem_free(dtrace_toxrange,
18278 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18279 		dtrace_toxrange = NULL;
18280 		dtrace_toxranges = 0;
18281 		dtrace_toxranges_max = 0;
18282 	}
18283 
18284 	ddi_remove_minor_node(dtrace_devi, NULL);
18285 	dtrace_devi = NULL;
18286 
18287 	ddi_soft_state_fini(&dtrace_softstate);
18288 
18289 	ASSERT(dtrace_vtime_references == 0);
18290 	ASSERT(dtrace_opens == 0);
18291 	ASSERT(dtrace_retained == NULL);
18292 
18293 	mutex_exit(&dtrace_lock);
18294 	mutex_exit(&dtrace_provider_lock);
18295 
18296 	/*
18297 	 * We don't destroy the task queue until after we have dropped our
18298 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18299 	 * attempting to do work after we have effectively detached but before
18300 	 * the task queue has been destroyed, all tasks dispatched via the
18301 	 * task queue must check that DTrace is still attached before
18302 	 * performing any operation.
18303 	 */
18304 	taskq_destroy(dtrace_taskq);
18305 	dtrace_taskq = NULL;
18306 
18307 	return (DDI_SUCCESS);
18308 }
18309 #endif
18310 
18311 #ifdef illumos
18312 /*ARGSUSED*/
18313 static int
18314 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18315 {
18316 	int error;
18317 
18318 	switch (infocmd) {
18319 	case DDI_INFO_DEVT2DEVINFO:
18320 		*result = (void *)dtrace_devi;
18321 		error = DDI_SUCCESS;
18322 		break;
18323 	case DDI_INFO_DEVT2INSTANCE:
18324 		*result = (void *)0;
18325 		error = DDI_SUCCESS;
18326 		break;
18327 	default:
18328 		error = DDI_FAILURE;
18329 	}
18330 	return (error);
18331 }
18332 #endif
18333 
18334 #ifdef illumos
18335 static struct cb_ops dtrace_cb_ops = {
18336 	dtrace_open,		/* open */
18337 	dtrace_close,		/* close */
18338 	nulldev,		/* strategy */
18339 	nulldev,		/* print */
18340 	nodev,			/* dump */
18341 	nodev,			/* read */
18342 	nodev,			/* write */
18343 	dtrace_ioctl,		/* ioctl */
18344 	nodev,			/* devmap */
18345 	nodev,			/* mmap */
18346 	nodev,			/* segmap */
18347 	nochpoll,		/* poll */
18348 	ddi_prop_op,		/* cb_prop_op */
18349 	0,			/* streamtab  */
18350 	D_NEW | D_MP		/* Driver compatibility flag */
18351 };
18352 
18353 static struct dev_ops dtrace_ops = {
18354 	DEVO_REV,		/* devo_rev */
18355 	0,			/* refcnt */
18356 	dtrace_info,		/* get_dev_info */
18357 	nulldev,		/* identify */
18358 	nulldev,		/* probe */
18359 	dtrace_attach,		/* attach */
18360 	dtrace_detach,		/* detach */
18361 	nodev,			/* reset */
18362 	&dtrace_cb_ops,		/* driver operations */
18363 	NULL,			/* bus operations */
18364 	nodev			/* dev power */
18365 };
18366 
18367 static struct modldrv modldrv = {
18368 	&mod_driverops,		/* module type (this is a pseudo driver) */
18369 	"Dynamic Tracing",	/* name of module */
18370 	&dtrace_ops,		/* driver ops */
18371 };
18372 
18373 static struct modlinkage modlinkage = {
18374 	MODREV_1,
18375 	(void *)&modldrv,
18376 	NULL
18377 };
18378 
18379 int
18380 _init(void)
18381 {
18382 	return (mod_install(&modlinkage));
18383 }
18384 
18385 int
18386 _info(struct modinfo *modinfop)
18387 {
18388 	return (mod_info(&modlinkage, modinfop));
18389 }
18390 
18391 int
18392 _fini(void)
18393 {
18394 	return (mod_remove(&modlinkage));
18395 }
18396 #else
18397 
18398 static d_ioctl_t	dtrace_ioctl;
18399 static d_ioctl_t	dtrace_ioctl_helper;
18400 static void		dtrace_load(void *);
18401 static int		dtrace_unload(void);
18402 static struct cdev	*dtrace_dev;
18403 static struct cdev	*helper_dev;
18404 
18405 void dtrace_invop_init(void);
18406 void dtrace_invop_uninit(void);
18407 
18408 static struct cdevsw dtrace_cdevsw = {
18409 	.d_version	= D_VERSION,
18410 	.d_ioctl	= dtrace_ioctl,
18411 	.d_open		= dtrace_open,
18412 	.d_name		= "dtrace",
18413 };
18414 
18415 static struct cdevsw helper_cdevsw = {
18416 	.d_version	= D_VERSION,
18417 	.d_ioctl	= dtrace_ioctl_helper,
18418 	.d_name		= "helper",
18419 };
18420 
18421 #include <dtrace_anon.c>
18422 #include <dtrace_ioctl.c>
18423 #include <dtrace_load.c>
18424 #include <dtrace_modevent.c>
18425 #include <dtrace_sysctl.c>
18426 #include <dtrace_unload.c>
18427 #include <dtrace_vtime.c>
18428 #include <dtrace_hacks.c>
18429 #include <dtrace_isa.c>
18430 
18431 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18432 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18433 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18434 
18435 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18436 MODULE_VERSION(dtrace, 1);
18437 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18438 #endif
18439