xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision 3877025f52ee205fe99ad4ff68229933d57e4bcb)
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
dtrace_nullop(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) + (size_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_INSCRATCHPTR(mstate, ptr, howmany) \
519 	((ptr) >= (mstate)->dtms_scratch_base && \
520 	(ptr) <= \
521 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - (howmany)))
522 
523 #define	DTRACE_LOADFUNC(bits)						\
524 /*CSTYLED*/								\
525 uint##bits##_t								\
526 dtrace_load##bits(uintptr_t addr)					\
527 {									\
528 	size_t size = bits / NBBY;					\
529 	/*CSTYLED*/							\
530 	uint##bits##_t rval;						\
531 	int i;								\
532 	volatile uint16_t *flags = (volatile uint16_t *)		\
533 	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
534 									\
535 	DTRACE_ALIGNCHECK(addr, size, flags);				\
536 									\
537 	for (i = 0; i < dtrace_toxranges; i++) {			\
538 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
539 			continue;					\
540 									\
541 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
542 			continue;					\
543 									\
544 		/*							\
545 		 * This address falls within a toxic region; return 0.	\
546 		 */							\
547 		*flags |= CPU_DTRACE_BADADDR;				\
548 		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
549 		return (0);						\
550 	}								\
551 									\
552 	__compiler_membar();						\
553 	*flags |= CPU_DTRACE_NOFAULT;					\
554 	/*CSTYLED*/							\
555 	rval = *((volatile uint##bits##_t *)addr);			\
556 	*flags &= ~CPU_DTRACE_NOFAULT;					\
557 	__compiler_membar();						\
558 									\
559 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
560 }
561 
562 #ifdef _LP64
563 #define	dtrace_loadptr	dtrace_load64
564 #else
565 #define	dtrace_loadptr	dtrace_load32
566 #endif
567 
568 #define	DTRACE_DYNHASH_FREE	0
569 #define	DTRACE_DYNHASH_SINK	1
570 #define	DTRACE_DYNHASH_VALID	2
571 
572 #define	DTRACE_MATCH_NEXT	0
573 #define	DTRACE_MATCH_DONE	1
574 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
575 #define	DTRACE_STATE_ALIGN	64
576 
577 #define	DTRACE_FLAGS2FLT(flags)						\
578 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
579 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
580 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
581 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
582 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
583 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
584 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
585 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
586 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
587 	DTRACEFLT_UNKNOWN)
588 
589 #define	DTRACEACT_ISSTRING(act)						\
590 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
591 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
592 
593 /* Function prototype definitions: */
594 static size_t dtrace_strlen(const char *, size_t);
595 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
596 static void dtrace_enabling_provide(dtrace_provider_t *);
597 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
598 static void dtrace_enabling_matchall(void);
599 static void dtrace_enabling_matchall_task(void *);
600 static void dtrace_enabling_reap(void *);
601 static dtrace_state_t *dtrace_anon_grab(void);
602 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
603     dtrace_state_t *, uint64_t, uint64_t);
604 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
605 static void dtrace_buffer_drop(dtrace_buffer_t *);
606 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
607 static ssize_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
608     dtrace_state_t *, dtrace_mstate_t *);
609 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
610     dtrace_optval_t);
611 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
612 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
613 uint16_t dtrace_load16(uintptr_t);
614 uint32_t dtrace_load32(uintptr_t);
615 uint64_t dtrace_load64(uintptr_t);
616 uint8_t dtrace_load8(uintptr_t);
617 void dtrace_dynvar_clean(dtrace_dstate_t *);
618 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
619     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
620 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
621 static int dtrace_priv_proc(dtrace_state_t *);
622 static void dtrace_getf_barrier(void);
623 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
624     dtrace_mstate_t *, dtrace_vstate_t *);
625 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
626     dtrace_mstate_t *, dtrace_vstate_t *);
627 
628 /*
629  * DTrace Probe Context Functions
630  *
631  * These functions are called from probe context.  Because probe context is
632  * any context in which C may be called, arbitrarily locks may be held,
633  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
634  * As a result, functions called from probe context may only call other DTrace
635  * support functions -- they may not interact at all with the system at large.
636  * (Note that the ASSERT macro is made probe-context safe by redefining it in
637  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
638  * loads are to be performed from probe context, they _must_ be in terms of
639  * the safe dtrace_load*() variants.
640  *
641  * Some functions in this block are not actually called from probe context;
642  * for these functions, there will be a comment above the function reading
643  * "Note:  not called from probe context."
644  */
645 void
dtrace_panic(const char * format,...)646 dtrace_panic(const char *format, ...)
647 {
648 	va_list alist;
649 
650 	va_start(alist, format);
651 #ifdef __FreeBSD__
652 	vpanic(format, alist);
653 #else
654 	dtrace_vpanic(format, alist);
655 #endif
656 	va_end(alist);
657 }
658 
659 int
dtrace_assfail(const char * a,const char * f,int l)660 dtrace_assfail(const char *a, const char *f, int l)
661 {
662 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
663 
664 	/*
665 	 * We just need something here that even the most clever compiler
666 	 * cannot optimize away.
667 	 */
668 	return (a[(uintptr_t)f]);
669 }
670 
671 /*
672  * Atomically increment a specified error counter from probe context.
673  */
674 static void
dtrace_error(uint32_t * counter)675 dtrace_error(uint32_t *counter)
676 {
677 	/*
678 	 * Most counters stored to in probe context are per-CPU counters.
679 	 * However, there are some error conditions that are sufficiently
680 	 * arcane that they don't merit per-CPU storage.  If these counters
681 	 * are incremented concurrently on different CPUs, scalability will be
682 	 * adversely affected -- but we don't expect them to be white-hot in a
683 	 * correctly constructed enabling...
684 	 */
685 	uint32_t oval, nval;
686 
687 	do {
688 		oval = *counter;
689 
690 		if ((nval = oval + 1) == 0) {
691 			/*
692 			 * If the counter would wrap, set it to 1 -- assuring
693 			 * that the counter is never zero when we have seen
694 			 * errors.  (The counter must be 32-bits because we
695 			 * aren't guaranteed a 64-bit compare&swap operation.)
696 			 * To save this code both the infamy of being fingered
697 			 * by a priggish news story and the indignity of being
698 			 * the target of a neo-puritan witch trial, we're
699 			 * carefully avoiding any colorful description of the
700 			 * likelihood of this condition -- but suffice it to
701 			 * say that it is only slightly more likely than the
702 			 * overflow of predicate cache IDs, as discussed in
703 			 * dtrace_predicate_create().
704 			 */
705 			nval = 1;
706 		}
707 	} while (dtrace_cas32(counter, oval, nval) != oval);
708 }
709 
710 /*
711  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
712  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
713  */
714 /* BEGIN CSTYLED */
715 DTRACE_LOADFUNC(8)
716 DTRACE_LOADFUNC(16)
717 DTRACE_LOADFUNC(32)
718 DTRACE_LOADFUNC(64)
719 /* END CSTYLED */
720 
721 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)722 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
723 {
724 	if (dest < mstate->dtms_scratch_base)
725 		return (0);
726 
727 	if (dest + size < dest)
728 		return (0);
729 
730 	if (dest + size > mstate->dtms_scratch_ptr)
731 		return (0);
732 
733 	return (1);
734 }
735 
736 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)737 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
738     dtrace_statvar_t **svars, int nsvars)
739 {
740 	int i;
741 	size_t maxglobalsize, maxlocalsize;
742 
743 	if (nsvars == 0)
744 		return (0);
745 
746 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
747 	maxlocalsize = maxglobalsize * (mp_maxid + 1);
748 
749 	for (i = 0; i < nsvars; i++) {
750 		dtrace_statvar_t *svar = svars[i];
751 		uint8_t scope;
752 		size_t size;
753 
754 		if (svar == NULL || (size = svar->dtsv_size) == 0)
755 			continue;
756 
757 		scope = svar->dtsv_var.dtdv_scope;
758 
759 		/*
760 		 * We verify that our size is valid in the spirit of providing
761 		 * defense in depth:  we want to prevent attackers from using
762 		 * DTrace to escalate an orthogonal kernel heap corruption bug
763 		 * into the ability to store to arbitrary locations in memory.
764 		 */
765 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
766 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
767 
768 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
769 		    svar->dtsv_size)) {
770 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
771 			    svar->dtsv_size);
772 			return (1);
773 		}
774 	}
775 
776 	return (0);
777 }
778 
779 /*
780  * Check to see if the address is within a memory region to which a store may
781  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
782  * region.  The caller of dtrace_canstore() is responsible for performing any
783  * alignment checks that are needed before stores are actually executed.
784  */
785 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)786 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
787     dtrace_vstate_t *vstate)
788 {
789 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
790 }
791 
792 /*
793  * Implementation of dtrace_canstore which communicates the upper bound of the
794  * allowed memory region.
795  */
796 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)797 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
798     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
799 {
800 	/*
801 	 * First, check to see if the address is in scratch space...
802 	 */
803 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
804 	    mstate->dtms_scratch_size)) {
805 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
806 		    mstate->dtms_scratch_size);
807 		return (1);
808 	}
809 
810 	/*
811 	 * Now check to see if it's a dynamic variable.  This check will pick
812 	 * up both thread-local variables and any global dynamically-allocated
813 	 * variables.
814 	 */
815 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
816 	    vstate->dtvs_dynvars.dtds_size)) {
817 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
818 		uintptr_t base = (uintptr_t)dstate->dtds_base +
819 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
820 		uintptr_t chunkoffs;
821 		dtrace_dynvar_t *dvar;
822 
823 		/*
824 		 * Before we assume that we can store here, we need to make
825 		 * sure that it isn't in our metadata -- storing to our
826 		 * dynamic variable metadata would corrupt our state.  For
827 		 * the range to not include any dynamic variable metadata,
828 		 * it must:
829 		 *
830 		 *	(1) Start above the hash table that is at the base of
831 		 *	the dynamic variable space
832 		 *
833 		 *	(2) Have a starting chunk offset that is beyond the
834 		 *	dtrace_dynvar_t that is at the base of every chunk
835 		 *
836 		 *	(3) Not span a chunk boundary
837 		 *
838 		 *	(4) Not be in the tuple space of a dynamic variable
839 		 *
840 		 */
841 		if (addr < base)
842 			return (0);
843 
844 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
845 
846 		if (chunkoffs < sizeof (dtrace_dynvar_t))
847 			return (0);
848 
849 		if (chunkoffs + sz > dstate->dtds_chunksize)
850 			return (0);
851 
852 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
853 
854 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
855 			return (0);
856 
857 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
858 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
859 			return (0);
860 
861 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
862 		return (1);
863 	}
864 
865 	/*
866 	 * Finally, check the static local and global variables.  These checks
867 	 * take the longest, so we perform them last.
868 	 */
869 	if (dtrace_canstore_statvar(addr, sz, remain,
870 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
871 		return (1);
872 
873 	if (dtrace_canstore_statvar(addr, sz, remain,
874 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
875 		return (1);
876 
877 	return (0);
878 }
879 
880 
881 /*
882  * Convenience routine to check to see if the address is within a memory
883  * region in which a load may be issued given the user's privilege level;
884  * if not, it sets the appropriate error flags and loads 'addr' into the
885  * illegal value slot.
886  *
887  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
888  * appropriate memory access protection.
889  */
890 static int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)891 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
892     dtrace_vstate_t *vstate)
893 {
894 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
895 }
896 
897 /*
898  * Implementation of dtrace_canload which communicates the uppoer bound of the
899  * allowed memory region.
900  */
901 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)902 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
903     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
904 {
905 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
906 	file_t *fp;
907 
908 	/*
909 	 * If we hold the privilege to read from kernel memory, then
910 	 * everything is readable.
911 	 */
912 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
913 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
914 		return (1);
915 	}
916 
917 	/*
918 	 * You can obviously read that which you can store.
919 	 */
920 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
921 		return (1);
922 
923 	/*
924 	 * We're allowed to read from our own string table.
925 	 */
926 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
927 	    mstate->dtms_difo->dtdo_strlen)) {
928 		DTRACE_RANGE_REMAIN(remain, addr,
929 		    mstate->dtms_difo->dtdo_strtab,
930 		    mstate->dtms_difo->dtdo_strlen);
931 		return (1);
932 	}
933 
934 	if (vstate->dtvs_state != NULL &&
935 	    dtrace_priv_proc(vstate->dtvs_state)) {
936 		proc_t *p;
937 
938 		/*
939 		 * When we have privileges to the current process, there are
940 		 * several context-related kernel structures that are safe to
941 		 * read, even absent the privilege to read from kernel memory.
942 		 * These reads are safe because these structures contain only
943 		 * state that (1) we're permitted to read, (2) is harmless or
944 		 * (3) contains pointers to additional kernel state that we're
945 		 * not permitted to read (and as such, do not present an
946 		 * opportunity for privilege escalation).  Finally (and
947 		 * critically), because of the nature of their relation with
948 		 * the current thread context, the memory associated with these
949 		 * structures cannot change over the duration of probe context,
950 		 * and it is therefore impossible for this memory to be
951 		 * deallocated and reallocated as something else while it's
952 		 * being operated upon.
953 		 */
954 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
955 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
956 			    sizeof (kthread_t));
957 			return (1);
958 		}
959 
960 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
961 		    sz, curthread->t_procp, sizeof (proc_t))) {
962 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
963 			    sizeof (proc_t));
964 			return (1);
965 		}
966 
967 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
968 		    curthread->t_cred, sizeof (cred_t))) {
969 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
970 			    sizeof (cred_t));
971 			return (1);
972 		}
973 
974 #ifdef illumos
975 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
976 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
977 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
978 			    sizeof (pid_t));
979 			return (1);
980 		}
981 
982 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
983 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
984 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
985 			    offsetof(cpu_t, cpu_pause_thread));
986 			return (1);
987 		}
988 #endif
989 	}
990 
991 	if ((fp = mstate->dtms_getf) != NULL) {
992 		uintptr_t psz = sizeof (void *);
993 		vnode_t *vp;
994 		vnodeops_t *op;
995 
996 		/*
997 		 * When getf() returns a file_t, the enabling is implicitly
998 		 * granted the (transient) right to read the returned file_t
999 		 * as well as the v_path and v_op->vnop_name of the underlying
1000 		 * vnode.  These accesses are allowed after a successful
1001 		 * getf() because the members that they refer to cannot change
1002 		 * once set -- and the barrier logic in the kernel's closef()
1003 		 * path assures that the file_t and its referenced vode_t
1004 		 * cannot themselves be stale (that is, it impossible for
1005 		 * either dtms_getf itself or its f_vnode member to reference
1006 		 * freed memory).
1007 		 */
1008 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1009 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1010 			return (1);
1011 		}
1012 
1013 		if ((vp = fp->f_vnode) != NULL) {
1014 			size_t slen;
1015 #ifdef illumos
1016 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1017 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1018 				    psz);
1019 				return (1);
1020 			}
1021 			slen = strlen(vp->v_path) + 1;
1022 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1023 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1024 				    slen);
1025 				return (1);
1026 			}
1027 #endif
1028 
1029 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1030 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1031 				    psz);
1032 				return (1);
1033 			}
1034 
1035 #ifdef illumos
1036 			if ((op = vp->v_op) != NULL &&
1037 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1038 				DTRACE_RANGE_REMAIN(remain, addr,
1039 				    &op->vnop_name, psz);
1040 				return (1);
1041 			}
1042 
1043 			if (op != NULL && op->vnop_name != NULL &&
1044 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
1045 			    (slen = strlen(op->vnop_name) + 1))) {
1046 				DTRACE_RANGE_REMAIN(remain, addr,
1047 				    op->vnop_name, slen);
1048 				return (1);
1049 			}
1050 #endif
1051 		}
1052 	}
1053 
1054 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1055 	*illval = addr;
1056 	return (0);
1057 }
1058 
1059 /*
1060  * Convenience routine to check to see if a given string is within a memory
1061  * region in which a load may be issued given the user's privilege level;
1062  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1063  * calls in the event that the user has all privileges.
1064  */
1065 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1066 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1067     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1068 {
1069 	size_t rsize;
1070 
1071 	/*
1072 	 * If we hold the privilege to read from kernel memory, then
1073 	 * everything is readable.
1074 	 */
1075 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1076 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1077 		return (1);
1078 	}
1079 
1080 	/*
1081 	 * Even if the caller is uninterested in querying the remaining valid
1082 	 * range, it is required to ensure that the access is allowed.
1083 	 */
1084 	if (remain == NULL) {
1085 		remain = &rsize;
1086 	}
1087 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1088 		size_t strsz;
1089 		/*
1090 		 * Perform the strlen after determining the length of the
1091 		 * memory region which is accessible.  This prevents timing
1092 		 * information from being used to find NULs in memory which is
1093 		 * not accessible to the caller.
1094 		 */
1095 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1096 		    MIN(sz, *remain));
1097 		if (strsz <= *remain) {
1098 			return (1);
1099 		}
1100 	}
1101 
1102 	return (0);
1103 }
1104 
1105 /*
1106  * Convenience routine to check to see if a given variable is within a memory
1107  * region in which a load may be issued given the user's privilege level.
1108  */
1109 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1110 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1111     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1112 {
1113 	size_t sz;
1114 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1115 
1116 	/*
1117 	 * Calculate the max size before performing any checks since even
1118 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1119 	 * return the max length via 'remain'.
1120 	 */
1121 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1122 		dtrace_state_t *state = vstate->dtvs_state;
1123 
1124 		if (state != NULL) {
1125 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1126 		} else {
1127 			/*
1128 			 * In helper context, we have a NULL state; fall back
1129 			 * to using the system-wide default for the string size
1130 			 * in this case.
1131 			 */
1132 			sz = dtrace_strsize_default;
1133 		}
1134 	} else {
1135 		sz = type->dtdt_size;
1136 	}
1137 
1138 	/*
1139 	 * If we hold the privilege to read from kernel memory, then
1140 	 * everything is readable.
1141 	 */
1142 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1143 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1144 		return (1);
1145 	}
1146 
1147 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1148 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1149 		    vstate));
1150 	}
1151 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1152 	    vstate));
1153 }
1154 
1155 /*
1156  * Convert a string to a signed integer using safe loads.
1157  *
1158  * NOTE: This function uses various macros from strtolctype.h to manipulate
1159  * digit values, etc -- these have all been checked to ensure they make
1160  * no additional function calls.
1161  */
1162 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1163 dtrace_strtoll(char *input, int base, size_t limit)
1164 {
1165 	uintptr_t pos = (uintptr_t)input;
1166 	int64_t val = 0;
1167 	int x;
1168 	boolean_t neg = B_FALSE;
1169 	char c, cc, ccc;
1170 	uintptr_t end = pos + limit;
1171 
1172 	/*
1173 	 * Consume any whitespace preceding digits.
1174 	 */
1175 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1176 		pos++;
1177 
1178 	/*
1179 	 * Handle an explicit sign if one is present.
1180 	 */
1181 	if (c == '-' || c == '+') {
1182 		if (c == '-')
1183 			neg = B_TRUE;
1184 		c = dtrace_load8(++pos);
1185 	}
1186 
1187 	/*
1188 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1189 	 * if present.
1190 	 */
1191 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1192 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1193 		pos += 2;
1194 		c = ccc;
1195 	}
1196 
1197 	/*
1198 	 * Read in contiguous digits until the first non-digit character.
1199 	 */
1200 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1201 	    c = dtrace_load8(++pos))
1202 		val = val * base + x;
1203 
1204 	return (neg ? -val : val);
1205 }
1206 
1207 /*
1208  * Compare two strings using safe loads.
1209  */
1210 static int
dtrace_strncmp(char * s1,char * s2,size_t limit)1211 dtrace_strncmp(char *s1, char *s2, size_t limit)
1212 {
1213 	uint8_t c1, c2;
1214 	volatile uint16_t *flags;
1215 
1216 	if (s1 == s2 || limit == 0)
1217 		return (0);
1218 
1219 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1220 
1221 	do {
1222 		if (s1 == NULL) {
1223 			c1 = '\0';
1224 		} else {
1225 			c1 = dtrace_load8((uintptr_t)s1++);
1226 		}
1227 
1228 		if (s2 == NULL) {
1229 			c2 = '\0';
1230 		} else {
1231 			c2 = dtrace_load8((uintptr_t)s2++);
1232 		}
1233 
1234 		if (c1 != c2)
1235 			return (c1 - c2);
1236 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1237 
1238 	return (0);
1239 }
1240 
1241 /*
1242  * Compute strlen(s) for a string using safe memory accesses.  The additional
1243  * len parameter is used to specify a maximum length to ensure completion.
1244  */
1245 static size_t
dtrace_strlen(const char * s,size_t lim)1246 dtrace_strlen(const char *s, size_t lim)
1247 {
1248 	uint_t len;
1249 
1250 	for (len = 0; len != lim; len++) {
1251 		if (dtrace_load8((uintptr_t)s++) == '\0')
1252 			break;
1253 	}
1254 
1255 	return (len);
1256 }
1257 
1258 /*
1259  * Check if an address falls within a toxic region.
1260  */
1261 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1262 dtrace_istoxic(uintptr_t kaddr, size_t size)
1263 {
1264 	uintptr_t taddr, tsize;
1265 	int i;
1266 
1267 	for (i = 0; i < dtrace_toxranges; i++) {
1268 		taddr = dtrace_toxrange[i].dtt_base;
1269 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1270 
1271 		if (kaddr - taddr < tsize) {
1272 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1273 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1274 			return (1);
1275 		}
1276 
1277 		if (taddr - kaddr < size) {
1278 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1279 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1280 			return (1);
1281 		}
1282 	}
1283 
1284 	return (0);
1285 }
1286 
1287 /*
1288  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1289  * memory specified by the DIF program.  The dst is assumed to be safe memory
1290  * that we can store to directly because it is managed by DTrace.  As with
1291  * standard bcopy, overlapping copies are handled properly.
1292  */
1293 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1294 dtrace_bcopy(const void *src, void *dst, size_t len)
1295 {
1296 	if (len != 0) {
1297 		uint8_t *s1 = dst;
1298 		const uint8_t *s2 = src;
1299 
1300 		if (s1 <= s2) {
1301 			do {
1302 				*s1++ = dtrace_load8((uintptr_t)s2++);
1303 			} while (--len != 0);
1304 		} else {
1305 			s2 += len;
1306 			s1 += len;
1307 
1308 			do {
1309 				*--s1 = dtrace_load8((uintptr_t)--s2);
1310 			} while (--len != 0);
1311 		}
1312 	}
1313 }
1314 
1315 /*
1316  * Copy src to dst using safe memory accesses, up to either the specified
1317  * length, or the point that a nul byte is encountered.  The src is assumed to
1318  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1319  * safe memory that we can store to directly because it is managed by DTrace.
1320  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1321  */
1322 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1323 dtrace_strcpy(const void *src, void *dst, size_t len)
1324 {
1325 	if (len != 0) {
1326 		uint8_t *s1 = dst, c;
1327 		const uint8_t *s2 = src;
1328 
1329 		do {
1330 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1331 		} while (--len != 0 && c != '\0');
1332 	}
1333 }
1334 
1335 /*
1336  * Copy src to dst, deriving the size and type from the specified (BYREF)
1337  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1338  * program.  The dst is assumed to be DTrace variable memory that is of the
1339  * specified type; we assume that we can store to directly.
1340  */
1341 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1342 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1343 {
1344 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1345 
1346 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1347 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1348 	} else {
1349 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1350 	}
1351 }
1352 
1353 /*
1354  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1355  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1356  * safe memory that we can access directly because it is managed by DTrace.
1357  */
1358 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1359 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1360 {
1361 	volatile uint16_t *flags;
1362 
1363 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1364 
1365 	if (s1 == s2)
1366 		return (0);
1367 
1368 	if (s1 == NULL || s2 == NULL)
1369 		return (1);
1370 
1371 	if (s1 != s2 && len != 0) {
1372 		const uint8_t *ps1 = s1;
1373 		const uint8_t *ps2 = s2;
1374 
1375 		do {
1376 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1377 				return (1);
1378 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1379 	}
1380 	return (0);
1381 }
1382 
1383 /*
1384  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1385  * is for safe DTrace-managed memory only.
1386  */
1387 static void
dtrace_bzero(void * dst,size_t len)1388 dtrace_bzero(void *dst, size_t len)
1389 {
1390 	uchar_t *cp;
1391 
1392 	for (cp = dst; len != 0; len--)
1393 		*cp++ = 0;
1394 }
1395 
1396 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1397 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1398 {
1399 	uint64_t result[2];
1400 
1401 	result[0] = addend1[0] + addend2[0];
1402 	result[1] = addend1[1] + addend2[1] +
1403 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1404 
1405 	sum[0] = result[0];
1406 	sum[1] = result[1];
1407 }
1408 
1409 /*
1410  * Shift the 128-bit value in a by b. If b is positive, shift left.
1411  * If b is negative, shift right.
1412  */
1413 static void
dtrace_shift_128(uint64_t * a,int b)1414 dtrace_shift_128(uint64_t *a, int b)
1415 {
1416 	uint64_t mask;
1417 
1418 	if (b == 0)
1419 		return;
1420 
1421 	if (b < 0) {
1422 		b = -b;
1423 		if (b >= 64) {
1424 			a[0] = a[1] >> (b - 64);
1425 			a[1] = 0;
1426 		} else {
1427 			a[0] >>= b;
1428 			mask = 1LL << (64 - b);
1429 			mask -= 1;
1430 			a[0] |= ((a[1] & mask) << (64 - b));
1431 			a[1] >>= b;
1432 		}
1433 	} else {
1434 		if (b >= 64) {
1435 			a[1] = a[0] << (b - 64);
1436 			a[0] = 0;
1437 		} else {
1438 			a[1] <<= b;
1439 			mask = a[0] >> (64 - b);
1440 			a[1] |= mask;
1441 			a[0] <<= b;
1442 		}
1443 	}
1444 }
1445 
1446 /*
1447  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1448  * use native multiplication on those, and then re-combine into the
1449  * resulting 128-bit value.
1450  *
1451  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1452  *     hi1 * hi2 << 64 +
1453  *     hi1 * lo2 << 32 +
1454  *     hi2 * lo1 << 32 +
1455  *     lo1 * lo2
1456  */
1457 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1458 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1459 {
1460 	uint64_t hi1, hi2, lo1, lo2;
1461 	uint64_t tmp[2];
1462 
1463 	hi1 = factor1 >> 32;
1464 	hi2 = factor2 >> 32;
1465 
1466 	lo1 = factor1 & DT_MASK_LO;
1467 	lo2 = factor2 & DT_MASK_LO;
1468 
1469 	product[0] = lo1 * lo2;
1470 	product[1] = hi1 * hi2;
1471 
1472 	tmp[0] = hi1 * lo2;
1473 	tmp[1] = 0;
1474 	dtrace_shift_128(tmp, 32);
1475 	dtrace_add_128(product, tmp, product);
1476 
1477 	tmp[0] = hi2 * lo1;
1478 	tmp[1] = 0;
1479 	dtrace_shift_128(tmp, 32);
1480 	dtrace_add_128(product, tmp, product);
1481 }
1482 
1483 /*
1484  * This privilege check should be used by actions and subroutines to
1485  * verify that the user credentials of the process that enabled the
1486  * invoking ECB match the target credentials
1487  */
1488 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1489 dtrace_priv_proc_common_user(dtrace_state_t *state)
1490 {
1491 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1492 
1493 	/*
1494 	 * We should always have a non-NULL state cred here, since if cred
1495 	 * is null (anonymous tracing), we fast-path bypass this routine.
1496 	 */
1497 	ASSERT(s_cr != NULL);
1498 
1499 	if ((cr = CRED()) != NULL &&
1500 	    s_cr->cr_uid == cr->cr_uid &&
1501 	    s_cr->cr_uid == cr->cr_ruid &&
1502 	    s_cr->cr_uid == cr->cr_suid &&
1503 	    s_cr->cr_gid == cr->cr_gid &&
1504 	    s_cr->cr_gid == cr->cr_rgid &&
1505 	    s_cr->cr_gid == cr->cr_sgid)
1506 		return (1);
1507 
1508 	return (0);
1509 }
1510 
1511 /*
1512  * This privilege check should be used by actions and subroutines to
1513  * verify that the zone of the process that enabled the invoking ECB
1514  * matches the target credentials
1515  */
1516 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1517 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1518 {
1519 #ifdef illumos
1520 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1521 
1522 	/*
1523 	 * We should always have a non-NULL state cred here, since if cred
1524 	 * is null (anonymous tracing), we fast-path bypass this routine.
1525 	 */
1526 	ASSERT(s_cr != NULL);
1527 
1528 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1529 		return (1);
1530 
1531 	return (0);
1532 #else
1533 	return (1);
1534 #endif
1535 }
1536 
1537 /*
1538  * This privilege check should be used by actions and subroutines to
1539  * verify that the process has not setuid or changed credentials.
1540  */
1541 static int
dtrace_priv_proc_common_nocd(void)1542 dtrace_priv_proc_common_nocd(void)
1543 {
1544 	proc_t *proc;
1545 
1546 	if ((proc = ttoproc(curthread)) != NULL &&
1547 	    !(proc->p_flag & SNOCD))
1548 		return (1);
1549 
1550 	return (0);
1551 }
1552 
1553 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1554 dtrace_priv_proc_destructive(dtrace_state_t *state)
1555 {
1556 	int action = state->dts_cred.dcr_action;
1557 
1558 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1559 	    dtrace_priv_proc_common_zone(state) == 0)
1560 		goto bad;
1561 
1562 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1563 	    dtrace_priv_proc_common_user(state) == 0)
1564 		goto bad;
1565 
1566 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1567 	    dtrace_priv_proc_common_nocd() == 0)
1568 		goto bad;
1569 
1570 	return (1);
1571 
1572 bad:
1573 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1574 
1575 	return (0);
1576 }
1577 
1578 static int
dtrace_priv_proc_control(dtrace_state_t * state)1579 dtrace_priv_proc_control(dtrace_state_t *state)
1580 {
1581 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1582 		return (1);
1583 
1584 	if (dtrace_priv_proc_common_zone(state) &&
1585 	    dtrace_priv_proc_common_user(state) &&
1586 	    dtrace_priv_proc_common_nocd())
1587 		return (1);
1588 
1589 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1590 
1591 	return (0);
1592 }
1593 
1594 static int
dtrace_priv_proc(dtrace_state_t * state)1595 dtrace_priv_proc(dtrace_state_t *state)
1596 {
1597 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1598 		return (1);
1599 
1600 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1601 
1602 	return (0);
1603 }
1604 
1605 static int
dtrace_priv_kernel(dtrace_state_t * state)1606 dtrace_priv_kernel(dtrace_state_t *state)
1607 {
1608 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1609 		return (1);
1610 
1611 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1612 
1613 	return (0);
1614 }
1615 
1616 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1617 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1618 {
1619 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1620 		return (1);
1621 
1622 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1623 
1624 	return (0);
1625 }
1626 
1627 /*
1628  * Determine if the dte_cond of the specified ECB allows for processing of
1629  * the current probe to continue.  Note that this routine may allow continued
1630  * processing, but with access(es) stripped from the mstate's dtms_access
1631  * field.
1632  */
1633 static int
dtrace_priv_probe(dtrace_state_t * state,dtrace_mstate_t * mstate,dtrace_ecb_t * ecb)1634 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1635     dtrace_ecb_t *ecb)
1636 {
1637 	dtrace_probe_t *probe = ecb->dte_probe;
1638 	dtrace_provider_t *prov = probe->dtpr_provider;
1639 	dtrace_pops_t *pops = &prov->dtpv_pops;
1640 	int mode = DTRACE_MODE_NOPRIV_DROP;
1641 
1642 	ASSERT(ecb->dte_cond);
1643 
1644 #ifdef illumos
1645 	if (pops->dtps_mode != NULL) {
1646 		mode = pops->dtps_mode(prov->dtpv_arg,
1647 		    probe->dtpr_id, probe->dtpr_arg);
1648 
1649 		ASSERT((mode & DTRACE_MODE_USER) ||
1650 		    (mode & DTRACE_MODE_KERNEL));
1651 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1652 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1653 	}
1654 
1655 	/*
1656 	 * If the dte_cond bits indicate that this consumer is only allowed to
1657 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1658 	 * entry point to check that the probe was fired while in a user
1659 	 * context.  If that's not the case, use the policy specified by the
1660 	 * provider to determine if we drop the probe or merely restrict
1661 	 * operation.
1662 	 */
1663 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1664 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1665 
1666 		if (!(mode & DTRACE_MODE_USER)) {
1667 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1668 				return (0);
1669 
1670 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1671 		}
1672 	}
1673 #endif
1674 
1675 	/*
1676 	 * This is more subtle than it looks. We have to be absolutely certain
1677 	 * that CRED() isn't going to change out from under us so it's only
1678 	 * legit to examine that structure if we're in constrained situations.
1679 	 * Currently, the only times we'll this check is if a non-super-user
1680 	 * has enabled the profile or syscall providers -- providers that
1681 	 * allow visibility of all processes. For the profile case, the check
1682 	 * above will ensure that we're examining a user context.
1683 	 */
1684 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1685 		cred_t *cr;
1686 		cred_t *s_cr = state->dts_cred.dcr_cred;
1687 		proc_t *proc;
1688 
1689 		ASSERT(s_cr != NULL);
1690 
1691 		if ((cr = CRED()) == NULL ||
1692 		    s_cr->cr_uid != cr->cr_uid ||
1693 		    s_cr->cr_uid != cr->cr_ruid ||
1694 		    s_cr->cr_uid != cr->cr_suid ||
1695 		    s_cr->cr_gid != cr->cr_gid ||
1696 		    s_cr->cr_gid != cr->cr_rgid ||
1697 		    s_cr->cr_gid != cr->cr_sgid ||
1698 		    (proc = ttoproc(curthread)) == NULL ||
1699 		    (proc->p_flag & SNOCD)) {
1700 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1701 				return (0);
1702 
1703 #ifdef illumos
1704 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1705 #endif
1706 		}
1707 	}
1708 
1709 #ifdef illumos
1710 	/*
1711 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1712 	 * in our zone, check to see if our mode policy is to restrict rather
1713 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1714 	 * and DTRACE_ACCESS_ARGS
1715 	 */
1716 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1717 		cred_t *cr;
1718 		cred_t *s_cr = state->dts_cred.dcr_cred;
1719 
1720 		ASSERT(s_cr != NULL);
1721 
1722 		if ((cr = CRED()) == NULL ||
1723 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1724 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1725 				return (0);
1726 
1727 			mstate->dtms_access &=
1728 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1729 		}
1730 	}
1731 #endif
1732 
1733 	return (1);
1734 }
1735 
1736 /*
1737  * Note:  not called from probe context.  This function is called
1738  * asynchronously (and at a regular interval) from outside of probe context to
1739  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1740  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1741  */
1742 void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1743 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1744 {
1745 	dtrace_dynvar_t *dirty;
1746 	dtrace_dstate_percpu_t *dcpu;
1747 	dtrace_dynvar_t **rinsep;
1748 	int i, j, work = 0;
1749 
1750 	CPU_FOREACH(i) {
1751 		dcpu = &dstate->dtds_percpu[i];
1752 		rinsep = &dcpu->dtdsc_rinsing;
1753 
1754 		/*
1755 		 * If the dirty list is NULL, there is no dirty work to do.
1756 		 */
1757 		if (dcpu->dtdsc_dirty == NULL)
1758 			continue;
1759 
1760 		if (dcpu->dtdsc_rinsing != NULL) {
1761 			/*
1762 			 * If the rinsing list is non-NULL, then it is because
1763 			 * this CPU was selected to accept another CPU's
1764 			 * dirty list -- and since that time, dirty buffers
1765 			 * have accumulated.  This is a highly unlikely
1766 			 * condition, but we choose to ignore the dirty
1767 			 * buffers -- they'll be picked up a future cleanse.
1768 			 */
1769 			continue;
1770 		}
1771 
1772 		if (dcpu->dtdsc_clean != NULL) {
1773 			/*
1774 			 * If the clean list is non-NULL, then we're in a
1775 			 * situation where a CPU has done deallocations (we
1776 			 * have a non-NULL dirty list) but no allocations (we
1777 			 * also have a non-NULL clean list).  We can't simply
1778 			 * move the dirty list into the clean list on this
1779 			 * CPU, yet we also don't want to allow this condition
1780 			 * to persist, lest a short clean list prevent a
1781 			 * massive dirty list from being cleaned (which in
1782 			 * turn could lead to otherwise avoidable dynamic
1783 			 * drops).  To deal with this, we look for some CPU
1784 			 * with a NULL clean list, NULL dirty list, and NULL
1785 			 * rinsing list -- and then we borrow this CPU to
1786 			 * rinse our dirty list.
1787 			 */
1788 			CPU_FOREACH(j) {
1789 				dtrace_dstate_percpu_t *rinser;
1790 
1791 				rinser = &dstate->dtds_percpu[j];
1792 
1793 				if (rinser->dtdsc_rinsing != NULL)
1794 					continue;
1795 
1796 				if (rinser->dtdsc_dirty != NULL)
1797 					continue;
1798 
1799 				if (rinser->dtdsc_clean != NULL)
1800 					continue;
1801 
1802 				rinsep = &rinser->dtdsc_rinsing;
1803 				break;
1804 			}
1805 
1806 			if (j > mp_maxid) {
1807 				/*
1808 				 * We were unable to find another CPU that
1809 				 * could accept this dirty list -- we are
1810 				 * therefore unable to clean it now.
1811 				 */
1812 				dtrace_dynvar_failclean++;
1813 				continue;
1814 			}
1815 		}
1816 
1817 		work = 1;
1818 
1819 		/*
1820 		 * Atomically move the dirty list aside.
1821 		 */
1822 		do {
1823 			dirty = dcpu->dtdsc_dirty;
1824 
1825 			/*
1826 			 * Before we zap the dirty list, set the rinsing list.
1827 			 * (This allows for a potential assertion in
1828 			 * dtrace_dynvar():  if a free dynamic variable appears
1829 			 * on a hash chain, either the dirty list or the
1830 			 * rinsing list for some CPU must be non-NULL.)
1831 			 */
1832 			*rinsep = dirty;
1833 			dtrace_membar_producer();
1834 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1835 		    dirty, NULL) != dirty);
1836 	}
1837 
1838 	if (!work) {
1839 		/*
1840 		 * We have no work to do; we can simply return.
1841 		 */
1842 		return;
1843 	}
1844 
1845 	dtrace_sync();
1846 
1847 	CPU_FOREACH(i) {
1848 		dcpu = &dstate->dtds_percpu[i];
1849 
1850 		if (dcpu->dtdsc_rinsing == NULL)
1851 			continue;
1852 
1853 		/*
1854 		 * We are now guaranteed that no hash chain contains a pointer
1855 		 * into this dirty list; we can make it clean.
1856 		 */
1857 		ASSERT(dcpu->dtdsc_clean == NULL);
1858 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1859 		dcpu->dtdsc_rinsing = NULL;
1860 	}
1861 
1862 	/*
1863 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1864 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1865 	 * This prevents a race whereby a CPU incorrectly decides that
1866 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1867 	 * after dtrace_dynvar_clean() has completed.
1868 	 */
1869 	dtrace_sync();
1870 
1871 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1872 }
1873 
1874 /*
1875  * Depending on the value of the op parameter, this function looks-up,
1876  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1877  * allocation is requested, this function will return a pointer to a
1878  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1879  * variable can be allocated.  If NULL is returned, the appropriate counter
1880  * will be incremented.
1881  */
1882 dtrace_dynvar_t *
dtrace_dynvar(dtrace_dstate_t * dstate,uint_t nkeys,dtrace_key_t * key,size_t dsize,dtrace_dynvar_op_t op,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1883 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1884     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1885     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1886 {
1887 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1888 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1889 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1890 	processorid_t me = curcpu, cpu = me;
1891 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1892 	size_t bucket, ksize;
1893 	size_t chunksize = dstate->dtds_chunksize;
1894 	uintptr_t kdata, lock, nstate;
1895 	uint_t i;
1896 
1897 	ASSERT(nkeys != 0);
1898 
1899 	/*
1900 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1901 	 * algorithm.  For the by-value portions, we perform the algorithm in
1902 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1903 	 * bit, and seems to have only a minute effect on distribution.  For
1904 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1905 	 * over each referenced byte.  It's painful to do this, but it's much
1906 	 * better than pathological hash distribution.  The efficacy of the
1907 	 * hashing algorithm (and a comparison with other algorithms) may be
1908 	 * found by running the ::dtrace_dynstat MDB dcmd.
1909 	 */
1910 	for (i = 0; i < nkeys; i++) {
1911 		if (key[i].dttk_size == 0) {
1912 			uint64_t val = key[i].dttk_value;
1913 
1914 			hashval += (val >> 48) & 0xffff;
1915 			hashval += (hashval << 10);
1916 			hashval ^= (hashval >> 6);
1917 
1918 			hashval += (val >> 32) & 0xffff;
1919 			hashval += (hashval << 10);
1920 			hashval ^= (hashval >> 6);
1921 
1922 			hashval += (val >> 16) & 0xffff;
1923 			hashval += (hashval << 10);
1924 			hashval ^= (hashval >> 6);
1925 
1926 			hashval += val & 0xffff;
1927 			hashval += (hashval << 10);
1928 			hashval ^= (hashval >> 6);
1929 		} else {
1930 			/*
1931 			 * This is incredibly painful, but it beats the hell
1932 			 * out of the alternative.
1933 			 */
1934 			uint64_t j, size = key[i].dttk_size;
1935 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1936 
1937 			if (!dtrace_canload(base, size, mstate, vstate))
1938 				break;
1939 
1940 			for (j = 0; j < size; j++) {
1941 				hashval += dtrace_load8(base + j);
1942 				hashval += (hashval << 10);
1943 				hashval ^= (hashval >> 6);
1944 			}
1945 		}
1946 	}
1947 
1948 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1949 		return (NULL);
1950 
1951 	hashval += (hashval << 3);
1952 	hashval ^= (hashval >> 11);
1953 	hashval += (hashval << 15);
1954 
1955 	/*
1956 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1957 	 * comes out to be one of our two sentinel hash values.  If this
1958 	 * actually happens, we set the hashval to be a value known to be a
1959 	 * non-sentinel value.
1960 	 */
1961 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1962 		hashval = DTRACE_DYNHASH_VALID;
1963 
1964 	/*
1965 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1966 	 * important here, tricks can be pulled to reduce it.  (However, it's
1967 	 * critical that hash collisions be kept to an absolute minimum;
1968 	 * they're much more painful than a divide.)  It's better to have a
1969 	 * solution that generates few collisions and still keeps things
1970 	 * relatively simple.
1971 	 */
1972 	bucket = hashval % dstate->dtds_hashsize;
1973 
1974 	if (op == DTRACE_DYNVAR_DEALLOC) {
1975 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1976 
1977 		for (;;) {
1978 			while ((lock = *lockp) & 1)
1979 				continue;
1980 
1981 			if (dtrace_casptr((volatile void *)lockp,
1982 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1983 				break;
1984 		}
1985 
1986 		dtrace_membar_producer();
1987 	}
1988 
1989 top:
1990 	prev = NULL;
1991 	lock = hash[bucket].dtdh_lock;
1992 
1993 	dtrace_membar_consumer();
1994 
1995 	start = hash[bucket].dtdh_chain;
1996 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1997 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1998 	    op != DTRACE_DYNVAR_DEALLOC));
1999 
2000 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
2001 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
2002 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
2003 
2004 		if (dvar->dtdv_hashval != hashval) {
2005 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
2006 				/*
2007 				 * We've reached the sink, and therefore the
2008 				 * end of the hash chain; we can kick out of
2009 				 * the loop knowing that we have seen a valid
2010 				 * snapshot of state.
2011 				 */
2012 				ASSERT(dvar->dtdv_next == NULL);
2013 				ASSERT(dvar == &dtrace_dynhash_sink);
2014 				break;
2015 			}
2016 
2017 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2018 				/*
2019 				 * We've gone off the rails:  somewhere along
2020 				 * the line, one of the members of this hash
2021 				 * chain was deleted.  Note that we could also
2022 				 * detect this by simply letting this loop run
2023 				 * to completion, as we would eventually hit
2024 				 * the end of the dirty list.  However, we
2025 				 * want to avoid running the length of the
2026 				 * dirty list unnecessarily (it might be quite
2027 				 * long), so we catch this as early as
2028 				 * possible by detecting the hash marker.  In
2029 				 * this case, we simply set dvar to NULL and
2030 				 * break; the conditional after the loop will
2031 				 * send us back to top.
2032 				 */
2033 				dvar = NULL;
2034 				break;
2035 			}
2036 
2037 			goto next;
2038 		}
2039 
2040 		if (dtuple->dtt_nkeys != nkeys)
2041 			goto next;
2042 
2043 		for (i = 0; i < nkeys; i++, dkey++) {
2044 			if (dkey->dttk_size != key[i].dttk_size)
2045 				goto next; /* size or type mismatch */
2046 
2047 			if (dkey->dttk_size != 0) {
2048 				if (dtrace_bcmp(
2049 				    (void *)(uintptr_t)key[i].dttk_value,
2050 				    (void *)(uintptr_t)dkey->dttk_value,
2051 				    dkey->dttk_size))
2052 					goto next;
2053 			} else {
2054 				if (dkey->dttk_value != key[i].dttk_value)
2055 					goto next;
2056 			}
2057 		}
2058 
2059 		if (op != DTRACE_DYNVAR_DEALLOC)
2060 			return (dvar);
2061 
2062 		ASSERT(dvar->dtdv_next == NULL ||
2063 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2064 
2065 		if (prev != NULL) {
2066 			ASSERT(hash[bucket].dtdh_chain != dvar);
2067 			ASSERT(start != dvar);
2068 			ASSERT(prev->dtdv_next == dvar);
2069 			prev->dtdv_next = dvar->dtdv_next;
2070 		} else {
2071 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2072 			    start, dvar->dtdv_next) != start) {
2073 				/*
2074 				 * We have failed to atomically swing the
2075 				 * hash table head pointer, presumably because
2076 				 * of a conflicting allocation on another CPU.
2077 				 * We need to reread the hash chain and try
2078 				 * again.
2079 				 */
2080 				goto top;
2081 			}
2082 		}
2083 
2084 		dtrace_membar_producer();
2085 
2086 		/*
2087 		 * Now set the hash value to indicate that it's free.
2088 		 */
2089 		ASSERT(hash[bucket].dtdh_chain != dvar);
2090 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2091 
2092 		dtrace_membar_producer();
2093 
2094 		/*
2095 		 * Set the next pointer to point at the dirty list, and
2096 		 * atomically swing the dirty pointer to the newly freed dvar.
2097 		 */
2098 		do {
2099 			next = dcpu->dtdsc_dirty;
2100 			dvar->dtdv_next = next;
2101 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2102 
2103 		/*
2104 		 * Finally, unlock this hash bucket.
2105 		 */
2106 		ASSERT(hash[bucket].dtdh_lock == lock);
2107 		ASSERT(lock & 1);
2108 		hash[bucket].dtdh_lock++;
2109 
2110 		return (NULL);
2111 next:
2112 		prev = dvar;
2113 		continue;
2114 	}
2115 
2116 	if (dvar == NULL) {
2117 		/*
2118 		 * If dvar is NULL, it is because we went off the rails:
2119 		 * one of the elements that we traversed in the hash chain
2120 		 * was deleted while we were traversing it.  In this case,
2121 		 * we assert that we aren't doing a dealloc (deallocs lock
2122 		 * the hash bucket to prevent themselves from racing with
2123 		 * one another), and retry the hash chain traversal.
2124 		 */
2125 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2126 		goto top;
2127 	}
2128 
2129 	if (op != DTRACE_DYNVAR_ALLOC) {
2130 		/*
2131 		 * If we are not to allocate a new variable, we want to
2132 		 * return NULL now.  Before we return, check that the value
2133 		 * of the lock word hasn't changed.  If it has, we may have
2134 		 * seen an inconsistent snapshot.
2135 		 */
2136 		if (op == DTRACE_DYNVAR_NOALLOC) {
2137 			if (hash[bucket].dtdh_lock != lock)
2138 				goto top;
2139 		} else {
2140 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2141 			ASSERT(hash[bucket].dtdh_lock == lock);
2142 			ASSERT(lock & 1);
2143 			hash[bucket].dtdh_lock++;
2144 		}
2145 
2146 		return (NULL);
2147 	}
2148 
2149 	/*
2150 	 * We need to allocate a new dynamic variable.  The size we need is the
2151 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2152 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2153 	 * the size of any referred-to data (dsize).  We then round the final
2154 	 * size up to the chunksize for allocation.
2155 	 */
2156 	for (ksize = 0, i = 0; i < nkeys; i++)
2157 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2158 
2159 	/*
2160 	 * This should be pretty much impossible, but could happen if, say,
2161 	 * strange DIF specified the tuple.  Ideally, this should be an
2162 	 * assertion and not an error condition -- but that requires that the
2163 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2164 	 * bullet-proof.  (That is, it must not be able to be fooled by
2165 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2166 	 * solving this would presumably not amount to solving the Halting
2167 	 * Problem -- but it still seems awfully hard.
2168 	 */
2169 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2170 	    ksize + dsize > chunksize) {
2171 		dcpu->dtdsc_drops++;
2172 		return (NULL);
2173 	}
2174 
2175 	nstate = DTRACE_DSTATE_EMPTY;
2176 
2177 	do {
2178 retry:
2179 		free = dcpu->dtdsc_free;
2180 
2181 		if (free == NULL) {
2182 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2183 			void *rval;
2184 
2185 			if (clean == NULL) {
2186 				/*
2187 				 * We're out of dynamic variable space on
2188 				 * this CPU.  Unless we have tried all CPUs,
2189 				 * we'll try to allocate from a different
2190 				 * CPU.
2191 				 */
2192 				switch (dstate->dtds_state) {
2193 				case DTRACE_DSTATE_CLEAN: {
2194 					void *sp = &dstate->dtds_state;
2195 
2196 					if (++cpu > mp_maxid)
2197 						cpu = 0;
2198 
2199 					if (dcpu->dtdsc_dirty != NULL &&
2200 					    nstate == DTRACE_DSTATE_EMPTY)
2201 						nstate = DTRACE_DSTATE_DIRTY;
2202 
2203 					if (dcpu->dtdsc_rinsing != NULL)
2204 						nstate = DTRACE_DSTATE_RINSING;
2205 
2206 					dcpu = &dstate->dtds_percpu[cpu];
2207 
2208 					if (cpu != me)
2209 						goto retry;
2210 
2211 					(void) dtrace_cas32(sp,
2212 					    DTRACE_DSTATE_CLEAN, nstate);
2213 
2214 					/*
2215 					 * To increment the correct bean
2216 					 * counter, take another lap.
2217 					 */
2218 					goto retry;
2219 				}
2220 
2221 				case DTRACE_DSTATE_DIRTY:
2222 					dcpu->dtdsc_dirty_drops++;
2223 					break;
2224 
2225 				case DTRACE_DSTATE_RINSING:
2226 					dcpu->dtdsc_rinsing_drops++;
2227 					break;
2228 
2229 				case DTRACE_DSTATE_EMPTY:
2230 					dcpu->dtdsc_drops++;
2231 					break;
2232 				}
2233 
2234 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2235 				return (NULL);
2236 			}
2237 
2238 			/*
2239 			 * The clean list appears to be non-empty.  We want to
2240 			 * move the clean list to the free list; we start by
2241 			 * moving the clean pointer aside.
2242 			 */
2243 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2244 			    clean, NULL) != clean) {
2245 				/*
2246 				 * We are in one of two situations:
2247 				 *
2248 				 *  (a)	The clean list was switched to the
2249 				 *	free list by another CPU.
2250 				 *
2251 				 *  (b)	The clean list was added to by the
2252 				 *	cleansing cyclic.
2253 				 *
2254 				 * In either of these situations, we can
2255 				 * just reattempt the free list allocation.
2256 				 */
2257 				goto retry;
2258 			}
2259 
2260 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2261 
2262 			/*
2263 			 * Now we'll move the clean list to our free list.
2264 			 * It's impossible for this to fail:  the only way
2265 			 * the free list can be updated is through this
2266 			 * code path, and only one CPU can own the clean list.
2267 			 * Thus, it would only be possible for this to fail if
2268 			 * this code were racing with dtrace_dynvar_clean().
2269 			 * (That is, if dtrace_dynvar_clean() updated the clean
2270 			 * list, and we ended up racing to update the free
2271 			 * list.)  This race is prevented by the dtrace_sync()
2272 			 * in dtrace_dynvar_clean() -- which flushes the
2273 			 * owners of the clean lists out before resetting
2274 			 * the clean lists.
2275 			 */
2276 			dcpu = &dstate->dtds_percpu[me];
2277 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2278 			ASSERT(rval == NULL);
2279 			goto retry;
2280 		}
2281 
2282 		dvar = free;
2283 		new_free = dvar->dtdv_next;
2284 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2285 
2286 	/*
2287 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2288 	 * tuple array and copy any referenced key data into the data space
2289 	 * following the tuple array.  As we do this, we relocate dttk_value
2290 	 * in the final tuple to point to the key data address in the chunk.
2291 	 */
2292 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2293 	dvar->dtdv_data = (void *)(kdata + ksize);
2294 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2295 
2296 	for (i = 0; i < nkeys; i++) {
2297 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2298 		size_t kesize = key[i].dttk_size;
2299 
2300 		if (kesize != 0) {
2301 			dtrace_bcopy(
2302 			    (const void *)(uintptr_t)key[i].dttk_value,
2303 			    (void *)kdata, kesize);
2304 			dkey->dttk_value = kdata;
2305 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2306 		} else {
2307 			dkey->dttk_value = key[i].dttk_value;
2308 		}
2309 
2310 		dkey->dttk_size = kesize;
2311 	}
2312 
2313 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2314 	dvar->dtdv_hashval = hashval;
2315 	dvar->dtdv_next = start;
2316 
2317 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2318 		return (dvar);
2319 
2320 	/*
2321 	 * The cas has failed.  Either another CPU is adding an element to
2322 	 * this hash chain, or another CPU is deleting an element from this
2323 	 * hash chain.  The simplest way to deal with both of these cases
2324 	 * (though not necessarily the most efficient) is to free our
2325 	 * allocated block and re-attempt it all.  Note that the free is
2326 	 * to the dirty list and _not_ to the free list.  This is to prevent
2327 	 * races with allocators, above.
2328 	 */
2329 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2330 
2331 	dtrace_membar_producer();
2332 
2333 	do {
2334 		free = dcpu->dtdsc_dirty;
2335 		dvar->dtdv_next = free;
2336 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2337 
2338 	goto top;
2339 }
2340 
2341 /*ARGSUSED*/
2342 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2343 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2344 {
2345 	if ((int64_t)nval < (int64_t)*oval)
2346 		*oval = nval;
2347 }
2348 
2349 /*ARGSUSED*/
2350 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2351 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2352 {
2353 	if ((int64_t)nval > (int64_t)*oval)
2354 		*oval = nval;
2355 }
2356 
2357 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2358 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2359 {
2360 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2361 	int64_t val = (int64_t)nval;
2362 
2363 	if (val < 0) {
2364 		for (i = 0; i < zero; i++) {
2365 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2366 				quanta[i] += incr;
2367 				return;
2368 			}
2369 		}
2370 	} else {
2371 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2372 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2373 				quanta[i - 1] += incr;
2374 				return;
2375 			}
2376 		}
2377 
2378 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2379 		return;
2380 	}
2381 
2382 	ASSERT(0);
2383 }
2384 
2385 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2386 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2387 {
2388 	uint64_t arg = *lquanta++;
2389 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2390 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2391 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2392 	int32_t val = (int32_t)nval, level;
2393 
2394 	ASSERT(step != 0);
2395 	ASSERT(levels != 0);
2396 
2397 	if (val < base) {
2398 		/*
2399 		 * This is an underflow.
2400 		 */
2401 		lquanta[0] += incr;
2402 		return;
2403 	}
2404 
2405 	level = (val - base) / step;
2406 
2407 	if (level < levels) {
2408 		lquanta[level + 1] += incr;
2409 		return;
2410 	}
2411 
2412 	/*
2413 	 * This is an overflow.
2414 	 */
2415 	lquanta[levels + 1] += incr;
2416 }
2417 
2418 static int
dtrace_aggregate_llquantize_bucket(uint16_t factor,uint16_t low,uint16_t high,uint16_t nsteps,int64_t value)2419 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2420     uint16_t high, uint16_t nsteps, int64_t value)
2421 {
2422 	int64_t this = 1, last, next;
2423 	int base = 1, order;
2424 
2425 	ASSERT(factor <= nsteps);
2426 	ASSERT(nsteps % factor == 0);
2427 
2428 	for (order = 0; order < low; order++)
2429 		this *= factor;
2430 
2431 	/*
2432 	 * If our value is less than our factor taken to the power of the
2433 	 * low order of magnitude, it goes into the zeroth bucket.
2434 	 */
2435 	if (value < (last = this))
2436 		return (0);
2437 
2438 	for (this *= factor; order <= high; order++) {
2439 		int nbuckets = this > nsteps ? nsteps : this;
2440 
2441 		if ((next = this * factor) < this) {
2442 			/*
2443 			 * We should not generally get log/linear quantizations
2444 			 * with a high magnitude that allows 64-bits to
2445 			 * overflow, but we nonetheless protect against this
2446 			 * by explicitly checking for overflow, and clamping
2447 			 * our value accordingly.
2448 			 */
2449 			value = this - 1;
2450 		}
2451 
2452 		if (value < this) {
2453 			/*
2454 			 * If our value lies within this order of magnitude,
2455 			 * determine its position by taking the offset within
2456 			 * the order of magnitude, dividing by the bucket
2457 			 * width, and adding to our (accumulated) base.
2458 			 */
2459 			return (base + (value - last) / (this / nbuckets));
2460 		}
2461 
2462 		base += nbuckets - (nbuckets / factor);
2463 		last = this;
2464 		this = next;
2465 	}
2466 
2467 	/*
2468 	 * Our value is greater than or equal to our factor taken to the
2469 	 * power of one plus the high magnitude -- return the top bucket.
2470 	 */
2471 	return (base);
2472 }
2473 
2474 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2475 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2476 {
2477 	uint64_t arg = *llquanta++;
2478 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2479 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2480 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2481 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2482 
2483 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2484 	    low, high, nsteps, nval)] += incr;
2485 }
2486 
2487 /*ARGSUSED*/
2488 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2489 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2490 {
2491 	data[0]++;
2492 	data[1] += nval;
2493 }
2494 
2495 /*ARGSUSED*/
2496 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2497 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2498 {
2499 	int64_t snval = (int64_t)nval;
2500 	uint64_t tmp[2];
2501 
2502 	data[0]++;
2503 	data[1] += nval;
2504 
2505 	/*
2506 	 * What we want to say here is:
2507 	 *
2508 	 * data[2] += nval * nval;
2509 	 *
2510 	 * But given that nval is 64-bit, we could easily overflow, so
2511 	 * we do this as 128-bit arithmetic.
2512 	 */
2513 	if (snval < 0)
2514 		snval = -snval;
2515 
2516 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2517 	dtrace_add_128(data + 2, tmp, data + 2);
2518 }
2519 
2520 /*ARGSUSED*/
2521 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2522 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2523 {
2524 	*oval = *oval + 1;
2525 }
2526 
2527 /*ARGSUSED*/
2528 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2529 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2530 {
2531 	*oval += nval;
2532 }
2533 
2534 /*
2535  * Aggregate given the tuple in the principal data buffer, and the aggregating
2536  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2537  * buffer is specified as the buf parameter.  This routine does not return
2538  * failure; if there is no space in the aggregation buffer, the data will be
2539  * dropped, and a corresponding counter incremented.
2540  */
2541 static void
dtrace_aggregate(dtrace_aggregation_t * agg,dtrace_buffer_t * dbuf,intptr_t offset,dtrace_buffer_t * buf,uint64_t expr,uint64_t arg)2542 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2543     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2544 {
2545 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2546 	uint32_t i, ndx, size, fsize;
2547 	uint32_t align = sizeof (uint64_t) - 1;
2548 	dtrace_aggbuffer_t *agb;
2549 	dtrace_aggkey_t *key;
2550 	uint32_t hashval = 0, limit, isstr;
2551 	caddr_t tomax, data, kdata;
2552 	dtrace_actkind_t action;
2553 	dtrace_action_t *act;
2554 	size_t offs;
2555 
2556 	if (buf == NULL)
2557 		return;
2558 
2559 	if (!agg->dtag_hasarg) {
2560 		/*
2561 		 * Currently, only quantize() and lquantize() take additional
2562 		 * arguments, and they have the same semantics:  an increment
2563 		 * value that defaults to 1 when not present.  If additional
2564 		 * aggregating actions take arguments, the setting of the
2565 		 * default argument value will presumably have to become more
2566 		 * sophisticated...
2567 		 */
2568 		arg = 1;
2569 	}
2570 
2571 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2572 	size = rec->dtrd_offset - agg->dtag_base;
2573 	fsize = size + rec->dtrd_size;
2574 
2575 	ASSERT(dbuf->dtb_tomax != NULL);
2576 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2577 
2578 	if ((tomax = buf->dtb_tomax) == NULL) {
2579 		dtrace_buffer_drop(buf);
2580 		return;
2581 	}
2582 
2583 	/*
2584 	 * The metastructure is always at the bottom of the buffer.
2585 	 */
2586 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2587 	    sizeof (dtrace_aggbuffer_t));
2588 
2589 	if (buf->dtb_offset == 0) {
2590 		/*
2591 		 * We just kludge up approximately 1/8th of the size to be
2592 		 * buckets.  If this guess ends up being routinely
2593 		 * off-the-mark, we may need to dynamically readjust this
2594 		 * based on past performance.
2595 		 */
2596 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2597 
2598 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2599 		    (uintptr_t)tomax || hashsize == 0) {
2600 			/*
2601 			 * We've been given a ludicrously small buffer;
2602 			 * increment our drop count and leave.
2603 			 */
2604 			dtrace_buffer_drop(buf);
2605 			return;
2606 		}
2607 
2608 		/*
2609 		 * And now, a pathetic attempt to try to get a an odd (or
2610 		 * perchance, a prime) hash size for better hash distribution.
2611 		 */
2612 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2613 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2614 
2615 		agb->dtagb_hashsize = hashsize;
2616 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2617 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2618 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2619 
2620 		for (i = 0; i < agb->dtagb_hashsize; i++)
2621 			agb->dtagb_hash[i] = NULL;
2622 	}
2623 
2624 	ASSERT(agg->dtag_first != NULL);
2625 	ASSERT(agg->dtag_first->dta_intuple);
2626 
2627 	/*
2628 	 * Calculate the hash value based on the key.  Note that we _don't_
2629 	 * include the aggid in the hashing (but we will store it as part of
2630 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2631 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2632 	 * gets good distribution in practice.  The efficacy of the hashing
2633 	 * algorithm (and a comparison with other algorithms) may be found by
2634 	 * running the ::dtrace_aggstat MDB dcmd.
2635 	 */
2636 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2637 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2638 		limit = i + act->dta_rec.dtrd_size;
2639 		ASSERT(limit <= size);
2640 		isstr = DTRACEACT_ISSTRING(act);
2641 
2642 		for (; i < limit; i++) {
2643 			hashval += data[i];
2644 			hashval += (hashval << 10);
2645 			hashval ^= (hashval >> 6);
2646 
2647 			if (isstr && data[i] == '\0')
2648 				break;
2649 		}
2650 	}
2651 
2652 	hashval += (hashval << 3);
2653 	hashval ^= (hashval >> 11);
2654 	hashval += (hashval << 15);
2655 
2656 	/*
2657 	 * Yes, the divide here is expensive -- but it's generally the least
2658 	 * of the performance issues given the amount of data that we iterate
2659 	 * over to compute hash values, compare data, etc.
2660 	 */
2661 	ndx = hashval % agb->dtagb_hashsize;
2662 
2663 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2664 		ASSERT((caddr_t)key >= tomax);
2665 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2666 
2667 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2668 			continue;
2669 
2670 		kdata = key->dtak_data;
2671 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2672 
2673 		for (act = agg->dtag_first; act->dta_intuple;
2674 		    act = act->dta_next) {
2675 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2676 			limit = i + act->dta_rec.dtrd_size;
2677 			ASSERT(limit <= size);
2678 			isstr = DTRACEACT_ISSTRING(act);
2679 
2680 			for (; i < limit; i++) {
2681 				if (kdata[i] != data[i])
2682 					goto next;
2683 
2684 				if (isstr && data[i] == '\0')
2685 					break;
2686 			}
2687 		}
2688 
2689 		if (action != key->dtak_action) {
2690 			/*
2691 			 * We are aggregating on the same value in the same
2692 			 * aggregation with two different aggregating actions.
2693 			 * (This should have been picked up in the compiler,
2694 			 * so we may be dealing with errant or devious DIF.)
2695 			 * This is an error condition; we indicate as much,
2696 			 * and return.
2697 			 */
2698 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2699 			return;
2700 		}
2701 
2702 		/*
2703 		 * This is a hit:  we need to apply the aggregator to
2704 		 * the value at this key.
2705 		 */
2706 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2707 		return;
2708 next:
2709 		continue;
2710 	}
2711 
2712 	/*
2713 	 * We didn't find it.  We need to allocate some zero-filled space,
2714 	 * link it into the hash table appropriately, and apply the aggregator
2715 	 * to the (zero-filled) value.
2716 	 */
2717 	offs = buf->dtb_offset;
2718 	while (offs & (align - 1))
2719 		offs += sizeof (uint32_t);
2720 
2721 	/*
2722 	 * If we don't have enough room to both allocate a new key _and_
2723 	 * its associated data, increment the drop count and return.
2724 	 */
2725 	if ((uintptr_t)tomax + offs + fsize >
2726 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2727 		dtrace_buffer_drop(buf);
2728 		return;
2729 	}
2730 
2731 	/*CONSTCOND*/
2732 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2733 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2734 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2735 
2736 	key->dtak_data = kdata = tomax + offs;
2737 	buf->dtb_offset = offs + fsize;
2738 
2739 	/*
2740 	 * Now copy the data across.
2741 	 */
2742 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2743 
2744 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2745 		kdata[i] = data[i];
2746 
2747 	/*
2748 	 * Because strings are not zeroed out by default, we need to iterate
2749 	 * looking for actions that store strings, and we need to explicitly
2750 	 * pad these strings out with zeroes.
2751 	 */
2752 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2753 		int nul;
2754 
2755 		if (!DTRACEACT_ISSTRING(act))
2756 			continue;
2757 
2758 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2759 		limit = i + act->dta_rec.dtrd_size;
2760 		ASSERT(limit <= size);
2761 
2762 		for (nul = 0; i < limit; i++) {
2763 			if (nul) {
2764 				kdata[i] = '\0';
2765 				continue;
2766 			}
2767 
2768 			if (data[i] != '\0')
2769 				continue;
2770 
2771 			nul = 1;
2772 		}
2773 	}
2774 
2775 	for (i = size; i < fsize; i++)
2776 		kdata[i] = 0;
2777 
2778 	key->dtak_hashval = hashval;
2779 	key->dtak_size = size;
2780 	key->dtak_action = action;
2781 	key->dtak_next = agb->dtagb_hash[ndx];
2782 	agb->dtagb_hash[ndx] = key;
2783 
2784 	/*
2785 	 * Finally, apply the aggregator.
2786 	 */
2787 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2788 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2789 }
2790 
2791 /*
2792  * Given consumer state, this routine finds a speculation in the INACTIVE
2793  * state and transitions it into the ACTIVE state.  If there is no speculation
2794  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2795  * incremented -- it is up to the caller to take appropriate action.
2796  */
2797 static int
dtrace_speculation(dtrace_state_t * state)2798 dtrace_speculation(dtrace_state_t *state)
2799 {
2800 	int i = 0;
2801 	dtrace_speculation_state_t curstate;
2802 	uint32_t *stat = &state->dts_speculations_unavail, count;
2803 
2804 	while (i < state->dts_nspeculations) {
2805 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2806 
2807 		curstate = spec->dtsp_state;
2808 
2809 		if (curstate != DTRACESPEC_INACTIVE) {
2810 			if (curstate == DTRACESPEC_COMMITTINGMANY ||
2811 			    curstate == DTRACESPEC_COMMITTING ||
2812 			    curstate == DTRACESPEC_DISCARDING)
2813 				stat = &state->dts_speculations_busy;
2814 			i++;
2815 			continue;
2816 		}
2817 
2818 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2819 		    curstate, DTRACESPEC_ACTIVE) == curstate)
2820 			return (i + 1);
2821 	}
2822 
2823 	/*
2824 	 * We couldn't find a speculation.  If we found as much as a single
2825 	 * busy speculation buffer, we'll attribute this failure as "busy"
2826 	 * instead of "unavail".
2827 	 */
2828 	do {
2829 		count = *stat;
2830 	} while (dtrace_cas32(stat, count, count + 1) != count);
2831 
2832 	return (0);
2833 }
2834 
2835 /*
2836  * This routine commits an active speculation.  If the specified speculation
2837  * is not in a valid state to perform a commit(), this routine will silently do
2838  * nothing.  The state of the specified speculation is transitioned according
2839  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2840  */
2841 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2842 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2843     dtrace_specid_t which)
2844 {
2845 	dtrace_speculation_t *spec;
2846 	dtrace_buffer_t *src, *dest;
2847 	uintptr_t daddr, saddr, dlimit, slimit;
2848 	dtrace_speculation_state_t curstate, new = 0;
2849 	ssize_t offs;
2850 	uint64_t timestamp;
2851 
2852 	if (which == 0)
2853 		return;
2854 
2855 	if (which > state->dts_nspeculations) {
2856 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2857 		return;
2858 	}
2859 
2860 	spec = &state->dts_speculations[which - 1];
2861 	src = &spec->dtsp_buffer[cpu];
2862 	dest = &state->dts_buffer[cpu];
2863 
2864 	do {
2865 		curstate = spec->dtsp_state;
2866 
2867 		if (curstate == DTRACESPEC_COMMITTINGMANY)
2868 			break;
2869 
2870 		switch (curstate) {
2871 		case DTRACESPEC_INACTIVE:
2872 		case DTRACESPEC_DISCARDING:
2873 			return;
2874 
2875 		case DTRACESPEC_COMMITTING:
2876 			/*
2877 			 * This is only possible if we are (a) commit()'ing
2878 			 * without having done a prior speculate() on this CPU
2879 			 * and (b) racing with another commit() on a different
2880 			 * CPU.  There's nothing to do -- we just assert that
2881 			 * our offset is 0.
2882 			 */
2883 			ASSERT(src->dtb_offset == 0);
2884 			return;
2885 
2886 		case DTRACESPEC_ACTIVE:
2887 			new = DTRACESPEC_COMMITTING;
2888 			break;
2889 
2890 		case DTRACESPEC_ACTIVEONE:
2891 			/*
2892 			 * This speculation is active on one CPU.  If our
2893 			 * buffer offset is non-zero, we know that the one CPU
2894 			 * must be us.  Otherwise, we are committing on a
2895 			 * different CPU from the speculate(), and we must
2896 			 * rely on being asynchronously cleaned.
2897 			 */
2898 			if (src->dtb_offset != 0) {
2899 				new = DTRACESPEC_COMMITTING;
2900 				break;
2901 			}
2902 			/*FALLTHROUGH*/
2903 
2904 		case DTRACESPEC_ACTIVEMANY:
2905 			new = DTRACESPEC_COMMITTINGMANY;
2906 			break;
2907 
2908 		default:
2909 			ASSERT(0);
2910 		}
2911 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2912 	    curstate, new) != curstate);
2913 
2914 	/*
2915 	 * We have set the state to indicate that we are committing this
2916 	 * speculation.  Now reserve the necessary space in the destination
2917 	 * buffer.
2918 	 */
2919 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2920 	    sizeof (uint64_t), state, NULL)) < 0) {
2921 		dtrace_buffer_drop(dest);
2922 		goto out;
2923 	}
2924 
2925 	/*
2926 	 * We have sufficient space to copy the speculative buffer into the
2927 	 * primary buffer.  First, modify the speculative buffer, filling
2928 	 * in the timestamp of all entries with the curstate time.  The data
2929 	 * must have the commit() time rather than the time it was traced,
2930 	 * so that all entries in the primary buffer are in timestamp order.
2931 	 */
2932 	timestamp = dtrace_gethrtime();
2933 	saddr = (uintptr_t)src->dtb_tomax;
2934 	slimit = saddr + src->dtb_offset;
2935 	while (saddr < slimit) {
2936 		size_t size;
2937 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2938 
2939 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2940 			saddr += sizeof (dtrace_epid_t);
2941 			continue;
2942 		}
2943 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2944 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2945 
2946 		ASSERT3U(saddr + size, <=, slimit);
2947 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2948 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2949 
2950 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2951 
2952 		saddr += size;
2953 	}
2954 
2955 	/*
2956 	 * Copy the buffer across.  (Note that this is a
2957 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2958 	 * a serious performance issue, a high-performance DTrace-specific
2959 	 * bcopy() should obviously be invented.)
2960 	 */
2961 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2962 	dlimit = daddr + src->dtb_offset;
2963 	saddr = (uintptr_t)src->dtb_tomax;
2964 
2965 	/*
2966 	 * First, the aligned portion.
2967 	 */
2968 	while (dlimit - daddr >= sizeof (uint64_t)) {
2969 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2970 
2971 		daddr += sizeof (uint64_t);
2972 		saddr += sizeof (uint64_t);
2973 	}
2974 
2975 	/*
2976 	 * Now any left-over bit...
2977 	 */
2978 	while (dlimit - daddr)
2979 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2980 
2981 	/*
2982 	 * Finally, commit the reserved space in the destination buffer.
2983 	 */
2984 	dest->dtb_offset = offs + src->dtb_offset;
2985 
2986 out:
2987 	/*
2988 	 * If we're lucky enough to be the only active CPU on this speculation
2989 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2990 	 */
2991 	if (curstate == DTRACESPEC_ACTIVE ||
2992 	    (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2993 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2994 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2995 
2996 		ASSERT(rval == DTRACESPEC_COMMITTING);
2997 	}
2998 
2999 	src->dtb_offset = 0;
3000 	src->dtb_xamot_drops += src->dtb_drops;
3001 	src->dtb_drops = 0;
3002 }
3003 
3004 /*
3005  * This routine discards an active speculation.  If the specified speculation
3006  * is not in a valid state to perform a discard(), this routine will silently
3007  * do nothing.  The state of the specified speculation is transitioned
3008  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3009  */
3010 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)3011 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3012     dtrace_specid_t which)
3013 {
3014 	dtrace_speculation_t *spec;
3015 	dtrace_speculation_state_t curstate, new = 0;
3016 	dtrace_buffer_t *buf;
3017 
3018 	if (which == 0)
3019 		return;
3020 
3021 	if (which > state->dts_nspeculations) {
3022 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3023 		return;
3024 	}
3025 
3026 	spec = &state->dts_speculations[which - 1];
3027 	buf = &spec->dtsp_buffer[cpu];
3028 
3029 	do {
3030 		curstate = spec->dtsp_state;
3031 
3032 		switch (curstate) {
3033 		case DTRACESPEC_INACTIVE:
3034 		case DTRACESPEC_COMMITTINGMANY:
3035 		case DTRACESPEC_COMMITTING:
3036 		case DTRACESPEC_DISCARDING:
3037 			return;
3038 
3039 		case DTRACESPEC_ACTIVE:
3040 		case DTRACESPEC_ACTIVEMANY:
3041 			new = DTRACESPEC_DISCARDING;
3042 			break;
3043 
3044 		case DTRACESPEC_ACTIVEONE:
3045 			if (buf->dtb_offset != 0) {
3046 				new = DTRACESPEC_INACTIVE;
3047 			} else {
3048 				new = DTRACESPEC_DISCARDING;
3049 			}
3050 			break;
3051 
3052 		default:
3053 			ASSERT(0);
3054 		}
3055 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3056 	    curstate, new) != curstate);
3057 
3058 	buf->dtb_offset = 0;
3059 	buf->dtb_drops = 0;
3060 }
3061 
3062 /*
3063  * Note:  not called from probe context.  This function is called
3064  * asynchronously from cross call context to clean any speculations that are
3065  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3066  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3067  * speculation.
3068  */
3069 static void
dtrace_speculation_clean_here(dtrace_state_t * state)3070 dtrace_speculation_clean_here(dtrace_state_t *state)
3071 {
3072 	dtrace_icookie_t cookie;
3073 	processorid_t cpu = curcpu;
3074 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3075 	dtrace_specid_t i;
3076 
3077 	cookie = dtrace_interrupt_disable();
3078 
3079 	if (dest->dtb_tomax == NULL) {
3080 		dtrace_interrupt_enable(cookie);
3081 		return;
3082 	}
3083 
3084 	for (i = 0; i < state->dts_nspeculations; i++) {
3085 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3086 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3087 
3088 		if (src->dtb_tomax == NULL)
3089 			continue;
3090 
3091 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3092 			src->dtb_offset = 0;
3093 			continue;
3094 		}
3095 
3096 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3097 			continue;
3098 
3099 		if (src->dtb_offset == 0)
3100 			continue;
3101 
3102 		dtrace_speculation_commit(state, cpu, i + 1);
3103 	}
3104 
3105 	dtrace_interrupt_enable(cookie);
3106 }
3107 
3108 /*
3109  * Note:  not called from probe context.  This function is called
3110  * asynchronously (and at a regular interval) to clean any speculations that
3111  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3112  * is work to be done, it cross calls all CPUs to perform that work;
3113  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3114  * INACTIVE state until they have been cleaned by all CPUs.
3115  */
3116 static void
dtrace_speculation_clean(dtrace_state_t * state)3117 dtrace_speculation_clean(dtrace_state_t *state)
3118 {
3119 	int work = 0, rv;
3120 	dtrace_specid_t i;
3121 
3122 	for (i = 0; i < state->dts_nspeculations; i++) {
3123 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3124 
3125 		ASSERT(!spec->dtsp_cleaning);
3126 
3127 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3128 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3129 			continue;
3130 
3131 		work++;
3132 		spec->dtsp_cleaning = 1;
3133 	}
3134 
3135 	if (!work)
3136 		return;
3137 
3138 	dtrace_xcall(DTRACE_CPUALL,
3139 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3140 
3141 	/*
3142 	 * We now know that all CPUs have committed or discarded their
3143 	 * speculation buffers, as appropriate.  We can now set the state
3144 	 * to inactive.
3145 	 */
3146 	for (i = 0; i < state->dts_nspeculations; i++) {
3147 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3148 		dtrace_speculation_state_t curstate, new;
3149 
3150 		if (!spec->dtsp_cleaning)
3151 			continue;
3152 
3153 		curstate = spec->dtsp_state;
3154 		ASSERT(curstate == DTRACESPEC_DISCARDING ||
3155 		    curstate == DTRACESPEC_COMMITTINGMANY);
3156 
3157 		new = DTRACESPEC_INACTIVE;
3158 
3159 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3160 		ASSERT(rv == curstate);
3161 		spec->dtsp_cleaning = 0;
3162 	}
3163 }
3164 
3165 /*
3166  * Called as part of a speculate() to get the speculative buffer associated
3167  * with a given speculation.  Returns NULL if the specified speculation is not
3168  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3169  * the active CPU is not the specified CPU -- the speculation will be
3170  * atomically transitioned into the ACTIVEMANY state.
3171  */
3172 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3173 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3174     dtrace_specid_t which)
3175 {
3176 	dtrace_speculation_t *spec;
3177 	dtrace_speculation_state_t curstate, new = 0;
3178 	dtrace_buffer_t *buf;
3179 
3180 	if (which == 0)
3181 		return (NULL);
3182 
3183 	if (which > state->dts_nspeculations) {
3184 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3185 		return (NULL);
3186 	}
3187 
3188 	spec = &state->dts_speculations[which - 1];
3189 	buf = &spec->dtsp_buffer[cpuid];
3190 
3191 	do {
3192 		curstate = spec->dtsp_state;
3193 
3194 		switch (curstate) {
3195 		case DTRACESPEC_INACTIVE:
3196 		case DTRACESPEC_COMMITTINGMANY:
3197 		case DTRACESPEC_DISCARDING:
3198 			return (NULL);
3199 
3200 		case DTRACESPEC_COMMITTING:
3201 			ASSERT(buf->dtb_offset == 0);
3202 			return (NULL);
3203 
3204 		case DTRACESPEC_ACTIVEONE:
3205 			/*
3206 			 * This speculation is currently active on one CPU.
3207 			 * Check the offset in the buffer; if it's non-zero,
3208 			 * that CPU must be us (and we leave the state alone).
3209 			 * If it's zero, assume that we're starting on a new
3210 			 * CPU -- and change the state to indicate that the
3211 			 * speculation is active on more than one CPU.
3212 			 */
3213 			if (buf->dtb_offset != 0)
3214 				return (buf);
3215 
3216 			new = DTRACESPEC_ACTIVEMANY;
3217 			break;
3218 
3219 		case DTRACESPEC_ACTIVEMANY:
3220 			return (buf);
3221 
3222 		case DTRACESPEC_ACTIVE:
3223 			new = DTRACESPEC_ACTIVEONE;
3224 			break;
3225 
3226 		default:
3227 			ASSERT(0);
3228 		}
3229 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3230 	    curstate, new) != curstate);
3231 
3232 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3233 	return (buf);
3234 }
3235 
3236 /*
3237  * Return a string.  In the event that the user lacks the privilege to access
3238  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3239  * don't fail access checking.
3240  *
3241  * dtrace_dif_variable() uses this routine as a helper for various
3242  * builtin values such as 'execname' and 'probefunc.'
3243  */
3244 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3245 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3246     dtrace_mstate_t *mstate)
3247 {
3248 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3249 	uintptr_t ret;
3250 	size_t strsz;
3251 
3252 	/*
3253 	 * The easy case: this probe is allowed to read all of memory, so
3254 	 * we can just return this as a vanilla pointer.
3255 	 */
3256 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3257 		return (addr);
3258 
3259 	/*
3260 	 * This is the tougher case: we copy the string in question from
3261 	 * kernel memory into scratch memory and return it that way: this
3262 	 * ensures that we won't trip up when access checking tests the
3263 	 * BYREF return value.
3264 	 */
3265 	strsz = dtrace_strlen((char *)addr, size) + 1;
3266 
3267 	if (mstate->dtms_scratch_ptr + strsz >
3268 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3269 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3270 		return (0);
3271 	}
3272 
3273 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3274 	    strsz);
3275 	ret = mstate->dtms_scratch_ptr;
3276 	mstate->dtms_scratch_ptr += strsz;
3277 	return (ret);
3278 }
3279 
3280 /*
3281  * Return a string from a memoy address which is known to have one or
3282  * more concatenated, individually zero terminated, sub-strings.
3283  * In the event that the user lacks the privilege to access
3284  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3285  * don't fail access checking.
3286  *
3287  * dtrace_dif_variable() uses this routine as a helper for various
3288  * builtin values such as 'execargs'.
3289  */
3290 static uintptr_t
dtrace_dif_varstrz(uintptr_t addr,size_t strsz,dtrace_state_t * state,dtrace_mstate_t * mstate)3291 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3292     dtrace_mstate_t *mstate)
3293 {
3294 	char *p;
3295 	size_t i;
3296 	uintptr_t ret;
3297 
3298 	if (mstate->dtms_scratch_ptr + strsz >
3299 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3300 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3301 		return (0);
3302 	}
3303 
3304 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3305 	    strsz);
3306 
3307 	/* Replace sub-string termination characters with a space. */
3308 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3309 	    p++, i++)
3310 		if (*p == '\0')
3311 			*p = ' ';
3312 
3313 	ret = mstate->dtms_scratch_ptr;
3314 	mstate->dtms_scratch_ptr += strsz;
3315 	return (ret);
3316 }
3317 
3318 /*
3319  * This function implements the DIF emulator's variable lookups.  The emulator
3320  * passes a reserved variable identifier and optional built-in array index.
3321  */
3322 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3323 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3324     uint64_t ndx)
3325 {
3326 	/*
3327 	 * If we're accessing one of the uncached arguments, we'll turn this
3328 	 * into a reference in the args array.
3329 	 */
3330 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3331 		ndx = v - DIF_VAR_ARG0;
3332 		v = DIF_VAR_ARGS;
3333 	}
3334 
3335 	switch (v) {
3336 	case DIF_VAR_ARGS:
3337 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3338 		if (ndx >= sizeof (mstate->dtms_arg) /
3339 		    sizeof (mstate->dtms_arg[0])) {
3340 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3341 			dtrace_provider_t *pv;
3342 			uint64_t val;
3343 
3344 			pv = mstate->dtms_probe->dtpr_provider;
3345 			if (pv->dtpv_pops.dtps_getargval != NULL)
3346 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3347 				    mstate->dtms_probe->dtpr_id,
3348 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3349 			else
3350 				val = dtrace_getarg(ndx, aframes);
3351 
3352 			/*
3353 			 * This is regrettably required to keep the compiler
3354 			 * from tail-optimizing the call to dtrace_getarg().
3355 			 * The condition always evaluates to true, but the
3356 			 * compiler has no way of figuring that out a priori.
3357 			 * (None of this would be necessary if the compiler
3358 			 * could be relied upon to _always_ tail-optimize
3359 			 * the call to dtrace_getarg() -- but it can't.)
3360 			 */
3361 			if (mstate->dtms_probe != NULL)
3362 				return (val);
3363 
3364 			ASSERT(0);
3365 		}
3366 
3367 		return (mstate->dtms_arg[ndx]);
3368 
3369 	case DIF_VAR_REGS:
3370 	case DIF_VAR_UREGS: {
3371 		struct trapframe *tframe;
3372 
3373 		if (!dtrace_priv_proc(state))
3374 			return (0);
3375 
3376 		if (v == DIF_VAR_REGS)
3377 			tframe = curthread->t_dtrace_trapframe;
3378 		else
3379 			tframe = curthread->td_frame;
3380 
3381 		if (tframe == NULL) {
3382 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3383 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3384 			return (0);
3385 		}
3386 
3387 		return (dtrace_getreg(tframe, ndx));
3388 	}
3389 
3390 	case DIF_VAR_CURTHREAD:
3391 		if (!dtrace_priv_proc(state))
3392 			return (0);
3393 		return ((uint64_t)(uintptr_t)curthread);
3394 
3395 	case DIF_VAR_TIMESTAMP:
3396 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3397 			mstate->dtms_timestamp = dtrace_gethrtime();
3398 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3399 		}
3400 		return (mstate->dtms_timestamp);
3401 
3402 	case DIF_VAR_VTIMESTAMP:
3403 		ASSERT(dtrace_vtime_references != 0);
3404 		return (curthread->t_dtrace_vtime);
3405 
3406 	case DIF_VAR_WALLTIMESTAMP:
3407 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3408 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3409 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3410 		}
3411 		return (mstate->dtms_walltimestamp);
3412 
3413 #ifdef illumos
3414 	case DIF_VAR_IPL:
3415 		if (!dtrace_priv_kernel(state))
3416 			return (0);
3417 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3418 			mstate->dtms_ipl = dtrace_getipl();
3419 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3420 		}
3421 		return (mstate->dtms_ipl);
3422 #endif
3423 
3424 	case DIF_VAR_EPID:
3425 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3426 		return (mstate->dtms_epid);
3427 
3428 	case DIF_VAR_ID:
3429 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3430 		return (mstate->dtms_probe->dtpr_id);
3431 
3432 	case DIF_VAR_STACKDEPTH:
3433 		if (!dtrace_priv_kernel(state))
3434 			return (0);
3435 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3436 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3437 
3438 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3439 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3440 		}
3441 		return (mstate->dtms_stackdepth);
3442 
3443 	case DIF_VAR_USTACKDEPTH:
3444 		if (!dtrace_priv_proc(state))
3445 			return (0);
3446 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3447 			/*
3448 			 * See comment in DIF_VAR_PID.
3449 			 */
3450 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3451 			    CPU_ON_INTR(CPU)) {
3452 				mstate->dtms_ustackdepth = 0;
3453 			} else {
3454 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3455 				mstate->dtms_ustackdepth =
3456 				    dtrace_getustackdepth();
3457 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3458 			}
3459 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3460 		}
3461 		return (mstate->dtms_ustackdepth);
3462 
3463 	case DIF_VAR_CALLER:
3464 		if (!dtrace_priv_kernel(state))
3465 			return (0);
3466 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3467 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3468 
3469 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3470 				/*
3471 				 * If this is an unanchored probe, we are
3472 				 * required to go through the slow path:
3473 				 * dtrace_caller() only guarantees correct
3474 				 * results for anchored probes.
3475 				 */
3476 				pc_t caller[2] = {0, 0};
3477 
3478 				dtrace_getpcstack(caller, 2, aframes,
3479 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3480 				mstate->dtms_caller = caller[1];
3481 			} else if ((mstate->dtms_caller =
3482 			    dtrace_caller(aframes)) == -1) {
3483 				/*
3484 				 * We have failed to do this the quick way;
3485 				 * we must resort to the slower approach of
3486 				 * calling dtrace_getpcstack().
3487 				 */
3488 				pc_t caller = 0;
3489 
3490 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3491 				mstate->dtms_caller = caller;
3492 			}
3493 
3494 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3495 		}
3496 		return (mstate->dtms_caller);
3497 
3498 	case DIF_VAR_UCALLER:
3499 		if (!dtrace_priv_proc(state))
3500 			return (0);
3501 
3502 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3503 			uint64_t ustack[3];
3504 
3505 			/*
3506 			 * dtrace_getupcstack() fills in the first uint64_t
3507 			 * with the current PID.  The second uint64_t will
3508 			 * be the program counter at user-level.  The third
3509 			 * uint64_t will contain the caller, which is what
3510 			 * we're after.
3511 			 */
3512 			ustack[2] = 0;
3513 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3514 			dtrace_getupcstack(ustack, 3);
3515 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3516 			mstate->dtms_ucaller = ustack[2];
3517 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3518 		}
3519 
3520 		return (mstate->dtms_ucaller);
3521 
3522 	case DIF_VAR_PROBEPROV:
3523 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3524 		return (dtrace_dif_varstr(
3525 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3526 		    state, mstate));
3527 
3528 	case DIF_VAR_PROBEMOD:
3529 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3530 		return (dtrace_dif_varstr(
3531 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3532 		    state, mstate));
3533 
3534 	case DIF_VAR_PROBEFUNC:
3535 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3536 		return (dtrace_dif_varstr(
3537 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3538 		    state, mstate));
3539 
3540 	case DIF_VAR_PROBENAME:
3541 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3542 		return (dtrace_dif_varstr(
3543 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3544 		    state, mstate));
3545 
3546 	case DIF_VAR_PID:
3547 		if (!dtrace_priv_proc(state))
3548 			return (0);
3549 
3550 #ifdef illumos
3551 		/*
3552 		 * Note that we are assuming that an unanchored probe is
3553 		 * always due to a high-level interrupt.  (And we're assuming
3554 		 * that there is only a single high level interrupt.)
3555 		 */
3556 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3557 			return (pid0.pid_id);
3558 
3559 		/*
3560 		 * It is always safe to dereference one's own t_procp pointer:
3561 		 * it always points to a valid, allocated proc structure.
3562 		 * Further, it is always safe to dereference the p_pidp member
3563 		 * of one's own proc structure.  (These are truisms becuase
3564 		 * threads and processes don't clean up their own state --
3565 		 * they leave that task to whomever reaps them.)
3566 		 */
3567 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3568 #else
3569 		return ((uint64_t)curproc->p_pid);
3570 #endif
3571 
3572 	case DIF_VAR_PPID:
3573 		if (!dtrace_priv_proc(state))
3574 			return (0);
3575 
3576 #ifdef illumos
3577 		/*
3578 		 * See comment in DIF_VAR_PID.
3579 		 */
3580 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3581 			return (pid0.pid_id);
3582 
3583 		/*
3584 		 * It is always safe to dereference one's own t_procp pointer:
3585 		 * it always points to a valid, allocated proc structure.
3586 		 * (This is true because threads don't clean up their own
3587 		 * state -- they leave that task to whomever reaps them.)
3588 		 */
3589 		return ((uint64_t)curthread->t_procp->p_ppid);
3590 #else
3591 		if (curproc->p_pid == proc0.p_pid)
3592 			return (curproc->p_pid);
3593 		else
3594 			return (curproc->p_pptr->p_pid);
3595 #endif
3596 
3597 	case DIF_VAR_TID:
3598 #ifdef illumos
3599 		/*
3600 		 * See comment in DIF_VAR_PID.
3601 		 */
3602 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3603 			return (0);
3604 #endif
3605 
3606 		return ((uint64_t)curthread->t_tid);
3607 
3608 	case DIF_VAR_EXECARGS: {
3609 		struct pargs *p_args = curthread->td_proc->p_args;
3610 
3611 		if (p_args == NULL)
3612 			return(0);
3613 
3614 		return (dtrace_dif_varstrz(
3615 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3616 	}
3617 
3618 	case DIF_VAR_EXECNAME:
3619 #ifdef illumos
3620 		if (!dtrace_priv_proc(state))
3621 			return (0);
3622 
3623 		/*
3624 		 * See comment in DIF_VAR_PID.
3625 		 */
3626 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3627 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3628 
3629 		/*
3630 		 * It is always safe to dereference one's own t_procp pointer:
3631 		 * it always points to a valid, allocated proc structure.
3632 		 * (This is true because threads don't clean up their own
3633 		 * state -- they leave that task to whomever reaps them.)
3634 		 */
3635 		return (dtrace_dif_varstr(
3636 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3637 		    state, mstate));
3638 #else
3639 		return (dtrace_dif_varstr(
3640 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3641 #endif
3642 
3643 	case DIF_VAR_ZONENAME:
3644 #ifdef illumos
3645 		if (!dtrace_priv_proc(state))
3646 			return (0);
3647 
3648 		/*
3649 		 * See comment in DIF_VAR_PID.
3650 		 */
3651 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3652 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3653 
3654 		/*
3655 		 * It is always safe to dereference one's own t_procp pointer:
3656 		 * it always points to a valid, allocated proc structure.
3657 		 * (This is true because threads don't clean up their own
3658 		 * state -- they leave that task to whomever reaps them.)
3659 		 */
3660 		return (dtrace_dif_varstr(
3661 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3662 		    state, mstate));
3663 #elif defined(__FreeBSD__)
3664 	/*
3665 	 * On FreeBSD, we introduce compatibility to zonename by falling through
3666 	 * into jailname.
3667 	 */
3668 	case DIF_VAR_JAILNAME:
3669 		if (!dtrace_priv_kernel(state))
3670 			return (0);
3671 
3672 		return (dtrace_dif_varstr(
3673 		    (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3674 		    state, mstate));
3675 
3676 	case DIF_VAR_JID:
3677 		if (!dtrace_priv_kernel(state))
3678 			return (0);
3679 
3680 		return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3681 #else
3682 		return (0);
3683 #endif
3684 
3685 	case DIF_VAR_UID:
3686 		if (!dtrace_priv_proc(state))
3687 			return (0);
3688 
3689 #ifdef illumos
3690 		/*
3691 		 * See comment in DIF_VAR_PID.
3692 		 */
3693 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3694 			return ((uint64_t)p0.p_cred->cr_uid);
3695 
3696 		/*
3697 		 * It is always safe to dereference one's own t_procp pointer:
3698 		 * it always points to a valid, allocated proc structure.
3699 		 * (This is true because threads don't clean up their own
3700 		 * state -- they leave that task to whomever reaps them.)
3701 		 *
3702 		 * Additionally, it is safe to dereference one's own process
3703 		 * credential, since this is never NULL after process birth.
3704 		 */
3705 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3706 #else
3707 		return ((uint64_t)curthread->td_ucred->cr_uid);
3708 #endif
3709 
3710 	case DIF_VAR_GID:
3711 		if (!dtrace_priv_proc(state))
3712 			return (0);
3713 
3714 #ifdef illumos
3715 		/*
3716 		 * See comment in DIF_VAR_PID.
3717 		 */
3718 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3719 			return ((uint64_t)p0.p_cred->cr_gid);
3720 
3721 		/*
3722 		 * It is always safe to dereference one's own t_procp pointer:
3723 		 * it always points to a valid, allocated proc structure.
3724 		 * (This is true because threads don't clean up their own
3725 		 * state -- they leave that task to whomever reaps them.)
3726 		 *
3727 		 * Additionally, it is safe to dereference one's own process
3728 		 * credential, since this is never NULL after process birth.
3729 		 */
3730 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3731 #else
3732 		return ((uint64_t)curthread->td_ucred->cr_gid);
3733 #endif
3734 
3735 	case DIF_VAR_ERRNO: {
3736 #ifdef illumos
3737 		klwp_t *lwp;
3738 		if (!dtrace_priv_proc(state))
3739 			return (0);
3740 
3741 		/*
3742 		 * See comment in DIF_VAR_PID.
3743 		 */
3744 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3745 			return (0);
3746 
3747 		/*
3748 		 * It is always safe to dereference one's own t_lwp pointer in
3749 		 * the event that this pointer is non-NULL.  (This is true
3750 		 * because threads and lwps don't clean up their own state --
3751 		 * they leave that task to whomever reaps them.)
3752 		 */
3753 		if ((lwp = curthread->t_lwp) == NULL)
3754 			return (0);
3755 
3756 		return ((uint64_t)lwp->lwp_errno);
3757 #else
3758 		return (curthread->td_errno);
3759 #endif
3760 	}
3761 #ifndef illumos
3762 	case DIF_VAR_CPU: {
3763 		return curcpu;
3764 	}
3765 #endif
3766 	default:
3767 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3768 		return (0);
3769 	}
3770 }
3771 
3772 
3773 typedef enum dtrace_json_state {
3774 	DTRACE_JSON_REST = 1,
3775 	DTRACE_JSON_OBJECT,
3776 	DTRACE_JSON_STRING,
3777 	DTRACE_JSON_STRING_ESCAPE,
3778 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3779 	DTRACE_JSON_COLON,
3780 	DTRACE_JSON_COMMA,
3781 	DTRACE_JSON_VALUE,
3782 	DTRACE_JSON_IDENTIFIER,
3783 	DTRACE_JSON_NUMBER,
3784 	DTRACE_JSON_NUMBER_FRAC,
3785 	DTRACE_JSON_NUMBER_EXP,
3786 	DTRACE_JSON_COLLECT_OBJECT
3787 } dtrace_json_state_t;
3788 
3789 /*
3790  * This function possesses just enough knowledge about JSON to extract a single
3791  * value from a JSON string and store it in the scratch buffer.  It is able
3792  * to extract nested object values, and members of arrays by index.
3793  *
3794  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3795  * be looked up as we descend into the object tree.  e.g.
3796  *
3797  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3798  *       with nelems = 5.
3799  *
3800  * The run time of this function must be bounded above by strsize to limit the
3801  * amount of work done in probe context.  As such, it is implemented as a
3802  * simple state machine, reading one character at a time using safe loads
3803  * until we find the requested element, hit a parsing error or run off the
3804  * end of the object or string.
3805  *
3806  * As there is no way for a subroutine to return an error without interrupting
3807  * clause execution, we simply return NULL in the event of a missing key or any
3808  * other error condition.  Each NULL return in this function is commented with
3809  * the error condition it represents -- parsing or otherwise.
3810  *
3811  * The set of states for the state machine closely matches the JSON
3812  * specification (http://json.org/).  Briefly:
3813  *
3814  *   DTRACE_JSON_REST:
3815  *     Skip whitespace until we find either a top-level Object, moving
3816  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3817  *
3818  *   DTRACE_JSON_OBJECT:
3819  *     Locate the next key String in an Object.  Sets a flag to denote
3820  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3821  *
3822  *   DTRACE_JSON_COLON:
3823  *     Skip whitespace until we find the colon that separates key Strings
3824  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3825  *
3826  *   DTRACE_JSON_VALUE:
3827  *     Detects the type of the next value (String, Number, Identifier, Object
3828  *     or Array) and routes to the states that process that type.  Here we also
3829  *     deal with the element selector list if we are requested to traverse down
3830  *     into the object tree.
3831  *
3832  *   DTRACE_JSON_COMMA:
3833  *     Skip whitespace until we find the comma that separates key-value pairs
3834  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3835  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3836  *     states return to this state at the end of their value, unless otherwise
3837  *     noted.
3838  *
3839  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3840  *     Processes a Number literal from the JSON, including any exponent
3841  *     component that may be present.  Numbers are returned as strings, which
3842  *     may be passed to strtoll() if an integer is required.
3843  *
3844  *   DTRACE_JSON_IDENTIFIER:
3845  *     Processes a "true", "false" or "null" literal in the JSON.
3846  *
3847  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3848  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3849  *     Processes a String literal from the JSON, whether the String denotes
3850  *     a key, a value or part of a larger Object.  Handles all escape sequences
3851  *     present in the specification, including four-digit unicode characters,
3852  *     but merely includes the escape sequence without converting it to the
3853  *     actual escaped character.  If the String is flagged as a key, we
3854  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3855  *
3856  *   DTRACE_JSON_COLLECT_OBJECT:
3857  *     This state collects an entire Object (or Array), correctly handling
3858  *     embedded strings.  If the full element selector list matches this nested
3859  *     object, we return the Object in full as a string.  If not, we use this
3860  *     state to skip to the next value at this level and continue processing.
3861  *
3862  * NOTE: This function uses various macros from strtolctype.h to manipulate
3863  * digit values, etc -- these have all been checked to ensure they make
3864  * no additional function calls.
3865  */
3866 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3867 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3868     char *dest)
3869 {
3870 	dtrace_json_state_t state = DTRACE_JSON_REST;
3871 	int64_t array_elem = INT64_MIN;
3872 	int64_t array_pos = 0;
3873 	uint8_t escape_unicount = 0;
3874 	boolean_t string_is_key = B_FALSE;
3875 	boolean_t collect_object = B_FALSE;
3876 	boolean_t found_key = B_FALSE;
3877 	boolean_t in_array = B_FALSE;
3878 	uint32_t braces = 0, brackets = 0;
3879 	char *elem = elemlist;
3880 	char *dd = dest;
3881 	uintptr_t cur;
3882 
3883 	for (cur = json; cur < json + size; cur++) {
3884 		char cc = dtrace_load8(cur);
3885 		if (cc == '\0')
3886 			return (NULL);
3887 
3888 		switch (state) {
3889 		case DTRACE_JSON_REST:
3890 			if (isspace(cc))
3891 				break;
3892 
3893 			if (cc == '{') {
3894 				state = DTRACE_JSON_OBJECT;
3895 				break;
3896 			}
3897 
3898 			if (cc == '[') {
3899 				in_array = B_TRUE;
3900 				array_pos = 0;
3901 				array_elem = dtrace_strtoll(elem, 10, size);
3902 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3903 				state = DTRACE_JSON_VALUE;
3904 				break;
3905 			}
3906 
3907 			/*
3908 			 * ERROR: expected to find a top-level object or array.
3909 			 */
3910 			return (NULL);
3911 		case DTRACE_JSON_OBJECT:
3912 			if (isspace(cc))
3913 				break;
3914 
3915 			if (cc == '"') {
3916 				state = DTRACE_JSON_STRING;
3917 				string_is_key = B_TRUE;
3918 				break;
3919 			}
3920 
3921 			/*
3922 			 * ERROR: either the object did not start with a key
3923 			 * string, or we've run off the end of the object
3924 			 * without finding the requested key.
3925 			 */
3926 			return (NULL);
3927 		case DTRACE_JSON_STRING:
3928 			if (cc == '\\') {
3929 				*dd++ = '\\';
3930 				state = DTRACE_JSON_STRING_ESCAPE;
3931 				break;
3932 			}
3933 
3934 			if (cc == '"') {
3935 				if (collect_object) {
3936 					/*
3937 					 * We don't reset the dest here, as
3938 					 * the string is part of a larger
3939 					 * object being collected.
3940 					 */
3941 					*dd++ = cc;
3942 					collect_object = B_FALSE;
3943 					state = DTRACE_JSON_COLLECT_OBJECT;
3944 					break;
3945 				}
3946 				*dd = '\0';
3947 				dd = dest; /* reset string buffer */
3948 				if (string_is_key) {
3949 					if (dtrace_strncmp(dest, elem,
3950 					    size) == 0)
3951 						found_key = B_TRUE;
3952 				} else if (found_key) {
3953 					if (nelems > 1) {
3954 						/*
3955 						 * We expected an object, not
3956 						 * this string.
3957 						 */
3958 						return (NULL);
3959 					}
3960 					return (dest);
3961 				}
3962 				state = string_is_key ? DTRACE_JSON_COLON :
3963 				    DTRACE_JSON_COMMA;
3964 				string_is_key = B_FALSE;
3965 				break;
3966 			}
3967 
3968 			*dd++ = cc;
3969 			break;
3970 		case DTRACE_JSON_STRING_ESCAPE:
3971 			*dd++ = cc;
3972 			if (cc == 'u') {
3973 				escape_unicount = 0;
3974 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3975 			} else {
3976 				state = DTRACE_JSON_STRING;
3977 			}
3978 			break;
3979 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3980 			if (!isxdigit(cc)) {
3981 				/*
3982 				 * ERROR: invalid unicode escape, expected
3983 				 * four valid hexidecimal digits.
3984 				 */
3985 				return (NULL);
3986 			}
3987 
3988 			*dd++ = cc;
3989 			if (++escape_unicount == 4)
3990 				state = DTRACE_JSON_STRING;
3991 			break;
3992 		case DTRACE_JSON_COLON:
3993 			if (isspace(cc))
3994 				break;
3995 
3996 			if (cc == ':') {
3997 				state = DTRACE_JSON_VALUE;
3998 				break;
3999 			}
4000 
4001 			/*
4002 			 * ERROR: expected a colon.
4003 			 */
4004 			return (NULL);
4005 		case DTRACE_JSON_COMMA:
4006 			if (isspace(cc))
4007 				break;
4008 
4009 			if (cc == ',') {
4010 				if (in_array) {
4011 					state = DTRACE_JSON_VALUE;
4012 					if (++array_pos == array_elem)
4013 						found_key = B_TRUE;
4014 				} else {
4015 					state = DTRACE_JSON_OBJECT;
4016 				}
4017 				break;
4018 			}
4019 
4020 			/*
4021 			 * ERROR: either we hit an unexpected character, or
4022 			 * we reached the end of the object or array without
4023 			 * finding the requested key.
4024 			 */
4025 			return (NULL);
4026 		case DTRACE_JSON_IDENTIFIER:
4027 			if (islower(cc)) {
4028 				*dd++ = cc;
4029 				break;
4030 			}
4031 
4032 			*dd = '\0';
4033 			dd = dest; /* reset string buffer */
4034 
4035 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
4036 			    dtrace_strncmp(dest, "false", 6) == 0 ||
4037 			    dtrace_strncmp(dest, "null", 5) == 0) {
4038 				if (found_key) {
4039 					if (nelems > 1) {
4040 						/*
4041 						 * ERROR: We expected an object,
4042 						 * not this identifier.
4043 						 */
4044 						return (NULL);
4045 					}
4046 					return (dest);
4047 				} else {
4048 					cur--;
4049 					state = DTRACE_JSON_COMMA;
4050 					break;
4051 				}
4052 			}
4053 
4054 			/*
4055 			 * ERROR: we did not recognise the identifier as one
4056 			 * of those in the JSON specification.
4057 			 */
4058 			return (NULL);
4059 		case DTRACE_JSON_NUMBER:
4060 			if (cc == '.') {
4061 				*dd++ = cc;
4062 				state = DTRACE_JSON_NUMBER_FRAC;
4063 				break;
4064 			}
4065 
4066 			if (cc == 'x' || cc == 'X') {
4067 				/*
4068 				 * ERROR: specification explicitly excludes
4069 				 * hexidecimal or octal numbers.
4070 				 */
4071 				return (NULL);
4072 			}
4073 
4074 			/* FALLTHRU */
4075 		case DTRACE_JSON_NUMBER_FRAC:
4076 			if (cc == 'e' || cc == 'E') {
4077 				*dd++ = cc;
4078 				state = DTRACE_JSON_NUMBER_EXP;
4079 				break;
4080 			}
4081 
4082 			if (cc == '+' || cc == '-') {
4083 				/*
4084 				 * ERROR: expect sign as part of exponent only.
4085 				 */
4086 				return (NULL);
4087 			}
4088 			/* FALLTHRU */
4089 		case DTRACE_JSON_NUMBER_EXP:
4090 			if (isdigit(cc) || cc == '+' || cc == '-') {
4091 				*dd++ = cc;
4092 				break;
4093 			}
4094 
4095 			*dd = '\0';
4096 			dd = dest; /* reset string buffer */
4097 			if (found_key) {
4098 				if (nelems > 1) {
4099 					/*
4100 					 * ERROR: We expected an object, not
4101 					 * this number.
4102 					 */
4103 					return (NULL);
4104 				}
4105 				return (dest);
4106 			}
4107 
4108 			cur--;
4109 			state = DTRACE_JSON_COMMA;
4110 			break;
4111 		case DTRACE_JSON_VALUE:
4112 			if (isspace(cc))
4113 				break;
4114 
4115 			if (cc == '{' || cc == '[') {
4116 				if (nelems > 1 && found_key) {
4117 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4118 					/*
4119 					 * If our element selector directs us
4120 					 * to descend into this nested object,
4121 					 * then move to the next selector
4122 					 * element in the list and restart the
4123 					 * state machine.
4124 					 */
4125 					while (*elem != '\0')
4126 						elem++;
4127 					elem++; /* skip the inter-element NUL */
4128 					nelems--;
4129 					dd = dest;
4130 					if (in_array) {
4131 						state = DTRACE_JSON_VALUE;
4132 						array_pos = 0;
4133 						array_elem = dtrace_strtoll(
4134 						    elem, 10, size);
4135 						found_key = array_elem == 0 ?
4136 						    B_TRUE : B_FALSE;
4137 					} else {
4138 						found_key = B_FALSE;
4139 						state = DTRACE_JSON_OBJECT;
4140 					}
4141 					break;
4142 				}
4143 
4144 				/*
4145 				 * Otherwise, we wish to either skip this
4146 				 * nested object or return it in full.
4147 				 */
4148 				if (cc == '[')
4149 					brackets = 1;
4150 				else
4151 					braces = 1;
4152 				*dd++ = cc;
4153 				state = DTRACE_JSON_COLLECT_OBJECT;
4154 				break;
4155 			}
4156 
4157 			if (cc == '"') {
4158 				state = DTRACE_JSON_STRING;
4159 				break;
4160 			}
4161 
4162 			if (islower(cc)) {
4163 				/*
4164 				 * Here we deal with true, false and null.
4165 				 */
4166 				*dd++ = cc;
4167 				state = DTRACE_JSON_IDENTIFIER;
4168 				break;
4169 			}
4170 
4171 			if (cc == '-' || isdigit(cc)) {
4172 				*dd++ = cc;
4173 				state = DTRACE_JSON_NUMBER;
4174 				break;
4175 			}
4176 
4177 			/*
4178 			 * ERROR: unexpected character at start of value.
4179 			 */
4180 			return (NULL);
4181 		case DTRACE_JSON_COLLECT_OBJECT:
4182 			if (cc == '\0')
4183 				/*
4184 				 * ERROR: unexpected end of input.
4185 				 */
4186 				return (NULL);
4187 
4188 			*dd++ = cc;
4189 			if (cc == '"') {
4190 				collect_object = B_TRUE;
4191 				state = DTRACE_JSON_STRING;
4192 				break;
4193 			}
4194 
4195 			if (cc == ']') {
4196 				if (brackets-- == 0) {
4197 					/*
4198 					 * ERROR: unbalanced brackets.
4199 					 */
4200 					return (NULL);
4201 				}
4202 			} else if (cc == '}') {
4203 				if (braces-- == 0) {
4204 					/*
4205 					 * ERROR: unbalanced braces.
4206 					 */
4207 					return (NULL);
4208 				}
4209 			} else if (cc == '{') {
4210 				braces++;
4211 			} else if (cc == '[') {
4212 				brackets++;
4213 			}
4214 
4215 			if (brackets == 0 && braces == 0) {
4216 				if (found_key) {
4217 					*dd = '\0';
4218 					return (dest);
4219 				}
4220 				dd = dest; /* reset string buffer */
4221 				state = DTRACE_JSON_COMMA;
4222 			}
4223 			break;
4224 		}
4225 	}
4226 	return (NULL);
4227 }
4228 
4229 /*
4230  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4231  * Notice that we don't bother validating the proper number of arguments or
4232  * their types in the tuple stack.  This isn't needed because all argument
4233  * interpretation is safe because of our load safety -- the worst that can
4234  * happen is that a bogus program can obtain bogus results.
4235  */
4236 static void
dtrace_dif_subr(uint_t subr,uint_t rd,uint64_t * regs,dtrace_key_t * tupregs,int nargs,dtrace_mstate_t * mstate,dtrace_state_t * state)4237 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4238     dtrace_key_t *tupregs, int nargs,
4239     dtrace_mstate_t *mstate, dtrace_state_t *state)
4240 {
4241 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4242 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4243 	dtrace_vstate_t *vstate = &state->dts_vstate;
4244 
4245 #ifdef illumos
4246 	union {
4247 		mutex_impl_t mi;
4248 		uint64_t mx;
4249 	} m;
4250 
4251 	union {
4252 		krwlock_t ri;
4253 		uintptr_t rw;
4254 	} r;
4255 #else
4256 	struct thread *lowner;
4257 	union {
4258 		struct lock_object *li;
4259 		uintptr_t lx;
4260 	} l;
4261 #endif
4262 
4263 	switch (subr) {
4264 	case DIF_SUBR_RAND:
4265 		regs[rd] = dtrace_xoroshiro128_plus_next(
4266 		    state->dts_rstate[curcpu]);
4267 		break;
4268 
4269 #ifdef illumos
4270 	case DIF_SUBR_MUTEX_OWNED:
4271 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4272 		    mstate, vstate)) {
4273 			regs[rd] = 0;
4274 			break;
4275 		}
4276 
4277 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4278 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4279 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4280 		else
4281 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4282 		break;
4283 
4284 	case DIF_SUBR_MUTEX_OWNER:
4285 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4286 		    mstate, vstate)) {
4287 			regs[rd] = 0;
4288 			break;
4289 		}
4290 
4291 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4292 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4293 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4294 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4295 		else
4296 			regs[rd] = 0;
4297 		break;
4298 
4299 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4300 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4301 		    mstate, vstate)) {
4302 			regs[rd] = 0;
4303 			break;
4304 		}
4305 
4306 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4307 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4308 		break;
4309 
4310 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4311 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4312 		    mstate, vstate)) {
4313 			regs[rd] = 0;
4314 			break;
4315 		}
4316 
4317 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4318 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4319 		break;
4320 
4321 	case DIF_SUBR_RW_READ_HELD: {
4322 		uintptr_t tmp;
4323 
4324 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4325 		    mstate, vstate)) {
4326 			regs[rd] = 0;
4327 			break;
4328 		}
4329 
4330 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4331 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4332 		break;
4333 	}
4334 
4335 	case DIF_SUBR_RW_WRITE_HELD:
4336 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4337 		    mstate, vstate)) {
4338 			regs[rd] = 0;
4339 			break;
4340 		}
4341 
4342 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4343 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4344 		break;
4345 
4346 	case DIF_SUBR_RW_ISWRITER:
4347 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4348 		    mstate, vstate)) {
4349 			regs[rd] = 0;
4350 			break;
4351 		}
4352 
4353 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4354 		regs[rd] = _RW_ISWRITER(&r.ri);
4355 		break;
4356 
4357 #else /* !illumos */
4358 	case DIF_SUBR_MUTEX_OWNED:
4359 		if (!dtrace_canload(tupregs[0].dttk_value,
4360 			sizeof (struct lock_object), mstate, vstate)) {
4361 			regs[rd] = 0;
4362 			break;
4363 		}
4364 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4365 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4366 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4367 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4368 		break;
4369 
4370 	case DIF_SUBR_MUTEX_OWNER:
4371 		if (!dtrace_canload(tupregs[0].dttk_value,
4372 			sizeof (struct lock_object), mstate, vstate)) {
4373 			regs[rd] = 0;
4374 			break;
4375 		}
4376 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4377 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4378 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4379 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4380 		regs[rd] = (uintptr_t)lowner;
4381 		break;
4382 
4383 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4384 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4385 		    mstate, vstate)) {
4386 			regs[rd] = 0;
4387 			break;
4388 		}
4389 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4390 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4391 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4392 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4393 		break;
4394 
4395 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4396 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4397 		    mstate, vstate)) {
4398 			regs[rd] = 0;
4399 			break;
4400 		}
4401 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4402 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4403 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4404 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4405 		break;
4406 
4407 	case DIF_SUBR_RW_READ_HELD:
4408 	case DIF_SUBR_SX_SHARED_HELD:
4409 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4410 		    mstate, vstate)) {
4411 			regs[rd] = 0;
4412 			break;
4413 		}
4414 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4415 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4416 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4417 		    lowner == NULL;
4418 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4419 		break;
4420 
4421 	case DIF_SUBR_RW_WRITE_HELD:
4422 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
4423 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4424 		    mstate, vstate)) {
4425 			regs[rd] = 0;
4426 			break;
4427 		}
4428 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4429 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4430 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4431 		    lowner != NULL;
4432 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4433 		break;
4434 
4435 	case DIF_SUBR_RW_ISWRITER:
4436 	case DIF_SUBR_SX_ISEXCLUSIVE:
4437 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4438 		    mstate, vstate)) {
4439 			regs[rd] = 0;
4440 			break;
4441 		}
4442 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4443 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4444 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4445 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4446 		regs[rd] = (lowner == curthread);
4447 		break;
4448 #endif /* illumos */
4449 
4450 	case DIF_SUBR_BCOPY: {
4451 		/*
4452 		 * We need to be sure that the destination is in the scratch
4453 		 * region -- no other region is allowed.
4454 		 */
4455 		uintptr_t src = tupregs[0].dttk_value;
4456 		uintptr_t dest = tupregs[1].dttk_value;
4457 		size_t size = tupregs[2].dttk_value;
4458 
4459 		if (!dtrace_inscratch(dest, size, mstate)) {
4460 			*flags |= CPU_DTRACE_BADADDR;
4461 			*illval = regs[rd];
4462 			break;
4463 		}
4464 
4465 		if (!dtrace_canload(src, size, mstate, vstate)) {
4466 			regs[rd] = 0;
4467 			break;
4468 		}
4469 
4470 		dtrace_bcopy((void *)src, (void *)dest, size);
4471 		break;
4472 	}
4473 
4474 	case DIF_SUBR_ALLOCA:
4475 	case DIF_SUBR_COPYIN: {
4476 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4477 		uint64_t size =
4478 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4479 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4480 
4481 		/*
4482 		 * This action doesn't require any credential checks since
4483 		 * probes will not activate in user contexts to which the
4484 		 * enabling user does not have permissions.
4485 		 */
4486 
4487 		/*
4488 		 * Rounding up the user allocation size could have overflowed
4489 		 * a large, bogus allocation (like -1ULL) to 0.
4490 		 */
4491 		if (scratch_size < size ||
4492 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4493 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4494 			regs[rd] = 0;
4495 			break;
4496 		}
4497 
4498 		if (subr == DIF_SUBR_COPYIN) {
4499 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4500 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4501 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4502 		}
4503 
4504 		mstate->dtms_scratch_ptr += scratch_size;
4505 		regs[rd] = dest;
4506 		break;
4507 	}
4508 
4509 	case DIF_SUBR_COPYINTO: {
4510 		uint64_t size = tupregs[1].dttk_value;
4511 		uintptr_t dest = tupregs[2].dttk_value;
4512 
4513 		/*
4514 		 * This action doesn't require any credential checks since
4515 		 * probes will not activate in user contexts to which the
4516 		 * enabling user does not have permissions.
4517 		 */
4518 		if (!dtrace_inscratch(dest, size, mstate)) {
4519 			*flags |= CPU_DTRACE_BADADDR;
4520 			*illval = regs[rd];
4521 			break;
4522 		}
4523 
4524 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4525 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4526 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4527 		break;
4528 	}
4529 
4530 	case DIF_SUBR_COPYINSTR: {
4531 		uintptr_t dest = mstate->dtms_scratch_ptr;
4532 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4533 
4534 		if (nargs > 1 && tupregs[1].dttk_value < size)
4535 			size = tupregs[1].dttk_value + 1;
4536 
4537 		/*
4538 		 * This action doesn't require any credential checks since
4539 		 * probes will not activate in user contexts to which the
4540 		 * enabling user does not have permissions.
4541 		 */
4542 		if (!DTRACE_INSCRATCH(mstate, size)) {
4543 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4544 			regs[rd] = 0;
4545 			break;
4546 		}
4547 
4548 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4549 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4550 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4551 
4552 		((char *)dest)[size - 1] = '\0';
4553 		mstate->dtms_scratch_ptr += size;
4554 		regs[rd] = dest;
4555 		break;
4556 	}
4557 
4558 #ifdef illumos
4559 	case DIF_SUBR_MSGSIZE:
4560 	case DIF_SUBR_MSGDSIZE: {
4561 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4562 		uintptr_t wptr, rptr;
4563 		size_t count = 0;
4564 		int cont = 0;
4565 
4566 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4567 
4568 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4569 			    vstate)) {
4570 				regs[rd] = 0;
4571 				break;
4572 			}
4573 
4574 			wptr = dtrace_loadptr(baddr +
4575 			    offsetof(mblk_t, b_wptr));
4576 
4577 			rptr = dtrace_loadptr(baddr +
4578 			    offsetof(mblk_t, b_rptr));
4579 
4580 			if (wptr < rptr) {
4581 				*flags |= CPU_DTRACE_BADADDR;
4582 				*illval = tupregs[0].dttk_value;
4583 				break;
4584 			}
4585 
4586 			daddr = dtrace_loadptr(baddr +
4587 			    offsetof(mblk_t, b_datap));
4588 
4589 			baddr = dtrace_loadptr(baddr +
4590 			    offsetof(mblk_t, b_cont));
4591 
4592 			/*
4593 			 * We want to prevent against denial-of-service here,
4594 			 * so we're only going to search the list for
4595 			 * dtrace_msgdsize_max mblks.
4596 			 */
4597 			if (cont++ > dtrace_msgdsize_max) {
4598 				*flags |= CPU_DTRACE_ILLOP;
4599 				break;
4600 			}
4601 
4602 			if (subr == DIF_SUBR_MSGDSIZE) {
4603 				if (dtrace_load8(daddr +
4604 				    offsetof(dblk_t, db_type)) != M_DATA)
4605 					continue;
4606 			}
4607 
4608 			count += wptr - rptr;
4609 		}
4610 
4611 		if (!(*flags & CPU_DTRACE_FAULT))
4612 			regs[rd] = count;
4613 
4614 		break;
4615 	}
4616 #endif
4617 
4618 	case DIF_SUBR_PROGENYOF: {
4619 		pid_t pid = tupregs[0].dttk_value;
4620 		proc_t *p;
4621 		int rval = 0;
4622 
4623 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4624 
4625 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4626 #ifdef illumos
4627 			if (p->p_pidp->pid_id == pid) {
4628 #else
4629 			if (p->p_pid == pid) {
4630 #endif
4631 				rval = 1;
4632 				break;
4633 			}
4634 		}
4635 
4636 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4637 
4638 		regs[rd] = rval;
4639 		break;
4640 	}
4641 
4642 	case DIF_SUBR_SPECULATION:
4643 		regs[rd] = dtrace_speculation(state);
4644 		break;
4645 
4646 	case DIF_SUBR_COPYOUT: {
4647 		uintptr_t kaddr = tupregs[0].dttk_value;
4648 		uintptr_t uaddr = tupregs[1].dttk_value;
4649 		uint64_t size = tupregs[2].dttk_value;
4650 
4651 		if (!dtrace_destructive_disallow &&
4652 		    dtrace_priv_proc_control(state) &&
4653 		    !dtrace_istoxic(kaddr, size) &&
4654 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4655 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4656 			dtrace_copyout(kaddr, uaddr, size, flags);
4657 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4658 		}
4659 		break;
4660 	}
4661 
4662 	case DIF_SUBR_COPYOUTSTR: {
4663 		uintptr_t kaddr = tupregs[0].dttk_value;
4664 		uintptr_t uaddr = tupregs[1].dttk_value;
4665 		uint64_t size = tupregs[2].dttk_value;
4666 		size_t lim;
4667 
4668 		if (!dtrace_destructive_disallow &&
4669 		    dtrace_priv_proc_control(state) &&
4670 		    !dtrace_istoxic(kaddr, size) &&
4671 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4672 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4673 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4674 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4675 		}
4676 		break;
4677 	}
4678 
4679 	case DIF_SUBR_STRLEN: {
4680 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4681 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4682 		size_t lim;
4683 
4684 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4685 			regs[rd] = 0;
4686 			break;
4687 		}
4688 
4689 		regs[rd] = dtrace_strlen((char *)addr, lim);
4690 		break;
4691 	}
4692 
4693 	case DIF_SUBR_STRCHR:
4694 	case DIF_SUBR_STRRCHR: {
4695 		/*
4696 		 * We're going to iterate over the string looking for the
4697 		 * specified character.  We will iterate until we have reached
4698 		 * the string length or we have found the character.  If this
4699 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4700 		 * of the specified character instead of the first.
4701 		 */
4702 		uintptr_t addr = tupregs[0].dttk_value;
4703 		uintptr_t addr_limit;
4704 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4705 		size_t lim;
4706 		char c, target = (char)tupregs[1].dttk_value;
4707 
4708 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4709 			regs[rd] = 0;
4710 			break;
4711 		}
4712 		addr_limit = addr + lim;
4713 
4714 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4715 			if ((c = dtrace_load8(addr)) == target) {
4716 				regs[rd] = addr;
4717 
4718 				if (subr == DIF_SUBR_STRCHR)
4719 					break;
4720 			}
4721 
4722 			if (c == '\0')
4723 				break;
4724 		}
4725 		break;
4726 	}
4727 
4728 	case DIF_SUBR_STRSTR:
4729 	case DIF_SUBR_INDEX:
4730 	case DIF_SUBR_RINDEX: {
4731 		/*
4732 		 * We're going to iterate over the string looking for the
4733 		 * specified string.  We will iterate until we have reached
4734 		 * the string length or we have found the string.  (Yes, this
4735 		 * is done in the most naive way possible -- but considering
4736 		 * that the string we're searching for is likely to be
4737 		 * relatively short, the complexity of Rabin-Karp or similar
4738 		 * hardly seems merited.)
4739 		 */
4740 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4741 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4742 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4743 		size_t len = dtrace_strlen(addr, size);
4744 		size_t sublen = dtrace_strlen(substr, size);
4745 		char *limit = addr + len, *orig = addr;
4746 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4747 		int inc = 1;
4748 
4749 		regs[rd] = notfound;
4750 
4751 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4752 			regs[rd] = 0;
4753 			break;
4754 		}
4755 
4756 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4757 		    vstate)) {
4758 			regs[rd] = 0;
4759 			break;
4760 		}
4761 
4762 		/*
4763 		 * strstr() and index()/rindex() have similar semantics if
4764 		 * both strings are the empty string: strstr() returns a
4765 		 * pointer to the (empty) string, and index() and rindex()
4766 		 * both return index 0 (regardless of any position argument).
4767 		 */
4768 		if (sublen == 0 && len == 0) {
4769 			if (subr == DIF_SUBR_STRSTR)
4770 				regs[rd] = (uintptr_t)addr;
4771 			else
4772 				regs[rd] = 0;
4773 			break;
4774 		}
4775 
4776 		if (subr != DIF_SUBR_STRSTR) {
4777 			if (subr == DIF_SUBR_RINDEX) {
4778 				limit = orig - 1;
4779 				addr += len;
4780 				inc = -1;
4781 			}
4782 
4783 			/*
4784 			 * Both index() and rindex() take an optional position
4785 			 * argument that denotes the starting position.
4786 			 */
4787 			if (nargs == 3) {
4788 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4789 
4790 				/*
4791 				 * If the position argument to index() is
4792 				 * negative, Perl implicitly clamps it at
4793 				 * zero.  This semantic is a little surprising
4794 				 * given the special meaning of negative
4795 				 * positions to similar Perl functions like
4796 				 * substr(), but it appears to reflect a
4797 				 * notion that index() can start from a
4798 				 * negative index and increment its way up to
4799 				 * the string.  Given this notion, Perl's
4800 				 * rindex() is at least self-consistent in
4801 				 * that it implicitly clamps positions greater
4802 				 * than the string length to be the string
4803 				 * length.  Where Perl completely loses
4804 				 * coherence, however, is when the specified
4805 				 * substring is the empty string ("").  In
4806 				 * this case, even if the position is
4807 				 * negative, rindex() returns 0 -- and even if
4808 				 * the position is greater than the length,
4809 				 * index() returns the string length.  These
4810 				 * semantics violate the notion that index()
4811 				 * should never return a value less than the
4812 				 * specified position and that rindex() should
4813 				 * never return a value greater than the
4814 				 * specified position.  (One assumes that
4815 				 * these semantics are artifacts of Perl's
4816 				 * implementation and not the results of
4817 				 * deliberate design -- it beggars belief that
4818 				 * even Larry Wall could desire such oddness.)
4819 				 * While in the abstract one would wish for
4820 				 * consistent position semantics across
4821 				 * substr(), index() and rindex() -- or at the
4822 				 * very least self-consistent position
4823 				 * semantics for index() and rindex() -- we
4824 				 * instead opt to keep with the extant Perl
4825 				 * semantics, in all their broken glory.  (Do
4826 				 * we have more desire to maintain Perl's
4827 				 * semantics than Perl does?  Probably.)
4828 				 */
4829 				if (subr == DIF_SUBR_RINDEX) {
4830 					if (pos < 0) {
4831 						if (sublen == 0)
4832 							regs[rd] = 0;
4833 						break;
4834 					}
4835 
4836 					if (pos > len)
4837 						pos = len;
4838 				} else {
4839 					if (pos < 0)
4840 						pos = 0;
4841 
4842 					if (pos >= len) {
4843 						if (sublen == 0)
4844 							regs[rd] = len;
4845 						break;
4846 					}
4847 				}
4848 
4849 				addr = orig + pos;
4850 			}
4851 		}
4852 
4853 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4854 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4855 				if (subr != DIF_SUBR_STRSTR) {
4856 					/*
4857 					 * As D index() and rindex() are
4858 					 * modeled on Perl (and not on awk),
4859 					 * we return a zero-based (and not a
4860 					 * one-based) index.  (For you Perl
4861 					 * weenies: no, we're not going to add
4862 					 * $[ -- and shouldn't you be at a con
4863 					 * or something?)
4864 					 */
4865 					regs[rd] = (uintptr_t)(addr - orig);
4866 					break;
4867 				}
4868 
4869 				ASSERT(subr == DIF_SUBR_STRSTR);
4870 				regs[rd] = (uintptr_t)addr;
4871 				break;
4872 			}
4873 		}
4874 
4875 		break;
4876 	}
4877 
4878 	case DIF_SUBR_STRTOK: {
4879 		uintptr_t addr = tupregs[0].dttk_value;
4880 		uintptr_t tokaddr = tupregs[1].dttk_value;
4881 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4882 		uintptr_t limit, toklimit;
4883 		size_t clim;
4884 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4885 		char *dest = (char *)mstate->dtms_scratch_ptr;
4886 		int i;
4887 
4888 		/*
4889 		 * Check both the token buffer and (later) the input buffer,
4890 		 * since both could be non-scratch addresses.
4891 		 */
4892 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4893 			regs[rd] = 0;
4894 			break;
4895 		}
4896 		toklimit = tokaddr + clim;
4897 
4898 		if (!DTRACE_INSCRATCH(mstate, size)) {
4899 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4900 			regs[rd] = 0;
4901 			break;
4902 		}
4903 
4904 		if (addr == 0) {
4905 			/*
4906 			 * If the address specified is NULL, we use our saved
4907 			 * strtok pointer from the mstate.  Note that this
4908 			 * means that the saved strtok pointer is _only_
4909 			 * valid within multiple enablings of the same probe --
4910 			 * it behaves like an implicit clause-local variable.
4911 			 */
4912 			addr = mstate->dtms_strtok;
4913 			limit = mstate->dtms_strtok_limit;
4914 		} else {
4915 			/*
4916 			 * If the user-specified address is non-NULL we must
4917 			 * access check it.  This is the only time we have
4918 			 * a chance to do so, since this address may reside
4919 			 * in the string table of this clause-- future calls
4920 			 * (when we fetch addr from mstate->dtms_strtok)
4921 			 * would fail this access check.
4922 			 */
4923 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4924 			    vstate)) {
4925 				regs[rd] = 0;
4926 				break;
4927 			}
4928 			limit = addr + clim;
4929 		}
4930 
4931 		/*
4932 		 * First, zero the token map, and then process the token
4933 		 * string -- setting a bit in the map for every character
4934 		 * found in the token string.
4935 		 */
4936 		for (i = 0; i < sizeof (tokmap); i++)
4937 			tokmap[i] = 0;
4938 
4939 		for (; tokaddr < toklimit; tokaddr++) {
4940 			if ((c = dtrace_load8(tokaddr)) == '\0')
4941 				break;
4942 
4943 			ASSERT((c >> 3) < sizeof (tokmap));
4944 			tokmap[c >> 3] |= (1 << (c & 0x7));
4945 		}
4946 
4947 		for (; addr < limit; addr++) {
4948 			/*
4949 			 * We're looking for a character that is _not_
4950 			 * contained in the token string.
4951 			 */
4952 			if ((c = dtrace_load8(addr)) == '\0')
4953 				break;
4954 
4955 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4956 				break;
4957 		}
4958 
4959 		if (c == '\0') {
4960 			/*
4961 			 * We reached the end of the string without finding
4962 			 * any character that was not in the token string.
4963 			 * We return NULL in this case, and we set the saved
4964 			 * address to NULL as well.
4965 			 */
4966 			regs[rd] = 0;
4967 			mstate->dtms_strtok = 0;
4968 			mstate->dtms_strtok_limit = 0;
4969 			break;
4970 		}
4971 
4972 		/*
4973 		 * From here on, we're copying into the destination string.
4974 		 */
4975 		for (i = 0; addr < limit && i < size - 1; addr++) {
4976 			if ((c = dtrace_load8(addr)) == '\0')
4977 				break;
4978 
4979 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4980 				break;
4981 
4982 			ASSERT(i < size);
4983 			dest[i++] = c;
4984 		}
4985 
4986 		ASSERT(i < size);
4987 		dest[i] = '\0';
4988 		regs[rd] = (uintptr_t)dest;
4989 		mstate->dtms_scratch_ptr += size;
4990 		mstate->dtms_strtok = addr;
4991 		mstate->dtms_strtok_limit = limit;
4992 		break;
4993 	}
4994 
4995 	case DIF_SUBR_SUBSTR: {
4996 		uintptr_t s = tupregs[0].dttk_value;
4997 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4998 		char *d = (char *)mstate->dtms_scratch_ptr;
4999 		int64_t index = (int64_t)tupregs[1].dttk_value;
5000 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
5001 		size_t len = dtrace_strlen((char *)s, size);
5002 		int64_t i;
5003 
5004 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5005 			regs[rd] = 0;
5006 			break;
5007 		}
5008 
5009 		if (!DTRACE_INSCRATCH(mstate, size)) {
5010 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5011 			regs[rd] = 0;
5012 			break;
5013 		}
5014 
5015 		if (nargs <= 2)
5016 			remaining = (int64_t)size;
5017 
5018 		if (index < 0) {
5019 			index += len;
5020 
5021 			if (index < 0 && index + remaining > 0) {
5022 				remaining += index;
5023 				index = 0;
5024 			}
5025 		}
5026 
5027 		if (index >= len || index < 0) {
5028 			remaining = 0;
5029 		} else if (remaining < 0) {
5030 			remaining += len - index;
5031 		} else if (index + remaining > size) {
5032 			remaining = size - index;
5033 		}
5034 
5035 		for (i = 0; i < remaining; i++) {
5036 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5037 				break;
5038 		}
5039 
5040 		d[i] = '\0';
5041 
5042 		mstate->dtms_scratch_ptr += size;
5043 		regs[rd] = (uintptr_t)d;
5044 		break;
5045 	}
5046 
5047 	case DIF_SUBR_JSON: {
5048 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5049 		uintptr_t json = tupregs[0].dttk_value;
5050 		size_t jsonlen = dtrace_strlen((char *)json, size);
5051 		uintptr_t elem = tupregs[1].dttk_value;
5052 		size_t elemlen = dtrace_strlen((char *)elem, size);
5053 
5054 		char *dest = (char *)mstate->dtms_scratch_ptr;
5055 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5056 		char *ee = elemlist;
5057 		int nelems = 1;
5058 		uintptr_t cur;
5059 
5060 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5061 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5062 			regs[rd] = 0;
5063 			break;
5064 		}
5065 
5066 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5067 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5068 			regs[rd] = 0;
5069 			break;
5070 		}
5071 
5072 		/*
5073 		 * Read the element selector and split it up into a packed list
5074 		 * of strings.
5075 		 */
5076 		for (cur = elem; cur < elem + elemlen; cur++) {
5077 			char cc = dtrace_load8(cur);
5078 
5079 			if (cur == elem && cc == '[') {
5080 				/*
5081 				 * If the first element selector key is
5082 				 * actually an array index then ignore the
5083 				 * bracket.
5084 				 */
5085 				continue;
5086 			}
5087 
5088 			if (cc == ']')
5089 				continue;
5090 
5091 			if (cc == '.' || cc == '[') {
5092 				nelems++;
5093 				cc = '\0';
5094 			}
5095 
5096 			*ee++ = cc;
5097 		}
5098 		*ee++ = '\0';
5099 
5100 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5101 		    nelems, dest)) != 0)
5102 			mstate->dtms_scratch_ptr += jsonlen + 1;
5103 		break;
5104 	}
5105 
5106 	case DIF_SUBR_TOUPPER:
5107 	case DIF_SUBR_TOLOWER: {
5108 		uintptr_t s = tupregs[0].dttk_value;
5109 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5110 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5111 		size_t len = dtrace_strlen((char *)s, size);
5112 		char lower, upper, convert;
5113 		int64_t i;
5114 
5115 		if (subr == DIF_SUBR_TOUPPER) {
5116 			lower = 'a';
5117 			upper = 'z';
5118 			convert = 'A';
5119 		} else {
5120 			lower = 'A';
5121 			upper = 'Z';
5122 			convert = 'a';
5123 		}
5124 
5125 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5126 			regs[rd] = 0;
5127 			break;
5128 		}
5129 
5130 		if (!DTRACE_INSCRATCH(mstate, size)) {
5131 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5132 			regs[rd] = 0;
5133 			break;
5134 		}
5135 
5136 		for (i = 0; i < size - 1; i++) {
5137 			if ((c = dtrace_load8(s + i)) == '\0')
5138 				break;
5139 
5140 			if (c >= lower && c <= upper)
5141 				c = convert + (c - lower);
5142 
5143 			dest[i] = c;
5144 		}
5145 
5146 		ASSERT(i < size);
5147 		dest[i] = '\0';
5148 		regs[rd] = (uintptr_t)dest;
5149 		mstate->dtms_scratch_ptr += size;
5150 		break;
5151 	}
5152 
5153 #ifdef illumos
5154 	case DIF_SUBR_GETMAJOR:
5155 #ifdef _LP64
5156 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5157 #else
5158 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5159 #endif
5160 		break;
5161 
5162 	case DIF_SUBR_GETMINOR:
5163 #ifdef _LP64
5164 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5165 #else
5166 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
5167 #endif
5168 		break;
5169 
5170 	case DIF_SUBR_DDI_PATHNAME: {
5171 		/*
5172 		 * This one is a galactic mess.  We are going to roughly
5173 		 * emulate ddi_pathname(), but it's made more complicated
5174 		 * by the fact that we (a) want to include the minor name and
5175 		 * (b) must proceed iteratively instead of recursively.
5176 		 */
5177 		uintptr_t dest = mstate->dtms_scratch_ptr;
5178 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5179 		char *start = (char *)dest, *end = start + size - 1;
5180 		uintptr_t daddr = tupregs[0].dttk_value;
5181 		int64_t minor = (int64_t)tupregs[1].dttk_value;
5182 		char *s;
5183 		int i, len, depth = 0;
5184 
5185 		/*
5186 		 * Due to all the pointer jumping we do and context we must
5187 		 * rely upon, we just mandate that the user must have kernel
5188 		 * read privileges to use this routine.
5189 		 */
5190 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5191 			*flags |= CPU_DTRACE_KPRIV;
5192 			*illval = daddr;
5193 			regs[rd] = 0;
5194 		}
5195 
5196 		if (!DTRACE_INSCRATCH(mstate, size)) {
5197 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5198 			regs[rd] = 0;
5199 			break;
5200 		}
5201 
5202 		*end = '\0';
5203 
5204 		/*
5205 		 * We want to have a name for the minor.  In order to do this,
5206 		 * we need to walk the minor list from the devinfo.  We want
5207 		 * to be sure that we don't infinitely walk a circular list,
5208 		 * so we check for circularity by sending a scout pointer
5209 		 * ahead two elements for every element that we iterate over;
5210 		 * if the list is circular, these will ultimately point to the
5211 		 * same element.  You may recognize this little trick as the
5212 		 * answer to a stupid interview question -- one that always
5213 		 * seems to be asked by those who had to have it laboriously
5214 		 * explained to them, and who can't even concisely describe
5215 		 * the conditions under which one would be forced to resort to
5216 		 * this technique.  Needless to say, those conditions are
5217 		 * found here -- and probably only here.  Is this the only use
5218 		 * of this infamous trick in shipping, production code?  If it
5219 		 * isn't, it probably should be...
5220 		 */
5221 		if (minor != -1) {
5222 			uintptr_t maddr = dtrace_loadptr(daddr +
5223 			    offsetof(struct dev_info, devi_minor));
5224 
5225 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5226 			uintptr_t name = offsetof(struct ddi_minor_data,
5227 			    d_minor) + offsetof(struct ddi_minor, name);
5228 			uintptr_t dev = offsetof(struct ddi_minor_data,
5229 			    d_minor) + offsetof(struct ddi_minor, dev);
5230 			uintptr_t scout;
5231 
5232 			if (maddr != NULL)
5233 				scout = dtrace_loadptr(maddr + next);
5234 
5235 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5236 				uint64_t m;
5237 #ifdef _LP64
5238 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5239 #else
5240 				m = dtrace_load32(maddr + dev) & MAXMIN;
5241 #endif
5242 				if (m != minor) {
5243 					maddr = dtrace_loadptr(maddr + next);
5244 
5245 					if (scout == NULL)
5246 						continue;
5247 
5248 					scout = dtrace_loadptr(scout + next);
5249 
5250 					if (scout == NULL)
5251 						continue;
5252 
5253 					scout = dtrace_loadptr(scout + next);
5254 
5255 					if (scout == NULL)
5256 						continue;
5257 
5258 					if (scout == maddr) {
5259 						*flags |= CPU_DTRACE_ILLOP;
5260 						break;
5261 					}
5262 
5263 					continue;
5264 				}
5265 
5266 				/*
5267 				 * We have the minor data.  Now we need to
5268 				 * copy the minor's name into the end of the
5269 				 * pathname.
5270 				 */
5271 				s = (char *)dtrace_loadptr(maddr + name);
5272 				len = dtrace_strlen(s, size);
5273 
5274 				if (*flags & CPU_DTRACE_FAULT)
5275 					break;
5276 
5277 				if (len != 0) {
5278 					if ((end -= (len + 1)) < start)
5279 						break;
5280 
5281 					*end = ':';
5282 				}
5283 
5284 				for (i = 1; i <= len; i++)
5285 					end[i] = dtrace_load8((uintptr_t)s++);
5286 				break;
5287 			}
5288 		}
5289 
5290 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5291 			ddi_node_state_t devi_state;
5292 
5293 			devi_state = dtrace_load32(daddr +
5294 			    offsetof(struct dev_info, devi_node_state));
5295 
5296 			if (*flags & CPU_DTRACE_FAULT)
5297 				break;
5298 
5299 			if (devi_state >= DS_INITIALIZED) {
5300 				s = (char *)dtrace_loadptr(daddr +
5301 				    offsetof(struct dev_info, devi_addr));
5302 				len = dtrace_strlen(s, size);
5303 
5304 				if (*flags & CPU_DTRACE_FAULT)
5305 					break;
5306 
5307 				if (len != 0) {
5308 					if ((end -= (len + 1)) < start)
5309 						break;
5310 
5311 					*end = '@';
5312 				}
5313 
5314 				for (i = 1; i <= len; i++)
5315 					end[i] = dtrace_load8((uintptr_t)s++);
5316 			}
5317 
5318 			/*
5319 			 * Now for the node name...
5320 			 */
5321 			s = (char *)dtrace_loadptr(daddr +
5322 			    offsetof(struct dev_info, devi_node_name));
5323 
5324 			daddr = dtrace_loadptr(daddr +
5325 			    offsetof(struct dev_info, devi_parent));
5326 
5327 			/*
5328 			 * If our parent is NULL (that is, if we're the root
5329 			 * node), we're going to use the special path
5330 			 * "devices".
5331 			 */
5332 			if (daddr == 0)
5333 				s = "devices";
5334 
5335 			len = dtrace_strlen(s, size);
5336 			if (*flags & CPU_DTRACE_FAULT)
5337 				break;
5338 
5339 			if ((end -= (len + 1)) < start)
5340 				break;
5341 
5342 			for (i = 1; i <= len; i++)
5343 				end[i] = dtrace_load8((uintptr_t)s++);
5344 			*end = '/';
5345 
5346 			if (depth++ > dtrace_devdepth_max) {
5347 				*flags |= CPU_DTRACE_ILLOP;
5348 				break;
5349 			}
5350 		}
5351 
5352 		if (end < start)
5353 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5354 
5355 		if (daddr == 0) {
5356 			regs[rd] = (uintptr_t)end;
5357 			mstate->dtms_scratch_ptr += size;
5358 		}
5359 
5360 		break;
5361 	}
5362 #endif
5363 
5364 	case DIF_SUBR_STRJOIN: {
5365 		char *d = (char *)mstate->dtms_scratch_ptr;
5366 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5367 		uintptr_t s1 = tupregs[0].dttk_value;
5368 		uintptr_t s2 = tupregs[1].dttk_value;
5369 		int i = 0, j = 0;
5370 		size_t lim1, lim2;
5371 		char c;
5372 
5373 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5374 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5375 			regs[rd] = 0;
5376 			break;
5377 		}
5378 
5379 		if (!DTRACE_INSCRATCH(mstate, size)) {
5380 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5381 			regs[rd] = 0;
5382 			break;
5383 		}
5384 
5385 		for (;;) {
5386 			if (i >= size) {
5387 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5388 				regs[rd] = 0;
5389 				break;
5390 			}
5391 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5392 			if ((d[i++] = c) == '\0') {
5393 				i--;
5394 				break;
5395 			}
5396 		}
5397 
5398 		for (;;) {
5399 			if (i >= size) {
5400 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5401 				regs[rd] = 0;
5402 				break;
5403 			}
5404 
5405 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5406 			if ((d[i++] = c) == '\0')
5407 				break;
5408 		}
5409 
5410 		if (i < size) {
5411 			mstate->dtms_scratch_ptr += i;
5412 			regs[rd] = (uintptr_t)d;
5413 		}
5414 
5415 		break;
5416 	}
5417 
5418 	case DIF_SUBR_STRTOLL: {
5419 		uintptr_t s = tupregs[0].dttk_value;
5420 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5421 		size_t lim;
5422 		int base = 10;
5423 
5424 		if (nargs > 1) {
5425 			if ((base = tupregs[1].dttk_value) <= 1 ||
5426 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5427 				*flags |= CPU_DTRACE_ILLOP;
5428 				break;
5429 			}
5430 		}
5431 
5432 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5433 			regs[rd] = INT64_MIN;
5434 			break;
5435 		}
5436 
5437 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5438 		break;
5439 	}
5440 
5441 	case DIF_SUBR_LLTOSTR: {
5442 		int64_t i = (int64_t)tupregs[0].dttk_value;
5443 		uint64_t val, digit;
5444 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5445 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5446 		int base = 10;
5447 
5448 		if (nargs > 1) {
5449 			if ((base = tupregs[1].dttk_value) <= 1 ||
5450 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5451 				*flags |= CPU_DTRACE_ILLOP;
5452 				break;
5453 			}
5454 		}
5455 
5456 		val = (base == 10 && i < 0) ? i * -1 : i;
5457 
5458 		if (!DTRACE_INSCRATCH(mstate, size)) {
5459 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5460 			regs[rd] = 0;
5461 			break;
5462 		}
5463 
5464 		for (*end-- = '\0'; val; val /= base) {
5465 			if ((digit = val % base) <= '9' - '0') {
5466 				*end-- = '0' + digit;
5467 			} else {
5468 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5469 			}
5470 		}
5471 
5472 		if (i == 0 && base == 16)
5473 			*end-- = '0';
5474 
5475 		if (base == 16)
5476 			*end-- = 'x';
5477 
5478 		if (i == 0 || base == 8 || base == 16)
5479 			*end-- = '0';
5480 
5481 		if (i < 0 && base == 10)
5482 			*end-- = '-';
5483 
5484 		regs[rd] = (uintptr_t)end + 1;
5485 		mstate->dtms_scratch_ptr += size;
5486 		break;
5487 	}
5488 
5489 	case DIF_SUBR_HTONS:
5490 	case DIF_SUBR_NTOHS:
5491 #if BYTE_ORDER == BIG_ENDIAN
5492 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5493 #else
5494 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5495 #endif
5496 		break;
5497 
5498 
5499 	case DIF_SUBR_HTONL:
5500 	case DIF_SUBR_NTOHL:
5501 #if BYTE_ORDER == BIG_ENDIAN
5502 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5503 #else
5504 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5505 #endif
5506 		break;
5507 
5508 
5509 	case DIF_SUBR_HTONLL:
5510 	case DIF_SUBR_NTOHLL:
5511 #if BYTE_ORDER == BIG_ENDIAN
5512 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5513 #else
5514 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5515 #endif
5516 		break;
5517 
5518 
5519 	case DIF_SUBR_DIRNAME:
5520 	case DIF_SUBR_BASENAME: {
5521 		char *dest = (char *)mstate->dtms_scratch_ptr;
5522 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5523 		uintptr_t src = tupregs[0].dttk_value;
5524 		int i, j, len = dtrace_strlen((char *)src, size);
5525 		int lastbase = -1, firstbase = -1, lastdir = -1;
5526 		int start, end;
5527 
5528 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5529 			regs[rd] = 0;
5530 			break;
5531 		}
5532 
5533 		if (!DTRACE_INSCRATCH(mstate, size)) {
5534 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5535 			regs[rd] = 0;
5536 			break;
5537 		}
5538 
5539 		/*
5540 		 * The basename and dirname for a zero-length string is
5541 		 * defined to be "."
5542 		 */
5543 		if (len == 0) {
5544 			len = 1;
5545 			src = (uintptr_t)".";
5546 		}
5547 
5548 		/*
5549 		 * Start from the back of the string, moving back toward the
5550 		 * front until we see a character that isn't a slash.  That
5551 		 * character is the last character in the basename.
5552 		 */
5553 		for (i = len - 1; i >= 0; i--) {
5554 			if (dtrace_load8(src + i) != '/')
5555 				break;
5556 		}
5557 
5558 		if (i >= 0)
5559 			lastbase = i;
5560 
5561 		/*
5562 		 * Starting from the last character in the basename, move
5563 		 * towards the front until we find a slash.  The character
5564 		 * that we processed immediately before that is the first
5565 		 * character in the basename.
5566 		 */
5567 		for (; i >= 0; i--) {
5568 			if (dtrace_load8(src + i) == '/')
5569 				break;
5570 		}
5571 
5572 		if (i >= 0)
5573 			firstbase = i + 1;
5574 
5575 		/*
5576 		 * Now keep going until we find a non-slash character.  That
5577 		 * character is the last character in the dirname.
5578 		 */
5579 		for (; i >= 0; i--) {
5580 			if (dtrace_load8(src + i) != '/')
5581 				break;
5582 		}
5583 
5584 		if (i >= 0)
5585 			lastdir = i;
5586 
5587 		ASSERT(!(lastbase == -1 && firstbase != -1));
5588 		ASSERT(!(firstbase == -1 && lastdir != -1));
5589 
5590 		if (lastbase == -1) {
5591 			/*
5592 			 * We didn't find a non-slash character.  We know that
5593 			 * the length is non-zero, so the whole string must be
5594 			 * slashes.  In either the dirname or the basename
5595 			 * case, we return '/'.
5596 			 */
5597 			ASSERT(firstbase == -1);
5598 			firstbase = lastbase = lastdir = 0;
5599 		}
5600 
5601 		if (firstbase == -1) {
5602 			/*
5603 			 * The entire string consists only of a basename
5604 			 * component.  If we're looking for dirname, we need
5605 			 * to change our string to be just "."; if we're
5606 			 * looking for a basename, we'll just set the first
5607 			 * character of the basename to be 0.
5608 			 */
5609 			if (subr == DIF_SUBR_DIRNAME) {
5610 				ASSERT(lastdir == -1);
5611 				src = (uintptr_t)".";
5612 				lastdir = 0;
5613 			} else {
5614 				firstbase = 0;
5615 			}
5616 		}
5617 
5618 		if (subr == DIF_SUBR_DIRNAME) {
5619 			if (lastdir == -1) {
5620 				/*
5621 				 * We know that we have a slash in the name --
5622 				 * or lastdir would be set to 0, above.  And
5623 				 * because lastdir is -1, we know that this
5624 				 * slash must be the first character.  (That
5625 				 * is, the full string must be of the form
5626 				 * "/basename".)  In this case, the last
5627 				 * character of the directory name is 0.
5628 				 */
5629 				lastdir = 0;
5630 			}
5631 
5632 			start = 0;
5633 			end = lastdir;
5634 		} else {
5635 			ASSERT(subr == DIF_SUBR_BASENAME);
5636 			ASSERT(firstbase != -1 && lastbase != -1);
5637 			start = firstbase;
5638 			end = lastbase;
5639 		}
5640 
5641 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5642 			dest[j] = dtrace_load8(src + i);
5643 
5644 		dest[j] = '\0';
5645 		regs[rd] = (uintptr_t)dest;
5646 		mstate->dtms_scratch_ptr += size;
5647 		break;
5648 	}
5649 
5650 	case DIF_SUBR_GETF: {
5651 		uintptr_t fd = tupregs[0].dttk_value;
5652 		struct filedesc *fdp;
5653 		file_t *fp;
5654 
5655 		if (!dtrace_priv_proc(state)) {
5656 			regs[rd] = 0;
5657 			break;
5658 		}
5659 		fdp = curproc->p_fd;
5660 		FILEDESC_SLOCK(fdp);
5661 		/*
5662 		 * XXXMJG this looks broken as no ref is taken.
5663 		 */
5664 		fp = fget_noref(fdp, fd);
5665 		mstate->dtms_getf = fp;
5666 		regs[rd] = (uintptr_t)fp;
5667 		FILEDESC_SUNLOCK(fdp);
5668 		break;
5669 	}
5670 
5671 	case DIF_SUBR_CLEANPATH: {
5672 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5673 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5674 		uintptr_t src = tupregs[0].dttk_value;
5675 		size_t lim;
5676 		int i = 0, j = 0;
5677 #ifdef illumos
5678 		zone_t *z;
5679 #endif
5680 
5681 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5682 			regs[rd] = 0;
5683 			break;
5684 		}
5685 
5686 		if (!DTRACE_INSCRATCH(mstate, size)) {
5687 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5688 			regs[rd] = 0;
5689 			break;
5690 		}
5691 
5692 		/*
5693 		 * Move forward, loading each character.
5694 		 */
5695 		do {
5696 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5697 next:
5698 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5699 				break;
5700 
5701 			if (c != '/') {
5702 				dest[j++] = c;
5703 				continue;
5704 			}
5705 
5706 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5707 
5708 			if (c == '/') {
5709 				/*
5710 				 * We have two slashes -- we can just advance
5711 				 * to the next character.
5712 				 */
5713 				goto next;
5714 			}
5715 
5716 			if (c != '.') {
5717 				/*
5718 				 * This is not "." and it's not ".." -- we can
5719 				 * just store the "/" and this character and
5720 				 * drive on.
5721 				 */
5722 				dest[j++] = '/';
5723 				dest[j++] = c;
5724 				continue;
5725 			}
5726 
5727 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5728 
5729 			if (c == '/') {
5730 				/*
5731 				 * This is a "/./" component.  We're not going
5732 				 * to store anything in the destination buffer;
5733 				 * we're just going to go to the next component.
5734 				 */
5735 				goto next;
5736 			}
5737 
5738 			if (c != '.') {
5739 				/*
5740 				 * This is not ".." -- we can just store the
5741 				 * "/." and this character and continue
5742 				 * processing.
5743 				 */
5744 				dest[j++] = '/';
5745 				dest[j++] = '.';
5746 				dest[j++] = c;
5747 				continue;
5748 			}
5749 
5750 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5751 
5752 			if (c != '/' && c != '\0') {
5753 				/*
5754 				 * This is not ".." -- it's "..[mumble]".
5755 				 * We'll store the "/.." and this character
5756 				 * and continue processing.
5757 				 */
5758 				dest[j++] = '/';
5759 				dest[j++] = '.';
5760 				dest[j++] = '.';
5761 				dest[j++] = c;
5762 				continue;
5763 			}
5764 
5765 			/*
5766 			 * This is "/../" or "/..\0".  We need to back up
5767 			 * our destination pointer until we find a "/".
5768 			 */
5769 			i--;
5770 			while (j != 0 && dest[--j] != '/')
5771 				continue;
5772 
5773 			if (c == '\0')
5774 				dest[++j] = '/';
5775 		} while (c != '\0');
5776 
5777 		dest[j] = '\0';
5778 
5779 #ifdef illumos
5780 		if (mstate->dtms_getf != NULL &&
5781 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5782 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5783 			/*
5784 			 * If we've done a getf() as a part of this ECB and we
5785 			 * don't have kernel access (and we're not in the global
5786 			 * zone), check if the path we cleaned up begins with
5787 			 * the zone's root path, and trim it off if so.  Note
5788 			 * that this is an output cleanliness issue, not a
5789 			 * security issue: knowing one's zone root path does
5790 			 * not enable privilege escalation.
5791 			 */
5792 			if (strstr(dest, z->zone_rootpath) == dest)
5793 				dest += strlen(z->zone_rootpath) - 1;
5794 		}
5795 #endif
5796 
5797 		regs[rd] = (uintptr_t)dest;
5798 		mstate->dtms_scratch_ptr += size;
5799 		break;
5800 	}
5801 
5802 	case DIF_SUBR_INET_NTOA:
5803 	case DIF_SUBR_INET_NTOA6:
5804 	case DIF_SUBR_INET_NTOP: {
5805 		size_t size;
5806 		int af, argi, i;
5807 		char *base, *end;
5808 
5809 		if (subr == DIF_SUBR_INET_NTOP) {
5810 			af = (int)tupregs[0].dttk_value;
5811 			argi = 1;
5812 		} else {
5813 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5814 			argi = 0;
5815 		}
5816 
5817 		if (af == AF_INET) {
5818 			ipaddr_t ip4;
5819 			uint8_t *ptr8, val;
5820 
5821 			if (!dtrace_canload(tupregs[argi].dttk_value,
5822 			    sizeof (ipaddr_t), mstate, vstate)) {
5823 				regs[rd] = 0;
5824 				break;
5825 			}
5826 
5827 			/*
5828 			 * Safely load the IPv4 address.
5829 			 */
5830 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5831 
5832 			/*
5833 			 * Check an IPv4 string will fit in scratch.
5834 			 */
5835 			size = INET_ADDRSTRLEN;
5836 			if (!DTRACE_INSCRATCH(mstate, size)) {
5837 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5838 				regs[rd] = 0;
5839 				break;
5840 			}
5841 			base = (char *)mstate->dtms_scratch_ptr;
5842 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5843 
5844 			/*
5845 			 * Stringify as a dotted decimal quad.
5846 			 */
5847 			*end-- = '\0';
5848 			ptr8 = (uint8_t *)&ip4;
5849 			for (i = 3; i >= 0; i--) {
5850 				val = ptr8[i];
5851 
5852 				if (val == 0) {
5853 					*end-- = '0';
5854 				} else {
5855 					for (; val; val /= 10) {
5856 						*end-- = '0' + (val % 10);
5857 					}
5858 				}
5859 
5860 				if (i > 0)
5861 					*end-- = '.';
5862 			}
5863 			ASSERT(end + 1 >= base);
5864 
5865 		} else if (af == AF_INET6) {
5866 			struct in6_addr ip6;
5867 			int firstzero, tryzero, numzero, v6end;
5868 			uint16_t val;
5869 			const char digits[] = "0123456789abcdef";
5870 
5871 			/*
5872 			 * Stringify using RFC 1884 convention 2 - 16 bit
5873 			 * hexadecimal values with a zero-run compression.
5874 			 * Lower case hexadecimal digits are used.
5875 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5876 			 * The IPv4 embedded form is returned for inet_ntop,
5877 			 * just the IPv4 string is returned for inet_ntoa6.
5878 			 */
5879 
5880 			if (!dtrace_canload(tupregs[argi].dttk_value,
5881 			    sizeof (struct in6_addr), mstate, vstate)) {
5882 				regs[rd] = 0;
5883 				break;
5884 			}
5885 
5886 			/*
5887 			 * Safely load the IPv6 address.
5888 			 */
5889 			dtrace_bcopy(
5890 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5891 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5892 
5893 			/*
5894 			 * Check an IPv6 string will fit in scratch.
5895 			 */
5896 			size = INET6_ADDRSTRLEN;
5897 			if (!DTRACE_INSCRATCH(mstate, size)) {
5898 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5899 				regs[rd] = 0;
5900 				break;
5901 			}
5902 			base = (char *)mstate->dtms_scratch_ptr;
5903 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5904 			*end-- = '\0';
5905 
5906 			/*
5907 			 * Find the longest run of 16 bit zero values
5908 			 * for the single allowed zero compression - "::".
5909 			 */
5910 			firstzero = -1;
5911 			tryzero = -1;
5912 			numzero = 1;
5913 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5914 #ifdef illumos
5915 				if (ip6._S6_un._S6_u8[i] == 0 &&
5916 #else
5917 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5918 #endif
5919 				    tryzero == -1 && i % 2 == 0) {
5920 					tryzero = i;
5921 					continue;
5922 				}
5923 
5924 				if (tryzero != -1 &&
5925 #ifdef illumos
5926 				    (ip6._S6_un._S6_u8[i] != 0 ||
5927 #else
5928 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5929 #endif
5930 				    i == sizeof (struct in6_addr) - 1)) {
5931 
5932 					if (i - tryzero <= numzero) {
5933 						tryzero = -1;
5934 						continue;
5935 					}
5936 
5937 					firstzero = tryzero;
5938 					numzero = i - i % 2 - tryzero;
5939 					tryzero = -1;
5940 
5941 #ifdef illumos
5942 					if (ip6._S6_un._S6_u8[i] == 0 &&
5943 #else
5944 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5945 #endif
5946 					    i == sizeof (struct in6_addr) - 1)
5947 						numzero += 2;
5948 				}
5949 			}
5950 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5951 
5952 			/*
5953 			 * Check for an IPv4 embedded address.
5954 			 */
5955 			v6end = sizeof (struct in6_addr) - 2;
5956 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5957 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5958 				for (i = sizeof (struct in6_addr) - 1;
5959 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5960 					ASSERT(end >= base);
5961 
5962 #ifdef illumos
5963 					val = ip6._S6_un._S6_u8[i];
5964 #else
5965 					val = ip6.__u6_addr.__u6_addr8[i];
5966 #endif
5967 
5968 					if (val == 0) {
5969 						*end-- = '0';
5970 					} else {
5971 						for (; val; val /= 10) {
5972 							*end-- = '0' + val % 10;
5973 						}
5974 					}
5975 
5976 					if (i > DTRACE_V4MAPPED_OFFSET)
5977 						*end-- = '.';
5978 				}
5979 
5980 				if (subr == DIF_SUBR_INET_NTOA6)
5981 					goto inetout;
5982 
5983 				/*
5984 				 * Set v6end to skip the IPv4 address that
5985 				 * we have already stringified.
5986 				 */
5987 				v6end = 10;
5988 			}
5989 
5990 			/*
5991 			 * Build the IPv6 string by working through the
5992 			 * address in reverse.
5993 			 */
5994 			for (i = v6end; i >= 0; i -= 2) {
5995 				ASSERT(end >= base);
5996 
5997 				if (i == firstzero + numzero - 2) {
5998 					*end-- = ':';
5999 					*end-- = ':';
6000 					i -= numzero - 2;
6001 					continue;
6002 				}
6003 
6004 				if (i < 14 && i != firstzero - 2)
6005 					*end-- = ':';
6006 
6007 #ifdef illumos
6008 				val = (ip6._S6_un._S6_u8[i] << 8) +
6009 				    ip6._S6_un._S6_u8[i + 1];
6010 #else
6011 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6012 				    ip6.__u6_addr.__u6_addr8[i + 1];
6013 #endif
6014 
6015 				if (val == 0) {
6016 					*end-- = '0';
6017 				} else {
6018 					for (; val; val /= 16) {
6019 						*end-- = digits[val % 16];
6020 					}
6021 				}
6022 			}
6023 			ASSERT(end + 1 >= base);
6024 
6025 		} else {
6026 			/*
6027 			 * The user didn't use AH_INET or AH_INET6.
6028 			 */
6029 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6030 			regs[rd] = 0;
6031 			break;
6032 		}
6033 
6034 inetout:	regs[rd] = (uintptr_t)end + 1;
6035 		mstate->dtms_scratch_ptr += size;
6036 		break;
6037 	}
6038 
6039 	case DIF_SUBR_MEMREF: {
6040 		uintptr_t size = 2 * sizeof(uintptr_t);
6041 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6042 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6043 
6044 		/* address and length */
6045 		memref[0] = tupregs[0].dttk_value;
6046 		memref[1] = tupregs[1].dttk_value;
6047 
6048 		regs[rd] = (uintptr_t) memref;
6049 		mstate->dtms_scratch_ptr += scratch_size;
6050 		break;
6051 	}
6052 
6053 #ifndef illumos
6054 	case DIF_SUBR_MEMSTR: {
6055 		char *str = (char *)mstate->dtms_scratch_ptr;
6056 		uintptr_t mem = tupregs[0].dttk_value;
6057 		char c = tupregs[1].dttk_value;
6058 		size_t size = tupregs[2].dttk_value;
6059 		uint8_t n;
6060 		int i;
6061 
6062 		regs[rd] = 0;
6063 
6064 		if (size == 0)
6065 			break;
6066 
6067 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6068 			break;
6069 
6070 		if (!DTRACE_INSCRATCH(mstate, size)) {
6071 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6072 			break;
6073 		}
6074 
6075 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6076 			*flags |= CPU_DTRACE_ILLOP;
6077 			break;
6078 		}
6079 
6080 		for (i = 0; i < size - 1; i++) {
6081 			n = dtrace_load8(mem++);
6082 			str[i] = (n == 0) ? c : n;
6083 		}
6084 		str[size - 1] = 0;
6085 
6086 		regs[rd] = (uintptr_t)str;
6087 		mstate->dtms_scratch_ptr += size;
6088 		break;
6089 	}
6090 #endif
6091 	}
6092 }
6093 
6094 /*
6095  * Emulate the execution of DTrace IR instructions specified by the given
6096  * DIF object.  This function is deliberately void of assertions as all of
6097  * the necessary checks are handled by a call to dtrace_difo_validate().
6098  */
6099 static uint64_t
6100 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6101     dtrace_vstate_t *vstate, dtrace_state_t *state)
6102 {
6103 	const dif_instr_t *text = difo->dtdo_buf;
6104 	const uint_t textlen = difo->dtdo_len;
6105 	const char *strtab = difo->dtdo_strtab;
6106 	const uint64_t *inttab = difo->dtdo_inttab;
6107 
6108 	uint64_t rval = 0;
6109 	dtrace_statvar_t *svar;
6110 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6111 	dtrace_difv_t *v;
6112 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6113 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6114 
6115 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6116 	uint64_t regs[DIF_DIR_NREGS];
6117 	uint64_t *tmp;
6118 
6119 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6120 	int64_t cc_r;
6121 	uint_t pc = 0, id, opc = 0;
6122 	uint8_t ttop = 0;
6123 	dif_instr_t instr;
6124 	uint_t r1, r2, rd;
6125 
6126 	/*
6127 	 * We stash the current DIF object into the machine state: we need it
6128 	 * for subsequent access checking.
6129 	 */
6130 	mstate->dtms_difo = difo;
6131 
6132 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6133 
6134 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6135 		opc = pc;
6136 
6137 		instr = text[pc++];
6138 		r1 = DIF_INSTR_R1(instr);
6139 		r2 = DIF_INSTR_R2(instr);
6140 		rd = DIF_INSTR_RD(instr);
6141 
6142 		switch (DIF_INSTR_OP(instr)) {
6143 		case DIF_OP_OR:
6144 			regs[rd] = regs[r1] | regs[r2];
6145 			break;
6146 		case DIF_OP_XOR:
6147 			regs[rd] = regs[r1] ^ regs[r2];
6148 			break;
6149 		case DIF_OP_AND:
6150 			regs[rd] = regs[r1] & regs[r2];
6151 			break;
6152 		case DIF_OP_SLL:
6153 			regs[rd] = regs[r1] << regs[r2];
6154 			break;
6155 		case DIF_OP_SRL:
6156 			regs[rd] = regs[r1] >> regs[r2];
6157 			break;
6158 		case DIF_OP_SUB:
6159 			regs[rd] = regs[r1] - regs[r2];
6160 			break;
6161 		case DIF_OP_ADD:
6162 			regs[rd] = regs[r1] + regs[r2];
6163 			break;
6164 		case DIF_OP_MUL:
6165 			regs[rd] = regs[r1] * regs[r2];
6166 			break;
6167 		case DIF_OP_SDIV:
6168 			if (regs[r2] == 0) {
6169 				regs[rd] = 0;
6170 				*flags |= CPU_DTRACE_DIVZERO;
6171 			} else {
6172 				regs[rd] = (int64_t)regs[r1] /
6173 				    (int64_t)regs[r2];
6174 			}
6175 			break;
6176 
6177 		case DIF_OP_UDIV:
6178 			if (regs[r2] == 0) {
6179 				regs[rd] = 0;
6180 				*flags |= CPU_DTRACE_DIVZERO;
6181 			} else {
6182 				regs[rd] = regs[r1] / regs[r2];
6183 			}
6184 			break;
6185 
6186 		case DIF_OP_SREM:
6187 			if (regs[r2] == 0) {
6188 				regs[rd] = 0;
6189 				*flags |= CPU_DTRACE_DIVZERO;
6190 			} else {
6191 				regs[rd] = (int64_t)regs[r1] %
6192 				    (int64_t)regs[r2];
6193 			}
6194 			break;
6195 
6196 		case DIF_OP_UREM:
6197 			if (regs[r2] == 0) {
6198 				regs[rd] = 0;
6199 				*flags |= CPU_DTRACE_DIVZERO;
6200 			} else {
6201 				regs[rd] = regs[r1] % regs[r2];
6202 			}
6203 			break;
6204 
6205 		case DIF_OP_NOT:
6206 			regs[rd] = ~regs[r1];
6207 			break;
6208 		case DIF_OP_MOV:
6209 			regs[rd] = regs[r1];
6210 			break;
6211 		case DIF_OP_CMP:
6212 			cc_r = regs[r1] - regs[r2];
6213 			cc_n = cc_r < 0;
6214 			cc_z = cc_r == 0;
6215 			cc_v = 0;
6216 			cc_c = regs[r1] < regs[r2];
6217 			break;
6218 		case DIF_OP_TST:
6219 			cc_n = cc_v = cc_c = 0;
6220 			cc_z = regs[r1] == 0;
6221 			break;
6222 		case DIF_OP_BA:
6223 			pc = DIF_INSTR_LABEL(instr);
6224 			break;
6225 		case DIF_OP_BE:
6226 			if (cc_z)
6227 				pc = DIF_INSTR_LABEL(instr);
6228 			break;
6229 		case DIF_OP_BNE:
6230 			if (cc_z == 0)
6231 				pc = DIF_INSTR_LABEL(instr);
6232 			break;
6233 		case DIF_OP_BG:
6234 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6235 				pc = DIF_INSTR_LABEL(instr);
6236 			break;
6237 		case DIF_OP_BGU:
6238 			if ((cc_c | cc_z) == 0)
6239 				pc = DIF_INSTR_LABEL(instr);
6240 			break;
6241 		case DIF_OP_BGE:
6242 			if ((cc_n ^ cc_v) == 0)
6243 				pc = DIF_INSTR_LABEL(instr);
6244 			break;
6245 		case DIF_OP_BGEU:
6246 			if (cc_c == 0)
6247 				pc = DIF_INSTR_LABEL(instr);
6248 			break;
6249 		case DIF_OP_BL:
6250 			if (cc_n ^ cc_v)
6251 				pc = DIF_INSTR_LABEL(instr);
6252 			break;
6253 		case DIF_OP_BLU:
6254 			if (cc_c)
6255 				pc = DIF_INSTR_LABEL(instr);
6256 			break;
6257 		case DIF_OP_BLE:
6258 			if (cc_z | (cc_n ^ cc_v))
6259 				pc = DIF_INSTR_LABEL(instr);
6260 			break;
6261 		case DIF_OP_BLEU:
6262 			if (cc_c | cc_z)
6263 				pc = DIF_INSTR_LABEL(instr);
6264 			break;
6265 		case DIF_OP_RLDSB:
6266 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6267 				break;
6268 			/*FALLTHROUGH*/
6269 		case DIF_OP_LDSB:
6270 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6271 			break;
6272 		case DIF_OP_RLDSH:
6273 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6274 				break;
6275 			/*FALLTHROUGH*/
6276 		case DIF_OP_LDSH:
6277 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6278 			break;
6279 		case DIF_OP_RLDSW:
6280 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6281 				break;
6282 			/*FALLTHROUGH*/
6283 		case DIF_OP_LDSW:
6284 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6285 			break;
6286 		case DIF_OP_RLDUB:
6287 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6288 				break;
6289 			/*FALLTHROUGH*/
6290 		case DIF_OP_LDUB:
6291 			regs[rd] = dtrace_load8(regs[r1]);
6292 			break;
6293 		case DIF_OP_RLDUH:
6294 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6295 				break;
6296 			/*FALLTHROUGH*/
6297 		case DIF_OP_LDUH:
6298 			regs[rd] = dtrace_load16(regs[r1]);
6299 			break;
6300 		case DIF_OP_RLDUW:
6301 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6302 				break;
6303 			/*FALLTHROUGH*/
6304 		case DIF_OP_LDUW:
6305 			regs[rd] = dtrace_load32(regs[r1]);
6306 			break;
6307 		case DIF_OP_RLDX:
6308 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6309 				break;
6310 			/*FALLTHROUGH*/
6311 		case DIF_OP_LDX:
6312 			regs[rd] = dtrace_load64(regs[r1]);
6313 			break;
6314 		case DIF_OP_ULDSB:
6315 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6316 			regs[rd] = (int8_t)
6317 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6318 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6319 			break;
6320 		case DIF_OP_ULDSH:
6321 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6322 			regs[rd] = (int16_t)
6323 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6324 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6325 			break;
6326 		case DIF_OP_ULDSW:
6327 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6328 			regs[rd] = (int32_t)
6329 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6330 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6331 			break;
6332 		case DIF_OP_ULDUB:
6333 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6334 			regs[rd] =
6335 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6336 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6337 			break;
6338 		case DIF_OP_ULDUH:
6339 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6340 			regs[rd] =
6341 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6342 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6343 			break;
6344 		case DIF_OP_ULDUW:
6345 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6346 			regs[rd] =
6347 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6348 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6349 			break;
6350 		case DIF_OP_ULDX:
6351 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6352 			regs[rd] =
6353 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6354 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6355 			break;
6356 		case DIF_OP_RET:
6357 			rval = regs[rd];
6358 			pc = textlen;
6359 			break;
6360 		case DIF_OP_NOP:
6361 			break;
6362 		case DIF_OP_SETX:
6363 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6364 			break;
6365 		case DIF_OP_SETS:
6366 			regs[rd] = (uint64_t)(uintptr_t)
6367 			    (strtab + DIF_INSTR_STRING(instr));
6368 			break;
6369 		case DIF_OP_SCMP: {
6370 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6371 			uintptr_t s1 = regs[r1];
6372 			uintptr_t s2 = regs[r2];
6373 			size_t lim1, lim2;
6374 
6375 			/*
6376 			 * If one of the strings is NULL then the limit becomes
6377 			 * 0 which compares 0 characters in dtrace_strncmp()
6378 			 * resulting in a false positive.  dtrace_strncmp()
6379 			 * treats a NULL as an empty 1-char string.
6380 			 */
6381 			lim1 = lim2 = 1;
6382 
6383 			if (s1 != 0 &&
6384 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6385 				break;
6386 			if (s2 != 0 &&
6387 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6388 				break;
6389 
6390 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6391 			    MIN(lim1, lim2));
6392 
6393 			cc_n = cc_r < 0;
6394 			cc_z = cc_r == 0;
6395 			cc_v = cc_c = 0;
6396 			break;
6397 		}
6398 		case DIF_OP_LDGA:
6399 			regs[rd] = dtrace_dif_variable(mstate, state,
6400 			    r1, regs[r2]);
6401 			break;
6402 		case DIF_OP_LDGS:
6403 			id = DIF_INSTR_VAR(instr);
6404 
6405 			if (id >= DIF_VAR_OTHER_UBASE) {
6406 				uintptr_t a;
6407 
6408 				id -= DIF_VAR_OTHER_UBASE;
6409 				svar = vstate->dtvs_globals[id];
6410 				ASSERT(svar != NULL);
6411 				v = &svar->dtsv_var;
6412 
6413 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6414 					regs[rd] = svar->dtsv_data;
6415 					break;
6416 				}
6417 
6418 				a = (uintptr_t)svar->dtsv_data;
6419 
6420 				if (*(uint8_t *)a == UINT8_MAX) {
6421 					/*
6422 					 * If the 0th byte is set to UINT8_MAX
6423 					 * then this is to be treated as a
6424 					 * reference to a NULL variable.
6425 					 */
6426 					regs[rd] = 0;
6427 				} else {
6428 					regs[rd] = a + sizeof (uint64_t);
6429 				}
6430 
6431 				break;
6432 			}
6433 
6434 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6435 			break;
6436 
6437 		case DIF_OP_STGS:
6438 			id = DIF_INSTR_VAR(instr);
6439 
6440 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6441 			id -= DIF_VAR_OTHER_UBASE;
6442 
6443 			VERIFY(id < vstate->dtvs_nglobals);
6444 			svar = vstate->dtvs_globals[id];
6445 			ASSERT(svar != NULL);
6446 			v = &svar->dtsv_var;
6447 
6448 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6449 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6450 				size_t lim;
6451 
6452 				ASSERT(a != 0);
6453 				ASSERT(svar->dtsv_size != 0);
6454 
6455 				if (regs[rd] == 0) {
6456 					*(uint8_t *)a = UINT8_MAX;
6457 					break;
6458 				} else {
6459 					*(uint8_t *)a = 0;
6460 					a += sizeof (uint64_t);
6461 				}
6462 				if (!dtrace_vcanload(
6463 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6464 				    &lim, mstate, vstate))
6465 					break;
6466 
6467 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6468 				    (void *)a, &v->dtdv_type, lim);
6469 				break;
6470 			}
6471 
6472 			svar->dtsv_data = regs[rd];
6473 			break;
6474 
6475 		case DIF_OP_LDTA:
6476 			/*
6477 			 * There are no DTrace built-in thread-local arrays at
6478 			 * present.  This opcode is saved for future work.
6479 			 */
6480 			*flags |= CPU_DTRACE_ILLOP;
6481 			regs[rd] = 0;
6482 			break;
6483 
6484 		case DIF_OP_LDLS:
6485 			id = DIF_INSTR_VAR(instr);
6486 
6487 			if (id < DIF_VAR_OTHER_UBASE) {
6488 				/*
6489 				 * For now, this has no meaning.
6490 				 */
6491 				regs[rd] = 0;
6492 				break;
6493 			}
6494 
6495 			id -= DIF_VAR_OTHER_UBASE;
6496 
6497 			ASSERT(id < vstate->dtvs_nlocals);
6498 			ASSERT(vstate->dtvs_locals != NULL);
6499 
6500 			svar = vstate->dtvs_locals[id];
6501 			ASSERT(svar != NULL);
6502 			v = &svar->dtsv_var;
6503 
6504 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6505 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6506 				size_t sz = v->dtdv_type.dtdt_size;
6507 				size_t lim;
6508 
6509 				sz += sizeof (uint64_t);
6510 				ASSERT(svar->dtsv_size == (mp_maxid + 1) * sz);
6511 				a += curcpu * sz;
6512 
6513 				if (*(uint8_t *)a == UINT8_MAX) {
6514 					/*
6515 					 * If the 0th byte is set to UINT8_MAX
6516 					 * then this is to be treated as a
6517 					 * reference to a NULL variable.
6518 					 */
6519 					regs[rd] = 0;
6520 				} else {
6521 					regs[rd] = a + sizeof (uint64_t);
6522 				}
6523 
6524 				break;
6525 			}
6526 
6527 			ASSERT(svar->dtsv_size ==
6528 			    (mp_maxid + 1) * sizeof (uint64_t));
6529 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6530 			regs[rd] = tmp[curcpu];
6531 			break;
6532 
6533 		case DIF_OP_STLS:
6534 			id = DIF_INSTR_VAR(instr);
6535 
6536 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6537 			id -= DIF_VAR_OTHER_UBASE;
6538 			VERIFY(id < vstate->dtvs_nlocals);
6539 
6540 			ASSERT(vstate->dtvs_locals != NULL);
6541 			svar = vstate->dtvs_locals[id];
6542 			ASSERT(svar != NULL);
6543 			v = &svar->dtsv_var;
6544 
6545 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6546 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6547 				size_t sz = v->dtdv_type.dtdt_size;
6548 				size_t lim;
6549 
6550 				sz += sizeof (uint64_t);
6551 				ASSERT(svar->dtsv_size == (mp_maxid + 1) * sz);
6552 				a += curcpu * sz;
6553 
6554 				if (regs[rd] == 0) {
6555 					*(uint8_t *)a = UINT8_MAX;
6556 					break;
6557 				} else {
6558 					*(uint8_t *)a = 0;
6559 					a += sizeof (uint64_t);
6560 				}
6561 
6562 				if (!dtrace_vcanload(
6563 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6564 				    &lim, mstate, vstate))
6565 					break;
6566 
6567 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6568 				    (void *)a, &v->dtdv_type, lim);
6569 				break;
6570 			}
6571 
6572 			ASSERT(svar->dtsv_size ==
6573 			    (mp_maxid + 1) * sizeof (uint64_t));
6574 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6575 			tmp[curcpu] = regs[rd];
6576 			break;
6577 
6578 		case DIF_OP_LDTS: {
6579 			dtrace_dynvar_t *dvar;
6580 			dtrace_key_t *key;
6581 
6582 			id = DIF_INSTR_VAR(instr);
6583 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6584 			id -= DIF_VAR_OTHER_UBASE;
6585 			v = &vstate->dtvs_tlocals[id];
6586 
6587 			key = &tupregs[DIF_DTR_NREGS];
6588 			key[0].dttk_value = (uint64_t)id;
6589 			key[0].dttk_size = 0;
6590 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6591 			key[1].dttk_size = 0;
6592 
6593 			dvar = dtrace_dynvar(dstate, 2, key,
6594 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6595 			    mstate, vstate);
6596 
6597 			if (dvar == NULL) {
6598 				regs[rd] = 0;
6599 				break;
6600 			}
6601 
6602 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6603 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6604 			} else {
6605 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6606 			}
6607 
6608 			break;
6609 		}
6610 
6611 		case DIF_OP_STTS: {
6612 			dtrace_dynvar_t *dvar;
6613 			dtrace_key_t *key;
6614 
6615 			id = DIF_INSTR_VAR(instr);
6616 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6617 			id -= DIF_VAR_OTHER_UBASE;
6618 			VERIFY(id < vstate->dtvs_ntlocals);
6619 
6620 			key = &tupregs[DIF_DTR_NREGS];
6621 			key[0].dttk_value = (uint64_t)id;
6622 			key[0].dttk_size = 0;
6623 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6624 			key[1].dttk_size = 0;
6625 			v = &vstate->dtvs_tlocals[id];
6626 
6627 			dvar = dtrace_dynvar(dstate, 2, key,
6628 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6629 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6630 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6631 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6632 
6633 			/*
6634 			 * Given that we're storing to thread-local data,
6635 			 * we need to flush our predicate cache.
6636 			 */
6637 			curthread->t_predcache = 0;
6638 
6639 			if (dvar == NULL)
6640 				break;
6641 
6642 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6643 				size_t lim;
6644 
6645 				if (!dtrace_vcanload(
6646 				    (void *)(uintptr_t)regs[rd],
6647 				    &v->dtdv_type, &lim, mstate, vstate))
6648 					break;
6649 
6650 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6651 				    dvar->dtdv_data, &v->dtdv_type, lim);
6652 			} else {
6653 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6654 			}
6655 
6656 			break;
6657 		}
6658 
6659 		case DIF_OP_SRA:
6660 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6661 			break;
6662 
6663 		case DIF_OP_CALL:
6664 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6665 			    regs, tupregs, ttop, mstate, state);
6666 			break;
6667 
6668 		case DIF_OP_PUSHTR:
6669 			if (ttop == DIF_DTR_NREGS) {
6670 				*flags |= CPU_DTRACE_TUPOFLOW;
6671 				break;
6672 			}
6673 
6674 			if (r1 == DIF_TYPE_STRING) {
6675 				/*
6676 				 * If this is a string type and the size is 0,
6677 				 * we'll use the system-wide default string
6678 				 * size.  Note that we are _not_ looking at
6679 				 * the value of the DTRACEOPT_STRSIZE option;
6680 				 * had this been set, we would expect to have
6681 				 * a non-zero size value in the "pushtr".
6682 				 */
6683 				tupregs[ttop].dttk_size =
6684 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6685 				    regs[r2] ? regs[r2] :
6686 				    dtrace_strsize_default) + 1;
6687 			} else {
6688 				if (regs[r2] > LONG_MAX) {
6689 					*flags |= CPU_DTRACE_ILLOP;
6690 					break;
6691 				}
6692 
6693 				tupregs[ttop].dttk_size = regs[r2];
6694 			}
6695 
6696 			tupregs[ttop++].dttk_value = regs[rd];
6697 			break;
6698 
6699 		case DIF_OP_PUSHTV:
6700 			if (ttop == DIF_DTR_NREGS) {
6701 				*flags |= CPU_DTRACE_TUPOFLOW;
6702 				break;
6703 			}
6704 
6705 			tupregs[ttop].dttk_value = regs[rd];
6706 			tupregs[ttop++].dttk_size = 0;
6707 			break;
6708 
6709 		case DIF_OP_POPTS:
6710 			if (ttop != 0)
6711 				ttop--;
6712 			break;
6713 
6714 		case DIF_OP_FLUSHTS:
6715 			ttop = 0;
6716 			break;
6717 
6718 		case DIF_OP_LDGAA:
6719 		case DIF_OP_LDTAA: {
6720 			dtrace_dynvar_t *dvar;
6721 			dtrace_key_t *key = tupregs;
6722 			uint_t nkeys = ttop;
6723 
6724 			id = DIF_INSTR_VAR(instr);
6725 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6726 			id -= DIF_VAR_OTHER_UBASE;
6727 
6728 			key[nkeys].dttk_value = (uint64_t)id;
6729 			key[nkeys++].dttk_size = 0;
6730 
6731 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6732 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6733 				key[nkeys++].dttk_size = 0;
6734 				VERIFY(id < vstate->dtvs_ntlocals);
6735 				v = &vstate->dtvs_tlocals[id];
6736 			} else {
6737 				VERIFY(id < vstate->dtvs_nglobals);
6738 				v = &vstate->dtvs_globals[id]->dtsv_var;
6739 			}
6740 
6741 			dvar = dtrace_dynvar(dstate, nkeys, key,
6742 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6743 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6744 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6745 
6746 			if (dvar == NULL) {
6747 				regs[rd] = 0;
6748 				break;
6749 			}
6750 
6751 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6752 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6753 			} else {
6754 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6755 			}
6756 
6757 			break;
6758 		}
6759 
6760 		case DIF_OP_STGAA:
6761 		case DIF_OP_STTAA: {
6762 			dtrace_dynvar_t *dvar;
6763 			dtrace_key_t *key = tupregs;
6764 			uint_t nkeys = ttop;
6765 
6766 			id = DIF_INSTR_VAR(instr);
6767 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6768 			id -= DIF_VAR_OTHER_UBASE;
6769 
6770 			key[nkeys].dttk_value = (uint64_t)id;
6771 			key[nkeys++].dttk_size = 0;
6772 
6773 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6774 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6775 				key[nkeys++].dttk_size = 0;
6776 				VERIFY(id < vstate->dtvs_ntlocals);
6777 				v = &vstate->dtvs_tlocals[id];
6778 			} else {
6779 				VERIFY(id < vstate->dtvs_nglobals);
6780 				v = &vstate->dtvs_globals[id]->dtsv_var;
6781 			}
6782 
6783 			dvar = dtrace_dynvar(dstate, nkeys, key,
6784 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6785 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6786 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6787 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6788 
6789 			if (dvar == NULL)
6790 				break;
6791 
6792 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6793 				size_t lim;
6794 
6795 				if (!dtrace_vcanload(
6796 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6797 				    &lim, mstate, vstate))
6798 					break;
6799 
6800 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6801 				    dvar->dtdv_data, &v->dtdv_type, lim);
6802 			} else {
6803 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6804 			}
6805 
6806 			break;
6807 		}
6808 
6809 		case DIF_OP_ALLOCS: {
6810 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6811 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6812 
6813 			/*
6814 			 * Rounding up the user allocation size could have
6815 			 * overflowed large, bogus allocations (like -1ULL) to
6816 			 * 0.
6817 			 */
6818 			if (size < regs[r1] ||
6819 			    !DTRACE_INSCRATCH(mstate, size)) {
6820 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6821 				regs[rd] = 0;
6822 				break;
6823 			}
6824 
6825 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6826 			mstate->dtms_scratch_ptr += size;
6827 			regs[rd] = ptr;
6828 			break;
6829 		}
6830 
6831 		case DIF_OP_COPYS:
6832 			if (!dtrace_canstore(regs[rd], regs[r2],
6833 			    mstate, vstate)) {
6834 				*flags |= CPU_DTRACE_BADADDR;
6835 				*illval = regs[rd];
6836 				break;
6837 			}
6838 
6839 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6840 				break;
6841 
6842 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6843 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6844 			break;
6845 
6846 		case DIF_OP_STB:
6847 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6848 				*flags |= CPU_DTRACE_BADADDR;
6849 				*illval = regs[rd];
6850 				break;
6851 			}
6852 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6853 			break;
6854 
6855 		case DIF_OP_STH:
6856 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6857 				*flags |= CPU_DTRACE_BADADDR;
6858 				*illval = regs[rd];
6859 				break;
6860 			}
6861 			if (regs[rd] & 1) {
6862 				*flags |= CPU_DTRACE_BADALIGN;
6863 				*illval = regs[rd];
6864 				break;
6865 			}
6866 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6867 			break;
6868 
6869 		case DIF_OP_STW:
6870 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6871 				*flags |= CPU_DTRACE_BADADDR;
6872 				*illval = regs[rd];
6873 				break;
6874 			}
6875 			if (regs[rd] & 3) {
6876 				*flags |= CPU_DTRACE_BADALIGN;
6877 				*illval = regs[rd];
6878 				break;
6879 			}
6880 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6881 			break;
6882 
6883 		case DIF_OP_STX:
6884 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6885 				*flags |= CPU_DTRACE_BADADDR;
6886 				*illval = regs[rd];
6887 				break;
6888 			}
6889 			if (regs[rd] & 7) {
6890 				*flags |= CPU_DTRACE_BADALIGN;
6891 				*illval = regs[rd];
6892 				break;
6893 			}
6894 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6895 			break;
6896 		}
6897 	}
6898 
6899 	if (!(*flags & CPU_DTRACE_FAULT))
6900 		return (rval);
6901 
6902 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6903 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6904 
6905 	return (0);
6906 }
6907 
6908 static void
6909 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6910 {
6911 	dtrace_probe_t *probe = ecb->dte_probe;
6912 	dtrace_provider_t *prov = probe->dtpr_provider;
6913 	char c[DTRACE_FULLNAMELEN + 80], *str;
6914 	char *msg = "dtrace: breakpoint action at probe ";
6915 	char *ecbmsg = " (ecb ";
6916 	uintptr_t val = (uintptr_t)ecb;
6917 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6918 
6919 	if (dtrace_destructive_disallow)
6920 		return;
6921 
6922 	/*
6923 	 * It's impossible to be taking action on the NULL probe.
6924 	 */
6925 	ASSERT(probe != NULL);
6926 
6927 	/*
6928 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6929 	 * print the provider name, module name, function name and name of
6930 	 * the probe, along with the hex address of the ECB with the breakpoint
6931 	 * action -- all of which we must place in the character buffer by
6932 	 * hand.
6933 	 */
6934 	while (*msg != '\0')
6935 		c[i++] = *msg++;
6936 
6937 	for (str = prov->dtpv_name; *str != '\0'; str++)
6938 		c[i++] = *str;
6939 	c[i++] = ':';
6940 
6941 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6942 		c[i++] = *str;
6943 	c[i++] = ':';
6944 
6945 	for (str = probe->dtpr_func; *str != '\0'; str++)
6946 		c[i++] = *str;
6947 	c[i++] = ':';
6948 
6949 	for (str = probe->dtpr_name; *str != '\0'; str++)
6950 		c[i++] = *str;
6951 
6952 	while (*ecbmsg != '\0')
6953 		c[i++] = *ecbmsg++;
6954 
6955 	while (shift >= 0) {
6956 		size_t mask = (size_t)0xf << shift;
6957 
6958 		if (val >= ((size_t)1 << shift))
6959 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6960 		shift -= 4;
6961 	}
6962 
6963 	c[i++] = ')';
6964 	c[i] = '\0';
6965 
6966 #ifdef illumos
6967 	debug_enter(c);
6968 #else
6969 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6970 #endif
6971 }
6972 
6973 static void
6974 dtrace_action_panic(dtrace_ecb_t *ecb)
6975 {
6976 	dtrace_probe_t *probe = ecb->dte_probe;
6977 
6978 	/*
6979 	 * It's impossible to be taking action on the NULL probe.
6980 	 */
6981 	ASSERT(probe != NULL);
6982 
6983 	if (dtrace_destructive_disallow)
6984 		return;
6985 
6986 	if (dtrace_panicked != NULL)
6987 		return;
6988 
6989 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6990 		return;
6991 
6992 	/*
6993 	 * We won the right to panic.  (We want to be sure that only one
6994 	 * thread calls panic() from dtrace_probe(), and that panic() is
6995 	 * called exactly once.)
6996 	 */
6997 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6998 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6999 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
7000 }
7001 
7002 static void
7003 dtrace_action_raise(uint64_t sig)
7004 {
7005 	if (dtrace_destructive_disallow)
7006 		return;
7007 
7008 	if (sig >= NSIG) {
7009 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7010 		return;
7011 	}
7012 
7013 #ifdef illumos
7014 	/*
7015 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7016 	 * invocations of the raise() action.
7017 	 */
7018 	if (curthread->t_dtrace_sig == 0)
7019 		curthread->t_dtrace_sig = (uint8_t)sig;
7020 
7021 	curthread->t_sig_check = 1;
7022 	aston(curthread);
7023 #else
7024 	struct proc *p = curproc;
7025 	PROC_LOCK(p);
7026 	kern_psignal(p, sig);
7027 	PROC_UNLOCK(p);
7028 #endif
7029 }
7030 
7031 static void
7032 dtrace_action_stop(void)
7033 {
7034 	if (dtrace_destructive_disallow)
7035 		return;
7036 
7037 #ifdef illumos
7038 	if (!curthread->t_dtrace_stop) {
7039 		curthread->t_dtrace_stop = 1;
7040 		curthread->t_sig_check = 1;
7041 		aston(curthread);
7042 	}
7043 #else
7044 	struct proc *p = curproc;
7045 	PROC_LOCK(p);
7046 	kern_psignal(p, SIGSTOP);
7047 	PROC_UNLOCK(p);
7048 #endif
7049 }
7050 
7051 static void
7052 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7053 {
7054 	hrtime_t now;
7055 	volatile uint16_t *flags;
7056 #ifdef illumos
7057 	cpu_t *cpu = CPU;
7058 #else
7059 	cpu_t *cpu = &solaris_cpu[curcpu];
7060 #endif
7061 
7062 	if (dtrace_destructive_disallow)
7063 		return;
7064 
7065 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7066 
7067 	now = dtrace_gethrtime();
7068 
7069 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7070 		/*
7071 		 * We need to advance the mark to the current time.
7072 		 */
7073 		cpu->cpu_dtrace_chillmark = now;
7074 		cpu->cpu_dtrace_chilled = 0;
7075 	}
7076 
7077 	/*
7078 	 * Now check to see if the requested chill time would take us over
7079 	 * the maximum amount of time allowed in the chill interval.  (Or
7080 	 * worse, if the calculation itself induces overflow.)
7081 	 */
7082 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7083 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7084 		*flags |= CPU_DTRACE_ILLOP;
7085 		return;
7086 	}
7087 
7088 	while (dtrace_gethrtime() - now < val)
7089 		continue;
7090 
7091 	/*
7092 	 * Normally, we assure that the value of the variable "timestamp" does
7093 	 * not change within an ECB.  The presence of chill() represents an
7094 	 * exception to this rule, however.
7095 	 */
7096 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7097 	cpu->cpu_dtrace_chilled += val;
7098 }
7099 
7100 static void
7101 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7102     uint64_t *buf, uint64_t arg)
7103 {
7104 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7105 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7106 	uint64_t *pcs = &buf[1], *fps;
7107 	char *str = (char *)&pcs[nframes];
7108 	int size, offs = 0, i, j;
7109 	size_t rem;
7110 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7111 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7112 	char *sym;
7113 
7114 	/*
7115 	 * Should be taking a faster path if string space has not been
7116 	 * allocated.
7117 	 */
7118 	ASSERT(strsize != 0);
7119 
7120 	/*
7121 	 * We will first allocate some temporary space for the frame pointers.
7122 	 */
7123 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7124 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7125 	    (nframes * sizeof (uint64_t));
7126 
7127 	if (!DTRACE_INSCRATCH(mstate, size)) {
7128 		/*
7129 		 * Not enough room for our frame pointers -- need to indicate
7130 		 * that we ran out of scratch space.
7131 		 */
7132 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7133 		return;
7134 	}
7135 
7136 	mstate->dtms_scratch_ptr += size;
7137 	saved = mstate->dtms_scratch_ptr;
7138 
7139 	/*
7140 	 * Now get a stack with both program counters and frame pointers.
7141 	 */
7142 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7143 	dtrace_getufpstack(buf, fps, nframes + 1);
7144 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7145 
7146 	/*
7147 	 * If that faulted, we're cooked.
7148 	 */
7149 	if (*flags & CPU_DTRACE_FAULT)
7150 		goto out;
7151 
7152 	/*
7153 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7154 	 * each iteration, we restore the scratch pointer.
7155 	 */
7156 	for (i = 0; i < nframes; i++) {
7157 		mstate->dtms_scratch_ptr = saved;
7158 
7159 		if (offs >= strsize)
7160 			break;
7161 
7162 		sym = (char *)(uintptr_t)dtrace_helper(
7163 		    DTRACE_HELPER_ACTION_USTACK,
7164 		    mstate, state, pcs[i], fps[i]);
7165 
7166 		/*
7167 		 * If we faulted while running the helper, we're going to
7168 		 * clear the fault and null out the corresponding string.
7169 		 */
7170 		if (*flags & CPU_DTRACE_FAULT) {
7171 			*flags &= ~CPU_DTRACE_FAULT;
7172 			str[offs++] = '\0';
7173 			continue;
7174 		}
7175 
7176 		if (sym == NULL) {
7177 			str[offs++] = '\0';
7178 			continue;
7179 		}
7180 
7181 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7182 		    &(state->dts_vstate))) {
7183 			str[offs++] = '\0';
7184 			continue;
7185 		}
7186 
7187 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7188 
7189 		/*
7190 		 * Now copy in the string that the helper returned to us.
7191 		 */
7192 		for (j = 0; offs + j < strsize && j < rem; j++) {
7193 			if ((str[offs + j] = sym[j]) == '\0')
7194 				break;
7195 		}
7196 
7197 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7198 
7199 		offs += j + 1;
7200 	}
7201 
7202 	if (offs >= strsize) {
7203 		/*
7204 		 * If we didn't have room for all of the strings, we don't
7205 		 * abort processing -- this needn't be a fatal error -- but we
7206 		 * still want to increment a counter (dts_stkstroverflows) to
7207 		 * allow this condition to be warned about.  (If this is from
7208 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7209 		 */
7210 		dtrace_error(&state->dts_stkstroverflows);
7211 	}
7212 
7213 	while (offs < strsize)
7214 		str[offs++] = '\0';
7215 
7216 out:
7217 	mstate->dtms_scratch_ptr = old;
7218 }
7219 
7220 static void
7221 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7222     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7223 {
7224 	volatile uint16_t *flags;
7225 	uint64_t val = *valp;
7226 	size_t valoffs = *valoffsp;
7227 
7228 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7229 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7230 
7231 	/*
7232 	 * If this is a string, we're going to only load until we find the zero
7233 	 * byte -- after which we'll store zero bytes.
7234 	 */
7235 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7236 		char c = '\0' + 1;
7237 		size_t s;
7238 
7239 		for (s = 0; s < size; s++) {
7240 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7241 				c = dtrace_load8(val++);
7242 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7243 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7244 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7245 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7246 				if (*flags & CPU_DTRACE_FAULT)
7247 					break;
7248 			}
7249 
7250 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7251 
7252 			if (c == '\0' && intuple)
7253 				break;
7254 		}
7255 	} else {
7256 		uint8_t c;
7257 		while (valoffs < end) {
7258 			if (dtkind == DIF_TF_BYREF) {
7259 				c = dtrace_load8(val++);
7260 			} else if (dtkind == DIF_TF_BYUREF) {
7261 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7262 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7263 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7264 				if (*flags & CPU_DTRACE_FAULT)
7265 					break;
7266 			}
7267 
7268 			DTRACE_STORE(uint8_t, tomax,
7269 			    valoffs++, c);
7270 		}
7271 	}
7272 
7273 	*valp = val;
7274 	*valoffsp = valoffs;
7275 }
7276 
7277 /*
7278  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7279  * defined, we also assert that we are not recursing unless the probe ID is an
7280  * error probe.
7281  */
7282 static dtrace_icookie_t
7283 dtrace_probe_enter(dtrace_id_t id)
7284 {
7285 	dtrace_icookie_t cookie;
7286 
7287 	cookie = dtrace_interrupt_disable();
7288 
7289 	/*
7290 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7291 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7292 	 * function is instrumented that should not have been instrumented or
7293 	 * that the ordering guarantee of the records will be violated,
7294 	 * resulting in unexpected output. If there is an exception to this
7295 	 * assertion, a new case should be added.
7296 	 */
7297 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7298 	    id == dtrace_probeid_error);
7299 	curthread->t_dtrace_inprobe = 1;
7300 
7301 	return (cookie);
7302 }
7303 
7304 /*
7305  * Clears the per-thread inprobe flag and enables interrupts.
7306  */
7307 static void
7308 dtrace_probe_exit(dtrace_icookie_t cookie)
7309 {
7310 
7311 	curthread->t_dtrace_inprobe = 0;
7312 	dtrace_interrupt_enable(cookie);
7313 }
7314 
7315 /*
7316  * If you're looking for the epicenter of DTrace, you just found it.  This
7317  * is the function called by the provider to fire a probe -- from which all
7318  * subsequent probe-context DTrace activity emanates.
7319  */
7320 void
7321 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7322     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7323 {
7324 	processorid_t cpuid;
7325 	dtrace_icookie_t cookie;
7326 	dtrace_probe_t *probe;
7327 	dtrace_mstate_t mstate;
7328 	dtrace_ecb_t *ecb;
7329 	dtrace_action_t *act;
7330 	intptr_t offs;
7331 	size_t size;
7332 	int vtime, onintr;
7333 	volatile uint16_t *flags;
7334 	hrtime_t now;
7335 
7336 	if (KERNEL_PANICKED())
7337 		return;
7338 
7339 #ifdef illumos
7340 	/*
7341 	 * Kick out immediately if this CPU is still being born (in which case
7342 	 * curthread will be set to -1) or the current thread can't allow
7343 	 * probes in its current context.
7344 	 */
7345 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7346 		return;
7347 #endif
7348 
7349 	cookie = dtrace_probe_enter(id);
7350 	probe = dtrace_probes[id - 1];
7351 	cpuid = curcpu;
7352 	onintr = CPU_ON_INTR(CPU);
7353 
7354 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7355 	    probe->dtpr_predcache == curthread->t_predcache) {
7356 		/*
7357 		 * We have hit in the predicate cache; we know that
7358 		 * this predicate would evaluate to be false.
7359 		 */
7360 		dtrace_probe_exit(cookie);
7361 		return;
7362 	}
7363 
7364 #ifdef illumos
7365 	if (panic_quiesce) {
7366 #else
7367 	if (KERNEL_PANICKED()) {
7368 #endif
7369 		/*
7370 		 * We don't trace anything if we're panicking.
7371 		 */
7372 		dtrace_probe_exit(cookie);
7373 		return;
7374 	}
7375 
7376 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7377 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7378 	vtime = dtrace_vtime_references != 0;
7379 
7380 	if (vtime && curthread->t_dtrace_start)
7381 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7382 
7383 	mstate.dtms_difo = NULL;
7384 	mstate.dtms_probe = probe;
7385 	mstate.dtms_strtok = 0;
7386 	mstate.dtms_arg[0] = arg0;
7387 	mstate.dtms_arg[1] = arg1;
7388 	mstate.dtms_arg[2] = arg2;
7389 	mstate.dtms_arg[3] = arg3;
7390 	mstate.dtms_arg[4] = arg4;
7391 
7392 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7393 
7394 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7395 		dtrace_predicate_t *pred = ecb->dte_predicate;
7396 		dtrace_state_t *state = ecb->dte_state;
7397 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7398 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7399 		dtrace_vstate_t *vstate = &state->dts_vstate;
7400 		dtrace_provider_t *prov = probe->dtpr_provider;
7401 		uint64_t tracememsize = 0;
7402 		int committed = 0;
7403 		caddr_t tomax;
7404 
7405 		/*
7406 		 * A little subtlety with the following (seemingly innocuous)
7407 		 * declaration of the automatic 'val':  by looking at the
7408 		 * code, you might think that it could be declared in the
7409 		 * action processing loop, below.  (That is, it's only used in
7410 		 * the action processing loop.)  However, it must be declared
7411 		 * out of that scope because in the case of DIF expression
7412 		 * arguments to aggregating actions, one iteration of the
7413 		 * action loop will use the last iteration's value.
7414 		 */
7415 		uint64_t val = 0;
7416 
7417 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7418 		mstate.dtms_getf = NULL;
7419 
7420 		*flags &= ~CPU_DTRACE_ERROR;
7421 
7422 		if (prov == dtrace_provider) {
7423 			/*
7424 			 * If dtrace itself is the provider of this probe,
7425 			 * we're only going to continue processing the ECB if
7426 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7427 			 * creating state.  (This prevents disjoint consumers
7428 			 * from seeing one another's metaprobes.)
7429 			 */
7430 			if (arg0 != (uint64_t)(uintptr_t)state)
7431 				continue;
7432 		}
7433 
7434 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7435 			/*
7436 			 * We're not currently active.  If our provider isn't
7437 			 * the dtrace pseudo provider, we're not interested.
7438 			 */
7439 			if (prov != dtrace_provider)
7440 				continue;
7441 
7442 			/*
7443 			 * Now we must further check if we are in the BEGIN
7444 			 * probe.  If we are, we will only continue processing
7445 			 * if we're still in WARMUP -- if one BEGIN enabling
7446 			 * has invoked the exit() action, we don't want to
7447 			 * evaluate subsequent BEGIN enablings.
7448 			 */
7449 			if (probe->dtpr_id == dtrace_probeid_begin &&
7450 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7451 				ASSERT(state->dts_activity ==
7452 				    DTRACE_ACTIVITY_DRAINING);
7453 				continue;
7454 			}
7455 		}
7456 
7457 		if (ecb->dte_cond) {
7458 			/*
7459 			 * If the dte_cond bits indicate that this
7460 			 * consumer is only allowed to see user-mode firings
7461 			 * of this probe, call the provider's dtps_usermode()
7462 			 * entry point to check that the probe was fired
7463 			 * while in a user context. Skip this ECB if that's
7464 			 * not the case.
7465 			 */
7466 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7467 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7468 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7469 				continue;
7470 
7471 #ifdef illumos
7472 			/*
7473 			 * This is more subtle than it looks. We have to be
7474 			 * absolutely certain that CRED() isn't going to
7475 			 * change out from under us so it's only legit to
7476 			 * examine that structure if we're in constrained
7477 			 * situations. Currently, the only times we'll this
7478 			 * check is if a non-super-user has enabled the
7479 			 * profile or syscall providers -- providers that
7480 			 * allow visibility of all processes. For the
7481 			 * profile case, the check above will ensure that
7482 			 * we're examining a user context.
7483 			 */
7484 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7485 				cred_t *cr;
7486 				cred_t *s_cr =
7487 				    ecb->dte_state->dts_cred.dcr_cred;
7488 				proc_t *proc;
7489 
7490 				ASSERT(s_cr != NULL);
7491 
7492 				if ((cr = CRED()) == NULL ||
7493 				    s_cr->cr_uid != cr->cr_uid ||
7494 				    s_cr->cr_uid != cr->cr_ruid ||
7495 				    s_cr->cr_uid != cr->cr_suid ||
7496 				    s_cr->cr_gid != cr->cr_gid ||
7497 				    s_cr->cr_gid != cr->cr_rgid ||
7498 				    s_cr->cr_gid != cr->cr_sgid ||
7499 				    (proc = ttoproc(curthread)) == NULL ||
7500 				    (proc->p_flag & SNOCD))
7501 					continue;
7502 			}
7503 
7504 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7505 				cred_t *cr;
7506 				cred_t *s_cr =
7507 				    ecb->dte_state->dts_cred.dcr_cred;
7508 
7509 				ASSERT(s_cr != NULL);
7510 
7511 				if ((cr = CRED()) == NULL ||
7512 				    s_cr->cr_zone->zone_id !=
7513 				    cr->cr_zone->zone_id)
7514 					continue;
7515 			}
7516 #endif
7517 		}
7518 
7519 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7520 			/*
7521 			 * We seem to be dead.  Unless we (a) have kernel
7522 			 * destructive permissions (b) have explicitly enabled
7523 			 * destructive actions and (c) destructive actions have
7524 			 * not been disabled, we're going to transition into
7525 			 * the KILLED state, from which no further processing
7526 			 * on this state will be performed.
7527 			 */
7528 			if (!dtrace_priv_kernel_destructive(state) ||
7529 			    !state->dts_cred.dcr_destructive ||
7530 			    dtrace_destructive_disallow) {
7531 				void *activity = &state->dts_activity;
7532 				dtrace_activity_t curstate;
7533 
7534 				do {
7535 					curstate = state->dts_activity;
7536 				} while (dtrace_cas32(activity, curstate,
7537 				    DTRACE_ACTIVITY_KILLED) != curstate);
7538 
7539 				continue;
7540 			}
7541 		}
7542 
7543 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7544 		    ecb->dte_alignment, state, &mstate)) < 0)
7545 			continue;
7546 
7547 		tomax = buf->dtb_tomax;
7548 		ASSERT(tomax != NULL);
7549 
7550 		if (ecb->dte_size != 0) {
7551 			dtrace_rechdr_t dtrh;
7552 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7553 				mstate.dtms_timestamp = dtrace_gethrtime();
7554 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7555 			}
7556 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7557 			dtrh.dtrh_epid = ecb->dte_epid;
7558 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7559 			    mstate.dtms_timestamp);
7560 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7561 		}
7562 
7563 		mstate.dtms_epid = ecb->dte_epid;
7564 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7565 
7566 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7567 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7568 		else
7569 			mstate.dtms_access = 0;
7570 
7571 		if (pred != NULL) {
7572 			dtrace_difo_t *dp = pred->dtp_difo;
7573 			uint64_t rval;
7574 
7575 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7576 
7577 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7578 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7579 
7580 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7581 					/*
7582 					 * Update the predicate cache...
7583 					 */
7584 					ASSERT(cid == pred->dtp_cacheid);
7585 					curthread->t_predcache = cid;
7586 				}
7587 
7588 				continue;
7589 			}
7590 		}
7591 
7592 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7593 		    act != NULL; act = act->dta_next) {
7594 			size_t valoffs;
7595 			dtrace_difo_t *dp;
7596 			dtrace_recdesc_t *rec = &act->dta_rec;
7597 
7598 			size = rec->dtrd_size;
7599 			valoffs = offs + rec->dtrd_offset;
7600 
7601 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7602 				uint64_t v = 0xbad;
7603 				dtrace_aggregation_t *agg;
7604 
7605 				agg = (dtrace_aggregation_t *)act;
7606 
7607 				if ((dp = act->dta_difo) != NULL)
7608 					v = dtrace_dif_emulate(dp,
7609 					    &mstate, vstate, state);
7610 
7611 				if (*flags & CPU_DTRACE_ERROR)
7612 					continue;
7613 
7614 				/*
7615 				 * Note that we always pass the expression
7616 				 * value from the previous iteration of the
7617 				 * action loop.  This value will only be used
7618 				 * if there is an expression argument to the
7619 				 * aggregating action, denoted by the
7620 				 * dtag_hasarg field.
7621 				 */
7622 				dtrace_aggregate(agg, buf,
7623 				    offs, aggbuf, v, val);
7624 				continue;
7625 			}
7626 
7627 			switch (act->dta_kind) {
7628 			case DTRACEACT_STOP:
7629 				if (dtrace_priv_proc_destructive(state))
7630 					dtrace_action_stop();
7631 				continue;
7632 
7633 			case DTRACEACT_BREAKPOINT:
7634 				if (dtrace_priv_kernel_destructive(state))
7635 					dtrace_action_breakpoint(ecb);
7636 				continue;
7637 
7638 			case DTRACEACT_PANIC:
7639 				if (dtrace_priv_kernel_destructive(state))
7640 					dtrace_action_panic(ecb);
7641 				continue;
7642 
7643 			case DTRACEACT_STACK:
7644 				if (!dtrace_priv_kernel(state))
7645 					continue;
7646 
7647 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7648 				    size / sizeof (pc_t), probe->dtpr_aframes,
7649 				    DTRACE_ANCHORED(probe) ? NULL :
7650 				    (uint32_t *)arg0);
7651 				continue;
7652 
7653 			case DTRACEACT_JSTACK:
7654 			case DTRACEACT_USTACK:
7655 				if (!dtrace_priv_proc(state))
7656 					continue;
7657 
7658 				/*
7659 				 * See comment in DIF_VAR_PID.
7660 				 */
7661 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7662 				    CPU_ON_INTR(CPU)) {
7663 					int depth = DTRACE_USTACK_NFRAMES(
7664 					    rec->dtrd_arg) + 1;
7665 
7666 					dtrace_bzero((void *)(tomax + valoffs),
7667 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7668 					    + depth * sizeof (uint64_t));
7669 
7670 					continue;
7671 				}
7672 
7673 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7674 				    curproc->p_dtrace_helpers != NULL) {
7675 					/*
7676 					 * This is the slow path -- we have
7677 					 * allocated string space, and we're
7678 					 * getting the stack of a process that
7679 					 * has helpers.  Call into a separate
7680 					 * routine to perform this processing.
7681 					 */
7682 					dtrace_action_ustack(&mstate, state,
7683 					    (uint64_t *)(tomax + valoffs),
7684 					    rec->dtrd_arg);
7685 					continue;
7686 				}
7687 
7688 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7689 				dtrace_getupcstack((uint64_t *)
7690 				    (tomax + valoffs),
7691 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7692 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7693 				continue;
7694 
7695 			default:
7696 				break;
7697 			}
7698 
7699 			dp = act->dta_difo;
7700 			ASSERT(dp != NULL);
7701 
7702 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7703 
7704 			if (*flags & CPU_DTRACE_ERROR)
7705 				continue;
7706 
7707 			switch (act->dta_kind) {
7708 			case DTRACEACT_SPECULATE: {
7709 				dtrace_rechdr_t *dtrh;
7710 
7711 				ASSERT(buf == &state->dts_buffer[cpuid]);
7712 				buf = dtrace_speculation_buffer(state,
7713 				    cpuid, val);
7714 
7715 				if (buf == NULL) {
7716 					*flags |= CPU_DTRACE_DROP;
7717 					continue;
7718 				}
7719 
7720 				offs = dtrace_buffer_reserve(buf,
7721 				    ecb->dte_needed, ecb->dte_alignment,
7722 				    state, NULL);
7723 
7724 				if (offs < 0) {
7725 					*flags |= CPU_DTRACE_DROP;
7726 					continue;
7727 				}
7728 
7729 				tomax = buf->dtb_tomax;
7730 				ASSERT(tomax != NULL);
7731 
7732 				if (ecb->dte_size == 0)
7733 					continue;
7734 
7735 				ASSERT3U(ecb->dte_size, >=,
7736 				    sizeof (dtrace_rechdr_t));
7737 				dtrh = ((void *)(tomax + offs));
7738 				dtrh->dtrh_epid = ecb->dte_epid;
7739 				/*
7740 				 * When the speculation is committed, all of
7741 				 * the records in the speculative buffer will
7742 				 * have their timestamps set to the commit
7743 				 * time.  Until then, it is set to a sentinel
7744 				 * value, for debugability.
7745 				 */
7746 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7747 				continue;
7748 			}
7749 
7750 			case DTRACEACT_PRINTM: {
7751 				/*
7752 				 * printm() assumes that the DIF returns a
7753 				 * pointer returned by memref(). memref() is a
7754 				 * subroutine that is used to get around the
7755 				 * single-valued returns of DIF and is assumed
7756 				 * to always be allocated in the scratch space.
7757 				 * Therefore, we need to validate that the
7758 				 * pointer given to printm() is in the scratch
7759 				 * space in order to avoid a potential panic.
7760 				 */
7761 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7762 
7763 				if (!DTRACE_INSCRATCHPTR(&mstate,
7764 				    (uintptr_t) memref,
7765 				    sizeof (uintptr_t) + sizeof (size_t))) {
7766 					*flags |= CPU_DTRACE_BADADDR;
7767 					continue;
7768 				}
7769 
7770 				/* Get the size from the memref. */
7771 				size = memref[1];
7772 
7773 				/*
7774 				 * Check if the size exceeds the allocated
7775 				 * buffer size.
7776 				 */
7777 				if (size + sizeof (size_t) >
7778 				    dp->dtdo_rtype.dtdt_size) {
7779 					/* Flag a drop! */
7780 					*flags |= CPU_DTRACE_DROP;
7781 					continue;
7782 				}
7783 
7784 				/* Store the size in the buffer first. */
7785 				DTRACE_STORE(size_t, tomax, valoffs, size);
7786 
7787 				/*
7788 				 * Offset the buffer address to the start
7789 				 * of the data.
7790 				 */
7791 				valoffs += sizeof(size_t);
7792 
7793 				/*
7794 				 * Reset to the memory address rather than
7795 				 * the memref array, then let the BYREF
7796 				 * code below do the work to store the
7797 				 * memory data in the buffer.
7798 				 */
7799 				val = memref[0];
7800 				break;
7801 			}
7802 
7803 			case DTRACEACT_CHILL:
7804 				if (dtrace_priv_kernel_destructive(state))
7805 					dtrace_action_chill(&mstate, val);
7806 				continue;
7807 
7808 			case DTRACEACT_RAISE:
7809 				if (dtrace_priv_proc_destructive(state))
7810 					dtrace_action_raise(val);
7811 				continue;
7812 
7813 			case DTRACEACT_COMMIT:
7814 				ASSERT(!committed);
7815 
7816 				/*
7817 				 * We need to commit our buffer state.
7818 				 */
7819 				if (ecb->dte_size)
7820 					buf->dtb_offset = offs + ecb->dte_size;
7821 				buf = &state->dts_buffer[cpuid];
7822 				dtrace_speculation_commit(state, cpuid, val);
7823 				committed = 1;
7824 				continue;
7825 
7826 			case DTRACEACT_DISCARD:
7827 				dtrace_speculation_discard(state, cpuid, val);
7828 				continue;
7829 
7830 			case DTRACEACT_DIFEXPR:
7831 			case DTRACEACT_LIBACT:
7832 			case DTRACEACT_PRINTF:
7833 			case DTRACEACT_PRINTA:
7834 			case DTRACEACT_SYSTEM:
7835 			case DTRACEACT_FREOPEN:
7836 			case DTRACEACT_TRACEMEM:
7837 				break;
7838 
7839 			case DTRACEACT_TRACEMEM_DYNSIZE:
7840 				tracememsize = val;
7841 				break;
7842 
7843 			case DTRACEACT_SYM:
7844 			case DTRACEACT_MOD:
7845 				if (!dtrace_priv_kernel(state))
7846 					continue;
7847 				break;
7848 
7849 			case DTRACEACT_USYM:
7850 			case DTRACEACT_UMOD:
7851 			case DTRACEACT_UADDR: {
7852 #ifdef illumos
7853 				struct pid *pid = curthread->t_procp->p_pidp;
7854 #endif
7855 
7856 				if (!dtrace_priv_proc(state))
7857 					continue;
7858 
7859 				DTRACE_STORE(uint64_t, tomax,
7860 #ifdef illumos
7861 				    valoffs, (uint64_t)pid->pid_id);
7862 #else
7863 				    valoffs, (uint64_t) curproc->p_pid);
7864 #endif
7865 				DTRACE_STORE(uint64_t, tomax,
7866 				    valoffs + sizeof (uint64_t), val);
7867 
7868 				continue;
7869 			}
7870 
7871 			case DTRACEACT_EXIT: {
7872 				/*
7873 				 * For the exit action, we are going to attempt
7874 				 * to atomically set our activity to be
7875 				 * draining.  If this fails (either because
7876 				 * another CPU has beat us to the exit action,
7877 				 * or because our current activity is something
7878 				 * other than ACTIVE or WARMUP), we will
7879 				 * continue.  This assures that the exit action
7880 				 * can be successfully recorded at most once
7881 				 * when we're in the ACTIVE state.  If we're
7882 				 * encountering the exit() action while in
7883 				 * COOLDOWN, however, we want to honor the new
7884 				 * status code.  (We know that we're the only
7885 				 * thread in COOLDOWN, so there is no race.)
7886 				 */
7887 				void *activity = &state->dts_activity;
7888 				dtrace_activity_t curstate = state->dts_activity;
7889 
7890 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7891 					break;
7892 
7893 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7894 					curstate = DTRACE_ACTIVITY_ACTIVE;
7895 
7896 				if (dtrace_cas32(activity, curstate,
7897 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7898 					*flags |= CPU_DTRACE_DROP;
7899 					continue;
7900 				}
7901 
7902 				break;
7903 			}
7904 
7905 			default:
7906 				ASSERT(0);
7907 			}
7908 
7909 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7910 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7911 				uintptr_t end = valoffs + size;
7912 
7913 				if (tracememsize != 0 &&
7914 				    valoffs + tracememsize < end) {
7915 					end = valoffs + tracememsize;
7916 					tracememsize = 0;
7917 				}
7918 
7919 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7920 				    !dtrace_vcanload((void *)(uintptr_t)val,
7921 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7922 					continue;
7923 
7924 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7925 				    &val, end, act->dta_intuple,
7926 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7927 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7928 				continue;
7929 			}
7930 
7931 			switch (size) {
7932 			case 0:
7933 				break;
7934 
7935 			case sizeof (uint8_t):
7936 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7937 				break;
7938 			case sizeof (uint16_t):
7939 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7940 				break;
7941 			case sizeof (uint32_t):
7942 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7943 				break;
7944 			case sizeof (uint64_t):
7945 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7946 				break;
7947 			default:
7948 				/*
7949 				 * Any other size should have been returned by
7950 				 * reference, not by value.
7951 				 */
7952 				ASSERT(0);
7953 				break;
7954 			}
7955 		}
7956 
7957 		if (*flags & CPU_DTRACE_DROP)
7958 			continue;
7959 
7960 		if (*flags & CPU_DTRACE_FAULT) {
7961 			int ndx;
7962 			dtrace_action_t *err;
7963 
7964 			buf->dtb_errors++;
7965 
7966 			if (probe->dtpr_id == dtrace_probeid_error) {
7967 				/*
7968 				 * There's nothing we can do -- we had an
7969 				 * error on the error probe.  We bump an
7970 				 * error counter to at least indicate that
7971 				 * this condition happened.
7972 				 */
7973 				dtrace_error(&state->dts_dblerrors);
7974 				continue;
7975 			}
7976 
7977 			if (vtime) {
7978 				/*
7979 				 * Before recursing on dtrace_probe(), we
7980 				 * need to explicitly clear out our start
7981 				 * time to prevent it from being accumulated
7982 				 * into t_dtrace_vtime.
7983 				 */
7984 				curthread->t_dtrace_start = 0;
7985 			}
7986 
7987 			/*
7988 			 * Iterate over the actions to figure out which action
7989 			 * we were processing when we experienced the error.
7990 			 * Note that act points _past_ the faulting action; if
7991 			 * act is ecb->dte_action, the fault was in the
7992 			 * predicate, if it's ecb->dte_action->dta_next it's
7993 			 * in action #1, and so on.
7994 			 */
7995 			for (err = ecb->dte_action, ndx = 0;
7996 			    err != act; err = err->dta_next, ndx++)
7997 				continue;
7998 
7999 			dtrace_probe_error(state, ecb->dte_epid, ndx,
8000 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
8001 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
8002 			    cpu_core[cpuid].cpuc_dtrace_illval);
8003 
8004 			continue;
8005 		}
8006 
8007 		if (!committed)
8008 			buf->dtb_offset = offs + ecb->dte_size;
8009 	}
8010 
8011 	if (vtime)
8012 		curthread->t_dtrace_start = dtrace_gethrtime();
8013 
8014 	dtrace_probe_exit(cookie);
8015 }
8016 
8017 /*
8018  * DTrace Probe Hashing Functions
8019  *
8020  * The functions in this section (and indeed, the functions in remaining
8021  * sections) are not _called_ from probe context.  (Any exceptions to this are
8022  * marked with a "Note:".)  Rather, they are called from elsewhere in the
8023  * DTrace framework to look-up probes in, add probes to and remove probes from
8024  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8025  * probe tuple -- allowing for fast lookups, regardless of what was
8026  * specified.)
8027  */
8028 static uint_t
8029 dtrace_hash_str(const char *p)
8030 {
8031 	unsigned int g;
8032 	uint_t hval = 0;
8033 
8034 	while (*p) {
8035 		hval = (hval << 4) + *p++;
8036 		if ((g = (hval & 0xf0000000)) != 0)
8037 			hval ^= g >> 24;
8038 		hval &= ~g;
8039 	}
8040 	return (hval);
8041 }
8042 
8043 static dtrace_hash_t *
8044 dtrace_hash_create(size_t stroffs, size_t nextoffs, size_t prevoffs)
8045 {
8046 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8047 
8048 	hash->dth_stroffs = stroffs;
8049 	hash->dth_nextoffs = nextoffs;
8050 	hash->dth_prevoffs = prevoffs;
8051 
8052 	hash->dth_size = 1;
8053 	hash->dth_mask = hash->dth_size - 1;
8054 
8055 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8056 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8057 
8058 	return (hash);
8059 }
8060 
8061 static void
8062 dtrace_hash_destroy(dtrace_hash_t *hash)
8063 {
8064 #ifdef DEBUG
8065 	int i;
8066 
8067 	for (i = 0; i < hash->dth_size; i++)
8068 		ASSERT(hash->dth_tab[i] == NULL);
8069 #endif
8070 
8071 	kmem_free(hash->dth_tab,
8072 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8073 	kmem_free(hash, sizeof (dtrace_hash_t));
8074 }
8075 
8076 static void
8077 dtrace_hash_resize(dtrace_hash_t *hash)
8078 {
8079 	int size = hash->dth_size, i, ndx;
8080 	int new_size = hash->dth_size << 1;
8081 	int new_mask = new_size - 1;
8082 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8083 
8084 	ASSERT((new_size & new_mask) == 0);
8085 
8086 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8087 
8088 	for (i = 0; i < size; i++) {
8089 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8090 			dtrace_probe_t *probe = bucket->dthb_chain;
8091 
8092 			ASSERT(probe != NULL);
8093 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8094 
8095 			next = bucket->dthb_next;
8096 			bucket->dthb_next = new_tab[ndx];
8097 			new_tab[ndx] = bucket;
8098 		}
8099 	}
8100 
8101 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8102 	hash->dth_tab = new_tab;
8103 	hash->dth_size = new_size;
8104 	hash->dth_mask = new_mask;
8105 }
8106 
8107 static void
8108 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8109 {
8110 	int hashval = DTRACE_HASHSTR(hash, new);
8111 	int ndx = hashval & hash->dth_mask;
8112 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8113 	dtrace_probe_t **nextp, **prevp;
8114 
8115 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8116 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8117 			goto add;
8118 	}
8119 
8120 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8121 		dtrace_hash_resize(hash);
8122 		dtrace_hash_add(hash, new);
8123 		return;
8124 	}
8125 
8126 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8127 	bucket->dthb_next = hash->dth_tab[ndx];
8128 	hash->dth_tab[ndx] = bucket;
8129 	hash->dth_nbuckets++;
8130 
8131 add:
8132 	nextp = DTRACE_HASHNEXT(hash, new);
8133 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8134 	*nextp = bucket->dthb_chain;
8135 
8136 	if (bucket->dthb_chain != NULL) {
8137 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8138 		ASSERT(*prevp == NULL);
8139 		*prevp = new;
8140 	}
8141 
8142 	bucket->dthb_chain = new;
8143 	bucket->dthb_len++;
8144 }
8145 
8146 static dtrace_probe_t *
8147 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8148 {
8149 	int hashval = DTRACE_HASHSTR(hash, template);
8150 	int ndx = hashval & hash->dth_mask;
8151 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8152 
8153 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8154 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8155 			return (bucket->dthb_chain);
8156 	}
8157 
8158 	return (NULL);
8159 }
8160 
8161 static int
8162 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8163 {
8164 	int hashval = DTRACE_HASHSTR(hash, template);
8165 	int ndx = hashval & hash->dth_mask;
8166 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8167 
8168 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8169 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8170 			return (bucket->dthb_len);
8171 	}
8172 
8173 	return (0);
8174 }
8175 
8176 static void
8177 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8178 {
8179 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8180 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8181 
8182 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8183 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8184 
8185 	/*
8186 	 * Find the bucket that we're removing this probe from.
8187 	 */
8188 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8189 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8190 			break;
8191 	}
8192 
8193 	ASSERT(bucket != NULL);
8194 
8195 	if (*prevp == NULL) {
8196 		if (*nextp == NULL) {
8197 			/*
8198 			 * The removed probe was the only probe on this
8199 			 * bucket; we need to remove the bucket.
8200 			 */
8201 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8202 
8203 			ASSERT(bucket->dthb_chain == probe);
8204 			ASSERT(b != NULL);
8205 
8206 			if (b == bucket) {
8207 				hash->dth_tab[ndx] = bucket->dthb_next;
8208 			} else {
8209 				while (b->dthb_next != bucket)
8210 					b = b->dthb_next;
8211 				b->dthb_next = bucket->dthb_next;
8212 			}
8213 
8214 			ASSERT(hash->dth_nbuckets > 0);
8215 			hash->dth_nbuckets--;
8216 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8217 			return;
8218 		}
8219 
8220 		bucket->dthb_chain = *nextp;
8221 	} else {
8222 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8223 	}
8224 
8225 	if (*nextp != NULL)
8226 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8227 }
8228 
8229 /*
8230  * DTrace Utility Functions
8231  *
8232  * These are random utility functions that are _not_ called from probe context.
8233  */
8234 static int
8235 dtrace_badattr(const dtrace_attribute_t *a)
8236 {
8237 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8238 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8239 	    a->dtat_class > DTRACE_CLASS_MAX);
8240 }
8241 
8242 /*
8243  * Return a duplicate copy of a string.  If the specified string is NULL,
8244  * this function returns a zero-length string.
8245  */
8246 static char *
8247 dtrace_strdup(const char *str)
8248 {
8249 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8250 
8251 	if (str != NULL)
8252 		(void) strcpy(new, str);
8253 
8254 	return (new);
8255 }
8256 
8257 #define	DTRACE_ISALPHA(c)	\
8258 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8259 
8260 static int
8261 dtrace_badname(const char *s)
8262 {
8263 	char c;
8264 
8265 	if (s == NULL || (c = *s++) == '\0')
8266 		return (0);
8267 
8268 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8269 		return (1);
8270 
8271 	while ((c = *s++) != '\0') {
8272 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8273 		    c != '-' && c != '_' && c != '.' && c != '`')
8274 			return (1);
8275 	}
8276 
8277 	return (0);
8278 }
8279 
8280 static void
8281 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8282 {
8283 	uint32_t priv;
8284 
8285 #ifdef illumos
8286 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8287 		/*
8288 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8289 		 */
8290 		priv = DTRACE_PRIV_ALL;
8291 	} else {
8292 		*uidp = crgetuid(cr);
8293 		*zoneidp = crgetzoneid(cr);
8294 
8295 		priv = 0;
8296 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8297 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8298 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8299 			priv |= DTRACE_PRIV_USER;
8300 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8301 			priv |= DTRACE_PRIV_PROC;
8302 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8303 			priv |= DTRACE_PRIV_OWNER;
8304 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8305 			priv |= DTRACE_PRIV_ZONEOWNER;
8306 	}
8307 #else
8308 	priv = DTRACE_PRIV_ALL;
8309 #endif
8310 
8311 	*privp = priv;
8312 }
8313 
8314 #ifdef DTRACE_ERRDEBUG
8315 static void
8316 dtrace_errdebug(const char *str)
8317 {
8318 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8319 	int occupied = 0;
8320 
8321 	mutex_enter(&dtrace_errlock);
8322 	dtrace_errlast = str;
8323 	dtrace_errthread = curthread;
8324 
8325 	while (occupied++ < DTRACE_ERRHASHSZ) {
8326 		if (dtrace_errhash[hval].dter_msg == str) {
8327 			dtrace_errhash[hval].dter_count++;
8328 			goto out;
8329 		}
8330 
8331 		if (dtrace_errhash[hval].dter_msg != NULL) {
8332 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8333 			continue;
8334 		}
8335 
8336 		dtrace_errhash[hval].dter_msg = str;
8337 		dtrace_errhash[hval].dter_count = 1;
8338 		goto out;
8339 	}
8340 
8341 	panic("dtrace: undersized error hash");
8342 out:
8343 	mutex_exit(&dtrace_errlock);
8344 }
8345 #endif
8346 
8347 /*
8348  * DTrace Matching Functions
8349  *
8350  * These functions are used to match groups of probes, given some elements of
8351  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8352  */
8353 static int
8354 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8355     zoneid_t zoneid)
8356 {
8357 	if (priv != DTRACE_PRIV_ALL) {
8358 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8359 		uint32_t match = priv & ppriv;
8360 
8361 		/*
8362 		 * No PRIV_DTRACE_* privileges...
8363 		 */
8364 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8365 		    DTRACE_PRIV_KERNEL)) == 0)
8366 			return (0);
8367 
8368 		/*
8369 		 * No matching bits, but there were bits to match...
8370 		 */
8371 		if (match == 0 && ppriv != 0)
8372 			return (0);
8373 
8374 		/*
8375 		 * Need to have permissions to the process, but don't...
8376 		 */
8377 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8378 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8379 			return (0);
8380 		}
8381 
8382 		/*
8383 		 * Need to be in the same zone unless we possess the
8384 		 * privilege to examine all zones.
8385 		 */
8386 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8387 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8388 			return (0);
8389 		}
8390 	}
8391 
8392 	return (1);
8393 }
8394 
8395 /*
8396  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8397  * consists of input pattern strings and an ops-vector to evaluate them.
8398  * This function returns >0 for match, 0 for no match, and <0 for error.
8399  */
8400 static int
8401 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8402     uint32_t priv, uid_t uid, zoneid_t zoneid)
8403 {
8404 	dtrace_provider_t *pvp = prp->dtpr_provider;
8405 	int rv;
8406 
8407 	if (pvp->dtpv_defunct)
8408 		return (0);
8409 
8410 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8411 		return (rv);
8412 
8413 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8414 		return (rv);
8415 
8416 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8417 		return (rv);
8418 
8419 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8420 		return (rv);
8421 
8422 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8423 		return (0);
8424 
8425 	return (rv);
8426 }
8427 
8428 /*
8429  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8430  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8431  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8432  * In addition, all of the recursion cases except for '*' matching have been
8433  * unwound.  For '*', we still implement recursive evaluation, but a depth
8434  * counter is maintained and matching is aborted if we recurse too deep.
8435  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8436  */
8437 static int
8438 dtrace_match_glob(const char *s, const char *p, int depth)
8439 {
8440 	const char *olds;
8441 	char s1, c;
8442 	int gs;
8443 
8444 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8445 		return (-1);
8446 
8447 	if (s == NULL)
8448 		s = ""; /* treat NULL as empty string */
8449 
8450 top:
8451 	olds = s;
8452 	s1 = *s++;
8453 
8454 	if (p == NULL)
8455 		return (0);
8456 
8457 	if ((c = *p++) == '\0')
8458 		return (s1 == '\0');
8459 
8460 	switch (c) {
8461 	case '[': {
8462 		int ok = 0, notflag = 0;
8463 		char lc = '\0';
8464 
8465 		if (s1 == '\0')
8466 			return (0);
8467 
8468 		if (*p == '!') {
8469 			notflag = 1;
8470 			p++;
8471 		}
8472 
8473 		if ((c = *p++) == '\0')
8474 			return (0);
8475 
8476 		do {
8477 			if (c == '-' && lc != '\0' && *p != ']') {
8478 				if ((c = *p++) == '\0')
8479 					return (0);
8480 				if (c == '\\' && (c = *p++) == '\0')
8481 					return (0);
8482 
8483 				if (notflag) {
8484 					if (s1 < lc || s1 > c)
8485 						ok++;
8486 					else
8487 						return (0);
8488 				} else if (lc <= s1 && s1 <= c)
8489 					ok++;
8490 
8491 			} else if (c == '\\' && (c = *p++) == '\0')
8492 				return (0);
8493 
8494 			lc = c; /* save left-hand 'c' for next iteration */
8495 
8496 			if (notflag) {
8497 				if (s1 != c)
8498 					ok++;
8499 				else
8500 					return (0);
8501 			} else if (s1 == c)
8502 				ok++;
8503 
8504 			if ((c = *p++) == '\0')
8505 				return (0);
8506 
8507 		} while (c != ']');
8508 
8509 		if (ok)
8510 			goto top;
8511 
8512 		return (0);
8513 	}
8514 
8515 	case '\\':
8516 		if ((c = *p++) == '\0')
8517 			return (0);
8518 		/*FALLTHRU*/
8519 
8520 	default:
8521 		if (c != s1)
8522 			return (0);
8523 		/*FALLTHRU*/
8524 
8525 	case '?':
8526 		if (s1 != '\0')
8527 			goto top;
8528 		return (0);
8529 
8530 	case '*':
8531 		while (*p == '*')
8532 			p++; /* consecutive *'s are identical to a single one */
8533 
8534 		if (*p == '\0')
8535 			return (1);
8536 
8537 		for (s = olds; *s != '\0'; s++) {
8538 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8539 				return (gs);
8540 		}
8541 
8542 		return (0);
8543 	}
8544 }
8545 
8546 /*ARGSUSED*/
8547 static int
8548 dtrace_match_string(const char *s, const char *p, int depth)
8549 {
8550 	return (s != NULL && strcmp(s, p) == 0);
8551 }
8552 
8553 /*ARGSUSED*/
8554 static int
8555 dtrace_match_nul(const char *s, const char *p, int depth)
8556 {
8557 	return (1); /* always match the empty pattern */
8558 }
8559 
8560 /*ARGSUSED*/
8561 static int
8562 dtrace_match_nonzero(const char *s, const char *p, int depth)
8563 {
8564 	return (s != NULL && s[0] != '\0');
8565 }
8566 
8567 static int
8568 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8569     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8570 {
8571 	dtrace_probe_t template, *probe;
8572 	dtrace_hash_t *hash = NULL;
8573 	int len, best = INT_MAX, nmatched = 0;
8574 	dtrace_id_t i;
8575 
8576 	ASSERT(MUTEX_HELD(&dtrace_lock));
8577 
8578 	/*
8579 	 * If the probe ID is specified in the key, just lookup by ID and
8580 	 * invoke the match callback once if a matching probe is found.
8581 	 */
8582 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8583 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8584 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8585 			(void) (*matched)(probe, arg);
8586 			nmatched++;
8587 		}
8588 		return (nmatched);
8589 	}
8590 
8591 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8592 	template.dtpr_func = (char *)pkp->dtpk_func;
8593 	template.dtpr_name = (char *)pkp->dtpk_name;
8594 
8595 	/*
8596 	 * We want to find the most distinct of the module name, function
8597 	 * name, and name.  So for each one that is not a glob pattern or
8598 	 * empty string, we perform a lookup in the corresponding hash and
8599 	 * use the hash table with the fewest collisions to do our search.
8600 	 */
8601 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8602 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8603 		best = len;
8604 		hash = dtrace_bymod;
8605 	}
8606 
8607 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8608 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8609 		best = len;
8610 		hash = dtrace_byfunc;
8611 	}
8612 
8613 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8614 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8615 		best = len;
8616 		hash = dtrace_byname;
8617 	}
8618 
8619 	/*
8620 	 * If we did not select a hash table, iterate over every probe and
8621 	 * invoke our callback for each one that matches our input probe key.
8622 	 */
8623 	if (hash == NULL) {
8624 		for (i = 0; i < dtrace_nprobes; i++) {
8625 			if ((probe = dtrace_probes[i]) == NULL ||
8626 			    dtrace_match_probe(probe, pkp, priv, uid,
8627 			    zoneid) <= 0)
8628 				continue;
8629 
8630 			nmatched++;
8631 
8632 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8633 				break;
8634 		}
8635 
8636 		return (nmatched);
8637 	}
8638 
8639 	/*
8640 	 * If we selected a hash table, iterate over each probe of the same key
8641 	 * name and invoke the callback for every probe that matches the other
8642 	 * attributes of our input probe key.
8643 	 */
8644 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8645 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8646 
8647 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8648 			continue;
8649 
8650 		nmatched++;
8651 
8652 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8653 			break;
8654 	}
8655 
8656 	return (nmatched);
8657 }
8658 
8659 /*
8660  * Return the function pointer dtrace_probecmp() should use to compare the
8661  * specified pattern with a string.  For NULL or empty patterns, we select
8662  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8663  * For non-empty non-glob strings, we use dtrace_match_string().
8664  */
8665 static dtrace_probekey_f *
8666 dtrace_probekey_func(const char *p)
8667 {
8668 	char c;
8669 
8670 	if (p == NULL || *p == '\0')
8671 		return (&dtrace_match_nul);
8672 
8673 	while ((c = *p++) != '\0') {
8674 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8675 			return (&dtrace_match_glob);
8676 	}
8677 
8678 	return (&dtrace_match_string);
8679 }
8680 
8681 /*
8682  * Build a probe comparison key for use with dtrace_match_probe() from the
8683  * given probe description.  By convention, a null key only matches anchored
8684  * probes: if each field is the empty string, reset dtpk_fmatch to
8685  * dtrace_match_nonzero().
8686  */
8687 static void
8688 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8689 {
8690 	pkp->dtpk_prov = pdp->dtpd_provider;
8691 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8692 
8693 	pkp->dtpk_mod = pdp->dtpd_mod;
8694 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8695 
8696 	pkp->dtpk_func = pdp->dtpd_func;
8697 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8698 
8699 	pkp->dtpk_name = pdp->dtpd_name;
8700 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8701 
8702 	pkp->dtpk_id = pdp->dtpd_id;
8703 
8704 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8705 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8706 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8707 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8708 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8709 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8710 }
8711 
8712 /*
8713  * DTrace Provider-to-Framework API Functions
8714  *
8715  * These functions implement much of the Provider-to-Framework API, as
8716  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8717  * the functions in the API for probe management (found below), and
8718  * dtrace_probe() itself (found above).
8719  */
8720 
8721 /*
8722  * Register the calling provider with the DTrace framework.  This should
8723  * generally be called by DTrace providers in their attach(9E) entry point.
8724  */
8725 int
8726 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8727     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8728 {
8729 	dtrace_provider_t *provider;
8730 
8731 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8732 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8733 		    "arguments", name ? name : "<NULL>");
8734 		return (EINVAL);
8735 	}
8736 
8737 	if (name[0] == '\0' || dtrace_badname(name)) {
8738 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8739 		    "provider name", name);
8740 		return (EINVAL);
8741 	}
8742 
8743 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8744 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8745 	    pops->dtps_destroy == NULL ||
8746 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8747 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8748 		    "provider ops", name);
8749 		return (EINVAL);
8750 	}
8751 
8752 	if (dtrace_badattr(&pap->dtpa_provider) ||
8753 	    dtrace_badattr(&pap->dtpa_mod) ||
8754 	    dtrace_badattr(&pap->dtpa_func) ||
8755 	    dtrace_badattr(&pap->dtpa_name) ||
8756 	    dtrace_badattr(&pap->dtpa_args)) {
8757 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8758 		    "provider attributes", name);
8759 		return (EINVAL);
8760 	}
8761 
8762 	if (priv & ~DTRACE_PRIV_ALL) {
8763 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8764 		    "privilege attributes", name);
8765 		return (EINVAL);
8766 	}
8767 
8768 	if ((priv & DTRACE_PRIV_KERNEL) &&
8769 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8770 	    pops->dtps_usermode == NULL) {
8771 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8772 		    "dtps_usermode() op for given privilege attributes", name);
8773 		return (EINVAL);
8774 	}
8775 
8776 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8777 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8778 	(void) strcpy(provider->dtpv_name, name);
8779 
8780 	provider->dtpv_attr = *pap;
8781 	provider->dtpv_priv.dtpp_flags = priv;
8782 	if (cr != NULL) {
8783 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8784 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8785 	}
8786 	provider->dtpv_pops = *pops;
8787 
8788 	if (pops->dtps_provide == NULL) {
8789 		ASSERT(pops->dtps_provide_module != NULL);
8790 		provider->dtpv_pops.dtps_provide =
8791 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8792 	}
8793 
8794 	if (pops->dtps_provide_module == NULL) {
8795 		ASSERT(pops->dtps_provide != NULL);
8796 		provider->dtpv_pops.dtps_provide_module =
8797 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8798 	}
8799 
8800 	if (pops->dtps_suspend == NULL) {
8801 		ASSERT(pops->dtps_resume == NULL);
8802 		provider->dtpv_pops.dtps_suspend =
8803 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8804 		provider->dtpv_pops.dtps_resume =
8805 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8806 	}
8807 
8808 	provider->dtpv_arg = arg;
8809 	*idp = (dtrace_provider_id_t)provider;
8810 
8811 	if (pops == &dtrace_provider_ops) {
8812 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8813 		ASSERT(MUTEX_HELD(&dtrace_lock));
8814 		ASSERT(dtrace_anon.dta_enabling == NULL);
8815 
8816 		/*
8817 		 * We make sure that the DTrace provider is at the head of
8818 		 * the provider chain.
8819 		 */
8820 		provider->dtpv_next = dtrace_provider;
8821 		dtrace_provider = provider;
8822 		return (0);
8823 	}
8824 
8825 	mutex_enter(&dtrace_provider_lock);
8826 	mutex_enter(&dtrace_lock);
8827 
8828 	/*
8829 	 * If there is at least one provider registered, we'll add this
8830 	 * provider after the first provider.
8831 	 */
8832 	if (dtrace_provider != NULL) {
8833 		provider->dtpv_next = dtrace_provider->dtpv_next;
8834 		dtrace_provider->dtpv_next = provider;
8835 	} else {
8836 		dtrace_provider = provider;
8837 	}
8838 
8839 	if (dtrace_retained != NULL) {
8840 		dtrace_enabling_provide(provider);
8841 
8842 		/*
8843 		 * Now we need to call dtrace_enabling_matchall() -- which
8844 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8845 		 * to drop all of our locks before calling into it...
8846 		 */
8847 		mutex_exit(&dtrace_lock);
8848 		mutex_exit(&dtrace_provider_lock);
8849 		dtrace_enabling_matchall();
8850 
8851 		return (0);
8852 	}
8853 
8854 	mutex_exit(&dtrace_lock);
8855 	mutex_exit(&dtrace_provider_lock);
8856 
8857 	return (0);
8858 }
8859 
8860 /*
8861  * Unregister the specified provider from the DTrace framework.  This should
8862  * generally be called by DTrace providers in their detach(9E) entry point.
8863  */
8864 int
8865 dtrace_unregister(dtrace_provider_id_t id)
8866 {
8867 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8868 	dtrace_provider_t *prev = NULL;
8869 	int i, self = 0, noreap = 0;
8870 	dtrace_probe_t *probe, *first = NULL;
8871 
8872 	if (old->dtpv_pops.dtps_enable ==
8873 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8874 		/*
8875 		 * If DTrace itself is the provider, we're called with locks
8876 		 * already held.
8877 		 */
8878 		ASSERT(old == dtrace_provider);
8879 #ifdef illumos
8880 		ASSERT(dtrace_devi != NULL);
8881 #endif
8882 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8883 		ASSERT(MUTEX_HELD(&dtrace_lock));
8884 		self = 1;
8885 
8886 		if (dtrace_provider->dtpv_next != NULL) {
8887 			/*
8888 			 * There's another provider here; return failure.
8889 			 */
8890 			return (EBUSY);
8891 		}
8892 	} else {
8893 		mutex_enter(&dtrace_provider_lock);
8894 #ifdef illumos
8895 		mutex_enter(&mod_lock);
8896 #endif
8897 		mutex_enter(&dtrace_lock);
8898 	}
8899 
8900 	/*
8901 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8902 	 * probes, we refuse to let providers slither away, unless this
8903 	 * provider has already been explicitly invalidated.
8904 	 */
8905 	if (!old->dtpv_defunct &&
8906 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8907 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8908 		if (!self) {
8909 			mutex_exit(&dtrace_lock);
8910 #ifdef illumos
8911 			mutex_exit(&mod_lock);
8912 #endif
8913 			mutex_exit(&dtrace_provider_lock);
8914 		}
8915 		return (EBUSY);
8916 	}
8917 
8918 	/*
8919 	 * Attempt to destroy the probes associated with this provider.
8920 	 */
8921 	for (i = 0; i < dtrace_nprobes; i++) {
8922 		if ((probe = dtrace_probes[i]) == NULL)
8923 			continue;
8924 
8925 		if (probe->dtpr_provider != old)
8926 			continue;
8927 
8928 		if (probe->dtpr_ecb == NULL)
8929 			continue;
8930 
8931 		/*
8932 		 * If we are trying to unregister a defunct provider, and the
8933 		 * provider was made defunct within the interval dictated by
8934 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8935 		 * attempt to reap our enablings.  To denote that the provider
8936 		 * should reattempt to unregister itself at some point in the
8937 		 * future, we will return a differentiable error code (EAGAIN
8938 		 * instead of EBUSY) in this case.
8939 		 */
8940 		if (dtrace_gethrtime() - old->dtpv_defunct >
8941 		    dtrace_unregister_defunct_reap)
8942 			noreap = 1;
8943 
8944 		if (!self) {
8945 			mutex_exit(&dtrace_lock);
8946 #ifdef illumos
8947 			mutex_exit(&mod_lock);
8948 #endif
8949 			mutex_exit(&dtrace_provider_lock);
8950 		}
8951 
8952 		if (noreap)
8953 			return (EBUSY);
8954 
8955 		(void) taskq_dispatch(dtrace_taskq,
8956 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8957 
8958 		return (EAGAIN);
8959 	}
8960 
8961 	/*
8962 	 * All of the probes for this provider are disabled; we can safely
8963 	 * remove all of them from their hash chains and from the probe array.
8964 	 */
8965 	for (i = 0; i < dtrace_nprobes; i++) {
8966 		if ((probe = dtrace_probes[i]) == NULL)
8967 			continue;
8968 
8969 		if (probe->dtpr_provider != old)
8970 			continue;
8971 
8972 		dtrace_probes[i] = NULL;
8973 
8974 		dtrace_hash_remove(dtrace_bymod, probe);
8975 		dtrace_hash_remove(dtrace_byfunc, probe);
8976 		dtrace_hash_remove(dtrace_byname, probe);
8977 
8978 		if (first == NULL) {
8979 			first = probe;
8980 			probe->dtpr_nextmod = NULL;
8981 		} else {
8982 			probe->dtpr_nextmod = first;
8983 			first = probe;
8984 		}
8985 	}
8986 
8987 	/*
8988 	 * The provider's probes have been removed from the hash chains and
8989 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8990 	 * everyone has cleared out from any probe array processing.
8991 	 */
8992 	dtrace_sync();
8993 
8994 	for (probe = first; probe != NULL; probe = first) {
8995 		first = probe->dtpr_nextmod;
8996 
8997 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8998 		    probe->dtpr_arg);
8999 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9000 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9001 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9002 #ifdef illumos
9003 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
9004 #else
9005 		free_unr(dtrace_arena, probe->dtpr_id);
9006 #endif
9007 		kmem_free(probe, sizeof (dtrace_probe_t));
9008 	}
9009 
9010 	if ((prev = dtrace_provider) == old) {
9011 #ifdef illumos
9012 		ASSERT(self || dtrace_devi == NULL);
9013 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9014 #endif
9015 		dtrace_provider = old->dtpv_next;
9016 	} else {
9017 		while (prev != NULL && prev->dtpv_next != old)
9018 			prev = prev->dtpv_next;
9019 
9020 		if (prev == NULL) {
9021 			panic("attempt to unregister non-existent "
9022 			    "dtrace provider %p\n", (void *)id);
9023 		}
9024 
9025 		prev->dtpv_next = old->dtpv_next;
9026 	}
9027 
9028 	if (!self) {
9029 		mutex_exit(&dtrace_lock);
9030 #ifdef illumos
9031 		mutex_exit(&mod_lock);
9032 #endif
9033 		mutex_exit(&dtrace_provider_lock);
9034 	}
9035 
9036 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9037 	kmem_free(old, sizeof (dtrace_provider_t));
9038 
9039 	return (0);
9040 }
9041 
9042 /*
9043  * Invalidate the specified provider.  All subsequent probe lookups for the
9044  * specified provider will fail, but its probes will not be removed.
9045  */
9046 void
9047 dtrace_invalidate(dtrace_provider_id_t id)
9048 {
9049 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9050 
9051 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9052 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9053 
9054 	mutex_enter(&dtrace_provider_lock);
9055 	mutex_enter(&dtrace_lock);
9056 
9057 	pvp->dtpv_defunct = dtrace_gethrtime();
9058 
9059 	mutex_exit(&dtrace_lock);
9060 	mutex_exit(&dtrace_provider_lock);
9061 }
9062 
9063 /*
9064  * Indicate whether or not DTrace has attached.
9065  */
9066 int
9067 dtrace_attached(void)
9068 {
9069 	/*
9070 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9071 	 * attached.  (It's non-NULL because DTrace is always itself a
9072 	 * provider.)
9073 	 */
9074 	return (dtrace_provider != NULL);
9075 }
9076 
9077 /*
9078  * Remove all the unenabled probes for the given provider.  This function is
9079  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9080  * -- just as many of its associated probes as it can.
9081  */
9082 int
9083 dtrace_condense(dtrace_provider_id_t id)
9084 {
9085 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9086 	int i;
9087 	dtrace_probe_t *probe;
9088 
9089 	/*
9090 	 * Make sure this isn't the dtrace provider itself.
9091 	 */
9092 	ASSERT(prov->dtpv_pops.dtps_enable !=
9093 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9094 
9095 	mutex_enter(&dtrace_provider_lock);
9096 	mutex_enter(&dtrace_lock);
9097 
9098 	/*
9099 	 * Attempt to destroy the probes associated with this provider.
9100 	 */
9101 	for (i = 0; i < dtrace_nprobes; i++) {
9102 		if ((probe = dtrace_probes[i]) == NULL)
9103 			continue;
9104 
9105 		if (probe->dtpr_provider != prov)
9106 			continue;
9107 
9108 		if (probe->dtpr_ecb != NULL)
9109 			continue;
9110 
9111 		dtrace_probes[i] = NULL;
9112 
9113 		dtrace_hash_remove(dtrace_bymod, probe);
9114 		dtrace_hash_remove(dtrace_byfunc, probe);
9115 		dtrace_hash_remove(dtrace_byname, probe);
9116 
9117 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9118 		    probe->dtpr_arg);
9119 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9120 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9121 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9122 		kmem_free(probe, sizeof (dtrace_probe_t));
9123 #ifdef illumos
9124 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9125 #else
9126 		free_unr(dtrace_arena, i + 1);
9127 #endif
9128 	}
9129 
9130 	mutex_exit(&dtrace_lock);
9131 	mutex_exit(&dtrace_provider_lock);
9132 
9133 	return (0);
9134 }
9135 
9136 /*
9137  * DTrace Probe Management Functions
9138  *
9139  * The functions in this section perform the DTrace probe management,
9140  * including functions to create probes, look-up probes, and call into the
9141  * providers to request that probes be provided.  Some of these functions are
9142  * in the Provider-to-Framework API; these functions can be identified by the
9143  * fact that they are not declared "static".
9144  */
9145 
9146 /*
9147  * Create a probe with the specified module name, function name, and name.
9148  */
9149 dtrace_id_t
9150 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9151     const char *func, const char *name, int aframes, void *arg)
9152 {
9153 	dtrace_probe_t *probe, **probes;
9154 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9155 	dtrace_id_t id;
9156 
9157 	if (provider == dtrace_provider) {
9158 		ASSERT(MUTEX_HELD(&dtrace_lock));
9159 	} else {
9160 		mutex_enter(&dtrace_lock);
9161 	}
9162 
9163 #ifdef illumos
9164 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9165 	    VM_BESTFIT | VM_SLEEP);
9166 #else
9167 	id = alloc_unr(dtrace_arena);
9168 #endif
9169 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9170 
9171 	probe->dtpr_id = id;
9172 	probe->dtpr_gen = dtrace_probegen++;
9173 	probe->dtpr_mod = dtrace_strdup(mod);
9174 	probe->dtpr_func = dtrace_strdup(func);
9175 	probe->dtpr_name = dtrace_strdup(name);
9176 	probe->dtpr_arg = arg;
9177 	probe->dtpr_aframes = aframes;
9178 	probe->dtpr_provider = provider;
9179 
9180 	dtrace_hash_add(dtrace_bymod, probe);
9181 	dtrace_hash_add(dtrace_byfunc, probe);
9182 	dtrace_hash_add(dtrace_byname, probe);
9183 
9184 	if (id - 1 >= dtrace_nprobes) {
9185 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9186 		size_t nsize = osize << 1;
9187 
9188 		if (nsize == 0) {
9189 			ASSERT(osize == 0);
9190 			ASSERT(dtrace_probes == NULL);
9191 			nsize = sizeof (dtrace_probe_t *);
9192 		}
9193 
9194 		probes = kmem_zalloc(nsize, KM_SLEEP);
9195 
9196 		if (dtrace_probes == NULL) {
9197 			ASSERT(osize == 0);
9198 			dtrace_probes = probes;
9199 			dtrace_nprobes = 1;
9200 		} else {
9201 			dtrace_probe_t **oprobes = dtrace_probes;
9202 
9203 			bcopy(oprobes, probes, osize);
9204 			dtrace_membar_producer();
9205 			dtrace_probes = probes;
9206 
9207 			dtrace_sync();
9208 
9209 			/*
9210 			 * All CPUs are now seeing the new probes array; we can
9211 			 * safely free the old array.
9212 			 */
9213 			kmem_free(oprobes, osize);
9214 			dtrace_nprobes <<= 1;
9215 		}
9216 
9217 		ASSERT(id - 1 < dtrace_nprobes);
9218 	}
9219 
9220 	ASSERT(dtrace_probes[id - 1] == NULL);
9221 	dtrace_probes[id - 1] = probe;
9222 
9223 	if (provider != dtrace_provider)
9224 		mutex_exit(&dtrace_lock);
9225 
9226 	return (id);
9227 }
9228 
9229 static dtrace_probe_t *
9230 dtrace_probe_lookup_id(dtrace_id_t id)
9231 {
9232 	ASSERT(MUTEX_HELD(&dtrace_lock));
9233 
9234 	if (id == 0 || id > dtrace_nprobes)
9235 		return (NULL);
9236 
9237 	return (dtrace_probes[id - 1]);
9238 }
9239 
9240 static int
9241 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9242 {
9243 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9244 
9245 	return (DTRACE_MATCH_DONE);
9246 }
9247 
9248 /*
9249  * Look up a probe based on provider and one or more of module name, function
9250  * name and probe name.
9251  */
9252 dtrace_id_t
9253 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9254     char *func, char *name)
9255 {
9256 	dtrace_probekey_t pkey;
9257 	dtrace_id_t id;
9258 	int match;
9259 
9260 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9261 	pkey.dtpk_pmatch = &dtrace_match_string;
9262 	pkey.dtpk_mod = mod;
9263 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9264 	pkey.dtpk_func = func;
9265 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9266 	pkey.dtpk_name = name;
9267 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9268 	pkey.dtpk_id = DTRACE_IDNONE;
9269 
9270 	mutex_enter(&dtrace_lock);
9271 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9272 	    dtrace_probe_lookup_match, &id);
9273 	mutex_exit(&dtrace_lock);
9274 
9275 	ASSERT(match == 1 || match == 0);
9276 	return (match ? id : 0);
9277 }
9278 
9279 /*
9280  * Returns the probe argument associated with the specified probe.
9281  */
9282 void *
9283 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9284 {
9285 	dtrace_probe_t *probe;
9286 	void *rval = NULL;
9287 
9288 	mutex_enter(&dtrace_lock);
9289 
9290 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9291 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9292 		rval = probe->dtpr_arg;
9293 
9294 	mutex_exit(&dtrace_lock);
9295 
9296 	return (rval);
9297 }
9298 
9299 /*
9300  * Copy a probe into a probe description.
9301  */
9302 static void
9303 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9304 {
9305 	bzero(pdp, sizeof (dtrace_probedesc_t));
9306 	pdp->dtpd_id = prp->dtpr_id;
9307 
9308 	(void) strncpy(pdp->dtpd_provider,
9309 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9310 
9311 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9312 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9313 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9314 }
9315 
9316 /*
9317  * Called to indicate that a probe -- or probes -- should be provided by a
9318  * specfied provider.  If the specified description is NULL, the provider will
9319  * be told to provide all of its probes.  (This is done whenever a new
9320  * consumer comes along, or whenever a retained enabling is to be matched.) If
9321  * the specified description is non-NULL, the provider is given the
9322  * opportunity to dynamically provide the specified probe, allowing providers
9323  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9324  * probes.)  If the provider is NULL, the operations will be applied to all
9325  * providers; if the provider is non-NULL the operations will only be applied
9326  * to the specified provider.  The dtrace_provider_lock must be held, and the
9327  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9328  * will need to grab the dtrace_lock when it reenters the framework through
9329  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9330  */
9331 static void
9332 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9333 {
9334 #ifdef illumos
9335 	modctl_t *ctl;
9336 #endif
9337 	int all = 0;
9338 
9339 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9340 
9341 	if (prv == NULL) {
9342 		all = 1;
9343 		prv = dtrace_provider;
9344 	}
9345 
9346 	do {
9347 		/*
9348 		 * First, call the blanket provide operation.
9349 		 */
9350 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9351 
9352 #ifdef illumos
9353 		/*
9354 		 * Now call the per-module provide operation.  We will grab
9355 		 * mod_lock to prevent the list from being modified.  Note
9356 		 * that this also prevents the mod_busy bits from changing.
9357 		 * (mod_busy can only be changed with mod_lock held.)
9358 		 */
9359 		mutex_enter(&mod_lock);
9360 
9361 		ctl = &modules;
9362 		do {
9363 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9364 				continue;
9365 
9366 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9367 
9368 		} while ((ctl = ctl->mod_next) != &modules);
9369 
9370 		mutex_exit(&mod_lock);
9371 #endif
9372 	} while (all && (prv = prv->dtpv_next) != NULL);
9373 }
9374 
9375 #ifdef illumos
9376 /*
9377  * Iterate over each probe, and call the Framework-to-Provider API function
9378  * denoted by offs.
9379  */
9380 static void
9381 dtrace_probe_foreach(uintptr_t offs)
9382 {
9383 	dtrace_provider_t *prov;
9384 	void (*func)(void *, dtrace_id_t, void *);
9385 	dtrace_probe_t *probe;
9386 	dtrace_icookie_t cookie;
9387 	int i;
9388 
9389 	/*
9390 	 * We disable interrupts to walk through the probe array.  This is
9391 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9392 	 * won't see stale data.
9393 	 */
9394 	cookie = dtrace_interrupt_disable();
9395 
9396 	for (i = 0; i < dtrace_nprobes; i++) {
9397 		if ((probe = dtrace_probes[i]) == NULL)
9398 			continue;
9399 
9400 		if (probe->dtpr_ecb == NULL) {
9401 			/*
9402 			 * This probe isn't enabled -- don't call the function.
9403 			 */
9404 			continue;
9405 		}
9406 
9407 		prov = probe->dtpr_provider;
9408 		func = *((void(**)(void *, dtrace_id_t, void *))
9409 		    ((uintptr_t)&prov->dtpv_pops + offs));
9410 
9411 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9412 	}
9413 
9414 	dtrace_interrupt_enable(cookie);
9415 }
9416 #endif
9417 
9418 static int
9419 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9420 {
9421 	dtrace_probekey_t pkey;
9422 	uint32_t priv;
9423 	uid_t uid;
9424 	zoneid_t zoneid;
9425 
9426 	ASSERT(MUTEX_HELD(&dtrace_lock));
9427 	dtrace_ecb_create_cache = NULL;
9428 
9429 	if (desc == NULL) {
9430 		/*
9431 		 * If we're passed a NULL description, we're being asked to
9432 		 * create an ECB with a NULL probe.
9433 		 */
9434 		(void) dtrace_ecb_create_enable(NULL, enab);
9435 		return (0);
9436 	}
9437 
9438 	dtrace_probekey(desc, &pkey);
9439 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9440 	    &priv, &uid, &zoneid);
9441 
9442 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9443 	    enab));
9444 }
9445 
9446 /*
9447  * DTrace Helper Provider Functions
9448  */
9449 static void
9450 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9451 {
9452 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9453 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9454 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9455 }
9456 
9457 static void
9458 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9459     const dof_provider_t *dofprov, char *strtab)
9460 {
9461 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9462 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9463 	    dofprov->dofpv_provattr);
9464 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9465 	    dofprov->dofpv_modattr);
9466 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9467 	    dofprov->dofpv_funcattr);
9468 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9469 	    dofprov->dofpv_nameattr);
9470 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9471 	    dofprov->dofpv_argsattr);
9472 }
9473 
9474 static void
9475 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9476 {
9477 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9478 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9479 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9480 	dof_provider_t *provider;
9481 	dof_probe_t *probe;
9482 	uint32_t *off, *enoff;
9483 	uint8_t *arg;
9484 	char *strtab;
9485 	uint_t i, nprobes;
9486 	dtrace_helper_provdesc_t dhpv;
9487 	dtrace_helper_probedesc_t dhpb;
9488 	dtrace_meta_t *meta = dtrace_meta_pid;
9489 	dtrace_mops_t *mops = &meta->dtm_mops;
9490 	void *parg;
9491 
9492 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9493 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9494 	    provider->dofpv_strtab * dof->dofh_secsize);
9495 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9496 	    provider->dofpv_probes * dof->dofh_secsize);
9497 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9498 	    provider->dofpv_prargs * dof->dofh_secsize);
9499 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9500 	    provider->dofpv_proffs * dof->dofh_secsize);
9501 
9502 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9503 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9504 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9505 	enoff = NULL;
9506 
9507 	/*
9508 	 * See dtrace_helper_provider_validate().
9509 	 */
9510 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9511 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9512 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9513 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9514 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9515 	}
9516 
9517 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9518 
9519 	/*
9520 	 * Create the provider.
9521 	 */
9522 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9523 
9524 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9525 		return;
9526 
9527 	meta->dtm_count++;
9528 
9529 	/*
9530 	 * Create the probes.
9531 	 */
9532 	for (i = 0; i < nprobes; i++) {
9533 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9534 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9535 
9536 		/* See the check in dtrace_helper_provider_validate(). */
9537 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9538 			continue;
9539 
9540 		dhpb.dthpb_mod = dhp->dofhp_mod;
9541 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9542 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9543 		dhpb.dthpb_base = probe->dofpr_addr;
9544 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9545 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9546 		if (enoff != NULL) {
9547 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9548 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9549 		} else {
9550 			dhpb.dthpb_enoffs = NULL;
9551 			dhpb.dthpb_nenoffs = 0;
9552 		}
9553 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9554 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9555 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9556 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9557 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9558 
9559 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9560 	}
9561 }
9562 
9563 static void
9564 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9565 {
9566 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9567 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9568 	int i;
9569 
9570 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9571 
9572 	for (i = 0; i < dof->dofh_secnum; i++) {
9573 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9574 		    dof->dofh_secoff + i * dof->dofh_secsize);
9575 
9576 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9577 			continue;
9578 
9579 		dtrace_helper_provide_one(dhp, sec, pid);
9580 	}
9581 
9582 	/*
9583 	 * We may have just created probes, so we must now rematch against
9584 	 * any retained enablings.  Note that this call will acquire both
9585 	 * cpu_lock and dtrace_lock; the fact that we are holding
9586 	 * dtrace_meta_lock now is what defines the ordering with respect to
9587 	 * these three locks.
9588 	 */
9589 	dtrace_enabling_matchall();
9590 }
9591 
9592 static void
9593 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9594 {
9595 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9596 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9597 	dof_sec_t *str_sec;
9598 	dof_provider_t *provider;
9599 	char *strtab;
9600 	dtrace_helper_provdesc_t dhpv;
9601 	dtrace_meta_t *meta = dtrace_meta_pid;
9602 	dtrace_mops_t *mops = &meta->dtm_mops;
9603 
9604 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9605 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9606 	    provider->dofpv_strtab * dof->dofh_secsize);
9607 
9608 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9609 
9610 	/*
9611 	 * Create the provider.
9612 	 */
9613 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9614 
9615 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9616 
9617 	meta->dtm_count--;
9618 }
9619 
9620 static void
9621 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9622 {
9623 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9624 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9625 	int i;
9626 
9627 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9628 
9629 	for (i = 0; i < dof->dofh_secnum; i++) {
9630 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9631 		    dof->dofh_secoff + i * dof->dofh_secsize);
9632 
9633 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9634 			continue;
9635 
9636 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9637 	}
9638 }
9639 
9640 /*
9641  * DTrace Meta Provider-to-Framework API Functions
9642  *
9643  * These functions implement the Meta Provider-to-Framework API, as described
9644  * in <sys/dtrace.h>.
9645  */
9646 int
9647 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9648     dtrace_meta_provider_id_t *idp)
9649 {
9650 	dtrace_meta_t *meta;
9651 	dtrace_helpers_t *help, *next;
9652 	int i;
9653 
9654 	*idp = DTRACE_METAPROVNONE;
9655 
9656 	/*
9657 	 * We strictly don't need the name, but we hold onto it for
9658 	 * debuggability. All hail error queues!
9659 	 */
9660 	if (name == NULL) {
9661 		cmn_err(CE_WARN, "failed to register meta-provider: "
9662 		    "invalid name");
9663 		return (EINVAL);
9664 	}
9665 
9666 	if (mops == NULL ||
9667 	    mops->dtms_create_probe == NULL ||
9668 	    mops->dtms_provide_pid == NULL ||
9669 	    mops->dtms_remove_pid == NULL) {
9670 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9671 		    "invalid ops", name);
9672 		return (EINVAL);
9673 	}
9674 
9675 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9676 	meta->dtm_mops = *mops;
9677 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9678 	(void) strcpy(meta->dtm_name, name);
9679 	meta->dtm_arg = arg;
9680 
9681 	mutex_enter(&dtrace_meta_lock);
9682 	mutex_enter(&dtrace_lock);
9683 
9684 	if (dtrace_meta_pid != NULL) {
9685 		mutex_exit(&dtrace_lock);
9686 		mutex_exit(&dtrace_meta_lock);
9687 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9688 		    "user-land meta-provider exists", name);
9689 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9690 		kmem_free(meta, sizeof (dtrace_meta_t));
9691 		return (EINVAL);
9692 	}
9693 
9694 	dtrace_meta_pid = meta;
9695 	*idp = (dtrace_meta_provider_id_t)meta;
9696 
9697 	/*
9698 	 * If there are providers and probes ready to go, pass them
9699 	 * off to the new meta provider now.
9700 	 */
9701 
9702 	help = dtrace_deferred_pid;
9703 	dtrace_deferred_pid = NULL;
9704 
9705 	mutex_exit(&dtrace_lock);
9706 
9707 	while (help != NULL) {
9708 		for (i = 0; i < help->dthps_nprovs; i++) {
9709 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9710 			    help->dthps_pid);
9711 		}
9712 
9713 		next = help->dthps_next;
9714 		help->dthps_next = NULL;
9715 		help->dthps_prev = NULL;
9716 		help->dthps_deferred = 0;
9717 		help = next;
9718 	}
9719 
9720 	mutex_exit(&dtrace_meta_lock);
9721 
9722 	return (0);
9723 }
9724 
9725 int
9726 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9727 {
9728 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9729 
9730 	mutex_enter(&dtrace_meta_lock);
9731 	mutex_enter(&dtrace_lock);
9732 
9733 	if (old == dtrace_meta_pid) {
9734 		pp = &dtrace_meta_pid;
9735 	} else {
9736 		panic("attempt to unregister non-existent "
9737 		    "dtrace meta-provider %p\n", (void *)old);
9738 	}
9739 
9740 	if (old->dtm_count != 0) {
9741 		mutex_exit(&dtrace_lock);
9742 		mutex_exit(&dtrace_meta_lock);
9743 		return (EBUSY);
9744 	}
9745 
9746 	*pp = NULL;
9747 
9748 	mutex_exit(&dtrace_lock);
9749 	mutex_exit(&dtrace_meta_lock);
9750 
9751 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9752 	kmem_free(old, sizeof (dtrace_meta_t));
9753 
9754 	return (0);
9755 }
9756 
9757 
9758 /*
9759  * DTrace DIF Object Functions
9760  */
9761 static int
9762 dtrace_difo_err(uint_t pc, const char *format, ...)
9763 {
9764 	if (dtrace_err_verbose) {
9765 		va_list alist;
9766 
9767 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9768 		va_start(alist, format);
9769 		(void) vuprintf(format, alist);
9770 		va_end(alist);
9771 	}
9772 
9773 #ifdef DTRACE_ERRDEBUG
9774 	dtrace_errdebug(format);
9775 #endif
9776 	return (1);
9777 }
9778 
9779 /*
9780  * Validate a DTrace DIF object by checking the IR instructions.  The following
9781  * rules are currently enforced by dtrace_difo_validate():
9782  *
9783  * 1. Each instruction must have a valid opcode
9784  * 2. Each register, string, variable, or subroutine reference must be valid
9785  * 3. No instruction can modify register %r0 (must be zero)
9786  * 4. All instruction reserved bits must be set to zero
9787  * 5. The last instruction must be a "ret" instruction
9788  * 6. All branch targets must reference a valid instruction _after_ the branch
9789  */
9790 static int
9791 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9792     cred_t *cr)
9793 {
9794 	int err = 0, i;
9795 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9796 	int kcheckload;
9797 	uint_t pc;
9798 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9799 
9800 	kcheckload = cr == NULL ||
9801 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9802 
9803 	dp->dtdo_destructive = 0;
9804 
9805 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9806 		dif_instr_t instr = dp->dtdo_buf[pc];
9807 
9808 		uint_t r1 = DIF_INSTR_R1(instr);
9809 		uint_t r2 = DIF_INSTR_R2(instr);
9810 		uint_t rd = DIF_INSTR_RD(instr);
9811 		uint_t rs = DIF_INSTR_RS(instr);
9812 		uint_t label = DIF_INSTR_LABEL(instr);
9813 		uint_t v = DIF_INSTR_VAR(instr);
9814 		uint_t subr = DIF_INSTR_SUBR(instr);
9815 		uint_t type = DIF_INSTR_TYPE(instr);
9816 		uint_t op = DIF_INSTR_OP(instr);
9817 
9818 		switch (op) {
9819 		case DIF_OP_OR:
9820 		case DIF_OP_XOR:
9821 		case DIF_OP_AND:
9822 		case DIF_OP_SLL:
9823 		case DIF_OP_SRL:
9824 		case DIF_OP_SRA:
9825 		case DIF_OP_SUB:
9826 		case DIF_OP_ADD:
9827 		case DIF_OP_MUL:
9828 		case DIF_OP_SDIV:
9829 		case DIF_OP_UDIV:
9830 		case DIF_OP_SREM:
9831 		case DIF_OP_UREM:
9832 		case DIF_OP_COPYS:
9833 			if (r1 >= nregs)
9834 				err += efunc(pc, "invalid register %u\n", r1);
9835 			if (r2 >= nregs)
9836 				err += efunc(pc, "invalid register %u\n", r2);
9837 			if (rd >= nregs)
9838 				err += efunc(pc, "invalid register %u\n", rd);
9839 			if (rd == 0)
9840 				err += efunc(pc, "cannot write to %%r0\n");
9841 			break;
9842 		case DIF_OP_NOT:
9843 		case DIF_OP_MOV:
9844 		case DIF_OP_ALLOCS:
9845 			if (r1 >= nregs)
9846 				err += efunc(pc, "invalid register %u\n", r1);
9847 			if (r2 != 0)
9848 				err += efunc(pc, "non-zero reserved bits\n");
9849 			if (rd >= nregs)
9850 				err += efunc(pc, "invalid register %u\n", rd);
9851 			if (rd == 0)
9852 				err += efunc(pc, "cannot write to %%r0\n");
9853 			break;
9854 		case DIF_OP_LDSB:
9855 		case DIF_OP_LDSH:
9856 		case DIF_OP_LDSW:
9857 		case DIF_OP_LDUB:
9858 		case DIF_OP_LDUH:
9859 		case DIF_OP_LDUW:
9860 		case DIF_OP_LDX:
9861 			if (r1 >= nregs)
9862 				err += efunc(pc, "invalid register %u\n", r1);
9863 			if (r2 != 0)
9864 				err += efunc(pc, "non-zero reserved bits\n");
9865 			if (rd >= nregs)
9866 				err += efunc(pc, "invalid register %u\n", rd);
9867 			if (rd == 0)
9868 				err += efunc(pc, "cannot write to %%r0\n");
9869 			if (kcheckload)
9870 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9871 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9872 			break;
9873 		case DIF_OP_RLDSB:
9874 		case DIF_OP_RLDSH:
9875 		case DIF_OP_RLDSW:
9876 		case DIF_OP_RLDUB:
9877 		case DIF_OP_RLDUH:
9878 		case DIF_OP_RLDUW:
9879 		case DIF_OP_RLDX:
9880 			if (r1 >= nregs)
9881 				err += efunc(pc, "invalid register %u\n", r1);
9882 			if (r2 != 0)
9883 				err += efunc(pc, "non-zero reserved bits\n");
9884 			if (rd >= nregs)
9885 				err += efunc(pc, "invalid register %u\n", rd);
9886 			if (rd == 0)
9887 				err += efunc(pc, "cannot write to %%r0\n");
9888 			break;
9889 		case DIF_OP_ULDSB:
9890 		case DIF_OP_ULDSH:
9891 		case DIF_OP_ULDSW:
9892 		case DIF_OP_ULDUB:
9893 		case DIF_OP_ULDUH:
9894 		case DIF_OP_ULDUW:
9895 		case DIF_OP_ULDX:
9896 			if (r1 >= nregs)
9897 				err += efunc(pc, "invalid register %u\n", r1);
9898 			if (r2 != 0)
9899 				err += efunc(pc, "non-zero reserved bits\n");
9900 			if (rd >= nregs)
9901 				err += efunc(pc, "invalid register %u\n", rd);
9902 			if (rd == 0)
9903 				err += efunc(pc, "cannot write to %%r0\n");
9904 			break;
9905 		case DIF_OP_STB:
9906 		case DIF_OP_STH:
9907 		case DIF_OP_STW:
9908 		case DIF_OP_STX:
9909 			if (r1 >= nregs)
9910 				err += efunc(pc, "invalid register %u\n", r1);
9911 			if (r2 != 0)
9912 				err += efunc(pc, "non-zero reserved bits\n");
9913 			if (rd >= nregs)
9914 				err += efunc(pc, "invalid register %u\n", rd);
9915 			if (rd == 0)
9916 				err += efunc(pc, "cannot write to 0 address\n");
9917 			break;
9918 		case DIF_OP_CMP:
9919 		case DIF_OP_SCMP:
9920 			if (r1 >= nregs)
9921 				err += efunc(pc, "invalid register %u\n", r1);
9922 			if (r2 >= nregs)
9923 				err += efunc(pc, "invalid register %u\n", r2);
9924 			if (rd != 0)
9925 				err += efunc(pc, "non-zero reserved bits\n");
9926 			break;
9927 		case DIF_OP_TST:
9928 			if (r1 >= nregs)
9929 				err += efunc(pc, "invalid register %u\n", r1);
9930 			if (r2 != 0 || rd != 0)
9931 				err += efunc(pc, "non-zero reserved bits\n");
9932 			break;
9933 		case DIF_OP_BA:
9934 		case DIF_OP_BE:
9935 		case DIF_OP_BNE:
9936 		case DIF_OP_BG:
9937 		case DIF_OP_BGU:
9938 		case DIF_OP_BGE:
9939 		case DIF_OP_BGEU:
9940 		case DIF_OP_BL:
9941 		case DIF_OP_BLU:
9942 		case DIF_OP_BLE:
9943 		case DIF_OP_BLEU:
9944 			if (label >= dp->dtdo_len) {
9945 				err += efunc(pc, "invalid branch target %u\n",
9946 				    label);
9947 			}
9948 			if (label <= pc) {
9949 				err += efunc(pc, "backward branch to %u\n",
9950 				    label);
9951 			}
9952 			break;
9953 		case DIF_OP_RET:
9954 			if (r1 != 0 || r2 != 0)
9955 				err += efunc(pc, "non-zero reserved bits\n");
9956 			if (rd >= nregs)
9957 				err += efunc(pc, "invalid register %u\n", rd);
9958 			break;
9959 		case DIF_OP_NOP:
9960 		case DIF_OP_POPTS:
9961 		case DIF_OP_FLUSHTS:
9962 			if (r1 != 0 || r2 != 0 || rd != 0)
9963 				err += efunc(pc, "non-zero reserved bits\n");
9964 			break;
9965 		case DIF_OP_SETX:
9966 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9967 				err += efunc(pc, "invalid integer ref %u\n",
9968 				    DIF_INSTR_INTEGER(instr));
9969 			}
9970 			if (rd >= nregs)
9971 				err += efunc(pc, "invalid register %u\n", rd);
9972 			if (rd == 0)
9973 				err += efunc(pc, "cannot write to %%r0\n");
9974 			break;
9975 		case DIF_OP_SETS:
9976 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9977 				err += efunc(pc, "invalid string ref %u\n",
9978 				    DIF_INSTR_STRING(instr));
9979 			}
9980 			if (rd >= nregs)
9981 				err += efunc(pc, "invalid register %u\n", rd);
9982 			if (rd == 0)
9983 				err += efunc(pc, "cannot write to %%r0\n");
9984 			break;
9985 		case DIF_OP_LDGA:
9986 		case DIF_OP_LDTA:
9987 			if (r1 > DIF_VAR_ARRAY_MAX)
9988 				err += efunc(pc, "invalid array %u\n", r1);
9989 			if (r2 >= nregs)
9990 				err += efunc(pc, "invalid register %u\n", r2);
9991 			if (rd >= nregs)
9992 				err += efunc(pc, "invalid register %u\n", rd);
9993 			if (rd == 0)
9994 				err += efunc(pc, "cannot write to %%r0\n");
9995 			break;
9996 		case DIF_OP_LDGS:
9997 		case DIF_OP_LDTS:
9998 		case DIF_OP_LDLS:
9999 		case DIF_OP_LDGAA:
10000 		case DIF_OP_LDTAA:
10001 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
10002 				err += efunc(pc, "invalid variable %u\n", v);
10003 			if (rd >= nregs)
10004 				err += efunc(pc, "invalid register %u\n", rd);
10005 			if (rd == 0)
10006 				err += efunc(pc, "cannot write to %%r0\n");
10007 			break;
10008 		case DIF_OP_STGS:
10009 		case DIF_OP_STTS:
10010 		case DIF_OP_STLS:
10011 		case DIF_OP_STGAA:
10012 		case DIF_OP_STTAA:
10013 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
10014 				err += efunc(pc, "invalid variable %u\n", v);
10015 			if (rs >= nregs)
10016 				err += efunc(pc, "invalid register %u\n", rd);
10017 			break;
10018 		case DIF_OP_CALL:
10019 			if (subr > DIF_SUBR_MAX)
10020 				err += efunc(pc, "invalid subr %u\n", subr);
10021 			if (rd >= nregs)
10022 				err += efunc(pc, "invalid register %u\n", rd);
10023 			if (rd == 0)
10024 				err += efunc(pc, "cannot write to %%r0\n");
10025 
10026 			if (subr == DIF_SUBR_COPYOUT ||
10027 			    subr == DIF_SUBR_COPYOUTSTR) {
10028 				dp->dtdo_destructive = 1;
10029 			}
10030 
10031 			if (subr == DIF_SUBR_GETF) {
10032 #ifdef __FreeBSD__
10033 				err += efunc(pc, "getf() not supported");
10034 #else
10035 				/*
10036 				 * If we have a getf() we need to record that
10037 				 * in our state.  Note that our state can be
10038 				 * NULL if this is a helper -- but in that
10039 				 * case, the call to getf() is itself illegal,
10040 				 * and will be caught (slightly later) when
10041 				 * the helper is validated.
10042 				 */
10043 				if (vstate->dtvs_state != NULL)
10044 					vstate->dtvs_state->dts_getf++;
10045 #endif
10046 			}
10047 
10048 			break;
10049 		case DIF_OP_PUSHTR:
10050 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10051 				err += efunc(pc, "invalid ref type %u\n", type);
10052 			if (r2 >= nregs)
10053 				err += efunc(pc, "invalid register %u\n", r2);
10054 			if (rs >= nregs)
10055 				err += efunc(pc, "invalid register %u\n", rs);
10056 			break;
10057 		case DIF_OP_PUSHTV:
10058 			if (type != DIF_TYPE_CTF)
10059 				err += efunc(pc, "invalid val type %u\n", type);
10060 			if (r2 >= nregs)
10061 				err += efunc(pc, "invalid register %u\n", r2);
10062 			if (rs >= nregs)
10063 				err += efunc(pc, "invalid register %u\n", rs);
10064 			break;
10065 		default:
10066 			err += efunc(pc, "invalid opcode %u\n",
10067 			    DIF_INSTR_OP(instr));
10068 		}
10069 	}
10070 
10071 	if (dp->dtdo_len != 0 &&
10072 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10073 		err += efunc(dp->dtdo_len - 1,
10074 		    "expected 'ret' as last DIF instruction\n");
10075 	}
10076 
10077 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10078 		/*
10079 		 * If we're not returning by reference, the size must be either
10080 		 * 0 or the size of one of the base types.
10081 		 */
10082 		switch (dp->dtdo_rtype.dtdt_size) {
10083 		case 0:
10084 		case sizeof (uint8_t):
10085 		case sizeof (uint16_t):
10086 		case sizeof (uint32_t):
10087 		case sizeof (uint64_t):
10088 			break;
10089 
10090 		default:
10091 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10092 		}
10093 	}
10094 
10095 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10096 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10097 		dtrace_diftype_t *vt, *et;
10098 		uint_t id, ndx;
10099 
10100 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10101 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10102 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10103 			err += efunc(i, "unrecognized variable scope %d\n",
10104 			    v->dtdv_scope);
10105 			break;
10106 		}
10107 
10108 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10109 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10110 			err += efunc(i, "unrecognized variable type %d\n",
10111 			    v->dtdv_kind);
10112 			break;
10113 		}
10114 
10115 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10116 			err += efunc(i, "%d exceeds variable id limit\n", id);
10117 			break;
10118 		}
10119 
10120 		if (id < DIF_VAR_OTHER_UBASE)
10121 			continue;
10122 
10123 		/*
10124 		 * For user-defined variables, we need to check that this
10125 		 * definition is identical to any previous definition that we
10126 		 * encountered.
10127 		 */
10128 		ndx = id - DIF_VAR_OTHER_UBASE;
10129 
10130 		switch (v->dtdv_scope) {
10131 		case DIFV_SCOPE_GLOBAL:
10132 			if (maxglobal == -1 || ndx > maxglobal)
10133 				maxglobal = ndx;
10134 
10135 			if (ndx < vstate->dtvs_nglobals) {
10136 				dtrace_statvar_t *svar;
10137 
10138 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10139 					existing = &svar->dtsv_var;
10140 			}
10141 
10142 			break;
10143 
10144 		case DIFV_SCOPE_THREAD:
10145 			if (maxtlocal == -1 || ndx > maxtlocal)
10146 				maxtlocal = ndx;
10147 
10148 			if (ndx < vstate->dtvs_ntlocals)
10149 				existing = &vstate->dtvs_tlocals[ndx];
10150 			break;
10151 
10152 		case DIFV_SCOPE_LOCAL:
10153 			if (maxlocal == -1 || ndx > maxlocal)
10154 				maxlocal = ndx;
10155 
10156 			if (ndx < vstate->dtvs_nlocals) {
10157 				dtrace_statvar_t *svar;
10158 
10159 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10160 					existing = &svar->dtsv_var;
10161 			}
10162 
10163 			break;
10164 		}
10165 
10166 		vt = &v->dtdv_type;
10167 
10168 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10169 			if (vt->dtdt_size == 0) {
10170 				err += efunc(i, "zero-sized variable\n");
10171 				break;
10172 			}
10173 
10174 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10175 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10176 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10177 				err += efunc(i, "oversized by-ref static\n");
10178 				break;
10179 			}
10180 		}
10181 
10182 		if (existing == NULL || existing->dtdv_id == 0)
10183 			continue;
10184 
10185 		ASSERT(existing->dtdv_id == v->dtdv_id);
10186 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10187 
10188 		if (existing->dtdv_kind != v->dtdv_kind)
10189 			err += efunc(i, "%d changed variable kind\n", id);
10190 
10191 		et = &existing->dtdv_type;
10192 
10193 		if (vt->dtdt_flags != et->dtdt_flags) {
10194 			err += efunc(i, "%d changed variable type flags\n", id);
10195 			break;
10196 		}
10197 
10198 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10199 			err += efunc(i, "%d changed variable type size\n", id);
10200 			break;
10201 		}
10202 	}
10203 
10204 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10205 		dif_instr_t instr = dp->dtdo_buf[pc];
10206 
10207 		uint_t v = DIF_INSTR_VAR(instr);
10208 		uint_t op = DIF_INSTR_OP(instr);
10209 
10210 		switch (op) {
10211 		case DIF_OP_LDGS:
10212 		case DIF_OP_LDGAA:
10213 		case DIF_OP_STGS:
10214 		case DIF_OP_STGAA:
10215 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10216 				err += efunc(pc, "invalid variable %u\n", v);
10217 			break;
10218 		case DIF_OP_LDTS:
10219 		case DIF_OP_LDTAA:
10220 		case DIF_OP_STTS:
10221 		case DIF_OP_STTAA:
10222 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10223 				err += efunc(pc, "invalid variable %u\n", v);
10224 			break;
10225 		case DIF_OP_LDLS:
10226 		case DIF_OP_STLS:
10227 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10228 				err += efunc(pc, "invalid variable %u\n", v);
10229 			break;
10230 		default:
10231 			break;
10232 		}
10233 	}
10234 
10235 	return (err);
10236 }
10237 
10238 /*
10239  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10240  * are much more constrained than normal DIFOs.  Specifically, they may
10241  * not:
10242  *
10243  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10244  *    miscellaneous string routines
10245  * 2. Access DTrace variables other than the args[] array, and the
10246  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10247  * 3. Have thread-local variables.
10248  * 4. Have dynamic variables.
10249  */
10250 static int
10251 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10252 {
10253 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10254 	int err = 0;
10255 	uint_t pc;
10256 
10257 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10258 		dif_instr_t instr = dp->dtdo_buf[pc];
10259 
10260 		uint_t v = DIF_INSTR_VAR(instr);
10261 		uint_t subr = DIF_INSTR_SUBR(instr);
10262 		uint_t op = DIF_INSTR_OP(instr);
10263 
10264 		switch (op) {
10265 		case DIF_OP_OR:
10266 		case DIF_OP_XOR:
10267 		case DIF_OP_AND:
10268 		case DIF_OP_SLL:
10269 		case DIF_OP_SRL:
10270 		case DIF_OP_SRA:
10271 		case DIF_OP_SUB:
10272 		case DIF_OP_ADD:
10273 		case DIF_OP_MUL:
10274 		case DIF_OP_SDIV:
10275 		case DIF_OP_UDIV:
10276 		case DIF_OP_SREM:
10277 		case DIF_OP_UREM:
10278 		case DIF_OP_COPYS:
10279 		case DIF_OP_NOT:
10280 		case DIF_OP_MOV:
10281 		case DIF_OP_RLDSB:
10282 		case DIF_OP_RLDSH:
10283 		case DIF_OP_RLDSW:
10284 		case DIF_OP_RLDUB:
10285 		case DIF_OP_RLDUH:
10286 		case DIF_OP_RLDUW:
10287 		case DIF_OP_RLDX:
10288 		case DIF_OP_ULDSB:
10289 		case DIF_OP_ULDSH:
10290 		case DIF_OP_ULDSW:
10291 		case DIF_OP_ULDUB:
10292 		case DIF_OP_ULDUH:
10293 		case DIF_OP_ULDUW:
10294 		case DIF_OP_ULDX:
10295 		case DIF_OP_STB:
10296 		case DIF_OP_STH:
10297 		case DIF_OP_STW:
10298 		case DIF_OP_STX:
10299 		case DIF_OP_ALLOCS:
10300 		case DIF_OP_CMP:
10301 		case DIF_OP_SCMP:
10302 		case DIF_OP_TST:
10303 		case DIF_OP_BA:
10304 		case DIF_OP_BE:
10305 		case DIF_OP_BNE:
10306 		case DIF_OP_BG:
10307 		case DIF_OP_BGU:
10308 		case DIF_OP_BGE:
10309 		case DIF_OP_BGEU:
10310 		case DIF_OP_BL:
10311 		case DIF_OP_BLU:
10312 		case DIF_OP_BLE:
10313 		case DIF_OP_BLEU:
10314 		case DIF_OP_RET:
10315 		case DIF_OP_NOP:
10316 		case DIF_OP_POPTS:
10317 		case DIF_OP_FLUSHTS:
10318 		case DIF_OP_SETX:
10319 		case DIF_OP_SETS:
10320 		case DIF_OP_LDGA:
10321 		case DIF_OP_LDLS:
10322 		case DIF_OP_STGS:
10323 		case DIF_OP_STLS:
10324 		case DIF_OP_PUSHTR:
10325 		case DIF_OP_PUSHTV:
10326 			break;
10327 
10328 		case DIF_OP_LDGS:
10329 			if (v >= DIF_VAR_OTHER_UBASE)
10330 				break;
10331 
10332 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10333 				break;
10334 
10335 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10336 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10337 			    v == DIF_VAR_EXECARGS ||
10338 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10339 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10340 				break;
10341 
10342 			err += efunc(pc, "illegal variable %u\n", v);
10343 			break;
10344 
10345 		case DIF_OP_LDTA:
10346 		case DIF_OP_LDTS:
10347 		case DIF_OP_LDGAA:
10348 		case DIF_OP_LDTAA:
10349 			err += efunc(pc, "illegal dynamic variable load\n");
10350 			break;
10351 
10352 		case DIF_OP_STTS:
10353 		case DIF_OP_STGAA:
10354 		case DIF_OP_STTAA:
10355 			err += efunc(pc, "illegal dynamic variable store\n");
10356 			break;
10357 
10358 		case DIF_OP_CALL:
10359 			if (subr == DIF_SUBR_ALLOCA ||
10360 			    subr == DIF_SUBR_BCOPY ||
10361 			    subr == DIF_SUBR_COPYIN ||
10362 			    subr == DIF_SUBR_COPYINTO ||
10363 			    subr == DIF_SUBR_COPYINSTR ||
10364 			    subr == DIF_SUBR_INDEX ||
10365 			    subr == DIF_SUBR_INET_NTOA ||
10366 			    subr == DIF_SUBR_INET_NTOA6 ||
10367 			    subr == DIF_SUBR_INET_NTOP ||
10368 			    subr == DIF_SUBR_JSON ||
10369 			    subr == DIF_SUBR_LLTOSTR ||
10370 			    subr == DIF_SUBR_STRTOLL ||
10371 			    subr == DIF_SUBR_RINDEX ||
10372 			    subr == DIF_SUBR_STRCHR ||
10373 			    subr == DIF_SUBR_STRJOIN ||
10374 			    subr == DIF_SUBR_STRRCHR ||
10375 			    subr == DIF_SUBR_STRSTR ||
10376 			    subr == DIF_SUBR_HTONS ||
10377 			    subr == DIF_SUBR_HTONL ||
10378 			    subr == DIF_SUBR_HTONLL ||
10379 			    subr == DIF_SUBR_NTOHS ||
10380 			    subr == DIF_SUBR_NTOHL ||
10381 			    subr == DIF_SUBR_NTOHLL ||
10382 			    subr == DIF_SUBR_MEMREF)
10383 				break;
10384 #ifdef __FreeBSD__
10385 			if (subr == DIF_SUBR_MEMSTR)
10386 				break;
10387 #endif
10388 
10389 			err += efunc(pc, "invalid subr %u\n", subr);
10390 			break;
10391 
10392 		default:
10393 			err += efunc(pc, "invalid opcode %u\n",
10394 			    DIF_INSTR_OP(instr));
10395 		}
10396 	}
10397 
10398 	return (err);
10399 }
10400 
10401 /*
10402  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10403  * basis; 0 if not.
10404  */
10405 static int
10406 dtrace_difo_cacheable(dtrace_difo_t *dp)
10407 {
10408 	int i;
10409 
10410 	if (dp == NULL)
10411 		return (0);
10412 
10413 	for (i = 0; i < dp->dtdo_varlen; i++) {
10414 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10415 
10416 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10417 			continue;
10418 
10419 		switch (v->dtdv_id) {
10420 		case DIF_VAR_CURTHREAD:
10421 		case DIF_VAR_PID:
10422 		case DIF_VAR_TID:
10423 		case DIF_VAR_EXECARGS:
10424 		case DIF_VAR_EXECNAME:
10425 		case DIF_VAR_ZONENAME:
10426 			break;
10427 
10428 		default:
10429 			return (0);
10430 		}
10431 	}
10432 
10433 	/*
10434 	 * This DIF object may be cacheable.  Now we need to look for any
10435 	 * array loading instructions, any memory loading instructions, or
10436 	 * any stores to thread-local variables.
10437 	 */
10438 	for (i = 0; i < dp->dtdo_len; i++) {
10439 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10440 
10441 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10442 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10443 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10444 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10445 			return (0);
10446 	}
10447 
10448 	return (1);
10449 }
10450 
10451 static void
10452 dtrace_difo_hold(dtrace_difo_t *dp)
10453 {
10454 	int i;
10455 
10456 	ASSERT(MUTEX_HELD(&dtrace_lock));
10457 
10458 	dp->dtdo_refcnt++;
10459 	ASSERT(dp->dtdo_refcnt != 0);
10460 
10461 	/*
10462 	 * We need to check this DIF object for references to the variable
10463 	 * DIF_VAR_VTIMESTAMP.
10464 	 */
10465 	for (i = 0; i < dp->dtdo_varlen; i++) {
10466 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10467 
10468 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10469 			continue;
10470 
10471 		if (dtrace_vtime_references++ == 0)
10472 			dtrace_vtime_enable();
10473 	}
10474 }
10475 
10476 /*
10477  * This routine calculates the dynamic variable chunksize for a given DIF
10478  * object.  The calculation is not fool-proof, and can probably be tricked by
10479  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10480  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10481  * if a dynamic variable size exceeds the chunksize.
10482  */
10483 static void
10484 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10485 {
10486 	uint64_t sval = 0;
10487 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10488 	const dif_instr_t *text = dp->dtdo_buf;
10489 	uint_t pc, srd = 0;
10490 	uint_t ttop = 0;
10491 	size_t size, ksize;
10492 	uint_t id, i;
10493 
10494 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10495 		dif_instr_t instr = text[pc];
10496 		uint_t op = DIF_INSTR_OP(instr);
10497 		uint_t rd = DIF_INSTR_RD(instr);
10498 		uint_t r1 = DIF_INSTR_R1(instr);
10499 		uint_t nkeys = 0;
10500 		uchar_t scope = 0;
10501 
10502 		dtrace_key_t *key = tupregs;
10503 
10504 		switch (op) {
10505 		case DIF_OP_SETX:
10506 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10507 			srd = rd;
10508 			continue;
10509 
10510 		case DIF_OP_STTS:
10511 			key = &tupregs[DIF_DTR_NREGS];
10512 			key[0].dttk_size = 0;
10513 			key[1].dttk_size = 0;
10514 			nkeys = 2;
10515 			scope = DIFV_SCOPE_THREAD;
10516 			break;
10517 
10518 		case DIF_OP_STGAA:
10519 		case DIF_OP_STTAA:
10520 			nkeys = ttop;
10521 
10522 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10523 				key[nkeys++].dttk_size = 0;
10524 
10525 			key[nkeys++].dttk_size = 0;
10526 
10527 			if (op == DIF_OP_STTAA) {
10528 				scope = DIFV_SCOPE_THREAD;
10529 			} else {
10530 				scope = DIFV_SCOPE_GLOBAL;
10531 			}
10532 
10533 			break;
10534 
10535 		case DIF_OP_PUSHTR:
10536 			if (ttop == DIF_DTR_NREGS)
10537 				return;
10538 
10539 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10540 				/*
10541 				 * If the register for the size of the "pushtr"
10542 				 * is %r0 (or the value is 0) and the type is
10543 				 * a string, we'll use the system-wide default
10544 				 * string size.
10545 				 */
10546 				tupregs[ttop++].dttk_size =
10547 				    dtrace_strsize_default;
10548 			} else {
10549 				if (srd == 0)
10550 					return;
10551 
10552 				if (sval > LONG_MAX)
10553 					return;
10554 
10555 				tupregs[ttop++].dttk_size = sval;
10556 			}
10557 
10558 			break;
10559 
10560 		case DIF_OP_PUSHTV:
10561 			if (ttop == DIF_DTR_NREGS)
10562 				return;
10563 
10564 			tupregs[ttop++].dttk_size = 0;
10565 			break;
10566 
10567 		case DIF_OP_FLUSHTS:
10568 			ttop = 0;
10569 			break;
10570 
10571 		case DIF_OP_POPTS:
10572 			if (ttop != 0)
10573 				ttop--;
10574 			break;
10575 		}
10576 
10577 		sval = 0;
10578 		srd = 0;
10579 
10580 		if (nkeys == 0)
10581 			continue;
10582 
10583 		/*
10584 		 * We have a dynamic variable allocation; calculate its size.
10585 		 */
10586 		for (ksize = 0, i = 0; i < nkeys; i++)
10587 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10588 
10589 		size = sizeof (dtrace_dynvar_t);
10590 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10591 		size += ksize;
10592 
10593 		/*
10594 		 * Now we need to determine the size of the stored data.
10595 		 */
10596 		id = DIF_INSTR_VAR(instr);
10597 
10598 		for (i = 0; i < dp->dtdo_varlen; i++) {
10599 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10600 
10601 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10602 				size += v->dtdv_type.dtdt_size;
10603 				break;
10604 			}
10605 		}
10606 
10607 		if (i == dp->dtdo_varlen)
10608 			return;
10609 
10610 		/*
10611 		 * We have the size.  If this is larger than the chunk size
10612 		 * for our dynamic variable state, reset the chunk size.
10613 		 */
10614 		size = P2ROUNDUP(size, sizeof (uint64_t));
10615 
10616 		/*
10617 		 * Before setting the chunk size, check that we're not going
10618 		 * to set it to a negative value...
10619 		 */
10620 		if (size > LONG_MAX)
10621 			return;
10622 
10623 		/*
10624 		 * ...and make certain that we didn't badly overflow.
10625 		 */
10626 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10627 			return;
10628 
10629 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10630 			vstate->dtvs_dynvars.dtds_chunksize = size;
10631 	}
10632 }
10633 
10634 static void
10635 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10636 {
10637 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10638 	uint_t id;
10639 
10640 	ASSERT(MUTEX_HELD(&dtrace_lock));
10641 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10642 
10643 	for (i = 0; i < dp->dtdo_varlen; i++) {
10644 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10645 		dtrace_statvar_t *svar, ***svarp = NULL;
10646 		size_t dsize = 0;
10647 		uint8_t scope = v->dtdv_scope;
10648 		int *np = NULL;
10649 
10650 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10651 			continue;
10652 
10653 		id -= DIF_VAR_OTHER_UBASE;
10654 
10655 		switch (scope) {
10656 		case DIFV_SCOPE_THREAD:
10657 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10658 				dtrace_difv_t *tlocals;
10659 
10660 				if ((ntlocals = (otlocals << 1)) == 0)
10661 					ntlocals = 1;
10662 
10663 				osz = otlocals * sizeof (dtrace_difv_t);
10664 				nsz = ntlocals * sizeof (dtrace_difv_t);
10665 
10666 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10667 
10668 				if (osz != 0) {
10669 					bcopy(vstate->dtvs_tlocals,
10670 					    tlocals, osz);
10671 					kmem_free(vstate->dtvs_tlocals, osz);
10672 				}
10673 
10674 				vstate->dtvs_tlocals = tlocals;
10675 				vstate->dtvs_ntlocals = ntlocals;
10676 			}
10677 
10678 			vstate->dtvs_tlocals[id] = *v;
10679 			continue;
10680 
10681 		case DIFV_SCOPE_LOCAL:
10682 			np = &vstate->dtvs_nlocals;
10683 			svarp = &vstate->dtvs_locals;
10684 
10685 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10686 				dsize = (mp_maxid + 1) *
10687 				    (v->dtdv_type.dtdt_size +
10688 				    sizeof (uint64_t));
10689 			else
10690 				dsize = (mp_maxid + 1) * sizeof (uint64_t);
10691 
10692 			break;
10693 
10694 		case DIFV_SCOPE_GLOBAL:
10695 			np = &vstate->dtvs_nglobals;
10696 			svarp = &vstate->dtvs_globals;
10697 
10698 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10699 				dsize = v->dtdv_type.dtdt_size +
10700 				    sizeof (uint64_t);
10701 
10702 			break;
10703 
10704 		default:
10705 			ASSERT(0);
10706 		}
10707 
10708 		while (id >= (oldsvars = *np)) {
10709 			dtrace_statvar_t **statics;
10710 			int newsvars, oldsize, newsize;
10711 
10712 			if ((newsvars = (oldsvars << 1)) == 0)
10713 				newsvars = 1;
10714 
10715 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10716 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10717 
10718 			statics = kmem_zalloc(newsize, KM_SLEEP);
10719 
10720 			if (oldsize != 0) {
10721 				bcopy(*svarp, statics, oldsize);
10722 				kmem_free(*svarp, oldsize);
10723 			}
10724 
10725 			*svarp = statics;
10726 			*np = newsvars;
10727 		}
10728 
10729 		if ((svar = (*svarp)[id]) == NULL) {
10730 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10731 			svar->dtsv_var = *v;
10732 
10733 			if ((svar->dtsv_size = dsize) != 0) {
10734 				svar->dtsv_data = (uint64_t)(uintptr_t)
10735 				    kmem_zalloc(dsize, KM_SLEEP);
10736 			}
10737 
10738 			(*svarp)[id] = svar;
10739 		}
10740 
10741 		svar->dtsv_refcnt++;
10742 	}
10743 
10744 	dtrace_difo_chunksize(dp, vstate);
10745 	dtrace_difo_hold(dp);
10746 }
10747 
10748 static dtrace_difo_t *
10749 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10750 {
10751 	dtrace_difo_t *new;
10752 	size_t sz;
10753 
10754 	ASSERT(dp->dtdo_buf != NULL);
10755 	ASSERT(dp->dtdo_refcnt != 0);
10756 
10757 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10758 
10759 	ASSERT(dp->dtdo_buf != NULL);
10760 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10761 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10762 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10763 	new->dtdo_len = dp->dtdo_len;
10764 
10765 	if (dp->dtdo_strtab != NULL) {
10766 		ASSERT(dp->dtdo_strlen != 0);
10767 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10768 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10769 		new->dtdo_strlen = dp->dtdo_strlen;
10770 	}
10771 
10772 	if (dp->dtdo_inttab != NULL) {
10773 		ASSERT(dp->dtdo_intlen != 0);
10774 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10775 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10776 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10777 		new->dtdo_intlen = dp->dtdo_intlen;
10778 	}
10779 
10780 	if (dp->dtdo_vartab != NULL) {
10781 		ASSERT(dp->dtdo_varlen != 0);
10782 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10783 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10784 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10785 		new->dtdo_varlen = dp->dtdo_varlen;
10786 	}
10787 
10788 	dtrace_difo_init(new, vstate);
10789 	return (new);
10790 }
10791 
10792 static void
10793 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10794 {
10795 	int i;
10796 
10797 	ASSERT(dp->dtdo_refcnt == 0);
10798 
10799 	for (i = 0; i < dp->dtdo_varlen; i++) {
10800 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10801 		dtrace_statvar_t *svar, **svarp = NULL;
10802 		uint_t id;
10803 		uint8_t scope = v->dtdv_scope;
10804 		int *np = NULL;
10805 
10806 		switch (scope) {
10807 		case DIFV_SCOPE_THREAD:
10808 			continue;
10809 
10810 		case DIFV_SCOPE_LOCAL:
10811 			np = &vstate->dtvs_nlocals;
10812 			svarp = vstate->dtvs_locals;
10813 			break;
10814 
10815 		case DIFV_SCOPE_GLOBAL:
10816 			np = &vstate->dtvs_nglobals;
10817 			svarp = vstate->dtvs_globals;
10818 			break;
10819 
10820 		default:
10821 			ASSERT(0);
10822 		}
10823 
10824 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10825 			continue;
10826 
10827 		id -= DIF_VAR_OTHER_UBASE;
10828 		ASSERT(id < *np);
10829 
10830 		svar = svarp[id];
10831 		ASSERT(svar != NULL);
10832 		ASSERT(svar->dtsv_refcnt > 0);
10833 
10834 		if (--svar->dtsv_refcnt > 0)
10835 			continue;
10836 
10837 		if (svar->dtsv_size != 0) {
10838 			ASSERT(svar->dtsv_data != 0);
10839 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10840 			    svar->dtsv_size);
10841 		}
10842 
10843 		kmem_free(svar, sizeof (dtrace_statvar_t));
10844 		svarp[id] = NULL;
10845 	}
10846 
10847 	if (dp->dtdo_buf != NULL)
10848 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10849 	if (dp->dtdo_inttab != NULL)
10850 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10851 	if (dp->dtdo_strtab != NULL)
10852 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10853 	if (dp->dtdo_vartab != NULL)
10854 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10855 
10856 	kmem_free(dp, sizeof (dtrace_difo_t));
10857 }
10858 
10859 static void
10860 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10861 {
10862 	int i;
10863 
10864 	ASSERT(MUTEX_HELD(&dtrace_lock));
10865 	ASSERT(dp->dtdo_refcnt != 0);
10866 
10867 	for (i = 0; i < dp->dtdo_varlen; i++) {
10868 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10869 
10870 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10871 			continue;
10872 
10873 		ASSERT(dtrace_vtime_references > 0);
10874 		if (--dtrace_vtime_references == 0)
10875 			dtrace_vtime_disable();
10876 	}
10877 
10878 	if (--dp->dtdo_refcnt == 0)
10879 		dtrace_difo_destroy(dp, vstate);
10880 }
10881 
10882 /*
10883  * DTrace Format Functions
10884  */
10885 static uint16_t
10886 dtrace_format_add(dtrace_state_t *state, char *str)
10887 {
10888 	char *fmt, **new;
10889 	uint16_t ndx, len = strlen(str) + 1;
10890 
10891 	fmt = kmem_zalloc(len, KM_SLEEP);
10892 	bcopy(str, fmt, len);
10893 
10894 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10895 		if (state->dts_formats[ndx] == NULL) {
10896 			state->dts_formats[ndx] = fmt;
10897 			return (ndx + 1);
10898 		}
10899 	}
10900 
10901 	if (state->dts_nformats == USHRT_MAX) {
10902 		/*
10903 		 * This is only likely if a denial-of-service attack is being
10904 		 * attempted.  As such, it's okay to fail silently here.
10905 		 */
10906 		kmem_free(fmt, len);
10907 		return (0);
10908 	}
10909 
10910 	/*
10911 	 * For simplicity, we always resize the formats array to be exactly the
10912 	 * number of formats.
10913 	 */
10914 	ndx = state->dts_nformats++;
10915 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10916 
10917 	if (state->dts_formats != NULL) {
10918 		ASSERT(ndx != 0);
10919 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10920 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10921 	}
10922 
10923 	state->dts_formats = new;
10924 	state->dts_formats[ndx] = fmt;
10925 
10926 	return (ndx + 1);
10927 }
10928 
10929 static void
10930 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10931 {
10932 	char *fmt;
10933 
10934 	ASSERT(state->dts_formats != NULL);
10935 	ASSERT(format <= state->dts_nformats);
10936 	ASSERT(state->dts_formats[format - 1] != NULL);
10937 
10938 	fmt = state->dts_formats[format - 1];
10939 	kmem_free(fmt, strlen(fmt) + 1);
10940 	state->dts_formats[format - 1] = NULL;
10941 }
10942 
10943 static void
10944 dtrace_format_destroy(dtrace_state_t *state)
10945 {
10946 	int i;
10947 
10948 	if (state->dts_nformats == 0) {
10949 		ASSERT(state->dts_formats == NULL);
10950 		return;
10951 	}
10952 
10953 	ASSERT(state->dts_formats != NULL);
10954 
10955 	for (i = 0; i < state->dts_nformats; i++) {
10956 		char *fmt = state->dts_formats[i];
10957 
10958 		if (fmt == NULL)
10959 			continue;
10960 
10961 		kmem_free(fmt, strlen(fmt) + 1);
10962 	}
10963 
10964 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10965 	state->dts_nformats = 0;
10966 	state->dts_formats = NULL;
10967 }
10968 
10969 /*
10970  * DTrace Predicate Functions
10971  */
10972 static dtrace_predicate_t *
10973 dtrace_predicate_create(dtrace_difo_t *dp)
10974 {
10975 	dtrace_predicate_t *pred;
10976 
10977 	ASSERT(MUTEX_HELD(&dtrace_lock));
10978 	ASSERT(dp->dtdo_refcnt != 0);
10979 
10980 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10981 	pred->dtp_difo = dp;
10982 	pred->dtp_refcnt = 1;
10983 
10984 	if (!dtrace_difo_cacheable(dp))
10985 		return (pred);
10986 
10987 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10988 		/*
10989 		 * This is only theoretically possible -- we have had 2^32
10990 		 * cacheable predicates on this machine.  We cannot allow any
10991 		 * more predicates to become cacheable:  as unlikely as it is,
10992 		 * there may be a thread caching a (now stale) predicate cache
10993 		 * ID. (N.B.: the temptation is being successfully resisted to
10994 		 * have this cmn_err() "Holy shit -- we executed this code!")
10995 		 */
10996 		return (pred);
10997 	}
10998 
10999 	pred->dtp_cacheid = dtrace_predcache_id++;
11000 
11001 	return (pred);
11002 }
11003 
11004 static void
11005 dtrace_predicate_hold(dtrace_predicate_t *pred)
11006 {
11007 	ASSERT(MUTEX_HELD(&dtrace_lock));
11008 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
11009 	ASSERT(pred->dtp_refcnt > 0);
11010 
11011 	pred->dtp_refcnt++;
11012 }
11013 
11014 static void
11015 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
11016 {
11017 	dtrace_difo_t *dp = pred->dtp_difo;
11018 
11019 	ASSERT(MUTEX_HELD(&dtrace_lock));
11020 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11021 	ASSERT(pred->dtp_refcnt > 0);
11022 
11023 	if (--pred->dtp_refcnt == 0) {
11024 		dtrace_difo_release(pred->dtp_difo, vstate);
11025 		kmem_free(pred, sizeof (dtrace_predicate_t));
11026 	}
11027 }
11028 
11029 /*
11030  * DTrace Action Description Functions
11031  */
11032 static dtrace_actdesc_t *
11033 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11034     uint64_t uarg, uint64_t arg)
11035 {
11036 	dtrace_actdesc_t *act;
11037 
11038 #ifdef illumos
11039 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11040 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11041 #endif
11042 
11043 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11044 	act->dtad_kind = kind;
11045 	act->dtad_ntuple = ntuple;
11046 	act->dtad_uarg = uarg;
11047 	act->dtad_arg = arg;
11048 	act->dtad_refcnt = 1;
11049 
11050 	return (act);
11051 }
11052 
11053 static void
11054 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11055 {
11056 	ASSERT(act->dtad_refcnt >= 1);
11057 	act->dtad_refcnt++;
11058 }
11059 
11060 static void
11061 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11062 {
11063 	dtrace_actkind_t kind = act->dtad_kind;
11064 	dtrace_difo_t *dp;
11065 
11066 	ASSERT(act->dtad_refcnt >= 1);
11067 
11068 	if (--act->dtad_refcnt != 0)
11069 		return;
11070 
11071 	if ((dp = act->dtad_difo) != NULL)
11072 		dtrace_difo_release(dp, vstate);
11073 
11074 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11075 		char *str = (char *)(uintptr_t)act->dtad_arg;
11076 
11077 #ifdef illumos
11078 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11079 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11080 #endif
11081 
11082 		if (str != NULL)
11083 			kmem_free(str, strlen(str) + 1);
11084 	}
11085 
11086 	kmem_free(act, sizeof (dtrace_actdesc_t));
11087 }
11088 
11089 /*
11090  * DTrace ECB Functions
11091  */
11092 static dtrace_ecb_t *
11093 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11094 {
11095 	dtrace_ecb_t *ecb;
11096 	dtrace_epid_t epid;
11097 
11098 	ASSERT(MUTEX_HELD(&dtrace_lock));
11099 
11100 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11101 	ecb->dte_predicate = NULL;
11102 	ecb->dte_probe = probe;
11103 
11104 	/*
11105 	 * The default size is the size of the default action: recording
11106 	 * the header.
11107 	 */
11108 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11109 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11110 
11111 	epid = state->dts_epid++;
11112 
11113 	if (epid - 1 >= state->dts_necbs) {
11114 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11115 		int necbs = state->dts_necbs << 1;
11116 
11117 		ASSERT(epid == state->dts_necbs + 1);
11118 
11119 		if (necbs == 0) {
11120 			ASSERT(oecbs == NULL);
11121 			necbs = 1;
11122 		}
11123 
11124 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11125 
11126 		if (oecbs != NULL)
11127 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11128 
11129 		dtrace_membar_producer();
11130 		state->dts_ecbs = ecbs;
11131 
11132 		if (oecbs != NULL) {
11133 			/*
11134 			 * If this state is active, we must dtrace_sync()
11135 			 * before we can free the old dts_ecbs array:  we're
11136 			 * coming in hot, and there may be active ring
11137 			 * buffer processing (which indexes into the dts_ecbs
11138 			 * array) on another CPU.
11139 			 */
11140 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11141 				dtrace_sync();
11142 
11143 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11144 		}
11145 
11146 		dtrace_membar_producer();
11147 		state->dts_necbs = necbs;
11148 	}
11149 
11150 	ecb->dte_state = state;
11151 
11152 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11153 	dtrace_membar_producer();
11154 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11155 
11156 	return (ecb);
11157 }
11158 
11159 static void
11160 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11161 {
11162 	dtrace_probe_t *probe = ecb->dte_probe;
11163 
11164 	ASSERT(MUTEX_HELD(&cpu_lock));
11165 	ASSERT(MUTEX_HELD(&dtrace_lock));
11166 	ASSERT(ecb->dte_next == NULL);
11167 
11168 	if (probe == NULL) {
11169 		/*
11170 		 * This is the NULL probe -- there's nothing to do.
11171 		 */
11172 		return;
11173 	}
11174 
11175 	if (probe->dtpr_ecb == NULL) {
11176 		dtrace_provider_t *prov = probe->dtpr_provider;
11177 
11178 		/*
11179 		 * We're the first ECB on this probe.
11180 		 */
11181 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11182 
11183 		if (ecb->dte_predicate != NULL)
11184 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11185 
11186 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11187 		    probe->dtpr_id, probe->dtpr_arg);
11188 	} else {
11189 		/*
11190 		 * This probe is already active.  Swing the last pointer to
11191 		 * point to the new ECB, and issue a dtrace_sync() to assure
11192 		 * that all CPUs have seen the change.
11193 		 */
11194 		ASSERT(probe->dtpr_ecb_last != NULL);
11195 		probe->dtpr_ecb_last->dte_next = ecb;
11196 		probe->dtpr_ecb_last = ecb;
11197 		probe->dtpr_predcache = 0;
11198 
11199 		dtrace_sync();
11200 	}
11201 }
11202 
11203 static int
11204 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11205 {
11206 	dtrace_action_t *act;
11207 	uint32_t curneeded = UINT32_MAX;
11208 	uint32_t aggbase = UINT32_MAX;
11209 
11210 	/*
11211 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11212 	 * we always record it first.)
11213 	 */
11214 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11215 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11216 
11217 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11218 		dtrace_recdesc_t *rec = &act->dta_rec;
11219 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11220 
11221 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11222 		    rec->dtrd_alignment);
11223 
11224 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11225 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11226 
11227 			ASSERT(rec->dtrd_size != 0);
11228 			ASSERT(agg->dtag_first != NULL);
11229 			ASSERT(act->dta_prev->dta_intuple);
11230 			ASSERT(aggbase != UINT32_MAX);
11231 			ASSERT(curneeded != UINT32_MAX);
11232 
11233 			agg->dtag_base = aggbase;
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 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11241 
11242 			aggbase = UINT32_MAX;
11243 			curneeded = UINT32_MAX;
11244 		} else if (act->dta_intuple) {
11245 			if (curneeded == UINT32_MAX) {
11246 				/*
11247 				 * This is the first record in a tuple.  Align
11248 				 * curneeded to be at offset 4 in an 8-byte
11249 				 * aligned block.
11250 				 */
11251 				ASSERT(act->dta_prev == NULL ||
11252 				    !act->dta_prev->dta_intuple);
11253 				ASSERT3U(aggbase, ==, UINT32_MAX);
11254 				curneeded = P2PHASEUP(ecb->dte_size,
11255 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11256 
11257 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11258 				ASSERT(IS_P2ALIGNED(aggbase,
11259 				    sizeof (uint64_t)));
11260 			}
11261 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11262 			rec->dtrd_offset = curneeded;
11263 			if (curneeded + rec->dtrd_size < curneeded)
11264 				return (EINVAL);
11265 			curneeded += rec->dtrd_size;
11266 		} else {
11267 			/* tuples must be followed by an aggregation */
11268 			ASSERT(act->dta_prev == NULL ||
11269 			    !act->dta_prev->dta_intuple);
11270 
11271 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11272 			    rec->dtrd_alignment);
11273 			rec->dtrd_offset = ecb->dte_size;
11274 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11275 				return (EINVAL);
11276 			ecb->dte_size += rec->dtrd_size;
11277 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11278 		}
11279 	}
11280 
11281 	if ((act = ecb->dte_action) != NULL &&
11282 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11283 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11284 		/*
11285 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11286 		 * actions store no data; set the size to 0.
11287 		 */
11288 		ecb->dte_size = 0;
11289 	}
11290 
11291 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11292 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11293 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11294 	    ecb->dte_needed);
11295 	return (0);
11296 }
11297 
11298 static dtrace_action_t *
11299 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11300 {
11301 	dtrace_aggregation_t *agg;
11302 	size_t size = sizeof (uint64_t);
11303 	int ntuple = desc->dtad_ntuple;
11304 	dtrace_action_t *act;
11305 	dtrace_recdesc_t *frec;
11306 	dtrace_aggid_t aggid;
11307 	dtrace_state_t *state = ecb->dte_state;
11308 
11309 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11310 	agg->dtag_ecb = ecb;
11311 
11312 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11313 
11314 	switch (desc->dtad_kind) {
11315 	case DTRACEAGG_MIN:
11316 		agg->dtag_initial = INT64_MAX;
11317 		agg->dtag_aggregate = dtrace_aggregate_min;
11318 		break;
11319 
11320 	case DTRACEAGG_MAX:
11321 		agg->dtag_initial = INT64_MIN;
11322 		agg->dtag_aggregate = dtrace_aggregate_max;
11323 		break;
11324 
11325 	case DTRACEAGG_COUNT:
11326 		agg->dtag_aggregate = dtrace_aggregate_count;
11327 		break;
11328 
11329 	case DTRACEAGG_QUANTIZE:
11330 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11331 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11332 		    sizeof (uint64_t);
11333 		break;
11334 
11335 	case DTRACEAGG_LQUANTIZE: {
11336 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11337 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11338 
11339 		agg->dtag_initial = desc->dtad_arg;
11340 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11341 
11342 		if (step == 0 || levels == 0)
11343 			goto err;
11344 
11345 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11346 		break;
11347 	}
11348 
11349 	case DTRACEAGG_LLQUANTIZE: {
11350 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11351 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11352 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11353 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11354 		int64_t v;
11355 
11356 		agg->dtag_initial = desc->dtad_arg;
11357 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11358 
11359 		if (factor < 2 || low >= high || nsteps < factor)
11360 			goto err;
11361 
11362 		/*
11363 		 * Now check that the number of steps evenly divides a power
11364 		 * of the factor.  (This assures both integer bucket size and
11365 		 * linearity within each magnitude.)
11366 		 */
11367 		for (v = factor; v < nsteps; v *= factor)
11368 			continue;
11369 
11370 		if ((v % nsteps) || (nsteps % factor))
11371 			goto err;
11372 
11373 		size = (dtrace_aggregate_llquantize_bucket(factor,
11374 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11375 		break;
11376 	}
11377 
11378 	case DTRACEAGG_AVG:
11379 		agg->dtag_aggregate = dtrace_aggregate_avg;
11380 		size = sizeof (uint64_t) * 2;
11381 		break;
11382 
11383 	case DTRACEAGG_STDDEV:
11384 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11385 		size = sizeof (uint64_t) * 4;
11386 		break;
11387 
11388 	case DTRACEAGG_SUM:
11389 		agg->dtag_aggregate = dtrace_aggregate_sum;
11390 		break;
11391 
11392 	default:
11393 		goto err;
11394 	}
11395 
11396 	agg->dtag_action.dta_rec.dtrd_size = size;
11397 
11398 	if (ntuple == 0)
11399 		goto err;
11400 
11401 	/*
11402 	 * We must make sure that we have enough actions for the n-tuple.
11403 	 */
11404 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11405 		if (DTRACEACT_ISAGG(act->dta_kind))
11406 			break;
11407 
11408 		if (--ntuple == 0) {
11409 			/*
11410 			 * This is the action with which our n-tuple begins.
11411 			 */
11412 			agg->dtag_first = act;
11413 			goto success;
11414 		}
11415 	}
11416 
11417 	/*
11418 	 * This n-tuple is short by ntuple elements.  Return failure.
11419 	 */
11420 	ASSERT(ntuple != 0);
11421 err:
11422 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11423 	return (NULL);
11424 
11425 success:
11426 	/*
11427 	 * If the last action in the tuple has a size of zero, it's actually
11428 	 * an expression argument for the aggregating action.
11429 	 */
11430 	ASSERT(ecb->dte_action_last != NULL);
11431 	act = ecb->dte_action_last;
11432 
11433 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11434 		ASSERT(act->dta_difo != NULL);
11435 
11436 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11437 			agg->dtag_hasarg = 1;
11438 	}
11439 
11440 	/*
11441 	 * We need to allocate an id for this aggregation.
11442 	 */
11443 #ifdef illumos
11444 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11445 	    VM_BESTFIT | VM_SLEEP);
11446 #else
11447 	aggid = alloc_unr(state->dts_aggid_arena);
11448 #endif
11449 
11450 	if (aggid - 1 >= state->dts_naggregations) {
11451 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11452 		dtrace_aggregation_t **aggs;
11453 		int naggs = state->dts_naggregations << 1;
11454 		int onaggs = state->dts_naggregations;
11455 
11456 		ASSERT(aggid == state->dts_naggregations + 1);
11457 
11458 		if (naggs == 0) {
11459 			ASSERT(oaggs == NULL);
11460 			naggs = 1;
11461 		}
11462 
11463 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11464 
11465 		if (oaggs != NULL) {
11466 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11467 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11468 		}
11469 
11470 		state->dts_aggregations = aggs;
11471 		state->dts_naggregations = naggs;
11472 	}
11473 
11474 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11475 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11476 
11477 	frec = &agg->dtag_first->dta_rec;
11478 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11479 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11480 
11481 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11482 		ASSERT(!act->dta_intuple);
11483 		act->dta_intuple = 1;
11484 	}
11485 
11486 	return (&agg->dtag_action);
11487 }
11488 
11489 static void
11490 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11491 {
11492 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11493 	dtrace_state_t *state = ecb->dte_state;
11494 	dtrace_aggid_t aggid = agg->dtag_id;
11495 
11496 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11497 #ifdef illumos
11498 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11499 #else
11500 	free_unr(state->dts_aggid_arena, aggid);
11501 #endif
11502 
11503 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11504 	state->dts_aggregations[aggid - 1] = NULL;
11505 
11506 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11507 }
11508 
11509 static int
11510 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11511 {
11512 	dtrace_action_t *action, *last;
11513 	dtrace_difo_t *dp = desc->dtad_difo;
11514 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11515 	uint16_t format = 0;
11516 	dtrace_recdesc_t *rec;
11517 	dtrace_state_t *state = ecb->dte_state;
11518 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11519 	uint64_t arg = desc->dtad_arg;
11520 
11521 	ASSERT(MUTEX_HELD(&dtrace_lock));
11522 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11523 
11524 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11525 		/*
11526 		 * If this is an aggregating action, there must be neither
11527 		 * a speculate nor a commit on the action chain.
11528 		 */
11529 		dtrace_action_t *act;
11530 
11531 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11532 			if (act->dta_kind == DTRACEACT_COMMIT)
11533 				return (EINVAL);
11534 
11535 			if (act->dta_kind == DTRACEACT_SPECULATE)
11536 				return (EINVAL);
11537 		}
11538 
11539 		action = dtrace_ecb_aggregation_create(ecb, desc);
11540 
11541 		if (action == NULL)
11542 			return (EINVAL);
11543 	} else {
11544 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11545 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11546 		    dp != NULL && dp->dtdo_destructive)) {
11547 			state->dts_destructive = 1;
11548 		}
11549 
11550 		switch (desc->dtad_kind) {
11551 		case DTRACEACT_PRINTF:
11552 		case DTRACEACT_PRINTA:
11553 		case DTRACEACT_SYSTEM:
11554 		case DTRACEACT_FREOPEN:
11555 		case DTRACEACT_DIFEXPR:
11556 			/*
11557 			 * We know that our arg is a string -- turn it into a
11558 			 * format.
11559 			 */
11560 			if (arg == 0) {
11561 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11562 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11563 				format = 0;
11564 			} else {
11565 				ASSERT(arg != 0);
11566 #ifdef illumos
11567 				ASSERT(arg > KERNELBASE);
11568 #endif
11569 				format = dtrace_format_add(state,
11570 				    (char *)(uintptr_t)arg);
11571 			}
11572 
11573 			/*FALLTHROUGH*/
11574 		case DTRACEACT_LIBACT:
11575 		case DTRACEACT_TRACEMEM:
11576 		case DTRACEACT_TRACEMEM_DYNSIZE:
11577 			if (dp == NULL)
11578 				return (EINVAL);
11579 
11580 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11581 				break;
11582 
11583 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11584 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11585 					return (EINVAL);
11586 
11587 				size = opt[DTRACEOPT_STRSIZE];
11588 			}
11589 
11590 			break;
11591 
11592 		case DTRACEACT_STACK:
11593 			if ((nframes = arg) == 0) {
11594 				nframes = opt[DTRACEOPT_STACKFRAMES];
11595 				ASSERT(nframes > 0);
11596 				arg = nframes;
11597 			}
11598 
11599 			size = nframes * sizeof (pc_t);
11600 			break;
11601 
11602 		case DTRACEACT_JSTACK:
11603 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11604 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11605 
11606 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11607 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11608 
11609 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11610 
11611 			/*FALLTHROUGH*/
11612 		case DTRACEACT_USTACK:
11613 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11614 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11615 				strsize = DTRACE_USTACK_STRSIZE(arg);
11616 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11617 				ASSERT(nframes > 0);
11618 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11619 			}
11620 
11621 			/*
11622 			 * Save a slot for the pid.
11623 			 */
11624 			size = (nframes + 1) * sizeof (uint64_t);
11625 			size += DTRACE_USTACK_STRSIZE(arg);
11626 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11627 
11628 			break;
11629 
11630 		case DTRACEACT_SYM:
11631 		case DTRACEACT_MOD:
11632 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11633 			    sizeof (uint64_t)) ||
11634 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11635 				return (EINVAL);
11636 			break;
11637 
11638 		case DTRACEACT_USYM:
11639 		case DTRACEACT_UMOD:
11640 		case DTRACEACT_UADDR:
11641 			if (dp == NULL ||
11642 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11643 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11644 				return (EINVAL);
11645 
11646 			/*
11647 			 * We have a slot for the pid, plus a slot for the
11648 			 * argument.  To keep things simple (aligned with
11649 			 * bitness-neutral sizing), we store each as a 64-bit
11650 			 * quantity.
11651 			 */
11652 			size = 2 * sizeof (uint64_t);
11653 			break;
11654 
11655 		case DTRACEACT_STOP:
11656 		case DTRACEACT_BREAKPOINT:
11657 		case DTRACEACT_PANIC:
11658 			break;
11659 
11660 		case DTRACEACT_CHILL:
11661 		case DTRACEACT_DISCARD:
11662 		case DTRACEACT_RAISE:
11663 			if (dp == NULL)
11664 				return (EINVAL);
11665 			break;
11666 
11667 		case DTRACEACT_EXIT:
11668 			if (dp == NULL ||
11669 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11670 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11671 				return (EINVAL);
11672 			break;
11673 
11674 		case DTRACEACT_SPECULATE:
11675 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11676 				return (EINVAL);
11677 
11678 			if (dp == NULL)
11679 				return (EINVAL);
11680 
11681 			state->dts_speculates = 1;
11682 			break;
11683 
11684 		case DTRACEACT_PRINTM:
11685 		    	size = dp->dtdo_rtype.dtdt_size;
11686 			break;
11687 
11688 		case DTRACEACT_COMMIT: {
11689 			dtrace_action_t *act = ecb->dte_action;
11690 
11691 			for (; act != NULL; act = act->dta_next) {
11692 				if (act->dta_kind == DTRACEACT_COMMIT)
11693 					return (EINVAL);
11694 			}
11695 
11696 			if (dp == NULL)
11697 				return (EINVAL);
11698 			break;
11699 		}
11700 
11701 		default:
11702 			return (EINVAL);
11703 		}
11704 
11705 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11706 			/*
11707 			 * If this is a data-storing action or a speculate,
11708 			 * we must be sure that there isn't a commit on the
11709 			 * action chain.
11710 			 */
11711 			dtrace_action_t *act = ecb->dte_action;
11712 
11713 			for (; act != NULL; act = act->dta_next) {
11714 				if (act->dta_kind == DTRACEACT_COMMIT)
11715 					return (EINVAL);
11716 			}
11717 		}
11718 
11719 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11720 		action->dta_rec.dtrd_size = size;
11721 	}
11722 
11723 	action->dta_refcnt = 1;
11724 	rec = &action->dta_rec;
11725 	size = rec->dtrd_size;
11726 
11727 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11728 		if (!(size & mask)) {
11729 			align = mask + 1;
11730 			break;
11731 		}
11732 	}
11733 
11734 	action->dta_kind = desc->dtad_kind;
11735 
11736 	if ((action->dta_difo = dp) != NULL)
11737 		dtrace_difo_hold(dp);
11738 
11739 	rec->dtrd_action = action->dta_kind;
11740 	rec->dtrd_arg = arg;
11741 	rec->dtrd_uarg = desc->dtad_uarg;
11742 	rec->dtrd_alignment = (uint16_t)align;
11743 	rec->dtrd_format = format;
11744 
11745 	if ((last = ecb->dte_action_last) != NULL) {
11746 		ASSERT(ecb->dte_action != NULL);
11747 		action->dta_prev = last;
11748 		last->dta_next = action;
11749 	} else {
11750 		ASSERT(ecb->dte_action == NULL);
11751 		ecb->dte_action = action;
11752 	}
11753 
11754 	ecb->dte_action_last = action;
11755 
11756 	return (0);
11757 }
11758 
11759 static void
11760 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11761 {
11762 	dtrace_action_t *act = ecb->dte_action, *next;
11763 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11764 	dtrace_difo_t *dp;
11765 	uint16_t format;
11766 
11767 	if (act != NULL && act->dta_refcnt > 1) {
11768 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11769 		act->dta_refcnt--;
11770 	} else {
11771 		for (; act != NULL; act = next) {
11772 			next = act->dta_next;
11773 			ASSERT(next != NULL || act == ecb->dte_action_last);
11774 			ASSERT(act->dta_refcnt == 1);
11775 
11776 			if ((format = act->dta_rec.dtrd_format) != 0)
11777 				dtrace_format_remove(ecb->dte_state, format);
11778 
11779 			if ((dp = act->dta_difo) != NULL)
11780 				dtrace_difo_release(dp, vstate);
11781 
11782 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11783 				dtrace_ecb_aggregation_destroy(ecb, act);
11784 			} else {
11785 				kmem_free(act, sizeof (dtrace_action_t));
11786 			}
11787 		}
11788 	}
11789 
11790 	ecb->dte_action = NULL;
11791 	ecb->dte_action_last = NULL;
11792 	ecb->dte_size = 0;
11793 }
11794 
11795 static void
11796 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11797 {
11798 	/*
11799 	 * We disable the ECB by removing it from its probe.
11800 	 */
11801 	dtrace_ecb_t *pecb, *prev = NULL;
11802 	dtrace_probe_t *probe = ecb->dte_probe;
11803 
11804 	ASSERT(MUTEX_HELD(&dtrace_lock));
11805 
11806 	if (probe == NULL) {
11807 		/*
11808 		 * This is the NULL probe; there is nothing to disable.
11809 		 */
11810 		return;
11811 	}
11812 
11813 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11814 		if (pecb == ecb)
11815 			break;
11816 		prev = pecb;
11817 	}
11818 
11819 	ASSERT(pecb != NULL);
11820 
11821 	if (prev == NULL) {
11822 		probe->dtpr_ecb = ecb->dte_next;
11823 	} else {
11824 		prev->dte_next = ecb->dte_next;
11825 	}
11826 
11827 	if (ecb == probe->dtpr_ecb_last) {
11828 		ASSERT(ecb->dte_next == NULL);
11829 		probe->dtpr_ecb_last = prev;
11830 	}
11831 
11832 	/*
11833 	 * The ECB has been disconnected from the probe; now sync to assure
11834 	 * that all CPUs have seen the change before returning.
11835 	 */
11836 	dtrace_sync();
11837 
11838 	if (probe->dtpr_ecb == NULL) {
11839 		/*
11840 		 * That was the last ECB on the probe; clear the predicate
11841 		 * cache ID for the probe, disable it and sync one more time
11842 		 * to assure that we'll never hit it again.
11843 		 */
11844 		dtrace_provider_t *prov = probe->dtpr_provider;
11845 
11846 		ASSERT(ecb->dte_next == NULL);
11847 		ASSERT(probe->dtpr_ecb_last == NULL);
11848 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11849 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11850 		    probe->dtpr_id, probe->dtpr_arg);
11851 		dtrace_sync();
11852 	} else {
11853 		/*
11854 		 * There is at least one ECB remaining on the probe.  If there
11855 		 * is _exactly_ one, set the probe's predicate cache ID to be
11856 		 * the predicate cache ID of the remaining ECB.
11857 		 */
11858 		ASSERT(probe->dtpr_ecb_last != NULL);
11859 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11860 
11861 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11862 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11863 
11864 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11865 
11866 			if (p != NULL)
11867 				probe->dtpr_predcache = p->dtp_cacheid;
11868 		}
11869 
11870 		ecb->dte_next = NULL;
11871 	}
11872 }
11873 
11874 static void
11875 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11876 {
11877 	dtrace_state_t *state = ecb->dte_state;
11878 	dtrace_vstate_t *vstate = &state->dts_vstate;
11879 	dtrace_predicate_t *pred;
11880 	dtrace_epid_t epid = ecb->dte_epid;
11881 
11882 	ASSERT(MUTEX_HELD(&dtrace_lock));
11883 	ASSERT(ecb->dte_next == NULL);
11884 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11885 
11886 	if ((pred = ecb->dte_predicate) != NULL)
11887 		dtrace_predicate_release(pred, vstate);
11888 
11889 	dtrace_ecb_action_remove(ecb);
11890 
11891 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11892 	state->dts_ecbs[epid - 1] = NULL;
11893 
11894 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11895 }
11896 
11897 static dtrace_ecb_t *
11898 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11899     dtrace_enabling_t *enab)
11900 {
11901 	dtrace_ecb_t *ecb;
11902 	dtrace_predicate_t *pred;
11903 	dtrace_actdesc_t *act;
11904 	dtrace_provider_t *prov;
11905 	dtrace_ecbdesc_t *desc = enab->dten_current;
11906 
11907 	ASSERT(MUTEX_HELD(&dtrace_lock));
11908 	ASSERT(state != NULL);
11909 
11910 	ecb = dtrace_ecb_add(state, probe);
11911 	ecb->dte_uarg = desc->dted_uarg;
11912 
11913 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11914 		dtrace_predicate_hold(pred);
11915 		ecb->dte_predicate = pred;
11916 	}
11917 
11918 	if (probe != NULL) {
11919 		/*
11920 		 * If the provider shows more leg than the consumer is old
11921 		 * enough to see, we need to enable the appropriate implicit
11922 		 * predicate bits to prevent the ecb from activating at
11923 		 * revealing times.
11924 		 *
11925 		 * Providers specifying DTRACE_PRIV_USER at register time
11926 		 * are stating that they need the /proc-style privilege
11927 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11928 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11929 		 */
11930 		prov = probe->dtpr_provider;
11931 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11932 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11933 			ecb->dte_cond |= DTRACE_COND_OWNER;
11934 
11935 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11936 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11937 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11938 
11939 		/*
11940 		 * If the provider shows us kernel innards and the user
11941 		 * is lacking sufficient privilege, enable the
11942 		 * DTRACE_COND_USERMODE implicit predicate.
11943 		 */
11944 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11945 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11946 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11947 	}
11948 
11949 	if (dtrace_ecb_create_cache != NULL) {
11950 		/*
11951 		 * If we have a cached ecb, we'll use its action list instead
11952 		 * of creating our own (saving both time and space).
11953 		 */
11954 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11955 		dtrace_action_t *act = cached->dte_action;
11956 
11957 		if (act != NULL) {
11958 			ASSERT(act->dta_refcnt > 0);
11959 			act->dta_refcnt++;
11960 			ecb->dte_action = act;
11961 			ecb->dte_action_last = cached->dte_action_last;
11962 			ecb->dte_needed = cached->dte_needed;
11963 			ecb->dte_size = cached->dte_size;
11964 			ecb->dte_alignment = cached->dte_alignment;
11965 		}
11966 
11967 		return (ecb);
11968 	}
11969 
11970 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11971 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11972 			dtrace_ecb_destroy(ecb);
11973 			return (NULL);
11974 		}
11975 	}
11976 
11977 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11978 		dtrace_ecb_destroy(ecb);
11979 		return (NULL);
11980 	}
11981 
11982 	return (dtrace_ecb_create_cache = ecb);
11983 }
11984 
11985 static int
11986 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11987 {
11988 	dtrace_ecb_t *ecb;
11989 	dtrace_enabling_t *enab = arg;
11990 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11991 
11992 	ASSERT(state != NULL);
11993 
11994 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11995 		/*
11996 		 * This probe was created in a generation for which this
11997 		 * enabling has previously created ECBs; we don't want to
11998 		 * enable it again, so just kick out.
11999 		 */
12000 		return (DTRACE_MATCH_NEXT);
12001 	}
12002 
12003 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
12004 		return (DTRACE_MATCH_DONE);
12005 
12006 	dtrace_ecb_enable(ecb);
12007 	return (DTRACE_MATCH_NEXT);
12008 }
12009 
12010 static dtrace_ecb_t *
12011 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
12012 {
12013 	dtrace_ecb_t *ecb;
12014 
12015 	ASSERT(MUTEX_HELD(&dtrace_lock));
12016 
12017 	if (id == 0 || id > state->dts_necbs)
12018 		return (NULL);
12019 
12020 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12021 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12022 
12023 	return (state->dts_ecbs[id - 1]);
12024 }
12025 
12026 static dtrace_aggregation_t *
12027 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12028 {
12029 	dtrace_aggregation_t *agg;
12030 
12031 	ASSERT(MUTEX_HELD(&dtrace_lock));
12032 
12033 	if (id == 0 || id > state->dts_naggregations)
12034 		return (NULL);
12035 
12036 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12037 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12038 	    agg->dtag_id == id);
12039 
12040 	return (state->dts_aggregations[id - 1]);
12041 }
12042 
12043 /*
12044  * DTrace Buffer Functions
12045  *
12046  * The following functions manipulate DTrace buffers.  Most of these functions
12047  * are called in the context of establishing or processing consumer state;
12048  * exceptions are explicitly noted.
12049  */
12050 
12051 /*
12052  * Note:  called from cross call context.  This function switches the two
12053  * buffers on a given CPU.  The atomicity of this operation is assured by
12054  * disabling interrupts while the actual switch takes place; the disabling of
12055  * interrupts serializes the execution with any execution of dtrace_probe() on
12056  * the same CPU.
12057  */
12058 static void
12059 dtrace_buffer_switch(dtrace_buffer_t *buf)
12060 {
12061 	caddr_t tomax = buf->dtb_tomax;
12062 	caddr_t xamot = buf->dtb_xamot;
12063 	dtrace_icookie_t cookie;
12064 	hrtime_t now;
12065 
12066 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12067 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12068 
12069 	cookie = dtrace_interrupt_disable();
12070 	now = dtrace_gethrtime();
12071 	buf->dtb_tomax = xamot;
12072 	buf->dtb_xamot = tomax;
12073 	buf->dtb_xamot_drops = buf->dtb_drops;
12074 	buf->dtb_xamot_offset = buf->dtb_offset;
12075 	buf->dtb_xamot_errors = buf->dtb_errors;
12076 	buf->dtb_xamot_flags = buf->dtb_flags;
12077 	buf->dtb_offset = 0;
12078 	buf->dtb_drops = 0;
12079 	buf->dtb_errors = 0;
12080 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12081 	buf->dtb_interval = now - buf->dtb_switched;
12082 	buf->dtb_switched = now;
12083 	dtrace_interrupt_enable(cookie);
12084 }
12085 
12086 /*
12087  * Note:  called from cross call context.  This function activates a buffer
12088  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12089  * is guaranteed by the disabling of interrupts.
12090  */
12091 static void
12092 dtrace_buffer_activate(dtrace_state_t *state)
12093 {
12094 	dtrace_buffer_t *buf;
12095 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12096 
12097 	buf = &state->dts_buffer[curcpu];
12098 
12099 	if (buf->dtb_tomax != NULL) {
12100 		/*
12101 		 * We might like to assert that the buffer is marked inactive,
12102 		 * but this isn't necessarily true:  the buffer for the CPU
12103 		 * that processes the BEGIN probe has its buffer activated
12104 		 * manually.  In this case, we take the (harmless) action
12105 		 * re-clearing the bit INACTIVE bit.
12106 		 */
12107 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12108 	}
12109 
12110 	dtrace_interrupt_enable(cookie);
12111 }
12112 
12113 #ifdef __FreeBSD__
12114 /*
12115  * Activate the specified per-CPU buffer.  This is used instead of
12116  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12117  * activating anonymous state.
12118  */
12119 static void
12120 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12121 {
12122 
12123 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12124 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12125 }
12126 #endif
12127 
12128 static int
12129 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12130     processorid_t cpu, int *factor)
12131 {
12132 #ifdef illumos
12133 	cpu_t *cp;
12134 #endif
12135 	dtrace_buffer_t *buf;
12136 	int allocated = 0, desired = 0;
12137 
12138 #ifdef illumos
12139 	ASSERT(MUTEX_HELD(&cpu_lock));
12140 	ASSERT(MUTEX_HELD(&dtrace_lock));
12141 
12142 	*factor = 1;
12143 
12144 	if (size > dtrace_nonroot_maxsize &&
12145 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12146 		return (EFBIG);
12147 
12148 	cp = cpu_list;
12149 
12150 	do {
12151 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12152 			continue;
12153 
12154 		buf = &bufs[cp->cpu_id];
12155 
12156 		/*
12157 		 * If there is already a buffer allocated for this CPU, it
12158 		 * is only possible that this is a DR event.  In this case,
12159 		 */
12160 		if (buf->dtb_tomax != NULL) {
12161 			ASSERT(buf->dtb_size == size);
12162 			continue;
12163 		}
12164 
12165 		ASSERT(buf->dtb_xamot == NULL);
12166 
12167 		if ((buf->dtb_tomax = kmem_zalloc(size,
12168 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12169 			goto err;
12170 
12171 		buf->dtb_size = size;
12172 		buf->dtb_flags = flags;
12173 		buf->dtb_offset = 0;
12174 		buf->dtb_drops = 0;
12175 
12176 		if (flags & DTRACEBUF_NOSWITCH)
12177 			continue;
12178 
12179 		if ((buf->dtb_xamot = kmem_zalloc(size,
12180 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12181 			goto err;
12182 	} while ((cp = cp->cpu_next) != cpu_list);
12183 
12184 	return (0);
12185 
12186 err:
12187 	cp = cpu_list;
12188 
12189 	do {
12190 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12191 			continue;
12192 
12193 		buf = &bufs[cp->cpu_id];
12194 		desired += 2;
12195 
12196 		if (buf->dtb_xamot != NULL) {
12197 			ASSERT(buf->dtb_tomax != NULL);
12198 			ASSERT(buf->dtb_size == size);
12199 			kmem_free(buf->dtb_xamot, size);
12200 			allocated++;
12201 		}
12202 
12203 		if (buf->dtb_tomax != NULL) {
12204 			ASSERT(buf->dtb_size == size);
12205 			kmem_free(buf->dtb_tomax, size);
12206 			allocated++;
12207 		}
12208 
12209 		buf->dtb_tomax = NULL;
12210 		buf->dtb_xamot = NULL;
12211 		buf->dtb_size = 0;
12212 	} while ((cp = cp->cpu_next) != cpu_list);
12213 #else
12214 	int i;
12215 
12216 	*factor = 1;
12217 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12218     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12219 	/*
12220 	 * FreeBSD isn't good at limiting the amount of memory we
12221 	 * ask to malloc, so let's place a limit here before trying
12222 	 * to do something that might well end in tears at bedtime.
12223 	 */
12224 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12225 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12226 		return (ENOMEM);
12227 #endif
12228 
12229 	ASSERT(MUTEX_HELD(&dtrace_lock));
12230 	CPU_FOREACH(i) {
12231 		if (cpu != DTRACE_CPUALL && cpu != i)
12232 			continue;
12233 
12234 		buf = &bufs[i];
12235 
12236 		/*
12237 		 * If there is already a buffer allocated for this CPU, it
12238 		 * is only possible that this is a DR event.  In this case,
12239 		 * the buffer size must match our specified size.
12240 		 */
12241 		if (buf->dtb_tomax != NULL) {
12242 			ASSERT(buf->dtb_size == size);
12243 			continue;
12244 		}
12245 
12246 		ASSERT(buf->dtb_xamot == NULL);
12247 
12248 		if ((buf->dtb_tomax = kmem_zalloc(size,
12249 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12250 			goto err;
12251 
12252 		buf->dtb_size = size;
12253 		buf->dtb_flags = flags;
12254 		buf->dtb_offset = 0;
12255 		buf->dtb_drops = 0;
12256 
12257 		if (flags & DTRACEBUF_NOSWITCH)
12258 			continue;
12259 
12260 		if ((buf->dtb_xamot = kmem_zalloc(size,
12261 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12262 			goto err;
12263 	}
12264 
12265 	return (0);
12266 
12267 err:
12268 	/*
12269 	 * Error allocating memory, so free the buffers that were
12270 	 * allocated before the failed allocation.
12271 	 */
12272 	CPU_FOREACH(i) {
12273 		if (cpu != DTRACE_CPUALL && cpu != i)
12274 			continue;
12275 
12276 		buf = &bufs[i];
12277 		desired += 2;
12278 
12279 		if (buf->dtb_xamot != NULL) {
12280 			ASSERT(buf->dtb_tomax != NULL);
12281 			ASSERT(buf->dtb_size == size);
12282 			kmem_free(buf->dtb_xamot, size);
12283 			allocated++;
12284 		}
12285 
12286 		if (buf->dtb_tomax != NULL) {
12287 			ASSERT(buf->dtb_size == size);
12288 			kmem_free(buf->dtb_tomax, size);
12289 			allocated++;
12290 		}
12291 
12292 		buf->dtb_tomax = NULL;
12293 		buf->dtb_xamot = NULL;
12294 		buf->dtb_size = 0;
12295 
12296 	}
12297 #endif
12298 	*factor = desired / (allocated > 0 ? allocated : 1);
12299 
12300 	return (ENOMEM);
12301 }
12302 
12303 /*
12304  * Note:  called from probe context.  This function just increments the drop
12305  * count on a buffer.  It has been made a function to allow for the
12306  * possibility of understanding the source of mysterious drop counts.  (A
12307  * problem for which one may be particularly disappointed that DTrace cannot
12308  * be used to understand DTrace.)
12309  */
12310 static void
12311 dtrace_buffer_drop(dtrace_buffer_t *buf)
12312 {
12313 	buf->dtb_drops++;
12314 }
12315 
12316 /*
12317  * Note:  called from probe context.  This function is called to reserve space
12318  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12319  * mstate.  Returns the new offset in the buffer, or a negative value if an
12320  * error has occurred.
12321  */
12322 static ssize_t
12323 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12324     dtrace_state_t *state, dtrace_mstate_t *mstate)
12325 {
12326 	ssize_t offs = buf->dtb_offset, soffs;
12327 	intptr_t woffs;
12328 	caddr_t tomax;
12329 	size_t total;
12330 
12331 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12332 		return (-1);
12333 
12334 	if ((tomax = buf->dtb_tomax) == NULL) {
12335 		dtrace_buffer_drop(buf);
12336 		return (-1);
12337 	}
12338 
12339 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12340 		while (offs & (align - 1)) {
12341 			/*
12342 			 * Assert that our alignment is off by a number which
12343 			 * is itself sizeof (uint32_t) aligned.
12344 			 */
12345 			ASSERT(!((align - (offs & (align - 1))) &
12346 			    (sizeof (uint32_t) - 1)));
12347 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12348 			offs += sizeof (uint32_t);
12349 		}
12350 
12351 		if ((soffs = offs + needed) > buf->dtb_size) {
12352 			dtrace_buffer_drop(buf);
12353 			return (-1);
12354 		}
12355 
12356 		if (mstate == NULL)
12357 			return (offs);
12358 
12359 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12360 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12361 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12362 
12363 		return (offs);
12364 	}
12365 
12366 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12367 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12368 		    (buf->dtb_flags & DTRACEBUF_FULL))
12369 			return (-1);
12370 		goto out;
12371 	}
12372 
12373 	total = needed + (offs & (align - 1));
12374 
12375 	/*
12376 	 * For a ring buffer, life is quite a bit more complicated.  Before
12377 	 * we can store any padding, we need to adjust our wrapping offset.
12378 	 * (If we've never before wrapped or we're not about to, no adjustment
12379 	 * is required.)
12380 	 */
12381 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12382 	    offs + total > buf->dtb_size) {
12383 		woffs = buf->dtb_xamot_offset;
12384 
12385 		if (offs + total > buf->dtb_size) {
12386 			/*
12387 			 * We can't fit in the end of the buffer.  First, a
12388 			 * sanity check that we can fit in the buffer at all.
12389 			 */
12390 			if (total > buf->dtb_size) {
12391 				dtrace_buffer_drop(buf);
12392 				return (-1);
12393 			}
12394 
12395 			/*
12396 			 * We're going to be storing at the top of the buffer,
12397 			 * so now we need to deal with the wrapped offset.  We
12398 			 * only reset our wrapped offset to 0 if it is
12399 			 * currently greater than the current offset.  If it
12400 			 * is less than the current offset, it is because a
12401 			 * previous allocation induced a wrap -- but the
12402 			 * allocation didn't subsequently take the space due
12403 			 * to an error or false predicate evaluation.  In this
12404 			 * case, we'll just leave the wrapped offset alone: if
12405 			 * the wrapped offset hasn't been advanced far enough
12406 			 * for this allocation, it will be adjusted in the
12407 			 * lower loop.
12408 			 */
12409 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12410 				if (woffs >= offs)
12411 					woffs = 0;
12412 			} else {
12413 				woffs = 0;
12414 			}
12415 
12416 			/*
12417 			 * Now we know that we're going to be storing to the
12418 			 * top of the buffer and that there is room for us
12419 			 * there.  We need to clear the buffer from the current
12420 			 * offset to the end (there may be old gunk there).
12421 			 */
12422 			while (offs < buf->dtb_size)
12423 				tomax[offs++] = 0;
12424 
12425 			/*
12426 			 * We need to set our offset to zero.  And because we
12427 			 * are wrapping, we need to set the bit indicating as
12428 			 * much.  We can also adjust our needed space back
12429 			 * down to the space required by the ECB -- we know
12430 			 * that the top of the buffer is aligned.
12431 			 */
12432 			offs = 0;
12433 			total = needed;
12434 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12435 		} else {
12436 			/*
12437 			 * There is room for us in the buffer, so we simply
12438 			 * need to check the wrapped offset.
12439 			 */
12440 			if (woffs < offs) {
12441 				/*
12442 				 * The wrapped offset is less than the offset.
12443 				 * This can happen if we allocated buffer space
12444 				 * that induced a wrap, but then we didn't
12445 				 * subsequently take the space due to an error
12446 				 * or false predicate evaluation.  This is
12447 				 * okay; we know that _this_ allocation isn't
12448 				 * going to induce a wrap.  We still can't
12449 				 * reset the wrapped offset to be zero,
12450 				 * however: the space may have been trashed in
12451 				 * the previous failed probe attempt.  But at
12452 				 * least the wrapped offset doesn't need to
12453 				 * be adjusted at all...
12454 				 */
12455 				goto out;
12456 			}
12457 		}
12458 
12459 		while (offs + total > woffs) {
12460 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12461 			size_t size;
12462 
12463 			if (epid == DTRACE_EPIDNONE) {
12464 				size = sizeof (uint32_t);
12465 			} else {
12466 				ASSERT3U(epid, <=, state->dts_necbs);
12467 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12468 
12469 				size = state->dts_ecbs[epid - 1]->dte_size;
12470 			}
12471 
12472 			ASSERT(woffs + size <= buf->dtb_size);
12473 			ASSERT(size != 0);
12474 
12475 			if (woffs + size == buf->dtb_size) {
12476 				/*
12477 				 * We've reached the end of the buffer; we want
12478 				 * to set the wrapped offset to 0 and break
12479 				 * out.  However, if the offs is 0, then we're
12480 				 * in a strange edge-condition:  the amount of
12481 				 * space that we want to reserve plus the size
12482 				 * of the record that we're overwriting is
12483 				 * greater than the size of the buffer.  This
12484 				 * is problematic because if we reserve the
12485 				 * space but subsequently don't consume it (due
12486 				 * to a failed predicate or error) the wrapped
12487 				 * offset will be 0 -- yet the EPID at offset 0
12488 				 * will not be committed.  This situation is
12489 				 * relatively easy to deal with:  if we're in
12490 				 * this case, the buffer is indistinguishable
12491 				 * from one that hasn't wrapped; we need only
12492 				 * finish the job by clearing the wrapped bit,
12493 				 * explicitly setting the offset to be 0, and
12494 				 * zero'ing out the old data in the buffer.
12495 				 */
12496 				if (offs == 0) {
12497 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12498 					buf->dtb_offset = 0;
12499 					woffs = total;
12500 
12501 					while (woffs < buf->dtb_size)
12502 						tomax[woffs++] = 0;
12503 				}
12504 
12505 				woffs = 0;
12506 				break;
12507 			}
12508 
12509 			woffs += size;
12510 		}
12511 
12512 		/*
12513 		 * We have a wrapped offset.  It may be that the wrapped offset
12514 		 * has become zero -- that's okay.
12515 		 */
12516 		buf->dtb_xamot_offset = woffs;
12517 	}
12518 
12519 out:
12520 	/*
12521 	 * Now we can plow the buffer with any necessary padding.
12522 	 */
12523 	while (offs & (align - 1)) {
12524 		/*
12525 		 * Assert that our alignment is off by a number which
12526 		 * is itself sizeof (uint32_t) aligned.
12527 		 */
12528 		ASSERT(!((align - (offs & (align - 1))) &
12529 		    (sizeof (uint32_t) - 1)));
12530 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12531 		offs += sizeof (uint32_t);
12532 	}
12533 
12534 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12535 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12536 			buf->dtb_flags |= DTRACEBUF_FULL;
12537 			return (-1);
12538 		}
12539 	}
12540 
12541 	if (mstate == NULL)
12542 		return (offs);
12543 
12544 	/*
12545 	 * For ring buffers and fill buffers, the scratch space is always
12546 	 * the inactive buffer.
12547 	 */
12548 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12549 	mstate->dtms_scratch_size = buf->dtb_size;
12550 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12551 
12552 	return (offs);
12553 }
12554 
12555 static void
12556 dtrace_buffer_polish(dtrace_buffer_t *buf)
12557 {
12558 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12559 	ASSERT(MUTEX_HELD(&dtrace_lock));
12560 
12561 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12562 		return;
12563 
12564 	/*
12565 	 * We need to polish the ring buffer.  There are three cases:
12566 	 *
12567 	 * - The first (and presumably most common) is that there is no gap
12568 	 *   between the buffer offset and the wrapped offset.  In this case,
12569 	 *   there is nothing in the buffer that isn't valid data; we can
12570 	 *   mark the buffer as polished and return.
12571 	 *
12572 	 * - The second (less common than the first but still more common
12573 	 *   than the third) is that there is a gap between the buffer offset
12574 	 *   and the wrapped offset, and the wrapped offset is larger than the
12575 	 *   buffer offset.  This can happen because of an alignment issue, or
12576 	 *   can happen because of a call to dtrace_buffer_reserve() that
12577 	 *   didn't subsequently consume the buffer space.  In this case,
12578 	 *   we need to zero the data from the buffer offset to the wrapped
12579 	 *   offset.
12580 	 *
12581 	 * - The third (and least common) is that there is a gap between the
12582 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12583 	 *   _less_ than the buffer offset.  This can only happen because a
12584 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12585 	 *   was not subsequently consumed.  In this case, we need to zero the
12586 	 *   space from the offset to the end of the buffer _and_ from the
12587 	 *   top of the buffer to the wrapped offset.
12588 	 */
12589 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12590 		bzero(buf->dtb_tomax + buf->dtb_offset,
12591 		    buf->dtb_xamot_offset - buf->dtb_offset);
12592 	}
12593 
12594 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12595 		bzero(buf->dtb_tomax + buf->dtb_offset,
12596 		    buf->dtb_size - buf->dtb_offset);
12597 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12598 	}
12599 }
12600 
12601 /*
12602  * This routine determines if data generated at the specified time has likely
12603  * been entirely consumed at user-level.  This routine is called to determine
12604  * if an ECB on a defunct probe (but for an active enabling) can be safely
12605  * disabled and destroyed.
12606  */
12607 static int
12608 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12609 {
12610 	int i;
12611 
12612 	CPU_FOREACH(i) {
12613 		dtrace_buffer_t *buf = &bufs[i];
12614 
12615 		if (buf->dtb_size == 0)
12616 			continue;
12617 
12618 		if (buf->dtb_flags & DTRACEBUF_RING)
12619 			return (0);
12620 
12621 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12622 			return (0);
12623 
12624 		if (buf->dtb_switched - buf->dtb_interval < when)
12625 			return (0);
12626 	}
12627 
12628 	return (1);
12629 }
12630 
12631 static void
12632 dtrace_buffer_free(dtrace_buffer_t *bufs)
12633 {
12634 	int i;
12635 
12636 	CPU_FOREACH(i) {
12637 		dtrace_buffer_t *buf = &bufs[i];
12638 
12639 		if (buf->dtb_tomax == NULL) {
12640 			ASSERT(buf->dtb_xamot == NULL);
12641 			ASSERT(buf->dtb_size == 0);
12642 			continue;
12643 		}
12644 
12645 		if (buf->dtb_xamot != NULL) {
12646 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12647 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12648 		}
12649 
12650 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12651 		buf->dtb_size = 0;
12652 		buf->dtb_tomax = NULL;
12653 		buf->dtb_xamot = NULL;
12654 	}
12655 }
12656 
12657 /*
12658  * DTrace Enabling Functions
12659  */
12660 static dtrace_enabling_t *
12661 dtrace_enabling_create(dtrace_vstate_t *vstate)
12662 {
12663 	dtrace_enabling_t *enab;
12664 
12665 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12666 	enab->dten_vstate = vstate;
12667 
12668 	return (enab);
12669 }
12670 
12671 static void
12672 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12673 {
12674 	dtrace_ecbdesc_t **ndesc;
12675 	size_t osize, nsize;
12676 
12677 	/*
12678 	 * We can't add to enablings after we've enabled them, or after we've
12679 	 * retained them.
12680 	 */
12681 	ASSERT(enab->dten_probegen == 0);
12682 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12683 
12684 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12685 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12686 		return;
12687 	}
12688 
12689 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12690 
12691 	if (enab->dten_maxdesc == 0) {
12692 		enab->dten_maxdesc = 1;
12693 	} else {
12694 		enab->dten_maxdesc <<= 1;
12695 	}
12696 
12697 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12698 
12699 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12700 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12701 	bcopy(enab->dten_desc, ndesc, osize);
12702 	if (enab->dten_desc != NULL)
12703 		kmem_free(enab->dten_desc, osize);
12704 
12705 	enab->dten_desc = ndesc;
12706 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12707 }
12708 
12709 static void
12710 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12711     dtrace_probedesc_t *pd)
12712 {
12713 	dtrace_ecbdesc_t *new;
12714 	dtrace_predicate_t *pred;
12715 	dtrace_actdesc_t *act;
12716 
12717 	/*
12718 	 * We're going to create a new ECB description that matches the
12719 	 * specified ECB in every way, but has the specified probe description.
12720 	 */
12721 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12722 
12723 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12724 		dtrace_predicate_hold(pred);
12725 
12726 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12727 		dtrace_actdesc_hold(act);
12728 
12729 	new->dted_action = ecb->dted_action;
12730 	new->dted_pred = ecb->dted_pred;
12731 	new->dted_probe = *pd;
12732 	new->dted_uarg = ecb->dted_uarg;
12733 
12734 	dtrace_enabling_add(enab, new);
12735 }
12736 
12737 static void
12738 dtrace_enabling_dump(dtrace_enabling_t *enab)
12739 {
12740 	int i;
12741 
12742 	for (i = 0; i < enab->dten_ndesc; i++) {
12743 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12744 
12745 #ifdef __FreeBSD__
12746 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12747 		    desc->dtpd_provider, desc->dtpd_mod,
12748 		    desc->dtpd_func, desc->dtpd_name);
12749 #else
12750 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12751 		    desc->dtpd_provider, desc->dtpd_mod,
12752 		    desc->dtpd_func, desc->dtpd_name);
12753 #endif
12754 	}
12755 }
12756 
12757 static void
12758 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12759 {
12760 	int i;
12761 	dtrace_ecbdesc_t *ep;
12762 	dtrace_vstate_t *vstate = enab->dten_vstate;
12763 
12764 	ASSERT(MUTEX_HELD(&dtrace_lock));
12765 
12766 	for (i = 0; i < enab->dten_ndesc; i++) {
12767 		dtrace_actdesc_t *act, *next;
12768 		dtrace_predicate_t *pred;
12769 
12770 		ep = enab->dten_desc[i];
12771 
12772 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12773 			dtrace_predicate_release(pred, vstate);
12774 
12775 		for (act = ep->dted_action; act != NULL; act = next) {
12776 			next = act->dtad_next;
12777 			dtrace_actdesc_release(act, vstate);
12778 		}
12779 
12780 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12781 	}
12782 
12783 	if (enab->dten_desc != NULL)
12784 		kmem_free(enab->dten_desc,
12785 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12786 
12787 	/*
12788 	 * If this was a retained enabling, decrement the dts_nretained count
12789 	 * and take it off of the dtrace_retained list.
12790 	 */
12791 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12792 	    dtrace_retained == enab) {
12793 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12794 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12795 		enab->dten_vstate->dtvs_state->dts_nretained--;
12796 		dtrace_retained_gen++;
12797 	}
12798 
12799 	if (enab->dten_prev == NULL) {
12800 		if (dtrace_retained == enab) {
12801 			dtrace_retained = enab->dten_next;
12802 
12803 			if (dtrace_retained != NULL)
12804 				dtrace_retained->dten_prev = NULL;
12805 		}
12806 	} else {
12807 		ASSERT(enab != dtrace_retained);
12808 		ASSERT(dtrace_retained != NULL);
12809 		enab->dten_prev->dten_next = enab->dten_next;
12810 	}
12811 
12812 	if (enab->dten_next != NULL) {
12813 		ASSERT(dtrace_retained != NULL);
12814 		enab->dten_next->dten_prev = enab->dten_prev;
12815 	}
12816 
12817 	kmem_free(enab, sizeof (dtrace_enabling_t));
12818 }
12819 
12820 static int
12821 dtrace_enabling_retain(dtrace_enabling_t *enab)
12822 {
12823 	dtrace_state_t *state;
12824 
12825 	ASSERT(MUTEX_HELD(&dtrace_lock));
12826 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12827 	ASSERT(enab->dten_vstate != NULL);
12828 
12829 	state = enab->dten_vstate->dtvs_state;
12830 	ASSERT(state != NULL);
12831 
12832 	/*
12833 	 * We only allow each state to retain dtrace_retain_max enablings.
12834 	 */
12835 	if (state->dts_nretained >= dtrace_retain_max)
12836 		return (ENOSPC);
12837 
12838 	state->dts_nretained++;
12839 	dtrace_retained_gen++;
12840 
12841 	if (dtrace_retained == NULL) {
12842 		dtrace_retained = enab;
12843 		return (0);
12844 	}
12845 
12846 	enab->dten_next = dtrace_retained;
12847 	dtrace_retained->dten_prev = enab;
12848 	dtrace_retained = enab;
12849 
12850 	return (0);
12851 }
12852 
12853 static int
12854 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12855     dtrace_probedesc_t *create)
12856 {
12857 	dtrace_enabling_t *new, *enab;
12858 	int found = 0, err = ENOENT;
12859 
12860 	ASSERT(MUTEX_HELD(&dtrace_lock));
12861 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12862 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12863 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12864 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12865 
12866 	new = dtrace_enabling_create(&state->dts_vstate);
12867 
12868 	/*
12869 	 * Iterate over all retained enablings, looking for enablings that
12870 	 * match the specified state.
12871 	 */
12872 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12873 		int i;
12874 
12875 		/*
12876 		 * dtvs_state can only be NULL for helper enablings -- and
12877 		 * helper enablings can't be retained.
12878 		 */
12879 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12880 
12881 		if (enab->dten_vstate->dtvs_state != state)
12882 			continue;
12883 
12884 		/*
12885 		 * Now iterate over each probe description; we're looking for
12886 		 * an exact match to the specified probe description.
12887 		 */
12888 		for (i = 0; i < enab->dten_ndesc; i++) {
12889 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12890 			dtrace_probedesc_t *pd = &ep->dted_probe;
12891 
12892 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12893 				continue;
12894 
12895 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12896 				continue;
12897 
12898 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12899 				continue;
12900 
12901 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12902 				continue;
12903 
12904 			/*
12905 			 * We have a winning probe!  Add it to our growing
12906 			 * enabling.
12907 			 */
12908 			found = 1;
12909 			dtrace_enabling_addlike(new, ep, create);
12910 		}
12911 	}
12912 
12913 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12914 		dtrace_enabling_destroy(new);
12915 		return (err);
12916 	}
12917 
12918 	return (0);
12919 }
12920 
12921 static void
12922 dtrace_enabling_retract(dtrace_state_t *state)
12923 {
12924 	dtrace_enabling_t *enab, *next;
12925 
12926 	ASSERT(MUTEX_HELD(&dtrace_lock));
12927 
12928 	/*
12929 	 * Iterate over all retained enablings, destroy the enablings retained
12930 	 * for the specified state.
12931 	 */
12932 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12933 		next = enab->dten_next;
12934 
12935 		/*
12936 		 * dtvs_state can only be NULL for helper enablings -- and
12937 		 * helper enablings can't be retained.
12938 		 */
12939 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12940 
12941 		if (enab->dten_vstate->dtvs_state == state) {
12942 			ASSERT(state->dts_nretained > 0);
12943 			dtrace_enabling_destroy(enab);
12944 		}
12945 	}
12946 
12947 	ASSERT(state->dts_nretained == 0);
12948 }
12949 
12950 static int
12951 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12952 {
12953 	int i = 0;
12954 	int matched = 0;
12955 
12956 	ASSERT(MUTEX_HELD(&cpu_lock));
12957 	ASSERT(MUTEX_HELD(&dtrace_lock));
12958 
12959 	for (i = 0; i < enab->dten_ndesc; i++) {
12960 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12961 
12962 		enab->dten_current = ep;
12963 		enab->dten_error = 0;
12964 
12965 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12966 
12967 		if (enab->dten_error != 0) {
12968 			/*
12969 			 * If we get an error half-way through enabling the
12970 			 * probes, we kick out -- perhaps with some number of
12971 			 * them enabled.  Leaving enabled probes enabled may
12972 			 * be slightly confusing for user-level, but we expect
12973 			 * that no one will attempt to actually drive on in
12974 			 * the face of such errors.  If this is an anonymous
12975 			 * enabling (indicated with a NULL nmatched pointer),
12976 			 * we cmn_err() a message.  We aren't expecting to
12977 			 * get such an error -- such as it can exist at all,
12978 			 * it would be a result of corrupted DOF in the driver
12979 			 * properties.
12980 			 */
12981 			if (nmatched == NULL) {
12982 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12983 				    "error on %p: %d", (void *)ep,
12984 				    enab->dten_error);
12985 			}
12986 
12987 			return (enab->dten_error);
12988 		}
12989 	}
12990 
12991 	enab->dten_probegen = dtrace_probegen;
12992 	if (nmatched != NULL)
12993 		*nmatched = matched;
12994 
12995 	return (0);
12996 }
12997 
12998 static void
12999 dtrace_enabling_matchall_task(void *args __unused)
13000 {
13001 	dtrace_enabling_matchall();
13002 }
13003 
13004 static void
13005 dtrace_enabling_matchall(void)
13006 {
13007 	dtrace_enabling_t *enab;
13008 
13009 	mutex_enter(&cpu_lock);
13010 	mutex_enter(&dtrace_lock);
13011 
13012 	/*
13013 	 * Iterate over all retained enablings to see if any probes match
13014 	 * against them.  We only perform this operation on enablings for which
13015 	 * we have sufficient permissions by virtue of being in the global zone
13016 	 * or in the same zone as the DTrace client.  Because we can be called
13017 	 * after dtrace_detach() has been called, we cannot assert that there
13018 	 * are retained enablings.  We can safely load from dtrace_retained,
13019 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
13020 	 * block pending our completion.
13021 	 */
13022 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13023 #ifdef illumos
13024 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
13025 
13026 		if (INGLOBALZONE(curproc) ||
13027 		    cr != NULL && getzoneid() == crgetzoneid(cr))
13028 #endif
13029 			(void) dtrace_enabling_match(enab, NULL);
13030 	}
13031 
13032 	mutex_exit(&dtrace_lock);
13033 	mutex_exit(&cpu_lock);
13034 }
13035 
13036 /*
13037  * If an enabling is to be enabled without having matched probes (that is, if
13038  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13039  * enabling must be _primed_ by creating an ECB for every ECB description.
13040  * This must be done to assure that we know the number of speculations, the
13041  * number of aggregations, the minimum buffer size needed, etc. before we
13042  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13043  * enabling any probes, we create ECBs for every ECB decription, but with a
13044  * NULL probe -- which is exactly what this function does.
13045  */
13046 static void
13047 dtrace_enabling_prime(dtrace_state_t *state)
13048 {
13049 	dtrace_enabling_t *enab;
13050 	int i;
13051 
13052 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13053 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13054 
13055 		if (enab->dten_vstate->dtvs_state != state)
13056 			continue;
13057 
13058 		/*
13059 		 * We don't want to prime an enabling more than once, lest
13060 		 * we allow a malicious user to induce resource exhaustion.
13061 		 * (The ECBs that result from priming an enabling aren't
13062 		 * leaked -- but they also aren't deallocated until the
13063 		 * consumer state is destroyed.)
13064 		 */
13065 		if (enab->dten_primed)
13066 			continue;
13067 
13068 		for (i = 0; i < enab->dten_ndesc; i++) {
13069 			enab->dten_current = enab->dten_desc[i];
13070 			(void) dtrace_probe_enable(NULL, enab);
13071 		}
13072 
13073 		enab->dten_primed = 1;
13074 	}
13075 }
13076 
13077 /*
13078  * Called to indicate that probes should be provided due to retained
13079  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13080  * must take an initial lap through the enabling calling the dtps_provide()
13081  * entry point explicitly to allow for autocreated probes.
13082  */
13083 static void
13084 dtrace_enabling_provide(dtrace_provider_t *prv)
13085 {
13086 	int i, all = 0;
13087 	dtrace_probedesc_t desc;
13088 	dtrace_genid_t gen;
13089 
13090 	ASSERT(MUTEX_HELD(&dtrace_lock));
13091 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13092 
13093 	if (prv == NULL) {
13094 		all = 1;
13095 		prv = dtrace_provider;
13096 	}
13097 
13098 	do {
13099 		dtrace_enabling_t *enab;
13100 		void *parg = prv->dtpv_arg;
13101 
13102 retry:
13103 		gen = dtrace_retained_gen;
13104 		for (enab = dtrace_retained; enab != NULL;
13105 		    enab = enab->dten_next) {
13106 			for (i = 0; i < enab->dten_ndesc; i++) {
13107 				desc = enab->dten_desc[i]->dted_probe;
13108 				mutex_exit(&dtrace_lock);
13109 				prv->dtpv_pops.dtps_provide(parg, &desc);
13110 				mutex_enter(&dtrace_lock);
13111 				/*
13112 				 * Process the retained enablings again if
13113 				 * they have changed while we weren't holding
13114 				 * dtrace_lock.
13115 				 */
13116 				if (gen != dtrace_retained_gen)
13117 					goto retry;
13118 			}
13119 		}
13120 	} while (all && (prv = prv->dtpv_next) != NULL);
13121 
13122 	mutex_exit(&dtrace_lock);
13123 	dtrace_probe_provide(NULL, all ? NULL : prv);
13124 	mutex_enter(&dtrace_lock);
13125 }
13126 
13127 /*
13128  * Called to reap ECBs that are attached to probes from defunct providers.
13129  */
13130 static void
13131 dtrace_enabling_reap(void *args __unused)
13132 {
13133 	dtrace_provider_t *prov;
13134 	dtrace_probe_t *probe;
13135 	dtrace_ecb_t *ecb;
13136 	hrtime_t when;
13137 	int i;
13138 
13139 	mutex_enter(&cpu_lock);
13140 	mutex_enter(&dtrace_lock);
13141 
13142 	for (i = 0; i < dtrace_nprobes; i++) {
13143 		if ((probe = dtrace_probes[i]) == NULL)
13144 			continue;
13145 
13146 		if (probe->dtpr_ecb == NULL)
13147 			continue;
13148 
13149 		prov = probe->dtpr_provider;
13150 
13151 		if ((when = prov->dtpv_defunct) == 0)
13152 			continue;
13153 
13154 		/*
13155 		 * We have ECBs on a defunct provider:  we want to reap these
13156 		 * ECBs to allow the provider to unregister.  The destruction
13157 		 * of these ECBs must be done carefully:  if we destroy the ECB
13158 		 * and the consumer later wishes to consume an EPID that
13159 		 * corresponds to the destroyed ECB (and if the EPID metadata
13160 		 * has not been previously consumed), the consumer will abort
13161 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13162 		 * eliminate) the possibility of this, we will only destroy an
13163 		 * ECB for a defunct provider if, for the state that
13164 		 * corresponds to the ECB:
13165 		 *
13166 		 *  (a)	There is no speculative tracing (which can effectively
13167 		 *	cache an EPID for an arbitrary amount of time).
13168 		 *
13169 		 *  (b)	The principal buffers have been switched twice since the
13170 		 *	provider became defunct.
13171 		 *
13172 		 *  (c)	The aggregation buffers are of zero size or have been
13173 		 *	switched twice since the provider became defunct.
13174 		 *
13175 		 * We use dts_speculates to determine (a) and call a function
13176 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13177 		 * that as soon as we've been unable to destroy one of the ECBs
13178 		 * associated with the probe, we quit trying -- reaping is only
13179 		 * fruitful in as much as we can destroy all ECBs associated
13180 		 * with the defunct provider's probes.
13181 		 */
13182 		while ((ecb = probe->dtpr_ecb) != NULL) {
13183 			dtrace_state_t *state = ecb->dte_state;
13184 			dtrace_buffer_t *buf = state->dts_buffer;
13185 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13186 
13187 			if (state->dts_speculates)
13188 				break;
13189 
13190 			if (!dtrace_buffer_consumed(buf, when))
13191 				break;
13192 
13193 			if (!dtrace_buffer_consumed(aggbuf, when))
13194 				break;
13195 
13196 			dtrace_ecb_disable(ecb);
13197 			ASSERT(probe->dtpr_ecb != ecb);
13198 			dtrace_ecb_destroy(ecb);
13199 		}
13200 	}
13201 
13202 	mutex_exit(&dtrace_lock);
13203 	mutex_exit(&cpu_lock);
13204 }
13205 
13206 /*
13207  * DTrace DOF Functions
13208  */
13209 /*ARGSUSED*/
13210 static void
13211 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13212 {
13213 	if (dtrace_err_verbose)
13214 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13215 
13216 #ifdef DTRACE_ERRDEBUG
13217 	dtrace_errdebug(str);
13218 #endif
13219 }
13220 
13221 /*
13222  * Create DOF out of a currently enabled state.  Right now, we only create
13223  * DOF containing the run-time options -- but this could be expanded to create
13224  * complete DOF representing the enabled state.
13225  */
13226 static dof_hdr_t *
13227 dtrace_dof_create(dtrace_state_t *state)
13228 {
13229 	dof_hdr_t *dof;
13230 	dof_sec_t *sec;
13231 	dof_optdesc_t *opt;
13232 	int i, len = sizeof (dof_hdr_t) +
13233 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13234 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13235 
13236 	ASSERT(MUTEX_HELD(&dtrace_lock));
13237 
13238 	dof = kmem_zalloc(len, KM_SLEEP);
13239 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13240 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13241 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13242 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13243 
13244 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13245 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13246 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13247 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13248 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13249 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13250 
13251 	dof->dofh_flags = 0;
13252 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13253 	dof->dofh_secsize = sizeof (dof_sec_t);
13254 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13255 	dof->dofh_secoff = sizeof (dof_hdr_t);
13256 	dof->dofh_loadsz = len;
13257 	dof->dofh_filesz = len;
13258 	dof->dofh_pad = 0;
13259 
13260 	/*
13261 	 * Fill in the option section header...
13262 	 */
13263 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13264 	sec->dofs_type = DOF_SECT_OPTDESC;
13265 	sec->dofs_align = sizeof (uint64_t);
13266 	sec->dofs_flags = DOF_SECF_LOAD;
13267 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13268 
13269 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13270 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13271 
13272 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13273 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13274 
13275 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13276 		opt[i].dofo_option = i;
13277 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13278 		opt[i].dofo_value = state->dts_options[i];
13279 	}
13280 
13281 	return (dof);
13282 }
13283 
13284 static dof_hdr_t *
13285 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13286 {
13287 	dof_hdr_t hdr, *dof;
13288 
13289 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13290 
13291 	/*
13292 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13293 	 */
13294 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13295 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13296 		*errp = EFAULT;
13297 		return (NULL);
13298 	}
13299 
13300 	/*
13301 	 * Now we'll allocate the entire DOF and copy it in -- provided
13302 	 * that the length isn't outrageous.
13303 	 */
13304 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13305 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13306 		*errp = E2BIG;
13307 		return (NULL);
13308 	}
13309 
13310 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13311 		dtrace_dof_error(&hdr, "invalid load size");
13312 		*errp = EINVAL;
13313 		return (NULL);
13314 	}
13315 
13316 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13317 
13318 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13319 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13320 		kmem_free(dof, hdr.dofh_loadsz);
13321 		*errp = EFAULT;
13322 		return (NULL);
13323 	}
13324 
13325 	return (dof);
13326 }
13327 
13328 #ifdef __FreeBSD__
13329 static dof_hdr_t *
13330 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13331 {
13332 	dof_hdr_t hdr, *dof;
13333 	struct thread *td;
13334 	size_t loadsz;
13335 
13336 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13337 
13338 	td = curthread;
13339 
13340 	/*
13341 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13342 	 */
13343 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13344 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13345 		*errp = EFAULT;
13346 		return (NULL);
13347 	}
13348 
13349 	/*
13350 	 * Now we'll allocate the entire DOF and copy it in -- provided
13351 	 * that the length isn't outrageous.
13352 	 */
13353 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13354 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13355 		*errp = E2BIG;
13356 		return (NULL);
13357 	}
13358 	loadsz = (size_t)hdr.dofh_loadsz;
13359 
13360 	if (loadsz < sizeof (hdr)) {
13361 		dtrace_dof_error(&hdr, "invalid load size");
13362 		*errp = EINVAL;
13363 		return (NULL);
13364 	}
13365 
13366 	dof = kmem_alloc(loadsz, KM_SLEEP);
13367 
13368 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13369 	    dof->dofh_loadsz != loadsz) {
13370 		kmem_free(dof, hdr.dofh_loadsz);
13371 		*errp = EFAULT;
13372 		return (NULL);
13373 	}
13374 
13375 	return (dof);
13376 }
13377 
13378 static __inline uchar_t
13379 dtrace_dof_char(char c)
13380 {
13381 
13382 	switch (c) {
13383 	case '0':
13384 	case '1':
13385 	case '2':
13386 	case '3':
13387 	case '4':
13388 	case '5':
13389 	case '6':
13390 	case '7':
13391 	case '8':
13392 	case '9':
13393 		return (c - '0');
13394 	case 'A':
13395 	case 'B':
13396 	case 'C':
13397 	case 'D':
13398 	case 'E':
13399 	case 'F':
13400 		return (c - 'A' + 10);
13401 	case 'a':
13402 	case 'b':
13403 	case 'c':
13404 	case 'd':
13405 	case 'e':
13406 	case 'f':
13407 		return (c - 'a' + 10);
13408 	}
13409 	/* Should not reach here. */
13410 	return (UCHAR_MAX);
13411 }
13412 #endif /* __FreeBSD__ */
13413 
13414 static dof_hdr_t *
13415 dtrace_dof_property(const char *name)
13416 {
13417 #ifdef __FreeBSD__
13418 	uint8_t *dofbuf;
13419 	u_char *data, *eol;
13420 	caddr_t doffile;
13421 	size_t bytes, len, i;
13422 	dof_hdr_t *dof;
13423 	u_char c1, c2;
13424 
13425 	dof = NULL;
13426 
13427 	doffile = preload_search_by_type("dtrace_dof");
13428 	if (doffile == NULL)
13429 		return (NULL);
13430 
13431 	data = preload_fetch_addr(doffile);
13432 	len = preload_fetch_size(doffile);
13433 	for (;;) {
13434 		/* Look for the end of the line. All lines end in a newline. */
13435 		eol = memchr(data, '\n', len);
13436 		if (eol == NULL)
13437 			return (NULL);
13438 
13439 		if (strncmp(name, data, strlen(name)) == 0)
13440 			break;
13441 
13442 		eol++; /* skip past the newline */
13443 		len -= eol - data;
13444 		data = eol;
13445 	}
13446 
13447 	/* We've found the data corresponding to the specified key. */
13448 
13449 	data += strlen(name) + 1; /* skip past the '=' */
13450 	len = eol - data;
13451 	if (len % 2 != 0) {
13452 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13453 		goto doferr;
13454 	}
13455 	bytes = len / 2;
13456 	if (bytes < sizeof(dof_hdr_t)) {
13457 		dtrace_dof_error(NULL, "truncated header");
13458 		goto doferr;
13459 	}
13460 
13461 	/*
13462 	 * Each byte is represented by the two ASCII characters in its hex
13463 	 * representation.
13464 	 */
13465 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13466 	for (i = 0; i < bytes; i++) {
13467 		c1 = dtrace_dof_char(data[i * 2]);
13468 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13469 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13470 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13471 			goto doferr;
13472 		}
13473 		dofbuf[i] = c1 * 16 + c2;
13474 	}
13475 
13476 	dof = (dof_hdr_t *)dofbuf;
13477 	if (bytes < dof->dofh_loadsz) {
13478 		dtrace_dof_error(NULL, "truncated DOF");
13479 		goto doferr;
13480 	}
13481 
13482 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13483 		dtrace_dof_error(NULL, "oversized DOF");
13484 		goto doferr;
13485 	}
13486 
13487 	return (dof);
13488 
13489 doferr:
13490 	free(dof, M_SOLARIS);
13491 	return (NULL);
13492 #else /* __FreeBSD__ */
13493 	uchar_t *buf;
13494 	uint64_t loadsz;
13495 	unsigned int len, i;
13496 	dof_hdr_t *dof;
13497 
13498 	/*
13499 	 * Unfortunately, array of values in .conf files are always (and
13500 	 * only) interpreted to be integer arrays.  We must read our DOF
13501 	 * as an integer array, and then squeeze it into a byte array.
13502 	 */
13503 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13504 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13505 		return (NULL);
13506 
13507 	for (i = 0; i < len; i++)
13508 		buf[i] = (uchar_t)(((int *)buf)[i]);
13509 
13510 	if (len < sizeof (dof_hdr_t)) {
13511 		ddi_prop_free(buf);
13512 		dtrace_dof_error(NULL, "truncated header");
13513 		return (NULL);
13514 	}
13515 
13516 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13517 		ddi_prop_free(buf);
13518 		dtrace_dof_error(NULL, "truncated DOF");
13519 		return (NULL);
13520 	}
13521 
13522 	if (loadsz >= dtrace_dof_maxsize) {
13523 		ddi_prop_free(buf);
13524 		dtrace_dof_error(NULL, "oversized DOF");
13525 		return (NULL);
13526 	}
13527 
13528 	dof = kmem_alloc(loadsz, KM_SLEEP);
13529 	bcopy(buf, dof, loadsz);
13530 	ddi_prop_free(buf);
13531 
13532 	return (dof);
13533 #endif /* !__FreeBSD__ */
13534 }
13535 
13536 static void
13537 dtrace_dof_destroy(dof_hdr_t *dof)
13538 {
13539 	kmem_free(dof, dof->dofh_loadsz);
13540 }
13541 
13542 /*
13543  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13544  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13545  * a type other than DOF_SECT_NONE is specified, the header is checked against
13546  * this type and NULL is returned if the types do not match.
13547  */
13548 static dof_sec_t *
13549 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13550 {
13551 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13552 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13553 
13554 	if (i >= dof->dofh_secnum) {
13555 		dtrace_dof_error(dof, "referenced section index is invalid");
13556 		return (NULL);
13557 	}
13558 
13559 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13560 		dtrace_dof_error(dof, "referenced section is not loadable");
13561 		return (NULL);
13562 	}
13563 
13564 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13565 		dtrace_dof_error(dof, "referenced section is the wrong type");
13566 		return (NULL);
13567 	}
13568 
13569 	return (sec);
13570 }
13571 
13572 static dtrace_probedesc_t *
13573 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13574 {
13575 	dof_probedesc_t *probe;
13576 	dof_sec_t *strtab;
13577 	uintptr_t daddr = (uintptr_t)dof;
13578 	uintptr_t str;
13579 	size_t size;
13580 
13581 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13582 		dtrace_dof_error(dof, "invalid probe section");
13583 		return (NULL);
13584 	}
13585 
13586 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13587 		dtrace_dof_error(dof, "bad alignment in probe description");
13588 		return (NULL);
13589 	}
13590 
13591 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13592 		dtrace_dof_error(dof, "truncated probe description");
13593 		return (NULL);
13594 	}
13595 
13596 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13597 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13598 
13599 	if (strtab == NULL)
13600 		return (NULL);
13601 
13602 	str = daddr + strtab->dofs_offset;
13603 	size = strtab->dofs_size;
13604 
13605 	if (probe->dofp_provider >= strtab->dofs_size) {
13606 		dtrace_dof_error(dof, "corrupt probe provider");
13607 		return (NULL);
13608 	}
13609 
13610 	(void) strncpy(desc->dtpd_provider,
13611 	    (char *)(str + probe->dofp_provider),
13612 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13613 
13614 	if (probe->dofp_mod >= strtab->dofs_size) {
13615 		dtrace_dof_error(dof, "corrupt probe module");
13616 		return (NULL);
13617 	}
13618 
13619 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13620 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13621 
13622 	if (probe->dofp_func >= strtab->dofs_size) {
13623 		dtrace_dof_error(dof, "corrupt probe function");
13624 		return (NULL);
13625 	}
13626 
13627 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13628 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13629 
13630 	if (probe->dofp_name >= strtab->dofs_size) {
13631 		dtrace_dof_error(dof, "corrupt probe name");
13632 		return (NULL);
13633 	}
13634 
13635 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13636 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13637 
13638 	return (desc);
13639 }
13640 
13641 static dtrace_difo_t *
13642 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13643     cred_t *cr)
13644 {
13645 	dtrace_difo_t *dp;
13646 	size_t ttl = 0;
13647 	dof_difohdr_t *dofd;
13648 	uintptr_t daddr = (uintptr_t)dof;
13649 	size_t max = dtrace_difo_maxsize;
13650 	int i, l, n;
13651 
13652 	static const struct {
13653 		int section;
13654 		int bufoffs;
13655 		int lenoffs;
13656 		int entsize;
13657 		int align;
13658 		const char *msg;
13659 	} difo[] = {
13660 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13661 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13662 		sizeof (dif_instr_t), "multiple DIF sections" },
13663 
13664 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13665 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13666 		sizeof (uint64_t), "multiple integer tables" },
13667 
13668 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13669 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13670 		sizeof (char), "multiple string tables" },
13671 
13672 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13673 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13674 		sizeof (uint_t), "multiple variable tables" },
13675 
13676 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13677 	};
13678 
13679 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13680 		dtrace_dof_error(dof, "invalid DIFO header section");
13681 		return (NULL);
13682 	}
13683 
13684 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13685 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13686 		return (NULL);
13687 	}
13688 
13689 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13690 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13691 		dtrace_dof_error(dof, "bad size in DIFO header");
13692 		return (NULL);
13693 	}
13694 
13695 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13696 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13697 
13698 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13699 	dp->dtdo_rtype = dofd->dofd_rtype;
13700 
13701 	for (l = 0; l < n; l++) {
13702 		dof_sec_t *subsec;
13703 		void **bufp;
13704 		uint32_t *lenp;
13705 
13706 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13707 		    dofd->dofd_links[l])) == NULL)
13708 			goto err; /* invalid section link */
13709 
13710 		if (ttl + subsec->dofs_size > max) {
13711 			dtrace_dof_error(dof, "exceeds maximum size");
13712 			goto err;
13713 		}
13714 
13715 		ttl += subsec->dofs_size;
13716 
13717 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13718 			if (subsec->dofs_type != difo[i].section)
13719 				continue;
13720 
13721 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13722 				dtrace_dof_error(dof, "section not loaded");
13723 				goto err;
13724 			}
13725 
13726 			if (subsec->dofs_align != difo[i].align) {
13727 				dtrace_dof_error(dof, "bad alignment");
13728 				goto err;
13729 			}
13730 
13731 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13732 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13733 
13734 			if (*bufp != NULL) {
13735 				dtrace_dof_error(dof, difo[i].msg);
13736 				goto err;
13737 			}
13738 
13739 			if (difo[i].entsize != subsec->dofs_entsize) {
13740 				dtrace_dof_error(dof, "entry size mismatch");
13741 				goto err;
13742 			}
13743 
13744 			if (subsec->dofs_entsize != 0 &&
13745 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13746 				dtrace_dof_error(dof, "corrupt entry size");
13747 				goto err;
13748 			}
13749 
13750 			*lenp = subsec->dofs_size;
13751 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13752 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13753 			    *bufp, subsec->dofs_size);
13754 
13755 			if (subsec->dofs_entsize != 0)
13756 				*lenp /= subsec->dofs_entsize;
13757 
13758 			break;
13759 		}
13760 
13761 		/*
13762 		 * If we encounter a loadable DIFO sub-section that is not
13763 		 * known to us, assume this is a broken program and fail.
13764 		 */
13765 		if (difo[i].section == DOF_SECT_NONE &&
13766 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13767 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13768 			goto err;
13769 		}
13770 	}
13771 
13772 	if (dp->dtdo_buf == NULL) {
13773 		/*
13774 		 * We can't have a DIF object without DIF text.
13775 		 */
13776 		dtrace_dof_error(dof, "missing DIF text");
13777 		goto err;
13778 	}
13779 
13780 	/*
13781 	 * Before we validate the DIF object, run through the variable table
13782 	 * looking for the strings -- if any of their size are under, we'll set
13783 	 * their size to be the system-wide default string size.  Note that
13784 	 * this should _not_ happen if the "strsize" option has been set --
13785 	 * in this case, the compiler should have set the size to reflect the
13786 	 * setting of the option.
13787 	 */
13788 	for (i = 0; i < dp->dtdo_varlen; i++) {
13789 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13790 		dtrace_diftype_t *t = &v->dtdv_type;
13791 
13792 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13793 			continue;
13794 
13795 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13796 			t->dtdt_size = dtrace_strsize_default;
13797 	}
13798 
13799 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13800 		goto err;
13801 
13802 	dtrace_difo_init(dp, vstate);
13803 	return (dp);
13804 
13805 err:
13806 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13807 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13808 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13809 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13810 
13811 	kmem_free(dp, sizeof (dtrace_difo_t));
13812 	return (NULL);
13813 }
13814 
13815 static dtrace_predicate_t *
13816 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13817     cred_t *cr)
13818 {
13819 	dtrace_difo_t *dp;
13820 
13821 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13822 		return (NULL);
13823 
13824 	return (dtrace_predicate_create(dp));
13825 }
13826 
13827 static dtrace_actdesc_t *
13828 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13829     cred_t *cr)
13830 {
13831 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13832 	dof_actdesc_t *desc;
13833 	dof_sec_t *difosec;
13834 	size_t offs;
13835 	uintptr_t daddr = (uintptr_t)dof;
13836 	uint64_t arg;
13837 	dtrace_actkind_t kind;
13838 
13839 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13840 		dtrace_dof_error(dof, "invalid action section");
13841 		return (NULL);
13842 	}
13843 
13844 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13845 		dtrace_dof_error(dof, "truncated action description");
13846 		return (NULL);
13847 	}
13848 
13849 	if (sec->dofs_align != sizeof (uint64_t)) {
13850 		dtrace_dof_error(dof, "bad alignment in action description");
13851 		return (NULL);
13852 	}
13853 
13854 	if (sec->dofs_size < sec->dofs_entsize) {
13855 		dtrace_dof_error(dof, "section entry size exceeds total size");
13856 		return (NULL);
13857 	}
13858 
13859 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13860 		dtrace_dof_error(dof, "bad entry size in action description");
13861 		return (NULL);
13862 	}
13863 
13864 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13865 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13866 		return (NULL);
13867 	}
13868 
13869 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13870 		desc = (dof_actdesc_t *)(daddr +
13871 		    (uintptr_t)sec->dofs_offset + offs);
13872 		kind = (dtrace_actkind_t)desc->dofa_kind;
13873 
13874 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13875 		    (kind != DTRACEACT_PRINTA ||
13876 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13877 		    (kind == DTRACEACT_DIFEXPR &&
13878 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13879 			dof_sec_t *strtab;
13880 			char *str, *fmt;
13881 			uint64_t i;
13882 
13883 			/*
13884 			 * The argument to these actions is an index into the
13885 			 * DOF string table.  For printf()-like actions, this
13886 			 * is the format string.  For print(), this is the
13887 			 * CTF type of the expression result.
13888 			 */
13889 			if ((strtab = dtrace_dof_sect(dof,
13890 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13891 				goto err;
13892 
13893 			str = (char *)((uintptr_t)dof +
13894 			    (uintptr_t)strtab->dofs_offset);
13895 
13896 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13897 				if (str[i] == '\0')
13898 					break;
13899 			}
13900 
13901 			if (i >= strtab->dofs_size) {
13902 				dtrace_dof_error(dof, "bogus format string");
13903 				goto err;
13904 			}
13905 
13906 			if (i == desc->dofa_arg) {
13907 				dtrace_dof_error(dof, "empty format string");
13908 				goto err;
13909 			}
13910 
13911 			i -= desc->dofa_arg;
13912 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13913 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13914 			arg = (uint64_t)(uintptr_t)fmt;
13915 		} else {
13916 			if (kind == DTRACEACT_PRINTA) {
13917 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13918 				arg = 0;
13919 			} else {
13920 				arg = desc->dofa_arg;
13921 			}
13922 		}
13923 
13924 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13925 		    desc->dofa_uarg, arg);
13926 
13927 		if (last != NULL) {
13928 			last->dtad_next = act;
13929 		} else {
13930 			first = act;
13931 		}
13932 
13933 		last = act;
13934 
13935 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13936 			continue;
13937 
13938 		if ((difosec = dtrace_dof_sect(dof,
13939 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13940 			goto err;
13941 
13942 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13943 
13944 		if (act->dtad_difo == NULL)
13945 			goto err;
13946 	}
13947 
13948 	ASSERT(first != NULL);
13949 	return (first);
13950 
13951 err:
13952 	for (act = first; act != NULL; act = next) {
13953 		next = act->dtad_next;
13954 		dtrace_actdesc_release(act, vstate);
13955 	}
13956 
13957 	return (NULL);
13958 }
13959 
13960 static dtrace_ecbdesc_t *
13961 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13962     cred_t *cr)
13963 {
13964 	dtrace_ecbdesc_t *ep;
13965 	dof_ecbdesc_t *ecb;
13966 	dtrace_probedesc_t *desc;
13967 	dtrace_predicate_t *pred = NULL;
13968 
13969 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13970 		dtrace_dof_error(dof, "truncated ECB description");
13971 		return (NULL);
13972 	}
13973 
13974 	if (sec->dofs_align != sizeof (uint64_t)) {
13975 		dtrace_dof_error(dof, "bad alignment in ECB description");
13976 		return (NULL);
13977 	}
13978 
13979 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13980 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13981 
13982 	if (sec == NULL)
13983 		return (NULL);
13984 
13985 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13986 	ep->dted_uarg = ecb->dofe_uarg;
13987 	desc = &ep->dted_probe;
13988 
13989 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13990 		goto err;
13991 
13992 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13993 		if ((sec = dtrace_dof_sect(dof,
13994 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13995 			goto err;
13996 
13997 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13998 			goto err;
13999 
14000 		ep->dted_pred.dtpdd_predicate = pred;
14001 	}
14002 
14003 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
14004 		if ((sec = dtrace_dof_sect(dof,
14005 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
14006 			goto err;
14007 
14008 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
14009 
14010 		if (ep->dted_action == NULL)
14011 			goto err;
14012 	}
14013 
14014 	return (ep);
14015 
14016 err:
14017 	if (pred != NULL)
14018 		dtrace_predicate_release(pred, vstate);
14019 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
14020 	return (NULL);
14021 }
14022 
14023 /*
14024  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
14025  * specified DOF.  SETX relocations are computed using 'ubase', the base load
14026  * address of the object containing the DOF, and DOFREL relocations are relative
14027  * to the relocation offset within the DOF.
14028  */
14029 static int
14030 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14031     uint64_t udaddr)
14032 {
14033 	uintptr_t daddr = (uintptr_t)dof;
14034 	uintptr_t ts_end;
14035 	dof_relohdr_t *dofr =
14036 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14037 	dof_sec_t *ss, *rs, *ts;
14038 	dof_relodesc_t *r;
14039 	uint_t i, n;
14040 
14041 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14042 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14043 		dtrace_dof_error(dof, "invalid relocation header");
14044 		return (-1);
14045 	}
14046 
14047 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14048 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14049 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14050 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14051 
14052 	if (ss == NULL || rs == NULL || ts == NULL)
14053 		return (-1); /* dtrace_dof_error() has been called already */
14054 
14055 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14056 	    rs->dofs_align != sizeof (uint64_t)) {
14057 		dtrace_dof_error(dof, "invalid relocation section");
14058 		return (-1);
14059 	}
14060 
14061 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14062 	n = rs->dofs_size / rs->dofs_entsize;
14063 
14064 	for (i = 0; i < n; i++) {
14065 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14066 
14067 		switch (r->dofr_type) {
14068 		case DOF_RELO_NONE:
14069 			break;
14070 		case DOF_RELO_SETX:
14071 		case DOF_RELO_DOFREL:
14072 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14073 			    sizeof (uint64_t) > ts->dofs_size) {
14074 				dtrace_dof_error(dof, "bad relocation offset");
14075 				return (-1);
14076 			}
14077 
14078 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14079 				dtrace_dof_error(dof, "bad relocation offset");
14080 				return (-1);
14081 			}
14082 
14083 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14084 				dtrace_dof_error(dof, "misaligned setx relo");
14085 				return (-1);
14086 			}
14087 
14088 			if (r->dofr_type == DOF_RELO_SETX)
14089 				*(uint64_t *)taddr += ubase;
14090 			else
14091 				*(uint64_t *)taddr +=
14092 				    udaddr + ts->dofs_offset + r->dofr_offset;
14093 			break;
14094 		default:
14095 			dtrace_dof_error(dof, "invalid relocation type");
14096 			return (-1);
14097 		}
14098 
14099 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14100 	}
14101 
14102 	return (0);
14103 }
14104 
14105 /*
14106  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14107  * header:  it should be at the front of a memory region that is at least
14108  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14109  * size.  It need not be validated in any other way.
14110  */
14111 static int
14112 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14113     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14114 {
14115 	uint64_t len = dof->dofh_loadsz, seclen;
14116 	uintptr_t daddr = (uintptr_t)dof;
14117 	dtrace_ecbdesc_t *ep;
14118 	dtrace_enabling_t *enab;
14119 	uint_t i;
14120 
14121 	ASSERT(MUTEX_HELD(&dtrace_lock));
14122 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14123 
14124 	/*
14125 	 * Check the DOF header identification bytes.  In addition to checking
14126 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14127 	 * we can use them later without fear of regressing existing binaries.
14128 	 */
14129 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14130 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14131 		dtrace_dof_error(dof, "DOF magic string mismatch");
14132 		return (-1);
14133 	}
14134 
14135 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14136 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14137 		dtrace_dof_error(dof, "DOF has invalid data model");
14138 		return (-1);
14139 	}
14140 
14141 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14142 		dtrace_dof_error(dof, "DOF encoding mismatch");
14143 		return (-1);
14144 	}
14145 
14146 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14147 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14148 		dtrace_dof_error(dof, "DOF version mismatch");
14149 		return (-1);
14150 	}
14151 
14152 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14153 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14154 		return (-1);
14155 	}
14156 
14157 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14158 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14159 		return (-1);
14160 	}
14161 
14162 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14163 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14164 		return (-1);
14165 	}
14166 
14167 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14168 		if (dof->dofh_ident[i] != 0) {
14169 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14170 			return (-1);
14171 		}
14172 	}
14173 
14174 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14175 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14176 		return (-1);
14177 	}
14178 
14179 	if (dof->dofh_secsize == 0) {
14180 		dtrace_dof_error(dof, "zero section header size");
14181 		return (-1);
14182 	}
14183 
14184 	/*
14185 	 * Check that the section headers don't exceed the amount of DOF
14186 	 * data.  Note that we cast the section size and number of sections
14187 	 * to uint64_t's to prevent possible overflow in the multiplication.
14188 	 */
14189 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14190 
14191 	if (dof->dofh_secoff > len || seclen > len ||
14192 	    dof->dofh_secoff + seclen > len) {
14193 		dtrace_dof_error(dof, "truncated section headers");
14194 		return (-1);
14195 	}
14196 
14197 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14198 		dtrace_dof_error(dof, "misaligned section headers");
14199 		return (-1);
14200 	}
14201 
14202 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14203 		dtrace_dof_error(dof, "misaligned section size");
14204 		return (-1);
14205 	}
14206 
14207 	/*
14208 	 * Take an initial pass through the section headers to be sure that
14209 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14210 	 * set, do not permit sections relating to providers, probes, or args.
14211 	 */
14212 	for (i = 0; i < dof->dofh_secnum; i++) {
14213 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14214 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14215 
14216 		if (noprobes) {
14217 			switch (sec->dofs_type) {
14218 			case DOF_SECT_PROVIDER:
14219 			case DOF_SECT_PROBES:
14220 			case DOF_SECT_PRARGS:
14221 			case DOF_SECT_PROFFS:
14222 				dtrace_dof_error(dof, "illegal sections "
14223 				    "for enabling");
14224 				return (-1);
14225 			}
14226 		}
14227 
14228 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14229 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14230 			dtrace_dof_error(dof, "loadable section with load "
14231 			    "flag unset");
14232 			return (-1);
14233 		}
14234 
14235 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14236 			continue; /* just ignore non-loadable sections */
14237 
14238 		if (!ISP2(sec->dofs_align)) {
14239 			dtrace_dof_error(dof, "bad section alignment");
14240 			return (-1);
14241 		}
14242 
14243 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14244 			dtrace_dof_error(dof, "misaligned section");
14245 			return (-1);
14246 		}
14247 
14248 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14249 		    sec->dofs_offset + sec->dofs_size > len) {
14250 			dtrace_dof_error(dof, "corrupt section header");
14251 			return (-1);
14252 		}
14253 
14254 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14255 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14256 			dtrace_dof_error(dof, "non-terminating string table");
14257 			return (-1);
14258 		}
14259 	}
14260 
14261 	/*
14262 	 * Take a second pass through the sections and locate and perform any
14263 	 * relocations that are present.  We do this after the first pass to
14264 	 * be sure that all sections have had their headers validated.
14265 	 */
14266 	for (i = 0; i < dof->dofh_secnum; i++) {
14267 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14268 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14269 
14270 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14271 			continue; /* skip sections that are not loadable */
14272 
14273 		switch (sec->dofs_type) {
14274 		case DOF_SECT_URELHDR:
14275 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14276 				return (-1);
14277 			break;
14278 		}
14279 	}
14280 
14281 	if ((enab = *enabp) == NULL)
14282 		enab = *enabp = dtrace_enabling_create(vstate);
14283 
14284 	for (i = 0; i < dof->dofh_secnum; i++) {
14285 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14286 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14287 
14288 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14289 			continue;
14290 
14291 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14292 			dtrace_enabling_destroy(enab);
14293 			*enabp = NULL;
14294 			return (-1);
14295 		}
14296 
14297 		dtrace_enabling_add(enab, ep);
14298 	}
14299 
14300 	return (0);
14301 }
14302 
14303 /*
14304  * Process DOF for any options.  This routine assumes that the DOF has been
14305  * at least processed by dtrace_dof_slurp().
14306  */
14307 static int
14308 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14309 {
14310 	int i, rval;
14311 	uint32_t entsize;
14312 	size_t offs;
14313 	dof_optdesc_t *desc;
14314 
14315 	for (i = 0; i < dof->dofh_secnum; i++) {
14316 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14317 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14318 
14319 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14320 			continue;
14321 
14322 		if (sec->dofs_align != sizeof (uint64_t)) {
14323 			dtrace_dof_error(dof, "bad alignment in "
14324 			    "option description");
14325 			return (EINVAL);
14326 		}
14327 
14328 		if ((entsize = sec->dofs_entsize) == 0) {
14329 			dtrace_dof_error(dof, "zeroed option entry size");
14330 			return (EINVAL);
14331 		}
14332 
14333 		if (entsize < sizeof (dof_optdesc_t)) {
14334 			dtrace_dof_error(dof, "bad option entry size");
14335 			return (EINVAL);
14336 		}
14337 
14338 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14339 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14340 			    (uintptr_t)sec->dofs_offset + offs);
14341 
14342 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14343 				dtrace_dof_error(dof, "non-zero option string");
14344 				return (EINVAL);
14345 			}
14346 
14347 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14348 				dtrace_dof_error(dof, "unset option");
14349 				return (EINVAL);
14350 			}
14351 
14352 			if ((rval = dtrace_state_option(state,
14353 			    desc->dofo_option, desc->dofo_value)) != 0) {
14354 				dtrace_dof_error(dof, "rejected option");
14355 				return (rval);
14356 			}
14357 		}
14358 	}
14359 
14360 	return (0);
14361 }
14362 
14363 /*
14364  * DTrace Consumer State Functions
14365  */
14366 static int
14367 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14368 {
14369 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14370 	void *base;
14371 	uintptr_t limit;
14372 	dtrace_dynvar_t *dvar, *next, *start;
14373 	int i;
14374 
14375 	ASSERT(MUTEX_HELD(&dtrace_lock));
14376 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14377 
14378 	bzero(dstate, sizeof (dtrace_dstate_t));
14379 
14380 	if ((dstate->dtds_chunksize = chunksize) == 0)
14381 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14382 
14383 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14384 
14385 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14386 		size = min;
14387 
14388 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14389 		return (ENOMEM);
14390 
14391 	dstate->dtds_size = size;
14392 	dstate->dtds_base = base;
14393 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14394 	bzero(dstate->dtds_percpu,
14395 	    (mp_maxid + 1) * sizeof (dtrace_dstate_percpu_t));
14396 
14397 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14398 
14399 	if (hashsize != 1 && (hashsize & 1))
14400 		hashsize--;
14401 
14402 	dstate->dtds_hashsize = hashsize;
14403 	dstate->dtds_hash = dstate->dtds_base;
14404 
14405 	/*
14406 	 * Set all of our hash buckets to point to the single sink, and (if
14407 	 * it hasn't already been set), set the sink's hash value to be the
14408 	 * sink sentinel value.  The sink is needed for dynamic variable
14409 	 * lookups to know that they have iterated over an entire, valid hash
14410 	 * chain.
14411 	 */
14412 	for (i = 0; i < hashsize; i++)
14413 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14414 
14415 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14416 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14417 
14418 	/*
14419 	 * Determine number of active CPUs.  Divide free list evenly among
14420 	 * active CPUs.
14421 	 */
14422 	start = (dtrace_dynvar_t *)
14423 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14424 	limit = (uintptr_t)base + size;
14425 
14426 	VERIFY((uintptr_t)start < limit);
14427 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14428 
14429 	maxper = (limit - (uintptr_t)start) / (mp_maxid + 1);
14430 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14431 
14432 	CPU_FOREACH(i) {
14433 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14434 
14435 		/*
14436 		 * If we don't even have enough chunks to make it once through
14437 		 * NCPUs, we're just going to allocate everything to the first
14438 		 * CPU.  And if we're on the last CPU, we're going to allocate
14439 		 * whatever is left over.  In either case, we set the limit to
14440 		 * be the limit of the dynamic variable space.
14441 		 */
14442 		if (maxper == 0 || i == mp_maxid) {
14443 			limit = (uintptr_t)base + size;
14444 			start = NULL;
14445 		} else {
14446 			limit = (uintptr_t)start + maxper;
14447 			start = (dtrace_dynvar_t *)limit;
14448 		}
14449 
14450 		VERIFY(limit <= (uintptr_t)base + size);
14451 
14452 		for (;;) {
14453 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14454 			    dstate->dtds_chunksize);
14455 
14456 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14457 				break;
14458 
14459 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14460 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14461 			dvar->dtdv_next = next;
14462 			dvar = next;
14463 		}
14464 
14465 		if (maxper == 0)
14466 			break;
14467 	}
14468 
14469 	return (0);
14470 }
14471 
14472 static void
14473 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14474 {
14475 	ASSERT(MUTEX_HELD(&cpu_lock));
14476 
14477 	if (dstate->dtds_base == NULL)
14478 		return;
14479 
14480 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14481 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14482 }
14483 
14484 static void
14485 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14486 {
14487 	/*
14488 	 * Logical XOR, where are you?
14489 	 */
14490 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14491 
14492 	if (vstate->dtvs_nglobals > 0) {
14493 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14494 		    sizeof (dtrace_statvar_t *));
14495 	}
14496 
14497 	if (vstate->dtvs_ntlocals > 0) {
14498 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14499 		    sizeof (dtrace_difv_t));
14500 	}
14501 
14502 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14503 
14504 	if (vstate->dtvs_nlocals > 0) {
14505 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14506 		    sizeof (dtrace_statvar_t *));
14507 	}
14508 }
14509 
14510 #ifdef illumos
14511 static void
14512 dtrace_state_clean(dtrace_state_t *state)
14513 {
14514 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14515 		return;
14516 
14517 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14518 	dtrace_speculation_clean(state);
14519 }
14520 
14521 static void
14522 dtrace_state_deadman(dtrace_state_t *state)
14523 {
14524 	hrtime_t now;
14525 
14526 	dtrace_sync();
14527 
14528 	now = dtrace_gethrtime();
14529 
14530 	if (state != dtrace_anon.dta_state &&
14531 	    now - state->dts_laststatus >= dtrace_deadman_user)
14532 		return;
14533 
14534 	/*
14535 	 * We must be sure that dts_alive never appears to be less than the
14536 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14537 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14538 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14539 	 * the new value.  This assures that dts_alive never appears to be
14540 	 * less than its true value, regardless of the order in which the
14541 	 * stores to the underlying storage are issued.
14542 	 */
14543 	state->dts_alive = INT64_MAX;
14544 	dtrace_membar_producer();
14545 	state->dts_alive = now;
14546 }
14547 #else	/* !illumos */
14548 static void
14549 dtrace_state_clean(void *arg)
14550 {
14551 	dtrace_state_t *state = arg;
14552 	dtrace_optval_t *opt = state->dts_options;
14553 
14554 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14555 		return;
14556 
14557 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14558 	dtrace_speculation_clean(state);
14559 
14560 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14561 	    dtrace_state_clean, state);
14562 }
14563 
14564 static void
14565 dtrace_state_deadman(void *arg)
14566 {
14567 	dtrace_state_t *state = arg;
14568 	hrtime_t now;
14569 
14570 	dtrace_sync();
14571 
14572 	dtrace_debug_output();
14573 
14574 	now = dtrace_gethrtime();
14575 
14576 	if (state != dtrace_anon.dta_state &&
14577 	    now - state->dts_laststatus >= dtrace_deadman_user)
14578 		return;
14579 
14580 	/*
14581 	 * We must be sure that dts_alive never appears to be less than the
14582 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14583 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14584 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14585 	 * the new value.  This assures that dts_alive never appears to be
14586 	 * less than its true value, regardless of the order in which the
14587 	 * stores to the underlying storage are issued.
14588 	 */
14589 	state->dts_alive = INT64_MAX;
14590 	dtrace_membar_producer();
14591 	state->dts_alive = now;
14592 
14593 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14594 	    dtrace_state_deadman, state);
14595 }
14596 #endif	/* illumos */
14597 
14598 static dtrace_state_t *
14599 #ifdef illumos
14600 dtrace_state_create(dev_t *devp, cred_t *cr)
14601 #else
14602 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14603 #endif
14604 {
14605 #ifdef illumos
14606 	minor_t minor;
14607 	major_t major;
14608 #else
14609 	cred_t *cr = NULL;
14610 	int m = 0;
14611 #endif
14612 	char c[30];
14613 	dtrace_state_t *state;
14614 	dtrace_optval_t *opt;
14615 	int bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t), i;
14616 	int cpu_it;
14617 
14618 	ASSERT(MUTEX_HELD(&dtrace_lock));
14619 	ASSERT(MUTEX_HELD(&cpu_lock));
14620 
14621 #ifdef illumos
14622 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14623 	    VM_BESTFIT | VM_SLEEP);
14624 
14625 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14626 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14627 		return (NULL);
14628 	}
14629 
14630 	state = ddi_get_soft_state(dtrace_softstate, minor);
14631 #else
14632 	if (dev != NULL) {
14633 		cr = dev->si_cred;
14634 		m = dev2unit(dev);
14635 	}
14636 
14637 	/* Allocate memory for the state. */
14638 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14639 #endif
14640 
14641 	state->dts_epid = DTRACE_EPIDNONE + 1;
14642 
14643 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14644 #ifdef illumos
14645 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14646 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14647 
14648 	if (devp != NULL) {
14649 		major = getemajor(*devp);
14650 	} else {
14651 		major = ddi_driver_major(dtrace_devi);
14652 	}
14653 
14654 	state->dts_dev = makedevice(major, minor);
14655 
14656 	if (devp != NULL)
14657 		*devp = state->dts_dev;
14658 #else
14659 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14660 	state->dts_dev = dev;
14661 #endif
14662 
14663 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14664 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14665 
14666 	/*
14667          * Allocate and initialise the per-process per-CPU random state.
14668 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14669          * assumed to be seeded at this point (if from Fortuna seed file).
14670 	 */
14671 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14672 	for (cpu_it = 1; cpu_it <= mp_maxid; cpu_it++) {
14673 		/*
14674 		 * Each CPU is assigned a 2^64 period, non-overlapping
14675 		 * subsequence.
14676 		 */
14677 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it - 1],
14678 		    state->dts_rstate[cpu_it]);
14679 	}
14680 
14681 #ifdef illumos
14682 	state->dts_cleaner = CYCLIC_NONE;
14683 	state->dts_deadman = CYCLIC_NONE;
14684 #else
14685 	callout_init(&state->dts_cleaner, 1);
14686 	callout_init(&state->dts_deadman, 1);
14687 #endif
14688 	state->dts_vstate.dtvs_state = state;
14689 
14690 	for (i = 0; i < DTRACEOPT_MAX; i++)
14691 		state->dts_options[i] = DTRACEOPT_UNSET;
14692 
14693 	/*
14694 	 * Set the default options.
14695 	 */
14696 	opt = state->dts_options;
14697 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14698 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14699 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14700 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14701 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14702 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14703 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14704 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14705 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14706 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14707 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14708 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14709 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14710 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14711 
14712 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14713 
14714 	/*
14715 	 * Depending on the user credentials, we set flag bits which alter probe
14716 	 * visibility or the amount of destructiveness allowed.  In the case of
14717 	 * actual anonymous tracing, or the possession of all privileges, all of
14718 	 * the normal checks are bypassed.
14719 	 */
14720 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14721 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14722 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14723 	} else {
14724 		/*
14725 		 * Set up the credentials for this instantiation.  We take a
14726 		 * hold on the credential to prevent it from disappearing on
14727 		 * us; this in turn prevents the zone_t referenced by this
14728 		 * credential from disappearing.  This means that we can
14729 		 * examine the credential and the zone from probe context.
14730 		 */
14731 		crhold(cr);
14732 		state->dts_cred.dcr_cred = cr;
14733 
14734 		/*
14735 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14736 		 * unlocks the use of variables like pid, zonename, etc.
14737 		 */
14738 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14739 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14740 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14741 		}
14742 
14743 		/*
14744 		 * dtrace_user allows use of syscall and profile providers.
14745 		 * If the user also has proc_owner and/or proc_zone, we
14746 		 * extend the scope to include additional visibility and
14747 		 * destructive power.
14748 		 */
14749 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14750 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14751 				state->dts_cred.dcr_visible |=
14752 				    DTRACE_CRV_ALLPROC;
14753 
14754 				state->dts_cred.dcr_action |=
14755 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14756 			}
14757 
14758 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14759 				state->dts_cred.dcr_visible |=
14760 				    DTRACE_CRV_ALLZONE;
14761 
14762 				state->dts_cred.dcr_action |=
14763 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14764 			}
14765 
14766 			/*
14767 			 * If we have all privs in whatever zone this is,
14768 			 * we can do destructive things to processes which
14769 			 * have altered credentials.
14770 			 */
14771 #ifdef illumos
14772 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14773 			    cr->cr_zone->zone_privset)) {
14774 				state->dts_cred.dcr_action |=
14775 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14776 			}
14777 #endif
14778 		}
14779 
14780 		/*
14781 		 * Holding the dtrace_kernel privilege also implies that
14782 		 * the user has the dtrace_user privilege from a visibility
14783 		 * perspective.  But without further privileges, some
14784 		 * destructive actions are not available.
14785 		 */
14786 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14787 			/*
14788 			 * Make all probes in all zones visible.  However,
14789 			 * this doesn't mean that all actions become available
14790 			 * to all zones.
14791 			 */
14792 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14793 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14794 
14795 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14796 			    DTRACE_CRA_PROC;
14797 			/*
14798 			 * Holding proc_owner means that destructive actions
14799 			 * for *this* zone are allowed.
14800 			 */
14801 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14802 				state->dts_cred.dcr_action |=
14803 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14804 
14805 			/*
14806 			 * Holding proc_zone means that destructive actions
14807 			 * for this user/group ID in all zones is allowed.
14808 			 */
14809 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14810 				state->dts_cred.dcr_action |=
14811 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14812 
14813 #ifdef illumos
14814 			/*
14815 			 * If we have all privs in whatever zone this is,
14816 			 * we can do destructive things to processes which
14817 			 * have altered credentials.
14818 			 */
14819 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14820 			    cr->cr_zone->zone_privset)) {
14821 				state->dts_cred.dcr_action |=
14822 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14823 			}
14824 #endif
14825 		}
14826 
14827 		/*
14828 		 * Holding the dtrace_proc privilege gives control over fasttrap
14829 		 * and pid providers.  We need to grant wider destructive
14830 		 * privileges in the event that the user has proc_owner and/or
14831 		 * proc_zone.
14832 		 */
14833 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14834 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14835 				state->dts_cred.dcr_action |=
14836 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14837 
14838 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14839 				state->dts_cred.dcr_action |=
14840 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14841 		}
14842 	}
14843 
14844 	return (state);
14845 }
14846 
14847 static int
14848 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14849 {
14850 	dtrace_optval_t *opt = state->dts_options, size;
14851 	processorid_t cpu = 0;
14852 	int flags = 0, rval, factor, divisor = 1;
14853 
14854 	ASSERT(MUTEX_HELD(&dtrace_lock));
14855 	ASSERT(MUTEX_HELD(&cpu_lock));
14856 	ASSERT(which < DTRACEOPT_MAX);
14857 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14858 	    (state == dtrace_anon.dta_state &&
14859 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14860 
14861 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14862 		return (0);
14863 
14864 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14865 		cpu = opt[DTRACEOPT_CPU];
14866 
14867 	if (which == DTRACEOPT_SPECSIZE)
14868 		flags |= DTRACEBUF_NOSWITCH;
14869 
14870 	if (which == DTRACEOPT_BUFSIZE) {
14871 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14872 			flags |= DTRACEBUF_RING;
14873 
14874 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14875 			flags |= DTRACEBUF_FILL;
14876 
14877 		if (state != dtrace_anon.dta_state ||
14878 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14879 			flags |= DTRACEBUF_INACTIVE;
14880 	}
14881 
14882 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14883 		/*
14884 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14885 		 * aligned, drop it down by the difference.
14886 		 */
14887 		if (size & (sizeof (uint64_t) - 1))
14888 			size -= size & (sizeof (uint64_t) - 1);
14889 
14890 		if (size < state->dts_reserve) {
14891 			/*
14892 			 * Buffers always must be large enough to accommodate
14893 			 * their prereserved space.  We return E2BIG instead
14894 			 * of ENOMEM in this case to allow for user-level
14895 			 * software to differentiate the cases.
14896 			 */
14897 			return (E2BIG);
14898 		}
14899 
14900 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14901 
14902 		if (rval != ENOMEM) {
14903 			opt[which] = size;
14904 			return (rval);
14905 		}
14906 
14907 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14908 			return (rval);
14909 
14910 		for (divisor = 2; divisor < factor; divisor <<= 1)
14911 			continue;
14912 	}
14913 
14914 	return (ENOMEM);
14915 }
14916 
14917 static int
14918 dtrace_state_buffers(dtrace_state_t *state)
14919 {
14920 	dtrace_speculation_t *spec = state->dts_speculations;
14921 	int rval, i;
14922 
14923 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14924 	    DTRACEOPT_BUFSIZE)) != 0)
14925 		return (rval);
14926 
14927 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14928 	    DTRACEOPT_AGGSIZE)) != 0)
14929 		return (rval);
14930 
14931 	for (i = 0; i < state->dts_nspeculations; i++) {
14932 		if ((rval = dtrace_state_buffer(state,
14933 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14934 			return (rval);
14935 	}
14936 
14937 	return (0);
14938 }
14939 
14940 static void
14941 dtrace_state_prereserve(dtrace_state_t *state)
14942 {
14943 	dtrace_ecb_t *ecb;
14944 	dtrace_probe_t *probe;
14945 
14946 	state->dts_reserve = 0;
14947 
14948 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14949 		return;
14950 
14951 	/*
14952 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14953 	 * prereserved space to be the space required by the END probes.
14954 	 */
14955 	probe = dtrace_probes[dtrace_probeid_end - 1];
14956 	ASSERT(probe != NULL);
14957 
14958 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14959 		if (ecb->dte_state != state)
14960 			continue;
14961 
14962 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14963 	}
14964 }
14965 
14966 static int
14967 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14968 {
14969 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14970 	dtrace_speculation_t *spec;
14971 	dtrace_buffer_t *buf;
14972 #ifdef illumos
14973 	cyc_handler_t hdlr;
14974 	cyc_time_t when;
14975 #endif
14976 	int rval = 0, i, bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t);
14977 	dtrace_icookie_t cookie;
14978 
14979 	mutex_enter(&cpu_lock);
14980 	mutex_enter(&dtrace_lock);
14981 
14982 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14983 		rval = EBUSY;
14984 		goto out;
14985 	}
14986 
14987 	/*
14988 	 * Before we can perform any checks, we must prime all of the
14989 	 * retained enablings that correspond to this state.
14990 	 */
14991 	dtrace_enabling_prime(state);
14992 
14993 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14994 		rval = EACCES;
14995 		goto out;
14996 	}
14997 
14998 	dtrace_state_prereserve(state);
14999 
15000 	/*
15001 	 * Now we want to do is try to allocate our speculations.
15002 	 * We do not automatically resize the number of speculations; if
15003 	 * this fails, we will fail the operation.
15004 	 */
15005 	nspec = opt[DTRACEOPT_NSPEC];
15006 	ASSERT(nspec != DTRACEOPT_UNSET);
15007 
15008 	if (nspec > INT_MAX) {
15009 		rval = ENOMEM;
15010 		goto out;
15011 	}
15012 
15013 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
15014 	    KM_NOSLEEP | KM_NORMALPRI);
15015 
15016 	if (spec == NULL) {
15017 		rval = ENOMEM;
15018 		goto out;
15019 	}
15020 
15021 	state->dts_speculations = spec;
15022 	state->dts_nspeculations = (int)nspec;
15023 
15024 	for (i = 0; i < nspec; i++) {
15025 		if ((buf = kmem_zalloc(bufsize,
15026 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15027 			rval = ENOMEM;
15028 			goto err;
15029 		}
15030 
15031 		spec[i].dtsp_buffer = buf;
15032 	}
15033 
15034 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15035 		if (dtrace_anon.dta_state == NULL) {
15036 			rval = ENOENT;
15037 			goto out;
15038 		}
15039 
15040 		if (state->dts_necbs != 0) {
15041 			rval = EALREADY;
15042 			goto out;
15043 		}
15044 
15045 		state->dts_anon = dtrace_anon_grab();
15046 		ASSERT(state->dts_anon != NULL);
15047 		state = state->dts_anon;
15048 
15049 		/*
15050 		 * We want "grabanon" to be set in the grabbed state, so we'll
15051 		 * copy that option value from the grabbing state into the
15052 		 * grabbed state.
15053 		 */
15054 		state->dts_options[DTRACEOPT_GRABANON] =
15055 		    opt[DTRACEOPT_GRABANON];
15056 
15057 		*cpu = dtrace_anon.dta_beganon;
15058 
15059 		/*
15060 		 * If the anonymous state is active (as it almost certainly
15061 		 * is if the anonymous enabling ultimately matched anything),
15062 		 * we don't allow any further option processing -- but we
15063 		 * don't return failure.
15064 		 */
15065 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15066 			goto out;
15067 	}
15068 
15069 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15070 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15071 		if (state->dts_aggregations == NULL) {
15072 			/*
15073 			 * We're not going to create an aggregation buffer
15074 			 * because we don't have any ECBs that contain
15075 			 * aggregations -- set this option to 0.
15076 			 */
15077 			opt[DTRACEOPT_AGGSIZE] = 0;
15078 		} else {
15079 			/*
15080 			 * If we have an aggregation buffer, we must also have
15081 			 * a buffer to use as scratch.
15082 			 */
15083 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15084 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15085 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15086 			}
15087 		}
15088 	}
15089 
15090 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15091 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15092 		if (!state->dts_speculates) {
15093 			/*
15094 			 * We're not going to create speculation buffers
15095 			 * because we don't have any ECBs that actually
15096 			 * speculate -- set the speculation size to 0.
15097 			 */
15098 			opt[DTRACEOPT_SPECSIZE] = 0;
15099 		}
15100 	}
15101 
15102 	/*
15103 	 * The bare minimum size for any buffer that we're actually going to
15104 	 * do anything to is sizeof (uint64_t).
15105 	 */
15106 	sz = sizeof (uint64_t);
15107 
15108 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15109 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15110 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15111 		/*
15112 		 * A buffer size has been explicitly set to 0 (or to a size
15113 		 * that will be adjusted to 0) and we need the space -- we
15114 		 * need to return failure.  We return ENOSPC to differentiate
15115 		 * it from failing to allocate a buffer due to failure to meet
15116 		 * the reserve (for which we return E2BIG).
15117 		 */
15118 		rval = ENOSPC;
15119 		goto out;
15120 	}
15121 
15122 	if ((rval = dtrace_state_buffers(state)) != 0)
15123 		goto err;
15124 
15125 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15126 		sz = dtrace_dstate_defsize;
15127 
15128 	do {
15129 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15130 
15131 		if (rval == 0)
15132 			break;
15133 
15134 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15135 			goto err;
15136 	} while (sz >>= 1);
15137 
15138 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15139 
15140 	if (rval != 0)
15141 		goto err;
15142 
15143 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15144 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15145 
15146 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15147 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15148 
15149 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15150 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15151 
15152 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15153 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15154 
15155 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15156 #ifdef illumos
15157 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15158 	hdlr.cyh_arg = state;
15159 	hdlr.cyh_level = CY_LOW_LEVEL;
15160 
15161 	when.cyt_when = 0;
15162 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15163 
15164 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15165 
15166 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15167 	hdlr.cyh_arg = state;
15168 	hdlr.cyh_level = CY_LOW_LEVEL;
15169 
15170 	when.cyt_when = 0;
15171 	when.cyt_interval = dtrace_deadman_interval;
15172 
15173 	state->dts_deadman = cyclic_add(&hdlr, &when);
15174 #else
15175 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15176 	    dtrace_state_clean, state);
15177 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15178 	    dtrace_state_deadman, state);
15179 #endif
15180 
15181 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15182 
15183 #ifdef illumos
15184 	if (state->dts_getf != 0 &&
15185 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15186 		/*
15187 		 * We don't have kernel privs but we have at least one call
15188 		 * to getf(); we need to bump our zone's count, and (if
15189 		 * this is the first enabling to have an unprivileged call
15190 		 * to getf()) we need to hook into closef().
15191 		 */
15192 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15193 
15194 		if (dtrace_getf++ == 0) {
15195 			ASSERT(dtrace_closef == NULL);
15196 			dtrace_closef = dtrace_getf_barrier;
15197 		}
15198 	}
15199 #endif
15200 
15201 	/*
15202 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15203 	 * interrupts here both to record the CPU on which we fired the BEGIN
15204 	 * probe (the data from this CPU will be processed first at user
15205 	 * level) and to manually activate the buffer for this CPU.
15206 	 */
15207 	cookie = dtrace_interrupt_disable();
15208 	*cpu = curcpu;
15209 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15210 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15211 
15212 	dtrace_probe(dtrace_probeid_begin,
15213 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15214 	dtrace_interrupt_enable(cookie);
15215 	/*
15216 	 * We may have had an exit action from a BEGIN probe; only change our
15217 	 * state to ACTIVE if we're still in WARMUP.
15218 	 */
15219 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15220 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15221 
15222 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15223 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15224 
15225 #ifdef __FreeBSD__
15226 	/*
15227 	 * We enable anonymous tracing before APs are started, so we must
15228 	 * activate buffers using the current CPU.
15229 	 */
15230 	if (state == dtrace_anon.dta_state) {
15231 		CPU_FOREACH(i)
15232 			dtrace_buffer_activate_cpu(state, i);
15233 	} else
15234 		dtrace_xcall(DTRACE_CPUALL,
15235 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15236 #else
15237 	/*
15238 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15239 	 * want each CPU to transition its principal buffer out of the
15240 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15241 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15242 	 * atomically transition from processing none of a state's ECBs to
15243 	 * processing all of them.
15244 	 */
15245 	dtrace_xcall(DTRACE_CPUALL,
15246 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15247 #endif
15248 	goto out;
15249 
15250 err:
15251 	dtrace_buffer_free(state->dts_buffer);
15252 	dtrace_buffer_free(state->dts_aggbuffer);
15253 
15254 	if ((nspec = state->dts_nspeculations) == 0) {
15255 		ASSERT(state->dts_speculations == NULL);
15256 		goto out;
15257 	}
15258 
15259 	spec = state->dts_speculations;
15260 	ASSERT(spec != NULL);
15261 
15262 	for (i = 0; i < state->dts_nspeculations; i++) {
15263 		if ((buf = spec[i].dtsp_buffer) == NULL)
15264 			break;
15265 
15266 		dtrace_buffer_free(buf);
15267 		kmem_free(buf, bufsize);
15268 	}
15269 
15270 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15271 	state->dts_nspeculations = 0;
15272 	state->dts_speculations = NULL;
15273 
15274 out:
15275 	mutex_exit(&dtrace_lock);
15276 	mutex_exit(&cpu_lock);
15277 
15278 	return (rval);
15279 }
15280 
15281 static int
15282 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15283 {
15284 	dtrace_icookie_t cookie;
15285 
15286 	ASSERT(MUTEX_HELD(&dtrace_lock));
15287 
15288 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15289 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15290 		return (EINVAL);
15291 
15292 	/*
15293 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15294 	 * to be sure that every CPU has seen it.  See below for the details
15295 	 * on why this is done.
15296 	 */
15297 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15298 	dtrace_sync();
15299 
15300 	/*
15301 	 * By this point, it is impossible for any CPU to be still processing
15302 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15303 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15304 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15305 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15306 	 * iff we're in the END probe.
15307 	 */
15308 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15309 	dtrace_sync();
15310 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15311 
15312 	/*
15313 	 * Finally, we can release the reserve and call the END probe.  We
15314 	 * disable interrupts across calling the END probe to allow us to
15315 	 * return the CPU on which we actually called the END probe.  This
15316 	 * allows user-land to be sure that this CPU's principal buffer is
15317 	 * processed last.
15318 	 */
15319 	state->dts_reserve = 0;
15320 
15321 	cookie = dtrace_interrupt_disable();
15322 	*cpu = curcpu;
15323 	dtrace_probe(dtrace_probeid_end,
15324 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15325 	dtrace_interrupt_enable(cookie);
15326 
15327 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15328 	dtrace_sync();
15329 
15330 #ifdef illumos
15331 	if (state->dts_getf != 0 &&
15332 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15333 		/*
15334 		 * We don't have kernel privs but we have at least one call
15335 		 * to getf(); we need to lower our zone's count, and (if
15336 		 * this is the last enabling to have an unprivileged call
15337 		 * to getf()) we need to clear the closef() hook.
15338 		 */
15339 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15340 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15341 		ASSERT(dtrace_getf > 0);
15342 
15343 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15344 
15345 		if (--dtrace_getf == 0)
15346 			dtrace_closef = NULL;
15347 	}
15348 #endif
15349 
15350 	return (0);
15351 }
15352 
15353 static int
15354 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15355     dtrace_optval_t val)
15356 {
15357 	ASSERT(MUTEX_HELD(&dtrace_lock));
15358 
15359 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15360 		return (EBUSY);
15361 
15362 	if (option >= DTRACEOPT_MAX)
15363 		return (EINVAL);
15364 
15365 	if (option != DTRACEOPT_CPU && val < 0)
15366 		return (EINVAL);
15367 
15368 	switch (option) {
15369 	case DTRACEOPT_DESTRUCTIVE:
15370 		if (dtrace_destructive_disallow)
15371 			return (EACCES);
15372 
15373 		state->dts_cred.dcr_destructive = 1;
15374 		break;
15375 
15376 	case DTRACEOPT_BUFSIZE:
15377 	case DTRACEOPT_DYNVARSIZE:
15378 	case DTRACEOPT_AGGSIZE:
15379 	case DTRACEOPT_SPECSIZE:
15380 	case DTRACEOPT_STRSIZE:
15381 		if (val < 0)
15382 			return (EINVAL);
15383 
15384 		if (val >= LONG_MAX) {
15385 			/*
15386 			 * If this is an otherwise negative value, set it to
15387 			 * the highest multiple of 128m less than LONG_MAX.
15388 			 * Technically, we're adjusting the size without
15389 			 * regard to the buffer resizing policy, but in fact,
15390 			 * this has no effect -- if we set the buffer size to
15391 			 * ~LONG_MAX and the buffer policy is ultimately set to
15392 			 * be "manual", the buffer allocation is guaranteed to
15393 			 * fail, if only because the allocation requires two
15394 			 * buffers.  (We set the the size to the highest
15395 			 * multiple of 128m because it ensures that the size
15396 			 * will remain a multiple of a megabyte when
15397 			 * repeatedly halved -- all the way down to 15m.)
15398 			 */
15399 			val = LONG_MAX - (1 << 27) + 1;
15400 		}
15401 	}
15402 
15403 	state->dts_options[option] = val;
15404 
15405 	return (0);
15406 }
15407 
15408 static void
15409 dtrace_state_destroy(dtrace_state_t *state)
15410 {
15411 	dtrace_ecb_t *ecb;
15412 	dtrace_vstate_t *vstate = &state->dts_vstate;
15413 #ifdef illumos
15414 	minor_t minor = getminor(state->dts_dev);
15415 #endif
15416 	int i, bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t);
15417 	dtrace_speculation_t *spec = state->dts_speculations;
15418 	int nspec = state->dts_nspeculations;
15419 	uint32_t match;
15420 
15421 	ASSERT(MUTEX_HELD(&dtrace_lock));
15422 	ASSERT(MUTEX_HELD(&cpu_lock));
15423 
15424 	/*
15425 	 * First, retract any retained enablings for this state.
15426 	 */
15427 	dtrace_enabling_retract(state);
15428 	ASSERT(state->dts_nretained == 0);
15429 
15430 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15431 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15432 		/*
15433 		 * We have managed to come into dtrace_state_destroy() on a
15434 		 * hot enabling -- almost certainly because of a disorderly
15435 		 * shutdown of a consumer.  (That is, a consumer that is
15436 		 * exiting without having called dtrace_stop().) In this case,
15437 		 * we're going to set our activity to be KILLED, and then
15438 		 * issue a sync to be sure that everyone is out of probe
15439 		 * context before we start blowing away ECBs.
15440 		 */
15441 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15442 		dtrace_sync();
15443 	}
15444 
15445 	/*
15446 	 * Release the credential hold we took in dtrace_state_create().
15447 	 */
15448 	if (state->dts_cred.dcr_cred != NULL)
15449 		crfree(state->dts_cred.dcr_cred);
15450 
15451 	/*
15452 	 * Now we can safely disable and destroy any enabled probes.  Because
15453 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15454 	 * (especially if they're all enabled), we take two passes through the
15455 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15456 	 * in the second we disable whatever is left over.
15457 	 */
15458 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15459 		for (i = 0; i < state->dts_necbs; i++) {
15460 			if ((ecb = state->dts_ecbs[i]) == NULL)
15461 				continue;
15462 
15463 			if (match && ecb->dte_probe != NULL) {
15464 				dtrace_probe_t *probe = ecb->dte_probe;
15465 				dtrace_provider_t *prov = probe->dtpr_provider;
15466 
15467 				if (!(prov->dtpv_priv.dtpp_flags & match))
15468 					continue;
15469 			}
15470 
15471 			dtrace_ecb_disable(ecb);
15472 			dtrace_ecb_destroy(ecb);
15473 		}
15474 
15475 		if (!match)
15476 			break;
15477 	}
15478 
15479 	/*
15480 	 * Before we free the buffers, perform one more sync to assure that
15481 	 * every CPU is out of probe context.
15482 	 */
15483 	dtrace_sync();
15484 
15485 	dtrace_buffer_free(state->dts_buffer);
15486 	dtrace_buffer_free(state->dts_aggbuffer);
15487 
15488 	for (i = 0; i < nspec; i++)
15489 		dtrace_buffer_free(spec[i].dtsp_buffer);
15490 
15491 #ifdef illumos
15492 	if (state->dts_cleaner != CYCLIC_NONE)
15493 		cyclic_remove(state->dts_cleaner);
15494 
15495 	if (state->dts_deadman != CYCLIC_NONE)
15496 		cyclic_remove(state->dts_deadman);
15497 #else
15498 	callout_stop(&state->dts_cleaner);
15499 	callout_drain(&state->dts_cleaner);
15500 	callout_stop(&state->dts_deadman);
15501 	callout_drain(&state->dts_deadman);
15502 #endif
15503 
15504 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15505 	dtrace_vstate_fini(vstate);
15506 	if (state->dts_ecbs != NULL)
15507 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15508 
15509 	if (state->dts_aggregations != NULL) {
15510 #ifdef DEBUG
15511 		for (i = 0; i < state->dts_naggregations; i++)
15512 			ASSERT(state->dts_aggregations[i] == NULL);
15513 #endif
15514 		ASSERT(state->dts_naggregations > 0);
15515 		kmem_free(state->dts_aggregations,
15516 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15517 	}
15518 
15519 	kmem_free(state->dts_buffer, bufsize);
15520 	kmem_free(state->dts_aggbuffer, bufsize);
15521 
15522 	for (i = 0; i < nspec; i++)
15523 		kmem_free(spec[i].dtsp_buffer, bufsize);
15524 
15525 	if (spec != NULL)
15526 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15527 
15528 	dtrace_format_destroy(state);
15529 
15530 	if (state->dts_aggid_arena != NULL) {
15531 #ifdef illumos
15532 		vmem_destroy(state->dts_aggid_arena);
15533 #else
15534 		delete_unrhdr(state->dts_aggid_arena);
15535 #endif
15536 		state->dts_aggid_arena = NULL;
15537 	}
15538 #ifdef illumos
15539 	ddi_soft_state_free(dtrace_softstate, minor);
15540 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15541 #endif
15542 }
15543 
15544 /*
15545  * DTrace Anonymous Enabling Functions
15546  */
15547 static dtrace_state_t *
15548 dtrace_anon_grab(void)
15549 {
15550 	dtrace_state_t *state;
15551 
15552 	ASSERT(MUTEX_HELD(&dtrace_lock));
15553 
15554 	if ((state = dtrace_anon.dta_state) == NULL) {
15555 		ASSERT(dtrace_anon.dta_enabling == NULL);
15556 		return (NULL);
15557 	}
15558 
15559 	ASSERT(dtrace_anon.dta_enabling != NULL);
15560 	ASSERT(dtrace_retained != NULL);
15561 
15562 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15563 	dtrace_anon.dta_enabling = NULL;
15564 	dtrace_anon.dta_state = NULL;
15565 
15566 	return (state);
15567 }
15568 
15569 static void
15570 dtrace_anon_property(void)
15571 {
15572 	int i, rv;
15573 	dtrace_state_t *state;
15574 	dof_hdr_t *dof;
15575 	char c[32];		/* enough for "dof-data-" + digits */
15576 
15577 	ASSERT(MUTEX_HELD(&dtrace_lock));
15578 	ASSERT(MUTEX_HELD(&cpu_lock));
15579 
15580 	for (i = 0; ; i++) {
15581 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15582 
15583 		dtrace_err_verbose = 1;
15584 
15585 		if ((dof = dtrace_dof_property(c)) == NULL) {
15586 			dtrace_err_verbose = 0;
15587 			break;
15588 		}
15589 
15590 #ifdef illumos
15591 		/*
15592 		 * We want to create anonymous state, so we need to transition
15593 		 * the kernel debugger to indicate that DTrace is active.  If
15594 		 * this fails (e.g. because the debugger has modified text in
15595 		 * some way), we won't continue with the processing.
15596 		 */
15597 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15598 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15599 			    "enabling ignored.");
15600 			dtrace_dof_destroy(dof);
15601 			break;
15602 		}
15603 #endif
15604 
15605 		/*
15606 		 * If we haven't allocated an anonymous state, we'll do so now.
15607 		 */
15608 		if ((state = dtrace_anon.dta_state) == NULL) {
15609 			state = dtrace_state_create(NULL, NULL);
15610 			dtrace_anon.dta_state = state;
15611 
15612 			if (state == NULL) {
15613 				/*
15614 				 * This basically shouldn't happen:  the only
15615 				 * failure mode from dtrace_state_create() is a
15616 				 * failure of ddi_soft_state_zalloc() that
15617 				 * itself should never happen.  Still, the
15618 				 * interface allows for a failure mode, and
15619 				 * we want to fail as gracefully as possible:
15620 				 * we'll emit an error message and cease
15621 				 * processing anonymous state in this case.
15622 				 */
15623 				cmn_err(CE_WARN, "failed to create "
15624 				    "anonymous state");
15625 				dtrace_dof_destroy(dof);
15626 				break;
15627 			}
15628 		}
15629 
15630 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15631 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15632 
15633 		if (rv == 0)
15634 			rv = dtrace_dof_options(dof, state);
15635 
15636 		dtrace_err_verbose = 0;
15637 		dtrace_dof_destroy(dof);
15638 
15639 		if (rv != 0) {
15640 			/*
15641 			 * This is malformed DOF; chuck any anonymous state
15642 			 * that we created.
15643 			 */
15644 			ASSERT(dtrace_anon.dta_enabling == NULL);
15645 			dtrace_state_destroy(state);
15646 			dtrace_anon.dta_state = NULL;
15647 			break;
15648 		}
15649 
15650 		ASSERT(dtrace_anon.dta_enabling != NULL);
15651 	}
15652 
15653 	if (dtrace_anon.dta_enabling != NULL) {
15654 		int rval;
15655 
15656 		/*
15657 		 * dtrace_enabling_retain() can only fail because we are
15658 		 * trying to retain more enablings than are allowed -- but
15659 		 * we only have one anonymous enabling, and we are guaranteed
15660 		 * to be allowed at least one retained enabling; we assert
15661 		 * that dtrace_enabling_retain() returns success.
15662 		 */
15663 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15664 		ASSERT(rval == 0);
15665 
15666 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15667 	}
15668 }
15669 
15670 /*
15671  * DTrace Helper Functions
15672  */
15673 static void
15674 dtrace_helper_trace(dtrace_helper_action_t *helper,
15675     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15676 {
15677 	uint32_t size, next, nnext, i;
15678 	dtrace_helptrace_t *ent, *buffer;
15679 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15680 
15681 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15682 		return;
15683 
15684 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15685 
15686 	/*
15687 	 * What would a tracing framework be without its own tracing
15688 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15689 	 */
15690 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15691 	    sizeof (uint64_t) - sizeof (uint64_t);
15692 
15693 	/*
15694 	 * Iterate until we can allocate a slot in the trace buffer.
15695 	 */
15696 	do {
15697 		next = dtrace_helptrace_next;
15698 
15699 		if (next + size < dtrace_helptrace_bufsize) {
15700 			nnext = next + size;
15701 		} else {
15702 			nnext = size;
15703 		}
15704 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15705 
15706 	/*
15707 	 * We have our slot; fill it in.
15708 	 */
15709 	if (nnext == size) {
15710 		dtrace_helptrace_wrapped++;
15711 		next = 0;
15712 	}
15713 
15714 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15715 	ent->dtht_helper = helper;
15716 	ent->dtht_where = where;
15717 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15718 
15719 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15720 	    mstate->dtms_fltoffs : -1;
15721 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15722 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15723 
15724 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15725 		dtrace_statvar_t *svar;
15726 
15727 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15728 			continue;
15729 
15730 		ASSERT(svar->dtsv_size >= (mp_maxid + 1) * sizeof (uint64_t));
15731 		ent->dtht_locals[i] =
15732 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15733 	}
15734 }
15735 
15736 static uint64_t
15737 dtrace_helper(int which, dtrace_mstate_t *mstate,
15738     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15739 {
15740 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15741 	uint64_t sarg0 = mstate->dtms_arg[0];
15742 	uint64_t sarg1 = mstate->dtms_arg[1];
15743 	uint64_t rval = 0;
15744 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15745 	dtrace_helper_action_t *helper;
15746 	dtrace_vstate_t *vstate;
15747 	dtrace_difo_t *pred;
15748 	int i, trace = dtrace_helptrace_buffer != NULL;
15749 
15750 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15751 
15752 	if (helpers == NULL)
15753 		return (0);
15754 
15755 	if ((helper = helpers->dthps_actions[which]) == NULL)
15756 		return (0);
15757 
15758 	vstate = &helpers->dthps_vstate;
15759 	mstate->dtms_arg[0] = arg0;
15760 	mstate->dtms_arg[1] = arg1;
15761 
15762 	/*
15763 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15764 	 * we'll call the corresponding actions.  Note that the below calls
15765 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15766 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15767 	 * the stored DIF offset with its own (which is the desired behavior).
15768 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15769 	 * from machine state; this is okay, too.
15770 	 */
15771 	for (; helper != NULL; helper = helper->dtha_next) {
15772 		if ((pred = helper->dtha_predicate) != NULL) {
15773 			if (trace)
15774 				dtrace_helper_trace(helper, mstate, vstate, 0);
15775 
15776 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15777 				goto next;
15778 
15779 			if (*flags & CPU_DTRACE_FAULT)
15780 				goto err;
15781 		}
15782 
15783 		for (i = 0; i < helper->dtha_nactions; i++) {
15784 			if (trace)
15785 				dtrace_helper_trace(helper,
15786 				    mstate, vstate, i + 1);
15787 
15788 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15789 			    mstate, vstate, state);
15790 
15791 			if (*flags & CPU_DTRACE_FAULT)
15792 				goto err;
15793 		}
15794 
15795 next:
15796 		if (trace)
15797 			dtrace_helper_trace(helper, mstate, vstate,
15798 			    DTRACE_HELPTRACE_NEXT);
15799 	}
15800 
15801 	if (trace)
15802 		dtrace_helper_trace(helper, mstate, vstate,
15803 		    DTRACE_HELPTRACE_DONE);
15804 
15805 	/*
15806 	 * Restore the arg0 that we saved upon entry.
15807 	 */
15808 	mstate->dtms_arg[0] = sarg0;
15809 	mstate->dtms_arg[1] = sarg1;
15810 
15811 	return (rval);
15812 
15813 err:
15814 	if (trace)
15815 		dtrace_helper_trace(helper, mstate, vstate,
15816 		    DTRACE_HELPTRACE_ERR);
15817 
15818 	/*
15819 	 * Restore the arg0 that we saved upon entry.
15820 	 */
15821 	mstate->dtms_arg[0] = sarg0;
15822 	mstate->dtms_arg[1] = sarg1;
15823 
15824 	return (0);
15825 }
15826 
15827 static void
15828 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15829     dtrace_vstate_t *vstate)
15830 {
15831 	int i;
15832 
15833 	if (helper->dtha_predicate != NULL)
15834 		dtrace_difo_release(helper->dtha_predicate, vstate);
15835 
15836 	for (i = 0; i < helper->dtha_nactions; i++) {
15837 		ASSERT(helper->dtha_actions[i] != NULL);
15838 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15839 	}
15840 
15841 	kmem_free(helper->dtha_actions,
15842 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15843 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15844 }
15845 
15846 static int
15847 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15848 {
15849 	proc_t *p = curproc;
15850 	dtrace_vstate_t *vstate;
15851 	int i;
15852 
15853 	if (help == NULL)
15854 		help = p->p_dtrace_helpers;
15855 
15856 	ASSERT(MUTEX_HELD(&dtrace_lock));
15857 
15858 	if (help == NULL || gen > help->dthps_generation)
15859 		return (EINVAL);
15860 
15861 	vstate = &help->dthps_vstate;
15862 
15863 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15864 		dtrace_helper_action_t *last = NULL, *h, *next;
15865 
15866 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15867 			next = h->dtha_next;
15868 
15869 			if (h->dtha_generation == gen) {
15870 				if (last != NULL) {
15871 					last->dtha_next = next;
15872 				} else {
15873 					help->dthps_actions[i] = next;
15874 				}
15875 
15876 				dtrace_helper_action_destroy(h, vstate);
15877 			} else {
15878 				last = h;
15879 			}
15880 		}
15881 	}
15882 
15883 	/*
15884 	 * Interate until we've cleared out all helper providers with the
15885 	 * given generation number.
15886 	 */
15887 	for (;;) {
15888 		dtrace_helper_provider_t *prov;
15889 
15890 		/*
15891 		 * Look for a helper provider with the right generation. We
15892 		 * have to start back at the beginning of the list each time
15893 		 * because we drop dtrace_lock. It's unlikely that we'll make
15894 		 * more than two passes.
15895 		 */
15896 		for (i = 0; i < help->dthps_nprovs; i++) {
15897 			prov = help->dthps_provs[i];
15898 
15899 			if (prov->dthp_generation == gen)
15900 				break;
15901 		}
15902 
15903 		/*
15904 		 * If there were no matches, we're done.
15905 		 */
15906 		if (i == help->dthps_nprovs)
15907 			break;
15908 
15909 		/*
15910 		 * Move the last helper provider into this slot.
15911 		 */
15912 		help->dthps_nprovs--;
15913 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15914 		help->dthps_provs[help->dthps_nprovs] = NULL;
15915 
15916 		mutex_exit(&dtrace_lock);
15917 
15918 		/*
15919 		 * If we have a meta provider, remove this helper provider.
15920 		 */
15921 		mutex_enter(&dtrace_meta_lock);
15922 		if (dtrace_meta_pid != NULL) {
15923 			ASSERT(dtrace_deferred_pid == NULL);
15924 			dtrace_helper_provider_remove(&prov->dthp_prov,
15925 			    p->p_pid);
15926 		}
15927 		mutex_exit(&dtrace_meta_lock);
15928 
15929 		dtrace_helper_provider_destroy(prov);
15930 
15931 		mutex_enter(&dtrace_lock);
15932 	}
15933 
15934 	return (0);
15935 }
15936 
15937 static int
15938 dtrace_helper_validate(dtrace_helper_action_t *helper)
15939 {
15940 	int err = 0, i;
15941 	dtrace_difo_t *dp;
15942 
15943 	if ((dp = helper->dtha_predicate) != NULL)
15944 		err += dtrace_difo_validate_helper(dp);
15945 
15946 	for (i = 0; i < helper->dtha_nactions; i++)
15947 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15948 
15949 	return (err == 0);
15950 }
15951 
15952 static int
15953 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15954     dtrace_helpers_t *help)
15955 {
15956 	dtrace_helper_action_t *helper, *last;
15957 	dtrace_actdesc_t *act;
15958 	dtrace_vstate_t *vstate;
15959 	dtrace_predicate_t *pred;
15960 	int count = 0, nactions = 0, i;
15961 
15962 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15963 		return (EINVAL);
15964 
15965 	last = help->dthps_actions[which];
15966 	vstate = &help->dthps_vstate;
15967 
15968 	for (count = 0; last != NULL; last = last->dtha_next) {
15969 		count++;
15970 		if (last->dtha_next == NULL)
15971 			break;
15972 	}
15973 
15974 	/*
15975 	 * If we already have dtrace_helper_actions_max helper actions for this
15976 	 * helper action type, we'll refuse to add a new one.
15977 	 */
15978 	if (count >= dtrace_helper_actions_max)
15979 		return (ENOSPC);
15980 
15981 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15982 	helper->dtha_generation = help->dthps_generation;
15983 
15984 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15985 		ASSERT(pred->dtp_difo != NULL);
15986 		dtrace_difo_hold(pred->dtp_difo);
15987 		helper->dtha_predicate = pred->dtp_difo;
15988 	}
15989 
15990 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15991 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15992 			goto err;
15993 
15994 		if (act->dtad_difo == NULL)
15995 			goto err;
15996 
15997 		nactions++;
15998 	}
15999 
16000 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
16001 	    (helper->dtha_nactions = nactions), KM_SLEEP);
16002 
16003 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
16004 		dtrace_difo_hold(act->dtad_difo);
16005 		helper->dtha_actions[i++] = act->dtad_difo;
16006 	}
16007 
16008 	if (!dtrace_helper_validate(helper))
16009 		goto err;
16010 
16011 	if (last == NULL) {
16012 		help->dthps_actions[which] = helper;
16013 	} else {
16014 		last->dtha_next = helper;
16015 	}
16016 
16017 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16018 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16019 		dtrace_helptrace_next = 0;
16020 	}
16021 
16022 	return (0);
16023 err:
16024 	dtrace_helper_action_destroy(helper, vstate);
16025 	return (EINVAL);
16026 }
16027 
16028 static void
16029 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16030     dof_helper_t *dofhp)
16031 {
16032 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16033 
16034 	mutex_enter(&dtrace_meta_lock);
16035 	mutex_enter(&dtrace_lock);
16036 
16037 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16038 		/*
16039 		 * If the dtrace module is loaded but not attached, or if
16040 		 * there aren't isn't a meta provider registered to deal with
16041 		 * these provider descriptions, we need to postpone creating
16042 		 * the actual providers until later.
16043 		 */
16044 
16045 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16046 		    dtrace_deferred_pid != help) {
16047 			help->dthps_deferred = 1;
16048 			help->dthps_pid = p->p_pid;
16049 			help->dthps_next = dtrace_deferred_pid;
16050 			help->dthps_prev = NULL;
16051 			if (dtrace_deferred_pid != NULL)
16052 				dtrace_deferred_pid->dthps_prev = help;
16053 			dtrace_deferred_pid = help;
16054 		}
16055 
16056 		mutex_exit(&dtrace_lock);
16057 
16058 	} else if (dofhp != NULL) {
16059 		/*
16060 		 * If the dtrace module is loaded and we have a particular
16061 		 * helper provider description, pass that off to the
16062 		 * meta provider.
16063 		 */
16064 
16065 		mutex_exit(&dtrace_lock);
16066 
16067 		dtrace_helper_provide(dofhp, p->p_pid);
16068 
16069 	} else {
16070 		/*
16071 		 * Otherwise, just pass all the helper provider descriptions
16072 		 * off to the meta provider.
16073 		 */
16074 
16075 		int i;
16076 		mutex_exit(&dtrace_lock);
16077 
16078 		for (i = 0; i < help->dthps_nprovs; i++) {
16079 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16080 			    p->p_pid);
16081 		}
16082 	}
16083 
16084 	mutex_exit(&dtrace_meta_lock);
16085 }
16086 
16087 static int
16088 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16089 {
16090 	dtrace_helper_provider_t *hprov, **tmp_provs;
16091 	uint_t tmp_maxprovs, i;
16092 
16093 	ASSERT(MUTEX_HELD(&dtrace_lock));
16094 	ASSERT(help != NULL);
16095 
16096 	/*
16097 	 * If we already have dtrace_helper_providers_max helper providers,
16098 	 * we're refuse to add a new one.
16099 	 */
16100 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16101 		return (ENOSPC);
16102 
16103 	/*
16104 	 * Check to make sure this isn't a duplicate.
16105 	 */
16106 	for (i = 0; i < help->dthps_nprovs; i++) {
16107 		if (dofhp->dofhp_addr ==
16108 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16109 			return (EALREADY);
16110 	}
16111 
16112 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16113 	hprov->dthp_prov = *dofhp;
16114 	hprov->dthp_ref = 1;
16115 	hprov->dthp_generation = gen;
16116 
16117 	/*
16118 	 * Allocate a bigger table for helper providers if it's already full.
16119 	 */
16120 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16121 		tmp_maxprovs = help->dthps_maxprovs;
16122 		tmp_provs = help->dthps_provs;
16123 
16124 		if (help->dthps_maxprovs == 0)
16125 			help->dthps_maxprovs = 2;
16126 		else
16127 			help->dthps_maxprovs *= 2;
16128 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16129 			help->dthps_maxprovs = dtrace_helper_providers_max;
16130 
16131 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16132 
16133 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16134 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16135 
16136 		if (tmp_provs != NULL) {
16137 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16138 			    sizeof (dtrace_helper_provider_t *));
16139 			kmem_free(tmp_provs, tmp_maxprovs *
16140 			    sizeof (dtrace_helper_provider_t *));
16141 		}
16142 	}
16143 
16144 	help->dthps_provs[help->dthps_nprovs] = hprov;
16145 	help->dthps_nprovs++;
16146 
16147 	return (0);
16148 }
16149 
16150 static void
16151 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16152 {
16153 	mutex_enter(&dtrace_lock);
16154 
16155 	if (--hprov->dthp_ref == 0) {
16156 		dof_hdr_t *dof;
16157 		mutex_exit(&dtrace_lock);
16158 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16159 		dtrace_dof_destroy(dof);
16160 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16161 	} else {
16162 		mutex_exit(&dtrace_lock);
16163 	}
16164 }
16165 
16166 static int
16167 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16168 {
16169 	uintptr_t daddr = (uintptr_t)dof;
16170 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16171 	dof_provider_t *provider;
16172 	dof_probe_t *probe;
16173 	uint8_t *arg;
16174 	char *strtab, *typestr;
16175 	dof_stridx_t typeidx;
16176 	size_t typesz;
16177 	uint_t nprobes, j, k;
16178 
16179 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16180 
16181 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16182 		dtrace_dof_error(dof, "misaligned section offset");
16183 		return (-1);
16184 	}
16185 
16186 	/*
16187 	 * The section needs to be large enough to contain the DOF provider
16188 	 * structure appropriate for the given version.
16189 	 */
16190 	if (sec->dofs_size <
16191 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16192 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16193 	    sizeof (dof_provider_t))) {
16194 		dtrace_dof_error(dof, "provider section too small");
16195 		return (-1);
16196 	}
16197 
16198 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16199 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16200 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16201 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16202 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16203 
16204 	if (str_sec == NULL || prb_sec == NULL ||
16205 	    arg_sec == NULL || off_sec == NULL)
16206 		return (-1);
16207 
16208 	enoff_sec = NULL;
16209 
16210 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16211 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16212 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16213 	    provider->dofpv_prenoffs)) == NULL)
16214 		return (-1);
16215 
16216 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16217 
16218 	if (provider->dofpv_name >= str_sec->dofs_size ||
16219 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16220 		dtrace_dof_error(dof, "invalid provider name");
16221 		return (-1);
16222 	}
16223 
16224 	if (prb_sec->dofs_entsize == 0 ||
16225 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16226 		dtrace_dof_error(dof, "invalid entry size");
16227 		return (-1);
16228 	}
16229 
16230 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16231 		dtrace_dof_error(dof, "misaligned entry size");
16232 		return (-1);
16233 	}
16234 
16235 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16236 		dtrace_dof_error(dof, "invalid entry size");
16237 		return (-1);
16238 	}
16239 
16240 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16241 		dtrace_dof_error(dof, "misaligned section offset");
16242 		return (-1);
16243 	}
16244 
16245 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16246 		dtrace_dof_error(dof, "invalid entry size");
16247 		return (-1);
16248 	}
16249 
16250 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16251 
16252 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16253 
16254 	/*
16255 	 * Take a pass through the probes to check for errors.
16256 	 */
16257 	for (j = 0; j < nprobes; j++) {
16258 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16259 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16260 
16261 		if (probe->dofpr_func >= str_sec->dofs_size) {
16262 			dtrace_dof_error(dof, "invalid function name");
16263 			return (-1);
16264 		}
16265 
16266 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16267 			dtrace_dof_error(dof, "function name too long");
16268 			/*
16269 			 * Keep going if the function name is too long.
16270 			 * Unlike provider and probe names, we cannot reasonably
16271 			 * impose restrictions on function names, since they're
16272 			 * a property of the code being instrumented. We will
16273 			 * skip this probe in dtrace_helper_provide_one().
16274 			 */
16275 		}
16276 
16277 		if (probe->dofpr_name >= str_sec->dofs_size ||
16278 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16279 			dtrace_dof_error(dof, "invalid probe name");
16280 			return (-1);
16281 		}
16282 
16283 		/*
16284 		 * The offset count must not wrap the index, and the offsets
16285 		 * must also not overflow the section's data.
16286 		 */
16287 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16288 		    probe->dofpr_offidx ||
16289 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16290 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16291 			dtrace_dof_error(dof, "invalid probe offset");
16292 			return (-1);
16293 		}
16294 
16295 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16296 			/*
16297 			 * If there's no is-enabled offset section, make sure
16298 			 * there aren't any is-enabled offsets. Otherwise
16299 			 * perform the same checks as for probe offsets
16300 			 * (immediately above).
16301 			 */
16302 			if (enoff_sec == NULL) {
16303 				if (probe->dofpr_enoffidx != 0 ||
16304 				    probe->dofpr_nenoffs != 0) {
16305 					dtrace_dof_error(dof, "is-enabled "
16306 					    "offsets with null section");
16307 					return (-1);
16308 				}
16309 			} else if (probe->dofpr_enoffidx +
16310 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16311 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16312 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16313 				dtrace_dof_error(dof, "invalid is-enabled "
16314 				    "offset");
16315 				return (-1);
16316 			}
16317 
16318 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16319 				dtrace_dof_error(dof, "zero probe and "
16320 				    "is-enabled offsets");
16321 				return (-1);
16322 			}
16323 		} else if (probe->dofpr_noffs == 0) {
16324 			dtrace_dof_error(dof, "zero probe offsets");
16325 			return (-1);
16326 		}
16327 
16328 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16329 		    probe->dofpr_argidx ||
16330 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16331 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16332 			dtrace_dof_error(dof, "invalid args");
16333 			return (-1);
16334 		}
16335 
16336 		typeidx = probe->dofpr_nargv;
16337 		typestr = strtab + probe->dofpr_nargv;
16338 		for (k = 0; k < probe->dofpr_nargc; k++) {
16339 			if (typeidx >= str_sec->dofs_size) {
16340 				dtrace_dof_error(dof, "bad "
16341 				    "native argument type");
16342 				return (-1);
16343 			}
16344 
16345 			typesz = strlen(typestr) + 1;
16346 			if (typesz > DTRACE_ARGTYPELEN) {
16347 				dtrace_dof_error(dof, "native "
16348 				    "argument type too long");
16349 				return (-1);
16350 			}
16351 			typeidx += typesz;
16352 			typestr += typesz;
16353 		}
16354 
16355 		typeidx = probe->dofpr_xargv;
16356 		typestr = strtab + probe->dofpr_xargv;
16357 		for (k = 0; k < probe->dofpr_xargc; k++) {
16358 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16359 				dtrace_dof_error(dof, "bad "
16360 				    "native argument index");
16361 				return (-1);
16362 			}
16363 
16364 			if (typeidx >= str_sec->dofs_size) {
16365 				dtrace_dof_error(dof, "bad "
16366 				    "translated argument type");
16367 				return (-1);
16368 			}
16369 
16370 			typesz = strlen(typestr) + 1;
16371 			if (typesz > DTRACE_ARGTYPELEN) {
16372 				dtrace_dof_error(dof, "translated argument "
16373 				    "type too long");
16374 				return (-1);
16375 			}
16376 
16377 			typeidx += typesz;
16378 			typestr += typesz;
16379 		}
16380 	}
16381 
16382 	return (0);
16383 }
16384 
16385 static int
16386 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16387 {
16388 	dtrace_helpers_t *help;
16389 	dtrace_vstate_t *vstate;
16390 	dtrace_enabling_t *enab = NULL;
16391 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16392 	uintptr_t daddr = (uintptr_t)dof;
16393 
16394 	ASSERT(MUTEX_HELD(&dtrace_lock));
16395 
16396 	if ((help = p->p_dtrace_helpers) == NULL)
16397 		help = dtrace_helpers_create(p);
16398 
16399 	vstate = &help->dthps_vstate;
16400 
16401 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16402 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16403 		dtrace_dof_destroy(dof);
16404 		return (rv);
16405 	}
16406 
16407 	/*
16408 	 * Look for helper providers and validate their descriptions.
16409 	 */
16410 	for (i = 0; i < dof->dofh_secnum; i++) {
16411 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16412 		    dof->dofh_secoff + i * dof->dofh_secsize);
16413 
16414 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16415 			continue;
16416 
16417 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16418 			dtrace_enabling_destroy(enab);
16419 			dtrace_dof_destroy(dof);
16420 			return (-1);
16421 		}
16422 
16423 		nprovs++;
16424 	}
16425 
16426 	/*
16427 	 * Now we need to walk through the ECB descriptions in the enabling.
16428 	 */
16429 	for (i = 0; i < enab->dten_ndesc; i++) {
16430 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16431 		dtrace_probedesc_t *desc = &ep->dted_probe;
16432 
16433 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16434 			continue;
16435 
16436 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16437 			continue;
16438 
16439 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16440 			continue;
16441 
16442 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16443 		    ep, help)) != 0) {
16444 			/*
16445 			 * Adding this helper action failed -- we are now going
16446 			 * to rip out the entire generation and return failure.
16447 			 */
16448 			(void) dtrace_helper_destroygen(help,
16449 			    help->dthps_generation);
16450 			dtrace_enabling_destroy(enab);
16451 			dtrace_dof_destroy(dof);
16452 			return (-1);
16453 		}
16454 
16455 		nhelpers++;
16456 	}
16457 
16458 	if (nhelpers < enab->dten_ndesc)
16459 		dtrace_dof_error(dof, "unmatched helpers");
16460 
16461 	gen = help->dthps_generation++;
16462 	dtrace_enabling_destroy(enab);
16463 
16464 	if (nprovs > 0) {
16465 		/*
16466 		 * Now that this is in-kernel, we change the sense of the
16467 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16468 		 * and dofhp_addr denotes the address at user-level.
16469 		 */
16470 		dhp->dofhp_addr = dhp->dofhp_dof;
16471 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16472 
16473 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16474 			mutex_exit(&dtrace_lock);
16475 			dtrace_helper_provider_register(p, help, dhp);
16476 			mutex_enter(&dtrace_lock);
16477 
16478 			destroy = 0;
16479 		}
16480 	}
16481 
16482 	if (destroy)
16483 		dtrace_dof_destroy(dof);
16484 
16485 	return (gen);
16486 }
16487 
16488 static dtrace_helpers_t *
16489 dtrace_helpers_create(proc_t *p)
16490 {
16491 	dtrace_helpers_t *help;
16492 
16493 	ASSERT(MUTEX_HELD(&dtrace_lock));
16494 	ASSERT(p->p_dtrace_helpers == NULL);
16495 
16496 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16497 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16498 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16499 
16500 	p->p_dtrace_helpers = help;
16501 	dtrace_helpers++;
16502 
16503 	return (help);
16504 }
16505 
16506 #ifdef illumos
16507 static
16508 #endif
16509 void
16510 dtrace_helpers_destroy(proc_t *p)
16511 {
16512 	dtrace_helpers_t *help;
16513 	dtrace_vstate_t *vstate;
16514 #ifdef illumos
16515 	proc_t *p = curproc;
16516 #endif
16517 	int i;
16518 
16519 	mutex_enter(&dtrace_lock);
16520 
16521 	ASSERT(p->p_dtrace_helpers != NULL);
16522 	ASSERT(dtrace_helpers > 0);
16523 
16524 	help = p->p_dtrace_helpers;
16525 	vstate = &help->dthps_vstate;
16526 
16527 	/*
16528 	 * We're now going to lose the help from this process.
16529 	 */
16530 	p->p_dtrace_helpers = NULL;
16531 	dtrace_sync();
16532 
16533 	/*
16534 	 * Destory the helper actions.
16535 	 */
16536 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16537 		dtrace_helper_action_t *h, *next;
16538 
16539 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16540 			next = h->dtha_next;
16541 			dtrace_helper_action_destroy(h, vstate);
16542 			h = next;
16543 		}
16544 	}
16545 
16546 	mutex_exit(&dtrace_lock);
16547 
16548 	/*
16549 	 * Destroy the helper providers.
16550 	 */
16551 	if (help->dthps_maxprovs > 0) {
16552 		mutex_enter(&dtrace_meta_lock);
16553 		if (dtrace_meta_pid != NULL) {
16554 			ASSERT(dtrace_deferred_pid == NULL);
16555 
16556 			for (i = 0; i < help->dthps_nprovs; i++) {
16557 				dtrace_helper_provider_remove(
16558 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16559 			}
16560 		} else {
16561 			mutex_enter(&dtrace_lock);
16562 			ASSERT(help->dthps_deferred == 0 ||
16563 			    help->dthps_next != NULL ||
16564 			    help->dthps_prev != NULL ||
16565 			    help == dtrace_deferred_pid);
16566 
16567 			/*
16568 			 * Remove the helper from the deferred list.
16569 			 */
16570 			if (help->dthps_next != NULL)
16571 				help->dthps_next->dthps_prev = help->dthps_prev;
16572 			if (help->dthps_prev != NULL)
16573 				help->dthps_prev->dthps_next = help->dthps_next;
16574 			if (dtrace_deferred_pid == help) {
16575 				dtrace_deferred_pid = help->dthps_next;
16576 				ASSERT(help->dthps_prev == NULL);
16577 			}
16578 
16579 			mutex_exit(&dtrace_lock);
16580 		}
16581 
16582 		mutex_exit(&dtrace_meta_lock);
16583 
16584 		for (i = 0; i < help->dthps_nprovs; i++) {
16585 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16586 		}
16587 
16588 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16589 		    sizeof (dtrace_helper_provider_t *));
16590 	}
16591 
16592 	mutex_enter(&dtrace_lock);
16593 
16594 	dtrace_vstate_fini(&help->dthps_vstate);
16595 	kmem_free(help->dthps_actions,
16596 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16597 	kmem_free(help, sizeof (dtrace_helpers_t));
16598 
16599 	--dtrace_helpers;
16600 	mutex_exit(&dtrace_lock);
16601 }
16602 
16603 #ifdef illumos
16604 static
16605 #endif
16606 void
16607 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16608 {
16609 	dtrace_helpers_t *help, *newhelp;
16610 	dtrace_helper_action_t *helper, *new, *last;
16611 	dtrace_difo_t *dp;
16612 	dtrace_vstate_t *vstate;
16613 	int i, j, sz, hasprovs = 0;
16614 
16615 	mutex_enter(&dtrace_lock);
16616 	ASSERT(from->p_dtrace_helpers != NULL);
16617 	ASSERT(dtrace_helpers > 0);
16618 
16619 	help = from->p_dtrace_helpers;
16620 	newhelp = dtrace_helpers_create(to);
16621 	ASSERT(to->p_dtrace_helpers != NULL);
16622 
16623 	newhelp->dthps_generation = help->dthps_generation;
16624 	vstate = &newhelp->dthps_vstate;
16625 
16626 	/*
16627 	 * Duplicate the helper actions.
16628 	 */
16629 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16630 		if ((helper = help->dthps_actions[i]) == NULL)
16631 			continue;
16632 
16633 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16634 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16635 			    KM_SLEEP);
16636 			new->dtha_generation = helper->dtha_generation;
16637 
16638 			if ((dp = helper->dtha_predicate) != NULL) {
16639 				dp = dtrace_difo_duplicate(dp, vstate);
16640 				new->dtha_predicate = dp;
16641 			}
16642 
16643 			new->dtha_nactions = helper->dtha_nactions;
16644 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16645 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16646 
16647 			for (j = 0; j < new->dtha_nactions; j++) {
16648 				dtrace_difo_t *dp = helper->dtha_actions[j];
16649 
16650 				ASSERT(dp != NULL);
16651 				dp = dtrace_difo_duplicate(dp, vstate);
16652 				new->dtha_actions[j] = dp;
16653 			}
16654 
16655 			if (last != NULL) {
16656 				last->dtha_next = new;
16657 			} else {
16658 				newhelp->dthps_actions[i] = new;
16659 			}
16660 
16661 			last = new;
16662 		}
16663 	}
16664 
16665 	/*
16666 	 * Duplicate the helper providers and register them with the
16667 	 * DTrace framework.
16668 	 */
16669 	if (help->dthps_nprovs > 0) {
16670 		newhelp->dthps_nprovs = help->dthps_nprovs;
16671 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16672 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16673 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16674 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16675 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16676 			newhelp->dthps_provs[i]->dthp_ref++;
16677 		}
16678 
16679 		hasprovs = 1;
16680 	}
16681 
16682 	mutex_exit(&dtrace_lock);
16683 
16684 	if (hasprovs)
16685 		dtrace_helper_provider_register(to, newhelp, NULL);
16686 }
16687 
16688 /*
16689  * DTrace Hook Functions
16690  */
16691 static void
16692 dtrace_module_loaded(modctl_t *ctl)
16693 {
16694 	dtrace_provider_t *prv;
16695 
16696 	mutex_enter(&dtrace_provider_lock);
16697 #ifdef illumos
16698 	mutex_enter(&mod_lock);
16699 #endif
16700 
16701 #ifdef illumos
16702 	ASSERT(ctl->mod_busy);
16703 #endif
16704 
16705 	/*
16706 	 * We're going to call each providers per-module provide operation
16707 	 * specifying only this module.
16708 	 */
16709 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16710 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16711 
16712 #ifdef illumos
16713 	mutex_exit(&mod_lock);
16714 #endif
16715 	mutex_exit(&dtrace_provider_lock);
16716 
16717 	/*
16718 	 * If we have any retained enablings, we need to match against them.
16719 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16720 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16721 	 * module.  (In particular, this happens when loading scheduling
16722 	 * classes.)  So if we have any retained enablings, we need to dispatch
16723 	 * our task queue to do the match for us.
16724 	 */
16725 	mutex_enter(&dtrace_lock);
16726 
16727 	if (dtrace_retained == NULL) {
16728 		mutex_exit(&dtrace_lock);
16729 		return;
16730 	}
16731 
16732 	(void)taskq_dispatch(dtrace_taskq,
16733 	    (task_func_t *)dtrace_enabling_matchall_task, NULL, TQ_SLEEP);
16734 
16735 	mutex_exit(&dtrace_lock);
16736 
16737 	/*
16738 	 * And now, for a little heuristic sleaze:  in general, we want to
16739 	 * match modules as soon as they load.  However, we cannot guarantee
16740 	 * this, because it would lead us to the lock ordering violation
16741 	 * outlined above.  The common case, of course, is that cpu_lock is
16742 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16743 	 * long enough for the task queue to do its work.  If it's not, it's
16744 	 * not a serious problem -- it just means that the module that we
16745 	 * just loaded may not be immediately instrumentable.
16746 	 */
16747 	delay(1);
16748 }
16749 
16750 static void
16751 #ifdef illumos
16752 dtrace_module_unloaded(modctl_t *ctl)
16753 #else
16754 dtrace_module_unloaded(modctl_t *ctl, int *error)
16755 #endif
16756 {
16757 	dtrace_probe_t template, *probe, *first, *next;
16758 	dtrace_provider_t *prov;
16759 #ifndef illumos
16760 	char modname[DTRACE_MODNAMELEN];
16761 	size_t len;
16762 #endif
16763 
16764 #ifdef illumos
16765 	template.dtpr_mod = ctl->mod_modname;
16766 #else
16767 	/* Handle the fact that ctl->filename may end in ".ko". */
16768 	strlcpy(modname, ctl->filename, sizeof(modname));
16769 	len = strlen(ctl->filename);
16770 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16771 		modname[len - 3] = '\0';
16772 	template.dtpr_mod = modname;
16773 #endif
16774 
16775 	mutex_enter(&dtrace_provider_lock);
16776 #ifdef illumos
16777 	mutex_enter(&mod_lock);
16778 #endif
16779 	mutex_enter(&dtrace_lock);
16780 
16781 #ifndef illumos
16782 	if (ctl->nenabled > 0) {
16783 		/* Don't allow unloads if a probe is enabled. */
16784 		mutex_exit(&dtrace_provider_lock);
16785 		mutex_exit(&dtrace_lock);
16786 		*error = -1;
16787 		printf(
16788 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16789 		return;
16790 	}
16791 #endif
16792 
16793 	if (dtrace_bymod == NULL) {
16794 		/*
16795 		 * The DTrace module is loaded (obviously) but not attached;
16796 		 * we don't have any work to do.
16797 		 */
16798 		mutex_exit(&dtrace_provider_lock);
16799 #ifdef illumos
16800 		mutex_exit(&mod_lock);
16801 #endif
16802 		mutex_exit(&dtrace_lock);
16803 		return;
16804 	}
16805 
16806 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16807 	    probe != NULL; probe = probe->dtpr_nextmod) {
16808 		if (probe->dtpr_ecb != NULL) {
16809 			mutex_exit(&dtrace_provider_lock);
16810 #ifdef illumos
16811 			mutex_exit(&mod_lock);
16812 #endif
16813 			mutex_exit(&dtrace_lock);
16814 
16815 			/*
16816 			 * This shouldn't _actually_ be possible -- we're
16817 			 * unloading a module that has an enabled probe in it.
16818 			 * (It's normally up to the provider to make sure that
16819 			 * this can't happen.)  However, because dtps_enable()
16820 			 * doesn't have a failure mode, there can be an
16821 			 * enable/unload race.  Upshot:  we don't want to
16822 			 * assert, but we're not going to disable the
16823 			 * probe, either.
16824 			 */
16825 			if (dtrace_err_verbose) {
16826 #ifdef illumos
16827 				cmn_err(CE_WARN, "unloaded module '%s' had "
16828 				    "enabled probes", ctl->mod_modname);
16829 #else
16830 				cmn_err(CE_WARN, "unloaded module '%s' had "
16831 				    "enabled probes", modname);
16832 #endif
16833 			}
16834 
16835 			return;
16836 		}
16837 	}
16838 
16839 	probe = first;
16840 
16841 	for (first = NULL; probe != NULL; probe = next) {
16842 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16843 
16844 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16845 
16846 		next = probe->dtpr_nextmod;
16847 		dtrace_hash_remove(dtrace_bymod, probe);
16848 		dtrace_hash_remove(dtrace_byfunc, probe);
16849 		dtrace_hash_remove(dtrace_byname, probe);
16850 
16851 		if (first == NULL) {
16852 			first = probe;
16853 			probe->dtpr_nextmod = NULL;
16854 		} else {
16855 			probe->dtpr_nextmod = first;
16856 			first = probe;
16857 		}
16858 	}
16859 
16860 	/*
16861 	 * We've removed all of the module's probes from the hash chains and
16862 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16863 	 * everyone has cleared out from any probe array processing.
16864 	 */
16865 	dtrace_sync();
16866 
16867 	for (probe = first; probe != NULL; probe = first) {
16868 		first = probe->dtpr_nextmod;
16869 		prov = probe->dtpr_provider;
16870 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16871 		    probe->dtpr_arg);
16872 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16873 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16874 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16875 #ifdef illumos
16876 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16877 #else
16878 		free_unr(dtrace_arena, probe->dtpr_id);
16879 #endif
16880 		kmem_free(probe, sizeof (dtrace_probe_t));
16881 	}
16882 
16883 	mutex_exit(&dtrace_lock);
16884 #ifdef illumos
16885 	mutex_exit(&mod_lock);
16886 #endif
16887 	mutex_exit(&dtrace_provider_lock);
16888 }
16889 
16890 #ifndef illumos
16891 static void
16892 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16893 {
16894 
16895 	dtrace_module_loaded(lf);
16896 }
16897 
16898 static void
16899 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16900 {
16901 
16902 	if (*error != 0)
16903 		/* We already have an error, so don't do anything. */
16904 		return;
16905 	dtrace_module_unloaded(lf, error);
16906 }
16907 #endif
16908 
16909 #ifdef illumos
16910 static void
16911 dtrace_suspend(void)
16912 {
16913 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16914 }
16915 
16916 static void
16917 dtrace_resume(void)
16918 {
16919 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16920 }
16921 #endif
16922 
16923 static int
16924 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16925 {
16926 	ASSERT(MUTEX_HELD(&cpu_lock));
16927 	mutex_enter(&dtrace_lock);
16928 
16929 	switch (what) {
16930 	case CPU_CONFIG: {
16931 		dtrace_state_t *state;
16932 		dtrace_optval_t *opt, rs, c;
16933 
16934 		/*
16935 		 * For now, we only allocate a new buffer for anonymous state.
16936 		 */
16937 		if ((state = dtrace_anon.dta_state) == NULL)
16938 			break;
16939 
16940 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16941 			break;
16942 
16943 		opt = state->dts_options;
16944 		c = opt[DTRACEOPT_CPU];
16945 
16946 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16947 			break;
16948 
16949 		/*
16950 		 * Regardless of what the actual policy is, we're going to
16951 		 * temporarily set our resize policy to be manual.  We're
16952 		 * also going to temporarily set our CPU option to denote
16953 		 * the newly configured CPU.
16954 		 */
16955 		rs = opt[DTRACEOPT_BUFRESIZE];
16956 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16957 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16958 
16959 		(void) dtrace_state_buffers(state);
16960 
16961 		opt[DTRACEOPT_BUFRESIZE] = rs;
16962 		opt[DTRACEOPT_CPU] = c;
16963 
16964 		break;
16965 	}
16966 
16967 	case CPU_UNCONFIG:
16968 		/*
16969 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16970 		 * buffer will be freed when the consumer exits.)
16971 		 */
16972 		break;
16973 
16974 	default:
16975 		break;
16976 	}
16977 
16978 	mutex_exit(&dtrace_lock);
16979 	return (0);
16980 }
16981 
16982 #ifdef illumos
16983 static void
16984 dtrace_cpu_setup_initial(processorid_t cpu)
16985 {
16986 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16987 }
16988 #endif
16989 
16990 static void
16991 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16992 {
16993 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16994 		int osize, nsize;
16995 		dtrace_toxrange_t *range;
16996 
16997 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16998 
16999 		if (osize == 0) {
17000 			ASSERT(dtrace_toxrange == NULL);
17001 			ASSERT(dtrace_toxranges_max == 0);
17002 			dtrace_toxranges_max = 1;
17003 		} else {
17004 			dtrace_toxranges_max <<= 1;
17005 		}
17006 
17007 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17008 		range = kmem_zalloc(nsize, KM_SLEEP);
17009 
17010 		if (dtrace_toxrange != NULL) {
17011 			ASSERT(osize != 0);
17012 			bcopy(dtrace_toxrange, range, osize);
17013 			kmem_free(dtrace_toxrange, osize);
17014 		}
17015 
17016 		dtrace_toxrange = range;
17017 	}
17018 
17019 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17020 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17021 
17022 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17023 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17024 	dtrace_toxranges++;
17025 }
17026 
17027 static void
17028 dtrace_getf_barrier(void)
17029 {
17030 #ifdef illumos
17031 	/*
17032 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17033 	 * that contain calls to getf(), this routine will be called on every
17034 	 * closef() before either the underlying vnode is released or the
17035 	 * file_t itself is freed.  By the time we are here, it is essential
17036 	 * that the file_t can no longer be accessed from a call to getf()
17037 	 * in probe context -- that assures that a dtrace_sync() can be used
17038 	 * to clear out any enablings referring to the old structures.
17039 	 */
17040 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17041 	    kcred->cr_zone->zone_dtrace_getf != 0)
17042 		dtrace_sync();
17043 #endif
17044 }
17045 
17046 /*
17047  * DTrace Driver Cookbook Functions
17048  */
17049 #ifdef illumos
17050 /*ARGSUSED*/
17051 static int
17052 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17053 {
17054 	dtrace_provider_id_t id;
17055 	dtrace_state_t *state = NULL;
17056 	dtrace_enabling_t *enab;
17057 
17058 	mutex_enter(&cpu_lock);
17059 	mutex_enter(&dtrace_provider_lock);
17060 	mutex_enter(&dtrace_lock);
17061 
17062 	if (ddi_soft_state_init(&dtrace_softstate,
17063 	    sizeof (dtrace_state_t), 0) != 0) {
17064 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17065 		mutex_exit(&cpu_lock);
17066 		mutex_exit(&dtrace_provider_lock);
17067 		mutex_exit(&dtrace_lock);
17068 		return (DDI_FAILURE);
17069 	}
17070 
17071 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17072 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17073 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17074 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17075 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17076 		ddi_remove_minor_node(devi, NULL);
17077 		ddi_soft_state_fini(&dtrace_softstate);
17078 		mutex_exit(&cpu_lock);
17079 		mutex_exit(&dtrace_provider_lock);
17080 		mutex_exit(&dtrace_lock);
17081 		return (DDI_FAILURE);
17082 	}
17083 
17084 	ddi_report_dev(devi);
17085 	dtrace_devi = devi;
17086 
17087 	dtrace_modload = dtrace_module_loaded;
17088 	dtrace_modunload = dtrace_module_unloaded;
17089 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17090 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17091 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17092 	dtrace_cpustart_init = dtrace_suspend;
17093 	dtrace_cpustart_fini = dtrace_resume;
17094 	dtrace_debugger_init = dtrace_suspend;
17095 	dtrace_debugger_fini = dtrace_resume;
17096 
17097 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17098 
17099 	ASSERT(MUTEX_HELD(&cpu_lock));
17100 
17101 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17102 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17103 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17104 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17105 	    VM_SLEEP | VMC_IDENTIFIER);
17106 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17107 	    1, INT_MAX, 0);
17108 
17109 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17110 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17111 	    NULL, NULL, NULL, NULL, NULL, 0);
17112 
17113 	ASSERT(MUTEX_HELD(&cpu_lock));
17114 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17115 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17116 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17117 
17118 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17119 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17120 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17121 
17122 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17123 	    offsetof(dtrace_probe_t, dtpr_nextname),
17124 	    offsetof(dtrace_probe_t, dtpr_prevname));
17125 
17126 	if (dtrace_retain_max < 1) {
17127 		cmn_err(CE_WARN, "illegal value (%zu) for dtrace_retain_max; "
17128 		    "setting to 1", dtrace_retain_max);
17129 		dtrace_retain_max = 1;
17130 	}
17131 
17132 	/*
17133 	 * Now discover our toxic ranges.
17134 	 */
17135 	dtrace_toxic_ranges(dtrace_toxrange_add);
17136 
17137 	/*
17138 	 * Before we register ourselves as a provider to our own framework,
17139 	 * we would like to assert that dtrace_provider is NULL -- but that's
17140 	 * not true if we were loaded as a dependency of a DTrace provider.
17141 	 * Once we've registered, we can assert that dtrace_provider is our
17142 	 * pseudo provider.
17143 	 */
17144 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17145 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17146 
17147 	ASSERT(dtrace_provider != NULL);
17148 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17149 
17150 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17151 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17152 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17153 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17154 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17155 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17156 
17157 	dtrace_anon_property();
17158 	mutex_exit(&cpu_lock);
17159 
17160 	/*
17161 	 * If there are already providers, we must ask them to provide their
17162 	 * probes, and then match any anonymous enabling against them.  Note
17163 	 * that there should be no other retained enablings at this time:
17164 	 * the only retained enablings at this time should be the anonymous
17165 	 * enabling.
17166 	 */
17167 	if (dtrace_anon.dta_enabling != NULL) {
17168 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17169 
17170 		dtrace_enabling_provide(NULL);
17171 		state = dtrace_anon.dta_state;
17172 
17173 		/*
17174 		 * We couldn't hold cpu_lock across the above call to
17175 		 * dtrace_enabling_provide(), but we must hold it to actually
17176 		 * enable the probes.  We have to drop all of our locks, pick
17177 		 * up cpu_lock, and regain our locks before matching the
17178 		 * retained anonymous enabling.
17179 		 */
17180 		mutex_exit(&dtrace_lock);
17181 		mutex_exit(&dtrace_provider_lock);
17182 
17183 		mutex_enter(&cpu_lock);
17184 		mutex_enter(&dtrace_provider_lock);
17185 		mutex_enter(&dtrace_lock);
17186 
17187 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17188 			(void) dtrace_enabling_match(enab, NULL);
17189 
17190 		mutex_exit(&cpu_lock);
17191 	}
17192 
17193 	mutex_exit(&dtrace_lock);
17194 	mutex_exit(&dtrace_provider_lock);
17195 
17196 	if (state != NULL) {
17197 		/*
17198 		 * If we created any anonymous state, set it going now.
17199 		 */
17200 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17201 	}
17202 
17203 	return (DDI_SUCCESS);
17204 }
17205 #endif	/* illumos */
17206 
17207 #ifndef illumos
17208 static void dtrace_dtr(void *);
17209 #endif
17210 
17211 /*ARGSUSED*/
17212 static int
17213 #ifdef illumos
17214 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17215 #else
17216 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17217 #endif
17218 {
17219 	dtrace_state_t *state;
17220 	uint32_t priv;
17221 	uid_t uid;
17222 	zoneid_t zoneid;
17223 
17224 #ifdef illumos
17225 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17226 		return (0);
17227 
17228 	/*
17229 	 * If this wasn't an open with the "helper" minor, then it must be
17230 	 * the "dtrace" minor.
17231 	 */
17232 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17233 		return (ENXIO);
17234 #else
17235 	cred_t *cred_p = NULL;
17236 	cred_p = dev->si_cred;
17237 
17238 	/*
17239 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17240 	 * caller lacks sufficient permission to do anything with DTrace.
17241 	 */
17242 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17243 	if (priv == DTRACE_PRIV_NONE) {
17244 #endif
17245 
17246 		return (EACCES);
17247 	}
17248 
17249 	/*
17250 	 * Ask all providers to provide all their probes.
17251 	 */
17252 	mutex_enter(&dtrace_provider_lock);
17253 	dtrace_probe_provide(NULL, NULL);
17254 	mutex_exit(&dtrace_provider_lock);
17255 
17256 	mutex_enter(&cpu_lock);
17257 	mutex_enter(&dtrace_lock);
17258 	dtrace_opens++;
17259 	dtrace_membar_producer();
17260 
17261 #ifdef illumos
17262 	/*
17263 	 * If the kernel debugger is active (that is, if the kernel debugger
17264 	 * modified text in some way), we won't allow the open.
17265 	 */
17266 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17267 		dtrace_opens--;
17268 		mutex_exit(&cpu_lock);
17269 		mutex_exit(&dtrace_lock);
17270 		return (EBUSY);
17271 	}
17272 
17273 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17274 		/*
17275 		 * If DTrace helper tracing is enabled, we need to allocate the
17276 		 * trace buffer and initialize the values.
17277 		 */
17278 		dtrace_helptrace_buffer =
17279 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17280 		dtrace_helptrace_next = 0;
17281 		dtrace_helptrace_wrapped = 0;
17282 		dtrace_helptrace_enable = 0;
17283 	}
17284 
17285 	state = dtrace_state_create(devp, cred_p);
17286 #else
17287 	state = dtrace_state_create(dev, NULL);
17288 	devfs_set_cdevpriv(state, dtrace_dtr);
17289 #endif
17290 
17291 	mutex_exit(&cpu_lock);
17292 
17293 	if (state == NULL) {
17294 #ifdef illumos
17295 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17296 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17297 #else
17298 		--dtrace_opens;
17299 #endif
17300 		mutex_exit(&dtrace_lock);
17301 		return (EAGAIN);
17302 	}
17303 
17304 	mutex_exit(&dtrace_lock);
17305 
17306 	return (0);
17307 }
17308 
17309 /*ARGSUSED*/
17310 #ifdef illumos
17311 static int
17312 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17313 #else
17314 static void
17315 dtrace_dtr(void *data)
17316 #endif
17317 {
17318 #ifdef illumos
17319 	minor_t minor = getminor(dev);
17320 	dtrace_state_t *state;
17321 #endif
17322 	dtrace_helptrace_t *buf = NULL;
17323 
17324 #ifdef illumos
17325 	if (minor == DTRACEMNRN_HELPER)
17326 		return (0);
17327 
17328 	state = ddi_get_soft_state(dtrace_softstate, minor);
17329 #else
17330 	dtrace_state_t *state = data;
17331 #endif
17332 
17333 	mutex_enter(&cpu_lock);
17334 	mutex_enter(&dtrace_lock);
17335 
17336 #ifdef illumos
17337 	if (state->dts_anon)
17338 #else
17339 	if (state != NULL && state->dts_anon)
17340 #endif
17341 	{
17342 		/*
17343 		 * There is anonymous state. Destroy that first.
17344 		 */
17345 		ASSERT(dtrace_anon.dta_state == NULL);
17346 		dtrace_state_destroy(state->dts_anon);
17347 	}
17348 
17349 	if (dtrace_helptrace_disable) {
17350 		/*
17351 		 * If we have been told to disable helper tracing, set the
17352 		 * buffer to NULL before calling into dtrace_state_destroy();
17353 		 * we take advantage of its dtrace_sync() to know that no
17354 		 * CPU is in probe context with enabled helper tracing
17355 		 * after it returns.
17356 		 */
17357 		buf = dtrace_helptrace_buffer;
17358 		dtrace_helptrace_buffer = NULL;
17359 	}
17360 
17361 #ifdef illumos
17362 	dtrace_state_destroy(state);
17363 #else
17364 	if (state != NULL) {
17365 		dtrace_state_destroy(state);
17366 		kmem_free(state, 0);
17367 	}
17368 #endif
17369 	ASSERT(dtrace_opens > 0);
17370 
17371 #ifdef illumos
17372 	/*
17373 	 * Only relinquish control of the kernel debugger interface when there
17374 	 * are no consumers and no anonymous enablings.
17375 	 */
17376 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17377 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17378 #else
17379 	--dtrace_opens;
17380 #endif
17381 
17382 	if (buf != NULL) {
17383 		kmem_free(buf, dtrace_helptrace_bufsize);
17384 		dtrace_helptrace_disable = 0;
17385 	}
17386 
17387 	mutex_exit(&dtrace_lock);
17388 	mutex_exit(&cpu_lock);
17389 
17390 #ifdef illumos
17391 	return (0);
17392 #endif
17393 }
17394 
17395 #ifdef illumos
17396 /*ARGSUSED*/
17397 static int
17398 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17399 {
17400 	int rval;
17401 	dof_helper_t help, *dhp = NULL;
17402 
17403 	switch (cmd) {
17404 	case DTRACEHIOC_ADDDOF:
17405 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17406 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17407 			return (EFAULT);
17408 		}
17409 
17410 		dhp = &help;
17411 		arg = (intptr_t)help.dofhp_dof;
17412 		/*FALLTHROUGH*/
17413 
17414 	case DTRACEHIOC_ADD: {
17415 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17416 
17417 		if (dof == NULL)
17418 			return (rval);
17419 
17420 		mutex_enter(&dtrace_lock);
17421 
17422 		/*
17423 		 * dtrace_helper_slurp() takes responsibility for the dof --
17424 		 * it may free it now or it may save it and free it later.
17425 		 */
17426 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17427 			*rv = rval;
17428 			rval = 0;
17429 		} else {
17430 			rval = EINVAL;
17431 		}
17432 
17433 		mutex_exit(&dtrace_lock);
17434 		return (rval);
17435 	}
17436 
17437 	case DTRACEHIOC_REMOVE: {
17438 		mutex_enter(&dtrace_lock);
17439 		rval = dtrace_helper_destroygen(NULL, arg);
17440 		mutex_exit(&dtrace_lock);
17441 
17442 		return (rval);
17443 	}
17444 
17445 	default:
17446 		break;
17447 	}
17448 
17449 	return (ENOTTY);
17450 }
17451 
17452 /*ARGSUSED*/
17453 static int
17454 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17455 {
17456 	minor_t minor = getminor(dev);
17457 	dtrace_state_t *state;
17458 	int rval;
17459 
17460 	if (minor == DTRACEMNRN_HELPER)
17461 		return (dtrace_ioctl_helper(cmd, arg, rv));
17462 
17463 	state = ddi_get_soft_state(dtrace_softstate, minor);
17464 
17465 	if (state->dts_anon) {
17466 		ASSERT(dtrace_anon.dta_state == NULL);
17467 		state = state->dts_anon;
17468 	}
17469 
17470 	switch (cmd) {
17471 	case DTRACEIOC_PROVIDER: {
17472 		dtrace_providerdesc_t pvd;
17473 		dtrace_provider_t *pvp;
17474 
17475 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17476 			return (EFAULT);
17477 
17478 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17479 		mutex_enter(&dtrace_provider_lock);
17480 
17481 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17482 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17483 				break;
17484 		}
17485 
17486 		mutex_exit(&dtrace_provider_lock);
17487 
17488 		if (pvp == NULL)
17489 			return (ESRCH);
17490 
17491 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17492 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17493 
17494 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17495 			return (EFAULT);
17496 
17497 		return (0);
17498 	}
17499 
17500 	case DTRACEIOC_EPROBE: {
17501 		dtrace_eprobedesc_t epdesc;
17502 		dtrace_ecb_t *ecb;
17503 		dtrace_action_t *act;
17504 		void *buf;
17505 		size_t size;
17506 		uintptr_t dest;
17507 		int nrecs;
17508 
17509 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17510 			return (EFAULT);
17511 
17512 		mutex_enter(&dtrace_lock);
17513 
17514 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17515 			mutex_exit(&dtrace_lock);
17516 			return (EINVAL);
17517 		}
17518 
17519 		if (ecb->dte_probe == NULL) {
17520 			mutex_exit(&dtrace_lock);
17521 			return (EINVAL);
17522 		}
17523 
17524 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17525 		epdesc.dtepd_uarg = ecb->dte_uarg;
17526 		epdesc.dtepd_size = ecb->dte_size;
17527 
17528 		nrecs = epdesc.dtepd_nrecs;
17529 		epdesc.dtepd_nrecs = 0;
17530 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17531 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17532 				continue;
17533 
17534 			epdesc.dtepd_nrecs++;
17535 		}
17536 
17537 		/*
17538 		 * Now that we have the size, we need to allocate a temporary
17539 		 * buffer in which to store the complete description.  We need
17540 		 * the temporary buffer to be able to drop dtrace_lock()
17541 		 * across the copyout(), below.
17542 		 */
17543 		size = sizeof (dtrace_eprobedesc_t) +
17544 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17545 
17546 		buf = kmem_alloc(size, KM_SLEEP);
17547 		dest = (uintptr_t)buf;
17548 
17549 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17550 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17551 
17552 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17553 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17554 				continue;
17555 
17556 			if (nrecs-- == 0)
17557 				break;
17558 
17559 			bcopy(&act->dta_rec, (void *)dest,
17560 			    sizeof (dtrace_recdesc_t));
17561 			dest += sizeof (dtrace_recdesc_t);
17562 		}
17563 
17564 		mutex_exit(&dtrace_lock);
17565 
17566 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17567 			kmem_free(buf, size);
17568 			return (EFAULT);
17569 		}
17570 
17571 		kmem_free(buf, size);
17572 		return (0);
17573 	}
17574 
17575 	case DTRACEIOC_AGGDESC: {
17576 		dtrace_aggdesc_t aggdesc;
17577 		dtrace_action_t *act;
17578 		dtrace_aggregation_t *agg;
17579 		int nrecs;
17580 		uint32_t offs;
17581 		dtrace_recdesc_t *lrec;
17582 		void *buf;
17583 		size_t size;
17584 		uintptr_t dest;
17585 
17586 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17587 			return (EFAULT);
17588 
17589 		mutex_enter(&dtrace_lock);
17590 
17591 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17592 			mutex_exit(&dtrace_lock);
17593 			return (EINVAL);
17594 		}
17595 
17596 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17597 
17598 		nrecs = aggdesc.dtagd_nrecs;
17599 		aggdesc.dtagd_nrecs = 0;
17600 
17601 		offs = agg->dtag_base;
17602 		lrec = &agg->dtag_action.dta_rec;
17603 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17604 
17605 		for (act = agg->dtag_first; ; act = act->dta_next) {
17606 			ASSERT(act->dta_intuple ||
17607 			    DTRACEACT_ISAGG(act->dta_kind));
17608 
17609 			/*
17610 			 * If this action has a record size of zero, it
17611 			 * denotes an argument to the aggregating action.
17612 			 * Because the presence of this record doesn't (or
17613 			 * shouldn't) affect the way the data is interpreted,
17614 			 * we don't copy it out to save user-level the
17615 			 * confusion of dealing with a zero-length record.
17616 			 */
17617 			if (act->dta_rec.dtrd_size == 0) {
17618 				ASSERT(agg->dtag_hasarg);
17619 				continue;
17620 			}
17621 
17622 			aggdesc.dtagd_nrecs++;
17623 
17624 			if (act == &agg->dtag_action)
17625 				break;
17626 		}
17627 
17628 		/*
17629 		 * Now that we have the size, we need to allocate a temporary
17630 		 * buffer in which to store the complete description.  We need
17631 		 * the temporary buffer to be able to drop dtrace_lock()
17632 		 * across the copyout(), below.
17633 		 */
17634 		size = sizeof (dtrace_aggdesc_t) +
17635 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17636 
17637 		buf = kmem_alloc(size, KM_SLEEP);
17638 		dest = (uintptr_t)buf;
17639 
17640 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17641 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17642 
17643 		for (act = agg->dtag_first; ; act = act->dta_next) {
17644 			dtrace_recdesc_t rec = act->dta_rec;
17645 
17646 			/*
17647 			 * See the comment in the above loop for why we pass
17648 			 * over zero-length records.
17649 			 */
17650 			if (rec.dtrd_size == 0) {
17651 				ASSERT(agg->dtag_hasarg);
17652 				continue;
17653 			}
17654 
17655 			if (nrecs-- == 0)
17656 				break;
17657 
17658 			rec.dtrd_offset -= offs;
17659 			bcopy(&rec, (void *)dest, sizeof (rec));
17660 			dest += sizeof (dtrace_recdesc_t);
17661 
17662 			if (act == &agg->dtag_action)
17663 				break;
17664 		}
17665 
17666 		mutex_exit(&dtrace_lock);
17667 
17668 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17669 			kmem_free(buf, size);
17670 			return (EFAULT);
17671 		}
17672 
17673 		kmem_free(buf, size);
17674 		return (0);
17675 	}
17676 
17677 	case DTRACEIOC_ENABLE: {
17678 		dof_hdr_t *dof;
17679 		dtrace_enabling_t *enab = NULL;
17680 		dtrace_vstate_t *vstate;
17681 		int err = 0;
17682 
17683 		*rv = 0;
17684 
17685 		/*
17686 		 * If a NULL argument has been passed, we take this as our
17687 		 * cue to reevaluate our enablings.
17688 		 */
17689 		if (arg == NULL) {
17690 			dtrace_enabling_matchall();
17691 
17692 			return (0);
17693 		}
17694 
17695 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17696 			return (rval);
17697 
17698 		mutex_enter(&cpu_lock);
17699 		mutex_enter(&dtrace_lock);
17700 		vstate = &state->dts_vstate;
17701 
17702 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17703 			mutex_exit(&dtrace_lock);
17704 			mutex_exit(&cpu_lock);
17705 			dtrace_dof_destroy(dof);
17706 			return (EBUSY);
17707 		}
17708 
17709 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17710 			mutex_exit(&dtrace_lock);
17711 			mutex_exit(&cpu_lock);
17712 			dtrace_dof_destroy(dof);
17713 			return (EINVAL);
17714 		}
17715 
17716 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17717 			dtrace_enabling_destroy(enab);
17718 			mutex_exit(&dtrace_lock);
17719 			mutex_exit(&cpu_lock);
17720 			dtrace_dof_destroy(dof);
17721 			return (rval);
17722 		}
17723 
17724 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17725 			err = dtrace_enabling_retain(enab);
17726 		} else {
17727 			dtrace_enabling_destroy(enab);
17728 		}
17729 
17730 		mutex_exit(&cpu_lock);
17731 		mutex_exit(&dtrace_lock);
17732 		dtrace_dof_destroy(dof);
17733 
17734 		return (err);
17735 	}
17736 
17737 	case DTRACEIOC_REPLICATE: {
17738 		dtrace_repldesc_t desc;
17739 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17740 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17741 		int err;
17742 
17743 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17744 			return (EFAULT);
17745 
17746 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17747 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17748 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17749 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17750 
17751 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17752 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17753 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17754 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17755 
17756 		mutex_enter(&dtrace_lock);
17757 		err = dtrace_enabling_replicate(state, match, create);
17758 		mutex_exit(&dtrace_lock);
17759 
17760 		return (err);
17761 	}
17762 
17763 	case DTRACEIOC_PROBEMATCH:
17764 	case DTRACEIOC_PROBES: {
17765 		dtrace_probe_t *probe = NULL;
17766 		dtrace_probedesc_t desc;
17767 		dtrace_probekey_t pkey;
17768 		dtrace_id_t i;
17769 		int m = 0;
17770 		uint32_t priv;
17771 		uid_t uid;
17772 		zoneid_t zoneid;
17773 
17774 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17775 			return (EFAULT);
17776 
17777 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17778 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17779 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17780 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17781 
17782 		/*
17783 		 * Before we attempt to match this probe, we want to give
17784 		 * all providers the opportunity to provide it.
17785 		 */
17786 		if (desc.dtpd_id == DTRACE_IDNONE) {
17787 			mutex_enter(&dtrace_provider_lock);
17788 			dtrace_probe_provide(&desc, NULL);
17789 			mutex_exit(&dtrace_provider_lock);
17790 			desc.dtpd_id++;
17791 		}
17792 
17793 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17794 			dtrace_probekey(&desc, &pkey);
17795 			pkey.dtpk_id = DTRACE_IDNONE;
17796 		}
17797 
17798 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17799 
17800 		mutex_enter(&dtrace_lock);
17801 
17802 		if (cmd == DTRACEIOC_PROBEMATCH) {
17803 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17804 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17805 				    (m = dtrace_match_probe(probe, &pkey,
17806 				    priv, uid, zoneid)) != 0)
17807 					break;
17808 			}
17809 
17810 			if (m < 0) {
17811 				mutex_exit(&dtrace_lock);
17812 				return (EINVAL);
17813 			}
17814 
17815 		} else {
17816 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17817 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17818 				    dtrace_match_priv(probe, priv, uid, zoneid))
17819 					break;
17820 			}
17821 		}
17822 
17823 		if (probe == NULL) {
17824 			mutex_exit(&dtrace_lock);
17825 			return (ESRCH);
17826 		}
17827 
17828 		dtrace_probe_description(probe, &desc);
17829 		mutex_exit(&dtrace_lock);
17830 
17831 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17832 			return (EFAULT);
17833 
17834 		return (0);
17835 	}
17836 
17837 	case DTRACEIOC_PROBEARG: {
17838 		dtrace_argdesc_t desc;
17839 		dtrace_probe_t *probe;
17840 		dtrace_provider_t *prov;
17841 
17842 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17843 			return (EFAULT);
17844 
17845 		if (desc.dtargd_id == DTRACE_IDNONE)
17846 			return (EINVAL);
17847 
17848 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17849 			return (EINVAL);
17850 
17851 		mutex_enter(&dtrace_provider_lock);
17852 		mutex_enter(&mod_lock);
17853 		mutex_enter(&dtrace_lock);
17854 
17855 		if (desc.dtargd_id > dtrace_nprobes) {
17856 			mutex_exit(&dtrace_lock);
17857 			mutex_exit(&mod_lock);
17858 			mutex_exit(&dtrace_provider_lock);
17859 			return (EINVAL);
17860 		}
17861 
17862 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17863 			mutex_exit(&dtrace_lock);
17864 			mutex_exit(&mod_lock);
17865 			mutex_exit(&dtrace_provider_lock);
17866 			return (EINVAL);
17867 		}
17868 
17869 		mutex_exit(&dtrace_lock);
17870 
17871 		prov = probe->dtpr_provider;
17872 
17873 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17874 			/*
17875 			 * There isn't any typed information for this probe.
17876 			 * Set the argument number to DTRACE_ARGNONE.
17877 			 */
17878 			desc.dtargd_ndx = DTRACE_ARGNONE;
17879 		} else {
17880 			desc.dtargd_native[0] = '\0';
17881 			desc.dtargd_xlate[0] = '\0';
17882 			desc.dtargd_mapping = desc.dtargd_ndx;
17883 
17884 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17885 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17886 		}
17887 
17888 		mutex_exit(&mod_lock);
17889 		mutex_exit(&dtrace_provider_lock);
17890 
17891 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17892 			return (EFAULT);
17893 
17894 		return (0);
17895 	}
17896 
17897 	case DTRACEIOC_GO: {
17898 		processorid_t cpuid;
17899 		rval = dtrace_state_go(state, &cpuid);
17900 
17901 		if (rval != 0)
17902 			return (rval);
17903 
17904 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17905 			return (EFAULT);
17906 
17907 		return (0);
17908 	}
17909 
17910 	case DTRACEIOC_STOP: {
17911 		processorid_t cpuid;
17912 
17913 		mutex_enter(&dtrace_lock);
17914 		rval = dtrace_state_stop(state, &cpuid);
17915 		mutex_exit(&dtrace_lock);
17916 
17917 		if (rval != 0)
17918 			return (rval);
17919 
17920 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17921 			return (EFAULT);
17922 
17923 		return (0);
17924 	}
17925 
17926 	case DTRACEIOC_DOFGET: {
17927 		dof_hdr_t hdr, *dof;
17928 		uint64_t len;
17929 
17930 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17931 			return (EFAULT);
17932 
17933 		mutex_enter(&dtrace_lock);
17934 		dof = dtrace_dof_create(state);
17935 		mutex_exit(&dtrace_lock);
17936 
17937 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17938 		rval = copyout(dof, (void *)arg, len);
17939 		dtrace_dof_destroy(dof);
17940 
17941 		return (rval == 0 ? 0 : EFAULT);
17942 	}
17943 
17944 	case DTRACEIOC_AGGSNAP:
17945 	case DTRACEIOC_BUFSNAP: {
17946 		dtrace_bufdesc_t desc;
17947 		caddr_t cached;
17948 		dtrace_buffer_t *buf;
17949 
17950 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17951 			return (EFAULT);
17952 
17953 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17954 			return (EINVAL);
17955 
17956 		mutex_enter(&dtrace_lock);
17957 
17958 		if (cmd == DTRACEIOC_BUFSNAP) {
17959 			buf = &state->dts_buffer[desc.dtbd_cpu];
17960 		} else {
17961 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17962 		}
17963 
17964 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17965 			size_t sz = buf->dtb_offset;
17966 
17967 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17968 				mutex_exit(&dtrace_lock);
17969 				return (EBUSY);
17970 			}
17971 
17972 			/*
17973 			 * If this buffer has already been consumed, we're
17974 			 * going to indicate that there's nothing left here
17975 			 * to consume.
17976 			 */
17977 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17978 				mutex_exit(&dtrace_lock);
17979 
17980 				desc.dtbd_size = 0;
17981 				desc.dtbd_drops = 0;
17982 				desc.dtbd_errors = 0;
17983 				desc.dtbd_oldest = 0;
17984 				sz = sizeof (desc);
17985 
17986 				if (copyout(&desc, (void *)arg, sz) != 0)
17987 					return (EFAULT);
17988 
17989 				return (0);
17990 			}
17991 
17992 			/*
17993 			 * If this is a ring buffer that has wrapped, we want
17994 			 * to copy the whole thing out.
17995 			 */
17996 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17997 				dtrace_buffer_polish(buf);
17998 				sz = buf->dtb_size;
17999 			}
18000 
18001 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
18002 				mutex_exit(&dtrace_lock);
18003 				return (EFAULT);
18004 			}
18005 
18006 			desc.dtbd_size = sz;
18007 			desc.dtbd_drops = buf->dtb_drops;
18008 			desc.dtbd_errors = buf->dtb_errors;
18009 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18010 			desc.dtbd_timestamp = dtrace_gethrtime();
18011 
18012 			mutex_exit(&dtrace_lock);
18013 
18014 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18015 				return (EFAULT);
18016 
18017 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18018 
18019 			return (0);
18020 		}
18021 
18022 		if (buf->dtb_tomax == NULL) {
18023 			ASSERT(buf->dtb_xamot == NULL);
18024 			mutex_exit(&dtrace_lock);
18025 			return (ENOENT);
18026 		}
18027 
18028 		cached = buf->dtb_tomax;
18029 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18030 
18031 		dtrace_xcall(desc.dtbd_cpu,
18032 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18033 
18034 		state->dts_errors += buf->dtb_xamot_errors;
18035 
18036 		/*
18037 		 * If the buffers did not actually switch, then the cross call
18038 		 * did not take place -- presumably because the given CPU is
18039 		 * not in the ready set.  If this is the case, we'll return
18040 		 * ENOENT.
18041 		 */
18042 		if (buf->dtb_tomax == cached) {
18043 			ASSERT(buf->dtb_xamot != cached);
18044 			mutex_exit(&dtrace_lock);
18045 			return (ENOENT);
18046 		}
18047 
18048 		ASSERT(cached == buf->dtb_xamot);
18049 
18050 		/*
18051 		 * We have our snapshot; now copy it out.
18052 		 */
18053 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18054 		    buf->dtb_xamot_offset) != 0) {
18055 			mutex_exit(&dtrace_lock);
18056 			return (EFAULT);
18057 		}
18058 
18059 		desc.dtbd_size = buf->dtb_xamot_offset;
18060 		desc.dtbd_drops = buf->dtb_xamot_drops;
18061 		desc.dtbd_errors = buf->dtb_xamot_errors;
18062 		desc.dtbd_oldest = 0;
18063 		desc.dtbd_timestamp = buf->dtb_switched;
18064 
18065 		mutex_exit(&dtrace_lock);
18066 
18067 		/*
18068 		 * Finally, copy out the buffer description.
18069 		 */
18070 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18071 			return (EFAULT);
18072 
18073 		return (0);
18074 	}
18075 
18076 	case DTRACEIOC_CONF: {
18077 		dtrace_conf_t conf;
18078 
18079 		bzero(&conf, sizeof (conf));
18080 		conf.dtc_difversion = DIF_VERSION;
18081 		conf.dtc_difintregs = DIF_DIR_NREGS;
18082 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18083 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18084 
18085 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18086 			return (EFAULT);
18087 
18088 		return (0);
18089 	}
18090 
18091 	case DTRACEIOC_STATUS: {
18092 		dtrace_status_t stat;
18093 		dtrace_dstate_t *dstate;
18094 		int i, j;
18095 		uint64_t nerrs;
18096 
18097 		/*
18098 		 * See the comment in dtrace_state_deadman() for the reason
18099 		 * for setting dts_laststatus to INT64_MAX before setting
18100 		 * it to the correct value.
18101 		 */
18102 		state->dts_laststatus = INT64_MAX;
18103 		dtrace_membar_producer();
18104 		state->dts_laststatus = dtrace_gethrtime();
18105 
18106 		bzero(&stat, sizeof (stat));
18107 
18108 		mutex_enter(&dtrace_lock);
18109 
18110 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18111 			mutex_exit(&dtrace_lock);
18112 			return (ENOENT);
18113 		}
18114 
18115 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18116 			stat.dtst_exiting = 1;
18117 
18118 		nerrs = state->dts_errors;
18119 		dstate = &state->dts_vstate.dtvs_dynvars;
18120 
18121 		for (i = 0; i < NCPU; i++) {
18122 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18123 
18124 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18125 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18126 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18127 
18128 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18129 				stat.dtst_filled++;
18130 
18131 			nerrs += state->dts_buffer[i].dtb_errors;
18132 
18133 			for (j = 0; j < state->dts_nspeculations; j++) {
18134 				dtrace_speculation_t *spec;
18135 				dtrace_buffer_t *buf;
18136 
18137 				spec = &state->dts_speculations[j];
18138 				buf = &spec->dtsp_buffer[i];
18139 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18140 			}
18141 		}
18142 
18143 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18144 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18145 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18146 		stat.dtst_dblerrors = state->dts_dblerrors;
18147 		stat.dtst_killed =
18148 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18149 		stat.dtst_errors = nerrs;
18150 
18151 		mutex_exit(&dtrace_lock);
18152 
18153 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18154 			return (EFAULT);
18155 
18156 		return (0);
18157 	}
18158 
18159 	case DTRACEIOC_FORMAT: {
18160 		dtrace_fmtdesc_t fmt;
18161 		char *str;
18162 		int len;
18163 
18164 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18165 			return (EFAULT);
18166 
18167 		mutex_enter(&dtrace_lock);
18168 
18169 		if (fmt.dtfd_format == 0 ||
18170 		    fmt.dtfd_format > state->dts_nformats) {
18171 			mutex_exit(&dtrace_lock);
18172 			return (EINVAL);
18173 		}
18174 
18175 		/*
18176 		 * Format strings are allocated contiguously and they are
18177 		 * never freed; if a format index is less than the number
18178 		 * of formats, we can assert that the format map is non-NULL
18179 		 * and that the format for the specified index is non-NULL.
18180 		 */
18181 		ASSERT(state->dts_formats != NULL);
18182 		str = state->dts_formats[fmt.dtfd_format - 1];
18183 		ASSERT(str != NULL);
18184 
18185 		len = strlen(str) + 1;
18186 
18187 		if (len > fmt.dtfd_length) {
18188 			fmt.dtfd_length = len;
18189 
18190 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18191 				mutex_exit(&dtrace_lock);
18192 				return (EINVAL);
18193 			}
18194 		} else {
18195 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18196 				mutex_exit(&dtrace_lock);
18197 				return (EINVAL);
18198 			}
18199 		}
18200 
18201 		mutex_exit(&dtrace_lock);
18202 		return (0);
18203 	}
18204 
18205 	default:
18206 		break;
18207 	}
18208 
18209 	return (ENOTTY);
18210 }
18211 
18212 /*ARGSUSED*/
18213 static int
18214 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18215 {
18216 	dtrace_state_t *state;
18217 
18218 	switch (cmd) {
18219 	case DDI_DETACH:
18220 		break;
18221 
18222 	case DDI_SUSPEND:
18223 		return (DDI_SUCCESS);
18224 
18225 	default:
18226 		return (DDI_FAILURE);
18227 	}
18228 
18229 	mutex_enter(&cpu_lock);
18230 	mutex_enter(&dtrace_provider_lock);
18231 	mutex_enter(&dtrace_lock);
18232 
18233 	ASSERT(dtrace_opens == 0);
18234 
18235 	if (dtrace_helpers > 0) {
18236 		mutex_exit(&dtrace_provider_lock);
18237 		mutex_exit(&dtrace_lock);
18238 		mutex_exit(&cpu_lock);
18239 		return (DDI_FAILURE);
18240 	}
18241 
18242 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18243 		mutex_exit(&dtrace_provider_lock);
18244 		mutex_exit(&dtrace_lock);
18245 		mutex_exit(&cpu_lock);
18246 		return (DDI_FAILURE);
18247 	}
18248 
18249 	dtrace_provider = NULL;
18250 
18251 	if ((state = dtrace_anon_grab()) != NULL) {
18252 		/*
18253 		 * If there were ECBs on this state, the provider should
18254 		 * have not been allowed to detach; assert that there is
18255 		 * none.
18256 		 */
18257 		ASSERT(state->dts_necbs == 0);
18258 		dtrace_state_destroy(state);
18259 
18260 		/*
18261 		 * If we're being detached with anonymous state, we need to
18262 		 * indicate to the kernel debugger that DTrace is now inactive.
18263 		 */
18264 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18265 	}
18266 
18267 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18268 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18269 	dtrace_cpu_init = NULL;
18270 	dtrace_helpers_cleanup = NULL;
18271 	dtrace_helpers_fork = NULL;
18272 	dtrace_cpustart_init = NULL;
18273 	dtrace_cpustart_fini = NULL;
18274 	dtrace_debugger_init = NULL;
18275 	dtrace_debugger_fini = NULL;
18276 	dtrace_modload = NULL;
18277 	dtrace_modunload = NULL;
18278 
18279 	ASSERT(dtrace_getf == 0);
18280 	ASSERT(dtrace_closef == NULL);
18281 
18282 	mutex_exit(&cpu_lock);
18283 
18284 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18285 	dtrace_probes = NULL;
18286 	dtrace_nprobes = 0;
18287 
18288 	dtrace_hash_destroy(dtrace_bymod);
18289 	dtrace_hash_destroy(dtrace_byfunc);
18290 	dtrace_hash_destroy(dtrace_byname);
18291 	dtrace_bymod = NULL;
18292 	dtrace_byfunc = NULL;
18293 	dtrace_byname = NULL;
18294 
18295 	kmem_cache_destroy(dtrace_state_cache);
18296 	vmem_destroy(dtrace_minor);
18297 	vmem_destroy(dtrace_arena);
18298 
18299 	if (dtrace_toxrange != NULL) {
18300 		kmem_free(dtrace_toxrange,
18301 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18302 		dtrace_toxrange = NULL;
18303 		dtrace_toxranges = 0;
18304 		dtrace_toxranges_max = 0;
18305 	}
18306 
18307 	ddi_remove_minor_node(dtrace_devi, NULL);
18308 	dtrace_devi = NULL;
18309 
18310 	ddi_soft_state_fini(&dtrace_softstate);
18311 
18312 	ASSERT(dtrace_vtime_references == 0);
18313 	ASSERT(dtrace_opens == 0);
18314 	ASSERT(dtrace_retained == NULL);
18315 
18316 	mutex_exit(&dtrace_lock);
18317 	mutex_exit(&dtrace_provider_lock);
18318 
18319 	/*
18320 	 * We don't destroy the task queue until after we have dropped our
18321 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18322 	 * attempting to do work after we have effectively detached but before
18323 	 * the task queue has been destroyed, all tasks dispatched via the
18324 	 * task queue must check that DTrace is still attached before
18325 	 * performing any operation.
18326 	 */
18327 	taskq_destroy(dtrace_taskq);
18328 	dtrace_taskq = NULL;
18329 
18330 	return (DDI_SUCCESS);
18331 }
18332 #endif
18333 
18334 #ifdef illumos
18335 /*ARGSUSED*/
18336 static int
18337 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18338 {
18339 	int error;
18340 
18341 	switch (infocmd) {
18342 	case DDI_INFO_DEVT2DEVINFO:
18343 		*result = (void *)dtrace_devi;
18344 		error = DDI_SUCCESS;
18345 		break;
18346 	case DDI_INFO_DEVT2INSTANCE:
18347 		*result = (void *)0;
18348 		error = DDI_SUCCESS;
18349 		break;
18350 	default:
18351 		error = DDI_FAILURE;
18352 	}
18353 	return (error);
18354 }
18355 #endif
18356 
18357 #ifdef illumos
18358 static struct cb_ops dtrace_cb_ops = {
18359 	dtrace_open,		/* open */
18360 	dtrace_close,		/* close */
18361 	nulldev,		/* strategy */
18362 	nulldev,		/* print */
18363 	nodev,			/* dump */
18364 	nodev,			/* read */
18365 	nodev,			/* write */
18366 	dtrace_ioctl,		/* ioctl */
18367 	nodev,			/* devmap */
18368 	nodev,			/* mmap */
18369 	nodev,			/* segmap */
18370 	nochpoll,		/* poll */
18371 	ddi_prop_op,		/* cb_prop_op */
18372 	0,			/* streamtab  */
18373 	D_NEW | D_MP		/* Driver compatibility flag */
18374 };
18375 
18376 static struct dev_ops dtrace_ops = {
18377 	DEVO_REV,		/* devo_rev */
18378 	0,			/* refcnt */
18379 	dtrace_info,		/* get_dev_info */
18380 	nulldev,		/* identify */
18381 	nulldev,		/* probe */
18382 	dtrace_attach,		/* attach */
18383 	dtrace_detach,		/* detach */
18384 	nodev,			/* reset */
18385 	&dtrace_cb_ops,		/* driver operations */
18386 	NULL,			/* bus operations */
18387 	nodev			/* dev power */
18388 };
18389 
18390 static struct modldrv modldrv = {
18391 	&mod_driverops,		/* module type (this is a pseudo driver) */
18392 	"Dynamic Tracing",	/* name of module */
18393 	&dtrace_ops,		/* driver ops */
18394 };
18395 
18396 static struct modlinkage modlinkage = {
18397 	MODREV_1,
18398 	(void *)&modldrv,
18399 	NULL
18400 };
18401 
18402 int
18403 _init(void)
18404 {
18405 	return (mod_install(&modlinkage));
18406 }
18407 
18408 int
18409 _info(struct modinfo *modinfop)
18410 {
18411 	return (mod_info(&modlinkage, modinfop));
18412 }
18413 
18414 int
18415 _fini(void)
18416 {
18417 	return (mod_remove(&modlinkage));
18418 }
18419 #else
18420 
18421 static d_ioctl_t	dtrace_ioctl;
18422 static d_ioctl_t	dtrace_ioctl_helper;
18423 static void		dtrace_load(void *);
18424 static int		dtrace_unload(void);
18425 static struct cdev	*dtrace_dev;
18426 static struct cdev	*helper_dev;
18427 
18428 void dtrace_invop_init(void);
18429 void dtrace_invop_uninit(void);
18430 
18431 static struct cdevsw dtrace_cdevsw = {
18432 	.d_version	= D_VERSION,
18433 	.d_ioctl	= dtrace_ioctl,
18434 	.d_open		= dtrace_open,
18435 	.d_name		= "dtrace",
18436 };
18437 
18438 static struct cdevsw helper_cdevsw = {
18439 	.d_version	= D_VERSION,
18440 	.d_ioctl	= dtrace_ioctl_helper,
18441 	.d_name		= "helper",
18442 };
18443 
18444 #include <dtrace_anon.c>
18445 #include <dtrace_ioctl.c>
18446 #include <dtrace_load.c>
18447 #include <dtrace_modevent.c>
18448 #include <dtrace_sysctl.c>
18449 #include <dtrace_unload.c>
18450 #include <dtrace_vtime.c>
18451 #include <dtrace_hacks.c>
18452 
18453 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18454 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18455 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18456 
18457 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18458 MODULE_VERSION(dtrace, 1);
18459 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18460 #endif
18461