xref: /freebsd-13-stable/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision f12a50fed2df3994b05d7c8702f06bb117c156d6)
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) + (uintptr_t)offset)) = (type)(what);
476 
477 #if !defined(__x86) && !defined(__aarch64__)
478 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
479 	if (addr & (size - 1)) {					\
480 		*flags |= CPU_DTRACE_BADALIGN;				\
481 		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
482 		return (0);						\
483 	}
484 #else
485 #define	DTRACE_ALIGNCHECK(addr, size, flags)
486 #endif
487 
488 /*
489  * Test whether a range of memory starting at testaddr of size testsz falls
490  * within the range of memory described by addr, sz.  We take care to avoid
491  * problems with overflow and underflow of the unsigned quantities, and
492  * disallow all negative sizes.  Ranges of size 0 are allowed.
493  */
494 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
495 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
496 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
497 	(testaddr) + (testsz) >= (testaddr))
498 
499 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
500 do {									\
501 	if ((remp) != NULL) {						\
502 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
503 	}								\
504 } while (0)
505 
506 
507 /*
508  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
509  * alloc_sz on the righthand side of the comparison in order to avoid overflow
510  * or underflow in the comparison with it.  This is simpler than the INRANGE
511  * check above, because we know that the dtms_scratch_ptr is valid in the
512  * range.  Allocations of size zero are allowed.
513  */
514 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
515 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
516 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
517 
518 #define DTRACE_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_reap(void);
598 static dtrace_state_t *dtrace_anon_grab(void);
599 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
600     dtrace_state_t *, uint64_t, uint64_t);
601 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
602 static void dtrace_buffer_drop(dtrace_buffer_t *);
603 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
604 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
605     dtrace_state_t *, dtrace_mstate_t *);
606 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
607     dtrace_optval_t);
608 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
609 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
610 uint16_t dtrace_load16(uintptr_t);
611 uint32_t dtrace_load32(uintptr_t);
612 uint64_t dtrace_load64(uintptr_t);
613 uint8_t dtrace_load8(uintptr_t);
614 void dtrace_dynvar_clean(dtrace_dstate_t *);
615 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
616     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
617 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
618 static int dtrace_priv_proc(dtrace_state_t *);
619 static void dtrace_getf_barrier(void);
620 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
621     dtrace_mstate_t *, dtrace_vstate_t *);
622 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
623     dtrace_mstate_t *, dtrace_vstate_t *);
624 
625 /*
626  * DTrace Probe Context Functions
627  *
628  * These functions are called from probe context.  Because probe context is
629  * any context in which C may be called, arbitrarily locks may be held,
630  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
631  * As a result, functions called from probe context may only call other DTrace
632  * support functions -- they may not interact at all with the system at large.
633  * (Note that the ASSERT macro is made probe-context safe by redefining it in
634  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
635  * loads are to be performed from probe context, they _must_ be in terms of
636  * the safe dtrace_load*() variants.
637  *
638  * Some functions in this block are not actually called from probe context;
639  * for these functions, there will be a comment above the function reading
640  * "Note:  not called from probe context."
641  */
642 void
dtrace_panic(const char * format,...)643 dtrace_panic(const char *format, ...)
644 {
645 	va_list alist;
646 
647 	va_start(alist, format);
648 #ifdef __FreeBSD__
649 	vpanic(format, alist);
650 #else
651 	dtrace_vpanic(format, alist);
652 #endif
653 	va_end(alist);
654 }
655 
656 int
dtrace_assfail(const char * a,const char * f,int l)657 dtrace_assfail(const char *a, const char *f, int l)
658 {
659 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
660 
661 	/*
662 	 * We just need something here that even the most clever compiler
663 	 * cannot optimize away.
664 	 */
665 	return (a[(uintptr_t)f]);
666 }
667 
668 /*
669  * Atomically increment a specified error counter from probe context.
670  */
671 static void
dtrace_error(uint32_t * counter)672 dtrace_error(uint32_t *counter)
673 {
674 	/*
675 	 * Most counters stored to in probe context are per-CPU counters.
676 	 * However, there are some error conditions that are sufficiently
677 	 * arcane that they don't merit per-CPU storage.  If these counters
678 	 * are incremented concurrently on different CPUs, scalability will be
679 	 * adversely affected -- but we don't expect them to be white-hot in a
680 	 * correctly constructed enabling...
681 	 */
682 	uint32_t oval, nval;
683 
684 	do {
685 		oval = *counter;
686 
687 		if ((nval = oval + 1) == 0) {
688 			/*
689 			 * If the counter would wrap, set it to 1 -- assuring
690 			 * that the counter is never zero when we have seen
691 			 * errors.  (The counter must be 32-bits because we
692 			 * aren't guaranteed a 64-bit compare&swap operation.)
693 			 * To save this code both the infamy of being fingered
694 			 * by a priggish news story and the indignity of being
695 			 * the target of a neo-puritan witch trial, we're
696 			 * carefully avoiding any colorful description of the
697 			 * likelihood of this condition -- but suffice it to
698 			 * say that it is only slightly more likely than the
699 			 * overflow of predicate cache IDs, as discussed in
700 			 * dtrace_predicate_create().
701 			 */
702 			nval = 1;
703 		}
704 	} while (dtrace_cas32(counter, oval, nval) != oval);
705 }
706 
707 /*
708  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
709  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
710  */
711 /* BEGIN CSTYLED */
712 DTRACE_LOADFUNC(8)
713 DTRACE_LOADFUNC(16)
714 DTRACE_LOADFUNC(32)
715 DTRACE_LOADFUNC(64)
716 /* END CSTYLED */
717 
718 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)719 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
720 {
721 	if (dest < mstate->dtms_scratch_base)
722 		return (0);
723 
724 	if (dest + size < dest)
725 		return (0);
726 
727 	if (dest + size > mstate->dtms_scratch_ptr)
728 		return (0);
729 
730 	return (1);
731 }
732 
733 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)734 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
735     dtrace_statvar_t **svars, int nsvars)
736 {
737 	int i;
738 	size_t maxglobalsize, maxlocalsize;
739 
740 	if (nsvars == 0)
741 		return (0);
742 
743 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
744 	maxlocalsize = maxglobalsize * NCPU;
745 
746 	for (i = 0; i < nsvars; i++) {
747 		dtrace_statvar_t *svar = svars[i];
748 		uint8_t scope;
749 		size_t size;
750 
751 		if (svar == NULL || (size = svar->dtsv_size) == 0)
752 			continue;
753 
754 		scope = svar->dtsv_var.dtdv_scope;
755 
756 		/*
757 		 * We verify that our size is valid in the spirit of providing
758 		 * defense in depth:  we want to prevent attackers from using
759 		 * DTrace to escalate an orthogonal kernel heap corruption bug
760 		 * into the ability to store to arbitrary locations in memory.
761 		 */
762 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
763 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
764 
765 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
766 		    svar->dtsv_size)) {
767 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
768 			    svar->dtsv_size);
769 			return (1);
770 		}
771 	}
772 
773 	return (0);
774 }
775 
776 /*
777  * Check to see if the address is within a memory region to which a store may
778  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
779  * region.  The caller of dtrace_canstore() is responsible for performing any
780  * alignment checks that are needed before stores are actually executed.
781  */
782 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)783 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
784     dtrace_vstate_t *vstate)
785 {
786 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
787 }
788 
789 /*
790  * Implementation of dtrace_canstore which communicates the upper bound of the
791  * allowed memory region.
792  */
793 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)794 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
795     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
796 {
797 	/*
798 	 * First, check to see if the address is in scratch space...
799 	 */
800 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
801 	    mstate->dtms_scratch_size)) {
802 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
803 		    mstate->dtms_scratch_size);
804 		return (1);
805 	}
806 
807 	/*
808 	 * Now check to see if it's a dynamic variable.  This check will pick
809 	 * up both thread-local variables and any global dynamically-allocated
810 	 * variables.
811 	 */
812 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
813 	    vstate->dtvs_dynvars.dtds_size)) {
814 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
815 		uintptr_t base = (uintptr_t)dstate->dtds_base +
816 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
817 		uintptr_t chunkoffs;
818 		dtrace_dynvar_t *dvar;
819 
820 		/*
821 		 * Before we assume that we can store here, we need to make
822 		 * sure that it isn't in our metadata -- storing to our
823 		 * dynamic variable metadata would corrupt our state.  For
824 		 * the range to not include any dynamic variable metadata,
825 		 * it must:
826 		 *
827 		 *	(1) Start above the hash table that is at the base of
828 		 *	the dynamic variable space
829 		 *
830 		 *	(2) Have a starting chunk offset that is beyond the
831 		 *	dtrace_dynvar_t that is at the base of every chunk
832 		 *
833 		 *	(3) Not span a chunk boundary
834 		 *
835 		 *	(4) Not be in the tuple space of a dynamic variable
836 		 *
837 		 */
838 		if (addr < base)
839 			return (0);
840 
841 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
842 
843 		if (chunkoffs < sizeof (dtrace_dynvar_t))
844 			return (0);
845 
846 		if (chunkoffs + sz > dstate->dtds_chunksize)
847 			return (0);
848 
849 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
850 
851 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
852 			return (0);
853 
854 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
855 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
856 			return (0);
857 
858 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
859 		return (1);
860 	}
861 
862 	/*
863 	 * Finally, check the static local and global variables.  These checks
864 	 * take the longest, so we perform them last.
865 	 */
866 	if (dtrace_canstore_statvar(addr, sz, remain,
867 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
868 		return (1);
869 
870 	if (dtrace_canstore_statvar(addr, sz, remain,
871 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
872 		return (1);
873 
874 	return (0);
875 }
876 
877 
878 /*
879  * Convenience routine to check to see if the address is within a memory
880  * region in which a load may be issued given the user's privilege level;
881  * if not, it sets the appropriate error flags and loads 'addr' into the
882  * illegal value slot.
883  *
884  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
885  * appropriate memory access protection.
886  */
887 static int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)888 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
889     dtrace_vstate_t *vstate)
890 {
891 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
892 }
893 
894 /*
895  * Implementation of dtrace_canload which communicates the uppoer bound of the
896  * allowed memory region.
897  */
898 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)899 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
900     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
901 {
902 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
903 	file_t *fp;
904 
905 	/*
906 	 * If we hold the privilege to read from kernel memory, then
907 	 * everything is readable.
908 	 */
909 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
910 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
911 		return (1);
912 	}
913 
914 	/*
915 	 * You can obviously read that which you can store.
916 	 */
917 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
918 		return (1);
919 
920 	/*
921 	 * We're allowed to read from our own string table.
922 	 */
923 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
924 	    mstate->dtms_difo->dtdo_strlen)) {
925 		DTRACE_RANGE_REMAIN(remain, addr,
926 		    mstate->dtms_difo->dtdo_strtab,
927 		    mstate->dtms_difo->dtdo_strlen);
928 		return (1);
929 	}
930 
931 	if (vstate->dtvs_state != NULL &&
932 	    dtrace_priv_proc(vstate->dtvs_state)) {
933 		proc_t *p;
934 
935 		/*
936 		 * When we have privileges to the current process, there are
937 		 * several context-related kernel structures that are safe to
938 		 * read, even absent the privilege to read from kernel memory.
939 		 * These reads are safe because these structures contain only
940 		 * state that (1) we're permitted to read, (2) is harmless or
941 		 * (3) contains pointers to additional kernel state that we're
942 		 * not permitted to read (and as such, do not present an
943 		 * opportunity for privilege escalation).  Finally (and
944 		 * critically), because of the nature of their relation with
945 		 * the current thread context, the memory associated with these
946 		 * structures cannot change over the duration of probe context,
947 		 * and it is therefore impossible for this memory to be
948 		 * deallocated and reallocated as something else while it's
949 		 * being operated upon.
950 		 */
951 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
952 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
953 			    sizeof (kthread_t));
954 			return (1);
955 		}
956 
957 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
958 		    sz, curthread->t_procp, sizeof (proc_t))) {
959 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
960 			    sizeof (proc_t));
961 			return (1);
962 		}
963 
964 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
965 		    curthread->t_cred, sizeof (cred_t))) {
966 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
967 			    sizeof (cred_t));
968 			return (1);
969 		}
970 
971 #ifdef illumos
972 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
973 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
974 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
975 			    sizeof (pid_t));
976 			return (1);
977 		}
978 
979 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
980 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
981 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
982 			    offsetof(cpu_t, cpu_pause_thread));
983 			return (1);
984 		}
985 #endif
986 	}
987 
988 	if ((fp = mstate->dtms_getf) != NULL) {
989 		uintptr_t psz = sizeof (void *);
990 		vnode_t *vp;
991 		vnodeops_t *op;
992 
993 		/*
994 		 * When getf() returns a file_t, the enabling is implicitly
995 		 * granted the (transient) right to read the returned file_t
996 		 * as well as the v_path and v_op->vnop_name of the underlying
997 		 * vnode.  These accesses are allowed after a successful
998 		 * getf() because the members that they refer to cannot change
999 		 * once set -- and the barrier logic in the kernel's closef()
1000 		 * path assures that the file_t and its referenced vode_t
1001 		 * cannot themselves be stale (that is, it impossible for
1002 		 * either dtms_getf itself or its f_vnode member to reference
1003 		 * freed memory).
1004 		 */
1005 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1006 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1007 			return (1);
1008 		}
1009 
1010 		if ((vp = fp->f_vnode) != NULL) {
1011 			size_t slen;
1012 #ifdef illumos
1013 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1014 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1015 				    psz);
1016 				return (1);
1017 			}
1018 			slen = strlen(vp->v_path) + 1;
1019 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1020 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1021 				    slen);
1022 				return (1);
1023 			}
1024 #endif
1025 
1026 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1027 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1028 				    psz);
1029 				return (1);
1030 			}
1031 
1032 #ifdef illumos
1033 			if ((op = vp->v_op) != NULL &&
1034 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1035 				DTRACE_RANGE_REMAIN(remain, addr,
1036 				    &op->vnop_name, psz);
1037 				return (1);
1038 			}
1039 
1040 			if (op != NULL && op->vnop_name != NULL &&
1041 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
1042 			    (slen = strlen(op->vnop_name) + 1))) {
1043 				DTRACE_RANGE_REMAIN(remain, addr,
1044 				    op->vnop_name, slen);
1045 				return (1);
1046 			}
1047 #endif
1048 		}
1049 	}
1050 
1051 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1052 	*illval = addr;
1053 	return (0);
1054 }
1055 
1056 /*
1057  * Convenience routine to check to see if a given string is within a memory
1058  * region in which a load may be issued given the user's privilege level;
1059  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1060  * calls in the event that the user has all privileges.
1061  */
1062 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1063 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1064     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1065 {
1066 	size_t rsize;
1067 
1068 	/*
1069 	 * If we hold the privilege to read from kernel memory, then
1070 	 * everything is readable.
1071 	 */
1072 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1073 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1074 		return (1);
1075 	}
1076 
1077 	/*
1078 	 * Even if the caller is uninterested in querying the remaining valid
1079 	 * range, it is required to ensure that the access is allowed.
1080 	 */
1081 	if (remain == NULL) {
1082 		remain = &rsize;
1083 	}
1084 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1085 		size_t strsz;
1086 		/*
1087 		 * Perform the strlen after determining the length of the
1088 		 * memory region which is accessible.  This prevents timing
1089 		 * information from being used to find NULs in memory which is
1090 		 * not accessible to the caller.
1091 		 */
1092 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1093 		    MIN(sz, *remain));
1094 		if (strsz <= *remain) {
1095 			return (1);
1096 		}
1097 	}
1098 
1099 	return (0);
1100 }
1101 
1102 /*
1103  * Convenience routine to check to see if a given variable is within a memory
1104  * region in which a load may be issued given the user's privilege level.
1105  */
1106 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1107 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1108     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1109 {
1110 	size_t sz;
1111 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1112 
1113 	/*
1114 	 * Calculate the max size before performing any checks since even
1115 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1116 	 * return the max length via 'remain'.
1117 	 */
1118 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1119 		dtrace_state_t *state = vstate->dtvs_state;
1120 
1121 		if (state != NULL) {
1122 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1123 		} else {
1124 			/*
1125 			 * In helper context, we have a NULL state; fall back
1126 			 * to using the system-wide default for the string size
1127 			 * in this case.
1128 			 */
1129 			sz = dtrace_strsize_default;
1130 		}
1131 	} else {
1132 		sz = type->dtdt_size;
1133 	}
1134 
1135 	/*
1136 	 * If we hold the privilege to read from kernel memory, then
1137 	 * everything is readable.
1138 	 */
1139 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1140 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1141 		return (1);
1142 	}
1143 
1144 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1145 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1146 		    vstate));
1147 	}
1148 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1149 	    vstate));
1150 }
1151 
1152 /*
1153  * Convert a string to a signed integer using safe loads.
1154  *
1155  * NOTE: This function uses various macros from strtolctype.h to manipulate
1156  * digit values, etc -- these have all been checked to ensure they make
1157  * no additional function calls.
1158  */
1159 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1160 dtrace_strtoll(char *input, int base, size_t limit)
1161 {
1162 	uintptr_t pos = (uintptr_t)input;
1163 	int64_t val = 0;
1164 	int x;
1165 	boolean_t neg = B_FALSE;
1166 	char c, cc, ccc;
1167 	uintptr_t end = pos + limit;
1168 
1169 	/*
1170 	 * Consume any whitespace preceding digits.
1171 	 */
1172 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1173 		pos++;
1174 
1175 	/*
1176 	 * Handle an explicit sign if one is present.
1177 	 */
1178 	if (c == '-' || c == '+') {
1179 		if (c == '-')
1180 			neg = B_TRUE;
1181 		c = dtrace_load8(++pos);
1182 	}
1183 
1184 	/*
1185 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1186 	 * if present.
1187 	 */
1188 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1189 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1190 		pos += 2;
1191 		c = ccc;
1192 	}
1193 
1194 	/*
1195 	 * Read in contiguous digits until the first non-digit character.
1196 	 */
1197 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1198 	    c = dtrace_load8(++pos))
1199 		val = val * base + x;
1200 
1201 	return (neg ? -val : val);
1202 }
1203 
1204 /*
1205  * Compare two strings using safe loads.
1206  */
1207 static int
dtrace_strncmp(char * s1,char * s2,size_t limit)1208 dtrace_strncmp(char *s1, char *s2, size_t limit)
1209 {
1210 	uint8_t c1, c2;
1211 	volatile uint16_t *flags;
1212 
1213 	if (s1 == s2 || limit == 0)
1214 		return (0);
1215 
1216 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1217 
1218 	do {
1219 		if (s1 == NULL) {
1220 			c1 = '\0';
1221 		} else {
1222 			c1 = dtrace_load8((uintptr_t)s1++);
1223 		}
1224 
1225 		if (s2 == NULL) {
1226 			c2 = '\0';
1227 		} else {
1228 			c2 = dtrace_load8((uintptr_t)s2++);
1229 		}
1230 
1231 		if (c1 != c2)
1232 			return (c1 - c2);
1233 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1234 
1235 	return (0);
1236 }
1237 
1238 /*
1239  * Compute strlen(s) for a string using safe memory accesses.  The additional
1240  * len parameter is used to specify a maximum length to ensure completion.
1241  */
1242 static size_t
dtrace_strlen(const char * s,size_t lim)1243 dtrace_strlen(const char *s, size_t lim)
1244 {
1245 	uint_t len;
1246 
1247 	for (len = 0; len != lim; len++) {
1248 		if (dtrace_load8((uintptr_t)s++) == '\0')
1249 			break;
1250 	}
1251 
1252 	return (len);
1253 }
1254 
1255 /*
1256  * Check if an address falls within a toxic region.
1257  */
1258 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1259 dtrace_istoxic(uintptr_t kaddr, size_t size)
1260 {
1261 	uintptr_t taddr, tsize;
1262 	int i;
1263 
1264 	for (i = 0; i < dtrace_toxranges; i++) {
1265 		taddr = dtrace_toxrange[i].dtt_base;
1266 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1267 
1268 		if (kaddr - taddr < tsize) {
1269 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1270 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1271 			return (1);
1272 		}
1273 
1274 		if (taddr - kaddr < size) {
1275 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1276 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1277 			return (1);
1278 		}
1279 	}
1280 
1281 	return (0);
1282 }
1283 
1284 /*
1285  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1286  * memory specified by the DIF program.  The dst is assumed to be safe memory
1287  * that we can store to directly because it is managed by DTrace.  As with
1288  * standard bcopy, overlapping copies are handled properly.
1289  */
1290 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1291 dtrace_bcopy(const void *src, void *dst, size_t len)
1292 {
1293 	if (len != 0) {
1294 		uint8_t *s1 = dst;
1295 		const uint8_t *s2 = src;
1296 
1297 		if (s1 <= s2) {
1298 			do {
1299 				*s1++ = dtrace_load8((uintptr_t)s2++);
1300 			} while (--len != 0);
1301 		} else {
1302 			s2 += len;
1303 			s1 += len;
1304 
1305 			do {
1306 				*--s1 = dtrace_load8((uintptr_t)--s2);
1307 			} while (--len != 0);
1308 		}
1309 	}
1310 }
1311 
1312 /*
1313  * Copy src to dst using safe memory accesses, up to either the specified
1314  * length, or the point that a nul byte is encountered.  The src is assumed to
1315  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1316  * safe memory that we can store to directly because it is managed by DTrace.
1317  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1318  */
1319 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1320 dtrace_strcpy(const void *src, void *dst, size_t len)
1321 {
1322 	if (len != 0) {
1323 		uint8_t *s1 = dst, c;
1324 		const uint8_t *s2 = src;
1325 
1326 		do {
1327 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1328 		} while (--len != 0 && c != '\0');
1329 	}
1330 }
1331 
1332 /*
1333  * Copy src to dst, deriving the size and type from the specified (BYREF)
1334  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1335  * program.  The dst is assumed to be DTrace variable memory that is of the
1336  * specified type; we assume that we can store to directly.
1337  */
1338 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1339 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1340 {
1341 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1342 
1343 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1344 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1345 	} else {
1346 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1347 	}
1348 }
1349 
1350 /*
1351  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1352  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1353  * safe memory that we can access directly because it is managed by DTrace.
1354  */
1355 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1356 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1357 {
1358 	volatile uint16_t *flags;
1359 
1360 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1361 
1362 	if (s1 == s2)
1363 		return (0);
1364 
1365 	if (s1 == NULL || s2 == NULL)
1366 		return (1);
1367 
1368 	if (s1 != s2 && len != 0) {
1369 		const uint8_t *ps1 = s1;
1370 		const uint8_t *ps2 = s2;
1371 
1372 		do {
1373 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1374 				return (1);
1375 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1376 	}
1377 	return (0);
1378 }
1379 
1380 /*
1381  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1382  * is for safe DTrace-managed memory only.
1383  */
1384 static void
dtrace_bzero(void * dst,size_t len)1385 dtrace_bzero(void *dst, size_t len)
1386 {
1387 	uchar_t *cp;
1388 
1389 	for (cp = dst; len != 0; len--)
1390 		*cp++ = 0;
1391 }
1392 
1393 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1394 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1395 {
1396 	uint64_t result[2];
1397 
1398 	result[0] = addend1[0] + addend2[0];
1399 	result[1] = addend1[1] + addend2[1] +
1400 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1401 
1402 	sum[0] = result[0];
1403 	sum[1] = result[1];
1404 }
1405 
1406 /*
1407  * Shift the 128-bit value in a by b. If b is positive, shift left.
1408  * If b is negative, shift right.
1409  */
1410 static void
dtrace_shift_128(uint64_t * a,int b)1411 dtrace_shift_128(uint64_t *a, int b)
1412 {
1413 	uint64_t mask;
1414 
1415 	if (b == 0)
1416 		return;
1417 
1418 	if (b < 0) {
1419 		b = -b;
1420 		if (b >= 64) {
1421 			a[0] = a[1] >> (b - 64);
1422 			a[1] = 0;
1423 		} else {
1424 			a[0] >>= b;
1425 			mask = 1LL << (64 - b);
1426 			mask -= 1;
1427 			a[0] |= ((a[1] & mask) << (64 - b));
1428 			a[1] >>= b;
1429 		}
1430 	} else {
1431 		if (b >= 64) {
1432 			a[1] = a[0] << (b - 64);
1433 			a[0] = 0;
1434 		} else {
1435 			a[1] <<= b;
1436 			mask = a[0] >> (64 - b);
1437 			a[1] |= mask;
1438 			a[0] <<= b;
1439 		}
1440 	}
1441 }
1442 
1443 /*
1444  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1445  * use native multiplication on those, and then re-combine into the
1446  * resulting 128-bit value.
1447  *
1448  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1449  *     hi1 * hi2 << 64 +
1450  *     hi1 * lo2 << 32 +
1451  *     hi2 * lo1 << 32 +
1452  *     lo1 * lo2
1453  */
1454 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1455 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1456 {
1457 	uint64_t hi1, hi2, lo1, lo2;
1458 	uint64_t tmp[2];
1459 
1460 	hi1 = factor1 >> 32;
1461 	hi2 = factor2 >> 32;
1462 
1463 	lo1 = factor1 & DT_MASK_LO;
1464 	lo2 = factor2 & DT_MASK_LO;
1465 
1466 	product[0] = lo1 * lo2;
1467 	product[1] = hi1 * hi2;
1468 
1469 	tmp[0] = hi1 * lo2;
1470 	tmp[1] = 0;
1471 	dtrace_shift_128(tmp, 32);
1472 	dtrace_add_128(product, tmp, product);
1473 
1474 	tmp[0] = hi2 * lo1;
1475 	tmp[1] = 0;
1476 	dtrace_shift_128(tmp, 32);
1477 	dtrace_add_128(product, tmp, product);
1478 }
1479 
1480 /*
1481  * This privilege check should be used by actions and subroutines to
1482  * verify that the user credentials of the process that enabled the
1483  * invoking ECB match the target credentials
1484  */
1485 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1486 dtrace_priv_proc_common_user(dtrace_state_t *state)
1487 {
1488 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1489 
1490 	/*
1491 	 * We should always have a non-NULL state cred here, since if cred
1492 	 * is null (anonymous tracing), we fast-path bypass this routine.
1493 	 */
1494 	ASSERT(s_cr != NULL);
1495 
1496 	if ((cr = CRED()) != NULL &&
1497 	    s_cr->cr_uid == cr->cr_uid &&
1498 	    s_cr->cr_uid == cr->cr_ruid &&
1499 	    s_cr->cr_uid == cr->cr_suid &&
1500 	    s_cr->cr_gid == cr->cr_gid &&
1501 	    s_cr->cr_gid == cr->cr_rgid &&
1502 	    s_cr->cr_gid == cr->cr_sgid)
1503 		return (1);
1504 
1505 	return (0);
1506 }
1507 
1508 /*
1509  * This privilege check should be used by actions and subroutines to
1510  * verify that the zone of the process that enabled the invoking ECB
1511  * matches the target credentials
1512  */
1513 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1514 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1515 {
1516 #ifdef illumos
1517 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1518 
1519 	/*
1520 	 * We should always have a non-NULL state cred here, since if cred
1521 	 * is null (anonymous tracing), we fast-path bypass this routine.
1522 	 */
1523 	ASSERT(s_cr != NULL);
1524 
1525 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1526 		return (1);
1527 
1528 	return (0);
1529 #else
1530 	return (1);
1531 #endif
1532 }
1533 
1534 /*
1535  * This privilege check should be used by actions and subroutines to
1536  * verify that the process has not setuid or changed credentials.
1537  */
1538 static int
dtrace_priv_proc_common_nocd(void)1539 dtrace_priv_proc_common_nocd(void)
1540 {
1541 	proc_t *proc;
1542 
1543 	if ((proc = ttoproc(curthread)) != NULL &&
1544 	    !(proc->p_flag & SNOCD))
1545 		return (1);
1546 
1547 	return (0);
1548 }
1549 
1550 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1551 dtrace_priv_proc_destructive(dtrace_state_t *state)
1552 {
1553 	int action = state->dts_cred.dcr_action;
1554 
1555 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1556 	    dtrace_priv_proc_common_zone(state) == 0)
1557 		goto bad;
1558 
1559 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1560 	    dtrace_priv_proc_common_user(state) == 0)
1561 		goto bad;
1562 
1563 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1564 	    dtrace_priv_proc_common_nocd() == 0)
1565 		goto bad;
1566 
1567 	return (1);
1568 
1569 bad:
1570 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1571 
1572 	return (0);
1573 }
1574 
1575 static int
dtrace_priv_proc_control(dtrace_state_t * state)1576 dtrace_priv_proc_control(dtrace_state_t *state)
1577 {
1578 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1579 		return (1);
1580 
1581 	if (dtrace_priv_proc_common_zone(state) &&
1582 	    dtrace_priv_proc_common_user(state) &&
1583 	    dtrace_priv_proc_common_nocd())
1584 		return (1);
1585 
1586 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1587 
1588 	return (0);
1589 }
1590 
1591 static int
dtrace_priv_proc(dtrace_state_t * state)1592 dtrace_priv_proc(dtrace_state_t *state)
1593 {
1594 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1595 		return (1);
1596 
1597 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1598 
1599 	return (0);
1600 }
1601 
1602 static int
dtrace_priv_kernel(dtrace_state_t * state)1603 dtrace_priv_kernel(dtrace_state_t *state)
1604 {
1605 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1606 		return (1);
1607 
1608 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1609 
1610 	return (0);
1611 }
1612 
1613 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1614 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1615 {
1616 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1617 		return (1);
1618 
1619 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1620 
1621 	return (0);
1622 }
1623 
1624 /*
1625  * Determine if the dte_cond of the specified ECB allows for processing of
1626  * the current probe to continue.  Note that this routine may allow continued
1627  * processing, but with access(es) stripped from the mstate's dtms_access
1628  * field.
1629  */
1630 static int
dtrace_priv_probe(dtrace_state_t * state,dtrace_mstate_t * mstate,dtrace_ecb_t * ecb)1631 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1632     dtrace_ecb_t *ecb)
1633 {
1634 	dtrace_probe_t *probe = ecb->dte_probe;
1635 	dtrace_provider_t *prov = probe->dtpr_provider;
1636 	dtrace_pops_t *pops = &prov->dtpv_pops;
1637 	int mode = DTRACE_MODE_NOPRIV_DROP;
1638 
1639 	ASSERT(ecb->dte_cond);
1640 
1641 #ifdef illumos
1642 	if (pops->dtps_mode != NULL) {
1643 		mode = pops->dtps_mode(prov->dtpv_arg,
1644 		    probe->dtpr_id, probe->dtpr_arg);
1645 
1646 		ASSERT((mode & DTRACE_MODE_USER) ||
1647 		    (mode & DTRACE_MODE_KERNEL));
1648 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1649 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1650 	}
1651 
1652 	/*
1653 	 * If the dte_cond bits indicate that this consumer is only allowed to
1654 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1655 	 * entry point to check that the probe was fired while in a user
1656 	 * context.  If that's not the case, use the policy specified by the
1657 	 * provider to determine if we drop the probe or merely restrict
1658 	 * operation.
1659 	 */
1660 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1661 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1662 
1663 		if (!(mode & DTRACE_MODE_USER)) {
1664 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1665 				return (0);
1666 
1667 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1668 		}
1669 	}
1670 #endif
1671 
1672 	/*
1673 	 * This is more subtle than it looks. We have to be absolutely certain
1674 	 * that CRED() isn't going to change out from under us so it's only
1675 	 * legit to examine that structure if we're in constrained situations.
1676 	 * Currently, the only times we'll this check is if a non-super-user
1677 	 * has enabled the profile or syscall providers -- providers that
1678 	 * allow visibility of all processes. For the profile case, the check
1679 	 * above will ensure that we're examining a user context.
1680 	 */
1681 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1682 		cred_t *cr;
1683 		cred_t *s_cr = state->dts_cred.dcr_cred;
1684 		proc_t *proc;
1685 
1686 		ASSERT(s_cr != NULL);
1687 
1688 		if ((cr = CRED()) == NULL ||
1689 		    s_cr->cr_uid != cr->cr_uid ||
1690 		    s_cr->cr_uid != cr->cr_ruid ||
1691 		    s_cr->cr_uid != cr->cr_suid ||
1692 		    s_cr->cr_gid != cr->cr_gid ||
1693 		    s_cr->cr_gid != cr->cr_rgid ||
1694 		    s_cr->cr_gid != cr->cr_sgid ||
1695 		    (proc = ttoproc(curthread)) == NULL ||
1696 		    (proc->p_flag & SNOCD)) {
1697 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1698 				return (0);
1699 
1700 #ifdef illumos
1701 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1702 #endif
1703 		}
1704 	}
1705 
1706 #ifdef illumos
1707 	/*
1708 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1709 	 * in our zone, check to see if our mode policy is to restrict rather
1710 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1711 	 * and DTRACE_ACCESS_ARGS
1712 	 */
1713 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1714 		cred_t *cr;
1715 		cred_t *s_cr = state->dts_cred.dcr_cred;
1716 
1717 		ASSERT(s_cr != NULL);
1718 
1719 		if ((cr = CRED()) == NULL ||
1720 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1721 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1722 				return (0);
1723 
1724 			mstate->dtms_access &=
1725 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1726 		}
1727 	}
1728 #endif
1729 
1730 	return (1);
1731 }
1732 
1733 /*
1734  * Note:  not called from probe context.  This function is called
1735  * asynchronously (and at a regular interval) from outside of probe context to
1736  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1737  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1738  */
1739 void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1740 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1741 {
1742 	dtrace_dynvar_t *dirty;
1743 	dtrace_dstate_percpu_t *dcpu;
1744 	dtrace_dynvar_t **rinsep;
1745 	int i, j, work = 0;
1746 
1747 	for (i = 0; i < NCPU; i++) {
1748 		dcpu = &dstate->dtds_percpu[i];
1749 		rinsep = &dcpu->dtdsc_rinsing;
1750 
1751 		/*
1752 		 * If the dirty list is NULL, there is no dirty work to do.
1753 		 */
1754 		if (dcpu->dtdsc_dirty == NULL)
1755 			continue;
1756 
1757 		if (dcpu->dtdsc_rinsing != NULL) {
1758 			/*
1759 			 * If the rinsing list is non-NULL, then it is because
1760 			 * this CPU was selected to accept another CPU's
1761 			 * dirty list -- and since that time, dirty buffers
1762 			 * have accumulated.  This is a highly unlikely
1763 			 * condition, but we choose to ignore the dirty
1764 			 * buffers -- they'll be picked up a future cleanse.
1765 			 */
1766 			continue;
1767 		}
1768 
1769 		if (dcpu->dtdsc_clean != NULL) {
1770 			/*
1771 			 * If the clean list is non-NULL, then we're in a
1772 			 * situation where a CPU has done deallocations (we
1773 			 * have a non-NULL dirty list) but no allocations (we
1774 			 * also have a non-NULL clean list).  We can't simply
1775 			 * move the dirty list into the clean list on this
1776 			 * CPU, yet we also don't want to allow this condition
1777 			 * to persist, lest a short clean list prevent a
1778 			 * massive dirty list from being cleaned (which in
1779 			 * turn could lead to otherwise avoidable dynamic
1780 			 * drops).  To deal with this, we look for some CPU
1781 			 * with a NULL clean list, NULL dirty list, and NULL
1782 			 * rinsing list -- and then we borrow this CPU to
1783 			 * rinse our dirty list.
1784 			 */
1785 			for (j = 0; j < NCPU; j++) {
1786 				dtrace_dstate_percpu_t *rinser;
1787 
1788 				rinser = &dstate->dtds_percpu[j];
1789 
1790 				if (rinser->dtdsc_rinsing != NULL)
1791 					continue;
1792 
1793 				if (rinser->dtdsc_dirty != NULL)
1794 					continue;
1795 
1796 				if (rinser->dtdsc_clean != NULL)
1797 					continue;
1798 
1799 				rinsep = &rinser->dtdsc_rinsing;
1800 				break;
1801 			}
1802 
1803 			if (j == NCPU) {
1804 				/*
1805 				 * We were unable to find another CPU that
1806 				 * could accept this dirty list -- we are
1807 				 * therefore unable to clean it now.
1808 				 */
1809 				dtrace_dynvar_failclean++;
1810 				continue;
1811 			}
1812 		}
1813 
1814 		work = 1;
1815 
1816 		/*
1817 		 * Atomically move the dirty list aside.
1818 		 */
1819 		do {
1820 			dirty = dcpu->dtdsc_dirty;
1821 
1822 			/*
1823 			 * Before we zap the dirty list, set the rinsing list.
1824 			 * (This allows for a potential assertion in
1825 			 * dtrace_dynvar():  if a free dynamic variable appears
1826 			 * on a hash chain, either the dirty list or the
1827 			 * rinsing list for some CPU must be non-NULL.)
1828 			 */
1829 			*rinsep = dirty;
1830 			dtrace_membar_producer();
1831 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1832 		    dirty, NULL) != dirty);
1833 	}
1834 
1835 	if (!work) {
1836 		/*
1837 		 * We have no work to do; we can simply return.
1838 		 */
1839 		return;
1840 	}
1841 
1842 	dtrace_sync();
1843 
1844 	for (i = 0; i < NCPU; i++) {
1845 		dcpu = &dstate->dtds_percpu[i];
1846 
1847 		if (dcpu->dtdsc_rinsing == NULL)
1848 			continue;
1849 
1850 		/*
1851 		 * We are now guaranteed that no hash chain contains a pointer
1852 		 * into this dirty list; we can make it clean.
1853 		 */
1854 		ASSERT(dcpu->dtdsc_clean == NULL);
1855 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1856 		dcpu->dtdsc_rinsing = NULL;
1857 	}
1858 
1859 	/*
1860 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1861 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1862 	 * This prevents a race whereby a CPU incorrectly decides that
1863 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1864 	 * after dtrace_dynvar_clean() has completed.
1865 	 */
1866 	dtrace_sync();
1867 
1868 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1869 }
1870 
1871 /*
1872  * Depending on the value of the op parameter, this function looks-up,
1873  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1874  * allocation is requested, this function will return a pointer to a
1875  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1876  * variable can be allocated.  If NULL is returned, the appropriate counter
1877  * will be incremented.
1878  */
1879 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)1880 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1881     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1882     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1883 {
1884 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1885 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1886 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1887 	processorid_t me = curcpu, cpu = me;
1888 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1889 	size_t bucket, ksize;
1890 	size_t chunksize = dstate->dtds_chunksize;
1891 	uintptr_t kdata, lock, nstate;
1892 	uint_t i;
1893 
1894 	ASSERT(nkeys != 0);
1895 
1896 	/*
1897 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1898 	 * algorithm.  For the by-value portions, we perform the algorithm in
1899 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1900 	 * bit, and seems to have only a minute effect on distribution.  For
1901 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1902 	 * over each referenced byte.  It's painful to do this, but it's much
1903 	 * better than pathological hash distribution.  The efficacy of the
1904 	 * hashing algorithm (and a comparison with other algorithms) may be
1905 	 * found by running the ::dtrace_dynstat MDB dcmd.
1906 	 */
1907 	for (i = 0; i < nkeys; i++) {
1908 		if (key[i].dttk_size == 0) {
1909 			uint64_t val = key[i].dttk_value;
1910 
1911 			hashval += (val >> 48) & 0xffff;
1912 			hashval += (hashval << 10);
1913 			hashval ^= (hashval >> 6);
1914 
1915 			hashval += (val >> 32) & 0xffff;
1916 			hashval += (hashval << 10);
1917 			hashval ^= (hashval >> 6);
1918 
1919 			hashval += (val >> 16) & 0xffff;
1920 			hashval += (hashval << 10);
1921 			hashval ^= (hashval >> 6);
1922 
1923 			hashval += val & 0xffff;
1924 			hashval += (hashval << 10);
1925 			hashval ^= (hashval >> 6);
1926 		} else {
1927 			/*
1928 			 * This is incredibly painful, but it beats the hell
1929 			 * out of the alternative.
1930 			 */
1931 			uint64_t j, size = key[i].dttk_size;
1932 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1933 
1934 			if (!dtrace_canload(base, size, mstate, vstate))
1935 				break;
1936 
1937 			for (j = 0; j < size; j++) {
1938 				hashval += dtrace_load8(base + j);
1939 				hashval += (hashval << 10);
1940 				hashval ^= (hashval >> 6);
1941 			}
1942 		}
1943 	}
1944 
1945 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1946 		return (NULL);
1947 
1948 	hashval += (hashval << 3);
1949 	hashval ^= (hashval >> 11);
1950 	hashval += (hashval << 15);
1951 
1952 	/*
1953 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1954 	 * comes out to be one of our two sentinel hash values.  If this
1955 	 * actually happens, we set the hashval to be a value known to be a
1956 	 * non-sentinel value.
1957 	 */
1958 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1959 		hashval = DTRACE_DYNHASH_VALID;
1960 
1961 	/*
1962 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1963 	 * important here, tricks can be pulled to reduce it.  (However, it's
1964 	 * critical that hash collisions be kept to an absolute minimum;
1965 	 * they're much more painful than a divide.)  It's better to have a
1966 	 * solution that generates few collisions and still keeps things
1967 	 * relatively simple.
1968 	 */
1969 	bucket = hashval % dstate->dtds_hashsize;
1970 
1971 	if (op == DTRACE_DYNVAR_DEALLOC) {
1972 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1973 
1974 		for (;;) {
1975 			while ((lock = *lockp) & 1)
1976 				continue;
1977 
1978 			if (dtrace_casptr((volatile void *)lockp,
1979 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1980 				break;
1981 		}
1982 
1983 		dtrace_membar_producer();
1984 	}
1985 
1986 top:
1987 	prev = NULL;
1988 	lock = hash[bucket].dtdh_lock;
1989 
1990 	dtrace_membar_consumer();
1991 
1992 	start = hash[bucket].dtdh_chain;
1993 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1994 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1995 	    op != DTRACE_DYNVAR_DEALLOC));
1996 
1997 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1998 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1999 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
2000 
2001 		if (dvar->dtdv_hashval != hashval) {
2002 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
2003 				/*
2004 				 * We've reached the sink, and therefore the
2005 				 * end of the hash chain; we can kick out of
2006 				 * the loop knowing that we have seen a valid
2007 				 * snapshot of state.
2008 				 */
2009 				ASSERT(dvar->dtdv_next == NULL);
2010 				ASSERT(dvar == &dtrace_dynhash_sink);
2011 				break;
2012 			}
2013 
2014 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2015 				/*
2016 				 * We've gone off the rails:  somewhere along
2017 				 * the line, one of the members of this hash
2018 				 * chain was deleted.  Note that we could also
2019 				 * detect this by simply letting this loop run
2020 				 * to completion, as we would eventually hit
2021 				 * the end of the dirty list.  However, we
2022 				 * want to avoid running the length of the
2023 				 * dirty list unnecessarily (it might be quite
2024 				 * long), so we catch this as early as
2025 				 * possible by detecting the hash marker.  In
2026 				 * this case, we simply set dvar to NULL and
2027 				 * break; the conditional after the loop will
2028 				 * send us back to top.
2029 				 */
2030 				dvar = NULL;
2031 				break;
2032 			}
2033 
2034 			goto next;
2035 		}
2036 
2037 		if (dtuple->dtt_nkeys != nkeys)
2038 			goto next;
2039 
2040 		for (i = 0; i < nkeys; i++, dkey++) {
2041 			if (dkey->dttk_size != key[i].dttk_size)
2042 				goto next; /* size or type mismatch */
2043 
2044 			if (dkey->dttk_size != 0) {
2045 				if (dtrace_bcmp(
2046 				    (void *)(uintptr_t)key[i].dttk_value,
2047 				    (void *)(uintptr_t)dkey->dttk_value,
2048 				    dkey->dttk_size))
2049 					goto next;
2050 			} else {
2051 				if (dkey->dttk_value != key[i].dttk_value)
2052 					goto next;
2053 			}
2054 		}
2055 
2056 		if (op != DTRACE_DYNVAR_DEALLOC)
2057 			return (dvar);
2058 
2059 		ASSERT(dvar->dtdv_next == NULL ||
2060 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2061 
2062 		if (prev != NULL) {
2063 			ASSERT(hash[bucket].dtdh_chain != dvar);
2064 			ASSERT(start != dvar);
2065 			ASSERT(prev->dtdv_next == dvar);
2066 			prev->dtdv_next = dvar->dtdv_next;
2067 		} else {
2068 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2069 			    start, dvar->dtdv_next) != start) {
2070 				/*
2071 				 * We have failed to atomically swing the
2072 				 * hash table head pointer, presumably because
2073 				 * of a conflicting allocation on another CPU.
2074 				 * We need to reread the hash chain and try
2075 				 * again.
2076 				 */
2077 				goto top;
2078 			}
2079 		}
2080 
2081 		dtrace_membar_producer();
2082 
2083 		/*
2084 		 * Now set the hash value to indicate that it's free.
2085 		 */
2086 		ASSERT(hash[bucket].dtdh_chain != dvar);
2087 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2088 
2089 		dtrace_membar_producer();
2090 
2091 		/*
2092 		 * Set the next pointer to point at the dirty list, and
2093 		 * atomically swing the dirty pointer to the newly freed dvar.
2094 		 */
2095 		do {
2096 			next = dcpu->dtdsc_dirty;
2097 			dvar->dtdv_next = next;
2098 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2099 
2100 		/*
2101 		 * Finally, unlock this hash bucket.
2102 		 */
2103 		ASSERT(hash[bucket].dtdh_lock == lock);
2104 		ASSERT(lock & 1);
2105 		hash[bucket].dtdh_lock++;
2106 
2107 		return (NULL);
2108 next:
2109 		prev = dvar;
2110 		continue;
2111 	}
2112 
2113 	if (dvar == NULL) {
2114 		/*
2115 		 * If dvar is NULL, it is because we went off the rails:
2116 		 * one of the elements that we traversed in the hash chain
2117 		 * was deleted while we were traversing it.  In this case,
2118 		 * we assert that we aren't doing a dealloc (deallocs lock
2119 		 * the hash bucket to prevent themselves from racing with
2120 		 * one another), and retry the hash chain traversal.
2121 		 */
2122 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2123 		goto top;
2124 	}
2125 
2126 	if (op != DTRACE_DYNVAR_ALLOC) {
2127 		/*
2128 		 * If we are not to allocate a new variable, we want to
2129 		 * return NULL now.  Before we return, check that the value
2130 		 * of the lock word hasn't changed.  If it has, we may have
2131 		 * seen an inconsistent snapshot.
2132 		 */
2133 		if (op == DTRACE_DYNVAR_NOALLOC) {
2134 			if (hash[bucket].dtdh_lock != lock)
2135 				goto top;
2136 		} else {
2137 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2138 			ASSERT(hash[bucket].dtdh_lock == lock);
2139 			ASSERT(lock & 1);
2140 			hash[bucket].dtdh_lock++;
2141 		}
2142 
2143 		return (NULL);
2144 	}
2145 
2146 	/*
2147 	 * We need to allocate a new dynamic variable.  The size we need is the
2148 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2149 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2150 	 * the size of any referred-to data (dsize).  We then round the final
2151 	 * size up to the chunksize for allocation.
2152 	 */
2153 	for (ksize = 0, i = 0; i < nkeys; i++)
2154 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2155 
2156 	/*
2157 	 * This should be pretty much impossible, but could happen if, say,
2158 	 * strange DIF specified the tuple.  Ideally, this should be an
2159 	 * assertion and not an error condition -- but that requires that the
2160 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2161 	 * bullet-proof.  (That is, it must not be able to be fooled by
2162 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2163 	 * solving this would presumably not amount to solving the Halting
2164 	 * Problem -- but it still seems awfully hard.
2165 	 */
2166 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2167 	    ksize + dsize > chunksize) {
2168 		dcpu->dtdsc_drops++;
2169 		return (NULL);
2170 	}
2171 
2172 	nstate = DTRACE_DSTATE_EMPTY;
2173 
2174 	do {
2175 retry:
2176 		free = dcpu->dtdsc_free;
2177 
2178 		if (free == NULL) {
2179 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2180 			void *rval;
2181 
2182 			if (clean == NULL) {
2183 				/*
2184 				 * We're out of dynamic variable space on
2185 				 * this CPU.  Unless we have tried all CPUs,
2186 				 * we'll try to allocate from a different
2187 				 * CPU.
2188 				 */
2189 				switch (dstate->dtds_state) {
2190 				case DTRACE_DSTATE_CLEAN: {
2191 					void *sp = &dstate->dtds_state;
2192 
2193 					if (++cpu >= NCPU)
2194 						cpu = 0;
2195 
2196 					if (dcpu->dtdsc_dirty != NULL &&
2197 					    nstate == DTRACE_DSTATE_EMPTY)
2198 						nstate = DTRACE_DSTATE_DIRTY;
2199 
2200 					if (dcpu->dtdsc_rinsing != NULL)
2201 						nstate = DTRACE_DSTATE_RINSING;
2202 
2203 					dcpu = &dstate->dtds_percpu[cpu];
2204 
2205 					if (cpu != me)
2206 						goto retry;
2207 
2208 					(void) dtrace_cas32(sp,
2209 					    DTRACE_DSTATE_CLEAN, nstate);
2210 
2211 					/*
2212 					 * To increment the correct bean
2213 					 * counter, take another lap.
2214 					 */
2215 					goto retry;
2216 				}
2217 
2218 				case DTRACE_DSTATE_DIRTY:
2219 					dcpu->dtdsc_dirty_drops++;
2220 					break;
2221 
2222 				case DTRACE_DSTATE_RINSING:
2223 					dcpu->dtdsc_rinsing_drops++;
2224 					break;
2225 
2226 				case DTRACE_DSTATE_EMPTY:
2227 					dcpu->dtdsc_drops++;
2228 					break;
2229 				}
2230 
2231 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2232 				return (NULL);
2233 			}
2234 
2235 			/*
2236 			 * The clean list appears to be non-empty.  We want to
2237 			 * move the clean list to the free list; we start by
2238 			 * moving the clean pointer aside.
2239 			 */
2240 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2241 			    clean, NULL) != clean) {
2242 				/*
2243 				 * We are in one of two situations:
2244 				 *
2245 				 *  (a)	The clean list was switched to the
2246 				 *	free list by another CPU.
2247 				 *
2248 				 *  (b)	The clean list was added to by the
2249 				 *	cleansing cyclic.
2250 				 *
2251 				 * In either of these situations, we can
2252 				 * just reattempt the free list allocation.
2253 				 */
2254 				goto retry;
2255 			}
2256 
2257 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2258 
2259 			/*
2260 			 * Now we'll move the clean list to our free list.
2261 			 * It's impossible for this to fail:  the only way
2262 			 * the free list can be updated is through this
2263 			 * code path, and only one CPU can own the clean list.
2264 			 * Thus, it would only be possible for this to fail if
2265 			 * this code were racing with dtrace_dynvar_clean().
2266 			 * (That is, if dtrace_dynvar_clean() updated the clean
2267 			 * list, and we ended up racing to update the free
2268 			 * list.)  This race is prevented by the dtrace_sync()
2269 			 * in dtrace_dynvar_clean() -- which flushes the
2270 			 * owners of the clean lists out before resetting
2271 			 * the clean lists.
2272 			 */
2273 			dcpu = &dstate->dtds_percpu[me];
2274 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2275 			ASSERT(rval == NULL);
2276 			goto retry;
2277 		}
2278 
2279 		dvar = free;
2280 		new_free = dvar->dtdv_next;
2281 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2282 
2283 	/*
2284 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2285 	 * tuple array and copy any referenced key data into the data space
2286 	 * following the tuple array.  As we do this, we relocate dttk_value
2287 	 * in the final tuple to point to the key data address in the chunk.
2288 	 */
2289 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2290 	dvar->dtdv_data = (void *)(kdata + ksize);
2291 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2292 
2293 	for (i = 0; i < nkeys; i++) {
2294 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2295 		size_t kesize = key[i].dttk_size;
2296 
2297 		if (kesize != 0) {
2298 			dtrace_bcopy(
2299 			    (const void *)(uintptr_t)key[i].dttk_value,
2300 			    (void *)kdata, kesize);
2301 			dkey->dttk_value = kdata;
2302 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2303 		} else {
2304 			dkey->dttk_value = key[i].dttk_value;
2305 		}
2306 
2307 		dkey->dttk_size = kesize;
2308 	}
2309 
2310 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2311 	dvar->dtdv_hashval = hashval;
2312 	dvar->dtdv_next = start;
2313 
2314 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2315 		return (dvar);
2316 
2317 	/*
2318 	 * The cas has failed.  Either another CPU is adding an element to
2319 	 * this hash chain, or another CPU is deleting an element from this
2320 	 * hash chain.  The simplest way to deal with both of these cases
2321 	 * (though not necessarily the most efficient) is to free our
2322 	 * allocated block and re-attempt it all.  Note that the free is
2323 	 * to the dirty list and _not_ to the free list.  This is to prevent
2324 	 * races with allocators, above.
2325 	 */
2326 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2327 
2328 	dtrace_membar_producer();
2329 
2330 	do {
2331 		free = dcpu->dtdsc_dirty;
2332 		dvar->dtdv_next = free;
2333 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2334 
2335 	goto top;
2336 }
2337 
2338 /*ARGSUSED*/
2339 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2340 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2341 {
2342 	if ((int64_t)nval < (int64_t)*oval)
2343 		*oval = nval;
2344 }
2345 
2346 /*ARGSUSED*/
2347 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2348 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2349 {
2350 	if ((int64_t)nval > (int64_t)*oval)
2351 		*oval = nval;
2352 }
2353 
2354 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2355 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2356 {
2357 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2358 	int64_t val = (int64_t)nval;
2359 
2360 	if (val < 0) {
2361 		for (i = 0; i < zero; i++) {
2362 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2363 				quanta[i] += incr;
2364 				return;
2365 			}
2366 		}
2367 	} else {
2368 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2369 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2370 				quanta[i - 1] += incr;
2371 				return;
2372 			}
2373 		}
2374 
2375 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2376 		return;
2377 	}
2378 
2379 	ASSERT(0);
2380 }
2381 
2382 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2383 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2384 {
2385 	uint64_t arg = *lquanta++;
2386 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2387 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2388 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2389 	int32_t val = (int32_t)nval, level;
2390 
2391 	ASSERT(step != 0);
2392 	ASSERT(levels != 0);
2393 
2394 	if (val < base) {
2395 		/*
2396 		 * This is an underflow.
2397 		 */
2398 		lquanta[0] += incr;
2399 		return;
2400 	}
2401 
2402 	level = (val - base) / step;
2403 
2404 	if (level < levels) {
2405 		lquanta[level + 1] += incr;
2406 		return;
2407 	}
2408 
2409 	/*
2410 	 * This is an overflow.
2411 	 */
2412 	lquanta[levels + 1] += incr;
2413 }
2414 
2415 static int
dtrace_aggregate_llquantize_bucket(uint16_t factor,uint16_t low,uint16_t high,uint16_t nsteps,int64_t value)2416 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2417     uint16_t high, uint16_t nsteps, int64_t value)
2418 {
2419 	int64_t this = 1, last, next;
2420 	int base = 1, order;
2421 
2422 	ASSERT(factor <= nsteps);
2423 	ASSERT(nsteps % factor == 0);
2424 
2425 	for (order = 0; order < low; order++)
2426 		this *= factor;
2427 
2428 	/*
2429 	 * If our value is less than our factor taken to the power of the
2430 	 * low order of magnitude, it goes into the zeroth bucket.
2431 	 */
2432 	if (value < (last = this))
2433 		return (0);
2434 
2435 	for (this *= factor; order <= high; order++) {
2436 		int nbuckets = this > nsteps ? nsteps : this;
2437 
2438 		if ((next = this * factor) < this) {
2439 			/*
2440 			 * We should not generally get log/linear quantizations
2441 			 * with a high magnitude that allows 64-bits to
2442 			 * overflow, but we nonetheless protect against this
2443 			 * by explicitly checking for overflow, and clamping
2444 			 * our value accordingly.
2445 			 */
2446 			value = this - 1;
2447 		}
2448 
2449 		if (value < this) {
2450 			/*
2451 			 * If our value lies within this order of magnitude,
2452 			 * determine its position by taking the offset within
2453 			 * the order of magnitude, dividing by the bucket
2454 			 * width, and adding to our (accumulated) base.
2455 			 */
2456 			return (base + (value - last) / (this / nbuckets));
2457 		}
2458 
2459 		base += nbuckets - (nbuckets / factor);
2460 		last = this;
2461 		this = next;
2462 	}
2463 
2464 	/*
2465 	 * Our value is greater than or equal to our factor taken to the
2466 	 * power of one plus the high magnitude -- return the top bucket.
2467 	 */
2468 	return (base);
2469 }
2470 
2471 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2472 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2473 {
2474 	uint64_t arg = *llquanta++;
2475 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2476 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2477 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2478 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2479 
2480 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2481 	    low, high, nsteps, nval)] += incr;
2482 }
2483 
2484 /*ARGSUSED*/
2485 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2486 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2487 {
2488 	data[0]++;
2489 	data[1] += nval;
2490 }
2491 
2492 /*ARGSUSED*/
2493 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2494 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2495 {
2496 	int64_t snval = (int64_t)nval;
2497 	uint64_t tmp[2];
2498 
2499 	data[0]++;
2500 	data[1] += nval;
2501 
2502 	/*
2503 	 * What we want to say here is:
2504 	 *
2505 	 * data[2] += nval * nval;
2506 	 *
2507 	 * But given that nval is 64-bit, we could easily overflow, so
2508 	 * we do this as 128-bit arithmetic.
2509 	 */
2510 	if (snval < 0)
2511 		snval = -snval;
2512 
2513 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2514 	dtrace_add_128(data + 2, tmp, data + 2);
2515 }
2516 
2517 /*ARGSUSED*/
2518 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2519 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2520 {
2521 	*oval = *oval + 1;
2522 }
2523 
2524 /*ARGSUSED*/
2525 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2526 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2527 {
2528 	*oval += nval;
2529 }
2530 
2531 /*
2532  * Aggregate given the tuple in the principal data buffer, and the aggregating
2533  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2534  * buffer is specified as the buf parameter.  This routine does not return
2535  * failure; if there is no space in the aggregation buffer, the data will be
2536  * dropped, and a corresponding counter incremented.
2537  */
2538 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)2539 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2540     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2541 {
2542 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2543 	uint32_t i, ndx, size, fsize;
2544 	uint32_t align = sizeof (uint64_t) - 1;
2545 	dtrace_aggbuffer_t *agb;
2546 	dtrace_aggkey_t *key;
2547 	uint32_t hashval = 0, limit, isstr;
2548 	caddr_t tomax, data, kdata;
2549 	dtrace_actkind_t action;
2550 	dtrace_action_t *act;
2551 	uintptr_t offs;
2552 
2553 	if (buf == NULL)
2554 		return;
2555 
2556 	if (!agg->dtag_hasarg) {
2557 		/*
2558 		 * Currently, only quantize() and lquantize() take additional
2559 		 * arguments, and they have the same semantics:  an increment
2560 		 * value that defaults to 1 when not present.  If additional
2561 		 * aggregating actions take arguments, the setting of the
2562 		 * default argument value will presumably have to become more
2563 		 * sophisticated...
2564 		 */
2565 		arg = 1;
2566 	}
2567 
2568 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2569 	size = rec->dtrd_offset - agg->dtag_base;
2570 	fsize = size + rec->dtrd_size;
2571 
2572 	ASSERT(dbuf->dtb_tomax != NULL);
2573 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2574 
2575 	if ((tomax = buf->dtb_tomax) == NULL) {
2576 		dtrace_buffer_drop(buf);
2577 		return;
2578 	}
2579 
2580 	/*
2581 	 * The metastructure is always at the bottom of the buffer.
2582 	 */
2583 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2584 	    sizeof (dtrace_aggbuffer_t));
2585 
2586 	if (buf->dtb_offset == 0) {
2587 		/*
2588 		 * We just kludge up approximately 1/8th of the size to be
2589 		 * buckets.  If this guess ends up being routinely
2590 		 * off-the-mark, we may need to dynamically readjust this
2591 		 * based on past performance.
2592 		 */
2593 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2594 
2595 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2596 		    (uintptr_t)tomax || hashsize == 0) {
2597 			/*
2598 			 * We've been given a ludicrously small buffer;
2599 			 * increment our drop count and leave.
2600 			 */
2601 			dtrace_buffer_drop(buf);
2602 			return;
2603 		}
2604 
2605 		/*
2606 		 * And now, a pathetic attempt to try to get a an odd (or
2607 		 * perchance, a prime) hash size for better hash distribution.
2608 		 */
2609 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2610 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2611 
2612 		agb->dtagb_hashsize = hashsize;
2613 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2614 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2615 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2616 
2617 		for (i = 0; i < agb->dtagb_hashsize; i++)
2618 			agb->dtagb_hash[i] = NULL;
2619 	}
2620 
2621 	ASSERT(agg->dtag_first != NULL);
2622 	ASSERT(agg->dtag_first->dta_intuple);
2623 
2624 	/*
2625 	 * Calculate the hash value based on the key.  Note that we _don't_
2626 	 * include the aggid in the hashing (but we will store it as part of
2627 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2628 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2629 	 * gets good distribution in practice.  The efficacy of the hashing
2630 	 * algorithm (and a comparison with other algorithms) may be found by
2631 	 * running the ::dtrace_aggstat MDB dcmd.
2632 	 */
2633 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2634 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2635 		limit = i + act->dta_rec.dtrd_size;
2636 		ASSERT(limit <= size);
2637 		isstr = DTRACEACT_ISSTRING(act);
2638 
2639 		for (; i < limit; i++) {
2640 			hashval += data[i];
2641 			hashval += (hashval << 10);
2642 			hashval ^= (hashval >> 6);
2643 
2644 			if (isstr && data[i] == '\0')
2645 				break;
2646 		}
2647 	}
2648 
2649 	hashval += (hashval << 3);
2650 	hashval ^= (hashval >> 11);
2651 	hashval += (hashval << 15);
2652 
2653 	/*
2654 	 * Yes, the divide here is expensive -- but it's generally the least
2655 	 * of the performance issues given the amount of data that we iterate
2656 	 * over to compute hash values, compare data, etc.
2657 	 */
2658 	ndx = hashval % agb->dtagb_hashsize;
2659 
2660 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2661 		ASSERT((caddr_t)key >= tomax);
2662 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2663 
2664 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2665 			continue;
2666 
2667 		kdata = key->dtak_data;
2668 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2669 
2670 		for (act = agg->dtag_first; act->dta_intuple;
2671 		    act = act->dta_next) {
2672 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2673 			limit = i + act->dta_rec.dtrd_size;
2674 			ASSERT(limit <= size);
2675 			isstr = DTRACEACT_ISSTRING(act);
2676 
2677 			for (; i < limit; i++) {
2678 				if (kdata[i] != data[i])
2679 					goto next;
2680 
2681 				if (isstr && data[i] == '\0')
2682 					break;
2683 			}
2684 		}
2685 
2686 		if (action != key->dtak_action) {
2687 			/*
2688 			 * We are aggregating on the same value in the same
2689 			 * aggregation with two different aggregating actions.
2690 			 * (This should have been picked up in the compiler,
2691 			 * so we may be dealing with errant or devious DIF.)
2692 			 * This is an error condition; we indicate as much,
2693 			 * and return.
2694 			 */
2695 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2696 			return;
2697 		}
2698 
2699 		/*
2700 		 * This is a hit:  we need to apply the aggregator to
2701 		 * the value at this key.
2702 		 */
2703 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2704 		return;
2705 next:
2706 		continue;
2707 	}
2708 
2709 	/*
2710 	 * We didn't find it.  We need to allocate some zero-filled space,
2711 	 * link it into the hash table appropriately, and apply the aggregator
2712 	 * to the (zero-filled) value.
2713 	 */
2714 	offs = buf->dtb_offset;
2715 	while (offs & (align - 1))
2716 		offs += sizeof (uint32_t);
2717 
2718 	/*
2719 	 * If we don't have enough room to both allocate a new key _and_
2720 	 * its associated data, increment the drop count and return.
2721 	 */
2722 	if ((uintptr_t)tomax + offs + fsize >
2723 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2724 		dtrace_buffer_drop(buf);
2725 		return;
2726 	}
2727 
2728 	/*CONSTCOND*/
2729 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2730 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2731 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2732 
2733 	key->dtak_data = kdata = tomax + offs;
2734 	buf->dtb_offset = offs + fsize;
2735 
2736 	/*
2737 	 * Now copy the data across.
2738 	 */
2739 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2740 
2741 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2742 		kdata[i] = data[i];
2743 
2744 	/*
2745 	 * Because strings are not zeroed out by default, we need to iterate
2746 	 * looking for actions that store strings, and we need to explicitly
2747 	 * pad these strings out with zeroes.
2748 	 */
2749 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2750 		int nul;
2751 
2752 		if (!DTRACEACT_ISSTRING(act))
2753 			continue;
2754 
2755 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2756 		limit = i + act->dta_rec.dtrd_size;
2757 		ASSERT(limit <= size);
2758 
2759 		for (nul = 0; i < limit; i++) {
2760 			if (nul) {
2761 				kdata[i] = '\0';
2762 				continue;
2763 			}
2764 
2765 			if (data[i] != '\0')
2766 				continue;
2767 
2768 			nul = 1;
2769 		}
2770 	}
2771 
2772 	for (i = size; i < fsize; i++)
2773 		kdata[i] = 0;
2774 
2775 	key->dtak_hashval = hashval;
2776 	key->dtak_size = size;
2777 	key->dtak_action = action;
2778 	key->dtak_next = agb->dtagb_hash[ndx];
2779 	agb->dtagb_hash[ndx] = key;
2780 
2781 	/*
2782 	 * Finally, apply the aggregator.
2783 	 */
2784 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2785 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2786 }
2787 
2788 /*
2789  * Given consumer state, this routine finds a speculation in the INACTIVE
2790  * state and transitions it into the ACTIVE state.  If there is no speculation
2791  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2792  * incremented -- it is up to the caller to take appropriate action.
2793  */
2794 static int
dtrace_speculation(dtrace_state_t * state)2795 dtrace_speculation(dtrace_state_t *state)
2796 {
2797 	int i = 0;
2798 	dtrace_speculation_state_t curstate;
2799 	uint32_t *stat = &state->dts_speculations_unavail, count;
2800 
2801 	while (i < state->dts_nspeculations) {
2802 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2803 
2804 		curstate = spec->dtsp_state;
2805 
2806 		if (curstate != DTRACESPEC_INACTIVE) {
2807 			if (curstate == DTRACESPEC_COMMITTINGMANY ||
2808 			    curstate == DTRACESPEC_COMMITTING ||
2809 			    curstate == DTRACESPEC_DISCARDING)
2810 				stat = &state->dts_speculations_busy;
2811 			i++;
2812 			continue;
2813 		}
2814 
2815 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2816 		    curstate, DTRACESPEC_ACTIVE) == curstate)
2817 			return (i + 1);
2818 	}
2819 
2820 	/*
2821 	 * We couldn't find a speculation.  If we found as much as a single
2822 	 * busy speculation buffer, we'll attribute this failure as "busy"
2823 	 * instead of "unavail".
2824 	 */
2825 	do {
2826 		count = *stat;
2827 	} while (dtrace_cas32(stat, count, count + 1) != count);
2828 
2829 	return (0);
2830 }
2831 
2832 /*
2833  * This routine commits an active speculation.  If the specified speculation
2834  * is not in a valid state to perform a commit(), this routine will silently do
2835  * nothing.  The state of the specified speculation is transitioned according
2836  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2837  */
2838 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2839 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2840     dtrace_specid_t which)
2841 {
2842 	dtrace_speculation_t *spec;
2843 	dtrace_buffer_t *src, *dest;
2844 	uintptr_t daddr, saddr, dlimit, slimit;
2845 	dtrace_speculation_state_t curstate, new = 0;
2846 	intptr_t offs;
2847 	uint64_t timestamp;
2848 
2849 	if (which == 0)
2850 		return;
2851 
2852 	if (which > state->dts_nspeculations) {
2853 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2854 		return;
2855 	}
2856 
2857 	spec = &state->dts_speculations[which - 1];
2858 	src = &spec->dtsp_buffer[cpu];
2859 	dest = &state->dts_buffer[cpu];
2860 
2861 	do {
2862 		curstate = spec->dtsp_state;
2863 
2864 		if (curstate == DTRACESPEC_COMMITTINGMANY)
2865 			break;
2866 
2867 		switch (curstate) {
2868 		case DTRACESPEC_INACTIVE:
2869 		case DTRACESPEC_DISCARDING:
2870 			return;
2871 
2872 		case DTRACESPEC_COMMITTING:
2873 			/*
2874 			 * This is only possible if we are (a) commit()'ing
2875 			 * without having done a prior speculate() on this CPU
2876 			 * and (b) racing with another commit() on a different
2877 			 * CPU.  There's nothing to do -- we just assert that
2878 			 * our offset is 0.
2879 			 */
2880 			ASSERT(src->dtb_offset == 0);
2881 			return;
2882 
2883 		case DTRACESPEC_ACTIVE:
2884 			new = DTRACESPEC_COMMITTING;
2885 			break;
2886 
2887 		case DTRACESPEC_ACTIVEONE:
2888 			/*
2889 			 * This speculation is active on one CPU.  If our
2890 			 * buffer offset is non-zero, we know that the one CPU
2891 			 * must be us.  Otherwise, we are committing on a
2892 			 * different CPU from the speculate(), and we must
2893 			 * rely on being asynchronously cleaned.
2894 			 */
2895 			if (src->dtb_offset != 0) {
2896 				new = DTRACESPEC_COMMITTING;
2897 				break;
2898 			}
2899 			/*FALLTHROUGH*/
2900 
2901 		case DTRACESPEC_ACTIVEMANY:
2902 			new = DTRACESPEC_COMMITTINGMANY;
2903 			break;
2904 
2905 		default:
2906 			ASSERT(0);
2907 		}
2908 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2909 	    curstate, new) != curstate);
2910 
2911 	/*
2912 	 * We have set the state to indicate that we are committing this
2913 	 * speculation.  Now reserve the necessary space in the destination
2914 	 * buffer.
2915 	 */
2916 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2917 	    sizeof (uint64_t), state, NULL)) < 0) {
2918 		dtrace_buffer_drop(dest);
2919 		goto out;
2920 	}
2921 
2922 	/*
2923 	 * We have sufficient space to copy the speculative buffer into the
2924 	 * primary buffer.  First, modify the speculative buffer, filling
2925 	 * in the timestamp of all entries with the curstate time.  The data
2926 	 * must have the commit() time rather than the time it was traced,
2927 	 * so that all entries in the primary buffer are in timestamp order.
2928 	 */
2929 	timestamp = dtrace_gethrtime();
2930 	saddr = (uintptr_t)src->dtb_tomax;
2931 	slimit = saddr + src->dtb_offset;
2932 	while (saddr < slimit) {
2933 		size_t size;
2934 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2935 
2936 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2937 			saddr += sizeof (dtrace_epid_t);
2938 			continue;
2939 		}
2940 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2941 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2942 
2943 		ASSERT3U(saddr + size, <=, slimit);
2944 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2945 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2946 
2947 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2948 
2949 		saddr += size;
2950 	}
2951 
2952 	/*
2953 	 * Copy the buffer across.  (Note that this is a
2954 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2955 	 * a serious performance issue, a high-performance DTrace-specific
2956 	 * bcopy() should obviously be invented.)
2957 	 */
2958 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2959 	dlimit = daddr + src->dtb_offset;
2960 	saddr = (uintptr_t)src->dtb_tomax;
2961 
2962 	/*
2963 	 * First, the aligned portion.
2964 	 */
2965 	while (dlimit - daddr >= sizeof (uint64_t)) {
2966 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2967 
2968 		daddr += sizeof (uint64_t);
2969 		saddr += sizeof (uint64_t);
2970 	}
2971 
2972 	/*
2973 	 * Now any left-over bit...
2974 	 */
2975 	while (dlimit - daddr)
2976 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2977 
2978 	/*
2979 	 * Finally, commit the reserved space in the destination buffer.
2980 	 */
2981 	dest->dtb_offset = offs + src->dtb_offset;
2982 
2983 out:
2984 	/*
2985 	 * If we're lucky enough to be the only active CPU on this speculation
2986 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2987 	 */
2988 	if (curstate == DTRACESPEC_ACTIVE ||
2989 	    (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2990 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2991 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2992 
2993 		ASSERT(rval == DTRACESPEC_COMMITTING);
2994 	}
2995 
2996 	src->dtb_offset = 0;
2997 	src->dtb_xamot_drops += src->dtb_drops;
2998 	src->dtb_drops = 0;
2999 }
3000 
3001 /*
3002  * This routine discards an active speculation.  If the specified speculation
3003  * is not in a valid state to perform a discard(), this routine will silently
3004  * do nothing.  The state of the specified speculation is transitioned
3005  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3006  */
3007 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)3008 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3009     dtrace_specid_t which)
3010 {
3011 	dtrace_speculation_t *spec;
3012 	dtrace_speculation_state_t curstate, new = 0;
3013 	dtrace_buffer_t *buf;
3014 
3015 	if (which == 0)
3016 		return;
3017 
3018 	if (which > state->dts_nspeculations) {
3019 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3020 		return;
3021 	}
3022 
3023 	spec = &state->dts_speculations[which - 1];
3024 	buf = &spec->dtsp_buffer[cpu];
3025 
3026 	do {
3027 		curstate = spec->dtsp_state;
3028 
3029 		switch (curstate) {
3030 		case DTRACESPEC_INACTIVE:
3031 		case DTRACESPEC_COMMITTINGMANY:
3032 		case DTRACESPEC_COMMITTING:
3033 		case DTRACESPEC_DISCARDING:
3034 			return;
3035 
3036 		case DTRACESPEC_ACTIVE:
3037 		case DTRACESPEC_ACTIVEMANY:
3038 			new = DTRACESPEC_DISCARDING;
3039 			break;
3040 
3041 		case DTRACESPEC_ACTIVEONE:
3042 			if (buf->dtb_offset != 0) {
3043 				new = DTRACESPEC_INACTIVE;
3044 			} else {
3045 				new = DTRACESPEC_DISCARDING;
3046 			}
3047 			break;
3048 
3049 		default:
3050 			ASSERT(0);
3051 		}
3052 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3053 	    curstate, new) != curstate);
3054 
3055 	buf->dtb_offset = 0;
3056 	buf->dtb_drops = 0;
3057 }
3058 
3059 /*
3060  * Note:  not called from probe context.  This function is called
3061  * asynchronously from cross call context to clean any speculations that are
3062  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3063  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3064  * speculation.
3065  */
3066 static void
dtrace_speculation_clean_here(dtrace_state_t * state)3067 dtrace_speculation_clean_here(dtrace_state_t *state)
3068 {
3069 	dtrace_icookie_t cookie;
3070 	processorid_t cpu = curcpu;
3071 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3072 	dtrace_specid_t i;
3073 
3074 	cookie = dtrace_interrupt_disable();
3075 
3076 	if (dest->dtb_tomax == NULL) {
3077 		dtrace_interrupt_enable(cookie);
3078 		return;
3079 	}
3080 
3081 	for (i = 0; i < state->dts_nspeculations; i++) {
3082 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3083 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3084 
3085 		if (src->dtb_tomax == NULL)
3086 			continue;
3087 
3088 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3089 			src->dtb_offset = 0;
3090 			continue;
3091 		}
3092 
3093 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3094 			continue;
3095 
3096 		if (src->dtb_offset == 0)
3097 			continue;
3098 
3099 		dtrace_speculation_commit(state, cpu, i + 1);
3100 	}
3101 
3102 	dtrace_interrupt_enable(cookie);
3103 }
3104 
3105 /*
3106  * Note:  not called from probe context.  This function is called
3107  * asynchronously (and at a regular interval) to clean any speculations that
3108  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3109  * is work to be done, it cross calls all CPUs to perform that work;
3110  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3111  * INACTIVE state until they have been cleaned by all CPUs.
3112  */
3113 static void
dtrace_speculation_clean(dtrace_state_t * state)3114 dtrace_speculation_clean(dtrace_state_t *state)
3115 {
3116 	int work = 0, rv;
3117 	dtrace_specid_t i;
3118 
3119 	for (i = 0; i < state->dts_nspeculations; i++) {
3120 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3121 
3122 		ASSERT(!spec->dtsp_cleaning);
3123 
3124 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3125 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3126 			continue;
3127 
3128 		work++;
3129 		spec->dtsp_cleaning = 1;
3130 	}
3131 
3132 	if (!work)
3133 		return;
3134 
3135 	dtrace_xcall(DTRACE_CPUALL,
3136 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3137 
3138 	/*
3139 	 * We now know that all CPUs have committed or discarded their
3140 	 * speculation buffers, as appropriate.  We can now set the state
3141 	 * to inactive.
3142 	 */
3143 	for (i = 0; i < state->dts_nspeculations; i++) {
3144 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3145 		dtrace_speculation_state_t curstate, new;
3146 
3147 		if (!spec->dtsp_cleaning)
3148 			continue;
3149 
3150 		curstate = spec->dtsp_state;
3151 		ASSERT(curstate == DTRACESPEC_DISCARDING ||
3152 		    curstate == DTRACESPEC_COMMITTINGMANY);
3153 
3154 		new = DTRACESPEC_INACTIVE;
3155 
3156 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3157 		ASSERT(rv == curstate);
3158 		spec->dtsp_cleaning = 0;
3159 	}
3160 }
3161 
3162 /*
3163  * Called as part of a speculate() to get the speculative buffer associated
3164  * with a given speculation.  Returns NULL if the specified speculation is not
3165  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3166  * the active CPU is not the specified CPU -- the speculation will be
3167  * atomically transitioned into the ACTIVEMANY state.
3168  */
3169 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3170 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3171     dtrace_specid_t which)
3172 {
3173 	dtrace_speculation_t *spec;
3174 	dtrace_speculation_state_t curstate, new = 0;
3175 	dtrace_buffer_t *buf;
3176 
3177 	if (which == 0)
3178 		return (NULL);
3179 
3180 	if (which > state->dts_nspeculations) {
3181 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3182 		return (NULL);
3183 	}
3184 
3185 	spec = &state->dts_speculations[which - 1];
3186 	buf = &spec->dtsp_buffer[cpuid];
3187 
3188 	do {
3189 		curstate = spec->dtsp_state;
3190 
3191 		switch (curstate) {
3192 		case DTRACESPEC_INACTIVE:
3193 		case DTRACESPEC_COMMITTINGMANY:
3194 		case DTRACESPEC_DISCARDING:
3195 			return (NULL);
3196 
3197 		case DTRACESPEC_COMMITTING:
3198 			ASSERT(buf->dtb_offset == 0);
3199 			return (NULL);
3200 
3201 		case DTRACESPEC_ACTIVEONE:
3202 			/*
3203 			 * This speculation is currently active on one CPU.
3204 			 * Check the offset in the buffer; if it's non-zero,
3205 			 * that CPU must be us (and we leave the state alone).
3206 			 * If it's zero, assume that we're starting on a new
3207 			 * CPU -- and change the state to indicate that the
3208 			 * speculation is active on more than one CPU.
3209 			 */
3210 			if (buf->dtb_offset != 0)
3211 				return (buf);
3212 
3213 			new = DTRACESPEC_ACTIVEMANY;
3214 			break;
3215 
3216 		case DTRACESPEC_ACTIVEMANY:
3217 			return (buf);
3218 
3219 		case DTRACESPEC_ACTIVE:
3220 			new = DTRACESPEC_ACTIVEONE;
3221 			break;
3222 
3223 		default:
3224 			ASSERT(0);
3225 		}
3226 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3227 	    curstate, new) != curstate);
3228 
3229 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3230 	return (buf);
3231 }
3232 
3233 /*
3234  * Return a string.  In the event that the user lacks the privilege to access
3235  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3236  * don't fail access checking.
3237  *
3238  * dtrace_dif_variable() uses this routine as a helper for various
3239  * builtin values such as 'execname' and 'probefunc.'
3240  */
3241 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3242 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3243     dtrace_mstate_t *mstate)
3244 {
3245 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3246 	uintptr_t ret;
3247 	size_t strsz;
3248 
3249 	/*
3250 	 * The easy case: this probe is allowed to read all of memory, so
3251 	 * we can just return this as a vanilla pointer.
3252 	 */
3253 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3254 		return (addr);
3255 
3256 	/*
3257 	 * This is the tougher case: we copy the string in question from
3258 	 * kernel memory into scratch memory and return it that way: this
3259 	 * ensures that we won't trip up when access checking tests the
3260 	 * BYREF return value.
3261 	 */
3262 	strsz = dtrace_strlen((char *)addr, size) + 1;
3263 
3264 	if (mstate->dtms_scratch_ptr + strsz >
3265 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3266 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3267 		return (0);
3268 	}
3269 
3270 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3271 	    strsz);
3272 	ret = mstate->dtms_scratch_ptr;
3273 	mstate->dtms_scratch_ptr += strsz;
3274 	return (ret);
3275 }
3276 
3277 /*
3278  * Return a string from a memoy address which is known to have one or
3279  * more concatenated, individually zero terminated, sub-strings.
3280  * In the event that the user lacks the privilege to access
3281  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3282  * don't fail access checking.
3283  *
3284  * dtrace_dif_variable() uses this routine as a helper for various
3285  * builtin values such as 'execargs'.
3286  */
3287 static uintptr_t
dtrace_dif_varstrz(uintptr_t addr,size_t strsz,dtrace_state_t * state,dtrace_mstate_t * mstate)3288 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3289     dtrace_mstate_t *mstate)
3290 {
3291 	char *p;
3292 	size_t i;
3293 	uintptr_t ret;
3294 
3295 	if (mstate->dtms_scratch_ptr + strsz >
3296 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3297 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3298 		return (0);
3299 	}
3300 
3301 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3302 	    strsz);
3303 
3304 	/* Replace sub-string termination characters with a space. */
3305 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3306 	    p++, i++)
3307 		if (*p == '\0')
3308 			*p = ' ';
3309 
3310 	ret = mstate->dtms_scratch_ptr;
3311 	mstate->dtms_scratch_ptr += strsz;
3312 	return (ret);
3313 }
3314 
3315 /*
3316  * This function implements the DIF emulator's variable lookups.  The emulator
3317  * passes a reserved variable identifier and optional built-in array index.
3318  */
3319 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3320 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3321     uint64_t ndx)
3322 {
3323 	/*
3324 	 * If we're accessing one of the uncached arguments, we'll turn this
3325 	 * into a reference in the args array.
3326 	 */
3327 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3328 		ndx = v - DIF_VAR_ARG0;
3329 		v = DIF_VAR_ARGS;
3330 	}
3331 
3332 	switch (v) {
3333 	case DIF_VAR_ARGS:
3334 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3335 		if (ndx >= sizeof (mstate->dtms_arg) /
3336 		    sizeof (mstate->dtms_arg[0])) {
3337 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3338 			dtrace_provider_t *pv;
3339 			uint64_t val;
3340 
3341 			pv = mstate->dtms_probe->dtpr_provider;
3342 			if (pv->dtpv_pops.dtps_getargval != NULL)
3343 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3344 				    mstate->dtms_probe->dtpr_id,
3345 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3346 			else
3347 				val = dtrace_getarg(ndx, aframes);
3348 
3349 			/*
3350 			 * This is regrettably required to keep the compiler
3351 			 * from tail-optimizing the call to dtrace_getarg().
3352 			 * The condition always evaluates to true, but the
3353 			 * compiler has no way of figuring that out a priori.
3354 			 * (None of this would be necessary if the compiler
3355 			 * could be relied upon to _always_ tail-optimize
3356 			 * the call to dtrace_getarg() -- but it can't.)
3357 			 */
3358 			if (mstate->dtms_probe != NULL)
3359 				return (val);
3360 
3361 			ASSERT(0);
3362 		}
3363 
3364 		return (mstate->dtms_arg[ndx]);
3365 
3366 	case DIF_VAR_REGS:
3367 	case DIF_VAR_UREGS: {
3368 		struct trapframe *tframe;
3369 
3370 		if (!dtrace_priv_proc(state))
3371 			return (0);
3372 
3373 		if (v == DIF_VAR_REGS)
3374 			tframe = curthread->t_dtrace_trapframe;
3375 		else
3376 			tframe = curthread->td_frame;
3377 
3378 		if (tframe == NULL) {
3379 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3380 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3381 			return (0);
3382 		}
3383 
3384 		return (dtrace_getreg(tframe, ndx));
3385 	}
3386 
3387 	case DIF_VAR_CURTHREAD:
3388 		if (!dtrace_priv_proc(state))
3389 			return (0);
3390 		return ((uint64_t)(uintptr_t)curthread);
3391 
3392 	case DIF_VAR_TIMESTAMP:
3393 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3394 			mstate->dtms_timestamp = dtrace_gethrtime();
3395 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3396 		}
3397 		return (mstate->dtms_timestamp);
3398 
3399 	case DIF_VAR_VTIMESTAMP:
3400 		ASSERT(dtrace_vtime_references != 0);
3401 		return (curthread->t_dtrace_vtime);
3402 
3403 	case DIF_VAR_WALLTIMESTAMP:
3404 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3405 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3406 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3407 		}
3408 		return (mstate->dtms_walltimestamp);
3409 
3410 #ifdef illumos
3411 	case DIF_VAR_IPL:
3412 		if (!dtrace_priv_kernel(state))
3413 			return (0);
3414 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3415 			mstate->dtms_ipl = dtrace_getipl();
3416 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3417 		}
3418 		return (mstate->dtms_ipl);
3419 #endif
3420 
3421 	case DIF_VAR_EPID:
3422 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3423 		return (mstate->dtms_epid);
3424 
3425 	case DIF_VAR_ID:
3426 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3427 		return (mstate->dtms_probe->dtpr_id);
3428 
3429 	case DIF_VAR_STACKDEPTH:
3430 		if (!dtrace_priv_kernel(state))
3431 			return (0);
3432 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3433 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3434 
3435 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3436 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3437 		}
3438 		return (mstate->dtms_stackdepth);
3439 
3440 	case DIF_VAR_USTACKDEPTH:
3441 		if (!dtrace_priv_proc(state))
3442 			return (0);
3443 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3444 			/*
3445 			 * See comment in DIF_VAR_PID.
3446 			 */
3447 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3448 			    CPU_ON_INTR(CPU)) {
3449 				mstate->dtms_ustackdepth = 0;
3450 			} else {
3451 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3452 				mstate->dtms_ustackdepth =
3453 				    dtrace_getustackdepth();
3454 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3455 			}
3456 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3457 		}
3458 		return (mstate->dtms_ustackdepth);
3459 
3460 	case DIF_VAR_CALLER:
3461 		if (!dtrace_priv_kernel(state))
3462 			return (0);
3463 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3464 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3465 
3466 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3467 				/*
3468 				 * If this is an unanchored probe, we are
3469 				 * required to go through the slow path:
3470 				 * dtrace_caller() only guarantees correct
3471 				 * results for anchored probes.
3472 				 */
3473 				pc_t caller[2] = {0, 0};
3474 
3475 				dtrace_getpcstack(caller, 2, aframes,
3476 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3477 				mstate->dtms_caller = caller[1];
3478 			} else if ((mstate->dtms_caller =
3479 			    dtrace_caller(aframes)) == -1) {
3480 				/*
3481 				 * We have failed to do this the quick way;
3482 				 * we must resort to the slower approach of
3483 				 * calling dtrace_getpcstack().
3484 				 */
3485 				pc_t caller = 0;
3486 
3487 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3488 				mstate->dtms_caller = caller;
3489 			}
3490 
3491 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3492 		}
3493 		return (mstate->dtms_caller);
3494 
3495 	case DIF_VAR_UCALLER:
3496 		if (!dtrace_priv_proc(state))
3497 			return (0);
3498 
3499 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3500 			uint64_t ustack[3];
3501 
3502 			/*
3503 			 * dtrace_getupcstack() fills in the first uint64_t
3504 			 * with the current PID.  The second uint64_t will
3505 			 * be the program counter at user-level.  The third
3506 			 * uint64_t will contain the caller, which is what
3507 			 * we're after.
3508 			 */
3509 			ustack[2] = 0;
3510 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3511 			dtrace_getupcstack(ustack, 3);
3512 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3513 			mstate->dtms_ucaller = ustack[2];
3514 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3515 		}
3516 
3517 		return (mstate->dtms_ucaller);
3518 
3519 	case DIF_VAR_PROBEPROV:
3520 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3521 		return (dtrace_dif_varstr(
3522 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3523 		    state, mstate));
3524 
3525 	case DIF_VAR_PROBEMOD:
3526 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3527 		return (dtrace_dif_varstr(
3528 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3529 		    state, mstate));
3530 
3531 	case DIF_VAR_PROBEFUNC:
3532 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3533 		return (dtrace_dif_varstr(
3534 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3535 		    state, mstate));
3536 
3537 	case DIF_VAR_PROBENAME:
3538 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3539 		return (dtrace_dif_varstr(
3540 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3541 		    state, mstate));
3542 
3543 	case DIF_VAR_PID:
3544 		if (!dtrace_priv_proc(state))
3545 			return (0);
3546 
3547 #ifdef illumos
3548 		/*
3549 		 * Note that we are assuming that an unanchored probe is
3550 		 * always due to a high-level interrupt.  (And we're assuming
3551 		 * that there is only a single high level interrupt.)
3552 		 */
3553 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3554 			return (pid0.pid_id);
3555 
3556 		/*
3557 		 * It is always safe to dereference one's own t_procp pointer:
3558 		 * it always points to a valid, allocated proc structure.
3559 		 * Further, it is always safe to dereference the p_pidp member
3560 		 * of one's own proc structure.  (These are truisms becuase
3561 		 * threads and processes don't clean up their own state --
3562 		 * they leave that task to whomever reaps them.)
3563 		 */
3564 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3565 #else
3566 		return ((uint64_t)curproc->p_pid);
3567 #endif
3568 
3569 	case DIF_VAR_PPID:
3570 		if (!dtrace_priv_proc(state))
3571 			return (0);
3572 
3573 #ifdef illumos
3574 		/*
3575 		 * See comment in DIF_VAR_PID.
3576 		 */
3577 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3578 			return (pid0.pid_id);
3579 
3580 		/*
3581 		 * It is always safe to dereference one's own t_procp pointer:
3582 		 * it always points to a valid, allocated proc structure.
3583 		 * (This is true because threads don't clean up their own
3584 		 * state -- they leave that task to whomever reaps them.)
3585 		 */
3586 		return ((uint64_t)curthread->t_procp->p_ppid);
3587 #else
3588 		if (curproc->p_pid == proc0.p_pid)
3589 			return (curproc->p_pid);
3590 		else
3591 			return (curproc->p_pptr->p_pid);
3592 #endif
3593 
3594 	case DIF_VAR_TID:
3595 #ifdef illumos
3596 		/*
3597 		 * See comment in DIF_VAR_PID.
3598 		 */
3599 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3600 			return (0);
3601 #endif
3602 
3603 		return ((uint64_t)curthread->t_tid);
3604 
3605 	case DIF_VAR_EXECARGS: {
3606 		struct pargs *p_args = curthread->td_proc->p_args;
3607 
3608 		if (p_args == NULL)
3609 			return(0);
3610 
3611 		return (dtrace_dif_varstrz(
3612 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3613 	}
3614 
3615 	case DIF_VAR_EXECNAME:
3616 #ifdef illumos
3617 		if (!dtrace_priv_proc(state))
3618 			return (0);
3619 
3620 		/*
3621 		 * See comment in DIF_VAR_PID.
3622 		 */
3623 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3624 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3625 
3626 		/*
3627 		 * It is always safe to dereference one's own t_procp pointer:
3628 		 * it always points to a valid, allocated proc structure.
3629 		 * (This is true because threads don't clean up their own
3630 		 * state -- they leave that task to whomever reaps them.)
3631 		 */
3632 		return (dtrace_dif_varstr(
3633 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3634 		    state, mstate));
3635 #else
3636 		return (dtrace_dif_varstr(
3637 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3638 #endif
3639 
3640 	case DIF_VAR_ZONENAME:
3641 #ifdef illumos
3642 		if (!dtrace_priv_proc(state))
3643 			return (0);
3644 
3645 		/*
3646 		 * See comment in DIF_VAR_PID.
3647 		 */
3648 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3649 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3650 
3651 		/*
3652 		 * It is always safe to dereference one's own t_procp pointer:
3653 		 * it always points to a valid, allocated proc structure.
3654 		 * (This is true because threads don't clean up their own
3655 		 * state -- they leave that task to whomever reaps them.)
3656 		 */
3657 		return (dtrace_dif_varstr(
3658 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3659 		    state, mstate));
3660 #elif defined(__FreeBSD__)
3661 	/*
3662 	 * On FreeBSD, we introduce compatibility to zonename by falling through
3663 	 * into jailname.
3664 	 */
3665 	case DIF_VAR_JAILNAME:
3666 		if (!dtrace_priv_kernel(state))
3667 			return (0);
3668 
3669 		return (dtrace_dif_varstr(
3670 		    (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3671 		    state, mstate));
3672 
3673 	case DIF_VAR_JID:
3674 		if (!dtrace_priv_kernel(state))
3675 			return (0);
3676 
3677 		return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3678 #else
3679 		return (0);
3680 #endif
3681 
3682 	case DIF_VAR_UID:
3683 		if (!dtrace_priv_proc(state))
3684 			return (0);
3685 
3686 #ifdef illumos
3687 		/*
3688 		 * See comment in DIF_VAR_PID.
3689 		 */
3690 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3691 			return ((uint64_t)p0.p_cred->cr_uid);
3692 
3693 		/*
3694 		 * It is always safe to dereference one's own t_procp pointer:
3695 		 * it always points to a valid, allocated proc structure.
3696 		 * (This is true because threads don't clean up their own
3697 		 * state -- they leave that task to whomever reaps them.)
3698 		 *
3699 		 * Additionally, it is safe to dereference one's own process
3700 		 * credential, since this is never NULL after process birth.
3701 		 */
3702 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3703 #else
3704 		return ((uint64_t)curthread->td_ucred->cr_uid);
3705 #endif
3706 
3707 	case DIF_VAR_GID:
3708 		if (!dtrace_priv_proc(state))
3709 			return (0);
3710 
3711 #ifdef illumos
3712 		/*
3713 		 * See comment in DIF_VAR_PID.
3714 		 */
3715 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3716 			return ((uint64_t)p0.p_cred->cr_gid);
3717 
3718 		/*
3719 		 * It is always safe to dereference one's own t_procp pointer:
3720 		 * it always points to a valid, allocated proc structure.
3721 		 * (This is true because threads don't clean up their own
3722 		 * state -- they leave that task to whomever reaps them.)
3723 		 *
3724 		 * Additionally, it is safe to dereference one's own process
3725 		 * credential, since this is never NULL after process birth.
3726 		 */
3727 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3728 #else
3729 		return ((uint64_t)curthread->td_ucred->cr_gid);
3730 #endif
3731 
3732 	case DIF_VAR_ERRNO: {
3733 #ifdef illumos
3734 		klwp_t *lwp;
3735 		if (!dtrace_priv_proc(state))
3736 			return (0);
3737 
3738 		/*
3739 		 * See comment in DIF_VAR_PID.
3740 		 */
3741 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3742 			return (0);
3743 
3744 		/*
3745 		 * It is always safe to dereference one's own t_lwp pointer in
3746 		 * the event that this pointer is non-NULL.  (This is true
3747 		 * because threads and lwps don't clean up their own state --
3748 		 * they leave that task to whomever reaps them.)
3749 		 */
3750 		if ((lwp = curthread->t_lwp) == NULL)
3751 			return (0);
3752 
3753 		return ((uint64_t)lwp->lwp_errno);
3754 #else
3755 		return (curthread->td_errno);
3756 #endif
3757 	}
3758 #ifndef illumos
3759 	case DIF_VAR_CPU: {
3760 		return curcpu;
3761 	}
3762 #endif
3763 	default:
3764 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3765 		return (0);
3766 	}
3767 }
3768 
3769 
3770 typedef enum dtrace_json_state {
3771 	DTRACE_JSON_REST = 1,
3772 	DTRACE_JSON_OBJECT,
3773 	DTRACE_JSON_STRING,
3774 	DTRACE_JSON_STRING_ESCAPE,
3775 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3776 	DTRACE_JSON_COLON,
3777 	DTRACE_JSON_COMMA,
3778 	DTRACE_JSON_VALUE,
3779 	DTRACE_JSON_IDENTIFIER,
3780 	DTRACE_JSON_NUMBER,
3781 	DTRACE_JSON_NUMBER_FRAC,
3782 	DTRACE_JSON_NUMBER_EXP,
3783 	DTRACE_JSON_COLLECT_OBJECT
3784 } dtrace_json_state_t;
3785 
3786 /*
3787  * This function possesses just enough knowledge about JSON to extract a single
3788  * value from a JSON string and store it in the scratch buffer.  It is able
3789  * to extract nested object values, and members of arrays by index.
3790  *
3791  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3792  * be looked up as we descend into the object tree.  e.g.
3793  *
3794  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3795  *       with nelems = 5.
3796  *
3797  * The run time of this function must be bounded above by strsize to limit the
3798  * amount of work done in probe context.  As such, it is implemented as a
3799  * simple state machine, reading one character at a time using safe loads
3800  * until we find the requested element, hit a parsing error or run off the
3801  * end of the object or string.
3802  *
3803  * As there is no way for a subroutine to return an error without interrupting
3804  * clause execution, we simply return NULL in the event of a missing key or any
3805  * other error condition.  Each NULL return in this function is commented with
3806  * the error condition it represents -- parsing or otherwise.
3807  *
3808  * The set of states for the state machine closely matches the JSON
3809  * specification (http://json.org/).  Briefly:
3810  *
3811  *   DTRACE_JSON_REST:
3812  *     Skip whitespace until we find either a top-level Object, moving
3813  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3814  *
3815  *   DTRACE_JSON_OBJECT:
3816  *     Locate the next key String in an Object.  Sets a flag to denote
3817  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3818  *
3819  *   DTRACE_JSON_COLON:
3820  *     Skip whitespace until we find the colon that separates key Strings
3821  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3822  *
3823  *   DTRACE_JSON_VALUE:
3824  *     Detects the type of the next value (String, Number, Identifier, Object
3825  *     or Array) and routes to the states that process that type.  Here we also
3826  *     deal with the element selector list if we are requested to traverse down
3827  *     into the object tree.
3828  *
3829  *   DTRACE_JSON_COMMA:
3830  *     Skip whitespace until we find the comma that separates key-value pairs
3831  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3832  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3833  *     states return to this state at the end of their value, unless otherwise
3834  *     noted.
3835  *
3836  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3837  *     Processes a Number literal from the JSON, including any exponent
3838  *     component that may be present.  Numbers are returned as strings, which
3839  *     may be passed to strtoll() if an integer is required.
3840  *
3841  *   DTRACE_JSON_IDENTIFIER:
3842  *     Processes a "true", "false" or "null" literal in the JSON.
3843  *
3844  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3845  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3846  *     Processes a String literal from the JSON, whether the String denotes
3847  *     a key, a value or part of a larger Object.  Handles all escape sequences
3848  *     present in the specification, including four-digit unicode characters,
3849  *     but merely includes the escape sequence without converting it to the
3850  *     actual escaped character.  If the String is flagged as a key, we
3851  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3852  *
3853  *   DTRACE_JSON_COLLECT_OBJECT:
3854  *     This state collects an entire Object (or Array), correctly handling
3855  *     embedded strings.  If the full element selector list matches this nested
3856  *     object, we return the Object in full as a string.  If not, we use this
3857  *     state to skip to the next value at this level and continue processing.
3858  *
3859  * NOTE: This function uses various macros from strtolctype.h to manipulate
3860  * digit values, etc -- these have all been checked to ensure they make
3861  * no additional function calls.
3862  */
3863 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3864 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3865     char *dest)
3866 {
3867 	dtrace_json_state_t state = DTRACE_JSON_REST;
3868 	int64_t array_elem = INT64_MIN;
3869 	int64_t array_pos = 0;
3870 	uint8_t escape_unicount = 0;
3871 	boolean_t string_is_key = B_FALSE;
3872 	boolean_t collect_object = B_FALSE;
3873 	boolean_t found_key = B_FALSE;
3874 	boolean_t in_array = B_FALSE;
3875 	uint32_t braces = 0, brackets = 0;
3876 	char *elem = elemlist;
3877 	char *dd = dest;
3878 	uintptr_t cur;
3879 
3880 	for (cur = json; cur < json + size; cur++) {
3881 		char cc = dtrace_load8(cur);
3882 		if (cc == '\0')
3883 			return (NULL);
3884 
3885 		switch (state) {
3886 		case DTRACE_JSON_REST:
3887 			if (isspace(cc))
3888 				break;
3889 
3890 			if (cc == '{') {
3891 				state = DTRACE_JSON_OBJECT;
3892 				break;
3893 			}
3894 
3895 			if (cc == '[') {
3896 				in_array = B_TRUE;
3897 				array_pos = 0;
3898 				array_elem = dtrace_strtoll(elem, 10, size);
3899 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3900 				state = DTRACE_JSON_VALUE;
3901 				break;
3902 			}
3903 
3904 			/*
3905 			 * ERROR: expected to find a top-level object or array.
3906 			 */
3907 			return (NULL);
3908 		case DTRACE_JSON_OBJECT:
3909 			if (isspace(cc))
3910 				break;
3911 
3912 			if (cc == '"') {
3913 				state = DTRACE_JSON_STRING;
3914 				string_is_key = B_TRUE;
3915 				break;
3916 			}
3917 
3918 			/*
3919 			 * ERROR: either the object did not start with a key
3920 			 * string, or we've run off the end of the object
3921 			 * without finding the requested key.
3922 			 */
3923 			return (NULL);
3924 		case DTRACE_JSON_STRING:
3925 			if (cc == '\\') {
3926 				*dd++ = '\\';
3927 				state = DTRACE_JSON_STRING_ESCAPE;
3928 				break;
3929 			}
3930 
3931 			if (cc == '"') {
3932 				if (collect_object) {
3933 					/*
3934 					 * We don't reset the dest here, as
3935 					 * the string is part of a larger
3936 					 * object being collected.
3937 					 */
3938 					*dd++ = cc;
3939 					collect_object = B_FALSE;
3940 					state = DTRACE_JSON_COLLECT_OBJECT;
3941 					break;
3942 				}
3943 				*dd = '\0';
3944 				dd = dest; /* reset string buffer */
3945 				if (string_is_key) {
3946 					if (dtrace_strncmp(dest, elem,
3947 					    size) == 0)
3948 						found_key = B_TRUE;
3949 				} else if (found_key) {
3950 					if (nelems > 1) {
3951 						/*
3952 						 * We expected an object, not
3953 						 * this string.
3954 						 */
3955 						return (NULL);
3956 					}
3957 					return (dest);
3958 				}
3959 				state = string_is_key ? DTRACE_JSON_COLON :
3960 				    DTRACE_JSON_COMMA;
3961 				string_is_key = B_FALSE;
3962 				break;
3963 			}
3964 
3965 			*dd++ = cc;
3966 			break;
3967 		case DTRACE_JSON_STRING_ESCAPE:
3968 			*dd++ = cc;
3969 			if (cc == 'u') {
3970 				escape_unicount = 0;
3971 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3972 			} else {
3973 				state = DTRACE_JSON_STRING;
3974 			}
3975 			break;
3976 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3977 			if (!isxdigit(cc)) {
3978 				/*
3979 				 * ERROR: invalid unicode escape, expected
3980 				 * four valid hexidecimal digits.
3981 				 */
3982 				return (NULL);
3983 			}
3984 
3985 			*dd++ = cc;
3986 			if (++escape_unicount == 4)
3987 				state = DTRACE_JSON_STRING;
3988 			break;
3989 		case DTRACE_JSON_COLON:
3990 			if (isspace(cc))
3991 				break;
3992 
3993 			if (cc == ':') {
3994 				state = DTRACE_JSON_VALUE;
3995 				break;
3996 			}
3997 
3998 			/*
3999 			 * ERROR: expected a colon.
4000 			 */
4001 			return (NULL);
4002 		case DTRACE_JSON_COMMA:
4003 			if (isspace(cc))
4004 				break;
4005 
4006 			if (cc == ',') {
4007 				if (in_array) {
4008 					state = DTRACE_JSON_VALUE;
4009 					if (++array_pos == array_elem)
4010 						found_key = B_TRUE;
4011 				} else {
4012 					state = DTRACE_JSON_OBJECT;
4013 				}
4014 				break;
4015 			}
4016 
4017 			/*
4018 			 * ERROR: either we hit an unexpected character, or
4019 			 * we reached the end of the object or array without
4020 			 * finding the requested key.
4021 			 */
4022 			return (NULL);
4023 		case DTRACE_JSON_IDENTIFIER:
4024 			if (islower(cc)) {
4025 				*dd++ = cc;
4026 				break;
4027 			}
4028 
4029 			*dd = '\0';
4030 			dd = dest; /* reset string buffer */
4031 
4032 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
4033 			    dtrace_strncmp(dest, "false", 6) == 0 ||
4034 			    dtrace_strncmp(dest, "null", 5) == 0) {
4035 				if (found_key) {
4036 					if (nelems > 1) {
4037 						/*
4038 						 * ERROR: We expected an object,
4039 						 * not this identifier.
4040 						 */
4041 						return (NULL);
4042 					}
4043 					return (dest);
4044 				} else {
4045 					cur--;
4046 					state = DTRACE_JSON_COMMA;
4047 					break;
4048 				}
4049 			}
4050 
4051 			/*
4052 			 * ERROR: we did not recognise the identifier as one
4053 			 * of those in the JSON specification.
4054 			 */
4055 			return (NULL);
4056 		case DTRACE_JSON_NUMBER:
4057 			if (cc == '.') {
4058 				*dd++ = cc;
4059 				state = DTRACE_JSON_NUMBER_FRAC;
4060 				break;
4061 			}
4062 
4063 			if (cc == 'x' || cc == 'X') {
4064 				/*
4065 				 * ERROR: specification explicitly excludes
4066 				 * hexidecimal or octal numbers.
4067 				 */
4068 				return (NULL);
4069 			}
4070 
4071 			/* FALLTHRU */
4072 		case DTRACE_JSON_NUMBER_FRAC:
4073 			if (cc == 'e' || cc == 'E') {
4074 				*dd++ = cc;
4075 				state = DTRACE_JSON_NUMBER_EXP;
4076 				break;
4077 			}
4078 
4079 			if (cc == '+' || cc == '-') {
4080 				/*
4081 				 * ERROR: expect sign as part of exponent only.
4082 				 */
4083 				return (NULL);
4084 			}
4085 			/* FALLTHRU */
4086 		case DTRACE_JSON_NUMBER_EXP:
4087 			if (isdigit(cc) || cc == '+' || cc == '-') {
4088 				*dd++ = cc;
4089 				break;
4090 			}
4091 
4092 			*dd = '\0';
4093 			dd = dest; /* reset string buffer */
4094 			if (found_key) {
4095 				if (nelems > 1) {
4096 					/*
4097 					 * ERROR: We expected an object, not
4098 					 * this number.
4099 					 */
4100 					return (NULL);
4101 				}
4102 				return (dest);
4103 			}
4104 
4105 			cur--;
4106 			state = DTRACE_JSON_COMMA;
4107 			break;
4108 		case DTRACE_JSON_VALUE:
4109 			if (isspace(cc))
4110 				break;
4111 
4112 			if (cc == '{' || cc == '[') {
4113 				if (nelems > 1 && found_key) {
4114 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4115 					/*
4116 					 * If our element selector directs us
4117 					 * to descend into this nested object,
4118 					 * then move to the next selector
4119 					 * element in the list and restart the
4120 					 * state machine.
4121 					 */
4122 					while (*elem != '\0')
4123 						elem++;
4124 					elem++; /* skip the inter-element NUL */
4125 					nelems--;
4126 					dd = dest;
4127 					if (in_array) {
4128 						state = DTRACE_JSON_VALUE;
4129 						array_pos = 0;
4130 						array_elem = dtrace_strtoll(
4131 						    elem, 10, size);
4132 						found_key = array_elem == 0 ?
4133 						    B_TRUE : B_FALSE;
4134 					} else {
4135 						found_key = B_FALSE;
4136 						state = DTRACE_JSON_OBJECT;
4137 					}
4138 					break;
4139 				}
4140 
4141 				/*
4142 				 * Otherwise, we wish to either skip this
4143 				 * nested object or return it in full.
4144 				 */
4145 				if (cc == '[')
4146 					brackets = 1;
4147 				else
4148 					braces = 1;
4149 				*dd++ = cc;
4150 				state = DTRACE_JSON_COLLECT_OBJECT;
4151 				break;
4152 			}
4153 
4154 			if (cc == '"') {
4155 				state = DTRACE_JSON_STRING;
4156 				break;
4157 			}
4158 
4159 			if (islower(cc)) {
4160 				/*
4161 				 * Here we deal with true, false and null.
4162 				 */
4163 				*dd++ = cc;
4164 				state = DTRACE_JSON_IDENTIFIER;
4165 				break;
4166 			}
4167 
4168 			if (cc == '-' || isdigit(cc)) {
4169 				*dd++ = cc;
4170 				state = DTRACE_JSON_NUMBER;
4171 				break;
4172 			}
4173 
4174 			/*
4175 			 * ERROR: unexpected character at start of value.
4176 			 */
4177 			return (NULL);
4178 		case DTRACE_JSON_COLLECT_OBJECT:
4179 			if (cc == '\0')
4180 				/*
4181 				 * ERROR: unexpected end of input.
4182 				 */
4183 				return (NULL);
4184 
4185 			*dd++ = cc;
4186 			if (cc == '"') {
4187 				collect_object = B_TRUE;
4188 				state = DTRACE_JSON_STRING;
4189 				break;
4190 			}
4191 
4192 			if (cc == ']') {
4193 				if (brackets-- == 0) {
4194 					/*
4195 					 * ERROR: unbalanced brackets.
4196 					 */
4197 					return (NULL);
4198 				}
4199 			} else if (cc == '}') {
4200 				if (braces-- == 0) {
4201 					/*
4202 					 * ERROR: unbalanced braces.
4203 					 */
4204 					return (NULL);
4205 				}
4206 			} else if (cc == '{') {
4207 				braces++;
4208 			} else if (cc == '[') {
4209 				brackets++;
4210 			}
4211 
4212 			if (brackets == 0 && braces == 0) {
4213 				if (found_key) {
4214 					*dd = '\0';
4215 					return (dest);
4216 				}
4217 				dd = dest; /* reset string buffer */
4218 				state = DTRACE_JSON_COMMA;
4219 			}
4220 			break;
4221 		}
4222 	}
4223 	return (NULL);
4224 }
4225 
4226 /*
4227  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4228  * Notice that we don't bother validating the proper number of arguments or
4229  * their types in the tuple stack.  This isn't needed because all argument
4230  * interpretation is safe because of our load safety -- the worst that can
4231  * happen is that a bogus program can obtain bogus results.
4232  */
4233 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)4234 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4235     dtrace_key_t *tupregs, int nargs,
4236     dtrace_mstate_t *mstate, dtrace_state_t *state)
4237 {
4238 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4239 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4240 	dtrace_vstate_t *vstate = &state->dts_vstate;
4241 
4242 #ifdef illumos
4243 	union {
4244 		mutex_impl_t mi;
4245 		uint64_t mx;
4246 	} m;
4247 
4248 	union {
4249 		krwlock_t ri;
4250 		uintptr_t rw;
4251 	} r;
4252 #else
4253 	struct thread *lowner;
4254 	union {
4255 		struct lock_object *li;
4256 		uintptr_t lx;
4257 	} l;
4258 #endif
4259 
4260 	switch (subr) {
4261 	case DIF_SUBR_RAND:
4262 		regs[rd] = dtrace_xoroshiro128_plus_next(
4263 		    state->dts_rstate[curcpu]);
4264 		break;
4265 
4266 #ifdef illumos
4267 	case DIF_SUBR_MUTEX_OWNED:
4268 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4269 		    mstate, vstate)) {
4270 			regs[rd] = 0;
4271 			break;
4272 		}
4273 
4274 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4275 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4276 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4277 		else
4278 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4279 		break;
4280 
4281 	case DIF_SUBR_MUTEX_OWNER:
4282 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4283 		    mstate, vstate)) {
4284 			regs[rd] = 0;
4285 			break;
4286 		}
4287 
4288 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4289 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4290 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4291 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4292 		else
4293 			regs[rd] = 0;
4294 		break;
4295 
4296 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4297 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4298 		    mstate, vstate)) {
4299 			regs[rd] = 0;
4300 			break;
4301 		}
4302 
4303 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4304 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4305 		break;
4306 
4307 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4308 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4309 		    mstate, vstate)) {
4310 			regs[rd] = 0;
4311 			break;
4312 		}
4313 
4314 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4315 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4316 		break;
4317 
4318 	case DIF_SUBR_RW_READ_HELD: {
4319 		uintptr_t tmp;
4320 
4321 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4322 		    mstate, vstate)) {
4323 			regs[rd] = 0;
4324 			break;
4325 		}
4326 
4327 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4328 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4329 		break;
4330 	}
4331 
4332 	case DIF_SUBR_RW_WRITE_HELD:
4333 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4334 		    mstate, vstate)) {
4335 			regs[rd] = 0;
4336 			break;
4337 		}
4338 
4339 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4340 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4341 		break;
4342 
4343 	case DIF_SUBR_RW_ISWRITER:
4344 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4345 		    mstate, vstate)) {
4346 			regs[rd] = 0;
4347 			break;
4348 		}
4349 
4350 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4351 		regs[rd] = _RW_ISWRITER(&r.ri);
4352 		break;
4353 
4354 #else /* !illumos */
4355 	case DIF_SUBR_MUTEX_OWNED:
4356 		if (!dtrace_canload(tupregs[0].dttk_value,
4357 			sizeof (struct lock_object), mstate, vstate)) {
4358 			regs[rd] = 0;
4359 			break;
4360 		}
4361 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4362 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4363 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4364 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4365 		break;
4366 
4367 	case DIF_SUBR_MUTEX_OWNER:
4368 		if (!dtrace_canload(tupregs[0].dttk_value,
4369 			sizeof (struct lock_object), mstate, vstate)) {
4370 			regs[rd] = 0;
4371 			break;
4372 		}
4373 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4374 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4375 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4376 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4377 		regs[rd] = (uintptr_t)lowner;
4378 		break;
4379 
4380 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4381 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4382 		    mstate, vstate)) {
4383 			regs[rd] = 0;
4384 			break;
4385 		}
4386 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4387 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4388 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4389 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4390 		break;
4391 
4392 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4393 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4394 		    mstate, vstate)) {
4395 			regs[rd] = 0;
4396 			break;
4397 		}
4398 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4399 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4400 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4401 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4402 		break;
4403 
4404 	case DIF_SUBR_RW_READ_HELD:
4405 	case DIF_SUBR_SX_SHARED_HELD:
4406 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4407 		    mstate, vstate)) {
4408 			regs[rd] = 0;
4409 			break;
4410 		}
4411 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4412 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4413 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4414 		    lowner == NULL;
4415 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4416 		break;
4417 
4418 	case DIF_SUBR_RW_WRITE_HELD:
4419 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
4420 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4421 		    mstate, vstate)) {
4422 			regs[rd] = 0;
4423 			break;
4424 		}
4425 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4426 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4427 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4428 		    lowner != NULL;
4429 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4430 		break;
4431 
4432 	case DIF_SUBR_RW_ISWRITER:
4433 	case DIF_SUBR_SX_ISEXCLUSIVE:
4434 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4435 		    mstate, vstate)) {
4436 			regs[rd] = 0;
4437 			break;
4438 		}
4439 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4440 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4441 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4442 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4443 		regs[rd] = (lowner == curthread);
4444 		break;
4445 #endif /* illumos */
4446 
4447 	case DIF_SUBR_BCOPY: {
4448 		/*
4449 		 * We need to be sure that the destination is in the scratch
4450 		 * region -- no other region is allowed.
4451 		 */
4452 		uintptr_t src = tupregs[0].dttk_value;
4453 		uintptr_t dest = tupregs[1].dttk_value;
4454 		size_t size = tupregs[2].dttk_value;
4455 
4456 		if (!dtrace_inscratch(dest, size, mstate)) {
4457 			*flags |= CPU_DTRACE_BADADDR;
4458 			*illval = regs[rd];
4459 			break;
4460 		}
4461 
4462 		if (!dtrace_canload(src, size, mstate, vstate)) {
4463 			regs[rd] = 0;
4464 			break;
4465 		}
4466 
4467 		dtrace_bcopy((void *)src, (void *)dest, size);
4468 		break;
4469 	}
4470 
4471 	case DIF_SUBR_ALLOCA:
4472 	case DIF_SUBR_COPYIN: {
4473 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4474 		uint64_t size =
4475 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4476 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4477 
4478 		/*
4479 		 * This action doesn't require any credential checks since
4480 		 * probes will not activate in user contexts to which the
4481 		 * enabling user does not have permissions.
4482 		 */
4483 
4484 		/*
4485 		 * Rounding up the user allocation size could have overflowed
4486 		 * a large, bogus allocation (like -1ULL) to 0.
4487 		 */
4488 		if (scratch_size < size ||
4489 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4490 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4491 			regs[rd] = 0;
4492 			break;
4493 		}
4494 
4495 		if (subr == DIF_SUBR_COPYIN) {
4496 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4497 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4498 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4499 		}
4500 
4501 		mstate->dtms_scratch_ptr += scratch_size;
4502 		regs[rd] = dest;
4503 		break;
4504 	}
4505 
4506 	case DIF_SUBR_COPYINTO: {
4507 		uint64_t size = tupregs[1].dttk_value;
4508 		uintptr_t dest = tupregs[2].dttk_value;
4509 
4510 		/*
4511 		 * This action doesn't require any credential checks since
4512 		 * probes will not activate in user contexts to which the
4513 		 * enabling user does not have permissions.
4514 		 */
4515 		if (!dtrace_inscratch(dest, size, mstate)) {
4516 			*flags |= CPU_DTRACE_BADADDR;
4517 			*illval = regs[rd];
4518 			break;
4519 		}
4520 
4521 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4522 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4523 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4524 		break;
4525 	}
4526 
4527 	case DIF_SUBR_COPYINSTR: {
4528 		uintptr_t dest = mstate->dtms_scratch_ptr;
4529 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4530 
4531 		if (nargs > 1 && tupregs[1].dttk_value < size)
4532 			size = tupregs[1].dttk_value + 1;
4533 
4534 		/*
4535 		 * This action doesn't require any credential checks since
4536 		 * probes will not activate in user contexts to which the
4537 		 * enabling user does not have permissions.
4538 		 */
4539 		if (!DTRACE_INSCRATCH(mstate, size)) {
4540 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4541 			regs[rd] = 0;
4542 			break;
4543 		}
4544 
4545 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4546 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4547 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4548 
4549 		((char *)dest)[size - 1] = '\0';
4550 		mstate->dtms_scratch_ptr += size;
4551 		regs[rd] = dest;
4552 		break;
4553 	}
4554 
4555 #ifdef illumos
4556 	case DIF_SUBR_MSGSIZE:
4557 	case DIF_SUBR_MSGDSIZE: {
4558 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4559 		uintptr_t wptr, rptr;
4560 		size_t count = 0;
4561 		int cont = 0;
4562 
4563 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4564 
4565 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4566 			    vstate)) {
4567 				regs[rd] = 0;
4568 				break;
4569 			}
4570 
4571 			wptr = dtrace_loadptr(baddr +
4572 			    offsetof(mblk_t, b_wptr));
4573 
4574 			rptr = dtrace_loadptr(baddr +
4575 			    offsetof(mblk_t, b_rptr));
4576 
4577 			if (wptr < rptr) {
4578 				*flags |= CPU_DTRACE_BADADDR;
4579 				*illval = tupregs[0].dttk_value;
4580 				break;
4581 			}
4582 
4583 			daddr = dtrace_loadptr(baddr +
4584 			    offsetof(mblk_t, b_datap));
4585 
4586 			baddr = dtrace_loadptr(baddr +
4587 			    offsetof(mblk_t, b_cont));
4588 
4589 			/*
4590 			 * We want to prevent against denial-of-service here,
4591 			 * so we're only going to search the list for
4592 			 * dtrace_msgdsize_max mblks.
4593 			 */
4594 			if (cont++ > dtrace_msgdsize_max) {
4595 				*flags |= CPU_DTRACE_ILLOP;
4596 				break;
4597 			}
4598 
4599 			if (subr == DIF_SUBR_MSGDSIZE) {
4600 				if (dtrace_load8(daddr +
4601 				    offsetof(dblk_t, db_type)) != M_DATA)
4602 					continue;
4603 			}
4604 
4605 			count += wptr - rptr;
4606 		}
4607 
4608 		if (!(*flags & CPU_DTRACE_FAULT))
4609 			regs[rd] = count;
4610 
4611 		break;
4612 	}
4613 #endif
4614 
4615 	case DIF_SUBR_PROGENYOF: {
4616 		pid_t pid = tupregs[0].dttk_value;
4617 		proc_t *p;
4618 		int rval = 0;
4619 
4620 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4621 
4622 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4623 #ifdef illumos
4624 			if (p->p_pidp->pid_id == pid) {
4625 #else
4626 			if (p->p_pid == pid) {
4627 #endif
4628 				rval = 1;
4629 				break;
4630 			}
4631 		}
4632 
4633 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4634 
4635 		regs[rd] = rval;
4636 		break;
4637 	}
4638 
4639 	case DIF_SUBR_SPECULATION:
4640 		regs[rd] = dtrace_speculation(state);
4641 		break;
4642 
4643 	case DIF_SUBR_COPYOUT: {
4644 		uintptr_t kaddr = tupregs[0].dttk_value;
4645 		uintptr_t uaddr = tupregs[1].dttk_value;
4646 		uint64_t size = tupregs[2].dttk_value;
4647 
4648 		if (!dtrace_destructive_disallow &&
4649 		    dtrace_priv_proc_control(state) &&
4650 		    !dtrace_istoxic(kaddr, size) &&
4651 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4652 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4653 			dtrace_copyout(kaddr, uaddr, size, flags);
4654 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4655 		}
4656 		break;
4657 	}
4658 
4659 	case DIF_SUBR_COPYOUTSTR: {
4660 		uintptr_t kaddr = tupregs[0].dttk_value;
4661 		uintptr_t uaddr = tupregs[1].dttk_value;
4662 		uint64_t size = tupregs[2].dttk_value;
4663 		size_t lim;
4664 
4665 		if (!dtrace_destructive_disallow &&
4666 		    dtrace_priv_proc_control(state) &&
4667 		    !dtrace_istoxic(kaddr, size) &&
4668 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4669 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4670 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4671 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4672 		}
4673 		break;
4674 	}
4675 
4676 	case DIF_SUBR_STRLEN: {
4677 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4678 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4679 		size_t lim;
4680 
4681 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4682 			regs[rd] = 0;
4683 			break;
4684 		}
4685 
4686 		regs[rd] = dtrace_strlen((char *)addr, lim);
4687 		break;
4688 	}
4689 
4690 	case DIF_SUBR_STRCHR:
4691 	case DIF_SUBR_STRRCHR: {
4692 		/*
4693 		 * We're going to iterate over the string looking for the
4694 		 * specified character.  We will iterate until we have reached
4695 		 * the string length or we have found the character.  If this
4696 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4697 		 * of the specified character instead of the first.
4698 		 */
4699 		uintptr_t addr = tupregs[0].dttk_value;
4700 		uintptr_t addr_limit;
4701 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4702 		size_t lim;
4703 		char c, target = (char)tupregs[1].dttk_value;
4704 
4705 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4706 			regs[rd] = 0;
4707 			break;
4708 		}
4709 		addr_limit = addr + lim;
4710 
4711 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4712 			if ((c = dtrace_load8(addr)) == target) {
4713 				regs[rd] = addr;
4714 
4715 				if (subr == DIF_SUBR_STRCHR)
4716 					break;
4717 			}
4718 
4719 			if (c == '\0')
4720 				break;
4721 		}
4722 		break;
4723 	}
4724 
4725 	case DIF_SUBR_STRSTR:
4726 	case DIF_SUBR_INDEX:
4727 	case DIF_SUBR_RINDEX: {
4728 		/*
4729 		 * We're going to iterate over the string looking for the
4730 		 * specified string.  We will iterate until we have reached
4731 		 * the string length or we have found the string.  (Yes, this
4732 		 * is done in the most naive way possible -- but considering
4733 		 * that the string we're searching for is likely to be
4734 		 * relatively short, the complexity of Rabin-Karp or similar
4735 		 * hardly seems merited.)
4736 		 */
4737 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4738 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4739 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4740 		size_t len = dtrace_strlen(addr, size);
4741 		size_t sublen = dtrace_strlen(substr, size);
4742 		char *limit = addr + len, *orig = addr;
4743 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4744 		int inc = 1;
4745 
4746 		regs[rd] = notfound;
4747 
4748 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4749 			regs[rd] = 0;
4750 			break;
4751 		}
4752 
4753 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4754 		    vstate)) {
4755 			regs[rd] = 0;
4756 			break;
4757 		}
4758 
4759 		/*
4760 		 * strstr() and index()/rindex() have similar semantics if
4761 		 * both strings are the empty string: strstr() returns a
4762 		 * pointer to the (empty) string, and index() and rindex()
4763 		 * both return index 0 (regardless of any position argument).
4764 		 */
4765 		if (sublen == 0 && len == 0) {
4766 			if (subr == DIF_SUBR_STRSTR)
4767 				regs[rd] = (uintptr_t)addr;
4768 			else
4769 				regs[rd] = 0;
4770 			break;
4771 		}
4772 
4773 		if (subr != DIF_SUBR_STRSTR) {
4774 			if (subr == DIF_SUBR_RINDEX) {
4775 				limit = orig - 1;
4776 				addr += len;
4777 				inc = -1;
4778 			}
4779 
4780 			/*
4781 			 * Both index() and rindex() take an optional position
4782 			 * argument that denotes the starting position.
4783 			 */
4784 			if (nargs == 3) {
4785 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4786 
4787 				/*
4788 				 * If the position argument to index() is
4789 				 * negative, Perl implicitly clamps it at
4790 				 * zero.  This semantic is a little surprising
4791 				 * given the special meaning of negative
4792 				 * positions to similar Perl functions like
4793 				 * substr(), but it appears to reflect a
4794 				 * notion that index() can start from a
4795 				 * negative index and increment its way up to
4796 				 * the string.  Given this notion, Perl's
4797 				 * rindex() is at least self-consistent in
4798 				 * that it implicitly clamps positions greater
4799 				 * than the string length to be the string
4800 				 * length.  Where Perl completely loses
4801 				 * coherence, however, is when the specified
4802 				 * substring is the empty string ("").  In
4803 				 * this case, even if the position is
4804 				 * negative, rindex() returns 0 -- and even if
4805 				 * the position is greater than the length,
4806 				 * index() returns the string length.  These
4807 				 * semantics violate the notion that index()
4808 				 * should never return a value less than the
4809 				 * specified position and that rindex() should
4810 				 * never return a value greater than the
4811 				 * specified position.  (One assumes that
4812 				 * these semantics are artifacts of Perl's
4813 				 * implementation and not the results of
4814 				 * deliberate design -- it beggars belief that
4815 				 * even Larry Wall could desire such oddness.)
4816 				 * While in the abstract one would wish for
4817 				 * consistent position semantics across
4818 				 * substr(), index() and rindex() -- or at the
4819 				 * very least self-consistent position
4820 				 * semantics for index() and rindex() -- we
4821 				 * instead opt to keep with the extant Perl
4822 				 * semantics, in all their broken glory.  (Do
4823 				 * we have more desire to maintain Perl's
4824 				 * semantics than Perl does?  Probably.)
4825 				 */
4826 				if (subr == DIF_SUBR_RINDEX) {
4827 					if (pos < 0) {
4828 						if (sublen == 0)
4829 							regs[rd] = 0;
4830 						break;
4831 					}
4832 
4833 					if (pos > len)
4834 						pos = len;
4835 				} else {
4836 					if (pos < 0)
4837 						pos = 0;
4838 
4839 					if (pos >= len) {
4840 						if (sublen == 0)
4841 							regs[rd] = len;
4842 						break;
4843 					}
4844 				}
4845 
4846 				addr = orig + pos;
4847 			}
4848 		}
4849 
4850 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4851 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4852 				if (subr != DIF_SUBR_STRSTR) {
4853 					/*
4854 					 * As D index() and rindex() are
4855 					 * modeled on Perl (and not on awk),
4856 					 * we return a zero-based (and not a
4857 					 * one-based) index.  (For you Perl
4858 					 * weenies: no, we're not going to add
4859 					 * $[ -- and shouldn't you be at a con
4860 					 * or something?)
4861 					 */
4862 					regs[rd] = (uintptr_t)(addr - orig);
4863 					break;
4864 				}
4865 
4866 				ASSERT(subr == DIF_SUBR_STRSTR);
4867 				regs[rd] = (uintptr_t)addr;
4868 				break;
4869 			}
4870 		}
4871 
4872 		break;
4873 	}
4874 
4875 	case DIF_SUBR_STRTOK: {
4876 		uintptr_t addr = tupregs[0].dttk_value;
4877 		uintptr_t tokaddr = tupregs[1].dttk_value;
4878 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4879 		uintptr_t limit, toklimit;
4880 		size_t clim;
4881 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4882 		char *dest = (char *)mstate->dtms_scratch_ptr;
4883 		int i;
4884 
4885 		/*
4886 		 * Check both the token buffer and (later) the input buffer,
4887 		 * since both could be non-scratch addresses.
4888 		 */
4889 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4890 			regs[rd] = 0;
4891 			break;
4892 		}
4893 		toklimit = tokaddr + clim;
4894 
4895 		if (!DTRACE_INSCRATCH(mstate, size)) {
4896 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4897 			regs[rd] = 0;
4898 			break;
4899 		}
4900 
4901 		if (addr == 0) {
4902 			/*
4903 			 * If the address specified is NULL, we use our saved
4904 			 * strtok pointer from the mstate.  Note that this
4905 			 * means that the saved strtok pointer is _only_
4906 			 * valid within multiple enablings of the same probe --
4907 			 * it behaves like an implicit clause-local variable.
4908 			 */
4909 			addr = mstate->dtms_strtok;
4910 			limit = mstate->dtms_strtok_limit;
4911 		} else {
4912 			/*
4913 			 * If the user-specified address is non-NULL we must
4914 			 * access check it.  This is the only time we have
4915 			 * a chance to do so, since this address may reside
4916 			 * in the string table of this clause-- future calls
4917 			 * (when we fetch addr from mstate->dtms_strtok)
4918 			 * would fail this access check.
4919 			 */
4920 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4921 			    vstate)) {
4922 				regs[rd] = 0;
4923 				break;
4924 			}
4925 			limit = addr + clim;
4926 		}
4927 
4928 		/*
4929 		 * First, zero the token map, and then process the token
4930 		 * string -- setting a bit in the map for every character
4931 		 * found in the token string.
4932 		 */
4933 		for (i = 0; i < sizeof (tokmap); i++)
4934 			tokmap[i] = 0;
4935 
4936 		for (; tokaddr < toklimit; tokaddr++) {
4937 			if ((c = dtrace_load8(tokaddr)) == '\0')
4938 				break;
4939 
4940 			ASSERT((c >> 3) < sizeof (tokmap));
4941 			tokmap[c >> 3] |= (1 << (c & 0x7));
4942 		}
4943 
4944 		for (; addr < limit; addr++) {
4945 			/*
4946 			 * We're looking for a character that is _not_
4947 			 * contained in the token string.
4948 			 */
4949 			if ((c = dtrace_load8(addr)) == '\0')
4950 				break;
4951 
4952 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4953 				break;
4954 		}
4955 
4956 		if (c == '\0') {
4957 			/*
4958 			 * We reached the end of the string without finding
4959 			 * any character that was not in the token string.
4960 			 * We return NULL in this case, and we set the saved
4961 			 * address to NULL as well.
4962 			 */
4963 			regs[rd] = 0;
4964 			mstate->dtms_strtok = 0;
4965 			mstate->dtms_strtok_limit = 0;
4966 			break;
4967 		}
4968 
4969 		/*
4970 		 * From here on, we're copying into the destination string.
4971 		 */
4972 		for (i = 0; addr < limit && i < size - 1; addr++) {
4973 			if ((c = dtrace_load8(addr)) == '\0')
4974 				break;
4975 
4976 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4977 				break;
4978 
4979 			ASSERT(i < size);
4980 			dest[i++] = c;
4981 		}
4982 
4983 		ASSERT(i < size);
4984 		dest[i] = '\0';
4985 		regs[rd] = (uintptr_t)dest;
4986 		mstate->dtms_scratch_ptr += size;
4987 		mstate->dtms_strtok = addr;
4988 		mstate->dtms_strtok_limit = limit;
4989 		break;
4990 	}
4991 
4992 	case DIF_SUBR_SUBSTR: {
4993 		uintptr_t s = tupregs[0].dttk_value;
4994 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4995 		char *d = (char *)mstate->dtms_scratch_ptr;
4996 		int64_t index = (int64_t)tupregs[1].dttk_value;
4997 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4998 		size_t len = dtrace_strlen((char *)s, size);
4999 		int64_t i;
5000 
5001 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5002 			regs[rd] = 0;
5003 			break;
5004 		}
5005 
5006 		if (!DTRACE_INSCRATCH(mstate, size)) {
5007 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5008 			regs[rd] = 0;
5009 			break;
5010 		}
5011 
5012 		if (nargs <= 2)
5013 			remaining = (int64_t)size;
5014 
5015 		if (index < 0) {
5016 			index += len;
5017 
5018 			if (index < 0 && index + remaining > 0) {
5019 				remaining += index;
5020 				index = 0;
5021 			}
5022 		}
5023 
5024 		if (index >= len || index < 0) {
5025 			remaining = 0;
5026 		} else if (remaining < 0) {
5027 			remaining += len - index;
5028 		} else if (index + remaining > size) {
5029 			remaining = size - index;
5030 		}
5031 
5032 		for (i = 0; i < remaining; i++) {
5033 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5034 				break;
5035 		}
5036 
5037 		d[i] = '\0';
5038 
5039 		mstate->dtms_scratch_ptr += size;
5040 		regs[rd] = (uintptr_t)d;
5041 		break;
5042 	}
5043 
5044 	case DIF_SUBR_JSON: {
5045 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5046 		uintptr_t json = tupregs[0].dttk_value;
5047 		size_t jsonlen = dtrace_strlen((char *)json, size);
5048 		uintptr_t elem = tupregs[1].dttk_value;
5049 		size_t elemlen = dtrace_strlen((char *)elem, size);
5050 
5051 		char *dest = (char *)mstate->dtms_scratch_ptr;
5052 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5053 		char *ee = elemlist;
5054 		int nelems = 1;
5055 		uintptr_t cur;
5056 
5057 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5058 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5059 			regs[rd] = 0;
5060 			break;
5061 		}
5062 
5063 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5064 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5065 			regs[rd] = 0;
5066 			break;
5067 		}
5068 
5069 		/*
5070 		 * Read the element selector and split it up into a packed list
5071 		 * of strings.
5072 		 */
5073 		for (cur = elem; cur < elem + elemlen; cur++) {
5074 			char cc = dtrace_load8(cur);
5075 
5076 			if (cur == elem && cc == '[') {
5077 				/*
5078 				 * If the first element selector key is
5079 				 * actually an array index then ignore the
5080 				 * bracket.
5081 				 */
5082 				continue;
5083 			}
5084 
5085 			if (cc == ']')
5086 				continue;
5087 
5088 			if (cc == '.' || cc == '[') {
5089 				nelems++;
5090 				cc = '\0';
5091 			}
5092 
5093 			*ee++ = cc;
5094 		}
5095 		*ee++ = '\0';
5096 
5097 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5098 		    nelems, dest)) != 0)
5099 			mstate->dtms_scratch_ptr += jsonlen + 1;
5100 		break;
5101 	}
5102 
5103 	case DIF_SUBR_TOUPPER:
5104 	case DIF_SUBR_TOLOWER: {
5105 		uintptr_t s = tupregs[0].dttk_value;
5106 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5107 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5108 		size_t len = dtrace_strlen((char *)s, size);
5109 		char lower, upper, convert;
5110 		int64_t i;
5111 
5112 		if (subr == DIF_SUBR_TOUPPER) {
5113 			lower = 'a';
5114 			upper = 'z';
5115 			convert = 'A';
5116 		} else {
5117 			lower = 'A';
5118 			upper = 'Z';
5119 			convert = 'a';
5120 		}
5121 
5122 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5123 			regs[rd] = 0;
5124 			break;
5125 		}
5126 
5127 		if (!DTRACE_INSCRATCH(mstate, size)) {
5128 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5129 			regs[rd] = 0;
5130 			break;
5131 		}
5132 
5133 		for (i = 0; i < size - 1; i++) {
5134 			if ((c = dtrace_load8(s + i)) == '\0')
5135 				break;
5136 
5137 			if (c >= lower && c <= upper)
5138 				c = convert + (c - lower);
5139 
5140 			dest[i] = c;
5141 		}
5142 
5143 		ASSERT(i < size);
5144 		dest[i] = '\0';
5145 		regs[rd] = (uintptr_t)dest;
5146 		mstate->dtms_scratch_ptr += size;
5147 		break;
5148 	}
5149 
5150 #ifdef illumos
5151 	case DIF_SUBR_GETMAJOR:
5152 #ifdef _LP64
5153 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5154 #else
5155 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5156 #endif
5157 		break;
5158 
5159 	case DIF_SUBR_GETMINOR:
5160 #ifdef _LP64
5161 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5162 #else
5163 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
5164 #endif
5165 		break;
5166 
5167 	case DIF_SUBR_DDI_PATHNAME: {
5168 		/*
5169 		 * This one is a galactic mess.  We are going to roughly
5170 		 * emulate ddi_pathname(), but it's made more complicated
5171 		 * by the fact that we (a) want to include the minor name and
5172 		 * (b) must proceed iteratively instead of recursively.
5173 		 */
5174 		uintptr_t dest = mstate->dtms_scratch_ptr;
5175 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5176 		char *start = (char *)dest, *end = start + size - 1;
5177 		uintptr_t daddr = tupregs[0].dttk_value;
5178 		int64_t minor = (int64_t)tupregs[1].dttk_value;
5179 		char *s;
5180 		int i, len, depth = 0;
5181 
5182 		/*
5183 		 * Due to all the pointer jumping we do and context we must
5184 		 * rely upon, we just mandate that the user must have kernel
5185 		 * read privileges to use this routine.
5186 		 */
5187 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5188 			*flags |= CPU_DTRACE_KPRIV;
5189 			*illval = daddr;
5190 			regs[rd] = 0;
5191 		}
5192 
5193 		if (!DTRACE_INSCRATCH(mstate, size)) {
5194 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5195 			regs[rd] = 0;
5196 			break;
5197 		}
5198 
5199 		*end = '\0';
5200 
5201 		/*
5202 		 * We want to have a name for the minor.  In order to do this,
5203 		 * we need to walk the minor list from the devinfo.  We want
5204 		 * to be sure that we don't infinitely walk a circular list,
5205 		 * so we check for circularity by sending a scout pointer
5206 		 * ahead two elements for every element that we iterate over;
5207 		 * if the list is circular, these will ultimately point to the
5208 		 * same element.  You may recognize this little trick as the
5209 		 * answer to a stupid interview question -- one that always
5210 		 * seems to be asked by those who had to have it laboriously
5211 		 * explained to them, and who can't even concisely describe
5212 		 * the conditions under which one would be forced to resort to
5213 		 * this technique.  Needless to say, those conditions are
5214 		 * found here -- and probably only here.  Is this the only use
5215 		 * of this infamous trick in shipping, production code?  If it
5216 		 * isn't, it probably should be...
5217 		 */
5218 		if (minor != -1) {
5219 			uintptr_t maddr = dtrace_loadptr(daddr +
5220 			    offsetof(struct dev_info, devi_minor));
5221 
5222 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5223 			uintptr_t name = offsetof(struct ddi_minor_data,
5224 			    d_minor) + offsetof(struct ddi_minor, name);
5225 			uintptr_t dev = offsetof(struct ddi_minor_data,
5226 			    d_minor) + offsetof(struct ddi_minor, dev);
5227 			uintptr_t scout;
5228 
5229 			if (maddr != NULL)
5230 				scout = dtrace_loadptr(maddr + next);
5231 
5232 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5233 				uint64_t m;
5234 #ifdef _LP64
5235 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5236 #else
5237 				m = dtrace_load32(maddr + dev) & MAXMIN;
5238 #endif
5239 				if (m != minor) {
5240 					maddr = dtrace_loadptr(maddr + next);
5241 
5242 					if (scout == NULL)
5243 						continue;
5244 
5245 					scout = dtrace_loadptr(scout + next);
5246 
5247 					if (scout == NULL)
5248 						continue;
5249 
5250 					scout = dtrace_loadptr(scout + next);
5251 
5252 					if (scout == NULL)
5253 						continue;
5254 
5255 					if (scout == maddr) {
5256 						*flags |= CPU_DTRACE_ILLOP;
5257 						break;
5258 					}
5259 
5260 					continue;
5261 				}
5262 
5263 				/*
5264 				 * We have the minor data.  Now we need to
5265 				 * copy the minor's name into the end of the
5266 				 * pathname.
5267 				 */
5268 				s = (char *)dtrace_loadptr(maddr + name);
5269 				len = dtrace_strlen(s, size);
5270 
5271 				if (*flags & CPU_DTRACE_FAULT)
5272 					break;
5273 
5274 				if (len != 0) {
5275 					if ((end -= (len + 1)) < start)
5276 						break;
5277 
5278 					*end = ':';
5279 				}
5280 
5281 				for (i = 1; i <= len; i++)
5282 					end[i] = dtrace_load8((uintptr_t)s++);
5283 				break;
5284 			}
5285 		}
5286 
5287 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5288 			ddi_node_state_t devi_state;
5289 
5290 			devi_state = dtrace_load32(daddr +
5291 			    offsetof(struct dev_info, devi_node_state));
5292 
5293 			if (*flags & CPU_DTRACE_FAULT)
5294 				break;
5295 
5296 			if (devi_state >= DS_INITIALIZED) {
5297 				s = (char *)dtrace_loadptr(daddr +
5298 				    offsetof(struct dev_info, devi_addr));
5299 				len = dtrace_strlen(s, size);
5300 
5301 				if (*flags & CPU_DTRACE_FAULT)
5302 					break;
5303 
5304 				if (len != 0) {
5305 					if ((end -= (len + 1)) < start)
5306 						break;
5307 
5308 					*end = '@';
5309 				}
5310 
5311 				for (i = 1; i <= len; i++)
5312 					end[i] = dtrace_load8((uintptr_t)s++);
5313 			}
5314 
5315 			/*
5316 			 * Now for the node name...
5317 			 */
5318 			s = (char *)dtrace_loadptr(daddr +
5319 			    offsetof(struct dev_info, devi_node_name));
5320 
5321 			daddr = dtrace_loadptr(daddr +
5322 			    offsetof(struct dev_info, devi_parent));
5323 
5324 			/*
5325 			 * If our parent is NULL (that is, if we're the root
5326 			 * node), we're going to use the special path
5327 			 * "devices".
5328 			 */
5329 			if (daddr == 0)
5330 				s = "devices";
5331 
5332 			len = dtrace_strlen(s, size);
5333 			if (*flags & CPU_DTRACE_FAULT)
5334 				break;
5335 
5336 			if ((end -= (len + 1)) < start)
5337 				break;
5338 
5339 			for (i = 1; i <= len; i++)
5340 				end[i] = dtrace_load8((uintptr_t)s++);
5341 			*end = '/';
5342 
5343 			if (depth++ > dtrace_devdepth_max) {
5344 				*flags |= CPU_DTRACE_ILLOP;
5345 				break;
5346 			}
5347 		}
5348 
5349 		if (end < start)
5350 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5351 
5352 		if (daddr == 0) {
5353 			regs[rd] = (uintptr_t)end;
5354 			mstate->dtms_scratch_ptr += size;
5355 		}
5356 
5357 		break;
5358 	}
5359 #endif
5360 
5361 	case DIF_SUBR_STRJOIN: {
5362 		char *d = (char *)mstate->dtms_scratch_ptr;
5363 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5364 		uintptr_t s1 = tupregs[0].dttk_value;
5365 		uintptr_t s2 = tupregs[1].dttk_value;
5366 		int i = 0, j = 0;
5367 		size_t lim1, lim2;
5368 		char c;
5369 
5370 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5371 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5372 			regs[rd] = 0;
5373 			break;
5374 		}
5375 
5376 		if (!DTRACE_INSCRATCH(mstate, size)) {
5377 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5378 			regs[rd] = 0;
5379 			break;
5380 		}
5381 
5382 		for (;;) {
5383 			if (i >= size) {
5384 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5385 				regs[rd] = 0;
5386 				break;
5387 			}
5388 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5389 			if ((d[i++] = c) == '\0') {
5390 				i--;
5391 				break;
5392 			}
5393 		}
5394 
5395 		for (;;) {
5396 			if (i >= size) {
5397 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5398 				regs[rd] = 0;
5399 				break;
5400 			}
5401 
5402 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5403 			if ((d[i++] = c) == '\0')
5404 				break;
5405 		}
5406 
5407 		if (i < size) {
5408 			mstate->dtms_scratch_ptr += i;
5409 			regs[rd] = (uintptr_t)d;
5410 		}
5411 
5412 		break;
5413 	}
5414 
5415 	case DIF_SUBR_STRTOLL: {
5416 		uintptr_t s = tupregs[0].dttk_value;
5417 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5418 		size_t lim;
5419 		int base = 10;
5420 
5421 		if (nargs > 1) {
5422 			if ((base = tupregs[1].dttk_value) <= 1 ||
5423 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5424 				*flags |= CPU_DTRACE_ILLOP;
5425 				break;
5426 			}
5427 		}
5428 
5429 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5430 			regs[rd] = INT64_MIN;
5431 			break;
5432 		}
5433 
5434 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5435 		break;
5436 	}
5437 
5438 	case DIF_SUBR_LLTOSTR: {
5439 		int64_t i = (int64_t)tupregs[0].dttk_value;
5440 		uint64_t val, digit;
5441 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5442 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5443 		int base = 10;
5444 
5445 		if (nargs > 1) {
5446 			if ((base = tupregs[1].dttk_value) <= 1 ||
5447 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5448 				*flags |= CPU_DTRACE_ILLOP;
5449 				break;
5450 			}
5451 		}
5452 
5453 		val = (base == 10 && i < 0) ? i * -1 : i;
5454 
5455 		if (!DTRACE_INSCRATCH(mstate, size)) {
5456 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5457 			regs[rd] = 0;
5458 			break;
5459 		}
5460 
5461 		for (*end-- = '\0'; val; val /= base) {
5462 			if ((digit = val % base) <= '9' - '0') {
5463 				*end-- = '0' + digit;
5464 			} else {
5465 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5466 			}
5467 		}
5468 
5469 		if (i == 0 && base == 16)
5470 			*end-- = '0';
5471 
5472 		if (base == 16)
5473 			*end-- = 'x';
5474 
5475 		if (i == 0 || base == 8 || base == 16)
5476 			*end-- = '0';
5477 
5478 		if (i < 0 && base == 10)
5479 			*end-- = '-';
5480 
5481 		regs[rd] = (uintptr_t)end + 1;
5482 		mstate->dtms_scratch_ptr += size;
5483 		break;
5484 	}
5485 
5486 	case DIF_SUBR_HTONS:
5487 	case DIF_SUBR_NTOHS:
5488 #if BYTE_ORDER == BIG_ENDIAN
5489 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5490 #else
5491 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5492 #endif
5493 		break;
5494 
5495 
5496 	case DIF_SUBR_HTONL:
5497 	case DIF_SUBR_NTOHL:
5498 #if BYTE_ORDER == BIG_ENDIAN
5499 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5500 #else
5501 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5502 #endif
5503 		break;
5504 
5505 
5506 	case DIF_SUBR_HTONLL:
5507 	case DIF_SUBR_NTOHLL:
5508 #if BYTE_ORDER == BIG_ENDIAN
5509 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5510 #else
5511 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5512 #endif
5513 		break;
5514 
5515 
5516 	case DIF_SUBR_DIRNAME:
5517 	case DIF_SUBR_BASENAME: {
5518 		char *dest = (char *)mstate->dtms_scratch_ptr;
5519 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5520 		uintptr_t src = tupregs[0].dttk_value;
5521 		int i, j, len = dtrace_strlen((char *)src, size);
5522 		int lastbase = -1, firstbase = -1, lastdir = -1;
5523 		int start, end;
5524 
5525 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5526 			regs[rd] = 0;
5527 			break;
5528 		}
5529 
5530 		if (!DTRACE_INSCRATCH(mstate, size)) {
5531 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5532 			regs[rd] = 0;
5533 			break;
5534 		}
5535 
5536 		/*
5537 		 * The basename and dirname for a zero-length string is
5538 		 * defined to be "."
5539 		 */
5540 		if (len == 0) {
5541 			len = 1;
5542 			src = (uintptr_t)".";
5543 		}
5544 
5545 		/*
5546 		 * Start from the back of the string, moving back toward the
5547 		 * front until we see a character that isn't a slash.  That
5548 		 * character is the last character in the basename.
5549 		 */
5550 		for (i = len - 1; i >= 0; i--) {
5551 			if (dtrace_load8(src + i) != '/')
5552 				break;
5553 		}
5554 
5555 		if (i >= 0)
5556 			lastbase = i;
5557 
5558 		/*
5559 		 * Starting from the last character in the basename, move
5560 		 * towards the front until we find a slash.  The character
5561 		 * that we processed immediately before that is the first
5562 		 * character in the basename.
5563 		 */
5564 		for (; i >= 0; i--) {
5565 			if (dtrace_load8(src + i) == '/')
5566 				break;
5567 		}
5568 
5569 		if (i >= 0)
5570 			firstbase = i + 1;
5571 
5572 		/*
5573 		 * Now keep going until we find a non-slash character.  That
5574 		 * character is the last character in the dirname.
5575 		 */
5576 		for (; i >= 0; i--) {
5577 			if (dtrace_load8(src + i) != '/')
5578 				break;
5579 		}
5580 
5581 		if (i >= 0)
5582 			lastdir = i;
5583 
5584 		ASSERT(!(lastbase == -1 && firstbase != -1));
5585 		ASSERT(!(firstbase == -1 && lastdir != -1));
5586 
5587 		if (lastbase == -1) {
5588 			/*
5589 			 * We didn't find a non-slash character.  We know that
5590 			 * the length is non-zero, so the whole string must be
5591 			 * slashes.  In either the dirname or the basename
5592 			 * case, we return '/'.
5593 			 */
5594 			ASSERT(firstbase == -1);
5595 			firstbase = lastbase = lastdir = 0;
5596 		}
5597 
5598 		if (firstbase == -1) {
5599 			/*
5600 			 * The entire string consists only of a basename
5601 			 * component.  If we're looking for dirname, we need
5602 			 * to change our string to be just "."; if we're
5603 			 * looking for a basename, we'll just set the first
5604 			 * character of the basename to be 0.
5605 			 */
5606 			if (subr == DIF_SUBR_DIRNAME) {
5607 				ASSERT(lastdir == -1);
5608 				src = (uintptr_t)".";
5609 				lastdir = 0;
5610 			} else {
5611 				firstbase = 0;
5612 			}
5613 		}
5614 
5615 		if (subr == DIF_SUBR_DIRNAME) {
5616 			if (lastdir == -1) {
5617 				/*
5618 				 * We know that we have a slash in the name --
5619 				 * or lastdir would be set to 0, above.  And
5620 				 * because lastdir is -1, we know that this
5621 				 * slash must be the first character.  (That
5622 				 * is, the full string must be of the form
5623 				 * "/basename".)  In this case, the last
5624 				 * character of the directory name is 0.
5625 				 */
5626 				lastdir = 0;
5627 			}
5628 
5629 			start = 0;
5630 			end = lastdir;
5631 		} else {
5632 			ASSERT(subr == DIF_SUBR_BASENAME);
5633 			ASSERT(firstbase != -1 && lastbase != -1);
5634 			start = firstbase;
5635 			end = lastbase;
5636 		}
5637 
5638 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5639 			dest[j] = dtrace_load8(src + i);
5640 
5641 		dest[j] = '\0';
5642 		regs[rd] = (uintptr_t)dest;
5643 		mstate->dtms_scratch_ptr += size;
5644 		break;
5645 	}
5646 
5647 	case DIF_SUBR_GETF: {
5648 		uintptr_t fd = tupregs[0].dttk_value;
5649 		struct filedesc *fdp;
5650 		file_t *fp;
5651 
5652 		if (!dtrace_priv_proc(state)) {
5653 			regs[rd] = 0;
5654 			break;
5655 		}
5656 		fdp = curproc->p_fd;
5657 		FILEDESC_SLOCK(fdp);
5658 		fp = fget_locked(fdp, fd);
5659 		mstate->dtms_getf = fp;
5660 		regs[rd] = (uintptr_t)fp;
5661 		FILEDESC_SUNLOCK(fdp);
5662 		break;
5663 	}
5664 
5665 	case DIF_SUBR_CLEANPATH: {
5666 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5667 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5668 		uintptr_t src = tupregs[0].dttk_value;
5669 		size_t lim;
5670 		int i = 0, j = 0;
5671 #ifdef illumos
5672 		zone_t *z;
5673 #endif
5674 
5675 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5676 			regs[rd] = 0;
5677 			break;
5678 		}
5679 
5680 		if (!DTRACE_INSCRATCH(mstate, size)) {
5681 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5682 			regs[rd] = 0;
5683 			break;
5684 		}
5685 
5686 		/*
5687 		 * Move forward, loading each character.
5688 		 */
5689 		do {
5690 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5691 next:
5692 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5693 				break;
5694 
5695 			if (c != '/') {
5696 				dest[j++] = c;
5697 				continue;
5698 			}
5699 
5700 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5701 
5702 			if (c == '/') {
5703 				/*
5704 				 * We have two slashes -- we can just advance
5705 				 * to the next character.
5706 				 */
5707 				goto next;
5708 			}
5709 
5710 			if (c != '.') {
5711 				/*
5712 				 * This is not "." and it's not ".." -- we can
5713 				 * just store the "/" and this character and
5714 				 * drive on.
5715 				 */
5716 				dest[j++] = '/';
5717 				dest[j++] = c;
5718 				continue;
5719 			}
5720 
5721 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5722 
5723 			if (c == '/') {
5724 				/*
5725 				 * This is a "/./" component.  We're not going
5726 				 * to store anything in the destination buffer;
5727 				 * we're just going to go to the next component.
5728 				 */
5729 				goto next;
5730 			}
5731 
5732 			if (c != '.') {
5733 				/*
5734 				 * This is not ".." -- we can just store the
5735 				 * "/." and this character and continue
5736 				 * processing.
5737 				 */
5738 				dest[j++] = '/';
5739 				dest[j++] = '.';
5740 				dest[j++] = c;
5741 				continue;
5742 			}
5743 
5744 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5745 
5746 			if (c != '/' && c != '\0') {
5747 				/*
5748 				 * This is not ".." -- it's "..[mumble]".
5749 				 * We'll store the "/.." and this character
5750 				 * and continue processing.
5751 				 */
5752 				dest[j++] = '/';
5753 				dest[j++] = '.';
5754 				dest[j++] = '.';
5755 				dest[j++] = c;
5756 				continue;
5757 			}
5758 
5759 			/*
5760 			 * This is "/../" or "/..\0".  We need to back up
5761 			 * our destination pointer until we find a "/".
5762 			 */
5763 			i--;
5764 			while (j != 0 && dest[--j] != '/')
5765 				continue;
5766 
5767 			if (c == '\0')
5768 				dest[++j] = '/';
5769 		} while (c != '\0');
5770 
5771 		dest[j] = '\0';
5772 
5773 #ifdef illumos
5774 		if (mstate->dtms_getf != NULL &&
5775 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5776 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5777 			/*
5778 			 * If we've done a getf() as a part of this ECB and we
5779 			 * don't have kernel access (and we're not in the global
5780 			 * zone), check if the path we cleaned up begins with
5781 			 * the zone's root path, and trim it off if so.  Note
5782 			 * that this is an output cleanliness issue, not a
5783 			 * security issue: knowing one's zone root path does
5784 			 * not enable privilege escalation.
5785 			 */
5786 			if (strstr(dest, z->zone_rootpath) == dest)
5787 				dest += strlen(z->zone_rootpath) - 1;
5788 		}
5789 #endif
5790 
5791 		regs[rd] = (uintptr_t)dest;
5792 		mstate->dtms_scratch_ptr += size;
5793 		break;
5794 	}
5795 
5796 	case DIF_SUBR_INET_NTOA:
5797 	case DIF_SUBR_INET_NTOA6:
5798 	case DIF_SUBR_INET_NTOP: {
5799 		size_t size;
5800 		int af, argi, i;
5801 		char *base, *end;
5802 
5803 		if (subr == DIF_SUBR_INET_NTOP) {
5804 			af = (int)tupregs[0].dttk_value;
5805 			argi = 1;
5806 		} else {
5807 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5808 			argi = 0;
5809 		}
5810 
5811 		if (af == AF_INET) {
5812 			ipaddr_t ip4;
5813 			uint8_t *ptr8, val;
5814 
5815 			if (!dtrace_canload(tupregs[argi].dttk_value,
5816 			    sizeof (ipaddr_t), mstate, vstate)) {
5817 				regs[rd] = 0;
5818 				break;
5819 			}
5820 
5821 			/*
5822 			 * Safely load the IPv4 address.
5823 			 */
5824 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5825 
5826 			/*
5827 			 * Check an IPv4 string will fit in scratch.
5828 			 */
5829 			size = INET_ADDRSTRLEN;
5830 			if (!DTRACE_INSCRATCH(mstate, size)) {
5831 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5832 				regs[rd] = 0;
5833 				break;
5834 			}
5835 			base = (char *)mstate->dtms_scratch_ptr;
5836 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5837 
5838 			/*
5839 			 * Stringify as a dotted decimal quad.
5840 			 */
5841 			*end-- = '\0';
5842 			ptr8 = (uint8_t *)&ip4;
5843 			for (i = 3; i >= 0; i--) {
5844 				val = ptr8[i];
5845 
5846 				if (val == 0) {
5847 					*end-- = '0';
5848 				} else {
5849 					for (; val; val /= 10) {
5850 						*end-- = '0' + (val % 10);
5851 					}
5852 				}
5853 
5854 				if (i > 0)
5855 					*end-- = '.';
5856 			}
5857 			ASSERT(end + 1 >= base);
5858 
5859 		} else if (af == AF_INET6) {
5860 			struct in6_addr ip6;
5861 			int firstzero, tryzero, numzero, v6end;
5862 			uint16_t val;
5863 			const char digits[] = "0123456789abcdef";
5864 
5865 			/*
5866 			 * Stringify using RFC 1884 convention 2 - 16 bit
5867 			 * hexadecimal values with a zero-run compression.
5868 			 * Lower case hexadecimal digits are used.
5869 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5870 			 * The IPv4 embedded form is returned for inet_ntop,
5871 			 * just the IPv4 string is returned for inet_ntoa6.
5872 			 */
5873 
5874 			if (!dtrace_canload(tupregs[argi].dttk_value,
5875 			    sizeof (struct in6_addr), mstate, vstate)) {
5876 				regs[rd] = 0;
5877 				break;
5878 			}
5879 
5880 			/*
5881 			 * Safely load the IPv6 address.
5882 			 */
5883 			dtrace_bcopy(
5884 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5885 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5886 
5887 			/*
5888 			 * Check an IPv6 string will fit in scratch.
5889 			 */
5890 			size = INET6_ADDRSTRLEN;
5891 			if (!DTRACE_INSCRATCH(mstate, size)) {
5892 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5893 				regs[rd] = 0;
5894 				break;
5895 			}
5896 			base = (char *)mstate->dtms_scratch_ptr;
5897 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5898 			*end-- = '\0';
5899 
5900 			/*
5901 			 * Find the longest run of 16 bit zero values
5902 			 * for the single allowed zero compression - "::".
5903 			 */
5904 			firstzero = -1;
5905 			tryzero = -1;
5906 			numzero = 1;
5907 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5908 #ifdef illumos
5909 				if (ip6._S6_un._S6_u8[i] == 0 &&
5910 #else
5911 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5912 #endif
5913 				    tryzero == -1 && i % 2 == 0) {
5914 					tryzero = i;
5915 					continue;
5916 				}
5917 
5918 				if (tryzero != -1 &&
5919 #ifdef illumos
5920 				    (ip6._S6_un._S6_u8[i] != 0 ||
5921 #else
5922 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5923 #endif
5924 				    i == sizeof (struct in6_addr) - 1)) {
5925 
5926 					if (i - tryzero <= numzero) {
5927 						tryzero = -1;
5928 						continue;
5929 					}
5930 
5931 					firstzero = tryzero;
5932 					numzero = i - i % 2 - tryzero;
5933 					tryzero = -1;
5934 
5935 #ifdef illumos
5936 					if (ip6._S6_un._S6_u8[i] == 0 &&
5937 #else
5938 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5939 #endif
5940 					    i == sizeof (struct in6_addr) - 1)
5941 						numzero += 2;
5942 				}
5943 			}
5944 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5945 
5946 			/*
5947 			 * Check for an IPv4 embedded address.
5948 			 */
5949 			v6end = sizeof (struct in6_addr) - 2;
5950 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5951 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5952 				for (i = sizeof (struct in6_addr) - 1;
5953 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5954 					ASSERT(end >= base);
5955 
5956 #ifdef illumos
5957 					val = ip6._S6_un._S6_u8[i];
5958 #else
5959 					val = ip6.__u6_addr.__u6_addr8[i];
5960 #endif
5961 
5962 					if (val == 0) {
5963 						*end-- = '0';
5964 					} else {
5965 						for (; val; val /= 10) {
5966 							*end-- = '0' + val % 10;
5967 						}
5968 					}
5969 
5970 					if (i > DTRACE_V4MAPPED_OFFSET)
5971 						*end-- = '.';
5972 				}
5973 
5974 				if (subr == DIF_SUBR_INET_NTOA6)
5975 					goto inetout;
5976 
5977 				/*
5978 				 * Set v6end to skip the IPv4 address that
5979 				 * we have already stringified.
5980 				 */
5981 				v6end = 10;
5982 			}
5983 
5984 			/*
5985 			 * Build the IPv6 string by working through the
5986 			 * address in reverse.
5987 			 */
5988 			for (i = v6end; i >= 0; i -= 2) {
5989 				ASSERT(end >= base);
5990 
5991 				if (i == firstzero + numzero - 2) {
5992 					*end-- = ':';
5993 					*end-- = ':';
5994 					i -= numzero - 2;
5995 					continue;
5996 				}
5997 
5998 				if (i < 14 && i != firstzero - 2)
5999 					*end-- = ':';
6000 
6001 #ifdef illumos
6002 				val = (ip6._S6_un._S6_u8[i] << 8) +
6003 				    ip6._S6_un._S6_u8[i + 1];
6004 #else
6005 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6006 				    ip6.__u6_addr.__u6_addr8[i + 1];
6007 #endif
6008 
6009 				if (val == 0) {
6010 					*end-- = '0';
6011 				} else {
6012 					for (; val; val /= 16) {
6013 						*end-- = digits[val % 16];
6014 					}
6015 				}
6016 			}
6017 			ASSERT(end + 1 >= base);
6018 
6019 		} else {
6020 			/*
6021 			 * The user didn't use AH_INET or AH_INET6.
6022 			 */
6023 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6024 			regs[rd] = 0;
6025 			break;
6026 		}
6027 
6028 inetout:	regs[rd] = (uintptr_t)end + 1;
6029 		mstate->dtms_scratch_ptr += size;
6030 		break;
6031 	}
6032 
6033 	case DIF_SUBR_MEMREF: {
6034 		uintptr_t size = 2 * sizeof(uintptr_t);
6035 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6036 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6037 
6038 		/* address and length */
6039 		memref[0] = tupregs[0].dttk_value;
6040 		memref[1] = tupregs[1].dttk_value;
6041 
6042 		regs[rd] = (uintptr_t) memref;
6043 		mstate->dtms_scratch_ptr += scratch_size;
6044 		break;
6045 	}
6046 
6047 #ifndef illumos
6048 	case DIF_SUBR_MEMSTR: {
6049 		char *str = (char *)mstate->dtms_scratch_ptr;
6050 		uintptr_t mem = tupregs[0].dttk_value;
6051 		char c = tupregs[1].dttk_value;
6052 		size_t size = tupregs[2].dttk_value;
6053 		uint8_t n;
6054 		int i;
6055 
6056 		regs[rd] = 0;
6057 
6058 		if (size == 0)
6059 			break;
6060 
6061 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
6062 			break;
6063 
6064 		if (!DTRACE_INSCRATCH(mstate, size)) {
6065 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6066 			break;
6067 		}
6068 
6069 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6070 			*flags |= CPU_DTRACE_ILLOP;
6071 			break;
6072 		}
6073 
6074 		for (i = 0; i < size - 1; i++) {
6075 			n = dtrace_load8(mem++);
6076 			str[i] = (n == 0) ? c : n;
6077 		}
6078 		str[size - 1] = 0;
6079 
6080 		regs[rd] = (uintptr_t)str;
6081 		mstate->dtms_scratch_ptr += size;
6082 		break;
6083 	}
6084 #endif
6085 	}
6086 }
6087 
6088 /*
6089  * Emulate the execution of DTrace IR instructions specified by the given
6090  * DIF object.  This function is deliberately void of assertions as all of
6091  * the necessary checks are handled by a call to dtrace_difo_validate().
6092  */
6093 static uint64_t
6094 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6095     dtrace_vstate_t *vstate, dtrace_state_t *state)
6096 {
6097 	const dif_instr_t *text = difo->dtdo_buf;
6098 	const uint_t textlen = difo->dtdo_len;
6099 	const char *strtab = difo->dtdo_strtab;
6100 	const uint64_t *inttab = difo->dtdo_inttab;
6101 
6102 	uint64_t rval = 0;
6103 	dtrace_statvar_t *svar;
6104 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6105 	dtrace_difv_t *v;
6106 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6107 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6108 
6109 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6110 	uint64_t regs[DIF_DIR_NREGS];
6111 	uint64_t *tmp;
6112 
6113 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6114 	int64_t cc_r;
6115 	uint_t pc = 0, id, opc = 0;
6116 	uint8_t ttop = 0;
6117 	dif_instr_t instr;
6118 	uint_t r1, r2, rd;
6119 
6120 	/*
6121 	 * We stash the current DIF object into the machine state: we need it
6122 	 * for subsequent access checking.
6123 	 */
6124 	mstate->dtms_difo = difo;
6125 
6126 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
6127 
6128 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6129 		opc = pc;
6130 
6131 		instr = text[pc++];
6132 		r1 = DIF_INSTR_R1(instr);
6133 		r2 = DIF_INSTR_R2(instr);
6134 		rd = DIF_INSTR_RD(instr);
6135 
6136 		switch (DIF_INSTR_OP(instr)) {
6137 		case DIF_OP_OR:
6138 			regs[rd] = regs[r1] | regs[r2];
6139 			break;
6140 		case DIF_OP_XOR:
6141 			regs[rd] = regs[r1] ^ regs[r2];
6142 			break;
6143 		case DIF_OP_AND:
6144 			regs[rd] = regs[r1] & regs[r2];
6145 			break;
6146 		case DIF_OP_SLL:
6147 			regs[rd] = regs[r1] << regs[r2];
6148 			break;
6149 		case DIF_OP_SRL:
6150 			regs[rd] = regs[r1] >> regs[r2];
6151 			break;
6152 		case DIF_OP_SUB:
6153 			regs[rd] = regs[r1] - regs[r2];
6154 			break;
6155 		case DIF_OP_ADD:
6156 			regs[rd] = regs[r1] + regs[r2];
6157 			break;
6158 		case DIF_OP_MUL:
6159 			regs[rd] = regs[r1] * regs[r2];
6160 			break;
6161 		case DIF_OP_SDIV:
6162 			if (regs[r2] == 0) {
6163 				regs[rd] = 0;
6164 				*flags |= CPU_DTRACE_DIVZERO;
6165 			} else {
6166 				regs[rd] = (int64_t)regs[r1] /
6167 				    (int64_t)regs[r2];
6168 			}
6169 			break;
6170 
6171 		case DIF_OP_UDIV:
6172 			if (regs[r2] == 0) {
6173 				regs[rd] = 0;
6174 				*flags |= CPU_DTRACE_DIVZERO;
6175 			} else {
6176 				regs[rd] = regs[r1] / regs[r2];
6177 			}
6178 			break;
6179 
6180 		case DIF_OP_SREM:
6181 			if (regs[r2] == 0) {
6182 				regs[rd] = 0;
6183 				*flags |= CPU_DTRACE_DIVZERO;
6184 			} else {
6185 				regs[rd] = (int64_t)regs[r1] %
6186 				    (int64_t)regs[r2];
6187 			}
6188 			break;
6189 
6190 		case DIF_OP_UREM:
6191 			if (regs[r2] == 0) {
6192 				regs[rd] = 0;
6193 				*flags |= CPU_DTRACE_DIVZERO;
6194 			} else {
6195 				regs[rd] = regs[r1] % regs[r2];
6196 			}
6197 			break;
6198 
6199 		case DIF_OP_NOT:
6200 			regs[rd] = ~regs[r1];
6201 			break;
6202 		case DIF_OP_MOV:
6203 			regs[rd] = regs[r1];
6204 			break;
6205 		case DIF_OP_CMP:
6206 			cc_r = regs[r1] - regs[r2];
6207 			cc_n = cc_r < 0;
6208 			cc_z = cc_r == 0;
6209 			cc_v = 0;
6210 			cc_c = regs[r1] < regs[r2];
6211 			break;
6212 		case DIF_OP_TST:
6213 			cc_n = cc_v = cc_c = 0;
6214 			cc_z = regs[r1] == 0;
6215 			break;
6216 		case DIF_OP_BA:
6217 			pc = DIF_INSTR_LABEL(instr);
6218 			break;
6219 		case DIF_OP_BE:
6220 			if (cc_z)
6221 				pc = DIF_INSTR_LABEL(instr);
6222 			break;
6223 		case DIF_OP_BNE:
6224 			if (cc_z == 0)
6225 				pc = DIF_INSTR_LABEL(instr);
6226 			break;
6227 		case DIF_OP_BG:
6228 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6229 				pc = DIF_INSTR_LABEL(instr);
6230 			break;
6231 		case DIF_OP_BGU:
6232 			if ((cc_c | cc_z) == 0)
6233 				pc = DIF_INSTR_LABEL(instr);
6234 			break;
6235 		case DIF_OP_BGE:
6236 			if ((cc_n ^ cc_v) == 0)
6237 				pc = DIF_INSTR_LABEL(instr);
6238 			break;
6239 		case DIF_OP_BGEU:
6240 			if (cc_c == 0)
6241 				pc = DIF_INSTR_LABEL(instr);
6242 			break;
6243 		case DIF_OP_BL:
6244 			if (cc_n ^ cc_v)
6245 				pc = DIF_INSTR_LABEL(instr);
6246 			break;
6247 		case DIF_OP_BLU:
6248 			if (cc_c)
6249 				pc = DIF_INSTR_LABEL(instr);
6250 			break;
6251 		case DIF_OP_BLE:
6252 			if (cc_z | (cc_n ^ cc_v))
6253 				pc = DIF_INSTR_LABEL(instr);
6254 			break;
6255 		case DIF_OP_BLEU:
6256 			if (cc_c | cc_z)
6257 				pc = DIF_INSTR_LABEL(instr);
6258 			break;
6259 		case DIF_OP_RLDSB:
6260 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6261 				break;
6262 			/*FALLTHROUGH*/
6263 		case DIF_OP_LDSB:
6264 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6265 			break;
6266 		case DIF_OP_RLDSH:
6267 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6268 				break;
6269 			/*FALLTHROUGH*/
6270 		case DIF_OP_LDSH:
6271 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6272 			break;
6273 		case DIF_OP_RLDSW:
6274 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6275 				break;
6276 			/*FALLTHROUGH*/
6277 		case DIF_OP_LDSW:
6278 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6279 			break;
6280 		case DIF_OP_RLDUB:
6281 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6282 				break;
6283 			/*FALLTHROUGH*/
6284 		case DIF_OP_LDUB:
6285 			regs[rd] = dtrace_load8(regs[r1]);
6286 			break;
6287 		case DIF_OP_RLDUH:
6288 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6289 				break;
6290 			/*FALLTHROUGH*/
6291 		case DIF_OP_LDUH:
6292 			regs[rd] = dtrace_load16(regs[r1]);
6293 			break;
6294 		case DIF_OP_RLDUW:
6295 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6296 				break;
6297 			/*FALLTHROUGH*/
6298 		case DIF_OP_LDUW:
6299 			regs[rd] = dtrace_load32(regs[r1]);
6300 			break;
6301 		case DIF_OP_RLDX:
6302 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6303 				break;
6304 			/*FALLTHROUGH*/
6305 		case DIF_OP_LDX:
6306 			regs[rd] = dtrace_load64(regs[r1]);
6307 			break;
6308 		case DIF_OP_ULDSB:
6309 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6310 			regs[rd] = (int8_t)
6311 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6312 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6313 			break;
6314 		case DIF_OP_ULDSH:
6315 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6316 			regs[rd] = (int16_t)
6317 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6318 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6319 			break;
6320 		case DIF_OP_ULDSW:
6321 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6322 			regs[rd] = (int32_t)
6323 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6324 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6325 			break;
6326 		case DIF_OP_ULDUB:
6327 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6328 			regs[rd] =
6329 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6330 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6331 			break;
6332 		case DIF_OP_ULDUH:
6333 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6334 			regs[rd] =
6335 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6336 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6337 			break;
6338 		case DIF_OP_ULDUW:
6339 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6340 			regs[rd] =
6341 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6342 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6343 			break;
6344 		case DIF_OP_ULDX:
6345 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6346 			regs[rd] =
6347 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6348 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6349 			break;
6350 		case DIF_OP_RET:
6351 			rval = regs[rd];
6352 			pc = textlen;
6353 			break;
6354 		case DIF_OP_NOP:
6355 			break;
6356 		case DIF_OP_SETX:
6357 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6358 			break;
6359 		case DIF_OP_SETS:
6360 			regs[rd] = (uint64_t)(uintptr_t)
6361 			    (strtab + DIF_INSTR_STRING(instr));
6362 			break;
6363 		case DIF_OP_SCMP: {
6364 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6365 			uintptr_t s1 = regs[r1];
6366 			uintptr_t s2 = regs[r2];
6367 			size_t lim1, lim2;
6368 
6369 			/*
6370 			 * If one of the strings is NULL then the limit becomes
6371 			 * 0 which compares 0 characters in dtrace_strncmp()
6372 			 * resulting in a false positive.  dtrace_strncmp()
6373 			 * treats a NULL as an empty 1-char string.
6374 			 */
6375 			lim1 = lim2 = 1;
6376 
6377 			if (s1 != 0 &&
6378 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6379 				break;
6380 			if (s2 != 0 &&
6381 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6382 				break;
6383 
6384 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6385 			    MIN(lim1, lim2));
6386 
6387 			cc_n = cc_r < 0;
6388 			cc_z = cc_r == 0;
6389 			cc_v = cc_c = 0;
6390 			break;
6391 		}
6392 		case DIF_OP_LDGA:
6393 			regs[rd] = dtrace_dif_variable(mstate, state,
6394 			    r1, regs[r2]);
6395 			break;
6396 		case DIF_OP_LDGS:
6397 			id = DIF_INSTR_VAR(instr);
6398 
6399 			if (id >= DIF_VAR_OTHER_UBASE) {
6400 				uintptr_t a;
6401 
6402 				id -= DIF_VAR_OTHER_UBASE;
6403 				svar = vstate->dtvs_globals[id];
6404 				ASSERT(svar != NULL);
6405 				v = &svar->dtsv_var;
6406 
6407 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6408 					regs[rd] = svar->dtsv_data;
6409 					break;
6410 				}
6411 
6412 				a = (uintptr_t)svar->dtsv_data;
6413 
6414 				if (*(uint8_t *)a == UINT8_MAX) {
6415 					/*
6416 					 * If the 0th byte is set to UINT8_MAX
6417 					 * then this is to be treated as a
6418 					 * reference to a NULL variable.
6419 					 */
6420 					regs[rd] = 0;
6421 				} else {
6422 					regs[rd] = a + sizeof (uint64_t);
6423 				}
6424 
6425 				break;
6426 			}
6427 
6428 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6429 			break;
6430 
6431 		case DIF_OP_STGS:
6432 			id = DIF_INSTR_VAR(instr);
6433 
6434 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6435 			id -= DIF_VAR_OTHER_UBASE;
6436 
6437 			VERIFY(id < vstate->dtvs_nglobals);
6438 			svar = vstate->dtvs_globals[id];
6439 			ASSERT(svar != NULL);
6440 			v = &svar->dtsv_var;
6441 
6442 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6443 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6444 				size_t lim;
6445 
6446 				ASSERT(a != 0);
6447 				ASSERT(svar->dtsv_size != 0);
6448 
6449 				if (regs[rd] == 0) {
6450 					*(uint8_t *)a = UINT8_MAX;
6451 					break;
6452 				} else {
6453 					*(uint8_t *)a = 0;
6454 					a += sizeof (uint64_t);
6455 				}
6456 				if (!dtrace_vcanload(
6457 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6458 				    &lim, mstate, vstate))
6459 					break;
6460 
6461 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6462 				    (void *)a, &v->dtdv_type, lim);
6463 				break;
6464 			}
6465 
6466 			svar->dtsv_data = regs[rd];
6467 			break;
6468 
6469 		case DIF_OP_LDTA:
6470 			/*
6471 			 * There are no DTrace built-in thread-local arrays at
6472 			 * present.  This opcode is saved for future work.
6473 			 */
6474 			*flags |= CPU_DTRACE_ILLOP;
6475 			regs[rd] = 0;
6476 			break;
6477 
6478 		case DIF_OP_LDLS:
6479 			id = DIF_INSTR_VAR(instr);
6480 
6481 			if (id < DIF_VAR_OTHER_UBASE) {
6482 				/*
6483 				 * For now, this has no meaning.
6484 				 */
6485 				regs[rd] = 0;
6486 				break;
6487 			}
6488 
6489 			id -= DIF_VAR_OTHER_UBASE;
6490 
6491 			ASSERT(id < vstate->dtvs_nlocals);
6492 			ASSERT(vstate->dtvs_locals != NULL);
6493 
6494 			svar = vstate->dtvs_locals[id];
6495 			ASSERT(svar != NULL);
6496 			v = &svar->dtsv_var;
6497 
6498 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6499 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6500 				size_t sz = v->dtdv_type.dtdt_size;
6501 				size_t lim;
6502 
6503 				sz += sizeof (uint64_t);
6504 				ASSERT(svar->dtsv_size == NCPU * sz);
6505 				a += curcpu * sz;
6506 
6507 				if (*(uint8_t *)a == UINT8_MAX) {
6508 					/*
6509 					 * If the 0th byte is set to UINT8_MAX
6510 					 * then this is to be treated as a
6511 					 * reference to a NULL variable.
6512 					 */
6513 					regs[rd] = 0;
6514 				} else {
6515 					regs[rd] = a + sizeof (uint64_t);
6516 				}
6517 
6518 				break;
6519 			}
6520 
6521 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6522 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6523 			regs[rd] = tmp[curcpu];
6524 			break;
6525 
6526 		case DIF_OP_STLS:
6527 			id = DIF_INSTR_VAR(instr);
6528 
6529 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6530 			id -= DIF_VAR_OTHER_UBASE;
6531 			VERIFY(id < vstate->dtvs_nlocals);
6532 
6533 			ASSERT(vstate->dtvs_locals != NULL);
6534 			svar = vstate->dtvs_locals[id];
6535 			ASSERT(svar != NULL);
6536 			v = &svar->dtsv_var;
6537 
6538 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6539 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6540 				size_t sz = v->dtdv_type.dtdt_size;
6541 				size_t lim;
6542 
6543 				sz += sizeof (uint64_t);
6544 				ASSERT(svar->dtsv_size == NCPU * sz);
6545 				a += curcpu * sz;
6546 
6547 				if (regs[rd] == 0) {
6548 					*(uint8_t *)a = UINT8_MAX;
6549 					break;
6550 				} else {
6551 					*(uint8_t *)a = 0;
6552 					a += sizeof (uint64_t);
6553 				}
6554 
6555 				if (!dtrace_vcanload(
6556 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6557 				    &lim, mstate, vstate))
6558 					break;
6559 
6560 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6561 				    (void *)a, &v->dtdv_type, lim);
6562 				break;
6563 			}
6564 
6565 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6566 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6567 			tmp[curcpu] = regs[rd];
6568 			break;
6569 
6570 		case DIF_OP_LDTS: {
6571 			dtrace_dynvar_t *dvar;
6572 			dtrace_key_t *key;
6573 
6574 			id = DIF_INSTR_VAR(instr);
6575 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6576 			id -= DIF_VAR_OTHER_UBASE;
6577 			v = &vstate->dtvs_tlocals[id];
6578 
6579 			key = &tupregs[DIF_DTR_NREGS];
6580 			key[0].dttk_value = (uint64_t)id;
6581 			key[0].dttk_size = 0;
6582 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6583 			key[1].dttk_size = 0;
6584 
6585 			dvar = dtrace_dynvar(dstate, 2, key,
6586 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6587 			    mstate, vstate);
6588 
6589 			if (dvar == NULL) {
6590 				regs[rd] = 0;
6591 				break;
6592 			}
6593 
6594 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6595 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6596 			} else {
6597 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6598 			}
6599 
6600 			break;
6601 		}
6602 
6603 		case DIF_OP_STTS: {
6604 			dtrace_dynvar_t *dvar;
6605 			dtrace_key_t *key;
6606 
6607 			id = DIF_INSTR_VAR(instr);
6608 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6609 			id -= DIF_VAR_OTHER_UBASE;
6610 			VERIFY(id < vstate->dtvs_ntlocals);
6611 
6612 			key = &tupregs[DIF_DTR_NREGS];
6613 			key[0].dttk_value = (uint64_t)id;
6614 			key[0].dttk_size = 0;
6615 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6616 			key[1].dttk_size = 0;
6617 			v = &vstate->dtvs_tlocals[id];
6618 
6619 			dvar = dtrace_dynvar(dstate, 2, key,
6620 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6621 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6622 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6623 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6624 
6625 			/*
6626 			 * Given that we're storing to thread-local data,
6627 			 * we need to flush our predicate cache.
6628 			 */
6629 			curthread->t_predcache = 0;
6630 
6631 			if (dvar == NULL)
6632 				break;
6633 
6634 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6635 				size_t lim;
6636 
6637 				if (!dtrace_vcanload(
6638 				    (void *)(uintptr_t)regs[rd],
6639 				    &v->dtdv_type, &lim, mstate, vstate))
6640 					break;
6641 
6642 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6643 				    dvar->dtdv_data, &v->dtdv_type, lim);
6644 			} else {
6645 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6646 			}
6647 
6648 			break;
6649 		}
6650 
6651 		case DIF_OP_SRA:
6652 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6653 			break;
6654 
6655 		case DIF_OP_CALL:
6656 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6657 			    regs, tupregs, ttop, mstate, state);
6658 			break;
6659 
6660 		case DIF_OP_PUSHTR:
6661 			if (ttop == DIF_DTR_NREGS) {
6662 				*flags |= CPU_DTRACE_TUPOFLOW;
6663 				break;
6664 			}
6665 
6666 			if (r1 == DIF_TYPE_STRING) {
6667 				/*
6668 				 * If this is a string type and the size is 0,
6669 				 * we'll use the system-wide default string
6670 				 * size.  Note that we are _not_ looking at
6671 				 * the value of the DTRACEOPT_STRSIZE option;
6672 				 * had this been set, we would expect to have
6673 				 * a non-zero size value in the "pushtr".
6674 				 */
6675 				tupregs[ttop].dttk_size =
6676 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6677 				    regs[r2] ? regs[r2] :
6678 				    dtrace_strsize_default) + 1;
6679 			} else {
6680 				if (regs[r2] > LONG_MAX) {
6681 					*flags |= CPU_DTRACE_ILLOP;
6682 					break;
6683 				}
6684 
6685 				tupregs[ttop].dttk_size = regs[r2];
6686 			}
6687 
6688 			tupregs[ttop++].dttk_value = regs[rd];
6689 			break;
6690 
6691 		case DIF_OP_PUSHTV:
6692 			if (ttop == DIF_DTR_NREGS) {
6693 				*flags |= CPU_DTRACE_TUPOFLOW;
6694 				break;
6695 			}
6696 
6697 			tupregs[ttop].dttk_value = regs[rd];
6698 			tupregs[ttop++].dttk_size = 0;
6699 			break;
6700 
6701 		case DIF_OP_POPTS:
6702 			if (ttop != 0)
6703 				ttop--;
6704 			break;
6705 
6706 		case DIF_OP_FLUSHTS:
6707 			ttop = 0;
6708 			break;
6709 
6710 		case DIF_OP_LDGAA:
6711 		case DIF_OP_LDTAA: {
6712 			dtrace_dynvar_t *dvar;
6713 			dtrace_key_t *key = tupregs;
6714 			uint_t nkeys = ttop;
6715 
6716 			id = DIF_INSTR_VAR(instr);
6717 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6718 			id -= DIF_VAR_OTHER_UBASE;
6719 
6720 			key[nkeys].dttk_value = (uint64_t)id;
6721 			key[nkeys++].dttk_size = 0;
6722 
6723 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6724 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6725 				key[nkeys++].dttk_size = 0;
6726 				VERIFY(id < vstate->dtvs_ntlocals);
6727 				v = &vstate->dtvs_tlocals[id];
6728 			} else {
6729 				VERIFY(id < vstate->dtvs_nglobals);
6730 				v = &vstate->dtvs_globals[id]->dtsv_var;
6731 			}
6732 
6733 			dvar = dtrace_dynvar(dstate, nkeys, key,
6734 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6735 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6736 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6737 
6738 			if (dvar == NULL) {
6739 				regs[rd] = 0;
6740 				break;
6741 			}
6742 
6743 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6744 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6745 			} else {
6746 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6747 			}
6748 
6749 			break;
6750 		}
6751 
6752 		case DIF_OP_STGAA:
6753 		case DIF_OP_STTAA: {
6754 			dtrace_dynvar_t *dvar;
6755 			dtrace_key_t *key = tupregs;
6756 			uint_t nkeys = ttop;
6757 
6758 			id = DIF_INSTR_VAR(instr);
6759 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6760 			id -= DIF_VAR_OTHER_UBASE;
6761 
6762 			key[nkeys].dttk_value = (uint64_t)id;
6763 			key[nkeys++].dttk_size = 0;
6764 
6765 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6766 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6767 				key[nkeys++].dttk_size = 0;
6768 				VERIFY(id < vstate->dtvs_ntlocals);
6769 				v = &vstate->dtvs_tlocals[id];
6770 			} else {
6771 				VERIFY(id < vstate->dtvs_nglobals);
6772 				v = &vstate->dtvs_globals[id]->dtsv_var;
6773 			}
6774 
6775 			dvar = dtrace_dynvar(dstate, nkeys, key,
6776 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6777 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6778 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6779 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6780 
6781 			if (dvar == NULL)
6782 				break;
6783 
6784 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6785 				size_t lim;
6786 
6787 				if (!dtrace_vcanload(
6788 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6789 				    &lim, mstate, vstate))
6790 					break;
6791 
6792 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6793 				    dvar->dtdv_data, &v->dtdv_type, lim);
6794 			} else {
6795 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6796 			}
6797 
6798 			break;
6799 		}
6800 
6801 		case DIF_OP_ALLOCS: {
6802 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6803 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6804 
6805 			/*
6806 			 * Rounding up the user allocation size could have
6807 			 * overflowed large, bogus allocations (like -1ULL) to
6808 			 * 0.
6809 			 */
6810 			if (size < regs[r1] ||
6811 			    !DTRACE_INSCRATCH(mstate, size)) {
6812 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6813 				regs[rd] = 0;
6814 				break;
6815 			}
6816 
6817 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6818 			mstate->dtms_scratch_ptr += size;
6819 			regs[rd] = ptr;
6820 			break;
6821 		}
6822 
6823 		case DIF_OP_COPYS:
6824 			if (!dtrace_canstore(regs[rd], regs[r2],
6825 			    mstate, vstate)) {
6826 				*flags |= CPU_DTRACE_BADADDR;
6827 				*illval = regs[rd];
6828 				break;
6829 			}
6830 
6831 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6832 				break;
6833 
6834 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6835 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6836 			break;
6837 
6838 		case DIF_OP_STB:
6839 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6840 				*flags |= CPU_DTRACE_BADADDR;
6841 				*illval = regs[rd];
6842 				break;
6843 			}
6844 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6845 			break;
6846 
6847 		case DIF_OP_STH:
6848 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6849 				*flags |= CPU_DTRACE_BADADDR;
6850 				*illval = regs[rd];
6851 				break;
6852 			}
6853 			if (regs[rd] & 1) {
6854 				*flags |= CPU_DTRACE_BADALIGN;
6855 				*illval = regs[rd];
6856 				break;
6857 			}
6858 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6859 			break;
6860 
6861 		case DIF_OP_STW:
6862 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6863 				*flags |= CPU_DTRACE_BADADDR;
6864 				*illval = regs[rd];
6865 				break;
6866 			}
6867 			if (regs[rd] & 3) {
6868 				*flags |= CPU_DTRACE_BADALIGN;
6869 				*illval = regs[rd];
6870 				break;
6871 			}
6872 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6873 			break;
6874 
6875 		case DIF_OP_STX:
6876 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6877 				*flags |= CPU_DTRACE_BADADDR;
6878 				*illval = regs[rd];
6879 				break;
6880 			}
6881 			if (regs[rd] & 7) {
6882 				*flags |= CPU_DTRACE_BADALIGN;
6883 				*illval = regs[rd];
6884 				break;
6885 			}
6886 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6887 			break;
6888 		}
6889 	}
6890 
6891 	if (!(*flags & CPU_DTRACE_FAULT))
6892 		return (rval);
6893 
6894 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6895 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6896 
6897 	return (0);
6898 }
6899 
6900 static void
6901 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6902 {
6903 	dtrace_probe_t *probe = ecb->dte_probe;
6904 	dtrace_provider_t *prov = probe->dtpr_provider;
6905 	char c[DTRACE_FULLNAMELEN + 80], *str;
6906 	char *msg = "dtrace: breakpoint action at probe ";
6907 	char *ecbmsg = " (ecb ";
6908 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6909 	uintptr_t val = (uintptr_t)ecb;
6910 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6911 
6912 	if (dtrace_destructive_disallow)
6913 		return;
6914 
6915 	/*
6916 	 * It's impossible to be taking action on the NULL probe.
6917 	 */
6918 	ASSERT(probe != NULL);
6919 
6920 	/*
6921 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6922 	 * print the provider name, module name, function name and name of
6923 	 * the probe, along with the hex address of the ECB with the breakpoint
6924 	 * action -- all of which we must place in the character buffer by
6925 	 * hand.
6926 	 */
6927 	while (*msg != '\0')
6928 		c[i++] = *msg++;
6929 
6930 	for (str = prov->dtpv_name; *str != '\0'; str++)
6931 		c[i++] = *str;
6932 	c[i++] = ':';
6933 
6934 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6935 		c[i++] = *str;
6936 	c[i++] = ':';
6937 
6938 	for (str = probe->dtpr_func; *str != '\0'; str++)
6939 		c[i++] = *str;
6940 	c[i++] = ':';
6941 
6942 	for (str = probe->dtpr_name; *str != '\0'; str++)
6943 		c[i++] = *str;
6944 
6945 	while (*ecbmsg != '\0')
6946 		c[i++] = *ecbmsg++;
6947 
6948 	while (shift >= 0) {
6949 		mask = (uintptr_t)0xf << shift;
6950 
6951 		if (val >= ((uintptr_t)1 << shift))
6952 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6953 		shift -= 4;
6954 	}
6955 
6956 	c[i++] = ')';
6957 	c[i] = '\0';
6958 
6959 #ifdef illumos
6960 	debug_enter(c);
6961 #else
6962 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6963 #endif
6964 }
6965 
6966 static void
6967 dtrace_action_panic(dtrace_ecb_t *ecb)
6968 {
6969 	dtrace_probe_t *probe = ecb->dte_probe;
6970 
6971 	/*
6972 	 * It's impossible to be taking action on the NULL probe.
6973 	 */
6974 	ASSERT(probe != NULL);
6975 
6976 	if (dtrace_destructive_disallow)
6977 		return;
6978 
6979 	if (dtrace_panicked != NULL)
6980 		return;
6981 
6982 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6983 		return;
6984 
6985 	/*
6986 	 * We won the right to panic.  (We want to be sure that only one
6987 	 * thread calls panic() from dtrace_probe(), and that panic() is
6988 	 * called exactly once.)
6989 	 */
6990 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6991 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6992 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6993 }
6994 
6995 static void
6996 dtrace_action_raise(uint64_t sig)
6997 {
6998 	if (dtrace_destructive_disallow)
6999 		return;
7000 
7001 	if (sig >= NSIG) {
7002 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7003 		return;
7004 	}
7005 
7006 #ifdef illumos
7007 	/*
7008 	 * raise() has a queue depth of 1 -- we ignore all subsequent
7009 	 * invocations of the raise() action.
7010 	 */
7011 	if (curthread->t_dtrace_sig == 0)
7012 		curthread->t_dtrace_sig = (uint8_t)sig;
7013 
7014 	curthread->t_sig_check = 1;
7015 	aston(curthread);
7016 #else
7017 	struct proc *p = curproc;
7018 	PROC_LOCK(p);
7019 	kern_psignal(p, sig);
7020 	PROC_UNLOCK(p);
7021 #endif
7022 }
7023 
7024 static void
7025 dtrace_action_stop(void)
7026 {
7027 	if (dtrace_destructive_disallow)
7028 		return;
7029 
7030 #ifdef illumos
7031 	if (!curthread->t_dtrace_stop) {
7032 		curthread->t_dtrace_stop = 1;
7033 		curthread->t_sig_check = 1;
7034 		aston(curthread);
7035 	}
7036 #else
7037 	struct proc *p = curproc;
7038 	PROC_LOCK(p);
7039 	kern_psignal(p, SIGSTOP);
7040 	PROC_UNLOCK(p);
7041 #endif
7042 }
7043 
7044 static void
7045 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7046 {
7047 	hrtime_t now;
7048 	volatile uint16_t *flags;
7049 #ifdef illumos
7050 	cpu_t *cpu = CPU;
7051 #else
7052 	cpu_t *cpu = &solaris_cpu[curcpu];
7053 #endif
7054 
7055 	if (dtrace_destructive_disallow)
7056 		return;
7057 
7058 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7059 
7060 	now = dtrace_gethrtime();
7061 
7062 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7063 		/*
7064 		 * We need to advance the mark to the current time.
7065 		 */
7066 		cpu->cpu_dtrace_chillmark = now;
7067 		cpu->cpu_dtrace_chilled = 0;
7068 	}
7069 
7070 	/*
7071 	 * Now check to see if the requested chill time would take us over
7072 	 * the maximum amount of time allowed in the chill interval.  (Or
7073 	 * worse, if the calculation itself induces overflow.)
7074 	 */
7075 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7076 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7077 		*flags |= CPU_DTRACE_ILLOP;
7078 		return;
7079 	}
7080 
7081 	while (dtrace_gethrtime() - now < val)
7082 		continue;
7083 
7084 	/*
7085 	 * Normally, we assure that the value of the variable "timestamp" does
7086 	 * not change within an ECB.  The presence of chill() represents an
7087 	 * exception to this rule, however.
7088 	 */
7089 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7090 	cpu->cpu_dtrace_chilled += val;
7091 }
7092 
7093 static void
7094 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7095     uint64_t *buf, uint64_t arg)
7096 {
7097 	int nframes = DTRACE_USTACK_NFRAMES(arg);
7098 	int strsize = DTRACE_USTACK_STRSIZE(arg);
7099 	uint64_t *pcs = &buf[1], *fps;
7100 	char *str = (char *)&pcs[nframes];
7101 	int size, offs = 0, i, j;
7102 	size_t rem;
7103 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
7104 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7105 	char *sym;
7106 
7107 	/*
7108 	 * Should be taking a faster path if string space has not been
7109 	 * allocated.
7110 	 */
7111 	ASSERT(strsize != 0);
7112 
7113 	/*
7114 	 * We will first allocate some temporary space for the frame pointers.
7115 	 */
7116 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7117 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7118 	    (nframes * sizeof (uint64_t));
7119 
7120 	if (!DTRACE_INSCRATCH(mstate, size)) {
7121 		/*
7122 		 * Not enough room for our frame pointers -- need to indicate
7123 		 * that we ran out of scratch space.
7124 		 */
7125 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7126 		return;
7127 	}
7128 
7129 	mstate->dtms_scratch_ptr += size;
7130 	saved = mstate->dtms_scratch_ptr;
7131 
7132 	/*
7133 	 * Now get a stack with both program counters and frame pointers.
7134 	 */
7135 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7136 	dtrace_getufpstack(buf, fps, nframes + 1);
7137 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7138 
7139 	/*
7140 	 * If that faulted, we're cooked.
7141 	 */
7142 	if (*flags & CPU_DTRACE_FAULT)
7143 		goto out;
7144 
7145 	/*
7146 	 * Now we want to walk up the stack, calling the USTACK helper.  For
7147 	 * each iteration, we restore the scratch pointer.
7148 	 */
7149 	for (i = 0; i < nframes; i++) {
7150 		mstate->dtms_scratch_ptr = saved;
7151 
7152 		if (offs >= strsize)
7153 			break;
7154 
7155 		sym = (char *)(uintptr_t)dtrace_helper(
7156 		    DTRACE_HELPER_ACTION_USTACK,
7157 		    mstate, state, pcs[i], fps[i]);
7158 
7159 		/*
7160 		 * If we faulted while running the helper, we're going to
7161 		 * clear the fault and null out the corresponding string.
7162 		 */
7163 		if (*flags & CPU_DTRACE_FAULT) {
7164 			*flags &= ~CPU_DTRACE_FAULT;
7165 			str[offs++] = '\0';
7166 			continue;
7167 		}
7168 
7169 		if (sym == NULL) {
7170 			str[offs++] = '\0';
7171 			continue;
7172 		}
7173 
7174 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7175 		    &(state->dts_vstate))) {
7176 			str[offs++] = '\0';
7177 			continue;
7178 		}
7179 
7180 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7181 
7182 		/*
7183 		 * Now copy in the string that the helper returned to us.
7184 		 */
7185 		for (j = 0; offs + j < strsize && j < rem; j++) {
7186 			if ((str[offs + j] = sym[j]) == '\0')
7187 				break;
7188 		}
7189 
7190 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7191 
7192 		offs += j + 1;
7193 	}
7194 
7195 	if (offs >= strsize) {
7196 		/*
7197 		 * If we didn't have room for all of the strings, we don't
7198 		 * abort processing -- this needn't be a fatal error -- but we
7199 		 * still want to increment a counter (dts_stkstroverflows) to
7200 		 * allow this condition to be warned about.  (If this is from
7201 		 * a jstack() action, it is easily tuned via jstackstrsize.)
7202 		 */
7203 		dtrace_error(&state->dts_stkstroverflows);
7204 	}
7205 
7206 	while (offs < strsize)
7207 		str[offs++] = '\0';
7208 
7209 out:
7210 	mstate->dtms_scratch_ptr = old;
7211 }
7212 
7213 static void
7214 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7215     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7216 {
7217 	volatile uint16_t *flags;
7218 	uint64_t val = *valp;
7219 	size_t valoffs = *valoffsp;
7220 
7221 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7222 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7223 
7224 	/*
7225 	 * If this is a string, we're going to only load until we find the zero
7226 	 * byte -- after which we'll store zero bytes.
7227 	 */
7228 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7229 		char c = '\0' + 1;
7230 		size_t s;
7231 
7232 		for (s = 0; s < size; s++) {
7233 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
7234 				c = dtrace_load8(val++);
7235 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7236 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7237 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7238 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7239 				if (*flags & CPU_DTRACE_FAULT)
7240 					break;
7241 			}
7242 
7243 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7244 
7245 			if (c == '\0' && intuple)
7246 				break;
7247 		}
7248 	} else {
7249 		uint8_t c;
7250 		while (valoffs < end) {
7251 			if (dtkind == DIF_TF_BYREF) {
7252 				c = dtrace_load8(val++);
7253 			} else if (dtkind == DIF_TF_BYUREF) {
7254 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7255 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7256 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7257 				if (*flags & CPU_DTRACE_FAULT)
7258 					break;
7259 			}
7260 
7261 			DTRACE_STORE(uint8_t, tomax,
7262 			    valoffs++, c);
7263 		}
7264 	}
7265 
7266 	*valp = val;
7267 	*valoffsp = valoffs;
7268 }
7269 
7270 /*
7271  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7272  * defined, we also assert that we are not recursing unless the probe ID is an
7273  * error probe.
7274  */
7275 static dtrace_icookie_t
7276 dtrace_probe_enter(dtrace_id_t id)
7277 {
7278 	dtrace_icookie_t cookie;
7279 
7280 	cookie = dtrace_interrupt_disable();
7281 
7282 	/*
7283 	 * Unless this is an ERROR probe, we are not allowed to recurse in
7284 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
7285 	 * function is instrumented that should not have been instrumented or
7286 	 * that the ordering guarantee of the records will be violated,
7287 	 * resulting in unexpected output. If there is an exception to this
7288 	 * assertion, a new case should be added.
7289 	 */
7290 	ASSERT(curthread->t_dtrace_inprobe == 0 ||
7291 	    id == dtrace_probeid_error);
7292 	curthread->t_dtrace_inprobe = 1;
7293 
7294 	return (cookie);
7295 }
7296 
7297 /*
7298  * Clears the per-thread inprobe flag and enables interrupts.
7299  */
7300 static void
7301 dtrace_probe_exit(dtrace_icookie_t cookie)
7302 {
7303 
7304 	curthread->t_dtrace_inprobe = 0;
7305 	dtrace_interrupt_enable(cookie);
7306 }
7307 
7308 /*
7309  * If you're looking for the epicenter of DTrace, you just found it.  This
7310  * is the function called by the provider to fire a probe -- from which all
7311  * subsequent probe-context DTrace activity emanates.
7312  */
7313 void
7314 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7315     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7316 {
7317 	processorid_t cpuid;
7318 	dtrace_icookie_t cookie;
7319 	dtrace_probe_t *probe;
7320 	dtrace_mstate_t mstate;
7321 	dtrace_ecb_t *ecb;
7322 	dtrace_action_t *act;
7323 	intptr_t offs;
7324 	size_t size;
7325 	int vtime, onintr;
7326 	volatile uint16_t *flags;
7327 	hrtime_t now;
7328 
7329 	if (KERNEL_PANICKED())
7330 		return;
7331 
7332 #ifdef illumos
7333 	/*
7334 	 * Kick out immediately if this CPU is still being born (in which case
7335 	 * curthread will be set to -1) or the current thread can't allow
7336 	 * probes in its current context.
7337 	 */
7338 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7339 		return;
7340 #endif
7341 
7342 	cookie = dtrace_probe_enter(id);
7343 	probe = dtrace_probes[id - 1];
7344 	cpuid = curcpu;
7345 	onintr = CPU_ON_INTR(CPU);
7346 
7347 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7348 	    probe->dtpr_predcache == curthread->t_predcache) {
7349 		/*
7350 		 * We have hit in the predicate cache; we know that
7351 		 * this predicate would evaluate to be false.
7352 		 */
7353 		dtrace_probe_exit(cookie);
7354 		return;
7355 	}
7356 
7357 #ifdef illumos
7358 	if (panic_quiesce) {
7359 #else
7360 	if (KERNEL_PANICKED()) {
7361 #endif
7362 		/*
7363 		 * We don't trace anything if we're panicking.
7364 		 */
7365 		dtrace_probe_exit(cookie);
7366 		return;
7367 	}
7368 
7369 	now = mstate.dtms_timestamp = dtrace_gethrtime();
7370 	mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7371 	vtime = dtrace_vtime_references != 0;
7372 
7373 	if (vtime && curthread->t_dtrace_start)
7374 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7375 
7376 	mstate.dtms_difo = NULL;
7377 	mstate.dtms_probe = probe;
7378 	mstate.dtms_strtok = 0;
7379 	mstate.dtms_arg[0] = arg0;
7380 	mstate.dtms_arg[1] = arg1;
7381 	mstate.dtms_arg[2] = arg2;
7382 	mstate.dtms_arg[3] = arg3;
7383 	mstate.dtms_arg[4] = arg4;
7384 
7385 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7386 
7387 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7388 		dtrace_predicate_t *pred = ecb->dte_predicate;
7389 		dtrace_state_t *state = ecb->dte_state;
7390 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7391 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7392 		dtrace_vstate_t *vstate = &state->dts_vstate;
7393 		dtrace_provider_t *prov = probe->dtpr_provider;
7394 		uint64_t tracememsize = 0;
7395 		int committed = 0;
7396 		caddr_t tomax;
7397 
7398 		/*
7399 		 * A little subtlety with the following (seemingly innocuous)
7400 		 * declaration of the automatic 'val':  by looking at the
7401 		 * code, you might think that it could be declared in the
7402 		 * action processing loop, below.  (That is, it's only used in
7403 		 * the action processing loop.)  However, it must be declared
7404 		 * out of that scope because in the case of DIF expression
7405 		 * arguments to aggregating actions, one iteration of the
7406 		 * action loop will use the last iteration's value.
7407 		 */
7408 		uint64_t val = 0;
7409 
7410 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7411 		mstate.dtms_getf = NULL;
7412 
7413 		*flags &= ~CPU_DTRACE_ERROR;
7414 
7415 		if (prov == dtrace_provider) {
7416 			/*
7417 			 * If dtrace itself is the provider of this probe,
7418 			 * we're only going to continue processing the ECB if
7419 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7420 			 * creating state.  (This prevents disjoint consumers
7421 			 * from seeing one another's metaprobes.)
7422 			 */
7423 			if (arg0 != (uint64_t)(uintptr_t)state)
7424 				continue;
7425 		}
7426 
7427 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7428 			/*
7429 			 * We're not currently active.  If our provider isn't
7430 			 * the dtrace pseudo provider, we're not interested.
7431 			 */
7432 			if (prov != dtrace_provider)
7433 				continue;
7434 
7435 			/*
7436 			 * Now we must further check if we are in the BEGIN
7437 			 * probe.  If we are, we will only continue processing
7438 			 * if we're still in WARMUP -- if one BEGIN enabling
7439 			 * has invoked the exit() action, we don't want to
7440 			 * evaluate subsequent BEGIN enablings.
7441 			 */
7442 			if (probe->dtpr_id == dtrace_probeid_begin &&
7443 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7444 				ASSERT(state->dts_activity ==
7445 				    DTRACE_ACTIVITY_DRAINING);
7446 				continue;
7447 			}
7448 		}
7449 
7450 		if (ecb->dte_cond) {
7451 			/*
7452 			 * If the dte_cond bits indicate that this
7453 			 * consumer is only allowed to see user-mode firings
7454 			 * of this probe, call the provider's dtps_usermode()
7455 			 * entry point to check that the probe was fired
7456 			 * while in a user context. Skip this ECB if that's
7457 			 * not the case.
7458 			 */
7459 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7460 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7461 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7462 				continue;
7463 
7464 #ifdef illumos
7465 			/*
7466 			 * This is more subtle than it looks. We have to be
7467 			 * absolutely certain that CRED() isn't going to
7468 			 * change out from under us so it's only legit to
7469 			 * examine that structure if we're in constrained
7470 			 * situations. Currently, the only times we'll this
7471 			 * check is if a non-super-user has enabled the
7472 			 * profile or syscall providers -- providers that
7473 			 * allow visibility of all processes. For the
7474 			 * profile case, the check above will ensure that
7475 			 * we're examining a user context.
7476 			 */
7477 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7478 				cred_t *cr;
7479 				cred_t *s_cr =
7480 				    ecb->dte_state->dts_cred.dcr_cred;
7481 				proc_t *proc;
7482 
7483 				ASSERT(s_cr != NULL);
7484 
7485 				if ((cr = CRED()) == NULL ||
7486 				    s_cr->cr_uid != cr->cr_uid ||
7487 				    s_cr->cr_uid != cr->cr_ruid ||
7488 				    s_cr->cr_uid != cr->cr_suid ||
7489 				    s_cr->cr_gid != cr->cr_gid ||
7490 				    s_cr->cr_gid != cr->cr_rgid ||
7491 				    s_cr->cr_gid != cr->cr_sgid ||
7492 				    (proc = ttoproc(curthread)) == NULL ||
7493 				    (proc->p_flag & SNOCD))
7494 					continue;
7495 			}
7496 
7497 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7498 				cred_t *cr;
7499 				cred_t *s_cr =
7500 				    ecb->dte_state->dts_cred.dcr_cred;
7501 
7502 				ASSERT(s_cr != NULL);
7503 
7504 				if ((cr = CRED()) == NULL ||
7505 				    s_cr->cr_zone->zone_id !=
7506 				    cr->cr_zone->zone_id)
7507 					continue;
7508 			}
7509 #endif
7510 		}
7511 
7512 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7513 			/*
7514 			 * We seem to be dead.  Unless we (a) have kernel
7515 			 * destructive permissions (b) have explicitly enabled
7516 			 * destructive actions and (c) destructive actions have
7517 			 * not been disabled, we're going to transition into
7518 			 * the KILLED state, from which no further processing
7519 			 * on this state will be performed.
7520 			 */
7521 			if (!dtrace_priv_kernel_destructive(state) ||
7522 			    !state->dts_cred.dcr_destructive ||
7523 			    dtrace_destructive_disallow) {
7524 				void *activity = &state->dts_activity;
7525 				dtrace_activity_t curstate;
7526 
7527 				do {
7528 					curstate = state->dts_activity;
7529 				} while (dtrace_cas32(activity, curstate,
7530 				    DTRACE_ACTIVITY_KILLED) != curstate);
7531 
7532 				continue;
7533 			}
7534 		}
7535 
7536 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7537 		    ecb->dte_alignment, state, &mstate)) < 0)
7538 			continue;
7539 
7540 		tomax = buf->dtb_tomax;
7541 		ASSERT(tomax != NULL);
7542 
7543 		if (ecb->dte_size != 0) {
7544 			dtrace_rechdr_t dtrh;
7545 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7546 				mstate.dtms_timestamp = dtrace_gethrtime();
7547 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7548 			}
7549 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7550 			dtrh.dtrh_epid = ecb->dte_epid;
7551 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7552 			    mstate.dtms_timestamp);
7553 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7554 		}
7555 
7556 		mstate.dtms_epid = ecb->dte_epid;
7557 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7558 
7559 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7560 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7561 		else
7562 			mstate.dtms_access = 0;
7563 
7564 		if (pred != NULL) {
7565 			dtrace_difo_t *dp = pred->dtp_difo;
7566 			uint64_t rval;
7567 
7568 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7569 
7570 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7571 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7572 
7573 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7574 					/*
7575 					 * Update the predicate cache...
7576 					 */
7577 					ASSERT(cid == pred->dtp_cacheid);
7578 					curthread->t_predcache = cid;
7579 				}
7580 
7581 				continue;
7582 			}
7583 		}
7584 
7585 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7586 		    act != NULL; act = act->dta_next) {
7587 			size_t valoffs;
7588 			dtrace_difo_t *dp;
7589 			dtrace_recdesc_t *rec = &act->dta_rec;
7590 
7591 			size = rec->dtrd_size;
7592 			valoffs = offs + rec->dtrd_offset;
7593 
7594 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7595 				uint64_t v = 0xbad;
7596 				dtrace_aggregation_t *agg;
7597 
7598 				agg = (dtrace_aggregation_t *)act;
7599 
7600 				if ((dp = act->dta_difo) != NULL)
7601 					v = dtrace_dif_emulate(dp,
7602 					    &mstate, vstate, state);
7603 
7604 				if (*flags & CPU_DTRACE_ERROR)
7605 					continue;
7606 
7607 				/*
7608 				 * Note that we always pass the expression
7609 				 * value from the previous iteration of the
7610 				 * action loop.  This value will only be used
7611 				 * if there is an expression argument to the
7612 				 * aggregating action, denoted by the
7613 				 * dtag_hasarg field.
7614 				 */
7615 				dtrace_aggregate(agg, buf,
7616 				    offs, aggbuf, v, val);
7617 				continue;
7618 			}
7619 
7620 			switch (act->dta_kind) {
7621 			case DTRACEACT_STOP:
7622 				if (dtrace_priv_proc_destructive(state))
7623 					dtrace_action_stop();
7624 				continue;
7625 
7626 			case DTRACEACT_BREAKPOINT:
7627 				if (dtrace_priv_kernel_destructive(state))
7628 					dtrace_action_breakpoint(ecb);
7629 				continue;
7630 
7631 			case DTRACEACT_PANIC:
7632 				if (dtrace_priv_kernel_destructive(state))
7633 					dtrace_action_panic(ecb);
7634 				continue;
7635 
7636 			case DTRACEACT_STACK:
7637 				if (!dtrace_priv_kernel(state))
7638 					continue;
7639 
7640 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7641 				    size / sizeof (pc_t), probe->dtpr_aframes,
7642 				    DTRACE_ANCHORED(probe) ? NULL :
7643 				    (uint32_t *)arg0);
7644 				continue;
7645 
7646 			case DTRACEACT_JSTACK:
7647 			case DTRACEACT_USTACK:
7648 				if (!dtrace_priv_proc(state))
7649 					continue;
7650 
7651 				/*
7652 				 * See comment in DIF_VAR_PID.
7653 				 */
7654 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7655 				    CPU_ON_INTR(CPU)) {
7656 					int depth = DTRACE_USTACK_NFRAMES(
7657 					    rec->dtrd_arg) + 1;
7658 
7659 					dtrace_bzero((void *)(tomax + valoffs),
7660 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7661 					    + depth * sizeof (uint64_t));
7662 
7663 					continue;
7664 				}
7665 
7666 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7667 				    curproc->p_dtrace_helpers != NULL) {
7668 					/*
7669 					 * This is the slow path -- we have
7670 					 * allocated string space, and we're
7671 					 * getting the stack of a process that
7672 					 * has helpers.  Call into a separate
7673 					 * routine to perform this processing.
7674 					 */
7675 					dtrace_action_ustack(&mstate, state,
7676 					    (uint64_t *)(tomax + valoffs),
7677 					    rec->dtrd_arg);
7678 					continue;
7679 				}
7680 
7681 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7682 				dtrace_getupcstack((uint64_t *)
7683 				    (tomax + valoffs),
7684 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7685 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7686 				continue;
7687 
7688 			default:
7689 				break;
7690 			}
7691 
7692 			dp = act->dta_difo;
7693 			ASSERT(dp != NULL);
7694 
7695 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7696 
7697 			if (*flags & CPU_DTRACE_ERROR)
7698 				continue;
7699 
7700 			switch (act->dta_kind) {
7701 			case DTRACEACT_SPECULATE: {
7702 				dtrace_rechdr_t *dtrh;
7703 
7704 				ASSERT(buf == &state->dts_buffer[cpuid]);
7705 				buf = dtrace_speculation_buffer(state,
7706 				    cpuid, val);
7707 
7708 				if (buf == NULL) {
7709 					*flags |= CPU_DTRACE_DROP;
7710 					continue;
7711 				}
7712 
7713 				offs = dtrace_buffer_reserve(buf,
7714 				    ecb->dte_needed, ecb->dte_alignment,
7715 				    state, NULL);
7716 
7717 				if (offs < 0) {
7718 					*flags |= CPU_DTRACE_DROP;
7719 					continue;
7720 				}
7721 
7722 				tomax = buf->dtb_tomax;
7723 				ASSERT(tomax != NULL);
7724 
7725 				if (ecb->dte_size == 0)
7726 					continue;
7727 
7728 				ASSERT3U(ecb->dte_size, >=,
7729 				    sizeof (dtrace_rechdr_t));
7730 				dtrh = ((void *)(tomax + offs));
7731 				dtrh->dtrh_epid = ecb->dte_epid;
7732 				/*
7733 				 * When the speculation is committed, all of
7734 				 * the records in the speculative buffer will
7735 				 * have their timestamps set to the commit
7736 				 * time.  Until then, it is set to a sentinel
7737 				 * value, for debugability.
7738 				 */
7739 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7740 				continue;
7741 			}
7742 
7743 			case DTRACEACT_PRINTM: {
7744 				/*
7745 				 * printm() assumes that the DIF returns a
7746 				 * pointer returned by memref(). memref() is a
7747 				 * subroutine that is used to get around the
7748 				 * single-valued returns of DIF and is assumed
7749 				 * to always be allocated in the scratch space.
7750 				 * Therefore, we need to validate that the
7751 				 * pointer given to printm() is in the scratch
7752 				 * space in order to avoid a potential panic.
7753 				 */
7754 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7755 
7756 				if (!DTRACE_INSCRATCHPTR(&mstate,
7757 				    (uintptr_t)memref, 2 * sizeof(uintptr_t))) {
7758 					*flags |= CPU_DTRACE_BADADDR;
7759 					continue;
7760 				}
7761 
7762 				/* Get the size from the memref. */
7763 				size = memref[1];
7764 
7765 				/*
7766 				 * Check if the size exceeds the allocated
7767 				 * buffer size.
7768 				 */
7769 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7770 					/* Flag a drop! */
7771 					*flags |= CPU_DTRACE_DROP;
7772 					continue;
7773 				}
7774 
7775 				/* Store the size in the buffer first. */
7776 				DTRACE_STORE(uintptr_t, tomax,
7777 				    valoffs, size);
7778 
7779 				/*
7780 				 * Offset the buffer address to the start
7781 				 * of the data.
7782 				 */
7783 				valoffs += sizeof(uintptr_t);
7784 
7785 				/*
7786 				 * Reset to the memory address rather than
7787 				 * the memref array, then let the BYREF
7788 				 * code below do the work to store the
7789 				 * memory data in the buffer.
7790 				 */
7791 				val = memref[0];
7792 				break;
7793 			}
7794 
7795 			case DTRACEACT_CHILL:
7796 				if (dtrace_priv_kernel_destructive(state))
7797 					dtrace_action_chill(&mstate, val);
7798 				continue;
7799 
7800 			case DTRACEACT_RAISE:
7801 				if (dtrace_priv_proc_destructive(state))
7802 					dtrace_action_raise(val);
7803 				continue;
7804 
7805 			case DTRACEACT_COMMIT:
7806 				ASSERT(!committed);
7807 
7808 				/*
7809 				 * We need to commit our buffer state.
7810 				 */
7811 				if (ecb->dte_size)
7812 					buf->dtb_offset = offs + ecb->dte_size;
7813 				buf = &state->dts_buffer[cpuid];
7814 				dtrace_speculation_commit(state, cpuid, val);
7815 				committed = 1;
7816 				continue;
7817 
7818 			case DTRACEACT_DISCARD:
7819 				dtrace_speculation_discard(state, cpuid, val);
7820 				continue;
7821 
7822 			case DTRACEACT_DIFEXPR:
7823 			case DTRACEACT_LIBACT:
7824 			case DTRACEACT_PRINTF:
7825 			case DTRACEACT_PRINTA:
7826 			case DTRACEACT_SYSTEM:
7827 			case DTRACEACT_FREOPEN:
7828 			case DTRACEACT_TRACEMEM:
7829 				break;
7830 
7831 			case DTRACEACT_TRACEMEM_DYNSIZE:
7832 				tracememsize = val;
7833 				break;
7834 
7835 			case DTRACEACT_SYM:
7836 			case DTRACEACT_MOD:
7837 				if (!dtrace_priv_kernel(state))
7838 					continue;
7839 				break;
7840 
7841 			case DTRACEACT_USYM:
7842 			case DTRACEACT_UMOD:
7843 			case DTRACEACT_UADDR: {
7844 #ifdef illumos
7845 				struct pid *pid = curthread->t_procp->p_pidp;
7846 #endif
7847 
7848 				if (!dtrace_priv_proc(state))
7849 					continue;
7850 
7851 				DTRACE_STORE(uint64_t, tomax,
7852 #ifdef illumos
7853 				    valoffs, (uint64_t)pid->pid_id);
7854 #else
7855 				    valoffs, (uint64_t) curproc->p_pid);
7856 #endif
7857 				DTRACE_STORE(uint64_t, tomax,
7858 				    valoffs + sizeof (uint64_t), val);
7859 
7860 				continue;
7861 			}
7862 
7863 			case DTRACEACT_EXIT: {
7864 				/*
7865 				 * For the exit action, we are going to attempt
7866 				 * to atomically set our activity to be
7867 				 * draining.  If this fails (either because
7868 				 * another CPU has beat us to the exit action,
7869 				 * or because our current activity is something
7870 				 * other than ACTIVE or WARMUP), we will
7871 				 * continue.  This assures that the exit action
7872 				 * can be successfully recorded at most once
7873 				 * when we're in the ACTIVE state.  If we're
7874 				 * encountering the exit() action while in
7875 				 * COOLDOWN, however, we want to honor the new
7876 				 * status code.  (We know that we're the only
7877 				 * thread in COOLDOWN, so there is no race.)
7878 				 */
7879 				void *activity = &state->dts_activity;
7880 				dtrace_activity_t curstate = state->dts_activity;
7881 
7882 				if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7883 					break;
7884 
7885 				if (curstate != DTRACE_ACTIVITY_WARMUP)
7886 					curstate = DTRACE_ACTIVITY_ACTIVE;
7887 
7888 				if (dtrace_cas32(activity, curstate,
7889 				    DTRACE_ACTIVITY_DRAINING) != curstate) {
7890 					*flags |= CPU_DTRACE_DROP;
7891 					continue;
7892 				}
7893 
7894 				break;
7895 			}
7896 
7897 			default:
7898 				ASSERT(0);
7899 			}
7900 
7901 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7902 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7903 				uintptr_t end = valoffs + size;
7904 
7905 				if (tracememsize != 0 &&
7906 				    valoffs + tracememsize < end) {
7907 					end = valoffs + tracememsize;
7908 					tracememsize = 0;
7909 				}
7910 
7911 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7912 				    !dtrace_vcanload((void *)(uintptr_t)val,
7913 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7914 					continue;
7915 
7916 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7917 				    &val, end, act->dta_intuple,
7918 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7919 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7920 				continue;
7921 			}
7922 
7923 			switch (size) {
7924 			case 0:
7925 				break;
7926 
7927 			case sizeof (uint8_t):
7928 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7929 				break;
7930 			case sizeof (uint16_t):
7931 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7932 				break;
7933 			case sizeof (uint32_t):
7934 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7935 				break;
7936 			case sizeof (uint64_t):
7937 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7938 				break;
7939 			default:
7940 				/*
7941 				 * Any other size should have been returned by
7942 				 * reference, not by value.
7943 				 */
7944 				ASSERT(0);
7945 				break;
7946 			}
7947 		}
7948 
7949 		if (*flags & CPU_DTRACE_DROP)
7950 			continue;
7951 
7952 		if (*flags & CPU_DTRACE_FAULT) {
7953 			int ndx;
7954 			dtrace_action_t *err;
7955 
7956 			buf->dtb_errors++;
7957 
7958 			if (probe->dtpr_id == dtrace_probeid_error) {
7959 				/*
7960 				 * There's nothing we can do -- we had an
7961 				 * error on the error probe.  We bump an
7962 				 * error counter to at least indicate that
7963 				 * this condition happened.
7964 				 */
7965 				dtrace_error(&state->dts_dblerrors);
7966 				continue;
7967 			}
7968 
7969 			if (vtime) {
7970 				/*
7971 				 * Before recursing on dtrace_probe(), we
7972 				 * need to explicitly clear out our start
7973 				 * time to prevent it from being accumulated
7974 				 * into t_dtrace_vtime.
7975 				 */
7976 				curthread->t_dtrace_start = 0;
7977 			}
7978 
7979 			/*
7980 			 * Iterate over the actions to figure out which action
7981 			 * we were processing when we experienced the error.
7982 			 * Note that act points _past_ the faulting action; if
7983 			 * act is ecb->dte_action, the fault was in the
7984 			 * predicate, if it's ecb->dte_action->dta_next it's
7985 			 * in action #1, and so on.
7986 			 */
7987 			for (err = ecb->dte_action, ndx = 0;
7988 			    err != act; err = err->dta_next, ndx++)
7989 				continue;
7990 
7991 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7992 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7993 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7994 			    cpu_core[cpuid].cpuc_dtrace_illval);
7995 
7996 			continue;
7997 		}
7998 
7999 		if (!committed)
8000 			buf->dtb_offset = offs + ecb->dte_size;
8001 	}
8002 
8003 	if (vtime)
8004 		curthread->t_dtrace_start = dtrace_gethrtime();
8005 
8006 	dtrace_probe_exit(cookie);
8007 }
8008 
8009 /*
8010  * DTrace Probe Hashing Functions
8011  *
8012  * The functions in this section (and indeed, the functions in remaining
8013  * sections) are not _called_ from probe context.  (Any exceptions to this are
8014  * marked with a "Note:".)  Rather, they are called from elsewhere in the
8015  * DTrace framework to look-up probes in, add probes to and remove probes from
8016  * the DTrace probe hashes.  (Each probe is hashed by each element of the
8017  * probe tuple -- allowing for fast lookups, regardless of what was
8018  * specified.)
8019  */
8020 static uint_t
8021 dtrace_hash_str(const char *p)
8022 {
8023 	unsigned int g;
8024 	uint_t hval = 0;
8025 
8026 	while (*p) {
8027 		hval = (hval << 4) + *p++;
8028 		if ((g = (hval & 0xf0000000)) != 0)
8029 			hval ^= g >> 24;
8030 		hval &= ~g;
8031 	}
8032 	return (hval);
8033 }
8034 
8035 static dtrace_hash_t *
8036 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
8037 {
8038 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8039 
8040 	hash->dth_stroffs = stroffs;
8041 	hash->dth_nextoffs = nextoffs;
8042 	hash->dth_prevoffs = prevoffs;
8043 
8044 	hash->dth_size = 1;
8045 	hash->dth_mask = hash->dth_size - 1;
8046 
8047 	hash->dth_tab = kmem_zalloc(hash->dth_size *
8048 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8049 
8050 	return (hash);
8051 }
8052 
8053 static void
8054 dtrace_hash_destroy(dtrace_hash_t *hash)
8055 {
8056 #ifdef DEBUG
8057 	int i;
8058 
8059 	for (i = 0; i < hash->dth_size; i++)
8060 		ASSERT(hash->dth_tab[i] == NULL);
8061 #endif
8062 
8063 	kmem_free(hash->dth_tab,
8064 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
8065 	kmem_free(hash, sizeof (dtrace_hash_t));
8066 }
8067 
8068 static void
8069 dtrace_hash_resize(dtrace_hash_t *hash)
8070 {
8071 	int size = hash->dth_size, i, ndx;
8072 	int new_size = hash->dth_size << 1;
8073 	int new_mask = new_size - 1;
8074 	dtrace_hashbucket_t **new_tab, *bucket, *next;
8075 
8076 	ASSERT((new_size & new_mask) == 0);
8077 
8078 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8079 
8080 	for (i = 0; i < size; i++) {
8081 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8082 			dtrace_probe_t *probe = bucket->dthb_chain;
8083 
8084 			ASSERT(probe != NULL);
8085 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8086 
8087 			next = bucket->dthb_next;
8088 			bucket->dthb_next = new_tab[ndx];
8089 			new_tab[ndx] = bucket;
8090 		}
8091 	}
8092 
8093 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8094 	hash->dth_tab = new_tab;
8095 	hash->dth_size = new_size;
8096 	hash->dth_mask = new_mask;
8097 }
8098 
8099 static void
8100 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8101 {
8102 	int hashval = DTRACE_HASHSTR(hash, new);
8103 	int ndx = hashval & hash->dth_mask;
8104 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8105 	dtrace_probe_t **nextp, **prevp;
8106 
8107 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8108 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8109 			goto add;
8110 	}
8111 
8112 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8113 		dtrace_hash_resize(hash);
8114 		dtrace_hash_add(hash, new);
8115 		return;
8116 	}
8117 
8118 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8119 	bucket->dthb_next = hash->dth_tab[ndx];
8120 	hash->dth_tab[ndx] = bucket;
8121 	hash->dth_nbuckets++;
8122 
8123 add:
8124 	nextp = DTRACE_HASHNEXT(hash, new);
8125 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8126 	*nextp = bucket->dthb_chain;
8127 
8128 	if (bucket->dthb_chain != NULL) {
8129 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8130 		ASSERT(*prevp == NULL);
8131 		*prevp = new;
8132 	}
8133 
8134 	bucket->dthb_chain = new;
8135 	bucket->dthb_len++;
8136 }
8137 
8138 static dtrace_probe_t *
8139 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8140 {
8141 	int hashval = DTRACE_HASHSTR(hash, template);
8142 	int ndx = hashval & hash->dth_mask;
8143 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8144 
8145 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8146 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8147 			return (bucket->dthb_chain);
8148 	}
8149 
8150 	return (NULL);
8151 }
8152 
8153 static int
8154 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8155 {
8156 	int hashval = DTRACE_HASHSTR(hash, template);
8157 	int ndx = hashval & hash->dth_mask;
8158 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8159 
8160 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8161 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8162 			return (bucket->dthb_len);
8163 	}
8164 
8165 	return (0);
8166 }
8167 
8168 static void
8169 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8170 {
8171 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8172 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8173 
8174 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8175 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8176 
8177 	/*
8178 	 * Find the bucket that we're removing this probe from.
8179 	 */
8180 	for (; bucket != NULL; bucket = bucket->dthb_next) {
8181 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8182 			break;
8183 	}
8184 
8185 	ASSERT(bucket != NULL);
8186 
8187 	if (*prevp == NULL) {
8188 		if (*nextp == NULL) {
8189 			/*
8190 			 * The removed probe was the only probe on this
8191 			 * bucket; we need to remove the bucket.
8192 			 */
8193 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8194 
8195 			ASSERT(bucket->dthb_chain == probe);
8196 			ASSERT(b != NULL);
8197 
8198 			if (b == bucket) {
8199 				hash->dth_tab[ndx] = bucket->dthb_next;
8200 			} else {
8201 				while (b->dthb_next != bucket)
8202 					b = b->dthb_next;
8203 				b->dthb_next = bucket->dthb_next;
8204 			}
8205 
8206 			ASSERT(hash->dth_nbuckets > 0);
8207 			hash->dth_nbuckets--;
8208 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8209 			return;
8210 		}
8211 
8212 		bucket->dthb_chain = *nextp;
8213 	} else {
8214 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8215 	}
8216 
8217 	if (*nextp != NULL)
8218 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8219 }
8220 
8221 /*
8222  * DTrace Utility Functions
8223  *
8224  * These are random utility functions that are _not_ called from probe context.
8225  */
8226 static int
8227 dtrace_badattr(const dtrace_attribute_t *a)
8228 {
8229 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8230 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8231 	    a->dtat_class > DTRACE_CLASS_MAX);
8232 }
8233 
8234 /*
8235  * Return a duplicate copy of a string.  If the specified string is NULL,
8236  * this function returns a zero-length string.
8237  */
8238 static char *
8239 dtrace_strdup(const char *str)
8240 {
8241 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8242 
8243 	if (str != NULL)
8244 		(void) strcpy(new, str);
8245 
8246 	return (new);
8247 }
8248 
8249 #define	DTRACE_ISALPHA(c)	\
8250 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8251 
8252 static int
8253 dtrace_badname(const char *s)
8254 {
8255 	char c;
8256 
8257 	if (s == NULL || (c = *s++) == '\0')
8258 		return (0);
8259 
8260 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8261 		return (1);
8262 
8263 	while ((c = *s++) != '\0') {
8264 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8265 		    c != '-' && c != '_' && c != '.' && c != '`')
8266 			return (1);
8267 	}
8268 
8269 	return (0);
8270 }
8271 
8272 static void
8273 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8274 {
8275 	uint32_t priv;
8276 
8277 #ifdef illumos
8278 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8279 		/*
8280 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8281 		 */
8282 		priv = DTRACE_PRIV_ALL;
8283 	} else {
8284 		*uidp = crgetuid(cr);
8285 		*zoneidp = crgetzoneid(cr);
8286 
8287 		priv = 0;
8288 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8289 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8290 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8291 			priv |= DTRACE_PRIV_USER;
8292 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8293 			priv |= DTRACE_PRIV_PROC;
8294 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8295 			priv |= DTRACE_PRIV_OWNER;
8296 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8297 			priv |= DTRACE_PRIV_ZONEOWNER;
8298 	}
8299 #else
8300 	priv = DTRACE_PRIV_ALL;
8301 #endif
8302 
8303 	*privp = priv;
8304 }
8305 
8306 #ifdef DTRACE_ERRDEBUG
8307 static void
8308 dtrace_errdebug(const char *str)
8309 {
8310 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8311 	int occupied = 0;
8312 
8313 	mutex_enter(&dtrace_errlock);
8314 	dtrace_errlast = str;
8315 	dtrace_errthread = curthread;
8316 
8317 	while (occupied++ < DTRACE_ERRHASHSZ) {
8318 		if (dtrace_errhash[hval].dter_msg == str) {
8319 			dtrace_errhash[hval].dter_count++;
8320 			goto out;
8321 		}
8322 
8323 		if (dtrace_errhash[hval].dter_msg != NULL) {
8324 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8325 			continue;
8326 		}
8327 
8328 		dtrace_errhash[hval].dter_msg = str;
8329 		dtrace_errhash[hval].dter_count = 1;
8330 		goto out;
8331 	}
8332 
8333 	panic("dtrace: undersized error hash");
8334 out:
8335 	mutex_exit(&dtrace_errlock);
8336 }
8337 #endif
8338 
8339 /*
8340  * DTrace Matching Functions
8341  *
8342  * These functions are used to match groups of probes, given some elements of
8343  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8344  */
8345 static int
8346 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8347     zoneid_t zoneid)
8348 {
8349 	if (priv != DTRACE_PRIV_ALL) {
8350 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8351 		uint32_t match = priv & ppriv;
8352 
8353 		/*
8354 		 * No PRIV_DTRACE_* privileges...
8355 		 */
8356 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8357 		    DTRACE_PRIV_KERNEL)) == 0)
8358 			return (0);
8359 
8360 		/*
8361 		 * No matching bits, but there were bits to match...
8362 		 */
8363 		if (match == 0 && ppriv != 0)
8364 			return (0);
8365 
8366 		/*
8367 		 * Need to have permissions to the process, but don't...
8368 		 */
8369 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8370 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8371 			return (0);
8372 		}
8373 
8374 		/*
8375 		 * Need to be in the same zone unless we possess the
8376 		 * privilege to examine all zones.
8377 		 */
8378 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8379 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8380 			return (0);
8381 		}
8382 	}
8383 
8384 	return (1);
8385 }
8386 
8387 /*
8388  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8389  * consists of input pattern strings and an ops-vector to evaluate them.
8390  * This function returns >0 for match, 0 for no match, and <0 for error.
8391  */
8392 static int
8393 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8394     uint32_t priv, uid_t uid, zoneid_t zoneid)
8395 {
8396 	dtrace_provider_t *pvp = prp->dtpr_provider;
8397 	int rv;
8398 
8399 	if (pvp->dtpv_defunct)
8400 		return (0);
8401 
8402 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8403 		return (rv);
8404 
8405 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8406 		return (rv);
8407 
8408 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8409 		return (rv);
8410 
8411 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8412 		return (rv);
8413 
8414 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8415 		return (0);
8416 
8417 	return (rv);
8418 }
8419 
8420 /*
8421  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8422  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8423  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8424  * In addition, all of the recursion cases except for '*' matching have been
8425  * unwound.  For '*', we still implement recursive evaluation, but a depth
8426  * counter is maintained and matching is aborted if we recurse too deep.
8427  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8428  */
8429 static int
8430 dtrace_match_glob(const char *s, const char *p, int depth)
8431 {
8432 	const char *olds;
8433 	char s1, c;
8434 	int gs;
8435 
8436 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8437 		return (-1);
8438 
8439 	if (s == NULL)
8440 		s = ""; /* treat NULL as empty string */
8441 
8442 top:
8443 	olds = s;
8444 	s1 = *s++;
8445 
8446 	if (p == NULL)
8447 		return (0);
8448 
8449 	if ((c = *p++) == '\0')
8450 		return (s1 == '\0');
8451 
8452 	switch (c) {
8453 	case '[': {
8454 		int ok = 0, notflag = 0;
8455 		char lc = '\0';
8456 
8457 		if (s1 == '\0')
8458 			return (0);
8459 
8460 		if (*p == '!') {
8461 			notflag = 1;
8462 			p++;
8463 		}
8464 
8465 		if ((c = *p++) == '\0')
8466 			return (0);
8467 
8468 		do {
8469 			if (c == '-' && lc != '\0' && *p != ']') {
8470 				if ((c = *p++) == '\0')
8471 					return (0);
8472 				if (c == '\\' && (c = *p++) == '\0')
8473 					return (0);
8474 
8475 				if (notflag) {
8476 					if (s1 < lc || s1 > c)
8477 						ok++;
8478 					else
8479 						return (0);
8480 				} else if (lc <= s1 && s1 <= c)
8481 					ok++;
8482 
8483 			} else if (c == '\\' && (c = *p++) == '\0')
8484 				return (0);
8485 
8486 			lc = c; /* save left-hand 'c' for next iteration */
8487 
8488 			if (notflag) {
8489 				if (s1 != c)
8490 					ok++;
8491 				else
8492 					return (0);
8493 			} else if (s1 == c)
8494 				ok++;
8495 
8496 			if ((c = *p++) == '\0')
8497 				return (0);
8498 
8499 		} while (c != ']');
8500 
8501 		if (ok)
8502 			goto top;
8503 
8504 		return (0);
8505 	}
8506 
8507 	case '\\':
8508 		if ((c = *p++) == '\0')
8509 			return (0);
8510 		/*FALLTHRU*/
8511 
8512 	default:
8513 		if (c != s1)
8514 			return (0);
8515 		/*FALLTHRU*/
8516 
8517 	case '?':
8518 		if (s1 != '\0')
8519 			goto top;
8520 		return (0);
8521 
8522 	case '*':
8523 		while (*p == '*')
8524 			p++; /* consecutive *'s are identical to a single one */
8525 
8526 		if (*p == '\0')
8527 			return (1);
8528 
8529 		for (s = olds; *s != '\0'; s++) {
8530 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8531 				return (gs);
8532 		}
8533 
8534 		return (0);
8535 	}
8536 }
8537 
8538 /*ARGSUSED*/
8539 static int
8540 dtrace_match_string(const char *s, const char *p, int depth)
8541 {
8542 	return (s != NULL && strcmp(s, p) == 0);
8543 }
8544 
8545 /*ARGSUSED*/
8546 static int
8547 dtrace_match_nul(const char *s, const char *p, int depth)
8548 {
8549 	return (1); /* always match the empty pattern */
8550 }
8551 
8552 /*ARGSUSED*/
8553 static int
8554 dtrace_match_nonzero(const char *s, const char *p, int depth)
8555 {
8556 	return (s != NULL && s[0] != '\0');
8557 }
8558 
8559 static int
8560 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8561     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8562 {
8563 	dtrace_probe_t template, *probe;
8564 	dtrace_hash_t *hash = NULL;
8565 	int len, best = INT_MAX, nmatched = 0;
8566 	dtrace_id_t i;
8567 
8568 	ASSERT(MUTEX_HELD(&dtrace_lock));
8569 
8570 	/*
8571 	 * If the probe ID is specified in the key, just lookup by ID and
8572 	 * invoke the match callback once if a matching probe is found.
8573 	 */
8574 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8575 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8576 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8577 			(void) (*matched)(probe, arg);
8578 			nmatched++;
8579 		}
8580 		return (nmatched);
8581 	}
8582 
8583 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8584 	template.dtpr_func = (char *)pkp->dtpk_func;
8585 	template.dtpr_name = (char *)pkp->dtpk_name;
8586 
8587 	/*
8588 	 * We want to find the most distinct of the module name, function
8589 	 * name, and name.  So for each one that is not a glob pattern or
8590 	 * empty string, we perform a lookup in the corresponding hash and
8591 	 * use the hash table with the fewest collisions to do our search.
8592 	 */
8593 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8594 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8595 		best = len;
8596 		hash = dtrace_bymod;
8597 	}
8598 
8599 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8600 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8601 		best = len;
8602 		hash = dtrace_byfunc;
8603 	}
8604 
8605 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8606 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8607 		best = len;
8608 		hash = dtrace_byname;
8609 	}
8610 
8611 	/*
8612 	 * If we did not select a hash table, iterate over every probe and
8613 	 * invoke our callback for each one that matches our input probe key.
8614 	 */
8615 	if (hash == NULL) {
8616 		for (i = 0; i < dtrace_nprobes; i++) {
8617 			if ((probe = dtrace_probes[i]) == NULL ||
8618 			    dtrace_match_probe(probe, pkp, priv, uid,
8619 			    zoneid) <= 0)
8620 				continue;
8621 
8622 			nmatched++;
8623 
8624 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8625 				break;
8626 		}
8627 
8628 		return (nmatched);
8629 	}
8630 
8631 	/*
8632 	 * If we selected a hash table, iterate over each probe of the same key
8633 	 * name and invoke the callback for every probe that matches the other
8634 	 * attributes of our input probe key.
8635 	 */
8636 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8637 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8638 
8639 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8640 			continue;
8641 
8642 		nmatched++;
8643 
8644 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8645 			break;
8646 	}
8647 
8648 	return (nmatched);
8649 }
8650 
8651 /*
8652  * Return the function pointer dtrace_probecmp() should use to compare the
8653  * specified pattern with a string.  For NULL or empty patterns, we select
8654  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8655  * For non-empty non-glob strings, we use dtrace_match_string().
8656  */
8657 static dtrace_probekey_f *
8658 dtrace_probekey_func(const char *p)
8659 {
8660 	char c;
8661 
8662 	if (p == NULL || *p == '\0')
8663 		return (&dtrace_match_nul);
8664 
8665 	while ((c = *p++) != '\0') {
8666 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8667 			return (&dtrace_match_glob);
8668 	}
8669 
8670 	return (&dtrace_match_string);
8671 }
8672 
8673 /*
8674  * Build a probe comparison key for use with dtrace_match_probe() from the
8675  * given probe description.  By convention, a null key only matches anchored
8676  * probes: if each field is the empty string, reset dtpk_fmatch to
8677  * dtrace_match_nonzero().
8678  */
8679 static void
8680 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8681 {
8682 	pkp->dtpk_prov = pdp->dtpd_provider;
8683 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8684 
8685 	pkp->dtpk_mod = pdp->dtpd_mod;
8686 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8687 
8688 	pkp->dtpk_func = pdp->dtpd_func;
8689 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8690 
8691 	pkp->dtpk_name = pdp->dtpd_name;
8692 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8693 
8694 	pkp->dtpk_id = pdp->dtpd_id;
8695 
8696 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8697 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8698 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8699 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8700 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8701 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8702 }
8703 
8704 /*
8705  * DTrace Provider-to-Framework API Functions
8706  *
8707  * These functions implement much of the Provider-to-Framework API, as
8708  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8709  * the functions in the API for probe management (found below), and
8710  * dtrace_probe() itself (found above).
8711  */
8712 
8713 /*
8714  * Register the calling provider with the DTrace framework.  This should
8715  * generally be called by DTrace providers in their attach(9E) entry point.
8716  */
8717 int
8718 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8719     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8720 {
8721 	dtrace_provider_t *provider;
8722 
8723 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8724 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8725 		    "arguments", name ? name : "<NULL>");
8726 		return (EINVAL);
8727 	}
8728 
8729 	if (name[0] == '\0' || dtrace_badname(name)) {
8730 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8731 		    "provider name", name);
8732 		return (EINVAL);
8733 	}
8734 
8735 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8736 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8737 	    pops->dtps_destroy == NULL ||
8738 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8739 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8740 		    "provider ops", name);
8741 		return (EINVAL);
8742 	}
8743 
8744 	if (dtrace_badattr(&pap->dtpa_provider) ||
8745 	    dtrace_badattr(&pap->dtpa_mod) ||
8746 	    dtrace_badattr(&pap->dtpa_func) ||
8747 	    dtrace_badattr(&pap->dtpa_name) ||
8748 	    dtrace_badattr(&pap->dtpa_args)) {
8749 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8750 		    "provider attributes", name);
8751 		return (EINVAL);
8752 	}
8753 
8754 	if (priv & ~DTRACE_PRIV_ALL) {
8755 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8756 		    "privilege attributes", name);
8757 		return (EINVAL);
8758 	}
8759 
8760 	if ((priv & DTRACE_PRIV_KERNEL) &&
8761 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8762 	    pops->dtps_usermode == NULL) {
8763 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8764 		    "dtps_usermode() op for given privilege attributes", name);
8765 		return (EINVAL);
8766 	}
8767 
8768 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8769 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8770 	(void) strcpy(provider->dtpv_name, name);
8771 
8772 	provider->dtpv_attr = *pap;
8773 	provider->dtpv_priv.dtpp_flags = priv;
8774 	if (cr != NULL) {
8775 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8776 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8777 	}
8778 	provider->dtpv_pops = *pops;
8779 
8780 	if (pops->dtps_provide == NULL) {
8781 		ASSERT(pops->dtps_provide_module != NULL);
8782 		provider->dtpv_pops.dtps_provide =
8783 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8784 	}
8785 
8786 	if (pops->dtps_provide_module == NULL) {
8787 		ASSERT(pops->dtps_provide != NULL);
8788 		provider->dtpv_pops.dtps_provide_module =
8789 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8790 	}
8791 
8792 	if (pops->dtps_suspend == NULL) {
8793 		ASSERT(pops->dtps_resume == NULL);
8794 		provider->dtpv_pops.dtps_suspend =
8795 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8796 		provider->dtpv_pops.dtps_resume =
8797 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8798 	}
8799 
8800 	provider->dtpv_arg = arg;
8801 	*idp = (dtrace_provider_id_t)provider;
8802 
8803 	if (pops == &dtrace_provider_ops) {
8804 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8805 		ASSERT(MUTEX_HELD(&dtrace_lock));
8806 		ASSERT(dtrace_anon.dta_enabling == NULL);
8807 
8808 		/*
8809 		 * We make sure that the DTrace provider is at the head of
8810 		 * the provider chain.
8811 		 */
8812 		provider->dtpv_next = dtrace_provider;
8813 		dtrace_provider = provider;
8814 		return (0);
8815 	}
8816 
8817 	mutex_enter(&dtrace_provider_lock);
8818 	mutex_enter(&dtrace_lock);
8819 
8820 	/*
8821 	 * If there is at least one provider registered, we'll add this
8822 	 * provider after the first provider.
8823 	 */
8824 	if (dtrace_provider != NULL) {
8825 		provider->dtpv_next = dtrace_provider->dtpv_next;
8826 		dtrace_provider->dtpv_next = provider;
8827 	} else {
8828 		dtrace_provider = provider;
8829 	}
8830 
8831 	if (dtrace_retained != NULL) {
8832 		dtrace_enabling_provide(provider);
8833 
8834 		/*
8835 		 * Now we need to call dtrace_enabling_matchall() -- which
8836 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8837 		 * to drop all of our locks before calling into it...
8838 		 */
8839 		mutex_exit(&dtrace_lock);
8840 		mutex_exit(&dtrace_provider_lock);
8841 		dtrace_enabling_matchall();
8842 
8843 		return (0);
8844 	}
8845 
8846 	mutex_exit(&dtrace_lock);
8847 	mutex_exit(&dtrace_provider_lock);
8848 
8849 	return (0);
8850 }
8851 
8852 /*
8853  * Unregister the specified provider from the DTrace framework.  This should
8854  * generally be called by DTrace providers in their detach(9E) entry point.
8855  */
8856 int
8857 dtrace_unregister(dtrace_provider_id_t id)
8858 {
8859 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8860 	dtrace_provider_t *prev = NULL;
8861 	int i, self = 0, noreap = 0;
8862 	dtrace_probe_t *probe, *first = NULL;
8863 
8864 	if (old->dtpv_pops.dtps_enable ==
8865 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8866 		/*
8867 		 * If DTrace itself is the provider, we're called with locks
8868 		 * already held.
8869 		 */
8870 		ASSERT(old == dtrace_provider);
8871 #ifdef illumos
8872 		ASSERT(dtrace_devi != NULL);
8873 #endif
8874 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8875 		ASSERT(MUTEX_HELD(&dtrace_lock));
8876 		self = 1;
8877 
8878 		if (dtrace_provider->dtpv_next != NULL) {
8879 			/*
8880 			 * There's another provider here; return failure.
8881 			 */
8882 			return (EBUSY);
8883 		}
8884 	} else {
8885 		mutex_enter(&dtrace_provider_lock);
8886 #ifdef illumos
8887 		mutex_enter(&mod_lock);
8888 #endif
8889 		mutex_enter(&dtrace_lock);
8890 	}
8891 
8892 	/*
8893 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8894 	 * probes, we refuse to let providers slither away, unless this
8895 	 * provider has already been explicitly invalidated.
8896 	 */
8897 	if (!old->dtpv_defunct &&
8898 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8899 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8900 		if (!self) {
8901 			mutex_exit(&dtrace_lock);
8902 #ifdef illumos
8903 			mutex_exit(&mod_lock);
8904 #endif
8905 			mutex_exit(&dtrace_provider_lock);
8906 		}
8907 		return (EBUSY);
8908 	}
8909 
8910 	/*
8911 	 * Attempt to destroy the probes associated with this provider.
8912 	 */
8913 	for (i = 0; i < dtrace_nprobes; i++) {
8914 		if ((probe = dtrace_probes[i]) == NULL)
8915 			continue;
8916 
8917 		if (probe->dtpr_provider != old)
8918 			continue;
8919 
8920 		if (probe->dtpr_ecb == NULL)
8921 			continue;
8922 
8923 		/*
8924 		 * If we are trying to unregister a defunct provider, and the
8925 		 * provider was made defunct within the interval dictated by
8926 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8927 		 * attempt to reap our enablings.  To denote that the provider
8928 		 * should reattempt to unregister itself at some point in the
8929 		 * future, we will return a differentiable error code (EAGAIN
8930 		 * instead of EBUSY) in this case.
8931 		 */
8932 		if (dtrace_gethrtime() - old->dtpv_defunct >
8933 		    dtrace_unregister_defunct_reap)
8934 			noreap = 1;
8935 
8936 		if (!self) {
8937 			mutex_exit(&dtrace_lock);
8938 #ifdef illumos
8939 			mutex_exit(&mod_lock);
8940 #endif
8941 			mutex_exit(&dtrace_provider_lock);
8942 		}
8943 
8944 		if (noreap)
8945 			return (EBUSY);
8946 
8947 		(void) taskq_dispatch(dtrace_taskq,
8948 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8949 
8950 		return (EAGAIN);
8951 	}
8952 
8953 	/*
8954 	 * All of the probes for this provider are disabled; we can safely
8955 	 * remove all of them from their hash chains and from the probe array.
8956 	 */
8957 	for (i = 0; i < dtrace_nprobes; i++) {
8958 		if ((probe = dtrace_probes[i]) == NULL)
8959 			continue;
8960 
8961 		if (probe->dtpr_provider != old)
8962 			continue;
8963 
8964 		dtrace_probes[i] = NULL;
8965 
8966 		dtrace_hash_remove(dtrace_bymod, probe);
8967 		dtrace_hash_remove(dtrace_byfunc, probe);
8968 		dtrace_hash_remove(dtrace_byname, probe);
8969 
8970 		if (first == NULL) {
8971 			first = probe;
8972 			probe->dtpr_nextmod = NULL;
8973 		} else {
8974 			probe->dtpr_nextmod = first;
8975 			first = probe;
8976 		}
8977 	}
8978 
8979 	/*
8980 	 * The provider's probes have been removed from the hash chains and
8981 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8982 	 * everyone has cleared out from any probe array processing.
8983 	 */
8984 	dtrace_sync();
8985 
8986 	for (probe = first; probe != NULL; probe = first) {
8987 		first = probe->dtpr_nextmod;
8988 
8989 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8990 		    probe->dtpr_arg);
8991 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8992 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8993 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8994 #ifdef illumos
8995 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8996 #else
8997 		free_unr(dtrace_arena, probe->dtpr_id);
8998 #endif
8999 		kmem_free(probe, sizeof (dtrace_probe_t));
9000 	}
9001 
9002 	if ((prev = dtrace_provider) == old) {
9003 #ifdef illumos
9004 		ASSERT(self || dtrace_devi == NULL);
9005 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9006 #endif
9007 		dtrace_provider = old->dtpv_next;
9008 	} else {
9009 		while (prev != NULL && prev->dtpv_next != old)
9010 			prev = prev->dtpv_next;
9011 
9012 		if (prev == NULL) {
9013 			panic("attempt to unregister non-existent "
9014 			    "dtrace provider %p\n", (void *)id);
9015 		}
9016 
9017 		prev->dtpv_next = old->dtpv_next;
9018 	}
9019 
9020 	if (!self) {
9021 		mutex_exit(&dtrace_lock);
9022 #ifdef illumos
9023 		mutex_exit(&mod_lock);
9024 #endif
9025 		mutex_exit(&dtrace_provider_lock);
9026 	}
9027 
9028 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9029 	kmem_free(old, sizeof (dtrace_provider_t));
9030 
9031 	return (0);
9032 }
9033 
9034 /*
9035  * Invalidate the specified provider.  All subsequent probe lookups for the
9036  * specified provider will fail, but its probes will not be removed.
9037  */
9038 void
9039 dtrace_invalidate(dtrace_provider_id_t id)
9040 {
9041 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9042 
9043 	ASSERT(pvp->dtpv_pops.dtps_enable !=
9044 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9045 
9046 	mutex_enter(&dtrace_provider_lock);
9047 	mutex_enter(&dtrace_lock);
9048 
9049 	pvp->dtpv_defunct = dtrace_gethrtime();
9050 
9051 	mutex_exit(&dtrace_lock);
9052 	mutex_exit(&dtrace_provider_lock);
9053 }
9054 
9055 /*
9056  * Indicate whether or not DTrace has attached.
9057  */
9058 int
9059 dtrace_attached(void)
9060 {
9061 	/*
9062 	 * dtrace_provider will be non-NULL iff the DTrace driver has
9063 	 * attached.  (It's non-NULL because DTrace is always itself a
9064 	 * provider.)
9065 	 */
9066 	return (dtrace_provider != NULL);
9067 }
9068 
9069 /*
9070  * Remove all the unenabled probes for the given provider.  This function is
9071  * not unlike dtrace_unregister(), except that it doesn't remove the provider
9072  * -- just as many of its associated probes as it can.
9073  */
9074 int
9075 dtrace_condense(dtrace_provider_id_t id)
9076 {
9077 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
9078 	int i;
9079 	dtrace_probe_t *probe;
9080 
9081 	/*
9082 	 * Make sure this isn't the dtrace provider itself.
9083 	 */
9084 	ASSERT(prov->dtpv_pops.dtps_enable !=
9085 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9086 
9087 	mutex_enter(&dtrace_provider_lock);
9088 	mutex_enter(&dtrace_lock);
9089 
9090 	/*
9091 	 * Attempt to destroy the probes associated with this provider.
9092 	 */
9093 	for (i = 0; i < dtrace_nprobes; i++) {
9094 		if ((probe = dtrace_probes[i]) == NULL)
9095 			continue;
9096 
9097 		if (probe->dtpr_provider != prov)
9098 			continue;
9099 
9100 		if (probe->dtpr_ecb != NULL)
9101 			continue;
9102 
9103 		dtrace_probes[i] = NULL;
9104 
9105 		dtrace_hash_remove(dtrace_bymod, probe);
9106 		dtrace_hash_remove(dtrace_byfunc, probe);
9107 		dtrace_hash_remove(dtrace_byname, probe);
9108 
9109 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9110 		    probe->dtpr_arg);
9111 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9112 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9113 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9114 		kmem_free(probe, sizeof (dtrace_probe_t));
9115 #ifdef illumos
9116 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9117 #else
9118 		free_unr(dtrace_arena, i + 1);
9119 #endif
9120 	}
9121 
9122 	mutex_exit(&dtrace_lock);
9123 	mutex_exit(&dtrace_provider_lock);
9124 
9125 	return (0);
9126 }
9127 
9128 /*
9129  * DTrace Probe Management Functions
9130  *
9131  * The functions in this section perform the DTrace probe management,
9132  * including functions to create probes, look-up probes, and call into the
9133  * providers to request that probes be provided.  Some of these functions are
9134  * in the Provider-to-Framework API; these functions can be identified by the
9135  * fact that they are not declared "static".
9136  */
9137 
9138 /*
9139  * Create a probe with the specified module name, function name, and name.
9140  */
9141 dtrace_id_t
9142 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9143     const char *func, const char *name, int aframes, void *arg)
9144 {
9145 	dtrace_probe_t *probe, **probes;
9146 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9147 	dtrace_id_t id;
9148 
9149 	if (provider == dtrace_provider) {
9150 		ASSERT(MUTEX_HELD(&dtrace_lock));
9151 	} else {
9152 		mutex_enter(&dtrace_lock);
9153 	}
9154 
9155 #ifdef illumos
9156 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9157 	    VM_BESTFIT | VM_SLEEP);
9158 #else
9159 	id = alloc_unr(dtrace_arena);
9160 #endif
9161 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9162 
9163 	probe->dtpr_id = id;
9164 	probe->dtpr_gen = dtrace_probegen++;
9165 	probe->dtpr_mod = dtrace_strdup(mod);
9166 	probe->dtpr_func = dtrace_strdup(func);
9167 	probe->dtpr_name = dtrace_strdup(name);
9168 	probe->dtpr_arg = arg;
9169 	probe->dtpr_aframes = aframes;
9170 	probe->dtpr_provider = provider;
9171 
9172 	dtrace_hash_add(dtrace_bymod, probe);
9173 	dtrace_hash_add(dtrace_byfunc, probe);
9174 	dtrace_hash_add(dtrace_byname, probe);
9175 
9176 	if (id - 1 >= dtrace_nprobes) {
9177 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9178 		size_t nsize = osize << 1;
9179 
9180 		if (nsize == 0) {
9181 			ASSERT(osize == 0);
9182 			ASSERT(dtrace_probes == NULL);
9183 			nsize = sizeof (dtrace_probe_t *);
9184 		}
9185 
9186 		probes = kmem_zalloc(nsize, KM_SLEEP);
9187 
9188 		if (dtrace_probes == NULL) {
9189 			ASSERT(osize == 0);
9190 			dtrace_probes = probes;
9191 			dtrace_nprobes = 1;
9192 		} else {
9193 			dtrace_probe_t **oprobes = dtrace_probes;
9194 
9195 			bcopy(oprobes, probes, osize);
9196 			dtrace_membar_producer();
9197 			dtrace_probes = probes;
9198 
9199 			dtrace_sync();
9200 
9201 			/*
9202 			 * All CPUs are now seeing the new probes array; we can
9203 			 * safely free the old array.
9204 			 */
9205 			kmem_free(oprobes, osize);
9206 			dtrace_nprobes <<= 1;
9207 		}
9208 
9209 		ASSERT(id - 1 < dtrace_nprobes);
9210 	}
9211 
9212 	ASSERT(dtrace_probes[id - 1] == NULL);
9213 	dtrace_probes[id - 1] = probe;
9214 
9215 	if (provider != dtrace_provider)
9216 		mutex_exit(&dtrace_lock);
9217 
9218 	return (id);
9219 }
9220 
9221 static dtrace_probe_t *
9222 dtrace_probe_lookup_id(dtrace_id_t id)
9223 {
9224 	ASSERT(MUTEX_HELD(&dtrace_lock));
9225 
9226 	if (id == 0 || id > dtrace_nprobes)
9227 		return (NULL);
9228 
9229 	return (dtrace_probes[id - 1]);
9230 }
9231 
9232 static int
9233 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9234 {
9235 	*((dtrace_id_t *)arg) = probe->dtpr_id;
9236 
9237 	return (DTRACE_MATCH_DONE);
9238 }
9239 
9240 /*
9241  * Look up a probe based on provider and one or more of module name, function
9242  * name and probe name.
9243  */
9244 dtrace_id_t
9245 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9246     char *func, char *name)
9247 {
9248 	dtrace_probekey_t pkey;
9249 	dtrace_id_t id;
9250 	int match;
9251 
9252 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9253 	pkey.dtpk_pmatch = &dtrace_match_string;
9254 	pkey.dtpk_mod = mod;
9255 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9256 	pkey.dtpk_func = func;
9257 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9258 	pkey.dtpk_name = name;
9259 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9260 	pkey.dtpk_id = DTRACE_IDNONE;
9261 
9262 	mutex_enter(&dtrace_lock);
9263 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9264 	    dtrace_probe_lookup_match, &id);
9265 	mutex_exit(&dtrace_lock);
9266 
9267 	ASSERT(match == 1 || match == 0);
9268 	return (match ? id : 0);
9269 }
9270 
9271 /*
9272  * Returns the probe argument associated with the specified probe.
9273  */
9274 void *
9275 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9276 {
9277 	dtrace_probe_t *probe;
9278 	void *rval = NULL;
9279 
9280 	mutex_enter(&dtrace_lock);
9281 
9282 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9283 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9284 		rval = probe->dtpr_arg;
9285 
9286 	mutex_exit(&dtrace_lock);
9287 
9288 	return (rval);
9289 }
9290 
9291 /*
9292  * Copy a probe into a probe description.
9293  */
9294 static void
9295 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9296 {
9297 	bzero(pdp, sizeof (dtrace_probedesc_t));
9298 	pdp->dtpd_id = prp->dtpr_id;
9299 
9300 	(void) strncpy(pdp->dtpd_provider,
9301 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9302 
9303 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9304 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9305 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9306 }
9307 
9308 /*
9309  * Called to indicate that a probe -- or probes -- should be provided by a
9310  * specfied provider.  If the specified description is NULL, the provider will
9311  * be told to provide all of its probes.  (This is done whenever a new
9312  * consumer comes along, or whenever a retained enabling is to be matched.) If
9313  * the specified description is non-NULL, the provider is given the
9314  * opportunity to dynamically provide the specified probe, allowing providers
9315  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9316  * probes.)  If the provider is NULL, the operations will be applied to all
9317  * providers; if the provider is non-NULL the operations will only be applied
9318  * to the specified provider.  The dtrace_provider_lock must be held, and the
9319  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9320  * will need to grab the dtrace_lock when it reenters the framework through
9321  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9322  */
9323 static void
9324 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9325 {
9326 #ifdef illumos
9327 	modctl_t *ctl;
9328 #endif
9329 	int all = 0;
9330 
9331 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9332 
9333 	if (prv == NULL) {
9334 		all = 1;
9335 		prv = dtrace_provider;
9336 	}
9337 
9338 	do {
9339 		/*
9340 		 * First, call the blanket provide operation.
9341 		 */
9342 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9343 
9344 #ifdef illumos
9345 		/*
9346 		 * Now call the per-module provide operation.  We will grab
9347 		 * mod_lock to prevent the list from being modified.  Note
9348 		 * that this also prevents the mod_busy bits from changing.
9349 		 * (mod_busy can only be changed with mod_lock held.)
9350 		 */
9351 		mutex_enter(&mod_lock);
9352 
9353 		ctl = &modules;
9354 		do {
9355 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9356 				continue;
9357 
9358 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9359 
9360 		} while ((ctl = ctl->mod_next) != &modules);
9361 
9362 		mutex_exit(&mod_lock);
9363 #endif
9364 	} while (all && (prv = prv->dtpv_next) != NULL);
9365 }
9366 
9367 #ifdef illumos
9368 /*
9369  * Iterate over each probe, and call the Framework-to-Provider API function
9370  * denoted by offs.
9371  */
9372 static void
9373 dtrace_probe_foreach(uintptr_t offs)
9374 {
9375 	dtrace_provider_t *prov;
9376 	void (*func)(void *, dtrace_id_t, void *);
9377 	dtrace_probe_t *probe;
9378 	dtrace_icookie_t cookie;
9379 	int i;
9380 
9381 	/*
9382 	 * We disable interrupts to walk through the probe array.  This is
9383 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9384 	 * won't see stale data.
9385 	 */
9386 	cookie = dtrace_interrupt_disable();
9387 
9388 	for (i = 0; i < dtrace_nprobes; i++) {
9389 		if ((probe = dtrace_probes[i]) == NULL)
9390 			continue;
9391 
9392 		if (probe->dtpr_ecb == NULL) {
9393 			/*
9394 			 * This probe isn't enabled -- don't call the function.
9395 			 */
9396 			continue;
9397 		}
9398 
9399 		prov = probe->dtpr_provider;
9400 		func = *((void(**)(void *, dtrace_id_t, void *))
9401 		    ((uintptr_t)&prov->dtpv_pops + offs));
9402 
9403 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9404 	}
9405 
9406 	dtrace_interrupt_enable(cookie);
9407 }
9408 #endif
9409 
9410 static int
9411 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9412 {
9413 	dtrace_probekey_t pkey;
9414 	uint32_t priv;
9415 	uid_t uid;
9416 	zoneid_t zoneid;
9417 
9418 	ASSERT(MUTEX_HELD(&dtrace_lock));
9419 	dtrace_ecb_create_cache = NULL;
9420 
9421 	if (desc == NULL) {
9422 		/*
9423 		 * If we're passed a NULL description, we're being asked to
9424 		 * create an ECB with a NULL probe.
9425 		 */
9426 		(void) dtrace_ecb_create_enable(NULL, enab);
9427 		return (0);
9428 	}
9429 
9430 	dtrace_probekey(desc, &pkey);
9431 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9432 	    &priv, &uid, &zoneid);
9433 
9434 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9435 	    enab));
9436 }
9437 
9438 /*
9439  * DTrace Helper Provider Functions
9440  */
9441 static void
9442 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9443 {
9444 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9445 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9446 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9447 }
9448 
9449 static void
9450 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9451     const dof_provider_t *dofprov, char *strtab)
9452 {
9453 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9454 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9455 	    dofprov->dofpv_provattr);
9456 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9457 	    dofprov->dofpv_modattr);
9458 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9459 	    dofprov->dofpv_funcattr);
9460 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9461 	    dofprov->dofpv_nameattr);
9462 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9463 	    dofprov->dofpv_argsattr);
9464 }
9465 
9466 static void
9467 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9468 {
9469 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9470 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9471 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9472 	dof_provider_t *provider;
9473 	dof_probe_t *probe;
9474 	uint32_t *off, *enoff;
9475 	uint8_t *arg;
9476 	char *strtab;
9477 	uint_t i, nprobes;
9478 	dtrace_helper_provdesc_t dhpv;
9479 	dtrace_helper_probedesc_t dhpb;
9480 	dtrace_meta_t *meta = dtrace_meta_pid;
9481 	dtrace_mops_t *mops = &meta->dtm_mops;
9482 	void *parg;
9483 
9484 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9485 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9486 	    provider->dofpv_strtab * dof->dofh_secsize);
9487 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9488 	    provider->dofpv_probes * dof->dofh_secsize);
9489 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9490 	    provider->dofpv_prargs * dof->dofh_secsize);
9491 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9492 	    provider->dofpv_proffs * dof->dofh_secsize);
9493 
9494 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9495 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9496 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9497 	enoff = NULL;
9498 
9499 	/*
9500 	 * See dtrace_helper_provider_validate().
9501 	 */
9502 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9503 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9504 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9505 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9506 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9507 	}
9508 
9509 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9510 
9511 	/*
9512 	 * Create the provider.
9513 	 */
9514 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9515 
9516 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9517 		return;
9518 
9519 	meta->dtm_count++;
9520 
9521 	/*
9522 	 * Create the probes.
9523 	 */
9524 	for (i = 0; i < nprobes; i++) {
9525 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9526 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9527 
9528 		/* See the check in dtrace_helper_provider_validate(). */
9529 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9530 			continue;
9531 
9532 		dhpb.dthpb_mod = dhp->dofhp_mod;
9533 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9534 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9535 		dhpb.dthpb_base = probe->dofpr_addr;
9536 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9537 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9538 		if (enoff != NULL) {
9539 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9540 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9541 		} else {
9542 			dhpb.dthpb_enoffs = NULL;
9543 			dhpb.dthpb_nenoffs = 0;
9544 		}
9545 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9546 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9547 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9548 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9549 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9550 
9551 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9552 	}
9553 }
9554 
9555 static void
9556 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9557 {
9558 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9559 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9560 	int i;
9561 
9562 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9563 
9564 	for (i = 0; i < dof->dofh_secnum; i++) {
9565 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9566 		    dof->dofh_secoff + i * dof->dofh_secsize);
9567 
9568 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9569 			continue;
9570 
9571 		dtrace_helper_provide_one(dhp, sec, pid);
9572 	}
9573 
9574 	/*
9575 	 * We may have just created probes, so we must now rematch against
9576 	 * any retained enablings.  Note that this call will acquire both
9577 	 * cpu_lock and dtrace_lock; the fact that we are holding
9578 	 * dtrace_meta_lock now is what defines the ordering with respect to
9579 	 * these three locks.
9580 	 */
9581 	dtrace_enabling_matchall();
9582 }
9583 
9584 static void
9585 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9586 {
9587 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9588 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9589 	dof_sec_t *str_sec;
9590 	dof_provider_t *provider;
9591 	char *strtab;
9592 	dtrace_helper_provdesc_t dhpv;
9593 	dtrace_meta_t *meta = dtrace_meta_pid;
9594 	dtrace_mops_t *mops = &meta->dtm_mops;
9595 
9596 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9597 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9598 	    provider->dofpv_strtab * dof->dofh_secsize);
9599 
9600 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9601 
9602 	/*
9603 	 * Create the provider.
9604 	 */
9605 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9606 
9607 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9608 
9609 	meta->dtm_count--;
9610 }
9611 
9612 static void
9613 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9614 {
9615 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9616 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9617 	int i;
9618 
9619 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9620 
9621 	for (i = 0; i < dof->dofh_secnum; i++) {
9622 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9623 		    dof->dofh_secoff + i * dof->dofh_secsize);
9624 
9625 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9626 			continue;
9627 
9628 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9629 	}
9630 }
9631 
9632 /*
9633  * DTrace Meta Provider-to-Framework API Functions
9634  *
9635  * These functions implement the Meta Provider-to-Framework API, as described
9636  * in <sys/dtrace.h>.
9637  */
9638 int
9639 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9640     dtrace_meta_provider_id_t *idp)
9641 {
9642 	dtrace_meta_t *meta;
9643 	dtrace_helpers_t *help, *next;
9644 	int i;
9645 
9646 	*idp = DTRACE_METAPROVNONE;
9647 
9648 	/*
9649 	 * We strictly don't need the name, but we hold onto it for
9650 	 * debuggability. All hail error queues!
9651 	 */
9652 	if (name == NULL) {
9653 		cmn_err(CE_WARN, "failed to register meta-provider: "
9654 		    "invalid name");
9655 		return (EINVAL);
9656 	}
9657 
9658 	if (mops == NULL ||
9659 	    mops->dtms_create_probe == NULL ||
9660 	    mops->dtms_provide_pid == NULL ||
9661 	    mops->dtms_remove_pid == NULL) {
9662 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9663 		    "invalid ops", name);
9664 		return (EINVAL);
9665 	}
9666 
9667 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9668 	meta->dtm_mops = *mops;
9669 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9670 	(void) strcpy(meta->dtm_name, name);
9671 	meta->dtm_arg = arg;
9672 
9673 	mutex_enter(&dtrace_meta_lock);
9674 	mutex_enter(&dtrace_lock);
9675 
9676 	if (dtrace_meta_pid != NULL) {
9677 		mutex_exit(&dtrace_lock);
9678 		mutex_exit(&dtrace_meta_lock);
9679 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9680 		    "user-land meta-provider exists", name);
9681 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9682 		kmem_free(meta, sizeof (dtrace_meta_t));
9683 		return (EINVAL);
9684 	}
9685 
9686 	dtrace_meta_pid = meta;
9687 	*idp = (dtrace_meta_provider_id_t)meta;
9688 
9689 	/*
9690 	 * If there are providers and probes ready to go, pass them
9691 	 * off to the new meta provider now.
9692 	 */
9693 
9694 	help = dtrace_deferred_pid;
9695 	dtrace_deferred_pid = NULL;
9696 
9697 	mutex_exit(&dtrace_lock);
9698 
9699 	while (help != NULL) {
9700 		for (i = 0; i < help->dthps_nprovs; i++) {
9701 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9702 			    help->dthps_pid);
9703 		}
9704 
9705 		next = help->dthps_next;
9706 		help->dthps_next = NULL;
9707 		help->dthps_prev = NULL;
9708 		help->dthps_deferred = 0;
9709 		help = next;
9710 	}
9711 
9712 	mutex_exit(&dtrace_meta_lock);
9713 
9714 	return (0);
9715 }
9716 
9717 int
9718 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9719 {
9720 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9721 
9722 	mutex_enter(&dtrace_meta_lock);
9723 	mutex_enter(&dtrace_lock);
9724 
9725 	if (old == dtrace_meta_pid) {
9726 		pp = &dtrace_meta_pid;
9727 	} else {
9728 		panic("attempt to unregister non-existent "
9729 		    "dtrace meta-provider %p\n", (void *)old);
9730 	}
9731 
9732 	if (old->dtm_count != 0) {
9733 		mutex_exit(&dtrace_lock);
9734 		mutex_exit(&dtrace_meta_lock);
9735 		return (EBUSY);
9736 	}
9737 
9738 	*pp = NULL;
9739 
9740 	mutex_exit(&dtrace_lock);
9741 	mutex_exit(&dtrace_meta_lock);
9742 
9743 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9744 	kmem_free(old, sizeof (dtrace_meta_t));
9745 
9746 	return (0);
9747 }
9748 
9749 
9750 /*
9751  * DTrace DIF Object Functions
9752  */
9753 static int
9754 dtrace_difo_err(uint_t pc, const char *format, ...)
9755 {
9756 	if (dtrace_err_verbose) {
9757 		va_list alist;
9758 
9759 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9760 		va_start(alist, format);
9761 		(void) vuprintf(format, alist);
9762 		va_end(alist);
9763 	}
9764 
9765 #ifdef DTRACE_ERRDEBUG
9766 	dtrace_errdebug(format);
9767 #endif
9768 	return (1);
9769 }
9770 
9771 /*
9772  * Validate a DTrace DIF object by checking the IR instructions.  The following
9773  * rules are currently enforced by dtrace_difo_validate():
9774  *
9775  * 1. Each instruction must have a valid opcode
9776  * 2. Each register, string, variable, or subroutine reference must be valid
9777  * 3. No instruction can modify register %r0 (must be zero)
9778  * 4. All instruction reserved bits must be set to zero
9779  * 5. The last instruction must be a "ret" instruction
9780  * 6. All branch targets must reference a valid instruction _after_ the branch
9781  */
9782 static int
9783 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9784     cred_t *cr)
9785 {
9786 	int err = 0, i;
9787 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9788 	int kcheckload;
9789 	uint_t pc;
9790 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9791 
9792 	kcheckload = cr == NULL ||
9793 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9794 
9795 	dp->dtdo_destructive = 0;
9796 
9797 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9798 		dif_instr_t instr = dp->dtdo_buf[pc];
9799 
9800 		uint_t r1 = DIF_INSTR_R1(instr);
9801 		uint_t r2 = DIF_INSTR_R2(instr);
9802 		uint_t rd = DIF_INSTR_RD(instr);
9803 		uint_t rs = DIF_INSTR_RS(instr);
9804 		uint_t label = DIF_INSTR_LABEL(instr);
9805 		uint_t v = DIF_INSTR_VAR(instr);
9806 		uint_t subr = DIF_INSTR_SUBR(instr);
9807 		uint_t type = DIF_INSTR_TYPE(instr);
9808 		uint_t op = DIF_INSTR_OP(instr);
9809 
9810 		switch (op) {
9811 		case DIF_OP_OR:
9812 		case DIF_OP_XOR:
9813 		case DIF_OP_AND:
9814 		case DIF_OP_SLL:
9815 		case DIF_OP_SRL:
9816 		case DIF_OP_SRA:
9817 		case DIF_OP_SUB:
9818 		case DIF_OP_ADD:
9819 		case DIF_OP_MUL:
9820 		case DIF_OP_SDIV:
9821 		case DIF_OP_UDIV:
9822 		case DIF_OP_SREM:
9823 		case DIF_OP_UREM:
9824 		case DIF_OP_COPYS:
9825 			if (r1 >= nregs)
9826 				err += efunc(pc, "invalid register %u\n", r1);
9827 			if (r2 >= nregs)
9828 				err += efunc(pc, "invalid register %u\n", r2);
9829 			if (rd >= nregs)
9830 				err += efunc(pc, "invalid register %u\n", rd);
9831 			if (rd == 0)
9832 				err += efunc(pc, "cannot write to %%r0\n");
9833 			break;
9834 		case DIF_OP_NOT:
9835 		case DIF_OP_MOV:
9836 		case DIF_OP_ALLOCS:
9837 			if (r1 >= nregs)
9838 				err += efunc(pc, "invalid register %u\n", r1);
9839 			if (r2 != 0)
9840 				err += efunc(pc, "non-zero reserved bits\n");
9841 			if (rd >= nregs)
9842 				err += efunc(pc, "invalid register %u\n", rd);
9843 			if (rd == 0)
9844 				err += efunc(pc, "cannot write to %%r0\n");
9845 			break;
9846 		case DIF_OP_LDSB:
9847 		case DIF_OP_LDSH:
9848 		case DIF_OP_LDSW:
9849 		case DIF_OP_LDUB:
9850 		case DIF_OP_LDUH:
9851 		case DIF_OP_LDUW:
9852 		case DIF_OP_LDX:
9853 			if (r1 >= nregs)
9854 				err += efunc(pc, "invalid register %u\n", r1);
9855 			if (r2 != 0)
9856 				err += efunc(pc, "non-zero reserved bits\n");
9857 			if (rd >= nregs)
9858 				err += efunc(pc, "invalid register %u\n", rd);
9859 			if (rd == 0)
9860 				err += efunc(pc, "cannot write to %%r0\n");
9861 			if (kcheckload)
9862 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9863 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9864 			break;
9865 		case DIF_OP_RLDSB:
9866 		case DIF_OP_RLDSH:
9867 		case DIF_OP_RLDSW:
9868 		case DIF_OP_RLDUB:
9869 		case DIF_OP_RLDUH:
9870 		case DIF_OP_RLDUW:
9871 		case DIF_OP_RLDX:
9872 			if (r1 >= nregs)
9873 				err += efunc(pc, "invalid register %u\n", r1);
9874 			if (r2 != 0)
9875 				err += efunc(pc, "non-zero reserved bits\n");
9876 			if (rd >= nregs)
9877 				err += efunc(pc, "invalid register %u\n", rd);
9878 			if (rd == 0)
9879 				err += efunc(pc, "cannot write to %%r0\n");
9880 			break;
9881 		case DIF_OP_ULDSB:
9882 		case DIF_OP_ULDSH:
9883 		case DIF_OP_ULDSW:
9884 		case DIF_OP_ULDUB:
9885 		case DIF_OP_ULDUH:
9886 		case DIF_OP_ULDUW:
9887 		case DIF_OP_ULDX:
9888 			if (r1 >= nregs)
9889 				err += efunc(pc, "invalid register %u\n", r1);
9890 			if (r2 != 0)
9891 				err += efunc(pc, "non-zero reserved bits\n");
9892 			if (rd >= nregs)
9893 				err += efunc(pc, "invalid register %u\n", rd);
9894 			if (rd == 0)
9895 				err += efunc(pc, "cannot write to %%r0\n");
9896 			break;
9897 		case DIF_OP_STB:
9898 		case DIF_OP_STH:
9899 		case DIF_OP_STW:
9900 		case DIF_OP_STX:
9901 			if (r1 >= nregs)
9902 				err += efunc(pc, "invalid register %u\n", r1);
9903 			if (r2 != 0)
9904 				err += efunc(pc, "non-zero reserved bits\n");
9905 			if (rd >= nregs)
9906 				err += efunc(pc, "invalid register %u\n", rd);
9907 			if (rd == 0)
9908 				err += efunc(pc, "cannot write to 0 address\n");
9909 			break;
9910 		case DIF_OP_CMP:
9911 		case DIF_OP_SCMP:
9912 			if (r1 >= nregs)
9913 				err += efunc(pc, "invalid register %u\n", r1);
9914 			if (r2 >= nregs)
9915 				err += efunc(pc, "invalid register %u\n", r2);
9916 			if (rd != 0)
9917 				err += efunc(pc, "non-zero reserved bits\n");
9918 			break;
9919 		case DIF_OP_TST:
9920 			if (r1 >= nregs)
9921 				err += efunc(pc, "invalid register %u\n", r1);
9922 			if (r2 != 0 || rd != 0)
9923 				err += efunc(pc, "non-zero reserved bits\n");
9924 			break;
9925 		case DIF_OP_BA:
9926 		case DIF_OP_BE:
9927 		case DIF_OP_BNE:
9928 		case DIF_OP_BG:
9929 		case DIF_OP_BGU:
9930 		case DIF_OP_BGE:
9931 		case DIF_OP_BGEU:
9932 		case DIF_OP_BL:
9933 		case DIF_OP_BLU:
9934 		case DIF_OP_BLE:
9935 		case DIF_OP_BLEU:
9936 			if (label >= dp->dtdo_len) {
9937 				err += efunc(pc, "invalid branch target %u\n",
9938 				    label);
9939 			}
9940 			if (label <= pc) {
9941 				err += efunc(pc, "backward branch to %u\n",
9942 				    label);
9943 			}
9944 			break;
9945 		case DIF_OP_RET:
9946 			if (r1 != 0 || r2 != 0)
9947 				err += efunc(pc, "non-zero reserved bits\n");
9948 			if (rd >= nregs)
9949 				err += efunc(pc, "invalid register %u\n", rd);
9950 			break;
9951 		case DIF_OP_NOP:
9952 		case DIF_OP_POPTS:
9953 		case DIF_OP_FLUSHTS:
9954 			if (r1 != 0 || r2 != 0 || rd != 0)
9955 				err += efunc(pc, "non-zero reserved bits\n");
9956 			break;
9957 		case DIF_OP_SETX:
9958 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9959 				err += efunc(pc, "invalid integer ref %u\n",
9960 				    DIF_INSTR_INTEGER(instr));
9961 			}
9962 			if (rd >= nregs)
9963 				err += efunc(pc, "invalid register %u\n", rd);
9964 			if (rd == 0)
9965 				err += efunc(pc, "cannot write to %%r0\n");
9966 			break;
9967 		case DIF_OP_SETS:
9968 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9969 				err += efunc(pc, "invalid string ref %u\n",
9970 				    DIF_INSTR_STRING(instr));
9971 			}
9972 			if (rd >= nregs)
9973 				err += efunc(pc, "invalid register %u\n", rd);
9974 			if (rd == 0)
9975 				err += efunc(pc, "cannot write to %%r0\n");
9976 			break;
9977 		case DIF_OP_LDGA:
9978 		case DIF_OP_LDTA:
9979 			if (r1 > DIF_VAR_ARRAY_MAX)
9980 				err += efunc(pc, "invalid array %u\n", r1);
9981 			if (r2 >= nregs)
9982 				err += efunc(pc, "invalid register %u\n", r2);
9983 			if (rd >= nregs)
9984 				err += efunc(pc, "invalid register %u\n", rd);
9985 			if (rd == 0)
9986 				err += efunc(pc, "cannot write to %%r0\n");
9987 			break;
9988 		case DIF_OP_LDGS:
9989 		case DIF_OP_LDTS:
9990 		case DIF_OP_LDLS:
9991 		case DIF_OP_LDGAA:
9992 		case DIF_OP_LDTAA:
9993 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9994 				err += efunc(pc, "invalid variable %u\n", v);
9995 			if (rd >= nregs)
9996 				err += efunc(pc, "invalid register %u\n", rd);
9997 			if (rd == 0)
9998 				err += efunc(pc, "cannot write to %%r0\n");
9999 			break;
10000 		case DIF_OP_STGS:
10001 		case DIF_OP_STTS:
10002 		case DIF_OP_STLS:
10003 		case DIF_OP_STGAA:
10004 		case DIF_OP_STTAA:
10005 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
10006 				err += efunc(pc, "invalid variable %u\n", v);
10007 			if (rs >= nregs)
10008 				err += efunc(pc, "invalid register %u\n", rd);
10009 			break;
10010 		case DIF_OP_CALL:
10011 			if (subr > DIF_SUBR_MAX)
10012 				err += efunc(pc, "invalid subr %u\n", subr);
10013 			if (rd >= nregs)
10014 				err += efunc(pc, "invalid register %u\n", rd);
10015 			if (rd == 0)
10016 				err += efunc(pc, "cannot write to %%r0\n");
10017 
10018 			if (subr == DIF_SUBR_COPYOUT ||
10019 			    subr == DIF_SUBR_COPYOUTSTR) {
10020 				dp->dtdo_destructive = 1;
10021 			}
10022 
10023 			if (subr == DIF_SUBR_GETF) {
10024 #ifdef __FreeBSD__
10025 				err += efunc(pc, "getf() not supported");
10026 #else
10027 				/*
10028 				 * If we have a getf() we need to record that
10029 				 * in our state.  Note that our state can be
10030 				 * NULL if this is a helper -- but in that
10031 				 * case, the call to getf() is itself illegal,
10032 				 * and will be caught (slightly later) when
10033 				 * the helper is validated.
10034 				 */
10035 				if (vstate->dtvs_state != NULL)
10036 					vstate->dtvs_state->dts_getf++;
10037 #endif
10038 			}
10039 
10040 			break;
10041 		case DIF_OP_PUSHTR:
10042 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10043 				err += efunc(pc, "invalid ref type %u\n", type);
10044 			if (r2 >= nregs)
10045 				err += efunc(pc, "invalid register %u\n", r2);
10046 			if (rs >= nregs)
10047 				err += efunc(pc, "invalid register %u\n", rs);
10048 			break;
10049 		case DIF_OP_PUSHTV:
10050 			if (type != DIF_TYPE_CTF)
10051 				err += efunc(pc, "invalid val type %u\n", type);
10052 			if (r2 >= nregs)
10053 				err += efunc(pc, "invalid register %u\n", r2);
10054 			if (rs >= nregs)
10055 				err += efunc(pc, "invalid register %u\n", rs);
10056 			break;
10057 		default:
10058 			err += efunc(pc, "invalid opcode %u\n",
10059 			    DIF_INSTR_OP(instr));
10060 		}
10061 	}
10062 
10063 	if (dp->dtdo_len != 0 &&
10064 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10065 		err += efunc(dp->dtdo_len - 1,
10066 		    "expected 'ret' as last DIF instruction\n");
10067 	}
10068 
10069 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10070 		/*
10071 		 * If we're not returning by reference, the size must be either
10072 		 * 0 or the size of one of the base types.
10073 		 */
10074 		switch (dp->dtdo_rtype.dtdt_size) {
10075 		case 0:
10076 		case sizeof (uint8_t):
10077 		case sizeof (uint16_t):
10078 		case sizeof (uint32_t):
10079 		case sizeof (uint64_t):
10080 			break;
10081 
10082 		default:
10083 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
10084 		}
10085 	}
10086 
10087 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10088 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10089 		dtrace_diftype_t *vt, *et;
10090 		uint_t id, ndx;
10091 
10092 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10093 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10094 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10095 			err += efunc(i, "unrecognized variable scope %d\n",
10096 			    v->dtdv_scope);
10097 			break;
10098 		}
10099 
10100 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10101 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10102 			err += efunc(i, "unrecognized variable type %d\n",
10103 			    v->dtdv_kind);
10104 			break;
10105 		}
10106 
10107 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10108 			err += efunc(i, "%d exceeds variable id limit\n", id);
10109 			break;
10110 		}
10111 
10112 		if (id < DIF_VAR_OTHER_UBASE)
10113 			continue;
10114 
10115 		/*
10116 		 * For user-defined variables, we need to check that this
10117 		 * definition is identical to any previous definition that we
10118 		 * encountered.
10119 		 */
10120 		ndx = id - DIF_VAR_OTHER_UBASE;
10121 
10122 		switch (v->dtdv_scope) {
10123 		case DIFV_SCOPE_GLOBAL:
10124 			if (maxglobal == -1 || ndx > maxglobal)
10125 				maxglobal = ndx;
10126 
10127 			if (ndx < vstate->dtvs_nglobals) {
10128 				dtrace_statvar_t *svar;
10129 
10130 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10131 					existing = &svar->dtsv_var;
10132 			}
10133 
10134 			break;
10135 
10136 		case DIFV_SCOPE_THREAD:
10137 			if (maxtlocal == -1 || ndx > maxtlocal)
10138 				maxtlocal = ndx;
10139 
10140 			if (ndx < vstate->dtvs_ntlocals)
10141 				existing = &vstate->dtvs_tlocals[ndx];
10142 			break;
10143 
10144 		case DIFV_SCOPE_LOCAL:
10145 			if (maxlocal == -1 || ndx > maxlocal)
10146 				maxlocal = ndx;
10147 
10148 			if (ndx < vstate->dtvs_nlocals) {
10149 				dtrace_statvar_t *svar;
10150 
10151 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10152 					existing = &svar->dtsv_var;
10153 			}
10154 
10155 			break;
10156 		}
10157 
10158 		vt = &v->dtdv_type;
10159 
10160 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10161 			if (vt->dtdt_size == 0) {
10162 				err += efunc(i, "zero-sized variable\n");
10163 				break;
10164 			}
10165 
10166 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10167 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10168 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10169 				err += efunc(i, "oversized by-ref static\n");
10170 				break;
10171 			}
10172 		}
10173 
10174 		if (existing == NULL || existing->dtdv_id == 0)
10175 			continue;
10176 
10177 		ASSERT(existing->dtdv_id == v->dtdv_id);
10178 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10179 
10180 		if (existing->dtdv_kind != v->dtdv_kind)
10181 			err += efunc(i, "%d changed variable kind\n", id);
10182 
10183 		et = &existing->dtdv_type;
10184 
10185 		if (vt->dtdt_flags != et->dtdt_flags) {
10186 			err += efunc(i, "%d changed variable type flags\n", id);
10187 			break;
10188 		}
10189 
10190 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10191 			err += efunc(i, "%d changed variable type size\n", id);
10192 			break;
10193 		}
10194 	}
10195 
10196 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10197 		dif_instr_t instr = dp->dtdo_buf[pc];
10198 
10199 		uint_t v = DIF_INSTR_VAR(instr);
10200 		uint_t op = DIF_INSTR_OP(instr);
10201 
10202 		switch (op) {
10203 		case DIF_OP_LDGS:
10204 		case DIF_OP_LDGAA:
10205 		case DIF_OP_STGS:
10206 		case DIF_OP_STGAA:
10207 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10208 				err += efunc(pc, "invalid variable %u\n", v);
10209 			break;
10210 		case DIF_OP_LDTS:
10211 		case DIF_OP_LDTAA:
10212 		case DIF_OP_STTS:
10213 		case DIF_OP_STTAA:
10214 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10215 				err += efunc(pc, "invalid variable %u\n", v);
10216 			break;
10217 		case DIF_OP_LDLS:
10218 		case DIF_OP_STLS:
10219 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10220 				err += efunc(pc, "invalid variable %u\n", v);
10221 			break;
10222 		default:
10223 			break;
10224 		}
10225 	}
10226 
10227 	return (err);
10228 }
10229 
10230 /*
10231  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10232  * are much more constrained than normal DIFOs.  Specifically, they may
10233  * not:
10234  *
10235  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10236  *    miscellaneous string routines
10237  * 2. Access DTrace variables other than the args[] array, and the
10238  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10239  * 3. Have thread-local variables.
10240  * 4. Have dynamic variables.
10241  */
10242 static int
10243 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10244 {
10245 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10246 	int err = 0;
10247 	uint_t pc;
10248 
10249 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10250 		dif_instr_t instr = dp->dtdo_buf[pc];
10251 
10252 		uint_t v = DIF_INSTR_VAR(instr);
10253 		uint_t subr = DIF_INSTR_SUBR(instr);
10254 		uint_t op = DIF_INSTR_OP(instr);
10255 
10256 		switch (op) {
10257 		case DIF_OP_OR:
10258 		case DIF_OP_XOR:
10259 		case DIF_OP_AND:
10260 		case DIF_OP_SLL:
10261 		case DIF_OP_SRL:
10262 		case DIF_OP_SRA:
10263 		case DIF_OP_SUB:
10264 		case DIF_OP_ADD:
10265 		case DIF_OP_MUL:
10266 		case DIF_OP_SDIV:
10267 		case DIF_OP_UDIV:
10268 		case DIF_OP_SREM:
10269 		case DIF_OP_UREM:
10270 		case DIF_OP_COPYS:
10271 		case DIF_OP_NOT:
10272 		case DIF_OP_MOV:
10273 		case DIF_OP_RLDSB:
10274 		case DIF_OP_RLDSH:
10275 		case DIF_OP_RLDSW:
10276 		case DIF_OP_RLDUB:
10277 		case DIF_OP_RLDUH:
10278 		case DIF_OP_RLDUW:
10279 		case DIF_OP_RLDX:
10280 		case DIF_OP_ULDSB:
10281 		case DIF_OP_ULDSH:
10282 		case DIF_OP_ULDSW:
10283 		case DIF_OP_ULDUB:
10284 		case DIF_OP_ULDUH:
10285 		case DIF_OP_ULDUW:
10286 		case DIF_OP_ULDX:
10287 		case DIF_OP_STB:
10288 		case DIF_OP_STH:
10289 		case DIF_OP_STW:
10290 		case DIF_OP_STX:
10291 		case DIF_OP_ALLOCS:
10292 		case DIF_OP_CMP:
10293 		case DIF_OP_SCMP:
10294 		case DIF_OP_TST:
10295 		case DIF_OP_BA:
10296 		case DIF_OP_BE:
10297 		case DIF_OP_BNE:
10298 		case DIF_OP_BG:
10299 		case DIF_OP_BGU:
10300 		case DIF_OP_BGE:
10301 		case DIF_OP_BGEU:
10302 		case DIF_OP_BL:
10303 		case DIF_OP_BLU:
10304 		case DIF_OP_BLE:
10305 		case DIF_OP_BLEU:
10306 		case DIF_OP_RET:
10307 		case DIF_OP_NOP:
10308 		case DIF_OP_POPTS:
10309 		case DIF_OP_FLUSHTS:
10310 		case DIF_OP_SETX:
10311 		case DIF_OP_SETS:
10312 		case DIF_OP_LDGA:
10313 		case DIF_OP_LDLS:
10314 		case DIF_OP_STGS:
10315 		case DIF_OP_STLS:
10316 		case DIF_OP_PUSHTR:
10317 		case DIF_OP_PUSHTV:
10318 			break;
10319 
10320 		case DIF_OP_LDGS:
10321 			if (v >= DIF_VAR_OTHER_UBASE)
10322 				break;
10323 
10324 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10325 				break;
10326 
10327 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10328 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10329 			    v == DIF_VAR_EXECARGS ||
10330 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10331 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10332 				break;
10333 
10334 			err += efunc(pc, "illegal variable %u\n", v);
10335 			break;
10336 
10337 		case DIF_OP_LDTA:
10338 		case DIF_OP_LDTS:
10339 		case DIF_OP_LDGAA:
10340 		case DIF_OP_LDTAA:
10341 			err += efunc(pc, "illegal dynamic variable load\n");
10342 			break;
10343 
10344 		case DIF_OP_STTS:
10345 		case DIF_OP_STGAA:
10346 		case DIF_OP_STTAA:
10347 			err += efunc(pc, "illegal dynamic variable store\n");
10348 			break;
10349 
10350 		case DIF_OP_CALL:
10351 			if (subr == DIF_SUBR_ALLOCA ||
10352 			    subr == DIF_SUBR_BCOPY ||
10353 			    subr == DIF_SUBR_COPYIN ||
10354 			    subr == DIF_SUBR_COPYINTO ||
10355 			    subr == DIF_SUBR_COPYINSTR ||
10356 			    subr == DIF_SUBR_INDEX ||
10357 			    subr == DIF_SUBR_INET_NTOA ||
10358 			    subr == DIF_SUBR_INET_NTOA6 ||
10359 			    subr == DIF_SUBR_INET_NTOP ||
10360 			    subr == DIF_SUBR_JSON ||
10361 			    subr == DIF_SUBR_LLTOSTR ||
10362 			    subr == DIF_SUBR_STRTOLL ||
10363 			    subr == DIF_SUBR_RINDEX ||
10364 			    subr == DIF_SUBR_STRCHR ||
10365 			    subr == DIF_SUBR_STRJOIN ||
10366 			    subr == DIF_SUBR_STRRCHR ||
10367 			    subr == DIF_SUBR_STRSTR ||
10368 			    subr == DIF_SUBR_HTONS ||
10369 			    subr == DIF_SUBR_HTONL ||
10370 			    subr == DIF_SUBR_HTONLL ||
10371 			    subr == DIF_SUBR_NTOHS ||
10372 			    subr == DIF_SUBR_NTOHL ||
10373 			    subr == DIF_SUBR_NTOHLL ||
10374 			    subr == DIF_SUBR_MEMREF)
10375 				break;
10376 #ifdef __FreeBSD__
10377 			if (subr == DIF_SUBR_MEMSTR)
10378 				break;
10379 #endif
10380 
10381 			err += efunc(pc, "invalid subr %u\n", subr);
10382 			break;
10383 
10384 		default:
10385 			err += efunc(pc, "invalid opcode %u\n",
10386 			    DIF_INSTR_OP(instr));
10387 		}
10388 	}
10389 
10390 	return (err);
10391 }
10392 
10393 /*
10394  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10395  * basis; 0 if not.
10396  */
10397 static int
10398 dtrace_difo_cacheable(dtrace_difo_t *dp)
10399 {
10400 	int i;
10401 
10402 	if (dp == NULL)
10403 		return (0);
10404 
10405 	for (i = 0; i < dp->dtdo_varlen; i++) {
10406 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10407 
10408 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10409 			continue;
10410 
10411 		switch (v->dtdv_id) {
10412 		case DIF_VAR_CURTHREAD:
10413 		case DIF_VAR_PID:
10414 		case DIF_VAR_TID:
10415 		case DIF_VAR_EXECARGS:
10416 		case DIF_VAR_EXECNAME:
10417 		case DIF_VAR_ZONENAME:
10418 			break;
10419 
10420 		default:
10421 			return (0);
10422 		}
10423 	}
10424 
10425 	/*
10426 	 * This DIF object may be cacheable.  Now we need to look for any
10427 	 * array loading instructions, any memory loading instructions, or
10428 	 * any stores to thread-local variables.
10429 	 */
10430 	for (i = 0; i < dp->dtdo_len; i++) {
10431 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10432 
10433 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10434 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10435 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10436 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10437 			return (0);
10438 	}
10439 
10440 	return (1);
10441 }
10442 
10443 static void
10444 dtrace_difo_hold(dtrace_difo_t *dp)
10445 {
10446 	int i;
10447 
10448 	ASSERT(MUTEX_HELD(&dtrace_lock));
10449 
10450 	dp->dtdo_refcnt++;
10451 	ASSERT(dp->dtdo_refcnt != 0);
10452 
10453 	/*
10454 	 * We need to check this DIF object for references to the variable
10455 	 * DIF_VAR_VTIMESTAMP.
10456 	 */
10457 	for (i = 0; i < dp->dtdo_varlen; i++) {
10458 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10459 
10460 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10461 			continue;
10462 
10463 		if (dtrace_vtime_references++ == 0)
10464 			dtrace_vtime_enable();
10465 	}
10466 }
10467 
10468 /*
10469  * This routine calculates the dynamic variable chunksize for a given DIF
10470  * object.  The calculation is not fool-proof, and can probably be tricked by
10471  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10472  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10473  * if a dynamic variable size exceeds the chunksize.
10474  */
10475 static void
10476 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10477 {
10478 	uint64_t sval = 0;
10479 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10480 	const dif_instr_t *text = dp->dtdo_buf;
10481 	uint_t pc, srd = 0;
10482 	uint_t ttop = 0;
10483 	size_t size, ksize;
10484 	uint_t id, i;
10485 
10486 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10487 		dif_instr_t instr = text[pc];
10488 		uint_t op = DIF_INSTR_OP(instr);
10489 		uint_t rd = DIF_INSTR_RD(instr);
10490 		uint_t r1 = DIF_INSTR_R1(instr);
10491 		uint_t nkeys = 0;
10492 		uchar_t scope = 0;
10493 
10494 		dtrace_key_t *key = tupregs;
10495 
10496 		switch (op) {
10497 		case DIF_OP_SETX:
10498 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10499 			srd = rd;
10500 			continue;
10501 
10502 		case DIF_OP_STTS:
10503 			key = &tupregs[DIF_DTR_NREGS];
10504 			key[0].dttk_size = 0;
10505 			key[1].dttk_size = 0;
10506 			nkeys = 2;
10507 			scope = DIFV_SCOPE_THREAD;
10508 			break;
10509 
10510 		case DIF_OP_STGAA:
10511 		case DIF_OP_STTAA:
10512 			nkeys = ttop;
10513 
10514 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10515 				key[nkeys++].dttk_size = 0;
10516 
10517 			key[nkeys++].dttk_size = 0;
10518 
10519 			if (op == DIF_OP_STTAA) {
10520 				scope = DIFV_SCOPE_THREAD;
10521 			} else {
10522 				scope = DIFV_SCOPE_GLOBAL;
10523 			}
10524 
10525 			break;
10526 
10527 		case DIF_OP_PUSHTR:
10528 			if (ttop == DIF_DTR_NREGS)
10529 				return;
10530 
10531 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10532 				/*
10533 				 * If the register for the size of the "pushtr"
10534 				 * is %r0 (or the value is 0) and the type is
10535 				 * a string, we'll use the system-wide default
10536 				 * string size.
10537 				 */
10538 				tupregs[ttop++].dttk_size =
10539 				    dtrace_strsize_default;
10540 			} else {
10541 				if (srd == 0)
10542 					return;
10543 
10544 				if (sval > LONG_MAX)
10545 					return;
10546 
10547 				tupregs[ttop++].dttk_size = sval;
10548 			}
10549 
10550 			break;
10551 
10552 		case DIF_OP_PUSHTV:
10553 			if (ttop == DIF_DTR_NREGS)
10554 				return;
10555 
10556 			tupregs[ttop++].dttk_size = 0;
10557 			break;
10558 
10559 		case DIF_OP_FLUSHTS:
10560 			ttop = 0;
10561 			break;
10562 
10563 		case DIF_OP_POPTS:
10564 			if (ttop != 0)
10565 				ttop--;
10566 			break;
10567 		}
10568 
10569 		sval = 0;
10570 		srd = 0;
10571 
10572 		if (nkeys == 0)
10573 			continue;
10574 
10575 		/*
10576 		 * We have a dynamic variable allocation; calculate its size.
10577 		 */
10578 		for (ksize = 0, i = 0; i < nkeys; i++)
10579 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10580 
10581 		size = sizeof (dtrace_dynvar_t);
10582 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10583 		size += ksize;
10584 
10585 		/*
10586 		 * Now we need to determine the size of the stored data.
10587 		 */
10588 		id = DIF_INSTR_VAR(instr);
10589 
10590 		for (i = 0; i < dp->dtdo_varlen; i++) {
10591 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10592 
10593 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10594 				size += v->dtdv_type.dtdt_size;
10595 				break;
10596 			}
10597 		}
10598 
10599 		if (i == dp->dtdo_varlen)
10600 			return;
10601 
10602 		/*
10603 		 * We have the size.  If this is larger than the chunk size
10604 		 * for our dynamic variable state, reset the chunk size.
10605 		 */
10606 		size = P2ROUNDUP(size, sizeof (uint64_t));
10607 
10608 		/*
10609 		 * Before setting the chunk size, check that we're not going
10610 		 * to set it to a negative value...
10611 		 */
10612 		if (size > LONG_MAX)
10613 			return;
10614 
10615 		/*
10616 		 * ...and make certain that we didn't badly overflow.
10617 		 */
10618 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10619 			return;
10620 
10621 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10622 			vstate->dtvs_dynvars.dtds_chunksize = size;
10623 	}
10624 }
10625 
10626 static void
10627 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10628 {
10629 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10630 	uint_t id;
10631 
10632 	ASSERT(MUTEX_HELD(&dtrace_lock));
10633 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10634 
10635 	for (i = 0; i < dp->dtdo_varlen; i++) {
10636 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10637 		dtrace_statvar_t *svar, ***svarp = NULL;
10638 		size_t dsize = 0;
10639 		uint8_t scope = v->dtdv_scope;
10640 		int *np = NULL;
10641 
10642 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10643 			continue;
10644 
10645 		id -= DIF_VAR_OTHER_UBASE;
10646 
10647 		switch (scope) {
10648 		case DIFV_SCOPE_THREAD:
10649 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10650 				dtrace_difv_t *tlocals;
10651 
10652 				if ((ntlocals = (otlocals << 1)) == 0)
10653 					ntlocals = 1;
10654 
10655 				osz = otlocals * sizeof (dtrace_difv_t);
10656 				nsz = ntlocals * sizeof (dtrace_difv_t);
10657 
10658 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10659 
10660 				if (osz != 0) {
10661 					bcopy(vstate->dtvs_tlocals,
10662 					    tlocals, osz);
10663 					kmem_free(vstate->dtvs_tlocals, osz);
10664 				}
10665 
10666 				vstate->dtvs_tlocals = tlocals;
10667 				vstate->dtvs_ntlocals = ntlocals;
10668 			}
10669 
10670 			vstate->dtvs_tlocals[id] = *v;
10671 			continue;
10672 
10673 		case DIFV_SCOPE_LOCAL:
10674 			np = &vstate->dtvs_nlocals;
10675 			svarp = &vstate->dtvs_locals;
10676 
10677 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10678 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10679 				    sizeof (uint64_t));
10680 			else
10681 				dsize = NCPU * sizeof (uint64_t);
10682 
10683 			break;
10684 
10685 		case DIFV_SCOPE_GLOBAL:
10686 			np = &vstate->dtvs_nglobals;
10687 			svarp = &vstate->dtvs_globals;
10688 
10689 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10690 				dsize = v->dtdv_type.dtdt_size +
10691 				    sizeof (uint64_t);
10692 
10693 			break;
10694 
10695 		default:
10696 			ASSERT(0);
10697 		}
10698 
10699 		while (id >= (oldsvars = *np)) {
10700 			dtrace_statvar_t **statics;
10701 			int newsvars, oldsize, newsize;
10702 
10703 			if ((newsvars = (oldsvars << 1)) == 0)
10704 				newsvars = 1;
10705 
10706 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10707 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10708 
10709 			statics = kmem_zalloc(newsize, KM_SLEEP);
10710 
10711 			if (oldsize != 0) {
10712 				bcopy(*svarp, statics, oldsize);
10713 				kmem_free(*svarp, oldsize);
10714 			}
10715 
10716 			*svarp = statics;
10717 			*np = newsvars;
10718 		}
10719 
10720 		if ((svar = (*svarp)[id]) == NULL) {
10721 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10722 			svar->dtsv_var = *v;
10723 
10724 			if ((svar->dtsv_size = dsize) != 0) {
10725 				svar->dtsv_data = (uint64_t)(uintptr_t)
10726 				    kmem_zalloc(dsize, KM_SLEEP);
10727 			}
10728 
10729 			(*svarp)[id] = svar;
10730 		}
10731 
10732 		svar->dtsv_refcnt++;
10733 	}
10734 
10735 	dtrace_difo_chunksize(dp, vstate);
10736 	dtrace_difo_hold(dp);
10737 }
10738 
10739 static dtrace_difo_t *
10740 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10741 {
10742 	dtrace_difo_t *new;
10743 	size_t sz;
10744 
10745 	ASSERT(dp->dtdo_buf != NULL);
10746 	ASSERT(dp->dtdo_refcnt != 0);
10747 
10748 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10749 
10750 	ASSERT(dp->dtdo_buf != NULL);
10751 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10752 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10753 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10754 	new->dtdo_len = dp->dtdo_len;
10755 
10756 	if (dp->dtdo_strtab != NULL) {
10757 		ASSERT(dp->dtdo_strlen != 0);
10758 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10759 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10760 		new->dtdo_strlen = dp->dtdo_strlen;
10761 	}
10762 
10763 	if (dp->dtdo_inttab != NULL) {
10764 		ASSERT(dp->dtdo_intlen != 0);
10765 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10766 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10767 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10768 		new->dtdo_intlen = dp->dtdo_intlen;
10769 	}
10770 
10771 	if (dp->dtdo_vartab != NULL) {
10772 		ASSERT(dp->dtdo_varlen != 0);
10773 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10774 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10775 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10776 		new->dtdo_varlen = dp->dtdo_varlen;
10777 	}
10778 
10779 	dtrace_difo_init(new, vstate);
10780 	return (new);
10781 }
10782 
10783 static void
10784 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10785 {
10786 	int i;
10787 
10788 	ASSERT(dp->dtdo_refcnt == 0);
10789 
10790 	for (i = 0; i < dp->dtdo_varlen; i++) {
10791 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10792 		dtrace_statvar_t *svar, **svarp = NULL;
10793 		uint_t id;
10794 		uint8_t scope = v->dtdv_scope;
10795 		int *np = NULL;
10796 
10797 		switch (scope) {
10798 		case DIFV_SCOPE_THREAD:
10799 			continue;
10800 
10801 		case DIFV_SCOPE_LOCAL:
10802 			np = &vstate->dtvs_nlocals;
10803 			svarp = vstate->dtvs_locals;
10804 			break;
10805 
10806 		case DIFV_SCOPE_GLOBAL:
10807 			np = &vstate->dtvs_nglobals;
10808 			svarp = vstate->dtvs_globals;
10809 			break;
10810 
10811 		default:
10812 			ASSERT(0);
10813 		}
10814 
10815 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10816 			continue;
10817 
10818 		id -= DIF_VAR_OTHER_UBASE;
10819 		ASSERT(id < *np);
10820 
10821 		svar = svarp[id];
10822 		ASSERT(svar != NULL);
10823 		ASSERT(svar->dtsv_refcnt > 0);
10824 
10825 		if (--svar->dtsv_refcnt > 0)
10826 			continue;
10827 
10828 		if (svar->dtsv_size != 0) {
10829 			ASSERT(svar->dtsv_data != 0);
10830 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10831 			    svar->dtsv_size);
10832 		}
10833 
10834 		kmem_free(svar, sizeof (dtrace_statvar_t));
10835 		svarp[id] = NULL;
10836 	}
10837 
10838 	if (dp->dtdo_buf != NULL)
10839 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10840 	if (dp->dtdo_inttab != NULL)
10841 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10842 	if (dp->dtdo_strtab != NULL)
10843 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10844 	if (dp->dtdo_vartab != NULL)
10845 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10846 
10847 	kmem_free(dp, sizeof (dtrace_difo_t));
10848 }
10849 
10850 static void
10851 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10852 {
10853 	int i;
10854 
10855 	ASSERT(MUTEX_HELD(&dtrace_lock));
10856 	ASSERT(dp->dtdo_refcnt != 0);
10857 
10858 	for (i = 0; i < dp->dtdo_varlen; i++) {
10859 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10860 
10861 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10862 			continue;
10863 
10864 		ASSERT(dtrace_vtime_references > 0);
10865 		if (--dtrace_vtime_references == 0)
10866 			dtrace_vtime_disable();
10867 	}
10868 
10869 	if (--dp->dtdo_refcnt == 0)
10870 		dtrace_difo_destroy(dp, vstate);
10871 }
10872 
10873 /*
10874  * DTrace Format Functions
10875  */
10876 static uint16_t
10877 dtrace_format_add(dtrace_state_t *state, char *str)
10878 {
10879 	char *fmt, **new;
10880 	uint16_t ndx, len = strlen(str) + 1;
10881 
10882 	fmt = kmem_zalloc(len, KM_SLEEP);
10883 	bcopy(str, fmt, len);
10884 
10885 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10886 		if (state->dts_formats[ndx] == NULL) {
10887 			state->dts_formats[ndx] = fmt;
10888 			return (ndx + 1);
10889 		}
10890 	}
10891 
10892 	if (state->dts_nformats == USHRT_MAX) {
10893 		/*
10894 		 * This is only likely if a denial-of-service attack is being
10895 		 * attempted.  As such, it's okay to fail silently here.
10896 		 */
10897 		kmem_free(fmt, len);
10898 		return (0);
10899 	}
10900 
10901 	/*
10902 	 * For simplicity, we always resize the formats array to be exactly the
10903 	 * number of formats.
10904 	 */
10905 	ndx = state->dts_nformats++;
10906 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10907 
10908 	if (state->dts_formats != NULL) {
10909 		ASSERT(ndx != 0);
10910 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10911 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10912 	}
10913 
10914 	state->dts_formats = new;
10915 	state->dts_formats[ndx] = fmt;
10916 
10917 	return (ndx + 1);
10918 }
10919 
10920 static void
10921 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10922 {
10923 	char *fmt;
10924 
10925 	ASSERT(state->dts_formats != NULL);
10926 	ASSERT(format <= state->dts_nformats);
10927 	ASSERT(state->dts_formats[format - 1] != NULL);
10928 
10929 	fmt = state->dts_formats[format - 1];
10930 	kmem_free(fmt, strlen(fmt) + 1);
10931 	state->dts_formats[format - 1] = NULL;
10932 }
10933 
10934 static void
10935 dtrace_format_destroy(dtrace_state_t *state)
10936 {
10937 	int i;
10938 
10939 	if (state->dts_nformats == 0) {
10940 		ASSERT(state->dts_formats == NULL);
10941 		return;
10942 	}
10943 
10944 	ASSERT(state->dts_formats != NULL);
10945 
10946 	for (i = 0; i < state->dts_nformats; i++) {
10947 		char *fmt = state->dts_formats[i];
10948 
10949 		if (fmt == NULL)
10950 			continue;
10951 
10952 		kmem_free(fmt, strlen(fmt) + 1);
10953 	}
10954 
10955 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10956 	state->dts_nformats = 0;
10957 	state->dts_formats = NULL;
10958 }
10959 
10960 /*
10961  * DTrace Predicate Functions
10962  */
10963 static dtrace_predicate_t *
10964 dtrace_predicate_create(dtrace_difo_t *dp)
10965 {
10966 	dtrace_predicate_t *pred;
10967 
10968 	ASSERT(MUTEX_HELD(&dtrace_lock));
10969 	ASSERT(dp->dtdo_refcnt != 0);
10970 
10971 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10972 	pred->dtp_difo = dp;
10973 	pred->dtp_refcnt = 1;
10974 
10975 	if (!dtrace_difo_cacheable(dp))
10976 		return (pred);
10977 
10978 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10979 		/*
10980 		 * This is only theoretically possible -- we have had 2^32
10981 		 * cacheable predicates on this machine.  We cannot allow any
10982 		 * more predicates to become cacheable:  as unlikely as it is,
10983 		 * there may be a thread caching a (now stale) predicate cache
10984 		 * ID. (N.B.: the temptation is being successfully resisted to
10985 		 * have this cmn_err() "Holy shit -- we executed this code!")
10986 		 */
10987 		return (pred);
10988 	}
10989 
10990 	pred->dtp_cacheid = dtrace_predcache_id++;
10991 
10992 	return (pred);
10993 }
10994 
10995 static void
10996 dtrace_predicate_hold(dtrace_predicate_t *pred)
10997 {
10998 	ASSERT(MUTEX_HELD(&dtrace_lock));
10999 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
11000 	ASSERT(pred->dtp_refcnt > 0);
11001 
11002 	pred->dtp_refcnt++;
11003 }
11004 
11005 static void
11006 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
11007 {
11008 	dtrace_difo_t *dp = pred->dtp_difo;
11009 
11010 	ASSERT(MUTEX_HELD(&dtrace_lock));
11011 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11012 	ASSERT(pred->dtp_refcnt > 0);
11013 
11014 	if (--pred->dtp_refcnt == 0) {
11015 		dtrace_difo_release(pred->dtp_difo, vstate);
11016 		kmem_free(pred, sizeof (dtrace_predicate_t));
11017 	}
11018 }
11019 
11020 /*
11021  * DTrace Action Description Functions
11022  */
11023 static dtrace_actdesc_t *
11024 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11025     uint64_t uarg, uint64_t arg)
11026 {
11027 	dtrace_actdesc_t *act;
11028 
11029 #ifdef illumos
11030 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11031 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11032 #endif
11033 
11034 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11035 	act->dtad_kind = kind;
11036 	act->dtad_ntuple = ntuple;
11037 	act->dtad_uarg = uarg;
11038 	act->dtad_arg = arg;
11039 	act->dtad_refcnt = 1;
11040 
11041 	return (act);
11042 }
11043 
11044 static void
11045 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11046 {
11047 	ASSERT(act->dtad_refcnt >= 1);
11048 	act->dtad_refcnt++;
11049 }
11050 
11051 static void
11052 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11053 {
11054 	dtrace_actkind_t kind = act->dtad_kind;
11055 	dtrace_difo_t *dp;
11056 
11057 	ASSERT(act->dtad_refcnt >= 1);
11058 
11059 	if (--act->dtad_refcnt != 0)
11060 		return;
11061 
11062 	if ((dp = act->dtad_difo) != NULL)
11063 		dtrace_difo_release(dp, vstate);
11064 
11065 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
11066 		char *str = (char *)(uintptr_t)act->dtad_arg;
11067 
11068 #ifdef illumos
11069 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11070 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11071 #endif
11072 
11073 		if (str != NULL)
11074 			kmem_free(str, strlen(str) + 1);
11075 	}
11076 
11077 	kmem_free(act, sizeof (dtrace_actdesc_t));
11078 }
11079 
11080 /*
11081  * DTrace ECB Functions
11082  */
11083 static dtrace_ecb_t *
11084 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11085 {
11086 	dtrace_ecb_t *ecb;
11087 	dtrace_epid_t epid;
11088 
11089 	ASSERT(MUTEX_HELD(&dtrace_lock));
11090 
11091 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11092 	ecb->dte_predicate = NULL;
11093 	ecb->dte_probe = probe;
11094 
11095 	/*
11096 	 * The default size is the size of the default action: recording
11097 	 * the header.
11098 	 */
11099 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11100 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11101 
11102 	epid = state->dts_epid++;
11103 
11104 	if (epid - 1 >= state->dts_necbs) {
11105 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11106 		int necbs = state->dts_necbs << 1;
11107 
11108 		ASSERT(epid == state->dts_necbs + 1);
11109 
11110 		if (necbs == 0) {
11111 			ASSERT(oecbs == NULL);
11112 			necbs = 1;
11113 		}
11114 
11115 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11116 
11117 		if (oecbs != NULL)
11118 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11119 
11120 		dtrace_membar_producer();
11121 		state->dts_ecbs = ecbs;
11122 
11123 		if (oecbs != NULL) {
11124 			/*
11125 			 * If this state is active, we must dtrace_sync()
11126 			 * before we can free the old dts_ecbs array:  we're
11127 			 * coming in hot, and there may be active ring
11128 			 * buffer processing (which indexes into the dts_ecbs
11129 			 * array) on another CPU.
11130 			 */
11131 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11132 				dtrace_sync();
11133 
11134 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11135 		}
11136 
11137 		dtrace_membar_producer();
11138 		state->dts_necbs = necbs;
11139 	}
11140 
11141 	ecb->dte_state = state;
11142 
11143 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11144 	dtrace_membar_producer();
11145 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11146 
11147 	return (ecb);
11148 }
11149 
11150 static void
11151 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11152 {
11153 	dtrace_probe_t *probe = ecb->dte_probe;
11154 
11155 	ASSERT(MUTEX_HELD(&cpu_lock));
11156 	ASSERT(MUTEX_HELD(&dtrace_lock));
11157 	ASSERT(ecb->dte_next == NULL);
11158 
11159 	if (probe == NULL) {
11160 		/*
11161 		 * This is the NULL probe -- there's nothing to do.
11162 		 */
11163 		return;
11164 	}
11165 
11166 	if (probe->dtpr_ecb == NULL) {
11167 		dtrace_provider_t *prov = probe->dtpr_provider;
11168 
11169 		/*
11170 		 * We're the first ECB on this probe.
11171 		 */
11172 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11173 
11174 		if (ecb->dte_predicate != NULL)
11175 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11176 
11177 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11178 		    probe->dtpr_id, probe->dtpr_arg);
11179 	} else {
11180 		/*
11181 		 * This probe is already active.  Swing the last pointer to
11182 		 * point to the new ECB, and issue a dtrace_sync() to assure
11183 		 * that all CPUs have seen the change.
11184 		 */
11185 		ASSERT(probe->dtpr_ecb_last != NULL);
11186 		probe->dtpr_ecb_last->dte_next = ecb;
11187 		probe->dtpr_ecb_last = ecb;
11188 		probe->dtpr_predcache = 0;
11189 
11190 		dtrace_sync();
11191 	}
11192 }
11193 
11194 static int
11195 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11196 {
11197 	dtrace_action_t *act;
11198 	uint32_t curneeded = UINT32_MAX;
11199 	uint32_t aggbase = UINT32_MAX;
11200 
11201 	/*
11202 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11203 	 * we always record it first.)
11204 	 */
11205 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11206 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11207 
11208 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11209 		dtrace_recdesc_t *rec = &act->dta_rec;
11210 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11211 
11212 		ecb->dte_alignment = MAX(ecb->dte_alignment,
11213 		    rec->dtrd_alignment);
11214 
11215 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11216 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11217 
11218 			ASSERT(rec->dtrd_size != 0);
11219 			ASSERT(agg->dtag_first != NULL);
11220 			ASSERT(act->dta_prev->dta_intuple);
11221 			ASSERT(aggbase != UINT32_MAX);
11222 			ASSERT(curneeded != UINT32_MAX);
11223 
11224 			agg->dtag_base = aggbase;
11225 
11226 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11227 			rec->dtrd_offset = curneeded;
11228 			if (curneeded + rec->dtrd_size < curneeded)
11229 				return (EINVAL);
11230 			curneeded += rec->dtrd_size;
11231 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11232 
11233 			aggbase = UINT32_MAX;
11234 			curneeded = UINT32_MAX;
11235 		} else if (act->dta_intuple) {
11236 			if (curneeded == UINT32_MAX) {
11237 				/*
11238 				 * This is the first record in a tuple.  Align
11239 				 * curneeded to be at offset 4 in an 8-byte
11240 				 * aligned block.
11241 				 */
11242 				ASSERT(act->dta_prev == NULL ||
11243 				    !act->dta_prev->dta_intuple);
11244 				ASSERT3U(aggbase, ==, UINT32_MAX);
11245 				curneeded = P2PHASEUP(ecb->dte_size,
11246 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11247 
11248 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11249 				ASSERT(IS_P2ALIGNED(aggbase,
11250 				    sizeof (uint64_t)));
11251 			}
11252 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11253 			rec->dtrd_offset = curneeded;
11254 			if (curneeded + rec->dtrd_size < curneeded)
11255 				return (EINVAL);
11256 			curneeded += rec->dtrd_size;
11257 		} else {
11258 			/* tuples must be followed by an aggregation */
11259 			ASSERT(act->dta_prev == NULL ||
11260 			    !act->dta_prev->dta_intuple);
11261 
11262 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11263 			    rec->dtrd_alignment);
11264 			rec->dtrd_offset = ecb->dte_size;
11265 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11266 				return (EINVAL);
11267 			ecb->dte_size += rec->dtrd_size;
11268 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11269 		}
11270 	}
11271 
11272 	if ((act = ecb->dte_action) != NULL &&
11273 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11274 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11275 		/*
11276 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11277 		 * actions store no data; set the size to 0.
11278 		 */
11279 		ecb->dte_size = 0;
11280 	}
11281 
11282 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11283 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11284 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11285 	    ecb->dte_needed);
11286 	return (0);
11287 }
11288 
11289 static dtrace_action_t *
11290 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11291 {
11292 	dtrace_aggregation_t *agg;
11293 	size_t size = sizeof (uint64_t);
11294 	int ntuple = desc->dtad_ntuple;
11295 	dtrace_action_t *act;
11296 	dtrace_recdesc_t *frec;
11297 	dtrace_aggid_t aggid;
11298 	dtrace_state_t *state = ecb->dte_state;
11299 
11300 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11301 	agg->dtag_ecb = ecb;
11302 
11303 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11304 
11305 	switch (desc->dtad_kind) {
11306 	case DTRACEAGG_MIN:
11307 		agg->dtag_initial = INT64_MAX;
11308 		agg->dtag_aggregate = dtrace_aggregate_min;
11309 		break;
11310 
11311 	case DTRACEAGG_MAX:
11312 		agg->dtag_initial = INT64_MIN;
11313 		agg->dtag_aggregate = dtrace_aggregate_max;
11314 		break;
11315 
11316 	case DTRACEAGG_COUNT:
11317 		agg->dtag_aggregate = dtrace_aggregate_count;
11318 		break;
11319 
11320 	case DTRACEAGG_QUANTIZE:
11321 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11322 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11323 		    sizeof (uint64_t);
11324 		break;
11325 
11326 	case DTRACEAGG_LQUANTIZE: {
11327 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11328 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11329 
11330 		agg->dtag_initial = desc->dtad_arg;
11331 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11332 
11333 		if (step == 0 || levels == 0)
11334 			goto err;
11335 
11336 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11337 		break;
11338 	}
11339 
11340 	case DTRACEAGG_LLQUANTIZE: {
11341 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11342 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11343 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11344 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11345 		int64_t v;
11346 
11347 		agg->dtag_initial = desc->dtad_arg;
11348 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11349 
11350 		if (factor < 2 || low >= high || nsteps < factor)
11351 			goto err;
11352 
11353 		/*
11354 		 * Now check that the number of steps evenly divides a power
11355 		 * of the factor.  (This assures both integer bucket size and
11356 		 * linearity within each magnitude.)
11357 		 */
11358 		for (v = factor; v < nsteps; v *= factor)
11359 			continue;
11360 
11361 		if ((v % nsteps) || (nsteps % factor))
11362 			goto err;
11363 
11364 		size = (dtrace_aggregate_llquantize_bucket(factor,
11365 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11366 		break;
11367 	}
11368 
11369 	case DTRACEAGG_AVG:
11370 		agg->dtag_aggregate = dtrace_aggregate_avg;
11371 		size = sizeof (uint64_t) * 2;
11372 		break;
11373 
11374 	case DTRACEAGG_STDDEV:
11375 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11376 		size = sizeof (uint64_t) * 4;
11377 		break;
11378 
11379 	case DTRACEAGG_SUM:
11380 		agg->dtag_aggregate = dtrace_aggregate_sum;
11381 		break;
11382 
11383 	default:
11384 		goto err;
11385 	}
11386 
11387 	agg->dtag_action.dta_rec.dtrd_size = size;
11388 
11389 	if (ntuple == 0)
11390 		goto err;
11391 
11392 	/*
11393 	 * We must make sure that we have enough actions for the n-tuple.
11394 	 */
11395 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11396 		if (DTRACEACT_ISAGG(act->dta_kind))
11397 			break;
11398 
11399 		if (--ntuple == 0) {
11400 			/*
11401 			 * This is the action with which our n-tuple begins.
11402 			 */
11403 			agg->dtag_first = act;
11404 			goto success;
11405 		}
11406 	}
11407 
11408 	/*
11409 	 * This n-tuple is short by ntuple elements.  Return failure.
11410 	 */
11411 	ASSERT(ntuple != 0);
11412 err:
11413 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11414 	return (NULL);
11415 
11416 success:
11417 	/*
11418 	 * If the last action in the tuple has a size of zero, it's actually
11419 	 * an expression argument for the aggregating action.
11420 	 */
11421 	ASSERT(ecb->dte_action_last != NULL);
11422 	act = ecb->dte_action_last;
11423 
11424 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11425 		ASSERT(act->dta_difo != NULL);
11426 
11427 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11428 			agg->dtag_hasarg = 1;
11429 	}
11430 
11431 	/*
11432 	 * We need to allocate an id for this aggregation.
11433 	 */
11434 #ifdef illumos
11435 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11436 	    VM_BESTFIT | VM_SLEEP);
11437 #else
11438 	aggid = alloc_unr(state->dts_aggid_arena);
11439 #endif
11440 
11441 	if (aggid - 1 >= state->dts_naggregations) {
11442 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11443 		dtrace_aggregation_t **aggs;
11444 		int naggs = state->dts_naggregations << 1;
11445 		int onaggs = state->dts_naggregations;
11446 
11447 		ASSERT(aggid == state->dts_naggregations + 1);
11448 
11449 		if (naggs == 0) {
11450 			ASSERT(oaggs == NULL);
11451 			naggs = 1;
11452 		}
11453 
11454 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11455 
11456 		if (oaggs != NULL) {
11457 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11458 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11459 		}
11460 
11461 		state->dts_aggregations = aggs;
11462 		state->dts_naggregations = naggs;
11463 	}
11464 
11465 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11466 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11467 
11468 	frec = &agg->dtag_first->dta_rec;
11469 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11470 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11471 
11472 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11473 		ASSERT(!act->dta_intuple);
11474 		act->dta_intuple = 1;
11475 	}
11476 
11477 	return (&agg->dtag_action);
11478 }
11479 
11480 static void
11481 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11482 {
11483 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11484 	dtrace_state_t *state = ecb->dte_state;
11485 	dtrace_aggid_t aggid = agg->dtag_id;
11486 
11487 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11488 #ifdef illumos
11489 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11490 #else
11491 	free_unr(state->dts_aggid_arena, aggid);
11492 #endif
11493 
11494 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11495 	state->dts_aggregations[aggid - 1] = NULL;
11496 
11497 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11498 }
11499 
11500 static int
11501 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11502 {
11503 	dtrace_action_t *action, *last;
11504 	dtrace_difo_t *dp = desc->dtad_difo;
11505 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11506 	uint16_t format = 0;
11507 	dtrace_recdesc_t *rec;
11508 	dtrace_state_t *state = ecb->dte_state;
11509 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11510 	uint64_t arg = desc->dtad_arg;
11511 
11512 	ASSERT(MUTEX_HELD(&dtrace_lock));
11513 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11514 
11515 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11516 		/*
11517 		 * If this is an aggregating action, there must be neither
11518 		 * a speculate nor a commit on the action chain.
11519 		 */
11520 		dtrace_action_t *act;
11521 
11522 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11523 			if (act->dta_kind == DTRACEACT_COMMIT)
11524 				return (EINVAL);
11525 
11526 			if (act->dta_kind == DTRACEACT_SPECULATE)
11527 				return (EINVAL);
11528 		}
11529 
11530 		action = dtrace_ecb_aggregation_create(ecb, desc);
11531 
11532 		if (action == NULL)
11533 			return (EINVAL);
11534 	} else {
11535 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11536 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11537 		    dp != NULL && dp->dtdo_destructive)) {
11538 			state->dts_destructive = 1;
11539 		}
11540 
11541 		switch (desc->dtad_kind) {
11542 		case DTRACEACT_PRINTF:
11543 		case DTRACEACT_PRINTA:
11544 		case DTRACEACT_SYSTEM:
11545 		case DTRACEACT_FREOPEN:
11546 		case DTRACEACT_DIFEXPR:
11547 			/*
11548 			 * We know that our arg is a string -- turn it into a
11549 			 * format.
11550 			 */
11551 			if (arg == 0) {
11552 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11553 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11554 				format = 0;
11555 			} else {
11556 				ASSERT(arg != 0);
11557 #ifdef illumos
11558 				ASSERT(arg > KERNELBASE);
11559 #endif
11560 				format = dtrace_format_add(state,
11561 				    (char *)(uintptr_t)arg);
11562 			}
11563 
11564 			/*FALLTHROUGH*/
11565 		case DTRACEACT_LIBACT:
11566 		case DTRACEACT_TRACEMEM:
11567 		case DTRACEACT_TRACEMEM_DYNSIZE:
11568 			if (dp == NULL)
11569 				return (EINVAL);
11570 
11571 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11572 				break;
11573 
11574 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11575 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11576 					return (EINVAL);
11577 
11578 				size = opt[DTRACEOPT_STRSIZE];
11579 			}
11580 
11581 			break;
11582 
11583 		case DTRACEACT_STACK:
11584 			if ((nframes = arg) == 0) {
11585 				nframes = opt[DTRACEOPT_STACKFRAMES];
11586 				ASSERT(nframes > 0);
11587 				arg = nframes;
11588 			}
11589 
11590 			size = nframes * sizeof (pc_t);
11591 			break;
11592 
11593 		case DTRACEACT_JSTACK:
11594 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11595 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11596 
11597 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11598 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11599 
11600 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11601 
11602 			/*FALLTHROUGH*/
11603 		case DTRACEACT_USTACK:
11604 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11605 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11606 				strsize = DTRACE_USTACK_STRSIZE(arg);
11607 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11608 				ASSERT(nframes > 0);
11609 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11610 			}
11611 
11612 			/*
11613 			 * Save a slot for the pid.
11614 			 */
11615 			size = (nframes + 1) * sizeof (uint64_t);
11616 			size += DTRACE_USTACK_STRSIZE(arg);
11617 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11618 
11619 			break;
11620 
11621 		case DTRACEACT_SYM:
11622 		case DTRACEACT_MOD:
11623 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11624 			    sizeof (uint64_t)) ||
11625 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11626 				return (EINVAL);
11627 			break;
11628 
11629 		case DTRACEACT_USYM:
11630 		case DTRACEACT_UMOD:
11631 		case DTRACEACT_UADDR:
11632 			if (dp == NULL ||
11633 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11634 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11635 				return (EINVAL);
11636 
11637 			/*
11638 			 * We have a slot for the pid, plus a slot for the
11639 			 * argument.  To keep things simple (aligned with
11640 			 * bitness-neutral sizing), we store each as a 64-bit
11641 			 * quantity.
11642 			 */
11643 			size = 2 * sizeof (uint64_t);
11644 			break;
11645 
11646 		case DTRACEACT_STOP:
11647 		case DTRACEACT_BREAKPOINT:
11648 		case DTRACEACT_PANIC:
11649 			break;
11650 
11651 		case DTRACEACT_CHILL:
11652 		case DTRACEACT_DISCARD:
11653 		case DTRACEACT_RAISE:
11654 			if (dp == NULL)
11655 				return (EINVAL);
11656 			break;
11657 
11658 		case DTRACEACT_EXIT:
11659 			if (dp == NULL ||
11660 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11661 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11662 				return (EINVAL);
11663 			break;
11664 
11665 		case DTRACEACT_SPECULATE:
11666 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11667 				return (EINVAL);
11668 
11669 			if (dp == NULL)
11670 				return (EINVAL);
11671 
11672 			state->dts_speculates = 1;
11673 			break;
11674 
11675 		case DTRACEACT_PRINTM:
11676 		    	size = dp->dtdo_rtype.dtdt_size;
11677 			break;
11678 
11679 		case DTRACEACT_COMMIT: {
11680 			dtrace_action_t *act = ecb->dte_action;
11681 
11682 			for (; act != NULL; act = act->dta_next) {
11683 				if (act->dta_kind == DTRACEACT_COMMIT)
11684 					return (EINVAL);
11685 			}
11686 
11687 			if (dp == NULL)
11688 				return (EINVAL);
11689 			break;
11690 		}
11691 
11692 		default:
11693 			return (EINVAL);
11694 		}
11695 
11696 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11697 			/*
11698 			 * If this is a data-storing action or a speculate,
11699 			 * we must be sure that there isn't a commit on the
11700 			 * action chain.
11701 			 */
11702 			dtrace_action_t *act = ecb->dte_action;
11703 
11704 			for (; act != NULL; act = act->dta_next) {
11705 				if (act->dta_kind == DTRACEACT_COMMIT)
11706 					return (EINVAL);
11707 			}
11708 		}
11709 
11710 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11711 		action->dta_rec.dtrd_size = size;
11712 	}
11713 
11714 	action->dta_refcnt = 1;
11715 	rec = &action->dta_rec;
11716 	size = rec->dtrd_size;
11717 
11718 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11719 		if (!(size & mask)) {
11720 			align = mask + 1;
11721 			break;
11722 		}
11723 	}
11724 
11725 	action->dta_kind = desc->dtad_kind;
11726 
11727 	if ((action->dta_difo = dp) != NULL)
11728 		dtrace_difo_hold(dp);
11729 
11730 	rec->dtrd_action = action->dta_kind;
11731 	rec->dtrd_arg = arg;
11732 	rec->dtrd_uarg = desc->dtad_uarg;
11733 	rec->dtrd_alignment = (uint16_t)align;
11734 	rec->dtrd_format = format;
11735 
11736 	if ((last = ecb->dte_action_last) != NULL) {
11737 		ASSERT(ecb->dte_action != NULL);
11738 		action->dta_prev = last;
11739 		last->dta_next = action;
11740 	} else {
11741 		ASSERT(ecb->dte_action == NULL);
11742 		ecb->dte_action = action;
11743 	}
11744 
11745 	ecb->dte_action_last = action;
11746 
11747 	return (0);
11748 }
11749 
11750 static void
11751 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11752 {
11753 	dtrace_action_t *act = ecb->dte_action, *next;
11754 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11755 	dtrace_difo_t *dp;
11756 	uint16_t format;
11757 
11758 	if (act != NULL && act->dta_refcnt > 1) {
11759 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11760 		act->dta_refcnt--;
11761 	} else {
11762 		for (; act != NULL; act = next) {
11763 			next = act->dta_next;
11764 			ASSERT(next != NULL || act == ecb->dte_action_last);
11765 			ASSERT(act->dta_refcnt == 1);
11766 
11767 			if ((format = act->dta_rec.dtrd_format) != 0)
11768 				dtrace_format_remove(ecb->dte_state, format);
11769 
11770 			if ((dp = act->dta_difo) != NULL)
11771 				dtrace_difo_release(dp, vstate);
11772 
11773 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11774 				dtrace_ecb_aggregation_destroy(ecb, act);
11775 			} else {
11776 				kmem_free(act, sizeof (dtrace_action_t));
11777 			}
11778 		}
11779 	}
11780 
11781 	ecb->dte_action = NULL;
11782 	ecb->dte_action_last = NULL;
11783 	ecb->dte_size = 0;
11784 }
11785 
11786 static void
11787 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11788 {
11789 	/*
11790 	 * We disable the ECB by removing it from its probe.
11791 	 */
11792 	dtrace_ecb_t *pecb, *prev = NULL;
11793 	dtrace_probe_t *probe = ecb->dte_probe;
11794 
11795 	ASSERT(MUTEX_HELD(&dtrace_lock));
11796 
11797 	if (probe == NULL) {
11798 		/*
11799 		 * This is the NULL probe; there is nothing to disable.
11800 		 */
11801 		return;
11802 	}
11803 
11804 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11805 		if (pecb == ecb)
11806 			break;
11807 		prev = pecb;
11808 	}
11809 
11810 	ASSERT(pecb != NULL);
11811 
11812 	if (prev == NULL) {
11813 		probe->dtpr_ecb = ecb->dte_next;
11814 	} else {
11815 		prev->dte_next = ecb->dte_next;
11816 	}
11817 
11818 	if (ecb == probe->dtpr_ecb_last) {
11819 		ASSERT(ecb->dte_next == NULL);
11820 		probe->dtpr_ecb_last = prev;
11821 	}
11822 
11823 	/*
11824 	 * The ECB has been disconnected from the probe; now sync to assure
11825 	 * that all CPUs have seen the change before returning.
11826 	 */
11827 	dtrace_sync();
11828 
11829 	if (probe->dtpr_ecb == NULL) {
11830 		/*
11831 		 * That was the last ECB on the probe; clear the predicate
11832 		 * cache ID for the probe, disable it and sync one more time
11833 		 * to assure that we'll never hit it again.
11834 		 */
11835 		dtrace_provider_t *prov = probe->dtpr_provider;
11836 
11837 		ASSERT(ecb->dte_next == NULL);
11838 		ASSERT(probe->dtpr_ecb_last == NULL);
11839 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11840 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11841 		    probe->dtpr_id, probe->dtpr_arg);
11842 		dtrace_sync();
11843 	} else {
11844 		/*
11845 		 * There is at least one ECB remaining on the probe.  If there
11846 		 * is _exactly_ one, set the probe's predicate cache ID to be
11847 		 * the predicate cache ID of the remaining ECB.
11848 		 */
11849 		ASSERT(probe->dtpr_ecb_last != NULL);
11850 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11851 
11852 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11853 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11854 
11855 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11856 
11857 			if (p != NULL)
11858 				probe->dtpr_predcache = p->dtp_cacheid;
11859 		}
11860 
11861 		ecb->dte_next = NULL;
11862 	}
11863 }
11864 
11865 static void
11866 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11867 {
11868 	dtrace_state_t *state = ecb->dte_state;
11869 	dtrace_vstate_t *vstate = &state->dts_vstate;
11870 	dtrace_predicate_t *pred;
11871 	dtrace_epid_t epid = ecb->dte_epid;
11872 
11873 	ASSERT(MUTEX_HELD(&dtrace_lock));
11874 	ASSERT(ecb->dte_next == NULL);
11875 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11876 
11877 	if ((pred = ecb->dte_predicate) != NULL)
11878 		dtrace_predicate_release(pred, vstate);
11879 
11880 	dtrace_ecb_action_remove(ecb);
11881 
11882 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11883 	state->dts_ecbs[epid - 1] = NULL;
11884 
11885 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11886 }
11887 
11888 static dtrace_ecb_t *
11889 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11890     dtrace_enabling_t *enab)
11891 {
11892 	dtrace_ecb_t *ecb;
11893 	dtrace_predicate_t *pred;
11894 	dtrace_actdesc_t *act;
11895 	dtrace_provider_t *prov;
11896 	dtrace_ecbdesc_t *desc = enab->dten_current;
11897 
11898 	ASSERT(MUTEX_HELD(&dtrace_lock));
11899 	ASSERT(state != NULL);
11900 
11901 	ecb = dtrace_ecb_add(state, probe);
11902 	ecb->dte_uarg = desc->dted_uarg;
11903 
11904 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11905 		dtrace_predicate_hold(pred);
11906 		ecb->dte_predicate = pred;
11907 	}
11908 
11909 	if (probe != NULL) {
11910 		/*
11911 		 * If the provider shows more leg than the consumer is old
11912 		 * enough to see, we need to enable the appropriate implicit
11913 		 * predicate bits to prevent the ecb from activating at
11914 		 * revealing times.
11915 		 *
11916 		 * Providers specifying DTRACE_PRIV_USER at register time
11917 		 * are stating that they need the /proc-style privilege
11918 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11919 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11920 		 */
11921 		prov = probe->dtpr_provider;
11922 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11923 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11924 			ecb->dte_cond |= DTRACE_COND_OWNER;
11925 
11926 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11927 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11928 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11929 
11930 		/*
11931 		 * If the provider shows us kernel innards and the user
11932 		 * is lacking sufficient privilege, enable the
11933 		 * DTRACE_COND_USERMODE implicit predicate.
11934 		 */
11935 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11936 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11937 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11938 	}
11939 
11940 	if (dtrace_ecb_create_cache != NULL) {
11941 		/*
11942 		 * If we have a cached ecb, we'll use its action list instead
11943 		 * of creating our own (saving both time and space).
11944 		 */
11945 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11946 		dtrace_action_t *act = cached->dte_action;
11947 
11948 		if (act != NULL) {
11949 			ASSERT(act->dta_refcnt > 0);
11950 			act->dta_refcnt++;
11951 			ecb->dte_action = act;
11952 			ecb->dte_action_last = cached->dte_action_last;
11953 			ecb->dte_needed = cached->dte_needed;
11954 			ecb->dte_size = cached->dte_size;
11955 			ecb->dte_alignment = cached->dte_alignment;
11956 		}
11957 
11958 		return (ecb);
11959 	}
11960 
11961 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11962 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11963 			dtrace_ecb_destroy(ecb);
11964 			return (NULL);
11965 		}
11966 	}
11967 
11968 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11969 		dtrace_ecb_destroy(ecb);
11970 		return (NULL);
11971 	}
11972 
11973 	return (dtrace_ecb_create_cache = ecb);
11974 }
11975 
11976 static int
11977 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11978 {
11979 	dtrace_ecb_t *ecb;
11980 	dtrace_enabling_t *enab = arg;
11981 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11982 
11983 	ASSERT(state != NULL);
11984 
11985 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11986 		/*
11987 		 * This probe was created in a generation for which this
11988 		 * enabling has previously created ECBs; we don't want to
11989 		 * enable it again, so just kick out.
11990 		 */
11991 		return (DTRACE_MATCH_NEXT);
11992 	}
11993 
11994 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11995 		return (DTRACE_MATCH_DONE);
11996 
11997 	dtrace_ecb_enable(ecb);
11998 	return (DTRACE_MATCH_NEXT);
11999 }
12000 
12001 static dtrace_ecb_t *
12002 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
12003 {
12004 	dtrace_ecb_t *ecb;
12005 
12006 	ASSERT(MUTEX_HELD(&dtrace_lock));
12007 
12008 	if (id == 0 || id > state->dts_necbs)
12009 		return (NULL);
12010 
12011 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12012 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12013 
12014 	return (state->dts_ecbs[id - 1]);
12015 }
12016 
12017 static dtrace_aggregation_t *
12018 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12019 {
12020 	dtrace_aggregation_t *agg;
12021 
12022 	ASSERT(MUTEX_HELD(&dtrace_lock));
12023 
12024 	if (id == 0 || id > state->dts_naggregations)
12025 		return (NULL);
12026 
12027 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12028 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12029 	    agg->dtag_id == id);
12030 
12031 	return (state->dts_aggregations[id - 1]);
12032 }
12033 
12034 /*
12035  * DTrace Buffer Functions
12036  *
12037  * The following functions manipulate DTrace buffers.  Most of these functions
12038  * are called in the context of establishing or processing consumer state;
12039  * exceptions are explicitly noted.
12040  */
12041 
12042 /*
12043  * Note:  called from cross call context.  This function switches the two
12044  * buffers on a given CPU.  The atomicity of this operation is assured by
12045  * disabling interrupts while the actual switch takes place; the disabling of
12046  * interrupts serializes the execution with any execution of dtrace_probe() on
12047  * the same CPU.
12048  */
12049 static void
12050 dtrace_buffer_switch(dtrace_buffer_t *buf)
12051 {
12052 	caddr_t tomax = buf->dtb_tomax;
12053 	caddr_t xamot = buf->dtb_xamot;
12054 	dtrace_icookie_t cookie;
12055 	hrtime_t now;
12056 
12057 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12058 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12059 
12060 	cookie = dtrace_interrupt_disable();
12061 	now = dtrace_gethrtime();
12062 	buf->dtb_tomax = xamot;
12063 	buf->dtb_xamot = tomax;
12064 	buf->dtb_xamot_drops = buf->dtb_drops;
12065 	buf->dtb_xamot_offset = buf->dtb_offset;
12066 	buf->dtb_xamot_errors = buf->dtb_errors;
12067 	buf->dtb_xamot_flags = buf->dtb_flags;
12068 	buf->dtb_offset = 0;
12069 	buf->dtb_drops = 0;
12070 	buf->dtb_errors = 0;
12071 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12072 	buf->dtb_interval = now - buf->dtb_switched;
12073 	buf->dtb_switched = now;
12074 	dtrace_interrupt_enable(cookie);
12075 }
12076 
12077 /*
12078  * Note:  called from cross call context.  This function activates a buffer
12079  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12080  * is guaranteed by the disabling of interrupts.
12081  */
12082 static void
12083 dtrace_buffer_activate(dtrace_state_t *state)
12084 {
12085 	dtrace_buffer_t *buf;
12086 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12087 
12088 	buf = &state->dts_buffer[curcpu];
12089 
12090 	if (buf->dtb_tomax != NULL) {
12091 		/*
12092 		 * We might like to assert that the buffer is marked inactive,
12093 		 * but this isn't necessarily true:  the buffer for the CPU
12094 		 * that processes the BEGIN probe has its buffer activated
12095 		 * manually.  In this case, we take the (harmless) action
12096 		 * re-clearing the bit INACTIVE bit.
12097 		 */
12098 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12099 	}
12100 
12101 	dtrace_interrupt_enable(cookie);
12102 }
12103 
12104 #ifdef __FreeBSD__
12105 /*
12106  * Activate the specified per-CPU buffer.  This is used instead of
12107  * dtrace_buffer_activate() when APs have not yet started, i.e. when
12108  * activating anonymous state.
12109  */
12110 static void
12111 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12112 {
12113 
12114 	if (state->dts_buffer[cpu].dtb_tomax != NULL)
12115 		state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12116 }
12117 #endif
12118 
12119 static int
12120 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12121     processorid_t cpu, int *factor)
12122 {
12123 #ifdef illumos
12124 	cpu_t *cp;
12125 #endif
12126 	dtrace_buffer_t *buf;
12127 	int allocated = 0, desired = 0;
12128 
12129 #ifdef illumos
12130 	ASSERT(MUTEX_HELD(&cpu_lock));
12131 	ASSERT(MUTEX_HELD(&dtrace_lock));
12132 
12133 	*factor = 1;
12134 
12135 	if (size > dtrace_nonroot_maxsize &&
12136 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12137 		return (EFBIG);
12138 
12139 	cp = cpu_list;
12140 
12141 	do {
12142 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12143 			continue;
12144 
12145 		buf = &bufs[cp->cpu_id];
12146 
12147 		/*
12148 		 * If there is already a buffer allocated for this CPU, it
12149 		 * is only possible that this is a DR event.  In this case,
12150 		 */
12151 		if (buf->dtb_tomax != NULL) {
12152 			ASSERT(buf->dtb_size == size);
12153 			continue;
12154 		}
12155 
12156 		ASSERT(buf->dtb_xamot == NULL);
12157 
12158 		if ((buf->dtb_tomax = kmem_zalloc(size,
12159 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12160 			goto err;
12161 
12162 		buf->dtb_size = size;
12163 		buf->dtb_flags = flags;
12164 		buf->dtb_offset = 0;
12165 		buf->dtb_drops = 0;
12166 
12167 		if (flags & DTRACEBUF_NOSWITCH)
12168 			continue;
12169 
12170 		if ((buf->dtb_xamot = kmem_zalloc(size,
12171 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12172 			goto err;
12173 	} while ((cp = cp->cpu_next) != cpu_list);
12174 
12175 	return (0);
12176 
12177 err:
12178 	cp = cpu_list;
12179 
12180 	do {
12181 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12182 			continue;
12183 
12184 		buf = &bufs[cp->cpu_id];
12185 		desired += 2;
12186 
12187 		if (buf->dtb_xamot != NULL) {
12188 			ASSERT(buf->dtb_tomax != NULL);
12189 			ASSERT(buf->dtb_size == size);
12190 			kmem_free(buf->dtb_xamot, size);
12191 			allocated++;
12192 		}
12193 
12194 		if (buf->dtb_tomax != NULL) {
12195 			ASSERT(buf->dtb_size == size);
12196 			kmem_free(buf->dtb_tomax, size);
12197 			allocated++;
12198 		}
12199 
12200 		buf->dtb_tomax = NULL;
12201 		buf->dtb_xamot = NULL;
12202 		buf->dtb_size = 0;
12203 	} while ((cp = cp->cpu_next) != cpu_list);
12204 #else
12205 	int i;
12206 
12207 	*factor = 1;
12208 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12209     defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12210 	/*
12211 	 * FreeBSD isn't good at limiting the amount of memory we
12212 	 * ask to malloc, so let's place a limit here before trying
12213 	 * to do something that might well end in tears at bedtime.
12214 	 */
12215 	int bufsize_percpu_frac = dtrace_bufsize_max_frac * mp_ncpus;
12216 	if (size > physmem * PAGE_SIZE / bufsize_percpu_frac)
12217 		return (ENOMEM);
12218 #endif
12219 
12220 	ASSERT(MUTEX_HELD(&dtrace_lock));
12221 	CPU_FOREACH(i) {
12222 		if (cpu != DTRACE_CPUALL && cpu != i)
12223 			continue;
12224 
12225 		buf = &bufs[i];
12226 
12227 		/*
12228 		 * If there is already a buffer allocated for this CPU, it
12229 		 * is only possible that this is a DR event.  In this case,
12230 		 * the buffer size must match our specified size.
12231 		 */
12232 		if (buf->dtb_tomax != NULL) {
12233 			ASSERT(buf->dtb_size == size);
12234 			continue;
12235 		}
12236 
12237 		ASSERT(buf->dtb_xamot == NULL);
12238 
12239 		if ((buf->dtb_tomax = kmem_zalloc(size,
12240 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12241 			goto err;
12242 
12243 		buf->dtb_size = size;
12244 		buf->dtb_flags = flags;
12245 		buf->dtb_offset = 0;
12246 		buf->dtb_drops = 0;
12247 
12248 		if (flags & DTRACEBUF_NOSWITCH)
12249 			continue;
12250 
12251 		if ((buf->dtb_xamot = kmem_zalloc(size,
12252 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12253 			goto err;
12254 	}
12255 
12256 	return (0);
12257 
12258 err:
12259 	/*
12260 	 * Error allocating memory, so free the buffers that were
12261 	 * allocated before the failed allocation.
12262 	 */
12263 	CPU_FOREACH(i) {
12264 		if (cpu != DTRACE_CPUALL && cpu != i)
12265 			continue;
12266 
12267 		buf = &bufs[i];
12268 		desired += 2;
12269 
12270 		if (buf->dtb_xamot != NULL) {
12271 			ASSERT(buf->dtb_tomax != NULL);
12272 			ASSERT(buf->dtb_size == size);
12273 			kmem_free(buf->dtb_xamot, size);
12274 			allocated++;
12275 		}
12276 
12277 		if (buf->dtb_tomax != NULL) {
12278 			ASSERT(buf->dtb_size == size);
12279 			kmem_free(buf->dtb_tomax, size);
12280 			allocated++;
12281 		}
12282 
12283 		buf->dtb_tomax = NULL;
12284 		buf->dtb_xamot = NULL;
12285 		buf->dtb_size = 0;
12286 
12287 	}
12288 #endif
12289 	*factor = desired / (allocated > 0 ? allocated : 1);
12290 
12291 	return (ENOMEM);
12292 }
12293 
12294 /*
12295  * Note:  called from probe context.  This function just increments the drop
12296  * count on a buffer.  It has been made a function to allow for the
12297  * possibility of understanding the source of mysterious drop counts.  (A
12298  * problem for which one may be particularly disappointed that DTrace cannot
12299  * be used to understand DTrace.)
12300  */
12301 static void
12302 dtrace_buffer_drop(dtrace_buffer_t *buf)
12303 {
12304 	buf->dtb_drops++;
12305 }
12306 
12307 /*
12308  * Note:  called from probe context.  This function is called to reserve space
12309  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12310  * mstate.  Returns the new offset in the buffer, or a negative value if an
12311  * error has occurred.
12312  */
12313 static intptr_t
12314 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12315     dtrace_state_t *state, dtrace_mstate_t *mstate)
12316 {
12317 	intptr_t offs = buf->dtb_offset, soffs;
12318 	intptr_t woffs;
12319 	caddr_t tomax;
12320 	size_t total;
12321 
12322 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12323 		return (-1);
12324 
12325 	if ((tomax = buf->dtb_tomax) == NULL) {
12326 		dtrace_buffer_drop(buf);
12327 		return (-1);
12328 	}
12329 
12330 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12331 		while (offs & (align - 1)) {
12332 			/*
12333 			 * Assert that our alignment is off by a number which
12334 			 * is itself sizeof (uint32_t) aligned.
12335 			 */
12336 			ASSERT(!((align - (offs & (align - 1))) &
12337 			    (sizeof (uint32_t) - 1)));
12338 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12339 			offs += sizeof (uint32_t);
12340 		}
12341 
12342 		if ((soffs = offs + needed) > buf->dtb_size) {
12343 			dtrace_buffer_drop(buf);
12344 			return (-1);
12345 		}
12346 
12347 		if (mstate == NULL)
12348 			return (offs);
12349 
12350 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12351 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12352 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12353 
12354 		return (offs);
12355 	}
12356 
12357 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12358 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12359 		    (buf->dtb_flags & DTRACEBUF_FULL))
12360 			return (-1);
12361 		goto out;
12362 	}
12363 
12364 	total = needed + (offs & (align - 1));
12365 
12366 	/*
12367 	 * For a ring buffer, life is quite a bit more complicated.  Before
12368 	 * we can store any padding, we need to adjust our wrapping offset.
12369 	 * (If we've never before wrapped or we're not about to, no adjustment
12370 	 * is required.)
12371 	 */
12372 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12373 	    offs + total > buf->dtb_size) {
12374 		woffs = buf->dtb_xamot_offset;
12375 
12376 		if (offs + total > buf->dtb_size) {
12377 			/*
12378 			 * We can't fit in the end of the buffer.  First, a
12379 			 * sanity check that we can fit in the buffer at all.
12380 			 */
12381 			if (total > buf->dtb_size) {
12382 				dtrace_buffer_drop(buf);
12383 				return (-1);
12384 			}
12385 
12386 			/*
12387 			 * We're going to be storing at the top of the buffer,
12388 			 * so now we need to deal with the wrapped offset.  We
12389 			 * only reset our wrapped offset to 0 if it is
12390 			 * currently greater than the current offset.  If it
12391 			 * is less than the current offset, it is because a
12392 			 * previous allocation induced a wrap -- but the
12393 			 * allocation didn't subsequently take the space due
12394 			 * to an error or false predicate evaluation.  In this
12395 			 * case, we'll just leave the wrapped offset alone: if
12396 			 * the wrapped offset hasn't been advanced far enough
12397 			 * for this allocation, it will be adjusted in the
12398 			 * lower loop.
12399 			 */
12400 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12401 				if (woffs >= offs)
12402 					woffs = 0;
12403 			} else {
12404 				woffs = 0;
12405 			}
12406 
12407 			/*
12408 			 * Now we know that we're going to be storing to the
12409 			 * top of the buffer and that there is room for us
12410 			 * there.  We need to clear the buffer from the current
12411 			 * offset to the end (there may be old gunk there).
12412 			 */
12413 			while (offs < buf->dtb_size)
12414 				tomax[offs++] = 0;
12415 
12416 			/*
12417 			 * We need to set our offset to zero.  And because we
12418 			 * are wrapping, we need to set the bit indicating as
12419 			 * much.  We can also adjust our needed space back
12420 			 * down to the space required by the ECB -- we know
12421 			 * that the top of the buffer is aligned.
12422 			 */
12423 			offs = 0;
12424 			total = needed;
12425 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12426 		} else {
12427 			/*
12428 			 * There is room for us in the buffer, so we simply
12429 			 * need to check the wrapped offset.
12430 			 */
12431 			if (woffs < offs) {
12432 				/*
12433 				 * The wrapped offset is less than the offset.
12434 				 * This can happen if we allocated buffer space
12435 				 * that induced a wrap, but then we didn't
12436 				 * subsequently take the space due to an error
12437 				 * or false predicate evaluation.  This is
12438 				 * okay; we know that _this_ allocation isn't
12439 				 * going to induce a wrap.  We still can't
12440 				 * reset the wrapped offset to be zero,
12441 				 * however: the space may have been trashed in
12442 				 * the previous failed probe attempt.  But at
12443 				 * least the wrapped offset doesn't need to
12444 				 * be adjusted at all...
12445 				 */
12446 				goto out;
12447 			}
12448 		}
12449 
12450 		while (offs + total > woffs) {
12451 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12452 			size_t size;
12453 
12454 			if (epid == DTRACE_EPIDNONE) {
12455 				size = sizeof (uint32_t);
12456 			} else {
12457 				ASSERT3U(epid, <=, state->dts_necbs);
12458 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12459 
12460 				size = state->dts_ecbs[epid - 1]->dte_size;
12461 			}
12462 
12463 			ASSERT(woffs + size <= buf->dtb_size);
12464 			ASSERT(size != 0);
12465 
12466 			if (woffs + size == buf->dtb_size) {
12467 				/*
12468 				 * We've reached the end of the buffer; we want
12469 				 * to set the wrapped offset to 0 and break
12470 				 * out.  However, if the offs is 0, then we're
12471 				 * in a strange edge-condition:  the amount of
12472 				 * space that we want to reserve plus the size
12473 				 * of the record that we're overwriting is
12474 				 * greater than the size of the buffer.  This
12475 				 * is problematic because if we reserve the
12476 				 * space but subsequently don't consume it (due
12477 				 * to a failed predicate or error) the wrapped
12478 				 * offset will be 0 -- yet the EPID at offset 0
12479 				 * will not be committed.  This situation is
12480 				 * relatively easy to deal with:  if we're in
12481 				 * this case, the buffer is indistinguishable
12482 				 * from one that hasn't wrapped; we need only
12483 				 * finish the job by clearing the wrapped bit,
12484 				 * explicitly setting the offset to be 0, and
12485 				 * zero'ing out the old data in the buffer.
12486 				 */
12487 				if (offs == 0) {
12488 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12489 					buf->dtb_offset = 0;
12490 					woffs = total;
12491 
12492 					while (woffs < buf->dtb_size)
12493 						tomax[woffs++] = 0;
12494 				}
12495 
12496 				woffs = 0;
12497 				break;
12498 			}
12499 
12500 			woffs += size;
12501 		}
12502 
12503 		/*
12504 		 * We have a wrapped offset.  It may be that the wrapped offset
12505 		 * has become zero -- that's okay.
12506 		 */
12507 		buf->dtb_xamot_offset = woffs;
12508 	}
12509 
12510 out:
12511 	/*
12512 	 * Now we can plow the buffer with any necessary padding.
12513 	 */
12514 	while (offs & (align - 1)) {
12515 		/*
12516 		 * Assert that our alignment is off by a number which
12517 		 * is itself sizeof (uint32_t) aligned.
12518 		 */
12519 		ASSERT(!((align - (offs & (align - 1))) &
12520 		    (sizeof (uint32_t) - 1)));
12521 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12522 		offs += sizeof (uint32_t);
12523 	}
12524 
12525 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12526 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12527 			buf->dtb_flags |= DTRACEBUF_FULL;
12528 			return (-1);
12529 		}
12530 	}
12531 
12532 	if (mstate == NULL)
12533 		return (offs);
12534 
12535 	/*
12536 	 * For ring buffers and fill buffers, the scratch space is always
12537 	 * the inactive buffer.
12538 	 */
12539 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12540 	mstate->dtms_scratch_size = buf->dtb_size;
12541 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12542 
12543 	return (offs);
12544 }
12545 
12546 static void
12547 dtrace_buffer_polish(dtrace_buffer_t *buf)
12548 {
12549 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12550 	ASSERT(MUTEX_HELD(&dtrace_lock));
12551 
12552 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12553 		return;
12554 
12555 	/*
12556 	 * We need to polish the ring buffer.  There are three cases:
12557 	 *
12558 	 * - The first (and presumably most common) is that there is no gap
12559 	 *   between the buffer offset and the wrapped offset.  In this case,
12560 	 *   there is nothing in the buffer that isn't valid data; we can
12561 	 *   mark the buffer as polished and return.
12562 	 *
12563 	 * - The second (less common than the first but still more common
12564 	 *   than the third) is that there is a gap between the buffer offset
12565 	 *   and the wrapped offset, and the wrapped offset is larger than the
12566 	 *   buffer offset.  This can happen because of an alignment issue, or
12567 	 *   can happen because of a call to dtrace_buffer_reserve() that
12568 	 *   didn't subsequently consume the buffer space.  In this case,
12569 	 *   we need to zero the data from the buffer offset to the wrapped
12570 	 *   offset.
12571 	 *
12572 	 * - The third (and least common) is that there is a gap between the
12573 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12574 	 *   _less_ than the buffer offset.  This can only happen because a
12575 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12576 	 *   was not subsequently consumed.  In this case, we need to zero the
12577 	 *   space from the offset to the end of the buffer _and_ from the
12578 	 *   top of the buffer to the wrapped offset.
12579 	 */
12580 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12581 		bzero(buf->dtb_tomax + buf->dtb_offset,
12582 		    buf->dtb_xamot_offset - buf->dtb_offset);
12583 	}
12584 
12585 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12586 		bzero(buf->dtb_tomax + buf->dtb_offset,
12587 		    buf->dtb_size - buf->dtb_offset);
12588 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12589 	}
12590 }
12591 
12592 /*
12593  * This routine determines if data generated at the specified time has likely
12594  * been entirely consumed at user-level.  This routine is called to determine
12595  * if an ECB on a defunct probe (but for an active enabling) can be safely
12596  * disabled and destroyed.
12597  */
12598 static int
12599 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12600 {
12601 	int i;
12602 
12603 	for (i = 0; i < NCPU; i++) {
12604 		dtrace_buffer_t *buf = &bufs[i];
12605 
12606 		if (buf->dtb_size == 0)
12607 			continue;
12608 
12609 		if (buf->dtb_flags & DTRACEBUF_RING)
12610 			return (0);
12611 
12612 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12613 			return (0);
12614 
12615 		if (buf->dtb_switched - buf->dtb_interval < when)
12616 			return (0);
12617 	}
12618 
12619 	return (1);
12620 }
12621 
12622 static void
12623 dtrace_buffer_free(dtrace_buffer_t *bufs)
12624 {
12625 	int i;
12626 
12627 	for (i = 0; i < NCPU; i++) {
12628 		dtrace_buffer_t *buf = &bufs[i];
12629 
12630 		if (buf->dtb_tomax == NULL) {
12631 			ASSERT(buf->dtb_xamot == NULL);
12632 			ASSERT(buf->dtb_size == 0);
12633 			continue;
12634 		}
12635 
12636 		if (buf->dtb_xamot != NULL) {
12637 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12638 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12639 		}
12640 
12641 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12642 		buf->dtb_size = 0;
12643 		buf->dtb_tomax = NULL;
12644 		buf->dtb_xamot = NULL;
12645 	}
12646 }
12647 
12648 /*
12649  * DTrace Enabling Functions
12650  */
12651 static dtrace_enabling_t *
12652 dtrace_enabling_create(dtrace_vstate_t *vstate)
12653 {
12654 	dtrace_enabling_t *enab;
12655 
12656 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12657 	enab->dten_vstate = vstate;
12658 
12659 	return (enab);
12660 }
12661 
12662 static void
12663 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12664 {
12665 	dtrace_ecbdesc_t **ndesc;
12666 	size_t osize, nsize;
12667 
12668 	/*
12669 	 * We can't add to enablings after we've enabled them, or after we've
12670 	 * retained them.
12671 	 */
12672 	ASSERT(enab->dten_probegen == 0);
12673 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12674 
12675 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12676 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12677 		return;
12678 	}
12679 
12680 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12681 
12682 	if (enab->dten_maxdesc == 0) {
12683 		enab->dten_maxdesc = 1;
12684 	} else {
12685 		enab->dten_maxdesc <<= 1;
12686 	}
12687 
12688 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12689 
12690 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12691 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12692 	bcopy(enab->dten_desc, ndesc, osize);
12693 	if (enab->dten_desc != NULL)
12694 		kmem_free(enab->dten_desc, osize);
12695 
12696 	enab->dten_desc = ndesc;
12697 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12698 }
12699 
12700 static void
12701 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12702     dtrace_probedesc_t *pd)
12703 {
12704 	dtrace_ecbdesc_t *new;
12705 	dtrace_predicate_t *pred;
12706 	dtrace_actdesc_t *act;
12707 
12708 	/*
12709 	 * We're going to create a new ECB description that matches the
12710 	 * specified ECB in every way, but has the specified probe description.
12711 	 */
12712 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12713 
12714 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12715 		dtrace_predicate_hold(pred);
12716 
12717 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12718 		dtrace_actdesc_hold(act);
12719 
12720 	new->dted_action = ecb->dted_action;
12721 	new->dted_pred = ecb->dted_pred;
12722 	new->dted_probe = *pd;
12723 	new->dted_uarg = ecb->dted_uarg;
12724 
12725 	dtrace_enabling_add(enab, new);
12726 }
12727 
12728 static void
12729 dtrace_enabling_dump(dtrace_enabling_t *enab)
12730 {
12731 	int i;
12732 
12733 	for (i = 0; i < enab->dten_ndesc; i++) {
12734 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12735 
12736 #ifdef __FreeBSD__
12737 		printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12738 		    desc->dtpd_provider, desc->dtpd_mod,
12739 		    desc->dtpd_func, desc->dtpd_name);
12740 #else
12741 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12742 		    desc->dtpd_provider, desc->dtpd_mod,
12743 		    desc->dtpd_func, desc->dtpd_name);
12744 #endif
12745 	}
12746 }
12747 
12748 static void
12749 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12750 {
12751 	int i;
12752 	dtrace_ecbdesc_t *ep;
12753 	dtrace_vstate_t *vstate = enab->dten_vstate;
12754 
12755 	ASSERT(MUTEX_HELD(&dtrace_lock));
12756 
12757 	for (i = 0; i < enab->dten_ndesc; i++) {
12758 		dtrace_actdesc_t *act, *next;
12759 		dtrace_predicate_t *pred;
12760 
12761 		ep = enab->dten_desc[i];
12762 
12763 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12764 			dtrace_predicate_release(pred, vstate);
12765 
12766 		for (act = ep->dted_action; act != NULL; act = next) {
12767 			next = act->dtad_next;
12768 			dtrace_actdesc_release(act, vstate);
12769 		}
12770 
12771 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12772 	}
12773 
12774 	if (enab->dten_desc != NULL)
12775 		kmem_free(enab->dten_desc,
12776 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12777 
12778 	/*
12779 	 * If this was a retained enabling, decrement the dts_nretained count
12780 	 * and take it off of the dtrace_retained list.
12781 	 */
12782 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12783 	    dtrace_retained == enab) {
12784 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12785 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12786 		enab->dten_vstate->dtvs_state->dts_nretained--;
12787 		dtrace_retained_gen++;
12788 	}
12789 
12790 	if (enab->dten_prev == NULL) {
12791 		if (dtrace_retained == enab) {
12792 			dtrace_retained = enab->dten_next;
12793 
12794 			if (dtrace_retained != NULL)
12795 				dtrace_retained->dten_prev = NULL;
12796 		}
12797 	} else {
12798 		ASSERT(enab != dtrace_retained);
12799 		ASSERT(dtrace_retained != NULL);
12800 		enab->dten_prev->dten_next = enab->dten_next;
12801 	}
12802 
12803 	if (enab->dten_next != NULL) {
12804 		ASSERT(dtrace_retained != NULL);
12805 		enab->dten_next->dten_prev = enab->dten_prev;
12806 	}
12807 
12808 	kmem_free(enab, sizeof (dtrace_enabling_t));
12809 }
12810 
12811 static int
12812 dtrace_enabling_retain(dtrace_enabling_t *enab)
12813 {
12814 	dtrace_state_t *state;
12815 
12816 	ASSERT(MUTEX_HELD(&dtrace_lock));
12817 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12818 	ASSERT(enab->dten_vstate != NULL);
12819 
12820 	state = enab->dten_vstate->dtvs_state;
12821 	ASSERT(state != NULL);
12822 
12823 	/*
12824 	 * We only allow each state to retain dtrace_retain_max enablings.
12825 	 */
12826 	if (state->dts_nretained >= dtrace_retain_max)
12827 		return (ENOSPC);
12828 
12829 	state->dts_nretained++;
12830 	dtrace_retained_gen++;
12831 
12832 	if (dtrace_retained == NULL) {
12833 		dtrace_retained = enab;
12834 		return (0);
12835 	}
12836 
12837 	enab->dten_next = dtrace_retained;
12838 	dtrace_retained->dten_prev = enab;
12839 	dtrace_retained = enab;
12840 
12841 	return (0);
12842 }
12843 
12844 static int
12845 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12846     dtrace_probedesc_t *create)
12847 {
12848 	dtrace_enabling_t *new, *enab;
12849 	int found = 0, err = ENOENT;
12850 
12851 	ASSERT(MUTEX_HELD(&dtrace_lock));
12852 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12853 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12854 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12855 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12856 
12857 	new = dtrace_enabling_create(&state->dts_vstate);
12858 
12859 	/*
12860 	 * Iterate over all retained enablings, looking for enablings that
12861 	 * match the specified state.
12862 	 */
12863 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12864 		int i;
12865 
12866 		/*
12867 		 * dtvs_state can only be NULL for helper enablings -- and
12868 		 * helper enablings can't be retained.
12869 		 */
12870 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12871 
12872 		if (enab->dten_vstate->dtvs_state != state)
12873 			continue;
12874 
12875 		/*
12876 		 * Now iterate over each probe description; we're looking for
12877 		 * an exact match to the specified probe description.
12878 		 */
12879 		for (i = 0; i < enab->dten_ndesc; i++) {
12880 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12881 			dtrace_probedesc_t *pd = &ep->dted_probe;
12882 
12883 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12884 				continue;
12885 
12886 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12887 				continue;
12888 
12889 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12890 				continue;
12891 
12892 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12893 				continue;
12894 
12895 			/*
12896 			 * We have a winning probe!  Add it to our growing
12897 			 * enabling.
12898 			 */
12899 			found = 1;
12900 			dtrace_enabling_addlike(new, ep, create);
12901 		}
12902 	}
12903 
12904 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12905 		dtrace_enabling_destroy(new);
12906 		return (err);
12907 	}
12908 
12909 	return (0);
12910 }
12911 
12912 static void
12913 dtrace_enabling_retract(dtrace_state_t *state)
12914 {
12915 	dtrace_enabling_t *enab, *next;
12916 
12917 	ASSERT(MUTEX_HELD(&dtrace_lock));
12918 
12919 	/*
12920 	 * Iterate over all retained enablings, destroy the enablings retained
12921 	 * for the specified state.
12922 	 */
12923 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12924 		next = enab->dten_next;
12925 
12926 		/*
12927 		 * dtvs_state can only be NULL for helper enablings -- and
12928 		 * helper enablings can't be retained.
12929 		 */
12930 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12931 
12932 		if (enab->dten_vstate->dtvs_state == state) {
12933 			ASSERT(state->dts_nretained > 0);
12934 			dtrace_enabling_destroy(enab);
12935 		}
12936 	}
12937 
12938 	ASSERT(state->dts_nretained == 0);
12939 }
12940 
12941 static int
12942 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12943 {
12944 	int i = 0;
12945 	int matched = 0;
12946 
12947 	ASSERT(MUTEX_HELD(&cpu_lock));
12948 	ASSERT(MUTEX_HELD(&dtrace_lock));
12949 
12950 	for (i = 0; i < enab->dten_ndesc; i++) {
12951 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12952 
12953 		enab->dten_current = ep;
12954 		enab->dten_error = 0;
12955 
12956 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12957 
12958 		if (enab->dten_error != 0) {
12959 			/*
12960 			 * If we get an error half-way through enabling the
12961 			 * probes, we kick out -- perhaps with some number of
12962 			 * them enabled.  Leaving enabled probes enabled may
12963 			 * be slightly confusing for user-level, but we expect
12964 			 * that no one will attempt to actually drive on in
12965 			 * the face of such errors.  If this is an anonymous
12966 			 * enabling (indicated with a NULL nmatched pointer),
12967 			 * we cmn_err() a message.  We aren't expecting to
12968 			 * get such an error -- such as it can exist at all,
12969 			 * it would be a result of corrupted DOF in the driver
12970 			 * properties.
12971 			 */
12972 			if (nmatched == NULL) {
12973 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12974 				    "error on %p: %d", (void *)ep,
12975 				    enab->dten_error);
12976 			}
12977 
12978 			return (enab->dten_error);
12979 		}
12980 	}
12981 
12982 	enab->dten_probegen = dtrace_probegen;
12983 	if (nmatched != NULL)
12984 		*nmatched = matched;
12985 
12986 	return (0);
12987 }
12988 
12989 static void
12990 dtrace_enabling_matchall(void)
12991 {
12992 	dtrace_enabling_t *enab;
12993 
12994 	mutex_enter(&cpu_lock);
12995 	mutex_enter(&dtrace_lock);
12996 
12997 	/*
12998 	 * Iterate over all retained enablings to see if any probes match
12999 	 * against them.  We only perform this operation on enablings for which
13000 	 * we have sufficient permissions by virtue of being in the global zone
13001 	 * or in the same zone as the DTrace client.  Because we can be called
13002 	 * after dtrace_detach() has been called, we cannot assert that there
13003 	 * are retained enablings.  We can safely load from dtrace_retained,
13004 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
13005 	 * block pending our completion.
13006 	 */
13007 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13008 #ifdef illumos
13009 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
13010 
13011 		if (INGLOBALZONE(curproc) ||
13012 		    cr != NULL && getzoneid() == crgetzoneid(cr))
13013 #endif
13014 			(void) dtrace_enabling_match(enab, NULL);
13015 	}
13016 
13017 	mutex_exit(&dtrace_lock);
13018 	mutex_exit(&cpu_lock);
13019 }
13020 
13021 /*
13022  * If an enabling is to be enabled without having matched probes (that is, if
13023  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13024  * enabling must be _primed_ by creating an ECB for every ECB description.
13025  * This must be done to assure that we know the number of speculations, the
13026  * number of aggregations, the minimum buffer size needed, etc. before we
13027  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
13028  * enabling any probes, we create ECBs for every ECB decription, but with a
13029  * NULL probe -- which is exactly what this function does.
13030  */
13031 static void
13032 dtrace_enabling_prime(dtrace_state_t *state)
13033 {
13034 	dtrace_enabling_t *enab;
13035 	int i;
13036 
13037 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13038 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
13039 
13040 		if (enab->dten_vstate->dtvs_state != state)
13041 			continue;
13042 
13043 		/*
13044 		 * We don't want to prime an enabling more than once, lest
13045 		 * we allow a malicious user to induce resource exhaustion.
13046 		 * (The ECBs that result from priming an enabling aren't
13047 		 * leaked -- but they also aren't deallocated until the
13048 		 * consumer state is destroyed.)
13049 		 */
13050 		if (enab->dten_primed)
13051 			continue;
13052 
13053 		for (i = 0; i < enab->dten_ndesc; i++) {
13054 			enab->dten_current = enab->dten_desc[i];
13055 			(void) dtrace_probe_enable(NULL, enab);
13056 		}
13057 
13058 		enab->dten_primed = 1;
13059 	}
13060 }
13061 
13062 /*
13063  * Called to indicate that probes should be provided due to retained
13064  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
13065  * must take an initial lap through the enabling calling the dtps_provide()
13066  * entry point explicitly to allow for autocreated probes.
13067  */
13068 static void
13069 dtrace_enabling_provide(dtrace_provider_t *prv)
13070 {
13071 	int i, all = 0;
13072 	dtrace_probedesc_t desc;
13073 	dtrace_genid_t gen;
13074 
13075 	ASSERT(MUTEX_HELD(&dtrace_lock));
13076 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13077 
13078 	if (prv == NULL) {
13079 		all = 1;
13080 		prv = dtrace_provider;
13081 	}
13082 
13083 	do {
13084 		dtrace_enabling_t *enab;
13085 		void *parg = prv->dtpv_arg;
13086 
13087 retry:
13088 		gen = dtrace_retained_gen;
13089 		for (enab = dtrace_retained; enab != NULL;
13090 		    enab = enab->dten_next) {
13091 			for (i = 0; i < enab->dten_ndesc; i++) {
13092 				desc = enab->dten_desc[i]->dted_probe;
13093 				mutex_exit(&dtrace_lock);
13094 				prv->dtpv_pops.dtps_provide(parg, &desc);
13095 				mutex_enter(&dtrace_lock);
13096 				/*
13097 				 * Process the retained enablings again if
13098 				 * they have changed while we weren't holding
13099 				 * dtrace_lock.
13100 				 */
13101 				if (gen != dtrace_retained_gen)
13102 					goto retry;
13103 			}
13104 		}
13105 	} while (all && (prv = prv->dtpv_next) != NULL);
13106 
13107 	mutex_exit(&dtrace_lock);
13108 	dtrace_probe_provide(NULL, all ? NULL : prv);
13109 	mutex_enter(&dtrace_lock);
13110 }
13111 
13112 /*
13113  * Called to reap ECBs that are attached to probes from defunct providers.
13114  */
13115 static void
13116 dtrace_enabling_reap(void)
13117 {
13118 	dtrace_provider_t *prov;
13119 	dtrace_probe_t *probe;
13120 	dtrace_ecb_t *ecb;
13121 	hrtime_t when;
13122 	int i;
13123 
13124 	mutex_enter(&cpu_lock);
13125 	mutex_enter(&dtrace_lock);
13126 
13127 	for (i = 0; i < dtrace_nprobes; i++) {
13128 		if ((probe = dtrace_probes[i]) == NULL)
13129 			continue;
13130 
13131 		if (probe->dtpr_ecb == NULL)
13132 			continue;
13133 
13134 		prov = probe->dtpr_provider;
13135 
13136 		if ((when = prov->dtpv_defunct) == 0)
13137 			continue;
13138 
13139 		/*
13140 		 * We have ECBs on a defunct provider:  we want to reap these
13141 		 * ECBs to allow the provider to unregister.  The destruction
13142 		 * of these ECBs must be done carefully:  if we destroy the ECB
13143 		 * and the consumer later wishes to consume an EPID that
13144 		 * corresponds to the destroyed ECB (and if the EPID metadata
13145 		 * has not been previously consumed), the consumer will abort
13146 		 * processing on the unknown EPID.  To reduce (but not, sadly,
13147 		 * eliminate) the possibility of this, we will only destroy an
13148 		 * ECB for a defunct provider if, for the state that
13149 		 * corresponds to the ECB:
13150 		 *
13151 		 *  (a)	There is no speculative tracing (which can effectively
13152 		 *	cache an EPID for an arbitrary amount of time).
13153 		 *
13154 		 *  (b)	The principal buffers have been switched twice since the
13155 		 *	provider became defunct.
13156 		 *
13157 		 *  (c)	The aggregation buffers are of zero size or have been
13158 		 *	switched twice since the provider became defunct.
13159 		 *
13160 		 * We use dts_speculates to determine (a) and call a function
13161 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
13162 		 * that as soon as we've been unable to destroy one of the ECBs
13163 		 * associated with the probe, we quit trying -- reaping is only
13164 		 * fruitful in as much as we can destroy all ECBs associated
13165 		 * with the defunct provider's probes.
13166 		 */
13167 		while ((ecb = probe->dtpr_ecb) != NULL) {
13168 			dtrace_state_t *state = ecb->dte_state;
13169 			dtrace_buffer_t *buf = state->dts_buffer;
13170 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13171 
13172 			if (state->dts_speculates)
13173 				break;
13174 
13175 			if (!dtrace_buffer_consumed(buf, when))
13176 				break;
13177 
13178 			if (!dtrace_buffer_consumed(aggbuf, when))
13179 				break;
13180 
13181 			dtrace_ecb_disable(ecb);
13182 			ASSERT(probe->dtpr_ecb != ecb);
13183 			dtrace_ecb_destroy(ecb);
13184 		}
13185 	}
13186 
13187 	mutex_exit(&dtrace_lock);
13188 	mutex_exit(&cpu_lock);
13189 }
13190 
13191 /*
13192  * DTrace DOF Functions
13193  */
13194 /*ARGSUSED*/
13195 static void
13196 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13197 {
13198 	if (dtrace_err_verbose)
13199 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
13200 
13201 #ifdef DTRACE_ERRDEBUG
13202 	dtrace_errdebug(str);
13203 #endif
13204 }
13205 
13206 /*
13207  * Create DOF out of a currently enabled state.  Right now, we only create
13208  * DOF containing the run-time options -- but this could be expanded to create
13209  * complete DOF representing the enabled state.
13210  */
13211 static dof_hdr_t *
13212 dtrace_dof_create(dtrace_state_t *state)
13213 {
13214 	dof_hdr_t *dof;
13215 	dof_sec_t *sec;
13216 	dof_optdesc_t *opt;
13217 	int i, len = sizeof (dof_hdr_t) +
13218 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13219 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13220 
13221 	ASSERT(MUTEX_HELD(&dtrace_lock));
13222 
13223 	dof = kmem_zalloc(len, KM_SLEEP);
13224 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13225 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13226 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13227 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13228 
13229 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13230 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13231 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13232 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13233 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13234 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13235 
13236 	dof->dofh_flags = 0;
13237 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13238 	dof->dofh_secsize = sizeof (dof_sec_t);
13239 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13240 	dof->dofh_secoff = sizeof (dof_hdr_t);
13241 	dof->dofh_loadsz = len;
13242 	dof->dofh_filesz = len;
13243 	dof->dofh_pad = 0;
13244 
13245 	/*
13246 	 * Fill in the option section header...
13247 	 */
13248 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13249 	sec->dofs_type = DOF_SECT_OPTDESC;
13250 	sec->dofs_align = sizeof (uint64_t);
13251 	sec->dofs_flags = DOF_SECF_LOAD;
13252 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13253 
13254 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13255 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13256 
13257 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13258 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13259 
13260 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13261 		opt[i].dofo_option = i;
13262 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13263 		opt[i].dofo_value = state->dts_options[i];
13264 	}
13265 
13266 	return (dof);
13267 }
13268 
13269 static dof_hdr_t *
13270 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13271 {
13272 	dof_hdr_t hdr, *dof;
13273 
13274 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13275 
13276 	/*
13277 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13278 	 */
13279 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13280 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13281 		*errp = EFAULT;
13282 		return (NULL);
13283 	}
13284 
13285 	/*
13286 	 * Now we'll allocate the entire DOF and copy it in -- provided
13287 	 * that the length isn't outrageous.
13288 	 */
13289 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13290 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13291 		*errp = E2BIG;
13292 		return (NULL);
13293 	}
13294 
13295 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13296 		dtrace_dof_error(&hdr, "invalid load size");
13297 		*errp = EINVAL;
13298 		return (NULL);
13299 	}
13300 
13301 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13302 
13303 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13304 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13305 		kmem_free(dof, hdr.dofh_loadsz);
13306 		*errp = EFAULT;
13307 		return (NULL);
13308 	}
13309 
13310 	return (dof);
13311 }
13312 
13313 #ifdef __FreeBSD__
13314 static dof_hdr_t *
13315 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13316 {
13317 	dof_hdr_t hdr, *dof;
13318 	struct thread *td;
13319 	size_t loadsz;
13320 
13321 	ASSERT(!MUTEX_HELD(&dtrace_lock));
13322 
13323 	td = curthread;
13324 
13325 	/*
13326 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13327 	 */
13328 	if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13329 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13330 		*errp = EFAULT;
13331 		return (NULL);
13332 	}
13333 
13334 	/*
13335 	 * Now we'll allocate the entire DOF and copy it in -- provided
13336 	 * that the length isn't outrageous.
13337 	 */
13338 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13339 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13340 		*errp = E2BIG;
13341 		return (NULL);
13342 	}
13343 	loadsz = (size_t)hdr.dofh_loadsz;
13344 
13345 	if (loadsz < sizeof (hdr)) {
13346 		dtrace_dof_error(&hdr, "invalid load size");
13347 		*errp = EINVAL;
13348 		return (NULL);
13349 	}
13350 
13351 	dof = kmem_alloc(loadsz, KM_SLEEP);
13352 
13353 	if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13354 	    dof->dofh_loadsz != loadsz) {
13355 		kmem_free(dof, hdr.dofh_loadsz);
13356 		*errp = EFAULT;
13357 		return (NULL);
13358 	}
13359 
13360 	return (dof);
13361 }
13362 
13363 static __inline uchar_t
13364 dtrace_dof_char(char c)
13365 {
13366 
13367 	switch (c) {
13368 	case '0':
13369 	case '1':
13370 	case '2':
13371 	case '3':
13372 	case '4':
13373 	case '5':
13374 	case '6':
13375 	case '7':
13376 	case '8':
13377 	case '9':
13378 		return (c - '0');
13379 	case 'A':
13380 	case 'B':
13381 	case 'C':
13382 	case 'D':
13383 	case 'E':
13384 	case 'F':
13385 		return (c - 'A' + 10);
13386 	case 'a':
13387 	case 'b':
13388 	case 'c':
13389 	case 'd':
13390 	case 'e':
13391 	case 'f':
13392 		return (c - 'a' + 10);
13393 	}
13394 	/* Should not reach here. */
13395 	return (UCHAR_MAX);
13396 }
13397 #endif /* __FreeBSD__ */
13398 
13399 static dof_hdr_t *
13400 dtrace_dof_property(const char *name)
13401 {
13402 #ifdef __FreeBSD__
13403 	uint8_t *dofbuf;
13404 	u_char *data, *eol;
13405 	caddr_t doffile;
13406 	size_t bytes, len, i;
13407 	dof_hdr_t *dof;
13408 	u_char c1, c2;
13409 
13410 	dof = NULL;
13411 
13412 	doffile = preload_search_by_type("dtrace_dof");
13413 	if (doffile == NULL)
13414 		return (NULL);
13415 
13416 	data = preload_fetch_addr(doffile);
13417 	len = preload_fetch_size(doffile);
13418 	for (;;) {
13419 		/* Look for the end of the line. All lines end in a newline. */
13420 		eol = memchr(data, '\n', len);
13421 		if (eol == NULL)
13422 			return (NULL);
13423 
13424 		if (strncmp(name, data, strlen(name)) == 0)
13425 			break;
13426 
13427 		eol++; /* skip past the newline */
13428 		len -= eol - data;
13429 		data = eol;
13430 	}
13431 
13432 	/* We've found the data corresponding to the specified key. */
13433 
13434 	data += strlen(name) + 1; /* skip past the '=' */
13435 	len = eol - data;
13436 	if (len % 2 != 0) {
13437 		dtrace_dof_error(NULL, "invalid DOF encoding length");
13438 		goto doferr;
13439 	}
13440 	bytes = len / 2;
13441 	if (bytes < sizeof(dof_hdr_t)) {
13442 		dtrace_dof_error(NULL, "truncated header");
13443 		goto doferr;
13444 	}
13445 
13446 	/*
13447 	 * Each byte is represented by the two ASCII characters in its hex
13448 	 * representation.
13449 	 */
13450 	dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13451 	for (i = 0; i < bytes; i++) {
13452 		c1 = dtrace_dof_char(data[i * 2]);
13453 		c2 = dtrace_dof_char(data[i * 2 + 1]);
13454 		if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13455 			dtrace_dof_error(NULL, "invalid hex char in DOF");
13456 			goto doferr;
13457 		}
13458 		dofbuf[i] = c1 * 16 + c2;
13459 	}
13460 
13461 	dof = (dof_hdr_t *)dofbuf;
13462 	if (bytes < dof->dofh_loadsz) {
13463 		dtrace_dof_error(NULL, "truncated DOF");
13464 		goto doferr;
13465 	}
13466 
13467 	if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13468 		dtrace_dof_error(NULL, "oversized DOF");
13469 		goto doferr;
13470 	}
13471 
13472 	return (dof);
13473 
13474 doferr:
13475 	free(dof, M_SOLARIS);
13476 	return (NULL);
13477 #else /* __FreeBSD__ */
13478 	uchar_t *buf;
13479 	uint64_t loadsz;
13480 	unsigned int len, i;
13481 	dof_hdr_t *dof;
13482 
13483 	/*
13484 	 * Unfortunately, array of values in .conf files are always (and
13485 	 * only) interpreted to be integer arrays.  We must read our DOF
13486 	 * as an integer array, and then squeeze it into a byte array.
13487 	 */
13488 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13489 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13490 		return (NULL);
13491 
13492 	for (i = 0; i < len; i++)
13493 		buf[i] = (uchar_t)(((int *)buf)[i]);
13494 
13495 	if (len < sizeof (dof_hdr_t)) {
13496 		ddi_prop_free(buf);
13497 		dtrace_dof_error(NULL, "truncated header");
13498 		return (NULL);
13499 	}
13500 
13501 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13502 		ddi_prop_free(buf);
13503 		dtrace_dof_error(NULL, "truncated DOF");
13504 		return (NULL);
13505 	}
13506 
13507 	if (loadsz >= dtrace_dof_maxsize) {
13508 		ddi_prop_free(buf);
13509 		dtrace_dof_error(NULL, "oversized DOF");
13510 		return (NULL);
13511 	}
13512 
13513 	dof = kmem_alloc(loadsz, KM_SLEEP);
13514 	bcopy(buf, dof, loadsz);
13515 	ddi_prop_free(buf);
13516 
13517 	return (dof);
13518 #endif /* !__FreeBSD__ */
13519 }
13520 
13521 static void
13522 dtrace_dof_destroy(dof_hdr_t *dof)
13523 {
13524 	kmem_free(dof, dof->dofh_loadsz);
13525 }
13526 
13527 /*
13528  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13529  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13530  * a type other than DOF_SECT_NONE is specified, the header is checked against
13531  * this type and NULL is returned if the types do not match.
13532  */
13533 static dof_sec_t *
13534 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13535 {
13536 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13537 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13538 
13539 	if (i >= dof->dofh_secnum) {
13540 		dtrace_dof_error(dof, "referenced section index is invalid");
13541 		return (NULL);
13542 	}
13543 
13544 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13545 		dtrace_dof_error(dof, "referenced section is not loadable");
13546 		return (NULL);
13547 	}
13548 
13549 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13550 		dtrace_dof_error(dof, "referenced section is the wrong type");
13551 		return (NULL);
13552 	}
13553 
13554 	return (sec);
13555 }
13556 
13557 static dtrace_probedesc_t *
13558 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13559 {
13560 	dof_probedesc_t *probe;
13561 	dof_sec_t *strtab;
13562 	uintptr_t daddr = (uintptr_t)dof;
13563 	uintptr_t str;
13564 	size_t size;
13565 
13566 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13567 		dtrace_dof_error(dof, "invalid probe section");
13568 		return (NULL);
13569 	}
13570 
13571 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13572 		dtrace_dof_error(dof, "bad alignment in probe description");
13573 		return (NULL);
13574 	}
13575 
13576 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13577 		dtrace_dof_error(dof, "truncated probe description");
13578 		return (NULL);
13579 	}
13580 
13581 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13582 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13583 
13584 	if (strtab == NULL)
13585 		return (NULL);
13586 
13587 	str = daddr + strtab->dofs_offset;
13588 	size = strtab->dofs_size;
13589 
13590 	if (probe->dofp_provider >= strtab->dofs_size) {
13591 		dtrace_dof_error(dof, "corrupt probe provider");
13592 		return (NULL);
13593 	}
13594 
13595 	(void) strncpy(desc->dtpd_provider,
13596 	    (char *)(str + probe->dofp_provider),
13597 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13598 
13599 	if (probe->dofp_mod >= strtab->dofs_size) {
13600 		dtrace_dof_error(dof, "corrupt probe module");
13601 		return (NULL);
13602 	}
13603 
13604 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13605 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13606 
13607 	if (probe->dofp_func >= strtab->dofs_size) {
13608 		dtrace_dof_error(dof, "corrupt probe function");
13609 		return (NULL);
13610 	}
13611 
13612 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13613 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13614 
13615 	if (probe->dofp_name >= strtab->dofs_size) {
13616 		dtrace_dof_error(dof, "corrupt probe name");
13617 		return (NULL);
13618 	}
13619 
13620 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13621 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13622 
13623 	return (desc);
13624 }
13625 
13626 static dtrace_difo_t *
13627 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13628     cred_t *cr)
13629 {
13630 	dtrace_difo_t *dp;
13631 	size_t ttl = 0;
13632 	dof_difohdr_t *dofd;
13633 	uintptr_t daddr = (uintptr_t)dof;
13634 	size_t max = dtrace_difo_maxsize;
13635 	int i, l, n;
13636 
13637 	static const struct {
13638 		int section;
13639 		int bufoffs;
13640 		int lenoffs;
13641 		int entsize;
13642 		int align;
13643 		const char *msg;
13644 	} difo[] = {
13645 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13646 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13647 		sizeof (dif_instr_t), "multiple DIF sections" },
13648 
13649 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13650 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13651 		sizeof (uint64_t), "multiple integer tables" },
13652 
13653 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13654 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13655 		sizeof (char), "multiple string tables" },
13656 
13657 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13658 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13659 		sizeof (uint_t), "multiple variable tables" },
13660 
13661 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13662 	};
13663 
13664 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13665 		dtrace_dof_error(dof, "invalid DIFO header section");
13666 		return (NULL);
13667 	}
13668 
13669 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13670 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13671 		return (NULL);
13672 	}
13673 
13674 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13675 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13676 		dtrace_dof_error(dof, "bad size in DIFO header");
13677 		return (NULL);
13678 	}
13679 
13680 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13681 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13682 
13683 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13684 	dp->dtdo_rtype = dofd->dofd_rtype;
13685 
13686 	for (l = 0; l < n; l++) {
13687 		dof_sec_t *subsec;
13688 		void **bufp;
13689 		uint32_t *lenp;
13690 
13691 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13692 		    dofd->dofd_links[l])) == NULL)
13693 			goto err; /* invalid section link */
13694 
13695 		if (ttl + subsec->dofs_size > max) {
13696 			dtrace_dof_error(dof, "exceeds maximum size");
13697 			goto err;
13698 		}
13699 
13700 		ttl += subsec->dofs_size;
13701 
13702 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13703 			if (subsec->dofs_type != difo[i].section)
13704 				continue;
13705 
13706 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13707 				dtrace_dof_error(dof, "section not loaded");
13708 				goto err;
13709 			}
13710 
13711 			if (subsec->dofs_align != difo[i].align) {
13712 				dtrace_dof_error(dof, "bad alignment");
13713 				goto err;
13714 			}
13715 
13716 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13717 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13718 
13719 			if (*bufp != NULL) {
13720 				dtrace_dof_error(dof, difo[i].msg);
13721 				goto err;
13722 			}
13723 
13724 			if (difo[i].entsize != subsec->dofs_entsize) {
13725 				dtrace_dof_error(dof, "entry size mismatch");
13726 				goto err;
13727 			}
13728 
13729 			if (subsec->dofs_entsize != 0 &&
13730 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13731 				dtrace_dof_error(dof, "corrupt entry size");
13732 				goto err;
13733 			}
13734 
13735 			*lenp = subsec->dofs_size;
13736 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13737 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13738 			    *bufp, subsec->dofs_size);
13739 
13740 			if (subsec->dofs_entsize != 0)
13741 				*lenp /= subsec->dofs_entsize;
13742 
13743 			break;
13744 		}
13745 
13746 		/*
13747 		 * If we encounter a loadable DIFO sub-section that is not
13748 		 * known to us, assume this is a broken program and fail.
13749 		 */
13750 		if (difo[i].section == DOF_SECT_NONE &&
13751 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13752 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13753 			goto err;
13754 		}
13755 	}
13756 
13757 	if (dp->dtdo_buf == NULL) {
13758 		/*
13759 		 * We can't have a DIF object without DIF text.
13760 		 */
13761 		dtrace_dof_error(dof, "missing DIF text");
13762 		goto err;
13763 	}
13764 
13765 	/*
13766 	 * Before we validate the DIF object, run through the variable table
13767 	 * looking for the strings -- if any of their size are under, we'll set
13768 	 * their size to be the system-wide default string size.  Note that
13769 	 * this should _not_ happen if the "strsize" option has been set --
13770 	 * in this case, the compiler should have set the size to reflect the
13771 	 * setting of the option.
13772 	 */
13773 	for (i = 0; i < dp->dtdo_varlen; i++) {
13774 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13775 		dtrace_diftype_t *t = &v->dtdv_type;
13776 
13777 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13778 			continue;
13779 
13780 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13781 			t->dtdt_size = dtrace_strsize_default;
13782 	}
13783 
13784 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13785 		goto err;
13786 
13787 	dtrace_difo_init(dp, vstate);
13788 	return (dp);
13789 
13790 err:
13791 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13792 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13793 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13794 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13795 
13796 	kmem_free(dp, sizeof (dtrace_difo_t));
13797 	return (NULL);
13798 }
13799 
13800 static dtrace_predicate_t *
13801 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13802     cred_t *cr)
13803 {
13804 	dtrace_difo_t *dp;
13805 
13806 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13807 		return (NULL);
13808 
13809 	return (dtrace_predicate_create(dp));
13810 }
13811 
13812 static dtrace_actdesc_t *
13813 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13814     cred_t *cr)
13815 {
13816 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13817 	dof_actdesc_t *desc;
13818 	dof_sec_t *difosec;
13819 	size_t offs;
13820 	uintptr_t daddr = (uintptr_t)dof;
13821 	uint64_t arg;
13822 	dtrace_actkind_t kind;
13823 
13824 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13825 		dtrace_dof_error(dof, "invalid action section");
13826 		return (NULL);
13827 	}
13828 
13829 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13830 		dtrace_dof_error(dof, "truncated action description");
13831 		return (NULL);
13832 	}
13833 
13834 	if (sec->dofs_align != sizeof (uint64_t)) {
13835 		dtrace_dof_error(dof, "bad alignment in action description");
13836 		return (NULL);
13837 	}
13838 
13839 	if (sec->dofs_size < sec->dofs_entsize) {
13840 		dtrace_dof_error(dof, "section entry size exceeds total size");
13841 		return (NULL);
13842 	}
13843 
13844 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13845 		dtrace_dof_error(dof, "bad entry size in action description");
13846 		return (NULL);
13847 	}
13848 
13849 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13850 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13851 		return (NULL);
13852 	}
13853 
13854 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13855 		desc = (dof_actdesc_t *)(daddr +
13856 		    (uintptr_t)sec->dofs_offset + offs);
13857 		kind = (dtrace_actkind_t)desc->dofa_kind;
13858 
13859 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13860 		    (kind != DTRACEACT_PRINTA ||
13861 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13862 		    (kind == DTRACEACT_DIFEXPR &&
13863 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13864 			dof_sec_t *strtab;
13865 			char *str, *fmt;
13866 			uint64_t i;
13867 
13868 			/*
13869 			 * The argument to these actions is an index into the
13870 			 * DOF string table.  For printf()-like actions, this
13871 			 * is the format string.  For print(), this is the
13872 			 * CTF type of the expression result.
13873 			 */
13874 			if ((strtab = dtrace_dof_sect(dof,
13875 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13876 				goto err;
13877 
13878 			str = (char *)((uintptr_t)dof +
13879 			    (uintptr_t)strtab->dofs_offset);
13880 
13881 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13882 				if (str[i] == '\0')
13883 					break;
13884 			}
13885 
13886 			if (i >= strtab->dofs_size) {
13887 				dtrace_dof_error(dof, "bogus format string");
13888 				goto err;
13889 			}
13890 
13891 			if (i == desc->dofa_arg) {
13892 				dtrace_dof_error(dof, "empty format string");
13893 				goto err;
13894 			}
13895 
13896 			i -= desc->dofa_arg;
13897 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13898 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13899 			arg = (uint64_t)(uintptr_t)fmt;
13900 		} else {
13901 			if (kind == DTRACEACT_PRINTA) {
13902 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13903 				arg = 0;
13904 			} else {
13905 				arg = desc->dofa_arg;
13906 			}
13907 		}
13908 
13909 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13910 		    desc->dofa_uarg, arg);
13911 
13912 		if (last != NULL) {
13913 			last->dtad_next = act;
13914 		} else {
13915 			first = act;
13916 		}
13917 
13918 		last = act;
13919 
13920 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13921 			continue;
13922 
13923 		if ((difosec = dtrace_dof_sect(dof,
13924 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13925 			goto err;
13926 
13927 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13928 
13929 		if (act->dtad_difo == NULL)
13930 			goto err;
13931 	}
13932 
13933 	ASSERT(first != NULL);
13934 	return (first);
13935 
13936 err:
13937 	for (act = first; act != NULL; act = next) {
13938 		next = act->dtad_next;
13939 		dtrace_actdesc_release(act, vstate);
13940 	}
13941 
13942 	return (NULL);
13943 }
13944 
13945 static dtrace_ecbdesc_t *
13946 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13947     cred_t *cr)
13948 {
13949 	dtrace_ecbdesc_t *ep;
13950 	dof_ecbdesc_t *ecb;
13951 	dtrace_probedesc_t *desc;
13952 	dtrace_predicate_t *pred = NULL;
13953 
13954 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13955 		dtrace_dof_error(dof, "truncated ECB description");
13956 		return (NULL);
13957 	}
13958 
13959 	if (sec->dofs_align != sizeof (uint64_t)) {
13960 		dtrace_dof_error(dof, "bad alignment in ECB description");
13961 		return (NULL);
13962 	}
13963 
13964 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13965 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13966 
13967 	if (sec == NULL)
13968 		return (NULL);
13969 
13970 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13971 	ep->dted_uarg = ecb->dofe_uarg;
13972 	desc = &ep->dted_probe;
13973 
13974 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13975 		goto err;
13976 
13977 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13978 		if ((sec = dtrace_dof_sect(dof,
13979 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13980 			goto err;
13981 
13982 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13983 			goto err;
13984 
13985 		ep->dted_pred.dtpdd_predicate = pred;
13986 	}
13987 
13988 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13989 		if ((sec = dtrace_dof_sect(dof,
13990 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13991 			goto err;
13992 
13993 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13994 
13995 		if (ep->dted_action == NULL)
13996 			goto err;
13997 	}
13998 
13999 	return (ep);
14000 
14001 err:
14002 	if (pred != NULL)
14003 		dtrace_predicate_release(pred, vstate);
14004 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
14005 	return (NULL);
14006 }
14007 
14008 /*
14009  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
14010  * specified DOF.  SETX relocations are computed using 'ubase', the base load
14011  * address of the object containing the DOF, and DOFREL relocations are relative
14012  * to the relocation offset within the DOF.
14013  */
14014 static int
14015 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14016     uint64_t udaddr)
14017 {
14018 	uintptr_t daddr = (uintptr_t)dof;
14019 	uintptr_t ts_end;
14020 	dof_relohdr_t *dofr =
14021 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14022 	dof_sec_t *ss, *rs, *ts;
14023 	dof_relodesc_t *r;
14024 	uint_t i, n;
14025 
14026 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14027 	    sec->dofs_align != sizeof (dof_secidx_t)) {
14028 		dtrace_dof_error(dof, "invalid relocation header");
14029 		return (-1);
14030 	}
14031 
14032 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14033 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14034 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14035 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14036 
14037 	if (ss == NULL || rs == NULL || ts == NULL)
14038 		return (-1); /* dtrace_dof_error() has been called already */
14039 
14040 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14041 	    rs->dofs_align != sizeof (uint64_t)) {
14042 		dtrace_dof_error(dof, "invalid relocation section");
14043 		return (-1);
14044 	}
14045 
14046 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14047 	n = rs->dofs_size / rs->dofs_entsize;
14048 
14049 	for (i = 0; i < n; i++) {
14050 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14051 
14052 		switch (r->dofr_type) {
14053 		case DOF_RELO_NONE:
14054 			break;
14055 		case DOF_RELO_SETX:
14056 		case DOF_RELO_DOFREL:
14057 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14058 			    sizeof (uint64_t) > ts->dofs_size) {
14059 				dtrace_dof_error(dof, "bad relocation offset");
14060 				return (-1);
14061 			}
14062 
14063 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14064 				dtrace_dof_error(dof, "bad relocation offset");
14065 				return (-1);
14066 			}
14067 
14068 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14069 				dtrace_dof_error(dof, "misaligned setx relo");
14070 				return (-1);
14071 			}
14072 
14073 			if (r->dofr_type == DOF_RELO_SETX)
14074 				*(uint64_t *)taddr += ubase;
14075 			else
14076 				*(uint64_t *)taddr +=
14077 				    udaddr + ts->dofs_offset + r->dofr_offset;
14078 			break;
14079 		default:
14080 			dtrace_dof_error(dof, "invalid relocation type");
14081 			return (-1);
14082 		}
14083 
14084 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14085 	}
14086 
14087 	return (0);
14088 }
14089 
14090 /*
14091  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14092  * header:  it should be at the front of a memory region that is at least
14093  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14094  * size.  It need not be validated in any other way.
14095  */
14096 static int
14097 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14098     dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14099 {
14100 	uint64_t len = dof->dofh_loadsz, seclen;
14101 	uintptr_t daddr = (uintptr_t)dof;
14102 	dtrace_ecbdesc_t *ep;
14103 	dtrace_enabling_t *enab;
14104 	uint_t i;
14105 
14106 	ASSERT(MUTEX_HELD(&dtrace_lock));
14107 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14108 
14109 	/*
14110 	 * Check the DOF header identification bytes.  In addition to checking
14111 	 * valid settings, we also verify that unused bits/bytes are zeroed so
14112 	 * we can use them later without fear of regressing existing binaries.
14113 	 */
14114 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14115 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14116 		dtrace_dof_error(dof, "DOF magic string mismatch");
14117 		return (-1);
14118 	}
14119 
14120 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14121 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14122 		dtrace_dof_error(dof, "DOF has invalid data model");
14123 		return (-1);
14124 	}
14125 
14126 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14127 		dtrace_dof_error(dof, "DOF encoding mismatch");
14128 		return (-1);
14129 	}
14130 
14131 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14132 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14133 		dtrace_dof_error(dof, "DOF version mismatch");
14134 		return (-1);
14135 	}
14136 
14137 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14138 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14139 		return (-1);
14140 	}
14141 
14142 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14143 		dtrace_dof_error(dof, "DOF uses too many integer registers");
14144 		return (-1);
14145 	}
14146 
14147 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14148 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
14149 		return (-1);
14150 	}
14151 
14152 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14153 		if (dof->dofh_ident[i] != 0) {
14154 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
14155 			return (-1);
14156 		}
14157 	}
14158 
14159 	if (dof->dofh_flags & ~DOF_FL_VALID) {
14160 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
14161 		return (-1);
14162 	}
14163 
14164 	if (dof->dofh_secsize == 0) {
14165 		dtrace_dof_error(dof, "zero section header size");
14166 		return (-1);
14167 	}
14168 
14169 	/*
14170 	 * Check that the section headers don't exceed the amount of DOF
14171 	 * data.  Note that we cast the section size and number of sections
14172 	 * to uint64_t's to prevent possible overflow in the multiplication.
14173 	 */
14174 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14175 
14176 	if (dof->dofh_secoff > len || seclen > len ||
14177 	    dof->dofh_secoff + seclen > len) {
14178 		dtrace_dof_error(dof, "truncated section headers");
14179 		return (-1);
14180 	}
14181 
14182 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14183 		dtrace_dof_error(dof, "misaligned section headers");
14184 		return (-1);
14185 	}
14186 
14187 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14188 		dtrace_dof_error(dof, "misaligned section size");
14189 		return (-1);
14190 	}
14191 
14192 	/*
14193 	 * Take an initial pass through the section headers to be sure that
14194 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
14195 	 * set, do not permit sections relating to providers, probes, or args.
14196 	 */
14197 	for (i = 0; i < dof->dofh_secnum; i++) {
14198 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14199 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14200 
14201 		if (noprobes) {
14202 			switch (sec->dofs_type) {
14203 			case DOF_SECT_PROVIDER:
14204 			case DOF_SECT_PROBES:
14205 			case DOF_SECT_PRARGS:
14206 			case DOF_SECT_PROFFS:
14207 				dtrace_dof_error(dof, "illegal sections "
14208 				    "for enabling");
14209 				return (-1);
14210 			}
14211 		}
14212 
14213 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14214 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
14215 			dtrace_dof_error(dof, "loadable section with load "
14216 			    "flag unset");
14217 			return (-1);
14218 		}
14219 
14220 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14221 			continue; /* just ignore non-loadable sections */
14222 
14223 		if (!ISP2(sec->dofs_align)) {
14224 			dtrace_dof_error(dof, "bad section alignment");
14225 			return (-1);
14226 		}
14227 
14228 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
14229 			dtrace_dof_error(dof, "misaligned section");
14230 			return (-1);
14231 		}
14232 
14233 		if (sec->dofs_offset > len || sec->dofs_size > len ||
14234 		    sec->dofs_offset + sec->dofs_size > len) {
14235 			dtrace_dof_error(dof, "corrupt section header");
14236 			return (-1);
14237 		}
14238 
14239 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14240 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14241 			dtrace_dof_error(dof, "non-terminating string table");
14242 			return (-1);
14243 		}
14244 	}
14245 
14246 	/*
14247 	 * Take a second pass through the sections and locate and perform any
14248 	 * relocations that are present.  We do this after the first pass to
14249 	 * be sure that all sections have had their headers validated.
14250 	 */
14251 	for (i = 0; i < dof->dofh_secnum; i++) {
14252 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14253 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14254 
14255 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
14256 			continue; /* skip sections that are not loadable */
14257 
14258 		switch (sec->dofs_type) {
14259 		case DOF_SECT_URELHDR:
14260 			if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14261 				return (-1);
14262 			break;
14263 		}
14264 	}
14265 
14266 	if ((enab = *enabp) == NULL)
14267 		enab = *enabp = dtrace_enabling_create(vstate);
14268 
14269 	for (i = 0; i < dof->dofh_secnum; i++) {
14270 		dof_sec_t *sec = (dof_sec_t *)(daddr +
14271 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14272 
14273 		if (sec->dofs_type != DOF_SECT_ECBDESC)
14274 			continue;
14275 
14276 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14277 			dtrace_enabling_destroy(enab);
14278 			*enabp = NULL;
14279 			return (-1);
14280 		}
14281 
14282 		dtrace_enabling_add(enab, ep);
14283 	}
14284 
14285 	return (0);
14286 }
14287 
14288 /*
14289  * Process DOF for any options.  This routine assumes that the DOF has been
14290  * at least processed by dtrace_dof_slurp().
14291  */
14292 static int
14293 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14294 {
14295 	int i, rval;
14296 	uint32_t entsize;
14297 	size_t offs;
14298 	dof_optdesc_t *desc;
14299 
14300 	for (i = 0; i < dof->dofh_secnum; i++) {
14301 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14302 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14303 
14304 		if (sec->dofs_type != DOF_SECT_OPTDESC)
14305 			continue;
14306 
14307 		if (sec->dofs_align != sizeof (uint64_t)) {
14308 			dtrace_dof_error(dof, "bad alignment in "
14309 			    "option description");
14310 			return (EINVAL);
14311 		}
14312 
14313 		if ((entsize = sec->dofs_entsize) == 0) {
14314 			dtrace_dof_error(dof, "zeroed option entry size");
14315 			return (EINVAL);
14316 		}
14317 
14318 		if (entsize < sizeof (dof_optdesc_t)) {
14319 			dtrace_dof_error(dof, "bad option entry size");
14320 			return (EINVAL);
14321 		}
14322 
14323 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14324 			desc = (dof_optdesc_t *)((uintptr_t)dof +
14325 			    (uintptr_t)sec->dofs_offset + offs);
14326 
14327 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14328 				dtrace_dof_error(dof, "non-zero option string");
14329 				return (EINVAL);
14330 			}
14331 
14332 			if (desc->dofo_value == DTRACEOPT_UNSET) {
14333 				dtrace_dof_error(dof, "unset option");
14334 				return (EINVAL);
14335 			}
14336 
14337 			if ((rval = dtrace_state_option(state,
14338 			    desc->dofo_option, desc->dofo_value)) != 0) {
14339 				dtrace_dof_error(dof, "rejected option");
14340 				return (rval);
14341 			}
14342 		}
14343 	}
14344 
14345 	return (0);
14346 }
14347 
14348 /*
14349  * DTrace Consumer State Functions
14350  */
14351 static int
14352 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14353 {
14354 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14355 	void *base;
14356 	uintptr_t limit;
14357 	dtrace_dynvar_t *dvar, *next, *start;
14358 	int i;
14359 
14360 	ASSERT(MUTEX_HELD(&dtrace_lock));
14361 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14362 
14363 	bzero(dstate, sizeof (dtrace_dstate_t));
14364 
14365 	if ((dstate->dtds_chunksize = chunksize) == 0)
14366 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14367 
14368 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
14369 
14370 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14371 		size = min;
14372 
14373 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14374 		return (ENOMEM);
14375 
14376 	dstate->dtds_size = size;
14377 	dstate->dtds_base = base;
14378 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14379 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14380 
14381 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14382 
14383 	if (hashsize != 1 && (hashsize & 1))
14384 		hashsize--;
14385 
14386 	dstate->dtds_hashsize = hashsize;
14387 	dstate->dtds_hash = dstate->dtds_base;
14388 
14389 	/*
14390 	 * Set all of our hash buckets to point to the single sink, and (if
14391 	 * it hasn't already been set), set the sink's hash value to be the
14392 	 * sink sentinel value.  The sink is needed for dynamic variable
14393 	 * lookups to know that they have iterated over an entire, valid hash
14394 	 * chain.
14395 	 */
14396 	for (i = 0; i < hashsize; i++)
14397 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14398 
14399 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14400 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14401 
14402 	/*
14403 	 * Determine number of active CPUs.  Divide free list evenly among
14404 	 * active CPUs.
14405 	 */
14406 	start = (dtrace_dynvar_t *)
14407 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14408 	limit = (uintptr_t)base + size;
14409 
14410 	VERIFY((uintptr_t)start < limit);
14411 	VERIFY((uintptr_t)start >= (uintptr_t)base);
14412 
14413 	maxper = (limit - (uintptr_t)start) / NCPU;
14414 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14415 
14416 #ifndef illumos
14417 	CPU_FOREACH(i) {
14418 #else
14419 	for (i = 0; i < NCPU; i++) {
14420 #endif
14421 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14422 
14423 		/*
14424 		 * If we don't even have enough chunks to make it once through
14425 		 * NCPUs, we're just going to allocate everything to the first
14426 		 * CPU.  And if we're on the last CPU, we're going to allocate
14427 		 * whatever is left over.  In either case, we set the limit to
14428 		 * be the limit of the dynamic variable space.
14429 		 */
14430 		if (maxper == 0 || i == NCPU - 1) {
14431 			limit = (uintptr_t)base + size;
14432 			start = NULL;
14433 		} else {
14434 			limit = (uintptr_t)start + maxper;
14435 			start = (dtrace_dynvar_t *)limit;
14436 		}
14437 
14438 		VERIFY(limit <= (uintptr_t)base + size);
14439 
14440 		for (;;) {
14441 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14442 			    dstate->dtds_chunksize);
14443 
14444 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14445 				break;
14446 
14447 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14448 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14449 			dvar->dtdv_next = next;
14450 			dvar = next;
14451 		}
14452 
14453 		if (maxper == 0)
14454 			break;
14455 	}
14456 
14457 	return (0);
14458 }
14459 
14460 static void
14461 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14462 {
14463 	ASSERT(MUTEX_HELD(&cpu_lock));
14464 
14465 	if (dstate->dtds_base == NULL)
14466 		return;
14467 
14468 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14469 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14470 }
14471 
14472 static void
14473 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14474 {
14475 	/*
14476 	 * Logical XOR, where are you?
14477 	 */
14478 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14479 
14480 	if (vstate->dtvs_nglobals > 0) {
14481 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14482 		    sizeof (dtrace_statvar_t *));
14483 	}
14484 
14485 	if (vstate->dtvs_ntlocals > 0) {
14486 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14487 		    sizeof (dtrace_difv_t));
14488 	}
14489 
14490 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14491 
14492 	if (vstate->dtvs_nlocals > 0) {
14493 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14494 		    sizeof (dtrace_statvar_t *));
14495 	}
14496 }
14497 
14498 #ifdef illumos
14499 static void
14500 dtrace_state_clean(dtrace_state_t *state)
14501 {
14502 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14503 		return;
14504 
14505 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14506 	dtrace_speculation_clean(state);
14507 }
14508 
14509 static void
14510 dtrace_state_deadman(dtrace_state_t *state)
14511 {
14512 	hrtime_t now;
14513 
14514 	dtrace_sync();
14515 
14516 	now = dtrace_gethrtime();
14517 
14518 	if (state != dtrace_anon.dta_state &&
14519 	    now - state->dts_laststatus >= dtrace_deadman_user)
14520 		return;
14521 
14522 	/*
14523 	 * We must be sure that dts_alive never appears to be less than the
14524 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14525 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14526 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14527 	 * the new value.  This assures that dts_alive never appears to be
14528 	 * less than its true value, regardless of the order in which the
14529 	 * stores to the underlying storage are issued.
14530 	 */
14531 	state->dts_alive = INT64_MAX;
14532 	dtrace_membar_producer();
14533 	state->dts_alive = now;
14534 }
14535 #else	/* !illumos */
14536 static void
14537 dtrace_state_clean(void *arg)
14538 {
14539 	dtrace_state_t *state = arg;
14540 	dtrace_optval_t *opt = state->dts_options;
14541 
14542 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14543 		return;
14544 
14545 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14546 	dtrace_speculation_clean(state);
14547 
14548 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14549 	    dtrace_state_clean, state);
14550 }
14551 
14552 static void
14553 dtrace_state_deadman(void *arg)
14554 {
14555 	dtrace_state_t *state = arg;
14556 	hrtime_t now;
14557 
14558 	dtrace_sync();
14559 
14560 	dtrace_debug_output();
14561 
14562 	now = dtrace_gethrtime();
14563 
14564 	if (state != dtrace_anon.dta_state &&
14565 	    now - state->dts_laststatus >= dtrace_deadman_user)
14566 		return;
14567 
14568 	/*
14569 	 * We must be sure that dts_alive never appears to be less than the
14570 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14571 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14572 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14573 	 * the new value.  This assures that dts_alive never appears to be
14574 	 * less than its true value, regardless of the order in which the
14575 	 * stores to the underlying storage are issued.
14576 	 */
14577 	state->dts_alive = INT64_MAX;
14578 	dtrace_membar_producer();
14579 	state->dts_alive = now;
14580 
14581 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14582 	    dtrace_state_deadman, state);
14583 }
14584 #endif	/* illumos */
14585 
14586 static dtrace_state_t *
14587 #ifdef illumos
14588 dtrace_state_create(dev_t *devp, cred_t *cr)
14589 #else
14590 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14591 #endif
14592 {
14593 #ifdef illumos
14594 	minor_t minor;
14595 	major_t major;
14596 #else
14597 	cred_t *cr = NULL;
14598 	int m = 0;
14599 #endif
14600 	char c[30];
14601 	dtrace_state_t *state;
14602 	dtrace_optval_t *opt;
14603 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14604 	int cpu_it;
14605 
14606 	ASSERT(MUTEX_HELD(&dtrace_lock));
14607 	ASSERT(MUTEX_HELD(&cpu_lock));
14608 
14609 #ifdef illumos
14610 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14611 	    VM_BESTFIT | VM_SLEEP);
14612 
14613 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14614 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14615 		return (NULL);
14616 	}
14617 
14618 	state = ddi_get_soft_state(dtrace_softstate, minor);
14619 #else
14620 	if (dev != NULL) {
14621 		cr = dev->si_cred;
14622 		m = dev2unit(dev);
14623 	}
14624 
14625 	/* Allocate memory for the state. */
14626 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14627 #endif
14628 
14629 	state->dts_epid = DTRACE_EPIDNONE + 1;
14630 
14631 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14632 #ifdef illumos
14633 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14634 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14635 
14636 	if (devp != NULL) {
14637 		major = getemajor(*devp);
14638 	} else {
14639 		major = ddi_driver_major(dtrace_devi);
14640 	}
14641 
14642 	state->dts_dev = makedevice(major, minor);
14643 
14644 	if (devp != NULL)
14645 		*devp = state->dts_dev;
14646 #else
14647 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14648 	state->dts_dev = dev;
14649 #endif
14650 
14651 	/*
14652 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14653 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14654 	 * other hand, it saves an additional memory reference in the probe
14655 	 * path.
14656 	 */
14657 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14658 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14659 
14660 	/*
14661          * Allocate and initialise the per-process per-CPU random state.
14662 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14663          * assumed to be seeded at this point (if from Fortuna seed file).
14664 	 */
14665 	arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14666 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14667 		/*
14668 		 * Each CPU is assigned a 2^64 period, non-overlapping
14669 		 * subsequence.
14670 		 */
14671 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14672 		    state->dts_rstate[cpu_it]);
14673 	}
14674 
14675 #ifdef illumos
14676 	state->dts_cleaner = CYCLIC_NONE;
14677 	state->dts_deadman = CYCLIC_NONE;
14678 #else
14679 	callout_init(&state->dts_cleaner, 1);
14680 	callout_init(&state->dts_deadman, 1);
14681 #endif
14682 	state->dts_vstate.dtvs_state = state;
14683 
14684 	for (i = 0; i < DTRACEOPT_MAX; i++)
14685 		state->dts_options[i] = DTRACEOPT_UNSET;
14686 
14687 	/*
14688 	 * Set the default options.
14689 	 */
14690 	opt = state->dts_options;
14691 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14692 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14693 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14694 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14695 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14696 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14697 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14698 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14699 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14700 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14701 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14702 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14703 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14704 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14705 
14706 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14707 
14708 	/*
14709 	 * Depending on the user credentials, we set flag bits which alter probe
14710 	 * visibility or the amount of destructiveness allowed.  In the case of
14711 	 * actual anonymous tracing, or the possession of all privileges, all of
14712 	 * the normal checks are bypassed.
14713 	 */
14714 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14715 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14716 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14717 	} else {
14718 		/*
14719 		 * Set up the credentials for this instantiation.  We take a
14720 		 * hold on the credential to prevent it from disappearing on
14721 		 * us; this in turn prevents the zone_t referenced by this
14722 		 * credential from disappearing.  This means that we can
14723 		 * examine the credential and the zone from probe context.
14724 		 */
14725 		crhold(cr);
14726 		state->dts_cred.dcr_cred = cr;
14727 
14728 		/*
14729 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14730 		 * unlocks the use of variables like pid, zonename, etc.
14731 		 */
14732 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14733 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14734 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14735 		}
14736 
14737 		/*
14738 		 * dtrace_user allows use of syscall and profile providers.
14739 		 * If the user also has proc_owner and/or proc_zone, we
14740 		 * extend the scope to include additional visibility and
14741 		 * destructive power.
14742 		 */
14743 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14744 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14745 				state->dts_cred.dcr_visible |=
14746 				    DTRACE_CRV_ALLPROC;
14747 
14748 				state->dts_cred.dcr_action |=
14749 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14750 			}
14751 
14752 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14753 				state->dts_cred.dcr_visible |=
14754 				    DTRACE_CRV_ALLZONE;
14755 
14756 				state->dts_cred.dcr_action |=
14757 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14758 			}
14759 
14760 			/*
14761 			 * If we have all privs in whatever zone this is,
14762 			 * we can do destructive things to processes which
14763 			 * have altered credentials.
14764 			 */
14765 #ifdef illumos
14766 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14767 			    cr->cr_zone->zone_privset)) {
14768 				state->dts_cred.dcr_action |=
14769 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14770 			}
14771 #endif
14772 		}
14773 
14774 		/*
14775 		 * Holding the dtrace_kernel privilege also implies that
14776 		 * the user has the dtrace_user privilege from a visibility
14777 		 * perspective.  But without further privileges, some
14778 		 * destructive actions are not available.
14779 		 */
14780 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14781 			/*
14782 			 * Make all probes in all zones visible.  However,
14783 			 * this doesn't mean that all actions become available
14784 			 * to all zones.
14785 			 */
14786 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14787 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14788 
14789 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14790 			    DTRACE_CRA_PROC;
14791 			/*
14792 			 * Holding proc_owner means that destructive actions
14793 			 * for *this* zone are allowed.
14794 			 */
14795 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14796 				state->dts_cred.dcr_action |=
14797 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14798 
14799 			/*
14800 			 * Holding proc_zone means that destructive actions
14801 			 * for this user/group ID in all zones is allowed.
14802 			 */
14803 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14804 				state->dts_cred.dcr_action |=
14805 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14806 
14807 #ifdef illumos
14808 			/*
14809 			 * If we have all privs in whatever zone this is,
14810 			 * we can do destructive things to processes which
14811 			 * have altered credentials.
14812 			 */
14813 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14814 			    cr->cr_zone->zone_privset)) {
14815 				state->dts_cred.dcr_action |=
14816 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14817 			}
14818 #endif
14819 		}
14820 
14821 		/*
14822 		 * Holding the dtrace_proc privilege gives control over fasttrap
14823 		 * and pid providers.  We need to grant wider destructive
14824 		 * privileges in the event that the user has proc_owner and/or
14825 		 * proc_zone.
14826 		 */
14827 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14828 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14829 				state->dts_cred.dcr_action |=
14830 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14831 
14832 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14833 				state->dts_cred.dcr_action |=
14834 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14835 		}
14836 	}
14837 
14838 	return (state);
14839 }
14840 
14841 static int
14842 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14843 {
14844 	dtrace_optval_t *opt = state->dts_options, size;
14845 	processorid_t cpu = 0;
14846 	int flags = 0, rval, factor, divisor = 1;
14847 
14848 	ASSERT(MUTEX_HELD(&dtrace_lock));
14849 	ASSERT(MUTEX_HELD(&cpu_lock));
14850 	ASSERT(which < DTRACEOPT_MAX);
14851 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14852 	    (state == dtrace_anon.dta_state &&
14853 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14854 
14855 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14856 		return (0);
14857 
14858 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14859 		cpu = opt[DTRACEOPT_CPU];
14860 
14861 	if (which == DTRACEOPT_SPECSIZE)
14862 		flags |= DTRACEBUF_NOSWITCH;
14863 
14864 	if (which == DTRACEOPT_BUFSIZE) {
14865 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14866 			flags |= DTRACEBUF_RING;
14867 
14868 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14869 			flags |= DTRACEBUF_FILL;
14870 
14871 		if (state != dtrace_anon.dta_state ||
14872 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14873 			flags |= DTRACEBUF_INACTIVE;
14874 	}
14875 
14876 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14877 		/*
14878 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14879 		 * aligned, drop it down by the difference.
14880 		 */
14881 		if (size & (sizeof (uint64_t) - 1))
14882 			size -= size & (sizeof (uint64_t) - 1);
14883 
14884 		if (size < state->dts_reserve) {
14885 			/*
14886 			 * Buffers always must be large enough to accommodate
14887 			 * their prereserved space.  We return E2BIG instead
14888 			 * of ENOMEM in this case to allow for user-level
14889 			 * software to differentiate the cases.
14890 			 */
14891 			return (E2BIG);
14892 		}
14893 
14894 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14895 
14896 		if (rval != ENOMEM) {
14897 			opt[which] = size;
14898 			return (rval);
14899 		}
14900 
14901 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14902 			return (rval);
14903 
14904 		for (divisor = 2; divisor < factor; divisor <<= 1)
14905 			continue;
14906 	}
14907 
14908 	return (ENOMEM);
14909 }
14910 
14911 static int
14912 dtrace_state_buffers(dtrace_state_t *state)
14913 {
14914 	dtrace_speculation_t *spec = state->dts_speculations;
14915 	int rval, i;
14916 
14917 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14918 	    DTRACEOPT_BUFSIZE)) != 0)
14919 		return (rval);
14920 
14921 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14922 	    DTRACEOPT_AGGSIZE)) != 0)
14923 		return (rval);
14924 
14925 	for (i = 0; i < state->dts_nspeculations; i++) {
14926 		if ((rval = dtrace_state_buffer(state,
14927 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14928 			return (rval);
14929 	}
14930 
14931 	return (0);
14932 }
14933 
14934 static void
14935 dtrace_state_prereserve(dtrace_state_t *state)
14936 {
14937 	dtrace_ecb_t *ecb;
14938 	dtrace_probe_t *probe;
14939 
14940 	state->dts_reserve = 0;
14941 
14942 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14943 		return;
14944 
14945 	/*
14946 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14947 	 * prereserved space to be the space required by the END probes.
14948 	 */
14949 	probe = dtrace_probes[dtrace_probeid_end - 1];
14950 	ASSERT(probe != NULL);
14951 
14952 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14953 		if (ecb->dte_state != state)
14954 			continue;
14955 
14956 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14957 	}
14958 }
14959 
14960 static int
14961 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14962 {
14963 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14964 	dtrace_speculation_t *spec;
14965 	dtrace_buffer_t *buf;
14966 #ifdef illumos
14967 	cyc_handler_t hdlr;
14968 	cyc_time_t when;
14969 #endif
14970 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14971 	dtrace_icookie_t cookie;
14972 
14973 	mutex_enter(&cpu_lock);
14974 	mutex_enter(&dtrace_lock);
14975 
14976 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14977 		rval = EBUSY;
14978 		goto out;
14979 	}
14980 
14981 	/*
14982 	 * Before we can perform any checks, we must prime all of the
14983 	 * retained enablings that correspond to this state.
14984 	 */
14985 	dtrace_enabling_prime(state);
14986 
14987 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14988 		rval = EACCES;
14989 		goto out;
14990 	}
14991 
14992 	dtrace_state_prereserve(state);
14993 
14994 	/*
14995 	 * Now we want to do is try to allocate our speculations.
14996 	 * We do not automatically resize the number of speculations; if
14997 	 * this fails, we will fail the operation.
14998 	 */
14999 	nspec = opt[DTRACEOPT_NSPEC];
15000 	ASSERT(nspec != DTRACEOPT_UNSET);
15001 
15002 	if (nspec > INT_MAX) {
15003 		rval = ENOMEM;
15004 		goto out;
15005 	}
15006 
15007 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
15008 	    KM_NOSLEEP | KM_NORMALPRI);
15009 
15010 	if (spec == NULL) {
15011 		rval = ENOMEM;
15012 		goto out;
15013 	}
15014 
15015 	state->dts_speculations = spec;
15016 	state->dts_nspeculations = (int)nspec;
15017 
15018 	for (i = 0; i < nspec; i++) {
15019 		if ((buf = kmem_zalloc(bufsize,
15020 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15021 			rval = ENOMEM;
15022 			goto err;
15023 		}
15024 
15025 		spec[i].dtsp_buffer = buf;
15026 	}
15027 
15028 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15029 		if (dtrace_anon.dta_state == NULL) {
15030 			rval = ENOENT;
15031 			goto out;
15032 		}
15033 
15034 		if (state->dts_necbs != 0) {
15035 			rval = EALREADY;
15036 			goto out;
15037 		}
15038 
15039 		state->dts_anon = dtrace_anon_grab();
15040 		ASSERT(state->dts_anon != NULL);
15041 		state = state->dts_anon;
15042 
15043 		/*
15044 		 * We want "grabanon" to be set in the grabbed state, so we'll
15045 		 * copy that option value from the grabbing state into the
15046 		 * grabbed state.
15047 		 */
15048 		state->dts_options[DTRACEOPT_GRABANON] =
15049 		    opt[DTRACEOPT_GRABANON];
15050 
15051 		*cpu = dtrace_anon.dta_beganon;
15052 
15053 		/*
15054 		 * If the anonymous state is active (as it almost certainly
15055 		 * is if the anonymous enabling ultimately matched anything),
15056 		 * we don't allow any further option processing -- but we
15057 		 * don't return failure.
15058 		 */
15059 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15060 			goto out;
15061 	}
15062 
15063 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15064 	    opt[DTRACEOPT_AGGSIZE] != 0) {
15065 		if (state->dts_aggregations == NULL) {
15066 			/*
15067 			 * We're not going to create an aggregation buffer
15068 			 * because we don't have any ECBs that contain
15069 			 * aggregations -- set this option to 0.
15070 			 */
15071 			opt[DTRACEOPT_AGGSIZE] = 0;
15072 		} else {
15073 			/*
15074 			 * If we have an aggregation buffer, we must also have
15075 			 * a buffer to use as scratch.
15076 			 */
15077 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15078 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15079 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15080 			}
15081 		}
15082 	}
15083 
15084 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15085 	    opt[DTRACEOPT_SPECSIZE] != 0) {
15086 		if (!state->dts_speculates) {
15087 			/*
15088 			 * We're not going to create speculation buffers
15089 			 * because we don't have any ECBs that actually
15090 			 * speculate -- set the speculation size to 0.
15091 			 */
15092 			opt[DTRACEOPT_SPECSIZE] = 0;
15093 		}
15094 	}
15095 
15096 	/*
15097 	 * The bare minimum size for any buffer that we're actually going to
15098 	 * do anything to is sizeof (uint64_t).
15099 	 */
15100 	sz = sizeof (uint64_t);
15101 
15102 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15103 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15104 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15105 		/*
15106 		 * A buffer size has been explicitly set to 0 (or to a size
15107 		 * that will be adjusted to 0) and we need the space -- we
15108 		 * need to return failure.  We return ENOSPC to differentiate
15109 		 * it from failing to allocate a buffer due to failure to meet
15110 		 * the reserve (for which we return E2BIG).
15111 		 */
15112 		rval = ENOSPC;
15113 		goto out;
15114 	}
15115 
15116 	if ((rval = dtrace_state_buffers(state)) != 0)
15117 		goto err;
15118 
15119 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15120 		sz = dtrace_dstate_defsize;
15121 
15122 	do {
15123 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15124 
15125 		if (rval == 0)
15126 			break;
15127 
15128 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15129 			goto err;
15130 	} while (sz >>= 1);
15131 
15132 	opt[DTRACEOPT_DYNVARSIZE] = sz;
15133 
15134 	if (rval != 0)
15135 		goto err;
15136 
15137 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15138 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15139 
15140 	if (opt[DTRACEOPT_CLEANRATE] == 0)
15141 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15142 
15143 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15144 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15145 
15146 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15147 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15148 
15149 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15150 #ifdef illumos
15151 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15152 	hdlr.cyh_arg = state;
15153 	hdlr.cyh_level = CY_LOW_LEVEL;
15154 
15155 	when.cyt_when = 0;
15156 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15157 
15158 	state->dts_cleaner = cyclic_add(&hdlr, &when);
15159 
15160 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15161 	hdlr.cyh_arg = state;
15162 	hdlr.cyh_level = CY_LOW_LEVEL;
15163 
15164 	when.cyt_when = 0;
15165 	when.cyt_interval = dtrace_deadman_interval;
15166 
15167 	state->dts_deadman = cyclic_add(&hdlr, &when);
15168 #else
15169 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15170 	    dtrace_state_clean, state);
15171 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15172 	    dtrace_state_deadman, state);
15173 #endif
15174 
15175 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15176 
15177 #ifdef illumos
15178 	if (state->dts_getf != 0 &&
15179 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15180 		/*
15181 		 * We don't have kernel privs but we have at least one call
15182 		 * to getf(); we need to bump our zone's count, and (if
15183 		 * this is the first enabling to have an unprivileged call
15184 		 * to getf()) we need to hook into closef().
15185 		 */
15186 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15187 
15188 		if (dtrace_getf++ == 0) {
15189 			ASSERT(dtrace_closef == NULL);
15190 			dtrace_closef = dtrace_getf_barrier;
15191 		}
15192 	}
15193 #endif
15194 
15195 	/*
15196 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
15197 	 * interrupts here both to record the CPU on which we fired the BEGIN
15198 	 * probe (the data from this CPU will be processed first at user
15199 	 * level) and to manually activate the buffer for this CPU.
15200 	 */
15201 	cookie = dtrace_interrupt_disable();
15202 	*cpu = curcpu;
15203 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15204 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15205 
15206 	dtrace_probe(dtrace_probeid_begin,
15207 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15208 	dtrace_interrupt_enable(cookie);
15209 	/*
15210 	 * We may have had an exit action from a BEGIN probe; only change our
15211 	 * state to ACTIVE if we're still in WARMUP.
15212 	 */
15213 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15214 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15215 
15216 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15217 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15218 
15219 #ifdef __FreeBSD__
15220 	/*
15221 	 * We enable anonymous tracing before APs are started, so we must
15222 	 * activate buffers using the current CPU.
15223 	 */
15224 	if (state == dtrace_anon.dta_state)
15225 		for (int i = 0; i < NCPU; i++)
15226 			dtrace_buffer_activate_cpu(state, i);
15227 	else
15228 		dtrace_xcall(DTRACE_CPUALL,
15229 		    (dtrace_xcall_t)dtrace_buffer_activate, state);
15230 #else
15231 	/*
15232 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15233 	 * want each CPU to transition its principal buffer out of the
15234 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
15235 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15236 	 * atomically transition from processing none of a state's ECBs to
15237 	 * processing all of them.
15238 	 */
15239 	dtrace_xcall(DTRACE_CPUALL,
15240 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
15241 #endif
15242 	goto out;
15243 
15244 err:
15245 	dtrace_buffer_free(state->dts_buffer);
15246 	dtrace_buffer_free(state->dts_aggbuffer);
15247 
15248 	if ((nspec = state->dts_nspeculations) == 0) {
15249 		ASSERT(state->dts_speculations == NULL);
15250 		goto out;
15251 	}
15252 
15253 	spec = state->dts_speculations;
15254 	ASSERT(spec != NULL);
15255 
15256 	for (i = 0; i < state->dts_nspeculations; i++) {
15257 		if ((buf = spec[i].dtsp_buffer) == NULL)
15258 			break;
15259 
15260 		dtrace_buffer_free(buf);
15261 		kmem_free(buf, bufsize);
15262 	}
15263 
15264 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15265 	state->dts_nspeculations = 0;
15266 	state->dts_speculations = NULL;
15267 
15268 out:
15269 	mutex_exit(&dtrace_lock);
15270 	mutex_exit(&cpu_lock);
15271 
15272 	return (rval);
15273 }
15274 
15275 static int
15276 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15277 {
15278 	dtrace_icookie_t cookie;
15279 
15280 	ASSERT(MUTEX_HELD(&dtrace_lock));
15281 
15282 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15283 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15284 		return (EINVAL);
15285 
15286 	/*
15287 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15288 	 * to be sure that every CPU has seen it.  See below for the details
15289 	 * on why this is done.
15290 	 */
15291 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15292 	dtrace_sync();
15293 
15294 	/*
15295 	 * By this point, it is impossible for any CPU to be still processing
15296 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
15297 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15298 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
15299 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15300 	 * iff we're in the END probe.
15301 	 */
15302 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15303 	dtrace_sync();
15304 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15305 
15306 	/*
15307 	 * Finally, we can release the reserve and call the END probe.  We
15308 	 * disable interrupts across calling the END probe to allow us to
15309 	 * return the CPU on which we actually called the END probe.  This
15310 	 * allows user-land to be sure that this CPU's principal buffer is
15311 	 * processed last.
15312 	 */
15313 	state->dts_reserve = 0;
15314 
15315 	cookie = dtrace_interrupt_disable();
15316 	*cpu = curcpu;
15317 	dtrace_probe(dtrace_probeid_end,
15318 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15319 	dtrace_interrupt_enable(cookie);
15320 
15321 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15322 	dtrace_sync();
15323 
15324 #ifdef illumos
15325 	if (state->dts_getf != 0 &&
15326 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15327 		/*
15328 		 * We don't have kernel privs but we have at least one call
15329 		 * to getf(); we need to lower our zone's count, and (if
15330 		 * this is the last enabling to have an unprivileged call
15331 		 * to getf()) we need to clear the closef() hook.
15332 		 */
15333 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15334 		ASSERT(dtrace_closef == dtrace_getf_barrier);
15335 		ASSERT(dtrace_getf > 0);
15336 
15337 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15338 
15339 		if (--dtrace_getf == 0)
15340 			dtrace_closef = NULL;
15341 	}
15342 #endif
15343 
15344 	return (0);
15345 }
15346 
15347 static int
15348 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15349     dtrace_optval_t val)
15350 {
15351 	ASSERT(MUTEX_HELD(&dtrace_lock));
15352 
15353 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15354 		return (EBUSY);
15355 
15356 	if (option >= DTRACEOPT_MAX)
15357 		return (EINVAL);
15358 
15359 	if (option != DTRACEOPT_CPU && val < 0)
15360 		return (EINVAL);
15361 
15362 	switch (option) {
15363 	case DTRACEOPT_DESTRUCTIVE:
15364 		if (dtrace_destructive_disallow)
15365 			return (EACCES);
15366 
15367 		state->dts_cred.dcr_destructive = 1;
15368 		break;
15369 
15370 	case DTRACEOPT_BUFSIZE:
15371 	case DTRACEOPT_DYNVARSIZE:
15372 	case DTRACEOPT_AGGSIZE:
15373 	case DTRACEOPT_SPECSIZE:
15374 	case DTRACEOPT_STRSIZE:
15375 		if (val < 0)
15376 			return (EINVAL);
15377 
15378 		if (val >= LONG_MAX) {
15379 			/*
15380 			 * If this is an otherwise negative value, set it to
15381 			 * the highest multiple of 128m less than LONG_MAX.
15382 			 * Technically, we're adjusting the size without
15383 			 * regard to the buffer resizing policy, but in fact,
15384 			 * this has no effect -- if we set the buffer size to
15385 			 * ~LONG_MAX and the buffer policy is ultimately set to
15386 			 * be "manual", the buffer allocation is guaranteed to
15387 			 * fail, if only because the allocation requires two
15388 			 * buffers.  (We set the the size to the highest
15389 			 * multiple of 128m because it ensures that the size
15390 			 * will remain a multiple of a megabyte when
15391 			 * repeatedly halved -- all the way down to 15m.)
15392 			 */
15393 			val = LONG_MAX - (1 << 27) + 1;
15394 		}
15395 	}
15396 
15397 	state->dts_options[option] = val;
15398 
15399 	return (0);
15400 }
15401 
15402 static void
15403 dtrace_state_destroy(dtrace_state_t *state)
15404 {
15405 	dtrace_ecb_t *ecb;
15406 	dtrace_vstate_t *vstate = &state->dts_vstate;
15407 #ifdef illumos
15408 	minor_t minor = getminor(state->dts_dev);
15409 #endif
15410 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15411 	dtrace_speculation_t *spec = state->dts_speculations;
15412 	int nspec = state->dts_nspeculations;
15413 	uint32_t match;
15414 
15415 	ASSERT(MUTEX_HELD(&dtrace_lock));
15416 	ASSERT(MUTEX_HELD(&cpu_lock));
15417 
15418 	/*
15419 	 * First, retract any retained enablings for this state.
15420 	 */
15421 	dtrace_enabling_retract(state);
15422 	ASSERT(state->dts_nretained == 0);
15423 
15424 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15425 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15426 		/*
15427 		 * We have managed to come into dtrace_state_destroy() on a
15428 		 * hot enabling -- almost certainly because of a disorderly
15429 		 * shutdown of a consumer.  (That is, a consumer that is
15430 		 * exiting without having called dtrace_stop().) In this case,
15431 		 * we're going to set our activity to be KILLED, and then
15432 		 * issue a sync to be sure that everyone is out of probe
15433 		 * context before we start blowing away ECBs.
15434 		 */
15435 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
15436 		dtrace_sync();
15437 	}
15438 
15439 	/*
15440 	 * Release the credential hold we took in dtrace_state_create().
15441 	 */
15442 	if (state->dts_cred.dcr_cred != NULL)
15443 		crfree(state->dts_cred.dcr_cred);
15444 
15445 	/*
15446 	 * Now we can safely disable and destroy any enabled probes.  Because
15447 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15448 	 * (especially if they're all enabled), we take two passes through the
15449 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15450 	 * in the second we disable whatever is left over.
15451 	 */
15452 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15453 		for (i = 0; i < state->dts_necbs; i++) {
15454 			if ((ecb = state->dts_ecbs[i]) == NULL)
15455 				continue;
15456 
15457 			if (match && ecb->dte_probe != NULL) {
15458 				dtrace_probe_t *probe = ecb->dte_probe;
15459 				dtrace_provider_t *prov = probe->dtpr_provider;
15460 
15461 				if (!(prov->dtpv_priv.dtpp_flags & match))
15462 					continue;
15463 			}
15464 
15465 			dtrace_ecb_disable(ecb);
15466 			dtrace_ecb_destroy(ecb);
15467 		}
15468 
15469 		if (!match)
15470 			break;
15471 	}
15472 
15473 	/*
15474 	 * Before we free the buffers, perform one more sync to assure that
15475 	 * every CPU is out of probe context.
15476 	 */
15477 	dtrace_sync();
15478 
15479 	dtrace_buffer_free(state->dts_buffer);
15480 	dtrace_buffer_free(state->dts_aggbuffer);
15481 
15482 	for (i = 0; i < nspec; i++)
15483 		dtrace_buffer_free(spec[i].dtsp_buffer);
15484 
15485 #ifdef illumos
15486 	if (state->dts_cleaner != CYCLIC_NONE)
15487 		cyclic_remove(state->dts_cleaner);
15488 
15489 	if (state->dts_deadman != CYCLIC_NONE)
15490 		cyclic_remove(state->dts_deadman);
15491 #else
15492 	callout_stop(&state->dts_cleaner);
15493 	callout_drain(&state->dts_cleaner);
15494 	callout_stop(&state->dts_deadman);
15495 	callout_drain(&state->dts_deadman);
15496 #endif
15497 
15498 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15499 	dtrace_vstate_fini(vstate);
15500 	if (state->dts_ecbs != NULL)
15501 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15502 
15503 	if (state->dts_aggregations != NULL) {
15504 #ifdef DEBUG
15505 		for (i = 0; i < state->dts_naggregations; i++)
15506 			ASSERT(state->dts_aggregations[i] == NULL);
15507 #endif
15508 		ASSERT(state->dts_naggregations > 0);
15509 		kmem_free(state->dts_aggregations,
15510 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15511 	}
15512 
15513 	kmem_free(state->dts_buffer, bufsize);
15514 	kmem_free(state->dts_aggbuffer, bufsize);
15515 
15516 	for (i = 0; i < nspec; i++)
15517 		kmem_free(spec[i].dtsp_buffer, bufsize);
15518 
15519 	if (spec != NULL)
15520 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15521 
15522 	dtrace_format_destroy(state);
15523 
15524 	if (state->dts_aggid_arena != NULL) {
15525 #ifdef illumos
15526 		vmem_destroy(state->dts_aggid_arena);
15527 #else
15528 		delete_unrhdr(state->dts_aggid_arena);
15529 #endif
15530 		state->dts_aggid_arena = NULL;
15531 	}
15532 #ifdef illumos
15533 	ddi_soft_state_free(dtrace_softstate, minor);
15534 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15535 #endif
15536 }
15537 
15538 /*
15539  * DTrace Anonymous Enabling Functions
15540  */
15541 static dtrace_state_t *
15542 dtrace_anon_grab(void)
15543 {
15544 	dtrace_state_t *state;
15545 
15546 	ASSERT(MUTEX_HELD(&dtrace_lock));
15547 
15548 	if ((state = dtrace_anon.dta_state) == NULL) {
15549 		ASSERT(dtrace_anon.dta_enabling == NULL);
15550 		return (NULL);
15551 	}
15552 
15553 	ASSERT(dtrace_anon.dta_enabling != NULL);
15554 	ASSERT(dtrace_retained != NULL);
15555 
15556 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15557 	dtrace_anon.dta_enabling = NULL;
15558 	dtrace_anon.dta_state = NULL;
15559 
15560 	return (state);
15561 }
15562 
15563 static void
15564 dtrace_anon_property(void)
15565 {
15566 	int i, rv;
15567 	dtrace_state_t *state;
15568 	dof_hdr_t *dof;
15569 	char c[32];		/* enough for "dof-data-" + digits */
15570 
15571 	ASSERT(MUTEX_HELD(&dtrace_lock));
15572 	ASSERT(MUTEX_HELD(&cpu_lock));
15573 
15574 	for (i = 0; ; i++) {
15575 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15576 
15577 		dtrace_err_verbose = 1;
15578 
15579 		if ((dof = dtrace_dof_property(c)) == NULL) {
15580 			dtrace_err_verbose = 0;
15581 			break;
15582 		}
15583 
15584 #ifdef illumos
15585 		/*
15586 		 * We want to create anonymous state, so we need to transition
15587 		 * the kernel debugger to indicate that DTrace is active.  If
15588 		 * this fails (e.g. because the debugger has modified text in
15589 		 * some way), we won't continue with the processing.
15590 		 */
15591 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15592 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15593 			    "enabling ignored.");
15594 			dtrace_dof_destroy(dof);
15595 			break;
15596 		}
15597 #endif
15598 
15599 		/*
15600 		 * If we haven't allocated an anonymous state, we'll do so now.
15601 		 */
15602 		if ((state = dtrace_anon.dta_state) == NULL) {
15603 			state = dtrace_state_create(NULL, NULL);
15604 			dtrace_anon.dta_state = state;
15605 
15606 			if (state == NULL) {
15607 				/*
15608 				 * This basically shouldn't happen:  the only
15609 				 * failure mode from dtrace_state_create() is a
15610 				 * failure of ddi_soft_state_zalloc() that
15611 				 * itself should never happen.  Still, the
15612 				 * interface allows for a failure mode, and
15613 				 * we want to fail as gracefully as possible:
15614 				 * we'll emit an error message and cease
15615 				 * processing anonymous state in this case.
15616 				 */
15617 				cmn_err(CE_WARN, "failed to create "
15618 				    "anonymous state");
15619 				dtrace_dof_destroy(dof);
15620 				break;
15621 			}
15622 		}
15623 
15624 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15625 		    &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15626 
15627 		if (rv == 0)
15628 			rv = dtrace_dof_options(dof, state);
15629 
15630 		dtrace_err_verbose = 0;
15631 		dtrace_dof_destroy(dof);
15632 
15633 		if (rv != 0) {
15634 			/*
15635 			 * This is malformed DOF; chuck any anonymous state
15636 			 * that we created.
15637 			 */
15638 			ASSERT(dtrace_anon.dta_enabling == NULL);
15639 			dtrace_state_destroy(state);
15640 			dtrace_anon.dta_state = NULL;
15641 			break;
15642 		}
15643 
15644 		ASSERT(dtrace_anon.dta_enabling != NULL);
15645 	}
15646 
15647 	if (dtrace_anon.dta_enabling != NULL) {
15648 		int rval;
15649 
15650 		/*
15651 		 * dtrace_enabling_retain() can only fail because we are
15652 		 * trying to retain more enablings than are allowed -- but
15653 		 * we only have one anonymous enabling, and we are guaranteed
15654 		 * to be allowed at least one retained enabling; we assert
15655 		 * that dtrace_enabling_retain() returns success.
15656 		 */
15657 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15658 		ASSERT(rval == 0);
15659 
15660 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15661 	}
15662 }
15663 
15664 /*
15665  * DTrace Helper Functions
15666  */
15667 static void
15668 dtrace_helper_trace(dtrace_helper_action_t *helper,
15669     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15670 {
15671 	uint32_t size, next, nnext, i;
15672 	dtrace_helptrace_t *ent, *buffer;
15673 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15674 
15675 	if ((buffer = dtrace_helptrace_buffer) == NULL)
15676 		return;
15677 
15678 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15679 
15680 	/*
15681 	 * What would a tracing framework be without its own tracing
15682 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15683 	 */
15684 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15685 	    sizeof (uint64_t) - sizeof (uint64_t);
15686 
15687 	/*
15688 	 * Iterate until we can allocate a slot in the trace buffer.
15689 	 */
15690 	do {
15691 		next = dtrace_helptrace_next;
15692 
15693 		if (next + size < dtrace_helptrace_bufsize) {
15694 			nnext = next + size;
15695 		} else {
15696 			nnext = size;
15697 		}
15698 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15699 
15700 	/*
15701 	 * We have our slot; fill it in.
15702 	 */
15703 	if (nnext == size) {
15704 		dtrace_helptrace_wrapped++;
15705 		next = 0;
15706 	}
15707 
15708 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15709 	ent->dtht_helper = helper;
15710 	ent->dtht_where = where;
15711 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15712 
15713 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15714 	    mstate->dtms_fltoffs : -1;
15715 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15716 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15717 
15718 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15719 		dtrace_statvar_t *svar;
15720 
15721 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15722 			continue;
15723 
15724 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15725 		ent->dtht_locals[i] =
15726 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15727 	}
15728 }
15729 
15730 static uint64_t
15731 dtrace_helper(int which, dtrace_mstate_t *mstate,
15732     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15733 {
15734 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15735 	uint64_t sarg0 = mstate->dtms_arg[0];
15736 	uint64_t sarg1 = mstate->dtms_arg[1];
15737 	uint64_t rval = 0;
15738 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15739 	dtrace_helper_action_t *helper;
15740 	dtrace_vstate_t *vstate;
15741 	dtrace_difo_t *pred;
15742 	int i, trace = dtrace_helptrace_buffer != NULL;
15743 
15744 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15745 
15746 	if (helpers == NULL)
15747 		return (0);
15748 
15749 	if ((helper = helpers->dthps_actions[which]) == NULL)
15750 		return (0);
15751 
15752 	vstate = &helpers->dthps_vstate;
15753 	mstate->dtms_arg[0] = arg0;
15754 	mstate->dtms_arg[1] = arg1;
15755 
15756 	/*
15757 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15758 	 * we'll call the corresponding actions.  Note that the below calls
15759 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15760 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15761 	 * the stored DIF offset with its own (which is the desired behavior).
15762 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15763 	 * from machine state; this is okay, too.
15764 	 */
15765 	for (; helper != NULL; helper = helper->dtha_next) {
15766 		if ((pred = helper->dtha_predicate) != NULL) {
15767 			if (trace)
15768 				dtrace_helper_trace(helper, mstate, vstate, 0);
15769 
15770 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15771 				goto next;
15772 
15773 			if (*flags & CPU_DTRACE_FAULT)
15774 				goto err;
15775 		}
15776 
15777 		for (i = 0; i < helper->dtha_nactions; i++) {
15778 			if (trace)
15779 				dtrace_helper_trace(helper,
15780 				    mstate, vstate, i + 1);
15781 
15782 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15783 			    mstate, vstate, state);
15784 
15785 			if (*flags & CPU_DTRACE_FAULT)
15786 				goto err;
15787 		}
15788 
15789 next:
15790 		if (trace)
15791 			dtrace_helper_trace(helper, mstate, vstate,
15792 			    DTRACE_HELPTRACE_NEXT);
15793 	}
15794 
15795 	if (trace)
15796 		dtrace_helper_trace(helper, mstate, vstate,
15797 		    DTRACE_HELPTRACE_DONE);
15798 
15799 	/*
15800 	 * Restore the arg0 that we saved upon entry.
15801 	 */
15802 	mstate->dtms_arg[0] = sarg0;
15803 	mstate->dtms_arg[1] = sarg1;
15804 
15805 	return (rval);
15806 
15807 err:
15808 	if (trace)
15809 		dtrace_helper_trace(helper, mstate, vstate,
15810 		    DTRACE_HELPTRACE_ERR);
15811 
15812 	/*
15813 	 * Restore the arg0 that we saved upon entry.
15814 	 */
15815 	mstate->dtms_arg[0] = sarg0;
15816 	mstate->dtms_arg[1] = sarg1;
15817 
15818 	return (0);
15819 }
15820 
15821 static void
15822 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15823     dtrace_vstate_t *vstate)
15824 {
15825 	int i;
15826 
15827 	if (helper->dtha_predicate != NULL)
15828 		dtrace_difo_release(helper->dtha_predicate, vstate);
15829 
15830 	for (i = 0; i < helper->dtha_nactions; i++) {
15831 		ASSERT(helper->dtha_actions[i] != NULL);
15832 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15833 	}
15834 
15835 	kmem_free(helper->dtha_actions,
15836 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15837 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15838 }
15839 
15840 static int
15841 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15842 {
15843 	proc_t *p = curproc;
15844 	dtrace_vstate_t *vstate;
15845 	int i;
15846 
15847 	if (help == NULL)
15848 		help = p->p_dtrace_helpers;
15849 
15850 	ASSERT(MUTEX_HELD(&dtrace_lock));
15851 
15852 	if (help == NULL || gen > help->dthps_generation)
15853 		return (EINVAL);
15854 
15855 	vstate = &help->dthps_vstate;
15856 
15857 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15858 		dtrace_helper_action_t *last = NULL, *h, *next;
15859 
15860 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15861 			next = h->dtha_next;
15862 
15863 			if (h->dtha_generation == gen) {
15864 				if (last != NULL) {
15865 					last->dtha_next = next;
15866 				} else {
15867 					help->dthps_actions[i] = next;
15868 				}
15869 
15870 				dtrace_helper_action_destroy(h, vstate);
15871 			} else {
15872 				last = h;
15873 			}
15874 		}
15875 	}
15876 
15877 	/*
15878 	 * Interate until we've cleared out all helper providers with the
15879 	 * given generation number.
15880 	 */
15881 	for (;;) {
15882 		dtrace_helper_provider_t *prov;
15883 
15884 		/*
15885 		 * Look for a helper provider with the right generation. We
15886 		 * have to start back at the beginning of the list each time
15887 		 * because we drop dtrace_lock. It's unlikely that we'll make
15888 		 * more than two passes.
15889 		 */
15890 		for (i = 0; i < help->dthps_nprovs; i++) {
15891 			prov = help->dthps_provs[i];
15892 
15893 			if (prov->dthp_generation == gen)
15894 				break;
15895 		}
15896 
15897 		/*
15898 		 * If there were no matches, we're done.
15899 		 */
15900 		if (i == help->dthps_nprovs)
15901 			break;
15902 
15903 		/*
15904 		 * Move the last helper provider into this slot.
15905 		 */
15906 		help->dthps_nprovs--;
15907 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15908 		help->dthps_provs[help->dthps_nprovs] = NULL;
15909 
15910 		mutex_exit(&dtrace_lock);
15911 
15912 		/*
15913 		 * If we have a meta provider, remove this helper provider.
15914 		 */
15915 		mutex_enter(&dtrace_meta_lock);
15916 		if (dtrace_meta_pid != NULL) {
15917 			ASSERT(dtrace_deferred_pid == NULL);
15918 			dtrace_helper_provider_remove(&prov->dthp_prov,
15919 			    p->p_pid);
15920 		}
15921 		mutex_exit(&dtrace_meta_lock);
15922 
15923 		dtrace_helper_provider_destroy(prov);
15924 
15925 		mutex_enter(&dtrace_lock);
15926 	}
15927 
15928 	return (0);
15929 }
15930 
15931 static int
15932 dtrace_helper_validate(dtrace_helper_action_t *helper)
15933 {
15934 	int err = 0, i;
15935 	dtrace_difo_t *dp;
15936 
15937 	if ((dp = helper->dtha_predicate) != NULL)
15938 		err += dtrace_difo_validate_helper(dp);
15939 
15940 	for (i = 0; i < helper->dtha_nactions; i++)
15941 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15942 
15943 	return (err == 0);
15944 }
15945 
15946 static int
15947 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15948     dtrace_helpers_t *help)
15949 {
15950 	dtrace_helper_action_t *helper, *last;
15951 	dtrace_actdesc_t *act;
15952 	dtrace_vstate_t *vstate;
15953 	dtrace_predicate_t *pred;
15954 	int count = 0, nactions = 0, i;
15955 
15956 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15957 		return (EINVAL);
15958 
15959 	last = help->dthps_actions[which];
15960 	vstate = &help->dthps_vstate;
15961 
15962 	for (count = 0; last != NULL; last = last->dtha_next) {
15963 		count++;
15964 		if (last->dtha_next == NULL)
15965 			break;
15966 	}
15967 
15968 	/*
15969 	 * If we already have dtrace_helper_actions_max helper actions for this
15970 	 * helper action type, we'll refuse to add a new one.
15971 	 */
15972 	if (count >= dtrace_helper_actions_max)
15973 		return (ENOSPC);
15974 
15975 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15976 	helper->dtha_generation = help->dthps_generation;
15977 
15978 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15979 		ASSERT(pred->dtp_difo != NULL);
15980 		dtrace_difo_hold(pred->dtp_difo);
15981 		helper->dtha_predicate = pred->dtp_difo;
15982 	}
15983 
15984 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15985 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15986 			goto err;
15987 
15988 		if (act->dtad_difo == NULL)
15989 			goto err;
15990 
15991 		nactions++;
15992 	}
15993 
15994 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15995 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15996 
15997 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15998 		dtrace_difo_hold(act->dtad_difo);
15999 		helper->dtha_actions[i++] = act->dtad_difo;
16000 	}
16001 
16002 	if (!dtrace_helper_validate(helper))
16003 		goto err;
16004 
16005 	if (last == NULL) {
16006 		help->dthps_actions[which] = helper;
16007 	} else {
16008 		last->dtha_next = helper;
16009 	}
16010 
16011 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16012 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16013 		dtrace_helptrace_next = 0;
16014 	}
16015 
16016 	return (0);
16017 err:
16018 	dtrace_helper_action_destroy(helper, vstate);
16019 	return (EINVAL);
16020 }
16021 
16022 static void
16023 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16024     dof_helper_t *dofhp)
16025 {
16026 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16027 
16028 	mutex_enter(&dtrace_meta_lock);
16029 	mutex_enter(&dtrace_lock);
16030 
16031 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16032 		/*
16033 		 * If the dtrace module is loaded but not attached, or if
16034 		 * there aren't isn't a meta provider registered to deal with
16035 		 * these provider descriptions, we need to postpone creating
16036 		 * the actual providers until later.
16037 		 */
16038 
16039 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16040 		    dtrace_deferred_pid != help) {
16041 			help->dthps_deferred = 1;
16042 			help->dthps_pid = p->p_pid;
16043 			help->dthps_next = dtrace_deferred_pid;
16044 			help->dthps_prev = NULL;
16045 			if (dtrace_deferred_pid != NULL)
16046 				dtrace_deferred_pid->dthps_prev = help;
16047 			dtrace_deferred_pid = help;
16048 		}
16049 
16050 		mutex_exit(&dtrace_lock);
16051 
16052 	} else if (dofhp != NULL) {
16053 		/*
16054 		 * If the dtrace module is loaded and we have a particular
16055 		 * helper provider description, pass that off to the
16056 		 * meta provider.
16057 		 */
16058 
16059 		mutex_exit(&dtrace_lock);
16060 
16061 		dtrace_helper_provide(dofhp, p->p_pid);
16062 
16063 	} else {
16064 		/*
16065 		 * Otherwise, just pass all the helper provider descriptions
16066 		 * off to the meta provider.
16067 		 */
16068 
16069 		int i;
16070 		mutex_exit(&dtrace_lock);
16071 
16072 		for (i = 0; i < help->dthps_nprovs; i++) {
16073 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16074 			    p->p_pid);
16075 		}
16076 	}
16077 
16078 	mutex_exit(&dtrace_meta_lock);
16079 }
16080 
16081 static int
16082 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16083 {
16084 	dtrace_helper_provider_t *hprov, **tmp_provs;
16085 	uint_t tmp_maxprovs, i;
16086 
16087 	ASSERT(MUTEX_HELD(&dtrace_lock));
16088 	ASSERT(help != NULL);
16089 
16090 	/*
16091 	 * If we already have dtrace_helper_providers_max helper providers,
16092 	 * we're refuse to add a new one.
16093 	 */
16094 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
16095 		return (ENOSPC);
16096 
16097 	/*
16098 	 * Check to make sure this isn't a duplicate.
16099 	 */
16100 	for (i = 0; i < help->dthps_nprovs; i++) {
16101 		if (dofhp->dofhp_addr ==
16102 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
16103 			return (EALREADY);
16104 	}
16105 
16106 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16107 	hprov->dthp_prov = *dofhp;
16108 	hprov->dthp_ref = 1;
16109 	hprov->dthp_generation = gen;
16110 
16111 	/*
16112 	 * Allocate a bigger table for helper providers if it's already full.
16113 	 */
16114 	if (help->dthps_maxprovs == help->dthps_nprovs) {
16115 		tmp_maxprovs = help->dthps_maxprovs;
16116 		tmp_provs = help->dthps_provs;
16117 
16118 		if (help->dthps_maxprovs == 0)
16119 			help->dthps_maxprovs = 2;
16120 		else
16121 			help->dthps_maxprovs *= 2;
16122 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
16123 			help->dthps_maxprovs = dtrace_helper_providers_max;
16124 
16125 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16126 
16127 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16128 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16129 
16130 		if (tmp_provs != NULL) {
16131 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16132 			    sizeof (dtrace_helper_provider_t *));
16133 			kmem_free(tmp_provs, tmp_maxprovs *
16134 			    sizeof (dtrace_helper_provider_t *));
16135 		}
16136 	}
16137 
16138 	help->dthps_provs[help->dthps_nprovs] = hprov;
16139 	help->dthps_nprovs++;
16140 
16141 	return (0);
16142 }
16143 
16144 static void
16145 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16146 {
16147 	mutex_enter(&dtrace_lock);
16148 
16149 	if (--hprov->dthp_ref == 0) {
16150 		dof_hdr_t *dof;
16151 		mutex_exit(&dtrace_lock);
16152 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16153 		dtrace_dof_destroy(dof);
16154 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16155 	} else {
16156 		mutex_exit(&dtrace_lock);
16157 	}
16158 }
16159 
16160 static int
16161 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16162 {
16163 	uintptr_t daddr = (uintptr_t)dof;
16164 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16165 	dof_provider_t *provider;
16166 	dof_probe_t *probe;
16167 	uint8_t *arg;
16168 	char *strtab, *typestr;
16169 	dof_stridx_t typeidx;
16170 	size_t typesz;
16171 	uint_t nprobes, j, k;
16172 
16173 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16174 
16175 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16176 		dtrace_dof_error(dof, "misaligned section offset");
16177 		return (-1);
16178 	}
16179 
16180 	/*
16181 	 * The section needs to be large enough to contain the DOF provider
16182 	 * structure appropriate for the given version.
16183 	 */
16184 	if (sec->dofs_size <
16185 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16186 	    offsetof(dof_provider_t, dofpv_prenoffs) :
16187 	    sizeof (dof_provider_t))) {
16188 		dtrace_dof_error(dof, "provider section too small");
16189 		return (-1);
16190 	}
16191 
16192 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16193 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16194 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16195 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16196 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16197 
16198 	if (str_sec == NULL || prb_sec == NULL ||
16199 	    arg_sec == NULL || off_sec == NULL)
16200 		return (-1);
16201 
16202 	enoff_sec = NULL;
16203 
16204 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16205 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
16206 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16207 	    provider->dofpv_prenoffs)) == NULL)
16208 		return (-1);
16209 
16210 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16211 
16212 	if (provider->dofpv_name >= str_sec->dofs_size ||
16213 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16214 		dtrace_dof_error(dof, "invalid provider name");
16215 		return (-1);
16216 	}
16217 
16218 	if (prb_sec->dofs_entsize == 0 ||
16219 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
16220 		dtrace_dof_error(dof, "invalid entry size");
16221 		return (-1);
16222 	}
16223 
16224 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16225 		dtrace_dof_error(dof, "misaligned entry size");
16226 		return (-1);
16227 	}
16228 
16229 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16230 		dtrace_dof_error(dof, "invalid entry size");
16231 		return (-1);
16232 	}
16233 
16234 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16235 		dtrace_dof_error(dof, "misaligned section offset");
16236 		return (-1);
16237 	}
16238 
16239 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16240 		dtrace_dof_error(dof, "invalid entry size");
16241 		return (-1);
16242 	}
16243 
16244 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16245 
16246 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16247 
16248 	/*
16249 	 * Take a pass through the probes to check for errors.
16250 	 */
16251 	for (j = 0; j < nprobes; j++) {
16252 		probe = (dof_probe_t *)(uintptr_t)(daddr +
16253 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16254 
16255 		if (probe->dofpr_func >= str_sec->dofs_size) {
16256 			dtrace_dof_error(dof, "invalid function name");
16257 			return (-1);
16258 		}
16259 
16260 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16261 			dtrace_dof_error(dof, "function name too long");
16262 			/*
16263 			 * Keep going if the function name is too long.
16264 			 * Unlike provider and probe names, we cannot reasonably
16265 			 * impose restrictions on function names, since they're
16266 			 * a property of the code being instrumented. We will
16267 			 * skip this probe in dtrace_helper_provide_one().
16268 			 */
16269 		}
16270 
16271 		if (probe->dofpr_name >= str_sec->dofs_size ||
16272 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16273 			dtrace_dof_error(dof, "invalid probe name");
16274 			return (-1);
16275 		}
16276 
16277 		/*
16278 		 * The offset count must not wrap the index, and the offsets
16279 		 * must also not overflow the section's data.
16280 		 */
16281 		if (probe->dofpr_offidx + probe->dofpr_noffs <
16282 		    probe->dofpr_offidx ||
16283 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
16284 		    off_sec->dofs_entsize > off_sec->dofs_size) {
16285 			dtrace_dof_error(dof, "invalid probe offset");
16286 			return (-1);
16287 		}
16288 
16289 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16290 			/*
16291 			 * If there's no is-enabled offset section, make sure
16292 			 * there aren't any is-enabled offsets. Otherwise
16293 			 * perform the same checks as for probe offsets
16294 			 * (immediately above).
16295 			 */
16296 			if (enoff_sec == NULL) {
16297 				if (probe->dofpr_enoffidx != 0 ||
16298 				    probe->dofpr_nenoffs != 0) {
16299 					dtrace_dof_error(dof, "is-enabled "
16300 					    "offsets with null section");
16301 					return (-1);
16302 				}
16303 			} else if (probe->dofpr_enoffidx +
16304 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16305 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16306 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16307 				dtrace_dof_error(dof, "invalid is-enabled "
16308 				    "offset");
16309 				return (-1);
16310 			}
16311 
16312 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16313 				dtrace_dof_error(dof, "zero probe and "
16314 				    "is-enabled offsets");
16315 				return (-1);
16316 			}
16317 		} else if (probe->dofpr_noffs == 0) {
16318 			dtrace_dof_error(dof, "zero probe offsets");
16319 			return (-1);
16320 		}
16321 
16322 		if (probe->dofpr_argidx + probe->dofpr_xargc <
16323 		    probe->dofpr_argidx ||
16324 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
16325 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
16326 			dtrace_dof_error(dof, "invalid args");
16327 			return (-1);
16328 		}
16329 
16330 		typeidx = probe->dofpr_nargv;
16331 		typestr = strtab + probe->dofpr_nargv;
16332 		for (k = 0; k < probe->dofpr_nargc; k++) {
16333 			if (typeidx >= str_sec->dofs_size) {
16334 				dtrace_dof_error(dof, "bad "
16335 				    "native argument type");
16336 				return (-1);
16337 			}
16338 
16339 			typesz = strlen(typestr) + 1;
16340 			if (typesz > DTRACE_ARGTYPELEN) {
16341 				dtrace_dof_error(dof, "native "
16342 				    "argument type too long");
16343 				return (-1);
16344 			}
16345 			typeidx += typesz;
16346 			typestr += typesz;
16347 		}
16348 
16349 		typeidx = probe->dofpr_xargv;
16350 		typestr = strtab + probe->dofpr_xargv;
16351 		for (k = 0; k < probe->dofpr_xargc; k++) {
16352 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16353 				dtrace_dof_error(dof, "bad "
16354 				    "native argument index");
16355 				return (-1);
16356 			}
16357 
16358 			if (typeidx >= str_sec->dofs_size) {
16359 				dtrace_dof_error(dof, "bad "
16360 				    "translated argument type");
16361 				return (-1);
16362 			}
16363 
16364 			typesz = strlen(typestr) + 1;
16365 			if (typesz > DTRACE_ARGTYPELEN) {
16366 				dtrace_dof_error(dof, "translated argument "
16367 				    "type too long");
16368 				return (-1);
16369 			}
16370 
16371 			typeidx += typesz;
16372 			typestr += typesz;
16373 		}
16374 	}
16375 
16376 	return (0);
16377 }
16378 
16379 static int
16380 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16381 {
16382 	dtrace_helpers_t *help;
16383 	dtrace_vstate_t *vstate;
16384 	dtrace_enabling_t *enab = NULL;
16385 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16386 	uintptr_t daddr = (uintptr_t)dof;
16387 
16388 	ASSERT(MUTEX_HELD(&dtrace_lock));
16389 
16390 	if ((help = p->p_dtrace_helpers) == NULL)
16391 		help = dtrace_helpers_create(p);
16392 
16393 	vstate = &help->dthps_vstate;
16394 
16395 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16396 	    dhp->dofhp_dof, B_FALSE)) != 0) {
16397 		dtrace_dof_destroy(dof);
16398 		return (rv);
16399 	}
16400 
16401 	/*
16402 	 * Look for helper providers and validate their descriptions.
16403 	 */
16404 	for (i = 0; i < dof->dofh_secnum; i++) {
16405 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16406 		    dof->dofh_secoff + i * dof->dofh_secsize);
16407 
16408 		if (sec->dofs_type != DOF_SECT_PROVIDER)
16409 			continue;
16410 
16411 		if (dtrace_helper_provider_validate(dof, sec) != 0) {
16412 			dtrace_enabling_destroy(enab);
16413 			dtrace_dof_destroy(dof);
16414 			return (-1);
16415 		}
16416 
16417 		nprovs++;
16418 	}
16419 
16420 	/*
16421 	 * Now we need to walk through the ECB descriptions in the enabling.
16422 	 */
16423 	for (i = 0; i < enab->dten_ndesc; i++) {
16424 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16425 		dtrace_probedesc_t *desc = &ep->dted_probe;
16426 
16427 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16428 			continue;
16429 
16430 		if (strcmp(desc->dtpd_mod, "helper") != 0)
16431 			continue;
16432 
16433 		if (strcmp(desc->dtpd_func, "ustack") != 0)
16434 			continue;
16435 
16436 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16437 		    ep, help)) != 0) {
16438 			/*
16439 			 * Adding this helper action failed -- we are now going
16440 			 * to rip out the entire generation and return failure.
16441 			 */
16442 			(void) dtrace_helper_destroygen(help,
16443 			    help->dthps_generation);
16444 			dtrace_enabling_destroy(enab);
16445 			dtrace_dof_destroy(dof);
16446 			return (-1);
16447 		}
16448 
16449 		nhelpers++;
16450 	}
16451 
16452 	if (nhelpers < enab->dten_ndesc)
16453 		dtrace_dof_error(dof, "unmatched helpers");
16454 
16455 	gen = help->dthps_generation++;
16456 	dtrace_enabling_destroy(enab);
16457 
16458 	if (nprovs > 0) {
16459 		/*
16460 		 * Now that this is in-kernel, we change the sense of the
16461 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
16462 		 * and dofhp_addr denotes the address at user-level.
16463 		 */
16464 		dhp->dofhp_addr = dhp->dofhp_dof;
16465 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16466 
16467 		if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16468 			mutex_exit(&dtrace_lock);
16469 			dtrace_helper_provider_register(p, help, dhp);
16470 			mutex_enter(&dtrace_lock);
16471 
16472 			destroy = 0;
16473 		}
16474 	}
16475 
16476 	if (destroy)
16477 		dtrace_dof_destroy(dof);
16478 
16479 	return (gen);
16480 }
16481 
16482 static dtrace_helpers_t *
16483 dtrace_helpers_create(proc_t *p)
16484 {
16485 	dtrace_helpers_t *help;
16486 
16487 	ASSERT(MUTEX_HELD(&dtrace_lock));
16488 	ASSERT(p->p_dtrace_helpers == NULL);
16489 
16490 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16491 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16492 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16493 
16494 	p->p_dtrace_helpers = help;
16495 	dtrace_helpers++;
16496 
16497 	return (help);
16498 }
16499 
16500 #ifdef illumos
16501 static
16502 #endif
16503 void
16504 dtrace_helpers_destroy(proc_t *p)
16505 {
16506 	dtrace_helpers_t *help;
16507 	dtrace_vstate_t *vstate;
16508 #ifdef illumos
16509 	proc_t *p = curproc;
16510 #endif
16511 	int i;
16512 
16513 	mutex_enter(&dtrace_lock);
16514 
16515 	ASSERT(p->p_dtrace_helpers != NULL);
16516 	ASSERT(dtrace_helpers > 0);
16517 
16518 	help = p->p_dtrace_helpers;
16519 	vstate = &help->dthps_vstate;
16520 
16521 	/*
16522 	 * We're now going to lose the help from this process.
16523 	 */
16524 	p->p_dtrace_helpers = NULL;
16525 	dtrace_sync();
16526 
16527 	/*
16528 	 * Destory the helper actions.
16529 	 */
16530 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16531 		dtrace_helper_action_t *h, *next;
16532 
16533 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16534 			next = h->dtha_next;
16535 			dtrace_helper_action_destroy(h, vstate);
16536 			h = next;
16537 		}
16538 	}
16539 
16540 	mutex_exit(&dtrace_lock);
16541 
16542 	/*
16543 	 * Destroy the helper providers.
16544 	 */
16545 	if (help->dthps_maxprovs > 0) {
16546 		mutex_enter(&dtrace_meta_lock);
16547 		if (dtrace_meta_pid != NULL) {
16548 			ASSERT(dtrace_deferred_pid == NULL);
16549 
16550 			for (i = 0; i < help->dthps_nprovs; i++) {
16551 				dtrace_helper_provider_remove(
16552 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16553 			}
16554 		} else {
16555 			mutex_enter(&dtrace_lock);
16556 			ASSERT(help->dthps_deferred == 0 ||
16557 			    help->dthps_next != NULL ||
16558 			    help->dthps_prev != NULL ||
16559 			    help == dtrace_deferred_pid);
16560 
16561 			/*
16562 			 * Remove the helper from the deferred list.
16563 			 */
16564 			if (help->dthps_next != NULL)
16565 				help->dthps_next->dthps_prev = help->dthps_prev;
16566 			if (help->dthps_prev != NULL)
16567 				help->dthps_prev->dthps_next = help->dthps_next;
16568 			if (dtrace_deferred_pid == help) {
16569 				dtrace_deferred_pid = help->dthps_next;
16570 				ASSERT(help->dthps_prev == NULL);
16571 			}
16572 
16573 			mutex_exit(&dtrace_lock);
16574 		}
16575 
16576 		mutex_exit(&dtrace_meta_lock);
16577 
16578 		for (i = 0; i < help->dthps_nprovs; i++) {
16579 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16580 		}
16581 
16582 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16583 		    sizeof (dtrace_helper_provider_t *));
16584 	}
16585 
16586 	mutex_enter(&dtrace_lock);
16587 
16588 	dtrace_vstate_fini(&help->dthps_vstate);
16589 	kmem_free(help->dthps_actions,
16590 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16591 	kmem_free(help, sizeof (dtrace_helpers_t));
16592 
16593 	--dtrace_helpers;
16594 	mutex_exit(&dtrace_lock);
16595 }
16596 
16597 #ifdef illumos
16598 static
16599 #endif
16600 void
16601 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16602 {
16603 	dtrace_helpers_t *help, *newhelp;
16604 	dtrace_helper_action_t *helper, *new, *last;
16605 	dtrace_difo_t *dp;
16606 	dtrace_vstate_t *vstate;
16607 	int i, j, sz, hasprovs = 0;
16608 
16609 	mutex_enter(&dtrace_lock);
16610 	ASSERT(from->p_dtrace_helpers != NULL);
16611 	ASSERT(dtrace_helpers > 0);
16612 
16613 	help = from->p_dtrace_helpers;
16614 	newhelp = dtrace_helpers_create(to);
16615 	ASSERT(to->p_dtrace_helpers != NULL);
16616 
16617 	newhelp->dthps_generation = help->dthps_generation;
16618 	vstate = &newhelp->dthps_vstate;
16619 
16620 	/*
16621 	 * Duplicate the helper actions.
16622 	 */
16623 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16624 		if ((helper = help->dthps_actions[i]) == NULL)
16625 			continue;
16626 
16627 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16628 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16629 			    KM_SLEEP);
16630 			new->dtha_generation = helper->dtha_generation;
16631 
16632 			if ((dp = helper->dtha_predicate) != NULL) {
16633 				dp = dtrace_difo_duplicate(dp, vstate);
16634 				new->dtha_predicate = dp;
16635 			}
16636 
16637 			new->dtha_nactions = helper->dtha_nactions;
16638 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16639 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16640 
16641 			for (j = 0; j < new->dtha_nactions; j++) {
16642 				dtrace_difo_t *dp = helper->dtha_actions[j];
16643 
16644 				ASSERT(dp != NULL);
16645 				dp = dtrace_difo_duplicate(dp, vstate);
16646 				new->dtha_actions[j] = dp;
16647 			}
16648 
16649 			if (last != NULL) {
16650 				last->dtha_next = new;
16651 			} else {
16652 				newhelp->dthps_actions[i] = new;
16653 			}
16654 
16655 			last = new;
16656 		}
16657 	}
16658 
16659 	/*
16660 	 * Duplicate the helper providers and register them with the
16661 	 * DTrace framework.
16662 	 */
16663 	if (help->dthps_nprovs > 0) {
16664 		newhelp->dthps_nprovs = help->dthps_nprovs;
16665 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16666 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16667 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16668 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16669 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16670 			newhelp->dthps_provs[i]->dthp_ref++;
16671 		}
16672 
16673 		hasprovs = 1;
16674 	}
16675 
16676 	mutex_exit(&dtrace_lock);
16677 
16678 	if (hasprovs)
16679 		dtrace_helper_provider_register(to, newhelp, NULL);
16680 }
16681 
16682 /*
16683  * DTrace Hook Functions
16684  */
16685 static void
16686 dtrace_module_loaded(modctl_t *ctl)
16687 {
16688 	dtrace_provider_t *prv;
16689 
16690 	mutex_enter(&dtrace_provider_lock);
16691 #ifdef illumos
16692 	mutex_enter(&mod_lock);
16693 #endif
16694 
16695 #ifdef illumos
16696 	ASSERT(ctl->mod_busy);
16697 #endif
16698 
16699 	/*
16700 	 * We're going to call each providers per-module provide operation
16701 	 * specifying only this module.
16702 	 */
16703 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16704 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16705 
16706 #ifdef illumos
16707 	mutex_exit(&mod_lock);
16708 #endif
16709 	mutex_exit(&dtrace_provider_lock);
16710 
16711 	/*
16712 	 * If we have any retained enablings, we need to match against them.
16713 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16714 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16715 	 * module.  (In particular, this happens when loading scheduling
16716 	 * classes.)  So if we have any retained enablings, we need to dispatch
16717 	 * our task queue to do the match for us.
16718 	 */
16719 	mutex_enter(&dtrace_lock);
16720 
16721 	if (dtrace_retained == NULL) {
16722 		mutex_exit(&dtrace_lock);
16723 		return;
16724 	}
16725 
16726 	(void) taskq_dispatch(dtrace_taskq,
16727 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16728 
16729 	mutex_exit(&dtrace_lock);
16730 
16731 	/*
16732 	 * And now, for a little heuristic sleaze:  in general, we want to
16733 	 * match modules as soon as they load.  However, we cannot guarantee
16734 	 * this, because it would lead us to the lock ordering violation
16735 	 * outlined above.  The common case, of course, is that cpu_lock is
16736 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16737 	 * long enough for the task queue to do its work.  If it's not, it's
16738 	 * not a serious problem -- it just means that the module that we
16739 	 * just loaded may not be immediately instrumentable.
16740 	 */
16741 	delay(1);
16742 }
16743 
16744 static void
16745 #ifdef illumos
16746 dtrace_module_unloaded(modctl_t *ctl)
16747 #else
16748 dtrace_module_unloaded(modctl_t *ctl, int *error)
16749 #endif
16750 {
16751 	dtrace_probe_t template, *probe, *first, *next;
16752 	dtrace_provider_t *prov;
16753 #ifndef illumos
16754 	char modname[DTRACE_MODNAMELEN];
16755 	size_t len;
16756 #endif
16757 
16758 #ifdef illumos
16759 	template.dtpr_mod = ctl->mod_modname;
16760 #else
16761 	/* Handle the fact that ctl->filename may end in ".ko". */
16762 	strlcpy(modname, ctl->filename, sizeof(modname));
16763 	len = strlen(ctl->filename);
16764 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16765 		modname[len - 3] = '\0';
16766 	template.dtpr_mod = modname;
16767 #endif
16768 
16769 	mutex_enter(&dtrace_provider_lock);
16770 #ifdef illumos
16771 	mutex_enter(&mod_lock);
16772 #endif
16773 	mutex_enter(&dtrace_lock);
16774 
16775 #ifndef illumos
16776 	if (ctl->nenabled > 0) {
16777 		/* Don't allow unloads if a probe is enabled. */
16778 		mutex_exit(&dtrace_provider_lock);
16779 		mutex_exit(&dtrace_lock);
16780 		*error = -1;
16781 		printf(
16782 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16783 		return;
16784 	}
16785 #endif
16786 
16787 	if (dtrace_bymod == NULL) {
16788 		/*
16789 		 * The DTrace module is loaded (obviously) but not attached;
16790 		 * we don't have any work to do.
16791 		 */
16792 		mutex_exit(&dtrace_provider_lock);
16793 #ifdef illumos
16794 		mutex_exit(&mod_lock);
16795 #endif
16796 		mutex_exit(&dtrace_lock);
16797 		return;
16798 	}
16799 
16800 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16801 	    probe != NULL; probe = probe->dtpr_nextmod) {
16802 		if (probe->dtpr_ecb != NULL) {
16803 			mutex_exit(&dtrace_provider_lock);
16804 #ifdef illumos
16805 			mutex_exit(&mod_lock);
16806 #endif
16807 			mutex_exit(&dtrace_lock);
16808 
16809 			/*
16810 			 * This shouldn't _actually_ be possible -- we're
16811 			 * unloading a module that has an enabled probe in it.
16812 			 * (It's normally up to the provider to make sure that
16813 			 * this can't happen.)  However, because dtps_enable()
16814 			 * doesn't have a failure mode, there can be an
16815 			 * enable/unload race.  Upshot:  we don't want to
16816 			 * assert, but we're not going to disable the
16817 			 * probe, either.
16818 			 */
16819 			if (dtrace_err_verbose) {
16820 #ifdef illumos
16821 				cmn_err(CE_WARN, "unloaded module '%s' had "
16822 				    "enabled probes", ctl->mod_modname);
16823 #else
16824 				cmn_err(CE_WARN, "unloaded module '%s' had "
16825 				    "enabled probes", modname);
16826 #endif
16827 			}
16828 
16829 			return;
16830 		}
16831 	}
16832 
16833 	probe = first;
16834 
16835 	for (first = NULL; probe != NULL; probe = next) {
16836 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16837 
16838 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16839 
16840 		next = probe->dtpr_nextmod;
16841 		dtrace_hash_remove(dtrace_bymod, probe);
16842 		dtrace_hash_remove(dtrace_byfunc, probe);
16843 		dtrace_hash_remove(dtrace_byname, probe);
16844 
16845 		if (first == NULL) {
16846 			first = probe;
16847 			probe->dtpr_nextmod = NULL;
16848 		} else {
16849 			probe->dtpr_nextmod = first;
16850 			first = probe;
16851 		}
16852 	}
16853 
16854 	/*
16855 	 * We've removed all of the module's probes from the hash chains and
16856 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16857 	 * everyone has cleared out from any probe array processing.
16858 	 */
16859 	dtrace_sync();
16860 
16861 	for (probe = first; probe != NULL; probe = first) {
16862 		first = probe->dtpr_nextmod;
16863 		prov = probe->dtpr_provider;
16864 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16865 		    probe->dtpr_arg);
16866 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16867 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16868 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16869 #ifdef illumos
16870 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16871 #else
16872 		free_unr(dtrace_arena, probe->dtpr_id);
16873 #endif
16874 		kmem_free(probe, sizeof (dtrace_probe_t));
16875 	}
16876 
16877 	mutex_exit(&dtrace_lock);
16878 #ifdef illumos
16879 	mutex_exit(&mod_lock);
16880 #endif
16881 	mutex_exit(&dtrace_provider_lock);
16882 }
16883 
16884 #ifndef illumos
16885 static void
16886 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16887 {
16888 
16889 	dtrace_module_loaded(lf);
16890 }
16891 
16892 static void
16893 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16894 {
16895 
16896 	if (*error != 0)
16897 		/* We already have an error, so don't do anything. */
16898 		return;
16899 	dtrace_module_unloaded(lf, error);
16900 }
16901 #endif
16902 
16903 #ifdef illumos
16904 static void
16905 dtrace_suspend(void)
16906 {
16907 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16908 }
16909 
16910 static void
16911 dtrace_resume(void)
16912 {
16913 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16914 }
16915 #endif
16916 
16917 static int
16918 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16919 {
16920 	ASSERT(MUTEX_HELD(&cpu_lock));
16921 	mutex_enter(&dtrace_lock);
16922 
16923 	switch (what) {
16924 	case CPU_CONFIG: {
16925 		dtrace_state_t *state;
16926 		dtrace_optval_t *opt, rs, c;
16927 
16928 		/*
16929 		 * For now, we only allocate a new buffer for anonymous state.
16930 		 */
16931 		if ((state = dtrace_anon.dta_state) == NULL)
16932 			break;
16933 
16934 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16935 			break;
16936 
16937 		opt = state->dts_options;
16938 		c = opt[DTRACEOPT_CPU];
16939 
16940 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16941 			break;
16942 
16943 		/*
16944 		 * Regardless of what the actual policy is, we're going to
16945 		 * temporarily set our resize policy to be manual.  We're
16946 		 * also going to temporarily set our CPU option to denote
16947 		 * the newly configured CPU.
16948 		 */
16949 		rs = opt[DTRACEOPT_BUFRESIZE];
16950 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16951 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16952 
16953 		(void) dtrace_state_buffers(state);
16954 
16955 		opt[DTRACEOPT_BUFRESIZE] = rs;
16956 		opt[DTRACEOPT_CPU] = c;
16957 
16958 		break;
16959 	}
16960 
16961 	case CPU_UNCONFIG:
16962 		/*
16963 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16964 		 * buffer will be freed when the consumer exits.)
16965 		 */
16966 		break;
16967 
16968 	default:
16969 		break;
16970 	}
16971 
16972 	mutex_exit(&dtrace_lock);
16973 	return (0);
16974 }
16975 
16976 #ifdef illumos
16977 static void
16978 dtrace_cpu_setup_initial(processorid_t cpu)
16979 {
16980 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16981 }
16982 #endif
16983 
16984 static void
16985 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16986 {
16987 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16988 		int osize, nsize;
16989 		dtrace_toxrange_t *range;
16990 
16991 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16992 
16993 		if (osize == 0) {
16994 			ASSERT(dtrace_toxrange == NULL);
16995 			ASSERT(dtrace_toxranges_max == 0);
16996 			dtrace_toxranges_max = 1;
16997 		} else {
16998 			dtrace_toxranges_max <<= 1;
16999 		}
17000 
17001 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17002 		range = kmem_zalloc(nsize, KM_SLEEP);
17003 
17004 		if (dtrace_toxrange != NULL) {
17005 			ASSERT(osize != 0);
17006 			bcopy(dtrace_toxrange, range, osize);
17007 			kmem_free(dtrace_toxrange, osize);
17008 		}
17009 
17010 		dtrace_toxrange = range;
17011 	}
17012 
17013 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17014 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17015 
17016 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17017 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17018 	dtrace_toxranges++;
17019 }
17020 
17021 static void
17022 dtrace_getf_barrier(void)
17023 {
17024 #ifdef illumos
17025 	/*
17026 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17027 	 * that contain calls to getf(), this routine will be called on every
17028 	 * closef() before either the underlying vnode is released or the
17029 	 * file_t itself is freed.  By the time we are here, it is essential
17030 	 * that the file_t can no longer be accessed from a call to getf()
17031 	 * in probe context -- that assures that a dtrace_sync() can be used
17032 	 * to clear out any enablings referring to the old structures.
17033 	 */
17034 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17035 	    kcred->cr_zone->zone_dtrace_getf != 0)
17036 		dtrace_sync();
17037 #endif
17038 }
17039 
17040 /*
17041  * DTrace Driver Cookbook Functions
17042  */
17043 #ifdef illumos
17044 /*ARGSUSED*/
17045 static int
17046 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17047 {
17048 	dtrace_provider_id_t id;
17049 	dtrace_state_t *state = NULL;
17050 	dtrace_enabling_t *enab;
17051 
17052 	mutex_enter(&cpu_lock);
17053 	mutex_enter(&dtrace_provider_lock);
17054 	mutex_enter(&dtrace_lock);
17055 
17056 	if (ddi_soft_state_init(&dtrace_softstate,
17057 	    sizeof (dtrace_state_t), 0) != 0) {
17058 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17059 		mutex_exit(&cpu_lock);
17060 		mutex_exit(&dtrace_provider_lock);
17061 		mutex_exit(&dtrace_lock);
17062 		return (DDI_FAILURE);
17063 	}
17064 
17065 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17066 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17067 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17068 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17069 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17070 		ddi_remove_minor_node(devi, NULL);
17071 		ddi_soft_state_fini(&dtrace_softstate);
17072 		mutex_exit(&cpu_lock);
17073 		mutex_exit(&dtrace_provider_lock);
17074 		mutex_exit(&dtrace_lock);
17075 		return (DDI_FAILURE);
17076 	}
17077 
17078 	ddi_report_dev(devi);
17079 	dtrace_devi = devi;
17080 
17081 	dtrace_modload = dtrace_module_loaded;
17082 	dtrace_modunload = dtrace_module_unloaded;
17083 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17084 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17085 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17086 	dtrace_cpustart_init = dtrace_suspend;
17087 	dtrace_cpustart_fini = dtrace_resume;
17088 	dtrace_debugger_init = dtrace_suspend;
17089 	dtrace_debugger_fini = dtrace_resume;
17090 
17091 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17092 
17093 	ASSERT(MUTEX_HELD(&cpu_lock));
17094 
17095 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17096 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17097 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17098 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17099 	    VM_SLEEP | VMC_IDENTIFIER);
17100 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17101 	    1, INT_MAX, 0);
17102 
17103 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17104 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17105 	    NULL, NULL, NULL, NULL, NULL, 0);
17106 
17107 	ASSERT(MUTEX_HELD(&cpu_lock));
17108 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17109 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17110 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17111 
17112 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17113 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17114 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17115 
17116 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17117 	    offsetof(dtrace_probe_t, dtpr_nextname),
17118 	    offsetof(dtrace_probe_t, dtpr_prevname));
17119 
17120 	if (dtrace_retain_max < 1) {
17121 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
17122 		    "setting to 1", dtrace_retain_max);
17123 		dtrace_retain_max = 1;
17124 	}
17125 
17126 	/*
17127 	 * Now discover our toxic ranges.
17128 	 */
17129 	dtrace_toxic_ranges(dtrace_toxrange_add);
17130 
17131 	/*
17132 	 * Before we register ourselves as a provider to our own framework,
17133 	 * we would like to assert that dtrace_provider is NULL -- but that's
17134 	 * not true if we were loaded as a dependency of a DTrace provider.
17135 	 * Once we've registered, we can assert that dtrace_provider is our
17136 	 * pseudo provider.
17137 	 */
17138 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17139 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17140 
17141 	ASSERT(dtrace_provider != NULL);
17142 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17143 
17144 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17145 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17146 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17147 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17148 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17149 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17150 
17151 	dtrace_anon_property();
17152 	mutex_exit(&cpu_lock);
17153 
17154 	/*
17155 	 * If there are already providers, we must ask them to provide their
17156 	 * probes, and then match any anonymous enabling against them.  Note
17157 	 * that there should be no other retained enablings at this time:
17158 	 * the only retained enablings at this time should be the anonymous
17159 	 * enabling.
17160 	 */
17161 	if (dtrace_anon.dta_enabling != NULL) {
17162 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17163 
17164 		dtrace_enabling_provide(NULL);
17165 		state = dtrace_anon.dta_state;
17166 
17167 		/*
17168 		 * We couldn't hold cpu_lock across the above call to
17169 		 * dtrace_enabling_provide(), but we must hold it to actually
17170 		 * enable the probes.  We have to drop all of our locks, pick
17171 		 * up cpu_lock, and regain our locks before matching the
17172 		 * retained anonymous enabling.
17173 		 */
17174 		mutex_exit(&dtrace_lock);
17175 		mutex_exit(&dtrace_provider_lock);
17176 
17177 		mutex_enter(&cpu_lock);
17178 		mutex_enter(&dtrace_provider_lock);
17179 		mutex_enter(&dtrace_lock);
17180 
17181 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17182 			(void) dtrace_enabling_match(enab, NULL);
17183 
17184 		mutex_exit(&cpu_lock);
17185 	}
17186 
17187 	mutex_exit(&dtrace_lock);
17188 	mutex_exit(&dtrace_provider_lock);
17189 
17190 	if (state != NULL) {
17191 		/*
17192 		 * If we created any anonymous state, set it going now.
17193 		 */
17194 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17195 	}
17196 
17197 	return (DDI_SUCCESS);
17198 }
17199 #endif	/* illumos */
17200 
17201 #ifndef illumos
17202 static void dtrace_dtr(void *);
17203 #endif
17204 
17205 /*ARGSUSED*/
17206 static int
17207 #ifdef illumos
17208 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17209 #else
17210 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17211 #endif
17212 {
17213 	dtrace_state_t *state;
17214 	uint32_t priv;
17215 	uid_t uid;
17216 	zoneid_t zoneid;
17217 
17218 #ifdef illumos
17219 	if (getminor(*devp) == DTRACEMNRN_HELPER)
17220 		return (0);
17221 
17222 	/*
17223 	 * If this wasn't an open with the "helper" minor, then it must be
17224 	 * the "dtrace" minor.
17225 	 */
17226 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
17227 		return (ENXIO);
17228 #else
17229 	cred_t *cred_p = NULL;
17230 	cred_p = dev->si_cred;
17231 
17232 	/*
17233 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17234 	 * caller lacks sufficient permission to do anything with DTrace.
17235 	 */
17236 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17237 	if (priv == DTRACE_PRIV_NONE) {
17238 #endif
17239 
17240 		return (EACCES);
17241 	}
17242 
17243 	/*
17244 	 * Ask all providers to provide all their probes.
17245 	 */
17246 	mutex_enter(&dtrace_provider_lock);
17247 	dtrace_probe_provide(NULL, NULL);
17248 	mutex_exit(&dtrace_provider_lock);
17249 
17250 	mutex_enter(&cpu_lock);
17251 	mutex_enter(&dtrace_lock);
17252 	dtrace_opens++;
17253 	dtrace_membar_producer();
17254 
17255 #ifdef illumos
17256 	/*
17257 	 * If the kernel debugger is active (that is, if the kernel debugger
17258 	 * modified text in some way), we won't allow the open.
17259 	 */
17260 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17261 		dtrace_opens--;
17262 		mutex_exit(&cpu_lock);
17263 		mutex_exit(&dtrace_lock);
17264 		return (EBUSY);
17265 	}
17266 
17267 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17268 		/*
17269 		 * If DTrace helper tracing is enabled, we need to allocate the
17270 		 * trace buffer and initialize the values.
17271 		 */
17272 		dtrace_helptrace_buffer =
17273 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17274 		dtrace_helptrace_next = 0;
17275 		dtrace_helptrace_wrapped = 0;
17276 		dtrace_helptrace_enable = 0;
17277 	}
17278 
17279 	state = dtrace_state_create(devp, cred_p);
17280 #else
17281 	state = dtrace_state_create(dev, NULL);
17282 	devfs_set_cdevpriv(state, dtrace_dtr);
17283 #endif
17284 
17285 	mutex_exit(&cpu_lock);
17286 
17287 	if (state == NULL) {
17288 #ifdef illumos
17289 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17290 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17291 #else
17292 		--dtrace_opens;
17293 #endif
17294 		mutex_exit(&dtrace_lock);
17295 		return (EAGAIN);
17296 	}
17297 
17298 	mutex_exit(&dtrace_lock);
17299 
17300 	return (0);
17301 }
17302 
17303 /*ARGSUSED*/
17304 #ifdef illumos
17305 static int
17306 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17307 #else
17308 static void
17309 dtrace_dtr(void *data)
17310 #endif
17311 {
17312 #ifdef illumos
17313 	minor_t minor = getminor(dev);
17314 	dtrace_state_t *state;
17315 #endif
17316 	dtrace_helptrace_t *buf = NULL;
17317 
17318 #ifdef illumos
17319 	if (minor == DTRACEMNRN_HELPER)
17320 		return (0);
17321 
17322 	state = ddi_get_soft_state(dtrace_softstate, minor);
17323 #else
17324 	dtrace_state_t *state = data;
17325 #endif
17326 
17327 	mutex_enter(&cpu_lock);
17328 	mutex_enter(&dtrace_lock);
17329 
17330 #ifdef illumos
17331 	if (state->dts_anon)
17332 #else
17333 	if (state != NULL && state->dts_anon)
17334 #endif
17335 	{
17336 		/*
17337 		 * There is anonymous state. Destroy that first.
17338 		 */
17339 		ASSERT(dtrace_anon.dta_state == NULL);
17340 		dtrace_state_destroy(state->dts_anon);
17341 	}
17342 
17343 	if (dtrace_helptrace_disable) {
17344 		/*
17345 		 * If we have been told to disable helper tracing, set the
17346 		 * buffer to NULL before calling into dtrace_state_destroy();
17347 		 * we take advantage of its dtrace_sync() to know that no
17348 		 * CPU is in probe context with enabled helper tracing
17349 		 * after it returns.
17350 		 */
17351 		buf = dtrace_helptrace_buffer;
17352 		dtrace_helptrace_buffer = NULL;
17353 	}
17354 
17355 #ifdef illumos
17356 	dtrace_state_destroy(state);
17357 #else
17358 	if (state != NULL) {
17359 		dtrace_state_destroy(state);
17360 		kmem_free(state, 0);
17361 	}
17362 #endif
17363 	ASSERT(dtrace_opens > 0);
17364 
17365 #ifdef illumos
17366 	/*
17367 	 * Only relinquish control of the kernel debugger interface when there
17368 	 * are no consumers and no anonymous enablings.
17369 	 */
17370 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17371 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17372 #else
17373 	--dtrace_opens;
17374 #endif
17375 
17376 	if (buf != NULL) {
17377 		kmem_free(buf, dtrace_helptrace_bufsize);
17378 		dtrace_helptrace_disable = 0;
17379 	}
17380 
17381 	mutex_exit(&dtrace_lock);
17382 	mutex_exit(&cpu_lock);
17383 
17384 #ifdef illumos
17385 	return (0);
17386 #endif
17387 }
17388 
17389 #ifdef illumos
17390 /*ARGSUSED*/
17391 static int
17392 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17393 {
17394 	int rval;
17395 	dof_helper_t help, *dhp = NULL;
17396 
17397 	switch (cmd) {
17398 	case DTRACEHIOC_ADDDOF:
17399 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17400 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
17401 			return (EFAULT);
17402 		}
17403 
17404 		dhp = &help;
17405 		arg = (intptr_t)help.dofhp_dof;
17406 		/*FALLTHROUGH*/
17407 
17408 	case DTRACEHIOC_ADD: {
17409 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17410 
17411 		if (dof == NULL)
17412 			return (rval);
17413 
17414 		mutex_enter(&dtrace_lock);
17415 
17416 		/*
17417 		 * dtrace_helper_slurp() takes responsibility for the dof --
17418 		 * it may free it now or it may save it and free it later.
17419 		 */
17420 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17421 			*rv = rval;
17422 			rval = 0;
17423 		} else {
17424 			rval = EINVAL;
17425 		}
17426 
17427 		mutex_exit(&dtrace_lock);
17428 		return (rval);
17429 	}
17430 
17431 	case DTRACEHIOC_REMOVE: {
17432 		mutex_enter(&dtrace_lock);
17433 		rval = dtrace_helper_destroygen(NULL, arg);
17434 		mutex_exit(&dtrace_lock);
17435 
17436 		return (rval);
17437 	}
17438 
17439 	default:
17440 		break;
17441 	}
17442 
17443 	return (ENOTTY);
17444 }
17445 
17446 /*ARGSUSED*/
17447 static int
17448 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17449 {
17450 	minor_t minor = getminor(dev);
17451 	dtrace_state_t *state;
17452 	int rval;
17453 
17454 	if (minor == DTRACEMNRN_HELPER)
17455 		return (dtrace_ioctl_helper(cmd, arg, rv));
17456 
17457 	state = ddi_get_soft_state(dtrace_softstate, minor);
17458 
17459 	if (state->dts_anon) {
17460 		ASSERT(dtrace_anon.dta_state == NULL);
17461 		state = state->dts_anon;
17462 	}
17463 
17464 	switch (cmd) {
17465 	case DTRACEIOC_PROVIDER: {
17466 		dtrace_providerdesc_t pvd;
17467 		dtrace_provider_t *pvp;
17468 
17469 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17470 			return (EFAULT);
17471 
17472 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17473 		mutex_enter(&dtrace_provider_lock);
17474 
17475 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17476 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17477 				break;
17478 		}
17479 
17480 		mutex_exit(&dtrace_provider_lock);
17481 
17482 		if (pvp == NULL)
17483 			return (ESRCH);
17484 
17485 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17486 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17487 
17488 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17489 			return (EFAULT);
17490 
17491 		return (0);
17492 	}
17493 
17494 	case DTRACEIOC_EPROBE: {
17495 		dtrace_eprobedesc_t epdesc;
17496 		dtrace_ecb_t *ecb;
17497 		dtrace_action_t *act;
17498 		void *buf;
17499 		size_t size;
17500 		uintptr_t dest;
17501 		int nrecs;
17502 
17503 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17504 			return (EFAULT);
17505 
17506 		mutex_enter(&dtrace_lock);
17507 
17508 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17509 			mutex_exit(&dtrace_lock);
17510 			return (EINVAL);
17511 		}
17512 
17513 		if (ecb->dte_probe == NULL) {
17514 			mutex_exit(&dtrace_lock);
17515 			return (EINVAL);
17516 		}
17517 
17518 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17519 		epdesc.dtepd_uarg = ecb->dte_uarg;
17520 		epdesc.dtepd_size = ecb->dte_size;
17521 
17522 		nrecs = epdesc.dtepd_nrecs;
17523 		epdesc.dtepd_nrecs = 0;
17524 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17525 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17526 				continue;
17527 
17528 			epdesc.dtepd_nrecs++;
17529 		}
17530 
17531 		/*
17532 		 * Now that we have the size, we need to allocate a temporary
17533 		 * buffer in which to store the complete description.  We need
17534 		 * the temporary buffer to be able to drop dtrace_lock()
17535 		 * across the copyout(), below.
17536 		 */
17537 		size = sizeof (dtrace_eprobedesc_t) +
17538 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17539 
17540 		buf = kmem_alloc(size, KM_SLEEP);
17541 		dest = (uintptr_t)buf;
17542 
17543 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17544 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17545 
17546 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17547 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17548 				continue;
17549 
17550 			if (nrecs-- == 0)
17551 				break;
17552 
17553 			bcopy(&act->dta_rec, (void *)dest,
17554 			    sizeof (dtrace_recdesc_t));
17555 			dest += sizeof (dtrace_recdesc_t);
17556 		}
17557 
17558 		mutex_exit(&dtrace_lock);
17559 
17560 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17561 			kmem_free(buf, size);
17562 			return (EFAULT);
17563 		}
17564 
17565 		kmem_free(buf, size);
17566 		return (0);
17567 	}
17568 
17569 	case DTRACEIOC_AGGDESC: {
17570 		dtrace_aggdesc_t aggdesc;
17571 		dtrace_action_t *act;
17572 		dtrace_aggregation_t *agg;
17573 		int nrecs;
17574 		uint32_t offs;
17575 		dtrace_recdesc_t *lrec;
17576 		void *buf;
17577 		size_t size;
17578 		uintptr_t dest;
17579 
17580 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17581 			return (EFAULT);
17582 
17583 		mutex_enter(&dtrace_lock);
17584 
17585 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17586 			mutex_exit(&dtrace_lock);
17587 			return (EINVAL);
17588 		}
17589 
17590 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17591 
17592 		nrecs = aggdesc.dtagd_nrecs;
17593 		aggdesc.dtagd_nrecs = 0;
17594 
17595 		offs = agg->dtag_base;
17596 		lrec = &agg->dtag_action.dta_rec;
17597 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17598 
17599 		for (act = agg->dtag_first; ; act = act->dta_next) {
17600 			ASSERT(act->dta_intuple ||
17601 			    DTRACEACT_ISAGG(act->dta_kind));
17602 
17603 			/*
17604 			 * If this action has a record size of zero, it
17605 			 * denotes an argument to the aggregating action.
17606 			 * Because the presence of this record doesn't (or
17607 			 * shouldn't) affect the way the data is interpreted,
17608 			 * we don't copy it out to save user-level the
17609 			 * confusion of dealing with a zero-length record.
17610 			 */
17611 			if (act->dta_rec.dtrd_size == 0) {
17612 				ASSERT(agg->dtag_hasarg);
17613 				continue;
17614 			}
17615 
17616 			aggdesc.dtagd_nrecs++;
17617 
17618 			if (act == &agg->dtag_action)
17619 				break;
17620 		}
17621 
17622 		/*
17623 		 * Now that we have the size, we need to allocate a temporary
17624 		 * buffer in which to store the complete description.  We need
17625 		 * the temporary buffer to be able to drop dtrace_lock()
17626 		 * across the copyout(), below.
17627 		 */
17628 		size = sizeof (dtrace_aggdesc_t) +
17629 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17630 
17631 		buf = kmem_alloc(size, KM_SLEEP);
17632 		dest = (uintptr_t)buf;
17633 
17634 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17635 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17636 
17637 		for (act = agg->dtag_first; ; act = act->dta_next) {
17638 			dtrace_recdesc_t rec = act->dta_rec;
17639 
17640 			/*
17641 			 * See the comment in the above loop for why we pass
17642 			 * over zero-length records.
17643 			 */
17644 			if (rec.dtrd_size == 0) {
17645 				ASSERT(agg->dtag_hasarg);
17646 				continue;
17647 			}
17648 
17649 			if (nrecs-- == 0)
17650 				break;
17651 
17652 			rec.dtrd_offset -= offs;
17653 			bcopy(&rec, (void *)dest, sizeof (rec));
17654 			dest += sizeof (dtrace_recdesc_t);
17655 
17656 			if (act == &agg->dtag_action)
17657 				break;
17658 		}
17659 
17660 		mutex_exit(&dtrace_lock);
17661 
17662 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17663 			kmem_free(buf, size);
17664 			return (EFAULT);
17665 		}
17666 
17667 		kmem_free(buf, size);
17668 		return (0);
17669 	}
17670 
17671 	case DTRACEIOC_ENABLE: {
17672 		dof_hdr_t *dof;
17673 		dtrace_enabling_t *enab = NULL;
17674 		dtrace_vstate_t *vstate;
17675 		int err = 0;
17676 
17677 		*rv = 0;
17678 
17679 		/*
17680 		 * If a NULL argument has been passed, we take this as our
17681 		 * cue to reevaluate our enablings.
17682 		 */
17683 		if (arg == NULL) {
17684 			dtrace_enabling_matchall();
17685 
17686 			return (0);
17687 		}
17688 
17689 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17690 			return (rval);
17691 
17692 		mutex_enter(&cpu_lock);
17693 		mutex_enter(&dtrace_lock);
17694 		vstate = &state->dts_vstate;
17695 
17696 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17697 			mutex_exit(&dtrace_lock);
17698 			mutex_exit(&cpu_lock);
17699 			dtrace_dof_destroy(dof);
17700 			return (EBUSY);
17701 		}
17702 
17703 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17704 			mutex_exit(&dtrace_lock);
17705 			mutex_exit(&cpu_lock);
17706 			dtrace_dof_destroy(dof);
17707 			return (EINVAL);
17708 		}
17709 
17710 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17711 			dtrace_enabling_destroy(enab);
17712 			mutex_exit(&dtrace_lock);
17713 			mutex_exit(&cpu_lock);
17714 			dtrace_dof_destroy(dof);
17715 			return (rval);
17716 		}
17717 
17718 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17719 			err = dtrace_enabling_retain(enab);
17720 		} else {
17721 			dtrace_enabling_destroy(enab);
17722 		}
17723 
17724 		mutex_exit(&cpu_lock);
17725 		mutex_exit(&dtrace_lock);
17726 		dtrace_dof_destroy(dof);
17727 
17728 		return (err);
17729 	}
17730 
17731 	case DTRACEIOC_REPLICATE: {
17732 		dtrace_repldesc_t desc;
17733 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17734 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17735 		int err;
17736 
17737 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17738 			return (EFAULT);
17739 
17740 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17741 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17742 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17743 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17744 
17745 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17746 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17747 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17748 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17749 
17750 		mutex_enter(&dtrace_lock);
17751 		err = dtrace_enabling_replicate(state, match, create);
17752 		mutex_exit(&dtrace_lock);
17753 
17754 		return (err);
17755 	}
17756 
17757 	case DTRACEIOC_PROBEMATCH:
17758 	case DTRACEIOC_PROBES: {
17759 		dtrace_probe_t *probe = NULL;
17760 		dtrace_probedesc_t desc;
17761 		dtrace_probekey_t pkey;
17762 		dtrace_id_t i;
17763 		int m = 0;
17764 		uint32_t priv;
17765 		uid_t uid;
17766 		zoneid_t zoneid;
17767 
17768 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17769 			return (EFAULT);
17770 
17771 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17772 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17773 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17774 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17775 
17776 		/*
17777 		 * Before we attempt to match this probe, we want to give
17778 		 * all providers the opportunity to provide it.
17779 		 */
17780 		if (desc.dtpd_id == DTRACE_IDNONE) {
17781 			mutex_enter(&dtrace_provider_lock);
17782 			dtrace_probe_provide(&desc, NULL);
17783 			mutex_exit(&dtrace_provider_lock);
17784 			desc.dtpd_id++;
17785 		}
17786 
17787 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17788 			dtrace_probekey(&desc, &pkey);
17789 			pkey.dtpk_id = DTRACE_IDNONE;
17790 		}
17791 
17792 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17793 
17794 		mutex_enter(&dtrace_lock);
17795 
17796 		if (cmd == DTRACEIOC_PROBEMATCH) {
17797 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17798 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17799 				    (m = dtrace_match_probe(probe, &pkey,
17800 				    priv, uid, zoneid)) != 0)
17801 					break;
17802 			}
17803 
17804 			if (m < 0) {
17805 				mutex_exit(&dtrace_lock);
17806 				return (EINVAL);
17807 			}
17808 
17809 		} else {
17810 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17811 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17812 				    dtrace_match_priv(probe, priv, uid, zoneid))
17813 					break;
17814 			}
17815 		}
17816 
17817 		if (probe == NULL) {
17818 			mutex_exit(&dtrace_lock);
17819 			return (ESRCH);
17820 		}
17821 
17822 		dtrace_probe_description(probe, &desc);
17823 		mutex_exit(&dtrace_lock);
17824 
17825 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17826 			return (EFAULT);
17827 
17828 		return (0);
17829 	}
17830 
17831 	case DTRACEIOC_PROBEARG: {
17832 		dtrace_argdesc_t desc;
17833 		dtrace_probe_t *probe;
17834 		dtrace_provider_t *prov;
17835 
17836 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17837 			return (EFAULT);
17838 
17839 		if (desc.dtargd_id == DTRACE_IDNONE)
17840 			return (EINVAL);
17841 
17842 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17843 			return (EINVAL);
17844 
17845 		mutex_enter(&dtrace_provider_lock);
17846 		mutex_enter(&mod_lock);
17847 		mutex_enter(&dtrace_lock);
17848 
17849 		if (desc.dtargd_id > dtrace_nprobes) {
17850 			mutex_exit(&dtrace_lock);
17851 			mutex_exit(&mod_lock);
17852 			mutex_exit(&dtrace_provider_lock);
17853 			return (EINVAL);
17854 		}
17855 
17856 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17857 			mutex_exit(&dtrace_lock);
17858 			mutex_exit(&mod_lock);
17859 			mutex_exit(&dtrace_provider_lock);
17860 			return (EINVAL);
17861 		}
17862 
17863 		mutex_exit(&dtrace_lock);
17864 
17865 		prov = probe->dtpr_provider;
17866 
17867 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17868 			/*
17869 			 * There isn't any typed information for this probe.
17870 			 * Set the argument number to DTRACE_ARGNONE.
17871 			 */
17872 			desc.dtargd_ndx = DTRACE_ARGNONE;
17873 		} else {
17874 			desc.dtargd_native[0] = '\0';
17875 			desc.dtargd_xlate[0] = '\0';
17876 			desc.dtargd_mapping = desc.dtargd_ndx;
17877 
17878 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17879 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17880 		}
17881 
17882 		mutex_exit(&mod_lock);
17883 		mutex_exit(&dtrace_provider_lock);
17884 
17885 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17886 			return (EFAULT);
17887 
17888 		return (0);
17889 	}
17890 
17891 	case DTRACEIOC_GO: {
17892 		processorid_t cpuid;
17893 		rval = dtrace_state_go(state, &cpuid);
17894 
17895 		if (rval != 0)
17896 			return (rval);
17897 
17898 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17899 			return (EFAULT);
17900 
17901 		return (0);
17902 	}
17903 
17904 	case DTRACEIOC_STOP: {
17905 		processorid_t cpuid;
17906 
17907 		mutex_enter(&dtrace_lock);
17908 		rval = dtrace_state_stop(state, &cpuid);
17909 		mutex_exit(&dtrace_lock);
17910 
17911 		if (rval != 0)
17912 			return (rval);
17913 
17914 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17915 			return (EFAULT);
17916 
17917 		return (0);
17918 	}
17919 
17920 	case DTRACEIOC_DOFGET: {
17921 		dof_hdr_t hdr, *dof;
17922 		uint64_t len;
17923 
17924 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17925 			return (EFAULT);
17926 
17927 		mutex_enter(&dtrace_lock);
17928 		dof = dtrace_dof_create(state);
17929 		mutex_exit(&dtrace_lock);
17930 
17931 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17932 		rval = copyout(dof, (void *)arg, len);
17933 		dtrace_dof_destroy(dof);
17934 
17935 		return (rval == 0 ? 0 : EFAULT);
17936 	}
17937 
17938 	case DTRACEIOC_AGGSNAP:
17939 	case DTRACEIOC_BUFSNAP: {
17940 		dtrace_bufdesc_t desc;
17941 		caddr_t cached;
17942 		dtrace_buffer_t *buf;
17943 
17944 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17945 			return (EFAULT);
17946 
17947 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17948 			return (EINVAL);
17949 
17950 		mutex_enter(&dtrace_lock);
17951 
17952 		if (cmd == DTRACEIOC_BUFSNAP) {
17953 			buf = &state->dts_buffer[desc.dtbd_cpu];
17954 		} else {
17955 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17956 		}
17957 
17958 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17959 			size_t sz = buf->dtb_offset;
17960 
17961 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17962 				mutex_exit(&dtrace_lock);
17963 				return (EBUSY);
17964 			}
17965 
17966 			/*
17967 			 * If this buffer has already been consumed, we're
17968 			 * going to indicate that there's nothing left here
17969 			 * to consume.
17970 			 */
17971 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17972 				mutex_exit(&dtrace_lock);
17973 
17974 				desc.dtbd_size = 0;
17975 				desc.dtbd_drops = 0;
17976 				desc.dtbd_errors = 0;
17977 				desc.dtbd_oldest = 0;
17978 				sz = sizeof (desc);
17979 
17980 				if (copyout(&desc, (void *)arg, sz) != 0)
17981 					return (EFAULT);
17982 
17983 				return (0);
17984 			}
17985 
17986 			/*
17987 			 * If this is a ring buffer that has wrapped, we want
17988 			 * to copy the whole thing out.
17989 			 */
17990 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17991 				dtrace_buffer_polish(buf);
17992 				sz = buf->dtb_size;
17993 			}
17994 
17995 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17996 				mutex_exit(&dtrace_lock);
17997 				return (EFAULT);
17998 			}
17999 
18000 			desc.dtbd_size = sz;
18001 			desc.dtbd_drops = buf->dtb_drops;
18002 			desc.dtbd_errors = buf->dtb_errors;
18003 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18004 			desc.dtbd_timestamp = dtrace_gethrtime();
18005 
18006 			mutex_exit(&dtrace_lock);
18007 
18008 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18009 				return (EFAULT);
18010 
18011 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18012 
18013 			return (0);
18014 		}
18015 
18016 		if (buf->dtb_tomax == NULL) {
18017 			ASSERT(buf->dtb_xamot == NULL);
18018 			mutex_exit(&dtrace_lock);
18019 			return (ENOENT);
18020 		}
18021 
18022 		cached = buf->dtb_tomax;
18023 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18024 
18025 		dtrace_xcall(desc.dtbd_cpu,
18026 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
18027 
18028 		state->dts_errors += buf->dtb_xamot_errors;
18029 
18030 		/*
18031 		 * If the buffers did not actually switch, then the cross call
18032 		 * did not take place -- presumably because the given CPU is
18033 		 * not in the ready set.  If this is the case, we'll return
18034 		 * ENOENT.
18035 		 */
18036 		if (buf->dtb_tomax == cached) {
18037 			ASSERT(buf->dtb_xamot != cached);
18038 			mutex_exit(&dtrace_lock);
18039 			return (ENOENT);
18040 		}
18041 
18042 		ASSERT(cached == buf->dtb_xamot);
18043 
18044 		/*
18045 		 * We have our snapshot; now copy it out.
18046 		 */
18047 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
18048 		    buf->dtb_xamot_offset) != 0) {
18049 			mutex_exit(&dtrace_lock);
18050 			return (EFAULT);
18051 		}
18052 
18053 		desc.dtbd_size = buf->dtb_xamot_offset;
18054 		desc.dtbd_drops = buf->dtb_xamot_drops;
18055 		desc.dtbd_errors = buf->dtb_xamot_errors;
18056 		desc.dtbd_oldest = 0;
18057 		desc.dtbd_timestamp = buf->dtb_switched;
18058 
18059 		mutex_exit(&dtrace_lock);
18060 
18061 		/*
18062 		 * Finally, copy out the buffer description.
18063 		 */
18064 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18065 			return (EFAULT);
18066 
18067 		return (0);
18068 	}
18069 
18070 	case DTRACEIOC_CONF: {
18071 		dtrace_conf_t conf;
18072 
18073 		bzero(&conf, sizeof (conf));
18074 		conf.dtc_difversion = DIF_VERSION;
18075 		conf.dtc_difintregs = DIF_DIR_NREGS;
18076 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18077 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18078 
18079 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18080 			return (EFAULT);
18081 
18082 		return (0);
18083 	}
18084 
18085 	case DTRACEIOC_STATUS: {
18086 		dtrace_status_t stat;
18087 		dtrace_dstate_t *dstate;
18088 		int i, j;
18089 		uint64_t nerrs;
18090 
18091 		/*
18092 		 * See the comment in dtrace_state_deadman() for the reason
18093 		 * for setting dts_laststatus to INT64_MAX before setting
18094 		 * it to the correct value.
18095 		 */
18096 		state->dts_laststatus = INT64_MAX;
18097 		dtrace_membar_producer();
18098 		state->dts_laststatus = dtrace_gethrtime();
18099 
18100 		bzero(&stat, sizeof (stat));
18101 
18102 		mutex_enter(&dtrace_lock);
18103 
18104 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18105 			mutex_exit(&dtrace_lock);
18106 			return (ENOENT);
18107 		}
18108 
18109 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18110 			stat.dtst_exiting = 1;
18111 
18112 		nerrs = state->dts_errors;
18113 		dstate = &state->dts_vstate.dtvs_dynvars;
18114 
18115 		for (i = 0; i < NCPU; i++) {
18116 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18117 
18118 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18119 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18120 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18121 
18122 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18123 				stat.dtst_filled++;
18124 
18125 			nerrs += state->dts_buffer[i].dtb_errors;
18126 
18127 			for (j = 0; j < state->dts_nspeculations; j++) {
18128 				dtrace_speculation_t *spec;
18129 				dtrace_buffer_t *buf;
18130 
18131 				spec = &state->dts_speculations[j];
18132 				buf = &spec->dtsp_buffer[i];
18133 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18134 			}
18135 		}
18136 
18137 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18138 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18139 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18140 		stat.dtst_dblerrors = state->dts_dblerrors;
18141 		stat.dtst_killed =
18142 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18143 		stat.dtst_errors = nerrs;
18144 
18145 		mutex_exit(&dtrace_lock);
18146 
18147 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18148 			return (EFAULT);
18149 
18150 		return (0);
18151 	}
18152 
18153 	case DTRACEIOC_FORMAT: {
18154 		dtrace_fmtdesc_t fmt;
18155 		char *str;
18156 		int len;
18157 
18158 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18159 			return (EFAULT);
18160 
18161 		mutex_enter(&dtrace_lock);
18162 
18163 		if (fmt.dtfd_format == 0 ||
18164 		    fmt.dtfd_format > state->dts_nformats) {
18165 			mutex_exit(&dtrace_lock);
18166 			return (EINVAL);
18167 		}
18168 
18169 		/*
18170 		 * Format strings are allocated contiguously and they are
18171 		 * never freed; if a format index is less than the number
18172 		 * of formats, we can assert that the format map is non-NULL
18173 		 * and that the format for the specified index is non-NULL.
18174 		 */
18175 		ASSERT(state->dts_formats != NULL);
18176 		str = state->dts_formats[fmt.dtfd_format - 1];
18177 		ASSERT(str != NULL);
18178 
18179 		len = strlen(str) + 1;
18180 
18181 		if (len > fmt.dtfd_length) {
18182 			fmt.dtfd_length = len;
18183 
18184 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18185 				mutex_exit(&dtrace_lock);
18186 				return (EINVAL);
18187 			}
18188 		} else {
18189 			if (copyout(str, fmt.dtfd_string, len) != 0) {
18190 				mutex_exit(&dtrace_lock);
18191 				return (EINVAL);
18192 			}
18193 		}
18194 
18195 		mutex_exit(&dtrace_lock);
18196 		return (0);
18197 	}
18198 
18199 	default:
18200 		break;
18201 	}
18202 
18203 	return (ENOTTY);
18204 }
18205 
18206 /*ARGSUSED*/
18207 static int
18208 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18209 {
18210 	dtrace_state_t *state;
18211 
18212 	switch (cmd) {
18213 	case DDI_DETACH:
18214 		break;
18215 
18216 	case DDI_SUSPEND:
18217 		return (DDI_SUCCESS);
18218 
18219 	default:
18220 		return (DDI_FAILURE);
18221 	}
18222 
18223 	mutex_enter(&cpu_lock);
18224 	mutex_enter(&dtrace_provider_lock);
18225 	mutex_enter(&dtrace_lock);
18226 
18227 	ASSERT(dtrace_opens == 0);
18228 
18229 	if (dtrace_helpers > 0) {
18230 		mutex_exit(&dtrace_provider_lock);
18231 		mutex_exit(&dtrace_lock);
18232 		mutex_exit(&cpu_lock);
18233 		return (DDI_FAILURE);
18234 	}
18235 
18236 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18237 		mutex_exit(&dtrace_provider_lock);
18238 		mutex_exit(&dtrace_lock);
18239 		mutex_exit(&cpu_lock);
18240 		return (DDI_FAILURE);
18241 	}
18242 
18243 	dtrace_provider = NULL;
18244 
18245 	if ((state = dtrace_anon_grab()) != NULL) {
18246 		/*
18247 		 * If there were ECBs on this state, the provider should
18248 		 * have not been allowed to detach; assert that there is
18249 		 * none.
18250 		 */
18251 		ASSERT(state->dts_necbs == 0);
18252 		dtrace_state_destroy(state);
18253 
18254 		/*
18255 		 * If we're being detached with anonymous state, we need to
18256 		 * indicate to the kernel debugger that DTrace is now inactive.
18257 		 */
18258 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18259 	}
18260 
18261 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18262 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18263 	dtrace_cpu_init = NULL;
18264 	dtrace_helpers_cleanup = NULL;
18265 	dtrace_helpers_fork = NULL;
18266 	dtrace_cpustart_init = NULL;
18267 	dtrace_cpustart_fini = NULL;
18268 	dtrace_debugger_init = NULL;
18269 	dtrace_debugger_fini = NULL;
18270 	dtrace_modload = NULL;
18271 	dtrace_modunload = NULL;
18272 
18273 	ASSERT(dtrace_getf == 0);
18274 	ASSERT(dtrace_closef == NULL);
18275 
18276 	mutex_exit(&cpu_lock);
18277 
18278 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18279 	dtrace_probes = NULL;
18280 	dtrace_nprobes = 0;
18281 
18282 	dtrace_hash_destroy(dtrace_bymod);
18283 	dtrace_hash_destroy(dtrace_byfunc);
18284 	dtrace_hash_destroy(dtrace_byname);
18285 	dtrace_bymod = NULL;
18286 	dtrace_byfunc = NULL;
18287 	dtrace_byname = NULL;
18288 
18289 	kmem_cache_destroy(dtrace_state_cache);
18290 	vmem_destroy(dtrace_minor);
18291 	vmem_destroy(dtrace_arena);
18292 
18293 	if (dtrace_toxrange != NULL) {
18294 		kmem_free(dtrace_toxrange,
18295 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18296 		dtrace_toxrange = NULL;
18297 		dtrace_toxranges = 0;
18298 		dtrace_toxranges_max = 0;
18299 	}
18300 
18301 	ddi_remove_minor_node(dtrace_devi, NULL);
18302 	dtrace_devi = NULL;
18303 
18304 	ddi_soft_state_fini(&dtrace_softstate);
18305 
18306 	ASSERT(dtrace_vtime_references == 0);
18307 	ASSERT(dtrace_opens == 0);
18308 	ASSERT(dtrace_retained == NULL);
18309 
18310 	mutex_exit(&dtrace_lock);
18311 	mutex_exit(&dtrace_provider_lock);
18312 
18313 	/*
18314 	 * We don't destroy the task queue until after we have dropped our
18315 	 * locks (taskq_destroy() may block on running tasks).  To prevent
18316 	 * attempting to do work after we have effectively detached but before
18317 	 * the task queue has been destroyed, all tasks dispatched via the
18318 	 * task queue must check that DTrace is still attached before
18319 	 * performing any operation.
18320 	 */
18321 	taskq_destroy(dtrace_taskq);
18322 	dtrace_taskq = NULL;
18323 
18324 	return (DDI_SUCCESS);
18325 }
18326 #endif
18327 
18328 #ifdef illumos
18329 /*ARGSUSED*/
18330 static int
18331 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18332 {
18333 	int error;
18334 
18335 	switch (infocmd) {
18336 	case DDI_INFO_DEVT2DEVINFO:
18337 		*result = (void *)dtrace_devi;
18338 		error = DDI_SUCCESS;
18339 		break;
18340 	case DDI_INFO_DEVT2INSTANCE:
18341 		*result = (void *)0;
18342 		error = DDI_SUCCESS;
18343 		break;
18344 	default:
18345 		error = DDI_FAILURE;
18346 	}
18347 	return (error);
18348 }
18349 #endif
18350 
18351 #ifdef illumos
18352 static struct cb_ops dtrace_cb_ops = {
18353 	dtrace_open,		/* open */
18354 	dtrace_close,		/* close */
18355 	nulldev,		/* strategy */
18356 	nulldev,		/* print */
18357 	nodev,			/* dump */
18358 	nodev,			/* read */
18359 	nodev,			/* write */
18360 	dtrace_ioctl,		/* ioctl */
18361 	nodev,			/* devmap */
18362 	nodev,			/* mmap */
18363 	nodev,			/* segmap */
18364 	nochpoll,		/* poll */
18365 	ddi_prop_op,		/* cb_prop_op */
18366 	0,			/* streamtab  */
18367 	D_NEW | D_MP		/* Driver compatibility flag */
18368 };
18369 
18370 static struct dev_ops dtrace_ops = {
18371 	DEVO_REV,		/* devo_rev */
18372 	0,			/* refcnt */
18373 	dtrace_info,		/* get_dev_info */
18374 	nulldev,		/* identify */
18375 	nulldev,		/* probe */
18376 	dtrace_attach,		/* attach */
18377 	dtrace_detach,		/* detach */
18378 	nodev,			/* reset */
18379 	&dtrace_cb_ops,		/* driver operations */
18380 	NULL,			/* bus operations */
18381 	nodev			/* dev power */
18382 };
18383 
18384 static struct modldrv modldrv = {
18385 	&mod_driverops,		/* module type (this is a pseudo driver) */
18386 	"Dynamic Tracing",	/* name of module */
18387 	&dtrace_ops,		/* driver ops */
18388 };
18389 
18390 static struct modlinkage modlinkage = {
18391 	MODREV_1,
18392 	(void *)&modldrv,
18393 	NULL
18394 };
18395 
18396 int
18397 _init(void)
18398 {
18399 	return (mod_install(&modlinkage));
18400 }
18401 
18402 int
18403 _info(struct modinfo *modinfop)
18404 {
18405 	return (mod_info(&modlinkage, modinfop));
18406 }
18407 
18408 int
18409 _fini(void)
18410 {
18411 	return (mod_remove(&modlinkage));
18412 }
18413 #else
18414 
18415 static d_ioctl_t	dtrace_ioctl;
18416 static d_ioctl_t	dtrace_ioctl_helper;
18417 static void		dtrace_load(void *);
18418 static int		dtrace_unload(void);
18419 static struct cdev	*dtrace_dev;
18420 static struct cdev	*helper_dev;
18421 
18422 void dtrace_invop_init(void);
18423 void dtrace_invop_uninit(void);
18424 
18425 static struct cdevsw dtrace_cdevsw = {
18426 	.d_version	= D_VERSION,
18427 	.d_ioctl	= dtrace_ioctl,
18428 	.d_open		= dtrace_open,
18429 	.d_name		= "dtrace",
18430 };
18431 
18432 static struct cdevsw helper_cdevsw = {
18433 	.d_version	= D_VERSION,
18434 	.d_ioctl	= dtrace_ioctl_helper,
18435 	.d_name		= "helper",
18436 };
18437 
18438 #include <dtrace_anon.c>
18439 #include <dtrace_ioctl.c>
18440 #include <dtrace_load.c>
18441 #include <dtrace_modevent.c>
18442 #include <dtrace_sysctl.c>
18443 #include <dtrace_unload.c>
18444 #include <dtrace_vtime.c>
18445 #include <dtrace_hacks.c>
18446 #include <dtrace_isa.c>
18447 
18448 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18449 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18450 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18451 
18452 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18453 MODULE_VERSION(dtrace, 1);
18454 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
18455 #endif
18456