xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision a1452eec4768272056aa070db94ea7184ce1117c)
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 	*flags |= CPU_DTRACE_NOFAULT;					\
553 	/*CSTYLED*/							\
554 	rval = *((volatile uint##bits##_t *)addr);			\
555 	*flags &= ~CPU_DTRACE_NOFAULT;					\
556 									\
557 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
558 }
559 
560 #ifdef _LP64
561 #define	dtrace_loadptr	dtrace_load64
562 #else
563 #define	dtrace_loadptr	dtrace_load32
564 #endif
565 
566 #define	DTRACE_DYNHASH_FREE	0
567 #define	DTRACE_DYNHASH_SINK	1
568 #define	DTRACE_DYNHASH_VALID	2
569 
570 #define	DTRACE_MATCH_NEXT	0
571 #define	DTRACE_MATCH_DONE	1
572 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
573 #define	DTRACE_STATE_ALIGN	64
574 
575 #define	DTRACE_FLAGS2FLT(flags)						\
576 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
577 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
578 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
579 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
580 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
581 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
582 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
583 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
584 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
585 	DTRACEFLT_UNKNOWN)
586 
587 #define	DTRACEACT_ISSTRING(act)						\
588 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
589 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
590 
591 /* Function prototype definitions: */
592 static size_t dtrace_strlen(const char *, size_t);
593 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
594 static void dtrace_enabling_provide(dtrace_provider_t *);
595 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
596 static void dtrace_enabling_matchall(void);
597 static void dtrace_enabling_matchall_task(void *);
598 static void dtrace_enabling_reap(void *);
599 static dtrace_state_t *dtrace_anon_grab(void);
600 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
601     dtrace_state_t *, uint64_t, uint64_t);
602 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
603 static void dtrace_buffer_drop(dtrace_buffer_t *);
604 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
605 static ssize_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
606     dtrace_state_t *, dtrace_mstate_t *);
607 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
608     dtrace_optval_t);
609 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
610 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
611 uint16_t dtrace_load16(uintptr_t);
612 uint32_t dtrace_load32(uintptr_t);
613 uint64_t dtrace_load64(uintptr_t);
614 uint8_t dtrace_load8(uintptr_t);
615 void dtrace_dynvar_clean(dtrace_dstate_t *);
616 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
617     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
618 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
619 static int dtrace_priv_proc(dtrace_state_t *);
620 static void dtrace_getf_barrier(void);
621 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
622     dtrace_mstate_t *, dtrace_vstate_t *);
623 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
624     dtrace_mstate_t *, dtrace_vstate_t *);
625 
626 /*
627  * DTrace Probe Context Functions
628  *
629  * These functions are called from probe context.  Because probe context is
630  * any context in which C may be called, arbitrarily locks may be held,
631  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
632  * As a result, functions called from probe context may only call other DTrace
633  * support functions -- they may not interact at all with the system at large.
634  * (Note that the ASSERT macro is made probe-context safe by redefining it in
635  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
636  * loads are to be performed from probe context, they _must_ be in terms of
637  * the safe dtrace_load*() variants.
638  *
639  * Some functions in this block are not actually called from probe context;
640  * for these functions, there will be a comment above the function reading
641  * "Note:  not called from probe context."
642  */
643 void
dtrace_panic(const char * format,...)644 dtrace_panic(const char *format, ...)
645 {
646 	va_list alist;
647 
648 	va_start(alist, format);
649 #ifdef __FreeBSD__
650 	vpanic(format, alist);
651 #else
652 	dtrace_vpanic(format, alist);
653 #endif
654 	va_end(alist);
655 }
656 
657 int
dtrace_assfail(const char * a,const char * f,int l)658 dtrace_assfail(const char *a, const char *f, int l)
659 {
660 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
661 
662 	/*
663 	 * We just need something here that even the most clever compiler
664 	 * cannot optimize away.
665 	 */
666 	return (a[(uintptr_t)f]);
667 }
668 
669 /*
670  * Atomically increment a specified error counter from probe context.
671  */
672 static void
dtrace_error(uint32_t * counter)673 dtrace_error(uint32_t *counter)
674 {
675 	/*
676 	 * Most counters stored to in probe context are per-CPU counters.
677 	 * However, there are some error conditions that are sufficiently
678 	 * arcane that they don't merit per-CPU storage.  If these counters
679 	 * are incremented concurrently on different CPUs, scalability will be
680 	 * adversely affected -- but we don't expect them to be white-hot in a
681 	 * correctly constructed enabling...
682 	 */
683 	uint32_t oval, nval;
684 
685 	do {
686 		oval = *counter;
687 
688 		if ((nval = oval + 1) == 0) {
689 			/*
690 			 * If the counter would wrap, set it to 1 -- assuring
691 			 * that the counter is never zero when we have seen
692 			 * errors.  (The counter must be 32-bits because we
693 			 * aren't guaranteed a 64-bit compare&swap operation.)
694 			 * To save this code both the infamy of being fingered
695 			 * by a priggish news story and the indignity of being
696 			 * the target of a neo-puritan witch trial, we're
697 			 * carefully avoiding any colorful description of the
698 			 * likelihood of this condition -- but suffice it to
699 			 * say that it is only slightly more likely than the
700 			 * overflow of predicate cache IDs, as discussed in
701 			 * dtrace_predicate_create().
702 			 */
703 			nval = 1;
704 		}
705 	} while (dtrace_cas32(counter, oval, nval) != oval);
706 }
707 
708 /*
709  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
710  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
711  */
712 /* BEGIN CSTYLED */
713 DTRACE_LOADFUNC(8)
714 DTRACE_LOADFUNC(16)
715 DTRACE_LOADFUNC(32)
716 DTRACE_LOADFUNC(64)
717 /* END CSTYLED */
718 
719 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)720 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
721 {
722 	if (dest < mstate->dtms_scratch_base)
723 		return (0);
724 
725 	if (dest + size < dest)
726 		return (0);
727 
728 	if (dest + size > mstate->dtms_scratch_ptr)
729 		return (0);
730 
731 	return (1);
732 }
733 
734 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)735 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
736     dtrace_statvar_t **svars, int nsvars)
737 {
738 	int i;
739 	size_t maxglobalsize, maxlocalsize;
740 
741 	if (nsvars == 0)
742 		return (0);
743 
744 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
745 	maxlocalsize = maxglobalsize * (mp_maxid + 1);
746 
747 	for (i = 0; i < nsvars; i++) {
748 		dtrace_statvar_t *svar = svars[i];
749 		uint8_t scope;
750 		size_t size;
751 
752 		if (svar == NULL || (size = svar->dtsv_size) == 0)
753 			continue;
754 
755 		scope = svar->dtsv_var.dtdv_scope;
756 
757 		/*
758 		 * We verify that our size is valid in the spirit of providing
759 		 * defense in depth:  we want to prevent attackers from using
760 		 * DTrace to escalate an orthogonal kernel heap corruption bug
761 		 * into the ability to store to arbitrary locations in memory.
762 		 */
763 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
764 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
765 
766 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
767 		    svar->dtsv_size)) {
768 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
769 			    svar->dtsv_size);
770 			return (1);
771 		}
772 	}
773 
774 	return (0);
775 }
776 
777 /*
778  * Check to see if the address is within a memory region to which a store may
779  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
780  * region.  The caller of dtrace_canstore() is responsible for performing any
781  * alignment checks that are needed before stores are actually executed.
782  */
783 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)784 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
785     dtrace_vstate_t *vstate)
786 {
787 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
788 }
789 
790 /*
791  * Implementation of dtrace_canstore which communicates the upper bound of the
792  * allowed memory region.
793  */
794 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)795 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
796     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
797 {
798 	/*
799 	 * First, check to see if the address is in scratch space...
800 	 */
801 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
802 	    mstate->dtms_scratch_size)) {
803 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
804 		    mstate->dtms_scratch_size);
805 		return (1);
806 	}
807 
808 	/*
809 	 * Now check to see if it's a dynamic variable.  This check will pick
810 	 * up both thread-local variables and any global dynamically-allocated
811 	 * variables.
812 	 */
813 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
814 	    vstate->dtvs_dynvars.dtds_size)) {
815 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
816 		uintptr_t base = (uintptr_t)dstate->dtds_base +
817 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
818 		uintptr_t chunkoffs;
819 		dtrace_dynvar_t *dvar;
820 
821 		/*
822 		 * Before we assume that we can store here, we need to make
823 		 * sure that it isn't in our metadata -- storing to our
824 		 * dynamic variable metadata would corrupt our state.  For
825 		 * the range to not include any dynamic variable metadata,
826 		 * it must:
827 		 *
828 		 *	(1) Start above the hash table that is at the base of
829 		 *	the dynamic variable space
830 		 *
831 		 *	(2) Have a starting chunk offset that is beyond the
832 		 *	dtrace_dynvar_t that is at the base of every chunk
833 		 *
834 		 *	(3) Not span a chunk boundary
835 		 *
836 		 *	(4) Not be in the tuple space of a dynamic variable
837 		 *
838 		 */
839 		if (addr < base)
840 			return (0);
841 
842 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
843 
844 		if (chunkoffs < sizeof (dtrace_dynvar_t))
845 			return (0);
846 
847 		if (chunkoffs + sz > dstate->dtds_chunksize)
848 			return (0);
849 
850 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
851 
852 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
853 			return (0);
854 
855 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
856 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
857 			return (0);
858 
859 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
860 		return (1);
861 	}
862 
863 	/*
864 	 * Finally, check the static local and global variables.  These checks
865 	 * take the longest, so we perform them last.
866 	 */
867 	if (dtrace_canstore_statvar(addr, sz, remain,
868 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
869 		return (1);
870 
871 	if (dtrace_canstore_statvar(addr, sz, remain,
872 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
873 		return (1);
874 
875 	return (0);
876 }
877 
878 
879 /*
880  * Convenience routine to check to see if the address is within a memory
881  * region in which a load may be issued given the user's privilege level;
882  * if not, it sets the appropriate error flags and loads 'addr' into the
883  * illegal value slot.
884  *
885  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
886  * appropriate memory access protection.
887  */
888 static int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)889 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
890     dtrace_vstate_t *vstate)
891 {
892 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
893 }
894 
895 /*
896  * Implementation of dtrace_canload which communicates the uppoer bound of the
897  * allowed memory region.
898  */
899 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)900 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
901     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
902 {
903 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
904 	file_t *fp;
905 
906 	/*
907 	 * If we hold the privilege to read from kernel memory, then
908 	 * everything is readable.
909 	 */
910 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
911 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
912 		return (1);
913 	}
914 
915 	/*
916 	 * You can obviously read that which you can store.
917 	 */
918 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
919 		return (1);
920 
921 	/*
922 	 * We're allowed to read from our own string table.
923 	 */
924 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
925 	    mstate->dtms_difo->dtdo_strlen)) {
926 		DTRACE_RANGE_REMAIN(remain, addr,
927 		    mstate->dtms_difo->dtdo_strtab,
928 		    mstate->dtms_difo->dtdo_strlen);
929 		return (1);
930 	}
931 
932 	if (vstate->dtvs_state != NULL &&
933 	    dtrace_priv_proc(vstate->dtvs_state)) {
934 		proc_t *p;
935 
936 		/*
937 		 * When we have privileges to the current process, there are
938 		 * several context-related kernel structures that are safe to
939 		 * read, even absent the privilege to read from kernel memory.
940 		 * These reads are safe because these structures contain only
941 		 * state that (1) we're permitted to read, (2) is harmless or
942 		 * (3) contains pointers to additional kernel state that we're
943 		 * not permitted to read (and as such, do not present an
944 		 * opportunity for privilege escalation).  Finally (and
945 		 * critically), because of the nature of their relation with
946 		 * the current thread context, the memory associated with these
947 		 * structures cannot change over the duration of probe context,
948 		 * and it is therefore impossible for this memory to be
949 		 * deallocated and reallocated as something else while it's
950 		 * being operated upon.
951 		 */
952 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
953 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
954 			    sizeof (kthread_t));
955 			return (1);
956 		}
957 
958 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
959 		    sz, curthread->t_procp, sizeof (proc_t))) {
960 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
961 			    sizeof (proc_t));
962 			return (1);
963 		}
964 
965 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
966 		    curthread->t_cred, sizeof (cred_t))) {
967 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
968 			    sizeof (cred_t));
969 			return (1);
970 		}
971 
972 #ifdef illumos
973 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
974 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
975 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
976 			    sizeof (pid_t));
977 			return (1);
978 		}
979 
980 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
981 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
982 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
983 			    offsetof(cpu_t, cpu_pause_thread));
984 			return (1);
985 		}
986 #endif
987 	}
988 
989 	if ((fp = mstate->dtms_getf) != NULL) {
990 		uintptr_t psz = sizeof (void *);
991 		vnode_t *vp;
992 		vnodeops_t *op;
993 
994 		/*
995 		 * When getf() returns a file_t, the enabling is implicitly
996 		 * granted the (transient) right to read the returned file_t
997 		 * as well as the v_path and v_op->vnop_name of the underlying
998 		 * vnode.  These accesses are allowed after a successful
999 		 * getf() because the members that they refer to cannot change
1000 		 * once set -- and the barrier logic in the kernel's closef()
1001 		 * path assures that the file_t and its referenced vode_t
1002 		 * cannot themselves be stale (that is, it impossible for
1003 		 * either dtms_getf itself or its f_vnode member to reference
1004 		 * freed memory).
1005 		 */
1006 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1007 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1008 			return (1);
1009 		}
1010 
1011 		if ((vp = fp->f_vnode) != NULL) {
1012 			size_t slen;
1013 #ifdef illumos
1014 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1015 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1016 				    psz);
1017 				return (1);
1018 			}
1019 			slen = strlen(vp->v_path) + 1;
1020 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1021 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1022 				    slen);
1023 				return (1);
1024 			}
1025 #endif
1026 
1027 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1028 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1029 				    psz);
1030 				return (1);
1031 			}
1032 
1033 #ifdef illumos
1034 			if ((op = vp->v_op) != NULL &&
1035 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1036 				DTRACE_RANGE_REMAIN(remain, addr,
1037 				    &op->vnop_name, psz);
1038 				return (1);
1039 			}
1040 
1041 			if (op != NULL && op->vnop_name != NULL &&
1042 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
1043 			    (slen = strlen(op->vnop_name) + 1))) {
1044 				DTRACE_RANGE_REMAIN(remain, addr,
1045 				    op->vnop_name, slen);
1046 				return (1);
1047 			}
1048 #endif
1049 		}
1050 	}
1051 
1052 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1053 	*illval = addr;
1054 	return (0);
1055 }
1056 
1057 /*
1058  * Convenience routine to check to see if a given string is within a memory
1059  * region in which a load may be issued given the user's privilege level;
1060  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1061  * calls in the event that the user has all privileges.
1062  */
1063 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1064 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1065     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1066 {
1067 	size_t rsize;
1068 
1069 	/*
1070 	 * If we hold the privilege to read from kernel memory, then
1071 	 * everything is readable.
1072 	 */
1073 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1074 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1075 		return (1);
1076 	}
1077 
1078 	/*
1079 	 * Even if the caller is uninterested in querying the remaining valid
1080 	 * range, it is required to ensure that the access is allowed.
1081 	 */
1082 	if (remain == NULL) {
1083 		remain = &rsize;
1084 	}
1085 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1086 		size_t strsz;
1087 		/*
1088 		 * Perform the strlen after determining the length of the
1089 		 * memory region which is accessible.  This prevents timing
1090 		 * information from being used to find NULs in memory which is
1091 		 * not accessible to the caller.
1092 		 */
1093 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1094 		    MIN(sz, *remain));
1095 		if (strsz <= *remain) {
1096 			return (1);
1097 		}
1098 	}
1099 
1100 	return (0);
1101 }
1102 
1103 /*
1104  * Convenience routine to check to see if a given variable is within a memory
1105  * region in which a load may be issued given the user's privilege level.
1106  */
1107 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1108 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1109     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1110 {
1111 	size_t sz;
1112 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1113 
1114 	/*
1115 	 * Calculate the max size before performing any checks since even
1116 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1117 	 * return the max length via 'remain'.
1118 	 */
1119 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1120 		dtrace_state_t *state = vstate->dtvs_state;
1121 
1122 		if (state != NULL) {
1123 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1124 		} else {
1125 			/*
1126 			 * In helper context, we have a NULL state; fall back
1127 			 * to using the system-wide default for the string size
1128 			 * in this case.
1129 			 */
1130 			sz = dtrace_strsize_default;
1131 		}
1132 	} else {
1133 		sz = type->dtdt_size;
1134 	}
1135 
1136 	/*
1137 	 * If we hold the privilege to read from kernel memory, then
1138 	 * everything is readable.
1139 	 */
1140 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1141 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1142 		return (1);
1143 	}
1144 
1145 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1146 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1147 		    vstate));
1148 	}
1149 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1150 	    vstate));
1151 }
1152 
1153 /*
1154  * Convert a string to a signed integer using safe loads.
1155  *
1156  * NOTE: This function uses various macros from strtolctype.h to manipulate
1157  * digit values, etc -- these have all been checked to ensure they make
1158  * no additional function calls.
1159  */
1160 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1161 dtrace_strtoll(char *input, int base, size_t limit)
1162 {
1163 	uintptr_t pos = (uintptr_t)input;
1164 	int64_t val = 0;
1165 	int x;
1166 	boolean_t neg = B_FALSE;
1167 	char c, cc, ccc;
1168 	uintptr_t end = pos + limit;
1169 
1170 	/*
1171 	 * Consume any whitespace preceding digits.
1172 	 */
1173 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1174 		pos++;
1175 
1176 	/*
1177 	 * Handle an explicit sign if one is present.
1178 	 */
1179 	if (c == '-' || c == '+') {
1180 		if (c == '-')
1181 			neg = B_TRUE;
1182 		c = dtrace_load8(++pos);
1183 	}
1184 
1185 	/*
1186 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1187 	 * if present.
1188 	 */
1189 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1190 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1191 		pos += 2;
1192 		c = ccc;
1193 	}
1194 
1195 	/*
1196 	 * Read in contiguous digits until the first non-digit character.
1197 	 */
1198 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1199 	    c = dtrace_load8(++pos))
1200 		val = val * base + x;
1201 
1202 	return (neg ? -val : val);
1203 }
1204 
1205 /*
1206  * Compare two strings using safe loads.
1207  */
1208 static int
dtrace_strncmp(char * s1,char * s2,size_t limit)1209 dtrace_strncmp(char *s1, char *s2, size_t limit)
1210 {
1211 	uint8_t c1, c2;
1212 	volatile uint16_t *flags;
1213 
1214 	if (s1 == s2 || limit == 0)
1215 		return (0);
1216 
1217 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1218 
1219 	do {
1220 		if (s1 == NULL) {
1221 			c1 = '\0';
1222 		} else {
1223 			c1 = dtrace_load8((uintptr_t)s1++);
1224 		}
1225 
1226 		if (s2 == NULL) {
1227 			c2 = '\0';
1228 		} else {
1229 			c2 = dtrace_load8((uintptr_t)s2++);
1230 		}
1231 
1232 		if (c1 != c2)
1233 			return (c1 - c2);
1234 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1235 
1236 	return (0);
1237 }
1238 
1239 /*
1240  * Compute strlen(s) for a string using safe memory accesses.  The additional
1241  * len parameter is used to specify a maximum length to ensure completion.
1242  */
1243 static size_t
dtrace_strlen(const char * s,size_t lim)1244 dtrace_strlen(const char *s, size_t lim)
1245 {
1246 	uint_t len;
1247 
1248 	for (len = 0; len != lim; len++) {
1249 		if (dtrace_load8((uintptr_t)s++) == '\0')
1250 			break;
1251 	}
1252 
1253 	return (len);
1254 }
1255 
1256 /*
1257  * Check if an address falls within a toxic region.
1258  */
1259 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1260 dtrace_istoxic(uintptr_t kaddr, size_t size)
1261 {
1262 	uintptr_t taddr, tsize;
1263 	int i;
1264 
1265 	for (i = 0; i < dtrace_toxranges; i++) {
1266 		taddr = dtrace_toxrange[i].dtt_base;
1267 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1268 
1269 		if (kaddr - taddr < tsize) {
1270 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1271 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1272 			return (1);
1273 		}
1274 
1275 		if (taddr - kaddr < size) {
1276 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1277 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1278 			return (1);
1279 		}
1280 	}
1281 
1282 	return (0);
1283 }
1284 
1285 /*
1286  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1287  * memory specified by the DIF program.  The dst is assumed to be safe memory
1288  * that we can store to directly because it is managed by DTrace.  As with
1289  * standard bcopy, overlapping copies are handled properly.
1290  */
1291 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1292 dtrace_bcopy(const void *src, void *dst, size_t len)
1293 {
1294 	if (len != 0) {
1295 		uint8_t *s1 = dst;
1296 		const uint8_t *s2 = src;
1297 
1298 		if (s1 <= s2) {
1299 			do {
1300 				*s1++ = dtrace_load8((uintptr_t)s2++);
1301 			} while (--len != 0);
1302 		} else {
1303 			s2 += len;
1304 			s1 += len;
1305 
1306 			do {
1307 				*--s1 = dtrace_load8((uintptr_t)--s2);
1308 			} while (--len != 0);
1309 		}
1310 	}
1311 }
1312 
1313 /*
1314  * Copy src to dst using safe memory accesses, up to either the specified
1315  * length, or the point that a nul byte is encountered.  The src is assumed to
1316  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1317  * safe memory that we can store to directly because it is managed by DTrace.
1318  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1319  */
1320 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1321 dtrace_strcpy(const void *src, void *dst, size_t len)
1322 {
1323 	if (len != 0) {
1324 		uint8_t *s1 = dst, c;
1325 		const uint8_t *s2 = src;
1326 
1327 		do {
1328 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1329 		} while (--len != 0 && c != '\0');
1330 	}
1331 }
1332 
1333 /*
1334  * Copy src to dst, deriving the size and type from the specified (BYREF)
1335  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1336  * program.  The dst is assumed to be DTrace variable memory that is of the
1337  * specified type; we assume that we can store to directly.
1338  */
1339 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1340 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1341 {
1342 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1343 
1344 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1345 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1346 	} else {
1347 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1348 	}
1349 }
1350 
1351 /*
1352  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1353  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1354  * safe memory that we can access directly because it is managed by DTrace.
1355  */
1356 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1357 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1358 {
1359 	volatile uint16_t *flags;
1360 
1361 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1362 
1363 	if (s1 == s2)
1364 		return (0);
1365 
1366 	if (s1 == NULL || s2 == NULL)
1367 		return (1);
1368 
1369 	if (s1 != s2 && len != 0) {
1370 		const uint8_t *ps1 = s1;
1371 		const uint8_t *ps2 = s2;
1372 
1373 		do {
1374 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1375 				return (1);
1376 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1377 	}
1378 	return (0);
1379 }
1380 
1381 /*
1382  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1383  * is for safe DTrace-managed memory only.
1384  */
1385 static void
dtrace_bzero(void * dst,size_t len)1386 dtrace_bzero(void *dst, size_t len)
1387 {
1388 	uchar_t *cp;
1389 
1390 	for (cp = dst; len != 0; len--)
1391 		*cp++ = 0;
1392 }
1393 
1394 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1395 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1396 {
1397 	uint64_t result[2];
1398 
1399 	result[0] = addend1[0] + addend2[0];
1400 	result[1] = addend1[1] + addend2[1] +
1401 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1402 
1403 	sum[0] = result[0];
1404 	sum[1] = result[1];
1405 }
1406 
1407 /*
1408  * Shift the 128-bit value in a by b. If b is positive, shift left.
1409  * If b is negative, shift right.
1410  */
1411 static void
dtrace_shift_128(uint64_t * a,int b)1412 dtrace_shift_128(uint64_t *a, int b)
1413 {
1414 	uint64_t mask;
1415 
1416 	if (b == 0)
1417 		return;
1418 
1419 	if (b < 0) {
1420 		b = -b;
1421 		if (b >= 64) {
1422 			a[0] = a[1] >> (b - 64);
1423 			a[1] = 0;
1424 		} else {
1425 			a[0] >>= b;
1426 			mask = 1LL << (64 - b);
1427 			mask -= 1;
1428 			a[0] |= ((a[1] & mask) << (64 - b));
1429 			a[1] >>= b;
1430 		}
1431 	} else {
1432 		if (b >= 64) {
1433 			a[1] = a[0] << (b - 64);
1434 			a[0] = 0;
1435 		} else {
1436 			a[1] <<= b;
1437 			mask = a[0] >> (64 - b);
1438 			a[1] |= mask;
1439 			a[0] <<= b;
1440 		}
1441 	}
1442 }
1443 
1444 /*
1445  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1446  * use native multiplication on those, and then re-combine into the
1447  * resulting 128-bit value.
1448  *
1449  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1450  *     hi1 * hi2 << 64 +
1451  *     hi1 * lo2 << 32 +
1452  *     hi2 * lo1 << 32 +
1453  *     lo1 * lo2
1454  */
1455 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1456 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1457 {
1458 	uint64_t hi1, hi2, lo1, lo2;
1459 	uint64_t tmp[2];
1460 
1461 	hi1 = factor1 >> 32;
1462 	hi2 = factor2 >> 32;
1463 
1464 	lo1 = factor1 & DT_MASK_LO;
1465 	lo2 = factor2 & DT_MASK_LO;
1466 
1467 	product[0] = lo1 * lo2;
1468 	product[1] = hi1 * hi2;
1469 
1470 	tmp[0] = hi1 * lo2;
1471 	tmp[1] = 0;
1472 	dtrace_shift_128(tmp, 32);
1473 	dtrace_add_128(product, tmp, product);
1474 
1475 	tmp[0] = hi2 * lo1;
1476 	tmp[1] = 0;
1477 	dtrace_shift_128(tmp, 32);
1478 	dtrace_add_128(product, tmp, product);
1479 }
1480 
1481 /*
1482  * This privilege check should be used by actions and subroutines to
1483  * verify that the user credentials of the process that enabled the
1484  * invoking ECB match the target credentials
1485  */
1486 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1487 dtrace_priv_proc_common_user(dtrace_state_t *state)
1488 {
1489 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1490 
1491 	/*
1492 	 * We should always have a non-NULL state cred here, since if cred
1493 	 * is null (anonymous tracing), we fast-path bypass this routine.
1494 	 */
1495 	ASSERT(s_cr != NULL);
1496 
1497 	if ((cr = CRED()) != NULL &&
1498 	    s_cr->cr_uid == cr->cr_uid &&
1499 	    s_cr->cr_uid == cr->cr_ruid &&
1500 	    s_cr->cr_uid == cr->cr_suid &&
1501 	    s_cr->cr_gid == cr->cr_gid &&
1502 	    s_cr->cr_gid == cr->cr_rgid &&
1503 	    s_cr->cr_gid == cr->cr_sgid)
1504 		return (1);
1505 
1506 	return (0);
1507 }
1508 
1509 /*
1510  * This privilege check should be used by actions and subroutines to
1511  * verify that the zone of the process that enabled the invoking ECB
1512  * matches the target credentials
1513  */
1514 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1515 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1516 {
1517 #ifdef illumos
1518 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1519 
1520 	/*
1521 	 * We should always have a non-NULL state cred here, since if cred
1522 	 * is null (anonymous tracing), we fast-path bypass this routine.
1523 	 */
1524 	ASSERT(s_cr != NULL);
1525 
1526 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1527 		return (1);
1528 
1529 	return (0);
1530 #else
1531 	return (1);
1532 #endif
1533 }
1534 
1535 /*
1536  * This privilege check should be used by actions and subroutines to
1537  * verify that the process has not setuid or changed credentials.
1538  */
1539 static int
dtrace_priv_proc_common_nocd(void)1540 dtrace_priv_proc_common_nocd(void)
1541 {
1542 	proc_t *proc;
1543 
1544 	if ((proc = ttoproc(curthread)) != NULL &&
1545 	    !(proc->p_flag & SNOCD))
1546 		return (1);
1547 
1548 	return (0);
1549 }
1550 
1551 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1552 dtrace_priv_proc_destructive(dtrace_state_t *state)
1553 {
1554 	int action = state->dts_cred.dcr_action;
1555 
1556 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1557 	    dtrace_priv_proc_common_zone(state) == 0)
1558 		goto bad;
1559 
1560 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1561 	    dtrace_priv_proc_common_user(state) == 0)
1562 		goto bad;
1563 
1564 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1565 	    dtrace_priv_proc_common_nocd() == 0)
1566 		goto bad;
1567 
1568 	return (1);
1569 
1570 bad:
1571 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1572 
1573 	return (0);
1574 }
1575 
1576 static int
dtrace_priv_proc_control(dtrace_state_t * state)1577 dtrace_priv_proc_control(dtrace_state_t *state)
1578 {
1579 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1580 		return (1);
1581 
1582 	if (dtrace_priv_proc_common_zone(state) &&
1583 	    dtrace_priv_proc_common_user(state) &&
1584 	    dtrace_priv_proc_common_nocd())
1585 		return (1);
1586 
1587 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1588 
1589 	return (0);
1590 }
1591 
1592 static int
dtrace_priv_proc(dtrace_state_t * state)1593 dtrace_priv_proc(dtrace_state_t *state)
1594 {
1595 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1596 		return (1);
1597 
1598 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1599 
1600 	return (0);
1601 }
1602 
1603 static int
dtrace_priv_kernel(dtrace_state_t * state)1604 dtrace_priv_kernel(dtrace_state_t *state)
1605 {
1606 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1607 		return (1);
1608 
1609 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1610 
1611 	return (0);
1612 }
1613 
1614 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1615 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1616 {
1617 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1618 		return (1);
1619 
1620 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1621 
1622 	return (0);
1623 }
1624 
1625 /*
1626  * Determine if the dte_cond of the specified ECB allows for processing of
1627  * the current probe to continue.  Note that this routine may allow continued
1628  * processing, but with access(es) stripped from the mstate's dtms_access
1629  * field.
1630  */
1631 static int
dtrace_priv_probe(dtrace_state_t * state,dtrace_mstate_t * mstate,dtrace_ecb_t * ecb)1632 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1633     dtrace_ecb_t *ecb)
1634 {
1635 	dtrace_probe_t *probe = ecb->dte_probe;
1636 	dtrace_provider_t *prov = probe->dtpr_provider;
1637 	dtrace_pops_t *pops = &prov->dtpv_pops;
1638 	int mode = DTRACE_MODE_NOPRIV_DROP;
1639 
1640 	ASSERT(ecb->dte_cond);
1641 
1642 #ifdef illumos
1643 	if (pops->dtps_mode != NULL) {
1644 		mode = pops->dtps_mode(prov->dtpv_arg,
1645 		    probe->dtpr_id, probe->dtpr_arg);
1646 
1647 		ASSERT((mode & DTRACE_MODE_USER) ||
1648 		    (mode & DTRACE_MODE_KERNEL));
1649 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1650 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1651 	}
1652 
1653 	/*
1654 	 * If the dte_cond bits indicate that this consumer is only allowed to
1655 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1656 	 * entry point to check that the probe was fired while in a user
1657 	 * context.  If that's not the case, use the policy specified by the
1658 	 * provider to determine if we drop the probe or merely restrict
1659 	 * operation.
1660 	 */
1661 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1662 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1663 
1664 		if (!(mode & DTRACE_MODE_USER)) {
1665 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1666 				return (0);
1667 
1668 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1669 		}
1670 	}
1671 #endif
1672 
1673 	/*
1674 	 * This is more subtle than it looks. We have to be absolutely certain
1675 	 * that CRED() isn't going to change out from under us so it's only
1676 	 * legit to examine that structure if we're in constrained situations.
1677 	 * Currently, the only times we'll this check is if a non-super-user
1678 	 * has enabled the profile or syscall providers -- providers that
1679 	 * allow visibility of all processes. For the profile case, the check
1680 	 * above will ensure that we're examining a user context.
1681 	 */
1682 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1683 		cred_t *cr;
1684 		cred_t *s_cr = state->dts_cred.dcr_cred;
1685 		proc_t *proc;
1686 
1687 		ASSERT(s_cr != NULL);
1688 
1689 		if ((cr = CRED()) == NULL ||
1690 		    s_cr->cr_uid != cr->cr_uid ||
1691 		    s_cr->cr_uid != cr->cr_ruid ||
1692 		    s_cr->cr_uid != cr->cr_suid ||
1693 		    s_cr->cr_gid != cr->cr_gid ||
1694 		    s_cr->cr_gid != cr->cr_rgid ||
1695 		    s_cr->cr_gid != cr->cr_sgid ||
1696 		    (proc = ttoproc(curthread)) == NULL ||
1697 		    (proc->p_flag & SNOCD)) {
1698 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1699 				return (0);
1700 
1701 #ifdef illumos
1702 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1703 #endif
1704 		}
1705 	}
1706 
1707 #ifdef illumos
1708 	/*
1709 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1710 	 * in our zone, check to see if our mode policy is to restrict rather
1711 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1712 	 * and DTRACE_ACCESS_ARGS
1713 	 */
1714 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1715 		cred_t *cr;
1716 		cred_t *s_cr = state->dts_cred.dcr_cred;
1717 
1718 		ASSERT(s_cr != NULL);
1719 
1720 		if ((cr = CRED()) == NULL ||
1721 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1722 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1723 				return (0);
1724 
1725 			mstate->dtms_access &=
1726 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1727 		}
1728 	}
1729 #endif
1730 
1731 	return (1);
1732 }
1733 
1734 /*
1735  * Note:  not called from probe context.  This function is called
1736  * asynchronously (and at a regular interval) from outside of probe context to
1737  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1738  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1739  */
1740 void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1741 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1742 {
1743 	dtrace_dynvar_t *dirty;
1744 	dtrace_dstate_percpu_t *dcpu;
1745 	dtrace_dynvar_t **rinsep;
1746 	int i, j, work = 0;
1747 
1748 	CPU_FOREACH(i) {
1749 		dcpu = &dstate->dtds_percpu[i];
1750 		rinsep = &dcpu->dtdsc_rinsing;
1751 
1752 		/*
1753 		 * If the dirty list is NULL, there is no dirty work to do.
1754 		 */
1755 		if (dcpu->dtdsc_dirty == NULL)
1756 			continue;
1757 
1758 		if (dcpu->dtdsc_rinsing != NULL) {
1759 			/*
1760 			 * If the rinsing list is non-NULL, then it is because
1761 			 * this CPU was selected to accept another CPU's
1762 			 * dirty list -- and since that time, dirty buffers
1763 			 * have accumulated.  This is a highly unlikely
1764 			 * condition, but we choose to ignore the dirty
1765 			 * buffers -- they'll be picked up a future cleanse.
1766 			 */
1767 			continue;
1768 		}
1769 
1770 		if (dcpu->dtdsc_clean != NULL) {
1771 			/*
1772 			 * If the clean list is non-NULL, then we're in a
1773 			 * situation where a CPU has done deallocations (we
1774 			 * have a non-NULL dirty list) but no allocations (we
1775 			 * also have a non-NULL clean list).  We can't simply
1776 			 * move the dirty list into the clean list on this
1777 			 * CPU, yet we also don't want to allow this condition
1778 			 * to persist, lest a short clean list prevent a
1779 			 * massive dirty list from being cleaned (which in
1780 			 * turn could lead to otherwise avoidable dynamic
1781 			 * drops).  To deal with this, we look for some CPU
1782 			 * with a NULL clean list, NULL dirty list, and NULL
1783 			 * rinsing list -- and then we borrow this CPU to
1784 			 * rinse our dirty list.
1785 			 */
1786 			CPU_FOREACH(j) {
1787 				dtrace_dstate_percpu_t *rinser;
1788 
1789 				rinser = &dstate->dtds_percpu[j];
1790 
1791 				if (rinser->dtdsc_rinsing != NULL)
1792 					continue;
1793 
1794 				if (rinser->dtdsc_dirty != NULL)
1795 					continue;
1796 
1797 				if (rinser->dtdsc_clean != NULL)
1798 					continue;
1799 
1800 				rinsep = &rinser->dtdsc_rinsing;
1801 				break;
1802 			}
1803 
1804 			if (j > mp_maxid) {
1805 				/*
1806 				 * We were unable to find another CPU that
1807 				 * could accept this dirty list -- we are
1808 				 * therefore unable to clean it now.
1809 				 */
1810 				dtrace_dynvar_failclean++;
1811 				continue;
1812 			}
1813 		}
1814 
1815 		work = 1;
1816 
1817 		/*
1818 		 * Atomically move the dirty list aside.
1819 		 */
1820 		do {
1821 			dirty = dcpu->dtdsc_dirty;
1822 
1823 			/*
1824 			 * Before we zap the dirty list, set the rinsing list.
1825 			 * (This allows for a potential assertion in
1826 			 * dtrace_dynvar():  if a free dynamic variable appears
1827 			 * on a hash chain, either the dirty list or the
1828 			 * rinsing list for some CPU must be non-NULL.)
1829 			 */
1830 			*rinsep = dirty;
1831 			dtrace_membar_producer();
1832 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1833 		    dirty, NULL) != dirty);
1834 	}
1835 
1836 	if (!work) {
1837 		/*
1838 		 * We have no work to do; we can simply return.
1839 		 */
1840 		return;
1841 	}
1842 
1843 	dtrace_sync();
1844 
1845 	CPU_FOREACH(i) {
1846 		dcpu = &dstate->dtds_percpu[i];
1847 
1848 		if (dcpu->dtdsc_rinsing == NULL)
1849 			continue;
1850 
1851 		/*
1852 		 * We are now guaranteed that no hash chain contains a pointer
1853 		 * into this dirty list; we can make it clean.
1854 		 */
1855 		ASSERT(dcpu->dtdsc_clean == NULL);
1856 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1857 		dcpu->dtdsc_rinsing = NULL;
1858 	}
1859 
1860 	/*
1861 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1862 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1863 	 * This prevents a race whereby a CPU incorrectly decides that
1864 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1865 	 * after dtrace_dynvar_clean() has completed.
1866 	 */
1867 	dtrace_sync();
1868 
1869 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1870 }
1871 
1872 /*
1873  * Depending on the value of the op parameter, this function looks-up,
1874  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1875  * allocation is requested, this function will return a pointer to a
1876  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1877  * variable can be allocated.  If NULL is returned, the appropriate counter
1878  * will be incremented.
1879  */
1880 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)1881 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1882     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1883     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1884 {
1885 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1886 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1887 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1888 	processorid_t me = curcpu, cpu = me;
1889 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1890 	size_t bucket, ksize;
1891 	size_t chunksize = dstate->dtds_chunksize;
1892 	uintptr_t kdata, lock, nstate;
1893 	uint_t i;
1894 
1895 	ASSERT(nkeys != 0);
1896 
1897 	/*
1898 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1899 	 * algorithm.  For the by-value portions, we perform the algorithm in
1900 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1901 	 * bit, and seems to have only a minute effect on distribution.  For
1902 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1903 	 * over each referenced byte.  It's painful to do this, but it's much
1904 	 * better than pathological hash distribution.  The efficacy of the
1905 	 * hashing algorithm (and a comparison with other algorithms) may be
1906 	 * found by running the ::dtrace_dynstat MDB dcmd.
1907 	 */
1908 	for (i = 0; i < nkeys; i++) {
1909 		if (key[i].dttk_size == 0) {
1910 			uint64_t val = key[i].dttk_value;
1911 
1912 			hashval += (val >> 48) & 0xffff;
1913 			hashval += (hashval << 10);
1914 			hashval ^= (hashval >> 6);
1915 
1916 			hashval += (val >> 32) & 0xffff;
1917 			hashval += (hashval << 10);
1918 			hashval ^= (hashval >> 6);
1919 
1920 			hashval += (val >> 16) & 0xffff;
1921 			hashval += (hashval << 10);
1922 			hashval ^= (hashval >> 6);
1923 
1924 			hashval += val & 0xffff;
1925 			hashval += (hashval << 10);
1926 			hashval ^= (hashval >> 6);
1927 		} else {
1928 			/*
1929 			 * This is incredibly painful, but it beats the hell
1930 			 * out of the alternative.
1931 			 */
1932 			uint64_t j, size = key[i].dttk_size;
1933 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1934 
1935 			if (!dtrace_canload(base, size, mstate, vstate))
1936 				break;
1937 
1938 			for (j = 0; j < size; j++) {
1939 				hashval += dtrace_load8(base + j);
1940 				hashval += (hashval << 10);
1941 				hashval ^= (hashval >> 6);
1942 			}
1943 		}
1944 	}
1945 
1946 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1947 		return (NULL);
1948 
1949 	hashval += (hashval << 3);
1950 	hashval ^= (hashval >> 11);
1951 	hashval += (hashval << 15);
1952 
1953 	/*
1954 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1955 	 * comes out to be one of our two sentinel hash values.  If this
1956 	 * actually happens, we set the hashval to be a value known to be a
1957 	 * non-sentinel value.
1958 	 */
1959 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1960 		hashval = DTRACE_DYNHASH_VALID;
1961 
1962 	/*
1963 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1964 	 * important here, tricks can be pulled to reduce it.  (However, it's
1965 	 * critical that hash collisions be kept to an absolute minimum;
1966 	 * they're much more painful than a divide.)  It's better to have a
1967 	 * solution that generates few collisions and still keeps things
1968 	 * relatively simple.
1969 	 */
1970 	bucket = hashval % dstate->dtds_hashsize;
1971 
1972 	if (op == DTRACE_DYNVAR_DEALLOC) {
1973 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1974 
1975 		for (;;) {
1976 			while ((lock = *lockp) & 1)
1977 				continue;
1978 
1979 			if (dtrace_casptr((volatile void *)lockp,
1980 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1981 				break;
1982 		}
1983 
1984 		dtrace_membar_producer();
1985 	}
1986 
1987 top:
1988 	prev = NULL;
1989 	lock = hash[bucket].dtdh_lock;
1990 
1991 	dtrace_membar_consumer();
1992 
1993 	start = hash[bucket].dtdh_chain;
1994 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1995 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1996 	    op != DTRACE_DYNVAR_DEALLOC));
1997 
1998 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1999 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
2000 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
2001 
2002 		if (dvar->dtdv_hashval != hashval) {
2003 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
2004 				/*
2005 				 * We've reached the sink, and therefore the
2006 				 * end of the hash chain; we can kick out of
2007 				 * the loop knowing that we have seen a valid
2008 				 * snapshot of state.
2009 				 */
2010 				ASSERT(dvar->dtdv_next == NULL);
2011 				ASSERT(dvar == &dtrace_dynhash_sink);
2012 				break;
2013 			}
2014 
2015 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2016 				/*
2017 				 * We've gone off the rails:  somewhere along
2018 				 * the line, one of the members of this hash
2019 				 * chain was deleted.  Note that we could also
2020 				 * detect this by simply letting this loop run
2021 				 * to completion, as we would eventually hit
2022 				 * the end of the dirty list.  However, we
2023 				 * want to avoid running the length of the
2024 				 * dirty list unnecessarily (it might be quite
2025 				 * long), so we catch this as early as
2026 				 * possible by detecting the hash marker.  In
2027 				 * this case, we simply set dvar to NULL and
2028 				 * break; the conditional after the loop will
2029 				 * send us back to top.
2030 				 */
2031 				dvar = NULL;
2032 				break;
2033 			}
2034 
2035 			goto next;
2036 		}
2037 
2038 		if (dtuple->dtt_nkeys != nkeys)
2039 			goto next;
2040 
2041 		for (i = 0; i < nkeys; i++, dkey++) {
2042 			if (dkey->dttk_size != key[i].dttk_size)
2043 				goto next; /* size or type mismatch */
2044 
2045 			if (dkey->dttk_size != 0) {
2046 				if (dtrace_bcmp(
2047 				    (void *)(uintptr_t)key[i].dttk_value,
2048 				    (void *)(uintptr_t)dkey->dttk_value,
2049 				    dkey->dttk_size))
2050 					goto next;
2051 			} else {
2052 				if (dkey->dttk_value != key[i].dttk_value)
2053 					goto next;
2054 			}
2055 		}
2056 
2057 		if (op != DTRACE_DYNVAR_DEALLOC)
2058 			return (dvar);
2059 
2060 		ASSERT(dvar->dtdv_next == NULL ||
2061 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2062 
2063 		if (prev != NULL) {
2064 			ASSERT(hash[bucket].dtdh_chain != dvar);
2065 			ASSERT(start != dvar);
2066 			ASSERT(prev->dtdv_next == dvar);
2067 			prev->dtdv_next = dvar->dtdv_next;
2068 		} else {
2069 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2070 			    start, dvar->dtdv_next) != start) {
2071 				/*
2072 				 * We have failed to atomically swing the
2073 				 * hash table head pointer, presumably because
2074 				 * of a conflicting allocation on another CPU.
2075 				 * We need to reread the hash chain and try
2076 				 * again.
2077 				 */
2078 				goto top;
2079 			}
2080 		}
2081 
2082 		dtrace_membar_producer();
2083 
2084 		/*
2085 		 * Now set the hash value to indicate that it's free.
2086 		 */
2087 		ASSERT(hash[bucket].dtdh_chain != dvar);
2088 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2089 
2090 		dtrace_membar_producer();
2091 
2092 		/*
2093 		 * Set the next pointer to point at the dirty list, and
2094 		 * atomically swing the dirty pointer to the newly freed dvar.
2095 		 */
2096 		do {
2097 			next = dcpu->dtdsc_dirty;
2098 			dvar->dtdv_next = next;
2099 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2100 
2101 		/*
2102 		 * Finally, unlock this hash bucket.
2103 		 */
2104 		ASSERT(hash[bucket].dtdh_lock == lock);
2105 		ASSERT(lock & 1);
2106 		hash[bucket].dtdh_lock++;
2107 
2108 		return (NULL);
2109 next:
2110 		prev = dvar;
2111 		continue;
2112 	}
2113 
2114 	if (dvar == NULL) {
2115 		/*
2116 		 * If dvar is NULL, it is because we went off the rails:
2117 		 * one of the elements that we traversed in the hash chain
2118 		 * was deleted while we were traversing it.  In this case,
2119 		 * we assert that we aren't doing a dealloc (deallocs lock
2120 		 * the hash bucket to prevent themselves from racing with
2121 		 * one another), and retry the hash chain traversal.
2122 		 */
2123 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2124 		goto top;
2125 	}
2126 
2127 	if (op != DTRACE_DYNVAR_ALLOC) {
2128 		/*
2129 		 * If we are not to allocate a new variable, we want to
2130 		 * return NULL now.  Before we return, check that the value
2131 		 * of the lock word hasn't changed.  If it has, we may have
2132 		 * seen an inconsistent snapshot.
2133 		 */
2134 		if (op == DTRACE_DYNVAR_NOALLOC) {
2135 			if (hash[bucket].dtdh_lock != lock)
2136 				goto top;
2137 		} else {
2138 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2139 			ASSERT(hash[bucket].dtdh_lock == lock);
2140 			ASSERT(lock & 1);
2141 			hash[bucket].dtdh_lock++;
2142 		}
2143 
2144 		return (NULL);
2145 	}
2146 
2147 	/*
2148 	 * We need to allocate a new dynamic variable.  The size we need is the
2149 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2150 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2151 	 * the size of any referred-to data (dsize).  We then round the final
2152 	 * size up to the chunksize for allocation.
2153 	 */
2154 	for (ksize = 0, i = 0; i < nkeys; i++)
2155 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2156 
2157 	/*
2158 	 * This should be pretty much impossible, but could happen if, say,
2159 	 * strange DIF specified the tuple.  Ideally, this should be an
2160 	 * assertion and not an error condition -- but that requires that the
2161 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2162 	 * bullet-proof.  (That is, it must not be able to be fooled by
2163 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2164 	 * solving this would presumably not amount to solving the Halting
2165 	 * Problem -- but it still seems awfully hard.
2166 	 */
2167 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2168 	    ksize + dsize > chunksize) {
2169 		dcpu->dtdsc_drops++;
2170 		return (NULL);
2171 	}
2172 
2173 	nstate = DTRACE_DSTATE_EMPTY;
2174 
2175 	do {
2176 retry:
2177 		free = dcpu->dtdsc_free;
2178 
2179 		if (free == NULL) {
2180 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2181 			void *rval;
2182 
2183 			if (clean == NULL) {
2184 				/*
2185 				 * We're out of dynamic variable space on
2186 				 * this CPU.  Unless we have tried all CPUs,
2187 				 * we'll try to allocate from a different
2188 				 * CPU.
2189 				 */
2190 				switch (dstate->dtds_state) {
2191 				case DTRACE_DSTATE_CLEAN: {
2192 					void *sp = &dstate->dtds_state;
2193 
2194 					if (++cpu > mp_maxid)
2195 						cpu = 0;
2196 
2197 					if (dcpu->dtdsc_dirty != NULL &&
2198 					    nstate == DTRACE_DSTATE_EMPTY)
2199 						nstate = DTRACE_DSTATE_DIRTY;
2200 
2201 					if (dcpu->dtdsc_rinsing != NULL)
2202 						nstate = DTRACE_DSTATE_RINSING;
2203 
2204 					dcpu = &dstate->dtds_percpu[cpu];
2205 
2206 					if (cpu != me)
2207 						goto retry;
2208 
2209 					(void) dtrace_cas32(sp,
2210 					    DTRACE_DSTATE_CLEAN, nstate);
2211 
2212 					/*
2213 					 * To increment the correct bean
2214 					 * counter, take another lap.
2215 					 */
2216 					goto retry;
2217 				}
2218 
2219 				case DTRACE_DSTATE_DIRTY:
2220 					dcpu->dtdsc_dirty_drops++;
2221 					break;
2222 
2223 				case DTRACE_DSTATE_RINSING:
2224 					dcpu->dtdsc_rinsing_drops++;
2225 					break;
2226 
2227 				case DTRACE_DSTATE_EMPTY:
2228 					dcpu->dtdsc_drops++;
2229 					break;
2230 				}
2231 
2232 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2233 				return (NULL);
2234 			}
2235 
2236 			/*
2237 			 * The clean list appears to be non-empty.  We want to
2238 			 * move the clean list to the free list; we start by
2239 			 * moving the clean pointer aside.
2240 			 */
2241 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2242 			    clean, NULL) != clean) {
2243 				/*
2244 				 * We are in one of two situations:
2245 				 *
2246 				 *  (a)	The clean list was switched to the
2247 				 *	free list by another CPU.
2248 				 *
2249 				 *  (b)	The clean list was added to by the
2250 				 *	cleansing cyclic.
2251 				 *
2252 				 * In either of these situations, we can
2253 				 * just reattempt the free list allocation.
2254 				 */
2255 				goto retry;
2256 			}
2257 
2258 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2259 
2260 			/*
2261 			 * Now we'll move the clean list to our free list.
2262 			 * It's impossible for this to fail:  the only way
2263 			 * the free list can be updated is through this
2264 			 * code path, and only one CPU can own the clean list.
2265 			 * Thus, it would only be possible for this to fail if
2266 			 * this code were racing with dtrace_dynvar_clean().
2267 			 * (That is, if dtrace_dynvar_clean() updated the clean
2268 			 * list, and we ended up racing to update the free
2269 			 * list.)  This race is prevented by the dtrace_sync()
2270 			 * in dtrace_dynvar_clean() -- which flushes the
2271 			 * owners of the clean lists out before resetting
2272 			 * the clean lists.
2273 			 */
2274 			dcpu = &dstate->dtds_percpu[me];
2275 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2276 			ASSERT(rval == NULL);
2277 			goto retry;
2278 		}
2279 
2280 		dvar = free;
2281 		new_free = dvar->dtdv_next;
2282 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2283 
2284 	/*
2285 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2286 	 * tuple array and copy any referenced key data into the data space
2287 	 * following the tuple array.  As we do this, we relocate dttk_value
2288 	 * in the final tuple to point to the key data address in the chunk.
2289 	 */
2290 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2291 	dvar->dtdv_data = (void *)(kdata + ksize);
2292 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2293 
2294 	for (i = 0; i < nkeys; i++) {
2295 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2296 		size_t kesize = key[i].dttk_size;
2297 
2298 		if (kesize != 0) {
2299 			dtrace_bcopy(
2300 			    (const void *)(uintptr_t)key[i].dttk_value,
2301 			    (void *)kdata, kesize);
2302 			dkey->dttk_value = kdata;
2303 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2304 		} else {
2305 			dkey->dttk_value = key[i].dttk_value;
2306 		}
2307 
2308 		dkey->dttk_size = kesize;
2309 	}
2310 
2311 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2312 	dvar->dtdv_hashval = hashval;
2313 	dvar->dtdv_next = start;
2314 
2315 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2316 		return (dvar);
2317 
2318 	/*
2319 	 * The cas has failed.  Either another CPU is adding an element to
2320 	 * this hash chain, or another CPU is deleting an element from this
2321 	 * hash chain.  The simplest way to deal with both of these cases
2322 	 * (though not necessarily the most efficient) is to free our
2323 	 * allocated block and re-attempt it all.  Note that the free is
2324 	 * to the dirty list and _not_ to the free list.  This is to prevent
2325 	 * races with allocators, above.
2326 	 */
2327 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2328 
2329 	dtrace_membar_producer();
2330 
2331 	do {
2332 		free = dcpu->dtdsc_dirty;
2333 		dvar->dtdv_next = free;
2334 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2335 
2336 	goto top;
2337 }
2338 
2339 /*ARGSUSED*/
2340 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2341 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2342 {
2343 	if ((int64_t)nval < (int64_t)*oval)
2344 		*oval = nval;
2345 }
2346 
2347 /*ARGSUSED*/
2348 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2349 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2350 {
2351 	if ((int64_t)nval > (int64_t)*oval)
2352 		*oval = nval;
2353 }
2354 
2355 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2356 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2357 {
2358 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2359 	int64_t val = (int64_t)nval;
2360 
2361 	if (val < 0) {
2362 		for (i = 0; i < zero; i++) {
2363 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2364 				quanta[i] += incr;
2365 				return;
2366 			}
2367 		}
2368 	} else {
2369 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2370 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2371 				quanta[i - 1] += incr;
2372 				return;
2373 			}
2374 		}
2375 
2376 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2377 		return;
2378 	}
2379 
2380 	ASSERT(0);
2381 }
2382 
2383 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2384 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2385 {
2386 	uint64_t arg = *lquanta++;
2387 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2388 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2389 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2390 	int32_t val = (int32_t)nval, level;
2391 
2392 	ASSERT(step != 0);
2393 	ASSERT(levels != 0);
2394 
2395 	if (val < base) {
2396 		/*
2397 		 * This is an underflow.
2398 		 */
2399 		lquanta[0] += incr;
2400 		return;
2401 	}
2402 
2403 	level = (val - base) / step;
2404 
2405 	if (level < levels) {
2406 		lquanta[level + 1] += incr;
2407 		return;
2408 	}
2409 
2410 	/*
2411 	 * This is an overflow.
2412 	 */
2413 	lquanta[levels + 1] += incr;
2414 }
2415 
2416 static int
dtrace_aggregate_llquantize_bucket(uint16_t factor,uint16_t low,uint16_t high,uint16_t nsteps,int64_t value)2417 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2418     uint16_t high, uint16_t nsteps, int64_t value)
2419 {
2420 	int64_t this = 1, last, next;
2421 	int base = 1, order;
2422 
2423 	ASSERT(factor <= nsteps);
2424 	ASSERT(nsteps % factor == 0);
2425 
2426 	for (order = 0; order < low; order++)
2427 		this *= factor;
2428 
2429 	/*
2430 	 * If our value is less than our factor taken to the power of the
2431 	 * low order of magnitude, it goes into the zeroth bucket.
2432 	 */
2433 	if (value < (last = this))
2434 		return (0);
2435 
2436 	for (this *= factor; order <= high; order++) {
2437 		int nbuckets = this > nsteps ? nsteps : this;
2438 
2439 		if ((next = this * factor) < this) {
2440 			/*
2441 			 * We should not generally get log/linear quantizations
2442 			 * with a high magnitude that allows 64-bits to
2443 			 * overflow, but we nonetheless protect against this
2444 			 * by explicitly checking for overflow, and clamping
2445 			 * our value accordingly.
2446 			 */
2447 			value = this - 1;
2448 		}
2449 
2450 		if (value < this) {
2451 			/*
2452 			 * If our value lies within this order of magnitude,
2453 			 * determine its position by taking the offset within
2454 			 * the order of magnitude, dividing by the bucket
2455 			 * width, and adding to our (accumulated) base.
2456 			 */
2457 			return (base + (value - last) / (this / nbuckets));
2458 		}
2459 
2460 		base += nbuckets - (nbuckets / factor);
2461 		last = this;
2462 		this = next;
2463 	}
2464 
2465 	/*
2466 	 * Our value is greater than or equal to our factor taken to the
2467 	 * power of one plus the high magnitude -- return the top bucket.
2468 	 */
2469 	return (base);
2470 }
2471 
2472 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2473 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2474 {
2475 	uint64_t arg = *llquanta++;
2476 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2477 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2478 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2479 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2480 
2481 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2482 	    low, high, nsteps, nval)] += incr;
2483 }
2484 
2485 /*ARGSUSED*/
2486 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2487 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2488 {
2489 	data[0]++;
2490 	data[1] += nval;
2491 }
2492 
2493 /*ARGSUSED*/
2494 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2495 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2496 {
2497 	int64_t snval = (int64_t)nval;
2498 	uint64_t tmp[2];
2499 
2500 	data[0]++;
2501 	data[1] += nval;
2502 
2503 	/*
2504 	 * What we want to say here is:
2505 	 *
2506 	 * data[2] += nval * nval;
2507 	 *
2508 	 * But given that nval is 64-bit, we could easily overflow, so
2509 	 * we do this as 128-bit arithmetic.
2510 	 */
2511 	if (snval < 0)
2512 		snval = -snval;
2513 
2514 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2515 	dtrace_add_128(data + 2, tmp, data + 2);
2516 }
2517 
2518 /*ARGSUSED*/
2519 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2520 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2521 {
2522 	*oval = *oval + 1;
2523 }
2524 
2525 /*ARGSUSED*/
2526 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2527 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2528 {
2529 	*oval += nval;
2530 }
2531 
2532 /*
2533  * Aggregate given the tuple in the principal data buffer, and the aggregating
2534  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2535  * buffer is specified as the buf parameter.  This routine does not return
2536  * failure; if there is no space in the aggregation buffer, the data will be
2537  * dropped, and a corresponding counter incremented.
2538  */
2539 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)2540 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2541     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2542 {
2543 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2544 	uint32_t i, ndx, size, fsize;
2545 	uint32_t align = sizeof (uint64_t) - 1;
2546 	dtrace_aggbuffer_t *agb;
2547 	dtrace_aggkey_t *key;
2548 	uint32_t hashval = 0, limit, isstr;
2549 	caddr_t tomax, data, kdata;
2550 	dtrace_actkind_t action;
2551 	dtrace_action_t *act;
2552 	size_t offs;
2553 
2554 	if (buf == NULL)
2555 		return;
2556 
2557 	if (!agg->dtag_hasarg) {
2558 		/*
2559 		 * Currently, only quantize() and lquantize() take additional
2560 		 * arguments, and they have the same semantics:  an increment
2561 		 * value that defaults to 1 when not present.  If additional
2562 		 * aggregating actions take arguments, the setting of the
2563 		 * default argument value will presumably have to become more
2564 		 * sophisticated...
2565 		 */
2566 		arg = 1;
2567 	}
2568 
2569 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2570 	size = rec->dtrd_offset - agg->dtag_base;
2571 	fsize = size + rec->dtrd_size;
2572 
2573 	ASSERT(dbuf->dtb_tomax != NULL);
2574 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2575 
2576 	if ((tomax = buf->dtb_tomax) == NULL) {
2577 		dtrace_buffer_drop(buf);
2578 		return;
2579 	}
2580 
2581 	/*
2582 	 * The metastructure is always at the bottom of the buffer.
2583 	 */
2584 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2585 	    sizeof (dtrace_aggbuffer_t));
2586 
2587 	if (buf->dtb_offset == 0) {
2588 		/*
2589 		 * We just kludge up approximately 1/8th of the size to be
2590 		 * buckets.  If this guess ends up being routinely
2591 		 * off-the-mark, we may need to dynamically readjust this
2592 		 * based on past performance.
2593 		 */
2594 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2595 
2596 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2597 		    (uintptr_t)tomax || hashsize == 0) {
2598 			/*
2599 			 * We've been given a ludicrously small buffer;
2600 			 * increment our drop count and leave.
2601 			 */
2602 			dtrace_buffer_drop(buf);
2603 			return;
2604 		}
2605 
2606 		/*
2607 		 * And now, a pathetic attempt to try to get a an odd (or
2608 		 * perchance, a prime) hash size for better hash distribution.
2609 		 */
2610 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2611 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2612 
2613 		agb->dtagb_hashsize = hashsize;
2614 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2615 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2616 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2617 
2618 		for (i = 0; i < agb->dtagb_hashsize; i++)
2619 			agb->dtagb_hash[i] = NULL;
2620 	}
2621 
2622 	ASSERT(agg->dtag_first != NULL);
2623 	ASSERT(agg->dtag_first->dta_intuple);
2624 
2625 	/*
2626 	 * Calculate the hash value based on the key.  Note that we _don't_
2627 	 * include the aggid in the hashing (but we will store it as part of
2628 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2629 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2630 	 * gets good distribution in practice.  The efficacy of the hashing
2631 	 * algorithm (and a comparison with other algorithms) may be found by
2632 	 * running the ::dtrace_aggstat MDB dcmd.
2633 	 */
2634 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2635 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2636 		limit = i + act->dta_rec.dtrd_size;
2637 		ASSERT(limit <= size);
2638 		isstr = DTRACEACT_ISSTRING(act);
2639 
2640 		for (; i < limit; i++) {
2641 			hashval += data[i];
2642 			hashval += (hashval << 10);
2643 			hashval ^= (hashval >> 6);
2644 
2645 			if (isstr && data[i] == '\0')
2646 				break;
2647 		}
2648 	}
2649 
2650 	hashval += (hashval << 3);
2651 	hashval ^= (hashval >> 11);
2652 	hashval += (hashval << 15);
2653 
2654 	/*
2655 	 * Yes, the divide here is expensive -- but it's generally the least
2656 	 * of the performance issues given the amount of data that we iterate
2657 	 * over to compute hash values, compare data, etc.
2658 	 */
2659 	ndx = hashval % agb->dtagb_hashsize;
2660 
2661 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2662 		ASSERT((caddr_t)key >= tomax);
2663 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2664 
2665 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2666 			continue;
2667 
2668 		kdata = key->dtak_data;
2669 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2670 
2671 		for (act = agg->dtag_first; act->dta_intuple;
2672 		    act = act->dta_next) {
2673 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2674 			limit = i + act->dta_rec.dtrd_size;
2675 			ASSERT(limit <= size);
2676 			isstr = DTRACEACT_ISSTRING(act);
2677 
2678 			for (; i < limit; i++) {
2679 				if (kdata[i] != data[i])
2680 					goto next;
2681 
2682 				if (isstr && data[i] == '\0')
2683 					break;
2684 			}
2685 		}
2686 
2687 		if (action != key->dtak_action) {
2688 			/*
2689 			 * We are aggregating on the same value in the same
2690 			 * aggregation with two different aggregating actions.
2691 			 * (This should have been picked up in the compiler,
2692 			 * so we may be dealing with errant or devious DIF.)
2693 			 * This is an error condition; we indicate as much,
2694 			 * and return.
2695 			 */
2696 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2697 			return;
2698 		}
2699 
2700 		/*
2701 		 * This is a hit:  we need to apply the aggregator to
2702 		 * the value at this key.
2703 		 */
2704 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2705 		return;
2706 next:
2707 		continue;
2708 	}
2709 
2710 	/*
2711 	 * We didn't find it.  We need to allocate some zero-filled space,
2712 	 * link it into the hash table appropriately, and apply the aggregator
2713 	 * to the (zero-filled) value.
2714 	 */
2715 	offs = buf->dtb_offset;
2716 	while (offs & (align - 1))
2717 		offs += sizeof (uint32_t);
2718 
2719 	/*
2720 	 * If we don't have enough room to both allocate a new key _and_
2721 	 * its associated data, increment the drop count and return.
2722 	 */
2723 	if ((uintptr_t)tomax + offs + fsize >
2724 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2725 		dtrace_buffer_drop(buf);
2726 		return;
2727 	}
2728 
2729 	/*CONSTCOND*/
2730 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2731 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2732 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2733 
2734 	key->dtak_data = kdata = tomax + offs;
2735 	buf->dtb_offset = offs + fsize;
2736 
2737 	/*
2738 	 * Now copy the data across.
2739 	 */
2740 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2741 
2742 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2743 		kdata[i] = data[i];
2744 
2745 	/*
2746 	 * Because strings are not zeroed out by default, we need to iterate
2747 	 * looking for actions that store strings, and we need to explicitly
2748 	 * pad these strings out with zeroes.
2749 	 */
2750 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2751 		int nul;
2752 
2753 		if (!DTRACEACT_ISSTRING(act))
2754 			continue;
2755 
2756 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2757 		limit = i + act->dta_rec.dtrd_size;
2758 		ASSERT(limit <= size);
2759 
2760 		for (nul = 0; i < limit; i++) {
2761 			if (nul) {
2762 				kdata[i] = '\0';
2763 				continue;
2764 			}
2765 
2766 			if (data[i] != '\0')
2767 				continue;
2768 
2769 			nul = 1;
2770 		}
2771 	}
2772 
2773 	for (i = size; i < fsize; i++)
2774 		kdata[i] = 0;
2775 
2776 	key->dtak_hashval = hashval;
2777 	key->dtak_size = size;
2778 	key->dtak_action = action;
2779 	key->dtak_next = agb->dtagb_hash[ndx];
2780 	agb->dtagb_hash[ndx] = key;
2781 
2782 	/*
2783 	 * Finally, apply the aggregator.
2784 	 */
2785 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2786 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2787 }
2788 
2789 /*
2790  * Given consumer state, this routine finds a speculation in the INACTIVE
2791  * state and transitions it into the ACTIVE state.  If there is no speculation
2792  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2793  * incremented -- it is up to the caller to take appropriate action.
2794  */
2795 static int
dtrace_speculation(dtrace_state_t * state)2796 dtrace_speculation(dtrace_state_t *state)
2797 {
2798 	int i = 0;
2799 	dtrace_speculation_state_t curstate;
2800 	uint32_t *stat = &state->dts_speculations_unavail, count;
2801 
2802 	while (i < state->dts_nspeculations) {
2803 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2804 
2805 		curstate = spec->dtsp_state;
2806 
2807 		if (curstate != DTRACESPEC_INACTIVE) {
2808 			if (curstate == DTRACESPEC_COMMITTINGMANY ||
2809 			    curstate == DTRACESPEC_COMMITTING ||
2810 			    curstate == DTRACESPEC_DISCARDING)
2811 				stat = &state->dts_speculations_busy;
2812 			i++;
2813 			continue;
2814 		}
2815 
2816 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2817 		    curstate, DTRACESPEC_ACTIVE) == curstate)
2818 			return (i + 1);
2819 	}
2820 
2821 	/*
2822 	 * We couldn't find a speculation.  If we found as much as a single
2823 	 * busy speculation buffer, we'll attribute this failure as "busy"
2824 	 * instead of "unavail".
2825 	 */
2826 	do {
2827 		count = *stat;
2828 	} while (dtrace_cas32(stat, count, count + 1) != count);
2829 
2830 	return (0);
2831 }
2832 
2833 /*
2834  * This routine commits an active speculation.  If the specified speculation
2835  * is not in a valid state to perform a commit(), this routine will silently do
2836  * nothing.  The state of the specified speculation is transitioned according
2837  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2838  */
2839 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2840 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2841     dtrace_specid_t which)
2842 {
2843 	dtrace_speculation_t *spec;
2844 	dtrace_buffer_t *src, *dest;
2845 	uintptr_t daddr, saddr, dlimit, slimit;
2846 	dtrace_speculation_state_t curstate, new = 0;
2847 	ssize_t offs;
2848 	uint64_t timestamp;
2849 
2850 	if (which == 0)
2851 		return;
2852 
2853 	if (which > state->dts_nspeculations) {
2854 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2855 		return;
2856 	}
2857 
2858 	spec = &state->dts_speculations[which - 1];
2859 	src = &spec->dtsp_buffer[cpu];
2860 	dest = &state->dts_buffer[cpu];
2861 
2862 	do {
2863 		curstate = spec->dtsp_state;
2864 
2865 		if (curstate == DTRACESPEC_COMMITTINGMANY)
2866 			break;
2867 
2868 		switch (curstate) {
2869 		case DTRACESPEC_INACTIVE:
2870 		case DTRACESPEC_DISCARDING:
2871 			return;
2872 
2873 		case DTRACESPEC_COMMITTING:
2874 			/*
2875 			 * This is only possible if we are (a) commit()'ing
2876 			 * without having done a prior speculate() on this CPU
2877 			 * and (b) racing with another commit() on a different
2878 			 * CPU.  There's nothing to do -- we just assert that
2879 			 * our offset is 0.
2880 			 */
2881 			ASSERT(src->dtb_offset == 0);
2882 			return;
2883 
2884 		case DTRACESPEC_ACTIVE:
2885 			new = DTRACESPEC_COMMITTING;
2886 			break;
2887 
2888 		case DTRACESPEC_ACTIVEONE:
2889 			/*
2890 			 * This speculation is active on one CPU.  If our
2891 			 * buffer offset is non-zero, we know that the one CPU
2892 			 * must be us.  Otherwise, we are committing on a
2893 			 * different CPU from the speculate(), and we must
2894 			 * rely on being asynchronously cleaned.
2895 			 */
2896 			if (src->dtb_offset != 0) {
2897 				new = DTRACESPEC_COMMITTING;
2898 				break;
2899 			}
2900 			/*FALLTHROUGH*/
2901 
2902 		case DTRACESPEC_ACTIVEMANY:
2903 			new = DTRACESPEC_COMMITTINGMANY;
2904 			break;
2905 
2906 		default:
2907 			ASSERT(0);
2908 		}
2909 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2910 	    curstate, new) != curstate);
2911 
2912 	/*
2913 	 * We have set the state to indicate that we are committing this
2914 	 * speculation.  Now reserve the necessary space in the destination
2915 	 * buffer.
2916 	 */
2917 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2918 	    sizeof (uint64_t), state, NULL)) < 0) {
2919 		dtrace_buffer_drop(dest);
2920 		goto out;
2921 	}
2922 
2923 	/*
2924 	 * We have sufficient space to copy the speculative buffer into the
2925 	 * primary buffer.  First, modify the speculative buffer, filling
2926 	 * in the timestamp of all entries with the curstate time.  The data
2927 	 * must have the commit() time rather than the time it was traced,
2928 	 * so that all entries in the primary buffer are in timestamp order.
2929 	 */
2930 	timestamp = dtrace_gethrtime();
2931 	saddr = (uintptr_t)src->dtb_tomax;
2932 	slimit = saddr + src->dtb_offset;
2933 	while (saddr < slimit) {
2934 		size_t size;
2935 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2936 
2937 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2938 			saddr += sizeof (dtrace_epid_t);
2939 			continue;
2940 		}
2941 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2942 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2943 
2944 		ASSERT3U(saddr + size, <=, slimit);
2945 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2946 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2947 
2948 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2949 
2950 		saddr += size;
2951 	}
2952 
2953 	/*
2954 	 * Copy the buffer across.  (Note that this is a
2955 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2956 	 * a serious performance issue, a high-performance DTrace-specific
2957 	 * bcopy() should obviously be invented.)
2958 	 */
2959 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2960 	dlimit = daddr + src->dtb_offset;
2961 	saddr = (uintptr_t)src->dtb_tomax;
2962 
2963 	/*
2964 	 * First, the aligned portion.
2965 	 */
2966 	while (dlimit - daddr >= sizeof (uint64_t)) {
2967 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2968 
2969 		daddr += sizeof (uint64_t);
2970 		saddr += sizeof (uint64_t);
2971 	}
2972 
2973 	/*
2974 	 * Now any left-over bit...
2975 	 */
2976 	while (dlimit - daddr)
2977 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2978 
2979 	/*
2980 	 * Finally, commit the reserved space in the destination buffer.
2981 	 */
2982 	dest->dtb_offset = offs + src->dtb_offset;
2983 
2984 out:
2985 	/*
2986 	 * If we're lucky enough to be the only active CPU on this speculation
2987 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2988 	 */
2989 	if (curstate == DTRACESPEC_ACTIVE ||
2990 	    (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2991 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2992 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2993 
2994 		ASSERT(rval == DTRACESPEC_COMMITTING);
2995 	}
2996 
2997 	src->dtb_offset = 0;
2998 	src->dtb_xamot_drops += src->dtb_drops;
2999 	src->dtb_drops = 0;
3000 }
3001 
3002 /*
3003  * This routine discards an active speculation.  If the specified speculation
3004  * is not in a valid state to perform a discard(), this routine will silently
3005  * do nothing.  The state of the specified speculation is transitioned
3006  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3007  */
3008 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)3009 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3010     dtrace_specid_t which)
3011 {
3012 	dtrace_speculation_t *spec;
3013 	dtrace_speculation_state_t curstate, new = 0;
3014 	dtrace_buffer_t *buf;
3015 
3016 	if (which == 0)
3017 		return;
3018 
3019 	if (which > state->dts_nspeculations) {
3020 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3021 		return;
3022 	}
3023 
3024 	spec = &state->dts_speculations[which - 1];
3025 	buf = &spec->dtsp_buffer[cpu];
3026 
3027 	do {
3028 		curstate = spec->dtsp_state;
3029 
3030 		switch (curstate) {
3031 		case DTRACESPEC_INACTIVE:
3032 		case DTRACESPEC_COMMITTINGMANY:
3033 		case DTRACESPEC_COMMITTING:
3034 		case DTRACESPEC_DISCARDING:
3035 			return;
3036 
3037 		case DTRACESPEC_ACTIVE:
3038 		case DTRACESPEC_ACTIVEMANY:
3039 			new = DTRACESPEC_DISCARDING;
3040 			break;
3041 
3042 		case DTRACESPEC_ACTIVEONE:
3043 			if (buf->dtb_offset != 0) {
3044 				new = DTRACESPEC_INACTIVE;
3045 			} else {
3046 				new = DTRACESPEC_DISCARDING;
3047 			}
3048 			break;
3049 
3050 		default:
3051 			ASSERT(0);
3052 		}
3053 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3054 	    curstate, new) != curstate);
3055 
3056 	buf->dtb_offset = 0;
3057 	buf->dtb_drops = 0;
3058 }
3059 
3060 /*
3061  * Note:  not called from probe context.  This function is called
3062  * asynchronously from cross call context to clean any speculations that are
3063  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3064  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3065  * speculation.
3066  */
3067 static void
dtrace_speculation_clean_here(dtrace_state_t * state)3068 dtrace_speculation_clean_here(dtrace_state_t *state)
3069 {
3070 	dtrace_icookie_t cookie;
3071 	processorid_t cpu = curcpu;
3072 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3073 	dtrace_specid_t i;
3074 
3075 	cookie = dtrace_interrupt_disable();
3076 
3077 	if (dest->dtb_tomax == NULL) {
3078 		dtrace_interrupt_enable(cookie);
3079 		return;
3080 	}
3081 
3082 	for (i = 0; i < state->dts_nspeculations; i++) {
3083 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3084 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3085 
3086 		if (src->dtb_tomax == NULL)
3087 			continue;
3088 
3089 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3090 			src->dtb_offset = 0;
3091 			continue;
3092 		}
3093 
3094 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3095 			continue;
3096 
3097 		if (src->dtb_offset == 0)
3098 			continue;
3099 
3100 		dtrace_speculation_commit(state, cpu, i + 1);
3101 	}
3102 
3103 	dtrace_interrupt_enable(cookie);
3104 }
3105 
3106 /*
3107  * Note:  not called from probe context.  This function is called
3108  * asynchronously (and at a regular interval) to clean any speculations that
3109  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3110  * is work to be done, it cross calls all CPUs to perform that work;
3111  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3112  * INACTIVE state until they have been cleaned by all CPUs.
3113  */
3114 static void
dtrace_speculation_clean(dtrace_state_t * state)3115 dtrace_speculation_clean(dtrace_state_t *state)
3116 {
3117 	int work = 0, rv;
3118 	dtrace_specid_t i;
3119 
3120 	for (i = 0; i < state->dts_nspeculations; i++) {
3121 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3122 
3123 		ASSERT(!spec->dtsp_cleaning);
3124 
3125 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3126 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3127 			continue;
3128 
3129 		work++;
3130 		spec->dtsp_cleaning = 1;
3131 	}
3132 
3133 	if (!work)
3134 		return;
3135 
3136 	dtrace_xcall(DTRACE_CPUALL,
3137 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3138 
3139 	/*
3140 	 * We now know that all CPUs have committed or discarded their
3141 	 * speculation buffers, as appropriate.  We can now set the state
3142 	 * to inactive.
3143 	 */
3144 	for (i = 0; i < state->dts_nspeculations; i++) {
3145 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3146 		dtrace_speculation_state_t curstate, new;
3147 
3148 		if (!spec->dtsp_cleaning)
3149 			continue;
3150 
3151 		curstate = spec->dtsp_state;
3152 		ASSERT(curstate == DTRACESPEC_DISCARDING ||
3153 		    curstate == DTRACESPEC_COMMITTINGMANY);
3154 
3155 		new = DTRACESPEC_INACTIVE;
3156 
3157 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3158 		ASSERT(rv == curstate);
3159 		spec->dtsp_cleaning = 0;
3160 	}
3161 }
3162 
3163 /*
3164  * Called as part of a speculate() to get the speculative buffer associated
3165  * with a given speculation.  Returns NULL if the specified speculation is not
3166  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3167  * the active CPU is not the specified CPU -- the speculation will be
3168  * atomically transitioned into the ACTIVEMANY state.
3169  */
3170 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3171 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3172     dtrace_specid_t which)
3173 {
3174 	dtrace_speculation_t *spec;
3175 	dtrace_speculation_state_t curstate, new = 0;
3176 	dtrace_buffer_t *buf;
3177 
3178 	if (which == 0)
3179 		return (NULL);
3180 
3181 	if (which > state->dts_nspeculations) {
3182 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3183 		return (NULL);
3184 	}
3185 
3186 	spec = &state->dts_speculations[which - 1];
3187 	buf = &spec->dtsp_buffer[cpuid];
3188 
3189 	do {
3190 		curstate = spec->dtsp_state;
3191 
3192 		switch (curstate) {
3193 		case DTRACESPEC_INACTIVE:
3194 		case DTRACESPEC_COMMITTINGMANY:
3195 		case DTRACESPEC_DISCARDING:
3196 			return (NULL);
3197 
3198 		case DTRACESPEC_COMMITTING:
3199 			ASSERT(buf->dtb_offset == 0);
3200 			return (NULL);
3201 
3202 		case DTRACESPEC_ACTIVEONE:
3203 			/*
3204 			 * This speculation is currently active on one CPU.
3205 			 * Check the offset in the buffer; if it's non-zero,
3206 			 * that CPU must be us (and we leave the state alone).
3207 			 * If it's zero, assume that we're starting on a new
3208 			 * CPU -- and change the state to indicate that the
3209 			 * speculation is active on more than one CPU.
3210 			 */
3211 			if (buf->dtb_offset != 0)
3212 				return (buf);
3213 
3214 			new = DTRACESPEC_ACTIVEMANY;
3215 			break;
3216 
3217 		case DTRACESPEC_ACTIVEMANY:
3218 			return (buf);
3219 
3220 		case DTRACESPEC_ACTIVE:
3221 			new = DTRACESPEC_ACTIVEONE;
3222 			break;
3223 
3224 		default:
3225 			ASSERT(0);
3226 		}
3227 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3228 	    curstate, new) != curstate);
3229 
3230 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3231 	return (buf);
3232 }
3233 
3234 /*
3235  * Return a string.  In the event that the user lacks the privilege to access
3236  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3237  * don't fail access checking.
3238  *
3239  * dtrace_dif_variable() uses this routine as a helper for various
3240  * builtin values such as 'execname' and 'probefunc.'
3241  */
3242 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3243 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3244     dtrace_mstate_t *mstate)
3245 {
3246 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3247 	uintptr_t ret;
3248 	size_t strsz;
3249 
3250 	/*
3251 	 * The easy case: this probe is allowed to read all of memory, so
3252 	 * we can just return this as a vanilla pointer.
3253 	 */
3254 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3255 		return (addr);
3256 
3257 	/*
3258 	 * This is the tougher case: we copy the string in question from
3259 	 * kernel memory into scratch memory and return it that way: this
3260 	 * ensures that we won't trip up when access checking tests the
3261 	 * BYREF return value.
3262 	 */
3263 	strsz = dtrace_strlen((char *)addr, size) + 1;
3264 
3265 	if (mstate->dtms_scratch_ptr + strsz >
3266 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3267 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3268 		return (0);
3269 	}
3270 
3271 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3272 	    strsz);
3273 	ret = mstate->dtms_scratch_ptr;
3274 	mstate->dtms_scratch_ptr += strsz;
3275 	return (ret);
3276 }
3277 
3278 /*
3279  * Return a string from a memoy address which is known to have one or
3280  * more concatenated, individually zero terminated, sub-strings.
3281  * In the event that the user lacks the privilege to access
3282  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3283  * don't fail access checking.
3284  *
3285  * dtrace_dif_variable() uses this routine as a helper for various
3286  * builtin values such as 'execargs'.
3287  */
3288 static uintptr_t
dtrace_dif_varstrz(uintptr_t addr,size_t strsz,dtrace_state_t * state,dtrace_mstate_t * mstate)3289 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3290     dtrace_mstate_t *mstate)
3291 {
3292 	char *p;
3293 	size_t i;
3294 	uintptr_t ret;
3295 
3296 	if (mstate->dtms_scratch_ptr + strsz >
3297 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3298 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3299 		return (0);
3300 	}
3301 
3302 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3303 	    strsz);
3304 
3305 	/* Replace sub-string termination characters with a space. */
3306 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3307 	    p++, i++)
3308 		if (*p == '\0')
3309 			*p = ' ';
3310 
3311 	ret = mstate->dtms_scratch_ptr;
3312 	mstate->dtms_scratch_ptr += strsz;
3313 	return (ret);
3314 }
3315 
3316 /*
3317  * This function implements the DIF emulator's variable lookups.  The emulator
3318  * passes a reserved variable identifier and optional built-in array index.
3319  */
3320 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3321 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3322     uint64_t ndx)
3323 {
3324 	/*
3325 	 * If we're accessing one of the uncached arguments, we'll turn this
3326 	 * into a reference in the args array.
3327 	 */
3328 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3329 		ndx = v - DIF_VAR_ARG0;
3330 		v = DIF_VAR_ARGS;
3331 	}
3332 
3333 	switch (v) {
3334 	case DIF_VAR_ARGS:
3335 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3336 		if (ndx >= sizeof (mstate->dtms_arg) /
3337 		    sizeof (mstate->dtms_arg[0])) {
3338 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3339 			dtrace_provider_t *pv;
3340 			uint64_t val;
3341 
3342 			pv = mstate->dtms_probe->dtpr_provider;
3343 			if (pv->dtpv_pops.dtps_getargval != NULL)
3344 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3345 				    mstate->dtms_probe->dtpr_id,
3346 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3347 			else
3348 				val = dtrace_getarg(ndx, aframes);
3349 
3350 			/*
3351 			 * This is regrettably required to keep the compiler
3352 			 * from tail-optimizing the call to dtrace_getarg().
3353 			 * The condition always evaluates to true, but the
3354 			 * compiler has no way of figuring that out a priori.
3355 			 * (None of this would be necessary if the compiler
3356 			 * could be relied upon to _always_ tail-optimize
3357 			 * the call to dtrace_getarg() -- but it can't.)
3358 			 */
3359 			if (mstate->dtms_probe != NULL)
3360 				return (val);
3361 
3362 			ASSERT(0);
3363 		}
3364 
3365 		return (mstate->dtms_arg[ndx]);
3366 
3367 	case DIF_VAR_REGS:
3368 	case DIF_VAR_UREGS: {
3369 		struct trapframe *tframe;
3370 
3371 		if (!dtrace_priv_proc(state))
3372 			return (0);
3373 
3374 		if (v == DIF_VAR_REGS)
3375 			tframe = curthread->t_dtrace_trapframe;
3376 		else
3377 			tframe = curthread->td_frame;
3378 
3379 		if (tframe == NULL) {
3380 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3381 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3382 			return (0);
3383 		}
3384 
3385 		return (dtrace_getreg(tframe, ndx));
3386 	}
3387 
3388 	case DIF_VAR_CURTHREAD:
3389 		if (!dtrace_priv_proc(state))
3390 			return (0);
3391 		return ((uint64_t)(uintptr_t)curthread);
3392 
3393 	case DIF_VAR_TIMESTAMP:
3394 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3395 			mstate->dtms_timestamp = dtrace_gethrtime();
3396 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3397 		}
3398 		return (mstate->dtms_timestamp);
3399 
3400 	case DIF_VAR_VTIMESTAMP:
3401 		ASSERT(dtrace_vtime_references != 0);
3402 		return (curthread->t_dtrace_vtime);
3403 
3404 	case DIF_VAR_WALLTIMESTAMP:
3405 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3406 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3407 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3408 		}
3409 		return (mstate->dtms_walltimestamp);
3410 
3411 #ifdef illumos
3412 	case DIF_VAR_IPL:
3413 		if (!dtrace_priv_kernel(state))
3414 			return (0);
3415 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3416 			mstate->dtms_ipl = dtrace_getipl();
3417 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3418 		}
3419 		return (mstate->dtms_ipl);
3420 #endif
3421 
3422 	case DIF_VAR_EPID:
3423 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3424 		return (mstate->dtms_epid);
3425 
3426 	case DIF_VAR_ID:
3427 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3428 		return (mstate->dtms_probe->dtpr_id);
3429 
3430 	case DIF_VAR_STACKDEPTH:
3431 		if (!dtrace_priv_kernel(state))
3432 			return (0);
3433 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3434 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3435 
3436 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3437 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3438 		}
3439 		return (mstate->dtms_stackdepth);
3440 
3441 	case DIF_VAR_USTACKDEPTH:
3442 		if (!dtrace_priv_proc(state))
3443 			return (0);
3444 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3445 			/*
3446 			 * See comment in DIF_VAR_PID.
3447 			 */
3448 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3449 			    CPU_ON_INTR(CPU)) {
3450 				mstate->dtms_ustackdepth = 0;
3451 			} else {
3452 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3453 				mstate->dtms_ustackdepth =
3454 				    dtrace_getustackdepth();
3455 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3456 			}
3457 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3458 		}
3459 		return (mstate->dtms_ustackdepth);
3460 
3461 	case DIF_VAR_CALLER:
3462 		if (!dtrace_priv_kernel(state))
3463 			return (0);
3464 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3465 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3466 
3467 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3468 				/*
3469 				 * If this is an unanchored probe, we are
3470 				 * required to go through the slow path:
3471 				 * dtrace_caller() only guarantees correct
3472 				 * results for anchored probes.
3473 				 */
3474 				pc_t caller[2] = {0, 0};
3475 
3476 				dtrace_getpcstack(caller, 2, aframes,
3477 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3478 				mstate->dtms_caller = caller[1];
3479 			} else if ((mstate->dtms_caller =
3480 			    dtrace_caller(aframes)) == -1) {
3481 				/*
3482 				 * We have failed to do this the quick way;
3483 				 * we must resort to the slower approach of
3484 				 * calling dtrace_getpcstack().
3485 				 */
3486 				pc_t caller = 0;
3487 
3488 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3489 				mstate->dtms_caller = caller;
3490 			}
3491 
3492 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3493 		}
3494 		return (mstate->dtms_caller);
3495 
3496 	case DIF_VAR_UCALLER:
3497 		if (!dtrace_priv_proc(state))
3498 			return (0);
3499 
3500 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3501 			uint64_t ustack[3];
3502 
3503 			/*
3504 			 * dtrace_getupcstack() fills in the first uint64_t
3505 			 * with the current PID.  The second uint64_t will
3506 			 * be the program counter at user-level.  The third
3507 			 * uint64_t will contain the caller, which is what
3508 			 * we're after.
3509 			 */
3510 			ustack[2] = 0;
3511 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3512 			dtrace_getupcstack(ustack, 3);
3513 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3514 			mstate->dtms_ucaller = ustack[2];
3515 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3516 		}
3517 
3518 		return (mstate->dtms_ucaller);
3519 
3520 	case DIF_VAR_PROBEPROV:
3521 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3522 		return (dtrace_dif_varstr(
3523 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3524 		    state, mstate));
3525 
3526 	case DIF_VAR_PROBEMOD:
3527 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3528 		return (dtrace_dif_varstr(
3529 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3530 		    state, mstate));
3531 
3532 	case DIF_VAR_PROBEFUNC:
3533 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3534 		return (dtrace_dif_varstr(
3535 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3536 		    state, mstate));
3537 
3538 	case DIF_VAR_PROBENAME:
3539 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3540 		return (dtrace_dif_varstr(
3541 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3542 		    state, mstate));
3543 
3544 	case DIF_VAR_PID:
3545 		if (!dtrace_priv_proc(state))
3546 			return (0);
3547 
3548 #ifdef illumos
3549 		/*
3550 		 * Note that we are assuming that an unanchored probe is
3551 		 * always due to a high-level interrupt.  (And we're assuming
3552 		 * that there is only a single high level interrupt.)
3553 		 */
3554 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3555 			return (pid0.pid_id);
3556 
3557 		/*
3558 		 * It is always safe to dereference one's own t_procp pointer:
3559 		 * it always points to a valid, allocated proc structure.
3560 		 * Further, it is always safe to dereference the p_pidp member
3561 		 * of one's own proc structure.  (These are truisms becuase
3562 		 * threads and processes don't clean up their own state --
3563 		 * they leave that task to whomever reaps them.)
3564 		 */
3565 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3566 #else
3567 		return ((uint64_t)curproc->p_pid);
3568 #endif
3569 
3570 	case DIF_VAR_PPID:
3571 		if (!dtrace_priv_proc(state))
3572 			return (0);
3573 
3574 #ifdef illumos
3575 		/*
3576 		 * See comment in DIF_VAR_PID.
3577 		 */
3578 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3579 			return (pid0.pid_id);
3580 
3581 		/*
3582 		 * It is always safe to dereference one's own t_procp pointer:
3583 		 * it always points to a valid, allocated proc structure.
3584 		 * (This is true because threads don't clean up their own
3585 		 * state -- they leave that task to whomever reaps them.)
3586 		 */
3587 		return ((uint64_t)curthread->t_procp->p_ppid);
3588 #else
3589 		if (curproc->p_pid == proc0.p_pid)
3590 			return (curproc->p_pid);
3591 		else
3592 			return (curproc->p_pptr->p_pid);
3593 #endif
3594 
3595 	case DIF_VAR_TID:
3596 #ifdef illumos
3597 		/*
3598 		 * See comment in DIF_VAR_PID.
3599 		 */
3600 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3601 			return (0);
3602 #endif
3603 
3604 		return ((uint64_t)curthread->t_tid);
3605 
3606 	case DIF_VAR_EXECARGS: {
3607 		struct pargs *p_args = curthread->td_proc->p_args;
3608 
3609 		if (p_args == NULL)
3610 			return(0);
3611 
3612 		return (dtrace_dif_varstrz(
3613 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3614 	}
3615 
3616 	case DIF_VAR_EXECNAME:
3617 #ifdef illumos
3618 		if (!dtrace_priv_proc(state))
3619 			return (0);
3620 
3621 		/*
3622 		 * See comment in DIF_VAR_PID.
3623 		 */
3624 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3625 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3626 
3627 		/*
3628 		 * It is always safe to dereference one's own t_procp pointer:
3629 		 * it always points to a valid, allocated proc structure.
3630 		 * (This is true because threads don't clean up their own
3631 		 * state -- they leave that task to whomever reaps them.)
3632 		 */
3633 		return (dtrace_dif_varstr(
3634 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3635 		    state, mstate));
3636 #else
3637 		return (dtrace_dif_varstr(
3638 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3639 #endif
3640 
3641 	case DIF_VAR_ZONENAME:
3642 #ifdef illumos
3643 		if (!dtrace_priv_proc(state))
3644 			return (0);
3645 
3646 		/*
3647 		 * See comment in DIF_VAR_PID.
3648 		 */
3649 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3650 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3651 
3652 		/*
3653 		 * It is always safe to dereference one's own t_procp pointer:
3654 		 * it always points to a valid, allocated proc structure.
3655 		 * (This is true because threads don't clean up their own
3656 		 * state -- they leave that task to whomever reaps them.)
3657 		 */
3658 		return (dtrace_dif_varstr(
3659 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3660 		    state, mstate));
3661 #elif defined(__FreeBSD__)
3662 	/*
3663 	 * On FreeBSD, we introduce compatibility to zonename by falling through
3664 	 * into jailname.
3665 	 */
3666 	case DIF_VAR_JAILNAME:
3667 		if (!dtrace_priv_kernel(state))
3668 			return (0);
3669 
3670 		return (dtrace_dif_varstr(
3671 		    (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3672 		    state, mstate));
3673 
3674 	case DIF_VAR_JID:
3675 		if (!dtrace_priv_kernel(state))
3676 			return (0);
3677 
3678 		return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3679 #else
3680 		return (0);
3681 #endif
3682 
3683 	case DIF_VAR_UID:
3684 		if (!dtrace_priv_proc(state))
3685 			return (0);
3686 
3687 #ifdef illumos
3688 		/*
3689 		 * See comment in DIF_VAR_PID.
3690 		 */
3691 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3692 			return ((uint64_t)p0.p_cred->cr_uid);
3693 
3694 		/*
3695 		 * It is always safe to dereference one's own t_procp pointer:
3696 		 * it always points to a valid, allocated proc structure.
3697 		 * (This is true because threads don't clean up their own
3698 		 * state -- they leave that task to whomever reaps them.)
3699 		 *
3700 		 * Additionally, it is safe to dereference one's own process
3701 		 * credential, since this is never NULL after process birth.
3702 		 */
3703 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3704 #else
3705 		return ((uint64_t)curthread->td_ucred->cr_uid);
3706 #endif
3707 
3708 	case DIF_VAR_GID:
3709 		if (!dtrace_priv_proc(state))
3710 			return (0);
3711 
3712 #ifdef illumos
3713 		/*
3714 		 * See comment in DIF_VAR_PID.
3715 		 */
3716 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3717 			return ((uint64_t)p0.p_cred->cr_gid);
3718 
3719 		/*
3720 		 * It is always safe to dereference one's own t_procp pointer:
3721 		 * it always points to a valid, allocated proc structure.
3722 		 * (This is true because threads don't clean up their own
3723 		 * state -- they leave that task to whomever reaps them.)
3724 		 *
3725 		 * Additionally, it is safe to dereference one's own process
3726 		 * credential, since this is never NULL after process birth.
3727 		 */
3728 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3729 #else
3730 		return ((uint64_t)curthread->td_ucred->cr_gid);
3731 #endif
3732 
3733 	case DIF_VAR_ERRNO: {
3734 #ifdef illumos
3735 		klwp_t *lwp;
3736 		if (!dtrace_priv_proc(state))
3737 			return (0);
3738 
3739 		/*
3740 		 * See comment in DIF_VAR_PID.
3741 		 */
3742 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3743 			return (0);
3744 
3745 		/*
3746 		 * It is always safe to dereference one's own t_lwp pointer in
3747 		 * the event that this pointer is non-NULL.  (This is true
3748 		 * because threads and lwps don't clean up their own state --
3749 		 * they leave that task to whomever reaps them.)
3750 		 */
3751 		if ((lwp = curthread->t_lwp) == NULL)
3752 			return (0);
3753 
3754 		return ((uint64_t)lwp->lwp_errno);
3755 #else
3756 		return (curthread->td_errno);
3757 #endif
3758 	}
3759 #ifndef illumos
3760 	case DIF_VAR_CPU: {
3761 		return curcpu;
3762 	}
3763 #endif
3764 	default:
3765 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3766 		return (0);
3767 	}
3768 }
3769 
3770 
3771 typedef enum dtrace_json_state {
3772 	DTRACE_JSON_REST = 1,
3773 	DTRACE_JSON_OBJECT,
3774 	DTRACE_JSON_STRING,
3775 	DTRACE_JSON_STRING_ESCAPE,
3776 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3777 	DTRACE_JSON_COLON,
3778 	DTRACE_JSON_COMMA,
3779 	DTRACE_JSON_VALUE,
3780 	DTRACE_JSON_IDENTIFIER,
3781 	DTRACE_JSON_NUMBER,
3782 	DTRACE_JSON_NUMBER_FRAC,
3783 	DTRACE_JSON_NUMBER_EXP,
3784 	DTRACE_JSON_COLLECT_OBJECT
3785 } dtrace_json_state_t;
3786 
3787 /*
3788  * This function possesses just enough knowledge about JSON to extract a single
3789  * value from a JSON string and store it in the scratch buffer.  It is able
3790  * to extract nested object values, and members of arrays by index.
3791  *
3792  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3793  * be looked up as we descend into the object tree.  e.g.
3794  *
3795  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3796  *       with nelems = 5.
3797  *
3798  * The run time of this function must be bounded above by strsize to limit the
3799  * amount of work done in probe context.  As such, it is implemented as a
3800  * simple state machine, reading one character at a time using safe loads
3801  * until we find the requested element, hit a parsing error or run off the
3802  * end of the object or string.
3803  *
3804  * As there is no way for a subroutine to return an error without interrupting
3805  * clause execution, we simply return NULL in the event of a missing key or any
3806  * other error condition.  Each NULL return in this function is commented with
3807  * the error condition it represents -- parsing or otherwise.
3808  *
3809  * The set of states for the state machine closely matches the JSON
3810  * specification (http://json.org/).  Briefly:
3811  *
3812  *   DTRACE_JSON_REST:
3813  *     Skip whitespace until we find either a top-level Object, moving
3814  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3815  *
3816  *   DTRACE_JSON_OBJECT:
3817  *     Locate the next key String in an Object.  Sets a flag to denote
3818  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3819  *
3820  *   DTRACE_JSON_COLON:
3821  *     Skip whitespace until we find the colon that separates key Strings
3822  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3823  *
3824  *   DTRACE_JSON_VALUE:
3825  *     Detects the type of the next value (String, Number, Identifier, Object
3826  *     or Array) and routes to the states that process that type.  Here we also
3827  *     deal with the element selector list if we are requested to traverse down
3828  *     into the object tree.
3829  *
3830  *   DTRACE_JSON_COMMA:
3831  *     Skip whitespace until we find the comma that separates key-value pairs
3832  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3833  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3834  *     states return to this state at the end of their value, unless otherwise
3835  *     noted.
3836  *
3837  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3838  *     Processes a Number literal from the JSON, including any exponent
3839  *     component that may be present.  Numbers are returned as strings, which
3840  *     may be passed to strtoll() if an integer is required.
3841  *
3842  *   DTRACE_JSON_IDENTIFIER:
3843  *     Processes a "true", "false" or "null" literal in the JSON.
3844  *
3845  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3846  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3847  *     Processes a String literal from the JSON, whether the String denotes
3848  *     a key, a value or part of a larger Object.  Handles all escape sequences
3849  *     present in the specification, including four-digit unicode characters,
3850  *     but merely includes the escape sequence without converting it to the
3851  *     actual escaped character.  If the String is flagged as a key, we
3852  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3853  *
3854  *   DTRACE_JSON_COLLECT_OBJECT:
3855  *     This state collects an entire Object (or Array), correctly handling
3856  *     embedded strings.  If the full element selector list matches this nested
3857  *     object, we return the Object in full as a string.  If not, we use this
3858  *     state to skip to the next value at this level and continue processing.
3859  *
3860  * NOTE: This function uses various macros from strtolctype.h to manipulate
3861  * digit values, etc -- these have all been checked to ensure they make
3862  * no additional function calls.
3863  */
3864 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3865 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3866     char *dest)
3867 {
3868 	dtrace_json_state_t state = DTRACE_JSON_REST;
3869 	int64_t array_elem = INT64_MIN;
3870 	int64_t array_pos = 0;
3871 	uint8_t escape_unicount = 0;
3872 	boolean_t string_is_key = B_FALSE;
3873 	boolean_t collect_object = B_FALSE;
3874 	boolean_t found_key = B_FALSE;
3875 	boolean_t in_array = B_FALSE;
3876 	uint32_t braces = 0, brackets = 0;
3877 	char *elem = elemlist;
3878 	char *dd = dest;
3879 	uintptr_t cur;
3880 
3881 	for (cur = json; cur < json + size; cur++) {
3882 		char cc = dtrace_load8(cur);
3883 		if (cc == '\0')
3884 			return (NULL);
3885 
3886 		switch (state) {
3887 		case DTRACE_JSON_REST:
3888 			if (isspace(cc))
3889 				break;
3890 
3891 			if (cc == '{') {
3892 				state = DTRACE_JSON_OBJECT;
3893 				break;
3894 			}
3895 
3896 			if (cc == '[') {
3897 				in_array = B_TRUE;
3898 				array_pos = 0;
3899 				array_elem = dtrace_strtoll(elem, 10, size);
3900 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3901 				state = DTRACE_JSON_VALUE;
3902 				break;
3903 			}
3904 
3905 			/*
3906 			 * ERROR: expected to find a top-level object or array.
3907 			 */
3908 			return (NULL);
3909 		case DTRACE_JSON_OBJECT:
3910 			if (isspace(cc))
3911 				break;
3912 
3913 			if (cc == '"') {
3914 				state = DTRACE_JSON_STRING;
3915 				string_is_key = B_TRUE;
3916 				break;
3917 			}
3918 
3919 			/*
3920 			 * ERROR: either the object did not start with a key
3921 			 * string, or we've run off the end of the object
3922 			 * without finding the requested key.
3923 			 */
3924 			return (NULL);
3925 		case DTRACE_JSON_STRING:
3926 			if (cc == '\\') {
3927 				*dd++ = '\\';
3928 				state = DTRACE_JSON_STRING_ESCAPE;
3929 				break;
3930 			}
3931 
3932 			if (cc == '"') {
3933 				if (collect_object) {
3934 					/*
3935 					 * We don't reset the dest here, as
3936 					 * the string is part of a larger
3937 					 * object being collected.
3938 					 */
3939 					*dd++ = cc;
3940 					collect_object = B_FALSE;
3941 					state = DTRACE_JSON_COLLECT_OBJECT;
3942 					break;
3943 				}
3944 				*dd = '\0';
3945 				dd = dest; /* reset string buffer */
3946 				if (string_is_key) {
3947 					if (dtrace_strncmp(dest, elem,
3948 					    size) == 0)
3949 						found_key = B_TRUE;
3950 				} else if (found_key) {
3951 					if (nelems > 1) {
3952 						/*
3953 						 * We expected an object, not
3954 						 * this string.
3955 						 */
3956 						return (NULL);
3957 					}
3958 					return (dest);
3959 				}
3960 				state = string_is_key ? DTRACE_JSON_COLON :
3961 				    DTRACE_JSON_COMMA;
3962 				string_is_key = B_FALSE;
3963 				break;
3964 			}
3965 
3966 			*dd++ = cc;
3967 			break;
3968 		case DTRACE_JSON_STRING_ESCAPE:
3969 			*dd++ = cc;
3970 			if (cc == 'u') {
3971 				escape_unicount = 0;
3972 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3973 			} else {
3974 				state = DTRACE_JSON_STRING;
3975 			}
3976 			break;
3977 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3978 			if (!isxdigit(cc)) {
3979 				/*
3980 				 * ERROR: invalid unicode escape, expected
3981 				 * four valid hexidecimal digits.
3982 				 */
3983 				return (NULL);
3984 			}
3985 
3986 			*dd++ = cc;
3987 			if (++escape_unicount == 4)
3988 				state = DTRACE_JSON_STRING;
3989 			break;
3990 		case DTRACE_JSON_COLON:
3991 			if (isspace(cc))
3992 				break;
3993 
3994 			if (cc == ':') {
3995 				state = DTRACE_JSON_VALUE;
3996 				break;
3997 			}
3998 
3999 			/*
4000 			 * ERROR: expected a colon.
4001 			 */
4002 			return (NULL);
4003 		case DTRACE_JSON_COMMA:
4004 			if (isspace(cc))
4005 				break;
4006 
4007 			if (cc == ',') {
4008 				if (in_array) {
4009 					state = DTRACE_JSON_VALUE;
4010 					if (++array_pos == array_elem)
4011 						found_key = B_TRUE;
4012 				} else {
4013 					state = DTRACE_JSON_OBJECT;
4014 				}
4015 				break;
4016 			}
4017 
4018 			/*
4019 			 * ERROR: either we hit an unexpected character, or
4020 			 * we reached the end of the object or array without
4021 			 * finding the requested key.
4022 			 */
4023 			return (NULL);
4024 		case DTRACE_JSON_IDENTIFIER:
4025 			if (islower(cc)) {
4026 				*dd++ = cc;
4027 				break;
4028 			}
4029 
4030 			*dd = '\0';
4031 			dd = dest; /* reset string buffer */
4032 
4033 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
4034 			    dtrace_strncmp(dest, "false", 6) == 0 ||
4035 			    dtrace_strncmp(dest, "null", 5) == 0) {
4036 				if (found_key) {
4037 					if (nelems > 1) {
4038 						/*
4039 						 * ERROR: We expected an object,
4040 						 * not this identifier.
4041 						 */
4042 						return (NULL);
4043 					}
4044 					return (dest);
4045 				} else {
4046 					cur--;
4047 					state = DTRACE_JSON_COMMA;
4048 					break;
4049 				}
4050 			}
4051 
4052 			/*
4053 			 * ERROR: we did not recognise the identifier as one
4054 			 * of those in the JSON specification.
4055 			 */
4056 			return (NULL);
4057 		case DTRACE_JSON_NUMBER:
4058 			if (cc == '.') {
4059 				*dd++ = cc;
4060 				state = DTRACE_JSON_NUMBER_FRAC;
4061 				break;
4062 			}
4063 
4064 			if (cc == 'x' || cc == 'X') {
4065 				/*
4066 				 * ERROR: specification explicitly excludes
4067 				 * hexidecimal or octal numbers.
4068 				 */
4069 				return (NULL);
4070 			}
4071 
4072 			/* FALLTHRU */
4073 		case DTRACE_JSON_NUMBER_FRAC:
4074 			if (cc == 'e' || cc == 'E') {
4075 				*dd++ = cc;
4076 				state = DTRACE_JSON_NUMBER_EXP;
4077 				break;
4078 			}
4079 
4080 			if (cc == '+' || cc == '-') {
4081 				/*
4082 				 * ERROR: expect sign as part of exponent only.
4083 				 */
4084 				return (NULL);
4085 			}
4086 			/* FALLTHRU */
4087 		case DTRACE_JSON_NUMBER_EXP:
4088 			if (isdigit(cc) || cc == '+' || cc == '-') {
4089 				*dd++ = cc;
4090 				break;
4091 			}
4092 
4093 			*dd = '\0';
4094 			dd = dest; /* reset string buffer */
4095 			if (found_key) {
4096 				if (nelems > 1) {
4097 					/*
4098 					 * ERROR: We expected an object, not
4099 					 * this number.
4100 					 */
4101 					return (NULL);
4102 				}
4103 				return (dest);
4104 			}
4105 
4106 			cur--;
4107 			state = DTRACE_JSON_COMMA;
4108 			break;
4109 		case DTRACE_JSON_VALUE:
4110 			if (isspace(cc))
4111 				break;
4112 
4113 			if (cc == '{' || cc == '[') {
4114 				if (nelems > 1 && found_key) {
4115 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4116 					/*
4117 					 * If our element selector directs us
4118 					 * to descend into this nested object,
4119 					 * then move to the next selector
4120 					 * element in the list and restart the
4121 					 * state machine.
4122 					 */
4123 					while (*elem != '\0')
4124 						elem++;
4125 					elem++; /* skip the inter-element NUL */
4126 					nelems--;
4127 					dd = dest;
4128 					if (in_array) {
4129 						state = DTRACE_JSON_VALUE;
4130 						array_pos = 0;
4131 						array_elem = dtrace_strtoll(
4132 						    elem, 10, size);
4133 						found_key = array_elem == 0 ?
4134 						    B_TRUE : B_FALSE;
4135 					} else {
4136 						found_key = B_FALSE;
4137 						state = DTRACE_JSON_OBJECT;
4138 					}
4139 					break;
4140 				}
4141 
4142 				/*
4143 				 * Otherwise, we wish to either skip this
4144 				 * nested object or return it in full.
4145 				 */
4146 				if (cc == '[')
4147 					brackets = 1;
4148 				else
4149 					braces = 1;
4150 				*dd++ = cc;
4151 				state = DTRACE_JSON_COLLECT_OBJECT;
4152 				break;
4153 			}
4154 
4155 			if (cc == '"') {
4156 				state = DTRACE_JSON_STRING;
4157 				break;
4158 			}
4159 
4160 			if (islower(cc)) {
4161 				/*
4162 				 * Here we deal with true, false and null.
4163 				 */
4164 				*dd++ = cc;
4165 				state = DTRACE_JSON_IDENTIFIER;
4166 				break;
4167 			}
4168 
4169 			if (cc == '-' || isdigit(cc)) {
4170 				*dd++ = cc;
4171 				state = DTRACE_JSON_NUMBER;
4172 				break;
4173 			}
4174 
4175 			/*
4176 			 * ERROR: unexpected character at start of value.
4177 			 */
4178 			return (NULL);
4179 		case DTRACE_JSON_COLLECT_OBJECT:
4180 			if (cc == '\0')
4181 				/*
4182 				 * ERROR: unexpected end of input.
4183 				 */
4184 				return (NULL);
4185 
4186 			*dd++ = cc;
4187 			if (cc == '"') {
4188 				collect_object = B_TRUE;
4189 				state = DTRACE_JSON_STRING;
4190 				break;
4191 			}
4192 
4193 			if (cc == ']') {
4194 				if (brackets-- == 0) {
4195 					/*
4196 					 * ERROR: unbalanced brackets.
4197 					 */
4198 					return (NULL);
4199 				}
4200 			} else if (cc == '}') {
4201 				if (braces-- == 0) {
4202 					/*
4203 					 * ERROR: unbalanced braces.
4204 					 */
4205 					return (NULL);
4206 				}
4207 			} else if (cc == '{') {
4208 				braces++;
4209 			} else if (cc == '[') {
4210 				brackets++;
4211 			}
4212 
4213 			if (brackets == 0 && braces == 0) {
4214 				if (found_key) {
4215 					*dd = '\0';
4216 					return (dest);
4217 				}
4218 				dd = dest; /* reset string buffer */
4219 				state = DTRACE_JSON_COMMA;
4220 			}
4221 			break;
4222 		}
4223 	}
4224 	return (NULL);
4225 }
4226 
4227 /*
4228  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4229  * Notice that we don't bother validating the proper number of arguments or
4230  * their types in the tuple stack.  This isn't needed because all argument
4231  * interpretation is safe because of our load safety -- the worst that can
4232  * happen is that a bogus program can obtain bogus results.
4233  */
4234 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)4235 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4236     dtrace_key_t *tupregs, int nargs,
4237     dtrace_mstate_t *mstate, dtrace_state_t *state)
4238 {
4239 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4240 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4241 	dtrace_vstate_t *vstate = &state->dts_vstate;
4242 
4243 #ifdef illumos
4244 	union {
4245 		mutex_impl_t mi;
4246 		uint64_t mx;
4247 	} m;
4248 
4249 	union {
4250 		krwlock_t ri;
4251 		uintptr_t rw;
4252 	} r;
4253 #else
4254 	struct thread *lowner;
4255 	union {
4256 		struct lock_object *li;
4257 		uintptr_t lx;
4258 	} l;
4259 #endif
4260 
4261 	switch (subr) {
4262 	case DIF_SUBR_RAND:
4263 		regs[rd] = dtrace_xoroshiro128_plus_next(
4264 		    state->dts_rstate[curcpu]);
4265 		break;
4266 
4267 #ifdef illumos
4268 	case DIF_SUBR_MUTEX_OWNED:
4269 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4270 		    mstate, vstate)) {
4271 			regs[rd] = 0;
4272 			break;
4273 		}
4274 
4275 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4276 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4277 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4278 		else
4279 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4280 		break;
4281 
4282 	case DIF_SUBR_MUTEX_OWNER:
4283 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4284 		    mstate, vstate)) {
4285 			regs[rd] = 0;
4286 			break;
4287 		}
4288 
4289 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4290 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4291 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4292 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4293 		else
4294 			regs[rd] = 0;
4295 		break;
4296 
4297 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4298 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4299 		    mstate, vstate)) {
4300 			regs[rd] = 0;
4301 			break;
4302 		}
4303 
4304 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4305 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4306 		break;
4307 
4308 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4309 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4310 		    mstate, vstate)) {
4311 			regs[rd] = 0;
4312 			break;
4313 		}
4314 
4315 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4316 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4317 		break;
4318 
4319 	case DIF_SUBR_RW_READ_HELD: {
4320 		uintptr_t tmp;
4321 
4322 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4323 		    mstate, vstate)) {
4324 			regs[rd] = 0;
4325 			break;
4326 		}
4327 
4328 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4329 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4330 		break;
4331 	}
4332 
4333 	case DIF_SUBR_RW_WRITE_HELD:
4334 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4335 		    mstate, vstate)) {
4336 			regs[rd] = 0;
4337 			break;
4338 		}
4339 
4340 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4341 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4342 		break;
4343 
4344 	case DIF_SUBR_RW_ISWRITER:
4345 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4346 		    mstate, vstate)) {
4347 			regs[rd] = 0;
4348 			break;
4349 		}
4350 
4351 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4352 		regs[rd] = _RW_ISWRITER(&r.ri);
4353 		break;
4354 
4355 #else /* !illumos */
4356 	case DIF_SUBR_MUTEX_OWNED:
4357 		if (!dtrace_canload(tupregs[0].dttk_value,
4358 			sizeof (struct lock_object), mstate, vstate)) {
4359 			regs[rd] = 0;
4360 			break;
4361 		}
4362 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4363 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4364 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4365 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4366 		break;
4367 
4368 	case DIF_SUBR_MUTEX_OWNER:
4369 		if (!dtrace_canload(tupregs[0].dttk_value,
4370 			sizeof (struct lock_object), mstate, vstate)) {
4371 			regs[rd] = 0;
4372 			break;
4373 		}
4374 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4375 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4376 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4377 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4378 		regs[rd] = (uintptr_t)lowner;
4379 		break;
4380 
4381 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4382 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4383 		    mstate, vstate)) {
4384 			regs[rd] = 0;
4385 			break;
4386 		}
4387 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4388 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4389 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4390 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4391 		break;
4392 
4393 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4394 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4395 		    mstate, vstate)) {
4396 			regs[rd] = 0;
4397 			break;
4398 		}
4399 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4400 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4401 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4402 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4403 		break;
4404 
4405 	case DIF_SUBR_RW_READ_HELD:
4406 	case DIF_SUBR_SX_SHARED_HELD:
4407 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4408 		    mstate, vstate)) {
4409 			regs[rd] = 0;
4410 			break;
4411 		}
4412 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4413 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4414 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4415 		    lowner == NULL;
4416 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4417 		break;
4418 
4419 	case DIF_SUBR_RW_WRITE_HELD:
4420 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
4421 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4422 		    mstate, vstate)) {
4423 			regs[rd] = 0;
4424 			break;
4425 		}
4426 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4427 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4428 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4429 		    lowner != NULL;
4430 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4431 		break;
4432 
4433 	case DIF_SUBR_RW_ISWRITER:
4434 	case DIF_SUBR_SX_ISEXCLUSIVE:
4435 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4436 		    mstate, vstate)) {
4437 			regs[rd] = 0;
4438 			break;
4439 		}
4440 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4441 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4442 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4443 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4444 		regs[rd] = (lowner == curthread);
4445 		break;
4446 #endif /* illumos */
4447 
4448 	case DIF_SUBR_BCOPY: {
4449 		/*
4450 		 * We need to be sure that the destination is in the scratch
4451 		 * region -- no other region is allowed.
4452 		 */
4453 		uintptr_t src = tupregs[0].dttk_value;
4454 		uintptr_t dest = tupregs[1].dttk_value;
4455 		size_t size = tupregs[2].dttk_value;
4456 
4457 		if (!dtrace_inscratch(dest, size, mstate)) {
4458 			*flags |= CPU_DTRACE_BADADDR;
4459 			*illval = regs[rd];
4460 			break;
4461 		}
4462 
4463 		if (!dtrace_canload(src, size, mstate, vstate)) {
4464 			regs[rd] = 0;
4465 			break;
4466 		}
4467 
4468 		dtrace_bcopy((void *)src, (void *)dest, size);
4469 		break;
4470 	}
4471 
4472 	case DIF_SUBR_ALLOCA:
4473 	case DIF_SUBR_COPYIN: {
4474 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4475 		uint64_t size =
4476 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4477 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4478 
4479 		/*
4480 		 * This action doesn't require any credential checks since
4481 		 * probes will not activate in user contexts to which the
4482 		 * enabling user does not have permissions.
4483 		 */
4484 
4485 		/*
4486 		 * Rounding up the user allocation size could have overflowed
4487 		 * a large, bogus allocation (like -1ULL) to 0.
4488 		 */
4489 		if (scratch_size < size ||
4490 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4491 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4492 			regs[rd] = 0;
4493 			break;
4494 		}
4495 
4496 		if (subr == DIF_SUBR_COPYIN) {
4497 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4498 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4499 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4500 		}
4501 
4502 		mstate->dtms_scratch_ptr += scratch_size;
4503 		regs[rd] = dest;
4504 		break;
4505 	}
4506 
4507 	case DIF_SUBR_COPYINTO: {
4508 		uint64_t size = tupregs[1].dttk_value;
4509 		uintptr_t dest = tupregs[2].dttk_value;
4510 
4511 		/*
4512 		 * This action doesn't require any credential checks since
4513 		 * probes will not activate in user contexts to which the
4514 		 * enabling user does not have permissions.
4515 		 */
4516 		if (!dtrace_inscratch(dest, size, mstate)) {
4517 			*flags |= CPU_DTRACE_BADADDR;
4518 			*illval = regs[rd];
4519 			break;
4520 		}
4521 
4522 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4523 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4524 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4525 		break;
4526 	}
4527 
4528 	case DIF_SUBR_COPYINSTR: {
4529 		uintptr_t dest = mstate->dtms_scratch_ptr;
4530 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4531 
4532 		if (nargs > 1 && tupregs[1].dttk_value < size)
4533 			size = tupregs[1].dttk_value + 1;
4534 
4535 		/*
4536 		 * This action doesn't require any credential checks since
4537 		 * probes will not activate in user contexts to which the
4538 		 * enabling user does not have permissions.
4539 		 */
4540 		if (!DTRACE_INSCRATCH(mstate, size)) {
4541 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4542 			regs[rd] = 0;
4543 			break;
4544 		}
4545 
4546 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4547 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4548 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4549 
4550 		((char *)dest)[size - 1] = '\0';
4551 		mstate->dtms_scratch_ptr += size;
4552 		regs[rd] = dest;
4553 		break;
4554 	}
4555 
4556 #ifdef illumos
4557 	case DIF_SUBR_MSGSIZE:
4558 	case DIF_SUBR_MSGDSIZE: {
4559 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4560 		uintptr_t wptr, rptr;
4561 		size_t count = 0;
4562 		int cont = 0;
4563 
4564 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4565 
4566 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4567 			    vstate)) {
4568 				regs[rd] = 0;
4569 				break;
4570 			}
4571 
4572 			wptr = dtrace_loadptr(baddr +
4573 			    offsetof(mblk_t, b_wptr));
4574 
4575 			rptr = dtrace_loadptr(baddr +
4576 			    offsetof(mblk_t, b_rptr));
4577 
4578 			if (wptr < rptr) {
4579 				*flags |= CPU_DTRACE_BADADDR;
4580 				*illval = tupregs[0].dttk_value;
4581 				break;
4582 			}
4583 
4584 			daddr = dtrace_loadptr(baddr +
4585 			    offsetof(mblk_t, b_datap));
4586 
4587 			baddr = dtrace_loadptr(baddr +
4588 			    offsetof(mblk_t, b_cont));
4589 
4590 			/*
4591 			 * We want to prevent against denial-of-service here,
4592 			 * so we're only going to search the list for
4593 			 * dtrace_msgdsize_max mblks.
4594 			 */
4595 			if (cont++ > dtrace_msgdsize_max) {
4596 				*flags |= CPU_DTRACE_ILLOP;
4597 				break;
4598 			}
4599 
4600 			if (subr == DIF_SUBR_MSGDSIZE) {
4601 				if (dtrace_load8(daddr +
4602 				    offsetof(dblk_t, db_type)) != M_DATA)
4603 					continue;
4604 			}
4605 
4606 			count += wptr - rptr;
4607 		}
4608 
4609 		if (!(*flags & CPU_DTRACE_FAULT))
4610 			regs[rd] = count;
4611 
4612 		break;
4613 	}
4614 #endif
4615 
4616 	case DIF_SUBR_PROGENYOF: {
4617 		pid_t pid = tupregs[0].dttk_value;
4618 		proc_t *p;
4619 		int rval = 0;
4620 
4621 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4622 
4623 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4624 #ifdef illumos
4625 			if (p->p_pidp->pid_id == pid) {
4626 #else
4627 			if (p->p_pid == pid) {
4628 #endif
4629 				rval = 1;
4630 				break;
4631 			}
4632 		}
4633 
4634 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4635 
4636 		regs[rd] = rval;
4637 		break;
4638 	}
4639 
4640 	case DIF_SUBR_SPECULATION:
4641 		regs[rd] = dtrace_speculation(state);
4642 		break;
4643 
4644 	case DIF_SUBR_COPYOUT: {
4645 		uintptr_t kaddr = tupregs[0].dttk_value;
4646 		uintptr_t uaddr = tupregs[1].dttk_value;
4647 		uint64_t size = tupregs[2].dttk_value;
4648 
4649 		if (!dtrace_destructive_disallow &&
4650 		    dtrace_priv_proc_control(state) &&
4651 		    !dtrace_istoxic(kaddr, size) &&
4652 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4653 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4654 			dtrace_copyout(kaddr, uaddr, size, flags);
4655 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4656 		}
4657 		break;
4658 	}
4659 
4660 	case DIF_SUBR_COPYOUTSTR: {
4661 		uintptr_t kaddr = tupregs[0].dttk_value;
4662 		uintptr_t uaddr = tupregs[1].dttk_value;
4663 		uint64_t size = tupregs[2].dttk_value;
4664 		size_t lim;
4665 
4666 		if (!dtrace_destructive_disallow &&
4667 		    dtrace_priv_proc_control(state) &&
4668 		    !dtrace_istoxic(kaddr, size) &&
4669 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4670 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4671 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4672 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4673 		}
4674 		break;
4675 	}
4676 
4677 	case DIF_SUBR_STRLEN: {
4678 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4679 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4680 		size_t lim;
4681 
4682 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4683 			regs[rd] = 0;
4684 			break;
4685 		}
4686 
4687 		regs[rd] = dtrace_strlen((char *)addr, lim);
4688 		break;
4689 	}
4690 
4691 	case DIF_SUBR_STRCHR:
4692 	case DIF_SUBR_STRRCHR: {
4693 		/*
4694 		 * We're going to iterate over the string looking for the
4695 		 * specified character.  We will iterate until we have reached
4696 		 * the string length or we have found the character.  If this
4697 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4698 		 * of the specified character instead of the first.
4699 		 */
4700 		uintptr_t addr = tupregs[0].dttk_value;
4701 		uintptr_t addr_limit;
4702 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4703 		size_t lim;
4704 		char c, target = (char)tupregs[1].dttk_value;
4705 
4706 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4707 			regs[rd] = 0;
4708 			break;
4709 		}
4710 		addr_limit = addr + lim;
4711 
4712 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4713 			if ((c = dtrace_load8(addr)) == target) {
4714 				regs[rd] = addr;
4715 
4716 				if (subr == DIF_SUBR_STRCHR)
4717 					break;
4718 			}
4719 
4720 			if (c == '\0')
4721 				break;
4722 		}
4723 		break;
4724 	}
4725 
4726 	case DIF_SUBR_STRSTR:
4727 	case DIF_SUBR_INDEX:
4728 	case DIF_SUBR_RINDEX: {
4729 		/*
4730 		 * We're going to iterate over the string looking for the
4731 		 * specified string.  We will iterate until we have reached
4732 		 * the string length or we have found the string.  (Yes, this
4733 		 * is done in the most naive way possible -- but considering
4734 		 * that the string we're searching for is likely to be
4735 		 * relatively short, the complexity of Rabin-Karp or similar
4736 		 * hardly seems merited.)
4737 		 */
4738 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4739 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4740 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4741 		size_t len = dtrace_strlen(addr, size);
4742 		size_t sublen = dtrace_strlen(substr, size);
4743 		char *limit = addr + len, *orig = addr;
4744 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4745 		int inc = 1;
4746 
4747 		regs[rd] = notfound;
4748 
4749 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4750 			regs[rd] = 0;
4751 			break;
4752 		}
4753 
4754 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4755 		    vstate)) {
4756 			regs[rd] = 0;
4757 			break;
4758 		}
4759 
4760 		/*
4761 		 * strstr() and index()/rindex() have similar semantics if
4762 		 * both strings are the empty string: strstr() returns a
4763 		 * pointer to the (empty) string, and index() and rindex()
4764 		 * both return index 0 (regardless of any position argument).
4765 		 */
4766 		if (sublen == 0 && len == 0) {
4767 			if (subr == DIF_SUBR_STRSTR)
4768 				regs[rd] = (uintptr_t)addr;
4769 			else
4770 				regs[rd] = 0;
4771 			break;
4772 		}
4773 
4774 		if (subr != DIF_SUBR_STRSTR) {
4775 			if (subr == DIF_SUBR_RINDEX) {
4776 				limit = orig - 1;
4777 				addr += len;
4778 				inc = -1;
4779 			}
4780 
4781 			/*
4782 			 * Both index() and rindex() take an optional position
4783 			 * argument that denotes the starting position.
4784 			 */
4785 			if (nargs == 3) {
4786 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4787 
4788 				/*
4789 				 * If the position argument to index() is
4790 				 * negative, Perl implicitly clamps it at
4791 				 * zero.  This semantic is a little surprising
4792 				 * given the special meaning of negative
4793 				 * positions to similar Perl functions like
4794 				 * substr(), but it appears to reflect a
4795 				 * notion that index() can start from a
4796 				 * negative index and increment its way up to
4797 				 * the string.  Given this notion, Perl's
4798 				 * rindex() is at least self-consistent in
4799 				 * that it implicitly clamps positions greater
4800 				 * than the string length to be the string
4801 				 * length.  Where Perl completely loses
4802 				 * coherence, however, is when the specified
4803 				 * substring is the empty string ("").  In
4804 				 * this case, even if the position is
4805 				 * negative, rindex() returns 0 -- and even if
4806 				 * the position is greater than the length,
4807 				 * index() returns the string length.  These
4808 				 * semantics violate the notion that index()
4809 				 * should never return a value less than the
4810 				 * specified position and that rindex() should
4811 				 * never return a value greater than the
4812 				 * specified position.  (One assumes that
4813 				 * these semantics are artifacts of Perl's
4814 				 * implementation and not the results of
4815 				 * deliberate design -- it beggars belief that
4816 				 * even Larry Wall could desire such oddness.)
4817 				 * While in the abstract one would wish for
4818 				 * consistent position semantics across
4819 				 * substr(), index() and rindex() -- or at the
4820 				 * very least self-consistent position
4821 				 * semantics for index() and rindex() -- we
4822 				 * instead opt to keep with the extant Perl
4823 				 * semantics, in all their broken glory.  (Do
4824 				 * we have more desire to maintain Perl's
4825 				 * semantics than Perl does?  Probably.)
4826 				 */
4827 				if (subr == DIF_SUBR_RINDEX) {
4828 					if (pos < 0) {
4829 						if (sublen == 0)
4830 							regs[rd] = 0;
4831 						break;
4832 					}
4833 
4834 					if (pos > len)
4835 						pos = len;
4836 				} else {
4837 					if (pos < 0)
4838 						pos = 0;
4839 
4840 					if (pos >= len) {
4841 						if (sublen == 0)
4842 							regs[rd] = len;
4843 						break;
4844 					}
4845 				}
4846 
4847 				addr = orig + pos;
4848 			}
4849 		}
4850 
4851 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4852 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4853 				if (subr != DIF_SUBR_STRSTR) {
4854 					/*
4855 					 * As D index() and rindex() are
4856 					 * modeled on Perl (and not on awk),
4857 					 * we return a zero-based (and not a
4858 					 * one-based) index.  (For you Perl
4859 					 * weenies: no, we're not going to add
4860 					 * $[ -- and shouldn't you be at a con
4861 					 * or something?)
4862 					 */
4863 					regs[rd] = (uintptr_t)(addr - orig);
4864 					break;
4865 				}
4866 
4867 				ASSERT(subr == DIF_SUBR_STRSTR);
4868 				regs[rd] = (uintptr_t)addr;
4869 				break;
4870 			}
4871 		}
4872 
4873 		break;
4874 	}
4875 
4876 	case DIF_SUBR_STRTOK: {
4877 		uintptr_t addr = tupregs[0].dttk_value;
4878 		uintptr_t tokaddr = tupregs[1].dttk_value;
4879 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4880 		uintptr_t limit, toklimit;
4881 		size_t clim;
4882 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4883 		char *dest = (char *)mstate->dtms_scratch_ptr;
4884 		int i;
4885 
4886 		/*
4887 		 * Check both the token buffer and (later) the input buffer,
4888 		 * since both could be non-scratch addresses.
4889 		 */
4890 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4891 			regs[rd] = 0;
4892 			break;
4893 		}
4894 		toklimit = tokaddr + clim;
4895 
4896 		if (!DTRACE_INSCRATCH(mstate, size)) {
4897 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4898 			regs[rd] = 0;
4899 			break;
4900 		}
4901 
4902 		if (addr == 0) {
4903 			/*
4904 			 * If the address specified is NULL, we use our saved
4905 			 * strtok pointer from the mstate.  Note that this
4906 			 * means that the saved strtok pointer is _only_
4907 			 * valid within multiple enablings of the same probe --
4908 			 * it behaves like an implicit clause-local variable.
4909 			 */
4910 			addr = mstate->dtms_strtok;
4911 			limit = mstate->dtms_strtok_limit;
4912 		} else {
4913 			/*
4914 			 * If the user-specified address is non-NULL we must
4915 			 * access check it.  This is the only time we have
4916 			 * a chance to do so, since this address may reside
4917 			 * in the string table of this clause-- future calls
4918 			 * (when we fetch addr from mstate->dtms_strtok)
4919 			 * would fail this access check.
4920 			 */
4921 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4922 			    vstate)) {
4923 				regs[rd] = 0;
4924 				break;
4925 			}
4926 			limit = addr + clim;
4927 		}
4928 
4929 		/*
4930 		 * First, zero the token map, and then process the token
4931 		 * string -- setting a bit in the map for every character
4932 		 * found in the token string.
4933 		 */
4934 		for (i = 0; i < sizeof (tokmap); i++)
4935 			tokmap[i] = 0;
4936 
4937 		for (; tokaddr < toklimit; tokaddr++) {
4938 			if ((c = dtrace_load8(tokaddr)) == '\0')
4939 				break;
4940 
4941 			ASSERT((c >> 3) < sizeof (tokmap));
4942 			tokmap[c >> 3] |= (1 << (c & 0x7));
4943 		}
4944 
4945 		for (; addr < limit; addr++) {
4946 			/*
4947 			 * We're looking for a character that is _not_
4948 			 * contained in the token string.
4949 			 */
4950 			if ((c = dtrace_load8(addr)) == '\0')
4951 				break;
4952 
4953 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4954 				break;
4955 		}
4956 
4957 		if (c == '\0') {
4958 			/*
4959 			 * We reached the end of the string without finding
4960 			 * any character that was not in the token string.
4961 			 * We return NULL in this case, and we set the saved
4962 			 * address to NULL as well.
4963 			 */
4964 			regs[rd] = 0;
4965 			mstate->dtms_strtok = 0;
4966 			mstate->dtms_strtok_limit = 0;
4967 			break;
4968 		}
4969 
4970 		/*
4971 		 * From here on, we're copying into the destination string.
4972 		 */
4973 		for (i = 0; addr < limit && i < size - 1; addr++) {
4974 			if ((c = dtrace_load8(addr)) == '\0')
4975 				break;
4976 
4977 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4978 				break;
4979 
4980 			ASSERT(i < size);
4981 			dest[i++] = c;
4982 		}
4983 
4984 		ASSERT(i < size);
4985 		dest[i] = '\0';
4986 		regs[rd] = (uintptr_t)dest;
4987 		mstate->dtms_scratch_ptr += size;
4988 		mstate->dtms_strtok = addr;
4989 		mstate->dtms_strtok_limit = limit;
4990 		break;
4991 	}
4992 
4993 	case DIF_SUBR_SUBSTR: {
4994 		uintptr_t s = tupregs[0].dttk_value;
4995 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4996 		char *d = (char *)mstate->dtms_scratch_ptr;
4997 		int64_t index = (int64_t)tupregs[1].dttk_value;
4998 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4999 		size_t len = dtrace_strlen((char *)s, size);
5000 		int64_t i;
5001 
5002 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5003 			regs[rd] = 0;
5004 			break;
5005 		}
5006 
5007 		if (!DTRACE_INSCRATCH(mstate, size)) {
5008 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5009 			regs[rd] = 0;
5010 			break;
5011 		}
5012 
5013 		if (nargs <= 2)
5014 			remaining = (int64_t)size;
5015 
5016 		if (index < 0) {
5017 			index += len;
5018 
5019 			if (index < 0 && index + remaining > 0) {
5020 				remaining += index;
5021 				index = 0;
5022 			}
5023 		}
5024 
5025 		if (index >= len || index < 0) {
5026 			remaining = 0;
5027 		} else if (remaining < 0) {
5028 			remaining += len - index;
5029 		} else if (index + remaining > size) {
5030 			remaining = size - index;
5031 		}
5032 
5033 		for (i = 0; i < remaining; i++) {
5034 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5035 				break;
5036 		}
5037 
5038 		d[i] = '\0';
5039 
5040 		mstate->dtms_scratch_ptr += size;
5041 		regs[rd] = (uintptr_t)d;
5042 		break;
5043 	}
5044 
5045 	case DIF_SUBR_JSON: {
5046 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5047 		uintptr_t json = tupregs[0].dttk_value;
5048 		size_t jsonlen = dtrace_strlen((char *)json, size);
5049 		uintptr_t elem = tupregs[1].dttk_value;
5050 		size_t elemlen = dtrace_strlen((char *)elem, size);
5051 
5052 		char *dest = (char *)mstate->dtms_scratch_ptr;
5053 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5054 		char *ee = elemlist;
5055 		int nelems = 1;
5056 		uintptr_t cur;
5057 
5058 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5059 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5060 			regs[rd] = 0;
5061 			break;
5062 		}
5063 
5064 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5065 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5066 			regs[rd] = 0;
5067 			break;
5068 		}
5069 
5070 		/*
5071 		 * Read the element selector and split it up into a packed list
5072 		 * of strings.
5073 		 */
5074 		for (cur = elem; cur < elem + elemlen; cur++) {
5075 			char cc = dtrace_load8(cur);
5076 
5077 			if (cur == elem && cc == '[') {
5078 				/*
5079 				 * If the first element selector key is
5080 				 * actually an array index then ignore the
5081 				 * bracket.
5082 				 */
5083 				continue;
5084 			}
5085 
5086 			if (cc == ']')
5087 				continue;
5088 
5089 			if (cc == '.' || cc == '[') {
5090 				nelems++;
5091 				cc = '\0';
5092 			}
5093 
5094 			*ee++ = cc;
5095 		}
5096 		*ee++ = '\0';
5097 
5098 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5099 		    nelems, dest)) != 0)
5100 			mstate->dtms_scratch_ptr += jsonlen + 1;
5101 		break;
5102 	}
5103 
5104 	case DIF_SUBR_TOUPPER:
5105 	case DIF_SUBR_TOLOWER: {
5106 		uintptr_t s = tupregs[0].dttk_value;
5107 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5108 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5109 		size_t len = dtrace_strlen((char *)s, size);
5110 		char lower, upper, convert;
5111 		int64_t i;
5112 
5113 		if (subr == DIF_SUBR_TOUPPER) {
5114 			lower = 'a';
5115 			upper = 'z';
5116 			convert = 'A';
5117 		} else {
5118 			lower = 'A';
5119 			upper = 'Z';
5120 			convert = 'a';
5121 		}
5122 
5123 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5124 			regs[rd] = 0;
5125 			break;
5126 		}
5127 
5128 		if (!DTRACE_INSCRATCH(mstate, size)) {
5129 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5130 			regs[rd] = 0;
5131 			break;
5132 		}
5133 
5134 		for (i = 0; i < size - 1; i++) {
5135 			if ((c = dtrace_load8(s + i)) == '\0')
5136 				break;
5137 
5138 			if (c >= lower && c <= upper)
5139 				c = convert + (c - lower);
5140 
5141 			dest[i] = c;
5142 		}
5143 
5144 		ASSERT(i < size);
5145 		dest[i] = '\0';
5146 		regs[rd] = (uintptr_t)dest;
5147 		mstate->dtms_scratch_ptr += size;
5148 		break;
5149 	}
5150 
5151 #ifdef illumos
5152 	case DIF_SUBR_GETMAJOR:
5153 #ifdef _LP64
5154 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5155 #else
5156 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5157 #endif
5158 		break;
5159 
5160 	case DIF_SUBR_GETMINOR:
5161 #ifdef _LP64
5162 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5163 #else
5164 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
5165 #endif
5166 		break;
5167 
5168 	case DIF_SUBR_DDI_PATHNAME: {
5169 		/*
5170 		 * This one is a galactic mess.  We are going to roughly
5171 		 * emulate ddi_pathname(), but it's made more complicated
5172 		 * by the fact that we (a) want to include the minor name and
5173 		 * (b) must proceed iteratively instead of recursively.
5174 		 */
5175 		uintptr_t dest = mstate->dtms_scratch_ptr;
5176 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5177 		char *start = (char *)dest, *end = start + size - 1;
5178 		uintptr_t daddr = tupregs[0].dttk_value;
5179 		int64_t minor = (int64_t)tupregs[1].dttk_value;
5180 		char *s;
5181 		int i, len, depth = 0;
5182 
5183 		/*
5184 		 * Due to all the pointer jumping we do and context we must
5185 		 * rely upon, we just mandate that the user must have kernel
5186 		 * read privileges to use this routine.
5187 		 */
5188 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5189 			*flags |= CPU_DTRACE_KPRIV;
5190 			*illval = daddr;
5191 			regs[rd] = 0;
5192 		}
5193 
5194 		if (!DTRACE_INSCRATCH(mstate, size)) {
5195 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5196 			regs[rd] = 0;
5197 			break;
5198 		}
5199 
5200 		*end = '\0';
5201 
5202 		/*
5203 		 * We want to have a name for the minor.  In order to do this,
5204 		 * we need to walk the minor list from the devinfo.  We want
5205 		 * to be sure that we don't infinitely walk a circular list,
5206 		 * so we check for circularity by sending a scout pointer
5207 		 * ahead two elements for every element that we iterate over;
5208 		 * if the list is circular, these will ultimately point to the
5209 		 * same element.  You may recognize this little trick as the
5210 		 * answer to a stupid interview question -- one that always
5211 		 * seems to be asked by those who had to have it laboriously
5212 		 * explained to them, and who can't even concisely describe
5213 		 * the conditions under which one would be forced to resort to
5214 		 * this technique.  Needless to say, those conditions are
5215 		 * found here -- and probably only here.  Is this the only use
5216 		 * of this infamous trick in shipping, production code?  If it
5217 		 * isn't, it probably should be...
5218 		 */
5219 		if (minor != -1) {
5220 			uintptr_t maddr = dtrace_loadptr(daddr +
5221 			    offsetof(struct dev_info, devi_minor));
5222 
5223 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5224 			uintptr_t name = offsetof(struct ddi_minor_data,
5225 			    d_minor) + offsetof(struct ddi_minor, name);
5226 			uintptr_t dev = offsetof(struct ddi_minor_data,
5227 			    d_minor) + offsetof(struct ddi_minor, dev);
5228 			uintptr_t scout;
5229 
5230 			if (maddr != NULL)
5231 				scout = dtrace_loadptr(maddr + next);
5232 
5233 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5234 				uint64_t m;
5235 #ifdef _LP64
5236 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5237 #else
5238 				m = dtrace_load32(maddr + dev) & MAXMIN;
5239 #endif
5240 				if (m != minor) {
5241 					maddr = dtrace_loadptr(maddr + next);
5242 
5243 					if (scout == NULL)
5244 						continue;
5245 
5246 					scout = dtrace_loadptr(scout + next);
5247 
5248 					if (scout == NULL)
5249 						continue;
5250 
5251 					scout = dtrace_loadptr(scout + next);
5252 
5253 					if (scout == NULL)
5254 						continue;
5255 
5256 					if (scout == maddr) {
5257 						*flags |= CPU_DTRACE_ILLOP;
5258 						break;
5259 					}
5260 
5261 					continue;
5262 				}
5263 
5264 				/*
5265 				 * We have the minor data.  Now we need to
5266 				 * copy the minor's name into the end of the
5267 				 * pathname.
5268 				 */
5269 				s = (char *)dtrace_loadptr(maddr + name);
5270 				len = dtrace_strlen(s, size);
5271 
5272 				if (*flags & CPU_DTRACE_FAULT)
5273 					break;
5274 
5275 				if (len != 0) {
5276 					if ((end -= (len + 1)) < start)
5277 						break;
5278 
5279 					*end = ':';
5280 				}
5281 
5282 				for (i = 1; i <= len; i++)
5283 					end[i] = dtrace_load8((uintptr_t)s++);
5284 				break;
5285 			}
5286 		}
5287 
5288 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5289 			ddi_node_state_t devi_state;
5290 
5291 			devi_state = dtrace_load32(daddr +
5292 			    offsetof(struct dev_info, devi_node_state));
5293 
5294 			if (*flags & CPU_DTRACE_FAULT)
5295 				break;
5296 
5297 			if (devi_state >= DS_INITIALIZED) {
5298 				s = (char *)dtrace_loadptr(daddr +
5299 				    offsetof(struct dev_info, devi_addr));
5300 				len = dtrace_strlen(s, size);
5301 
5302 				if (*flags & CPU_DTRACE_FAULT)
5303 					break;
5304 
5305 				if (len != 0) {
5306 					if ((end -= (len + 1)) < start)
5307 						break;
5308 
5309 					*end = '@';
5310 				}
5311 
5312 				for (i = 1; i <= len; i++)
5313 					end[i] = dtrace_load8((uintptr_t)s++);
5314 			}
5315 
5316 			/*
5317 			 * Now for the node name...
5318 			 */
5319 			s = (char *)dtrace_loadptr(daddr +
5320 			    offsetof(struct dev_info, devi_node_name));
5321 
5322 			daddr = dtrace_loadptr(daddr +
5323 			    offsetof(struct dev_info, devi_parent));
5324 
5325 			/*
5326 			 * If our parent is NULL (that is, if we're the root
5327 			 * node), we're going to use the special path
5328 			 * "devices".
5329 			 */
5330 			if (daddr == 0)
5331 				s = "devices";
5332 
5333 			len = dtrace_strlen(s, size);
5334 			if (*flags & CPU_DTRACE_FAULT)
5335 				break;
5336 
5337 			if ((end -= (len + 1)) < start)
5338 				break;
5339 
5340 			for (i = 1; i <= len; i++)
5341 				end[i] = dtrace_load8((uintptr_t)s++);
5342 			*end = '/';
5343 
5344 			if (depth++ > dtrace_devdepth_max) {
5345 				*flags |= CPU_DTRACE_ILLOP;
5346 				break;
5347 			}
5348 		}
5349 
5350 		if (end < start)
5351 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5352 
5353 		if (daddr == 0) {
5354 			regs[rd] = (uintptr_t)end;
5355 			mstate->dtms_scratch_ptr += size;
5356 		}
5357 
5358 		break;
5359 	}
5360 #endif
5361 
5362 	case DIF_SUBR_STRJOIN: {
5363 		char *d = (char *)mstate->dtms_scratch_ptr;
5364 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5365 		uintptr_t s1 = tupregs[0].dttk_value;
5366 		uintptr_t s2 = tupregs[1].dttk_value;
5367 		int i = 0, j = 0;
5368 		size_t lim1, lim2;
5369 		char c;
5370 
5371 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5372 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5373 			regs[rd] = 0;
5374 			break;
5375 		}
5376 
5377 		if (!DTRACE_INSCRATCH(mstate, size)) {
5378 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5379 			regs[rd] = 0;
5380 			break;
5381 		}
5382 
5383 		for (;;) {
5384 			if (i >= size) {
5385 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5386 				regs[rd] = 0;
5387 				break;
5388 			}
5389 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5390 			if ((d[i++] = c) == '\0') {
5391 				i--;
5392 				break;
5393 			}
5394 		}
5395 
5396 		for (;;) {
5397 			if (i >= size) {
5398 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5399 				regs[rd] = 0;
5400 				break;
5401 			}
5402 
5403 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5404 			if ((d[i++] = c) == '\0')
5405 				break;
5406 		}
5407 
5408 		if (i < size) {
5409 			mstate->dtms_scratch_ptr += i;
5410 			regs[rd] = (uintptr_t)d;
5411 		}
5412 
5413 		break;
5414 	}
5415 
5416 	case DIF_SUBR_STRTOLL: {
5417 		uintptr_t s = tupregs[0].dttk_value;
5418 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5419 		size_t lim;
5420 		int base = 10;
5421 
5422 		if (nargs > 1) {
5423 			if ((base = tupregs[1].dttk_value) <= 1 ||
5424 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5425 				*flags |= CPU_DTRACE_ILLOP;
5426 				break;
5427 			}
5428 		}
5429 
5430 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5431 			regs[rd] = INT64_MIN;
5432 			break;
5433 		}
5434 
5435 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5436 		break;
5437 	}
5438 
5439 	case DIF_SUBR_LLTOSTR: {
5440 		int64_t i = (int64_t)tupregs[0].dttk_value;
5441 		uint64_t val, digit;
5442 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5443 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5444 		int base = 10;
5445 
5446 		if (nargs > 1) {
5447 			if ((base = tupregs[1].dttk_value) <= 1 ||
5448 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5449 				*flags |= CPU_DTRACE_ILLOP;
5450 				break;
5451 			}
5452 		}
5453 
5454 		val = (base == 10 && i < 0) ? i * -1 : i;
5455 
5456 		if (!DTRACE_INSCRATCH(mstate, size)) {
5457 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5458 			regs[rd] = 0;
5459 			break;
5460 		}
5461 
5462 		for (*end-- = '\0'; val; val /= base) {
5463 			if ((digit = val % base) <= '9' - '0') {
5464 				*end-- = '0' + digit;
5465 			} else {
5466 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5467 			}
5468 		}
5469 
5470 		if (i == 0 && base == 16)
5471 			*end-- = '0';
5472 
5473 		if (base == 16)
5474 			*end-- = 'x';
5475 
5476 		if (i == 0 || base == 8 || base == 16)
5477 			*end-- = '0';
5478 
5479 		if (i < 0 && base == 10)
5480 			*end-- = '-';
5481 
5482 		regs[rd] = (uintptr_t)end + 1;
5483 		mstate->dtms_scratch_ptr += size;
5484 		break;
5485 	}
5486 
5487 	case DIF_SUBR_HTONS:
5488 	case DIF_SUBR_NTOHS:
5489 #if BYTE_ORDER == BIG_ENDIAN
5490 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5491 #else
5492 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5493 #endif
5494 		break;
5495 
5496 
5497 	case DIF_SUBR_HTONL:
5498 	case DIF_SUBR_NTOHL:
5499 #if BYTE_ORDER == BIG_ENDIAN
5500 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5501 #else
5502 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5503 #endif
5504 		break;
5505 
5506 
5507 	case DIF_SUBR_HTONLL:
5508 	case DIF_SUBR_NTOHLL:
5509 #if BYTE_ORDER == BIG_ENDIAN
5510 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5511 #else
5512 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5513 #endif
5514 		break;
5515 
5516 
5517 	case DIF_SUBR_DIRNAME:
5518 	case DIF_SUBR_BASENAME: {
5519 		char *dest = (char *)mstate->dtms_scratch_ptr;
5520 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5521 		uintptr_t src = tupregs[0].dttk_value;
5522 		int i, j, len = dtrace_strlen((char *)src, size);
5523 		int lastbase = -1, firstbase = -1, lastdir = -1;
5524 		int start, end;
5525 
5526 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5527 			regs[rd] = 0;
5528 			break;
5529 		}
5530 
5531 		if (!DTRACE_INSCRATCH(mstate, size)) {
5532 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5533 			regs[rd] = 0;
5534 			break;
5535 		}
5536 
5537 		/*
5538 		 * The basename and dirname for a zero-length string is
5539 		 * defined to be "."
5540 		 */
5541 		if (len == 0) {
5542 			len = 1;
5543 			src = (uintptr_t)".";
5544 		}
5545 
5546 		/*
5547 		 * Start from the back of the string, moving back toward the
5548 		 * front until we see a character that isn't a slash.  That
5549 		 * character is the last character in the basename.
5550 		 */
5551 		for (i = len - 1; i >= 0; i--) {
5552 			if (dtrace_load8(src + i) != '/')
5553 				break;
5554 		}
5555 
5556 		if (i >= 0)
5557 			lastbase = i;
5558 
5559 		/*
5560 		 * Starting from the last character in the basename, move
5561 		 * towards the front until we find a slash.  The character
5562 		 * that we processed immediately before that is the first
5563 		 * character in the basename.
5564 		 */
5565 		for (; i >= 0; i--) {
5566 			if (dtrace_load8(src + i) == '/')
5567 				break;
5568 		}
5569 
5570 		if (i >= 0)
5571 			firstbase = i + 1;
5572 
5573 		/*
5574 		 * Now keep going until we find a non-slash character.  That
5575 		 * character is the last character in the dirname.
5576 		 */
5577 		for (; i >= 0; i--) {
5578 			if (dtrace_load8(src + i) != '/')
5579 				break;
5580 		}
5581 
5582 		if (i >= 0)
5583 			lastdir = i;
5584 
5585 		ASSERT(!(lastbase == -1 && firstbase != -1));
5586 		ASSERT(!(firstbase == -1 && lastdir != -1));
5587 
5588 		if (lastbase == -1) {
5589 			/*
5590 			 * We didn't find a non-slash character.  We know that
5591 			 * the length is non-zero, so the whole string must be
5592 			 * slashes.  In either the dirname or the basename
5593 			 * case, we return '/'.
5594 			 */
5595 			ASSERT(firstbase == -1);
5596 			firstbase = lastbase = lastdir = 0;
5597 		}
5598 
5599 		if (firstbase == -1) {
5600 			/*
5601 			 * The entire string consists only of a basename
5602 			 * component.  If we're looking for dirname, we need
5603 			 * to change our string to be just "."; if we're
5604 			 * looking for a basename, we'll just set the first
5605 			 * character of the basename to be 0.
5606 			 */
5607 			if (subr == DIF_SUBR_DIRNAME) {
5608 				ASSERT(lastdir == -1);
5609 				src = (uintptr_t)".";
5610 				lastdir = 0;
5611 			} else {
5612 				firstbase = 0;
5613 			}
5614 		}
5615 
5616 		if (subr == DIF_SUBR_DIRNAME) {
5617 			if (lastdir == -1) {
5618 				/*
5619 				 * We know that we have a slash in the name --
5620 				 * or lastdir would be set to 0, above.  And
5621 				 * because lastdir is -1, we know that this
5622 				 * slash must be the first character.  (That
5623 				 * is, the full string must be of the form
5624 				 * "/basename".)  In this case, the last
5625 				 * character of the directory name is 0.
5626 				 */
5627 				lastdir = 0;
5628 			}
5629 
5630 			start = 0;
5631 			end = lastdir;
5632 		} else {
5633 			ASSERT(subr == DIF_SUBR_BASENAME);
5634 			ASSERT(firstbase != -1 && lastbase != -1);
5635 			start = firstbase;
5636 			end = lastbase;
5637 		}
5638 
5639 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5640 			dest[j] = dtrace_load8(src + i);
5641 
5642 		dest[j] = '\0';
5643 		regs[rd] = (uintptr_t)dest;
5644 		mstate->dtms_scratch_ptr += size;
5645 		break;
5646 	}
5647 
5648 	case DIF_SUBR_GETF: {
5649 		uintptr_t fd = tupregs[0].dttk_value;
5650 		struct filedesc *fdp;
5651 		file_t *fp;
5652 
5653 		if (!dtrace_priv_proc(state)) {
5654 			regs[rd] = 0;
5655 			break;
5656 		}
5657 		fdp = curproc->p_fd;
5658 		FILEDESC_SLOCK(fdp);
5659 		/*
5660 		 * XXXMJG this looks broken as no ref is taken.
5661 		 */
5662 		fp = fget_noref(fdp, fd);
5663 		mstate->dtms_getf = fp;
5664 		regs[rd] = (uintptr_t)fp;
5665 		FILEDESC_SUNLOCK(fdp);
5666 		break;
5667 	}
5668 
5669 	case DIF_SUBR_CLEANPATH: {
5670 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5671 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5672 		uintptr_t src = tupregs[0].dttk_value;
5673 		size_t lim;
5674 		int i = 0, j = 0;
5675 #ifdef illumos
5676 		zone_t *z;
5677 #endif
5678 
5679 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5680 			regs[rd] = 0;
5681 			break;
5682 		}
5683 
5684 		if (!DTRACE_INSCRATCH(mstate, size)) {
5685 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5686 			regs[rd] = 0;
5687 			break;
5688 		}
5689 
5690 		/*
5691 		 * Move forward, loading each character.
5692 		 */
5693 		do {
5694 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5695 next:
5696 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5697 				break;
5698 
5699 			if (c != '/') {
5700 				dest[j++] = c;
5701 				continue;
5702 			}
5703 
5704 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5705 
5706 			if (c == '/') {
5707 				/*
5708 				 * We have two slashes -- we can just advance
5709 				 * to the next character.
5710 				 */
5711 				goto next;
5712 			}
5713 
5714 			if (c != '.') {
5715 				/*
5716 				 * This is not "." and it's not ".." -- we can
5717 				 * just store the "/" and this character and
5718 				 * drive on.
5719 				 */
5720 				dest[j++] = '/';
5721 				dest[j++] = c;
5722 				continue;
5723 			}
5724 
5725 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5726 
5727 			if (c == '/') {
5728 				/*
5729 				 * This is a "/./" component.  We're not going
5730 				 * to store anything in the destination buffer;
5731 				 * we're just going to go to the next component.
5732 				 */
5733 				goto next;
5734 			}
5735 
5736 			if (c != '.') {
5737 				/*
5738 				 * This is not ".." -- we can just store the
5739 				 * "/." and this character and continue
5740 				 * processing.
5741 				 */
5742 				dest[j++] = '/';
5743 				dest[j++] = '.';
5744 				dest[j++] = c;
5745 				continue;
5746 			}
5747 
5748 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5749 
5750 			if (c != '/' && c != '\0') {
5751 				/*
5752 				 * This is not ".." -- it's "..[mumble]".
5753 				 * We'll store the "/.." and this character
5754 				 * and continue processing.
5755 				 */
5756 				dest[j++] = '/';
5757 				dest[j++] = '.';
5758 				dest[j++] = '.';
5759 				dest[j++] = c;
5760 				continue;
5761 			}
5762 
5763 			/*
5764 			 * This is "/../" or "/..\0".  We need to back up
5765 			 * our destination pointer until we find a "/".
5766 			 */
5767 			i--;
5768 			while (j != 0 && dest[--j] != '/')
5769 				continue;
5770 
5771 			if (c == '\0')
5772 				dest[++j] = '/';
5773 		} while (c != '\0');
5774 
5775 		dest[j] = '\0';
5776 
5777 #ifdef illumos
5778 		if (mstate->dtms_getf != NULL &&
5779 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5780 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5781 			/*
5782 			 * If we've done a getf() as a part of this ECB and we
5783 			 * don't have kernel access (and we're not in the global
5784 			 * zone), check if the path we cleaned up begins with
5785 			 * the zone's root path, and trim it off if so.  Note
5786 			 * that this is an output cleanliness issue, not a
5787 			 * security issue: knowing one's zone root path does
5788 			 * not enable privilege escalation.
5789 			 */
5790 			if (strstr(dest, z->zone_rootpath) == dest)
5791 				dest += strlen(z->zone_rootpath) - 1;
5792 		}
5793 #endif
5794 
5795 		regs[rd] = (uintptr_t)dest;
5796 		mstate->dtms_scratch_ptr += size;
5797 		break;
5798 	}
5799 
5800 	case DIF_SUBR_INET_NTOA:
5801 	case DIF_SUBR_INET_NTOA6:
5802 	case DIF_SUBR_INET_NTOP: {
5803 		size_t size;
5804 		int af, argi, i;
5805 		char *base, *end;
5806 
5807 		if (subr == DIF_SUBR_INET_NTOP) {
5808 			af = (int)tupregs[0].dttk_value;
5809 			argi = 1;
5810 		} else {
5811 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5812 			argi = 0;
5813 		}
5814 
5815 		if (af == AF_INET) {
5816 			ipaddr_t ip4;
5817 			uint8_t *ptr8, val;
5818 
5819 			if (!dtrace_canload(tupregs[argi].dttk_value,
5820 			    sizeof (ipaddr_t), mstate, vstate)) {
5821 				regs[rd] = 0;
5822 				break;
5823 			}
5824 
5825 			/*
5826 			 * Safely load the IPv4 address.
5827 			 */
5828 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5829 
5830 			/*
5831 			 * Check an IPv4 string will fit in scratch.
5832 			 */
5833 			size = INET_ADDRSTRLEN;
5834 			if (!DTRACE_INSCRATCH(mstate, size)) {
5835 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5836 				regs[rd] = 0;
5837 				break;
5838 			}
5839 			base = (char *)mstate->dtms_scratch_ptr;
5840 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5841 
5842 			/*
5843 			 * Stringify as a dotted decimal quad.
5844 			 */
5845 			*end-- = '\0';
5846 			ptr8 = (uint8_t *)&ip4;
5847 			for (i = 3; i >= 0; i--) {
5848 				val = ptr8[i];
5849 
5850 				if (val == 0) {
5851 					*end-- = '0';
5852 				} else {
5853 					for (; val; val /= 10) {
5854 						*end-- = '0' + (val % 10);
5855 					}
5856 				}
5857 
5858 				if (i > 0)
5859 					*end-- = '.';
5860 			}
5861 			ASSERT(end + 1 >= base);
5862 
5863 		} else if (af == AF_INET6) {
5864 			struct in6_addr ip6;
5865 			int firstzero, tryzero, numzero, v6end;
5866 			uint16_t val;
5867 			const char digits[] = "0123456789abcdef";
5868 
5869 			/*
5870 			 * Stringify using RFC 1884 convention 2 - 16 bit
5871 			 * hexadecimal values with a zero-run compression.
5872 			 * Lower case hexadecimal digits are used.
5873 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5874 			 * The IPv4 embedded form is returned for inet_ntop,
5875 			 * just the IPv4 string is returned for inet_ntoa6.
5876 			 */
5877 
5878 			if (!dtrace_canload(tupregs[argi].dttk_value,
5879 			    sizeof (struct in6_addr), mstate, vstate)) {
5880 				regs[rd] = 0;
5881 				break;
5882 			}
5883 
5884 			/*
5885 			 * Safely load the IPv6 address.
5886 			 */
5887 			dtrace_bcopy(
5888 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5889 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5890 
5891 			/*
5892 			 * Check an IPv6 string will fit in scratch.
5893 			 */
5894 			size = INET6_ADDRSTRLEN;
5895 			if (!DTRACE_INSCRATCH(mstate, size)) {
5896 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5897 				regs[rd] = 0;
5898 				break;
5899 			}
5900 			base = (char *)mstate->dtms_scratch_ptr;
5901 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5902 			*end-- = '\0';
5903 
5904 			/*
5905 			 * Find the longest run of 16 bit zero values
5906 			 * for the single allowed zero compression - "::".
5907 			 */
5908 			firstzero = -1;
5909 			tryzero = -1;
5910 			numzero = 1;
5911 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5912 #ifdef illumos
5913 				if (ip6._S6_un._S6_u8[i] == 0 &&
5914 #else
5915 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5916 #endif
5917 				    tryzero == -1 && i % 2 == 0) {
5918 					tryzero = i;
5919 					continue;
5920 				}
5921 
5922 				if (tryzero != -1 &&
5923 #ifdef illumos
5924 				    (ip6._S6_un._S6_u8[i] != 0 ||
5925 #else
5926 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5927 #endif
5928 				    i == sizeof (struct in6_addr) - 1)) {
5929 
5930 					if (i - tryzero <= numzero) {
5931 						tryzero = -1;
5932 						continue;
5933 					}
5934 
5935 					firstzero = tryzero;
5936 					numzero = i - i % 2 - tryzero;
5937 					tryzero = -1;
5938 
5939 #ifdef illumos
5940 					if (ip6._S6_un._S6_u8[i] == 0 &&
5941 #else
5942 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5943 #endif
5944 					    i == sizeof (struct in6_addr) - 1)
5945 						numzero += 2;
5946 				}
5947 			}
5948 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5949 
5950 			/*
5951 			 * Check for an IPv4 embedded address.
5952 			 */
5953 			v6end = sizeof (struct in6_addr) - 2;
5954 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5955 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5956 				for (i = sizeof (struct in6_addr) - 1;
5957 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5958 					ASSERT(end >= base);
5959 
5960 #ifdef illumos
5961 					val = ip6._S6_un._S6_u8[i];
5962 #else
5963 					val = ip6.__u6_addr.__u6_addr8[i];
5964 #endif
5965 
5966 					if (val == 0) {
5967 						*end-- = '0';
5968 					} else {
5969 						for (; val; val /= 10) {
5970 							*end-- = '0' + val % 10;
5971 						}
5972 					}
5973 
5974 					if (i > DTRACE_V4MAPPED_OFFSET)
5975 						*end-- = '.';
5976 				}
5977 
5978 				if (subr == DIF_SUBR_INET_NTOA6)
5979 					goto inetout;
5980 
5981 				/*
5982 				 * Set v6end to skip the IPv4 address that
5983 				 * we have already stringified.
5984 				 */
5985 				v6end = 10;
5986 			}
5987 
5988 			/*
5989 			 * Build the IPv6 string by working through the
5990 			 * address in reverse.
5991 			 */
5992 			for (i = v6end; i >= 0; i -= 2) {
5993 				ASSERT(end >= base);
5994 
5995 				if (i == firstzero + numzero - 2) {
5996 					*end-- = ':';
5997 					*end-- = ':';
5998 					i -= numzero - 2;
5999 					continue;
6000 				}
6001 
6002 				if (i < 14 && i != firstzero - 2)
6003 					*end-- = ':';
6004 
6005 #ifdef illumos
6006 				val = (ip6._S6_un._S6_u8[i] << 8) +
6007 				    ip6._S6_un._S6_u8[i + 1];
6008 #else
6009 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6010 				    ip6.__u6_addr.__u6_addr8[i + 1];
6011 #endif
6012 
6013 				if (val == 0) {
6014 					*end-- = '0';
6015 				} else {
6016 					for (; val; val /= 16) {
6017 						*end-- = digits[val % 16];
6018 					}
6019 				}
6020 			}
6021 			ASSERT(end + 1 >= base);
6022 
6023 		} else {
6024 			/*
6025 			 * The user didn't use AH_INET or AH_INET6.
6026 			 */
6027 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6028 			regs[rd] = 0;
6029 			break;
6030 		}
6031 
6032 inetout:	regs[rd] = (uintptr_t)end + 1;
6033 		mstate->dtms_scratch_ptr += size;
6034 		break;
6035 	}
6036 
6037 	case DIF_SUBR_MEMREF: {
6038 		uintptr_t size = 2 * sizeof(uintptr_t);
6039 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6040 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6041 
6042 		/* address and length */
6043 		memref[0] = tupregs[0].dttk_value;
6044 		memref[1] = tupregs[1].dttk_value;
6045 
6046 		regs[rd] = (uintptr_t) memref;
6047 		mstate->dtms_scratch_ptr += scratch_size;
6048 		break;
6049 	}
6050 
6051 #ifndef illumos
6052 	case DIF_SUBR_MEMSTR: {
6053 		char *str = (char *)mstate->dtms_scratch_ptr;
6054 		uintptr_t mem = tupregs[0].dttk_value;
6055 		char c = tupregs[1].dttk_value;
6056 		size_t size = tupregs[2].dttk_value;
6057 		uint8_t n;
6058 		int i;
6059 
6060 		regs[rd] = 0;
6061 
6062 		if (size == 0)
6063 			break;
6064 
6065 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6066 			break;
6067 
6068 		if (!DTRACE_INSCRATCH(mstate, size)) {
6069 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6070 			break;
6071 		}
6072 
6073 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6074 			*flags |= CPU_DTRACE_ILLOP;
6075 			break;
6076 		}
6077 
6078 		for (i = 0; i < size - 1; i++) {
6079 			n = dtrace_load8(mem++);
6080 			str[i] = (n == 0) ? c : n;
6081 		}
6082 		str[size - 1] = 0;
6083 
6084 		regs[rd] = (uintptr_t)str;
6085 		mstate->dtms_scratch_ptr += size;
6086 		break;
6087 	}
6088 #endif
6089 	}
6090 }
6091 
6092 /*
6093  * Emulate the execution of DTrace IR instructions specified by the given
6094  * DIF object.  This function is deliberately void of assertions as all of
6095  * the necessary checks are handled by a call to dtrace_difo_validate().
6096  */
6097 static uint64_t
6098 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6099     dtrace_vstate_t *vstate, dtrace_state_t *state)
6100 {
6101 	const dif_instr_t *text = difo->dtdo_buf;
6102 	const uint_t textlen = difo->dtdo_len;
6103 	const char *strtab = difo->dtdo_strtab;
6104 	const uint64_t *inttab = difo->dtdo_inttab;
6105 
6106 	uint64_t rval = 0;
6107 	dtrace_statvar_t *svar;
6108 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6109 	dtrace_difv_t *v;
6110 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6111 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6112 
6113 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6114 	uint64_t regs[DIF_DIR_NREGS];
6115 	uint64_t *tmp;
6116 
6117 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6118 	int64_t cc_r;
6119 	uint_t pc = 0, id, opc = 0;
6120 	uint8_t ttop = 0;
6121 	dif_instr_t instr;
6122 	uint_t r1, r2, rd;
6123 
6124 	/*
6125 	 * We stash the current DIF object into the machine state: we need it
6126 	 * for subsequent access checking.
6127 	 */
6128 	mstate->dtms_difo = difo;
6129 
6130 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6131 
6132 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6133 		opc = pc;
6134 
6135 		instr = text[pc++];
6136 		r1 = DIF_INSTR_R1(instr);
6137 		r2 = DIF_INSTR_R2(instr);
6138 		rd = DIF_INSTR_RD(instr);
6139 
6140 		switch (DIF_INSTR_OP(instr)) {
6141 		case DIF_OP_OR:
6142 			regs[rd] = regs[r1] | regs[r2];
6143 			break;
6144 		case DIF_OP_XOR:
6145 			regs[rd] = regs[r1] ^ regs[r2];
6146 			break;
6147 		case DIF_OP_AND:
6148 			regs[rd] = regs[r1] & regs[r2];
6149 			break;
6150 		case DIF_OP_SLL:
6151 			regs[rd] = regs[r1] << regs[r2];
6152 			break;
6153 		case DIF_OP_SRL:
6154 			regs[rd] = regs[r1] >> regs[r2];
6155 			break;
6156 		case DIF_OP_SUB:
6157 			regs[rd] = regs[r1] - regs[r2];
6158 			break;
6159 		case DIF_OP_ADD:
6160 			regs[rd] = regs[r1] + regs[r2];
6161 			break;
6162 		case DIF_OP_MUL:
6163 			regs[rd] = regs[r1] * regs[r2];
6164 			break;
6165 		case DIF_OP_SDIV:
6166 			if (regs[r2] == 0) {
6167 				regs[rd] = 0;
6168 				*flags |= CPU_DTRACE_DIVZERO;
6169 			} else {
6170 				regs[rd] = (int64_t)regs[r1] /
6171 				    (int64_t)regs[r2];
6172 			}
6173 			break;
6174 
6175 		case DIF_OP_UDIV:
6176 			if (regs[r2] == 0) {
6177 				regs[rd] = 0;
6178 				*flags |= CPU_DTRACE_DIVZERO;
6179 			} else {
6180 				regs[rd] = regs[r1] / regs[r2];
6181 			}
6182 			break;
6183 
6184 		case DIF_OP_SREM:
6185 			if (regs[r2] == 0) {
6186 				regs[rd] = 0;
6187 				*flags |= CPU_DTRACE_DIVZERO;
6188 			} else {
6189 				regs[rd] = (int64_t)regs[r1] %
6190 				    (int64_t)regs[r2];
6191 			}
6192 			break;
6193 
6194 		case DIF_OP_UREM:
6195 			if (regs[r2] == 0) {
6196 				regs[rd] = 0;
6197 				*flags |= CPU_DTRACE_DIVZERO;
6198 			} else {
6199 				regs[rd] = regs[r1] % regs[r2];
6200 			}
6201 			break;
6202 
6203 		case DIF_OP_NOT:
6204 			regs[rd] = ~regs[r1];
6205 			break;
6206 		case DIF_OP_MOV:
6207 			regs[rd] = regs[r1];
6208 			break;
6209 		case DIF_OP_CMP:
6210 			cc_r = regs[r1] - regs[r2];
6211 			cc_n = cc_r < 0;
6212 			cc_z = cc_r == 0;
6213 			cc_v = 0;
6214 			cc_c = regs[r1] < regs[r2];
6215 			break;
6216 		case DIF_OP_TST:
6217 			cc_n = cc_v = cc_c = 0;
6218 			cc_z = regs[r1] == 0;
6219 			break;
6220 		case DIF_OP_BA:
6221 			pc = DIF_INSTR_LABEL(instr);
6222 			break;
6223 		case DIF_OP_BE:
6224 			if (cc_z)
6225 				pc = DIF_INSTR_LABEL(instr);
6226 			break;
6227 		case DIF_OP_BNE:
6228 			if (cc_z == 0)
6229 				pc = DIF_INSTR_LABEL(instr);
6230 			break;
6231 		case DIF_OP_BG:
6232 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6233 				pc = DIF_INSTR_LABEL(instr);
6234 			break;
6235 		case DIF_OP_BGU:
6236 			if ((cc_c | cc_z) == 0)
6237 				pc = DIF_INSTR_LABEL(instr);
6238 			break;
6239 		case DIF_OP_BGE:
6240 			if ((cc_n ^ cc_v) == 0)
6241 				pc = DIF_INSTR_LABEL(instr);
6242 			break;
6243 		case DIF_OP_BGEU:
6244 			if (cc_c == 0)
6245 				pc = DIF_INSTR_LABEL(instr);
6246 			break;
6247 		case DIF_OP_BL:
6248 			if (cc_n ^ cc_v)
6249 				pc = DIF_INSTR_LABEL(instr);
6250 			break;
6251 		case DIF_OP_BLU:
6252 			if (cc_c)
6253 				pc = DIF_INSTR_LABEL(instr);
6254 			break;
6255 		case DIF_OP_BLE:
6256 			if (cc_z | (cc_n ^ cc_v))
6257 				pc = DIF_INSTR_LABEL(instr);
6258 			break;
6259 		case DIF_OP_BLEU:
6260 			if (cc_c | cc_z)
6261 				pc = DIF_INSTR_LABEL(instr);
6262 			break;
6263 		case DIF_OP_RLDSB:
6264 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6265 				break;
6266 			/*FALLTHROUGH*/
6267 		case DIF_OP_LDSB:
6268 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6269 			break;
6270 		case DIF_OP_RLDSH:
6271 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6272 				break;
6273 			/*FALLTHROUGH*/
6274 		case DIF_OP_LDSH:
6275 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6276 			break;
6277 		case DIF_OP_RLDSW:
6278 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6279 				break;
6280 			/*FALLTHROUGH*/
6281 		case DIF_OP_LDSW:
6282 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6283 			break;
6284 		case DIF_OP_RLDUB:
6285 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6286 				break;
6287 			/*FALLTHROUGH*/
6288 		case DIF_OP_LDUB:
6289 			regs[rd] = dtrace_load8(regs[r1]);
6290 			break;
6291 		case DIF_OP_RLDUH:
6292 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6293 				break;
6294 			/*FALLTHROUGH*/
6295 		case DIF_OP_LDUH:
6296 			regs[rd] = dtrace_load16(regs[r1]);
6297 			break;
6298 		case DIF_OP_RLDUW:
6299 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6300 				break;
6301 			/*FALLTHROUGH*/
6302 		case DIF_OP_LDUW:
6303 			regs[rd] = dtrace_load32(regs[r1]);
6304 			break;
6305 		case DIF_OP_RLDX:
6306 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6307 				break;
6308 			/*FALLTHROUGH*/
6309 		case DIF_OP_LDX:
6310 			regs[rd] = dtrace_load64(regs[r1]);
6311 			break;
6312 		case DIF_OP_ULDSB:
6313 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6314 			regs[rd] = (int8_t)
6315 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6316 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6317 			break;
6318 		case DIF_OP_ULDSH:
6319 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6320 			regs[rd] = (int16_t)
6321 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6322 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6323 			break;
6324 		case DIF_OP_ULDSW:
6325 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6326 			regs[rd] = (int32_t)
6327 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6328 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6329 			break;
6330 		case DIF_OP_ULDUB:
6331 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6332 			regs[rd] =
6333 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6334 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6335 			break;
6336 		case DIF_OP_ULDUH:
6337 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6338 			regs[rd] =
6339 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6340 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6341 			break;
6342 		case DIF_OP_ULDUW:
6343 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6344 			regs[rd] =
6345 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6346 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6347 			break;
6348 		case DIF_OP_ULDX:
6349 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6350 			regs[rd] =
6351 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6352 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6353 			break;
6354 		case DIF_OP_RET:
6355 			rval = regs[rd];
6356 			pc = textlen;
6357 			break;
6358 		case DIF_OP_NOP:
6359 			break;
6360 		case DIF_OP_SETX:
6361 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6362 			break;
6363 		case DIF_OP_SETS:
6364 			regs[rd] = (uint64_t)(uintptr_t)
6365 			    (strtab + DIF_INSTR_STRING(instr));
6366 			break;
6367 		case DIF_OP_SCMP: {
6368 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6369 			uintptr_t s1 = regs[r1];
6370 			uintptr_t s2 = regs[r2];
6371 			size_t lim1, lim2;
6372 
6373 			/*
6374 			 * If one of the strings is NULL then the limit becomes
6375 			 * 0 which compares 0 characters in dtrace_strncmp()
6376 			 * resulting in a false positive.  dtrace_strncmp()
6377 			 * treats a NULL as an empty 1-char string.
6378 			 */
6379 			lim1 = lim2 = 1;
6380 
6381 			if (s1 != 0 &&
6382 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6383 				break;
6384 			if (s2 != 0 &&
6385 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6386 				break;
6387 
6388 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6389 			    MIN(lim1, lim2));
6390 
6391 			cc_n = cc_r < 0;
6392 			cc_z = cc_r == 0;
6393 			cc_v = cc_c = 0;
6394 			break;
6395 		}
6396 		case DIF_OP_LDGA:
6397 			regs[rd] = dtrace_dif_variable(mstate, state,
6398 			    r1, regs[r2]);
6399 			break;
6400 		case DIF_OP_LDGS:
6401 			id = DIF_INSTR_VAR(instr);
6402 
6403 			if (id >= DIF_VAR_OTHER_UBASE) {
6404 				uintptr_t a;
6405 
6406 				id -= DIF_VAR_OTHER_UBASE;
6407 				svar = vstate->dtvs_globals[id];
6408 				ASSERT(svar != NULL);
6409 				v = &svar->dtsv_var;
6410 
6411 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6412 					regs[rd] = svar->dtsv_data;
6413 					break;
6414 				}
6415 
6416 				a = (uintptr_t)svar->dtsv_data;
6417 
6418 				if (*(uint8_t *)a == UINT8_MAX) {
6419 					/*
6420 					 * If the 0th byte is set to UINT8_MAX
6421 					 * then this is to be treated as a
6422 					 * reference to a NULL variable.
6423 					 */
6424 					regs[rd] = 0;
6425 				} else {
6426 					regs[rd] = a + sizeof (uint64_t);
6427 				}
6428 
6429 				break;
6430 			}
6431 
6432 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6433 			break;
6434 
6435 		case DIF_OP_STGS:
6436 			id = DIF_INSTR_VAR(instr);
6437 
6438 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6439 			id -= DIF_VAR_OTHER_UBASE;
6440 
6441 			VERIFY(id < vstate->dtvs_nglobals);
6442 			svar = vstate->dtvs_globals[id];
6443 			ASSERT(svar != NULL);
6444 			v = &svar->dtsv_var;
6445 
6446 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6447 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6448 				size_t lim;
6449 
6450 				ASSERT(a != 0);
6451 				ASSERT(svar->dtsv_size != 0);
6452 
6453 				if (regs[rd] == 0) {
6454 					*(uint8_t *)a = UINT8_MAX;
6455 					break;
6456 				} else {
6457 					*(uint8_t *)a = 0;
6458 					a += sizeof (uint64_t);
6459 				}
6460 				if (!dtrace_vcanload(
6461 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6462 				    &lim, mstate, vstate))
6463 					break;
6464 
6465 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6466 				    (void *)a, &v->dtdv_type, lim);
6467 				break;
6468 			}
6469 
6470 			svar->dtsv_data = regs[rd];
6471 			break;
6472 
6473 		case DIF_OP_LDTA:
6474 			/*
6475 			 * There are no DTrace built-in thread-local arrays at
6476 			 * present.  This opcode is saved for future work.
6477 			 */
6478 			*flags |= CPU_DTRACE_ILLOP;
6479 			regs[rd] = 0;
6480 			break;
6481 
6482 		case DIF_OP_LDLS:
6483 			id = DIF_INSTR_VAR(instr);
6484 
6485 			if (id < DIF_VAR_OTHER_UBASE) {
6486 				/*
6487 				 * For now, this has no meaning.
6488 				 */
6489 				regs[rd] = 0;
6490 				break;
6491 			}
6492 
6493 			id -= DIF_VAR_OTHER_UBASE;
6494 
6495 			ASSERT(id < vstate->dtvs_nlocals);
6496 			ASSERT(vstate->dtvs_locals != NULL);
6497 
6498 			svar = vstate->dtvs_locals[id];
6499 			ASSERT(svar != NULL);
6500 			v = &svar->dtsv_var;
6501 
6502 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6503 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6504 				size_t sz = v->dtdv_type.dtdt_size;
6505 				size_t lim;
6506 
6507 				sz += sizeof (uint64_t);
6508 				ASSERT(svar->dtsv_size == (mp_maxid + 1) * sz);
6509 				a += curcpu * sz;
6510 
6511 				if (*(uint8_t *)a == UINT8_MAX) {
6512 					/*
6513 					 * If the 0th byte is set to UINT8_MAX
6514 					 * then this is to be treated as a
6515 					 * reference to a NULL variable.
6516 					 */
6517 					regs[rd] = 0;
6518 				} else {
6519 					regs[rd] = a + sizeof (uint64_t);
6520 				}
6521 
6522 				break;
6523 			}
6524 
6525 			ASSERT(svar->dtsv_size ==
6526 			    (mp_maxid + 1) * sizeof (uint64_t));
6527 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6528 			regs[rd] = tmp[curcpu];
6529 			break;
6530 
6531 		case DIF_OP_STLS:
6532 			id = DIF_INSTR_VAR(instr);
6533 
6534 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6535 			id -= DIF_VAR_OTHER_UBASE;
6536 			VERIFY(id < vstate->dtvs_nlocals);
6537 
6538 			ASSERT(vstate->dtvs_locals != NULL);
6539 			svar = vstate->dtvs_locals[id];
6540 			ASSERT(svar != NULL);
6541 			v = &svar->dtsv_var;
6542 
6543 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6544 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6545 				size_t sz = v->dtdv_type.dtdt_size;
6546 				size_t lim;
6547 
6548 				sz += sizeof (uint64_t);
6549 				ASSERT(svar->dtsv_size == (mp_maxid + 1) * sz);
6550 				a += curcpu * sz;
6551 
6552 				if (regs[rd] == 0) {
6553 					*(uint8_t *)a = UINT8_MAX;
6554 					break;
6555 				} else {
6556 					*(uint8_t *)a = 0;
6557 					a += sizeof (uint64_t);
6558 				}
6559 
6560 				if (!dtrace_vcanload(
6561 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6562 				    &lim, mstate, vstate))
6563 					break;
6564 
6565 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6566 				    (void *)a, &v->dtdv_type, lim);
6567 				break;
6568 			}
6569 
6570 			ASSERT(svar->dtsv_size ==
6571 			    (mp_maxid + 1) * sizeof (uint64_t));
6572 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6573 			tmp[curcpu] = regs[rd];
6574 			break;
6575 
6576 		case DIF_OP_LDTS: {
6577 			dtrace_dynvar_t *dvar;
6578 			dtrace_key_t *key;
6579 
6580 			id = DIF_INSTR_VAR(instr);
6581 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6582 			id -= DIF_VAR_OTHER_UBASE;
6583 			v = &vstate->dtvs_tlocals[id];
6584 
6585 			key = &tupregs[DIF_DTR_NREGS];
6586 			key[0].dttk_value = (uint64_t)id;
6587 			key[0].dttk_size = 0;
6588 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6589 			key[1].dttk_size = 0;
6590 
6591 			dvar = dtrace_dynvar(dstate, 2, key,
6592 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6593 			    mstate, vstate);
6594 
6595 			if (dvar == NULL) {
6596 				regs[rd] = 0;
6597 				break;
6598 			}
6599 
6600 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6601 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6602 			} else {
6603 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6604 			}
6605 
6606 			break;
6607 		}
6608 
6609 		case DIF_OP_STTS: {
6610 			dtrace_dynvar_t *dvar;
6611 			dtrace_key_t *key;
6612 
6613 			id = DIF_INSTR_VAR(instr);
6614 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6615 			id -= DIF_VAR_OTHER_UBASE;
6616 			VERIFY(id < vstate->dtvs_ntlocals);
6617 
6618 			key = &tupregs[DIF_DTR_NREGS];
6619 			key[0].dttk_value = (uint64_t)id;
6620 			key[0].dttk_size = 0;
6621 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6622 			key[1].dttk_size = 0;
6623 			v = &vstate->dtvs_tlocals[id];
6624 
6625 			dvar = dtrace_dynvar(dstate, 2, key,
6626 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6627 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6628 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6629 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6630 
6631 			/*
6632 			 * Given that we're storing to thread-local data,
6633 			 * we need to flush our predicate cache.
6634 			 */
6635 			curthread->t_predcache = 0;
6636 
6637 			if (dvar == NULL)
6638 				break;
6639 
6640 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6641 				size_t lim;
6642 
6643 				if (!dtrace_vcanload(
6644 				    (void *)(uintptr_t)regs[rd],
6645 				    &v->dtdv_type, &lim, mstate, vstate))
6646 					break;
6647 
6648 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6649 				    dvar->dtdv_data, &v->dtdv_type, lim);
6650 			} else {
6651 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6652 			}
6653 
6654 			break;
6655 		}
6656 
6657 		case DIF_OP_SRA:
6658 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6659 			break;
6660 
6661 		case DIF_OP_CALL:
6662 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6663 			    regs, tupregs, ttop, mstate, state);
6664 			break;
6665 
6666 		case DIF_OP_PUSHTR:
6667 			if (ttop == DIF_DTR_NREGS) {
6668 				*flags |= CPU_DTRACE_TUPOFLOW;
6669 				break;
6670 			}
6671 
6672 			if (r1 == DIF_TYPE_STRING) {
6673 				/*
6674 				 * If this is a string type and the size is 0,
6675 				 * we'll use the system-wide default string
6676 				 * size.  Note that we are _not_ looking at
6677 				 * the value of the DTRACEOPT_STRSIZE option;
6678 				 * had this been set, we would expect to have
6679 				 * a non-zero size value in the "pushtr".
6680 				 */
6681 				tupregs[ttop].dttk_size =
6682 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6683 				    regs[r2] ? regs[r2] :
6684 				    dtrace_strsize_default) + 1;
6685 			} else {
6686 				if (regs[r2] > LONG_MAX) {
6687 					*flags |= CPU_DTRACE_ILLOP;
6688 					break;
6689 				}
6690 
6691 				tupregs[ttop].dttk_size = regs[r2];
6692 			}
6693 
6694 			tupregs[ttop++].dttk_value = regs[rd];
6695 			break;
6696 
6697 		case DIF_OP_PUSHTV:
6698 			if (ttop == DIF_DTR_NREGS) {
6699 				*flags |= CPU_DTRACE_TUPOFLOW;
6700 				break;
6701 			}
6702 
6703 			tupregs[ttop].dttk_value = regs[rd];
6704 			tupregs[ttop++].dttk_size = 0;
6705 			break;
6706 
6707 		case DIF_OP_POPTS:
6708 			if (ttop != 0)
6709 				ttop--;
6710 			break;
6711 
6712 		case DIF_OP_FLUSHTS:
6713 			ttop = 0;
6714 			break;
6715 
6716 		case DIF_OP_LDGAA:
6717 		case DIF_OP_LDTAA: {
6718 			dtrace_dynvar_t *dvar;
6719 			dtrace_key_t *key = tupregs;
6720 			uint_t nkeys = ttop;
6721 
6722 			id = DIF_INSTR_VAR(instr);
6723 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6724 			id -= DIF_VAR_OTHER_UBASE;
6725 
6726 			key[nkeys].dttk_value = (uint64_t)id;
6727 			key[nkeys++].dttk_size = 0;
6728 
6729 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6730 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6731 				key[nkeys++].dttk_size = 0;
6732 				VERIFY(id < vstate->dtvs_ntlocals);
6733 				v = &vstate->dtvs_tlocals[id];
6734 			} else {
6735 				VERIFY(id < vstate->dtvs_nglobals);
6736 				v = &vstate->dtvs_globals[id]->dtsv_var;
6737 			}
6738 
6739 			dvar = dtrace_dynvar(dstate, nkeys, key,
6740 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6741 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6742 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6743 
6744 			if (dvar == NULL) {
6745 				regs[rd] = 0;
6746 				break;
6747 			}
6748 
6749 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6750 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6751 			} else {
6752 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6753 			}
6754 
6755 			break;
6756 		}
6757 
6758 		case DIF_OP_STGAA:
6759 		case DIF_OP_STTAA: {
6760 			dtrace_dynvar_t *dvar;
6761 			dtrace_key_t *key = tupregs;
6762 			uint_t nkeys = ttop;
6763 
6764 			id = DIF_INSTR_VAR(instr);
6765 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6766 			id -= DIF_VAR_OTHER_UBASE;
6767 
6768 			key[nkeys].dttk_value = (uint64_t)id;
6769 			key[nkeys++].dttk_size = 0;
6770 
6771 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6772 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6773 				key[nkeys++].dttk_size = 0;
6774 				VERIFY(id < vstate->dtvs_ntlocals);
6775 				v = &vstate->dtvs_tlocals[id];
6776 			} else {
6777 				VERIFY(id < vstate->dtvs_nglobals);
6778 				v = &vstate->dtvs_globals[id]->dtsv_var;
6779 			}
6780 
6781 			dvar = dtrace_dynvar(dstate, nkeys, key,
6782 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6783 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6784 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6785 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6786 
6787 			if (dvar == NULL)
6788 				break;
6789 
6790 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6791 				size_t lim;
6792 
6793 				if (!dtrace_vcanload(
6794 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6795 				    &lim, mstate, vstate))
6796 					break;
6797 
6798 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6799 				    dvar->dtdv_data, &v->dtdv_type, lim);
6800 			} else {
6801 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6802 			}
6803 
6804 			break;
6805 		}
6806 
6807 		case DIF_OP_ALLOCS: {
6808 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6809 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6810 
6811 			/*
6812 			 * Rounding up the user allocation size could have
6813 			 * overflowed large, bogus allocations (like -1ULL) to
6814 			 * 0.
6815 			 */
6816 			if (size < regs[r1] ||
6817 			    !DTRACE_INSCRATCH(mstate, size)) {
6818 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6819 				regs[rd] = 0;
6820 				break;
6821 			}
6822 
6823 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6824 			mstate->dtms_scratch_ptr += size;
6825 			regs[rd] = ptr;
6826 			break;
6827 		}
6828 
6829 		case DIF_OP_COPYS:
6830 			if (!dtrace_canstore(regs[rd], regs[r2],
6831 			    mstate, vstate)) {
6832 				*flags |= CPU_DTRACE_BADADDR;
6833 				*illval = regs[rd];
6834 				break;
6835 			}
6836 
6837 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6838 				break;
6839 
6840 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6841 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6842 			break;
6843 
6844 		case DIF_OP_STB:
6845 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6846 				*flags |= CPU_DTRACE_BADADDR;
6847 				*illval = regs[rd];
6848 				break;
6849 			}
6850 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6851 			break;
6852 
6853 		case DIF_OP_STH:
6854 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6855 				*flags |= CPU_DTRACE_BADADDR;
6856 				*illval = regs[rd];
6857 				break;
6858 			}
6859 			if (regs[rd] & 1) {
6860 				*flags |= CPU_DTRACE_BADALIGN;
6861 				*illval = regs[rd];
6862 				break;
6863 			}
6864 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6865 			break;
6866 
6867 		case DIF_OP_STW:
6868 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6869 				*flags |= CPU_DTRACE_BADADDR;
6870 				*illval = regs[rd];
6871 				break;
6872 			}
6873 			if (regs[rd] & 3) {
6874 				*flags |= CPU_DTRACE_BADALIGN;
6875 				*illval = regs[rd];
6876 				break;
6877 			}
6878 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6879 			break;
6880 
6881 		case DIF_OP_STX:
6882 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6883 				*flags |= CPU_DTRACE_BADADDR;
6884 				*illval = regs[rd];
6885 				break;
6886 			}
6887 			if (regs[rd] & 7) {
6888 				*flags |= CPU_DTRACE_BADALIGN;
6889 				*illval = regs[rd];
6890 				break;
6891 			}
6892 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6893 			break;
6894 		}
6895 	}
6896 
6897 	if (!(*flags & CPU_DTRACE_FAULT))
6898 		return (rval);
6899 
6900 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6901 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6902 
6903 	return (0);
6904 }
6905 
6906 static void
6907 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6908 {
6909 	dtrace_probe_t *probe = ecb->dte_probe;
6910 	dtrace_provider_t *prov = probe->dtpr_provider;
6911 	char c[DTRACE_FULLNAMELEN + 80], *str;
6912 	char *msg = "dtrace: breakpoint action at probe ";
6913 	char *ecbmsg = " (ecb ";
6914 	uintptr_t val = (uintptr_t)ecb;
6915 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6916 
6917 	if (dtrace_destructive_disallow)
6918 		return;
6919 
6920 	/*
6921 	 * It's impossible to be taking action on the NULL probe.
6922 	 */
6923 	ASSERT(probe != NULL);
6924 
6925 	/*
6926 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6927 	 * print the provider name, module name, function name and name of
6928 	 * the probe, along with the hex address of the ECB with the breakpoint
6929 	 * action -- all of which we must place in the character buffer by
6930 	 * hand.
6931 	 */
6932 	while (*msg != '\0')
6933 		c[i++] = *msg++;
6934 
6935 	for (str = prov->dtpv_name; *str != '\0'; str++)
6936 		c[i++] = *str;
6937 	c[i++] = ':';
6938 
6939 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6940 		c[i++] = *str;
6941 	c[i++] = ':';
6942 
6943 	for (str = probe->dtpr_func; *str != '\0'; str++)
6944 		c[i++] = *str;
6945 	c[i++] = ':';
6946 
6947 	for (str = probe->dtpr_name; *str != '\0'; str++)
6948 		c[i++] = *str;
6949 
6950 	while (*ecbmsg != '\0')
6951 		c[i++] = *ecbmsg++;
6952 
6953 	while (shift >= 0) {
6954 		size_t mask = (size_t)0xf << shift;
6955 
6956 		if (val >= ((size_t)1 << shift))
6957 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6958 		shift -= 4;
6959 	}
6960 
6961 	c[i++] = ')';
6962 	c[i] = '\0';
6963 
6964 #ifdef illumos
6965 	debug_enter(c);
6966 #else
6967 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6968 #endif
6969 }
6970 
6971 static void
6972 dtrace_action_panic(dtrace_ecb_t *ecb)
6973 {
6974 	dtrace_probe_t *probe = ecb->dte_probe;
6975 
6976 	/*
6977 	 * It's impossible to be taking action on the NULL probe.
6978 	 */
6979 	ASSERT(probe != NULL);
6980 
6981 	if (dtrace_destructive_disallow)
6982 		return;
6983 
6984 	if (dtrace_panicked != NULL)
6985 		return;
6986 
6987 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6988 		return;
6989 
6990 	/*
6991 	 * We won the right to panic.  (We want to be sure that only one
6992 	 * thread calls panic() from dtrace_probe(), and that panic() is
6993 	 * called exactly once.)
6994 	 */
6995 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6996 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6997 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6998 }
6999 
7000 static void
7001 dtrace_action_raise(uint64_t sig)
7002 {
7003 	if (dtrace_destructive_disallow)
7004 		return;
7005 
7006 	if (sig >= NSIG) {
7007 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7008 		return;
7009 	}
7010 
7011 #ifdef illumos
7012 	/*
7013 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7014 	 * invocations of the raise() action.
7015 	 */
7016 	if (curthread->t_dtrace_sig == 0)
7017 		curthread->t_dtrace_sig = (uint8_t)sig;
7018 
7019 	curthread->t_sig_check = 1;
7020 	aston(curthread);
7021 #else
7022 	struct proc *p = curproc;
7023 	PROC_LOCK(p);
7024 	kern_psignal(p, sig);
7025 	PROC_UNLOCK(p);
7026 #endif
7027 }
7028 
7029 static void
7030 dtrace_action_stop(void)
7031 {
7032 	if (dtrace_destructive_disallow)
7033 		return;
7034 
7035 #ifdef illumos
7036 	if (!curthread->t_dtrace_stop) {
7037 		curthread->t_dtrace_stop = 1;
7038 		curthread->t_sig_check = 1;
7039 		aston(curthread);
7040 	}
7041 #else
7042 	struct proc *p = curproc;
7043 	PROC_LOCK(p);
7044 	kern_psignal(p, SIGSTOP);
7045 	PROC_UNLOCK(p);
7046 #endif
7047 }
7048 
7049 static void
7050 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7051 {
7052 	hrtime_t now;
7053 	volatile uint16_t *flags;
7054 #ifdef illumos
7055 	cpu_t *cpu = CPU;
7056 #else
7057 	cpu_t *cpu = &solaris_cpu[curcpu];
7058 #endif
7059 
7060 	if (dtrace_destructive_disallow)
7061 		return;
7062 
7063 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7064 
7065 	now = dtrace_gethrtime();
7066 
7067 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7068 		/*
7069 		 * We need to advance the mark to the current time.
7070 		 */
7071 		cpu->cpu_dtrace_chillmark = now;
7072 		cpu->cpu_dtrace_chilled = 0;
7073 	}
7074 
7075 	/*
7076 	 * Now check to see if the requested chill time would take us over
7077 	 * the maximum amount of time allowed in the chill interval.  (Or
7078 	 * worse, if the calculation itself induces overflow.)
7079 	 */
7080 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7081 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7082 		*flags |= CPU_DTRACE_ILLOP;
7083 		return;
7084 	}
7085 
7086 	while (dtrace_gethrtime() - now < val)
7087 		continue;
7088 
7089 	/*
7090 	 * Normally, we assure that the value of the variable "timestamp" does
7091 	 * not change within an ECB.  The presence of chill() represents an
7092 	 * exception to this rule, however.
7093 	 */
7094 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7095 	cpu->cpu_dtrace_chilled += val;
7096 }
7097 
7098 static void
7099 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7100     uint64_t *buf, uint64_t arg)
7101 {
7102 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7103 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7104 	uint64_t *pcs = &buf[1], *fps;
7105 	char *str = (char *)&pcs[nframes];
7106 	int size, offs = 0, i, j;
7107 	size_t rem;
7108 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7109 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7110 	char *sym;
7111 
7112 	/*
7113 	 * Should be taking a faster path if string space has not been
7114 	 * allocated.
7115 	 */
7116 	ASSERT(strsize != 0);
7117 
7118 	/*
7119 	 * We will first allocate some temporary space for the frame pointers.
7120 	 */
7121 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7122 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7123 	    (nframes * sizeof (uint64_t));
7124 
7125 	if (!DTRACE_INSCRATCH(mstate, size)) {
7126 		/*
7127 		 * Not enough room for our frame pointers -- need to indicate
7128 		 * that we ran out of scratch space.
7129 		 */
7130 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7131 		return;
7132 	}
7133 
7134 	mstate->dtms_scratch_ptr += size;
7135 	saved = mstate->dtms_scratch_ptr;
7136 
7137 	/*
7138 	 * Now get a stack with both program counters and frame pointers.
7139 	 */
7140 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7141 	dtrace_getufpstack(buf, fps, nframes + 1);
7142 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7143 
7144 	/*
7145 	 * If that faulted, we're cooked.
7146 	 */
7147 	if (*flags & CPU_DTRACE_FAULT)
7148 		goto out;
7149 
7150 	/*
7151 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7152 	 * each iteration, we restore the scratch pointer.
7153 	 */
7154 	for (i = 0; i < nframes; i++) {
7155 		mstate->dtms_scratch_ptr = saved;
7156 
7157 		if (offs >= strsize)
7158 			break;
7159 
7160 		sym = (char *)(uintptr_t)dtrace_helper(
7161 		    DTRACE_HELPER_ACTION_USTACK,
7162 		    mstate, state, pcs[i], fps[i]);
7163 
7164 		/*
7165 		 * If we faulted while running the helper, we're going to
7166 		 * clear the fault and null out the corresponding string.
7167 		 */
7168 		if (*flags & CPU_DTRACE_FAULT) {
7169 			*flags &= ~CPU_DTRACE_FAULT;
7170 			str[offs++] = '\0';
7171 			continue;
7172 		}
7173 
7174 		if (sym == NULL) {
7175 			str[offs++] = '\0';
7176 			continue;
7177 		}
7178 
7179 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7180 		    &(state->dts_vstate))) {
7181 			str[offs++] = '\0';
7182 			continue;
7183 		}
7184 
7185 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7186 
7187 		/*
7188 		 * Now copy in the string that the helper returned to us.
7189 		 */
7190 		for (j = 0; offs + j < strsize && j < rem; j++) {
7191 			if ((str[offs + j] = sym[j]) == '\0')
7192 				break;
7193 		}
7194 
7195 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7196 
7197 		offs += j + 1;
7198 	}
7199 
7200 	if (offs >= strsize) {
7201 		/*
7202 		 * If we didn't have room for all of the strings, we don't
7203 		 * abort processing -- this needn't be a fatal error -- but we
7204 		 * still want to increment a counter (dts_stkstroverflows) to
7205 		 * allow this condition to be warned about.  (If this is from
7206 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7207 		 */
7208 		dtrace_error(&state->dts_stkstroverflows);
7209 	}
7210 
7211 	while (offs < strsize)
7212 		str[offs++] = '\0';
7213 
7214 out:
7215 	mstate->dtms_scratch_ptr = old;
7216 }
7217 
7218 static void
7219 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7220     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7221 {
7222 	volatile uint16_t *flags;
7223 	uint64_t val = *valp;
7224 	size_t valoffs = *valoffsp;
7225 
7226 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7227 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7228 
7229 	/*
7230 	 * If this is a string, we're going to only load until we find the zero
7231 	 * byte -- after which we'll store zero bytes.
7232 	 */
7233 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7234 		char c = '\0' + 1;
7235 		size_t s;
7236 
7237 		for (s = 0; s < size; s++) {
7238 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7239 				c = dtrace_load8(val++);
7240 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7241 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7242 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7243 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7244 				if (*flags & CPU_DTRACE_FAULT)
7245 					break;
7246 			}
7247 
7248 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7249 
7250 			if (c == '\0' && intuple)
7251 				break;
7252 		}
7253 	} else {
7254 		uint8_t c;
7255 		while (valoffs < end) {
7256 			if (dtkind == DIF_TF_BYREF) {
7257 				c = dtrace_load8(val++);
7258 			} else if (dtkind == DIF_TF_BYUREF) {
7259 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7260 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7261 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7262 				if (*flags & CPU_DTRACE_FAULT)
7263 					break;
7264 			}
7265 
7266 			DTRACE_STORE(uint8_t, tomax,
7267 			    valoffs++, c);
7268 		}
7269 	}
7270 
7271 	*valp = val;
7272 	*valoffsp = valoffs;
7273 }
7274 
7275 /*
7276  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7277  * defined, we also assert that we are not recursing unless the probe ID is an
7278  * error probe.
7279  */
7280 static dtrace_icookie_t
7281 dtrace_probe_enter(dtrace_id_t id)
7282 {
7283 	dtrace_icookie_t cookie;
7284 
7285 	cookie = dtrace_interrupt_disable();
7286 
7287 	/*
7288 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7289 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7290 	 * function is instrumented that should not have been instrumented or
7291 	 * that the ordering guarantee of the records will be violated,
7292 	 * resulting in unexpected output. If there is an exception to this
7293 	 * assertion, a new case should be added.
7294 	 */
7295 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7296 	    id == dtrace_probeid_error);
7297 	curthread->t_dtrace_inprobe = 1;
7298 
7299 	return (cookie);
7300 }
7301 
7302 /*
7303  * Clears the per-thread inprobe flag and enables interrupts.
7304  */
7305 static void
7306 dtrace_probe_exit(dtrace_icookie_t cookie)
7307 {
7308 
7309 	curthread->t_dtrace_inprobe = 0;
7310 	dtrace_interrupt_enable(cookie);
7311 }
7312 
7313 /*
7314  * If you're looking for the epicenter of DTrace, you just found it.  This
7315  * is the function called by the provider to fire a probe -- from which all
7316  * subsequent probe-context DTrace activity emanates.
7317  */
7318 void
7319 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7320     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7321 {
7322 	processorid_t cpuid;
7323 	dtrace_icookie_t cookie;
7324 	dtrace_probe_t *probe;
7325 	dtrace_mstate_t mstate;
7326 	dtrace_ecb_t *ecb;
7327 	dtrace_action_t *act;
7328 	intptr_t offs;
7329 	size_t size;
7330 	int vtime, onintr;
7331 	volatile uint16_t *flags;
7332 	hrtime_t now;
7333 
7334 	if (KERNEL_PANICKED())
7335 		return;
7336 
7337 #ifdef illumos
7338 	/*
7339 	 * Kick out immediately if this CPU is still being born (in which case
7340 	 * curthread will be set to -1) or the current thread can't allow
7341 	 * probes in its current context.
7342 	 */
7343 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7344 		return;
7345 #endif
7346 
7347 	cookie = dtrace_probe_enter(id);
7348 	probe = dtrace_probes[id - 1];
7349 	cpuid = curcpu;
7350 	onintr = CPU_ON_INTR(CPU);
7351 
7352 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7353 	    probe->dtpr_predcache == curthread->t_predcache) {
7354 		/*
7355 		 * We have hit in the predicate cache; we know that
7356 		 * this predicate would evaluate to be false.
7357 		 */
7358 		dtrace_probe_exit(cookie);
7359 		return;
7360 	}
7361 
7362 #ifdef illumos
7363 	if (panic_quiesce) {
7364 #else
7365 	if (KERNEL_PANICKED()) {
7366 #endif
7367 		/*
7368 		 * We don't trace anything if we're panicking.
7369 		 */
7370 		dtrace_probe_exit(cookie);
7371 		return;
7372 	}
7373 
7374 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7375 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7376 	vtime = dtrace_vtime_references != 0;
7377 
7378 	if (vtime && curthread->t_dtrace_start)
7379 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7380 
7381 	mstate.dtms_difo = NULL;
7382 	mstate.dtms_probe = probe;
7383 	mstate.dtms_strtok = 0;
7384 	mstate.dtms_arg[0] = arg0;
7385 	mstate.dtms_arg[1] = arg1;
7386 	mstate.dtms_arg[2] = arg2;
7387 	mstate.dtms_arg[3] = arg3;
7388 	mstate.dtms_arg[4] = arg4;
7389 
7390 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7391 
7392 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7393 		dtrace_predicate_t *pred = ecb->dte_predicate;
7394 		dtrace_state_t *state = ecb->dte_state;
7395 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7396 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7397 		dtrace_vstate_t *vstate = &state->dts_vstate;
7398 		dtrace_provider_t *prov = probe->dtpr_provider;
7399 		uint64_t tracememsize = 0;
7400 		int committed = 0;
7401 		caddr_t tomax;
7402 
7403 		/*
7404 		 * A little subtlety with the following (seemingly innocuous)
7405 		 * declaration of the automatic 'val':  by looking at the
7406 		 * code, you might think that it could be declared in the
7407 		 * action processing loop, below.  (That is, it's only used in
7408 		 * the action processing loop.)  However, it must be declared
7409 		 * out of that scope because in the case of DIF expression
7410 		 * arguments to aggregating actions, one iteration of the
7411 		 * action loop will use the last iteration's value.
7412 		 */
7413 		uint64_t val = 0;
7414 
7415 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7416 		mstate.dtms_getf = NULL;
7417 
7418 		*flags &= ~CPU_DTRACE_ERROR;
7419 
7420 		if (prov == dtrace_provider) {
7421 			/*
7422 			 * If dtrace itself is the provider of this probe,
7423 			 * we're only going to continue processing the ECB if
7424 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7425 			 * creating state.  (This prevents disjoint consumers
7426 			 * from seeing one another's metaprobes.)
7427 			 */
7428 			if (arg0 != (uint64_t)(uintptr_t)state)
7429 				continue;
7430 		}
7431 
7432 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7433 			/*
7434 			 * We're not currently active.  If our provider isn't
7435 			 * the dtrace pseudo provider, we're not interested.
7436 			 */
7437 			if (prov != dtrace_provider)
7438 				continue;
7439 
7440 			/*
7441 			 * Now we must further check if we are in the BEGIN
7442 			 * probe.  If we are, we will only continue processing
7443 			 * if we're still in WARMUP -- if one BEGIN enabling
7444 			 * has invoked the exit() action, we don't want to
7445 			 * evaluate subsequent BEGIN enablings.
7446 			 */
7447 			if (probe->dtpr_id == dtrace_probeid_begin &&
7448 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7449 				ASSERT(state->dts_activity ==
7450 				    DTRACE_ACTIVITY_DRAINING);
7451 				continue;
7452 			}
7453 		}
7454 
7455 		if (ecb->dte_cond) {
7456 			/*
7457 			 * If the dte_cond bits indicate that this
7458 			 * consumer is only allowed to see user-mode firings
7459 			 * of this probe, call the provider's dtps_usermode()
7460 			 * entry point to check that the probe was fired
7461 			 * while in a user context. Skip this ECB if that's
7462 			 * not the case.
7463 			 */
7464 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7465 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7466 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7467 				continue;
7468 
7469 #ifdef illumos
7470 			/*
7471 			 * This is more subtle than it looks. We have to be
7472 			 * absolutely certain that CRED() isn't going to
7473 			 * change out from under us so it's only legit to
7474 			 * examine that structure if we're in constrained
7475 			 * situations. Currently, the only times we'll this
7476 			 * check is if a non-super-user has enabled the
7477 			 * profile or syscall providers -- providers that
7478 			 * allow visibility of all processes. For the
7479 			 * profile case, the check above will ensure that
7480 			 * we're examining a user context.
7481 			 */
7482 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7483 				cred_t *cr;
7484 				cred_t *s_cr =
7485 				    ecb->dte_state->dts_cred.dcr_cred;
7486 				proc_t *proc;
7487 
7488 				ASSERT(s_cr != NULL);
7489 
7490 				if ((cr = CRED()) == NULL ||
7491 				    s_cr->cr_uid != cr->cr_uid ||
7492 				    s_cr->cr_uid != cr->cr_ruid ||
7493 				    s_cr->cr_uid != cr->cr_suid ||
7494 				    s_cr->cr_gid != cr->cr_gid ||
7495 				    s_cr->cr_gid != cr->cr_rgid ||
7496 				    s_cr->cr_gid != cr->cr_sgid ||
7497 				    (proc = ttoproc(curthread)) == NULL ||
7498 				    (proc->p_flag & SNOCD))
7499 					continue;
7500 			}
7501 
7502 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7503 				cred_t *cr;
7504 				cred_t *s_cr =
7505 				    ecb->dte_state->dts_cred.dcr_cred;
7506 
7507 				ASSERT(s_cr != NULL);
7508 
7509 				if ((cr = CRED()) == NULL ||
7510 				    s_cr->cr_zone->zone_id !=
7511 				    cr->cr_zone->zone_id)
7512 					continue;
7513 			}
7514 #endif
7515 		}
7516 
7517 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7518 			/*
7519 			 * We seem to be dead.  Unless we (a) have kernel
7520 			 * destructive permissions (b) have explicitly enabled
7521 			 * destructive actions and (c) destructive actions have
7522 			 * not been disabled, we're going to transition into
7523 			 * the KILLED state, from which no further processing
7524 			 * on this state will be performed.
7525 			 */
7526 			if (!dtrace_priv_kernel_destructive(state) ||
7527 			    !state->dts_cred.dcr_destructive ||
7528 			    dtrace_destructive_disallow) {
7529 				void *activity = &state->dts_activity;
7530 				dtrace_activity_t curstate;
7531 
7532 				do {
7533 					curstate = state->dts_activity;
7534 				} while (dtrace_cas32(activity, curstate,
7535 				    DTRACE_ACTIVITY_KILLED) != curstate);
7536 
7537 				continue;
7538 			}
7539 		}
7540 
7541 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7542 		    ecb->dte_alignment, state, &mstate)) < 0)
7543 			continue;
7544 
7545 		tomax = buf->dtb_tomax;
7546 		ASSERT(tomax != NULL);
7547 
7548 		if (ecb->dte_size != 0) {
7549 			dtrace_rechdr_t dtrh;
7550 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7551 				mstate.dtms_timestamp = dtrace_gethrtime();
7552 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7553 			}
7554 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7555 			dtrh.dtrh_epid = ecb->dte_epid;
7556 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7557 			    mstate.dtms_timestamp);
7558 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7559 		}
7560 
7561 		mstate.dtms_epid = ecb->dte_epid;
7562 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7563 
7564 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7565 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7566 		else
7567 			mstate.dtms_access = 0;
7568 
7569 		if (pred != NULL) {
7570 			dtrace_difo_t *dp = pred->dtp_difo;
7571 			uint64_t rval;
7572 
7573 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7574 
7575 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7576 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7577 
7578 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7579 					/*
7580 					 * Update the predicate cache...
7581 					 */
7582 					ASSERT(cid == pred->dtp_cacheid);
7583 					curthread->t_predcache = cid;
7584 				}
7585 
7586 				continue;
7587 			}
7588 		}
7589 
7590 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7591 		    act != NULL; act = act->dta_next) {
7592 			size_t valoffs;
7593 			dtrace_difo_t *dp;
7594 			dtrace_recdesc_t *rec = &act->dta_rec;
7595 
7596 			size = rec->dtrd_size;
7597 			valoffs = offs + rec->dtrd_offset;
7598 
7599 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7600 				uint64_t v = 0xbad;
7601 				dtrace_aggregation_t *agg;
7602 
7603 				agg = (dtrace_aggregation_t *)act;
7604 
7605 				if ((dp = act->dta_difo) != NULL)
7606 					v = dtrace_dif_emulate(dp,
7607 					    &mstate, vstate, state);
7608 
7609 				if (*flags & CPU_DTRACE_ERROR)
7610 					continue;
7611 
7612 				/*
7613 				 * Note that we always pass the expression
7614 				 * value from the previous iteration of the
7615 				 * action loop.  This value will only be used
7616 				 * if there is an expression argument to the
7617 				 * aggregating action, denoted by the
7618 				 * dtag_hasarg field.
7619 				 */
7620 				dtrace_aggregate(agg, buf,
7621 				    offs, aggbuf, v, val);
7622 				continue;
7623 			}
7624 
7625 			switch (act->dta_kind) {
7626 			case DTRACEACT_STOP:
7627 				if (dtrace_priv_proc_destructive(state))
7628 					dtrace_action_stop();
7629 				continue;
7630 
7631 			case DTRACEACT_BREAKPOINT:
7632 				if (dtrace_priv_kernel_destructive(state))
7633 					dtrace_action_breakpoint(ecb);
7634 				continue;
7635 
7636 			case DTRACEACT_PANIC:
7637 				if (dtrace_priv_kernel_destructive(state))
7638 					dtrace_action_panic(ecb);
7639 				continue;
7640 
7641 			case DTRACEACT_STACK:
7642 				if (!dtrace_priv_kernel(state))
7643 					continue;
7644 
7645 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7646 				    size / sizeof (pc_t), probe->dtpr_aframes,
7647 				    DTRACE_ANCHORED(probe) ? NULL :
7648 				    (uint32_t *)arg0);
7649 				continue;
7650 
7651 			case DTRACEACT_JSTACK:
7652 			case DTRACEACT_USTACK:
7653 				if (!dtrace_priv_proc(state))
7654 					continue;
7655 
7656 				/*
7657 				 * See comment in DIF_VAR_PID.
7658 				 */
7659 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7660 				    CPU_ON_INTR(CPU)) {
7661 					int depth = DTRACE_USTACK_NFRAMES(
7662 					    rec->dtrd_arg) + 1;
7663 
7664 					dtrace_bzero((void *)(tomax + valoffs),
7665 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7666 					    + depth * sizeof (uint64_t));
7667 
7668 					continue;
7669 				}
7670 
7671 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7672 				    curproc->p_dtrace_helpers != NULL) {
7673 					/*
7674 					 * This is the slow path -- we have
7675 					 * allocated string space, and we're
7676 					 * getting the stack of a process that
7677 					 * has helpers.  Call into a separate
7678 					 * routine to perform this processing.
7679 					 */
7680 					dtrace_action_ustack(&mstate, state,
7681 					    (uint64_t *)(tomax + valoffs),
7682 					    rec->dtrd_arg);
7683 					continue;
7684 				}
7685 
7686 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7687 				dtrace_getupcstack((uint64_t *)
7688 				    (tomax + valoffs),
7689 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7690 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7691 				continue;
7692 
7693 			default:
7694 				break;
7695 			}
7696 
7697 			dp = act->dta_difo;
7698 			ASSERT(dp != NULL);
7699 
7700 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7701 
7702 			if (*flags & CPU_DTRACE_ERROR)
7703 				continue;
7704 
7705 			switch (act->dta_kind) {
7706 			case DTRACEACT_SPECULATE: {
7707 				dtrace_rechdr_t *dtrh;
7708 
7709 				ASSERT(buf == &state->dts_buffer[cpuid]);
7710 				buf = dtrace_speculation_buffer(state,
7711 				    cpuid, val);
7712 
7713 				if (buf == NULL) {
7714 					*flags |= CPU_DTRACE_DROP;
7715 					continue;
7716 				}
7717 
7718 				offs = dtrace_buffer_reserve(buf,
7719 				    ecb->dte_needed, ecb->dte_alignment,
7720 				    state, NULL);
7721 
7722 				if (offs < 0) {
7723 					*flags |= CPU_DTRACE_DROP;
7724 					continue;
7725 				}
7726 
7727 				tomax = buf->dtb_tomax;
7728 				ASSERT(tomax != NULL);
7729 
7730 				if (ecb->dte_size == 0)
7731 					continue;
7732 
7733 				ASSERT3U(ecb->dte_size, >=,
7734 				    sizeof (dtrace_rechdr_t));
7735 				dtrh = ((void *)(tomax + offs));
7736 				dtrh->dtrh_epid = ecb->dte_epid;
7737 				/*
7738 				 * When the speculation is committed, all of
7739 				 * the records in the speculative buffer will
7740 				 * have their timestamps set to the commit
7741 				 * time.  Until then, it is set to a sentinel
7742 				 * value, for debugability.
7743 				 */
7744 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7745 				continue;
7746 			}
7747 
7748 			case DTRACEACT_PRINTM: {
7749 				/*
7750 				 * printm() assumes that the DIF returns a
7751 				 * pointer returned by memref(). memref() is a
7752 				 * subroutine that is used to get around the
7753 				 * single-valued returns of DIF and is assumed
7754 				 * to always be allocated in the scratch space.
7755 				 * Therefore, we need to validate that the
7756 				 * pointer given to printm() is in the scratch
7757 				 * space in order to avoid a potential panic.
7758 				 */
7759 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7760 
7761 				if (!DTRACE_INSCRATCHPTR(&mstate,
7762 				    (uintptr_t)memref, 2 * sizeof(uintptr_t))) {
7763 					*flags |= CPU_DTRACE_BADADDR;
7764 					continue;
7765 				}
7766 
7767 				/* Get the size from the memref. */
7768 				size = memref[1];
7769 
7770 				/*
7771 				 * Check if the size exceeds the allocated
7772 				 * buffer size.
7773 				 */
7774 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7775 					/* Flag a drop! */
7776 					*flags |= CPU_DTRACE_DROP;
7777 					continue;
7778 				}
7779 
7780 				/* Store the size in the buffer first. */
7781 				DTRACE_STORE(uintptr_t, tomax,
7782 				    valoffs, size);
7783 
7784 				/*
7785 				 * Offset the buffer address to the start
7786 				 * of the data.
7787 				 */
7788 				valoffs += sizeof(uintptr_t);
7789 
7790 				/*
7791 				 * Reset to the memory address rather than
7792 				 * the memref array, then let the BYREF
7793 				 * code below do the work to store the
7794 				 * memory data in the buffer.
7795 				 */
7796 				val = memref[0];
7797 				break;
7798 			}
7799 
7800 			case DTRACEACT_CHILL:
7801 				if (dtrace_priv_kernel_destructive(state))
7802 					dtrace_action_chill(&mstate, val);
7803 				continue;
7804 
7805 			case DTRACEACT_RAISE:
7806 				if (dtrace_priv_proc_destructive(state))
7807 					dtrace_action_raise(val);
7808 				continue;
7809 
7810 			case DTRACEACT_COMMIT:
7811 				ASSERT(!committed);
7812 
7813 				/*
7814 				 * We need to commit our buffer state.
7815 				 */
7816 				if (ecb->dte_size)
7817 					buf->dtb_offset = offs + ecb->dte_size;
7818 				buf = &state->dts_buffer[cpuid];
7819 				dtrace_speculation_commit(state, cpuid, val);
7820 				committed = 1;
7821 				continue;
7822 
7823 			case DTRACEACT_DISCARD:
7824 				dtrace_speculation_discard(state, cpuid, val);
7825 				continue;
7826 
7827 			case DTRACEACT_DIFEXPR:
7828 			case DTRACEACT_LIBACT:
7829 			case DTRACEACT_PRINTF:
7830 			case DTRACEACT_PRINTA:
7831 			case DTRACEACT_SYSTEM:
7832 			case DTRACEACT_FREOPEN:
7833 			case DTRACEACT_TRACEMEM:
7834 				break;
7835 
7836 			case DTRACEACT_TRACEMEM_DYNSIZE:
7837 				tracememsize = val;
7838 				break;
7839 
7840 			case DTRACEACT_SYM:
7841 			case DTRACEACT_MOD:
7842 				if (!dtrace_priv_kernel(state))
7843 					continue;
7844 				break;
7845 
7846 			case DTRACEACT_USYM:
7847 			case DTRACEACT_UMOD:
7848 			case DTRACEACT_UADDR: {
7849 #ifdef illumos
7850 				struct pid *pid = curthread->t_procp->p_pidp;
7851 #endif
7852 
7853 				if (!dtrace_priv_proc(state))
7854 					continue;
7855 
7856 				DTRACE_STORE(uint64_t, tomax,
7857 #ifdef illumos
7858 				    valoffs, (uint64_t)pid->pid_id);
7859 #else
7860 				    valoffs, (uint64_t) curproc->p_pid);
7861 #endif
7862 				DTRACE_STORE(uint64_t, tomax,
7863 				    valoffs + sizeof (uint64_t), val);
7864 
7865 				continue;
7866 			}
7867 
7868 			case DTRACEACT_EXIT: {
7869 				/*
7870 				 * For the exit action, we are going to attempt
7871 				 * to atomically set our activity to be
7872 				 * draining.  If this fails (either because
7873 				 * another CPU has beat us to the exit action,
7874 				 * or because our current activity is something
7875 				 * other than ACTIVE or WARMUP), we will
7876 				 * continue.  This assures that the exit action
7877 				 * can be successfully recorded at most once
7878 				 * when we're in the ACTIVE state.  If we're
7879 				 * encountering the exit() action while in
7880 				 * COOLDOWN, however, we want to honor the new
7881 				 * status code.  (We know that we're the only
7882 				 * thread in COOLDOWN, so there is no race.)
7883 				 */
7884 				void *activity = &state->dts_activity;
7885 				dtrace_activity_t curstate = state->dts_activity;
7886 
7887 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7888 					break;
7889 
7890 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7891 					curstate = DTRACE_ACTIVITY_ACTIVE;
7892 
7893 				if (dtrace_cas32(activity, curstate,
7894 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7895 					*flags |= CPU_DTRACE_DROP;
7896 					continue;
7897 				}
7898 
7899 				break;
7900 			}
7901 
7902 			default:
7903 				ASSERT(0);
7904 			}
7905 
7906 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7907 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7908 				uintptr_t end = valoffs + size;
7909 
7910 				if (tracememsize != 0 &&
7911 				    valoffs + tracememsize < end) {
7912 					end = valoffs + tracememsize;
7913 					tracememsize = 0;
7914 				}
7915 
7916 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7917 				    !dtrace_vcanload((void *)(uintptr_t)val,
7918 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7919 					continue;
7920 
7921 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7922 				    &val, end, act->dta_intuple,
7923 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7924 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7925 				continue;
7926 			}
7927 
7928 			switch (size) {
7929 			case 0:
7930 				break;
7931 
7932 			case sizeof (uint8_t):
7933 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7934 				break;
7935 			case sizeof (uint16_t):
7936 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7937 				break;
7938 			case sizeof (uint32_t):
7939 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7940 				break;
7941 			case sizeof (uint64_t):
7942 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7943 				break;
7944 			default:
7945 				/*
7946 				 * Any other size should have been returned by
7947 				 * reference, not by value.
7948 				 */
7949 				ASSERT(0);
7950 				break;
7951 			}
7952 		}
7953 
7954 		if (*flags & CPU_DTRACE_DROP)
7955 			continue;
7956 
7957 		if (*flags & CPU_DTRACE_FAULT) {
7958 			int ndx;
7959 			dtrace_action_t *err;
7960 
7961 			buf->dtb_errors++;
7962 
7963 			if (probe->dtpr_id == dtrace_probeid_error) {
7964 				/*
7965 				 * There's nothing we can do -- we had an
7966 				 * error on the error probe.  We bump an
7967 				 * error counter to at least indicate that
7968 				 * this condition happened.
7969 				 */
7970 				dtrace_error(&state->dts_dblerrors);
7971 				continue;
7972 			}
7973 
7974 			if (vtime) {
7975 				/*
7976 				 * Before recursing on dtrace_probe(), we
7977 				 * need to explicitly clear out our start
7978 				 * time to prevent it from being accumulated
7979 				 * into t_dtrace_vtime.
7980 				 */
7981 				curthread->t_dtrace_start = 0;
7982 			}
7983 
7984 			/*
7985 			 * Iterate over the actions to figure out which action
7986 			 * we were processing when we experienced the error.
7987 			 * Note that act points _past_ the faulting action; if
7988 			 * act is ecb->dte_action, the fault was in the
7989 			 * predicate, if it's ecb->dte_action->dta_next it's
7990 			 * in action #1, and so on.
7991 			 */
7992 			for (err = ecb->dte_action, ndx = 0;
7993 			    err != act; err = err->dta_next, ndx++)
7994 				continue;
7995 
7996 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7997 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7998 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7999 			    cpu_core[cpuid].cpuc_dtrace_illval);
8000 
8001 			continue;
8002 		}
8003 
8004 		if (!committed)
8005 			buf->dtb_offset = offs + ecb->dte_size;
8006 	}
8007 
8008 	if (vtime)
8009 		curthread->t_dtrace_start = dtrace_gethrtime();
8010 
8011 	dtrace_probe_exit(cookie);
8012 }
8013 
8014 /*
8015  * DTrace Probe Hashing Functions
8016  *
8017  * The functions in this section (and indeed, the functions in remaining
8018  * sections) are not _called_ from probe context.  (Any exceptions to this are
8019  * marked with a "Note:".)  Rather, they are called from elsewhere in the
8020  * DTrace framework to look-up probes in, add probes to and remove probes from
8021  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8022  * probe tuple -- allowing for fast lookups, regardless of what was
8023  * specified.)
8024  */
8025 static uint_t
8026 dtrace_hash_str(const char *p)
8027 {
8028 	unsigned int g;
8029 	uint_t hval = 0;
8030 
8031 	while (*p) {
8032 		hval = (hval << 4) + *p++;
8033 		if ((g = (hval & 0xf0000000)) != 0)
8034 			hval ^= g >> 24;
8035 		hval &= ~g;
8036 	}
8037 	return (hval);
8038 }
8039 
8040 static dtrace_hash_t *
8041 dtrace_hash_create(size_t stroffs, size_t nextoffs, size_t prevoffs)
8042 {
8043 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8044 
8045 	hash->dth_stroffs = stroffs;
8046 	hash->dth_nextoffs = nextoffs;
8047 	hash->dth_prevoffs = prevoffs;
8048 
8049 	hash->dth_size = 1;
8050 	hash->dth_mask = hash->dth_size - 1;
8051 
8052 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8053 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8054 
8055 	return (hash);
8056 }
8057 
8058 static void
8059 dtrace_hash_destroy(dtrace_hash_t *hash)
8060 {
8061 #ifdef DEBUG
8062 	int i;
8063 
8064 	for (i = 0; i < hash->dth_size; i++)
8065 		ASSERT(hash->dth_tab[i] == NULL);
8066 #endif
8067 
8068 	kmem_free(hash->dth_tab,
8069 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8070 	kmem_free(hash, sizeof (dtrace_hash_t));
8071 }
8072 
8073 static void
8074 dtrace_hash_resize(dtrace_hash_t *hash)
8075 {
8076 	int size = hash->dth_size, i, ndx;
8077 	int new_size = hash->dth_size << 1;
8078 	int new_mask = new_size - 1;
8079 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8080 
8081 	ASSERT((new_size & new_mask) == 0);
8082 
8083 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8084 
8085 	for (i = 0; i < size; i++) {
8086 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8087 			dtrace_probe_t *probe = bucket->dthb_chain;
8088 
8089 			ASSERT(probe != NULL);
8090 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8091 
8092 			next = bucket->dthb_next;
8093 			bucket->dthb_next = new_tab[ndx];
8094 			new_tab[ndx] = bucket;
8095 		}
8096 	}
8097 
8098 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8099 	hash->dth_tab = new_tab;
8100 	hash->dth_size = new_size;
8101 	hash->dth_mask = new_mask;
8102 }
8103 
8104 static void
8105 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8106 {
8107 	int hashval = DTRACE_HASHSTR(hash, new);
8108 	int ndx = hashval & hash->dth_mask;
8109 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8110 	dtrace_probe_t **nextp, **prevp;
8111 
8112 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8113 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8114 			goto add;
8115 	}
8116 
8117 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8118 		dtrace_hash_resize(hash);
8119 		dtrace_hash_add(hash, new);
8120 		return;
8121 	}
8122 
8123 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8124 	bucket->dthb_next = hash->dth_tab[ndx];
8125 	hash->dth_tab[ndx] = bucket;
8126 	hash->dth_nbuckets++;
8127 
8128 add:
8129 	nextp = DTRACE_HASHNEXT(hash, new);
8130 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8131 	*nextp = bucket->dthb_chain;
8132 
8133 	if (bucket->dthb_chain != NULL) {
8134 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8135 		ASSERT(*prevp == NULL);
8136 		*prevp = new;
8137 	}
8138 
8139 	bucket->dthb_chain = new;
8140 	bucket->dthb_len++;
8141 }
8142 
8143 static dtrace_probe_t *
8144 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8145 {
8146 	int hashval = DTRACE_HASHSTR(hash, template);
8147 	int ndx = hashval & hash->dth_mask;
8148 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8149 
8150 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8151 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8152 			return (bucket->dthb_chain);
8153 	}
8154 
8155 	return (NULL);
8156 }
8157 
8158 static int
8159 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8160 {
8161 	int hashval = DTRACE_HASHSTR(hash, template);
8162 	int ndx = hashval & hash->dth_mask;
8163 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8164 
8165 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8166 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8167 			return (bucket->dthb_len);
8168 	}
8169 
8170 	return (0);
8171 }
8172 
8173 static void
8174 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8175 {
8176 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8177 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8178 
8179 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8180 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8181 
8182 	/*
8183 	 * Find the bucket that we're removing this probe from.
8184 	 */
8185 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8186 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8187 			break;
8188 	}
8189 
8190 	ASSERT(bucket != NULL);
8191 
8192 	if (*prevp == NULL) {
8193 		if (*nextp == NULL) {
8194 			/*
8195 			 * The removed probe was the only probe on this
8196 			 * bucket; we need to remove the bucket.
8197 			 */
8198 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8199 
8200 			ASSERT(bucket->dthb_chain == probe);
8201 			ASSERT(b != NULL);
8202 
8203 			if (b == bucket) {
8204 				hash->dth_tab[ndx] = bucket->dthb_next;
8205 			} else {
8206 				while (b->dthb_next != bucket)
8207 					b = b->dthb_next;
8208 				b->dthb_next = bucket->dthb_next;
8209 			}
8210 
8211 			ASSERT(hash->dth_nbuckets > 0);
8212 			hash->dth_nbuckets--;
8213 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8214 			return;
8215 		}
8216 
8217 		bucket->dthb_chain = *nextp;
8218 	} else {
8219 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8220 	}
8221 
8222 	if (*nextp != NULL)
8223 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8224 }
8225 
8226 /*
8227  * DTrace Utility Functions
8228  *
8229  * These are random utility functions that are _not_ called from probe context.
8230  */
8231 static int
8232 dtrace_badattr(const dtrace_attribute_t *a)
8233 {
8234 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8235 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8236 	    a->dtat_class > DTRACE_CLASS_MAX);
8237 }
8238 
8239 /*
8240  * Return a duplicate copy of a string.  If the specified string is NULL,
8241  * this function returns a zero-length string.
8242  */
8243 static char *
8244 dtrace_strdup(const char *str)
8245 {
8246 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8247 
8248 	if (str != NULL)
8249 		(void) strcpy(new, str);
8250 
8251 	return (new);
8252 }
8253 
8254 #define	DTRACE_ISALPHA(c)	\
8255 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8256 
8257 static int
8258 dtrace_badname(const char *s)
8259 {
8260 	char c;
8261 
8262 	if (s == NULL || (c = *s++) == '\0')
8263 		return (0);
8264 
8265 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8266 		return (1);
8267 
8268 	while ((c = *s++) != '\0') {
8269 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8270 		    c != '-' && c != '_' && c != '.' && c != '`')
8271 			return (1);
8272 	}
8273 
8274 	return (0);
8275 }
8276 
8277 static void
8278 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8279 {
8280 	uint32_t priv;
8281 
8282 #ifdef illumos
8283 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8284 		/*
8285 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8286 		 */
8287 		priv = DTRACE_PRIV_ALL;
8288 	} else {
8289 		*uidp = crgetuid(cr);
8290 		*zoneidp = crgetzoneid(cr);
8291 
8292 		priv = 0;
8293 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8294 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8295 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8296 			priv |= DTRACE_PRIV_USER;
8297 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8298 			priv |= DTRACE_PRIV_PROC;
8299 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8300 			priv |= DTRACE_PRIV_OWNER;
8301 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8302 			priv |= DTRACE_PRIV_ZONEOWNER;
8303 	}
8304 #else
8305 	priv = DTRACE_PRIV_ALL;
8306 #endif
8307 
8308 	*privp = priv;
8309 }
8310 
8311 #ifdef DTRACE_ERRDEBUG
8312 static void
8313 dtrace_errdebug(const char *str)
8314 {
8315 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8316 	int occupied = 0;
8317 
8318 	mutex_enter(&dtrace_errlock);
8319 	dtrace_errlast = str;
8320 	dtrace_errthread = curthread;
8321 
8322 	while (occupied++ < DTRACE_ERRHASHSZ) {
8323 		if (dtrace_errhash[hval].dter_msg == str) {
8324 			dtrace_errhash[hval].dter_count++;
8325 			goto out;
8326 		}
8327 
8328 		if (dtrace_errhash[hval].dter_msg != NULL) {
8329 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8330 			continue;
8331 		}
8332 
8333 		dtrace_errhash[hval].dter_msg = str;
8334 		dtrace_errhash[hval].dter_count = 1;
8335 		goto out;
8336 	}
8337 
8338 	panic("dtrace: undersized error hash");
8339 out:
8340 	mutex_exit(&dtrace_errlock);
8341 }
8342 #endif
8343 
8344 /*
8345  * DTrace Matching Functions
8346  *
8347  * These functions are used to match groups of probes, given some elements of
8348  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8349  */
8350 static int
8351 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8352     zoneid_t zoneid)
8353 {
8354 	if (priv != DTRACE_PRIV_ALL) {
8355 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8356 		uint32_t match = priv & ppriv;
8357 
8358 		/*
8359 		 * No PRIV_DTRACE_* privileges...
8360 		 */
8361 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8362 		    DTRACE_PRIV_KERNEL)) == 0)
8363 			return (0);
8364 
8365 		/*
8366 		 * No matching bits, but there were bits to match...
8367 		 */
8368 		if (match == 0 && ppriv != 0)
8369 			return (0);
8370 
8371 		/*
8372 		 * Need to have permissions to the process, but don't...
8373 		 */
8374 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8375 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8376 			return (0);
8377 		}
8378 
8379 		/*
8380 		 * Need to be in the same zone unless we possess the
8381 		 * privilege to examine all zones.
8382 		 */
8383 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8384 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8385 			return (0);
8386 		}
8387 	}
8388 
8389 	return (1);
8390 }
8391 
8392 /*
8393  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8394  * consists of input pattern strings and an ops-vector to evaluate them.
8395  * This function returns >0 for match, 0 for no match, and <0 for error.
8396  */
8397 static int
8398 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8399     uint32_t priv, uid_t uid, zoneid_t zoneid)
8400 {
8401 	dtrace_provider_t *pvp = prp->dtpr_provider;
8402 	int rv;
8403 
8404 	if (pvp->dtpv_defunct)
8405 		return (0);
8406 
8407 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8408 		return (rv);
8409 
8410 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8411 		return (rv);
8412 
8413 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8414 		return (rv);
8415 
8416 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8417 		return (rv);
8418 
8419 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8420 		return (0);
8421 
8422 	return (rv);
8423 }
8424 
8425 /*
8426  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8427  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8428  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8429  * In addition, all of the recursion cases except for '*' matching have been
8430  * unwound.  For '*', we still implement recursive evaluation, but a depth
8431  * counter is maintained and matching is aborted if we recurse too deep.
8432  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8433  */
8434 static int
8435 dtrace_match_glob(const char *s, const char *p, int depth)
8436 {
8437 	const char *olds;
8438 	char s1, c;
8439 	int gs;
8440 
8441 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8442 		return (-1);
8443 
8444 	if (s == NULL)
8445 		s = ""; /* treat NULL as empty string */
8446 
8447 top:
8448 	olds = s;
8449 	s1 = *s++;
8450 
8451 	if (p == NULL)
8452 		return (0);
8453 
8454 	if ((c = *p++) == '\0')
8455 		return (s1 == '\0');
8456 
8457 	switch (c) {
8458 	case '[': {
8459 		int ok = 0, notflag = 0;
8460 		char lc = '\0';
8461 
8462 		if (s1 == '\0')
8463 			return (0);
8464 
8465 		if (*p == '!') {
8466 			notflag = 1;
8467 			p++;
8468 		}
8469 
8470 		if ((c = *p++) == '\0')
8471 			return (0);
8472 
8473 		do {
8474 			if (c == '-' && lc != '\0' && *p != ']') {
8475 				if ((c = *p++) == '\0')
8476 					return (0);
8477 				if (c == '\\' && (c = *p++) == '\0')
8478 					return (0);
8479 
8480 				if (notflag) {
8481 					if (s1 < lc || s1 > c)
8482 						ok++;
8483 					else
8484 						return (0);
8485 				} else if (lc <= s1 && s1 <= c)
8486 					ok++;
8487 
8488 			} else if (c == '\\' && (c = *p++) == '\0')
8489 				return (0);
8490 
8491 			lc = c; /* save left-hand 'c' for next iteration */
8492 
8493 			if (notflag) {
8494 				if (s1 != c)
8495 					ok++;
8496 				else
8497 					return (0);
8498 			} else if (s1 == c)
8499 				ok++;
8500 
8501 			if ((c = *p++) == '\0')
8502 				return (0);
8503 
8504 		} while (c != ']');
8505 
8506 		if (ok)
8507 			goto top;
8508 
8509 		return (0);
8510 	}
8511 
8512 	case '\\':
8513 		if ((c = *p++) == '\0')
8514 			return (0);
8515 		/*FALLTHRU*/
8516 
8517 	default:
8518 		if (c != s1)
8519 			return (0);
8520 		/*FALLTHRU*/
8521 
8522 	case '?':
8523 		if (s1 != '\0')
8524 			goto top;
8525 		return (0);
8526 
8527 	case '*':
8528 		while (*p == '*')
8529 			p++; /* consecutive *'s are identical to a single one */
8530 
8531 		if (*p == '\0')
8532 			return (1);
8533 
8534 		for (s = olds; *s != '\0'; s++) {
8535 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8536 				return (gs);
8537 		}
8538 
8539 		return (0);
8540 	}
8541 }
8542 
8543 /*ARGSUSED*/
8544 static int
8545 dtrace_match_string(const char *s, const char *p, int depth)
8546 {
8547 	return (s != NULL && strcmp(s, p) == 0);
8548 }
8549 
8550 /*ARGSUSED*/
8551 static int
8552 dtrace_match_nul(const char *s, const char *p, int depth)
8553 {
8554 	return (1); /* always match the empty pattern */
8555 }
8556 
8557 /*ARGSUSED*/
8558 static int
8559 dtrace_match_nonzero(const char *s, const char *p, int depth)
8560 {
8561 	return (s != NULL && s[0] != '\0');
8562 }
8563 
8564 static int
8565 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8566     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8567 {
8568 	dtrace_probe_t template, *probe;
8569 	dtrace_hash_t *hash = NULL;
8570 	int len, best = INT_MAX, nmatched = 0;
8571 	dtrace_id_t i;
8572 
8573 	ASSERT(MUTEX_HELD(&dtrace_lock));
8574 
8575 	/*
8576 	 * If the probe ID is specified in the key, just lookup by ID and
8577 	 * invoke the match callback once if a matching probe is found.
8578 	 */
8579 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8580 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8581 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8582 			(void) (*matched)(probe, arg);
8583 			nmatched++;
8584 		}
8585 		return (nmatched);
8586 	}
8587 
8588 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8589 	template.dtpr_func = (char *)pkp->dtpk_func;
8590 	template.dtpr_name = (char *)pkp->dtpk_name;
8591 
8592 	/*
8593 	 * We want to find the most distinct of the module name, function
8594 	 * name, and name.  So for each one that is not a glob pattern or
8595 	 * empty string, we perform a lookup in the corresponding hash and
8596 	 * use the hash table with the fewest collisions to do our search.
8597 	 */
8598 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8599 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8600 		best = len;
8601 		hash = dtrace_bymod;
8602 	}
8603 
8604 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8605 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8606 		best = len;
8607 		hash = dtrace_byfunc;
8608 	}
8609 
8610 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8611 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8612 		best = len;
8613 		hash = dtrace_byname;
8614 	}
8615 
8616 	/*
8617 	 * If we did not select a hash table, iterate over every probe and
8618 	 * invoke our callback for each one that matches our input probe key.
8619 	 */
8620 	if (hash == NULL) {
8621 		for (i = 0; i < dtrace_nprobes; i++) {
8622 			if ((probe = dtrace_probes[i]) == NULL ||
8623 			    dtrace_match_probe(probe, pkp, priv, uid,
8624 			    zoneid) <= 0)
8625 				continue;
8626 
8627 			nmatched++;
8628 
8629 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8630 				break;
8631 		}
8632 
8633 		return (nmatched);
8634 	}
8635 
8636 	/*
8637 	 * If we selected a hash table, iterate over each probe of the same key
8638 	 * name and invoke the callback for every probe that matches the other
8639 	 * attributes of our input probe key.
8640 	 */
8641 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8642 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8643 
8644 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8645 			continue;
8646 
8647 		nmatched++;
8648 
8649 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8650 			break;
8651 	}
8652 
8653 	return (nmatched);
8654 }
8655 
8656 /*
8657  * Return the function pointer dtrace_probecmp() should use to compare the
8658  * specified pattern with a string.  For NULL or empty patterns, we select
8659  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8660  * For non-empty non-glob strings, we use dtrace_match_string().
8661  */
8662 static dtrace_probekey_f *
8663 dtrace_probekey_func(const char *p)
8664 {
8665 	char c;
8666 
8667 	if (p == NULL || *p == '\0')
8668 		return (&dtrace_match_nul);
8669 
8670 	while ((c = *p++) != '\0') {
8671 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8672 			return (&dtrace_match_glob);
8673 	}
8674 
8675 	return (&dtrace_match_string);
8676 }
8677 
8678 /*
8679  * Build a probe comparison key for use with dtrace_match_probe() from the
8680  * given probe description.  By convention, a null key only matches anchored
8681  * probes: if each field is the empty string, reset dtpk_fmatch to
8682  * dtrace_match_nonzero().
8683  */
8684 static void
8685 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8686 {
8687 	pkp->dtpk_prov = pdp->dtpd_provider;
8688 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8689 
8690 	pkp->dtpk_mod = pdp->dtpd_mod;
8691 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8692 
8693 	pkp->dtpk_func = pdp->dtpd_func;
8694 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8695 
8696 	pkp->dtpk_name = pdp->dtpd_name;
8697 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8698 
8699 	pkp->dtpk_id = pdp->dtpd_id;
8700 
8701 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8702 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8703 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8704 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8705 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8706 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8707 }
8708 
8709 /*
8710  * DTrace Provider-to-Framework API Functions
8711  *
8712  * These functions implement much of the Provider-to-Framework API, as
8713  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8714  * the functions in the API for probe management (found below), and
8715  * dtrace_probe() itself (found above).
8716  */
8717 
8718 /*
8719  * Register the calling provider with the DTrace framework.  This should
8720  * generally be called by DTrace providers in their attach(9E) entry point.
8721  */
8722 int
8723 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8724     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8725 {
8726 	dtrace_provider_t *provider;
8727 
8728 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8729 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8730 		    "arguments", name ? name : "<NULL>");
8731 		return (EINVAL);
8732 	}
8733 
8734 	if (name[0] == '\0' || dtrace_badname(name)) {
8735 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8736 		    "provider name", name);
8737 		return (EINVAL);
8738 	}
8739 
8740 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8741 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8742 	    pops->dtps_destroy == NULL ||
8743 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8744 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8745 		    "provider ops", name);
8746 		return (EINVAL);
8747 	}
8748 
8749 	if (dtrace_badattr(&pap->dtpa_provider) ||
8750 	    dtrace_badattr(&pap->dtpa_mod) ||
8751 	    dtrace_badattr(&pap->dtpa_func) ||
8752 	    dtrace_badattr(&pap->dtpa_name) ||
8753 	    dtrace_badattr(&pap->dtpa_args)) {
8754 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8755 		    "provider attributes", name);
8756 		return (EINVAL);
8757 	}
8758 
8759 	if (priv & ~DTRACE_PRIV_ALL) {
8760 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8761 		    "privilege attributes", name);
8762 		return (EINVAL);
8763 	}
8764 
8765 	if ((priv & DTRACE_PRIV_KERNEL) &&
8766 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8767 	    pops->dtps_usermode == NULL) {
8768 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8769 		    "dtps_usermode() op for given privilege attributes", name);
8770 		return (EINVAL);
8771 	}
8772 
8773 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8774 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8775 	(void) strcpy(provider->dtpv_name, name);
8776 
8777 	provider->dtpv_attr = *pap;
8778 	provider->dtpv_priv.dtpp_flags = priv;
8779 	if (cr != NULL) {
8780 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8781 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8782 	}
8783 	provider->dtpv_pops = *pops;
8784 
8785 	if (pops->dtps_provide == NULL) {
8786 		ASSERT(pops->dtps_provide_module != NULL);
8787 		provider->dtpv_pops.dtps_provide =
8788 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8789 	}
8790 
8791 	if (pops->dtps_provide_module == NULL) {
8792 		ASSERT(pops->dtps_provide != NULL);
8793 		provider->dtpv_pops.dtps_provide_module =
8794 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8795 	}
8796 
8797 	if (pops->dtps_suspend == NULL) {
8798 		ASSERT(pops->dtps_resume == NULL);
8799 		provider->dtpv_pops.dtps_suspend =
8800 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8801 		provider->dtpv_pops.dtps_resume =
8802 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8803 	}
8804 
8805 	provider->dtpv_arg = arg;
8806 	*idp = (dtrace_provider_id_t)provider;
8807 
8808 	if (pops == &dtrace_provider_ops) {
8809 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8810 		ASSERT(MUTEX_HELD(&dtrace_lock));
8811 		ASSERT(dtrace_anon.dta_enabling == NULL);
8812 
8813 		/*
8814 		 * We make sure that the DTrace provider is at the head of
8815 		 * the provider chain.
8816 		 */
8817 		provider->dtpv_next = dtrace_provider;
8818 		dtrace_provider = provider;
8819 		return (0);
8820 	}
8821 
8822 	mutex_enter(&dtrace_provider_lock);
8823 	mutex_enter(&dtrace_lock);
8824 
8825 	/*
8826 	 * If there is at least one provider registered, we'll add this
8827 	 * provider after the first provider.
8828 	 */
8829 	if (dtrace_provider != NULL) {
8830 		provider->dtpv_next = dtrace_provider->dtpv_next;
8831 		dtrace_provider->dtpv_next = provider;
8832 	} else {
8833 		dtrace_provider = provider;
8834 	}
8835 
8836 	if (dtrace_retained != NULL) {
8837 		dtrace_enabling_provide(provider);
8838 
8839 		/*
8840 		 * Now we need to call dtrace_enabling_matchall() -- which
8841 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8842 		 * to drop all of our locks before calling into it...
8843 		 */
8844 		mutex_exit(&dtrace_lock);
8845 		mutex_exit(&dtrace_provider_lock);
8846 		dtrace_enabling_matchall();
8847 
8848 		return (0);
8849 	}
8850 
8851 	mutex_exit(&dtrace_lock);
8852 	mutex_exit(&dtrace_provider_lock);
8853 
8854 	return (0);
8855 }
8856 
8857 /*
8858  * Unregister the specified provider from the DTrace framework.  This should
8859  * generally be called by DTrace providers in their detach(9E) entry point.
8860  */
8861 int
8862 dtrace_unregister(dtrace_provider_id_t id)
8863 {
8864 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8865 	dtrace_provider_t *prev = NULL;
8866 	int i, self = 0, noreap = 0;
8867 	dtrace_probe_t *probe, *first = NULL;
8868 
8869 	if (old->dtpv_pops.dtps_enable ==
8870 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8871 		/*
8872 		 * If DTrace itself is the provider, we're called with locks
8873 		 * already held.
8874 		 */
8875 		ASSERT(old == dtrace_provider);
8876 #ifdef illumos
8877 		ASSERT(dtrace_devi != NULL);
8878 #endif
8879 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8880 		ASSERT(MUTEX_HELD(&dtrace_lock));
8881 		self = 1;
8882 
8883 		if (dtrace_provider->dtpv_next != NULL) {
8884 			/*
8885 			 * There's another provider here; return failure.
8886 			 */
8887 			return (EBUSY);
8888 		}
8889 	} else {
8890 		mutex_enter(&dtrace_provider_lock);
8891 #ifdef illumos
8892 		mutex_enter(&mod_lock);
8893 #endif
8894 		mutex_enter(&dtrace_lock);
8895 	}
8896 
8897 	/*
8898 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8899 	 * probes, we refuse to let providers slither away, unless this
8900 	 * provider has already been explicitly invalidated.
8901 	 */
8902 	if (!old->dtpv_defunct &&
8903 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8904 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8905 		if (!self) {
8906 			mutex_exit(&dtrace_lock);
8907 #ifdef illumos
8908 			mutex_exit(&mod_lock);
8909 #endif
8910 			mutex_exit(&dtrace_provider_lock);
8911 		}
8912 		return (EBUSY);
8913 	}
8914 
8915 	/*
8916 	 * Attempt to destroy the probes associated with this provider.
8917 	 */
8918 	for (i = 0; i < dtrace_nprobes; i++) {
8919 		if ((probe = dtrace_probes[i]) == NULL)
8920 			continue;
8921 
8922 		if (probe->dtpr_provider != old)
8923 			continue;
8924 
8925 		if (probe->dtpr_ecb == NULL)
8926 			continue;
8927 
8928 		/*
8929 		 * If we are trying to unregister a defunct provider, and the
8930 		 * provider was made defunct within the interval dictated by
8931 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8932 		 * attempt to reap our enablings.  To denote that the provider
8933 		 * should reattempt to unregister itself at some point in the
8934 		 * future, we will return a differentiable error code (EAGAIN
8935 		 * instead of EBUSY) in this case.
8936 		 */
8937 		if (dtrace_gethrtime() - old->dtpv_defunct >
8938 		    dtrace_unregister_defunct_reap)
8939 			noreap = 1;
8940 
8941 		if (!self) {
8942 			mutex_exit(&dtrace_lock);
8943 #ifdef illumos
8944 			mutex_exit(&mod_lock);
8945 #endif
8946 			mutex_exit(&dtrace_provider_lock);
8947 		}
8948 
8949 		if (noreap)
8950 			return (EBUSY);
8951 
8952 		(void) taskq_dispatch(dtrace_taskq,
8953 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8954 
8955 		return (EAGAIN);
8956 	}
8957 
8958 	/*
8959 	 * All of the probes for this provider are disabled; we can safely
8960 	 * remove all of them from their hash chains and from the probe array.
8961 	 */
8962 	for (i = 0; i < dtrace_nprobes; i++) {
8963 		if ((probe = dtrace_probes[i]) == NULL)
8964 			continue;
8965 
8966 		if (probe->dtpr_provider != old)
8967 			continue;
8968 
8969 		dtrace_probes[i] = NULL;
8970 
8971 		dtrace_hash_remove(dtrace_bymod, probe);
8972 		dtrace_hash_remove(dtrace_byfunc, probe);
8973 		dtrace_hash_remove(dtrace_byname, probe);
8974 
8975 		if (first == NULL) {
8976 			first = probe;
8977 			probe->dtpr_nextmod = NULL;
8978 		} else {
8979 			probe->dtpr_nextmod = first;
8980 			first = probe;
8981 		}
8982 	}
8983 
8984 	/*
8985 	 * The provider's probes have been removed from the hash chains and
8986 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8987 	 * everyone has cleared out from any probe array processing.
8988 	 */
8989 	dtrace_sync();
8990 
8991 	for (probe = first; probe != NULL; probe = first) {
8992 		first = probe->dtpr_nextmod;
8993 
8994 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8995 		    probe->dtpr_arg);
8996 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8997 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8998 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8999 #ifdef illumos
9000 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
9001 #else
9002 		free_unr(dtrace_arena, probe->dtpr_id);
9003 #endif
9004 		kmem_free(probe, sizeof (dtrace_probe_t));
9005 	}
9006 
9007 	if ((prev = dtrace_provider) == old) {
9008 #ifdef illumos
9009 		ASSERT(self || dtrace_devi == NULL);
9010 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9011 #endif
9012 		dtrace_provider = old->dtpv_next;
9013 	} else {
9014 		while (prev != NULL && prev->dtpv_next != old)
9015 			prev = prev->dtpv_next;
9016 
9017 		if (prev == NULL) {
9018 			panic("attempt to unregister non-existent "
9019 			    "dtrace provider %p\n", (void *)id);
9020 		}
9021 
9022 		prev->dtpv_next = old->dtpv_next;
9023 	}
9024 
9025 	if (!self) {
9026 		mutex_exit(&dtrace_lock);
9027 #ifdef illumos
9028 		mutex_exit(&mod_lock);
9029 #endif
9030 		mutex_exit(&dtrace_provider_lock);
9031 	}
9032 
9033 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9034 	kmem_free(old, sizeof (dtrace_provider_t));
9035 
9036 	return (0);
9037 }
9038 
9039 /*
9040  * Invalidate the specified provider.  All subsequent probe lookups for the
9041  * specified provider will fail, but its probes will not be removed.
9042  */
9043 void
9044 dtrace_invalidate(dtrace_provider_id_t id)
9045 {
9046 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9047 
9048 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9049 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9050 
9051 	mutex_enter(&dtrace_provider_lock);
9052 	mutex_enter(&dtrace_lock);
9053 
9054 	pvp->dtpv_defunct = dtrace_gethrtime();
9055 
9056 	mutex_exit(&dtrace_lock);
9057 	mutex_exit(&dtrace_provider_lock);
9058 }
9059 
9060 /*
9061  * Indicate whether or not DTrace has attached.
9062  */
9063 int
9064 dtrace_attached(void)
9065 {
9066 	/*
9067 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9068 	 * attached.  (It's non-NULL because DTrace is always itself a
9069 	 * provider.)
9070 	 */
9071 	return (dtrace_provider != NULL);
9072 }
9073 
9074 /*
9075  * Remove all the unenabled probes for the given provider.  This function is
9076  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9077  * -- just as many of its associated probes as it can.
9078  */
9079 int
9080 dtrace_condense(dtrace_provider_id_t id)
9081 {
9082 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9083 	int i;
9084 	dtrace_probe_t *probe;
9085 
9086 	/*
9087 	 * Make sure this isn't the dtrace provider itself.
9088 	 */
9089 	ASSERT(prov->dtpv_pops.dtps_enable !=
9090 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9091 
9092 	mutex_enter(&dtrace_provider_lock);
9093 	mutex_enter(&dtrace_lock);
9094 
9095 	/*
9096 	 * Attempt to destroy the probes associated with this provider.
9097 	 */
9098 	for (i = 0; i < dtrace_nprobes; i++) {
9099 		if ((probe = dtrace_probes[i]) == NULL)
9100 			continue;
9101 
9102 		if (probe->dtpr_provider != prov)
9103 			continue;
9104 
9105 		if (probe->dtpr_ecb != NULL)
9106 			continue;
9107 
9108 		dtrace_probes[i] = NULL;
9109 
9110 		dtrace_hash_remove(dtrace_bymod, probe);
9111 		dtrace_hash_remove(dtrace_byfunc, probe);
9112 		dtrace_hash_remove(dtrace_byname, probe);
9113 
9114 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9115 		    probe->dtpr_arg);
9116 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9117 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9118 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9119 		kmem_free(probe, sizeof (dtrace_probe_t));
9120 #ifdef illumos
9121 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9122 #else
9123 		free_unr(dtrace_arena, i + 1);
9124 #endif
9125 	}
9126 
9127 	mutex_exit(&dtrace_lock);
9128 	mutex_exit(&dtrace_provider_lock);
9129 
9130 	return (0);
9131 }
9132 
9133 /*
9134  * DTrace Probe Management Functions
9135  *
9136  * The functions in this section perform the DTrace probe management,
9137  * including functions to create probes, look-up probes, and call into the
9138  * providers to request that probes be provided.  Some of these functions are
9139  * in the Provider-to-Framework API; these functions can be identified by the
9140  * fact that they are not declared "static".
9141  */
9142 
9143 /*
9144  * Create a probe with the specified module name, function name, and name.
9145  */
9146 dtrace_id_t
9147 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9148     const char *func, const char *name, int aframes, void *arg)
9149 {
9150 	dtrace_probe_t *probe, **probes;
9151 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9152 	dtrace_id_t id;
9153 
9154 	if (provider == dtrace_provider) {
9155 		ASSERT(MUTEX_HELD(&dtrace_lock));
9156 	} else {
9157 		mutex_enter(&dtrace_lock);
9158 	}
9159 
9160 #ifdef illumos
9161 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9162 	    VM_BESTFIT | VM_SLEEP);
9163 #else
9164 	id = alloc_unr(dtrace_arena);
9165 #endif
9166 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9167 
9168 	probe->dtpr_id = id;
9169 	probe->dtpr_gen = dtrace_probegen++;
9170 	probe->dtpr_mod = dtrace_strdup(mod);
9171 	probe->dtpr_func = dtrace_strdup(func);
9172 	probe->dtpr_name = dtrace_strdup(name);
9173 	probe->dtpr_arg = arg;
9174 	probe->dtpr_aframes = aframes;
9175 	probe->dtpr_provider = provider;
9176 
9177 	dtrace_hash_add(dtrace_bymod, probe);
9178 	dtrace_hash_add(dtrace_byfunc, probe);
9179 	dtrace_hash_add(dtrace_byname, probe);
9180 
9181 	if (id - 1 >= dtrace_nprobes) {
9182 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9183 		size_t nsize = osize << 1;
9184 
9185 		if (nsize == 0) {
9186 			ASSERT(osize == 0);
9187 			ASSERT(dtrace_probes == NULL);
9188 			nsize = sizeof (dtrace_probe_t *);
9189 		}
9190 
9191 		probes = kmem_zalloc(nsize, KM_SLEEP);
9192 
9193 		if (dtrace_probes == NULL) {
9194 			ASSERT(osize == 0);
9195 			dtrace_probes = probes;
9196 			dtrace_nprobes = 1;
9197 		} else {
9198 			dtrace_probe_t **oprobes = dtrace_probes;
9199 
9200 			bcopy(oprobes, probes, osize);
9201 			dtrace_membar_producer();
9202 			dtrace_probes = probes;
9203 
9204 			dtrace_sync();
9205 
9206 			/*
9207 			 * All CPUs are now seeing the new probes array; we can
9208 			 * safely free the old array.
9209 			 */
9210 			kmem_free(oprobes, osize);
9211 			dtrace_nprobes <<= 1;
9212 		}
9213 
9214 		ASSERT(id - 1 < dtrace_nprobes);
9215 	}
9216 
9217 	ASSERT(dtrace_probes[id - 1] == NULL);
9218 	dtrace_probes[id - 1] = probe;
9219 
9220 	if (provider != dtrace_provider)
9221 		mutex_exit(&dtrace_lock);
9222 
9223 	return (id);
9224 }
9225 
9226 static dtrace_probe_t *
9227 dtrace_probe_lookup_id(dtrace_id_t id)
9228 {
9229 	ASSERT(MUTEX_HELD(&dtrace_lock));
9230 
9231 	if (id == 0 || id > dtrace_nprobes)
9232 		return (NULL);
9233 
9234 	return (dtrace_probes[id - 1]);
9235 }
9236 
9237 static int
9238 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9239 {
9240 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9241 
9242 	return (DTRACE_MATCH_DONE);
9243 }
9244 
9245 /*
9246  * Look up a probe based on provider and one or more of module name, function
9247  * name and probe name.
9248  */
9249 dtrace_id_t
9250 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9251     char *func, char *name)
9252 {
9253 	dtrace_probekey_t pkey;
9254 	dtrace_id_t id;
9255 	int match;
9256 
9257 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9258 	pkey.dtpk_pmatch = &dtrace_match_string;
9259 	pkey.dtpk_mod = mod;
9260 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9261 	pkey.dtpk_func = func;
9262 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9263 	pkey.dtpk_name = name;
9264 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9265 	pkey.dtpk_id = DTRACE_IDNONE;
9266 
9267 	mutex_enter(&dtrace_lock);
9268 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9269 	    dtrace_probe_lookup_match, &id);
9270 	mutex_exit(&dtrace_lock);
9271 
9272 	ASSERT(match == 1 || match == 0);
9273 	return (match ? id : 0);
9274 }
9275 
9276 /*
9277  * Returns the probe argument associated with the specified probe.
9278  */
9279 void *
9280 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9281 {
9282 	dtrace_probe_t *probe;
9283 	void *rval = NULL;
9284 
9285 	mutex_enter(&dtrace_lock);
9286 
9287 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9288 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9289 		rval = probe->dtpr_arg;
9290 
9291 	mutex_exit(&dtrace_lock);
9292 
9293 	return (rval);
9294 }
9295 
9296 /*
9297  * Copy a probe into a probe description.
9298  */
9299 static void
9300 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9301 {
9302 	bzero(pdp, sizeof (dtrace_probedesc_t));
9303 	pdp->dtpd_id = prp->dtpr_id;
9304 
9305 	(void) strncpy(pdp->dtpd_provider,
9306 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9307 
9308 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9309 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9310 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9311 }
9312 
9313 /*
9314  * Called to indicate that a probe -- or probes -- should be provided by a
9315  * specfied provider.  If the specified description is NULL, the provider will
9316  * be told to provide all of its probes.  (This is done whenever a new
9317  * consumer comes along, or whenever a retained enabling is to be matched.) If
9318  * the specified description is non-NULL, the provider is given the
9319  * opportunity to dynamically provide the specified probe, allowing providers
9320  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9321  * probes.)  If the provider is NULL, the operations will be applied to all
9322  * providers; if the provider is non-NULL the operations will only be applied
9323  * to the specified provider.  The dtrace_provider_lock must be held, and the
9324  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9325  * will need to grab the dtrace_lock when it reenters the framework through
9326  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9327  */
9328 static void
9329 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9330 {
9331 #ifdef illumos
9332 	modctl_t *ctl;
9333 #endif
9334 	int all = 0;
9335 
9336 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9337 
9338 	if (prv == NULL) {
9339 		all = 1;
9340 		prv = dtrace_provider;
9341 	}
9342 
9343 	do {
9344 		/*
9345 		 * First, call the blanket provide operation.
9346 		 */
9347 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9348 
9349 #ifdef illumos
9350 		/*
9351 		 * Now call the per-module provide operation.  We will grab
9352 		 * mod_lock to prevent the list from being modified.  Note
9353 		 * that this also prevents the mod_busy bits from changing.
9354 		 * (mod_busy can only be changed with mod_lock held.)
9355 		 */
9356 		mutex_enter(&mod_lock);
9357 
9358 		ctl = &modules;
9359 		do {
9360 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9361 				continue;
9362 
9363 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9364 
9365 		} while ((ctl = ctl->mod_next) != &modules);
9366 
9367 		mutex_exit(&mod_lock);
9368 #endif
9369 	} while (all && (prv = prv->dtpv_next) != NULL);
9370 }
9371 
9372 #ifdef illumos
9373 /*
9374  * Iterate over each probe, and call the Framework-to-Provider API function
9375  * denoted by offs.
9376  */
9377 static void
9378 dtrace_probe_foreach(uintptr_t offs)
9379 {
9380 	dtrace_provider_t *prov;
9381 	void (*func)(void *, dtrace_id_t, void *);
9382 	dtrace_probe_t *probe;
9383 	dtrace_icookie_t cookie;
9384 	int i;
9385 
9386 	/*
9387 	 * We disable interrupts to walk through the probe array.  This is
9388 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9389 	 * won't see stale data.
9390 	 */
9391 	cookie = dtrace_interrupt_disable();
9392 
9393 	for (i = 0; i < dtrace_nprobes; i++) {
9394 		if ((probe = dtrace_probes[i]) == NULL)
9395 			continue;
9396 
9397 		if (probe->dtpr_ecb == NULL) {
9398 			/*
9399 			 * This probe isn't enabled -- don't call the function.
9400 			 */
9401 			continue;
9402 		}
9403 
9404 		prov = probe->dtpr_provider;
9405 		func = *((void(**)(void *, dtrace_id_t, void *))
9406 		    ((uintptr_t)&prov->dtpv_pops + offs));
9407 
9408 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9409 	}
9410 
9411 	dtrace_interrupt_enable(cookie);
9412 }
9413 #endif
9414 
9415 static int
9416 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9417 {
9418 	dtrace_probekey_t pkey;
9419 	uint32_t priv;
9420 	uid_t uid;
9421 	zoneid_t zoneid;
9422 
9423 	ASSERT(MUTEX_HELD(&dtrace_lock));
9424 	dtrace_ecb_create_cache = NULL;
9425 
9426 	if (desc == NULL) {
9427 		/*
9428 		 * If we're passed a NULL description, we're being asked to
9429 		 * create an ECB with a NULL probe.
9430 		 */
9431 		(void) dtrace_ecb_create_enable(NULL, enab);
9432 		return (0);
9433 	}
9434 
9435 	dtrace_probekey(desc, &pkey);
9436 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9437 	    &priv, &uid, &zoneid);
9438 
9439 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9440 	    enab));
9441 }
9442 
9443 /*
9444  * DTrace Helper Provider Functions
9445  */
9446 static void
9447 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9448 {
9449 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9450 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9451 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9452 }
9453 
9454 static void
9455 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9456     const dof_provider_t *dofprov, char *strtab)
9457 {
9458 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9459 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9460 	    dofprov->dofpv_provattr);
9461 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9462 	    dofprov->dofpv_modattr);
9463 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9464 	    dofprov->dofpv_funcattr);
9465 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9466 	    dofprov->dofpv_nameattr);
9467 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9468 	    dofprov->dofpv_argsattr);
9469 }
9470 
9471 static void
9472 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9473 {
9474 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9475 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9476 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9477 	dof_provider_t *provider;
9478 	dof_probe_t *probe;
9479 	uint32_t *off, *enoff;
9480 	uint8_t *arg;
9481 	char *strtab;
9482 	uint_t i, nprobes;
9483 	dtrace_helper_provdesc_t dhpv;
9484 	dtrace_helper_probedesc_t dhpb;
9485 	dtrace_meta_t *meta = dtrace_meta_pid;
9486 	dtrace_mops_t *mops = &meta->dtm_mops;
9487 	void *parg;
9488 
9489 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9490 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9491 	    provider->dofpv_strtab * dof->dofh_secsize);
9492 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9493 	    provider->dofpv_probes * dof->dofh_secsize);
9494 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9495 	    provider->dofpv_prargs * dof->dofh_secsize);
9496 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9497 	    provider->dofpv_proffs * dof->dofh_secsize);
9498 
9499 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9500 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9501 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9502 	enoff = NULL;
9503 
9504 	/*
9505 	 * See dtrace_helper_provider_validate().
9506 	 */
9507 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9508 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9509 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9510 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9511 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9512 	}
9513 
9514 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9515 
9516 	/*
9517 	 * Create the provider.
9518 	 */
9519 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9520 
9521 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9522 		return;
9523 
9524 	meta->dtm_count++;
9525 
9526 	/*
9527 	 * Create the probes.
9528 	 */
9529 	for (i = 0; i < nprobes; i++) {
9530 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9531 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9532 
9533 		/* See the check in dtrace_helper_provider_validate(). */
9534 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9535 			continue;
9536 
9537 		dhpb.dthpb_mod = dhp->dofhp_mod;
9538 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9539 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9540 		dhpb.dthpb_base = probe->dofpr_addr;
9541 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9542 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9543 		if (enoff != NULL) {
9544 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9545 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9546 		} else {
9547 			dhpb.dthpb_enoffs = NULL;
9548 			dhpb.dthpb_nenoffs = 0;
9549 		}
9550 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9551 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9552 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9553 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9554 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9555 
9556 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9557 	}
9558 }
9559 
9560 static void
9561 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9562 {
9563 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9564 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9565 	int i;
9566 
9567 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9568 
9569 	for (i = 0; i < dof->dofh_secnum; i++) {
9570 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9571 		    dof->dofh_secoff + i * dof->dofh_secsize);
9572 
9573 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9574 			continue;
9575 
9576 		dtrace_helper_provide_one(dhp, sec, pid);
9577 	}
9578 
9579 	/*
9580 	 * We may have just created probes, so we must now rematch against
9581 	 * any retained enablings.  Note that this call will acquire both
9582 	 * cpu_lock and dtrace_lock; the fact that we are holding
9583 	 * dtrace_meta_lock now is what defines the ordering with respect to
9584 	 * these three locks.
9585 	 */
9586 	dtrace_enabling_matchall();
9587 }
9588 
9589 static void
9590 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9591 {
9592 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9593 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9594 	dof_sec_t *str_sec;
9595 	dof_provider_t *provider;
9596 	char *strtab;
9597 	dtrace_helper_provdesc_t dhpv;
9598 	dtrace_meta_t *meta = dtrace_meta_pid;
9599 	dtrace_mops_t *mops = &meta->dtm_mops;
9600 
9601 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9602 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9603 	    provider->dofpv_strtab * dof->dofh_secsize);
9604 
9605 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9606 
9607 	/*
9608 	 * Create the provider.
9609 	 */
9610 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9611 
9612 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9613 
9614 	meta->dtm_count--;
9615 }
9616 
9617 static void
9618 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9619 {
9620 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9621 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9622 	int i;
9623 
9624 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9625 
9626 	for (i = 0; i < dof->dofh_secnum; i++) {
9627 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9628 		    dof->dofh_secoff + i * dof->dofh_secsize);
9629 
9630 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9631 			continue;
9632 
9633 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9634 	}
9635 }
9636 
9637 /*
9638  * DTrace Meta Provider-to-Framework API Functions
9639  *
9640  * These functions implement the Meta Provider-to-Framework API, as described
9641  * in <sys/dtrace.h>.
9642  */
9643 int
9644 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9645     dtrace_meta_provider_id_t *idp)
9646 {
9647 	dtrace_meta_t *meta;
9648 	dtrace_helpers_t *help, *next;
9649 	int i;
9650 
9651 	*idp = DTRACE_METAPROVNONE;
9652 
9653 	/*
9654 	 * We strictly don't need the name, but we hold onto it for
9655 	 * debuggability. All hail error queues!
9656 	 */
9657 	if (name == NULL) {
9658 		cmn_err(CE_WARN, "failed to register meta-provider: "
9659 		    "invalid name");
9660 		return (EINVAL);
9661 	}
9662 
9663 	if (mops == NULL ||
9664 	    mops->dtms_create_probe == NULL ||
9665 	    mops->dtms_provide_pid == NULL ||
9666 	    mops->dtms_remove_pid == NULL) {
9667 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9668 		    "invalid ops", name);
9669 		return (EINVAL);
9670 	}
9671 
9672 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9673 	meta->dtm_mops = *mops;
9674 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9675 	(void) strcpy(meta->dtm_name, name);
9676 	meta->dtm_arg = arg;
9677 
9678 	mutex_enter(&dtrace_meta_lock);
9679 	mutex_enter(&dtrace_lock);
9680 
9681 	if (dtrace_meta_pid != NULL) {
9682 		mutex_exit(&dtrace_lock);
9683 		mutex_exit(&dtrace_meta_lock);
9684 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9685 		    "user-land meta-provider exists", name);
9686 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9687 		kmem_free(meta, sizeof (dtrace_meta_t));
9688 		return (EINVAL);
9689 	}
9690 
9691 	dtrace_meta_pid = meta;
9692 	*idp = (dtrace_meta_provider_id_t)meta;
9693 
9694 	/*
9695 	 * If there are providers and probes ready to go, pass them
9696 	 * off to the new meta provider now.
9697 	 */
9698 
9699 	help = dtrace_deferred_pid;
9700 	dtrace_deferred_pid = NULL;
9701 
9702 	mutex_exit(&dtrace_lock);
9703 
9704 	while (help != NULL) {
9705 		for (i = 0; i < help->dthps_nprovs; i++) {
9706 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9707 			    help->dthps_pid);
9708 		}
9709 
9710 		next = help->dthps_next;
9711 		help->dthps_next = NULL;
9712 		help->dthps_prev = NULL;
9713 		help->dthps_deferred = 0;
9714 		help = next;
9715 	}
9716 
9717 	mutex_exit(&dtrace_meta_lock);
9718 
9719 	return (0);
9720 }
9721 
9722 int
9723 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9724 {
9725 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9726 
9727 	mutex_enter(&dtrace_meta_lock);
9728 	mutex_enter(&dtrace_lock);
9729 
9730 	if (old == dtrace_meta_pid) {
9731 		pp = &dtrace_meta_pid;
9732 	} else {
9733 		panic("attempt to unregister non-existent "
9734 		    "dtrace meta-provider %p\n", (void *)old);
9735 	}
9736 
9737 	if (old->dtm_count != 0) {
9738 		mutex_exit(&dtrace_lock);
9739 		mutex_exit(&dtrace_meta_lock);
9740 		return (EBUSY);
9741 	}
9742 
9743 	*pp = NULL;
9744 
9745 	mutex_exit(&dtrace_lock);
9746 	mutex_exit(&dtrace_meta_lock);
9747 
9748 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9749 	kmem_free(old, sizeof (dtrace_meta_t));
9750 
9751 	return (0);
9752 }
9753 
9754 
9755 /*
9756  * DTrace DIF Object Functions
9757  */
9758 static int
9759 dtrace_difo_err(uint_t pc, const char *format, ...)
9760 {
9761 	if (dtrace_err_verbose) {
9762 		va_list alist;
9763 
9764 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9765 		va_start(alist, format);
9766 		(void) vuprintf(format, alist);
9767 		va_end(alist);
9768 	}
9769 
9770 #ifdef DTRACE_ERRDEBUG
9771 	dtrace_errdebug(format);
9772 #endif
9773 	return (1);
9774 }
9775 
9776 /*
9777  * Validate a DTrace DIF object by checking the IR instructions.  The following
9778  * rules are currently enforced by dtrace_difo_validate():
9779  *
9780  * 1. Each instruction must have a valid opcode
9781  * 2. Each register, string, variable, or subroutine reference must be valid
9782  * 3. No instruction can modify register %r0 (must be zero)
9783  * 4. All instruction reserved bits must be set to zero
9784  * 5. The last instruction must be a "ret" instruction
9785  * 6. All branch targets must reference a valid instruction _after_ the branch
9786  */
9787 static int
9788 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9789     cred_t *cr)
9790 {
9791 	int err = 0, i;
9792 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9793 	int kcheckload;
9794 	uint_t pc;
9795 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9796 
9797 	kcheckload = cr == NULL ||
9798 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9799 
9800 	dp->dtdo_destructive = 0;
9801 
9802 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9803 		dif_instr_t instr = dp->dtdo_buf[pc];
9804 
9805 		uint_t r1 = DIF_INSTR_R1(instr);
9806 		uint_t r2 = DIF_INSTR_R2(instr);
9807 		uint_t rd = DIF_INSTR_RD(instr);
9808 		uint_t rs = DIF_INSTR_RS(instr);
9809 		uint_t label = DIF_INSTR_LABEL(instr);
9810 		uint_t v = DIF_INSTR_VAR(instr);
9811 		uint_t subr = DIF_INSTR_SUBR(instr);
9812 		uint_t type = DIF_INSTR_TYPE(instr);
9813 		uint_t op = DIF_INSTR_OP(instr);
9814 
9815 		switch (op) {
9816 		case DIF_OP_OR:
9817 		case DIF_OP_XOR:
9818 		case DIF_OP_AND:
9819 		case DIF_OP_SLL:
9820 		case DIF_OP_SRL:
9821 		case DIF_OP_SRA:
9822 		case DIF_OP_SUB:
9823 		case DIF_OP_ADD:
9824 		case DIF_OP_MUL:
9825 		case DIF_OP_SDIV:
9826 		case DIF_OP_UDIV:
9827 		case DIF_OP_SREM:
9828 		case DIF_OP_UREM:
9829 		case DIF_OP_COPYS:
9830 			if (r1 >= nregs)
9831 				err += efunc(pc, "invalid register %u\n", r1);
9832 			if (r2 >= nregs)
9833 				err += efunc(pc, "invalid register %u\n", r2);
9834 			if (rd >= nregs)
9835 				err += efunc(pc, "invalid register %u\n", rd);
9836 			if (rd == 0)
9837 				err += efunc(pc, "cannot write to %%r0\n");
9838 			break;
9839 		case DIF_OP_NOT:
9840 		case DIF_OP_MOV:
9841 		case DIF_OP_ALLOCS:
9842 			if (r1 >= nregs)
9843 				err += efunc(pc, "invalid register %u\n", r1);
9844 			if (r2 != 0)
9845 				err += efunc(pc, "non-zero reserved bits\n");
9846 			if (rd >= nregs)
9847 				err += efunc(pc, "invalid register %u\n", rd);
9848 			if (rd == 0)
9849 				err += efunc(pc, "cannot write to %%r0\n");
9850 			break;
9851 		case DIF_OP_LDSB:
9852 		case DIF_OP_LDSH:
9853 		case DIF_OP_LDSW:
9854 		case DIF_OP_LDUB:
9855 		case DIF_OP_LDUH:
9856 		case DIF_OP_LDUW:
9857 		case DIF_OP_LDX:
9858 			if (r1 >= nregs)
9859 				err += efunc(pc, "invalid register %u\n", r1);
9860 			if (r2 != 0)
9861 				err += efunc(pc, "non-zero reserved bits\n");
9862 			if (rd >= nregs)
9863 				err += efunc(pc, "invalid register %u\n", rd);
9864 			if (rd == 0)
9865 				err += efunc(pc, "cannot write to %%r0\n");
9866 			if (kcheckload)
9867 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9868 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9869 			break;
9870 		case DIF_OP_RLDSB:
9871 		case DIF_OP_RLDSH:
9872 		case DIF_OP_RLDSW:
9873 		case DIF_OP_RLDUB:
9874 		case DIF_OP_RLDUH:
9875 		case DIF_OP_RLDUW:
9876 		case DIF_OP_RLDX:
9877 			if (r1 >= nregs)
9878 				err += efunc(pc, "invalid register %u\n", r1);
9879 			if (r2 != 0)
9880 				err += efunc(pc, "non-zero reserved bits\n");
9881 			if (rd >= nregs)
9882 				err += efunc(pc, "invalid register %u\n", rd);
9883 			if (rd == 0)
9884 				err += efunc(pc, "cannot write to %%r0\n");
9885 			break;
9886 		case DIF_OP_ULDSB:
9887 		case DIF_OP_ULDSH:
9888 		case DIF_OP_ULDSW:
9889 		case DIF_OP_ULDUB:
9890 		case DIF_OP_ULDUH:
9891 		case DIF_OP_ULDUW:
9892 		case DIF_OP_ULDX:
9893 			if (r1 >= nregs)
9894 				err += efunc(pc, "invalid register %u\n", r1);
9895 			if (r2 != 0)
9896 				err += efunc(pc, "non-zero reserved bits\n");
9897 			if (rd >= nregs)
9898 				err += efunc(pc, "invalid register %u\n", rd);
9899 			if (rd == 0)
9900 				err += efunc(pc, "cannot write to %%r0\n");
9901 			break;
9902 		case DIF_OP_STB:
9903 		case DIF_OP_STH:
9904 		case DIF_OP_STW:
9905 		case DIF_OP_STX:
9906 			if (r1 >= nregs)
9907 				err += efunc(pc, "invalid register %u\n", r1);
9908 			if (r2 != 0)
9909 				err += efunc(pc, "non-zero reserved bits\n");
9910 			if (rd >= nregs)
9911 				err += efunc(pc, "invalid register %u\n", rd);
9912 			if (rd == 0)
9913 				err += efunc(pc, "cannot write to 0 address\n");
9914 			break;
9915 		case DIF_OP_CMP:
9916 		case DIF_OP_SCMP:
9917 			if (r1 >= nregs)
9918 				err += efunc(pc, "invalid register %u\n", r1);
9919 			if (r2 >= nregs)
9920 				err += efunc(pc, "invalid register %u\n", r2);
9921 			if (rd != 0)
9922 				err += efunc(pc, "non-zero reserved bits\n");
9923 			break;
9924 		case DIF_OP_TST:
9925 			if (r1 >= nregs)
9926 				err += efunc(pc, "invalid register %u\n", r1);
9927 			if (r2 != 0 || rd != 0)
9928 				err += efunc(pc, "non-zero reserved bits\n");
9929 			break;
9930 		case DIF_OP_BA:
9931 		case DIF_OP_BE:
9932 		case DIF_OP_BNE:
9933 		case DIF_OP_BG:
9934 		case DIF_OP_BGU:
9935 		case DIF_OP_BGE:
9936 		case DIF_OP_BGEU:
9937 		case DIF_OP_BL:
9938 		case DIF_OP_BLU:
9939 		case DIF_OP_BLE:
9940 		case DIF_OP_BLEU:
9941 			if (label >= dp->dtdo_len) {
9942 				err += efunc(pc, "invalid branch target %u\n",
9943 				    label);
9944 			}
9945 			if (label <= pc) {
9946 				err += efunc(pc, "backward branch to %u\n",
9947 				    label);
9948 			}
9949 			break;
9950 		case DIF_OP_RET:
9951 			if (r1 != 0 || r2 != 0)
9952 				err += efunc(pc, "non-zero reserved bits\n");
9953 			if (rd >= nregs)
9954 				err += efunc(pc, "invalid register %u\n", rd);
9955 			break;
9956 		case DIF_OP_NOP:
9957 		case DIF_OP_POPTS:
9958 		case DIF_OP_FLUSHTS:
9959 			if (r1 != 0 || r2 != 0 || rd != 0)
9960 				err += efunc(pc, "non-zero reserved bits\n");
9961 			break;
9962 		case DIF_OP_SETX:
9963 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9964 				err += efunc(pc, "invalid integer ref %u\n",
9965 				    DIF_INSTR_INTEGER(instr));
9966 			}
9967 			if (rd >= nregs)
9968 				err += efunc(pc, "invalid register %u\n", rd);
9969 			if (rd == 0)
9970 				err += efunc(pc, "cannot write to %%r0\n");
9971 			break;
9972 		case DIF_OP_SETS:
9973 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9974 				err += efunc(pc, "invalid string ref %u\n",
9975 				    DIF_INSTR_STRING(instr));
9976 			}
9977 			if (rd >= nregs)
9978 				err += efunc(pc, "invalid register %u\n", rd);
9979 			if (rd == 0)
9980 				err += efunc(pc, "cannot write to %%r0\n");
9981 			break;
9982 		case DIF_OP_LDGA:
9983 		case DIF_OP_LDTA:
9984 			if (r1 > DIF_VAR_ARRAY_MAX)
9985 				err += efunc(pc, "invalid array %u\n", r1);
9986 			if (r2 >= nregs)
9987 				err += efunc(pc, "invalid register %u\n", r2);
9988 			if (rd >= nregs)
9989 				err += efunc(pc, "invalid register %u\n", rd);
9990 			if (rd == 0)
9991 				err += efunc(pc, "cannot write to %%r0\n");
9992 			break;
9993 		case DIF_OP_LDGS:
9994 		case DIF_OP_LDTS:
9995 		case DIF_OP_LDLS:
9996 		case DIF_OP_LDGAA:
9997 		case DIF_OP_LDTAA:
9998 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9999 				err += efunc(pc, "invalid variable %u\n", v);
10000 			if (rd >= nregs)
10001 				err += efunc(pc, "invalid register %u\n", rd);
10002 			if (rd == 0)
10003 				err += efunc(pc, "cannot write to %%r0\n");
10004 			break;
10005 		case DIF_OP_STGS:
10006 		case DIF_OP_STTS:
10007 		case DIF_OP_STLS:
10008 		case DIF_OP_STGAA:
10009 		case DIF_OP_STTAA:
10010 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
10011 				err += efunc(pc, "invalid variable %u\n", v);
10012 			if (rs >= nregs)
10013 				err += efunc(pc, "invalid register %u\n", rd);
10014 			break;
10015 		case DIF_OP_CALL:
10016 			if (subr > DIF_SUBR_MAX)
10017 				err += efunc(pc, "invalid subr %u\n", subr);
10018 			if (rd >= nregs)
10019 				err += efunc(pc, "invalid register %u\n", rd);
10020 			if (rd == 0)
10021 				err += efunc(pc, "cannot write to %%r0\n");
10022 
10023 			if (subr == DIF_SUBR_COPYOUT ||
10024 			    subr == DIF_SUBR_COPYOUTSTR) {
10025 				dp->dtdo_destructive = 1;
10026 			}
10027 
10028 			if (subr == DIF_SUBR_GETF) {
10029 #ifdef __FreeBSD__
10030 				err += efunc(pc, "getf() not supported");
10031 #else
10032 				/*
10033 				 * If we have a getf() we need to record that
10034 				 * in our state.  Note that our state can be
10035 				 * NULL if this is a helper -- but in that
10036 				 * case, the call to getf() is itself illegal,
10037 				 * and will be caught (slightly later) when
10038 				 * the helper is validated.
10039 				 */
10040 				if (vstate->dtvs_state != NULL)
10041 					vstate->dtvs_state->dts_getf++;
10042 #endif
10043 			}
10044 
10045 			break;
10046 		case DIF_OP_PUSHTR:
10047 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10048 				err += efunc(pc, "invalid ref type %u\n", type);
10049 			if (r2 >= nregs)
10050 				err += efunc(pc, "invalid register %u\n", r2);
10051 			if (rs >= nregs)
10052 				err += efunc(pc, "invalid register %u\n", rs);
10053 			break;
10054 		case DIF_OP_PUSHTV:
10055 			if (type != DIF_TYPE_CTF)
10056 				err += efunc(pc, "invalid val type %u\n", type);
10057 			if (r2 >= nregs)
10058 				err += efunc(pc, "invalid register %u\n", r2);
10059 			if (rs >= nregs)
10060 				err += efunc(pc, "invalid register %u\n", rs);
10061 			break;
10062 		default:
10063 			err += efunc(pc, "invalid opcode %u\n",
10064 			    DIF_INSTR_OP(instr));
10065 		}
10066 	}
10067 
10068 	if (dp->dtdo_len != 0 &&
10069 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10070 		err += efunc(dp->dtdo_len - 1,
10071 		    "expected 'ret' as last DIF instruction\n");
10072 	}
10073 
10074 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10075 		/*
10076 		 * If we're not returning by reference, the size must be either
10077 		 * 0 or the size of one of the base types.
10078 		 */
10079 		switch (dp->dtdo_rtype.dtdt_size) {
10080 		case 0:
10081 		case sizeof (uint8_t):
10082 		case sizeof (uint16_t):
10083 		case sizeof (uint32_t):
10084 		case sizeof (uint64_t):
10085 			break;
10086 
10087 		default:
10088 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10089 		}
10090 	}
10091 
10092 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10093 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10094 		dtrace_diftype_t *vt, *et;
10095 		uint_t id, ndx;
10096 
10097 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10098 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10099 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10100 			err += efunc(i, "unrecognized variable scope %d\n",
10101 			    v->dtdv_scope);
10102 			break;
10103 		}
10104 
10105 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10106 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10107 			err += efunc(i, "unrecognized variable type %d\n",
10108 			    v->dtdv_kind);
10109 			break;
10110 		}
10111 
10112 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10113 			err += efunc(i, "%d exceeds variable id limit\n", id);
10114 			break;
10115 		}
10116 
10117 		if (id < DIF_VAR_OTHER_UBASE)
10118 			continue;
10119 
10120 		/*
10121 		 * For user-defined variables, we need to check that this
10122 		 * definition is identical to any previous definition that we
10123 		 * encountered.
10124 		 */
10125 		ndx = id - DIF_VAR_OTHER_UBASE;
10126 
10127 		switch (v->dtdv_scope) {
10128 		case DIFV_SCOPE_GLOBAL:
10129 			if (maxglobal == -1 || ndx > maxglobal)
10130 				maxglobal = ndx;
10131 
10132 			if (ndx < vstate->dtvs_nglobals) {
10133 				dtrace_statvar_t *svar;
10134 
10135 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10136 					existing = &svar->dtsv_var;
10137 			}
10138 
10139 			break;
10140 
10141 		case DIFV_SCOPE_THREAD:
10142 			if (maxtlocal == -1 || ndx > maxtlocal)
10143 				maxtlocal = ndx;
10144 
10145 			if (ndx < vstate->dtvs_ntlocals)
10146 				existing = &vstate->dtvs_tlocals[ndx];
10147 			break;
10148 
10149 		case DIFV_SCOPE_LOCAL:
10150 			if (maxlocal == -1 || ndx > maxlocal)
10151 				maxlocal = ndx;
10152 
10153 			if (ndx < vstate->dtvs_nlocals) {
10154 				dtrace_statvar_t *svar;
10155 
10156 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10157 					existing = &svar->dtsv_var;
10158 			}
10159 
10160 			break;
10161 		}
10162 
10163 		vt = &v->dtdv_type;
10164 
10165 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10166 			if (vt->dtdt_size == 0) {
10167 				err += efunc(i, "zero-sized variable\n");
10168 				break;
10169 			}
10170 
10171 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10172 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10173 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10174 				err += efunc(i, "oversized by-ref static\n");
10175 				break;
10176 			}
10177 		}
10178 
10179 		if (existing == NULL || existing->dtdv_id == 0)
10180 			continue;
10181 
10182 		ASSERT(existing->dtdv_id == v->dtdv_id);
10183 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10184 
10185 		if (existing->dtdv_kind != v->dtdv_kind)
10186 			err += efunc(i, "%d changed variable kind\n", id);
10187 
10188 		et = &existing->dtdv_type;
10189 
10190 		if (vt->dtdt_flags != et->dtdt_flags) {
10191 			err += efunc(i, "%d changed variable type flags\n", id);
10192 			break;
10193 		}
10194 
10195 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10196 			err += efunc(i, "%d changed variable type size\n", id);
10197 			break;
10198 		}
10199 	}
10200 
10201 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10202 		dif_instr_t instr = dp->dtdo_buf[pc];
10203 
10204 		uint_t v = DIF_INSTR_VAR(instr);
10205 		uint_t op = DIF_INSTR_OP(instr);
10206 
10207 		switch (op) {
10208 		case DIF_OP_LDGS:
10209 		case DIF_OP_LDGAA:
10210 		case DIF_OP_STGS:
10211 		case DIF_OP_STGAA:
10212 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10213 				err += efunc(pc, "invalid variable %u\n", v);
10214 			break;
10215 		case DIF_OP_LDTS:
10216 		case DIF_OP_LDTAA:
10217 		case DIF_OP_STTS:
10218 		case DIF_OP_STTAA:
10219 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10220 				err += efunc(pc, "invalid variable %u\n", v);
10221 			break;
10222 		case DIF_OP_LDLS:
10223 		case DIF_OP_STLS:
10224 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10225 				err += efunc(pc, "invalid variable %u\n", v);
10226 			break;
10227 		default:
10228 			break;
10229 		}
10230 	}
10231 
10232 	return (err);
10233 }
10234 
10235 /*
10236  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10237  * are much more constrained than normal DIFOs.  Specifically, they may
10238  * not:
10239  *
10240  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10241  *    miscellaneous string routines
10242  * 2. Access DTrace variables other than the args[] array, and the
10243  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10244  * 3. Have thread-local variables.
10245  * 4. Have dynamic variables.
10246  */
10247 static int
10248 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10249 {
10250 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10251 	int err = 0;
10252 	uint_t pc;
10253 
10254 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10255 		dif_instr_t instr = dp->dtdo_buf[pc];
10256 
10257 		uint_t v = DIF_INSTR_VAR(instr);
10258 		uint_t subr = DIF_INSTR_SUBR(instr);
10259 		uint_t op = DIF_INSTR_OP(instr);
10260 
10261 		switch (op) {
10262 		case DIF_OP_OR:
10263 		case DIF_OP_XOR:
10264 		case DIF_OP_AND:
10265 		case DIF_OP_SLL:
10266 		case DIF_OP_SRL:
10267 		case DIF_OP_SRA:
10268 		case DIF_OP_SUB:
10269 		case DIF_OP_ADD:
10270 		case DIF_OP_MUL:
10271 		case DIF_OP_SDIV:
10272 		case DIF_OP_UDIV:
10273 		case DIF_OP_SREM:
10274 		case DIF_OP_UREM:
10275 		case DIF_OP_COPYS:
10276 		case DIF_OP_NOT:
10277 		case DIF_OP_MOV:
10278 		case DIF_OP_RLDSB:
10279 		case DIF_OP_RLDSH:
10280 		case DIF_OP_RLDSW:
10281 		case DIF_OP_RLDUB:
10282 		case DIF_OP_RLDUH:
10283 		case DIF_OP_RLDUW:
10284 		case DIF_OP_RLDX:
10285 		case DIF_OP_ULDSB:
10286 		case DIF_OP_ULDSH:
10287 		case DIF_OP_ULDSW:
10288 		case DIF_OP_ULDUB:
10289 		case DIF_OP_ULDUH:
10290 		case DIF_OP_ULDUW:
10291 		case DIF_OP_ULDX:
10292 		case DIF_OP_STB:
10293 		case DIF_OP_STH:
10294 		case DIF_OP_STW:
10295 		case DIF_OP_STX:
10296 		case DIF_OP_ALLOCS:
10297 		case DIF_OP_CMP:
10298 		case DIF_OP_SCMP:
10299 		case DIF_OP_TST:
10300 		case DIF_OP_BA:
10301 		case DIF_OP_BE:
10302 		case DIF_OP_BNE:
10303 		case DIF_OP_BG:
10304 		case DIF_OP_BGU:
10305 		case DIF_OP_BGE:
10306 		case DIF_OP_BGEU:
10307 		case DIF_OP_BL:
10308 		case DIF_OP_BLU:
10309 		case DIF_OP_BLE:
10310 		case DIF_OP_BLEU:
10311 		case DIF_OP_RET:
10312 		case DIF_OP_NOP:
10313 		case DIF_OP_POPTS:
10314 		case DIF_OP_FLUSHTS:
10315 		case DIF_OP_SETX:
10316 		case DIF_OP_SETS:
10317 		case DIF_OP_LDGA:
10318 		case DIF_OP_LDLS:
10319 		case DIF_OP_STGS:
10320 		case DIF_OP_STLS:
10321 		case DIF_OP_PUSHTR:
10322 		case DIF_OP_PUSHTV:
10323 			break;
10324 
10325 		case DIF_OP_LDGS:
10326 			if (v >= DIF_VAR_OTHER_UBASE)
10327 				break;
10328 
10329 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10330 				break;
10331 
10332 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10333 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10334 			    v == DIF_VAR_EXECARGS ||
10335 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10336 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10337 				break;
10338 
10339 			err += efunc(pc, "illegal variable %u\n", v);
10340 			break;
10341 
10342 		case DIF_OP_LDTA:
10343 		case DIF_OP_LDTS:
10344 		case DIF_OP_LDGAA:
10345 		case DIF_OP_LDTAA:
10346 			err += efunc(pc, "illegal dynamic variable load\n");
10347 			break;
10348 
10349 		case DIF_OP_STTS:
10350 		case DIF_OP_STGAA:
10351 		case DIF_OP_STTAA:
10352 			err += efunc(pc, "illegal dynamic variable store\n");
10353 			break;
10354 
10355 		case DIF_OP_CALL:
10356 			if (subr == DIF_SUBR_ALLOCA ||
10357 			    subr == DIF_SUBR_BCOPY ||
10358 			    subr == DIF_SUBR_COPYIN ||
10359 			    subr == DIF_SUBR_COPYINTO ||
10360 			    subr == DIF_SUBR_COPYINSTR ||
10361 			    subr == DIF_SUBR_INDEX ||
10362 			    subr == DIF_SUBR_INET_NTOA ||
10363 			    subr == DIF_SUBR_INET_NTOA6 ||
10364 			    subr == DIF_SUBR_INET_NTOP ||
10365 			    subr == DIF_SUBR_JSON ||
10366 			    subr == DIF_SUBR_LLTOSTR ||
10367 			    subr == DIF_SUBR_STRTOLL ||
10368 			    subr == DIF_SUBR_RINDEX ||
10369 			    subr == DIF_SUBR_STRCHR ||
10370 			    subr == DIF_SUBR_STRJOIN ||
10371 			    subr == DIF_SUBR_STRRCHR ||
10372 			    subr == DIF_SUBR_STRSTR ||
10373 			    subr == DIF_SUBR_HTONS ||
10374 			    subr == DIF_SUBR_HTONL ||
10375 			    subr == DIF_SUBR_HTONLL ||
10376 			    subr == DIF_SUBR_NTOHS ||
10377 			    subr == DIF_SUBR_NTOHL ||
10378 			    subr == DIF_SUBR_NTOHLL ||
10379 			    subr == DIF_SUBR_MEMREF)
10380 				break;
10381 #ifdef __FreeBSD__
10382 			if (subr == DIF_SUBR_MEMSTR)
10383 				break;
10384 #endif
10385 
10386 			err += efunc(pc, "invalid subr %u\n", subr);
10387 			break;
10388 
10389 		default:
10390 			err += efunc(pc, "invalid opcode %u\n",
10391 			    DIF_INSTR_OP(instr));
10392 		}
10393 	}
10394 
10395 	return (err);
10396 }
10397 
10398 /*
10399  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10400  * basis; 0 if not.
10401  */
10402 static int
10403 dtrace_difo_cacheable(dtrace_difo_t *dp)
10404 {
10405 	int i;
10406 
10407 	if (dp == NULL)
10408 		return (0);
10409 
10410 	for (i = 0; i < dp->dtdo_varlen; i++) {
10411 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10412 
10413 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10414 			continue;
10415 
10416 		switch (v->dtdv_id) {
10417 		case DIF_VAR_CURTHREAD:
10418 		case DIF_VAR_PID:
10419 		case DIF_VAR_TID:
10420 		case DIF_VAR_EXECARGS:
10421 		case DIF_VAR_EXECNAME:
10422 		case DIF_VAR_ZONENAME:
10423 			break;
10424 
10425 		default:
10426 			return (0);
10427 		}
10428 	}
10429 
10430 	/*
10431 	 * This DIF object may be cacheable.  Now we need to look for any
10432 	 * array loading instructions, any memory loading instructions, or
10433 	 * any stores to thread-local variables.
10434 	 */
10435 	for (i = 0; i < dp->dtdo_len; i++) {
10436 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10437 
10438 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10439 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10440 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10441 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10442 			return (0);
10443 	}
10444 
10445 	return (1);
10446 }
10447 
10448 static void
10449 dtrace_difo_hold(dtrace_difo_t *dp)
10450 {
10451 	int i;
10452 
10453 	ASSERT(MUTEX_HELD(&dtrace_lock));
10454 
10455 	dp->dtdo_refcnt++;
10456 	ASSERT(dp->dtdo_refcnt != 0);
10457 
10458 	/*
10459 	 * We need to check this DIF object for references to the variable
10460 	 * DIF_VAR_VTIMESTAMP.
10461 	 */
10462 	for (i = 0; i < dp->dtdo_varlen; i++) {
10463 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10464 
10465 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10466 			continue;
10467 
10468 		if (dtrace_vtime_references++ == 0)
10469 			dtrace_vtime_enable();
10470 	}
10471 }
10472 
10473 /*
10474  * This routine calculates the dynamic variable chunksize for a given DIF
10475  * object.  The calculation is not fool-proof, and can probably be tricked by
10476  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10477  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10478  * if a dynamic variable size exceeds the chunksize.
10479  */
10480 static void
10481 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10482 {
10483 	uint64_t sval = 0;
10484 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10485 	const dif_instr_t *text = dp->dtdo_buf;
10486 	uint_t pc, srd = 0;
10487 	uint_t ttop = 0;
10488 	size_t size, ksize;
10489 	uint_t id, i;
10490 
10491 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10492 		dif_instr_t instr = text[pc];
10493 		uint_t op = DIF_INSTR_OP(instr);
10494 		uint_t rd = DIF_INSTR_RD(instr);
10495 		uint_t r1 = DIF_INSTR_R1(instr);
10496 		uint_t nkeys = 0;
10497 		uchar_t scope = 0;
10498 
10499 		dtrace_key_t *key = tupregs;
10500 
10501 		switch (op) {
10502 		case DIF_OP_SETX:
10503 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10504 			srd = rd;
10505 			continue;
10506 
10507 		case DIF_OP_STTS:
10508 			key = &tupregs[DIF_DTR_NREGS];
10509 			key[0].dttk_size = 0;
10510 			key[1].dttk_size = 0;
10511 			nkeys = 2;
10512 			scope = DIFV_SCOPE_THREAD;
10513 			break;
10514 
10515 		case DIF_OP_STGAA:
10516 		case DIF_OP_STTAA:
10517 			nkeys = ttop;
10518 
10519 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10520 				key[nkeys++].dttk_size = 0;
10521 
10522 			key[nkeys++].dttk_size = 0;
10523 
10524 			if (op == DIF_OP_STTAA) {
10525 				scope = DIFV_SCOPE_THREAD;
10526 			} else {
10527 				scope = DIFV_SCOPE_GLOBAL;
10528 			}
10529 
10530 			break;
10531 
10532 		case DIF_OP_PUSHTR:
10533 			if (ttop == DIF_DTR_NREGS)
10534 				return;
10535 
10536 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10537 				/*
10538 				 * If the register for the size of the "pushtr"
10539 				 * is %r0 (or the value is 0) and the type is
10540 				 * a string, we'll use the system-wide default
10541 				 * string size.
10542 				 */
10543 				tupregs[ttop++].dttk_size =
10544 				    dtrace_strsize_default;
10545 			} else {
10546 				if (srd == 0)
10547 					return;
10548 
10549 				if (sval > LONG_MAX)
10550 					return;
10551 
10552 				tupregs[ttop++].dttk_size = sval;
10553 			}
10554 
10555 			break;
10556 
10557 		case DIF_OP_PUSHTV:
10558 			if (ttop == DIF_DTR_NREGS)
10559 				return;
10560 
10561 			tupregs[ttop++].dttk_size = 0;
10562 			break;
10563 
10564 		case DIF_OP_FLUSHTS:
10565 			ttop = 0;
10566 			break;
10567 
10568 		case DIF_OP_POPTS:
10569 			if (ttop != 0)
10570 				ttop--;
10571 			break;
10572 		}
10573 
10574 		sval = 0;
10575 		srd = 0;
10576 
10577 		if (nkeys == 0)
10578 			continue;
10579 
10580 		/*
10581 		 * We have a dynamic variable allocation; calculate its size.
10582 		 */
10583 		for (ksize = 0, i = 0; i < nkeys; i++)
10584 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10585 
10586 		size = sizeof (dtrace_dynvar_t);
10587 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10588 		size += ksize;
10589 
10590 		/*
10591 		 * Now we need to determine the size of the stored data.
10592 		 */
10593 		id = DIF_INSTR_VAR(instr);
10594 
10595 		for (i = 0; i < dp->dtdo_varlen; i++) {
10596 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10597 
10598 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10599 				size += v->dtdv_type.dtdt_size;
10600 				break;
10601 			}
10602 		}
10603 
10604 		if (i == dp->dtdo_varlen)
10605 			return;
10606 
10607 		/*
10608 		 * We have the size.  If this is larger than the chunk size
10609 		 * for our dynamic variable state, reset the chunk size.
10610 		 */
10611 		size = P2ROUNDUP(size, sizeof (uint64_t));
10612 
10613 		/*
10614 		 * Before setting the chunk size, check that we're not going
10615 		 * to set it to a negative value...
10616 		 */
10617 		if (size > LONG_MAX)
10618 			return;
10619 
10620 		/*
10621 		 * ...and make certain that we didn't badly overflow.
10622 		 */
10623 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10624 			return;
10625 
10626 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10627 			vstate->dtvs_dynvars.dtds_chunksize = size;
10628 	}
10629 }
10630 
10631 static void
10632 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10633 {
10634 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10635 	uint_t id;
10636 
10637 	ASSERT(MUTEX_HELD(&dtrace_lock));
10638 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10639 
10640 	for (i = 0; i < dp->dtdo_varlen; i++) {
10641 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10642 		dtrace_statvar_t *svar, ***svarp = NULL;
10643 		size_t dsize = 0;
10644 		uint8_t scope = v->dtdv_scope;
10645 		int *np = NULL;
10646 
10647 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10648 			continue;
10649 
10650 		id -= DIF_VAR_OTHER_UBASE;
10651 
10652 		switch (scope) {
10653 		case DIFV_SCOPE_THREAD:
10654 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10655 				dtrace_difv_t *tlocals;
10656 
10657 				if ((ntlocals = (otlocals << 1)) == 0)
10658 					ntlocals = 1;
10659 
10660 				osz = otlocals * sizeof (dtrace_difv_t);
10661 				nsz = ntlocals * sizeof (dtrace_difv_t);
10662 
10663 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10664 
10665 				if (osz != 0) {
10666 					bcopy(vstate->dtvs_tlocals,
10667 					    tlocals, osz);
10668 					kmem_free(vstate->dtvs_tlocals, osz);
10669 				}
10670 
10671 				vstate->dtvs_tlocals = tlocals;
10672 				vstate->dtvs_ntlocals = ntlocals;
10673 			}
10674 
10675 			vstate->dtvs_tlocals[id] = *v;
10676 			continue;
10677 
10678 		case DIFV_SCOPE_LOCAL:
10679 			np = &vstate->dtvs_nlocals;
10680 			svarp = &vstate->dtvs_locals;
10681 
10682 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10683 				dsize = (mp_maxid + 1) *
10684 				    (v->dtdv_type.dtdt_size +
10685 				    sizeof (uint64_t));
10686 			else
10687 				dsize = (mp_maxid + 1) * sizeof (uint64_t);
10688 
10689 			break;
10690 
10691 		case DIFV_SCOPE_GLOBAL:
10692 			np = &vstate->dtvs_nglobals;
10693 			svarp = &vstate->dtvs_globals;
10694 
10695 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10696 				dsize = v->dtdv_type.dtdt_size +
10697 				    sizeof (uint64_t);
10698 
10699 			break;
10700 
10701 		default:
10702 			ASSERT(0);
10703 		}
10704 
10705 		while (id >= (oldsvars = *np)) {
10706 			dtrace_statvar_t **statics;
10707 			int newsvars, oldsize, newsize;
10708 
10709 			if ((newsvars = (oldsvars << 1)) == 0)
10710 				newsvars = 1;
10711 
10712 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10713 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10714 
10715 			statics = kmem_zalloc(newsize, KM_SLEEP);
10716 
10717 			if (oldsize != 0) {
10718 				bcopy(*svarp, statics, oldsize);
10719 				kmem_free(*svarp, oldsize);
10720 			}
10721 
10722 			*svarp = statics;
10723 			*np = newsvars;
10724 		}
10725 
10726 		if ((svar = (*svarp)[id]) == NULL) {
10727 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10728 			svar->dtsv_var = *v;
10729 
10730 			if ((svar->dtsv_size = dsize) != 0) {
10731 				svar->dtsv_data = (uint64_t)(uintptr_t)
10732 				    kmem_zalloc(dsize, KM_SLEEP);
10733 			}
10734 
10735 			(*svarp)[id] = svar;
10736 		}
10737 
10738 		svar->dtsv_refcnt++;
10739 	}
10740 
10741 	dtrace_difo_chunksize(dp, vstate);
10742 	dtrace_difo_hold(dp);
10743 }
10744 
10745 static dtrace_difo_t *
10746 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10747 {
10748 	dtrace_difo_t *new;
10749 	size_t sz;
10750 
10751 	ASSERT(dp->dtdo_buf != NULL);
10752 	ASSERT(dp->dtdo_refcnt != 0);
10753 
10754 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10755 
10756 	ASSERT(dp->dtdo_buf != NULL);
10757 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10758 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10759 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10760 	new->dtdo_len = dp->dtdo_len;
10761 
10762 	if (dp->dtdo_strtab != NULL) {
10763 		ASSERT(dp->dtdo_strlen != 0);
10764 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10765 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10766 		new->dtdo_strlen = dp->dtdo_strlen;
10767 	}
10768 
10769 	if (dp->dtdo_inttab != NULL) {
10770 		ASSERT(dp->dtdo_intlen != 0);
10771 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10772 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10773 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10774 		new->dtdo_intlen = dp->dtdo_intlen;
10775 	}
10776 
10777 	if (dp->dtdo_vartab != NULL) {
10778 		ASSERT(dp->dtdo_varlen != 0);
10779 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10780 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10781 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10782 		new->dtdo_varlen = dp->dtdo_varlen;
10783 	}
10784 
10785 	dtrace_difo_init(new, vstate);
10786 	return (new);
10787 }
10788 
10789 static void
10790 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10791 {
10792 	int i;
10793 
10794 	ASSERT(dp->dtdo_refcnt == 0);
10795 
10796 	for (i = 0; i < dp->dtdo_varlen; i++) {
10797 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10798 		dtrace_statvar_t *svar, **svarp = NULL;
10799 		uint_t id;
10800 		uint8_t scope = v->dtdv_scope;
10801 		int *np = NULL;
10802 
10803 		switch (scope) {
10804 		case DIFV_SCOPE_THREAD:
10805 			continue;
10806 
10807 		case DIFV_SCOPE_LOCAL:
10808 			np = &vstate->dtvs_nlocals;
10809 			svarp = vstate->dtvs_locals;
10810 			break;
10811 
10812 		case DIFV_SCOPE_GLOBAL:
10813 			np = &vstate->dtvs_nglobals;
10814 			svarp = vstate->dtvs_globals;
10815 			break;
10816 
10817 		default:
10818 			ASSERT(0);
10819 		}
10820 
10821 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10822 			continue;
10823 
10824 		id -= DIF_VAR_OTHER_UBASE;
10825 		ASSERT(id < *np);
10826 
10827 		svar = svarp[id];
10828 		ASSERT(svar != NULL);
10829 		ASSERT(svar->dtsv_refcnt > 0);
10830 
10831 		if (--svar->dtsv_refcnt > 0)
10832 			continue;
10833 
10834 		if (svar->dtsv_size != 0) {
10835 			ASSERT(svar->dtsv_data != 0);
10836 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10837 			    svar->dtsv_size);
10838 		}
10839 
10840 		kmem_free(svar, sizeof (dtrace_statvar_t));
10841 		svarp[id] = NULL;
10842 	}
10843 
10844 	if (dp->dtdo_buf != NULL)
10845 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10846 	if (dp->dtdo_inttab != NULL)
10847 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10848 	if (dp->dtdo_strtab != NULL)
10849 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10850 	if (dp->dtdo_vartab != NULL)
10851 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10852 
10853 	kmem_free(dp, sizeof (dtrace_difo_t));
10854 }
10855 
10856 static void
10857 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10858 {
10859 	int i;
10860 
10861 	ASSERT(MUTEX_HELD(&dtrace_lock));
10862 	ASSERT(dp->dtdo_refcnt != 0);
10863 
10864 	for (i = 0; i < dp->dtdo_varlen; i++) {
10865 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10866 
10867 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10868 			continue;
10869 
10870 		ASSERT(dtrace_vtime_references > 0);
10871 		if (--dtrace_vtime_references == 0)
10872 			dtrace_vtime_disable();
10873 	}
10874 
10875 	if (--dp->dtdo_refcnt == 0)
10876 		dtrace_difo_destroy(dp, vstate);
10877 }
10878 
10879 /*
10880  * DTrace Format Functions
10881  */
10882 static uint16_t
10883 dtrace_format_add(dtrace_state_t *state, char *str)
10884 {
10885 	char *fmt, **new;
10886 	uint16_t ndx, len = strlen(str) + 1;
10887 
10888 	fmt = kmem_zalloc(len, KM_SLEEP);
10889 	bcopy(str, fmt, len);
10890 
10891 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10892 		if (state->dts_formats[ndx] == NULL) {
10893 			state->dts_formats[ndx] = fmt;
10894 			return (ndx + 1);
10895 		}
10896 	}
10897 
10898 	if (state->dts_nformats == USHRT_MAX) {
10899 		/*
10900 		 * This is only likely if a denial-of-service attack is being
10901 		 * attempted.  As such, it's okay to fail silently here.
10902 		 */
10903 		kmem_free(fmt, len);
10904 		return (0);
10905 	}
10906 
10907 	/*
10908 	 * For simplicity, we always resize the formats array to be exactly the
10909 	 * number of formats.
10910 	 */
10911 	ndx = state->dts_nformats++;
10912 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10913 
10914 	if (state->dts_formats != NULL) {
10915 		ASSERT(ndx != 0);
10916 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10917 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10918 	}
10919 
10920 	state->dts_formats = new;
10921 	state->dts_formats[ndx] = fmt;
10922 
10923 	return (ndx + 1);
10924 }
10925 
10926 static void
10927 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10928 {
10929 	char *fmt;
10930 
10931 	ASSERT(state->dts_formats != NULL);
10932 	ASSERT(format <= state->dts_nformats);
10933 	ASSERT(state->dts_formats[format - 1] != NULL);
10934 
10935 	fmt = state->dts_formats[format - 1];
10936 	kmem_free(fmt, strlen(fmt) + 1);
10937 	state->dts_formats[format - 1] = NULL;
10938 }
10939 
10940 static void
10941 dtrace_format_destroy(dtrace_state_t *state)
10942 {
10943 	int i;
10944 
10945 	if (state->dts_nformats == 0) {
10946 		ASSERT(state->dts_formats == NULL);
10947 		return;
10948 	}
10949 
10950 	ASSERT(state->dts_formats != NULL);
10951 
10952 	for (i = 0; i < state->dts_nformats; i++) {
10953 		char *fmt = state->dts_formats[i];
10954 
10955 		if (fmt == NULL)
10956 			continue;
10957 
10958 		kmem_free(fmt, strlen(fmt) + 1);
10959 	}
10960 
10961 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10962 	state->dts_nformats = 0;
10963 	state->dts_formats = NULL;
10964 }
10965 
10966 /*
10967  * DTrace Predicate Functions
10968  */
10969 static dtrace_predicate_t *
10970 dtrace_predicate_create(dtrace_difo_t *dp)
10971 {
10972 	dtrace_predicate_t *pred;
10973 
10974 	ASSERT(MUTEX_HELD(&dtrace_lock));
10975 	ASSERT(dp->dtdo_refcnt != 0);
10976 
10977 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10978 	pred->dtp_difo = dp;
10979 	pred->dtp_refcnt = 1;
10980 
10981 	if (!dtrace_difo_cacheable(dp))
10982 		return (pred);
10983 
10984 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10985 		/*
10986 		 * This is only theoretically possible -- we have had 2^32
10987 		 * cacheable predicates on this machine.  We cannot allow any
10988 		 * more predicates to become cacheable:  as unlikely as it is,
10989 		 * there may be a thread caching a (now stale) predicate cache
10990 		 * ID. (N.B.: the temptation is being successfully resisted to
10991 		 * have this cmn_err() "Holy shit -- we executed this code!")
10992 		 */
10993 		return (pred);
10994 	}
10995 
10996 	pred->dtp_cacheid = dtrace_predcache_id++;
10997 
10998 	return (pred);
10999 }
11000 
11001 static void
11002 dtrace_predicate_hold(dtrace_predicate_t *pred)
11003 {
11004 	ASSERT(MUTEX_HELD(&dtrace_lock));
11005 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
11006 	ASSERT(pred->dtp_refcnt > 0);
11007 
11008 	pred->dtp_refcnt++;
11009 }
11010 
11011 static void
11012 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
11013 {
11014 	dtrace_difo_t *dp = pred->dtp_difo;
11015 
11016 	ASSERT(MUTEX_HELD(&dtrace_lock));
11017 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11018 	ASSERT(pred->dtp_refcnt > 0);
11019 
11020 	if (--pred->dtp_refcnt == 0) {
11021 		dtrace_difo_release(pred->dtp_difo, vstate);
11022 		kmem_free(pred, sizeof (dtrace_predicate_t));
11023 	}
11024 }
11025 
11026 /*
11027  * DTrace Action Description Functions
11028  */
11029 static dtrace_actdesc_t *
11030 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11031     uint64_t uarg, uint64_t arg)
11032 {
11033 	dtrace_actdesc_t *act;
11034 
11035 #ifdef illumos
11036 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11037 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11038 #endif
11039 
11040 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11041 	act->dtad_kind = kind;
11042 	act->dtad_ntuple = ntuple;
11043 	act->dtad_uarg = uarg;
11044 	act->dtad_arg = arg;
11045 	act->dtad_refcnt = 1;
11046 
11047 	return (act);
11048 }
11049 
11050 static void
11051 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11052 {
11053 	ASSERT(act->dtad_refcnt >= 1);
11054 	act->dtad_refcnt++;
11055 }
11056 
11057 static void
11058 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11059 {
11060 	dtrace_actkind_t kind = act->dtad_kind;
11061 	dtrace_difo_t *dp;
11062 
11063 	ASSERT(act->dtad_refcnt >= 1);
11064 
11065 	if (--act->dtad_refcnt != 0)
11066 		return;
11067 
11068 	if ((dp = act->dtad_difo) != NULL)
11069 		dtrace_difo_release(dp, vstate);
11070 
11071 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11072 		char *str = (char *)(uintptr_t)act->dtad_arg;
11073 
11074 #ifdef illumos
11075 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11076 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11077 #endif
11078 
11079 		if (str != NULL)
11080 			kmem_free(str, strlen(str) + 1);
11081 	}
11082 
11083 	kmem_free(act, sizeof (dtrace_actdesc_t));
11084 }
11085 
11086 /*
11087  * DTrace ECB Functions
11088  */
11089 static dtrace_ecb_t *
11090 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11091 {
11092 	dtrace_ecb_t *ecb;
11093 	dtrace_epid_t epid;
11094 
11095 	ASSERT(MUTEX_HELD(&dtrace_lock));
11096 
11097 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11098 	ecb->dte_predicate = NULL;
11099 	ecb->dte_probe = probe;
11100 
11101 	/*
11102 	 * The default size is the size of the default action: recording
11103 	 * the header.
11104 	 */
11105 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11106 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11107 
11108 	epid = state->dts_epid++;
11109 
11110 	if (epid - 1 >= state->dts_necbs) {
11111 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11112 		int necbs = state->dts_necbs << 1;
11113 
11114 		ASSERT(epid == state->dts_necbs + 1);
11115 
11116 		if (necbs == 0) {
11117 			ASSERT(oecbs == NULL);
11118 			necbs = 1;
11119 		}
11120 
11121 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11122 
11123 		if (oecbs != NULL)
11124 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11125 
11126 		dtrace_membar_producer();
11127 		state->dts_ecbs = ecbs;
11128 
11129 		if (oecbs != NULL) {
11130 			/*
11131 			 * If this state is active, we must dtrace_sync()
11132 			 * before we can free the old dts_ecbs array:  we're
11133 			 * coming in hot, and there may be active ring
11134 			 * buffer processing (which indexes into the dts_ecbs
11135 			 * array) on another CPU.
11136 			 */
11137 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11138 				dtrace_sync();
11139 
11140 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11141 		}
11142 
11143 		dtrace_membar_producer();
11144 		state->dts_necbs = necbs;
11145 	}
11146 
11147 	ecb->dte_state = state;
11148 
11149 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11150 	dtrace_membar_producer();
11151 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11152 
11153 	return (ecb);
11154 }
11155 
11156 static void
11157 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11158 {
11159 	dtrace_probe_t *probe = ecb->dte_probe;
11160 
11161 	ASSERT(MUTEX_HELD(&cpu_lock));
11162 	ASSERT(MUTEX_HELD(&dtrace_lock));
11163 	ASSERT(ecb->dte_next == NULL);
11164 
11165 	if (probe == NULL) {
11166 		/*
11167 		 * This is the NULL probe -- there's nothing to do.
11168 		 */
11169 		return;
11170 	}
11171 
11172 	if (probe->dtpr_ecb == NULL) {
11173 		dtrace_provider_t *prov = probe->dtpr_provider;
11174 
11175 		/*
11176 		 * We're the first ECB on this probe.
11177 		 */
11178 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11179 
11180 		if (ecb->dte_predicate != NULL)
11181 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11182 
11183 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11184 		    probe->dtpr_id, probe->dtpr_arg);
11185 	} else {
11186 		/*
11187 		 * This probe is already active.  Swing the last pointer to
11188 		 * point to the new ECB, and issue a dtrace_sync() to assure
11189 		 * that all CPUs have seen the change.
11190 		 */
11191 		ASSERT(probe->dtpr_ecb_last != NULL);
11192 		probe->dtpr_ecb_last->dte_next = ecb;
11193 		probe->dtpr_ecb_last = ecb;
11194 		probe->dtpr_predcache = 0;
11195 
11196 		dtrace_sync();
11197 	}
11198 }
11199 
11200 static int
11201 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11202 {
11203 	dtrace_action_t *act;
11204 	uint32_t curneeded = UINT32_MAX;
11205 	uint32_t aggbase = UINT32_MAX;
11206 
11207 	/*
11208 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11209 	 * we always record it first.)
11210 	 */
11211 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11212 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11213 
11214 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11215 		dtrace_recdesc_t *rec = &act->dta_rec;
11216 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11217 
11218 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11219 		    rec->dtrd_alignment);
11220 
11221 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11222 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11223 
11224 			ASSERT(rec->dtrd_size != 0);
11225 			ASSERT(agg->dtag_first != NULL);
11226 			ASSERT(act->dta_prev->dta_intuple);
11227 			ASSERT(aggbase != UINT32_MAX);
11228 			ASSERT(curneeded != UINT32_MAX);
11229 
11230 			agg->dtag_base = aggbase;
11231 
11232 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11233 			rec->dtrd_offset = curneeded;
11234 			if (curneeded + rec->dtrd_size < curneeded)
11235 				return (EINVAL);
11236 			curneeded += rec->dtrd_size;
11237 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11238 
11239 			aggbase = UINT32_MAX;
11240 			curneeded = UINT32_MAX;
11241 		} else if (act->dta_intuple) {
11242 			if (curneeded == UINT32_MAX) {
11243 				/*
11244 				 * This is the first record in a tuple.  Align
11245 				 * curneeded to be at offset 4 in an 8-byte
11246 				 * aligned block.
11247 				 */
11248 				ASSERT(act->dta_prev == NULL ||
11249 				    !act->dta_prev->dta_intuple);
11250 				ASSERT3U(aggbase, ==, UINT32_MAX);
11251 				curneeded = P2PHASEUP(ecb->dte_size,
11252 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11253 
11254 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11255 				ASSERT(IS_P2ALIGNED(aggbase,
11256 				    sizeof (uint64_t)));
11257 			}
11258 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11259 			rec->dtrd_offset = curneeded;
11260 			if (curneeded + rec->dtrd_size < curneeded)
11261 				return (EINVAL);
11262 			curneeded += rec->dtrd_size;
11263 		} else {
11264 			/* tuples must be followed by an aggregation */
11265 			ASSERT(act->dta_prev == NULL ||
11266 			    !act->dta_prev->dta_intuple);
11267 
11268 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11269 			    rec->dtrd_alignment);
11270 			rec->dtrd_offset = ecb->dte_size;
11271 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11272 				return (EINVAL);
11273 			ecb->dte_size += rec->dtrd_size;
11274 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11275 		}
11276 	}
11277 
11278 	if ((act = ecb->dte_action) != NULL &&
11279 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11280 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11281 		/*
11282 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11283 		 * actions store no data; set the size to 0.
11284 		 */
11285 		ecb->dte_size = 0;
11286 	}
11287 
11288 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11289 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11290 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11291 	    ecb->dte_needed);
11292 	return (0);
11293 }
11294 
11295 static dtrace_action_t *
11296 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11297 {
11298 	dtrace_aggregation_t *agg;
11299 	size_t size = sizeof (uint64_t);
11300 	int ntuple = desc->dtad_ntuple;
11301 	dtrace_action_t *act;
11302 	dtrace_recdesc_t *frec;
11303 	dtrace_aggid_t aggid;
11304 	dtrace_state_t *state = ecb->dte_state;
11305 
11306 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11307 	agg->dtag_ecb = ecb;
11308 
11309 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11310 
11311 	switch (desc->dtad_kind) {
11312 	case DTRACEAGG_MIN:
11313 		agg->dtag_initial = INT64_MAX;
11314 		agg->dtag_aggregate = dtrace_aggregate_min;
11315 		break;
11316 
11317 	case DTRACEAGG_MAX:
11318 		agg->dtag_initial = INT64_MIN;
11319 		agg->dtag_aggregate = dtrace_aggregate_max;
11320 		break;
11321 
11322 	case DTRACEAGG_COUNT:
11323 		agg->dtag_aggregate = dtrace_aggregate_count;
11324 		break;
11325 
11326 	case DTRACEAGG_QUANTIZE:
11327 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11328 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11329 		    sizeof (uint64_t);
11330 		break;
11331 
11332 	case DTRACEAGG_LQUANTIZE: {
11333 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11334 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11335 
11336 		agg->dtag_initial = desc->dtad_arg;
11337 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11338 
11339 		if (step == 0 || levels == 0)
11340 			goto err;
11341 
11342 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11343 		break;
11344 	}
11345 
11346 	case DTRACEAGG_LLQUANTIZE: {
11347 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11348 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11349 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11350 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11351 		int64_t v;
11352 
11353 		agg->dtag_initial = desc->dtad_arg;
11354 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11355 
11356 		if (factor < 2 || low >= high || nsteps < factor)
11357 			goto err;
11358 
11359 		/*
11360 		 * Now check that the number of steps evenly divides a power
11361 		 * of the factor.  (This assures both integer bucket size and
11362 		 * linearity within each magnitude.)
11363 		 */
11364 		for (v = factor; v < nsteps; v *= factor)
11365 			continue;
11366 
11367 		if ((v % nsteps) || (nsteps % factor))
11368 			goto err;
11369 
11370 		size = (dtrace_aggregate_llquantize_bucket(factor,
11371 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11372 		break;
11373 	}
11374 
11375 	case DTRACEAGG_AVG:
11376 		agg->dtag_aggregate = dtrace_aggregate_avg;
11377 		size = sizeof (uint64_t) * 2;
11378 		break;
11379 
11380 	case DTRACEAGG_STDDEV:
11381 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11382 		size = sizeof (uint64_t) * 4;
11383 		break;
11384 
11385 	case DTRACEAGG_SUM:
11386 		agg->dtag_aggregate = dtrace_aggregate_sum;
11387 		break;
11388 
11389 	default:
11390 		goto err;
11391 	}
11392 
11393 	agg->dtag_action.dta_rec.dtrd_size = size;
11394 
11395 	if (ntuple == 0)
11396 		goto err;
11397 
11398 	/*
11399 	 * We must make sure that we have enough actions for the n-tuple.
11400 	 */
11401 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11402 		if (DTRACEACT_ISAGG(act->dta_kind))
11403 			break;
11404 
11405 		if (--ntuple == 0) {
11406 			/*
11407 			 * This is the action with which our n-tuple begins.
11408 			 */
11409 			agg->dtag_first = act;
11410 			goto success;
11411 		}
11412 	}
11413 
11414 	/*
11415 	 * This n-tuple is short by ntuple elements.  Return failure.
11416 	 */
11417 	ASSERT(ntuple != 0);
11418 err:
11419 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11420 	return (NULL);
11421 
11422 success:
11423 	/*
11424 	 * If the last action in the tuple has a size of zero, it's actually
11425 	 * an expression argument for the aggregating action.
11426 	 */
11427 	ASSERT(ecb->dte_action_last != NULL);
11428 	act = ecb->dte_action_last;
11429 
11430 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11431 		ASSERT(act->dta_difo != NULL);
11432 
11433 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11434 			agg->dtag_hasarg = 1;
11435 	}
11436 
11437 	/*
11438 	 * We need to allocate an id for this aggregation.
11439 	 */
11440 #ifdef illumos
11441 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11442 	    VM_BESTFIT | VM_SLEEP);
11443 #else
11444 	aggid = alloc_unr(state->dts_aggid_arena);
11445 #endif
11446 
11447 	if (aggid - 1 >= state->dts_naggregations) {
11448 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11449 		dtrace_aggregation_t **aggs;
11450 		int naggs = state->dts_naggregations << 1;
11451 		int onaggs = state->dts_naggregations;
11452 
11453 		ASSERT(aggid == state->dts_naggregations + 1);
11454 
11455 		if (naggs == 0) {
11456 			ASSERT(oaggs == NULL);
11457 			naggs = 1;
11458 		}
11459 
11460 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11461 
11462 		if (oaggs != NULL) {
11463 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11464 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11465 		}
11466 
11467 		state->dts_aggregations = aggs;
11468 		state->dts_naggregations = naggs;
11469 	}
11470 
11471 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11472 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11473 
11474 	frec = &agg->dtag_first->dta_rec;
11475 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11476 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11477 
11478 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11479 		ASSERT(!act->dta_intuple);
11480 		act->dta_intuple = 1;
11481 	}
11482 
11483 	return (&agg->dtag_action);
11484 }
11485 
11486 static void
11487 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11488 {
11489 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11490 	dtrace_state_t *state = ecb->dte_state;
11491 	dtrace_aggid_t aggid = agg->dtag_id;
11492 
11493 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11494 #ifdef illumos
11495 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11496 #else
11497 	free_unr(state->dts_aggid_arena, aggid);
11498 #endif
11499 
11500 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11501 	state->dts_aggregations[aggid - 1] = NULL;
11502 
11503 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11504 }
11505 
11506 static int
11507 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11508 {
11509 	dtrace_action_t *action, *last;
11510 	dtrace_difo_t *dp = desc->dtad_difo;
11511 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11512 	uint16_t format = 0;
11513 	dtrace_recdesc_t *rec;
11514 	dtrace_state_t *state = ecb->dte_state;
11515 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11516 	uint64_t arg = desc->dtad_arg;
11517 
11518 	ASSERT(MUTEX_HELD(&dtrace_lock));
11519 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11520 
11521 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11522 		/*
11523 		 * If this is an aggregating action, there must be neither
11524 		 * a speculate nor a commit on the action chain.
11525 		 */
11526 		dtrace_action_t *act;
11527 
11528 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11529 			if (act->dta_kind == DTRACEACT_COMMIT)
11530 				return (EINVAL);
11531 
11532 			if (act->dta_kind == DTRACEACT_SPECULATE)
11533 				return (EINVAL);
11534 		}
11535 
11536 		action = dtrace_ecb_aggregation_create(ecb, desc);
11537 
11538 		if (action == NULL)
11539 			return (EINVAL);
11540 	} else {
11541 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11542 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11543 		    dp != NULL && dp->dtdo_destructive)) {
11544 			state->dts_destructive = 1;
11545 		}
11546 
11547 		switch (desc->dtad_kind) {
11548 		case DTRACEACT_PRINTF:
11549 		case DTRACEACT_PRINTA:
11550 		case DTRACEACT_SYSTEM:
11551 		case DTRACEACT_FREOPEN:
11552 		case DTRACEACT_DIFEXPR:
11553 			/*
11554 			 * We know that our arg is a string -- turn it into a
11555 			 * format.
11556 			 */
11557 			if (arg == 0) {
11558 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11559 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11560 				format = 0;
11561 			} else {
11562 				ASSERT(arg != 0);
11563 #ifdef illumos
11564 				ASSERT(arg > KERNELBASE);
11565 #endif
11566 				format = dtrace_format_add(state,
11567 				    (char *)(uintptr_t)arg);
11568 			}
11569 
11570 			/*FALLTHROUGH*/
11571 		case DTRACEACT_LIBACT:
11572 		case DTRACEACT_TRACEMEM:
11573 		case DTRACEACT_TRACEMEM_DYNSIZE:
11574 			if (dp == NULL)
11575 				return (EINVAL);
11576 
11577 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11578 				break;
11579 
11580 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11581 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11582 					return (EINVAL);
11583 
11584 				size = opt[DTRACEOPT_STRSIZE];
11585 			}
11586 
11587 			break;
11588 
11589 		case DTRACEACT_STACK:
11590 			if ((nframes = arg) == 0) {
11591 				nframes = opt[DTRACEOPT_STACKFRAMES];
11592 				ASSERT(nframes > 0);
11593 				arg = nframes;
11594 			}
11595 
11596 			size = nframes * sizeof (pc_t);
11597 			break;
11598 
11599 		case DTRACEACT_JSTACK:
11600 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11601 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11602 
11603 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11604 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11605 
11606 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11607 
11608 			/*FALLTHROUGH*/
11609 		case DTRACEACT_USTACK:
11610 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11611 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11612 				strsize = DTRACE_USTACK_STRSIZE(arg);
11613 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11614 				ASSERT(nframes > 0);
11615 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11616 			}
11617 
11618 			/*
11619 			 * Save a slot for the pid.
11620 			 */
11621 			size = (nframes + 1) * sizeof (uint64_t);
11622 			size += DTRACE_USTACK_STRSIZE(arg);
11623 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11624 
11625 			break;
11626 
11627 		case DTRACEACT_SYM:
11628 		case DTRACEACT_MOD:
11629 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11630 			    sizeof (uint64_t)) ||
11631 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11632 				return (EINVAL);
11633 			break;
11634 
11635 		case DTRACEACT_USYM:
11636 		case DTRACEACT_UMOD:
11637 		case DTRACEACT_UADDR:
11638 			if (dp == NULL ||
11639 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11640 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11641 				return (EINVAL);
11642 
11643 			/*
11644 			 * We have a slot for the pid, plus a slot for the
11645 			 * argument.  To keep things simple (aligned with
11646 			 * bitness-neutral sizing), we store each as a 64-bit
11647 			 * quantity.
11648 			 */
11649 			size = 2 * sizeof (uint64_t);
11650 			break;
11651 
11652 		case DTRACEACT_STOP:
11653 		case DTRACEACT_BREAKPOINT:
11654 		case DTRACEACT_PANIC:
11655 			break;
11656 
11657 		case DTRACEACT_CHILL:
11658 		case DTRACEACT_DISCARD:
11659 		case DTRACEACT_RAISE:
11660 			if (dp == NULL)
11661 				return (EINVAL);
11662 			break;
11663 
11664 		case DTRACEACT_EXIT:
11665 			if (dp == NULL ||
11666 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11667 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11668 				return (EINVAL);
11669 			break;
11670 
11671 		case DTRACEACT_SPECULATE:
11672 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11673 				return (EINVAL);
11674 
11675 			if (dp == NULL)
11676 				return (EINVAL);
11677 
11678 			state->dts_speculates = 1;
11679 			break;
11680 
11681 		case DTRACEACT_PRINTM:
11682 		    	size = dp->dtdo_rtype.dtdt_size;
11683 			break;
11684 
11685 		case DTRACEACT_COMMIT: {
11686 			dtrace_action_t *act = ecb->dte_action;
11687 
11688 			for (; act != NULL; act = act->dta_next) {
11689 				if (act->dta_kind == DTRACEACT_COMMIT)
11690 					return (EINVAL);
11691 			}
11692 
11693 			if (dp == NULL)
11694 				return (EINVAL);
11695 			break;
11696 		}
11697 
11698 		default:
11699 			return (EINVAL);
11700 		}
11701 
11702 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11703 			/*
11704 			 * If this is a data-storing action or a speculate,
11705 			 * we must be sure that there isn't a commit on the
11706 			 * action chain.
11707 			 */
11708 			dtrace_action_t *act = ecb->dte_action;
11709 
11710 			for (; act != NULL; act = act->dta_next) {
11711 				if (act->dta_kind == DTRACEACT_COMMIT)
11712 					return (EINVAL);
11713 			}
11714 		}
11715 
11716 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11717 		action->dta_rec.dtrd_size = size;
11718 	}
11719 
11720 	action->dta_refcnt = 1;
11721 	rec = &action->dta_rec;
11722 	size = rec->dtrd_size;
11723 
11724 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11725 		if (!(size & mask)) {
11726 			align = mask + 1;
11727 			break;
11728 		}
11729 	}
11730 
11731 	action->dta_kind = desc->dtad_kind;
11732 
11733 	if ((action->dta_difo = dp) != NULL)
11734 		dtrace_difo_hold(dp);
11735 
11736 	rec->dtrd_action = action->dta_kind;
11737 	rec->dtrd_arg = arg;
11738 	rec->dtrd_uarg = desc->dtad_uarg;
11739 	rec->dtrd_alignment = (uint16_t)align;
11740 	rec->dtrd_format = format;
11741 
11742 	if ((last = ecb->dte_action_last) != NULL) {
11743 		ASSERT(ecb->dte_action != NULL);
11744 		action->dta_prev = last;
11745 		last->dta_next = action;
11746 	} else {
11747 		ASSERT(ecb->dte_action == NULL);
11748 		ecb->dte_action = action;
11749 	}
11750 
11751 	ecb->dte_action_last = action;
11752 
11753 	return (0);
11754 }
11755 
11756 static void
11757 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11758 {
11759 	dtrace_action_t *act = ecb->dte_action, *next;
11760 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11761 	dtrace_difo_t *dp;
11762 	uint16_t format;
11763 
11764 	if (act != NULL && act->dta_refcnt > 1) {
11765 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11766 		act->dta_refcnt--;
11767 	} else {
11768 		for (; act != NULL; act = next) {
11769 			next = act->dta_next;
11770 			ASSERT(next != NULL || act == ecb->dte_action_last);
11771 			ASSERT(act->dta_refcnt == 1);
11772 
11773 			if ((format = act->dta_rec.dtrd_format) != 0)
11774 				dtrace_format_remove(ecb->dte_state, format);
11775 
11776 			if ((dp = act->dta_difo) != NULL)
11777 				dtrace_difo_release(dp, vstate);
11778 
11779 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11780 				dtrace_ecb_aggregation_destroy(ecb, act);
11781 			} else {
11782 				kmem_free(act, sizeof (dtrace_action_t));
11783 			}
11784 		}
11785 	}
11786 
11787 	ecb->dte_action = NULL;
11788 	ecb->dte_action_last = NULL;
11789 	ecb->dte_size = 0;
11790 }
11791 
11792 static void
11793 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11794 {
11795 	/*
11796 	 * We disable the ECB by removing it from its probe.
11797 	 */
11798 	dtrace_ecb_t *pecb, *prev = NULL;
11799 	dtrace_probe_t *probe = ecb->dte_probe;
11800 
11801 	ASSERT(MUTEX_HELD(&dtrace_lock));
11802 
11803 	if (probe == NULL) {
11804 		/*
11805 		 * This is the NULL probe; there is nothing to disable.
11806 		 */
11807 		return;
11808 	}
11809 
11810 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11811 		if (pecb == ecb)
11812 			break;
11813 		prev = pecb;
11814 	}
11815 
11816 	ASSERT(pecb != NULL);
11817 
11818 	if (prev == NULL) {
11819 		probe->dtpr_ecb = ecb->dte_next;
11820 	} else {
11821 		prev->dte_next = ecb->dte_next;
11822 	}
11823 
11824 	if (ecb == probe->dtpr_ecb_last) {
11825 		ASSERT(ecb->dte_next == NULL);
11826 		probe->dtpr_ecb_last = prev;
11827 	}
11828 
11829 	/*
11830 	 * The ECB has been disconnected from the probe; now sync to assure
11831 	 * that all CPUs have seen the change before returning.
11832 	 */
11833 	dtrace_sync();
11834 
11835 	if (probe->dtpr_ecb == NULL) {
11836 		/*
11837 		 * That was the last ECB on the probe; clear the predicate
11838 		 * cache ID for the probe, disable it and sync one more time
11839 		 * to assure that we'll never hit it again.
11840 		 */
11841 		dtrace_provider_t *prov = probe->dtpr_provider;
11842 
11843 		ASSERT(ecb->dte_next == NULL);
11844 		ASSERT(probe->dtpr_ecb_last == NULL);
11845 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11846 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11847 		    probe->dtpr_id, probe->dtpr_arg);
11848 		dtrace_sync();
11849 	} else {
11850 		/*
11851 		 * There is at least one ECB remaining on the probe.  If there
11852 		 * is _exactly_ one, set the probe's predicate cache ID to be
11853 		 * the predicate cache ID of the remaining ECB.
11854 		 */
11855 		ASSERT(probe->dtpr_ecb_last != NULL);
11856 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11857 
11858 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11859 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11860 
11861 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11862 
11863 			if (p != NULL)
11864 				probe->dtpr_predcache = p->dtp_cacheid;
11865 		}
11866 
11867 		ecb->dte_next = NULL;
11868 	}
11869 }
11870 
11871 static void
11872 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11873 {
11874 	dtrace_state_t *state = ecb->dte_state;
11875 	dtrace_vstate_t *vstate = &state->dts_vstate;
11876 	dtrace_predicate_t *pred;
11877 	dtrace_epid_t epid = ecb->dte_epid;
11878 
11879 	ASSERT(MUTEX_HELD(&dtrace_lock));
11880 	ASSERT(ecb->dte_next == NULL);
11881 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11882 
11883 	if ((pred = ecb->dte_predicate) != NULL)
11884 		dtrace_predicate_release(pred, vstate);
11885 
11886 	dtrace_ecb_action_remove(ecb);
11887 
11888 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11889 	state->dts_ecbs[epid - 1] = NULL;
11890 
11891 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11892 }
11893 
11894 static dtrace_ecb_t *
11895 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11896     dtrace_enabling_t *enab)
11897 {
11898 	dtrace_ecb_t *ecb;
11899 	dtrace_predicate_t *pred;
11900 	dtrace_actdesc_t *act;
11901 	dtrace_provider_t *prov;
11902 	dtrace_ecbdesc_t *desc = enab->dten_current;
11903 
11904 	ASSERT(MUTEX_HELD(&dtrace_lock));
11905 	ASSERT(state != NULL);
11906 
11907 	ecb = dtrace_ecb_add(state, probe);
11908 	ecb->dte_uarg = desc->dted_uarg;
11909 
11910 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11911 		dtrace_predicate_hold(pred);
11912 		ecb->dte_predicate = pred;
11913 	}
11914 
11915 	if (probe != NULL) {
11916 		/*
11917 		 * If the provider shows more leg than the consumer is old
11918 		 * enough to see, we need to enable the appropriate implicit
11919 		 * predicate bits to prevent the ecb from activating at
11920 		 * revealing times.
11921 		 *
11922 		 * Providers specifying DTRACE_PRIV_USER at register time
11923 		 * are stating that they need the /proc-style privilege
11924 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11925 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11926 		 */
11927 		prov = probe->dtpr_provider;
11928 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11929 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11930 			ecb->dte_cond |= DTRACE_COND_OWNER;
11931 
11932 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11933 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11934 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11935 
11936 		/*
11937 		 * If the provider shows us kernel innards and the user
11938 		 * is lacking sufficient privilege, enable the
11939 		 * DTRACE_COND_USERMODE implicit predicate.
11940 		 */
11941 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11942 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11943 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11944 	}
11945 
11946 	if (dtrace_ecb_create_cache != NULL) {
11947 		/*
11948 		 * If we have a cached ecb, we'll use its action list instead
11949 		 * of creating our own (saving both time and space).
11950 		 */
11951 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11952 		dtrace_action_t *act = cached->dte_action;
11953 
11954 		if (act != NULL) {
11955 			ASSERT(act->dta_refcnt > 0);
11956 			act->dta_refcnt++;
11957 			ecb->dte_action = act;
11958 			ecb->dte_action_last = cached->dte_action_last;
11959 			ecb->dte_needed = cached->dte_needed;
11960 			ecb->dte_size = cached->dte_size;
11961 			ecb->dte_alignment = cached->dte_alignment;
11962 		}
11963 
11964 		return (ecb);
11965 	}
11966 
11967 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11968 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11969 			dtrace_ecb_destroy(ecb);
11970 			return (NULL);
11971 		}
11972 	}
11973 
11974 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11975 		dtrace_ecb_destroy(ecb);
11976 		return (NULL);
11977 	}
11978 
11979 	return (dtrace_ecb_create_cache = ecb);
11980 }
11981 
11982 static int
11983 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11984 {
11985 	dtrace_ecb_t *ecb;
11986 	dtrace_enabling_t *enab = arg;
11987 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11988 
11989 	ASSERT(state != NULL);
11990 
11991 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11992 		/*
11993 		 * This probe was created in a generation for which this
11994 		 * enabling has previously created ECBs; we don't want to
11995 		 * enable it again, so just kick out.
11996 		 */
11997 		return (DTRACE_MATCH_NEXT);
11998 	}
11999 
12000 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
12001 		return (DTRACE_MATCH_DONE);
12002 
12003 	dtrace_ecb_enable(ecb);
12004 	return (DTRACE_MATCH_NEXT);
12005 }
12006 
12007 static dtrace_ecb_t *
12008 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
12009 {
12010 	dtrace_ecb_t *ecb;
12011 
12012 	ASSERT(MUTEX_HELD(&dtrace_lock));
12013 
12014 	if (id == 0 || id > state->dts_necbs)
12015 		return (NULL);
12016 
12017 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12018 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12019 
12020 	return (state->dts_ecbs[id - 1]);
12021 }
12022 
12023 static dtrace_aggregation_t *
12024 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12025 {
12026 	dtrace_aggregation_t *agg;
12027 
12028 	ASSERT(MUTEX_HELD(&dtrace_lock));
12029 
12030 	if (id == 0 || id > state->dts_naggregations)
12031 		return (NULL);
12032 
12033 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12034 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12035 	    agg->dtag_id == id);
12036 
12037 	return (state->dts_aggregations[id - 1]);
12038 }
12039 
12040 /*
12041  * DTrace Buffer Functions
12042  *
12043  * The following functions manipulate DTrace buffers.  Most of these functions
12044  * are called in the context of establishing or processing consumer state;
12045  * exceptions are explicitly noted.
12046  */
12047 
12048 /*
12049  * Note:  called from cross call context.  This function switches the two
12050  * buffers on a given CPU.  The atomicity of this operation is assured by
12051  * disabling interrupts while the actual switch takes place; the disabling of
12052  * interrupts serializes the execution with any execution of dtrace_probe() on
12053  * the same CPU.
12054  */
12055 static void
12056 dtrace_buffer_switch(dtrace_buffer_t *buf)
12057 {
12058 	caddr_t tomax = buf->dtb_tomax;
12059 	caddr_t xamot = buf->dtb_xamot;
12060 	dtrace_icookie_t cookie;
12061 	hrtime_t now;
12062 
12063 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12064 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12065 
12066 	cookie = dtrace_interrupt_disable();
12067 	now = dtrace_gethrtime();
12068 	buf->dtb_tomax = xamot;
12069 	buf->dtb_xamot = tomax;
12070 	buf->dtb_xamot_drops = buf->dtb_drops;
12071 	buf->dtb_xamot_offset = buf->dtb_offset;
12072 	buf->dtb_xamot_errors = buf->dtb_errors;
12073 	buf->dtb_xamot_flags = buf->dtb_flags;
12074 	buf->dtb_offset = 0;
12075 	buf->dtb_drops = 0;
12076 	buf->dtb_errors = 0;
12077 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12078 	buf->dtb_interval = now - buf->dtb_switched;
12079 	buf->dtb_switched = now;
12080 	dtrace_interrupt_enable(cookie);
12081 }
12082 
12083 /*
12084  * Note:  called from cross call context.  This function activates a buffer
12085  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12086  * is guaranteed by the disabling of interrupts.
12087  */
12088 static void
12089 dtrace_buffer_activate(dtrace_state_t *state)
12090 {
12091 	dtrace_buffer_t *buf;
12092 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12093 
12094 	buf = &state->dts_buffer[curcpu];
12095 
12096 	if (buf->dtb_tomax != NULL) {
12097 		/*
12098 		 * We might like to assert that the buffer is marked inactive,
12099 		 * but this isn't necessarily true:  the buffer for the CPU
12100 		 * that processes the BEGIN probe has its buffer activated
12101 		 * manually.  In this case, we take the (harmless) action
12102 		 * re-clearing the bit INACTIVE bit.
12103 		 */
12104 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12105 	}
12106 
12107 	dtrace_interrupt_enable(cookie);
12108 }
12109 
12110 #ifdef __FreeBSD__
12111 /*
12112  * Activate the specified per-CPU buffer.  This is used instead of
12113  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12114  * activating anonymous state.
12115  */
12116 static void
12117 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12118 {
12119 
12120 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12121 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12122 }
12123 #endif
12124 
12125 static int
12126 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12127     processorid_t cpu, int *factor)
12128 {
12129 #ifdef illumos
12130 	cpu_t *cp;
12131 #endif
12132 	dtrace_buffer_t *buf;
12133 	int allocated = 0, desired = 0;
12134 
12135 #ifdef illumos
12136 	ASSERT(MUTEX_HELD(&cpu_lock));
12137 	ASSERT(MUTEX_HELD(&dtrace_lock));
12138 
12139 	*factor = 1;
12140 
12141 	if (size > dtrace_nonroot_maxsize &&
12142 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12143 		return (EFBIG);
12144 
12145 	cp = cpu_list;
12146 
12147 	do {
12148 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12149 			continue;
12150 
12151 		buf = &bufs[cp->cpu_id];
12152 
12153 		/*
12154 		 * If there is already a buffer allocated for this CPU, it
12155 		 * is only possible that this is a DR event.  In this case,
12156 		 */
12157 		if (buf->dtb_tomax != NULL) {
12158 			ASSERT(buf->dtb_size == size);
12159 			continue;
12160 		}
12161 
12162 		ASSERT(buf->dtb_xamot == NULL);
12163 
12164 		if ((buf->dtb_tomax = kmem_zalloc(size,
12165 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12166 			goto err;
12167 
12168 		buf->dtb_size = size;
12169 		buf->dtb_flags = flags;
12170 		buf->dtb_offset = 0;
12171 		buf->dtb_drops = 0;
12172 
12173 		if (flags & DTRACEBUF_NOSWITCH)
12174 			continue;
12175 
12176 		if ((buf->dtb_xamot = kmem_zalloc(size,
12177 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12178 			goto err;
12179 	} while ((cp = cp->cpu_next) != cpu_list);
12180 
12181 	return (0);
12182 
12183 err:
12184 	cp = cpu_list;
12185 
12186 	do {
12187 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12188 			continue;
12189 
12190 		buf = &bufs[cp->cpu_id];
12191 		desired += 2;
12192 
12193 		if (buf->dtb_xamot != NULL) {
12194 			ASSERT(buf->dtb_tomax != NULL);
12195 			ASSERT(buf->dtb_size == size);
12196 			kmem_free(buf->dtb_xamot, size);
12197 			allocated++;
12198 		}
12199 
12200 		if (buf->dtb_tomax != NULL) {
12201 			ASSERT(buf->dtb_size == size);
12202 			kmem_free(buf->dtb_tomax, size);
12203 			allocated++;
12204 		}
12205 
12206 		buf->dtb_tomax = NULL;
12207 		buf->dtb_xamot = NULL;
12208 		buf->dtb_size = 0;
12209 	} while ((cp = cp->cpu_next) != cpu_list);
12210 #else
12211 	int i;
12212 
12213 	*factor = 1;
12214 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12215     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12216 	/*
12217 	 * FreeBSD isn't good at limiting the amount of memory we
12218 	 * ask to malloc, so let's place a limit here before trying
12219 	 * to do something that might well end in tears at bedtime.
12220 	 */
12221 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12222 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12223 		return (ENOMEM);
12224 #endif
12225 
12226 	ASSERT(MUTEX_HELD(&dtrace_lock));
12227 	CPU_FOREACH(i) {
12228 		if (cpu != DTRACE_CPUALL && cpu != i)
12229 			continue;
12230 
12231 		buf = &bufs[i];
12232 
12233 		/*
12234 		 * If there is already a buffer allocated for this CPU, it
12235 		 * is only possible that this is a DR event.  In this case,
12236 		 * the buffer size must match our specified size.
12237 		 */
12238 		if (buf->dtb_tomax != NULL) {
12239 			ASSERT(buf->dtb_size == size);
12240 			continue;
12241 		}
12242 
12243 		ASSERT(buf->dtb_xamot == NULL);
12244 
12245 		if ((buf->dtb_tomax = kmem_zalloc(size,
12246 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12247 			goto err;
12248 
12249 		buf->dtb_size = size;
12250 		buf->dtb_flags = flags;
12251 		buf->dtb_offset = 0;
12252 		buf->dtb_drops = 0;
12253 
12254 		if (flags & DTRACEBUF_NOSWITCH)
12255 			continue;
12256 
12257 		if ((buf->dtb_xamot = kmem_zalloc(size,
12258 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12259 			goto err;
12260 	}
12261 
12262 	return (0);
12263 
12264 err:
12265 	/*
12266 	 * Error allocating memory, so free the buffers that were
12267 	 * allocated before the failed allocation.
12268 	 */
12269 	CPU_FOREACH(i) {
12270 		if (cpu != DTRACE_CPUALL && cpu != i)
12271 			continue;
12272 
12273 		buf = &bufs[i];
12274 		desired += 2;
12275 
12276 		if (buf->dtb_xamot != NULL) {
12277 			ASSERT(buf->dtb_tomax != NULL);
12278 			ASSERT(buf->dtb_size == size);
12279 			kmem_free(buf->dtb_xamot, size);
12280 			allocated++;
12281 		}
12282 
12283 		if (buf->dtb_tomax != NULL) {
12284 			ASSERT(buf->dtb_size == size);
12285 			kmem_free(buf->dtb_tomax, size);
12286 			allocated++;
12287 		}
12288 
12289 		buf->dtb_tomax = NULL;
12290 		buf->dtb_xamot = NULL;
12291 		buf->dtb_size = 0;
12292 
12293 	}
12294 #endif
12295 	*factor = desired / (allocated > 0 ? allocated : 1);
12296 
12297 	return (ENOMEM);
12298 }
12299 
12300 /*
12301  * Note:  called from probe context.  This function just increments the drop
12302  * count on a buffer.  It has been made a function to allow for the
12303  * possibility of understanding the source of mysterious drop counts.  (A
12304  * problem for which one may be particularly disappointed that DTrace cannot
12305  * be used to understand DTrace.)
12306  */
12307 static void
12308 dtrace_buffer_drop(dtrace_buffer_t *buf)
12309 {
12310 	buf->dtb_drops++;
12311 }
12312 
12313 /*
12314  * Note:  called from probe context.  This function is called to reserve space
12315  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12316  * mstate.  Returns the new offset in the buffer, or a negative value if an
12317  * error has occurred.
12318  */
12319 static ssize_t
12320 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12321     dtrace_state_t *state, dtrace_mstate_t *mstate)
12322 {
12323 	ssize_t offs = buf->dtb_offset, soffs;
12324 	intptr_t woffs;
12325 	caddr_t tomax;
12326 	size_t total;
12327 
12328 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12329 		return (-1);
12330 
12331 	if ((tomax = buf->dtb_tomax) == NULL) {
12332 		dtrace_buffer_drop(buf);
12333 		return (-1);
12334 	}
12335 
12336 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12337 		while (offs & (align - 1)) {
12338 			/*
12339 			 * Assert that our alignment is off by a number which
12340 			 * is itself sizeof (uint32_t) aligned.
12341 			 */
12342 			ASSERT(!((align - (offs & (align - 1))) &
12343 			    (sizeof (uint32_t) - 1)));
12344 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12345 			offs += sizeof (uint32_t);
12346 		}
12347 
12348 		if ((soffs = offs + needed) > buf->dtb_size) {
12349 			dtrace_buffer_drop(buf);
12350 			return (-1);
12351 		}
12352 
12353 		if (mstate == NULL)
12354 			return (offs);
12355 
12356 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12357 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12358 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12359 
12360 		return (offs);
12361 	}
12362 
12363 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12364 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12365 		    (buf->dtb_flags & DTRACEBUF_FULL))
12366 			return (-1);
12367 		goto out;
12368 	}
12369 
12370 	total = needed + (offs & (align - 1));
12371 
12372 	/*
12373 	 * For a ring buffer, life is quite a bit more complicated.  Before
12374 	 * we can store any padding, we need to adjust our wrapping offset.
12375 	 * (If we've never before wrapped or we're not about to, no adjustment
12376 	 * is required.)
12377 	 */
12378 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12379 	    offs + total > buf->dtb_size) {
12380 		woffs = buf->dtb_xamot_offset;
12381 
12382 		if (offs + total > buf->dtb_size) {
12383 			/*
12384 			 * We can't fit in the end of the buffer.  First, a
12385 			 * sanity check that we can fit in the buffer at all.
12386 			 */
12387 			if (total > buf->dtb_size) {
12388 				dtrace_buffer_drop(buf);
12389 				return (-1);
12390 			}
12391 
12392 			/*
12393 			 * We're going to be storing at the top of the buffer,
12394 			 * so now we need to deal with the wrapped offset.  We
12395 			 * only reset our wrapped offset to 0 if it is
12396 			 * currently greater than the current offset.  If it
12397 			 * is less than the current offset, it is because a
12398 			 * previous allocation induced a wrap -- but the
12399 			 * allocation didn't subsequently take the space due
12400 			 * to an error or false predicate evaluation.  In this
12401 			 * case, we'll just leave the wrapped offset alone: if
12402 			 * the wrapped offset hasn't been advanced far enough
12403 			 * for this allocation, it will be adjusted in the
12404 			 * lower loop.
12405 			 */
12406 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12407 				if (woffs >= offs)
12408 					woffs = 0;
12409 			} else {
12410 				woffs = 0;
12411 			}
12412 
12413 			/*
12414 			 * Now we know that we're going to be storing to the
12415 			 * top of the buffer and that there is room for us
12416 			 * there.  We need to clear the buffer from the current
12417 			 * offset to the end (there may be old gunk there).
12418 			 */
12419 			while (offs < buf->dtb_size)
12420 				tomax[offs++] = 0;
12421 
12422 			/*
12423 			 * We need to set our offset to zero.  And because we
12424 			 * are wrapping, we need to set the bit indicating as
12425 			 * much.  We can also adjust our needed space back
12426 			 * down to the space required by the ECB -- we know
12427 			 * that the top of the buffer is aligned.
12428 			 */
12429 			offs = 0;
12430 			total = needed;
12431 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12432 		} else {
12433 			/*
12434 			 * There is room for us in the buffer, so we simply
12435 			 * need to check the wrapped offset.
12436 			 */
12437 			if (woffs < offs) {
12438 				/*
12439 				 * The wrapped offset is less than the offset.
12440 				 * This can happen if we allocated buffer space
12441 				 * that induced a wrap, but then we didn't
12442 				 * subsequently take the space due to an error
12443 				 * or false predicate evaluation.  This is
12444 				 * okay; we know that _this_ allocation isn't
12445 				 * going to induce a wrap.  We still can't
12446 				 * reset the wrapped offset to be zero,
12447 				 * however: the space may have been trashed in
12448 				 * the previous failed probe attempt.  But at
12449 				 * least the wrapped offset doesn't need to
12450 				 * be adjusted at all...
12451 				 */
12452 				goto out;
12453 			}
12454 		}
12455 
12456 		while (offs + total > woffs) {
12457 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12458 			size_t size;
12459 
12460 			if (epid == DTRACE_EPIDNONE) {
12461 				size = sizeof (uint32_t);
12462 			} else {
12463 				ASSERT3U(epid, <=, state->dts_necbs);
12464 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12465 
12466 				size = state->dts_ecbs[epid - 1]->dte_size;
12467 			}
12468 
12469 			ASSERT(woffs + size <= buf->dtb_size);
12470 			ASSERT(size != 0);
12471 
12472 			if (woffs + size == buf->dtb_size) {
12473 				/*
12474 				 * We've reached the end of the buffer; we want
12475 				 * to set the wrapped offset to 0 and break
12476 				 * out.  However, if the offs is 0, then we're
12477 				 * in a strange edge-condition:  the amount of
12478 				 * space that we want to reserve plus the size
12479 				 * of the record that we're overwriting is
12480 				 * greater than the size of the buffer.  This
12481 				 * is problematic because if we reserve the
12482 				 * space but subsequently don't consume it (due
12483 				 * to a failed predicate or error) the wrapped
12484 				 * offset will be 0 -- yet the EPID at offset 0
12485 				 * will not be committed.  This situation is
12486 				 * relatively easy to deal with:  if we're in
12487 				 * this case, the buffer is indistinguishable
12488 				 * from one that hasn't wrapped; we need only
12489 				 * finish the job by clearing the wrapped bit,
12490 				 * explicitly setting the offset to be 0, and
12491 				 * zero'ing out the old data in the buffer.
12492 				 */
12493 				if (offs == 0) {
12494 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12495 					buf->dtb_offset = 0;
12496 					woffs = total;
12497 
12498 					while (woffs < buf->dtb_size)
12499 						tomax[woffs++] = 0;
12500 				}
12501 
12502 				woffs = 0;
12503 				break;
12504 			}
12505 
12506 			woffs += size;
12507 		}
12508 
12509 		/*
12510 		 * We have a wrapped offset.  It may be that the wrapped offset
12511 		 * has become zero -- that's okay.
12512 		 */
12513 		buf->dtb_xamot_offset = woffs;
12514 	}
12515 
12516 out:
12517 	/*
12518 	 * Now we can plow the buffer with any necessary padding.
12519 	 */
12520 	while (offs & (align - 1)) {
12521 		/*
12522 		 * Assert that our alignment is off by a number which
12523 		 * is itself sizeof (uint32_t) aligned.
12524 		 */
12525 		ASSERT(!((align - (offs & (align - 1))) &
12526 		    (sizeof (uint32_t) - 1)));
12527 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12528 		offs += sizeof (uint32_t);
12529 	}
12530 
12531 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12532 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12533 			buf->dtb_flags |= DTRACEBUF_FULL;
12534 			return (-1);
12535 		}
12536 	}
12537 
12538 	if (mstate == NULL)
12539 		return (offs);
12540 
12541 	/*
12542 	 * For ring buffers and fill buffers, the scratch space is always
12543 	 * the inactive buffer.
12544 	 */
12545 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12546 	mstate->dtms_scratch_size = buf->dtb_size;
12547 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12548 
12549 	return (offs);
12550 }
12551 
12552 static void
12553 dtrace_buffer_polish(dtrace_buffer_t *buf)
12554 {
12555 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12556 	ASSERT(MUTEX_HELD(&dtrace_lock));
12557 
12558 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12559 		return;
12560 
12561 	/*
12562 	 * We need to polish the ring buffer.  There are three cases:
12563 	 *
12564 	 * - The first (and presumably most common) is that there is no gap
12565 	 *   between the buffer offset and the wrapped offset.  In this case,
12566 	 *   there is nothing in the buffer that isn't valid data; we can
12567 	 *   mark the buffer as polished and return.
12568 	 *
12569 	 * - The second (less common than the first but still more common
12570 	 *   than the third) is that there is a gap between the buffer offset
12571 	 *   and the wrapped offset, and the wrapped offset is larger than the
12572 	 *   buffer offset.  This can happen because of an alignment issue, or
12573 	 *   can happen because of a call to dtrace_buffer_reserve() that
12574 	 *   didn't subsequently consume the buffer space.  In this case,
12575 	 *   we need to zero the data from the buffer offset to the wrapped
12576 	 *   offset.
12577 	 *
12578 	 * - The third (and least common) is that there is a gap between the
12579 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12580 	 *   _less_ than the buffer offset.  This can only happen because a
12581 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12582 	 *   was not subsequently consumed.  In this case, we need to zero the
12583 	 *   space from the offset to the end of the buffer _and_ from the
12584 	 *   top of the buffer to the wrapped offset.
12585 	 */
12586 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12587 		bzero(buf->dtb_tomax + buf->dtb_offset,
12588 		    buf->dtb_xamot_offset - buf->dtb_offset);
12589 	}
12590 
12591 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12592 		bzero(buf->dtb_tomax + buf->dtb_offset,
12593 		    buf->dtb_size - buf->dtb_offset);
12594 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12595 	}
12596 }
12597 
12598 /*
12599  * This routine determines if data generated at the specified time has likely
12600  * been entirely consumed at user-level.  This routine is called to determine
12601  * if an ECB on a defunct probe (but for an active enabling) can be safely
12602  * disabled and destroyed.
12603  */
12604 static int
12605 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12606 {
12607 	int i;
12608 
12609 	CPU_FOREACH(i) {
12610 		dtrace_buffer_t *buf = &bufs[i];
12611 
12612 		if (buf->dtb_size == 0)
12613 			continue;
12614 
12615 		if (buf->dtb_flags & DTRACEBUF_RING)
12616 			return (0);
12617 
12618 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12619 			return (0);
12620 
12621 		if (buf->dtb_switched - buf->dtb_interval < when)
12622 			return (0);
12623 	}
12624 
12625 	return (1);
12626 }
12627 
12628 static void
12629 dtrace_buffer_free(dtrace_buffer_t *bufs)
12630 {
12631 	int i;
12632 
12633 	CPU_FOREACH(i) {
12634 		dtrace_buffer_t *buf = &bufs[i];
12635 
12636 		if (buf->dtb_tomax == NULL) {
12637 			ASSERT(buf->dtb_xamot == NULL);
12638 			ASSERT(buf->dtb_size == 0);
12639 			continue;
12640 		}
12641 
12642 		if (buf->dtb_xamot != NULL) {
12643 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12644 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12645 		}
12646 
12647 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12648 		buf->dtb_size = 0;
12649 		buf->dtb_tomax = NULL;
12650 		buf->dtb_xamot = NULL;
12651 	}
12652 }
12653 
12654 /*
12655  * DTrace Enabling Functions
12656  */
12657 static dtrace_enabling_t *
12658 dtrace_enabling_create(dtrace_vstate_t *vstate)
12659 {
12660 	dtrace_enabling_t *enab;
12661 
12662 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12663 	enab->dten_vstate = vstate;
12664 
12665 	return (enab);
12666 }
12667 
12668 static void
12669 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12670 {
12671 	dtrace_ecbdesc_t **ndesc;
12672 	size_t osize, nsize;
12673 
12674 	/*
12675 	 * We can't add to enablings after we've enabled them, or after we've
12676 	 * retained them.
12677 	 */
12678 	ASSERT(enab->dten_probegen == 0);
12679 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12680 
12681 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12682 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12683 		return;
12684 	}
12685 
12686 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12687 
12688 	if (enab->dten_maxdesc == 0) {
12689 		enab->dten_maxdesc = 1;
12690 	} else {
12691 		enab->dten_maxdesc <<= 1;
12692 	}
12693 
12694 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12695 
12696 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12697 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12698 	bcopy(enab->dten_desc, ndesc, osize);
12699 	if (enab->dten_desc != NULL)
12700 		kmem_free(enab->dten_desc, osize);
12701 
12702 	enab->dten_desc = ndesc;
12703 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12704 }
12705 
12706 static void
12707 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12708     dtrace_probedesc_t *pd)
12709 {
12710 	dtrace_ecbdesc_t *new;
12711 	dtrace_predicate_t *pred;
12712 	dtrace_actdesc_t *act;
12713 
12714 	/*
12715 	 * We're going to create a new ECB description that matches the
12716 	 * specified ECB in every way, but has the specified probe description.
12717 	 */
12718 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12719 
12720 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12721 		dtrace_predicate_hold(pred);
12722 
12723 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12724 		dtrace_actdesc_hold(act);
12725 
12726 	new->dted_action = ecb->dted_action;
12727 	new->dted_pred = ecb->dted_pred;
12728 	new->dted_probe = *pd;
12729 	new->dted_uarg = ecb->dted_uarg;
12730 
12731 	dtrace_enabling_add(enab, new);
12732 }
12733 
12734 static void
12735 dtrace_enabling_dump(dtrace_enabling_t *enab)
12736 {
12737 	int i;
12738 
12739 	for (i = 0; i < enab->dten_ndesc; i++) {
12740 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12741 
12742 #ifdef __FreeBSD__
12743 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12744 		    desc->dtpd_provider, desc->dtpd_mod,
12745 		    desc->dtpd_func, desc->dtpd_name);
12746 #else
12747 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12748 		    desc->dtpd_provider, desc->dtpd_mod,
12749 		    desc->dtpd_func, desc->dtpd_name);
12750 #endif
12751 	}
12752 }
12753 
12754 static void
12755 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12756 {
12757 	int i;
12758 	dtrace_ecbdesc_t *ep;
12759 	dtrace_vstate_t *vstate = enab->dten_vstate;
12760 
12761 	ASSERT(MUTEX_HELD(&dtrace_lock));
12762 
12763 	for (i = 0; i < enab->dten_ndesc; i++) {
12764 		dtrace_actdesc_t *act, *next;
12765 		dtrace_predicate_t *pred;
12766 
12767 		ep = enab->dten_desc[i];
12768 
12769 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12770 			dtrace_predicate_release(pred, vstate);
12771 
12772 		for (act = ep->dted_action; act != NULL; act = next) {
12773 			next = act->dtad_next;
12774 			dtrace_actdesc_release(act, vstate);
12775 		}
12776 
12777 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12778 	}
12779 
12780 	if (enab->dten_desc != NULL)
12781 		kmem_free(enab->dten_desc,
12782 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12783 
12784 	/*
12785 	 * If this was a retained enabling, decrement the dts_nretained count
12786 	 * and take it off of the dtrace_retained list.
12787 	 */
12788 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12789 	    dtrace_retained == enab) {
12790 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12791 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12792 		enab->dten_vstate->dtvs_state->dts_nretained--;
12793 		dtrace_retained_gen++;
12794 	}
12795 
12796 	if (enab->dten_prev == NULL) {
12797 		if (dtrace_retained == enab) {
12798 			dtrace_retained = enab->dten_next;
12799 
12800 			if (dtrace_retained != NULL)
12801 				dtrace_retained->dten_prev = NULL;
12802 		}
12803 	} else {
12804 		ASSERT(enab != dtrace_retained);
12805 		ASSERT(dtrace_retained != NULL);
12806 		enab->dten_prev->dten_next = enab->dten_next;
12807 	}
12808 
12809 	if (enab->dten_next != NULL) {
12810 		ASSERT(dtrace_retained != NULL);
12811 		enab->dten_next->dten_prev = enab->dten_prev;
12812 	}
12813 
12814 	kmem_free(enab, sizeof (dtrace_enabling_t));
12815 }
12816 
12817 static int
12818 dtrace_enabling_retain(dtrace_enabling_t *enab)
12819 {
12820 	dtrace_state_t *state;
12821 
12822 	ASSERT(MUTEX_HELD(&dtrace_lock));
12823 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12824 	ASSERT(enab->dten_vstate != NULL);
12825 
12826 	state = enab->dten_vstate->dtvs_state;
12827 	ASSERT(state != NULL);
12828 
12829 	/*
12830 	 * We only allow each state to retain dtrace_retain_max enablings.
12831 	 */
12832 	if (state->dts_nretained >= dtrace_retain_max)
12833 		return (ENOSPC);
12834 
12835 	state->dts_nretained++;
12836 	dtrace_retained_gen++;
12837 
12838 	if (dtrace_retained == NULL) {
12839 		dtrace_retained = enab;
12840 		return (0);
12841 	}
12842 
12843 	enab->dten_next = dtrace_retained;
12844 	dtrace_retained->dten_prev = enab;
12845 	dtrace_retained = enab;
12846 
12847 	return (0);
12848 }
12849 
12850 static int
12851 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12852     dtrace_probedesc_t *create)
12853 {
12854 	dtrace_enabling_t *new, *enab;
12855 	int found = 0, err = ENOENT;
12856 
12857 	ASSERT(MUTEX_HELD(&dtrace_lock));
12858 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12859 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12860 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12861 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12862 
12863 	new = dtrace_enabling_create(&state->dts_vstate);
12864 
12865 	/*
12866 	 * Iterate over all retained enablings, looking for enablings that
12867 	 * match the specified state.
12868 	 */
12869 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12870 		int i;
12871 
12872 		/*
12873 		 * dtvs_state can only be NULL for helper enablings -- and
12874 		 * helper enablings can't be retained.
12875 		 */
12876 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12877 
12878 		if (enab->dten_vstate->dtvs_state != state)
12879 			continue;
12880 
12881 		/*
12882 		 * Now iterate over each probe description; we're looking for
12883 		 * an exact match to the specified probe description.
12884 		 */
12885 		for (i = 0; i < enab->dten_ndesc; i++) {
12886 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12887 			dtrace_probedesc_t *pd = &ep->dted_probe;
12888 
12889 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12890 				continue;
12891 
12892 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12893 				continue;
12894 
12895 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12896 				continue;
12897 
12898 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12899 				continue;
12900 
12901 			/*
12902 			 * We have a winning probe!  Add it to our growing
12903 			 * enabling.
12904 			 */
12905 			found = 1;
12906 			dtrace_enabling_addlike(new, ep, create);
12907 		}
12908 	}
12909 
12910 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12911 		dtrace_enabling_destroy(new);
12912 		return (err);
12913 	}
12914 
12915 	return (0);
12916 }
12917 
12918 static void
12919 dtrace_enabling_retract(dtrace_state_t *state)
12920 {
12921 	dtrace_enabling_t *enab, *next;
12922 
12923 	ASSERT(MUTEX_HELD(&dtrace_lock));
12924 
12925 	/*
12926 	 * Iterate over all retained enablings, destroy the enablings retained
12927 	 * for the specified state.
12928 	 */
12929 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12930 		next = enab->dten_next;
12931 
12932 		/*
12933 		 * dtvs_state can only be NULL for helper enablings -- and
12934 		 * helper enablings can't be retained.
12935 		 */
12936 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12937 
12938 		if (enab->dten_vstate->dtvs_state == state) {
12939 			ASSERT(state->dts_nretained > 0);
12940 			dtrace_enabling_destroy(enab);
12941 		}
12942 	}
12943 
12944 	ASSERT(state->dts_nretained == 0);
12945 }
12946 
12947 static int
12948 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12949 {
12950 	int i = 0;
12951 	int matched = 0;
12952 
12953 	ASSERT(MUTEX_HELD(&cpu_lock));
12954 	ASSERT(MUTEX_HELD(&dtrace_lock));
12955 
12956 	for (i = 0; i < enab->dten_ndesc; i++) {
12957 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12958 
12959 		enab->dten_current = ep;
12960 		enab->dten_error = 0;
12961 
12962 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12963 
12964 		if (enab->dten_error != 0) {
12965 			/*
12966 			 * If we get an error half-way through enabling the
12967 			 * probes, we kick out -- perhaps with some number of
12968 			 * them enabled.  Leaving enabled probes enabled may
12969 			 * be slightly confusing for user-level, but we expect
12970 			 * that no one will attempt to actually drive on in
12971 			 * the face of such errors.  If this is an anonymous
12972 			 * enabling (indicated with a NULL nmatched pointer),
12973 			 * we cmn_err() a message.  We aren't expecting to
12974 			 * get such an error -- such as it can exist at all,
12975 			 * it would be a result of corrupted DOF in the driver
12976 			 * properties.
12977 			 */
12978 			if (nmatched == NULL) {
12979 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12980 				    "error on %p: %d", (void *)ep,
12981 				    enab->dten_error);
12982 			}
12983 
12984 			return (enab->dten_error);
12985 		}
12986 	}
12987 
12988 	enab->dten_probegen = dtrace_probegen;
12989 	if (nmatched != NULL)
12990 		*nmatched = matched;
12991 
12992 	return (0);
12993 }
12994 
12995 static void
12996 dtrace_enabling_matchall_task(void *args __unused)
12997 {
12998 	dtrace_enabling_matchall();
12999 }
13000 
13001 static void
13002 dtrace_enabling_matchall(void)
13003 {
13004 	dtrace_enabling_t *enab;
13005 
13006 	mutex_enter(&cpu_lock);
13007 	mutex_enter(&dtrace_lock);
13008 
13009 	/*
13010 	 * Iterate over all retained enablings to see if any probes match
13011 	 * against them.  We only perform this operation on enablings for which
13012 	 * we have sufficient permissions by virtue of being in the global zone
13013 	 * or in the same zone as the DTrace client.  Because we can be called
13014 	 * after dtrace_detach() has been called, we cannot assert that there
13015 	 * are retained enablings.  We can safely load from dtrace_retained,
13016 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
13017 	 * block pending our completion.
13018 	 */
13019 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13020 #ifdef illumos
13021 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
13022 
13023 		if (INGLOBALZONE(curproc) ||
13024 		    cr != NULL && getzoneid() == crgetzoneid(cr))
13025 #endif
13026 			(void) dtrace_enabling_match(enab, NULL);
13027 	}
13028 
13029 	mutex_exit(&dtrace_lock);
13030 	mutex_exit(&cpu_lock);
13031 }
13032 
13033 /*
13034  * If an enabling is to be enabled without having matched probes (that is, if
13035  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13036  * enabling must be _primed_ by creating an ECB for every ECB description.
13037  * This must be done to assure that we know the number of speculations, the
13038  * number of aggregations, the minimum buffer size needed, etc. before we
13039  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13040  * enabling any probes, we create ECBs for every ECB decription, but with a
13041  * NULL probe -- which is exactly what this function does.
13042  */
13043 static void
13044 dtrace_enabling_prime(dtrace_state_t *state)
13045 {
13046 	dtrace_enabling_t *enab;
13047 	int i;
13048 
13049 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13050 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13051 
13052 		if (enab->dten_vstate->dtvs_state != state)
13053 			continue;
13054 
13055 		/*
13056 		 * We don't want to prime an enabling more than once, lest
13057 		 * we allow a malicious user to induce resource exhaustion.
13058 		 * (The ECBs that result from priming an enabling aren't
13059 		 * leaked -- but they also aren't deallocated until the
13060 		 * consumer state is destroyed.)
13061 		 */
13062 		if (enab->dten_primed)
13063 			continue;
13064 
13065 		for (i = 0; i < enab->dten_ndesc; i++) {
13066 			enab->dten_current = enab->dten_desc[i];
13067 			(void) dtrace_probe_enable(NULL, enab);
13068 		}
13069 
13070 		enab->dten_primed = 1;
13071 	}
13072 }
13073 
13074 /*
13075  * Called to indicate that probes should be provided due to retained
13076  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13077  * must take an initial lap through the enabling calling the dtps_provide()
13078  * entry point explicitly to allow for autocreated probes.
13079  */
13080 static void
13081 dtrace_enabling_provide(dtrace_provider_t *prv)
13082 {
13083 	int i, all = 0;
13084 	dtrace_probedesc_t desc;
13085 	dtrace_genid_t gen;
13086 
13087 	ASSERT(MUTEX_HELD(&dtrace_lock));
13088 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13089 
13090 	if (prv == NULL) {
13091 		all = 1;
13092 		prv = dtrace_provider;
13093 	}
13094 
13095 	do {
13096 		dtrace_enabling_t *enab;
13097 		void *parg = prv->dtpv_arg;
13098 
13099 retry:
13100 		gen = dtrace_retained_gen;
13101 		for (enab = dtrace_retained; enab != NULL;
13102 		    enab = enab->dten_next) {
13103 			for (i = 0; i < enab->dten_ndesc; i++) {
13104 				desc = enab->dten_desc[i]->dted_probe;
13105 				mutex_exit(&dtrace_lock);
13106 				prv->dtpv_pops.dtps_provide(parg, &desc);
13107 				mutex_enter(&dtrace_lock);
13108 				/*
13109 				 * Process the retained enablings again if
13110 				 * they have changed while we weren't holding
13111 				 * dtrace_lock.
13112 				 */
13113 				if (gen != dtrace_retained_gen)
13114 					goto retry;
13115 			}
13116 		}
13117 	} while (all && (prv = prv->dtpv_next) != NULL);
13118 
13119 	mutex_exit(&dtrace_lock);
13120 	dtrace_probe_provide(NULL, all ? NULL : prv);
13121 	mutex_enter(&dtrace_lock);
13122 }
13123 
13124 /*
13125  * Called to reap ECBs that are attached to probes from defunct providers.
13126  */
13127 static void
13128 dtrace_enabling_reap(void *args __unused)
13129 {
13130 	dtrace_provider_t *prov;
13131 	dtrace_probe_t *probe;
13132 	dtrace_ecb_t *ecb;
13133 	hrtime_t when;
13134 	int i;
13135 
13136 	mutex_enter(&cpu_lock);
13137 	mutex_enter(&dtrace_lock);
13138 
13139 	for (i = 0; i < dtrace_nprobes; i++) {
13140 		if ((probe = dtrace_probes[i]) == NULL)
13141 			continue;
13142 
13143 		if (probe->dtpr_ecb == NULL)
13144 			continue;
13145 
13146 		prov = probe->dtpr_provider;
13147 
13148 		if ((when = prov->dtpv_defunct) == 0)
13149 			continue;
13150 
13151 		/*
13152 		 * We have ECBs on a defunct provider:  we want to reap these
13153 		 * ECBs to allow the provider to unregister.  The destruction
13154 		 * of these ECBs must be done carefully:  if we destroy the ECB
13155 		 * and the consumer later wishes to consume an EPID that
13156 		 * corresponds to the destroyed ECB (and if the EPID metadata
13157 		 * has not been previously consumed), the consumer will abort
13158 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13159 		 * eliminate) the possibility of this, we will only destroy an
13160 		 * ECB for a defunct provider if, for the state that
13161 		 * corresponds to the ECB:
13162 		 *
13163 		 *  (a)	There is no speculative tracing (which can effectively
13164 		 *	cache an EPID for an arbitrary amount of time).
13165 		 *
13166 		 *  (b)	The principal buffers have been switched twice since the
13167 		 *	provider became defunct.
13168 		 *
13169 		 *  (c)	The aggregation buffers are of zero size or have been
13170 		 *	switched twice since the provider became defunct.
13171 		 *
13172 		 * We use dts_speculates to determine (a) and call a function
13173 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13174 		 * that as soon as we've been unable to destroy one of the ECBs
13175 		 * associated with the probe, we quit trying -- reaping is only
13176 		 * fruitful in as much as we can destroy all ECBs associated
13177 		 * with the defunct provider's probes.
13178 		 */
13179 		while ((ecb = probe->dtpr_ecb) != NULL) {
13180 			dtrace_state_t *state = ecb->dte_state;
13181 			dtrace_buffer_t *buf = state->dts_buffer;
13182 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13183 
13184 			if (state->dts_speculates)
13185 				break;
13186 
13187 			if (!dtrace_buffer_consumed(buf, when))
13188 				break;
13189 
13190 			if (!dtrace_buffer_consumed(aggbuf, when))
13191 				break;
13192 
13193 			dtrace_ecb_disable(ecb);
13194 			ASSERT(probe->dtpr_ecb != ecb);
13195 			dtrace_ecb_destroy(ecb);
13196 		}
13197 	}
13198 
13199 	mutex_exit(&dtrace_lock);
13200 	mutex_exit(&cpu_lock);
13201 }
13202 
13203 /*
13204  * DTrace DOF Functions
13205  */
13206 /*ARGSUSED*/
13207 static void
13208 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13209 {
13210 	if (dtrace_err_verbose)
13211 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13212 
13213 #ifdef DTRACE_ERRDEBUG
13214 	dtrace_errdebug(str);
13215 #endif
13216 }
13217 
13218 /*
13219  * Create DOF out of a currently enabled state.  Right now, we only create
13220  * DOF containing the run-time options -- but this could be expanded to create
13221  * complete DOF representing the enabled state.
13222  */
13223 static dof_hdr_t *
13224 dtrace_dof_create(dtrace_state_t *state)
13225 {
13226 	dof_hdr_t *dof;
13227 	dof_sec_t *sec;
13228 	dof_optdesc_t *opt;
13229 	int i, len = sizeof (dof_hdr_t) +
13230 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13231 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13232 
13233 	ASSERT(MUTEX_HELD(&dtrace_lock));
13234 
13235 	dof = kmem_zalloc(len, KM_SLEEP);
13236 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13237 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13238 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13239 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13240 
13241 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13242 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13243 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13244 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13245 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13246 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13247 
13248 	dof->dofh_flags = 0;
13249 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13250 	dof->dofh_secsize = sizeof (dof_sec_t);
13251 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13252 	dof->dofh_secoff = sizeof (dof_hdr_t);
13253 	dof->dofh_loadsz = len;
13254 	dof->dofh_filesz = len;
13255 	dof->dofh_pad = 0;
13256 
13257 	/*
13258 	 * Fill in the option section header...
13259 	 */
13260 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13261 	sec->dofs_type = DOF_SECT_OPTDESC;
13262 	sec->dofs_align = sizeof (uint64_t);
13263 	sec->dofs_flags = DOF_SECF_LOAD;
13264 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13265 
13266 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13267 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13268 
13269 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13270 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13271 
13272 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13273 		opt[i].dofo_option = i;
13274 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13275 		opt[i].dofo_value = state->dts_options[i];
13276 	}
13277 
13278 	return (dof);
13279 }
13280 
13281 static dof_hdr_t *
13282 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13283 {
13284 	dof_hdr_t hdr, *dof;
13285 
13286 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13287 
13288 	/*
13289 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13290 	 */
13291 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13292 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13293 		*errp = EFAULT;
13294 		return (NULL);
13295 	}
13296 
13297 	/*
13298 	 * Now we'll allocate the entire DOF and copy it in -- provided
13299 	 * that the length isn't outrageous.
13300 	 */
13301 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13302 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13303 		*errp = E2BIG;
13304 		return (NULL);
13305 	}
13306 
13307 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13308 		dtrace_dof_error(&hdr, "invalid load size");
13309 		*errp = EINVAL;
13310 		return (NULL);
13311 	}
13312 
13313 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13314 
13315 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13316 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13317 		kmem_free(dof, hdr.dofh_loadsz);
13318 		*errp = EFAULT;
13319 		return (NULL);
13320 	}
13321 
13322 	return (dof);
13323 }
13324 
13325 #ifdef __FreeBSD__
13326 static dof_hdr_t *
13327 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13328 {
13329 	dof_hdr_t hdr, *dof;
13330 	struct thread *td;
13331 	size_t loadsz;
13332 
13333 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13334 
13335 	td = curthread;
13336 
13337 	/*
13338 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13339 	 */
13340 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13341 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13342 		*errp = EFAULT;
13343 		return (NULL);
13344 	}
13345 
13346 	/*
13347 	 * Now we'll allocate the entire DOF and copy it in -- provided
13348 	 * that the length isn't outrageous.
13349 	 */
13350 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13351 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13352 		*errp = E2BIG;
13353 		return (NULL);
13354 	}
13355 	loadsz = (size_t)hdr.dofh_loadsz;
13356 
13357 	if (loadsz < sizeof (hdr)) {
13358 		dtrace_dof_error(&hdr, "invalid load size");
13359 		*errp = EINVAL;
13360 		return (NULL);
13361 	}
13362 
13363 	dof = kmem_alloc(loadsz, KM_SLEEP);
13364 
13365 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13366 	    dof->dofh_loadsz != loadsz) {
13367 		kmem_free(dof, hdr.dofh_loadsz);
13368 		*errp = EFAULT;
13369 		return (NULL);
13370 	}
13371 
13372 	return (dof);
13373 }
13374 
13375 static __inline uchar_t
13376 dtrace_dof_char(char c)
13377 {
13378 
13379 	switch (c) {
13380 	case '0':
13381 	case '1':
13382 	case '2':
13383 	case '3':
13384 	case '4':
13385 	case '5':
13386 	case '6':
13387 	case '7':
13388 	case '8':
13389 	case '9':
13390 		return (c - '0');
13391 	case 'A':
13392 	case 'B':
13393 	case 'C':
13394 	case 'D':
13395 	case 'E':
13396 	case 'F':
13397 		return (c - 'A' + 10);
13398 	case 'a':
13399 	case 'b':
13400 	case 'c':
13401 	case 'd':
13402 	case 'e':
13403 	case 'f':
13404 		return (c - 'a' + 10);
13405 	}
13406 	/* Should not reach here. */
13407 	return (UCHAR_MAX);
13408 }
13409 #endif /* __FreeBSD__ */
13410 
13411 static dof_hdr_t *
13412 dtrace_dof_property(const char *name)
13413 {
13414 #ifdef __FreeBSD__
13415 	uint8_t *dofbuf;
13416 	u_char *data, *eol;
13417 	caddr_t doffile;
13418 	size_t bytes, len, i;
13419 	dof_hdr_t *dof;
13420 	u_char c1, c2;
13421 
13422 	dof = NULL;
13423 
13424 	doffile = preload_search_by_type("dtrace_dof");
13425 	if (doffile == NULL)
13426 		return (NULL);
13427 
13428 	data = preload_fetch_addr(doffile);
13429 	len = preload_fetch_size(doffile);
13430 	for (;;) {
13431 		/* Look for the end of the line. All lines end in a newline. */
13432 		eol = memchr(data, '\n', len);
13433 		if (eol == NULL)
13434 			return (NULL);
13435 
13436 		if (strncmp(name, data, strlen(name)) == 0)
13437 			break;
13438 
13439 		eol++; /* skip past the newline */
13440 		len -= eol - data;
13441 		data = eol;
13442 	}
13443 
13444 	/* We've found the data corresponding to the specified key. */
13445 
13446 	data += strlen(name) + 1; /* skip past the '=' */
13447 	len = eol - data;
13448 	if (len % 2 != 0) {
13449 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13450 		goto doferr;
13451 	}
13452 	bytes = len / 2;
13453 	if (bytes < sizeof(dof_hdr_t)) {
13454 		dtrace_dof_error(NULL, "truncated header");
13455 		goto doferr;
13456 	}
13457 
13458 	/*
13459 	 * Each byte is represented by the two ASCII characters in its hex
13460 	 * representation.
13461 	 */
13462 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13463 	for (i = 0; i < bytes; i++) {
13464 		c1 = dtrace_dof_char(data[i * 2]);
13465 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13466 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13467 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13468 			goto doferr;
13469 		}
13470 		dofbuf[i] = c1 * 16 + c2;
13471 	}
13472 
13473 	dof = (dof_hdr_t *)dofbuf;
13474 	if (bytes < dof->dofh_loadsz) {
13475 		dtrace_dof_error(NULL, "truncated DOF");
13476 		goto doferr;
13477 	}
13478 
13479 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13480 		dtrace_dof_error(NULL, "oversized DOF");
13481 		goto doferr;
13482 	}
13483 
13484 	return (dof);
13485 
13486 doferr:
13487 	free(dof, M_SOLARIS);
13488 	return (NULL);
13489 #else /* __FreeBSD__ */
13490 	uchar_t *buf;
13491 	uint64_t loadsz;
13492 	unsigned int len, i;
13493 	dof_hdr_t *dof;
13494 
13495 	/*
13496 	 * Unfortunately, array of values in .conf files are always (and
13497 	 * only) interpreted to be integer arrays.  We must read our DOF
13498 	 * as an integer array, and then squeeze it into a byte array.
13499 	 */
13500 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13501 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13502 		return (NULL);
13503 
13504 	for (i = 0; i < len; i++)
13505 		buf[i] = (uchar_t)(((int *)buf)[i]);
13506 
13507 	if (len < sizeof (dof_hdr_t)) {
13508 		ddi_prop_free(buf);
13509 		dtrace_dof_error(NULL, "truncated header");
13510 		return (NULL);
13511 	}
13512 
13513 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13514 		ddi_prop_free(buf);
13515 		dtrace_dof_error(NULL, "truncated DOF");
13516 		return (NULL);
13517 	}
13518 
13519 	if (loadsz >= dtrace_dof_maxsize) {
13520 		ddi_prop_free(buf);
13521 		dtrace_dof_error(NULL, "oversized DOF");
13522 		return (NULL);
13523 	}
13524 
13525 	dof = kmem_alloc(loadsz, KM_SLEEP);
13526 	bcopy(buf, dof, loadsz);
13527 	ddi_prop_free(buf);
13528 
13529 	return (dof);
13530 #endif /* !__FreeBSD__ */
13531 }
13532 
13533 static void
13534 dtrace_dof_destroy(dof_hdr_t *dof)
13535 {
13536 	kmem_free(dof, dof->dofh_loadsz);
13537 }
13538 
13539 /*
13540  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13541  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13542  * a type other than DOF_SECT_NONE is specified, the header is checked against
13543  * this type and NULL is returned if the types do not match.
13544  */
13545 static dof_sec_t *
13546 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13547 {
13548 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13549 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13550 
13551 	if (i >= dof->dofh_secnum) {
13552 		dtrace_dof_error(dof, "referenced section index is invalid");
13553 		return (NULL);
13554 	}
13555 
13556 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13557 		dtrace_dof_error(dof, "referenced section is not loadable");
13558 		return (NULL);
13559 	}
13560 
13561 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13562 		dtrace_dof_error(dof, "referenced section is the wrong type");
13563 		return (NULL);
13564 	}
13565 
13566 	return (sec);
13567 }
13568 
13569 static dtrace_probedesc_t *
13570 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13571 {
13572 	dof_probedesc_t *probe;
13573 	dof_sec_t *strtab;
13574 	uintptr_t daddr = (uintptr_t)dof;
13575 	uintptr_t str;
13576 	size_t size;
13577 
13578 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13579 		dtrace_dof_error(dof, "invalid probe section");
13580 		return (NULL);
13581 	}
13582 
13583 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13584 		dtrace_dof_error(dof, "bad alignment in probe description");
13585 		return (NULL);
13586 	}
13587 
13588 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13589 		dtrace_dof_error(dof, "truncated probe description");
13590 		return (NULL);
13591 	}
13592 
13593 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13594 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13595 
13596 	if (strtab == NULL)
13597 		return (NULL);
13598 
13599 	str = daddr + strtab->dofs_offset;
13600 	size = strtab->dofs_size;
13601 
13602 	if (probe->dofp_provider >= strtab->dofs_size) {
13603 		dtrace_dof_error(dof, "corrupt probe provider");
13604 		return (NULL);
13605 	}
13606 
13607 	(void) strncpy(desc->dtpd_provider,
13608 	    (char *)(str + probe->dofp_provider),
13609 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13610 
13611 	if (probe->dofp_mod >= strtab->dofs_size) {
13612 		dtrace_dof_error(dof, "corrupt probe module");
13613 		return (NULL);
13614 	}
13615 
13616 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13617 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13618 
13619 	if (probe->dofp_func >= strtab->dofs_size) {
13620 		dtrace_dof_error(dof, "corrupt probe function");
13621 		return (NULL);
13622 	}
13623 
13624 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13625 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13626 
13627 	if (probe->dofp_name >= strtab->dofs_size) {
13628 		dtrace_dof_error(dof, "corrupt probe name");
13629 		return (NULL);
13630 	}
13631 
13632 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13633 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13634 
13635 	return (desc);
13636 }
13637 
13638 static dtrace_difo_t *
13639 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13640     cred_t *cr)
13641 {
13642 	dtrace_difo_t *dp;
13643 	size_t ttl = 0;
13644 	dof_difohdr_t *dofd;
13645 	uintptr_t daddr = (uintptr_t)dof;
13646 	size_t max = dtrace_difo_maxsize;
13647 	int i, l, n;
13648 
13649 	static const struct {
13650 		int section;
13651 		int bufoffs;
13652 		int lenoffs;
13653 		int entsize;
13654 		int align;
13655 		const char *msg;
13656 	} difo[] = {
13657 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13658 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13659 		sizeof (dif_instr_t), "multiple DIF sections" },
13660 
13661 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13662 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13663 		sizeof (uint64_t), "multiple integer tables" },
13664 
13665 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13666 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13667 		sizeof (char), "multiple string tables" },
13668 
13669 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13670 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13671 		sizeof (uint_t), "multiple variable tables" },
13672 
13673 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13674 	};
13675 
13676 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13677 		dtrace_dof_error(dof, "invalid DIFO header section");
13678 		return (NULL);
13679 	}
13680 
13681 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13682 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13683 		return (NULL);
13684 	}
13685 
13686 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13687 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13688 		dtrace_dof_error(dof, "bad size in DIFO header");
13689 		return (NULL);
13690 	}
13691 
13692 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13693 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13694 
13695 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13696 	dp->dtdo_rtype = dofd->dofd_rtype;
13697 
13698 	for (l = 0; l < n; l++) {
13699 		dof_sec_t *subsec;
13700 		void **bufp;
13701 		uint32_t *lenp;
13702 
13703 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13704 		    dofd->dofd_links[l])) == NULL)
13705 			goto err; /* invalid section link */
13706 
13707 		if (ttl + subsec->dofs_size > max) {
13708 			dtrace_dof_error(dof, "exceeds maximum size");
13709 			goto err;
13710 		}
13711 
13712 		ttl += subsec->dofs_size;
13713 
13714 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13715 			if (subsec->dofs_type != difo[i].section)
13716 				continue;
13717 
13718 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13719 				dtrace_dof_error(dof, "section not loaded");
13720 				goto err;
13721 			}
13722 
13723 			if (subsec->dofs_align != difo[i].align) {
13724 				dtrace_dof_error(dof, "bad alignment");
13725 				goto err;
13726 			}
13727 
13728 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13729 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13730 
13731 			if (*bufp != NULL) {
13732 				dtrace_dof_error(dof, difo[i].msg);
13733 				goto err;
13734 			}
13735 
13736 			if (difo[i].entsize != subsec->dofs_entsize) {
13737 				dtrace_dof_error(dof, "entry size mismatch");
13738 				goto err;
13739 			}
13740 
13741 			if (subsec->dofs_entsize != 0 &&
13742 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13743 				dtrace_dof_error(dof, "corrupt entry size");
13744 				goto err;
13745 			}
13746 
13747 			*lenp = subsec->dofs_size;
13748 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13749 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13750 			    *bufp, subsec->dofs_size);
13751 
13752 			if (subsec->dofs_entsize != 0)
13753 				*lenp /= subsec->dofs_entsize;
13754 
13755 			break;
13756 		}
13757 
13758 		/*
13759 		 * If we encounter a loadable DIFO sub-section that is not
13760 		 * known to us, assume this is a broken program and fail.
13761 		 */
13762 		if (difo[i].section == DOF_SECT_NONE &&
13763 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13764 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13765 			goto err;
13766 		}
13767 	}
13768 
13769 	if (dp->dtdo_buf == NULL) {
13770 		/*
13771 		 * We can't have a DIF object without DIF text.
13772 		 */
13773 		dtrace_dof_error(dof, "missing DIF text");
13774 		goto err;
13775 	}
13776 
13777 	/*
13778 	 * Before we validate the DIF object, run through the variable table
13779 	 * looking for the strings -- if any of their size are under, we'll set
13780 	 * their size to be the system-wide default string size.  Note that
13781 	 * this should _not_ happen if the "strsize" option has been set --
13782 	 * in this case, the compiler should have set the size to reflect the
13783 	 * setting of the option.
13784 	 */
13785 	for (i = 0; i < dp->dtdo_varlen; i++) {
13786 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13787 		dtrace_diftype_t *t = &v->dtdv_type;
13788 
13789 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13790 			continue;
13791 
13792 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13793 			t->dtdt_size = dtrace_strsize_default;
13794 	}
13795 
13796 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13797 		goto err;
13798 
13799 	dtrace_difo_init(dp, vstate);
13800 	return (dp);
13801 
13802 err:
13803 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13804 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13805 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13806 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13807 
13808 	kmem_free(dp, sizeof (dtrace_difo_t));
13809 	return (NULL);
13810 }
13811 
13812 static dtrace_predicate_t *
13813 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13814     cred_t *cr)
13815 {
13816 	dtrace_difo_t *dp;
13817 
13818 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13819 		return (NULL);
13820 
13821 	return (dtrace_predicate_create(dp));
13822 }
13823 
13824 static dtrace_actdesc_t *
13825 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13826     cred_t *cr)
13827 {
13828 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13829 	dof_actdesc_t *desc;
13830 	dof_sec_t *difosec;
13831 	size_t offs;
13832 	uintptr_t daddr = (uintptr_t)dof;
13833 	uint64_t arg;
13834 	dtrace_actkind_t kind;
13835 
13836 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13837 		dtrace_dof_error(dof, "invalid action section");
13838 		return (NULL);
13839 	}
13840 
13841 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13842 		dtrace_dof_error(dof, "truncated action description");
13843 		return (NULL);
13844 	}
13845 
13846 	if (sec->dofs_align != sizeof (uint64_t)) {
13847 		dtrace_dof_error(dof, "bad alignment in action description");
13848 		return (NULL);
13849 	}
13850 
13851 	if (sec->dofs_size < sec->dofs_entsize) {
13852 		dtrace_dof_error(dof, "section entry size exceeds total size");
13853 		return (NULL);
13854 	}
13855 
13856 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13857 		dtrace_dof_error(dof, "bad entry size in action description");
13858 		return (NULL);
13859 	}
13860 
13861 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13862 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13863 		return (NULL);
13864 	}
13865 
13866 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13867 		desc = (dof_actdesc_t *)(daddr +
13868 		    (uintptr_t)sec->dofs_offset + offs);
13869 		kind = (dtrace_actkind_t)desc->dofa_kind;
13870 
13871 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13872 		    (kind != DTRACEACT_PRINTA ||
13873 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13874 		    (kind == DTRACEACT_DIFEXPR &&
13875 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13876 			dof_sec_t *strtab;
13877 			char *str, *fmt;
13878 			uint64_t i;
13879 
13880 			/*
13881 			 * The argument to these actions is an index into the
13882 			 * DOF string table.  For printf()-like actions, this
13883 			 * is the format string.  For print(), this is the
13884 			 * CTF type of the expression result.
13885 			 */
13886 			if ((strtab = dtrace_dof_sect(dof,
13887 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13888 				goto err;
13889 
13890 			str = (char *)((uintptr_t)dof +
13891 			    (uintptr_t)strtab->dofs_offset);
13892 
13893 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13894 				if (str[i] == '\0')
13895 					break;
13896 			}
13897 
13898 			if (i >= strtab->dofs_size) {
13899 				dtrace_dof_error(dof, "bogus format string");
13900 				goto err;
13901 			}
13902 
13903 			if (i == desc->dofa_arg) {
13904 				dtrace_dof_error(dof, "empty format string");
13905 				goto err;
13906 			}
13907 
13908 			i -= desc->dofa_arg;
13909 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13910 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13911 			arg = (uint64_t)(uintptr_t)fmt;
13912 		} else {
13913 			if (kind == DTRACEACT_PRINTA) {
13914 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13915 				arg = 0;
13916 			} else {
13917 				arg = desc->dofa_arg;
13918 			}
13919 		}
13920 
13921 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13922 		    desc->dofa_uarg, arg);
13923 
13924 		if (last != NULL) {
13925 			last->dtad_next = act;
13926 		} else {
13927 			first = act;
13928 		}
13929 
13930 		last = act;
13931 
13932 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13933 			continue;
13934 
13935 		if ((difosec = dtrace_dof_sect(dof,
13936 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13937 			goto err;
13938 
13939 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13940 
13941 		if (act->dtad_difo == NULL)
13942 			goto err;
13943 	}
13944 
13945 	ASSERT(first != NULL);
13946 	return (first);
13947 
13948 err:
13949 	for (act = first; act != NULL; act = next) {
13950 		next = act->dtad_next;
13951 		dtrace_actdesc_release(act, vstate);
13952 	}
13953 
13954 	return (NULL);
13955 }
13956 
13957 static dtrace_ecbdesc_t *
13958 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13959     cred_t *cr)
13960 {
13961 	dtrace_ecbdesc_t *ep;
13962 	dof_ecbdesc_t *ecb;
13963 	dtrace_probedesc_t *desc;
13964 	dtrace_predicate_t *pred = NULL;
13965 
13966 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13967 		dtrace_dof_error(dof, "truncated ECB description");
13968 		return (NULL);
13969 	}
13970 
13971 	if (sec->dofs_align != sizeof (uint64_t)) {
13972 		dtrace_dof_error(dof, "bad alignment in ECB description");
13973 		return (NULL);
13974 	}
13975 
13976 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13977 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13978 
13979 	if (sec == NULL)
13980 		return (NULL);
13981 
13982 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13983 	ep->dted_uarg = ecb->dofe_uarg;
13984 	desc = &ep->dted_probe;
13985 
13986 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13987 		goto err;
13988 
13989 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13990 		if ((sec = dtrace_dof_sect(dof,
13991 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13992 			goto err;
13993 
13994 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13995 			goto err;
13996 
13997 		ep->dted_pred.dtpdd_predicate = pred;
13998 	}
13999 
14000 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
14001 		if ((sec = dtrace_dof_sect(dof,
14002 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
14003 			goto err;
14004 
14005 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
14006 
14007 		if (ep->dted_action == NULL)
14008 			goto err;
14009 	}
14010 
14011 	return (ep);
14012 
14013 err:
14014 	if (pred != NULL)
14015 		dtrace_predicate_release(pred, vstate);
14016 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
14017 	return (NULL);
14018 }
14019 
14020 /*
14021  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
14022  * specified DOF.  SETX relocations are computed using 'ubase', the base load
14023  * address of the object containing the DOF, and DOFREL relocations are relative
14024  * to the relocation offset within the DOF.
14025  */
14026 static int
14027 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14028     uint64_t udaddr)
14029 {
14030 	uintptr_t daddr = (uintptr_t)dof;
14031 	uintptr_t ts_end;
14032 	dof_relohdr_t *dofr =
14033 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14034 	dof_sec_t *ss, *rs, *ts;
14035 	dof_relodesc_t *r;
14036 	uint_t i, n;
14037 
14038 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14039 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14040 		dtrace_dof_error(dof, "invalid relocation header");
14041 		return (-1);
14042 	}
14043 
14044 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14045 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14046 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14047 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14048 
14049 	if (ss == NULL || rs == NULL || ts == NULL)
14050 		return (-1); /* dtrace_dof_error() has been called already */
14051 
14052 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14053 	    rs->dofs_align != sizeof (uint64_t)) {
14054 		dtrace_dof_error(dof, "invalid relocation section");
14055 		return (-1);
14056 	}
14057 
14058 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14059 	n = rs->dofs_size / rs->dofs_entsize;
14060 
14061 	for (i = 0; i < n; i++) {
14062 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14063 
14064 		switch (r->dofr_type) {
14065 		case DOF_RELO_NONE:
14066 			break;
14067 		case DOF_RELO_SETX:
14068 		case DOF_RELO_DOFREL:
14069 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14070 			    sizeof (uint64_t) > ts->dofs_size) {
14071 				dtrace_dof_error(dof, "bad relocation offset");
14072 				return (-1);
14073 			}
14074 
14075 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14076 				dtrace_dof_error(dof, "bad relocation offset");
14077 				return (-1);
14078 			}
14079 
14080 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14081 				dtrace_dof_error(dof, "misaligned setx relo");
14082 				return (-1);
14083 			}
14084 
14085 			if (r->dofr_type == DOF_RELO_SETX)
14086 				*(uint64_t *)taddr += ubase;
14087 			else
14088 				*(uint64_t *)taddr +=
14089 				    udaddr + ts->dofs_offset + r->dofr_offset;
14090 			break;
14091 		default:
14092 			dtrace_dof_error(dof, "invalid relocation type");
14093 			return (-1);
14094 		}
14095 
14096 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14097 	}
14098 
14099 	return (0);
14100 }
14101 
14102 /*
14103  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14104  * header:  it should be at the front of a memory region that is at least
14105  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14106  * size.  It need not be validated in any other way.
14107  */
14108 static int
14109 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14110     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14111 {
14112 	uint64_t len = dof->dofh_loadsz, seclen;
14113 	uintptr_t daddr = (uintptr_t)dof;
14114 	dtrace_ecbdesc_t *ep;
14115 	dtrace_enabling_t *enab;
14116 	uint_t i;
14117 
14118 	ASSERT(MUTEX_HELD(&dtrace_lock));
14119 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14120 
14121 	/*
14122 	 * Check the DOF header identification bytes.  In addition to checking
14123 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14124 	 * we can use them later without fear of regressing existing binaries.
14125 	 */
14126 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14127 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14128 		dtrace_dof_error(dof, "DOF magic string mismatch");
14129 		return (-1);
14130 	}
14131 
14132 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14133 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14134 		dtrace_dof_error(dof, "DOF has invalid data model");
14135 		return (-1);
14136 	}
14137 
14138 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14139 		dtrace_dof_error(dof, "DOF encoding mismatch");
14140 		return (-1);
14141 	}
14142 
14143 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14144 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14145 		dtrace_dof_error(dof, "DOF version mismatch");
14146 		return (-1);
14147 	}
14148 
14149 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14150 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14151 		return (-1);
14152 	}
14153 
14154 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14155 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14156 		return (-1);
14157 	}
14158 
14159 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14160 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14161 		return (-1);
14162 	}
14163 
14164 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14165 		if (dof->dofh_ident[i] != 0) {
14166 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14167 			return (-1);
14168 		}
14169 	}
14170 
14171 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14172 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14173 		return (-1);
14174 	}
14175 
14176 	if (dof->dofh_secsize == 0) {
14177 		dtrace_dof_error(dof, "zero section header size");
14178 		return (-1);
14179 	}
14180 
14181 	/*
14182 	 * Check that the section headers don't exceed the amount of DOF
14183 	 * data.  Note that we cast the section size and number of sections
14184 	 * to uint64_t's to prevent possible overflow in the multiplication.
14185 	 */
14186 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14187 
14188 	if (dof->dofh_secoff > len || seclen > len ||
14189 	    dof->dofh_secoff + seclen > len) {
14190 		dtrace_dof_error(dof, "truncated section headers");
14191 		return (-1);
14192 	}
14193 
14194 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14195 		dtrace_dof_error(dof, "misaligned section headers");
14196 		return (-1);
14197 	}
14198 
14199 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14200 		dtrace_dof_error(dof, "misaligned section size");
14201 		return (-1);
14202 	}
14203 
14204 	/*
14205 	 * Take an initial pass through the section headers to be sure that
14206 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14207 	 * set, do not permit sections relating to providers, probes, or args.
14208 	 */
14209 	for (i = 0; i < dof->dofh_secnum; i++) {
14210 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14211 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14212 
14213 		if (noprobes) {
14214 			switch (sec->dofs_type) {
14215 			case DOF_SECT_PROVIDER:
14216 			case DOF_SECT_PROBES:
14217 			case DOF_SECT_PRARGS:
14218 			case DOF_SECT_PROFFS:
14219 				dtrace_dof_error(dof, "illegal sections "
14220 				    "for enabling");
14221 				return (-1);
14222 			}
14223 		}
14224 
14225 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14226 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14227 			dtrace_dof_error(dof, "loadable section with load "
14228 			    "flag unset");
14229 			return (-1);
14230 		}
14231 
14232 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14233 			continue; /* just ignore non-loadable sections */
14234 
14235 		if (!ISP2(sec->dofs_align)) {
14236 			dtrace_dof_error(dof, "bad section alignment");
14237 			return (-1);
14238 		}
14239 
14240 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14241 			dtrace_dof_error(dof, "misaligned section");
14242 			return (-1);
14243 		}
14244 
14245 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14246 		    sec->dofs_offset + sec->dofs_size > len) {
14247 			dtrace_dof_error(dof, "corrupt section header");
14248 			return (-1);
14249 		}
14250 
14251 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14252 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14253 			dtrace_dof_error(dof, "non-terminating string table");
14254 			return (-1);
14255 		}
14256 	}
14257 
14258 	/*
14259 	 * Take a second pass through the sections and locate and perform any
14260 	 * relocations that are present.  We do this after the first pass to
14261 	 * be sure that all sections have had their headers validated.
14262 	 */
14263 	for (i = 0; i < dof->dofh_secnum; i++) {
14264 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14265 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14266 
14267 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14268 			continue; /* skip sections that are not loadable */
14269 
14270 		switch (sec->dofs_type) {
14271 		case DOF_SECT_URELHDR:
14272 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14273 				return (-1);
14274 			break;
14275 		}
14276 	}
14277 
14278 	if ((enab = *enabp) == NULL)
14279 		enab = *enabp = dtrace_enabling_create(vstate);
14280 
14281 	for (i = 0; i < dof->dofh_secnum; i++) {
14282 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14283 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14284 
14285 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14286 			continue;
14287 
14288 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14289 			dtrace_enabling_destroy(enab);
14290 			*enabp = NULL;
14291 			return (-1);
14292 		}
14293 
14294 		dtrace_enabling_add(enab, ep);
14295 	}
14296 
14297 	return (0);
14298 }
14299 
14300 /*
14301  * Process DOF for any options.  This routine assumes that the DOF has been
14302  * at least processed by dtrace_dof_slurp().
14303  */
14304 static int
14305 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14306 {
14307 	int i, rval;
14308 	uint32_t entsize;
14309 	size_t offs;
14310 	dof_optdesc_t *desc;
14311 
14312 	for (i = 0; i < dof->dofh_secnum; i++) {
14313 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14314 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14315 
14316 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14317 			continue;
14318 
14319 		if (sec->dofs_align != sizeof (uint64_t)) {
14320 			dtrace_dof_error(dof, "bad alignment in "
14321 			    "option description");
14322 			return (EINVAL);
14323 		}
14324 
14325 		if ((entsize = sec->dofs_entsize) == 0) {
14326 			dtrace_dof_error(dof, "zeroed option entry size");
14327 			return (EINVAL);
14328 		}
14329 
14330 		if (entsize < sizeof (dof_optdesc_t)) {
14331 			dtrace_dof_error(dof, "bad option entry size");
14332 			return (EINVAL);
14333 		}
14334 
14335 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14336 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14337 			    (uintptr_t)sec->dofs_offset + offs);
14338 
14339 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14340 				dtrace_dof_error(dof, "non-zero option string");
14341 				return (EINVAL);
14342 			}
14343 
14344 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14345 				dtrace_dof_error(dof, "unset option");
14346 				return (EINVAL);
14347 			}
14348 
14349 			if ((rval = dtrace_state_option(state,
14350 			    desc->dofo_option, desc->dofo_value)) != 0) {
14351 				dtrace_dof_error(dof, "rejected option");
14352 				return (rval);
14353 			}
14354 		}
14355 	}
14356 
14357 	return (0);
14358 }
14359 
14360 /*
14361  * DTrace Consumer State Functions
14362  */
14363 static int
14364 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14365 {
14366 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14367 	void *base;
14368 	uintptr_t limit;
14369 	dtrace_dynvar_t *dvar, *next, *start;
14370 	int i;
14371 
14372 	ASSERT(MUTEX_HELD(&dtrace_lock));
14373 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14374 
14375 	bzero(dstate, sizeof (dtrace_dstate_t));
14376 
14377 	if ((dstate->dtds_chunksize = chunksize) == 0)
14378 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14379 
14380 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14381 
14382 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14383 		size = min;
14384 
14385 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14386 		return (ENOMEM);
14387 
14388 	dstate->dtds_size = size;
14389 	dstate->dtds_base = base;
14390 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14391 	bzero(dstate->dtds_percpu,
14392 	    (mp_maxid + 1) * sizeof (dtrace_dstate_percpu_t));
14393 
14394 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14395 
14396 	if (hashsize != 1 && (hashsize & 1))
14397 		hashsize--;
14398 
14399 	dstate->dtds_hashsize = hashsize;
14400 	dstate->dtds_hash = dstate->dtds_base;
14401 
14402 	/*
14403 	 * Set all of our hash buckets to point to the single sink, and (if
14404 	 * it hasn't already been set), set the sink's hash value to be the
14405 	 * sink sentinel value.  The sink is needed for dynamic variable
14406 	 * lookups to know that they have iterated over an entire, valid hash
14407 	 * chain.
14408 	 */
14409 	for (i = 0; i < hashsize; i++)
14410 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14411 
14412 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14413 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14414 
14415 	/*
14416 	 * Determine number of active CPUs.  Divide free list evenly among
14417 	 * active CPUs.
14418 	 */
14419 	start = (dtrace_dynvar_t *)
14420 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14421 	limit = (uintptr_t)base + size;
14422 
14423 	VERIFY((uintptr_t)start < limit);
14424 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14425 
14426 	maxper = (limit - (uintptr_t)start) / (mp_maxid + 1);
14427 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14428 
14429 	CPU_FOREACH(i) {
14430 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14431 
14432 		/*
14433 		 * If we don't even have enough chunks to make it once through
14434 		 * NCPUs, we're just going to allocate everything to the first
14435 		 * CPU.  And if we're on the last CPU, we're going to allocate
14436 		 * whatever is left over.  In either case, we set the limit to
14437 		 * be the limit of the dynamic variable space.
14438 		 */
14439 		if (maxper == 0 || i == mp_maxid) {
14440 			limit = (uintptr_t)base + size;
14441 			start = NULL;
14442 		} else {
14443 			limit = (uintptr_t)start + maxper;
14444 			start = (dtrace_dynvar_t *)limit;
14445 		}
14446 
14447 		VERIFY(limit <= (uintptr_t)base + size);
14448 
14449 		for (;;) {
14450 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14451 			    dstate->dtds_chunksize);
14452 
14453 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14454 				break;
14455 
14456 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14457 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14458 			dvar->dtdv_next = next;
14459 			dvar = next;
14460 		}
14461 
14462 		if (maxper == 0)
14463 			break;
14464 	}
14465 
14466 	return (0);
14467 }
14468 
14469 static void
14470 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14471 {
14472 	ASSERT(MUTEX_HELD(&cpu_lock));
14473 
14474 	if (dstate->dtds_base == NULL)
14475 		return;
14476 
14477 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14478 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14479 }
14480 
14481 static void
14482 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14483 {
14484 	/*
14485 	 * Logical XOR, where are you?
14486 	 */
14487 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14488 
14489 	if (vstate->dtvs_nglobals > 0) {
14490 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14491 		    sizeof (dtrace_statvar_t *));
14492 	}
14493 
14494 	if (vstate->dtvs_ntlocals > 0) {
14495 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14496 		    sizeof (dtrace_difv_t));
14497 	}
14498 
14499 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14500 
14501 	if (vstate->dtvs_nlocals > 0) {
14502 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14503 		    sizeof (dtrace_statvar_t *));
14504 	}
14505 }
14506 
14507 #ifdef illumos
14508 static void
14509 dtrace_state_clean(dtrace_state_t *state)
14510 {
14511 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14512 		return;
14513 
14514 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14515 	dtrace_speculation_clean(state);
14516 }
14517 
14518 static void
14519 dtrace_state_deadman(dtrace_state_t *state)
14520 {
14521 	hrtime_t now;
14522 
14523 	dtrace_sync();
14524 
14525 	now = dtrace_gethrtime();
14526 
14527 	if (state != dtrace_anon.dta_state &&
14528 	    now - state->dts_laststatus >= dtrace_deadman_user)
14529 		return;
14530 
14531 	/*
14532 	 * We must be sure that dts_alive never appears to be less than the
14533 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14534 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14535 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14536 	 * the new value.  This assures that dts_alive never appears to be
14537 	 * less than its true value, regardless of the order in which the
14538 	 * stores to the underlying storage are issued.
14539 	 */
14540 	state->dts_alive = INT64_MAX;
14541 	dtrace_membar_producer();
14542 	state->dts_alive = now;
14543 }
14544 #else	/* !illumos */
14545 static void
14546 dtrace_state_clean(void *arg)
14547 {
14548 	dtrace_state_t *state = arg;
14549 	dtrace_optval_t *opt = state->dts_options;
14550 
14551 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14552 		return;
14553 
14554 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14555 	dtrace_speculation_clean(state);
14556 
14557 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14558 	    dtrace_state_clean, state);
14559 }
14560 
14561 static void
14562 dtrace_state_deadman(void *arg)
14563 {
14564 	dtrace_state_t *state = arg;
14565 	hrtime_t now;
14566 
14567 	dtrace_sync();
14568 
14569 	dtrace_debug_output();
14570 
14571 	now = dtrace_gethrtime();
14572 
14573 	if (state != dtrace_anon.dta_state &&
14574 	    now - state->dts_laststatus >= dtrace_deadman_user)
14575 		return;
14576 
14577 	/*
14578 	 * We must be sure that dts_alive never appears to be less than the
14579 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14580 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14581 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14582 	 * the new value.  This assures that dts_alive never appears to be
14583 	 * less than its true value, regardless of the order in which the
14584 	 * stores to the underlying storage are issued.
14585 	 */
14586 	state->dts_alive = INT64_MAX;
14587 	dtrace_membar_producer();
14588 	state->dts_alive = now;
14589 
14590 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14591 	    dtrace_state_deadman, state);
14592 }
14593 #endif	/* illumos */
14594 
14595 static dtrace_state_t *
14596 #ifdef illumos
14597 dtrace_state_create(dev_t *devp, cred_t *cr)
14598 #else
14599 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14600 #endif
14601 {
14602 #ifdef illumos
14603 	minor_t minor;
14604 	major_t major;
14605 #else
14606 	cred_t *cr = NULL;
14607 	int m = 0;
14608 #endif
14609 	char c[30];
14610 	dtrace_state_t *state;
14611 	dtrace_optval_t *opt;
14612 	int bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t), i;
14613 	int cpu_it;
14614 
14615 	ASSERT(MUTEX_HELD(&dtrace_lock));
14616 	ASSERT(MUTEX_HELD(&cpu_lock));
14617 
14618 #ifdef illumos
14619 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14620 	    VM_BESTFIT | VM_SLEEP);
14621 
14622 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14623 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14624 		return (NULL);
14625 	}
14626 
14627 	state = ddi_get_soft_state(dtrace_softstate, minor);
14628 #else
14629 	if (dev != NULL) {
14630 		cr = dev->si_cred;
14631 		m = dev2unit(dev);
14632 	}
14633 
14634 	/* Allocate memory for the state. */
14635 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14636 #endif
14637 
14638 	state->dts_epid = DTRACE_EPIDNONE + 1;
14639 
14640 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14641 #ifdef illumos
14642 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14643 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14644 
14645 	if (devp != NULL) {
14646 		major = getemajor(*devp);
14647 	} else {
14648 		major = ddi_driver_major(dtrace_devi);
14649 	}
14650 
14651 	state->dts_dev = makedevice(major, minor);
14652 
14653 	if (devp != NULL)
14654 		*devp = state->dts_dev;
14655 #else
14656 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14657 	state->dts_dev = dev;
14658 #endif
14659 
14660 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14661 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14662 
14663 	/*
14664          * Allocate and initialise the per-process per-CPU random state.
14665 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14666          * assumed to be seeded at this point (if from Fortuna seed file).
14667 	 */
14668 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14669 	for (cpu_it = 1; cpu_it <= mp_maxid; cpu_it++) {
14670 		/*
14671 		 * Each CPU is assigned a 2^64 period, non-overlapping
14672 		 * subsequence.
14673 		 */
14674 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it - 1],
14675 		    state->dts_rstate[cpu_it]);
14676 	}
14677 
14678 #ifdef illumos
14679 	state->dts_cleaner = CYCLIC_NONE;
14680 	state->dts_deadman = CYCLIC_NONE;
14681 #else
14682 	callout_init(&state->dts_cleaner, 1);
14683 	callout_init(&state->dts_deadman, 1);
14684 #endif
14685 	state->dts_vstate.dtvs_state = state;
14686 
14687 	for (i = 0; i < DTRACEOPT_MAX; i++)
14688 		state->dts_options[i] = DTRACEOPT_UNSET;
14689 
14690 	/*
14691 	 * Set the default options.
14692 	 */
14693 	opt = state->dts_options;
14694 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14695 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14696 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14697 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14698 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14699 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14700 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14701 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14702 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14703 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14704 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14705 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14706 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14707 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14708 
14709 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14710 
14711 	/*
14712 	 * Depending on the user credentials, we set flag bits which alter probe
14713 	 * visibility or the amount of destructiveness allowed.  In the case of
14714 	 * actual anonymous tracing, or the possession of all privileges, all of
14715 	 * the normal checks are bypassed.
14716 	 */
14717 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14718 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14719 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14720 	} else {
14721 		/*
14722 		 * Set up the credentials for this instantiation.  We take a
14723 		 * hold on the credential to prevent it from disappearing on
14724 		 * us; this in turn prevents the zone_t referenced by this
14725 		 * credential from disappearing.  This means that we can
14726 		 * examine the credential and the zone from probe context.
14727 		 */
14728 		crhold(cr);
14729 		state->dts_cred.dcr_cred = cr;
14730 
14731 		/*
14732 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14733 		 * unlocks the use of variables like pid, zonename, etc.
14734 		 */
14735 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14736 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14737 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14738 		}
14739 
14740 		/*
14741 		 * dtrace_user allows use of syscall and profile providers.
14742 		 * If the user also has proc_owner and/or proc_zone, we
14743 		 * extend the scope to include additional visibility and
14744 		 * destructive power.
14745 		 */
14746 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14747 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14748 				state->dts_cred.dcr_visible |=
14749 				    DTRACE_CRV_ALLPROC;
14750 
14751 				state->dts_cred.dcr_action |=
14752 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14753 			}
14754 
14755 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14756 				state->dts_cred.dcr_visible |=
14757 				    DTRACE_CRV_ALLZONE;
14758 
14759 				state->dts_cred.dcr_action |=
14760 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14761 			}
14762 
14763 			/*
14764 			 * If we have all privs in whatever zone this is,
14765 			 * we can do destructive things to processes which
14766 			 * have altered credentials.
14767 			 */
14768 #ifdef illumos
14769 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14770 			    cr->cr_zone->zone_privset)) {
14771 				state->dts_cred.dcr_action |=
14772 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14773 			}
14774 #endif
14775 		}
14776 
14777 		/*
14778 		 * Holding the dtrace_kernel privilege also implies that
14779 		 * the user has the dtrace_user privilege from a visibility
14780 		 * perspective.  But without further privileges, some
14781 		 * destructive actions are not available.
14782 		 */
14783 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14784 			/*
14785 			 * Make all probes in all zones visible.  However,
14786 			 * this doesn't mean that all actions become available
14787 			 * to all zones.
14788 			 */
14789 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14790 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14791 
14792 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14793 			    DTRACE_CRA_PROC;
14794 			/*
14795 			 * Holding proc_owner means that destructive actions
14796 			 * for *this* zone are allowed.
14797 			 */
14798 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14799 				state->dts_cred.dcr_action |=
14800 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14801 
14802 			/*
14803 			 * Holding proc_zone means that destructive actions
14804 			 * for this user/group ID in all zones is allowed.
14805 			 */
14806 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14807 				state->dts_cred.dcr_action |=
14808 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14809 
14810 #ifdef illumos
14811 			/*
14812 			 * If we have all privs in whatever zone this is,
14813 			 * we can do destructive things to processes which
14814 			 * have altered credentials.
14815 			 */
14816 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14817 			    cr->cr_zone->zone_privset)) {
14818 				state->dts_cred.dcr_action |=
14819 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14820 			}
14821 #endif
14822 		}
14823 
14824 		/*
14825 		 * Holding the dtrace_proc privilege gives control over fasttrap
14826 		 * and pid providers.  We need to grant wider destructive
14827 		 * privileges in the event that the user has proc_owner and/or
14828 		 * proc_zone.
14829 		 */
14830 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14831 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14832 				state->dts_cred.dcr_action |=
14833 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14834 
14835 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14836 				state->dts_cred.dcr_action |=
14837 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14838 		}
14839 	}
14840 
14841 	return (state);
14842 }
14843 
14844 static int
14845 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14846 {
14847 	dtrace_optval_t *opt = state->dts_options, size;
14848 	processorid_t cpu = 0;
14849 	int flags = 0, rval, factor, divisor = 1;
14850 
14851 	ASSERT(MUTEX_HELD(&dtrace_lock));
14852 	ASSERT(MUTEX_HELD(&cpu_lock));
14853 	ASSERT(which < DTRACEOPT_MAX);
14854 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14855 	    (state == dtrace_anon.dta_state &&
14856 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14857 
14858 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14859 		return (0);
14860 
14861 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14862 		cpu = opt[DTRACEOPT_CPU];
14863 
14864 	if (which == DTRACEOPT_SPECSIZE)
14865 		flags |= DTRACEBUF_NOSWITCH;
14866 
14867 	if (which == DTRACEOPT_BUFSIZE) {
14868 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14869 			flags |= DTRACEBUF_RING;
14870 
14871 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14872 			flags |= DTRACEBUF_FILL;
14873 
14874 		if (state != dtrace_anon.dta_state ||
14875 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14876 			flags |= DTRACEBUF_INACTIVE;
14877 	}
14878 
14879 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14880 		/*
14881 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14882 		 * aligned, drop it down by the difference.
14883 		 */
14884 		if (size & (sizeof (uint64_t) - 1))
14885 			size -= size & (sizeof (uint64_t) - 1);
14886 
14887 		if (size < state->dts_reserve) {
14888 			/*
14889 			 * Buffers always must be large enough to accommodate
14890 			 * their prereserved space.  We return E2BIG instead
14891 			 * of ENOMEM in this case to allow for user-level
14892 			 * software to differentiate the cases.
14893 			 */
14894 			return (E2BIG);
14895 		}
14896 
14897 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14898 
14899 		if (rval != ENOMEM) {
14900 			opt[which] = size;
14901 			return (rval);
14902 		}
14903 
14904 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14905 			return (rval);
14906 
14907 		for (divisor = 2; divisor < factor; divisor <<= 1)
14908 			continue;
14909 	}
14910 
14911 	return (ENOMEM);
14912 }
14913 
14914 static int
14915 dtrace_state_buffers(dtrace_state_t *state)
14916 {
14917 	dtrace_speculation_t *spec = state->dts_speculations;
14918 	int rval, i;
14919 
14920 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14921 	    DTRACEOPT_BUFSIZE)) != 0)
14922 		return (rval);
14923 
14924 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14925 	    DTRACEOPT_AGGSIZE)) != 0)
14926 		return (rval);
14927 
14928 	for (i = 0; i < state->dts_nspeculations; i++) {
14929 		if ((rval = dtrace_state_buffer(state,
14930 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14931 			return (rval);
14932 	}
14933 
14934 	return (0);
14935 }
14936 
14937 static void
14938 dtrace_state_prereserve(dtrace_state_t *state)
14939 {
14940 	dtrace_ecb_t *ecb;
14941 	dtrace_probe_t *probe;
14942 
14943 	state->dts_reserve = 0;
14944 
14945 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14946 		return;
14947 
14948 	/*
14949 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14950 	 * prereserved space to be the space required by the END probes.
14951 	 */
14952 	probe = dtrace_probes[dtrace_probeid_end - 1];
14953 	ASSERT(probe != NULL);
14954 
14955 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14956 		if (ecb->dte_state != state)
14957 			continue;
14958 
14959 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14960 	}
14961 }
14962 
14963 static int
14964 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14965 {
14966 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14967 	dtrace_speculation_t *spec;
14968 	dtrace_buffer_t *buf;
14969 #ifdef illumos
14970 	cyc_handler_t hdlr;
14971 	cyc_time_t when;
14972 #endif
14973 	int rval = 0, i, bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t);
14974 	dtrace_icookie_t cookie;
14975 
14976 	mutex_enter(&cpu_lock);
14977 	mutex_enter(&dtrace_lock);
14978 
14979 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14980 		rval = EBUSY;
14981 		goto out;
14982 	}
14983 
14984 	/*
14985 	 * Before we can perform any checks, we must prime all of the
14986 	 * retained enablings that correspond to this state.
14987 	 */
14988 	dtrace_enabling_prime(state);
14989 
14990 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14991 		rval = EACCES;
14992 		goto out;
14993 	}
14994 
14995 	dtrace_state_prereserve(state);
14996 
14997 	/*
14998 	 * Now we want to do is try to allocate our speculations.
14999 	 * We do not automatically resize the number of speculations; if
15000 	 * this fails, we will fail the operation.
15001 	 */
15002 	nspec = opt[DTRACEOPT_NSPEC];
15003 	ASSERT(nspec != DTRACEOPT_UNSET);
15004 
15005 	if (nspec > INT_MAX) {
15006 		rval = ENOMEM;
15007 		goto out;
15008 	}
15009 
15010 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
15011 	    KM_NOSLEEP | KM_NORMALPRI);
15012 
15013 	if (spec == NULL) {
15014 		rval = ENOMEM;
15015 		goto out;
15016 	}
15017 
15018 	state->dts_speculations = spec;
15019 	state->dts_nspeculations = (int)nspec;
15020 
15021 	for (i = 0; i < nspec; i++) {
15022 		if ((buf = kmem_zalloc(bufsize,
15023 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15024 			rval = ENOMEM;
15025 			goto err;
15026 		}
15027 
15028 		spec[i].dtsp_buffer = buf;
15029 	}
15030 
15031 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15032 		if (dtrace_anon.dta_state == NULL) {
15033 			rval = ENOENT;
15034 			goto out;
15035 		}
15036 
15037 		if (state->dts_necbs != 0) {
15038 			rval = EALREADY;
15039 			goto out;
15040 		}
15041 
15042 		state->dts_anon = dtrace_anon_grab();
15043 		ASSERT(state->dts_anon != NULL);
15044 		state = state->dts_anon;
15045 
15046 		/*
15047 		 * We want "grabanon" to be set in the grabbed state, so we'll
15048 		 * copy that option value from the grabbing state into the
15049 		 * grabbed state.
15050 		 */
15051 		state->dts_options[DTRACEOPT_GRABANON] =
15052 		    opt[DTRACEOPT_GRABANON];
15053 
15054 		*cpu = dtrace_anon.dta_beganon;
15055 
15056 		/*
15057 		 * If the anonymous state is active (as it almost certainly
15058 		 * is if the anonymous enabling ultimately matched anything),
15059 		 * we don't allow any further option processing -- but we
15060 		 * don't return failure.
15061 		 */
15062 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15063 			goto out;
15064 	}
15065 
15066 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15067 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15068 		if (state->dts_aggregations == NULL) {
15069 			/*
15070 			 * We're not going to create an aggregation buffer
15071 			 * because we don't have any ECBs that contain
15072 			 * aggregations -- set this option to 0.
15073 			 */
15074 			opt[DTRACEOPT_AGGSIZE] = 0;
15075 		} else {
15076 			/*
15077 			 * If we have an aggregation buffer, we must also have
15078 			 * a buffer to use as scratch.
15079 			 */
15080 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15081 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15082 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15083 			}
15084 		}
15085 	}
15086 
15087 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15088 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15089 		if (!state->dts_speculates) {
15090 			/*
15091 			 * We're not going to create speculation buffers
15092 			 * because we don't have any ECBs that actually
15093 			 * speculate -- set the speculation size to 0.
15094 			 */
15095 			opt[DTRACEOPT_SPECSIZE] = 0;
15096 		}
15097 	}
15098 
15099 	/*
15100 	 * The bare minimum size for any buffer that we're actually going to
15101 	 * do anything to is sizeof (uint64_t).
15102 	 */
15103 	sz = sizeof (uint64_t);
15104 
15105 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15106 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15107 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15108 		/*
15109 		 * A buffer size has been explicitly set to 0 (or to a size
15110 		 * that will be adjusted to 0) and we need the space -- we
15111 		 * need to return failure.  We return ENOSPC to differentiate
15112 		 * it from failing to allocate a buffer due to failure to meet
15113 		 * the reserve (for which we return E2BIG).
15114 		 */
15115 		rval = ENOSPC;
15116 		goto out;
15117 	}
15118 
15119 	if ((rval = dtrace_state_buffers(state)) != 0)
15120 		goto err;
15121 
15122 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15123 		sz = dtrace_dstate_defsize;
15124 
15125 	do {
15126 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15127 
15128 		if (rval == 0)
15129 			break;
15130 
15131 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15132 			goto err;
15133 	} while (sz >>= 1);
15134 
15135 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15136 
15137 	if (rval != 0)
15138 		goto err;
15139 
15140 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15141 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15142 
15143 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15144 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15145 
15146 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15147 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15148 
15149 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15150 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15151 
15152 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15153 #ifdef illumos
15154 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15155 	hdlr.cyh_arg = state;
15156 	hdlr.cyh_level = CY_LOW_LEVEL;
15157 
15158 	when.cyt_when = 0;
15159 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15160 
15161 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15162 
15163 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15164 	hdlr.cyh_arg = state;
15165 	hdlr.cyh_level = CY_LOW_LEVEL;
15166 
15167 	when.cyt_when = 0;
15168 	when.cyt_interval = dtrace_deadman_interval;
15169 
15170 	state->dts_deadman = cyclic_add(&hdlr, &when);
15171 #else
15172 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15173 	    dtrace_state_clean, state);
15174 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15175 	    dtrace_state_deadman, state);
15176 #endif
15177 
15178 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15179 
15180 #ifdef illumos
15181 	if (state->dts_getf != 0 &&
15182 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15183 		/*
15184 		 * We don't have kernel privs but we have at least one call
15185 		 * to getf(); we need to bump our zone's count, and (if
15186 		 * this is the first enabling to have an unprivileged call
15187 		 * to getf()) we need to hook into closef().
15188 		 */
15189 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15190 
15191 		if (dtrace_getf++ == 0) {
15192 			ASSERT(dtrace_closef == NULL);
15193 			dtrace_closef = dtrace_getf_barrier;
15194 		}
15195 	}
15196 #endif
15197 
15198 	/*
15199 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15200 	 * interrupts here both to record the CPU on which we fired the BEGIN
15201 	 * probe (the data from this CPU will be processed first at user
15202 	 * level) and to manually activate the buffer for this CPU.
15203 	 */
15204 	cookie = dtrace_interrupt_disable();
15205 	*cpu = curcpu;
15206 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15207 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15208 
15209 	dtrace_probe(dtrace_probeid_begin,
15210 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15211 	dtrace_interrupt_enable(cookie);
15212 	/*
15213 	 * We may have had an exit action from a BEGIN probe; only change our
15214 	 * state to ACTIVE if we're still in WARMUP.
15215 	 */
15216 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15217 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15218 
15219 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15220 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15221 
15222 #ifdef __FreeBSD__
15223 	/*
15224 	 * We enable anonymous tracing before APs are started, so we must
15225 	 * activate buffers using the current CPU.
15226 	 */
15227 	if (state == dtrace_anon.dta_state) {
15228 		CPU_FOREACH(i)
15229 			dtrace_buffer_activate_cpu(state, i);
15230 	} else
15231 		dtrace_xcall(DTRACE_CPUALL,
15232 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15233 #else
15234 	/*
15235 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15236 	 * want each CPU to transition its principal buffer out of the
15237 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15238 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15239 	 * atomically transition from processing none of a state's ECBs to
15240 	 * processing all of them.
15241 	 */
15242 	dtrace_xcall(DTRACE_CPUALL,
15243 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15244 #endif
15245 	goto out;
15246 
15247 err:
15248 	dtrace_buffer_free(state->dts_buffer);
15249 	dtrace_buffer_free(state->dts_aggbuffer);
15250 
15251 	if ((nspec = state->dts_nspeculations) == 0) {
15252 		ASSERT(state->dts_speculations == NULL);
15253 		goto out;
15254 	}
15255 
15256 	spec = state->dts_speculations;
15257 	ASSERT(spec != NULL);
15258 
15259 	for (i = 0; i < state->dts_nspeculations; i++) {
15260 		if ((buf = spec[i].dtsp_buffer) == NULL)
15261 			break;
15262 
15263 		dtrace_buffer_free(buf);
15264 		kmem_free(buf, bufsize);
15265 	}
15266 
15267 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15268 	state->dts_nspeculations = 0;
15269 	state->dts_speculations = NULL;
15270 
15271 out:
15272 	mutex_exit(&dtrace_lock);
15273 	mutex_exit(&cpu_lock);
15274 
15275 	return (rval);
15276 }
15277 
15278 static int
15279 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15280 {
15281 	dtrace_icookie_t cookie;
15282 
15283 	ASSERT(MUTEX_HELD(&dtrace_lock));
15284 
15285 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15286 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15287 		return (EINVAL);
15288 
15289 	/*
15290 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15291 	 * to be sure that every CPU has seen it.  See below for the details
15292 	 * on why this is done.
15293 	 */
15294 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15295 	dtrace_sync();
15296 
15297 	/*
15298 	 * By this point, it is impossible for any CPU to be still processing
15299 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15300 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15301 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15302 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15303 	 * iff we're in the END probe.
15304 	 */
15305 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15306 	dtrace_sync();
15307 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15308 
15309 	/*
15310 	 * Finally, we can release the reserve and call the END probe.  We
15311 	 * disable interrupts across calling the END probe to allow us to
15312 	 * return the CPU on which we actually called the END probe.  This
15313 	 * allows user-land to be sure that this CPU's principal buffer is
15314 	 * processed last.
15315 	 */
15316 	state->dts_reserve = 0;
15317 
15318 	cookie = dtrace_interrupt_disable();
15319 	*cpu = curcpu;
15320 	dtrace_probe(dtrace_probeid_end,
15321 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15322 	dtrace_interrupt_enable(cookie);
15323 
15324 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15325 	dtrace_sync();
15326 
15327 #ifdef illumos
15328 	if (state->dts_getf != 0 &&
15329 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15330 		/*
15331 		 * We don't have kernel privs but we have at least one call
15332 		 * to getf(); we need to lower our zone's count, and (if
15333 		 * this is the last enabling to have an unprivileged call
15334 		 * to getf()) we need to clear the closef() hook.
15335 		 */
15336 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15337 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15338 		ASSERT(dtrace_getf > 0);
15339 
15340 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15341 
15342 		if (--dtrace_getf == 0)
15343 			dtrace_closef = NULL;
15344 	}
15345 #endif
15346 
15347 	return (0);
15348 }
15349 
15350 static int
15351 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15352     dtrace_optval_t val)
15353 {
15354 	ASSERT(MUTEX_HELD(&dtrace_lock));
15355 
15356 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15357 		return (EBUSY);
15358 
15359 	if (option >= DTRACEOPT_MAX)
15360 		return (EINVAL);
15361 
15362 	if (option != DTRACEOPT_CPU && val < 0)
15363 		return (EINVAL);
15364 
15365 	switch (option) {
15366 	case DTRACEOPT_DESTRUCTIVE:
15367 		if (dtrace_destructive_disallow)
15368 			return (EACCES);
15369 
15370 		state->dts_cred.dcr_destructive = 1;
15371 		break;
15372 
15373 	case DTRACEOPT_BUFSIZE:
15374 	case DTRACEOPT_DYNVARSIZE:
15375 	case DTRACEOPT_AGGSIZE:
15376 	case DTRACEOPT_SPECSIZE:
15377 	case DTRACEOPT_STRSIZE:
15378 		if (val < 0)
15379 			return (EINVAL);
15380 
15381 		if (val >= LONG_MAX) {
15382 			/*
15383 			 * If this is an otherwise negative value, set it to
15384 			 * the highest multiple of 128m less than LONG_MAX.
15385 			 * Technically, we're adjusting the size without
15386 			 * regard to the buffer resizing policy, but in fact,
15387 			 * this has no effect -- if we set the buffer size to
15388 			 * ~LONG_MAX and the buffer policy is ultimately set to
15389 			 * be "manual", the buffer allocation is guaranteed to
15390 			 * fail, if only because the allocation requires two
15391 			 * buffers.  (We set the the size to the highest
15392 			 * multiple of 128m because it ensures that the size
15393 			 * will remain a multiple of a megabyte when
15394 			 * repeatedly halved -- all the way down to 15m.)
15395 			 */
15396 			val = LONG_MAX - (1 << 27) + 1;
15397 		}
15398 	}
15399 
15400 	state->dts_options[option] = val;
15401 
15402 	return (0);
15403 }
15404 
15405 static void
15406 dtrace_state_destroy(dtrace_state_t *state)
15407 {
15408 	dtrace_ecb_t *ecb;
15409 	dtrace_vstate_t *vstate = &state->dts_vstate;
15410 #ifdef illumos
15411 	minor_t minor = getminor(state->dts_dev);
15412 #endif
15413 	int i, bufsize = (mp_maxid + 1) * sizeof (dtrace_buffer_t);
15414 	dtrace_speculation_t *spec = state->dts_speculations;
15415 	int nspec = state->dts_nspeculations;
15416 	uint32_t match;
15417 
15418 	ASSERT(MUTEX_HELD(&dtrace_lock));
15419 	ASSERT(MUTEX_HELD(&cpu_lock));
15420 
15421 	/*
15422 	 * First, retract any retained enablings for this state.
15423 	 */
15424 	dtrace_enabling_retract(state);
15425 	ASSERT(state->dts_nretained == 0);
15426 
15427 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15428 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15429 		/*
15430 		 * We have managed to come into dtrace_state_destroy() on a
15431 		 * hot enabling -- almost certainly because of a disorderly
15432 		 * shutdown of a consumer.  (That is, a consumer that is
15433 		 * exiting without having called dtrace_stop().) In this case,
15434 		 * we're going to set our activity to be KILLED, and then
15435 		 * issue a sync to be sure that everyone is out of probe
15436 		 * context before we start blowing away ECBs.
15437 		 */
15438 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15439 		dtrace_sync();
15440 	}
15441 
15442 	/*
15443 	 * Release the credential hold we took in dtrace_state_create().
15444 	 */
15445 	if (state->dts_cred.dcr_cred != NULL)
15446 		crfree(state->dts_cred.dcr_cred);
15447 
15448 	/*
15449 	 * Now we can safely disable and destroy any enabled probes.  Because
15450 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15451 	 * (especially if they're all enabled), we take two passes through the
15452 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15453 	 * in the second we disable whatever is left over.
15454 	 */
15455 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15456 		for (i = 0; i < state->dts_necbs; i++) {
15457 			if ((ecb = state->dts_ecbs[i]) == NULL)
15458 				continue;
15459 
15460 			if (match && ecb->dte_probe != NULL) {
15461 				dtrace_probe_t *probe = ecb->dte_probe;
15462 				dtrace_provider_t *prov = probe->dtpr_provider;
15463 
15464 				if (!(prov->dtpv_priv.dtpp_flags & match))
15465 					continue;
15466 			}
15467 
15468 			dtrace_ecb_disable(ecb);
15469 			dtrace_ecb_destroy(ecb);
15470 		}
15471 
15472 		if (!match)
15473 			break;
15474 	}
15475 
15476 	/*
15477 	 * Before we free the buffers, perform one more sync to assure that
15478 	 * every CPU is out of probe context.
15479 	 */
15480 	dtrace_sync();
15481 
15482 	dtrace_buffer_free(state->dts_buffer);
15483 	dtrace_buffer_free(state->dts_aggbuffer);
15484 
15485 	for (i = 0; i < nspec; i++)
15486 		dtrace_buffer_free(spec[i].dtsp_buffer);
15487 
15488 #ifdef illumos
15489 	if (state->dts_cleaner != CYCLIC_NONE)
15490 		cyclic_remove(state->dts_cleaner);
15491 
15492 	if (state->dts_deadman != CYCLIC_NONE)
15493 		cyclic_remove(state->dts_deadman);
15494 #else
15495 	callout_stop(&state->dts_cleaner);
15496 	callout_drain(&state->dts_cleaner);
15497 	callout_stop(&state->dts_deadman);
15498 	callout_drain(&state->dts_deadman);
15499 #endif
15500 
15501 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15502 	dtrace_vstate_fini(vstate);
15503 	if (state->dts_ecbs != NULL)
15504 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15505 
15506 	if (state->dts_aggregations != NULL) {
15507 #ifdef DEBUG
15508 		for (i = 0; i < state->dts_naggregations; i++)
15509 			ASSERT(state->dts_aggregations[i] == NULL);
15510 #endif
15511 		ASSERT(state->dts_naggregations > 0);
15512 		kmem_free(state->dts_aggregations,
15513 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15514 	}
15515 
15516 	kmem_free(state->dts_buffer, bufsize);
15517 	kmem_free(state->dts_aggbuffer, bufsize);
15518 
15519 	for (i = 0; i < nspec; i++)
15520 		kmem_free(spec[i].dtsp_buffer, bufsize);
15521 
15522 	if (spec != NULL)
15523 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15524 
15525 	dtrace_format_destroy(state);
15526 
15527 	if (state->dts_aggid_arena != NULL) {
15528 #ifdef illumos
15529 		vmem_destroy(state->dts_aggid_arena);
15530 #else
15531 		delete_unrhdr(state->dts_aggid_arena);
15532 #endif
15533 		state->dts_aggid_arena = NULL;
15534 	}
15535 #ifdef illumos
15536 	ddi_soft_state_free(dtrace_softstate, minor);
15537 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15538 #endif
15539 }
15540 
15541 /*
15542  * DTrace Anonymous Enabling Functions
15543  */
15544 static dtrace_state_t *
15545 dtrace_anon_grab(void)
15546 {
15547 	dtrace_state_t *state;
15548 
15549 	ASSERT(MUTEX_HELD(&dtrace_lock));
15550 
15551 	if ((state = dtrace_anon.dta_state) == NULL) {
15552 		ASSERT(dtrace_anon.dta_enabling == NULL);
15553 		return (NULL);
15554 	}
15555 
15556 	ASSERT(dtrace_anon.dta_enabling != NULL);
15557 	ASSERT(dtrace_retained != NULL);
15558 
15559 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15560 	dtrace_anon.dta_enabling = NULL;
15561 	dtrace_anon.dta_state = NULL;
15562 
15563 	return (state);
15564 }
15565 
15566 static void
15567 dtrace_anon_property(void)
15568 {
15569 	int i, rv;
15570 	dtrace_state_t *state;
15571 	dof_hdr_t *dof;
15572 	char c[32];		/* enough for "dof-data-" + digits */
15573 
15574 	ASSERT(MUTEX_HELD(&dtrace_lock));
15575 	ASSERT(MUTEX_HELD(&cpu_lock));
15576 
15577 	for (i = 0; ; i++) {
15578 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15579 
15580 		dtrace_err_verbose = 1;
15581 
15582 		if ((dof = dtrace_dof_property(c)) == NULL) {
15583 			dtrace_err_verbose = 0;
15584 			break;
15585 		}
15586 
15587 #ifdef illumos
15588 		/*
15589 		 * We want to create anonymous state, so we need to transition
15590 		 * the kernel debugger to indicate that DTrace is active.  If
15591 		 * this fails (e.g. because the debugger has modified text in
15592 		 * some way), we won't continue with the processing.
15593 		 */
15594 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15595 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15596 			    "enabling ignored.");
15597 			dtrace_dof_destroy(dof);
15598 			break;
15599 		}
15600 #endif
15601 
15602 		/*
15603 		 * If we haven't allocated an anonymous state, we'll do so now.
15604 		 */
15605 		if ((state = dtrace_anon.dta_state) == NULL) {
15606 			state = dtrace_state_create(NULL, NULL);
15607 			dtrace_anon.dta_state = state;
15608 
15609 			if (state == NULL) {
15610 				/*
15611 				 * This basically shouldn't happen:  the only
15612 				 * failure mode from dtrace_state_create() is a
15613 				 * failure of ddi_soft_state_zalloc() that
15614 				 * itself should never happen.  Still, the
15615 				 * interface allows for a failure mode, and
15616 				 * we want to fail as gracefully as possible:
15617 				 * we'll emit an error message and cease
15618 				 * processing anonymous state in this case.
15619 				 */
15620 				cmn_err(CE_WARN, "failed to create "
15621 				    "anonymous state");
15622 				dtrace_dof_destroy(dof);
15623 				break;
15624 			}
15625 		}
15626 
15627 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15628 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15629 
15630 		if (rv == 0)
15631 			rv = dtrace_dof_options(dof, state);
15632 
15633 		dtrace_err_verbose = 0;
15634 		dtrace_dof_destroy(dof);
15635 
15636 		if (rv != 0) {
15637 			/*
15638 			 * This is malformed DOF; chuck any anonymous state
15639 			 * that we created.
15640 			 */
15641 			ASSERT(dtrace_anon.dta_enabling == NULL);
15642 			dtrace_state_destroy(state);
15643 			dtrace_anon.dta_state = NULL;
15644 			break;
15645 		}
15646 
15647 		ASSERT(dtrace_anon.dta_enabling != NULL);
15648 	}
15649 
15650 	if (dtrace_anon.dta_enabling != NULL) {
15651 		int rval;
15652 
15653 		/*
15654 		 * dtrace_enabling_retain() can only fail because we are
15655 		 * trying to retain more enablings than are allowed -- but
15656 		 * we only have one anonymous enabling, and we are guaranteed
15657 		 * to be allowed at least one retained enabling; we assert
15658 		 * that dtrace_enabling_retain() returns success.
15659 		 */
15660 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15661 		ASSERT(rval == 0);
15662 
15663 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15664 	}
15665 }
15666 
15667 /*
15668  * DTrace Helper Functions
15669  */
15670 static void
15671 dtrace_helper_trace(dtrace_helper_action_t *helper,
15672     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15673 {
15674 	uint32_t size, next, nnext, i;
15675 	dtrace_helptrace_t *ent, *buffer;
15676 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15677 
15678 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15679 		return;
15680 
15681 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15682 
15683 	/*
15684 	 * What would a tracing framework be without its own tracing
15685 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15686 	 */
15687 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15688 	    sizeof (uint64_t) - sizeof (uint64_t);
15689 
15690 	/*
15691 	 * Iterate until we can allocate a slot in the trace buffer.
15692 	 */
15693 	do {
15694 		next = dtrace_helptrace_next;
15695 
15696 		if (next + size < dtrace_helptrace_bufsize) {
15697 			nnext = next + size;
15698 		} else {
15699 			nnext = size;
15700 		}
15701 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15702 
15703 	/*
15704 	 * We have our slot; fill it in.
15705 	 */
15706 	if (nnext == size) {
15707 		dtrace_helptrace_wrapped++;
15708 		next = 0;
15709 	}
15710 
15711 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15712 	ent->dtht_helper = helper;
15713 	ent->dtht_where = where;
15714 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15715 
15716 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15717 	    mstate->dtms_fltoffs : -1;
15718 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15719 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15720 
15721 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15722 		dtrace_statvar_t *svar;
15723 
15724 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15725 			continue;
15726 
15727 		ASSERT(svar->dtsv_size >= (mp_maxid + 1) * sizeof (uint64_t));
15728 		ent->dtht_locals[i] =
15729 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15730 	}
15731 }
15732 
15733 static uint64_t
15734 dtrace_helper(int which, dtrace_mstate_t *mstate,
15735     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15736 {
15737 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15738 	uint64_t sarg0 = mstate->dtms_arg[0];
15739 	uint64_t sarg1 = mstate->dtms_arg[1];
15740 	uint64_t rval = 0;
15741 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15742 	dtrace_helper_action_t *helper;
15743 	dtrace_vstate_t *vstate;
15744 	dtrace_difo_t *pred;
15745 	int i, trace = dtrace_helptrace_buffer != NULL;
15746 
15747 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15748 
15749 	if (helpers == NULL)
15750 		return (0);
15751 
15752 	if ((helper = helpers->dthps_actions[which]) == NULL)
15753 		return (0);
15754 
15755 	vstate = &helpers->dthps_vstate;
15756 	mstate->dtms_arg[0] = arg0;
15757 	mstate->dtms_arg[1] = arg1;
15758 
15759 	/*
15760 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15761 	 * we'll call the corresponding actions.  Note that the below calls
15762 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15763 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15764 	 * the stored DIF offset with its own (which is the desired behavior).
15765 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15766 	 * from machine state; this is okay, too.
15767 	 */
15768 	for (; helper != NULL; helper = helper->dtha_next) {
15769 		if ((pred = helper->dtha_predicate) != NULL) {
15770 			if (trace)
15771 				dtrace_helper_trace(helper, mstate, vstate, 0);
15772 
15773 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15774 				goto next;
15775 
15776 			if (*flags & CPU_DTRACE_FAULT)
15777 				goto err;
15778 		}
15779 
15780 		for (i = 0; i < helper->dtha_nactions; i++) {
15781 			if (trace)
15782 				dtrace_helper_trace(helper,
15783 				    mstate, vstate, i + 1);
15784 
15785 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15786 			    mstate, vstate, state);
15787 
15788 			if (*flags & CPU_DTRACE_FAULT)
15789 				goto err;
15790 		}
15791 
15792 next:
15793 		if (trace)
15794 			dtrace_helper_trace(helper, mstate, vstate,
15795 			    DTRACE_HELPTRACE_NEXT);
15796 	}
15797 
15798 	if (trace)
15799 		dtrace_helper_trace(helper, mstate, vstate,
15800 		    DTRACE_HELPTRACE_DONE);
15801 
15802 	/*
15803 	 * Restore the arg0 that we saved upon entry.
15804 	 */
15805 	mstate->dtms_arg[0] = sarg0;
15806 	mstate->dtms_arg[1] = sarg1;
15807 
15808 	return (rval);
15809 
15810 err:
15811 	if (trace)
15812 		dtrace_helper_trace(helper, mstate, vstate,
15813 		    DTRACE_HELPTRACE_ERR);
15814 
15815 	/*
15816 	 * Restore the arg0 that we saved upon entry.
15817 	 */
15818 	mstate->dtms_arg[0] = sarg0;
15819 	mstate->dtms_arg[1] = sarg1;
15820 
15821 	return (0);
15822 }
15823 
15824 static void
15825 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15826     dtrace_vstate_t *vstate)
15827 {
15828 	int i;
15829 
15830 	if (helper->dtha_predicate != NULL)
15831 		dtrace_difo_release(helper->dtha_predicate, vstate);
15832 
15833 	for (i = 0; i < helper->dtha_nactions; i++) {
15834 		ASSERT(helper->dtha_actions[i] != NULL);
15835 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15836 	}
15837 
15838 	kmem_free(helper->dtha_actions,
15839 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15840 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15841 }
15842 
15843 static int
15844 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15845 {
15846 	proc_t *p = curproc;
15847 	dtrace_vstate_t *vstate;
15848 	int i;
15849 
15850 	if (help == NULL)
15851 		help = p->p_dtrace_helpers;
15852 
15853 	ASSERT(MUTEX_HELD(&dtrace_lock));
15854 
15855 	if (help == NULL || gen > help->dthps_generation)
15856 		return (EINVAL);
15857 
15858 	vstate = &help->dthps_vstate;
15859 
15860 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15861 		dtrace_helper_action_t *last = NULL, *h, *next;
15862 
15863 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15864 			next = h->dtha_next;
15865 
15866 			if (h->dtha_generation == gen) {
15867 				if (last != NULL) {
15868 					last->dtha_next = next;
15869 				} else {
15870 					help->dthps_actions[i] = next;
15871 				}
15872 
15873 				dtrace_helper_action_destroy(h, vstate);
15874 			} else {
15875 				last = h;
15876 			}
15877 		}
15878 	}
15879 
15880 	/*
15881 	 * Interate until we've cleared out all helper providers with the
15882 	 * given generation number.
15883 	 */
15884 	for (;;) {
15885 		dtrace_helper_provider_t *prov;
15886 
15887 		/*
15888 		 * Look for a helper provider with the right generation. We
15889 		 * have to start back at the beginning of the list each time
15890 		 * because we drop dtrace_lock. It's unlikely that we'll make
15891 		 * more than two passes.
15892 		 */
15893 		for (i = 0; i < help->dthps_nprovs; i++) {
15894 			prov = help->dthps_provs[i];
15895 
15896 			if (prov->dthp_generation == gen)
15897 				break;
15898 		}
15899 
15900 		/*
15901 		 * If there were no matches, we're done.
15902 		 */
15903 		if (i == help->dthps_nprovs)
15904 			break;
15905 
15906 		/*
15907 		 * Move the last helper provider into this slot.
15908 		 */
15909 		help->dthps_nprovs--;
15910 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15911 		help->dthps_provs[help->dthps_nprovs] = NULL;
15912 
15913 		mutex_exit(&dtrace_lock);
15914 
15915 		/*
15916 		 * If we have a meta provider, remove this helper provider.
15917 		 */
15918 		mutex_enter(&dtrace_meta_lock);
15919 		if (dtrace_meta_pid != NULL) {
15920 			ASSERT(dtrace_deferred_pid == NULL);
15921 			dtrace_helper_provider_remove(&prov->dthp_prov,
15922 			    p->p_pid);
15923 		}
15924 		mutex_exit(&dtrace_meta_lock);
15925 
15926 		dtrace_helper_provider_destroy(prov);
15927 
15928 		mutex_enter(&dtrace_lock);
15929 	}
15930 
15931 	return (0);
15932 }
15933 
15934 static int
15935 dtrace_helper_validate(dtrace_helper_action_t *helper)
15936 {
15937 	int err = 0, i;
15938 	dtrace_difo_t *dp;
15939 
15940 	if ((dp = helper->dtha_predicate) != NULL)
15941 		err += dtrace_difo_validate_helper(dp);
15942 
15943 	for (i = 0; i < helper->dtha_nactions; i++)
15944 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15945 
15946 	return (err == 0);
15947 }
15948 
15949 static int
15950 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15951     dtrace_helpers_t *help)
15952 {
15953 	dtrace_helper_action_t *helper, *last;
15954 	dtrace_actdesc_t *act;
15955 	dtrace_vstate_t *vstate;
15956 	dtrace_predicate_t *pred;
15957 	int count = 0, nactions = 0, i;
15958 
15959 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15960 		return (EINVAL);
15961 
15962 	last = help->dthps_actions[which];
15963 	vstate = &help->dthps_vstate;
15964 
15965 	for (count = 0; last != NULL; last = last->dtha_next) {
15966 		count++;
15967 		if (last->dtha_next == NULL)
15968 			break;
15969 	}
15970 
15971 	/*
15972 	 * If we already have dtrace_helper_actions_max helper actions for this
15973 	 * helper action type, we'll refuse to add a new one.
15974 	 */
15975 	if (count >= dtrace_helper_actions_max)
15976 		return (ENOSPC);
15977 
15978 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15979 	helper->dtha_generation = help->dthps_generation;
15980 
15981 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15982 		ASSERT(pred->dtp_difo != NULL);
15983 		dtrace_difo_hold(pred->dtp_difo);
15984 		helper->dtha_predicate = pred->dtp_difo;
15985 	}
15986 
15987 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15988 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15989 			goto err;
15990 
15991 		if (act->dtad_difo == NULL)
15992 			goto err;
15993 
15994 		nactions++;
15995 	}
15996 
15997 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15998 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15999 
16000 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
16001 		dtrace_difo_hold(act->dtad_difo);
16002 		helper->dtha_actions[i++] = act->dtad_difo;
16003 	}
16004 
16005 	if (!dtrace_helper_validate(helper))
16006 		goto err;
16007 
16008 	if (last == NULL) {
16009 		help->dthps_actions[which] = helper;
16010 	} else {
16011 		last->dtha_next = helper;
16012 	}
16013 
16014 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16015 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16016 		dtrace_helptrace_next = 0;
16017 	}
16018 
16019 	return (0);
16020 err:
16021 	dtrace_helper_action_destroy(helper, vstate);
16022 	return (EINVAL);
16023 }
16024 
16025 static void
16026 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16027     dof_helper_t *dofhp)
16028 {
16029 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16030 
16031 	mutex_enter(&dtrace_meta_lock);
16032 	mutex_enter(&dtrace_lock);
16033 
16034 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16035 		/*
16036 		 * If the dtrace module is loaded but not attached, or if
16037 		 * there aren't isn't a meta provider registered to deal with
16038 		 * these provider descriptions, we need to postpone creating
16039 		 * the actual providers until later.
16040 		 */
16041 
16042 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16043 		    dtrace_deferred_pid != help) {
16044 			help->dthps_deferred = 1;
16045 			help->dthps_pid = p->p_pid;
16046 			help->dthps_next = dtrace_deferred_pid;
16047 			help->dthps_prev = NULL;
16048 			if (dtrace_deferred_pid != NULL)
16049 				dtrace_deferred_pid->dthps_prev = help;
16050 			dtrace_deferred_pid = help;
16051 		}
16052 
16053 		mutex_exit(&dtrace_lock);
16054 
16055 	} else if (dofhp != NULL) {
16056 		/*
16057 		 * If the dtrace module is loaded and we have a particular
16058 		 * helper provider description, pass that off to the
16059 		 * meta provider.
16060 		 */
16061 
16062 		mutex_exit(&dtrace_lock);
16063 
16064 		dtrace_helper_provide(dofhp, p->p_pid);
16065 
16066 	} else {
16067 		/*
16068 		 * Otherwise, just pass all the helper provider descriptions
16069 		 * off to the meta provider.
16070 		 */
16071 
16072 		int i;
16073 		mutex_exit(&dtrace_lock);
16074 
16075 		for (i = 0; i < help->dthps_nprovs; i++) {
16076 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16077 			    p->p_pid);
16078 		}
16079 	}
16080 
16081 	mutex_exit(&dtrace_meta_lock);
16082 }
16083 
16084 static int
16085 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16086 {
16087 	dtrace_helper_provider_t *hprov, **tmp_provs;
16088 	uint_t tmp_maxprovs, i;
16089 
16090 	ASSERT(MUTEX_HELD(&dtrace_lock));
16091 	ASSERT(help != NULL);
16092 
16093 	/*
16094 	 * If we already have dtrace_helper_providers_max helper providers,
16095 	 * we're refuse to add a new one.
16096 	 */
16097 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16098 		return (ENOSPC);
16099 
16100 	/*
16101 	 * Check to make sure this isn't a duplicate.
16102 	 */
16103 	for (i = 0; i < help->dthps_nprovs; i++) {
16104 		if (dofhp->dofhp_addr ==
16105 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16106 			return (EALREADY);
16107 	}
16108 
16109 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16110 	hprov->dthp_prov = *dofhp;
16111 	hprov->dthp_ref = 1;
16112 	hprov->dthp_generation = gen;
16113 
16114 	/*
16115 	 * Allocate a bigger table for helper providers if it's already full.
16116 	 */
16117 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16118 		tmp_maxprovs = help->dthps_maxprovs;
16119 		tmp_provs = help->dthps_provs;
16120 
16121 		if (help->dthps_maxprovs == 0)
16122 			help->dthps_maxprovs = 2;
16123 		else
16124 			help->dthps_maxprovs *= 2;
16125 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16126 			help->dthps_maxprovs = dtrace_helper_providers_max;
16127 
16128 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16129 
16130 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16131 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16132 
16133 		if (tmp_provs != NULL) {
16134 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16135 			    sizeof (dtrace_helper_provider_t *));
16136 			kmem_free(tmp_provs, tmp_maxprovs *
16137 			    sizeof (dtrace_helper_provider_t *));
16138 		}
16139 	}
16140 
16141 	help->dthps_provs[help->dthps_nprovs] = hprov;
16142 	help->dthps_nprovs++;
16143 
16144 	return (0);
16145 }
16146 
16147 static void
16148 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16149 {
16150 	mutex_enter(&dtrace_lock);
16151 
16152 	if (--hprov->dthp_ref == 0) {
16153 		dof_hdr_t *dof;
16154 		mutex_exit(&dtrace_lock);
16155 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16156 		dtrace_dof_destroy(dof);
16157 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16158 	} else {
16159 		mutex_exit(&dtrace_lock);
16160 	}
16161 }
16162 
16163 static int
16164 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16165 {
16166 	uintptr_t daddr = (uintptr_t)dof;
16167 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16168 	dof_provider_t *provider;
16169 	dof_probe_t *probe;
16170 	uint8_t *arg;
16171 	char *strtab, *typestr;
16172 	dof_stridx_t typeidx;
16173 	size_t typesz;
16174 	uint_t nprobes, j, k;
16175 
16176 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16177 
16178 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16179 		dtrace_dof_error(dof, "misaligned section offset");
16180 		return (-1);
16181 	}
16182 
16183 	/*
16184 	 * The section needs to be large enough to contain the DOF provider
16185 	 * structure appropriate for the given version.
16186 	 */
16187 	if (sec->dofs_size <
16188 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16189 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16190 	    sizeof (dof_provider_t))) {
16191 		dtrace_dof_error(dof, "provider section too small");
16192 		return (-1);
16193 	}
16194 
16195 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16196 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16197 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16198 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16199 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16200 
16201 	if (str_sec == NULL || prb_sec == NULL ||
16202 	    arg_sec == NULL || off_sec == NULL)
16203 		return (-1);
16204 
16205 	enoff_sec = NULL;
16206 
16207 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16208 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16209 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16210 	    provider->dofpv_prenoffs)) == NULL)
16211 		return (-1);
16212 
16213 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16214 
16215 	if (provider->dofpv_name >= str_sec->dofs_size ||
16216 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16217 		dtrace_dof_error(dof, "invalid provider name");
16218 		return (-1);
16219 	}
16220 
16221 	if (prb_sec->dofs_entsize == 0 ||
16222 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16223 		dtrace_dof_error(dof, "invalid entry size");
16224 		return (-1);
16225 	}
16226 
16227 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16228 		dtrace_dof_error(dof, "misaligned entry size");
16229 		return (-1);
16230 	}
16231 
16232 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16233 		dtrace_dof_error(dof, "invalid entry size");
16234 		return (-1);
16235 	}
16236 
16237 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16238 		dtrace_dof_error(dof, "misaligned section offset");
16239 		return (-1);
16240 	}
16241 
16242 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16243 		dtrace_dof_error(dof, "invalid entry size");
16244 		return (-1);
16245 	}
16246 
16247 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16248 
16249 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16250 
16251 	/*
16252 	 * Take a pass through the probes to check for errors.
16253 	 */
16254 	for (j = 0; j < nprobes; j++) {
16255 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16256 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16257 
16258 		if (probe->dofpr_func >= str_sec->dofs_size) {
16259 			dtrace_dof_error(dof, "invalid function name");
16260 			return (-1);
16261 		}
16262 
16263 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16264 			dtrace_dof_error(dof, "function name too long");
16265 			/*
16266 			 * Keep going if the function name is too long.
16267 			 * Unlike provider and probe names, we cannot reasonably
16268 			 * impose restrictions on function names, since they're
16269 			 * a property of the code being instrumented. We will
16270 			 * skip this probe in dtrace_helper_provide_one().
16271 			 */
16272 		}
16273 
16274 		if (probe->dofpr_name >= str_sec->dofs_size ||
16275 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16276 			dtrace_dof_error(dof, "invalid probe name");
16277 			return (-1);
16278 		}
16279 
16280 		/*
16281 		 * The offset count must not wrap the index, and the offsets
16282 		 * must also not overflow the section's data.
16283 		 */
16284 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16285 		    probe->dofpr_offidx ||
16286 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16287 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16288 			dtrace_dof_error(dof, "invalid probe offset");
16289 			return (-1);
16290 		}
16291 
16292 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16293 			/*
16294 			 * If there's no is-enabled offset section, make sure
16295 			 * there aren't any is-enabled offsets. Otherwise
16296 			 * perform the same checks as for probe offsets
16297 			 * (immediately above).
16298 			 */
16299 			if (enoff_sec == NULL) {
16300 				if (probe->dofpr_enoffidx != 0 ||
16301 				    probe->dofpr_nenoffs != 0) {
16302 					dtrace_dof_error(dof, "is-enabled "
16303 					    "offsets with null section");
16304 					return (-1);
16305 				}
16306 			} else if (probe->dofpr_enoffidx +
16307 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16308 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16309 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16310 				dtrace_dof_error(dof, "invalid is-enabled "
16311 				    "offset");
16312 				return (-1);
16313 			}
16314 
16315 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16316 				dtrace_dof_error(dof, "zero probe and "
16317 				    "is-enabled offsets");
16318 				return (-1);
16319 			}
16320 		} else if (probe->dofpr_noffs == 0) {
16321 			dtrace_dof_error(dof, "zero probe offsets");
16322 			return (-1);
16323 		}
16324 
16325 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16326 		    probe->dofpr_argidx ||
16327 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16328 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16329 			dtrace_dof_error(dof, "invalid args");
16330 			return (-1);
16331 		}
16332 
16333 		typeidx = probe->dofpr_nargv;
16334 		typestr = strtab + probe->dofpr_nargv;
16335 		for (k = 0; k < probe->dofpr_nargc; k++) {
16336 			if (typeidx >= str_sec->dofs_size) {
16337 				dtrace_dof_error(dof, "bad "
16338 				    "native argument type");
16339 				return (-1);
16340 			}
16341 
16342 			typesz = strlen(typestr) + 1;
16343 			if (typesz > DTRACE_ARGTYPELEN) {
16344 				dtrace_dof_error(dof, "native "
16345 				    "argument type too long");
16346 				return (-1);
16347 			}
16348 			typeidx += typesz;
16349 			typestr += typesz;
16350 		}
16351 
16352 		typeidx = probe->dofpr_xargv;
16353 		typestr = strtab + probe->dofpr_xargv;
16354 		for (k = 0; k < probe->dofpr_xargc; k++) {
16355 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16356 				dtrace_dof_error(dof, "bad "
16357 				    "native argument index");
16358 				return (-1);
16359 			}
16360 
16361 			if (typeidx >= str_sec->dofs_size) {
16362 				dtrace_dof_error(dof, "bad "
16363 				    "translated argument type");
16364 				return (-1);
16365 			}
16366 
16367 			typesz = strlen(typestr) + 1;
16368 			if (typesz > DTRACE_ARGTYPELEN) {
16369 				dtrace_dof_error(dof, "translated argument "
16370 				    "type too long");
16371 				return (-1);
16372 			}
16373 
16374 			typeidx += typesz;
16375 			typestr += typesz;
16376 		}
16377 	}
16378 
16379 	return (0);
16380 }
16381 
16382 static int
16383 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16384 {
16385 	dtrace_helpers_t *help;
16386 	dtrace_vstate_t *vstate;
16387 	dtrace_enabling_t *enab = NULL;
16388 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16389 	uintptr_t daddr = (uintptr_t)dof;
16390 
16391 	ASSERT(MUTEX_HELD(&dtrace_lock));
16392 
16393 	if ((help = p->p_dtrace_helpers) == NULL)
16394 		help = dtrace_helpers_create(p);
16395 
16396 	vstate = &help->dthps_vstate;
16397 
16398 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16399 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16400 		dtrace_dof_destroy(dof);
16401 		return (rv);
16402 	}
16403 
16404 	/*
16405 	 * Look for helper providers and validate their descriptions.
16406 	 */
16407 	for (i = 0; i < dof->dofh_secnum; i++) {
16408 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16409 		    dof->dofh_secoff + i * dof->dofh_secsize);
16410 
16411 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16412 			continue;
16413 
16414 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16415 			dtrace_enabling_destroy(enab);
16416 			dtrace_dof_destroy(dof);
16417 			return (-1);
16418 		}
16419 
16420 		nprovs++;
16421 	}
16422 
16423 	/*
16424 	 * Now we need to walk through the ECB descriptions in the enabling.
16425 	 */
16426 	for (i = 0; i < enab->dten_ndesc; i++) {
16427 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16428 		dtrace_probedesc_t *desc = &ep->dted_probe;
16429 
16430 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16431 			continue;
16432 
16433 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16434 			continue;
16435 
16436 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16437 			continue;
16438 
16439 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16440 		    ep, help)) != 0) {
16441 			/*
16442 			 * Adding this helper action failed -- we are now going
16443 			 * to rip out the entire generation and return failure.
16444 			 */
16445 			(void) dtrace_helper_destroygen(help,
16446 			    help->dthps_generation);
16447 			dtrace_enabling_destroy(enab);
16448 			dtrace_dof_destroy(dof);
16449 			return (-1);
16450 		}
16451 
16452 		nhelpers++;
16453 	}
16454 
16455 	if (nhelpers < enab->dten_ndesc)
16456 		dtrace_dof_error(dof, "unmatched helpers");
16457 
16458 	gen = help->dthps_generation++;
16459 	dtrace_enabling_destroy(enab);
16460 
16461 	if (nprovs > 0) {
16462 		/*
16463 		 * Now that this is in-kernel, we change the sense of the
16464 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16465 		 * and dofhp_addr denotes the address at user-level.
16466 		 */
16467 		dhp->dofhp_addr = dhp->dofhp_dof;
16468 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16469 
16470 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16471 			mutex_exit(&dtrace_lock);
16472 			dtrace_helper_provider_register(p, help, dhp);
16473 			mutex_enter(&dtrace_lock);
16474 
16475 			destroy = 0;
16476 		}
16477 	}
16478 
16479 	if (destroy)
16480 		dtrace_dof_destroy(dof);
16481 
16482 	return (gen);
16483 }
16484 
16485 static dtrace_helpers_t *
16486 dtrace_helpers_create(proc_t *p)
16487 {
16488 	dtrace_helpers_t *help;
16489 
16490 	ASSERT(MUTEX_HELD(&dtrace_lock));
16491 	ASSERT(p->p_dtrace_helpers == NULL);
16492 
16493 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16494 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16495 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16496 
16497 	p->p_dtrace_helpers = help;
16498 	dtrace_helpers++;
16499 
16500 	return (help);
16501 }
16502 
16503 #ifdef illumos
16504 static
16505 #endif
16506 void
16507 dtrace_helpers_destroy(proc_t *p)
16508 {
16509 	dtrace_helpers_t *help;
16510 	dtrace_vstate_t *vstate;
16511 #ifdef illumos
16512 	proc_t *p = curproc;
16513 #endif
16514 	int i;
16515 
16516 	mutex_enter(&dtrace_lock);
16517 
16518 	ASSERT(p->p_dtrace_helpers != NULL);
16519 	ASSERT(dtrace_helpers > 0);
16520 
16521 	help = p->p_dtrace_helpers;
16522 	vstate = &help->dthps_vstate;
16523 
16524 	/*
16525 	 * We're now going to lose the help from this process.
16526 	 */
16527 	p->p_dtrace_helpers = NULL;
16528 	dtrace_sync();
16529 
16530 	/*
16531 	 * Destory the helper actions.
16532 	 */
16533 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16534 		dtrace_helper_action_t *h, *next;
16535 
16536 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16537 			next = h->dtha_next;
16538 			dtrace_helper_action_destroy(h, vstate);
16539 			h = next;
16540 		}
16541 	}
16542 
16543 	mutex_exit(&dtrace_lock);
16544 
16545 	/*
16546 	 * Destroy the helper providers.
16547 	 */
16548 	if (help->dthps_maxprovs > 0) {
16549 		mutex_enter(&dtrace_meta_lock);
16550 		if (dtrace_meta_pid != NULL) {
16551 			ASSERT(dtrace_deferred_pid == NULL);
16552 
16553 			for (i = 0; i < help->dthps_nprovs; i++) {
16554 				dtrace_helper_provider_remove(
16555 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16556 			}
16557 		} else {
16558 			mutex_enter(&dtrace_lock);
16559 			ASSERT(help->dthps_deferred == 0 ||
16560 			    help->dthps_next != NULL ||
16561 			    help->dthps_prev != NULL ||
16562 			    help == dtrace_deferred_pid);
16563 
16564 			/*
16565 			 * Remove the helper from the deferred list.
16566 			 */
16567 			if (help->dthps_next != NULL)
16568 				help->dthps_next->dthps_prev = help->dthps_prev;
16569 			if (help->dthps_prev != NULL)
16570 				help->dthps_prev->dthps_next = help->dthps_next;
16571 			if (dtrace_deferred_pid == help) {
16572 				dtrace_deferred_pid = help->dthps_next;
16573 				ASSERT(help->dthps_prev == NULL);
16574 			}
16575 
16576 			mutex_exit(&dtrace_lock);
16577 		}
16578 
16579 		mutex_exit(&dtrace_meta_lock);
16580 
16581 		for (i = 0; i < help->dthps_nprovs; i++) {
16582 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16583 		}
16584 
16585 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16586 		    sizeof (dtrace_helper_provider_t *));
16587 	}
16588 
16589 	mutex_enter(&dtrace_lock);
16590 
16591 	dtrace_vstate_fini(&help->dthps_vstate);
16592 	kmem_free(help->dthps_actions,
16593 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16594 	kmem_free(help, sizeof (dtrace_helpers_t));
16595 
16596 	--dtrace_helpers;
16597 	mutex_exit(&dtrace_lock);
16598 }
16599 
16600 #ifdef illumos
16601 static
16602 #endif
16603 void
16604 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16605 {
16606 	dtrace_helpers_t *help, *newhelp;
16607 	dtrace_helper_action_t *helper, *new, *last;
16608 	dtrace_difo_t *dp;
16609 	dtrace_vstate_t *vstate;
16610 	int i, j, sz, hasprovs = 0;
16611 
16612 	mutex_enter(&dtrace_lock);
16613 	ASSERT(from->p_dtrace_helpers != NULL);
16614 	ASSERT(dtrace_helpers > 0);
16615 
16616 	help = from->p_dtrace_helpers;
16617 	newhelp = dtrace_helpers_create(to);
16618 	ASSERT(to->p_dtrace_helpers != NULL);
16619 
16620 	newhelp->dthps_generation = help->dthps_generation;
16621 	vstate = &newhelp->dthps_vstate;
16622 
16623 	/*
16624 	 * Duplicate the helper actions.
16625 	 */
16626 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16627 		if ((helper = help->dthps_actions[i]) == NULL)
16628 			continue;
16629 
16630 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16631 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16632 			    KM_SLEEP);
16633 			new->dtha_generation = helper->dtha_generation;
16634 
16635 			if ((dp = helper->dtha_predicate) != NULL) {
16636 				dp = dtrace_difo_duplicate(dp, vstate);
16637 				new->dtha_predicate = dp;
16638 			}
16639 
16640 			new->dtha_nactions = helper->dtha_nactions;
16641 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16642 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16643 
16644 			for (j = 0; j < new->dtha_nactions; j++) {
16645 				dtrace_difo_t *dp = helper->dtha_actions[j];
16646 
16647 				ASSERT(dp != NULL);
16648 				dp = dtrace_difo_duplicate(dp, vstate);
16649 				new->dtha_actions[j] = dp;
16650 			}
16651 
16652 			if (last != NULL) {
16653 				last->dtha_next = new;
16654 			} else {
16655 				newhelp->dthps_actions[i] = new;
16656 			}
16657 
16658 			last = new;
16659 		}
16660 	}
16661 
16662 	/*
16663 	 * Duplicate the helper providers and register them with the
16664 	 * DTrace framework.
16665 	 */
16666 	if (help->dthps_nprovs > 0) {
16667 		newhelp->dthps_nprovs = help->dthps_nprovs;
16668 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16669 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16670 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16671 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16672 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16673 			newhelp->dthps_provs[i]->dthp_ref++;
16674 		}
16675 
16676 		hasprovs = 1;
16677 	}
16678 
16679 	mutex_exit(&dtrace_lock);
16680 
16681 	if (hasprovs)
16682 		dtrace_helper_provider_register(to, newhelp, NULL);
16683 }
16684 
16685 /*
16686  * DTrace Hook Functions
16687  */
16688 static void
16689 dtrace_module_loaded(modctl_t *ctl)
16690 {
16691 	dtrace_provider_t *prv;
16692 
16693 	mutex_enter(&dtrace_provider_lock);
16694 #ifdef illumos
16695 	mutex_enter(&mod_lock);
16696 #endif
16697 
16698 #ifdef illumos
16699 	ASSERT(ctl->mod_busy);
16700 #endif
16701 
16702 	/*
16703 	 * We're going to call each providers per-module provide operation
16704 	 * specifying only this module.
16705 	 */
16706 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16707 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16708 
16709 #ifdef illumos
16710 	mutex_exit(&mod_lock);
16711 #endif
16712 	mutex_exit(&dtrace_provider_lock);
16713 
16714 	/*
16715 	 * If we have any retained enablings, we need to match against them.
16716 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16717 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16718 	 * module.  (In particular, this happens when loading scheduling
16719 	 * classes.)  So if we have any retained enablings, we need to dispatch
16720 	 * our task queue to do the match for us.
16721 	 */
16722 	mutex_enter(&dtrace_lock);
16723 
16724 	if (dtrace_retained == NULL) {
16725 		mutex_exit(&dtrace_lock);
16726 		return;
16727 	}
16728 
16729 	(void)taskq_dispatch(dtrace_taskq,
16730 	    (task_func_t *)dtrace_enabling_matchall_task, NULL, TQ_SLEEP);
16731 
16732 	mutex_exit(&dtrace_lock);
16733 
16734 	/*
16735 	 * And now, for a little heuristic sleaze:  in general, we want to
16736 	 * match modules as soon as they load.  However, we cannot guarantee
16737 	 * this, because it would lead us to the lock ordering violation
16738 	 * outlined above.  The common case, of course, is that cpu_lock is
16739 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16740 	 * long enough for the task queue to do its work.  If it's not, it's
16741 	 * not a serious problem -- it just means that the module that we
16742 	 * just loaded may not be immediately instrumentable.
16743 	 */
16744 	delay(1);
16745 }
16746 
16747 static void
16748 #ifdef illumos
16749 dtrace_module_unloaded(modctl_t *ctl)
16750 #else
16751 dtrace_module_unloaded(modctl_t *ctl, int *error)
16752 #endif
16753 {
16754 	dtrace_probe_t template, *probe, *first, *next;
16755 	dtrace_provider_t *prov;
16756 #ifndef illumos
16757 	char modname[DTRACE_MODNAMELEN];
16758 	size_t len;
16759 #endif
16760 
16761 #ifdef illumos
16762 	template.dtpr_mod = ctl->mod_modname;
16763 #else
16764 	/* Handle the fact that ctl->filename may end in ".ko". */
16765 	strlcpy(modname, ctl->filename, sizeof(modname));
16766 	len = strlen(ctl->filename);
16767 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16768 		modname[len - 3] = '\0';
16769 	template.dtpr_mod = modname;
16770 #endif
16771 
16772 	mutex_enter(&dtrace_provider_lock);
16773 #ifdef illumos
16774 	mutex_enter(&mod_lock);
16775 #endif
16776 	mutex_enter(&dtrace_lock);
16777 
16778 #ifndef illumos
16779 	if (ctl->nenabled > 0) {
16780 		/* Don't allow unloads if a probe is enabled. */
16781 		mutex_exit(&dtrace_provider_lock);
16782 		mutex_exit(&dtrace_lock);
16783 		*error = -1;
16784 		printf(
16785 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16786 		return;
16787 	}
16788 #endif
16789 
16790 	if (dtrace_bymod == NULL) {
16791 		/*
16792 		 * The DTrace module is loaded (obviously) but not attached;
16793 		 * we don't have any work to do.
16794 		 */
16795 		mutex_exit(&dtrace_provider_lock);
16796 #ifdef illumos
16797 		mutex_exit(&mod_lock);
16798 #endif
16799 		mutex_exit(&dtrace_lock);
16800 		return;
16801 	}
16802 
16803 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16804 	    probe != NULL; probe = probe->dtpr_nextmod) {
16805 		if (probe->dtpr_ecb != NULL) {
16806 			mutex_exit(&dtrace_provider_lock);
16807 #ifdef illumos
16808 			mutex_exit(&mod_lock);
16809 #endif
16810 			mutex_exit(&dtrace_lock);
16811 
16812 			/*
16813 			 * This shouldn't _actually_ be possible -- we're
16814 			 * unloading a module that has an enabled probe in it.
16815 			 * (It's normally up to the provider to make sure that
16816 			 * this can't happen.)  However, because dtps_enable()
16817 			 * doesn't have a failure mode, there can be an
16818 			 * enable/unload race.  Upshot:  we don't want to
16819 			 * assert, but we're not going to disable the
16820 			 * probe, either.
16821 			 */
16822 			if (dtrace_err_verbose) {
16823 #ifdef illumos
16824 				cmn_err(CE_WARN, "unloaded module '%s' had "
16825 				    "enabled probes", ctl->mod_modname);
16826 #else
16827 				cmn_err(CE_WARN, "unloaded module '%s' had "
16828 				    "enabled probes", modname);
16829 #endif
16830 			}
16831 
16832 			return;
16833 		}
16834 	}
16835 
16836 	probe = first;
16837 
16838 	for (first = NULL; probe != NULL; probe = next) {
16839 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16840 
16841 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16842 
16843 		next = probe->dtpr_nextmod;
16844 		dtrace_hash_remove(dtrace_bymod, probe);
16845 		dtrace_hash_remove(dtrace_byfunc, probe);
16846 		dtrace_hash_remove(dtrace_byname, probe);
16847 
16848 		if (first == NULL) {
16849 			first = probe;
16850 			probe->dtpr_nextmod = NULL;
16851 		} else {
16852 			probe->dtpr_nextmod = first;
16853 			first = probe;
16854 		}
16855 	}
16856 
16857 	/*
16858 	 * We've removed all of the module's probes from the hash chains and
16859 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16860 	 * everyone has cleared out from any probe array processing.
16861 	 */
16862 	dtrace_sync();
16863 
16864 	for (probe = first; probe != NULL; probe = first) {
16865 		first = probe->dtpr_nextmod;
16866 		prov = probe->dtpr_provider;
16867 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16868 		    probe->dtpr_arg);
16869 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16870 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16871 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16872 #ifdef illumos
16873 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16874 #else
16875 		free_unr(dtrace_arena, probe->dtpr_id);
16876 #endif
16877 		kmem_free(probe, sizeof (dtrace_probe_t));
16878 	}
16879 
16880 	mutex_exit(&dtrace_lock);
16881 #ifdef illumos
16882 	mutex_exit(&mod_lock);
16883 #endif
16884 	mutex_exit(&dtrace_provider_lock);
16885 }
16886 
16887 #ifndef illumos
16888 static void
16889 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16890 {
16891 
16892 	dtrace_module_loaded(lf);
16893 }
16894 
16895 static void
16896 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16897 {
16898 
16899 	if (*error != 0)
16900 		/* We already have an error, so don't do anything. */
16901 		return;
16902 	dtrace_module_unloaded(lf, error);
16903 }
16904 #endif
16905 
16906 #ifdef illumos
16907 static void
16908 dtrace_suspend(void)
16909 {
16910 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16911 }
16912 
16913 static void
16914 dtrace_resume(void)
16915 {
16916 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16917 }
16918 #endif
16919 
16920 static int
16921 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16922 {
16923 	ASSERT(MUTEX_HELD(&cpu_lock));
16924 	mutex_enter(&dtrace_lock);
16925 
16926 	switch (what) {
16927 	case CPU_CONFIG: {
16928 		dtrace_state_t *state;
16929 		dtrace_optval_t *opt, rs, c;
16930 
16931 		/*
16932 		 * For now, we only allocate a new buffer for anonymous state.
16933 		 */
16934 		if ((state = dtrace_anon.dta_state) == NULL)
16935 			break;
16936 
16937 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16938 			break;
16939 
16940 		opt = state->dts_options;
16941 		c = opt[DTRACEOPT_CPU];
16942 
16943 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16944 			break;
16945 
16946 		/*
16947 		 * Regardless of what the actual policy is, we're going to
16948 		 * temporarily set our resize policy to be manual.  We're
16949 		 * also going to temporarily set our CPU option to denote
16950 		 * the newly configured CPU.
16951 		 */
16952 		rs = opt[DTRACEOPT_BUFRESIZE];
16953 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16954 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16955 
16956 		(void) dtrace_state_buffers(state);
16957 
16958 		opt[DTRACEOPT_BUFRESIZE] = rs;
16959 		opt[DTRACEOPT_CPU] = c;
16960 
16961 		break;
16962 	}
16963 
16964 	case CPU_UNCONFIG:
16965 		/*
16966 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16967 		 * buffer will be freed when the consumer exits.)
16968 		 */
16969 		break;
16970 
16971 	default:
16972 		break;
16973 	}
16974 
16975 	mutex_exit(&dtrace_lock);
16976 	return (0);
16977 }
16978 
16979 #ifdef illumos
16980 static void
16981 dtrace_cpu_setup_initial(processorid_t cpu)
16982 {
16983 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16984 }
16985 #endif
16986 
16987 static void
16988 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16989 {
16990 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16991 		int osize, nsize;
16992 		dtrace_toxrange_t *range;
16993 
16994 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16995 
16996 		if (osize == 0) {
16997 			ASSERT(dtrace_toxrange == NULL);
16998 			ASSERT(dtrace_toxranges_max == 0);
16999 			dtrace_toxranges_max = 1;
17000 		} else {
17001 			dtrace_toxranges_max <<= 1;
17002 		}
17003 
17004 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17005 		range = kmem_zalloc(nsize, KM_SLEEP);
17006 
17007 		if (dtrace_toxrange != NULL) {
17008 			ASSERT(osize != 0);
17009 			bcopy(dtrace_toxrange, range, osize);
17010 			kmem_free(dtrace_toxrange, osize);
17011 		}
17012 
17013 		dtrace_toxrange = range;
17014 	}
17015 
17016 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17017 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17018 
17019 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17020 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17021 	dtrace_toxranges++;
17022 }
17023 
17024 static void
17025 dtrace_getf_barrier(void)
17026 {
17027 #ifdef illumos
17028 	/*
17029 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17030 	 * that contain calls to getf(), this routine will be called on every
17031 	 * closef() before either the underlying vnode is released or the
17032 	 * file_t itself is freed.  By the time we are here, it is essential
17033 	 * that the file_t can no longer be accessed from a call to getf()
17034 	 * in probe context -- that assures that a dtrace_sync() can be used
17035 	 * to clear out any enablings referring to the old structures.
17036 	 */
17037 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17038 	    kcred->cr_zone->zone_dtrace_getf != 0)
17039 		dtrace_sync();
17040 #endif
17041 }
17042 
17043 /*
17044  * DTrace Driver Cookbook Functions
17045  */
17046 #ifdef illumos
17047 /*ARGSUSED*/
17048 static int
17049 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17050 {
17051 	dtrace_provider_id_t id;
17052 	dtrace_state_t *state = NULL;
17053 	dtrace_enabling_t *enab;
17054 
17055 	mutex_enter(&cpu_lock);
17056 	mutex_enter(&dtrace_provider_lock);
17057 	mutex_enter(&dtrace_lock);
17058 
17059 	if (ddi_soft_state_init(&dtrace_softstate,
17060 	    sizeof (dtrace_state_t), 0) != 0) {
17061 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17062 		mutex_exit(&cpu_lock);
17063 		mutex_exit(&dtrace_provider_lock);
17064 		mutex_exit(&dtrace_lock);
17065 		return (DDI_FAILURE);
17066 	}
17067 
17068 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17069 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17070 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17071 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17072 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17073 		ddi_remove_minor_node(devi, NULL);
17074 		ddi_soft_state_fini(&dtrace_softstate);
17075 		mutex_exit(&cpu_lock);
17076 		mutex_exit(&dtrace_provider_lock);
17077 		mutex_exit(&dtrace_lock);
17078 		return (DDI_FAILURE);
17079 	}
17080 
17081 	ddi_report_dev(devi);
17082 	dtrace_devi = devi;
17083 
17084 	dtrace_modload = dtrace_module_loaded;
17085 	dtrace_modunload = dtrace_module_unloaded;
17086 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17087 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17088 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17089 	dtrace_cpustart_init = dtrace_suspend;
17090 	dtrace_cpustart_fini = dtrace_resume;
17091 	dtrace_debugger_init = dtrace_suspend;
17092 	dtrace_debugger_fini = dtrace_resume;
17093 
17094 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17095 
17096 	ASSERT(MUTEX_HELD(&cpu_lock));
17097 
17098 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17099 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17100 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17101 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17102 	    VM_SLEEP | VMC_IDENTIFIER);
17103 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17104 	    1, INT_MAX, 0);
17105 
17106 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17107 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17108 	    NULL, NULL, NULL, NULL, NULL, 0);
17109 
17110 	ASSERT(MUTEX_HELD(&cpu_lock));
17111 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17112 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17113 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17114 
17115 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17116 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17117 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17118 
17119 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17120 	    offsetof(dtrace_probe_t, dtpr_nextname),
17121 	    offsetof(dtrace_probe_t, dtpr_prevname));
17122 
17123 	if (dtrace_retain_max < 1) {
17124 		cmn_err(CE_WARN, "illegal value (%zu) for dtrace_retain_max; "
17125 		    "setting to 1", dtrace_retain_max);
17126 		dtrace_retain_max = 1;
17127 	}
17128 
17129 	/*
17130 	 * Now discover our toxic ranges.
17131 	 */
17132 	dtrace_toxic_ranges(dtrace_toxrange_add);
17133 
17134 	/*
17135 	 * Before we register ourselves as a provider to our own framework,
17136 	 * we would like to assert that dtrace_provider is NULL -- but that's
17137 	 * not true if we were loaded as a dependency of a DTrace provider.
17138 	 * Once we've registered, we can assert that dtrace_provider is our
17139 	 * pseudo provider.
17140 	 */
17141 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17142 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17143 
17144 	ASSERT(dtrace_provider != NULL);
17145 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17146 
17147 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17148 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17149 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17150 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17151 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17152 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17153 
17154 	dtrace_anon_property();
17155 	mutex_exit(&cpu_lock);
17156 
17157 	/*
17158 	 * If there are already providers, we must ask them to provide their
17159 	 * probes, and then match any anonymous enabling against them.  Note
17160 	 * that there should be no other retained enablings at this time:
17161 	 * the only retained enablings at this time should be the anonymous
17162 	 * enabling.
17163 	 */
17164 	if (dtrace_anon.dta_enabling != NULL) {
17165 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17166 
17167 		dtrace_enabling_provide(NULL);
17168 		state = dtrace_anon.dta_state;
17169 
17170 		/*
17171 		 * We couldn't hold cpu_lock across the above call to
17172 		 * dtrace_enabling_provide(), but we must hold it to actually
17173 		 * enable the probes.  We have to drop all of our locks, pick
17174 		 * up cpu_lock, and regain our locks before matching the
17175 		 * retained anonymous enabling.
17176 		 */
17177 		mutex_exit(&dtrace_lock);
17178 		mutex_exit(&dtrace_provider_lock);
17179 
17180 		mutex_enter(&cpu_lock);
17181 		mutex_enter(&dtrace_provider_lock);
17182 		mutex_enter(&dtrace_lock);
17183 
17184 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17185 			(void) dtrace_enabling_match(enab, NULL);
17186 
17187 		mutex_exit(&cpu_lock);
17188 	}
17189 
17190 	mutex_exit(&dtrace_lock);
17191 	mutex_exit(&dtrace_provider_lock);
17192 
17193 	if (state != NULL) {
17194 		/*
17195 		 * If we created any anonymous state, set it going now.
17196 		 */
17197 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17198 	}
17199 
17200 	return (DDI_SUCCESS);
17201 }
17202 #endif	/* illumos */
17203 
17204 #ifndef illumos
17205 static void dtrace_dtr(void *);
17206 #endif
17207 
17208 /*ARGSUSED*/
17209 static int
17210 #ifdef illumos
17211 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17212 #else
17213 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17214 #endif
17215 {
17216 	dtrace_state_t *state;
17217 	uint32_t priv;
17218 	uid_t uid;
17219 	zoneid_t zoneid;
17220 
17221 #ifdef illumos
17222 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17223 		return (0);
17224 
17225 	/*
17226 	 * If this wasn't an open with the "helper" minor, then it must be
17227 	 * the "dtrace" minor.
17228 	 */
17229 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17230 		return (ENXIO);
17231 #else
17232 	cred_t *cred_p = NULL;
17233 	cred_p = dev->si_cred;
17234 
17235 	/*
17236 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17237 	 * caller lacks sufficient permission to do anything with DTrace.
17238 	 */
17239 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17240 	if (priv == DTRACE_PRIV_NONE) {
17241 #endif
17242 
17243 		return (EACCES);
17244 	}
17245 
17246 	/*
17247 	 * Ask all providers to provide all their probes.
17248 	 */
17249 	mutex_enter(&dtrace_provider_lock);
17250 	dtrace_probe_provide(NULL, NULL);
17251 	mutex_exit(&dtrace_provider_lock);
17252 
17253 	mutex_enter(&cpu_lock);
17254 	mutex_enter(&dtrace_lock);
17255 	dtrace_opens++;
17256 	dtrace_membar_producer();
17257 
17258 #ifdef illumos
17259 	/*
17260 	 * If the kernel debugger is active (that is, if the kernel debugger
17261 	 * modified text in some way), we won't allow the open.
17262 	 */
17263 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17264 		dtrace_opens--;
17265 		mutex_exit(&cpu_lock);
17266 		mutex_exit(&dtrace_lock);
17267 		return (EBUSY);
17268 	}
17269 
17270 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17271 		/*
17272 		 * If DTrace helper tracing is enabled, we need to allocate the
17273 		 * trace buffer and initialize the values.
17274 		 */
17275 		dtrace_helptrace_buffer =
17276 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17277 		dtrace_helptrace_next = 0;
17278 		dtrace_helptrace_wrapped = 0;
17279 		dtrace_helptrace_enable = 0;
17280 	}
17281 
17282 	state = dtrace_state_create(devp, cred_p);
17283 #else
17284 	state = dtrace_state_create(dev, NULL);
17285 	devfs_set_cdevpriv(state, dtrace_dtr);
17286 #endif
17287 
17288 	mutex_exit(&cpu_lock);
17289 
17290 	if (state == NULL) {
17291 #ifdef illumos
17292 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17293 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17294 #else
17295 		--dtrace_opens;
17296 #endif
17297 		mutex_exit(&dtrace_lock);
17298 		return (EAGAIN);
17299 	}
17300 
17301 	mutex_exit(&dtrace_lock);
17302 
17303 	return (0);
17304 }
17305 
17306 /*ARGSUSED*/
17307 #ifdef illumos
17308 static int
17309 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17310 #else
17311 static void
17312 dtrace_dtr(void *data)
17313 #endif
17314 {
17315 #ifdef illumos
17316 	minor_t minor = getminor(dev);
17317 	dtrace_state_t *state;
17318 #endif
17319 	dtrace_helptrace_t *buf = NULL;
17320 
17321 #ifdef illumos
17322 	if (minor == DTRACEMNRN_HELPER)
17323 		return (0);
17324 
17325 	state = ddi_get_soft_state(dtrace_softstate, minor);
17326 #else
17327 	dtrace_state_t *state = data;
17328 #endif
17329 
17330 	mutex_enter(&cpu_lock);
17331 	mutex_enter(&dtrace_lock);
17332 
17333 #ifdef illumos
17334 	if (state->dts_anon)
17335 #else
17336 	if (state != NULL && state->dts_anon)
17337 #endif
17338 	{
17339 		/*
17340 		 * There is anonymous state. Destroy that first.
17341 		 */
17342 		ASSERT(dtrace_anon.dta_state == NULL);
17343 		dtrace_state_destroy(state->dts_anon);
17344 	}
17345 
17346 	if (dtrace_helptrace_disable) {
17347 		/*
17348 		 * If we have been told to disable helper tracing, set the
17349 		 * buffer to NULL before calling into dtrace_state_destroy();
17350 		 * we take advantage of its dtrace_sync() to know that no
17351 		 * CPU is in probe context with enabled helper tracing
17352 		 * after it returns.
17353 		 */
17354 		buf = dtrace_helptrace_buffer;
17355 		dtrace_helptrace_buffer = NULL;
17356 	}
17357 
17358 #ifdef illumos
17359 	dtrace_state_destroy(state);
17360 #else
17361 	if (state != NULL) {
17362 		dtrace_state_destroy(state);
17363 		kmem_free(state, 0);
17364 	}
17365 #endif
17366 	ASSERT(dtrace_opens > 0);
17367 
17368 #ifdef illumos
17369 	/*
17370 	 * Only relinquish control of the kernel debugger interface when there
17371 	 * are no consumers and no anonymous enablings.
17372 	 */
17373 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17374 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17375 #else
17376 	--dtrace_opens;
17377 #endif
17378 
17379 	if (buf != NULL) {
17380 		kmem_free(buf, dtrace_helptrace_bufsize);
17381 		dtrace_helptrace_disable = 0;
17382 	}
17383 
17384 	mutex_exit(&dtrace_lock);
17385 	mutex_exit(&cpu_lock);
17386 
17387 #ifdef illumos
17388 	return (0);
17389 #endif
17390 }
17391 
17392 #ifdef illumos
17393 /*ARGSUSED*/
17394 static int
17395 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17396 {
17397 	int rval;
17398 	dof_helper_t help, *dhp = NULL;
17399 
17400 	switch (cmd) {
17401 	case DTRACEHIOC_ADDDOF:
17402 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17403 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17404 			return (EFAULT);
17405 		}
17406 
17407 		dhp = &help;
17408 		arg = (intptr_t)help.dofhp_dof;
17409 		/*FALLTHROUGH*/
17410 
17411 	case DTRACEHIOC_ADD: {
17412 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17413 
17414 		if (dof == NULL)
17415 			return (rval);
17416 
17417 		mutex_enter(&dtrace_lock);
17418 
17419 		/*
17420 		 * dtrace_helper_slurp() takes responsibility for the dof --
17421 		 * it may free it now or it may save it and free it later.
17422 		 */
17423 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17424 			*rv = rval;
17425 			rval = 0;
17426 		} else {
17427 			rval = EINVAL;
17428 		}
17429 
17430 		mutex_exit(&dtrace_lock);
17431 		return (rval);
17432 	}
17433 
17434 	case DTRACEHIOC_REMOVE: {
17435 		mutex_enter(&dtrace_lock);
17436 		rval = dtrace_helper_destroygen(NULL, arg);
17437 		mutex_exit(&dtrace_lock);
17438 
17439 		return (rval);
17440 	}
17441 
17442 	default:
17443 		break;
17444 	}
17445 
17446 	return (ENOTTY);
17447 }
17448 
17449 /*ARGSUSED*/
17450 static int
17451 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17452 {
17453 	minor_t minor = getminor(dev);
17454 	dtrace_state_t *state;
17455 	int rval;
17456 
17457 	if (minor == DTRACEMNRN_HELPER)
17458 		return (dtrace_ioctl_helper(cmd, arg, rv));
17459 
17460 	state = ddi_get_soft_state(dtrace_softstate, minor);
17461 
17462 	if (state->dts_anon) {
17463 		ASSERT(dtrace_anon.dta_state == NULL);
17464 		state = state->dts_anon;
17465 	}
17466 
17467 	switch (cmd) {
17468 	case DTRACEIOC_PROVIDER: {
17469 		dtrace_providerdesc_t pvd;
17470 		dtrace_provider_t *pvp;
17471 
17472 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17473 			return (EFAULT);
17474 
17475 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17476 		mutex_enter(&dtrace_provider_lock);
17477 
17478 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17479 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17480 				break;
17481 		}
17482 
17483 		mutex_exit(&dtrace_provider_lock);
17484 
17485 		if (pvp == NULL)
17486 			return (ESRCH);
17487 
17488 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17489 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17490 
17491 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17492 			return (EFAULT);
17493 
17494 		return (0);
17495 	}
17496 
17497 	case DTRACEIOC_EPROBE: {
17498 		dtrace_eprobedesc_t epdesc;
17499 		dtrace_ecb_t *ecb;
17500 		dtrace_action_t *act;
17501 		void *buf;
17502 		size_t size;
17503 		uintptr_t dest;
17504 		int nrecs;
17505 
17506 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17507 			return (EFAULT);
17508 
17509 		mutex_enter(&dtrace_lock);
17510 
17511 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17512 			mutex_exit(&dtrace_lock);
17513 			return (EINVAL);
17514 		}
17515 
17516 		if (ecb->dte_probe == NULL) {
17517 			mutex_exit(&dtrace_lock);
17518 			return (EINVAL);
17519 		}
17520 
17521 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17522 		epdesc.dtepd_uarg = ecb->dte_uarg;
17523 		epdesc.dtepd_size = ecb->dte_size;
17524 
17525 		nrecs = epdesc.dtepd_nrecs;
17526 		epdesc.dtepd_nrecs = 0;
17527 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17528 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17529 				continue;
17530 
17531 			epdesc.dtepd_nrecs++;
17532 		}
17533 
17534 		/*
17535 		 * Now that we have the size, we need to allocate a temporary
17536 		 * buffer in which to store the complete description.  We need
17537 		 * the temporary buffer to be able to drop dtrace_lock()
17538 		 * across the copyout(), below.
17539 		 */
17540 		size = sizeof (dtrace_eprobedesc_t) +
17541 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17542 
17543 		buf = kmem_alloc(size, KM_SLEEP);
17544 		dest = (uintptr_t)buf;
17545 
17546 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17547 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17548 
17549 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17550 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17551 				continue;
17552 
17553 			if (nrecs-- == 0)
17554 				break;
17555 
17556 			bcopy(&act->dta_rec, (void *)dest,
17557 			    sizeof (dtrace_recdesc_t));
17558 			dest += sizeof (dtrace_recdesc_t);
17559 		}
17560 
17561 		mutex_exit(&dtrace_lock);
17562 
17563 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17564 			kmem_free(buf, size);
17565 			return (EFAULT);
17566 		}
17567 
17568 		kmem_free(buf, size);
17569 		return (0);
17570 	}
17571 
17572 	case DTRACEIOC_AGGDESC: {
17573 		dtrace_aggdesc_t aggdesc;
17574 		dtrace_action_t *act;
17575 		dtrace_aggregation_t *agg;
17576 		int nrecs;
17577 		uint32_t offs;
17578 		dtrace_recdesc_t *lrec;
17579 		void *buf;
17580 		size_t size;
17581 		uintptr_t dest;
17582 
17583 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17584 			return (EFAULT);
17585 
17586 		mutex_enter(&dtrace_lock);
17587 
17588 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17589 			mutex_exit(&dtrace_lock);
17590 			return (EINVAL);
17591 		}
17592 
17593 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17594 
17595 		nrecs = aggdesc.dtagd_nrecs;
17596 		aggdesc.dtagd_nrecs = 0;
17597 
17598 		offs = agg->dtag_base;
17599 		lrec = &agg->dtag_action.dta_rec;
17600 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17601 
17602 		for (act = agg->dtag_first; ; act = act->dta_next) {
17603 			ASSERT(act->dta_intuple ||
17604 			    DTRACEACT_ISAGG(act->dta_kind));
17605 
17606 			/*
17607 			 * If this action has a record size of zero, it
17608 			 * denotes an argument to the aggregating action.
17609 			 * Because the presence of this record doesn't (or
17610 			 * shouldn't) affect the way the data is interpreted,
17611 			 * we don't copy it out to save user-level the
17612 			 * confusion of dealing with a zero-length record.
17613 			 */
17614 			if (act->dta_rec.dtrd_size == 0) {
17615 				ASSERT(agg->dtag_hasarg);
17616 				continue;
17617 			}
17618 
17619 			aggdesc.dtagd_nrecs++;
17620 
17621 			if (act == &agg->dtag_action)
17622 				break;
17623 		}
17624 
17625 		/*
17626 		 * Now that we have the size, we need to allocate a temporary
17627 		 * buffer in which to store the complete description.  We need
17628 		 * the temporary buffer to be able to drop dtrace_lock()
17629 		 * across the copyout(), below.
17630 		 */
17631 		size = sizeof (dtrace_aggdesc_t) +
17632 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17633 
17634 		buf = kmem_alloc(size, KM_SLEEP);
17635 		dest = (uintptr_t)buf;
17636 
17637 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17638 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17639 
17640 		for (act = agg->dtag_first; ; act = act->dta_next) {
17641 			dtrace_recdesc_t rec = act->dta_rec;
17642 
17643 			/*
17644 			 * See the comment in the above loop for why we pass
17645 			 * over zero-length records.
17646 			 */
17647 			if (rec.dtrd_size == 0) {
17648 				ASSERT(agg->dtag_hasarg);
17649 				continue;
17650 			}
17651 
17652 			if (nrecs-- == 0)
17653 				break;
17654 
17655 			rec.dtrd_offset -= offs;
17656 			bcopy(&rec, (void *)dest, sizeof (rec));
17657 			dest += sizeof (dtrace_recdesc_t);
17658 
17659 			if (act == &agg->dtag_action)
17660 				break;
17661 		}
17662 
17663 		mutex_exit(&dtrace_lock);
17664 
17665 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17666 			kmem_free(buf, size);
17667 			return (EFAULT);
17668 		}
17669 
17670 		kmem_free(buf, size);
17671 		return (0);
17672 	}
17673 
17674 	case DTRACEIOC_ENABLE: {
17675 		dof_hdr_t *dof;
17676 		dtrace_enabling_t *enab = NULL;
17677 		dtrace_vstate_t *vstate;
17678 		int err = 0;
17679 
17680 		*rv = 0;
17681 
17682 		/*
17683 		 * If a NULL argument has been passed, we take this as our
17684 		 * cue to reevaluate our enablings.
17685 		 */
17686 		if (arg == NULL) {
17687 			dtrace_enabling_matchall();
17688 
17689 			return (0);
17690 		}
17691 
17692 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17693 			return (rval);
17694 
17695 		mutex_enter(&cpu_lock);
17696 		mutex_enter(&dtrace_lock);
17697 		vstate = &state->dts_vstate;
17698 
17699 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17700 			mutex_exit(&dtrace_lock);
17701 			mutex_exit(&cpu_lock);
17702 			dtrace_dof_destroy(dof);
17703 			return (EBUSY);
17704 		}
17705 
17706 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17707 			mutex_exit(&dtrace_lock);
17708 			mutex_exit(&cpu_lock);
17709 			dtrace_dof_destroy(dof);
17710 			return (EINVAL);
17711 		}
17712 
17713 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17714 			dtrace_enabling_destroy(enab);
17715 			mutex_exit(&dtrace_lock);
17716 			mutex_exit(&cpu_lock);
17717 			dtrace_dof_destroy(dof);
17718 			return (rval);
17719 		}
17720 
17721 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17722 			err = dtrace_enabling_retain(enab);
17723 		} else {
17724 			dtrace_enabling_destroy(enab);
17725 		}
17726 
17727 		mutex_exit(&cpu_lock);
17728 		mutex_exit(&dtrace_lock);
17729 		dtrace_dof_destroy(dof);
17730 
17731 		return (err);
17732 	}
17733 
17734 	case DTRACEIOC_REPLICATE: {
17735 		dtrace_repldesc_t desc;
17736 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17737 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17738 		int err;
17739 
17740 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17741 			return (EFAULT);
17742 
17743 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17744 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17745 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17746 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17747 
17748 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17749 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17750 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17751 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17752 
17753 		mutex_enter(&dtrace_lock);
17754 		err = dtrace_enabling_replicate(state, match, create);
17755 		mutex_exit(&dtrace_lock);
17756 
17757 		return (err);
17758 	}
17759 
17760 	case DTRACEIOC_PROBEMATCH:
17761 	case DTRACEIOC_PROBES: {
17762 		dtrace_probe_t *probe = NULL;
17763 		dtrace_probedesc_t desc;
17764 		dtrace_probekey_t pkey;
17765 		dtrace_id_t i;
17766 		int m = 0;
17767 		uint32_t priv;
17768 		uid_t uid;
17769 		zoneid_t zoneid;
17770 
17771 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17772 			return (EFAULT);
17773 
17774 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17775 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17776 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17777 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17778 
17779 		/*
17780 		 * Before we attempt to match this probe, we want to give
17781 		 * all providers the opportunity to provide it.
17782 		 */
17783 		if (desc.dtpd_id == DTRACE_IDNONE) {
17784 			mutex_enter(&dtrace_provider_lock);
17785 			dtrace_probe_provide(&desc, NULL);
17786 			mutex_exit(&dtrace_provider_lock);
17787 			desc.dtpd_id++;
17788 		}
17789 
17790 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17791 			dtrace_probekey(&desc, &pkey);
17792 			pkey.dtpk_id = DTRACE_IDNONE;
17793 		}
17794 
17795 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17796 
17797 		mutex_enter(&dtrace_lock);
17798 
17799 		if (cmd == DTRACEIOC_PROBEMATCH) {
17800 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17801 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17802 				    (m = dtrace_match_probe(probe, &pkey,
17803 				    priv, uid, zoneid)) != 0)
17804 					break;
17805 			}
17806 
17807 			if (m < 0) {
17808 				mutex_exit(&dtrace_lock);
17809 				return (EINVAL);
17810 			}
17811 
17812 		} else {
17813 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17814 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17815 				    dtrace_match_priv(probe, priv, uid, zoneid))
17816 					break;
17817 			}
17818 		}
17819 
17820 		if (probe == NULL) {
17821 			mutex_exit(&dtrace_lock);
17822 			return (ESRCH);
17823 		}
17824 
17825 		dtrace_probe_description(probe, &desc);
17826 		mutex_exit(&dtrace_lock);
17827 
17828 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17829 			return (EFAULT);
17830 
17831 		return (0);
17832 	}
17833 
17834 	case DTRACEIOC_PROBEARG: {
17835 		dtrace_argdesc_t desc;
17836 		dtrace_probe_t *probe;
17837 		dtrace_provider_t *prov;
17838 
17839 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17840 			return (EFAULT);
17841 
17842 		if (desc.dtargd_id == DTRACE_IDNONE)
17843 			return (EINVAL);
17844 
17845 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17846 			return (EINVAL);
17847 
17848 		mutex_enter(&dtrace_provider_lock);
17849 		mutex_enter(&mod_lock);
17850 		mutex_enter(&dtrace_lock);
17851 
17852 		if (desc.dtargd_id > dtrace_nprobes) {
17853 			mutex_exit(&dtrace_lock);
17854 			mutex_exit(&mod_lock);
17855 			mutex_exit(&dtrace_provider_lock);
17856 			return (EINVAL);
17857 		}
17858 
17859 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17860 			mutex_exit(&dtrace_lock);
17861 			mutex_exit(&mod_lock);
17862 			mutex_exit(&dtrace_provider_lock);
17863 			return (EINVAL);
17864 		}
17865 
17866 		mutex_exit(&dtrace_lock);
17867 
17868 		prov = probe->dtpr_provider;
17869 
17870 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17871 			/*
17872 			 * There isn't any typed information for this probe.
17873 			 * Set the argument number to DTRACE_ARGNONE.
17874 			 */
17875 			desc.dtargd_ndx = DTRACE_ARGNONE;
17876 		} else {
17877 			desc.dtargd_native[0] = '\0';
17878 			desc.dtargd_xlate[0] = '\0';
17879 			desc.dtargd_mapping = desc.dtargd_ndx;
17880 
17881 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17882 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17883 		}
17884 
17885 		mutex_exit(&mod_lock);
17886 		mutex_exit(&dtrace_provider_lock);
17887 
17888 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17889 			return (EFAULT);
17890 
17891 		return (0);
17892 	}
17893 
17894 	case DTRACEIOC_GO: {
17895 		processorid_t cpuid;
17896 		rval = dtrace_state_go(state, &cpuid);
17897 
17898 		if (rval != 0)
17899 			return (rval);
17900 
17901 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17902 			return (EFAULT);
17903 
17904 		return (0);
17905 	}
17906 
17907 	case DTRACEIOC_STOP: {
17908 		processorid_t cpuid;
17909 
17910 		mutex_enter(&dtrace_lock);
17911 		rval = dtrace_state_stop(state, &cpuid);
17912 		mutex_exit(&dtrace_lock);
17913 
17914 		if (rval != 0)
17915 			return (rval);
17916 
17917 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17918 			return (EFAULT);
17919 
17920 		return (0);
17921 	}
17922 
17923 	case DTRACEIOC_DOFGET: {
17924 		dof_hdr_t hdr, *dof;
17925 		uint64_t len;
17926 
17927 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17928 			return (EFAULT);
17929 
17930 		mutex_enter(&dtrace_lock);
17931 		dof = dtrace_dof_create(state);
17932 		mutex_exit(&dtrace_lock);
17933 
17934 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17935 		rval = copyout(dof, (void *)arg, len);
17936 		dtrace_dof_destroy(dof);
17937 
17938 		return (rval == 0 ? 0 : EFAULT);
17939 	}
17940 
17941 	case DTRACEIOC_AGGSNAP:
17942 	case DTRACEIOC_BUFSNAP: {
17943 		dtrace_bufdesc_t desc;
17944 		caddr_t cached;
17945 		dtrace_buffer_t *buf;
17946 
17947 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17948 			return (EFAULT);
17949 
17950 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17951 			return (EINVAL);
17952 
17953 		mutex_enter(&dtrace_lock);
17954 
17955 		if (cmd == DTRACEIOC_BUFSNAP) {
17956 			buf = &state->dts_buffer[desc.dtbd_cpu];
17957 		} else {
17958 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17959 		}
17960 
17961 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17962 			size_t sz = buf->dtb_offset;
17963 
17964 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17965 				mutex_exit(&dtrace_lock);
17966 				return (EBUSY);
17967 			}
17968 
17969 			/*
17970 			 * If this buffer has already been consumed, we're
17971 			 * going to indicate that there's nothing left here
17972 			 * to consume.
17973 			 */
17974 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17975 				mutex_exit(&dtrace_lock);
17976 
17977 				desc.dtbd_size = 0;
17978 				desc.dtbd_drops = 0;
17979 				desc.dtbd_errors = 0;
17980 				desc.dtbd_oldest = 0;
17981 				sz = sizeof (desc);
17982 
17983 				if (copyout(&desc, (void *)arg, sz) != 0)
17984 					return (EFAULT);
17985 
17986 				return (0);
17987 			}
17988 
17989 			/*
17990 			 * If this is a ring buffer that has wrapped, we want
17991 			 * to copy the whole thing out.
17992 			 */
17993 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17994 				dtrace_buffer_polish(buf);
17995 				sz = buf->dtb_size;
17996 			}
17997 
17998 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17999 				mutex_exit(&dtrace_lock);
18000 				return (EFAULT);
18001 			}
18002 
18003 			desc.dtbd_size = sz;
18004 			desc.dtbd_drops = buf->dtb_drops;
18005 			desc.dtbd_errors = buf->dtb_errors;
18006 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18007 			desc.dtbd_timestamp = dtrace_gethrtime();
18008 
18009 			mutex_exit(&dtrace_lock);
18010 
18011 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18012 				return (EFAULT);
18013 
18014 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18015 
18016 			return (0);
18017 		}
18018 
18019 		if (buf->dtb_tomax == NULL) {
18020 			ASSERT(buf->dtb_xamot == NULL);
18021 			mutex_exit(&dtrace_lock);
18022 			return (ENOENT);
18023 		}
18024 
18025 		cached = buf->dtb_tomax;
18026 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18027 
18028 		dtrace_xcall(desc.dtbd_cpu,
18029 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18030 
18031 		state->dts_errors += buf->dtb_xamot_errors;
18032 
18033 		/*
18034 		 * If the buffers did not actually switch, then the cross call
18035 		 * did not take place -- presumably because the given CPU is
18036 		 * not in the ready set.  If this is the case, we'll return
18037 		 * ENOENT.
18038 		 */
18039 		if (buf->dtb_tomax == cached) {
18040 			ASSERT(buf->dtb_xamot != cached);
18041 			mutex_exit(&dtrace_lock);
18042 			return (ENOENT);
18043 		}
18044 
18045 		ASSERT(cached == buf->dtb_xamot);
18046 
18047 		/*
18048 		 * We have our snapshot; now copy it out.
18049 		 */
18050 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18051 		    buf->dtb_xamot_offset) != 0) {
18052 			mutex_exit(&dtrace_lock);
18053 			return (EFAULT);
18054 		}
18055 
18056 		desc.dtbd_size = buf->dtb_xamot_offset;
18057 		desc.dtbd_drops = buf->dtb_xamot_drops;
18058 		desc.dtbd_errors = buf->dtb_xamot_errors;
18059 		desc.dtbd_oldest = 0;
18060 		desc.dtbd_timestamp = buf->dtb_switched;
18061 
18062 		mutex_exit(&dtrace_lock);
18063 
18064 		/*
18065 		 * Finally, copy out the buffer description.
18066 		 */
18067 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18068 			return (EFAULT);
18069 
18070 		return (0);
18071 	}
18072 
18073 	case DTRACEIOC_CONF: {
18074 		dtrace_conf_t conf;
18075 
18076 		bzero(&conf, sizeof (conf));
18077 		conf.dtc_difversion = DIF_VERSION;
18078 		conf.dtc_difintregs = DIF_DIR_NREGS;
18079 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18080 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18081 
18082 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18083 			return (EFAULT);
18084 
18085 		return (0);
18086 	}
18087 
18088 	case DTRACEIOC_STATUS: {
18089 		dtrace_status_t stat;
18090 		dtrace_dstate_t *dstate;
18091 		int i, j;
18092 		uint64_t nerrs;
18093 
18094 		/*
18095 		 * See the comment in dtrace_state_deadman() for the reason
18096 		 * for setting dts_laststatus to INT64_MAX before setting
18097 		 * it to the correct value.
18098 		 */
18099 		state->dts_laststatus = INT64_MAX;
18100 		dtrace_membar_producer();
18101 		state->dts_laststatus = dtrace_gethrtime();
18102 
18103 		bzero(&stat, sizeof (stat));
18104 
18105 		mutex_enter(&dtrace_lock);
18106 
18107 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18108 			mutex_exit(&dtrace_lock);
18109 			return (ENOENT);
18110 		}
18111 
18112 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18113 			stat.dtst_exiting = 1;
18114 
18115 		nerrs = state->dts_errors;
18116 		dstate = &state->dts_vstate.dtvs_dynvars;
18117 
18118 		for (i = 0; i < NCPU; i++) {
18119 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18120 
18121 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18122 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18123 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18124 
18125 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18126 				stat.dtst_filled++;
18127 
18128 			nerrs += state->dts_buffer[i].dtb_errors;
18129 
18130 			for (j = 0; j < state->dts_nspeculations; j++) {
18131 				dtrace_speculation_t *spec;
18132 				dtrace_buffer_t *buf;
18133 
18134 				spec = &state->dts_speculations[j];
18135 				buf = &spec->dtsp_buffer[i];
18136 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18137 			}
18138 		}
18139 
18140 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18141 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18142 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18143 		stat.dtst_dblerrors = state->dts_dblerrors;
18144 		stat.dtst_killed =
18145 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18146 		stat.dtst_errors = nerrs;
18147 
18148 		mutex_exit(&dtrace_lock);
18149 
18150 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18151 			return (EFAULT);
18152 
18153 		return (0);
18154 	}
18155 
18156 	case DTRACEIOC_FORMAT: {
18157 		dtrace_fmtdesc_t fmt;
18158 		char *str;
18159 		int len;
18160 
18161 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18162 			return (EFAULT);
18163 
18164 		mutex_enter(&dtrace_lock);
18165 
18166 		if (fmt.dtfd_format == 0 ||
18167 		    fmt.dtfd_format > state->dts_nformats) {
18168 			mutex_exit(&dtrace_lock);
18169 			return (EINVAL);
18170 		}
18171 
18172 		/*
18173 		 * Format strings are allocated contiguously and they are
18174 		 * never freed; if a format index is less than the number
18175 		 * of formats, we can assert that the format map is non-NULL
18176 		 * and that the format for the specified index is non-NULL.
18177 		 */
18178 		ASSERT(state->dts_formats != NULL);
18179 		str = state->dts_formats[fmt.dtfd_format - 1];
18180 		ASSERT(str != NULL);
18181 
18182 		len = strlen(str) + 1;
18183 
18184 		if (len > fmt.dtfd_length) {
18185 			fmt.dtfd_length = len;
18186 
18187 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18188 				mutex_exit(&dtrace_lock);
18189 				return (EINVAL);
18190 			}
18191 		} else {
18192 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18193 				mutex_exit(&dtrace_lock);
18194 				return (EINVAL);
18195 			}
18196 		}
18197 
18198 		mutex_exit(&dtrace_lock);
18199 		return (0);
18200 	}
18201 
18202 	default:
18203 		break;
18204 	}
18205 
18206 	return (ENOTTY);
18207 }
18208 
18209 /*ARGSUSED*/
18210 static int
18211 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18212 {
18213 	dtrace_state_t *state;
18214 
18215 	switch (cmd) {
18216 	case DDI_DETACH:
18217 		break;
18218 
18219 	case DDI_SUSPEND:
18220 		return (DDI_SUCCESS);
18221 
18222 	default:
18223 		return (DDI_FAILURE);
18224 	}
18225 
18226 	mutex_enter(&cpu_lock);
18227 	mutex_enter(&dtrace_provider_lock);
18228 	mutex_enter(&dtrace_lock);
18229 
18230 	ASSERT(dtrace_opens == 0);
18231 
18232 	if (dtrace_helpers > 0) {
18233 		mutex_exit(&dtrace_provider_lock);
18234 		mutex_exit(&dtrace_lock);
18235 		mutex_exit(&cpu_lock);
18236 		return (DDI_FAILURE);
18237 	}
18238 
18239 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18240 		mutex_exit(&dtrace_provider_lock);
18241 		mutex_exit(&dtrace_lock);
18242 		mutex_exit(&cpu_lock);
18243 		return (DDI_FAILURE);
18244 	}
18245 
18246 	dtrace_provider = NULL;
18247 
18248 	if ((state = dtrace_anon_grab()) != NULL) {
18249 		/*
18250 		 * If there were ECBs on this state, the provider should
18251 		 * have not been allowed to detach; assert that there is
18252 		 * none.
18253 		 */
18254 		ASSERT(state->dts_necbs == 0);
18255 		dtrace_state_destroy(state);
18256 
18257 		/*
18258 		 * If we're being detached with anonymous state, we need to
18259 		 * indicate to the kernel debugger that DTrace is now inactive.
18260 		 */
18261 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18262 	}
18263 
18264 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18265 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18266 	dtrace_cpu_init = NULL;
18267 	dtrace_helpers_cleanup = NULL;
18268 	dtrace_helpers_fork = NULL;
18269 	dtrace_cpustart_init = NULL;
18270 	dtrace_cpustart_fini = NULL;
18271 	dtrace_debugger_init = NULL;
18272 	dtrace_debugger_fini = NULL;
18273 	dtrace_modload = NULL;
18274 	dtrace_modunload = NULL;
18275 
18276 	ASSERT(dtrace_getf == 0);
18277 	ASSERT(dtrace_closef == NULL);
18278 
18279 	mutex_exit(&cpu_lock);
18280 
18281 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18282 	dtrace_probes = NULL;
18283 	dtrace_nprobes = 0;
18284 
18285 	dtrace_hash_destroy(dtrace_bymod);
18286 	dtrace_hash_destroy(dtrace_byfunc);
18287 	dtrace_hash_destroy(dtrace_byname);
18288 	dtrace_bymod = NULL;
18289 	dtrace_byfunc = NULL;
18290 	dtrace_byname = NULL;
18291 
18292 	kmem_cache_destroy(dtrace_state_cache);
18293 	vmem_destroy(dtrace_minor);
18294 	vmem_destroy(dtrace_arena);
18295 
18296 	if (dtrace_toxrange != NULL) {
18297 		kmem_free(dtrace_toxrange,
18298 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18299 		dtrace_toxrange = NULL;
18300 		dtrace_toxranges = 0;
18301 		dtrace_toxranges_max = 0;
18302 	}
18303 
18304 	ddi_remove_minor_node(dtrace_devi, NULL);
18305 	dtrace_devi = NULL;
18306 
18307 	ddi_soft_state_fini(&dtrace_softstate);
18308 
18309 	ASSERT(dtrace_vtime_references == 0);
18310 	ASSERT(dtrace_opens == 0);
18311 	ASSERT(dtrace_retained == NULL);
18312 
18313 	mutex_exit(&dtrace_lock);
18314 	mutex_exit(&dtrace_provider_lock);
18315 
18316 	/*
18317 	 * We don't destroy the task queue until after we have dropped our
18318 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18319 	 * attempting to do work after we have effectively detached but before
18320 	 * the task queue has been destroyed, all tasks dispatched via the
18321 	 * task queue must check that DTrace is still attached before
18322 	 * performing any operation.
18323 	 */
18324 	taskq_destroy(dtrace_taskq);
18325 	dtrace_taskq = NULL;
18326 
18327 	return (DDI_SUCCESS);
18328 }
18329 #endif
18330 
18331 #ifdef illumos
18332 /*ARGSUSED*/
18333 static int
18334 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18335 {
18336 	int error;
18337 
18338 	switch (infocmd) {
18339 	case DDI_INFO_DEVT2DEVINFO:
18340 		*result = (void *)dtrace_devi;
18341 		error = DDI_SUCCESS;
18342 		break;
18343 	case DDI_INFO_DEVT2INSTANCE:
18344 		*result = (void *)0;
18345 		error = DDI_SUCCESS;
18346 		break;
18347 	default:
18348 		error = DDI_FAILURE;
18349 	}
18350 	return (error);
18351 }
18352 #endif
18353 
18354 #ifdef illumos
18355 static struct cb_ops dtrace_cb_ops = {
18356 	dtrace_open,		/* open */
18357 	dtrace_close,		/* close */
18358 	nulldev,		/* strategy */
18359 	nulldev,		/* print */
18360 	nodev,			/* dump */
18361 	nodev,			/* read */
18362 	nodev,			/* write */
18363 	dtrace_ioctl,		/* ioctl */
18364 	nodev,			/* devmap */
18365 	nodev,			/* mmap */
18366 	nodev,			/* segmap */
18367 	nochpoll,		/* poll */
18368 	ddi_prop_op,		/* cb_prop_op */
18369 	0,			/* streamtab  */
18370 	D_NEW | D_MP		/* Driver compatibility flag */
18371 };
18372 
18373 static struct dev_ops dtrace_ops = {
18374 	DEVO_REV,		/* devo_rev */
18375 	0,			/* refcnt */
18376 	dtrace_info,		/* get_dev_info */
18377 	nulldev,		/* identify */
18378 	nulldev,		/* probe */
18379 	dtrace_attach,		/* attach */
18380 	dtrace_detach,		/* detach */
18381 	nodev,			/* reset */
18382 	&dtrace_cb_ops,		/* driver operations */
18383 	NULL,			/* bus operations */
18384 	nodev			/* dev power */
18385 };
18386 
18387 static struct modldrv modldrv = {
18388 	&mod_driverops,		/* module type (this is a pseudo driver) */
18389 	"Dynamic Tracing",	/* name of module */
18390 	&dtrace_ops,		/* driver ops */
18391 };
18392 
18393 static struct modlinkage modlinkage = {
18394 	MODREV_1,
18395 	(void *)&modldrv,
18396 	NULL
18397 };
18398 
18399 int
18400 _init(void)
18401 {
18402 	return (mod_install(&modlinkage));
18403 }
18404 
18405 int
18406 _info(struct modinfo *modinfop)
18407 {
18408 	return (mod_info(&modlinkage, modinfop));
18409 }
18410 
18411 int
18412 _fini(void)
18413 {
18414 	return (mod_remove(&modlinkage));
18415 }
18416 #else
18417 
18418 static d_ioctl_t	dtrace_ioctl;
18419 static d_ioctl_t	dtrace_ioctl_helper;
18420 static void		dtrace_load(void *);
18421 static int		dtrace_unload(void);
18422 static struct cdev	*dtrace_dev;
18423 static struct cdev	*helper_dev;
18424 
18425 void dtrace_invop_init(void);
18426 void dtrace_invop_uninit(void);
18427 
18428 static struct cdevsw dtrace_cdevsw = {
18429 	.d_version	= D_VERSION,
18430 	.d_ioctl	= dtrace_ioctl,
18431 	.d_open		= dtrace_open,
18432 	.d_name		= "dtrace",
18433 };
18434 
18435 static struct cdevsw helper_cdevsw = {
18436 	.d_version	= D_VERSION,
18437 	.d_ioctl	= dtrace_ioctl_helper,
18438 	.d_name		= "helper",
18439 };
18440 
18441 #include <dtrace_anon.c>
18442 #include <dtrace_ioctl.c>
18443 #include <dtrace_load.c>
18444 #include <dtrace_modevent.c>
18445 #include <dtrace_sysctl.c>
18446 #include <dtrace_unload.c>
18447 #include <dtrace_vtime.c>
18448 #include <dtrace_hacks.c>
18449 
18450 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18451 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18452 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18453 
18454 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18455 MODULE_VERSION(dtrace, 1);
18456 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18457 #endif
18458