xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c (revision ff0ba87247820afbdfdc1b307c803f7923d0e4d3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  *
21  * $FreeBSD$
22  */
23 
24 /*
25  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2012 by Delphix. All rights reserved.
28  */
29 
30 /*
31  * DTrace - Dynamic Tracing for Solaris
32  *
33  * This is the implementation of the Solaris Dynamic Tracing framework
34  * (DTrace).  The user-visible interface to DTrace is described at length in
35  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
36  * library, the in-kernel DTrace framework, and the DTrace providers are
37  * described in the block comments in the <sys/dtrace.h> header file.  The
38  * internal architecture of DTrace is described in the block comments in the
39  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
40  * implementation very much assume mastery of all of these sources; if one has
41  * an unanswered question about the implementation, one should consult them
42  * first.
43  *
44  * The functions here are ordered roughly as follows:
45  *
46  *   - Probe context functions
47  *   - Probe hashing functions
48  *   - Non-probe context utility functions
49  *   - Matching functions
50  *   - Provider-to-Framework API functions
51  *   - Probe management functions
52  *   - DIF object functions
53  *   - Format functions
54  *   - Predicate functions
55  *   - ECB functions
56  *   - Buffer functions
57  *   - Enabling functions
58  *   - DOF functions
59  *   - Anonymous enabling functions
60  *   - Consumer state functions
61  *   - Helper functions
62  *   - Hook functions
63  *   - Driver cookbook functions
64  *
65  * Each group of functions begins with a block comment labelled the "DTrace
66  * [Group] Functions", allowing one to find each block by searching forward
67  * on capital-f functions.
68  */
69 #include <sys/errno.h>
70 #if !defined(sun)
71 #include <sys/time.h>
72 #endif
73 #include <sys/stat.h>
74 #include <sys/modctl.h>
75 #include <sys/conf.h>
76 #include <sys/systm.h>
77 #if defined(sun)
78 #include <sys/ddi.h>
79 #include <sys/sunddi.h>
80 #endif
81 #include <sys/cpuvar.h>
82 #include <sys/kmem.h>
83 #if defined(sun)
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 #if defined(sun)
91 #include <sys/mutex_impl.h>
92 #include <sys/rwlock_impl.h>
93 #endif
94 #include <sys/ctf_api.h>
95 #if defined(sun)
96 #include <sys/panic.h>
97 #include <sys/priv_impl.h>
98 #endif
99 #include <sys/policy.h>
100 #if defined(sun)
101 #include <sys/cred_impl.h>
102 #include <sys/procfs_isa.h>
103 #endif
104 #include <sys/taskq.h>
105 #if defined(sun)
106 #include <sys/mkdev.h>
107 #include <sys/kdi.h>
108 #endif
109 #include <sys/zone.h>
110 #include <sys/socket.h>
111 #include <netinet/in.h>
112 #include "strtolctype.h"
113 
114 /* FreeBSD includes: */
115 #if !defined(sun)
116 #include <sys/callout.h>
117 #include <sys/ctype.h>
118 #include <sys/eventhandler.h>
119 #include <sys/limits.h>
120 #include <sys/kdb.h>
121 #include <sys/kernel.h>
122 #include <sys/malloc.h>
123 #include <sys/sysctl.h>
124 #include <sys/lock.h>
125 #include <sys/mutex.h>
126 #include <sys/rwlock.h>
127 #include <sys/sx.h>
128 #include <sys/dtrace_bsd.h>
129 #include <netinet/in.h>
130 #include "dtrace_cddl.h"
131 #include "dtrace_debug.c"
132 #endif
133 
134 /*
135  * DTrace Tunable Variables
136  *
137  * The following variables may be tuned by adding a line to /etc/system that
138  * includes both the name of the DTrace module ("dtrace") and the name of the
139  * variable.  For example:
140  *
141  *   set dtrace:dtrace_destructive_disallow = 1
142  *
143  * In general, the only variables that one should be tuning this way are those
144  * that affect system-wide DTrace behavior, and for which the default behavior
145  * is undesirable.  Most of these variables are tunable on a per-consumer
146  * basis using DTrace options, and need not be tuned on a system-wide basis.
147  * When tuning these variables, avoid pathological values; while some attempt
148  * is made to verify the integrity of these variables, they are not considered
149  * part of the supported interface to DTrace, and they are therefore not
150  * checked comprehensively.  Further, these variables should not be tuned
151  * dynamically via "mdb -kw" or other means; they should only be tuned via
152  * /etc/system.
153  */
154 int		dtrace_destructive_disallow = 0;
155 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
156 size_t		dtrace_difo_maxsize = (256 * 1024);
157 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
158 size_t		dtrace_global_maxsize = (16 * 1024);
159 size_t		dtrace_actions_max = (16 * 1024);
160 size_t		dtrace_retain_max = 1024;
161 dtrace_optval_t	dtrace_helper_actions_max = 128;
162 dtrace_optval_t	dtrace_helper_providers_max = 32;
163 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
164 size_t		dtrace_strsize_default = 256;
165 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
166 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
167 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
168 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
169 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
170 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
171 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
172 dtrace_optval_t	dtrace_nspec_default = 1;
173 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
174 dtrace_optval_t dtrace_stackframes_default = 20;
175 dtrace_optval_t dtrace_ustackframes_default = 20;
176 dtrace_optval_t dtrace_jstackframes_default = 50;
177 dtrace_optval_t dtrace_jstackstrsize_default = 512;
178 int		dtrace_msgdsize_max = 128;
179 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
180 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
181 int		dtrace_devdepth_max = 32;
182 int		dtrace_err_verbose;
183 hrtime_t	dtrace_deadman_interval = NANOSEC;
184 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
185 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
186 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
187 #if !defined(sun)
188 int		dtrace_memstr_max = 4096;
189 #endif
190 
191 /*
192  * DTrace External Variables
193  *
194  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
195  * available to DTrace consumers via the backtick (`) syntax.  One of these,
196  * dtrace_zero, is made deliberately so:  it is provided as a source of
197  * well-known, zero-filled memory.  While this variable is not documented,
198  * it is used by some translators as an implementation detail.
199  */
200 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
201 
202 /*
203  * DTrace Internal Variables
204  */
205 #if defined(sun)
206 static dev_info_t	*dtrace_devi;		/* device info */
207 #endif
208 #if defined(sun)
209 static vmem_t		*dtrace_arena;		/* probe ID arena */
210 static vmem_t		*dtrace_minor;		/* minor number arena */
211 #else
212 static taskq_t		*dtrace_taskq;		/* task queue */
213 static struct unrhdr	*dtrace_arena;		/* Probe ID number.     */
214 #endif
215 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
216 static int		dtrace_nprobes;		/* number of probes */
217 static dtrace_provider_t *dtrace_provider;	/* provider list */
218 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
219 static int		dtrace_opens;		/* number of opens */
220 static int		dtrace_helpers;		/* number of helpers */
221 static int		dtrace_getf;		/* number of unpriv getf()s */
222 #if defined(sun)
223 static void		*dtrace_softstate;	/* softstate pointer */
224 #endif
225 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
226 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
227 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
228 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
229 static int		dtrace_toxranges;	/* number of toxic ranges */
230 static int		dtrace_toxranges_max;	/* size of toxic range array */
231 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
232 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
233 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
234 static kthread_t	*dtrace_panicked;	/* panicking thread */
235 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
236 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
237 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
238 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
239 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
240 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
241 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
242 #if !defined(sun)
243 static struct mtx	dtrace_unr_mtx;
244 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
245 int		dtrace_in_probe;	/* non-zero if executing a probe */
246 #if defined(__i386__) || defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
247 uintptr_t	dtrace_in_probe_addr;	/* Address of invop when already in probe */
248 #endif
249 static eventhandler_tag	dtrace_kld_load_tag;
250 static eventhandler_tag	dtrace_kld_unload_try_tag;
251 #endif
252 
253 /*
254  * DTrace Locking
255  * DTrace is protected by three (relatively coarse-grained) locks:
256  *
257  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
258  *     including enabling state, probes, ECBs, consumer state, helper state,
259  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
260  *     probe context is lock-free -- synchronization is handled via the
261  *     dtrace_sync() cross call mechanism.
262  *
263  * (2) dtrace_provider_lock is required when manipulating provider state, or
264  *     when provider state must be held constant.
265  *
266  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
267  *     when meta provider state must be held constant.
268  *
269  * The lock ordering between these three locks is dtrace_meta_lock before
270  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
271  * several places where dtrace_provider_lock is held by the framework as it
272  * calls into the providers -- which then call back into the framework,
273  * grabbing dtrace_lock.)
274  *
275  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
276  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
277  * role as a coarse-grained lock; it is acquired before both of these locks.
278  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
279  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
280  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
281  * acquired _between_ dtrace_provider_lock and dtrace_lock.
282  */
283 static kmutex_t		dtrace_lock;		/* probe state lock */
284 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
285 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
286 
287 #if !defined(sun)
288 /* XXX FreeBSD hacks. */
289 #define cr_suid		cr_svuid
290 #define cr_sgid		cr_svgid
291 #define	ipaddr_t	in_addr_t
292 #define mod_modname	pathname
293 #define vuprintf	vprintf
294 #define ttoproc(_a)	((_a)->td_proc)
295 #define crgetzoneid(_a)	0
296 #define	NCPU		MAXCPU
297 #define SNOCD		0
298 #define CPU_ON_INTR(_a)	0
299 
300 #define PRIV_EFFECTIVE		(1 << 0)
301 #define PRIV_DTRACE_KERNEL	(1 << 1)
302 #define PRIV_DTRACE_PROC	(1 << 2)
303 #define PRIV_DTRACE_USER	(1 << 3)
304 #define PRIV_PROC_OWNER		(1 << 4)
305 #define PRIV_PROC_ZONE		(1 << 5)
306 #define PRIV_ALL		~0
307 
308 SYSCTL_DECL(_debug_dtrace);
309 SYSCTL_DECL(_kern_dtrace);
310 #endif
311 
312 #if defined(sun)
313 #define curcpu	CPU->cpu_id
314 #endif
315 
316 
317 /*
318  * DTrace Provider Variables
319  *
320  * These are the variables relating to DTrace as a provider (that is, the
321  * provider of the BEGIN, END, and ERROR probes).
322  */
323 static dtrace_pattr_t	dtrace_provider_attr = {
324 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
325 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
326 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
327 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
328 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
329 };
330 
331 static void
332 dtrace_nullop(void)
333 {}
334 
335 static dtrace_pops_t	dtrace_provider_ops = {
336 	(void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
337 	(void (*)(void *, modctl_t *))dtrace_nullop,
338 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
339 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
340 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
341 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
342 	NULL,
343 	NULL,
344 	NULL,
345 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
346 };
347 
348 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
349 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
350 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
351 
352 /*
353  * DTrace Helper Tracing Variables
354  */
355 uint32_t dtrace_helptrace_next = 0;
356 uint32_t dtrace_helptrace_nlocals;
357 char	*dtrace_helptrace_buffer;
358 int	dtrace_helptrace_bufsize = 512 * 1024;
359 
360 #ifdef DEBUG
361 int	dtrace_helptrace_enabled = 1;
362 #else
363 int	dtrace_helptrace_enabled = 0;
364 #endif
365 
366 /*
367  * DTrace Error Hashing
368  *
369  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
370  * table.  This is very useful for checking coverage of tests that are
371  * expected to induce DIF or DOF processing errors, and may be useful for
372  * debugging problems in the DIF code generator or in DOF generation .  The
373  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
374  */
375 #ifdef DEBUG
376 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
377 static const char *dtrace_errlast;
378 static kthread_t *dtrace_errthread;
379 static kmutex_t dtrace_errlock;
380 #endif
381 
382 /*
383  * DTrace Macros and Constants
384  *
385  * These are various macros that are useful in various spots in the
386  * implementation, along with a few random constants that have no meaning
387  * outside of the implementation.  There is no real structure to this cpp
388  * mishmash -- but is there ever?
389  */
390 #define	DTRACE_HASHSTR(hash, probe)	\
391 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
392 
393 #define	DTRACE_HASHNEXT(hash, probe)	\
394 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
395 
396 #define	DTRACE_HASHPREV(hash, probe)	\
397 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
398 
399 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
400 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
401 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
402 
403 #define	DTRACE_AGGHASHSIZE_SLEW		17
404 
405 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
406 
407 /*
408  * The key for a thread-local variable consists of the lower 61 bits of the
409  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
410  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
411  * equal to a variable identifier.  This is necessary (but not sufficient) to
412  * assure that global associative arrays never collide with thread-local
413  * variables.  To guarantee that they cannot collide, we must also define the
414  * order for keying dynamic variables.  That order is:
415  *
416  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
417  *
418  * Because the variable-key and the tls-key are in orthogonal spaces, there is
419  * no way for a global variable key signature to match a thread-local key
420  * signature.
421  */
422 #if defined(sun)
423 #define	DTRACE_TLS_THRKEY(where) { \
424 	uint_t intr = 0; \
425 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
426 	for (; actv; actv >>= 1) \
427 		intr++; \
428 	ASSERT(intr < (1 << 3)); \
429 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
430 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
431 }
432 #else
433 #define	DTRACE_TLS_THRKEY(where) { \
434 	solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
435 	uint_t intr = 0; \
436 	uint_t actv = _c->cpu_intr_actv; \
437 	for (; actv; actv >>= 1) \
438 		intr++; \
439 	ASSERT(intr < (1 << 3)); \
440 	(where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
441 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
442 }
443 #endif
444 
445 #define	DT_BSWAP_8(x)	((x) & 0xff)
446 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
447 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
448 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
449 
450 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
451 
452 #define	DTRACE_STORE(type, tomax, offset, what) \
453 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
454 
455 #ifndef __x86
456 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
457 	if (addr & (size - 1)) {					\
458 		*flags |= CPU_DTRACE_BADALIGN;				\
459 		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
460 		return (0);						\
461 	}
462 #else
463 #define	DTRACE_ALIGNCHECK(addr, size, flags)
464 #endif
465 
466 /*
467  * Test whether a range of memory starting at testaddr of size testsz falls
468  * within the range of memory described by addr, sz.  We take care to avoid
469  * problems with overflow and underflow of the unsigned quantities, and
470  * disallow all negative sizes.  Ranges of size 0 are allowed.
471  */
472 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
473 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
474 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
475 	(testaddr) + (testsz) >= (testaddr))
476 
477 /*
478  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
479  * alloc_sz on the righthand side of the comparison in order to avoid overflow
480  * or underflow in the comparison with it.  This is simpler than the INRANGE
481  * check above, because we know that the dtms_scratch_ptr is valid in the
482  * range.  Allocations of size zero are allowed.
483  */
484 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
485 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
486 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
487 
488 #define	DTRACE_LOADFUNC(bits)						\
489 /*CSTYLED*/								\
490 uint##bits##_t								\
491 dtrace_load##bits(uintptr_t addr)					\
492 {									\
493 	size_t size = bits / NBBY;					\
494 	/*CSTYLED*/							\
495 	uint##bits##_t rval;						\
496 	int i;								\
497 	volatile uint16_t *flags = (volatile uint16_t *)		\
498 	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
499 									\
500 	DTRACE_ALIGNCHECK(addr, size, flags);				\
501 									\
502 	for (i = 0; i < dtrace_toxranges; i++) {			\
503 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
504 			continue;					\
505 									\
506 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
507 			continue;					\
508 									\
509 		/*							\
510 		 * This address falls within a toxic region; return 0.	\
511 		 */							\
512 		*flags |= CPU_DTRACE_BADADDR;				\
513 		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
514 		return (0);						\
515 	}								\
516 									\
517 	*flags |= CPU_DTRACE_NOFAULT;					\
518 	/*CSTYLED*/							\
519 	rval = *((volatile uint##bits##_t *)addr);			\
520 	*flags &= ~CPU_DTRACE_NOFAULT;					\
521 									\
522 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
523 }
524 
525 #ifdef _LP64
526 #define	dtrace_loadptr	dtrace_load64
527 #else
528 #define	dtrace_loadptr	dtrace_load32
529 #endif
530 
531 #define	DTRACE_DYNHASH_FREE	0
532 #define	DTRACE_DYNHASH_SINK	1
533 #define	DTRACE_DYNHASH_VALID	2
534 
535 #define	DTRACE_MATCH_NEXT	0
536 #define	DTRACE_MATCH_DONE	1
537 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
538 #define	DTRACE_STATE_ALIGN	64
539 
540 #define	DTRACE_FLAGS2FLT(flags)						\
541 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
542 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
543 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
544 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
545 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
546 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
547 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
548 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
549 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
550 	DTRACEFLT_UNKNOWN)
551 
552 #define	DTRACEACT_ISSTRING(act)						\
553 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
554 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
555 
556 /* Function prototype definitions: */
557 static size_t dtrace_strlen(const char *, size_t);
558 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
559 static void dtrace_enabling_provide(dtrace_provider_t *);
560 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
561 static void dtrace_enabling_matchall(void);
562 static void dtrace_enabling_reap(void);
563 static dtrace_state_t *dtrace_anon_grab(void);
564 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
565     dtrace_state_t *, uint64_t, uint64_t);
566 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
567 static void dtrace_buffer_drop(dtrace_buffer_t *);
568 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
569 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
570     dtrace_state_t *, dtrace_mstate_t *);
571 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
572     dtrace_optval_t);
573 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
574 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
575 uint16_t dtrace_load16(uintptr_t);
576 uint32_t dtrace_load32(uintptr_t);
577 uint64_t dtrace_load64(uintptr_t);
578 uint8_t dtrace_load8(uintptr_t);
579 void dtrace_dynvar_clean(dtrace_dstate_t *);
580 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
581     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
582 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
583 static int dtrace_priv_proc(dtrace_state_t *);
584 static void dtrace_getf_barrier(void);
585 
586 /*
587  * DTrace Probe Context Functions
588  *
589  * These functions are called from probe context.  Because probe context is
590  * any context in which C may be called, arbitrarily locks may be held,
591  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
592  * As a result, functions called from probe context may only call other DTrace
593  * support functions -- they may not interact at all with the system at large.
594  * (Note that the ASSERT macro is made probe-context safe by redefining it in
595  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
596  * loads are to be performed from probe context, they _must_ be in terms of
597  * the safe dtrace_load*() variants.
598  *
599  * Some functions in this block are not actually called from probe context;
600  * for these functions, there will be a comment above the function reading
601  * "Note:  not called from probe context."
602  */
603 void
604 dtrace_panic(const char *format, ...)
605 {
606 	va_list alist;
607 
608 	va_start(alist, format);
609 	dtrace_vpanic(format, alist);
610 	va_end(alist);
611 }
612 
613 int
614 dtrace_assfail(const char *a, const char *f, int l)
615 {
616 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
617 
618 	/*
619 	 * We just need something here that even the most clever compiler
620 	 * cannot optimize away.
621 	 */
622 	return (a[(uintptr_t)f]);
623 }
624 
625 /*
626  * Atomically increment a specified error counter from probe context.
627  */
628 static void
629 dtrace_error(uint32_t *counter)
630 {
631 	/*
632 	 * Most counters stored to in probe context are per-CPU counters.
633 	 * However, there are some error conditions that are sufficiently
634 	 * arcane that they don't merit per-CPU storage.  If these counters
635 	 * are incremented concurrently on different CPUs, scalability will be
636 	 * adversely affected -- but we don't expect them to be white-hot in a
637 	 * correctly constructed enabling...
638 	 */
639 	uint32_t oval, nval;
640 
641 	do {
642 		oval = *counter;
643 
644 		if ((nval = oval + 1) == 0) {
645 			/*
646 			 * If the counter would wrap, set it to 1 -- assuring
647 			 * that the counter is never zero when we have seen
648 			 * errors.  (The counter must be 32-bits because we
649 			 * aren't guaranteed a 64-bit compare&swap operation.)
650 			 * To save this code both the infamy of being fingered
651 			 * by a priggish news story and the indignity of being
652 			 * the target of a neo-puritan witch trial, we're
653 			 * carefully avoiding any colorful description of the
654 			 * likelihood of this condition -- but suffice it to
655 			 * say that it is only slightly more likely than the
656 			 * overflow of predicate cache IDs, as discussed in
657 			 * dtrace_predicate_create().
658 			 */
659 			nval = 1;
660 		}
661 	} while (dtrace_cas32(counter, oval, nval) != oval);
662 }
663 
664 /*
665  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
666  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
667  */
668 DTRACE_LOADFUNC(8)
669 DTRACE_LOADFUNC(16)
670 DTRACE_LOADFUNC(32)
671 DTRACE_LOADFUNC(64)
672 
673 static int
674 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
675 {
676 	if (dest < mstate->dtms_scratch_base)
677 		return (0);
678 
679 	if (dest + size < dest)
680 		return (0);
681 
682 	if (dest + size > mstate->dtms_scratch_ptr)
683 		return (0);
684 
685 	return (1);
686 }
687 
688 static int
689 dtrace_canstore_statvar(uint64_t addr, size_t sz,
690     dtrace_statvar_t **svars, int nsvars)
691 {
692 	int i;
693 
694 	for (i = 0; i < nsvars; i++) {
695 		dtrace_statvar_t *svar = svars[i];
696 
697 		if (svar == NULL || svar->dtsv_size == 0)
698 			continue;
699 
700 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
701 			return (1);
702 	}
703 
704 	return (0);
705 }
706 
707 /*
708  * Check to see if the address is within a memory region to which a store may
709  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
710  * region.  The caller of dtrace_canstore() is responsible for performing any
711  * alignment checks that are needed before stores are actually executed.
712  */
713 static int
714 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
715     dtrace_vstate_t *vstate)
716 {
717 	/*
718 	 * First, check to see if the address is in scratch space...
719 	 */
720 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
721 	    mstate->dtms_scratch_size))
722 		return (1);
723 
724 	/*
725 	 * Now check to see if it's a dynamic variable.  This check will pick
726 	 * up both thread-local variables and any global dynamically-allocated
727 	 * variables.
728 	 */
729 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
730 	    vstate->dtvs_dynvars.dtds_size)) {
731 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
732 		uintptr_t base = (uintptr_t)dstate->dtds_base +
733 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
734 		uintptr_t chunkoffs;
735 
736 		/*
737 		 * Before we assume that we can store here, we need to make
738 		 * sure that it isn't in our metadata -- storing to our
739 		 * dynamic variable metadata would corrupt our state.  For
740 		 * the range to not include any dynamic variable metadata,
741 		 * it must:
742 		 *
743 		 *	(1) Start above the hash table that is at the base of
744 		 *	the dynamic variable space
745 		 *
746 		 *	(2) Have a starting chunk offset that is beyond the
747 		 *	dtrace_dynvar_t that is at the base of every chunk
748 		 *
749 		 *	(3) Not span a chunk boundary
750 		 *
751 		 */
752 		if (addr < base)
753 			return (0);
754 
755 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
756 
757 		if (chunkoffs < sizeof (dtrace_dynvar_t))
758 			return (0);
759 
760 		if (chunkoffs + sz > dstate->dtds_chunksize)
761 			return (0);
762 
763 		return (1);
764 	}
765 
766 	/*
767 	 * Finally, check the static local and global variables.  These checks
768 	 * take the longest, so we perform them last.
769 	 */
770 	if (dtrace_canstore_statvar(addr, sz,
771 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
772 		return (1);
773 
774 	if (dtrace_canstore_statvar(addr, sz,
775 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
776 		return (1);
777 
778 	return (0);
779 }
780 
781 
782 /*
783  * Convenience routine to check to see if the address is within a memory
784  * region in which a load may be issued given the user's privilege level;
785  * if not, it sets the appropriate error flags and loads 'addr' into the
786  * illegal value slot.
787  *
788  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
789  * appropriate memory access protection.
790  */
791 static int
792 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
793     dtrace_vstate_t *vstate)
794 {
795 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
796 	file_t *fp;
797 
798 	/*
799 	 * If we hold the privilege to read from kernel memory, then
800 	 * everything is readable.
801 	 */
802 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
803 		return (1);
804 
805 	/*
806 	 * You can obviously read that which you can store.
807 	 */
808 	if (dtrace_canstore(addr, sz, mstate, vstate))
809 		return (1);
810 
811 	/*
812 	 * We're allowed to read from our own string table.
813 	 */
814 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
815 	    mstate->dtms_difo->dtdo_strlen))
816 		return (1);
817 
818 	if (vstate->dtvs_state != NULL &&
819 	    dtrace_priv_proc(vstate->dtvs_state)) {
820 		proc_t *p;
821 
822 		/*
823 		 * When we have privileges to the current process, there are
824 		 * several context-related kernel structures that are safe to
825 		 * read, even absent the privilege to read from kernel memory.
826 		 * These reads are safe because these structures contain only
827 		 * state that (1) we're permitted to read, (2) is harmless or
828 		 * (3) contains pointers to additional kernel state that we're
829 		 * not permitted to read (and as such, do not present an
830 		 * opportunity for privilege escalation).  Finally (and
831 		 * critically), because of the nature of their relation with
832 		 * the current thread context, the memory associated with these
833 		 * structures cannot change over the duration of probe context,
834 		 * and it is therefore impossible for this memory to be
835 		 * deallocated and reallocated as something else while it's
836 		 * being operated upon.
837 		 */
838 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
839 			return (1);
840 
841 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
842 		    sz, curthread->t_procp, sizeof (proc_t))) {
843 			return (1);
844 		}
845 
846 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
847 		    curthread->t_cred, sizeof (cred_t))) {
848 			return (1);
849 		}
850 
851 #if defined(sun)
852 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
853 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
854 			return (1);
855 		}
856 
857 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
858 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
859 			return (1);
860 		}
861 #endif
862 	}
863 
864 	if ((fp = mstate->dtms_getf) != NULL) {
865 		uintptr_t psz = sizeof (void *);
866 		vnode_t *vp;
867 		vnodeops_t *op;
868 
869 		/*
870 		 * When getf() returns a file_t, the enabling is implicitly
871 		 * granted the (transient) right to read the returned file_t
872 		 * as well as the v_path and v_op->vnop_name of the underlying
873 		 * vnode.  These accesses are allowed after a successful
874 		 * getf() because the members that they refer to cannot change
875 		 * once set -- and the barrier logic in the kernel's closef()
876 		 * path assures that the file_t and its referenced vode_t
877 		 * cannot themselves be stale (that is, it impossible for
878 		 * either dtms_getf itself or its f_vnode member to reference
879 		 * freed memory).
880 		 */
881 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
882 			return (1);
883 
884 		if ((vp = fp->f_vnode) != NULL) {
885 #if defined(sun)
886 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
887 				return (1);
888 			if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
889 			    vp->v_path, strlen(vp->v_path) + 1)) {
890 				return (1);
891 			}
892 #endif
893 
894 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
895 				return (1);
896 
897 #if defined(sun)
898 			if ((op = vp->v_op) != NULL &&
899 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
900 				return (1);
901 			}
902 
903 			if (op != NULL && op->vnop_name != NULL &&
904 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
905 			    strlen(op->vnop_name) + 1)) {
906 				return (1);
907 			}
908 #endif
909 		}
910 	}
911 
912 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
913 	*illval = addr;
914 	return (0);
915 }
916 
917 /*
918  * Convenience routine to check to see if a given string is within a memory
919  * region in which a load may be issued given the user's privilege level;
920  * this exists so that we don't need to issue unnecessary dtrace_strlen()
921  * calls in the event that the user has all privileges.
922  */
923 static int
924 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
925     dtrace_vstate_t *vstate)
926 {
927 	size_t strsz;
928 
929 	/*
930 	 * If we hold the privilege to read from kernel memory, then
931 	 * everything is readable.
932 	 */
933 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
934 		return (1);
935 
936 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
937 	if (dtrace_canload(addr, strsz, mstate, vstate))
938 		return (1);
939 
940 	return (0);
941 }
942 
943 /*
944  * Convenience routine to check to see if a given variable is within a memory
945  * region in which a load may be issued given the user's privilege level.
946  */
947 static int
948 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
949     dtrace_vstate_t *vstate)
950 {
951 	size_t sz;
952 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
953 
954 	/*
955 	 * If we hold the privilege to read from kernel memory, then
956 	 * everything is readable.
957 	 */
958 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
959 		return (1);
960 
961 	if (type->dtdt_kind == DIF_TYPE_STRING)
962 		sz = dtrace_strlen(src,
963 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
964 	else
965 		sz = type->dtdt_size;
966 
967 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
968 }
969 
970 /*
971  * Convert a string to a signed integer using safe loads.
972  *
973  * NOTE: This function uses various macros from strtolctype.h to manipulate
974  * digit values, etc -- these have all been checked to ensure they make
975  * no additional function calls.
976  */
977 static int64_t
978 dtrace_strtoll(char *input, int base, size_t limit)
979 {
980 	uintptr_t pos = (uintptr_t)input;
981 	int64_t val = 0;
982 	int x;
983 	boolean_t neg = B_FALSE;
984 	char c, cc, ccc;
985 	uintptr_t end = pos + limit;
986 
987 	/*
988 	 * Consume any whitespace preceding digits.
989 	 */
990 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
991 		pos++;
992 
993 	/*
994 	 * Handle an explicit sign if one is present.
995 	 */
996 	if (c == '-' || c == '+') {
997 		if (c == '-')
998 			neg = B_TRUE;
999 		c = dtrace_load8(++pos);
1000 	}
1001 
1002 	/*
1003 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1004 	 * if present.
1005 	 */
1006 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1007 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1008 		pos += 2;
1009 		c = ccc;
1010 	}
1011 
1012 	/*
1013 	 * Read in contiguous digits until the first non-digit character.
1014 	 */
1015 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1016 	    c = dtrace_load8(++pos))
1017 		val = val * base + x;
1018 
1019 	return (neg ? -val : val);
1020 }
1021 
1022 /*
1023  * Compare two strings using safe loads.
1024  */
1025 static int
1026 dtrace_strncmp(char *s1, char *s2, size_t limit)
1027 {
1028 	uint8_t c1, c2;
1029 	volatile uint16_t *flags;
1030 
1031 	if (s1 == s2 || limit == 0)
1032 		return (0);
1033 
1034 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1035 
1036 	do {
1037 		if (s1 == NULL) {
1038 			c1 = '\0';
1039 		} else {
1040 			c1 = dtrace_load8((uintptr_t)s1++);
1041 		}
1042 
1043 		if (s2 == NULL) {
1044 			c2 = '\0';
1045 		} else {
1046 			c2 = dtrace_load8((uintptr_t)s2++);
1047 		}
1048 
1049 		if (c1 != c2)
1050 			return (c1 - c2);
1051 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1052 
1053 	return (0);
1054 }
1055 
1056 /*
1057  * Compute strlen(s) for a string using safe memory accesses.  The additional
1058  * len parameter is used to specify a maximum length to ensure completion.
1059  */
1060 static size_t
1061 dtrace_strlen(const char *s, size_t lim)
1062 {
1063 	uint_t len;
1064 
1065 	for (len = 0; len != lim; len++) {
1066 		if (dtrace_load8((uintptr_t)s++) == '\0')
1067 			break;
1068 	}
1069 
1070 	return (len);
1071 }
1072 
1073 /*
1074  * Check if an address falls within a toxic region.
1075  */
1076 static int
1077 dtrace_istoxic(uintptr_t kaddr, size_t size)
1078 {
1079 	uintptr_t taddr, tsize;
1080 	int i;
1081 
1082 	for (i = 0; i < dtrace_toxranges; i++) {
1083 		taddr = dtrace_toxrange[i].dtt_base;
1084 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1085 
1086 		if (kaddr - taddr < tsize) {
1087 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1088 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1089 			return (1);
1090 		}
1091 
1092 		if (taddr - kaddr < size) {
1093 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1094 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1095 			return (1);
1096 		}
1097 	}
1098 
1099 	return (0);
1100 }
1101 
1102 /*
1103  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1104  * memory specified by the DIF program.  The dst is assumed to be safe memory
1105  * that we can store to directly because it is managed by DTrace.  As with
1106  * standard bcopy, overlapping copies are handled properly.
1107  */
1108 static void
1109 dtrace_bcopy(const void *src, void *dst, size_t len)
1110 {
1111 	if (len != 0) {
1112 		uint8_t *s1 = dst;
1113 		const uint8_t *s2 = src;
1114 
1115 		if (s1 <= s2) {
1116 			do {
1117 				*s1++ = dtrace_load8((uintptr_t)s2++);
1118 			} while (--len != 0);
1119 		} else {
1120 			s2 += len;
1121 			s1 += len;
1122 
1123 			do {
1124 				*--s1 = dtrace_load8((uintptr_t)--s2);
1125 			} while (--len != 0);
1126 		}
1127 	}
1128 }
1129 
1130 /*
1131  * Copy src to dst using safe memory accesses, up to either the specified
1132  * length, or the point that a nul byte is encountered.  The src is assumed to
1133  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1134  * safe memory that we can store to directly because it is managed by DTrace.
1135  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1136  */
1137 static void
1138 dtrace_strcpy(const void *src, void *dst, size_t len)
1139 {
1140 	if (len != 0) {
1141 		uint8_t *s1 = dst, c;
1142 		const uint8_t *s2 = src;
1143 
1144 		do {
1145 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1146 		} while (--len != 0 && c != '\0');
1147 	}
1148 }
1149 
1150 /*
1151  * Copy src to dst, deriving the size and type from the specified (BYREF)
1152  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1153  * program.  The dst is assumed to be DTrace variable memory that is of the
1154  * specified type; we assume that we can store to directly.
1155  */
1156 static void
1157 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1158 {
1159 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1160 
1161 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1162 		dtrace_strcpy(src, dst, type->dtdt_size);
1163 	} else {
1164 		dtrace_bcopy(src, dst, type->dtdt_size);
1165 	}
1166 }
1167 
1168 /*
1169  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1170  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1171  * safe memory that we can access directly because it is managed by DTrace.
1172  */
1173 static int
1174 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1175 {
1176 	volatile uint16_t *flags;
1177 
1178 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1179 
1180 	if (s1 == s2)
1181 		return (0);
1182 
1183 	if (s1 == NULL || s2 == NULL)
1184 		return (1);
1185 
1186 	if (s1 != s2 && len != 0) {
1187 		const uint8_t *ps1 = s1;
1188 		const uint8_t *ps2 = s2;
1189 
1190 		do {
1191 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1192 				return (1);
1193 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1194 	}
1195 	return (0);
1196 }
1197 
1198 /*
1199  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1200  * is for safe DTrace-managed memory only.
1201  */
1202 static void
1203 dtrace_bzero(void *dst, size_t len)
1204 {
1205 	uchar_t *cp;
1206 
1207 	for (cp = dst; len != 0; len--)
1208 		*cp++ = 0;
1209 }
1210 
1211 static void
1212 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1213 {
1214 	uint64_t result[2];
1215 
1216 	result[0] = addend1[0] + addend2[0];
1217 	result[1] = addend1[1] + addend2[1] +
1218 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1219 
1220 	sum[0] = result[0];
1221 	sum[1] = result[1];
1222 }
1223 
1224 /*
1225  * Shift the 128-bit value in a by b. If b is positive, shift left.
1226  * If b is negative, shift right.
1227  */
1228 static void
1229 dtrace_shift_128(uint64_t *a, int b)
1230 {
1231 	uint64_t mask;
1232 
1233 	if (b == 0)
1234 		return;
1235 
1236 	if (b < 0) {
1237 		b = -b;
1238 		if (b >= 64) {
1239 			a[0] = a[1] >> (b - 64);
1240 			a[1] = 0;
1241 		} else {
1242 			a[0] >>= b;
1243 			mask = 1LL << (64 - b);
1244 			mask -= 1;
1245 			a[0] |= ((a[1] & mask) << (64 - b));
1246 			a[1] >>= b;
1247 		}
1248 	} else {
1249 		if (b >= 64) {
1250 			a[1] = a[0] << (b - 64);
1251 			a[0] = 0;
1252 		} else {
1253 			a[1] <<= b;
1254 			mask = a[0] >> (64 - b);
1255 			a[1] |= mask;
1256 			a[0] <<= b;
1257 		}
1258 	}
1259 }
1260 
1261 /*
1262  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1263  * use native multiplication on those, and then re-combine into the
1264  * resulting 128-bit value.
1265  *
1266  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1267  *     hi1 * hi2 << 64 +
1268  *     hi1 * lo2 << 32 +
1269  *     hi2 * lo1 << 32 +
1270  *     lo1 * lo2
1271  */
1272 static void
1273 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1274 {
1275 	uint64_t hi1, hi2, lo1, lo2;
1276 	uint64_t tmp[2];
1277 
1278 	hi1 = factor1 >> 32;
1279 	hi2 = factor2 >> 32;
1280 
1281 	lo1 = factor1 & DT_MASK_LO;
1282 	lo2 = factor2 & DT_MASK_LO;
1283 
1284 	product[0] = lo1 * lo2;
1285 	product[1] = hi1 * hi2;
1286 
1287 	tmp[0] = hi1 * lo2;
1288 	tmp[1] = 0;
1289 	dtrace_shift_128(tmp, 32);
1290 	dtrace_add_128(product, tmp, product);
1291 
1292 	tmp[0] = hi2 * lo1;
1293 	tmp[1] = 0;
1294 	dtrace_shift_128(tmp, 32);
1295 	dtrace_add_128(product, tmp, product);
1296 }
1297 
1298 /*
1299  * This privilege check should be used by actions and subroutines to
1300  * verify that the user credentials of the process that enabled the
1301  * invoking ECB match the target credentials
1302  */
1303 static int
1304 dtrace_priv_proc_common_user(dtrace_state_t *state)
1305 {
1306 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1307 
1308 	/*
1309 	 * We should always have a non-NULL state cred here, since if cred
1310 	 * is null (anonymous tracing), we fast-path bypass this routine.
1311 	 */
1312 	ASSERT(s_cr != NULL);
1313 
1314 	if ((cr = CRED()) != NULL &&
1315 	    s_cr->cr_uid == cr->cr_uid &&
1316 	    s_cr->cr_uid == cr->cr_ruid &&
1317 	    s_cr->cr_uid == cr->cr_suid &&
1318 	    s_cr->cr_gid == cr->cr_gid &&
1319 	    s_cr->cr_gid == cr->cr_rgid &&
1320 	    s_cr->cr_gid == cr->cr_sgid)
1321 		return (1);
1322 
1323 	return (0);
1324 }
1325 
1326 /*
1327  * This privilege check should be used by actions and subroutines to
1328  * verify that the zone of the process that enabled the invoking ECB
1329  * matches the target credentials
1330  */
1331 static int
1332 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1333 {
1334 #if defined(sun)
1335 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1336 
1337 	/*
1338 	 * We should always have a non-NULL state cred here, since if cred
1339 	 * is null (anonymous tracing), we fast-path bypass this routine.
1340 	 */
1341 	ASSERT(s_cr != NULL);
1342 
1343 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1344 		return (1);
1345 
1346 	return (0);
1347 #else
1348 	return (1);
1349 #endif
1350 }
1351 
1352 /*
1353  * This privilege check should be used by actions and subroutines to
1354  * verify that the process has not setuid or changed credentials.
1355  */
1356 static int
1357 dtrace_priv_proc_common_nocd(void)
1358 {
1359 	proc_t *proc;
1360 
1361 	if ((proc = ttoproc(curthread)) != NULL &&
1362 	    !(proc->p_flag & SNOCD))
1363 		return (1);
1364 
1365 	return (0);
1366 }
1367 
1368 static int
1369 dtrace_priv_proc_destructive(dtrace_state_t *state)
1370 {
1371 	int action = state->dts_cred.dcr_action;
1372 
1373 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1374 	    dtrace_priv_proc_common_zone(state) == 0)
1375 		goto bad;
1376 
1377 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1378 	    dtrace_priv_proc_common_user(state) == 0)
1379 		goto bad;
1380 
1381 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1382 	    dtrace_priv_proc_common_nocd() == 0)
1383 		goto bad;
1384 
1385 	return (1);
1386 
1387 bad:
1388 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1389 
1390 	return (0);
1391 }
1392 
1393 static int
1394 dtrace_priv_proc_control(dtrace_state_t *state)
1395 {
1396 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1397 		return (1);
1398 
1399 	if (dtrace_priv_proc_common_zone(state) &&
1400 	    dtrace_priv_proc_common_user(state) &&
1401 	    dtrace_priv_proc_common_nocd())
1402 		return (1);
1403 
1404 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1405 
1406 	return (0);
1407 }
1408 
1409 static int
1410 dtrace_priv_proc(dtrace_state_t *state)
1411 {
1412 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1413 		return (1);
1414 
1415 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1416 
1417 	return (0);
1418 }
1419 
1420 static int
1421 dtrace_priv_kernel(dtrace_state_t *state)
1422 {
1423 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1424 		return (1);
1425 
1426 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1427 
1428 	return (0);
1429 }
1430 
1431 static int
1432 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1433 {
1434 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1435 		return (1);
1436 
1437 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1438 
1439 	return (0);
1440 }
1441 
1442 /*
1443  * Determine if the dte_cond of the specified ECB allows for processing of
1444  * the current probe to continue.  Note that this routine may allow continued
1445  * processing, but with access(es) stripped from the mstate's dtms_access
1446  * field.
1447  */
1448 static int
1449 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1450     dtrace_ecb_t *ecb)
1451 {
1452 	dtrace_probe_t *probe = ecb->dte_probe;
1453 	dtrace_provider_t *prov = probe->dtpr_provider;
1454 	dtrace_pops_t *pops = &prov->dtpv_pops;
1455 	int mode = DTRACE_MODE_NOPRIV_DROP;
1456 
1457 	ASSERT(ecb->dte_cond);
1458 
1459 #if defined(sun)
1460 	if (pops->dtps_mode != NULL) {
1461 		mode = pops->dtps_mode(prov->dtpv_arg,
1462 		    probe->dtpr_id, probe->dtpr_arg);
1463 
1464 		ASSERT((mode & DTRACE_MODE_USER) ||
1465 		    (mode & DTRACE_MODE_KERNEL));
1466 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1467 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1468 	}
1469 
1470 	/*
1471 	 * If the dte_cond bits indicate that this consumer is only allowed to
1472 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1473 	 * entry point to check that the probe was fired while in a user
1474 	 * context.  If that's not the case, use the policy specified by the
1475 	 * provider to determine if we drop the probe or merely restrict
1476 	 * operation.
1477 	 */
1478 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1479 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1480 
1481 		if (!(mode & DTRACE_MODE_USER)) {
1482 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1483 				return (0);
1484 
1485 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1486 		}
1487 	}
1488 #endif
1489 
1490 	/*
1491 	 * This is more subtle than it looks. We have to be absolutely certain
1492 	 * that CRED() isn't going to change out from under us so it's only
1493 	 * legit to examine that structure if we're in constrained situations.
1494 	 * Currently, the only times we'll this check is if a non-super-user
1495 	 * has enabled the profile or syscall providers -- providers that
1496 	 * allow visibility of all processes. For the profile case, the check
1497 	 * above will ensure that we're examining a user context.
1498 	 */
1499 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1500 		cred_t *cr;
1501 		cred_t *s_cr = state->dts_cred.dcr_cred;
1502 		proc_t *proc;
1503 
1504 		ASSERT(s_cr != NULL);
1505 
1506 		if ((cr = CRED()) == NULL ||
1507 		    s_cr->cr_uid != cr->cr_uid ||
1508 		    s_cr->cr_uid != cr->cr_ruid ||
1509 		    s_cr->cr_uid != cr->cr_suid ||
1510 		    s_cr->cr_gid != cr->cr_gid ||
1511 		    s_cr->cr_gid != cr->cr_rgid ||
1512 		    s_cr->cr_gid != cr->cr_sgid ||
1513 		    (proc = ttoproc(curthread)) == NULL ||
1514 		    (proc->p_flag & SNOCD)) {
1515 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1516 				return (0);
1517 
1518 #if defined(sun)
1519 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1520 #endif
1521 		}
1522 	}
1523 
1524 #if defined(sun)
1525 	/*
1526 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1527 	 * in our zone, check to see if our mode policy is to restrict rather
1528 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1529 	 * and DTRACE_ACCESS_ARGS
1530 	 */
1531 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1532 		cred_t *cr;
1533 		cred_t *s_cr = state->dts_cred.dcr_cred;
1534 
1535 		ASSERT(s_cr != NULL);
1536 
1537 		if ((cr = CRED()) == NULL ||
1538 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1539 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1540 				return (0);
1541 
1542 			mstate->dtms_access &=
1543 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1544 		}
1545 	}
1546 #endif
1547 
1548 	return (1);
1549 }
1550 
1551 /*
1552  * Note:  not called from probe context.  This function is called
1553  * asynchronously (and at a regular interval) from outside of probe context to
1554  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1555  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1556  */
1557 void
1558 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1559 {
1560 	dtrace_dynvar_t *dirty;
1561 	dtrace_dstate_percpu_t *dcpu;
1562 	dtrace_dynvar_t **rinsep;
1563 	int i, j, work = 0;
1564 
1565 	for (i = 0; i < NCPU; i++) {
1566 		dcpu = &dstate->dtds_percpu[i];
1567 		rinsep = &dcpu->dtdsc_rinsing;
1568 
1569 		/*
1570 		 * If the dirty list is NULL, there is no dirty work to do.
1571 		 */
1572 		if (dcpu->dtdsc_dirty == NULL)
1573 			continue;
1574 
1575 		if (dcpu->dtdsc_rinsing != NULL) {
1576 			/*
1577 			 * If the rinsing list is non-NULL, then it is because
1578 			 * this CPU was selected to accept another CPU's
1579 			 * dirty list -- and since that time, dirty buffers
1580 			 * have accumulated.  This is a highly unlikely
1581 			 * condition, but we choose to ignore the dirty
1582 			 * buffers -- they'll be picked up a future cleanse.
1583 			 */
1584 			continue;
1585 		}
1586 
1587 		if (dcpu->dtdsc_clean != NULL) {
1588 			/*
1589 			 * If the clean list is non-NULL, then we're in a
1590 			 * situation where a CPU has done deallocations (we
1591 			 * have a non-NULL dirty list) but no allocations (we
1592 			 * also have a non-NULL clean list).  We can't simply
1593 			 * move the dirty list into the clean list on this
1594 			 * CPU, yet we also don't want to allow this condition
1595 			 * to persist, lest a short clean list prevent a
1596 			 * massive dirty list from being cleaned (which in
1597 			 * turn could lead to otherwise avoidable dynamic
1598 			 * drops).  To deal with this, we look for some CPU
1599 			 * with a NULL clean list, NULL dirty list, and NULL
1600 			 * rinsing list -- and then we borrow this CPU to
1601 			 * rinse our dirty list.
1602 			 */
1603 			for (j = 0; j < NCPU; j++) {
1604 				dtrace_dstate_percpu_t *rinser;
1605 
1606 				rinser = &dstate->dtds_percpu[j];
1607 
1608 				if (rinser->dtdsc_rinsing != NULL)
1609 					continue;
1610 
1611 				if (rinser->dtdsc_dirty != NULL)
1612 					continue;
1613 
1614 				if (rinser->dtdsc_clean != NULL)
1615 					continue;
1616 
1617 				rinsep = &rinser->dtdsc_rinsing;
1618 				break;
1619 			}
1620 
1621 			if (j == NCPU) {
1622 				/*
1623 				 * We were unable to find another CPU that
1624 				 * could accept this dirty list -- we are
1625 				 * therefore unable to clean it now.
1626 				 */
1627 				dtrace_dynvar_failclean++;
1628 				continue;
1629 			}
1630 		}
1631 
1632 		work = 1;
1633 
1634 		/*
1635 		 * Atomically move the dirty list aside.
1636 		 */
1637 		do {
1638 			dirty = dcpu->dtdsc_dirty;
1639 
1640 			/*
1641 			 * Before we zap the dirty list, set the rinsing list.
1642 			 * (This allows for a potential assertion in
1643 			 * dtrace_dynvar():  if a free dynamic variable appears
1644 			 * on a hash chain, either the dirty list or the
1645 			 * rinsing list for some CPU must be non-NULL.)
1646 			 */
1647 			*rinsep = dirty;
1648 			dtrace_membar_producer();
1649 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1650 		    dirty, NULL) != dirty);
1651 	}
1652 
1653 	if (!work) {
1654 		/*
1655 		 * We have no work to do; we can simply return.
1656 		 */
1657 		return;
1658 	}
1659 
1660 	dtrace_sync();
1661 
1662 	for (i = 0; i < NCPU; i++) {
1663 		dcpu = &dstate->dtds_percpu[i];
1664 
1665 		if (dcpu->dtdsc_rinsing == NULL)
1666 			continue;
1667 
1668 		/*
1669 		 * We are now guaranteed that no hash chain contains a pointer
1670 		 * into this dirty list; we can make it clean.
1671 		 */
1672 		ASSERT(dcpu->dtdsc_clean == NULL);
1673 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1674 		dcpu->dtdsc_rinsing = NULL;
1675 	}
1676 
1677 	/*
1678 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1679 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1680 	 * This prevents a race whereby a CPU incorrectly decides that
1681 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1682 	 * after dtrace_dynvar_clean() has completed.
1683 	 */
1684 	dtrace_sync();
1685 
1686 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1687 }
1688 
1689 /*
1690  * Depending on the value of the op parameter, this function looks-up,
1691  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1692  * allocation is requested, this function will return a pointer to a
1693  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1694  * variable can be allocated.  If NULL is returned, the appropriate counter
1695  * will be incremented.
1696  */
1697 dtrace_dynvar_t *
1698 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1699     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1700     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1701 {
1702 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1703 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1704 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1705 	processorid_t me = curcpu, cpu = me;
1706 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1707 	size_t bucket, ksize;
1708 	size_t chunksize = dstate->dtds_chunksize;
1709 	uintptr_t kdata, lock, nstate;
1710 	uint_t i;
1711 
1712 	ASSERT(nkeys != 0);
1713 
1714 	/*
1715 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1716 	 * algorithm.  For the by-value portions, we perform the algorithm in
1717 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1718 	 * bit, and seems to have only a minute effect on distribution.  For
1719 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1720 	 * over each referenced byte.  It's painful to do this, but it's much
1721 	 * better than pathological hash distribution.  The efficacy of the
1722 	 * hashing algorithm (and a comparison with other algorithms) may be
1723 	 * found by running the ::dtrace_dynstat MDB dcmd.
1724 	 */
1725 	for (i = 0; i < nkeys; i++) {
1726 		if (key[i].dttk_size == 0) {
1727 			uint64_t val = key[i].dttk_value;
1728 
1729 			hashval += (val >> 48) & 0xffff;
1730 			hashval += (hashval << 10);
1731 			hashval ^= (hashval >> 6);
1732 
1733 			hashval += (val >> 32) & 0xffff;
1734 			hashval += (hashval << 10);
1735 			hashval ^= (hashval >> 6);
1736 
1737 			hashval += (val >> 16) & 0xffff;
1738 			hashval += (hashval << 10);
1739 			hashval ^= (hashval >> 6);
1740 
1741 			hashval += val & 0xffff;
1742 			hashval += (hashval << 10);
1743 			hashval ^= (hashval >> 6);
1744 		} else {
1745 			/*
1746 			 * This is incredibly painful, but it beats the hell
1747 			 * out of the alternative.
1748 			 */
1749 			uint64_t j, size = key[i].dttk_size;
1750 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1751 
1752 			if (!dtrace_canload(base, size, mstate, vstate))
1753 				break;
1754 
1755 			for (j = 0; j < size; j++) {
1756 				hashval += dtrace_load8(base + j);
1757 				hashval += (hashval << 10);
1758 				hashval ^= (hashval >> 6);
1759 			}
1760 		}
1761 	}
1762 
1763 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1764 		return (NULL);
1765 
1766 	hashval += (hashval << 3);
1767 	hashval ^= (hashval >> 11);
1768 	hashval += (hashval << 15);
1769 
1770 	/*
1771 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1772 	 * comes out to be one of our two sentinel hash values.  If this
1773 	 * actually happens, we set the hashval to be a value known to be a
1774 	 * non-sentinel value.
1775 	 */
1776 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1777 		hashval = DTRACE_DYNHASH_VALID;
1778 
1779 	/*
1780 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1781 	 * important here, tricks can be pulled to reduce it.  (However, it's
1782 	 * critical that hash collisions be kept to an absolute minimum;
1783 	 * they're much more painful than a divide.)  It's better to have a
1784 	 * solution that generates few collisions and still keeps things
1785 	 * relatively simple.
1786 	 */
1787 	bucket = hashval % dstate->dtds_hashsize;
1788 
1789 	if (op == DTRACE_DYNVAR_DEALLOC) {
1790 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1791 
1792 		for (;;) {
1793 			while ((lock = *lockp) & 1)
1794 				continue;
1795 
1796 			if (dtrace_casptr((volatile void *)lockp,
1797 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1798 				break;
1799 		}
1800 
1801 		dtrace_membar_producer();
1802 	}
1803 
1804 top:
1805 	prev = NULL;
1806 	lock = hash[bucket].dtdh_lock;
1807 
1808 	dtrace_membar_consumer();
1809 
1810 	start = hash[bucket].dtdh_chain;
1811 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1812 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1813 	    op != DTRACE_DYNVAR_DEALLOC));
1814 
1815 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1816 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1817 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1818 
1819 		if (dvar->dtdv_hashval != hashval) {
1820 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1821 				/*
1822 				 * We've reached the sink, and therefore the
1823 				 * end of the hash chain; we can kick out of
1824 				 * the loop knowing that we have seen a valid
1825 				 * snapshot of state.
1826 				 */
1827 				ASSERT(dvar->dtdv_next == NULL);
1828 				ASSERT(dvar == &dtrace_dynhash_sink);
1829 				break;
1830 			}
1831 
1832 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1833 				/*
1834 				 * We've gone off the rails:  somewhere along
1835 				 * the line, one of the members of this hash
1836 				 * chain was deleted.  Note that we could also
1837 				 * detect this by simply letting this loop run
1838 				 * to completion, as we would eventually hit
1839 				 * the end of the dirty list.  However, we
1840 				 * want to avoid running the length of the
1841 				 * dirty list unnecessarily (it might be quite
1842 				 * long), so we catch this as early as
1843 				 * possible by detecting the hash marker.  In
1844 				 * this case, we simply set dvar to NULL and
1845 				 * break; the conditional after the loop will
1846 				 * send us back to top.
1847 				 */
1848 				dvar = NULL;
1849 				break;
1850 			}
1851 
1852 			goto next;
1853 		}
1854 
1855 		if (dtuple->dtt_nkeys != nkeys)
1856 			goto next;
1857 
1858 		for (i = 0; i < nkeys; i++, dkey++) {
1859 			if (dkey->dttk_size != key[i].dttk_size)
1860 				goto next; /* size or type mismatch */
1861 
1862 			if (dkey->dttk_size != 0) {
1863 				if (dtrace_bcmp(
1864 				    (void *)(uintptr_t)key[i].dttk_value,
1865 				    (void *)(uintptr_t)dkey->dttk_value,
1866 				    dkey->dttk_size))
1867 					goto next;
1868 			} else {
1869 				if (dkey->dttk_value != key[i].dttk_value)
1870 					goto next;
1871 			}
1872 		}
1873 
1874 		if (op != DTRACE_DYNVAR_DEALLOC)
1875 			return (dvar);
1876 
1877 		ASSERT(dvar->dtdv_next == NULL ||
1878 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1879 
1880 		if (prev != NULL) {
1881 			ASSERT(hash[bucket].dtdh_chain != dvar);
1882 			ASSERT(start != dvar);
1883 			ASSERT(prev->dtdv_next == dvar);
1884 			prev->dtdv_next = dvar->dtdv_next;
1885 		} else {
1886 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1887 			    start, dvar->dtdv_next) != start) {
1888 				/*
1889 				 * We have failed to atomically swing the
1890 				 * hash table head pointer, presumably because
1891 				 * of a conflicting allocation on another CPU.
1892 				 * We need to reread the hash chain and try
1893 				 * again.
1894 				 */
1895 				goto top;
1896 			}
1897 		}
1898 
1899 		dtrace_membar_producer();
1900 
1901 		/*
1902 		 * Now set the hash value to indicate that it's free.
1903 		 */
1904 		ASSERT(hash[bucket].dtdh_chain != dvar);
1905 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1906 
1907 		dtrace_membar_producer();
1908 
1909 		/*
1910 		 * Set the next pointer to point at the dirty list, and
1911 		 * atomically swing the dirty pointer to the newly freed dvar.
1912 		 */
1913 		do {
1914 			next = dcpu->dtdsc_dirty;
1915 			dvar->dtdv_next = next;
1916 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1917 
1918 		/*
1919 		 * Finally, unlock this hash bucket.
1920 		 */
1921 		ASSERT(hash[bucket].dtdh_lock == lock);
1922 		ASSERT(lock & 1);
1923 		hash[bucket].dtdh_lock++;
1924 
1925 		return (NULL);
1926 next:
1927 		prev = dvar;
1928 		continue;
1929 	}
1930 
1931 	if (dvar == NULL) {
1932 		/*
1933 		 * If dvar is NULL, it is because we went off the rails:
1934 		 * one of the elements that we traversed in the hash chain
1935 		 * was deleted while we were traversing it.  In this case,
1936 		 * we assert that we aren't doing a dealloc (deallocs lock
1937 		 * the hash bucket to prevent themselves from racing with
1938 		 * one another), and retry the hash chain traversal.
1939 		 */
1940 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1941 		goto top;
1942 	}
1943 
1944 	if (op != DTRACE_DYNVAR_ALLOC) {
1945 		/*
1946 		 * If we are not to allocate a new variable, we want to
1947 		 * return NULL now.  Before we return, check that the value
1948 		 * of the lock word hasn't changed.  If it has, we may have
1949 		 * seen an inconsistent snapshot.
1950 		 */
1951 		if (op == DTRACE_DYNVAR_NOALLOC) {
1952 			if (hash[bucket].dtdh_lock != lock)
1953 				goto top;
1954 		} else {
1955 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1956 			ASSERT(hash[bucket].dtdh_lock == lock);
1957 			ASSERT(lock & 1);
1958 			hash[bucket].dtdh_lock++;
1959 		}
1960 
1961 		return (NULL);
1962 	}
1963 
1964 	/*
1965 	 * We need to allocate a new dynamic variable.  The size we need is the
1966 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1967 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1968 	 * the size of any referred-to data (dsize).  We then round the final
1969 	 * size up to the chunksize for allocation.
1970 	 */
1971 	for (ksize = 0, i = 0; i < nkeys; i++)
1972 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1973 
1974 	/*
1975 	 * This should be pretty much impossible, but could happen if, say,
1976 	 * strange DIF specified the tuple.  Ideally, this should be an
1977 	 * assertion and not an error condition -- but that requires that the
1978 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1979 	 * bullet-proof.  (That is, it must not be able to be fooled by
1980 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1981 	 * solving this would presumably not amount to solving the Halting
1982 	 * Problem -- but it still seems awfully hard.
1983 	 */
1984 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1985 	    ksize + dsize > chunksize) {
1986 		dcpu->dtdsc_drops++;
1987 		return (NULL);
1988 	}
1989 
1990 	nstate = DTRACE_DSTATE_EMPTY;
1991 
1992 	do {
1993 retry:
1994 		free = dcpu->dtdsc_free;
1995 
1996 		if (free == NULL) {
1997 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1998 			void *rval;
1999 
2000 			if (clean == NULL) {
2001 				/*
2002 				 * We're out of dynamic variable space on
2003 				 * this CPU.  Unless we have tried all CPUs,
2004 				 * we'll try to allocate from a different
2005 				 * CPU.
2006 				 */
2007 				switch (dstate->dtds_state) {
2008 				case DTRACE_DSTATE_CLEAN: {
2009 					void *sp = &dstate->dtds_state;
2010 
2011 					if (++cpu >= NCPU)
2012 						cpu = 0;
2013 
2014 					if (dcpu->dtdsc_dirty != NULL &&
2015 					    nstate == DTRACE_DSTATE_EMPTY)
2016 						nstate = DTRACE_DSTATE_DIRTY;
2017 
2018 					if (dcpu->dtdsc_rinsing != NULL)
2019 						nstate = DTRACE_DSTATE_RINSING;
2020 
2021 					dcpu = &dstate->dtds_percpu[cpu];
2022 
2023 					if (cpu != me)
2024 						goto retry;
2025 
2026 					(void) dtrace_cas32(sp,
2027 					    DTRACE_DSTATE_CLEAN, nstate);
2028 
2029 					/*
2030 					 * To increment the correct bean
2031 					 * counter, take another lap.
2032 					 */
2033 					goto retry;
2034 				}
2035 
2036 				case DTRACE_DSTATE_DIRTY:
2037 					dcpu->dtdsc_dirty_drops++;
2038 					break;
2039 
2040 				case DTRACE_DSTATE_RINSING:
2041 					dcpu->dtdsc_rinsing_drops++;
2042 					break;
2043 
2044 				case DTRACE_DSTATE_EMPTY:
2045 					dcpu->dtdsc_drops++;
2046 					break;
2047 				}
2048 
2049 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2050 				return (NULL);
2051 			}
2052 
2053 			/*
2054 			 * The clean list appears to be non-empty.  We want to
2055 			 * move the clean list to the free list; we start by
2056 			 * moving the clean pointer aside.
2057 			 */
2058 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2059 			    clean, NULL) != clean) {
2060 				/*
2061 				 * We are in one of two situations:
2062 				 *
2063 				 *  (a)	The clean list was switched to the
2064 				 *	free list by another CPU.
2065 				 *
2066 				 *  (b)	The clean list was added to by the
2067 				 *	cleansing cyclic.
2068 				 *
2069 				 * In either of these situations, we can
2070 				 * just reattempt the free list allocation.
2071 				 */
2072 				goto retry;
2073 			}
2074 
2075 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2076 
2077 			/*
2078 			 * Now we'll move the clean list to our free list.
2079 			 * It's impossible for this to fail:  the only way
2080 			 * the free list can be updated is through this
2081 			 * code path, and only one CPU can own the clean list.
2082 			 * Thus, it would only be possible for this to fail if
2083 			 * this code were racing with dtrace_dynvar_clean().
2084 			 * (That is, if dtrace_dynvar_clean() updated the clean
2085 			 * list, and we ended up racing to update the free
2086 			 * list.)  This race is prevented by the dtrace_sync()
2087 			 * in dtrace_dynvar_clean() -- which flushes the
2088 			 * owners of the clean lists out before resetting
2089 			 * the clean lists.
2090 			 */
2091 			dcpu = &dstate->dtds_percpu[me];
2092 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2093 			ASSERT(rval == NULL);
2094 			goto retry;
2095 		}
2096 
2097 		dvar = free;
2098 		new_free = dvar->dtdv_next;
2099 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2100 
2101 	/*
2102 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2103 	 * tuple array and copy any referenced key data into the data space
2104 	 * following the tuple array.  As we do this, we relocate dttk_value
2105 	 * in the final tuple to point to the key data address in the chunk.
2106 	 */
2107 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2108 	dvar->dtdv_data = (void *)(kdata + ksize);
2109 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2110 
2111 	for (i = 0; i < nkeys; i++) {
2112 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2113 		size_t kesize = key[i].dttk_size;
2114 
2115 		if (kesize != 0) {
2116 			dtrace_bcopy(
2117 			    (const void *)(uintptr_t)key[i].dttk_value,
2118 			    (void *)kdata, kesize);
2119 			dkey->dttk_value = kdata;
2120 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2121 		} else {
2122 			dkey->dttk_value = key[i].dttk_value;
2123 		}
2124 
2125 		dkey->dttk_size = kesize;
2126 	}
2127 
2128 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2129 	dvar->dtdv_hashval = hashval;
2130 	dvar->dtdv_next = start;
2131 
2132 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2133 		return (dvar);
2134 
2135 	/*
2136 	 * The cas has failed.  Either another CPU is adding an element to
2137 	 * this hash chain, or another CPU is deleting an element from this
2138 	 * hash chain.  The simplest way to deal with both of these cases
2139 	 * (though not necessarily the most efficient) is to free our
2140 	 * allocated block and tail-call ourselves.  Note that the free is
2141 	 * to the dirty list and _not_ to the free list.  This is to prevent
2142 	 * races with allocators, above.
2143 	 */
2144 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2145 
2146 	dtrace_membar_producer();
2147 
2148 	do {
2149 		free = dcpu->dtdsc_dirty;
2150 		dvar->dtdv_next = free;
2151 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2152 
2153 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2154 }
2155 
2156 /*ARGSUSED*/
2157 static void
2158 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2159 {
2160 	if ((int64_t)nval < (int64_t)*oval)
2161 		*oval = nval;
2162 }
2163 
2164 /*ARGSUSED*/
2165 static void
2166 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2167 {
2168 	if ((int64_t)nval > (int64_t)*oval)
2169 		*oval = nval;
2170 }
2171 
2172 static void
2173 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2174 {
2175 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2176 	int64_t val = (int64_t)nval;
2177 
2178 	if (val < 0) {
2179 		for (i = 0; i < zero; i++) {
2180 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2181 				quanta[i] += incr;
2182 				return;
2183 			}
2184 		}
2185 	} else {
2186 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2187 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2188 				quanta[i - 1] += incr;
2189 				return;
2190 			}
2191 		}
2192 
2193 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2194 		return;
2195 	}
2196 
2197 	ASSERT(0);
2198 }
2199 
2200 static void
2201 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2202 {
2203 	uint64_t arg = *lquanta++;
2204 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2205 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2206 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2207 	int32_t val = (int32_t)nval, level;
2208 
2209 	ASSERT(step != 0);
2210 	ASSERT(levels != 0);
2211 
2212 	if (val < base) {
2213 		/*
2214 		 * This is an underflow.
2215 		 */
2216 		lquanta[0] += incr;
2217 		return;
2218 	}
2219 
2220 	level = (val - base) / step;
2221 
2222 	if (level < levels) {
2223 		lquanta[level + 1] += incr;
2224 		return;
2225 	}
2226 
2227 	/*
2228 	 * This is an overflow.
2229 	 */
2230 	lquanta[levels + 1] += incr;
2231 }
2232 
2233 static int
2234 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2235     uint16_t high, uint16_t nsteps, int64_t value)
2236 {
2237 	int64_t this = 1, last, next;
2238 	int base = 1, order;
2239 
2240 	ASSERT(factor <= nsteps);
2241 	ASSERT(nsteps % factor == 0);
2242 
2243 	for (order = 0; order < low; order++)
2244 		this *= factor;
2245 
2246 	/*
2247 	 * If our value is less than our factor taken to the power of the
2248 	 * low order of magnitude, it goes into the zeroth bucket.
2249 	 */
2250 	if (value < (last = this))
2251 		return (0);
2252 
2253 	for (this *= factor; order <= high; order++) {
2254 		int nbuckets = this > nsteps ? nsteps : this;
2255 
2256 		if ((next = this * factor) < this) {
2257 			/*
2258 			 * We should not generally get log/linear quantizations
2259 			 * with a high magnitude that allows 64-bits to
2260 			 * overflow, but we nonetheless protect against this
2261 			 * by explicitly checking for overflow, and clamping
2262 			 * our value accordingly.
2263 			 */
2264 			value = this - 1;
2265 		}
2266 
2267 		if (value < this) {
2268 			/*
2269 			 * If our value lies within this order of magnitude,
2270 			 * determine its position by taking the offset within
2271 			 * the order of magnitude, dividing by the bucket
2272 			 * width, and adding to our (accumulated) base.
2273 			 */
2274 			return (base + (value - last) / (this / nbuckets));
2275 		}
2276 
2277 		base += nbuckets - (nbuckets / factor);
2278 		last = this;
2279 		this = next;
2280 	}
2281 
2282 	/*
2283 	 * Our value is greater than or equal to our factor taken to the
2284 	 * power of one plus the high magnitude -- return the top bucket.
2285 	 */
2286 	return (base);
2287 }
2288 
2289 static void
2290 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2291 {
2292 	uint64_t arg = *llquanta++;
2293 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2294 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2295 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2296 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2297 
2298 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2299 	    low, high, nsteps, nval)] += incr;
2300 }
2301 
2302 /*ARGSUSED*/
2303 static void
2304 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2305 {
2306 	data[0]++;
2307 	data[1] += nval;
2308 }
2309 
2310 /*ARGSUSED*/
2311 static void
2312 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2313 {
2314 	int64_t snval = (int64_t)nval;
2315 	uint64_t tmp[2];
2316 
2317 	data[0]++;
2318 	data[1] += nval;
2319 
2320 	/*
2321 	 * What we want to say here is:
2322 	 *
2323 	 * data[2] += nval * nval;
2324 	 *
2325 	 * But given that nval is 64-bit, we could easily overflow, so
2326 	 * we do this as 128-bit arithmetic.
2327 	 */
2328 	if (snval < 0)
2329 		snval = -snval;
2330 
2331 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2332 	dtrace_add_128(data + 2, tmp, data + 2);
2333 }
2334 
2335 /*ARGSUSED*/
2336 static void
2337 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2338 {
2339 	*oval = *oval + 1;
2340 }
2341 
2342 /*ARGSUSED*/
2343 static void
2344 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2345 {
2346 	*oval += nval;
2347 }
2348 
2349 /*
2350  * Aggregate given the tuple in the principal data buffer, and the aggregating
2351  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2352  * buffer is specified as the buf parameter.  This routine does not return
2353  * failure; if there is no space in the aggregation buffer, the data will be
2354  * dropped, and a corresponding counter incremented.
2355  */
2356 static void
2357 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2358     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2359 {
2360 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2361 	uint32_t i, ndx, size, fsize;
2362 	uint32_t align = sizeof (uint64_t) - 1;
2363 	dtrace_aggbuffer_t *agb;
2364 	dtrace_aggkey_t *key;
2365 	uint32_t hashval = 0, limit, isstr;
2366 	caddr_t tomax, data, kdata;
2367 	dtrace_actkind_t action;
2368 	dtrace_action_t *act;
2369 	uintptr_t offs;
2370 
2371 	if (buf == NULL)
2372 		return;
2373 
2374 	if (!agg->dtag_hasarg) {
2375 		/*
2376 		 * Currently, only quantize() and lquantize() take additional
2377 		 * arguments, and they have the same semantics:  an increment
2378 		 * value that defaults to 1 when not present.  If additional
2379 		 * aggregating actions take arguments, the setting of the
2380 		 * default argument value will presumably have to become more
2381 		 * sophisticated...
2382 		 */
2383 		arg = 1;
2384 	}
2385 
2386 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2387 	size = rec->dtrd_offset - agg->dtag_base;
2388 	fsize = size + rec->dtrd_size;
2389 
2390 	ASSERT(dbuf->dtb_tomax != NULL);
2391 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2392 
2393 	if ((tomax = buf->dtb_tomax) == NULL) {
2394 		dtrace_buffer_drop(buf);
2395 		return;
2396 	}
2397 
2398 	/*
2399 	 * The metastructure is always at the bottom of the buffer.
2400 	 */
2401 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2402 	    sizeof (dtrace_aggbuffer_t));
2403 
2404 	if (buf->dtb_offset == 0) {
2405 		/*
2406 		 * We just kludge up approximately 1/8th of the size to be
2407 		 * buckets.  If this guess ends up being routinely
2408 		 * off-the-mark, we may need to dynamically readjust this
2409 		 * based on past performance.
2410 		 */
2411 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2412 
2413 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2414 		    (uintptr_t)tomax || hashsize == 0) {
2415 			/*
2416 			 * We've been given a ludicrously small buffer;
2417 			 * increment our drop count and leave.
2418 			 */
2419 			dtrace_buffer_drop(buf);
2420 			return;
2421 		}
2422 
2423 		/*
2424 		 * And now, a pathetic attempt to try to get a an odd (or
2425 		 * perchance, a prime) hash size for better hash distribution.
2426 		 */
2427 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2428 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2429 
2430 		agb->dtagb_hashsize = hashsize;
2431 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2432 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2433 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2434 
2435 		for (i = 0; i < agb->dtagb_hashsize; i++)
2436 			agb->dtagb_hash[i] = NULL;
2437 	}
2438 
2439 	ASSERT(agg->dtag_first != NULL);
2440 	ASSERT(agg->dtag_first->dta_intuple);
2441 
2442 	/*
2443 	 * Calculate the hash value based on the key.  Note that we _don't_
2444 	 * include the aggid in the hashing (but we will store it as part of
2445 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2446 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2447 	 * gets good distribution in practice.  The efficacy of the hashing
2448 	 * algorithm (and a comparison with other algorithms) may be found by
2449 	 * running the ::dtrace_aggstat MDB dcmd.
2450 	 */
2451 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2452 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2453 		limit = i + act->dta_rec.dtrd_size;
2454 		ASSERT(limit <= size);
2455 		isstr = DTRACEACT_ISSTRING(act);
2456 
2457 		for (; i < limit; i++) {
2458 			hashval += data[i];
2459 			hashval += (hashval << 10);
2460 			hashval ^= (hashval >> 6);
2461 
2462 			if (isstr && data[i] == '\0')
2463 				break;
2464 		}
2465 	}
2466 
2467 	hashval += (hashval << 3);
2468 	hashval ^= (hashval >> 11);
2469 	hashval += (hashval << 15);
2470 
2471 	/*
2472 	 * Yes, the divide here is expensive -- but it's generally the least
2473 	 * of the performance issues given the amount of data that we iterate
2474 	 * over to compute hash values, compare data, etc.
2475 	 */
2476 	ndx = hashval % agb->dtagb_hashsize;
2477 
2478 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2479 		ASSERT((caddr_t)key >= tomax);
2480 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2481 
2482 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2483 			continue;
2484 
2485 		kdata = key->dtak_data;
2486 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2487 
2488 		for (act = agg->dtag_first; act->dta_intuple;
2489 		    act = act->dta_next) {
2490 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2491 			limit = i + act->dta_rec.dtrd_size;
2492 			ASSERT(limit <= size);
2493 			isstr = DTRACEACT_ISSTRING(act);
2494 
2495 			for (; i < limit; i++) {
2496 				if (kdata[i] != data[i])
2497 					goto next;
2498 
2499 				if (isstr && data[i] == '\0')
2500 					break;
2501 			}
2502 		}
2503 
2504 		if (action != key->dtak_action) {
2505 			/*
2506 			 * We are aggregating on the same value in the same
2507 			 * aggregation with two different aggregating actions.
2508 			 * (This should have been picked up in the compiler,
2509 			 * so we may be dealing with errant or devious DIF.)
2510 			 * This is an error condition; we indicate as much,
2511 			 * and return.
2512 			 */
2513 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2514 			return;
2515 		}
2516 
2517 		/*
2518 		 * This is a hit:  we need to apply the aggregator to
2519 		 * the value at this key.
2520 		 */
2521 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2522 		return;
2523 next:
2524 		continue;
2525 	}
2526 
2527 	/*
2528 	 * We didn't find it.  We need to allocate some zero-filled space,
2529 	 * link it into the hash table appropriately, and apply the aggregator
2530 	 * to the (zero-filled) value.
2531 	 */
2532 	offs = buf->dtb_offset;
2533 	while (offs & (align - 1))
2534 		offs += sizeof (uint32_t);
2535 
2536 	/*
2537 	 * If we don't have enough room to both allocate a new key _and_
2538 	 * its associated data, increment the drop count and return.
2539 	 */
2540 	if ((uintptr_t)tomax + offs + fsize >
2541 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2542 		dtrace_buffer_drop(buf);
2543 		return;
2544 	}
2545 
2546 	/*CONSTCOND*/
2547 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2548 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2549 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2550 
2551 	key->dtak_data = kdata = tomax + offs;
2552 	buf->dtb_offset = offs + fsize;
2553 
2554 	/*
2555 	 * Now copy the data across.
2556 	 */
2557 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2558 
2559 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2560 		kdata[i] = data[i];
2561 
2562 	/*
2563 	 * Because strings are not zeroed out by default, we need to iterate
2564 	 * looking for actions that store strings, and we need to explicitly
2565 	 * pad these strings out with zeroes.
2566 	 */
2567 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2568 		int nul;
2569 
2570 		if (!DTRACEACT_ISSTRING(act))
2571 			continue;
2572 
2573 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2574 		limit = i + act->dta_rec.dtrd_size;
2575 		ASSERT(limit <= size);
2576 
2577 		for (nul = 0; i < limit; i++) {
2578 			if (nul) {
2579 				kdata[i] = '\0';
2580 				continue;
2581 			}
2582 
2583 			if (data[i] != '\0')
2584 				continue;
2585 
2586 			nul = 1;
2587 		}
2588 	}
2589 
2590 	for (i = size; i < fsize; i++)
2591 		kdata[i] = 0;
2592 
2593 	key->dtak_hashval = hashval;
2594 	key->dtak_size = size;
2595 	key->dtak_action = action;
2596 	key->dtak_next = agb->dtagb_hash[ndx];
2597 	agb->dtagb_hash[ndx] = key;
2598 
2599 	/*
2600 	 * Finally, apply the aggregator.
2601 	 */
2602 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2603 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2604 }
2605 
2606 /*
2607  * Given consumer state, this routine finds a speculation in the INACTIVE
2608  * state and transitions it into the ACTIVE state.  If there is no speculation
2609  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2610  * incremented -- it is up to the caller to take appropriate action.
2611  */
2612 static int
2613 dtrace_speculation(dtrace_state_t *state)
2614 {
2615 	int i = 0;
2616 	dtrace_speculation_state_t current;
2617 	uint32_t *stat = &state->dts_speculations_unavail, count;
2618 
2619 	while (i < state->dts_nspeculations) {
2620 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2621 
2622 		current = spec->dtsp_state;
2623 
2624 		if (current != DTRACESPEC_INACTIVE) {
2625 			if (current == DTRACESPEC_COMMITTINGMANY ||
2626 			    current == DTRACESPEC_COMMITTING ||
2627 			    current == DTRACESPEC_DISCARDING)
2628 				stat = &state->dts_speculations_busy;
2629 			i++;
2630 			continue;
2631 		}
2632 
2633 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2634 		    current, DTRACESPEC_ACTIVE) == current)
2635 			return (i + 1);
2636 	}
2637 
2638 	/*
2639 	 * We couldn't find a speculation.  If we found as much as a single
2640 	 * busy speculation buffer, we'll attribute this failure as "busy"
2641 	 * instead of "unavail".
2642 	 */
2643 	do {
2644 		count = *stat;
2645 	} while (dtrace_cas32(stat, count, count + 1) != count);
2646 
2647 	return (0);
2648 }
2649 
2650 /*
2651  * This routine commits an active speculation.  If the specified speculation
2652  * is not in a valid state to perform a commit(), this routine will silently do
2653  * nothing.  The state of the specified speculation is transitioned according
2654  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2655  */
2656 static void
2657 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2658     dtrace_specid_t which)
2659 {
2660 	dtrace_speculation_t *spec;
2661 	dtrace_buffer_t *src, *dest;
2662 	uintptr_t daddr, saddr, dlimit, slimit;
2663 	dtrace_speculation_state_t current, new = 0;
2664 	intptr_t offs;
2665 	uint64_t timestamp;
2666 
2667 	if (which == 0)
2668 		return;
2669 
2670 	if (which > state->dts_nspeculations) {
2671 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2672 		return;
2673 	}
2674 
2675 	spec = &state->dts_speculations[which - 1];
2676 	src = &spec->dtsp_buffer[cpu];
2677 	dest = &state->dts_buffer[cpu];
2678 
2679 	do {
2680 		current = spec->dtsp_state;
2681 
2682 		if (current == DTRACESPEC_COMMITTINGMANY)
2683 			break;
2684 
2685 		switch (current) {
2686 		case DTRACESPEC_INACTIVE:
2687 		case DTRACESPEC_DISCARDING:
2688 			return;
2689 
2690 		case DTRACESPEC_COMMITTING:
2691 			/*
2692 			 * This is only possible if we are (a) commit()'ing
2693 			 * without having done a prior speculate() on this CPU
2694 			 * and (b) racing with another commit() on a different
2695 			 * CPU.  There's nothing to do -- we just assert that
2696 			 * our offset is 0.
2697 			 */
2698 			ASSERT(src->dtb_offset == 0);
2699 			return;
2700 
2701 		case DTRACESPEC_ACTIVE:
2702 			new = DTRACESPEC_COMMITTING;
2703 			break;
2704 
2705 		case DTRACESPEC_ACTIVEONE:
2706 			/*
2707 			 * This speculation is active on one CPU.  If our
2708 			 * buffer offset is non-zero, we know that the one CPU
2709 			 * must be us.  Otherwise, we are committing on a
2710 			 * different CPU from the speculate(), and we must
2711 			 * rely on being asynchronously cleaned.
2712 			 */
2713 			if (src->dtb_offset != 0) {
2714 				new = DTRACESPEC_COMMITTING;
2715 				break;
2716 			}
2717 			/*FALLTHROUGH*/
2718 
2719 		case DTRACESPEC_ACTIVEMANY:
2720 			new = DTRACESPEC_COMMITTINGMANY;
2721 			break;
2722 
2723 		default:
2724 			ASSERT(0);
2725 		}
2726 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2727 	    current, new) != current);
2728 
2729 	/*
2730 	 * We have set the state to indicate that we are committing this
2731 	 * speculation.  Now reserve the necessary space in the destination
2732 	 * buffer.
2733 	 */
2734 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2735 	    sizeof (uint64_t), state, NULL)) < 0) {
2736 		dtrace_buffer_drop(dest);
2737 		goto out;
2738 	}
2739 
2740 	/*
2741 	 * We have sufficient space to copy the speculative buffer into the
2742 	 * primary buffer.  First, modify the speculative buffer, filling
2743 	 * in the timestamp of all entries with the current time.  The data
2744 	 * must have the commit() time rather than the time it was traced,
2745 	 * so that all entries in the primary buffer are in timestamp order.
2746 	 */
2747 	timestamp = dtrace_gethrtime();
2748 	saddr = (uintptr_t)src->dtb_tomax;
2749 	slimit = saddr + src->dtb_offset;
2750 	while (saddr < slimit) {
2751 		size_t size;
2752 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2753 
2754 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2755 			saddr += sizeof (dtrace_epid_t);
2756 			continue;
2757 		}
2758 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2759 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2760 
2761 		ASSERT3U(saddr + size, <=, slimit);
2762 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2763 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2764 
2765 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2766 
2767 		saddr += size;
2768 	}
2769 
2770 	/*
2771 	 * Copy the buffer across.  (Note that this is a
2772 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2773 	 * a serious performance issue, a high-performance DTrace-specific
2774 	 * bcopy() should obviously be invented.)
2775 	 */
2776 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2777 	dlimit = daddr + src->dtb_offset;
2778 	saddr = (uintptr_t)src->dtb_tomax;
2779 
2780 	/*
2781 	 * First, the aligned portion.
2782 	 */
2783 	while (dlimit - daddr >= sizeof (uint64_t)) {
2784 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2785 
2786 		daddr += sizeof (uint64_t);
2787 		saddr += sizeof (uint64_t);
2788 	}
2789 
2790 	/*
2791 	 * Now any left-over bit...
2792 	 */
2793 	while (dlimit - daddr)
2794 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2795 
2796 	/*
2797 	 * Finally, commit the reserved space in the destination buffer.
2798 	 */
2799 	dest->dtb_offset = offs + src->dtb_offset;
2800 
2801 out:
2802 	/*
2803 	 * If we're lucky enough to be the only active CPU on this speculation
2804 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2805 	 */
2806 	if (current == DTRACESPEC_ACTIVE ||
2807 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2808 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2809 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2810 
2811 		ASSERT(rval == DTRACESPEC_COMMITTING);
2812 	}
2813 
2814 	src->dtb_offset = 0;
2815 	src->dtb_xamot_drops += src->dtb_drops;
2816 	src->dtb_drops = 0;
2817 }
2818 
2819 /*
2820  * This routine discards an active speculation.  If the specified speculation
2821  * is not in a valid state to perform a discard(), this routine will silently
2822  * do nothing.  The state of the specified speculation is transitioned
2823  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2824  */
2825 static void
2826 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2827     dtrace_specid_t which)
2828 {
2829 	dtrace_speculation_t *spec;
2830 	dtrace_speculation_state_t current, new = 0;
2831 	dtrace_buffer_t *buf;
2832 
2833 	if (which == 0)
2834 		return;
2835 
2836 	if (which > state->dts_nspeculations) {
2837 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2838 		return;
2839 	}
2840 
2841 	spec = &state->dts_speculations[which - 1];
2842 	buf = &spec->dtsp_buffer[cpu];
2843 
2844 	do {
2845 		current = spec->dtsp_state;
2846 
2847 		switch (current) {
2848 		case DTRACESPEC_INACTIVE:
2849 		case DTRACESPEC_COMMITTINGMANY:
2850 		case DTRACESPEC_COMMITTING:
2851 		case DTRACESPEC_DISCARDING:
2852 			return;
2853 
2854 		case DTRACESPEC_ACTIVE:
2855 		case DTRACESPEC_ACTIVEMANY:
2856 			new = DTRACESPEC_DISCARDING;
2857 			break;
2858 
2859 		case DTRACESPEC_ACTIVEONE:
2860 			if (buf->dtb_offset != 0) {
2861 				new = DTRACESPEC_INACTIVE;
2862 			} else {
2863 				new = DTRACESPEC_DISCARDING;
2864 			}
2865 			break;
2866 
2867 		default:
2868 			ASSERT(0);
2869 		}
2870 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2871 	    current, new) != current);
2872 
2873 	buf->dtb_offset = 0;
2874 	buf->dtb_drops = 0;
2875 }
2876 
2877 /*
2878  * Note:  not called from probe context.  This function is called
2879  * asynchronously from cross call context to clean any speculations that are
2880  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2881  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2882  * speculation.
2883  */
2884 static void
2885 dtrace_speculation_clean_here(dtrace_state_t *state)
2886 {
2887 	dtrace_icookie_t cookie;
2888 	processorid_t cpu = curcpu;
2889 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2890 	dtrace_specid_t i;
2891 
2892 	cookie = dtrace_interrupt_disable();
2893 
2894 	if (dest->dtb_tomax == NULL) {
2895 		dtrace_interrupt_enable(cookie);
2896 		return;
2897 	}
2898 
2899 	for (i = 0; i < state->dts_nspeculations; i++) {
2900 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2901 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2902 
2903 		if (src->dtb_tomax == NULL)
2904 			continue;
2905 
2906 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2907 			src->dtb_offset = 0;
2908 			continue;
2909 		}
2910 
2911 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2912 			continue;
2913 
2914 		if (src->dtb_offset == 0)
2915 			continue;
2916 
2917 		dtrace_speculation_commit(state, cpu, i + 1);
2918 	}
2919 
2920 	dtrace_interrupt_enable(cookie);
2921 }
2922 
2923 /*
2924  * Note:  not called from probe context.  This function is called
2925  * asynchronously (and at a regular interval) to clean any speculations that
2926  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2927  * is work to be done, it cross calls all CPUs to perform that work;
2928  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2929  * INACTIVE state until they have been cleaned by all CPUs.
2930  */
2931 static void
2932 dtrace_speculation_clean(dtrace_state_t *state)
2933 {
2934 	int work = 0, rv;
2935 	dtrace_specid_t i;
2936 
2937 	for (i = 0; i < state->dts_nspeculations; i++) {
2938 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2939 
2940 		ASSERT(!spec->dtsp_cleaning);
2941 
2942 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2943 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2944 			continue;
2945 
2946 		work++;
2947 		spec->dtsp_cleaning = 1;
2948 	}
2949 
2950 	if (!work)
2951 		return;
2952 
2953 	dtrace_xcall(DTRACE_CPUALL,
2954 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2955 
2956 	/*
2957 	 * We now know that all CPUs have committed or discarded their
2958 	 * speculation buffers, as appropriate.  We can now set the state
2959 	 * to inactive.
2960 	 */
2961 	for (i = 0; i < state->dts_nspeculations; i++) {
2962 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2963 		dtrace_speculation_state_t current, new;
2964 
2965 		if (!spec->dtsp_cleaning)
2966 			continue;
2967 
2968 		current = spec->dtsp_state;
2969 		ASSERT(current == DTRACESPEC_DISCARDING ||
2970 		    current == DTRACESPEC_COMMITTINGMANY);
2971 
2972 		new = DTRACESPEC_INACTIVE;
2973 
2974 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2975 		ASSERT(rv == current);
2976 		spec->dtsp_cleaning = 0;
2977 	}
2978 }
2979 
2980 /*
2981  * Called as part of a speculate() to get the speculative buffer associated
2982  * with a given speculation.  Returns NULL if the specified speculation is not
2983  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2984  * the active CPU is not the specified CPU -- the speculation will be
2985  * atomically transitioned into the ACTIVEMANY state.
2986  */
2987 static dtrace_buffer_t *
2988 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2989     dtrace_specid_t which)
2990 {
2991 	dtrace_speculation_t *spec;
2992 	dtrace_speculation_state_t current, new = 0;
2993 	dtrace_buffer_t *buf;
2994 
2995 	if (which == 0)
2996 		return (NULL);
2997 
2998 	if (which > state->dts_nspeculations) {
2999 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3000 		return (NULL);
3001 	}
3002 
3003 	spec = &state->dts_speculations[which - 1];
3004 	buf = &spec->dtsp_buffer[cpuid];
3005 
3006 	do {
3007 		current = spec->dtsp_state;
3008 
3009 		switch (current) {
3010 		case DTRACESPEC_INACTIVE:
3011 		case DTRACESPEC_COMMITTINGMANY:
3012 		case DTRACESPEC_DISCARDING:
3013 			return (NULL);
3014 
3015 		case DTRACESPEC_COMMITTING:
3016 			ASSERT(buf->dtb_offset == 0);
3017 			return (NULL);
3018 
3019 		case DTRACESPEC_ACTIVEONE:
3020 			/*
3021 			 * This speculation is currently active on one CPU.
3022 			 * Check the offset in the buffer; if it's non-zero,
3023 			 * that CPU must be us (and we leave the state alone).
3024 			 * If it's zero, assume that we're starting on a new
3025 			 * CPU -- and change the state to indicate that the
3026 			 * speculation is active on more than one CPU.
3027 			 */
3028 			if (buf->dtb_offset != 0)
3029 				return (buf);
3030 
3031 			new = DTRACESPEC_ACTIVEMANY;
3032 			break;
3033 
3034 		case DTRACESPEC_ACTIVEMANY:
3035 			return (buf);
3036 
3037 		case DTRACESPEC_ACTIVE:
3038 			new = DTRACESPEC_ACTIVEONE;
3039 			break;
3040 
3041 		default:
3042 			ASSERT(0);
3043 		}
3044 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3045 	    current, new) != current);
3046 
3047 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3048 	return (buf);
3049 }
3050 
3051 /*
3052  * Return a string.  In the event that the user lacks the privilege to access
3053  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3054  * don't fail access checking.
3055  *
3056  * dtrace_dif_variable() uses this routine as a helper for various
3057  * builtin values such as 'execname' and 'probefunc.'
3058  */
3059 uintptr_t
3060 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3061     dtrace_mstate_t *mstate)
3062 {
3063 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3064 	uintptr_t ret;
3065 	size_t strsz;
3066 
3067 	/*
3068 	 * The easy case: this probe is allowed to read all of memory, so
3069 	 * we can just return this as a vanilla pointer.
3070 	 */
3071 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3072 		return (addr);
3073 
3074 	/*
3075 	 * This is the tougher case: we copy the string in question from
3076 	 * kernel memory into scratch memory and return it that way: this
3077 	 * ensures that we won't trip up when access checking tests the
3078 	 * BYREF return value.
3079 	 */
3080 	strsz = dtrace_strlen((char *)addr, size) + 1;
3081 
3082 	if (mstate->dtms_scratch_ptr + strsz >
3083 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3084 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3085 		return (0);
3086 	}
3087 
3088 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3089 	    strsz);
3090 	ret = mstate->dtms_scratch_ptr;
3091 	mstate->dtms_scratch_ptr += strsz;
3092 	return (ret);
3093 }
3094 
3095 /*
3096  * Return a string from a memoy address which is known to have one or
3097  * more concatenated, individually zero terminated, sub-strings.
3098  * In the event that the user lacks the privilege to access
3099  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3100  * don't fail access checking.
3101  *
3102  * dtrace_dif_variable() uses this routine as a helper for various
3103  * builtin values such as 'execargs'.
3104  */
3105 static uintptr_t
3106 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3107     dtrace_mstate_t *mstate)
3108 {
3109 	char *p;
3110 	size_t i;
3111 	uintptr_t ret;
3112 
3113 	if (mstate->dtms_scratch_ptr + strsz >
3114 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3115 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3116 		return (0);
3117 	}
3118 
3119 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3120 	    strsz);
3121 
3122 	/* Replace sub-string termination characters with a space. */
3123 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3124 	    p++, i++)
3125 		if (*p == '\0')
3126 			*p = ' ';
3127 
3128 	ret = mstate->dtms_scratch_ptr;
3129 	mstate->dtms_scratch_ptr += strsz;
3130 	return (ret);
3131 }
3132 
3133 /*
3134  * This function implements the DIF emulator's variable lookups.  The emulator
3135  * passes a reserved variable identifier and optional built-in array index.
3136  */
3137 static uint64_t
3138 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3139     uint64_t ndx)
3140 {
3141 	/*
3142 	 * If we're accessing one of the uncached arguments, we'll turn this
3143 	 * into a reference in the args array.
3144 	 */
3145 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3146 		ndx = v - DIF_VAR_ARG0;
3147 		v = DIF_VAR_ARGS;
3148 	}
3149 
3150 	switch (v) {
3151 	case DIF_VAR_ARGS:
3152 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3153 		if (ndx >= sizeof (mstate->dtms_arg) /
3154 		    sizeof (mstate->dtms_arg[0])) {
3155 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3156 			dtrace_provider_t *pv;
3157 			uint64_t val;
3158 
3159 			pv = mstate->dtms_probe->dtpr_provider;
3160 			if (pv->dtpv_pops.dtps_getargval != NULL)
3161 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3162 				    mstate->dtms_probe->dtpr_id,
3163 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3164 			else
3165 				val = dtrace_getarg(ndx, aframes);
3166 
3167 			/*
3168 			 * This is regrettably required to keep the compiler
3169 			 * from tail-optimizing the call to dtrace_getarg().
3170 			 * The condition always evaluates to true, but the
3171 			 * compiler has no way of figuring that out a priori.
3172 			 * (None of this would be necessary if the compiler
3173 			 * could be relied upon to _always_ tail-optimize
3174 			 * the call to dtrace_getarg() -- but it can't.)
3175 			 */
3176 			if (mstate->dtms_probe != NULL)
3177 				return (val);
3178 
3179 			ASSERT(0);
3180 		}
3181 
3182 		return (mstate->dtms_arg[ndx]);
3183 
3184 #if defined(sun)
3185 	case DIF_VAR_UREGS: {
3186 		klwp_t *lwp;
3187 
3188 		if (!dtrace_priv_proc(state))
3189 			return (0);
3190 
3191 		if ((lwp = curthread->t_lwp) == NULL) {
3192 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3193 			cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3194 			return (0);
3195 		}
3196 
3197 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3198 		return (0);
3199 	}
3200 #else
3201 	case DIF_VAR_UREGS: {
3202 		struct trapframe *tframe;
3203 
3204 		if (!dtrace_priv_proc(state))
3205 			return (0);
3206 
3207 		if ((tframe = curthread->td_frame) == NULL) {
3208 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3209 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
3210 			return (0);
3211 		}
3212 
3213 		return (dtrace_getreg(tframe, ndx));
3214 	}
3215 #endif
3216 
3217 	case DIF_VAR_CURTHREAD:
3218 		if (!dtrace_priv_proc(state))
3219 			return (0);
3220 		return ((uint64_t)(uintptr_t)curthread);
3221 
3222 	case DIF_VAR_TIMESTAMP:
3223 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3224 			mstate->dtms_timestamp = dtrace_gethrtime();
3225 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3226 		}
3227 		return (mstate->dtms_timestamp);
3228 
3229 	case DIF_VAR_VTIMESTAMP:
3230 		ASSERT(dtrace_vtime_references != 0);
3231 		return (curthread->t_dtrace_vtime);
3232 
3233 	case DIF_VAR_WALLTIMESTAMP:
3234 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3235 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3236 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3237 		}
3238 		return (mstate->dtms_walltimestamp);
3239 
3240 #if defined(sun)
3241 	case DIF_VAR_IPL:
3242 		if (!dtrace_priv_kernel(state))
3243 			return (0);
3244 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3245 			mstate->dtms_ipl = dtrace_getipl();
3246 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3247 		}
3248 		return (mstate->dtms_ipl);
3249 #endif
3250 
3251 	case DIF_VAR_EPID:
3252 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3253 		return (mstate->dtms_epid);
3254 
3255 	case DIF_VAR_ID:
3256 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3257 		return (mstate->dtms_probe->dtpr_id);
3258 
3259 	case DIF_VAR_STACKDEPTH:
3260 		if (!dtrace_priv_kernel(state))
3261 			return (0);
3262 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3263 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3264 
3265 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3266 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3267 		}
3268 		return (mstate->dtms_stackdepth);
3269 
3270 	case DIF_VAR_USTACKDEPTH:
3271 		if (!dtrace_priv_proc(state))
3272 			return (0);
3273 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3274 			/*
3275 			 * See comment in DIF_VAR_PID.
3276 			 */
3277 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3278 			    CPU_ON_INTR(CPU)) {
3279 				mstate->dtms_ustackdepth = 0;
3280 			} else {
3281 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3282 				mstate->dtms_ustackdepth =
3283 				    dtrace_getustackdepth();
3284 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3285 			}
3286 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3287 		}
3288 		return (mstate->dtms_ustackdepth);
3289 
3290 	case DIF_VAR_CALLER:
3291 		if (!dtrace_priv_kernel(state))
3292 			return (0);
3293 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3294 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3295 
3296 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3297 				/*
3298 				 * If this is an unanchored probe, we are
3299 				 * required to go through the slow path:
3300 				 * dtrace_caller() only guarantees correct
3301 				 * results for anchored probes.
3302 				 */
3303 				pc_t caller[2] = {0, 0};
3304 
3305 				dtrace_getpcstack(caller, 2, aframes,
3306 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3307 				mstate->dtms_caller = caller[1];
3308 			} else if ((mstate->dtms_caller =
3309 			    dtrace_caller(aframes)) == -1) {
3310 				/*
3311 				 * We have failed to do this the quick way;
3312 				 * we must resort to the slower approach of
3313 				 * calling dtrace_getpcstack().
3314 				 */
3315 				pc_t caller = 0;
3316 
3317 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3318 				mstate->dtms_caller = caller;
3319 			}
3320 
3321 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3322 		}
3323 		return (mstate->dtms_caller);
3324 
3325 	case DIF_VAR_UCALLER:
3326 		if (!dtrace_priv_proc(state))
3327 			return (0);
3328 
3329 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3330 			uint64_t ustack[3];
3331 
3332 			/*
3333 			 * dtrace_getupcstack() fills in the first uint64_t
3334 			 * with the current PID.  The second uint64_t will
3335 			 * be the program counter at user-level.  The third
3336 			 * uint64_t will contain the caller, which is what
3337 			 * we're after.
3338 			 */
3339 			ustack[2] = 0;
3340 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3341 			dtrace_getupcstack(ustack, 3);
3342 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3343 			mstate->dtms_ucaller = ustack[2];
3344 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3345 		}
3346 
3347 		return (mstate->dtms_ucaller);
3348 
3349 	case DIF_VAR_PROBEPROV:
3350 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3351 		return (dtrace_dif_varstr(
3352 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3353 		    state, mstate));
3354 
3355 	case DIF_VAR_PROBEMOD:
3356 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3357 		return (dtrace_dif_varstr(
3358 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3359 		    state, mstate));
3360 
3361 	case DIF_VAR_PROBEFUNC:
3362 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3363 		return (dtrace_dif_varstr(
3364 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3365 		    state, mstate));
3366 
3367 	case DIF_VAR_PROBENAME:
3368 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3369 		return (dtrace_dif_varstr(
3370 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3371 		    state, mstate));
3372 
3373 	case DIF_VAR_PID:
3374 		if (!dtrace_priv_proc(state))
3375 			return (0);
3376 
3377 #if defined(sun)
3378 		/*
3379 		 * Note that we are assuming that an unanchored probe is
3380 		 * always due to a high-level interrupt.  (And we're assuming
3381 		 * that there is only a single high level interrupt.)
3382 		 */
3383 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3384 			return (pid0.pid_id);
3385 
3386 		/*
3387 		 * It is always safe to dereference one's own t_procp pointer:
3388 		 * it always points to a valid, allocated proc structure.
3389 		 * Further, it is always safe to dereference the p_pidp member
3390 		 * of one's own proc structure.  (These are truisms becuase
3391 		 * threads and processes don't clean up their own state --
3392 		 * they leave that task to whomever reaps them.)
3393 		 */
3394 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3395 #else
3396 		return ((uint64_t)curproc->p_pid);
3397 #endif
3398 
3399 	case DIF_VAR_PPID:
3400 		if (!dtrace_priv_proc(state))
3401 			return (0);
3402 
3403 #if defined(sun)
3404 		/*
3405 		 * See comment in DIF_VAR_PID.
3406 		 */
3407 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3408 			return (pid0.pid_id);
3409 
3410 		/*
3411 		 * It is always safe to dereference one's own t_procp pointer:
3412 		 * it always points to a valid, allocated proc structure.
3413 		 * (This is true because threads don't clean up their own
3414 		 * state -- they leave that task to whomever reaps them.)
3415 		 */
3416 		return ((uint64_t)curthread->t_procp->p_ppid);
3417 #else
3418 		if (curproc->p_pid == proc0.p_pid)
3419 			return (curproc->p_pid);
3420 		else
3421 			return (curproc->p_pptr->p_pid);
3422 #endif
3423 
3424 	case DIF_VAR_TID:
3425 #if defined(sun)
3426 		/*
3427 		 * See comment in DIF_VAR_PID.
3428 		 */
3429 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3430 			return (0);
3431 #endif
3432 
3433 		return ((uint64_t)curthread->t_tid);
3434 
3435 	case DIF_VAR_EXECARGS: {
3436 		struct pargs *p_args = curthread->td_proc->p_args;
3437 
3438 		if (p_args == NULL)
3439 			return(0);
3440 
3441 		return (dtrace_dif_varstrz(
3442 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3443 	}
3444 
3445 	case DIF_VAR_EXECNAME:
3446 #if defined(sun)
3447 		if (!dtrace_priv_proc(state))
3448 			return (0);
3449 
3450 		/*
3451 		 * See comment in DIF_VAR_PID.
3452 		 */
3453 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3454 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3455 
3456 		/*
3457 		 * It is always safe to dereference one's own t_procp pointer:
3458 		 * it always points to a valid, allocated proc structure.
3459 		 * (This is true because threads don't clean up their own
3460 		 * state -- they leave that task to whomever reaps them.)
3461 		 */
3462 		return (dtrace_dif_varstr(
3463 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3464 		    state, mstate));
3465 #else
3466 		return (dtrace_dif_varstr(
3467 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3468 #endif
3469 
3470 	case DIF_VAR_ZONENAME:
3471 #if defined(sun)
3472 		if (!dtrace_priv_proc(state))
3473 			return (0);
3474 
3475 		/*
3476 		 * See comment in DIF_VAR_PID.
3477 		 */
3478 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3479 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3480 
3481 		/*
3482 		 * It is always safe to dereference one's own t_procp pointer:
3483 		 * it always points to a valid, allocated proc structure.
3484 		 * (This is true because threads don't clean up their own
3485 		 * state -- they leave that task to whomever reaps them.)
3486 		 */
3487 		return (dtrace_dif_varstr(
3488 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3489 		    state, mstate));
3490 #else
3491 		return (0);
3492 #endif
3493 
3494 	case DIF_VAR_UID:
3495 		if (!dtrace_priv_proc(state))
3496 			return (0);
3497 
3498 #if defined(sun)
3499 		/*
3500 		 * See comment in DIF_VAR_PID.
3501 		 */
3502 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3503 			return ((uint64_t)p0.p_cred->cr_uid);
3504 #endif
3505 
3506 		/*
3507 		 * It is always safe to dereference one's own t_procp pointer:
3508 		 * it always points to a valid, allocated proc structure.
3509 		 * (This is true because threads don't clean up their own
3510 		 * state -- they leave that task to whomever reaps them.)
3511 		 *
3512 		 * Additionally, it is safe to dereference one's own process
3513 		 * credential, since this is never NULL after process birth.
3514 		 */
3515 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3516 
3517 	case DIF_VAR_GID:
3518 		if (!dtrace_priv_proc(state))
3519 			return (0);
3520 
3521 #if defined(sun)
3522 		/*
3523 		 * See comment in DIF_VAR_PID.
3524 		 */
3525 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3526 			return ((uint64_t)p0.p_cred->cr_gid);
3527 #endif
3528 
3529 		/*
3530 		 * It is always safe to dereference one's own t_procp pointer:
3531 		 * it always points to a valid, allocated proc structure.
3532 		 * (This is true because threads don't clean up their own
3533 		 * state -- they leave that task to whomever reaps them.)
3534 		 *
3535 		 * Additionally, it is safe to dereference one's own process
3536 		 * credential, since this is never NULL after process birth.
3537 		 */
3538 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3539 
3540 	case DIF_VAR_ERRNO: {
3541 #if defined(sun)
3542 		klwp_t *lwp;
3543 		if (!dtrace_priv_proc(state))
3544 			return (0);
3545 
3546 		/*
3547 		 * See comment in DIF_VAR_PID.
3548 		 */
3549 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3550 			return (0);
3551 
3552 		/*
3553 		 * It is always safe to dereference one's own t_lwp pointer in
3554 		 * the event that this pointer is non-NULL.  (This is true
3555 		 * because threads and lwps don't clean up their own state --
3556 		 * they leave that task to whomever reaps them.)
3557 		 */
3558 		if ((lwp = curthread->t_lwp) == NULL)
3559 			return (0);
3560 
3561 		return ((uint64_t)lwp->lwp_errno);
3562 #else
3563 		return (curthread->td_errno);
3564 #endif
3565 	}
3566 #if !defined(sun)
3567 	case DIF_VAR_CPU: {
3568 		return curcpu;
3569 	}
3570 #endif
3571 	default:
3572 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3573 		return (0);
3574 	}
3575 }
3576 
3577 
3578 typedef enum dtrace_json_state {
3579 	DTRACE_JSON_REST = 1,
3580 	DTRACE_JSON_OBJECT,
3581 	DTRACE_JSON_STRING,
3582 	DTRACE_JSON_STRING_ESCAPE,
3583 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3584 	DTRACE_JSON_COLON,
3585 	DTRACE_JSON_COMMA,
3586 	DTRACE_JSON_VALUE,
3587 	DTRACE_JSON_IDENTIFIER,
3588 	DTRACE_JSON_NUMBER,
3589 	DTRACE_JSON_NUMBER_FRAC,
3590 	DTRACE_JSON_NUMBER_EXP,
3591 	DTRACE_JSON_COLLECT_OBJECT
3592 } dtrace_json_state_t;
3593 
3594 /*
3595  * This function possesses just enough knowledge about JSON to extract a single
3596  * value from a JSON string and store it in the scratch buffer.  It is able
3597  * to extract nested object values, and members of arrays by index.
3598  *
3599  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3600  * be looked up as we descend into the object tree.  e.g.
3601  *
3602  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3603  *       with nelems = 5.
3604  *
3605  * The run time of this function must be bounded above by strsize to limit the
3606  * amount of work done in probe context.  As such, it is implemented as a
3607  * simple state machine, reading one character at a time using safe loads
3608  * until we find the requested element, hit a parsing error or run off the
3609  * end of the object or string.
3610  *
3611  * As there is no way for a subroutine to return an error without interrupting
3612  * clause execution, we simply return NULL in the event of a missing key or any
3613  * other error condition.  Each NULL return in this function is commented with
3614  * the error condition it represents -- parsing or otherwise.
3615  *
3616  * The set of states for the state machine closely matches the JSON
3617  * specification (http://json.org/).  Briefly:
3618  *
3619  *   DTRACE_JSON_REST:
3620  *     Skip whitespace until we find either a top-level Object, moving
3621  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3622  *
3623  *   DTRACE_JSON_OBJECT:
3624  *     Locate the next key String in an Object.  Sets a flag to denote
3625  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3626  *
3627  *   DTRACE_JSON_COLON:
3628  *     Skip whitespace until we find the colon that separates key Strings
3629  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3630  *
3631  *   DTRACE_JSON_VALUE:
3632  *     Detects the type of the next value (String, Number, Identifier, Object
3633  *     or Array) and routes to the states that process that type.  Here we also
3634  *     deal with the element selector list if we are requested to traverse down
3635  *     into the object tree.
3636  *
3637  *   DTRACE_JSON_COMMA:
3638  *     Skip whitespace until we find the comma that separates key-value pairs
3639  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3640  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3641  *     states return to this state at the end of their value, unless otherwise
3642  *     noted.
3643  *
3644  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3645  *     Processes a Number literal from the JSON, including any exponent
3646  *     component that may be present.  Numbers are returned as strings, which
3647  *     may be passed to strtoll() if an integer is required.
3648  *
3649  *   DTRACE_JSON_IDENTIFIER:
3650  *     Processes a "true", "false" or "null" literal in the JSON.
3651  *
3652  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3653  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3654  *     Processes a String literal from the JSON, whether the String denotes
3655  *     a key, a value or part of a larger Object.  Handles all escape sequences
3656  *     present in the specification, including four-digit unicode characters,
3657  *     but merely includes the escape sequence without converting it to the
3658  *     actual escaped character.  If the String is flagged as a key, we
3659  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3660  *
3661  *   DTRACE_JSON_COLLECT_OBJECT:
3662  *     This state collects an entire Object (or Array), correctly handling
3663  *     embedded strings.  If the full element selector list matches this nested
3664  *     object, we return the Object in full as a string.  If not, we use this
3665  *     state to skip to the next value at this level and continue processing.
3666  *
3667  * NOTE: This function uses various macros from strtolctype.h to manipulate
3668  * digit values, etc -- these have all been checked to ensure they make
3669  * no additional function calls.
3670  */
3671 static char *
3672 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3673     char *dest)
3674 {
3675 	dtrace_json_state_t state = DTRACE_JSON_REST;
3676 	int64_t array_elem = INT64_MIN;
3677 	int64_t array_pos = 0;
3678 	uint8_t escape_unicount = 0;
3679 	boolean_t string_is_key = B_FALSE;
3680 	boolean_t collect_object = B_FALSE;
3681 	boolean_t found_key = B_FALSE;
3682 	boolean_t in_array = B_FALSE;
3683 	uint32_t braces = 0, brackets = 0;
3684 	char *elem = elemlist;
3685 	char *dd = dest;
3686 	uintptr_t cur;
3687 
3688 	for (cur = json; cur < json + size; cur++) {
3689 		char cc = dtrace_load8(cur);
3690 		if (cc == '\0')
3691 			return (NULL);
3692 
3693 		switch (state) {
3694 		case DTRACE_JSON_REST:
3695 			if (isspace(cc))
3696 				break;
3697 
3698 			if (cc == '{') {
3699 				state = DTRACE_JSON_OBJECT;
3700 				break;
3701 			}
3702 
3703 			if (cc == '[') {
3704 				in_array = B_TRUE;
3705 				array_pos = 0;
3706 				array_elem = dtrace_strtoll(elem, 10, size);
3707 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3708 				state = DTRACE_JSON_VALUE;
3709 				break;
3710 			}
3711 
3712 			/*
3713 			 * ERROR: expected to find a top-level object or array.
3714 			 */
3715 			return (NULL);
3716 		case DTRACE_JSON_OBJECT:
3717 			if (isspace(cc))
3718 				break;
3719 
3720 			if (cc == '"') {
3721 				state = DTRACE_JSON_STRING;
3722 				string_is_key = B_TRUE;
3723 				break;
3724 			}
3725 
3726 			/*
3727 			 * ERROR: either the object did not start with a key
3728 			 * string, or we've run off the end of the object
3729 			 * without finding the requested key.
3730 			 */
3731 			return (NULL);
3732 		case DTRACE_JSON_STRING:
3733 			if (cc == '\\') {
3734 				*dd++ = '\\';
3735 				state = DTRACE_JSON_STRING_ESCAPE;
3736 				break;
3737 			}
3738 
3739 			if (cc == '"') {
3740 				if (collect_object) {
3741 					/*
3742 					 * We don't reset the dest here, as
3743 					 * the string is part of a larger
3744 					 * object being collected.
3745 					 */
3746 					*dd++ = cc;
3747 					collect_object = B_FALSE;
3748 					state = DTRACE_JSON_COLLECT_OBJECT;
3749 					break;
3750 				}
3751 				*dd = '\0';
3752 				dd = dest; /* reset string buffer */
3753 				if (string_is_key) {
3754 					if (dtrace_strncmp(dest, elem,
3755 					    size) == 0)
3756 						found_key = B_TRUE;
3757 				} else if (found_key) {
3758 					if (nelems > 1) {
3759 						/*
3760 						 * We expected an object, not
3761 						 * this string.
3762 						 */
3763 						return (NULL);
3764 					}
3765 					return (dest);
3766 				}
3767 				state = string_is_key ? DTRACE_JSON_COLON :
3768 				    DTRACE_JSON_COMMA;
3769 				string_is_key = B_FALSE;
3770 				break;
3771 			}
3772 
3773 			*dd++ = cc;
3774 			break;
3775 		case DTRACE_JSON_STRING_ESCAPE:
3776 			*dd++ = cc;
3777 			if (cc == 'u') {
3778 				escape_unicount = 0;
3779 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3780 			} else {
3781 				state = DTRACE_JSON_STRING;
3782 			}
3783 			break;
3784 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3785 			if (!isxdigit(cc)) {
3786 				/*
3787 				 * ERROR: invalid unicode escape, expected
3788 				 * four valid hexidecimal digits.
3789 				 */
3790 				return (NULL);
3791 			}
3792 
3793 			*dd++ = cc;
3794 			if (++escape_unicount == 4)
3795 				state = DTRACE_JSON_STRING;
3796 			break;
3797 		case DTRACE_JSON_COLON:
3798 			if (isspace(cc))
3799 				break;
3800 
3801 			if (cc == ':') {
3802 				state = DTRACE_JSON_VALUE;
3803 				break;
3804 			}
3805 
3806 			/*
3807 			 * ERROR: expected a colon.
3808 			 */
3809 			return (NULL);
3810 		case DTRACE_JSON_COMMA:
3811 			if (isspace(cc))
3812 				break;
3813 
3814 			if (cc == ',') {
3815 				if (in_array) {
3816 					state = DTRACE_JSON_VALUE;
3817 					if (++array_pos == array_elem)
3818 						found_key = B_TRUE;
3819 				} else {
3820 					state = DTRACE_JSON_OBJECT;
3821 				}
3822 				break;
3823 			}
3824 
3825 			/*
3826 			 * ERROR: either we hit an unexpected character, or
3827 			 * we reached the end of the object or array without
3828 			 * finding the requested key.
3829 			 */
3830 			return (NULL);
3831 		case DTRACE_JSON_IDENTIFIER:
3832 			if (islower(cc)) {
3833 				*dd++ = cc;
3834 				break;
3835 			}
3836 
3837 			*dd = '\0';
3838 			dd = dest; /* reset string buffer */
3839 
3840 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3841 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3842 			    dtrace_strncmp(dest, "null", 5) == 0) {
3843 				if (found_key) {
3844 					if (nelems > 1) {
3845 						/*
3846 						 * ERROR: We expected an object,
3847 						 * not this identifier.
3848 						 */
3849 						return (NULL);
3850 					}
3851 					return (dest);
3852 				} else {
3853 					cur--;
3854 					state = DTRACE_JSON_COMMA;
3855 					break;
3856 				}
3857 			}
3858 
3859 			/*
3860 			 * ERROR: we did not recognise the identifier as one
3861 			 * of those in the JSON specification.
3862 			 */
3863 			return (NULL);
3864 		case DTRACE_JSON_NUMBER:
3865 			if (cc == '.') {
3866 				*dd++ = cc;
3867 				state = DTRACE_JSON_NUMBER_FRAC;
3868 				break;
3869 			}
3870 
3871 			if (cc == 'x' || cc == 'X') {
3872 				/*
3873 				 * ERROR: specification explicitly excludes
3874 				 * hexidecimal or octal numbers.
3875 				 */
3876 				return (NULL);
3877 			}
3878 
3879 			/* FALLTHRU */
3880 		case DTRACE_JSON_NUMBER_FRAC:
3881 			if (cc == 'e' || cc == 'E') {
3882 				*dd++ = cc;
3883 				state = DTRACE_JSON_NUMBER_EXP;
3884 				break;
3885 			}
3886 
3887 			if (cc == '+' || cc == '-') {
3888 				/*
3889 				 * ERROR: expect sign as part of exponent only.
3890 				 */
3891 				return (NULL);
3892 			}
3893 			/* FALLTHRU */
3894 		case DTRACE_JSON_NUMBER_EXP:
3895 			if (isdigit(cc) || cc == '+' || cc == '-') {
3896 				*dd++ = cc;
3897 				break;
3898 			}
3899 
3900 			*dd = '\0';
3901 			dd = dest; /* reset string buffer */
3902 			if (found_key) {
3903 				if (nelems > 1) {
3904 					/*
3905 					 * ERROR: We expected an object, not
3906 					 * this number.
3907 					 */
3908 					return (NULL);
3909 				}
3910 				return (dest);
3911 			}
3912 
3913 			cur--;
3914 			state = DTRACE_JSON_COMMA;
3915 			break;
3916 		case DTRACE_JSON_VALUE:
3917 			if (isspace(cc))
3918 				break;
3919 
3920 			if (cc == '{' || cc == '[') {
3921 				if (nelems > 1 && found_key) {
3922 					in_array = cc == '[' ? B_TRUE : B_FALSE;
3923 					/*
3924 					 * If our element selector directs us
3925 					 * to descend into this nested object,
3926 					 * then move to the next selector
3927 					 * element in the list and restart the
3928 					 * state machine.
3929 					 */
3930 					while (*elem != '\0')
3931 						elem++;
3932 					elem++; /* skip the inter-element NUL */
3933 					nelems--;
3934 					dd = dest;
3935 					if (in_array) {
3936 						state = DTRACE_JSON_VALUE;
3937 						array_pos = 0;
3938 						array_elem = dtrace_strtoll(
3939 						    elem, 10, size);
3940 						found_key = array_elem == 0 ?
3941 						    B_TRUE : B_FALSE;
3942 					} else {
3943 						found_key = B_FALSE;
3944 						state = DTRACE_JSON_OBJECT;
3945 					}
3946 					break;
3947 				}
3948 
3949 				/*
3950 				 * Otherwise, we wish to either skip this
3951 				 * nested object or return it in full.
3952 				 */
3953 				if (cc == '[')
3954 					brackets = 1;
3955 				else
3956 					braces = 1;
3957 				*dd++ = cc;
3958 				state = DTRACE_JSON_COLLECT_OBJECT;
3959 				break;
3960 			}
3961 
3962 			if (cc == '"') {
3963 				state = DTRACE_JSON_STRING;
3964 				break;
3965 			}
3966 
3967 			if (islower(cc)) {
3968 				/*
3969 				 * Here we deal with true, false and null.
3970 				 */
3971 				*dd++ = cc;
3972 				state = DTRACE_JSON_IDENTIFIER;
3973 				break;
3974 			}
3975 
3976 			if (cc == '-' || isdigit(cc)) {
3977 				*dd++ = cc;
3978 				state = DTRACE_JSON_NUMBER;
3979 				break;
3980 			}
3981 
3982 			/*
3983 			 * ERROR: unexpected character at start of value.
3984 			 */
3985 			return (NULL);
3986 		case DTRACE_JSON_COLLECT_OBJECT:
3987 			if (cc == '\0')
3988 				/*
3989 				 * ERROR: unexpected end of input.
3990 				 */
3991 				return (NULL);
3992 
3993 			*dd++ = cc;
3994 			if (cc == '"') {
3995 				collect_object = B_TRUE;
3996 				state = DTRACE_JSON_STRING;
3997 				break;
3998 			}
3999 
4000 			if (cc == ']') {
4001 				if (brackets-- == 0) {
4002 					/*
4003 					 * ERROR: unbalanced brackets.
4004 					 */
4005 					return (NULL);
4006 				}
4007 			} else if (cc == '}') {
4008 				if (braces-- == 0) {
4009 					/*
4010 					 * ERROR: unbalanced braces.
4011 					 */
4012 					return (NULL);
4013 				}
4014 			} else if (cc == '{') {
4015 				braces++;
4016 			} else if (cc == '[') {
4017 				brackets++;
4018 			}
4019 
4020 			if (brackets == 0 && braces == 0) {
4021 				if (found_key) {
4022 					*dd = '\0';
4023 					return (dest);
4024 				}
4025 				dd = dest; /* reset string buffer */
4026 				state = DTRACE_JSON_COMMA;
4027 			}
4028 			break;
4029 		}
4030 	}
4031 	return (NULL);
4032 }
4033 
4034 /*
4035  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4036  * Notice that we don't bother validating the proper number of arguments or
4037  * their types in the tuple stack.  This isn't needed because all argument
4038  * interpretation is safe because of our load safety -- the worst that can
4039  * happen is that a bogus program can obtain bogus results.
4040  */
4041 static void
4042 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4043     dtrace_key_t *tupregs, int nargs,
4044     dtrace_mstate_t *mstate, dtrace_state_t *state)
4045 {
4046 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4047 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4048 	dtrace_vstate_t *vstate = &state->dts_vstate;
4049 
4050 #if defined(sun)
4051 	union {
4052 		mutex_impl_t mi;
4053 		uint64_t mx;
4054 	} m;
4055 
4056 	union {
4057 		krwlock_t ri;
4058 		uintptr_t rw;
4059 	} r;
4060 #else
4061 	struct thread *lowner;
4062 	union {
4063 		struct lock_object *li;
4064 		uintptr_t lx;
4065 	} l;
4066 #endif
4067 
4068 	switch (subr) {
4069 	case DIF_SUBR_RAND:
4070 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4071 		break;
4072 
4073 #if defined(sun)
4074 	case DIF_SUBR_MUTEX_OWNED:
4075 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4076 		    mstate, vstate)) {
4077 			regs[rd] = 0;
4078 			break;
4079 		}
4080 
4081 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4082 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4083 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4084 		else
4085 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4086 		break;
4087 
4088 	case DIF_SUBR_MUTEX_OWNER:
4089 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4090 		    mstate, vstate)) {
4091 			regs[rd] = 0;
4092 			break;
4093 		}
4094 
4095 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4096 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4097 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4098 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4099 		else
4100 			regs[rd] = 0;
4101 		break;
4102 
4103 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4104 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4105 		    mstate, vstate)) {
4106 			regs[rd] = 0;
4107 			break;
4108 		}
4109 
4110 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4111 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4112 		break;
4113 
4114 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4115 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4116 		    mstate, vstate)) {
4117 			regs[rd] = 0;
4118 			break;
4119 		}
4120 
4121 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4122 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4123 		break;
4124 
4125 	case DIF_SUBR_RW_READ_HELD: {
4126 		uintptr_t tmp;
4127 
4128 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4129 		    mstate, vstate)) {
4130 			regs[rd] = 0;
4131 			break;
4132 		}
4133 
4134 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4135 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4136 		break;
4137 	}
4138 
4139 	case DIF_SUBR_RW_WRITE_HELD:
4140 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4141 		    mstate, vstate)) {
4142 			regs[rd] = 0;
4143 			break;
4144 		}
4145 
4146 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4147 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4148 		break;
4149 
4150 	case DIF_SUBR_RW_ISWRITER:
4151 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4152 		    mstate, vstate)) {
4153 			regs[rd] = 0;
4154 			break;
4155 		}
4156 
4157 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4158 		regs[rd] = _RW_ISWRITER(&r.ri);
4159 		break;
4160 
4161 #else
4162 	case DIF_SUBR_MUTEX_OWNED:
4163 		if (!dtrace_canload(tupregs[0].dttk_value,
4164 			sizeof (struct lock_object), mstate, vstate)) {
4165 			regs[rd] = 0;
4166 			break;
4167 		}
4168 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4169 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4170 		break;
4171 
4172 	case DIF_SUBR_MUTEX_OWNER:
4173 		if (!dtrace_canload(tupregs[0].dttk_value,
4174 			sizeof (struct lock_object), mstate, vstate)) {
4175 			regs[rd] = 0;
4176 			break;
4177 		}
4178 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4179 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4180 		regs[rd] = (uintptr_t)lowner;
4181 		break;
4182 
4183 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4184 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4185 		    mstate, vstate)) {
4186 			regs[rd] = 0;
4187 			break;
4188 		}
4189 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4190 		/* XXX - should be only LC_SLEEPABLE? */
4191 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
4192 		    (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
4193 		break;
4194 
4195 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4196 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4197 		    mstate, vstate)) {
4198 			regs[rd] = 0;
4199 			break;
4200 		}
4201 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4202 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4203 		break;
4204 
4205 	case DIF_SUBR_RW_READ_HELD:
4206 	case DIF_SUBR_SX_SHARED_HELD:
4207 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4208 		    mstate, vstate)) {
4209 			regs[rd] = 0;
4210 			break;
4211 		}
4212 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4213 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4214 		    lowner == NULL;
4215 		break;
4216 
4217 	case DIF_SUBR_RW_WRITE_HELD:
4218 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
4219 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4220 		    mstate, vstate)) {
4221 			regs[rd] = 0;
4222 			break;
4223 		}
4224 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4225 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4226 		regs[rd] = (lowner == curthread);
4227 		break;
4228 
4229 	case DIF_SUBR_RW_ISWRITER:
4230 	case DIF_SUBR_SX_ISEXCLUSIVE:
4231 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4232 		    mstate, vstate)) {
4233 			regs[rd] = 0;
4234 			break;
4235 		}
4236 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4237 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4238 		    lowner != NULL;
4239 		break;
4240 #endif /* ! defined(sun) */
4241 
4242 	case DIF_SUBR_BCOPY: {
4243 		/*
4244 		 * We need to be sure that the destination is in the scratch
4245 		 * region -- no other region is allowed.
4246 		 */
4247 		uintptr_t src = tupregs[0].dttk_value;
4248 		uintptr_t dest = tupregs[1].dttk_value;
4249 		size_t size = tupregs[2].dttk_value;
4250 
4251 		if (!dtrace_inscratch(dest, size, mstate)) {
4252 			*flags |= CPU_DTRACE_BADADDR;
4253 			*illval = regs[rd];
4254 			break;
4255 		}
4256 
4257 		if (!dtrace_canload(src, size, mstate, vstate)) {
4258 			regs[rd] = 0;
4259 			break;
4260 		}
4261 
4262 		dtrace_bcopy((void *)src, (void *)dest, size);
4263 		break;
4264 	}
4265 
4266 	case DIF_SUBR_ALLOCA:
4267 	case DIF_SUBR_COPYIN: {
4268 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4269 		uint64_t size =
4270 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4271 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4272 
4273 		/*
4274 		 * This action doesn't require any credential checks since
4275 		 * probes will not activate in user contexts to which the
4276 		 * enabling user does not have permissions.
4277 		 */
4278 
4279 		/*
4280 		 * Rounding up the user allocation size could have overflowed
4281 		 * a large, bogus allocation (like -1ULL) to 0.
4282 		 */
4283 		if (scratch_size < size ||
4284 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4285 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4286 			regs[rd] = 0;
4287 			break;
4288 		}
4289 
4290 		if (subr == DIF_SUBR_COPYIN) {
4291 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4292 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4293 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4294 		}
4295 
4296 		mstate->dtms_scratch_ptr += scratch_size;
4297 		regs[rd] = dest;
4298 		break;
4299 	}
4300 
4301 	case DIF_SUBR_COPYINTO: {
4302 		uint64_t size = tupregs[1].dttk_value;
4303 		uintptr_t dest = tupregs[2].dttk_value;
4304 
4305 		/*
4306 		 * This action doesn't require any credential checks since
4307 		 * probes will not activate in user contexts to which the
4308 		 * enabling user does not have permissions.
4309 		 */
4310 		if (!dtrace_inscratch(dest, size, mstate)) {
4311 			*flags |= CPU_DTRACE_BADADDR;
4312 			*illval = regs[rd];
4313 			break;
4314 		}
4315 
4316 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4317 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4318 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4319 		break;
4320 	}
4321 
4322 	case DIF_SUBR_COPYINSTR: {
4323 		uintptr_t dest = mstate->dtms_scratch_ptr;
4324 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4325 
4326 		if (nargs > 1 && tupregs[1].dttk_value < size)
4327 			size = tupregs[1].dttk_value + 1;
4328 
4329 		/*
4330 		 * This action doesn't require any credential checks since
4331 		 * probes will not activate in user contexts to which the
4332 		 * enabling user does not have permissions.
4333 		 */
4334 		if (!DTRACE_INSCRATCH(mstate, size)) {
4335 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4336 			regs[rd] = 0;
4337 			break;
4338 		}
4339 
4340 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4341 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4342 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4343 
4344 		((char *)dest)[size - 1] = '\0';
4345 		mstate->dtms_scratch_ptr += size;
4346 		regs[rd] = dest;
4347 		break;
4348 	}
4349 
4350 #if defined(sun)
4351 	case DIF_SUBR_MSGSIZE:
4352 	case DIF_SUBR_MSGDSIZE: {
4353 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4354 		uintptr_t wptr, rptr;
4355 		size_t count = 0;
4356 		int cont = 0;
4357 
4358 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4359 
4360 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4361 			    vstate)) {
4362 				regs[rd] = 0;
4363 				break;
4364 			}
4365 
4366 			wptr = dtrace_loadptr(baddr +
4367 			    offsetof(mblk_t, b_wptr));
4368 
4369 			rptr = dtrace_loadptr(baddr +
4370 			    offsetof(mblk_t, b_rptr));
4371 
4372 			if (wptr < rptr) {
4373 				*flags |= CPU_DTRACE_BADADDR;
4374 				*illval = tupregs[0].dttk_value;
4375 				break;
4376 			}
4377 
4378 			daddr = dtrace_loadptr(baddr +
4379 			    offsetof(mblk_t, b_datap));
4380 
4381 			baddr = dtrace_loadptr(baddr +
4382 			    offsetof(mblk_t, b_cont));
4383 
4384 			/*
4385 			 * We want to prevent against denial-of-service here,
4386 			 * so we're only going to search the list for
4387 			 * dtrace_msgdsize_max mblks.
4388 			 */
4389 			if (cont++ > dtrace_msgdsize_max) {
4390 				*flags |= CPU_DTRACE_ILLOP;
4391 				break;
4392 			}
4393 
4394 			if (subr == DIF_SUBR_MSGDSIZE) {
4395 				if (dtrace_load8(daddr +
4396 				    offsetof(dblk_t, db_type)) != M_DATA)
4397 					continue;
4398 			}
4399 
4400 			count += wptr - rptr;
4401 		}
4402 
4403 		if (!(*flags & CPU_DTRACE_FAULT))
4404 			regs[rd] = count;
4405 
4406 		break;
4407 	}
4408 #endif
4409 
4410 	case DIF_SUBR_PROGENYOF: {
4411 		pid_t pid = tupregs[0].dttk_value;
4412 		proc_t *p;
4413 		int rval = 0;
4414 
4415 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4416 
4417 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4418 #if defined(sun)
4419 			if (p->p_pidp->pid_id == pid) {
4420 #else
4421 			if (p->p_pid == pid) {
4422 #endif
4423 				rval = 1;
4424 				break;
4425 			}
4426 		}
4427 
4428 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4429 
4430 		regs[rd] = rval;
4431 		break;
4432 	}
4433 
4434 	case DIF_SUBR_SPECULATION:
4435 		regs[rd] = dtrace_speculation(state);
4436 		break;
4437 
4438 	case DIF_SUBR_COPYOUT: {
4439 		uintptr_t kaddr = tupregs[0].dttk_value;
4440 		uintptr_t uaddr = tupregs[1].dttk_value;
4441 		uint64_t size = tupregs[2].dttk_value;
4442 
4443 		if (!dtrace_destructive_disallow &&
4444 		    dtrace_priv_proc_control(state) &&
4445 		    !dtrace_istoxic(kaddr, size)) {
4446 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4447 			dtrace_copyout(kaddr, uaddr, size, flags);
4448 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4449 		}
4450 		break;
4451 	}
4452 
4453 	case DIF_SUBR_COPYOUTSTR: {
4454 		uintptr_t kaddr = tupregs[0].dttk_value;
4455 		uintptr_t uaddr = tupregs[1].dttk_value;
4456 		uint64_t size = tupregs[2].dttk_value;
4457 
4458 		if (!dtrace_destructive_disallow &&
4459 		    dtrace_priv_proc_control(state) &&
4460 		    !dtrace_istoxic(kaddr, size)) {
4461 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4462 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
4463 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4464 		}
4465 		break;
4466 	}
4467 
4468 	case DIF_SUBR_STRLEN: {
4469 		size_t sz;
4470 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4471 		sz = dtrace_strlen((char *)addr,
4472 		    state->dts_options[DTRACEOPT_STRSIZE]);
4473 
4474 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4475 			regs[rd] = 0;
4476 			break;
4477 		}
4478 
4479 		regs[rd] = sz;
4480 
4481 		break;
4482 	}
4483 
4484 	case DIF_SUBR_STRCHR:
4485 	case DIF_SUBR_STRRCHR: {
4486 		/*
4487 		 * We're going to iterate over the string looking for the
4488 		 * specified character.  We will iterate until we have reached
4489 		 * the string length or we have found the character.  If this
4490 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4491 		 * of the specified character instead of the first.
4492 		 */
4493 		uintptr_t saddr = tupregs[0].dttk_value;
4494 		uintptr_t addr = tupregs[0].dttk_value;
4495 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4496 		char c, target = (char)tupregs[1].dttk_value;
4497 
4498 		for (regs[rd] = 0; addr < limit; addr++) {
4499 			if ((c = dtrace_load8(addr)) == target) {
4500 				regs[rd] = addr;
4501 
4502 				if (subr == DIF_SUBR_STRCHR)
4503 					break;
4504 			}
4505 
4506 			if (c == '\0')
4507 				break;
4508 		}
4509 
4510 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4511 			regs[rd] = 0;
4512 			break;
4513 		}
4514 
4515 		break;
4516 	}
4517 
4518 	case DIF_SUBR_STRSTR:
4519 	case DIF_SUBR_INDEX:
4520 	case DIF_SUBR_RINDEX: {
4521 		/*
4522 		 * We're going to iterate over the string looking for the
4523 		 * specified string.  We will iterate until we have reached
4524 		 * the string length or we have found the string.  (Yes, this
4525 		 * is done in the most naive way possible -- but considering
4526 		 * that the string we're searching for is likely to be
4527 		 * relatively short, the complexity of Rabin-Karp or similar
4528 		 * hardly seems merited.)
4529 		 */
4530 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4531 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4532 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4533 		size_t len = dtrace_strlen(addr, size);
4534 		size_t sublen = dtrace_strlen(substr, size);
4535 		char *limit = addr + len, *orig = addr;
4536 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4537 		int inc = 1;
4538 
4539 		regs[rd] = notfound;
4540 
4541 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4542 			regs[rd] = 0;
4543 			break;
4544 		}
4545 
4546 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4547 		    vstate)) {
4548 			regs[rd] = 0;
4549 			break;
4550 		}
4551 
4552 		/*
4553 		 * strstr() and index()/rindex() have similar semantics if
4554 		 * both strings are the empty string: strstr() returns a
4555 		 * pointer to the (empty) string, and index() and rindex()
4556 		 * both return index 0 (regardless of any position argument).
4557 		 */
4558 		if (sublen == 0 && len == 0) {
4559 			if (subr == DIF_SUBR_STRSTR)
4560 				regs[rd] = (uintptr_t)addr;
4561 			else
4562 				regs[rd] = 0;
4563 			break;
4564 		}
4565 
4566 		if (subr != DIF_SUBR_STRSTR) {
4567 			if (subr == DIF_SUBR_RINDEX) {
4568 				limit = orig - 1;
4569 				addr += len;
4570 				inc = -1;
4571 			}
4572 
4573 			/*
4574 			 * Both index() and rindex() take an optional position
4575 			 * argument that denotes the starting position.
4576 			 */
4577 			if (nargs == 3) {
4578 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4579 
4580 				/*
4581 				 * If the position argument to index() is
4582 				 * negative, Perl implicitly clamps it at
4583 				 * zero.  This semantic is a little surprising
4584 				 * given the special meaning of negative
4585 				 * positions to similar Perl functions like
4586 				 * substr(), but it appears to reflect a
4587 				 * notion that index() can start from a
4588 				 * negative index and increment its way up to
4589 				 * the string.  Given this notion, Perl's
4590 				 * rindex() is at least self-consistent in
4591 				 * that it implicitly clamps positions greater
4592 				 * than the string length to be the string
4593 				 * length.  Where Perl completely loses
4594 				 * coherence, however, is when the specified
4595 				 * substring is the empty string ("").  In
4596 				 * this case, even if the position is
4597 				 * negative, rindex() returns 0 -- and even if
4598 				 * the position is greater than the length,
4599 				 * index() returns the string length.  These
4600 				 * semantics violate the notion that index()
4601 				 * should never return a value less than the
4602 				 * specified position and that rindex() should
4603 				 * never return a value greater than the
4604 				 * specified position.  (One assumes that
4605 				 * these semantics are artifacts of Perl's
4606 				 * implementation and not the results of
4607 				 * deliberate design -- it beggars belief that
4608 				 * even Larry Wall could desire such oddness.)
4609 				 * While in the abstract one would wish for
4610 				 * consistent position semantics across
4611 				 * substr(), index() and rindex() -- or at the
4612 				 * very least self-consistent position
4613 				 * semantics for index() and rindex() -- we
4614 				 * instead opt to keep with the extant Perl
4615 				 * semantics, in all their broken glory.  (Do
4616 				 * we have more desire to maintain Perl's
4617 				 * semantics than Perl does?  Probably.)
4618 				 */
4619 				if (subr == DIF_SUBR_RINDEX) {
4620 					if (pos < 0) {
4621 						if (sublen == 0)
4622 							regs[rd] = 0;
4623 						break;
4624 					}
4625 
4626 					if (pos > len)
4627 						pos = len;
4628 				} else {
4629 					if (pos < 0)
4630 						pos = 0;
4631 
4632 					if (pos >= len) {
4633 						if (sublen == 0)
4634 							regs[rd] = len;
4635 						break;
4636 					}
4637 				}
4638 
4639 				addr = orig + pos;
4640 			}
4641 		}
4642 
4643 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4644 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4645 				if (subr != DIF_SUBR_STRSTR) {
4646 					/*
4647 					 * As D index() and rindex() are
4648 					 * modeled on Perl (and not on awk),
4649 					 * we return a zero-based (and not a
4650 					 * one-based) index.  (For you Perl
4651 					 * weenies: no, we're not going to add
4652 					 * $[ -- and shouldn't you be at a con
4653 					 * or something?)
4654 					 */
4655 					regs[rd] = (uintptr_t)(addr - orig);
4656 					break;
4657 				}
4658 
4659 				ASSERT(subr == DIF_SUBR_STRSTR);
4660 				regs[rd] = (uintptr_t)addr;
4661 				break;
4662 			}
4663 		}
4664 
4665 		break;
4666 	}
4667 
4668 	case DIF_SUBR_STRTOK: {
4669 		uintptr_t addr = tupregs[0].dttk_value;
4670 		uintptr_t tokaddr = tupregs[1].dttk_value;
4671 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4672 		uintptr_t limit, toklimit = tokaddr + size;
4673 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
4674 		char *dest = (char *)mstate->dtms_scratch_ptr;
4675 		int i;
4676 
4677 		/*
4678 		 * Check both the token buffer and (later) the input buffer,
4679 		 * since both could be non-scratch addresses.
4680 		 */
4681 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4682 			regs[rd] = 0;
4683 			break;
4684 		}
4685 
4686 		if (!DTRACE_INSCRATCH(mstate, size)) {
4687 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4688 			regs[rd] = 0;
4689 			break;
4690 		}
4691 
4692 		if (addr == 0) {
4693 			/*
4694 			 * If the address specified is NULL, we use our saved
4695 			 * strtok pointer from the mstate.  Note that this
4696 			 * means that the saved strtok pointer is _only_
4697 			 * valid within multiple enablings of the same probe --
4698 			 * it behaves like an implicit clause-local variable.
4699 			 */
4700 			addr = mstate->dtms_strtok;
4701 		} else {
4702 			/*
4703 			 * If the user-specified address is non-NULL we must
4704 			 * access check it.  This is the only time we have
4705 			 * a chance to do so, since this address may reside
4706 			 * in the string table of this clause-- future calls
4707 			 * (when we fetch addr from mstate->dtms_strtok)
4708 			 * would fail this access check.
4709 			 */
4710 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4711 				regs[rd] = 0;
4712 				break;
4713 			}
4714 		}
4715 
4716 		/*
4717 		 * First, zero the token map, and then process the token
4718 		 * string -- setting a bit in the map for every character
4719 		 * found in the token string.
4720 		 */
4721 		for (i = 0; i < sizeof (tokmap); i++)
4722 			tokmap[i] = 0;
4723 
4724 		for (; tokaddr < toklimit; tokaddr++) {
4725 			if ((c = dtrace_load8(tokaddr)) == '\0')
4726 				break;
4727 
4728 			ASSERT((c >> 3) < sizeof (tokmap));
4729 			tokmap[c >> 3] |= (1 << (c & 0x7));
4730 		}
4731 
4732 		for (limit = addr + size; addr < limit; addr++) {
4733 			/*
4734 			 * We're looking for a character that is _not_ contained
4735 			 * in the token string.
4736 			 */
4737 			if ((c = dtrace_load8(addr)) == '\0')
4738 				break;
4739 
4740 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4741 				break;
4742 		}
4743 
4744 		if (c == '\0') {
4745 			/*
4746 			 * We reached the end of the string without finding
4747 			 * any character that was not in the token string.
4748 			 * We return NULL in this case, and we set the saved
4749 			 * address to NULL as well.
4750 			 */
4751 			regs[rd] = 0;
4752 			mstate->dtms_strtok = 0;
4753 			break;
4754 		}
4755 
4756 		/*
4757 		 * From here on, we're copying into the destination string.
4758 		 */
4759 		for (i = 0; addr < limit && i < size - 1; addr++) {
4760 			if ((c = dtrace_load8(addr)) == '\0')
4761 				break;
4762 
4763 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4764 				break;
4765 
4766 			ASSERT(i < size);
4767 			dest[i++] = c;
4768 		}
4769 
4770 		ASSERT(i < size);
4771 		dest[i] = '\0';
4772 		regs[rd] = (uintptr_t)dest;
4773 		mstate->dtms_scratch_ptr += size;
4774 		mstate->dtms_strtok = addr;
4775 		break;
4776 	}
4777 
4778 	case DIF_SUBR_SUBSTR: {
4779 		uintptr_t s = tupregs[0].dttk_value;
4780 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4781 		char *d = (char *)mstate->dtms_scratch_ptr;
4782 		int64_t index = (int64_t)tupregs[1].dttk_value;
4783 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4784 		size_t len = dtrace_strlen((char *)s, size);
4785 		int64_t i;
4786 
4787 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4788 			regs[rd] = 0;
4789 			break;
4790 		}
4791 
4792 		if (!DTRACE_INSCRATCH(mstate, size)) {
4793 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4794 			regs[rd] = 0;
4795 			break;
4796 		}
4797 
4798 		if (nargs <= 2)
4799 			remaining = (int64_t)size;
4800 
4801 		if (index < 0) {
4802 			index += len;
4803 
4804 			if (index < 0 && index + remaining > 0) {
4805 				remaining += index;
4806 				index = 0;
4807 			}
4808 		}
4809 
4810 		if (index >= len || index < 0) {
4811 			remaining = 0;
4812 		} else if (remaining < 0) {
4813 			remaining += len - index;
4814 		} else if (index + remaining > size) {
4815 			remaining = size - index;
4816 		}
4817 
4818 		for (i = 0; i < remaining; i++) {
4819 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4820 				break;
4821 		}
4822 
4823 		d[i] = '\0';
4824 
4825 		mstate->dtms_scratch_ptr += size;
4826 		regs[rd] = (uintptr_t)d;
4827 		break;
4828 	}
4829 
4830 	case DIF_SUBR_JSON: {
4831 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4832 		uintptr_t json = tupregs[0].dttk_value;
4833 		size_t jsonlen = dtrace_strlen((char *)json, size);
4834 		uintptr_t elem = tupregs[1].dttk_value;
4835 		size_t elemlen = dtrace_strlen((char *)elem, size);
4836 
4837 		char *dest = (char *)mstate->dtms_scratch_ptr;
4838 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4839 		char *ee = elemlist;
4840 		int nelems = 1;
4841 		uintptr_t cur;
4842 
4843 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4844 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4845 			regs[rd] = 0;
4846 			break;
4847 		}
4848 
4849 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4850 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4851 			regs[rd] = 0;
4852 			break;
4853 		}
4854 
4855 		/*
4856 		 * Read the element selector and split it up into a packed list
4857 		 * of strings.
4858 		 */
4859 		for (cur = elem; cur < elem + elemlen; cur++) {
4860 			char cc = dtrace_load8(cur);
4861 
4862 			if (cur == elem && cc == '[') {
4863 				/*
4864 				 * If the first element selector key is
4865 				 * actually an array index then ignore the
4866 				 * bracket.
4867 				 */
4868 				continue;
4869 			}
4870 
4871 			if (cc == ']')
4872 				continue;
4873 
4874 			if (cc == '.' || cc == '[') {
4875 				nelems++;
4876 				cc = '\0';
4877 			}
4878 
4879 			*ee++ = cc;
4880 		}
4881 		*ee++ = '\0';
4882 
4883 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4884 		    nelems, dest)) != 0)
4885 			mstate->dtms_scratch_ptr += jsonlen + 1;
4886 		break;
4887 	}
4888 
4889 	case DIF_SUBR_TOUPPER:
4890 	case DIF_SUBR_TOLOWER: {
4891 		uintptr_t s = tupregs[0].dttk_value;
4892 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4893 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4894 		size_t len = dtrace_strlen((char *)s, size);
4895 		char lower, upper, convert;
4896 		int64_t i;
4897 
4898 		if (subr == DIF_SUBR_TOUPPER) {
4899 			lower = 'a';
4900 			upper = 'z';
4901 			convert = 'A';
4902 		} else {
4903 			lower = 'A';
4904 			upper = 'Z';
4905 			convert = 'a';
4906 		}
4907 
4908 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4909 			regs[rd] = 0;
4910 			break;
4911 		}
4912 
4913 		if (!DTRACE_INSCRATCH(mstate, size)) {
4914 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4915 			regs[rd] = 0;
4916 			break;
4917 		}
4918 
4919 		for (i = 0; i < size - 1; i++) {
4920 			if ((c = dtrace_load8(s + i)) == '\0')
4921 				break;
4922 
4923 			if (c >= lower && c <= upper)
4924 				c = convert + (c - lower);
4925 
4926 			dest[i] = c;
4927 		}
4928 
4929 		ASSERT(i < size);
4930 		dest[i] = '\0';
4931 		regs[rd] = (uintptr_t)dest;
4932 		mstate->dtms_scratch_ptr += size;
4933 		break;
4934 	}
4935 
4936 #if defined(sun)
4937 	case DIF_SUBR_GETMAJOR:
4938 #ifdef _LP64
4939 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4940 #else
4941 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4942 #endif
4943 		break;
4944 
4945 	case DIF_SUBR_GETMINOR:
4946 #ifdef _LP64
4947 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4948 #else
4949 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4950 #endif
4951 		break;
4952 
4953 	case DIF_SUBR_DDI_PATHNAME: {
4954 		/*
4955 		 * This one is a galactic mess.  We are going to roughly
4956 		 * emulate ddi_pathname(), but it's made more complicated
4957 		 * by the fact that we (a) want to include the minor name and
4958 		 * (b) must proceed iteratively instead of recursively.
4959 		 */
4960 		uintptr_t dest = mstate->dtms_scratch_ptr;
4961 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4962 		char *start = (char *)dest, *end = start + size - 1;
4963 		uintptr_t daddr = tupregs[0].dttk_value;
4964 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4965 		char *s;
4966 		int i, len, depth = 0;
4967 
4968 		/*
4969 		 * Due to all the pointer jumping we do and context we must
4970 		 * rely upon, we just mandate that the user must have kernel
4971 		 * read privileges to use this routine.
4972 		 */
4973 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4974 			*flags |= CPU_DTRACE_KPRIV;
4975 			*illval = daddr;
4976 			regs[rd] = 0;
4977 		}
4978 
4979 		if (!DTRACE_INSCRATCH(mstate, size)) {
4980 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4981 			regs[rd] = 0;
4982 			break;
4983 		}
4984 
4985 		*end = '\0';
4986 
4987 		/*
4988 		 * We want to have a name for the minor.  In order to do this,
4989 		 * we need to walk the minor list from the devinfo.  We want
4990 		 * to be sure that we don't infinitely walk a circular list,
4991 		 * so we check for circularity by sending a scout pointer
4992 		 * ahead two elements for every element that we iterate over;
4993 		 * if the list is circular, these will ultimately point to the
4994 		 * same element.  You may recognize this little trick as the
4995 		 * answer to a stupid interview question -- one that always
4996 		 * seems to be asked by those who had to have it laboriously
4997 		 * explained to them, and who can't even concisely describe
4998 		 * the conditions under which one would be forced to resort to
4999 		 * this technique.  Needless to say, those conditions are
5000 		 * found here -- and probably only here.  Is this the only use
5001 		 * of this infamous trick in shipping, production code?  If it
5002 		 * isn't, it probably should be...
5003 		 */
5004 		if (minor != -1) {
5005 			uintptr_t maddr = dtrace_loadptr(daddr +
5006 			    offsetof(struct dev_info, devi_minor));
5007 
5008 			uintptr_t next = offsetof(struct ddi_minor_data, next);
5009 			uintptr_t name = offsetof(struct ddi_minor_data,
5010 			    d_minor) + offsetof(struct ddi_minor, name);
5011 			uintptr_t dev = offsetof(struct ddi_minor_data,
5012 			    d_minor) + offsetof(struct ddi_minor, dev);
5013 			uintptr_t scout;
5014 
5015 			if (maddr != NULL)
5016 				scout = dtrace_loadptr(maddr + next);
5017 
5018 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5019 				uint64_t m;
5020 #ifdef _LP64
5021 				m = dtrace_load64(maddr + dev) & MAXMIN64;
5022 #else
5023 				m = dtrace_load32(maddr + dev) & MAXMIN;
5024 #endif
5025 				if (m != minor) {
5026 					maddr = dtrace_loadptr(maddr + next);
5027 
5028 					if (scout == NULL)
5029 						continue;
5030 
5031 					scout = dtrace_loadptr(scout + next);
5032 
5033 					if (scout == NULL)
5034 						continue;
5035 
5036 					scout = dtrace_loadptr(scout + next);
5037 
5038 					if (scout == NULL)
5039 						continue;
5040 
5041 					if (scout == maddr) {
5042 						*flags |= CPU_DTRACE_ILLOP;
5043 						break;
5044 					}
5045 
5046 					continue;
5047 				}
5048 
5049 				/*
5050 				 * We have the minor data.  Now we need to
5051 				 * copy the minor's name into the end of the
5052 				 * pathname.
5053 				 */
5054 				s = (char *)dtrace_loadptr(maddr + name);
5055 				len = dtrace_strlen(s, size);
5056 
5057 				if (*flags & CPU_DTRACE_FAULT)
5058 					break;
5059 
5060 				if (len != 0) {
5061 					if ((end -= (len + 1)) < start)
5062 						break;
5063 
5064 					*end = ':';
5065 				}
5066 
5067 				for (i = 1; i <= len; i++)
5068 					end[i] = dtrace_load8((uintptr_t)s++);
5069 				break;
5070 			}
5071 		}
5072 
5073 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5074 			ddi_node_state_t devi_state;
5075 
5076 			devi_state = dtrace_load32(daddr +
5077 			    offsetof(struct dev_info, devi_node_state));
5078 
5079 			if (*flags & CPU_DTRACE_FAULT)
5080 				break;
5081 
5082 			if (devi_state >= DS_INITIALIZED) {
5083 				s = (char *)dtrace_loadptr(daddr +
5084 				    offsetof(struct dev_info, devi_addr));
5085 				len = dtrace_strlen(s, size);
5086 
5087 				if (*flags & CPU_DTRACE_FAULT)
5088 					break;
5089 
5090 				if (len != 0) {
5091 					if ((end -= (len + 1)) < start)
5092 						break;
5093 
5094 					*end = '@';
5095 				}
5096 
5097 				for (i = 1; i <= len; i++)
5098 					end[i] = dtrace_load8((uintptr_t)s++);
5099 			}
5100 
5101 			/*
5102 			 * Now for the node name...
5103 			 */
5104 			s = (char *)dtrace_loadptr(daddr +
5105 			    offsetof(struct dev_info, devi_node_name));
5106 
5107 			daddr = dtrace_loadptr(daddr +
5108 			    offsetof(struct dev_info, devi_parent));
5109 
5110 			/*
5111 			 * If our parent is NULL (that is, if we're the root
5112 			 * node), we're going to use the special path
5113 			 * "devices".
5114 			 */
5115 			if (daddr == 0)
5116 				s = "devices";
5117 
5118 			len = dtrace_strlen(s, size);
5119 			if (*flags & CPU_DTRACE_FAULT)
5120 				break;
5121 
5122 			if ((end -= (len + 1)) < start)
5123 				break;
5124 
5125 			for (i = 1; i <= len; i++)
5126 				end[i] = dtrace_load8((uintptr_t)s++);
5127 			*end = '/';
5128 
5129 			if (depth++ > dtrace_devdepth_max) {
5130 				*flags |= CPU_DTRACE_ILLOP;
5131 				break;
5132 			}
5133 		}
5134 
5135 		if (end < start)
5136 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5137 
5138 		if (daddr == 0) {
5139 			regs[rd] = (uintptr_t)end;
5140 			mstate->dtms_scratch_ptr += size;
5141 		}
5142 
5143 		break;
5144 	}
5145 #endif
5146 
5147 	case DIF_SUBR_STRJOIN: {
5148 		char *d = (char *)mstate->dtms_scratch_ptr;
5149 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5150 		uintptr_t s1 = tupregs[0].dttk_value;
5151 		uintptr_t s2 = tupregs[1].dttk_value;
5152 		int i = 0;
5153 
5154 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
5155 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
5156 			regs[rd] = 0;
5157 			break;
5158 		}
5159 
5160 		if (!DTRACE_INSCRATCH(mstate, size)) {
5161 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5162 			regs[rd] = 0;
5163 			break;
5164 		}
5165 
5166 		for (;;) {
5167 			if (i >= size) {
5168 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5169 				regs[rd] = 0;
5170 				break;
5171 			}
5172 
5173 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
5174 				i--;
5175 				break;
5176 			}
5177 		}
5178 
5179 		for (;;) {
5180 			if (i >= size) {
5181 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5182 				regs[rd] = 0;
5183 				break;
5184 			}
5185 
5186 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
5187 				break;
5188 		}
5189 
5190 		if (i < size) {
5191 			mstate->dtms_scratch_ptr += i;
5192 			regs[rd] = (uintptr_t)d;
5193 		}
5194 
5195 		break;
5196 	}
5197 
5198 	case DIF_SUBR_STRTOLL: {
5199 		uintptr_t s = tupregs[0].dttk_value;
5200 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5201 		int base = 10;
5202 
5203 		if (nargs > 1) {
5204 			if ((base = tupregs[1].dttk_value) <= 1 ||
5205 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5206 				*flags |= CPU_DTRACE_ILLOP;
5207 				break;
5208 			}
5209 		}
5210 
5211 		if (!dtrace_strcanload(s, size, mstate, vstate)) {
5212 			regs[rd] = INT64_MIN;
5213 			break;
5214 		}
5215 
5216 		regs[rd] = dtrace_strtoll((char *)s, base, size);
5217 		break;
5218 	}
5219 
5220 	case DIF_SUBR_LLTOSTR: {
5221 		int64_t i = (int64_t)tupregs[0].dttk_value;
5222 		uint64_t val, digit;
5223 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5224 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5225 		int base = 10;
5226 
5227 		if (nargs > 1) {
5228 			if ((base = tupregs[1].dttk_value) <= 1 ||
5229 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5230 				*flags |= CPU_DTRACE_ILLOP;
5231 				break;
5232 			}
5233 		}
5234 
5235 		val = (base == 10 && i < 0) ? i * -1 : i;
5236 
5237 		if (!DTRACE_INSCRATCH(mstate, size)) {
5238 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5239 			regs[rd] = 0;
5240 			break;
5241 		}
5242 
5243 		for (*end-- = '\0'; val; val /= base) {
5244 			if ((digit = val % base) <= '9' - '0') {
5245 				*end-- = '0' + digit;
5246 			} else {
5247 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5248 			}
5249 		}
5250 
5251 		if (i == 0 && base == 16)
5252 			*end-- = '0';
5253 
5254 		if (base == 16)
5255 			*end-- = 'x';
5256 
5257 		if (i == 0 || base == 8 || base == 16)
5258 			*end-- = '0';
5259 
5260 		if (i < 0 && base == 10)
5261 			*end-- = '-';
5262 
5263 		regs[rd] = (uintptr_t)end + 1;
5264 		mstate->dtms_scratch_ptr += size;
5265 		break;
5266 	}
5267 
5268 	case DIF_SUBR_HTONS:
5269 	case DIF_SUBR_NTOHS:
5270 #if BYTE_ORDER == BIG_ENDIAN
5271 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5272 #else
5273 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5274 #endif
5275 		break;
5276 
5277 
5278 	case DIF_SUBR_HTONL:
5279 	case DIF_SUBR_NTOHL:
5280 #if BYTE_ORDER == BIG_ENDIAN
5281 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5282 #else
5283 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5284 #endif
5285 		break;
5286 
5287 
5288 	case DIF_SUBR_HTONLL:
5289 	case DIF_SUBR_NTOHLL:
5290 #if BYTE_ORDER == BIG_ENDIAN
5291 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5292 #else
5293 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5294 #endif
5295 		break;
5296 
5297 
5298 	case DIF_SUBR_DIRNAME:
5299 	case DIF_SUBR_BASENAME: {
5300 		char *dest = (char *)mstate->dtms_scratch_ptr;
5301 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5302 		uintptr_t src = tupregs[0].dttk_value;
5303 		int i, j, len = dtrace_strlen((char *)src, size);
5304 		int lastbase = -1, firstbase = -1, lastdir = -1;
5305 		int start, end;
5306 
5307 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5308 			regs[rd] = 0;
5309 			break;
5310 		}
5311 
5312 		if (!DTRACE_INSCRATCH(mstate, size)) {
5313 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5314 			regs[rd] = 0;
5315 			break;
5316 		}
5317 
5318 		/*
5319 		 * The basename and dirname for a zero-length string is
5320 		 * defined to be "."
5321 		 */
5322 		if (len == 0) {
5323 			len = 1;
5324 			src = (uintptr_t)".";
5325 		}
5326 
5327 		/*
5328 		 * Start from the back of the string, moving back toward the
5329 		 * front until we see a character that isn't a slash.  That
5330 		 * character is the last character in the basename.
5331 		 */
5332 		for (i = len - 1; i >= 0; i--) {
5333 			if (dtrace_load8(src + i) != '/')
5334 				break;
5335 		}
5336 
5337 		if (i >= 0)
5338 			lastbase = i;
5339 
5340 		/*
5341 		 * Starting from the last character in the basename, move
5342 		 * towards the front until we find a slash.  The character
5343 		 * that we processed immediately before that is the first
5344 		 * character in the basename.
5345 		 */
5346 		for (; i >= 0; i--) {
5347 			if (dtrace_load8(src + i) == '/')
5348 				break;
5349 		}
5350 
5351 		if (i >= 0)
5352 			firstbase = i + 1;
5353 
5354 		/*
5355 		 * Now keep going until we find a non-slash character.  That
5356 		 * character is the last character in the dirname.
5357 		 */
5358 		for (; i >= 0; i--) {
5359 			if (dtrace_load8(src + i) != '/')
5360 				break;
5361 		}
5362 
5363 		if (i >= 0)
5364 			lastdir = i;
5365 
5366 		ASSERT(!(lastbase == -1 && firstbase != -1));
5367 		ASSERT(!(firstbase == -1 && lastdir != -1));
5368 
5369 		if (lastbase == -1) {
5370 			/*
5371 			 * We didn't find a non-slash character.  We know that
5372 			 * the length is non-zero, so the whole string must be
5373 			 * slashes.  In either the dirname or the basename
5374 			 * case, we return '/'.
5375 			 */
5376 			ASSERT(firstbase == -1);
5377 			firstbase = lastbase = lastdir = 0;
5378 		}
5379 
5380 		if (firstbase == -1) {
5381 			/*
5382 			 * The entire string consists only of a basename
5383 			 * component.  If we're looking for dirname, we need
5384 			 * to change our string to be just "."; if we're
5385 			 * looking for a basename, we'll just set the first
5386 			 * character of the basename to be 0.
5387 			 */
5388 			if (subr == DIF_SUBR_DIRNAME) {
5389 				ASSERT(lastdir == -1);
5390 				src = (uintptr_t)".";
5391 				lastdir = 0;
5392 			} else {
5393 				firstbase = 0;
5394 			}
5395 		}
5396 
5397 		if (subr == DIF_SUBR_DIRNAME) {
5398 			if (lastdir == -1) {
5399 				/*
5400 				 * We know that we have a slash in the name --
5401 				 * or lastdir would be set to 0, above.  And
5402 				 * because lastdir is -1, we know that this
5403 				 * slash must be the first character.  (That
5404 				 * is, the full string must be of the form
5405 				 * "/basename".)  In this case, the last
5406 				 * character of the directory name is 0.
5407 				 */
5408 				lastdir = 0;
5409 			}
5410 
5411 			start = 0;
5412 			end = lastdir;
5413 		} else {
5414 			ASSERT(subr == DIF_SUBR_BASENAME);
5415 			ASSERT(firstbase != -1 && lastbase != -1);
5416 			start = firstbase;
5417 			end = lastbase;
5418 		}
5419 
5420 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5421 			dest[j] = dtrace_load8(src + i);
5422 
5423 		dest[j] = '\0';
5424 		regs[rd] = (uintptr_t)dest;
5425 		mstate->dtms_scratch_ptr += size;
5426 		break;
5427 	}
5428 
5429 	case DIF_SUBR_GETF: {
5430 		uintptr_t fd = tupregs[0].dttk_value;
5431 		struct filedesc *fdp;
5432 		file_t *fp;
5433 
5434 		if (!dtrace_priv_proc(state)) {
5435 			regs[rd] = 0;
5436 			break;
5437 		}
5438 		fdp = curproc->p_fd;
5439 		FILEDESC_SLOCK(fdp);
5440 		fp = fget_locked(fdp, fd);
5441 		mstate->dtms_getf = fp;
5442 		regs[rd] = (uintptr_t)fp;
5443 		FILEDESC_SUNLOCK(fdp);
5444 		break;
5445 	}
5446 
5447 	case DIF_SUBR_CLEANPATH: {
5448 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5449 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5450 		uintptr_t src = tupregs[0].dttk_value;
5451 		int i = 0, j = 0;
5452 #if defined(sun)
5453 		zone_t *z;
5454 #endif
5455 
5456 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
5457 			regs[rd] = 0;
5458 			break;
5459 		}
5460 
5461 		if (!DTRACE_INSCRATCH(mstate, size)) {
5462 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5463 			regs[rd] = 0;
5464 			break;
5465 		}
5466 
5467 		/*
5468 		 * Move forward, loading each character.
5469 		 */
5470 		do {
5471 			c = dtrace_load8(src + i++);
5472 next:
5473 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5474 				break;
5475 
5476 			if (c != '/') {
5477 				dest[j++] = c;
5478 				continue;
5479 			}
5480 
5481 			c = dtrace_load8(src + i++);
5482 
5483 			if (c == '/') {
5484 				/*
5485 				 * We have two slashes -- we can just advance
5486 				 * to the next character.
5487 				 */
5488 				goto next;
5489 			}
5490 
5491 			if (c != '.') {
5492 				/*
5493 				 * This is not "." and it's not ".." -- we can
5494 				 * just store the "/" and this character and
5495 				 * drive on.
5496 				 */
5497 				dest[j++] = '/';
5498 				dest[j++] = c;
5499 				continue;
5500 			}
5501 
5502 			c = dtrace_load8(src + i++);
5503 
5504 			if (c == '/') {
5505 				/*
5506 				 * This is a "/./" component.  We're not going
5507 				 * to store anything in the destination buffer;
5508 				 * we're just going to go to the next component.
5509 				 */
5510 				goto next;
5511 			}
5512 
5513 			if (c != '.') {
5514 				/*
5515 				 * This is not ".." -- we can just store the
5516 				 * "/." and this character and continue
5517 				 * processing.
5518 				 */
5519 				dest[j++] = '/';
5520 				dest[j++] = '.';
5521 				dest[j++] = c;
5522 				continue;
5523 			}
5524 
5525 			c = dtrace_load8(src + i++);
5526 
5527 			if (c != '/' && c != '\0') {
5528 				/*
5529 				 * This is not ".." -- it's "..[mumble]".
5530 				 * We'll store the "/.." and this character
5531 				 * and continue processing.
5532 				 */
5533 				dest[j++] = '/';
5534 				dest[j++] = '.';
5535 				dest[j++] = '.';
5536 				dest[j++] = c;
5537 				continue;
5538 			}
5539 
5540 			/*
5541 			 * This is "/../" or "/..\0".  We need to back up
5542 			 * our destination pointer until we find a "/".
5543 			 */
5544 			i--;
5545 			while (j != 0 && dest[--j] != '/')
5546 				continue;
5547 
5548 			if (c == '\0')
5549 				dest[++j] = '/';
5550 		} while (c != '\0');
5551 
5552 		dest[j] = '\0';
5553 
5554 #if defined(sun)
5555 		if (mstate->dtms_getf != NULL &&
5556 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5557 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5558 			/*
5559 			 * If we've done a getf() as a part of this ECB and we
5560 			 * don't have kernel access (and we're not in the global
5561 			 * zone), check if the path we cleaned up begins with
5562 			 * the zone's root path, and trim it off if so.  Note
5563 			 * that this is an output cleanliness issue, not a
5564 			 * security issue: knowing one's zone root path does
5565 			 * not enable privilege escalation.
5566 			 */
5567 			if (strstr(dest, z->zone_rootpath) == dest)
5568 				dest += strlen(z->zone_rootpath) - 1;
5569 		}
5570 #endif
5571 
5572 		regs[rd] = (uintptr_t)dest;
5573 		mstate->dtms_scratch_ptr += size;
5574 		break;
5575 	}
5576 
5577 	case DIF_SUBR_INET_NTOA:
5578 	case DIF_SUBR_INET_NTOA6:
5579 	case DIF_SUBR_INET_NTOP: {
5580 		size_t size;
5581 		int af, argi, i;
5582 		char *base, *end;
5583 
5584 		if (subr == DIF_SUBR_INET_NTOP) {
5585 			af = (int)tupregs[0].dttk_value;
5586 			argi = 1;
5587 		} else {
5588 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5589 			argi = 0;
5590 		}
5591 
5592 		if (af == AF_INET) {
5593 			ipaddr_t ip4;
5594 			uint8_t *ptr8, val;
5595 
5596 			/*
5597 			 * Safely load the IPv4 address.
5598 			 */
5599 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5600 
5601 			/*
5602 			 * Check an IPv4 string will fit in scratch.
5603 			 */
5604 			size = INET_ADDRSTRLEN;
5605 			if (!DTRACE_INSCRATCH(mstate, size)) {
5606 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5607 				regs[rd] = 0;
5608 				break;
5609 			}
5610 			base = (char *)mstate->dtms_scratch_ptr;
5611 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5612 
5613 			/*
5614 			 * Stringify as a dotted decimal quad.
5615 			 */
5616 			*end-- = '\0';
5617 			ptr8 = (uint8_t *)&ip4;
5618 			for (i = 3; i >= 0; i--) {
5619 				val = ptr8[i];
5620 
5621 				if (val == 0) {
5622 					*end-- = '0';
5623 				} else {
5624 					for (; val; val /= 10) {
5625 						*end-- = '0' + (val % 10);
5626 					}
5627 				}
5628 
5629 				if (i > 0)
5630 					*end-- = '.';
5631 			}
5632 			ASSERT(end + 1 >= base);
5633 
5634 		} else if (af == AF_INET6) {
5635 			struct in6_addr ip6;
5636 			int firstzero, tryzero, numzero, v6end;
5637 			uint16_t val;
5638 			const char digits[] = "0123456789abcdef";
5639 
5640 			/*
5641 			 * Stringify using RFC 1884 convention 2 - 16 bit
5642 			 * hexadecimal values with a zero-run compression.
5643 			 * Lower case hexadecimal digits are used.
5644 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5645 			 * The IPv4 embedded form is returned for inet_ntop,
5646 			 * just the IPv4 string is returned for inet_ntoa6.
5647 			 */
5648 
5649 			/*
5650 			 * Safely load the IPv6 address.
5651 			 */
5652 			dtrace_bcopy(
5653 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5654 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5655 
5656 			/*
5657 			 * Check an IPv6 string will fit in scratch.
5658 			 */
5659 			size = INET6_ADDRSTRLEN;
5660 			if (!DTRACE_INSCRATCH(mstate, size)) {
5661 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5662 				regs[rd] = 0;
5663 				break;
5664 			}
5665 			base = (char *)mstate->dtms_scratch_ptr;
5666 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5667 			*end-- = '\0';
5668 
5669 			/*
5670 			 * Find the longest run of 16 bit zero values
5671 			 * for the single allowed zero compression - "::".
5672 			 */
5673 			firstzero = -1;
5674 			tryzero = -1;
5675 			numzero = 1;
5676 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5677 #if defined(sun)
5678 				if (ip6._S6_un._S6_u8[i] == 0 &&
5679 #else
5680 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5681 #endif
5682 				    tryzero == -1 && i % 2 == 0) {
5683 					tryzero = i;
5684 					continue;
5685 				}
5686 
5687 				if (tryzero != -1 &&
5688 #if defined(sun)
5689 				    (ip6._S6_un._S6_u8[i] != 0 ||
5690 #else
5691 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5692 #endif
5693 				    i == sizeof (struct in6_addr) - 1)) {
5694 
5695 					if (i - tryzero <= numzero) {
5696 						tryzero = -1;
5697 						continue;
5698 					}
5699 
5700 					firstzero = tryzero;
5701 					numzero = i - i % 2 - tryzero;
5702 					tryzero = -1;
5703 
5704 #if defined(sun)
5705 					if (ip6._S6_un._S6_u8[i] == 0 &&
5706 #else
5707 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5708 #endif
5709 					    i == sizeof (struct in6_addr) - 1)
5710 						numzero += 2;
5711 				}
5712 			}
5713 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5714 
5715 			/*
5716 			 * Check for an IPv4 embedded address.
5717 			 */
5718 			v6end = sizeof (struct in6_addr) - 2;
5719 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5720 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5721 				for (i = sizeof (struct in6_addr) - 1;
5722 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5723 					ASSERT(end >= base);
5724 
5725 #if defined(sun)
5726 					val = ip6._S6_un._S6_u8[i];
5727 #else
5728 					val = ip6.__u6_addr.__u6_addr8[i];
5729 #endif
5730 
5731 					if (val == 0) {
5732 						*end-- = '0';
5733 					} else {
5734 						for (; val; val /= 10) {
5735 							*end-- = '0' + val % 10;
5736 						}
5737 					}
5738 
5739 					if (i > DTRACE_V4MAPPED_OFFSET)
5740 						*end-- = '.';
5741 				}
5742 
5743 				if (subr == DIF_SUBR_INET_NTOA6)
5744 					goto inetout;
5745 
5746 				/*
5747 				 * Set v6end to skip the IPv4 address that
5748 				 * we have already stringified.
5749 				 */
5750 				v6end = 10;
5751 			}
5752 
5753 			/*
5754 			 * Build the IPv6 string by working through the
5755 			 * address in reverse.
5756 			 */
5757 			for (i = v6end; i >= 0; i -= 2) {
5758 				ASSERT(end >= base);
5759 
5760 				if (i == firstzero + numzero - 2) {
5761 					*end-- = ':';
5762 					*end-- = ':';
5763 					i -= numzero - 2;
5764 					continue;
5765 				}
5766 
5767 				if (i < 14 && i != firstzero - 2)
5768 					*end-- = ':';
5769 
5770 #if defined(sun)
5771 				val = (ip6._S6_un._S6_u8[i] << 8) +
5772 				    ip6._S6_un._S6_u8[i + 1];
5773 #else
5774 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5775 				    ip6.__u6_addr.__u6_addr8[i + 1];
5776 #endif
5777 
5778 				if (val == 0) {
5779 					*end-- = '0';
5780 				} else {
5781 					for (; val; val /= 16) {
5782 						*end-- = digits[val % 16];
5783 					}
5784 				}
5785 			}
5786 			ASSERT(end + 1 >= base);
5787 
5788 		} else {
5789 			/*
5790 			 * The user didn't use AH_INET or AH_INET6.
5791 			 */
5792 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5793 			regs[rd] = 0;
5794 			break;
5795 		}
5796 
5797 inetout:	regs[rd] = (uintptr_t)end + 1;
5798 		mstate->dtms_scratch_ptr += size;
5799 		break;
5800 	}
5801 
5802 	case DIF_SUBR_MEMREF: {
5803 		uintptr_t size = 2 * sizeof(uintptr_t);
5804 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5805 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5806 
5807 		/* address and length */
5808 		memref[0] = tupregs[0].dttk_value;
5809 		memref[1] = tupregs[1].dttk_value;
5810 
5811 		regs[rd] = (uintptr_t) memref;
5812 		mstate->dtms_scratch_ptr += scratch_size;
5813 		break;
5814 	}
5815 
5816 #if !defined(sun)
5817 	case DIF_SUBR_MEMSTR: {
5818 		char *str = (char *)mstate->dtms_scratch_ptr;
5819 		uintptr_t mem = tupregs[0].dttk_value;
5820 		char c = tupregs[1].dttk_value;
5821 		size_t size = tupregs[2].dttk_value;
5822 		uint8_t n;
5823 		int i;
5824 
5825 		regs[rd] = 0;
5826 
5827 		if (size == 0)
5828 			break;
5829 
5830 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
5831 			break;
5832 
5833 		if (!DTRACE_INSCRATCH(mstate, size)) {
5834 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5835 			break;
5836 		}
5837 
5838 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5839 			*flags |= CPU_DTRACE_ILLOP;
5840 			break;
5841 		}
5842 
5843 		for (i = 0; i < size - 1; i++) {
5844 			n = dtrace_load8(mem++);
5845 			str[i] = (n == 0) ? c : n;
5846 		}
5847 		str[size - 1] = 0;
5848 
5849 		regs[rd] = (uintptr_t)str;
5850 		mstate->dtms_scratch_ptr += size;
5851 		break;
5852 	}
5853 #endif
5854 
5855 	case DIF_SUBR_TYPEREF: {
5856 		uintptr_t size = 4 * sizeof(uintptr_t);
5857 		uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5858 		size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5859 
5860 		/* address, num_elements, type_str, type_len */
5861 		typeref[0] = tupregs[0].dttk_value;
5862 		typeref[1] = tupregs[1].dttk_value;
5863 		typeref[2] = tupregs[2].dttk_value;
5864 		typeref[3] = tupregs[3].dttk_value;
5865 
5866 		regs[rd] = (uintptr_t) typeref;
5867 		mstate->dtms_scratch_ptr += scratch_size;
5868 		break;
5869 	}
5870 	}
5871 }
5872 
5873 /*
5874  * Emulate the execution of DTrace IR instructions specified by the given
5875  * DIF object.  This function is deliberately void of assertions as all of
5876  * the necessary checks are handled by a call to dtrace_difo_validate().
5877  */
5878 static uint64_t
5879 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5880     dtrace_vstate_t *vstate, dtrace_state_t *state)
5881 {
5882 	const dif_instr_t *text = difo->dtdo_buf;
5883 	const uint_t textlen = difo->dtdo_len;
5884 	const char *strtab = difo->dtdo_strtab;
5885 	const uint64_t *inttab = difo->dtdo_inttab;
5886 
5887 	uint64_t rval = 0;
5888 	dtrace_statvar_t *svar;
5889 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5890 	dtrace_difv_t *v;
5891 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5892 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5893 
5894 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5895 	uint64_t regs[DIF_DIR_NREGS];
5896 	uint64_t *tmp;
5897 
5898 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5899 	int64_t cc_r;
5900 	uint_t pc = 0, id, opc = 0;
5901 	uint8_t ttop = 0;
5902 	dif_instr_t instr;
5903 	uint_t r1, r2, rd;
5904 
5905 	/*
5906 	 * We stash the current DIF object into the machine state: we need it
5907 	 * for subsequent access checking.
5908 	 */
5909 	mstate->dtms_difo = difo;
5910 
5911 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5912 
5913 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5914 		opc = pc;
5915 
5916 		instr = text[pc++];
5917 		r1 = DIF_INSTR_R1(instr);
5918 		r2 = DIF_INSTR_R2(instr);
5919 		rd = DIF_INSTR_RD(instr);
5920 
5921 		switch (DIF_INSTR_OP(instr)) {
5922 		case DIF_OP_OR:
5923 			regs[rd] = regs[r1] | regs[r2];
5924 			break;
5925 		case DIF_OP_XOR:
5926 			regs[rd] = regs[r1] ^ regs[r2];
5927 			break;
5928 		case DIF_OP_AND:
5929 			regs[rd] = regs[r1] & regs[r2];
5930 			break;
5931 		case DIF_OP_SLL:
5932 			regs[rd] = regs[r1] << regs[r2];
5933 			break;
5934 		case DIF_OP_SRL:
5935 			regs[rd] = regs[r1] >> regs[r2];
5936 			break;
5937 		case DIF_OP_SUB:
5938 			regs[rd] = regs[r1] - regs[r2];
5939 			break;
5940 		case DIF_OP_ADD:
5941 			regs[rd] = regs[r1] + regs[r2];
5942 			break;
5943 		case DIF_OP_MUL:
5944 			regs[rd] = regs[r1] * regs[r2];
5945 			break;
5946 		case DIF_OP_SDIV:
5947 			if (regs[r2] == 0) {
5948 				regs[rd] = 0;
5949 				*flags |= CPU_DTRACE_DIVZERO;
5950 			} else {
5951 				regs[rd] = (int64_t)regs[r1] /
5952 				    (int64_t)regs[r2];
5953 			}
5954 			break;
5955 
5956 		case DIF_OP_UDIV:
5957 			if (regs[r2] == 0) {
5958 				regs[rd] = 0;
5959 				*flags |= CPU_DTRACE_DIVZERO;
5960 			} else {
5961 				regs[rd] = regs[r1] / regs[r2];
5962 			}
5963 			break;
5964 
5965 		case DIF_OP_SREM:
5966 			if (regs[r2] == 0) {
5967 				regs[rd] = 0;
5968 				*flags |= CPU_DTRACE_DIVZERO;
5969 			} else {
5970 				regs[rd] = (int64_t)regs[r1] %
5971 				    (int64_t)regs[r2];
5972 			}
5973 			break;
5974 
5975 		case DIF_OP_UREM:
5976 			if (regs[r2] == 0) {
5977 				regs[rd] = 0;
5978 				*flags |= CPU_DTRACE_DIVZERO;
5979 			} else {
5980 				regs[rd] = regs[r1] % regs[r2];
5981 			}
5982 			break;
5983 
5984 		case DIF_OP_NOT:
5985 			regs[rd] = ~regs[r1];
5986 			break;
5987 		case DIF_OP_MOV:
5988 			regs[rd] = regs[r1];
5989 			break;
5990 		case DIF_OP_CMP:
5991 			cc_r = regs[r1] - regs[r2];
5992 			cc_n = cc_r < 0;
5993 			cc_z = cc_r == 0;
5994 			cc_v = 0;
5995 			cc_c = regs[r1] < regs[r2];
5996 			break;
5997 		case DIF_OP_TST:
5998 			cc_n = cc_v = cc_c = 0;
5999 			cc_z = regs[r1] == 0;
6000 			break;
6001 		case DIF_OP_BA:
6002 			pc = DIF_INSTR_LABEL(instr);
6003 			break;
6004 		case DIF_OP_BE:
6005 			if (cc_z)
6006 				pc = DIF_INSTR_LABEL(instr);
6007 			break;
6008 		case DIF_OP_BNE:
6009 			if (cc_z == 0)
6010 				pc = DIF_INSTR_LABEL(instr);
6011 			break;
6012 		case DIF_OP_BG:
6013 			if ((cc_z | (cc_n ^ cc_v)) == 0)
6014 				pc = DIF_INSTR_LABEL(instr);
6015 			break;
6016 		case DIF_OP_BGU:
6017 			if ((cc_c | cc_z) == 0)
6018 				pc = DIF_INSTR_LABEL(instr);
6019 			break;
6020 		case DIF_OP_BGE:
6021 			if ((cc_n ^ cc_v) == 0)
6022 				pc = DIF_INSTR_LABEL(instr);
6023 			break;
6024 		case DIF_OP_BGEU:
6025 			if (cc_c == 0)
6026 				pc = DIF_INSTR_LABEL(instr);
6027 			break;
6028 		case DIF_OP_BL:
6029 			if (cc_n ^ cc_v)
6030 				pc = DIF_INSTR_LABEL(instr);
6031 			break;
6032 		case DIF_OP_BLU:
6033 			if (cc_c)
6034 				pc = DIF_INSTR_LABEL(instr);
6035 			break;
6036 		case DIF_OP_BLE:
6037 			if (cc_z | (cc_n ^ cc_v))
6038 				pc = DIF_INSTR_LABEL(instr);
6039 			break;
6040 		case DIF_OP_BLEU:
6041 			if (cc_c | cc_z)
6042 				pc = DIF_INSTR_LABEL(instr);
6043 			break;
6044 		case DIF_OP_RLDSB:
6045 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6046 				break;
6047 			/*FALLTHROUGH*/
6048 		case DIF_OP_LDSB:
6049 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6050 			break;
6051 		case DIF_OP_RLDSH:
6052 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6053 				break;
6054 			/*FALLTHROUGH*/
6055 		case DIF_OP_LDSH:
6056 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6057 			break;
6058 		case DIF_OP_RLDSW:
6059 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6060 				break;
6061 			/*FALLTHROUGH*/
6062 		case DIF_OP_LDSW:
6063 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6064 			break;
6065 		case DIF_OP_RLDUB:
6066 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6067 				break;
6068 			/*FALLTHROUGH*/
6069 		case DIF_OP_LDUB:
6070 			regs[rd] = dtrace_load8(regs[r1]);
6071 			break;
6072 		case DIF_OP_RLDUH:
6073 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6074 				break;
6075 			/*FALLTHROUGH*/
6076 		case DIF_OP_LDUH:
6077 			regs[rd] = dtrace_load16(regs[r1]);
6078 			break;
6079 		case DIF_OP_RLDUW:
6080 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6081 				break;
6082 			/*FALLTHROUGH*/
6083 		case DIF_OP_LDUW:
6084 			regs[rd] = dtrace_load32(regs[r1]);
6085 			break;
6086 		case DIF_OP_RLDX:
6087 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6088 				break;
6089 			/*FALLTHROUGH*/
6090 		case DIF_OP_LDX:
6091 			regs[rd] = dtrace_load64(regs[r1]);
6092 			break;
6093 		case DIF_OP_ULDSB:
6094 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6095 			regs[rd] = (int8_t)
6096 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6097 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6098 			break;
6099 		case DIF_OP_ULDSH:
6100 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6101 			regs[rd] = (int16_t)
6102 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6103 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6104 			break;
6105 		case DIF_OP_ULDSW:
6106 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6107 			regs[rd] = (int32_t)
6108 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6109 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6110 			break;
6111 		case DIF_OP_ULDUB:
6112 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6113 			regs[rd] =
6114 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6115 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6116 			break;
6117 		case DIF_OP_ULDUH:
6118 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6119 			regs[rd] =
6120 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6121 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6122 			break;
6123 		case DIF_OP_ULDUW:
6124 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6125 			regs[rd] =
6126 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6127 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6128 			break;
6129 		case DIF_OP_ULDX:
6130 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6131 			regs[rd] =
6132 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6133 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6134 			break;
6135 		case DIF_OP_RET:
6136 			rval = regs[rd];
6137 			pc = textlen;
6138 			break;
6139 		case DIF_OP_NOP:
6140 			break;
6141 		case DIF_OP_SETX:
6142 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6143 			break;
6144 		case DIF_OP_SETS:
6145 			regs[rd] = (uint64_t)(uintptr_t)
6146 			    (strtab + DIF_INSTR_STRING(instr));
6147 			break;
6148 		case DIF_OP_SCMP: {
6149 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6150 			uintptr_t s1 = regs[r1];
6151 			uintptr_t s2 = regs[r2];
6152 
6153 			if (s1 != 0 &&
6154 			    !dtrace_strcanload(s1, sz, mstate, vstate))
6155 				break;
6156 			if (s2 != 0 &&
6157 			    !dtrace_strcanload(s2, sz, mstate, vstate))
6158 				break;
6159 
6160 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
6161 
6162 			cc_n = cc_r < 0;
6163 			cc_z = cc_r == 0;
6164 			cc_v = cc_c = 0;
6165 			break;
6166 		}
6167 		case DIF_OP_LDGA:
6168 			regs[rd] = dtrace_dif_variable(mstate, state,
6169 			    r1, regs[r2]);
6170 			break;
6171 		case DIF_OP_LDGS:
6172 			id = DIF_INSTR_VAR(instr);
6173 
6174 			if (id >= DIF_VAR_OTHER_UBASE) {
6175 				uintptr_t a;
6176 
6177 				id -= DIF_VAR_OTHER_UBASE;
6178 				svar = vstate->dtvs_globals[id];
6179 				ASSERT(svar != NULL);
6180 				v = &svar->dtsv_var;
6181 
6182 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6183 					regs[rd] = svar->dtsv_data;
6184 					break;
6185 				}
6186 
6187 				a = (uintptr_t)svar->dtsv_data;
6188 
6189 				if (*(uint8_t *)a == UINT8_MAX) {
6190 					/*
6191 					 * If the 0th byte is set to UINT8_MAX
6192 					 * then this is to be treated as a
6193 					 * reference to a NULL variable.
6194 					 */
6195 					regs[rd] = 0;
6196 				} else {
6197 					regs[rd] = a + sizeof (uint64_t);
6198 				}
6199 
6200 				break;
6201 			}
6202 
6203 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6204 			break;
6205 
6206 		case DIF_OP_STGS:
6207 			id = DIF_INSTR_VAR(instr);
6208 
6209 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6210 			id -= DIF_VAR_OTHER_UBASE;
6211 
6212 			svar = vstate->dtvs_globals[id];
6213 			ASSERT(svar != NULL);
6214 			v = &svar->dtsv_var;
6215 
6216 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6217 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6218 
6219 				ASSERT(a != 0);
6220 				ASSERT(svar->dtsv_size != 0);
6221 
6222 				if (regs[rd] == 0) {
6223 					*(uint8_t *)a = UINT8_MAX;
6224 					break;
6225 				} else {
6226 					*(uint8_t *)a = 0;
6227 					a += sizeof (uint64_t);
6228 				}
6229 				if (!dtrace_vcanload(
6230 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6231 				    mstate, vstate))
6232 					break;
6233 
6234 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6235 				    (void *)a, &v->dtdv_type);
6236 				break;
6237 			}
6238 
6239 			svar->dtsv_data = regs[rd];
6240 			break;
6241 
6242 		case DIF_OP_LDTA:
6243 			/*
6244 			 * There are no DTrace built-in thread-local arrays at
6245 			 * present.  This opcode is saved for future work.
6246 			 */
6247 			*flags |= CPU_DTRACE_ILLOP;
6248 			regs[rd] = 0;
6249 			break;
6250 
6251 		case DIF_OP_LDLS:
6252 			id = DIF_INSTR_VAR(instr);
6253 
6254 			if (id < DIF_VAR_OTHER_UBASE) {
6255 				/*
6256 				 * For now, this has no meaning.
6257 				 */
6258 				regs[rd] = 0;
6259 				break;
6260 			}
6261 
6262 			id -= DIF_VAR_OTHER_UBASE;
6263 
6264 			ASSERT(id < vstate->dtvs_nlocals);
6265 			ASSERT(vstate->dtvs_locals != NULL);
6266 
6267 			svar = vstate->dtvs_locals[id];
6268 			ASSERT(svar != NULL);
6269 			v = &svar->dtsv_var;
6270 
6271 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6272 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6273 				size_t sz = v->dtdv_type.dtdt_size;
6274 
6275 				sz += sizeof (uint64_t);
6276 				ASSERT(svar->dtsv_size == NCPU * sz);
6277 				a += curcpu * sz;
6278 
6279 				if (*(uint8_t *)a == UINT8_MAX) {
6280 					/*
6281 					 * If the 0th byte is set to UINT8_MAX
6282 					 * then this is to be treated as a
6283 					 * reference to a NULL variable.
6284 					 */
6285 					regs[rd] = 0;
6286 				} else {
6287 					regs[rd] = a + sizeof (uint64_t);
6288 				}
6289 
6290 				break;
6291 			}
6292 
6293 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6294 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6295 			regs[rd] = tmp[curcpu];
6296 			break;
6297 
6298 		case DIF_OP_STLS:
6299 			id = DIF_INSTR_VAR(instr);
6300 
6301 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6302 			id -= DIF_VAR_OTHER_UBASE;
6303 			ASSERT(id < vstate->dtvs_nlocals);
6304 
6305 			ASSERT(vstate->dtvs_locals != NULL);
6306 			svar = vstate->dtvs_locals[id];
6307 			ASSERT(svar != NULL);
6308 			v = &svar->dtsv_var;
6309 
6310 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6311 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6312 				size_t sz = v->dtdv_type.dtdt_size;
6313 
6314 				sz += sizeof (uint64_t);
6315 				ASSERT(svar->dtsv_size == NCPU * sz);
6316 				a += curcpu * sz;
6317 
6318 				if (regs[rd] == 0) {
6319 					*(uint8_t *)a = UINT8_MAX;
6320 					break;
6321 				} else {
6322 					*(uint8_t *)a = 0;
6323 					a += sizeof (uint64_t);
6324 				}
6325 
6326 				if (!dtrace_vcanload(
6327 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6328 				    mstate, vstate))
6329 					break;
6330 
6331 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6332 				    (void *)a, &v->dtdv_type);
6333 				break;
6334 			}
6335 
6336 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6337 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6338 			tmp[curcpu] = regs[rd];
6339 			break;
6340 
6341 		case DIF_OP_LDTS: {
6342 			dtrace_dynvar_t *dvar;
6343 			dtrace_key_t *key;
6344 
6345 			id = DIF_INSTR_VAR(instr);
6346 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6347 			id -= DIF_VAR_OTHER_UBASE;
6348 			v = &vstate->dtvs_tlocals[id];
6349 
6350 			key = &tupregs[DIF_DTR_NREGS];
6351 			key[0].dttk_value = (uint64_t)id;
6352 			key[0].dttk_size = 0;
6353 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6354 			key[1].dttk_size = 0;
6355 
6356 			dvar = dtrace_dynvar(dstate, 2, key,
6357 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6358 			    mstate, vstate);
6359 
6360 			if (dvar == NULL) {
6361 				regs[rd] = 0;
6362 				break;
6363 			}
6364 
6365 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6366 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6367 			} else {
6368 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6369 			}
6370 
6371 			break;
6372 		}
6373 
6374 		case DIF_OP_STTS: {
6375 			dtrace_dynvar_t *dvar;
6376 			dtrace_key_t *key;
6377 
6378 			id = DIF_INSTR_VAR(instr);
6379 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6380 			id -= DIF_VAR_OTHER_UBASE;
6381 
6382 			key = &tupregs[DIF_DTR_NREGS];
6383 			key[0].dttk_value = (uint64_t)id;
6384 			key[0].dttk_size = 0;
6385 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6386 			key[1].dttk_size = 0;
6387 			v = &vstate->dtvs_tlocals[id];
6388 
6389 			dvar = dtrace_dynvar(dstate, 2, key,
6390 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6391 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6392 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6393 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6394 
6395 			/*
6396 			 * Given that we're storing to thread-local data,
6397 			 * we need to flush our predicate cache.
6398 			 */
6399 			curthread->t_predcache = 0;
6400 
6401 			if (dvar == NULL)
6402 				break;
6403 
6404 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6405 				if (!dtrace_vcanload(
6406 				    (void *)(uintptr_t)regs[rd],
6407 				    &v->dtdv_type, mstate, vstate))
6408 					break;
6409 
6410 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6411 				    dvar->dtdv_data, &v->dtdv_type);
6412 			} else {
6413 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6414 			}
6415 
6416 			break;
6417 		}
6418 
6419 		case DIF_OP_SRA:
6420 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6421 			break;
6422 
6423 		case DIF_OP_CALL:
6424 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6425 			    regs, tupregs, ttop, mstate, state);
6426 			break;
6427 
6428 		case DIF_OP_PUSHTR:
6429 			if (ttop == DIF_DTR_NREGS) {
6430 				*flags |= CPU_DTRACE_TUPOFLOW;
6431 				break;
6432 			}
6433 
6434 			if (r1 == DIF_TYPE_STRING) {
6435 				/*
6436 				 * If this is a string type and the size is 0,
6437 				 * we'll use the system-wide default string
6438 				 * size.  Note that we are _not_ looking at
6439 				 * the value of the DTRACEOPT_STRSIZE option;
6440 				 * had this been set, we would expect to have
6441 				 * a non-zero size value in the "pushtr".
6442 				 */
6443 				tupregs[ttop].dttk_size =
6444 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6445 				    regs[r2] ? regs[r2] :
6446 				    dtrace_strsize_default) + 1;
6447 			} else {
6448 				tupregs[ttop].dttk_size = regs[r2];
6449 			}
6450 
6451 			tupregs[ttop++].dttk_value = regs[rd];
6452 			break;
6453 
6454 		case DIF_OP_PUSHTV:
6455 			if (ttop == DIF_DTR_NREGS) {
6456 				*flags |= CPU_DTRACE_TUPOFLOW;
6457 				break;
6458 			}
6459 
6460 			tupregs[ttop].dttk_value = regs[rd];
6461 			tupregs[ttop++].dttk_size = 0;
6462 			break;
6463 
6464 		case DIF_OP_POPTS:
6465 			if (ttop != 0)
6466 				ttop--;
6467 			break;
6468 
6469 		case DIF_OP_FLUSHTS:
6470 			ttop = 0;
6471 			break;
6472 
6473 		case DIF_OP_LDGAA:
6474 		case DIF_OP_LDTAA: {
6475 			dtrace_dynvar_t *dvar;
6476 			dtrace_key_t *key = tupregs;
6477 			uint_t nkeys = ttop;
6478 
6479 			id = DIF_INSTR_VAR(instr);
6480 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6481 			id -= DIF_VAR_OTHER_UBASE;
6482 
6483 			key[nkeys].dttk_value = (uint64_t)id;
6484 			key[nkeys++].dttk_size = 0;
6485 
6486 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6487 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6488 				key[nkeys++].dttk_size = 0;
6489 				v = &vstate->dtvs_tlocals[id];
6490 			} else {
6491 				v = &vstate->dtvs_globals[id]->dtsv_var;
6492 			}
6493 
6494 			dvar = dtrace_dynvar(dstate, nkeys, key,
6495 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6496 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6497 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6498 
6499 			if (dvar == NULL) {
6500 				regs[rd] = 0;
6501 				break;
6502 			}
6503 
6504 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6505 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6506 			} else {
6507 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6508 			}
6509 
6510 			break;
6511 		}
6512 
6513 		case DIF_OP_STGAA:
6514 		case DIF_OP_STTAA: {
6515 			dtrace_dynvar_t *dvar;
6516 			dtrace_key_t *key = tupregs;
6517 			uint_t nkeys = ttop;
6518 
6519 			id = DIF_INSTR_VAR(instr);
6520 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6521 			id -= DIF_VAR_OTHER_UBASE;
6522 
6523 			key[nkeys].dttk_value = (uint64_t)id;
6524 			key[nkeys++].dttk_size = 0;
6525 
6526 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6527 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6528 				key[nkeys++].dttk_size = 0;
6529 				v = &vstate->dtvs_tlocals[id];
6530 			} else {
6531 				v = &vstate->dtvs_globals[id]->dtsv_var;
6532 			}
6533 
6534 			dvar = dtrace_dynvar(dstate, nkeys, key,
6535 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6536 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6537 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6538 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6539 
6540 			if (dvar == NULL)
6541 				break;
6542 
6543 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6544 				if (!dtrace_vcanload(
6545 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6546 				    mstate, vstate))
6547 					break;
6548 
6549 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6550 				    dvar->dtdv_data, &v->dtdv_type);
6551 			} else {
6552 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6553 			}
6554 
6555 			break;
6556 		}
6557 
6558 		case DIF_OP_ALLOCS: {
6559 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6560 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6561 
6562 			/*
6563 			 * Rounding up the user allocation size could have
6564 			 * overflowed large, bogus allocations (like -1ULL) to
6565 			 * 0.
6566 			 */
6567 			if (size < regs[r1] ||
6568 			    !DTRACE_INSCRATCH(mstate, size)) {
6569 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6570 				regs[rd] = 0;
6571 				break;
6572 			}
6573 
6574 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6575 			mstate->dtms_scratch_ptr += size;
6576 			regs[rd] = ptr;
6577 			break;
6578 		}
6579 
6580 		case DIF_OP_COPYS:
6581 			if (!dtrace_canstore(regs[rd], regs[r2],
6582 			    mstate, vstate)) {
6583 				*flags |= CPU_DTRACE_BADADDR;
6584 				*illval = regs[rd];
6585 				break;
6586 			}
6587 
6588 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6589 				break;
6590 
6591 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6592 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6593 			break;
6594 
6595 		case DIF_OP_STB:
6596 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6597 				*flags |= CPU_DTRACE_BADADDR;
6598 				*illval = regs[rd];
6599 				break;
6600 			}
6601 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6602 			break;
6603 
6604 		case DIF_OP_STH:
6605 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6606 				*flags |= CPU_DTRACE_BADADDR;
6607 				*illval = regs[rd];
6608 				break;
6609 			}
6610 			if (regs[rd] & 1) {
6611 				*flags |= CPU_DTRACE_BADALIGN;
6612 				*illval = regs[rd];
6613 				break;
6614 			}
6615 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6616 			break;
6617 
6618 		case DIF_OP_STW:
6619 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6620 				*flags |= CPU_DTRACE_BADADDR;
6621 				*illval = regs[rd];
6622 				break;
6623 			}
6624 			if (regs[rd] & 3) {
6625 				*flags |= CPU_DTRACE_BADALIGN;
6626 				*illval = regs[rd];
6627 				break;
6628 			}
6629 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6630 			break;
6631 
6632 		case DIF_OP_STX:
6633 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6634 				*flags |= CPU_DTRACE_BADADDR;
6635 				*illval = regs[rd];
6636 				break;
6637 			}
6638 			if (regs[rd] & 7) {
6639 				*flags |= CPU_DTRACE_BADALIGN;
6640 				*illval = regs[rd];
6641 				break;
6642 			}
6643 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6644 			break;
6645 		}
6646 	}
6647 
6648 	if (!(*flags & CPU_DTRACE_FAULT))
6649 		return (rval);
6650 
6651 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6652 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6653 
6654 	return (0);
6655 }
6656 
6657 static void
6658 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6659 {
6660 	dtrace_probe_t *probe = ecb->dte_probe;
6661 	dtrace_provider_t *prov = probe->dtpr_provider;
6662 	char c[DTRACE_FULLNAMELEN + 80], *str;
6663 	char *msg = "dtrace: breakpoint action at probe ";
6664 	char *ecbmsg = " (ecb ";
6665 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6666 	uintptr_t val = (uintptr_t)ecb;
6667 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6668 
6669 	if (dtrace_destructive_disallow)
6670 		return;
6671 
6672 	/*
6673 	 * It's impossible to be taking action on the NULL probe.
6674 	 */
6675 	ASSERT(probe != NULL);
6676 
6677 	/*
6678 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6679 	 * print the provider name, module name, function name and name of
6680 	 * the probe, along with the hex address of the ECB with the breakpoint
6681 	 * action -- all of which we must place in the character buffer by
6682 	 * hand.
6683 	 */
6684 	while (*msg != '\0')
6685 		c[i++] = *msg++;
6686 
6687 	for (str = prov->dtpv_name; *str != '\0'; str++)
6688 		c[i++] = *str;
6689 	c[i++] = ':';
6690 
6691 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6692 		c[i++] = *str;
6693 	c[i++] = ':';
6694 
6695 	for (str = probe->dtpr_func; *str != '\0'; str++)
6696 		c[i++] = *str;
6697 	c[i++] = ':';
6698 
6699 	for (str = probe->dtpr_name; *str != '\0'; str++)
6700 		c[i++] = *str;
6701 
6702 	while (*ecbmsg != '\0')
6703 		c[i++] = *ecbmsg++;
6704 
6705 	while (shift >= 0) {
6706 		mask = (uintptr_t)0xf << shift;
6707 
6708 		if (val >= ((uintptr_t)1 << shift))
6709 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6710 		shift -= 4;
6711 	}
6712 
6713 	c[i++] = ')';
6714 	c[i] = '\0';
6715 
6716 #if defined(sun)
6717 	debug_enter(c);
6718 #else
6719 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6720 #endif
6721 }
6722 
6723 static void
6724 dtrace_action_panic(dtrace_ecb_t *ecb)
6725 {
6726 	dtrace_probe_t *probe = ecb->dte_probe;
6727 
6728 	/*
6729 	 * It's impossible to be taking action on the NULL probe.
6730 	 */
6731 	ASSERT(probe != NULL);
6732 
6733 	if (dtrace_destructive_disallow)
6734 		return;
6735 
6736 	if (dtrace_panicked != NULL)
6737 		return;
6738 
6739 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6740 		return;
6741 
6742 	/*
6743 	 * We won the right to panic.  (We want to be sure that only one
6744 	 * thread calls panic() from dtrace_probe(), and that panic() is
6745 	 * called exactly once.)
6746 	 */
6747 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6748 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6749 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6750 }
6751 
6752 static void
6753 dtrace_action_raise(uint64_t sig)
6754 {
6755 	if (dtrace_destructive_disallow)
6756 		return;
6757 
6758 	if (sig >= NSIG) {
6759 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6760 		return;
6761 	}
6762 
6763 #if defined(sun)
6764 	/*
6765 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6766 	 * invocations of the raise() action.
6767 	 */
6768 	if (curthread->t_dtrace_sig == 0)
6769 		curthread->t_dtrace_sig = (uint8_t)sig;
6770 
6771 	curthread->t_sig_check = 1;
6772 	aston(curthread);
6773 #else
6774 	struct proc *p = curproc;
6775 	PROC_LOCK(p);
6776 	kern_psignal(p, sig);
6777 	PROC_UNLOCK(p);
6778 #endif
6779 }
6780 
6781 static void
6782 dtrace_action_stop(void)
6783 {
6784 	if (dtrace_destructive_disallow)
6785 		return;
6786 
6787 #if defined(sun)
6788 	if (!curthread->t_dtrace_stop) {
6789 		curthread->t_dtrace_stop = 1;
6790 		curthread->t_sig_check = 1;
6791 		aston(curthread);
6792 	}
6793 #else
6794 	struct proc *p = curproc;
6795 	PROC_LOCK(p);
6796 	kern_psignal(p, SIGSTOP);
6797 	PROC_UNLOCK(p);
6798 #endif
6799 }
6800 
6801 static void
6802 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6803 {
6804 	hrtime_t now;
6805 	volatile uint16_t *flags;
6806 #if defined(sun)
6807 	cpu_t *cpu = CPU;
6808 #else
6809 	cpu_t *cpu = &solaris_cpu[curcpu];
6810 #endif
6811 
6812 	if (dtrace_destructive_disallow)
6813 		return;
6814 
6815 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6816 
6817 	now = dtrace_gethrtime();
6818 
6819 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6820 		/*
6821 		 * We need to advance the mark to the current time.
6822 		 */
6823 		cpu->cpu_dtrace_chillmark = now;
6824 		cpu->cpu_dtrace_chilled = 0;
6825 	}
6826 
6827 	/*
6828 	 * Now check to see if the requested chill time would take us over
6829 	 * the maximum amount of time allowed in the chill interval.  (Or
6830 	 * worse, if the calculation itself induces overflow.)
6831 	 */
6832 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6833 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6834 		*flags |= CPU_DTRACE_ILLOP;
6835 		return;
6836 	}
6837 
6838 	while (dtrace_gethrtime() - now < val)
6839 		continue;
6840 
6841 	/*
6842 	 * Normally, we assure that the value of the variable "timestamp" does
6843 	 * not change within an ECB.  The presence of chill() represents an
6844 	 * exception to this rule, however.
6845 	 */
6846 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6847 	cpu->cpu_dtrace_chilled += val;
6848 }
6849 
6850 static void
6851 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6852     uint64_t *buf, uint64_t arg)
6853 {
6854 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6855 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6856 	uint64_t *pcs = &buf[1], *fps;
6857 	char *str = (char *)&pcs[nframes];
6858 	int size, offs = 0, i, j;
6859 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6860 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6861 	char *sym;
6862 
6863 	/*
6864 	 * Should be taking a faster path if string space has not been
6865 	 * allocated.
6866 	 */
6867 	ASSERT(strsize != 0);
6868 
6869 	/*
6870 	 * We will first allocate some temporary space for the frame pointers.
6871 	 */
6872 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6873 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6874 	    (nframes * sizeof (uint64_t));
6875 
6876 	if (!DTRACE_INSCRATCH(mstate, size)) {
6877 		/*
6878 		 * Not enough room for our frame pointers -- need to indicate
6879 		 * that we ran out of scratch space.
6880 		 */
6881 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6882 		return;
6883 	}
6884 
6885 	mstate->dtms_scratch_ptr += size;
6886 	saved = mstate->dtms_scratch_ptr;
6887 
6888 	/*
6889 	 * Now get a stack with both program counters and frame pointers.
6890 	 */
6891 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6892 	dtrace_getufpstack(buf, fps, nframes + 1);
6893 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6894 
6895 	/*
6896 	 * If that faulted, we're cooked.
6897 	 */
6898 	if (*flags & CPU_DTRACE_FAULT)
6899 		goto out;
6900 
6901 	/*
6902 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6903 	 * each iteration, we restore the scratch pointer.
6904 	 */
6905 	for (i = 0; i < nframes; i++) {
6906 		mstate->dtms_scratch_ptr = saved;
6907 
6908 		if (offs >= strsize)
6909 			break;
6910 
6911 		sym = (char *)(uintptr_t)dtrace_helper(
6912 		    DTRACE_HELPER_ACTION_USTACK,
6913 		    mstate, state, pcs[i], fps[i]);
6914 
6915 		/*
6916 		 * If we faulted while running the helper, we're going to
6917 		 * clear the fault and null out the corresponding string.
6918 		 */
6919 		if (*flags & CPU_DTRACE_FAULT) {
6920 			*flags &= ~CPU_DTRACE_FAULT;
6921 			str[offs++] = '\0';
6922 			continue;
6923 		}
6924 
6925 		if (sym == NULL) {
6926 			str[offs++] = '\0';
6927 			continue;
6928 		}
6929 
6930 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6931 
6932 		/*
6933 		 * Now copy in the string that the helper returned to us.
6934 		 */
6935 		for (j = 0; offs + j < strsize; j++) {
6936 			if ((str[offs + j] = sym[j]) == '\0')
6937 				break;
6938 		}
6939 
6940 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6941 
6942 		offs += j + 1;
6943 	}
6944 
6945 	if (offs >= strsize) {
6946 		/*
6947 		 * If we didn't have room for all of the strings, we don't
6948 		 * abort processing -- this needn't be a fatal error -- but we
6949 		 * still want to increment a counter (dts_stkstroverflows) to
6950 		 * allow this condition to be warned about.  (If this is from
6951 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6952 		 */
6953 		dtrace_error(&state->dts_stkstroverflows);
6954 	}
6955 
6956 	while (offs < strsize)
6957 		str[offs++] = '\0';
6958 
6959 out:
6960 	mstate->dtms_scratch_ptr = old;
6961 }
6962 
6963 static void
6964 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6965     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6966 {
6967 	volatile uint16_t *flags;
6968 	uint64_t val = *valp;
6969 	size_t valoffs = *valoffsp;
6970 
6971 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6972 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6973 
6974 	/*
6975 	 * If this is a string, we're going to only load until we find the zero
6976 	 * byte -- after which we'll store zero bytes.
6977 	 */
6978 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6979 		char c = '\0' + 1;
6980 		size_t s;
6981 
6982 		for (s = 0; s < size; s++) {
6983 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6984 				c = dtrace_load8(val++);
6985 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6986 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6987 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6988 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6989 				if (*flags & CPU_DTRACE_FAULT)
6990 					break;
6991 			}
6992 
6993 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6994 
6995 			if (c == '\0' && intuple)
6996 				break;
6997 		}
6998 	} else {
6999 		uint8_t c;
7000 		while (valoffs < end) {
7001 			if (dtkind == DIF_TF_BYREF) {
7002 				c = dtrace_load8(val++);
7003 			} else if (dtkind == DIF_TF_BYUREF) {
7004 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7005 				c = dtrace_fuword8((void *)(uintptr_t)val++);
7006 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7007 				if (*flags & CPU_DTRACE_FAULT)
7008 					break;
7009 			}
7010 
7011 			DTRACE_STORE(uint8_t, tomax,
7012 			    valoffs++, c);
7013 		}
7014 	}
7015 
7016 	*valp = val;
7017 	*valoffsp = valoffs;
7018 }
7019 
7020 /*
7021  * If you're looking for the epicenter of DTrace, you just found it.  This
7022  * is the function called by the provider to fire a probe -- from which all
7023  * subsequent probe-context DTrace activity emanates.
7024  */
7025 void
7026 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7027     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7028 {
7029 	processorid_t cpuid;
7030 	dtrace_icookie_t cookie;
7031 	dtrace_probe_t *probe;
7032 	dtrace_mstate_t mstate;
7033 	dtrace_ecb_t *ecb;
7034 	dtrace_action_t *act;
7035 	intptr_t offs;
7036 	size_t size;
7037 	int vtime, onintr;
7038 	volatile uint16_t *flags;
7039 	hrtime_t now;
7040 
7041 	if (panicstr != NULL)
7042 		return;
7043 
7044 #if defined(sun)
7045 	/*
7046 	 * Kick out immediately if this CPU is still being born (in which case
7047 	 * curthread will be set to -1) or the current thread can't allow
7048 	 * probes in its current context.
7049 	 */
7050 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7051 		return;
7052 #endif
7053 
7054 	cookie = dtrace_interrupt_disable();
7055 	probe = dtrace_probes[id - 1];
7056 	cpuid = curcpu;
7057 	onintr = CPU_ON_INTR(CPU);
7058 
7059 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7060 	    probe->dtpr_predcache == curthread->t_predcache) {
7061 		/*
7062 		 * We have hit in the predicate cache; we know that
7063 		 * this predicate would evaluate to be false.
7064 		 */
7065 		dtrace_interrupt_enable(cookie);
7066 		return;
7067 	}
7068 
7069 #if defined(sun)
7070 	if (panic_quiesce) {
7071 #else
7072 	if (panicstr != NULL) {
7073 #endif
7074 		/*
7075 		 * We don't trace anything if we're panicking.
7076 		 */
7077 		dtrace_interrupt_enable(cookie);
7078 		return;
7079 	}
7080 
7081 	now = dtrace_gethrtime();
7082 	vtime = dtrace_vtime_references != 0;
7083 
7084 	if (vtime && curthread->t_dtrace_start)
7085 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7086 
7087 	mstate.dtms_difo = NULL;
7088 	mstate.dtms_probe = probe;
7089 	mstate.dtms_strtok = 0;
7090 	mstate.dtms_arg[0] = arg0;
7091 	mstate.dtms_arg[1] = arg1;
7092 	mstate.dtms_arg[2] = arg2;
7093 	mstate.dtms_arg[3] = arg3;
7094 	mstate.dtms_arg[4] = arg4;
7095 
7096 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7097 
7098 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7099 		dtrace_predicate_t *pred = ecb->dte_predicate;
7100 		dtrace_state_t *state = ecb->dte_state;
7101 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7102 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7103 		dtrace_vstate_t *vstate = &state->dts_vstate;
7104 		dtrace_provider_t *prov = probe->dtpr_provider;
7105 		uint64_t tracememsize = 0;
7106 		int committed = 0;
7107 		caddr_t tomax;
7108 
7109 		/*
7110 		 * A little subtlety with the following (seemingly innocuous)
7111 		 * declaration of the automatic 'val':  by looking at the
7112 		 * code, you might think that it could be declared in the
7113 		 * action processing loop, below.  (That is, it's only used in
7114 		 * the action processing loop.)  However, it must be declared
7115 		 * out of that scope because in the case of DIF expression
7116 		 * arguments to aggregating actions, one iteration of the
7117 		 * action loop will use the last iteration's value.
7118 		 */
7119 		uint64_t val = 0;
7120 
7121 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7122 		mstate.dtms_getf = NULL;
7123 
7124 		*flags &= ~CPU_DTRACE_ERROR;
7125 
7126 		if (prov == dtrace_provider) {
7127 			/*
7128 			 * If dtrace itself is the provider of this probe,
7129 			 * we're only going to continue processing the ECB if
7130 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7131 			 * creating state.  (This prevents disjoint consumers
7132 			 * from seeing one another's metaprobes.)
7133 			 */
7134 			if (arg0 != (uint64_t)(uintptr_t)state)
7135 				continue;
7136 		}
7137 
7138 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7139 			/*
7140 			 * We're not currently active.  If our provider isn't
7141 			 * the dtrace pseudo provider, we're not interested.
7142 			 */
7143 			if (prov != dtrace_provider)
7144 				continue;
7145 
7146 			/*
7147 			 * Now we must further check if we are in the BEGIN
7148 			 * probe.  If we are, we will only continue processing
7149 			 * if we're still in WARMUP -- if one BEGIN enabling
7150 			 * has invoked the exit() action, we don't want to
7151 			 * evaluate subsequent BEGIN enablings.
7152 			 */
7153 			if (probe->dtpr_id == dtrace_probeid_begin &&
7154 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7155 				ASSERT(state->dts_activity ==
7156 				    DTRACE_ACTIVITY_DRAINING);
7157 				continue;
7158 			}
7159 		}
7160 
7161 		if (ecb->dte_cond) {
7162 			/*
7163 			 * If the dte_cond bits indicate that this
7164 			 * consumer is only allowed to see user-mode firings
7165 			 * of this probe, call the provider's dtps_usermode()
7166 			 * entry point to check that the probe was fired
7167 			 * while in a user context. Skip this ECB if that's
7168 			 * not the case.
7169 			 */
7170 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7171 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7172 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7173 				continue;
7174 
7175 #if defined(sun)
7176 			/*
7177 			 * This is more subtle than it looks. We have to be
7178 			 * absolutely certain that CRED() isn't going to
7179 			 * change out from under us so it's only legit to
7180 			 * examine that structure if we're in constrained
7181 			 * situations. Currently, the only times we'll this
7182 			 * check is if a non-super-user has enabled the
7183 			 * profile or syscall providers -- providers that
7184 			 * allow visibility of all processes. For the
7185 			 * profile case, the check above will ensure that
7186 			 * we're examining a user context.
7187 			 */
7188 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7189 				cred_t *cr;
7190 				cred_t *s_cr =
7191 				    ecb->dte_state->dts_cred.dcr_cred;
7192 				proc_t *proc;
7193 
7194 				ASSERT(s_cr != NULL);
7195 
7196 				if ((cr = CRED()) == NULL ||
7197 				    s_cr->cr_uid != cr->cr_uid ||
7198 				    s_cr->cr_uid != cr->cr_ruid ||
7199 				    s_cr->cr_uid != cr->cr_suid ||
7200 				    s_cr->cr_gid != cr->cr_gid ||
7201 				    s_cr->cr_gid != cr->cr_rgid ||
7202 				    s_cr->cr_gid != cr->cr_sgid ||
7203 				    (proc = ttoproc(curthread)) == NULL ||
7204 				    (proc->p_flag & SNOCD))
7205 					continue;
7206 			}
7207 
7208 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7209 				cred_t *cr;
7210 				cred_t *s_cr =
7211 				    ecb->dte_state->dts_cred.dcr_cred;
7212 
7213 				ASSERT(s_cr != NULL);
7214 
7215 				if ((cr = CRED()) == NULL ||
7216 				    s_cr->cr_zone->zone_id !=
7217 				    cr->cr_zone->zone_id)
7218 					continue;
7219 			}
7220 #endif
7221 		}
7222 
7223 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7224 			/*
7225 			 * We seem to be dead.  Unless we (a) have kernel
7226 			 * destructive permissions (b) have explicitly enabled
7227 			 * destructive actions and (c) destructive actions have
7228 			 * not been disabled, we're going to transition into
7229 			 * the KILLED state, from which no further processing
7230 			 * on this state will be performed.
7231 			 */
7232 			if (!dtrace_priv_kernel_destructive(state) ||
7233 			    !state->dts_cred.dcr_destructive ||
7234 			    dtrace_destructive_disallow) {
7235 				void *activity = &state->dts_activity;
7236 				dtrace_activity_t current;
7237 
7238 				do {
7239 					current = state->dts_activity;
7240 				} while (dtrace_cas32(activity, current,
7241 				    DTRACE_ACTIVITY_KILLED) != current);
7242 
7243 				continue;
7244 			}
7245 		}
7246 
7247 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7248 		    ecb->dte_alignment, state, &mstate)) < 0)
7249 			continue;
7250 
7251 		tomax = buf->dtb_tomax;
7252 		ASSERT(tomax != NULL);
7253 
7254 		if (ecb->dte_size != 0) {
7255 			dtrace_rechdr_t dtrh;
7256 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7257 				mstate.dtms_timestamp = dtrace_gethrtime();
7258 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7259 			}
7260 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7261 			dtrh.dtrh_epid = ecb->dte_epid;
7262 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7263 			    mstate.dtms_timestamp);
7264 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7265 		}
7266 
7267 		mstate.dtms_epid = ecb->dte_epid;
7268 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7269 
7270 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7271 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7272 		else
7273 			mstate.dtms_access = 0;
7274 
7275 		if (pred != NULL) {
7276 			dtrace_difo_t *dp = pred->dtp_difo;
7277 			int rval;
7278 
7279 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7280 
7281 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7282 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7283 
7284 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7285 					/*
7286 					 * Update the predicate cache...
7287 					 */
7288 					ASSERT(cid == pred->dtp_cacheid);
7289 					curthread->t_predcache = cid;
7290 				}
7291 
7292 				continue;
7293 			}
7294 		}
7295 
7296 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7297 		    act != NULL; act = act->dta_next) {
7298 			size_t valoffs;
7299 			dtrace_difo_t *dp;
7300 			dtrace_recdesc_t *rec = &act->dta_rec;
7301 
7302 			size = rec->dtrd_size;
7303 			valoffs = offs + rec->dtrd_offset;
7304 
7305 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7306 				uint64_t v = 0xbad;
7307 				dtrace_aggregation_t *agg;
7308 
7309 				agg = (dtrace_aggregation_t *)act;
7310 
7311 				if ((dp = act->dta_difo) != NULL)
7312 					v = dtrace_dif_emulate(dp,
7313 					    &mstate, vstate, state);
7314 
7315 				if (*flags & CPU_DTRACE_ERROR)
7316 					continue;
7317 
7318 				/*
7319 				 * Note that we always pass the expression
7320 				 * value from the previous iteration of the
7321 				 * action loop.  This value will only be used
7322 				 * if there is an expression argument to the
7323 				 * aggregating action, denoted by the
7324 				 * dtag_hasarg field.
7325 				 */
7326 				dtrace_aggregate(agg, buf,
7327 				    offs, aggbuf, v, val);
7328 				continue;
7329 			}
7330 
7331 			switch (act->dta_kind) {
7332 			case DTRACEACT_STOP:
7333 				if (dtrace_priv_proc_destructive(state))
7334 					dtrace_action_stop();
7335 				continue;
7336 
7337 			case DTRACEACT_BREAKPOINT:
7338 				if (dtrace_priv_kernel_destructive(state))
7339 					dtrace_action_breakpoint(ecb);
7340 				continue;
7341 
7342 			case DTRACEACT_PANIC:
7343 				if (dtrace_priv_kernel_destructive(state))
7344 					dtrace_action_panic(ecb);
7345 				continue;
7346 
7347 			case DTRACEACT_STACK:
7348 				if (!dtrace_priv_kernel(state))
7349 					continue;
7350 
7351 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7352 				    size / sizeof (pc_t), probe->dtpr_aframes,
7353 				    DTRACE_ANCHORED(probe) ? NULL :
7354 				    (uint32_t *)arg0);
7355 				continue;
7356 
7357 			case DTRACEACT_JSTACK:
7358 			case DTRACEACT_USTACK:
7359 				if (!dtrace_priv_proc(state))
7360 					continue;
7361 
7362 				/*
7363 				 * See comment in DIF_VAR_PID.
7364 				 */
7365 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7366 				    CPU_ON_INTR(CPU)) {
7367 					int depth = DTRACE_USTACK_NFRAMES(
7368 					    rec->dtrd_arg) + 1;
7369 
7370 					dtrace_bzero((void *)(tomax + valoffs),
7371 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7372 					    + depth * sizeof (uint64_t));
7373 
7374 					continue;
7375 				}
7376 
7377 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7378 				    curproc->p_dtrace_helpers != NULL) {
7379 					/*
7380 					 * This is the slow path -- we have
7381 					 * allocated string space, and we're
7382 					 * getting the stack of a process that
7383 					 * has helpers.  Call into a separate
7384 					 * routine to perform this processing.
7385 					 */
7386 					dtrace_action_ustack(&mstate, state,
7387 					    (uint64_t *)(tomax + valoffs),
7388 					    rec->dtrd_arg);
7389 					continue;
7390 				}
7391 
7392 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7393 				dtrace_getupcstack((uint64_t *)
7394 				    (tomax + valoffs),
7395 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7396 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7397 				continue;
7398 
7399 			default:
7400 				break;
7401 			}
7402 
7403 			dp = act->dta_difo;
7404 			ASSERT(dp != NULL);
7405 
7406 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7407 
7408 			if (*flags & CPU_DTRACE_ERROR)
7409 				continue;
7410 
7411 			switch (act->dta_kind) {
7412 			case DTRACEACT_SPECULATE: {
7413 				dtrace_rechdr_t *dtrh;
7414 
7415 				ASSERT(buf == &state->dts_buffer[cpuid]);
7416 				buf = dtrace_speculation_buffer(state,
7417 				    cpuid, val);
7418 
7419 				if (buf == NULL) {
7420 					*flags |= CPU_DTRACE_DROP;
7421 					continue;
7422 				}
7423 
7424 				offs = dtrace_buffer_reserve(buf,
7425 				    ecb->dte_needed, ecb->dte_alignment,
7426 				    state, NULL);
7427 
7428 				if (offs < 0) {
7429 					*flags |= CPU_DTRACE_DROP;
7430 					continue;
7431 				}
7432 
7433 				tomax = buf->dtb_tomax;
7434 				ASSERT(tomax != NULL);
7435 
7436 				if (ecb->dte_size == 0)
7437 					continue;
7438 
7439 				ASSERT3U(ecb->dte_size, >=,
7440 				    sizeof (dtrace_rechdr_t));
7441 				dtrh = ((void *)(tomax + offs));
7442 				dtrh->dtrh_epid = ecb->dte_epid;
7443 				/*
7444 				 * When the speculation is committed, all of
7445 				 * the records in the speculative buffer will
7446 				 * have their timestamps set to the commit
7447 				 * time.  Until then, it is set to a sentinel
7448 				 * value, for debugability.
7449 				 */
7450 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7451 				continue;
7452 			}
7453 
7454 			case DTRACEACT_PRINTM: {
7455 				/* The DIF returns a 'memref'. */
7456 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7457 
7458 				/* Get the size from the memref. */
7459 				size = memref[1];
7460 
7461 				/*
7462 				 * Check if the size exceeds the allocated
7463 				 * buffer size.
7464 				 */
7465 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7466 					/* Flag a drop! */
7467 					*flags |= CPU_DTRACE_DROP;
7468 					continue;
7469 				}
7470 
7471 				/* Store the size in the buffer first. */
7472 				DTRACE_STORE(uintptr_t, tomax,
7473 				    valoffs, size);
7474 
7475 				/*
7476 				 * Offset the buffer address to the start
7477 				 * of the data.
7478 				 */
7479 				valoffs += sizeof(uintptr_t);
7480 
7481 				/*
7482 				 * Reset to the memory address rather than
7483 				 * the memref array, then let the BYREF
7484 				 * code below do the work to store the
7485 				 * memory data in the buffer.
7486 				 */
7487 				val = memref[0];
7488 				break;
7489 			}
7490 
7491 			case DTRACEACT_PRINTT: {
7492 				/* The DIF returns a 'typeref'. */
7493 				uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
7494 				char c = '\0' + 1;
7495 				size_t s;
7496 
7497 				/*
7498 				 * Get the type string length and round it
7499 				 * up so that the data that follows is
7500 				 * aligned for easy access.
7501 				 */
7502 				size_t typs = strlen((char *) typeref[2]) + 1;
7503 				typs = roundup(typs,  sizeof(uintptr_t));
7504 
7505 				/*
7506 				 *Get the size from the typeref using the
7507 				 * number of elements and the type size.
7508 				 */
7509 				size = typeref[1] * typeref[3];
7510 
7511 				/*
7512 				 * Check if the size exceeds the allocated
7513 				 * buffer size.
7514 				 */
7515 				if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7516 					/* Flag a drop! */
7517 					*flags |= CPU_DTRACE_DROP;
7518 
7519 				}
7520 
7521 				/* Store the size in the buffer first. */
7522 				DTRACE_STORE(uintptr_t, tomax,
7523 				    valoffs, size);
7524 				valoffs += sizeof(uintptr_t);
7525 
7526 				/* Store the type size in the buffer. */
7527 				DTRACE_STORE(uintptr_t, tomax,
7528 				    valoffs, typeref[3]);
7529 				valoffs += sizeof(uintptr_t);
7530 
7531 				val = typeref[2];
7532 
7533 				for (s = 0; s < typs; s++) {
7534 					if (c != '\0')
7535 						c = dtrace_load8(val++);
7536 
7537 					DTRACE_STORE(uint8_t, tomax,
7538 					    valoffs++, c);
7539 				}
7540 
7541 				/*
7542 				 * Reset to the memory address rather than
7543 				 * the typeref array, then let the BYREF
7544 				 * code below do the work to store the
7545 				 * memory data in the buffer.
7546 				 */
7547 				val = typeref[0];
7548 				break;
7549 			}
7550 
7551 			case DTRACEACT_CHILL:
7552 				if (dtrace_priv_kernel_destructive(state))
7553 					dtrace_action_chill(&mstate, val);
7554 				continue;
7555 
7556 			case DTRACEACT_RAISE:
7557 				if (dtrace_priv_proc_destructive(state))
7558 					dtrace_action_raise(val);
7559 				continue;
7560 
7561 			case DTRACEACT_COMMIT:
7562 				ASSERT(!committed);
7563 
7564 				/*
7565 				 * We need to commit our buffer state.
7566 				 */
7567 				if (ecb->dte_size)
7568 					buf->dtb_offset = offs + ecb->dte_size;
7569 				buf = &state->dts_buffer[cpuid];
7570 				dtrace_speculation_commit(state, cpuid, val);
7571 				committed = 1;
7572 				continue;
7573 
7574 			case DTRACEACT_DISCARD:
7575 				dtrace_speculation_discard(state, cpuid, val);
7576 				continue;
7577 
7578 			case DTRACEACT_DIFEXPR:
7579 			case DTRACEACT_LIBACT:
7580 			case DTRACEACT_PRINTF:
7581 			case DTRACEACT_PRINTA:
7582 			case DTRACEACT_SYSTEM:
7583 			case DTRACEACT_FREOPEN:
7584 			case DTRACEACT_TRACEMEM:
7585 				break;
7586 
7587 			case DTRACEACT_TRACEMEM_DYNSIZE:
7588 				tracememsize = val;
7589 				break;
7590 
7591 			case DTRACEACT_SYM:
7592 			case DTRACEACT_MOD:
7593 				if (!dtrace_priv_kernel(state))
7594 					continue;
7595 				break;
7596 
7597 			case DTRACEACT_USYM:
7598 			case DTRACEACT_UMOD:
7599 			case DTRACEACT_UADDR: {
7600 #if defined(sun)
7601 				struct pid *pid = curthread->t_procp->p_pidp;
7602 #endif
7603 
7604 				if (!dtrace_priv_proc(state))
7605 					continue;
7606 
7607 				DTRACE_STORE(uint64_t, tomax,
7608 #if defined(sun)
7609 				    valoffs, (uint64_t)pid->pid_id);
7610 #else
7611 				    valoffs, (uint64_t) curproc->p_pid);
7612 #endif
7613 				DTRACE_STORE(uint64_t, tomax,
7614 				    valoffs + sizeof (uint64_t), val);
7615 
7616 				continue;
7617 			}
7618 
7619 			case DTRACEACT_EXIT: {
7620 				/*
7621 				 * For the exit action, we are going to attempt
7622 				 * to atomically set our activity to be
7623 				 * draining.  If this fails (either because
7624 				 * another CPU has beat us to the exit action,
7625 				 * or because our current activity is something
7626 				 * other than ACTIVE or WARMUP), we will
7627 				 * continue.  This assures that the exit action
7628 				 * can be successfully recorded at most once
7629 				 * when we're in the ACTIVE state.  If we're
7630 				 * encountering the exit() action while in
7631 				 * COOLDOWN, however, we want to honor the new
7632 				 * status code.  (We know that we're the only
7633 				 * thread in COOLDOWN, so there is no race.)
7634 				 */
7635 				void *activity = &state->dts_activity;
7636 				dtrace_activity_t current = state->dts_activity;
7637 
7638 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7639 					break;
7640 
7641 				if (current != DTRACE_ACTIVITY_WARMUP)
7642 					current = DTRACE_ACTIVITY_ACTIVE;
7643 
7644 				if (dtrace_cas32(activity, current,
7645 				    DTRACE_ACTIVITY_DRAINING) != current) {
7646 					*flags |= CPU_DTRACE_DROP;
7647 					continue;
7648 				}
7649 
7650 				break;
7651 			}
7652 
7653 			default:
7654 				ASSERT(0);
7655 			}
7656 
7657 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7658 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7659 				uintptr_t end = valoffs + size;
7660 
7661 				if (tracememsize != 0 &&
7662 				    valoffs + tracememsize < end) {
7663 					end = valoffs + tracememsize;
7664 					tracememsize = 0;
7665 				}
7666 
7667 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7668 				    !dtrace_vcanload((void *)(uintptr_t)val,
7669 				    &dp->dtdo_rtype, &mstate, vstate))
7670 					continue;
7671 
7672 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7673 				    &val, end, act->dta_intuple,
7674 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7675 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7676 				continue;
7677 			}
7678 
7679 			switch (size) {
7680 			case 0:
7681 				break;
7682 
7683 			case sizeof (uint8_t):
7684 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7685 				break;
7686 			case sizeof (uint16_t):
7687 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7688 				break;
7689 			case sizeof (uint32_t):
7690 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7691 				break;
7692 			case sizeof (uint64_t):
7693 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7694 				break;
7695 			default:
7696 				/*
7697 				 * Any other size should have been returned by
7698 				 * reference, not by value.
7699 				 */
7700 				ASSERT(0);
7701 				break;
7702 			}
7703 		}
7704 
7705 		if (*flags & CPU_DTRACE_DROP)
7706 			continue;
7707 
7708 		if (*flags & CPU_DTRACE_FAULT) {
7709 			int ndx;
7710 			dtrace_action_t *err;
7711 
7712 			buf->dtb_errors++;
7713 
7714 			if (probe->dtpr_id == dtrace_probeid_error) {
7715 				/*
7716 				 * There's nothing we can do -- we had an
7717 				 * error on the error probe.  We bump an
7718 				 * error counter to at least indicate that
7719 				 * this condition happened.
7720 				 */
7721 				dtrace_error(&state->dts_dblerrors);
7722 				continue;
7723 			}
7724 
7725 			if (vtime) {
7726 				/*
7727 				 * Before recursing on dtrace_probe(), we
7728 				 * need to explicitly clear out our start
7729 				 * time to prevent it from being accumulated
7730 				 * into t_dtrace_vtime.
7731 				 */
7732 				curthread->t_dtrace_start = 0;
7733 			}
7734 
7735 			/*
7736 			 * Iterate over the actions to figure out which action
7737 			 * we were processing when we experienced the error.
7738 			 * Note that act points _past_ the faulting action; if
7739 			 * act is ecb->dte_action, the fault was in the
7740 			 * predicate, if it's ecb->dte_action->dta_next it's
7741 			 * in action #1, and so on.
7742 			 */
7743 			for (err = ecb->dte_action, ndx = 0;
7744 			    err != act; err = err->dta_next, ndx++)
7745 				continue;
7746 
7747 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7748 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7749 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7750 			    cpu_core[cpuid].cpuc_dtrace_illval);
7751 
7752 			continue;
7753 		}
7754 
7755 		if (!committed)
7756 			buf->dtb_offset = offs + ecb->dte_size;
7757 	}
7758 
7759 	if (vtime)
7760 		curthread->t_dtrace_start = dtrace_gethrtime();
7761 
7762 	dtrace_interrupt_enable(cookie);
7763 }
7764 
7765 /*
7766  * DTrace Probe Hashing Functions
7767  *
7768  * The functions in this section (and indeed, the functions in remaining
7769  * sections) are not _called_ from probe context.  (Any exceptions to this are
7770  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7771  * DTrace framework to look-up probes in, add probes to and remove probes from
7772  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7773  * probe tuple -- allowing for fast lookups, regardless of what was
7774  * specified.)
7775  */
7776 static uint_t
7777 dtrace_hash_str(const char *p)
7778 {
7779 	unsigned int g;
7780 	uint_t hval = 0;
7781 
7782 	while (*p) {
7783 		hval = (hval << 4) + *p++;
7784 		if ((g = (hval & 0xf0000000)) != 0)
7785 			hval ^= g >> 24;
7786 		hval &= ~g;
7787 	}
7788 	return (hval);
7789 }
7790 
7791 static dtrace_hash_t *
7792 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7793 {
7794 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7795 
7796 	hash->dth_stroffs = stroffs;
7797 	hash->dth_nextoffs = nextoffs;
7798 	hash->dth_prevoffs = prevoffs;
7799 
7800 	hash->dth_size = 1;
7801 	hash->dth_mask = hash->dth_size - 1;
7802 
7803 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7804 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7805 
7806 	return (hash);
7807 }
7808 
7809 static void
7810 dtrace_hash_destroy(dtrace_hash_t *hash)
7811 {
7812 #ifdef DEBUG
7813 	int i;
7814 
7815 	for (i = 0; i < hash->dth_size; i++)
7816 		ASSERT(hash->dth_tab[i] == NULL);
7817 #endif
7818 
7819 	kmem_free(hash->dth_tab,
7820 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7821 	kmem_free(hash, sizeof (dtrace_hash_t));
7822 }
7823 
7824 static void
7825 dtrace_hash_resize(dtrace_hash_t *hash)
7826 {
7827 	int size = hash->dth_size, i, ndx;
7828 	int new_size = hash->dth_size << 1;
7829 	int new_mask = new_size - 1;
7830 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7831 
7832 	ASSERT((new_size & new_mask) == 0);
7833 
7834 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7835 
7836 	for (i = 0; i < size; i++) {
7837 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7838 			dtrace_probe_t *probe = bucket->dthb_chain;
7839 
7840 			ASSERT(probe != NULL);
7841 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7842 
7843 			next = bucket->dthb_next;
7844 			bucket->dthb_next = new_tab[ndx];
7845 			new_tab[ndx] = bucket;
7846 		}
7847 	}
7848 
7849 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7850 	hash->dth_tab = new_tab;
7851 	hash->dth_size = new_size;
7852 	hash->dth_mask = new_mask;
7853 }
7854 
7855 static void
7856 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7857 {
7858 	int hashval = DTRACE_HASHSTR(hash, new);
7859 	int ndx = hashval & hash->dth_mask;
7860 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7861 	dtrace_probe_t **nextp, **prevp;
7862 
7863 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7864 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7865 			goto add;
7866 	}
7867 
7868 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7869 		dtrace_hash_resize(hash);
7870 		dtrace_hash_add(hash, new);
7871 		return;
7872 	}
7873 
7874 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7875 	bucket->dthb_next = hash->dth_tab[ndx];
7876 	hash->dth_tab[ndx] = bucket;
7877 	hash->dth_nbuckets++;
7878 
7879 add:
7880 	nextp = DTRACE_HASHNEXT(hash, new);
7881 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7882 	*nextp = bucket->dthb_chain;
7883 
7884 	if (bucket->dthb_chain != NULL) {
7885 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7886 		ASSERT(*prevp == NULL);
7887 		*prevp = new;
7888 	}
7889 
7890 	bucket->dthb_chain = new;
7891 	bucket->dthb_len++;
7892 }
7893 
7894 static dtrace_probe_t *
7895 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7896 {
7897 	int hashval = DTRACE_HASHSTR(hash, template);
7898 	int ndx = hashval & hash->dth_mask;
7899 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7900 
7901 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7902 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7903 			return (bucket->dthb_chain);
7904 	}
7905 
7906 	return (NULL);
7907 }
7908 
7909 static int
7910 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7911 {
7912 	int hashval = DTRACE_HASHSTR(hash, template);
7913 	int ndx = hashval & hash->dth_mask;
7914 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7915 
7916 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7917 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7918 			return (bucket->dthb_len);
7919 	}
7920 
7921 	return (0);
7922 }
7923 
7924 static void
7925 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7926 {
7927 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7928 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7929 
7930 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7931 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7932 
7933 	/*
7934 	 * Find the bucket that we're removing this probe from.
7935 	 */
7936 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7937 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7938 			break;
7939 	}
7940 
7941 	ASSERT(bucket != NULL);
7942 
7943 	if (*prevp == NULL) {
7944 		if (*nextp == NULL) {
7945 			/*
7946 			 * The removed probe was the only probe on this
7947 			 * bucket; we need to remove the bucket.
7948 			 */
7949 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7950 
7951 			ASSERT(bucket->dthb_chain == probe);
7952 			ASSERT(b != NULL);
7953 
7954 			if (b == bucket) {
7955 				hash->dth_tab[ndx] = bucket->dthb_next;
7956 			} else {
7957 				while (b->dthb_next != bucket)
7958 					b = b->dthb_next;
7959 				b->dthb_next = bucket->dthb_next;
7960 			}
7961 
7962 			ASSERT(hash->dth_nbuckets > 0);
7963 			hash->dth_nbuckets--;
7964 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7965 			return;
7966 		}
7967 
7968 		bucket->dthb_chain = *nextp;
7969 	} else {
7970 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7971 	}
7972 
7973 	if (*nextp != NULL)
7974 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7975 }
7976 
7977 /*
7978  * DTrace Utility Functions
7979  *
7980  * These are random utility functions that are _not_ called from probe context.
7981  */
7982 static int
7983 dtrace_badattr(const dtrace_attribute_t *a)
7984 {
7985 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7986 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7987 	    a->dtat_class > DTRACE_CLASS_MAX);
7988 }
7989 
7990 /*
7991  * Return a duplicate copy of a string.  If the specified string is NULL,
7992  * this function returns a zero-length string.
7993  */
7994 static char *
7995 dtrace_strdup(const char *str)
7996 {
7997 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7998 
7999 	if (str != NULL)
8000 		(void) strcpy(new, str);
8001 
8002 	return (new);
8003 }
8004 
8005 #define	DTRACE_ISALPHA(c)	\
8006 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8007 
8008 static int
8009 dtrace_badname(const char *s)
8010 {
8011 	char c;
8012 
8013 	if (s == NULL || (c = *s++) == '\0')
8014 		return (0);
8015 
8016 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8017 		return (1);
8018 
8019 	while ((c = *s++) != '\0') {
8020 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8021 		    c != '-' && c != '_' && c != '.' && c != '`')
8022 			return (1);
8023 	}
8024 
8025 	return (0);
8026 }
8027 
8028 static void
8029 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8030 {
8031 	uint32_t priv;
8032 
8033 #if defined(sun)
8034 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8035 		/*
8036 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8037 		 */
8038 		priv = DTRACE_PRIV_ALL;
8039 	} else {
8040 		*uidp = crgetuid(cr);
8041 		*zoneidp = crgetzoneid(cr);
8042 
8043 		priv = 0;
8044 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8045 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8046 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8047 			priv |= DTRACE_PRIV_USER;
8048 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8049 			priv |= DTRACE_PRIV_PROC;
8050 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8051 			priv |= DTRACE_PRIV_OWNER;
8052 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8053 			priv |= DTRACE_PRIV_ZONEOWNER;
8054 	}
8055 #else
8056 	priv = DTRACE_PRIV_ALL;
8057 #endif
8058 
8059 	*privp = priv;
8060 }
8061 
8062 #ifdef DTRACE_ERRDEBUG
8063 static void
8064 dtrace_errdebug(const char *str)
8065 {
8066 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8067 	int occupied = 0;
8068 
8069 	mutex_enter(&dtrace_errlock);
8070 	dtrace_errlast = str;
8071 	dtrace_errthread = curthread;
8072 
8073 	while (occupied++ < DTRACE_ERRHASHSZ) {
8074 		if (dtrace_errhash[hval].dter_msg == str) {
8075 			dtrace_errhash[hval].dter_count++;
8076 			goto out;
8077 		}
8078 
8079 		if (dtrace_errhash[hval].dter_msg != NULL) {
8080 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8081 			continue;
8082 		}
8083 
8084 		dtrace_errhash[hval].dter_msg = str;
8085 		dtrace_errhash[hval].dter_count = 1;
8086 		goto out;
8087 	}
8088 
8089 	panic("dtrace: undersized error hash");
8090 out:
8091 	mutex_exit(&dtrace_errlock);
8092 }
8093 #endif
8094 
8095 /*
8096  * DTrace Matching Functions
8097  *
8098  * These functions are used to match groups of probes, given some elements of
8099  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8100  */
8101 static int
8102 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8103     zoneid_t zoneid)
8104 {
8105 	if (priv != DTRACE_PRIV_ALL) {
8106 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8107 		uint32_t match = priv & ppriv;
8108 
8109 		/*
8110 		 * No PRIV_DTRACE_* privileges...
8111 		 */
8112 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8113 		    DTRACE_PRIV_KERNEL)) == 0)
8114 			return (0);
8115 
8116 		/*
8117 		 * No matching bits, but there were bits to match...
8118 		 */
8119 		if (match == 0 && ppriv != 0)
8120 			return (0);
8121 
8122 		/*
8123 		 * Need to have permissions to the process, but don't...
8124 		 */
8125 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8126 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8127 			return (0);
8128 		}
8129 
8130 		/*
8131 		 * Need to be in the same zone unless we possess the
8132 		 * privilege to examine all zones.
8133 		 */
8134 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8135 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8136 			return (0);
8137 		}
8138 	}
8139 
8140 	return (1);
8141 }
8142 
8143 /*
8144  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8145  * consists of input pattern strings and an ops-vector to evaluate them.
8146  * This function returns >0 for match, 0 for no match, and <0 for error.
8147  */
8148 static int
8149 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8150     uint32_t priv, uid_t uid, zoneid_t zoneid)
8151 {
8152 	dtrace_provider_t *pvp = prp->dtpr_provider;
8153 	int rv;
8154 
8155 	if (pvp->dtpv_defunct)
8156 		return (0);
8157 
8158 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8159 		return (rv);
8160 
8161 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8162 		return (rv);
8163 
8164 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8165 		return (rv);
8166 
8167 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8168 		return (rv);
8169 
8170 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8171 		return (0);
8172 
8173 	return (rv);
8174 }
8175 
8176 /*
8177  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8178  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8179  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8180  * In addition, all of the recursion cases except for '*' matching have been
8181  * unwound.  For '*', we still implement recursive evaluation, but a depth
8182  * counter is maintained and matching is aborted if we recurse too deep.
8183  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8184  */
8185 static int
8186 dtrace_match_glob(const char *s, const char *p, int depth)
8187 {
8188 	const char *olds;
8189 	char s1, c;
8190 	int gs;
8191 
8192 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8193 		return (-1);
8194 
8195 	if (s == NULL)
8196 		s = ""; /* treat NULL as empty string */
8197 
8198 top:
8199 	olds = s;
8200 	s1 = *s++;
8201 
8202 	if (p == NULL)
8203 		return (0);
8204 
8205 	if ((c = *p++) == '\0')
8206 		return (s1 == '\0');
8207 
8208 	switch (c) {
8209 	case '[': {
8210 		int ok = 0, notflag = 0;
8211 		char lc = '\0';
8212 
8213 		if (s1 == '\0')
8214 			return (0);
8215 
8216 		if (*p == '!') {
8217 			notflag = 1;
8218 			p++;
8219 		}
8220 
8221 		if ((c = *p++) == '\0')
8222 			return (0);
8223 
8224 		do {
8225 			if (c == '-' && lc != '\0' && *p != ']') {
8226 				if ((c = *p++) == '\0')
8227 					return (0);
8228 				if (c == '\\' && (c = *p++) == '\0')
8229 					return (0);
8230 
8231 				if (notflag) {
8232 					if (s1 < lc || s1 > c)
8233 						ok++;
8234 					else
8235 						return (0);
8236 				} else if (lc <= s1 && s1 <= c)
8237 					ok++;
8238 
8239 			} else if (c == '\\' && (c = *p++) == '\0')
8240 				return (0);
8241 
8242 			lc = c; /* save left-hand 'c' for next iteration */
8243 
8244 			if (notflag) {
8245 				if (s1 != c)
8246 					ok++;
8247 				else
8248 					return (0);
8249 			} else if (s1 == c)
8250 				ok++;
8251 
8252 			if ((c = *p++) == '\0')
8253 				return (0);
8254 
8255 		} while (c != ']');
8256 
8257 		if (ok)
8258 			goto top;
8259 
8260 		return (0);
8261 	}
8262 
8263 	case '\\':
8264 		if ((c = *p++) == '\0')
8265 			return (0);
8266 		/*FALLTHRU*/
8267 
8268 	default:
8269 		if (c != s1)
8270 			return (0);
8271 		/*FALLTHRU*/
8272 
8273 	case '?':
8274 		if (s1 != '\0')
8275 			goto top;
8276 		return (0);
8277 
8278 	case '*':
8279 		while (*p == '*')
8280 			p++; /* consecutive *'s are identical to a single one */
8281 
8282 		if (*p == '\0')
8283 			return (1);
8284 
8285 		for (s = olds; *s != '\0'; s++) {
8286 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8287 				return (gs);
8288 		}
8289 
8290 		return (0);
8291 	}
8292 }
8293 
8294 /*ARGSUSED*/
8295 static int
8296 dtrace_match_string(const char *s, const char *p, int depth)
8297 {
8298 	return (s != NULL && strcmp(s, p) == 0);
8299 }
8300 
8301 /*ARGSUSED*/
8302 static int
8303 dtrace_match_nul(const char *s, const char *p, int depth)
8304 {
8305 	return (1); /* always match the empty pattern */
8306 }
8307 
8308 /*ARGSUSED*/
8309 static int
8310 dtrace_match_nonzero(const char *s, const char *p, int depth)
8311 {
8312 	return (s != NULL && s[0] != '\0');
8313 }
8314 
8315 static int
8316 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8317     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8318 {
8319 	dtrace_probe_t template, *probe;
8320 	dtrace_hash_t *hash = NULL;
8321 	int len, best = INT_MAX, nmatched = 0;
8322 	dtrace_id_t i;
8323 
8324 	ASSERT(MUTEX_HELD(&dtrace_lock));
8325 
8326 	/*
8327 	 * If the probe ID is specified in the key, just lookup by ID and
8328 	 * invoke the match callback once if a matching probe is found.
8329 	 */
8330 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8331 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8332 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8333 			(void) (*matched)(probe, arg);
8334 			nmatched++;
8335 		}
8336 		return (nmatched);
8337 	}
8338 
8339 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8340 	template.dtpr_func = (char *)pkp->dtpk_func;
8341 	template.dtpr_name = (char *)pkp->dtpk_name;
8342 
8343 	/*
8344 	 * We want to find the most distinct of the module name, function
8345 	 * name, and name.  So for each one that is not a glob pattern or
8346 	 * empty string, we perform a lookup in the corresponding hash and
8347 	 * use the hash table with the fewest collisions to do our search.
8348 	 */
8349 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8350 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8351 		best = len;
8352 		hash = dtrace_bymod;
8353 	}
8354 
8355 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8356 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8357 		best = len;
8358 		hash = dtrace_byfunc;
8359 	}
8360 
8361 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8362 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8363 		best = len;
8364 		hash = dtrace_byname;
8365 	}
8366 
8367 	/*
8368 	 * If we did not select a hash table, iterate over every probe and
8369 	 * invoke our callback for each one that matches our input probe key.
8370 	 */
8371 	if (hash == NULL) {
8372 		for (i = 0; i < dtrace_nprobes; i++) {
8373 			if ((probe = dtrace_probes[i]) == NULL ||
8374 			    dtrace_match_probe(probe, pkp, priv, uid,
8375 			    zoneid) <= 0)
8376 				continue;
8377 
8378 			nmatched++;
8379 
8380 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8381 				break;
8382 		}
8383 
8384 		return (nmatched);
8385 	}
8386 
8387 	/*
8388 	 * If we selected a hash table, iterate over each probe of the same key
8389 	 * name and invoke the callback for every probe that matches the other
8390 	 * attributes of our input probe key.
8391 	 */
8392 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8393 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8394 
8395 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8396 			continue;
8397 
8398 		nmatched++;
8399 
8400 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8401 			break;
8402 	}
8403 
8404 	return (nmatched);
8405 }
8406 
8407 /*
8408  * Return the function pointer dtrace_probecmp() should use to compare the
8409  * specified pattern with a string.  For NULL or empty patterns, we select
8410  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8411  * For non-empty non-glob strings, we use dtrace_match_string().
8412  */
8413 static dtrace_probekey_f *
8414 dtrace_probekey_func(const char *p)
8415 {
8416 	char c;
8417 
8418 	if (p == NULL || *p == '\0')
8419 		return (&dtrace_match_nul);
8420 
8421 	while ((c = *p++) != '\0') {
8422 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8423 			return (&dtrace_match_glob);
8424 	}
8425 
8426 	return (&dtrace_match_string);
8427 }
8428 
8429 /*
8430  * Build a probe comparison key for use with dtrace_match_probe() from the
8431  * given probe description.  By convention, a null key only matches anchored
8432  * probes: if each field is the empty string, reset dtpk_fmatch to
8433  * dtrace_match_nonzero().
8434  */
8435 static void
8436 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8437 {
8438 	pkp->dtpk_prov = pdp->dtpd_provider;
8439 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8440 
8441 	pkp->dtpk_mod = pdp->dtpd_mod;
8442 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8443 
8444 	pkp->dtpk_func = pdp->dtpd_func;
8445 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8446 
8447 	pkp->dtpk_name = pdp->dtpd_name;
8448 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8449 
8450 	pkp->dtpk_id = pdp->dtpd_id;
8451 
8452 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8453 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8454 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8455 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8456 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8457 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8458 }
8459 
8460 /*
8461  * DTrace Provider-to-Framework API Functions
8462  *
8463  * These functions implement much of the Provider-to-Framework API, as
8464  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8465  * the functions in the API for probe management (found below), and
8466  * dtrace_probe() itself (found above).
8467  */
8468 
8469 /*
8470  * Register the calling provider with the DTrace framework.  This should
8471  * generally be called by DTrace providers in their attach(9E) entry point.
8472  */
8473 int
8474 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8475     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8476 {
8477 	dtrace_provider_t *provider;
8478 
8479 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8480 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8481 		    "arguments", name ? name : "<NULL>");
8482 		return (EINVAL);
8483 	}
8484 
8485 	if (name[0] == '\0' || dtrace_badname(name)) {
8486 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8487 		    "provider name", name);
8488 		return (EINVAL);
8489 	}
8490 
8491 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8492 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8493 	    pops->dtps_destroy == NULL ||
8494 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8495 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8496 		    "provider ops", name);
8497 		return (EINVAL);
8498 	}
8499 
8500 	if (dtrace_badattr(&pap->dtpa_provider) ||
8501 	    dtrace_badattr(&pap->dtpa_mod) ||
8502 	    dtrace_badattr(&pap->dtpa_func) ||
8503 	    dtrace_badattr(&pap->dtpa_name) ||
8504 	    dtrace_badattr(&pap->dtpa_args)) {
8505 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8506 		    "provider attributes", name);
8507 		return (EINVAL);
8508 	}
8509 
8510 	if (priv & ~DTRACE_PRIV_ALL) {
8511 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8512 		    "privilege attributes", name);
8513 		return (EINVAL);
8514 	}
8515 
8516 	if ((priv & DTRACE_PRIV_KERNEL) &&
8517 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8518 	    pops->dtps_usermode == NULL) {
8519 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8520 		    "dtps_usermode() op for given privilege attributes", name);
8521 		return (EINVAL);
8522 	}
8523 
8524 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8525 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8526 	(void) strcpy(provider->dtpv_name, name);
8527 
8528 	provider->dtpv_attr = *pap;
8529 	provider->dtpv_priv.dtpp_flags = priv;
8530 	if (cr != NULL) {
8531 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8532 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8533 	}
8534 	provider->dtpv_pops = *pops;
8535 
8536 	if (pops->dtps_provide == NULL) {
8537 		ASSERT(pops->dtps_provide_module != NULL);
8538 		provider->dtpv_pops.dtps_provide =
8539 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8540 	}
8541 
8542 	if (pops->dtps_provide_module == NULL) {
8543 		ASSERT(pops->dtps_provide != NULL);
8544 		provider->dtpv_pops.dtps_provide_module =
8545 		    (void (*)(void *, modctl_t *))dtrace_nullop;
8546 	}
8547 
8548 	if (pops->dtps_suspend == NULL) {
8549 		ASSERT(pops->dtps_resume == NULL);
8550 		provider->dtpv_pops.dtps_suspend =
8551 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8552 		provider->dtpv_pops.dtps_resume =
8553 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8554 	}
8555 
8556 	provider->dtpv_arg = arg;
8557 	*idp = (dtrace_provider_id_t)provider;
8558 
8559 	if (pops == &dtrace_provider_ops) {
8560 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8561 		ASSERT(MUTEX_HELD(&dtrace_lock));
8562 		ASSERT(dtrace_anon.dta_enabling == NULL);
8563 
8564 		/*
8565 		 * We make sure that the DTrace provider is at the head of
8566 		 * the provider chain.
8567 		 */
8568 		provider->dtpv_next = dtrace_provider;
8569 		dtrace_provider = provider;
8570 		return (0);
8571 	}
8572 
8573 	mutex_enter(&dtrace_provider_lock);
8574 	mutex_enter(&dtrace_lock);
8575 
8576 	/*
8577 	 * If there is at least one provider registered, we'll add this
8578 	 * provider after the first provider.
8579 	 */
8580 	if (dtrace_provider != NULL) {
8581 		provider->dtpv_next = dtrace_provider->dtpv_next;
8582 		dtrace_provider->dtpv_next = provider;
8583 	} else {
8584 		dtrace_provider = provider;
8585 	}
8586 
8587 	if (dtrace_retained != NULL) {
8588 		dtrace_enabling_provide(provider);
8589 
8590 		/*
8591 		 * Now we need to call dtrace_enabling_matchall() -- which
8592 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8593 		 * to drop all of our locks before calling into it...
8594 		 */
8595 		mutex_exit(&dtrace_lock);
8596 		mutex_exit(&dtrace_provider_lock);
8597 		dtrace_enabling_matchall();
8598 
8599 		return (0);
8600 	}
8601 
8602 	mutex_exit(&dtrace_lock);
8603 	mutex_exit(&dtrace_provider_lock);
8604 
8605 	return (0);
8606 }
8607 
8608 /*
8609  * Unregister the specified provider from the DTrace framework.  This should
8610  * generally be called by DTrace providers in their detach(9E) entry point.
8611  */
8612 int
8613 dtrace_unregister(dtrace_provider_id_t id)
8614 {
8615 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8616 	dtrace_provider_t *prev = NULL;
8617 	int i, self = 0, noreap = 0;
8618 	dtrace_probe_t *probe, *first = NULL;
8619 
8620 	if (old->dtpv_pops.dtps_enable ==
8621 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8622 		/*
8623 		 * If DTrace itself is the provider, we're called with locks
8624 		 * already held.
8625 		 */
8626 		ASSERT(old == dtrace_provider);
8627 #if defined(sun)
8628 		ASSERT(dtrace_devi != NULL);
8629 #endif
8630 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8631 		ASSERT(MUTEX_HELD(&dtrace_lock));
8632 		self = 1;
8633 
8634 		if (dtrace_provider->dtpv_next != NULL) {
8635 			/*
8636 			 * There's another provider here; return failure.
8637 			 */
8638 			return (EBUSY);
8639 		}
8640 	} else {
8641 		mutex_enter(&dtrace_provider_lock);
8642 #if defined(sun)
8643 		mutex_enter(&mod_lock);
8644 #endif
8645 		mutex_enter(&dtrace_lock);
8646 	}
8647 
8648 	/*
8649 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8650 	 * probes, we refuse to let providers slither away, unless this
8651 	 * provider has already been explicitly invalidated.
8652 	 */
8653 	if (!old->dtpv_defunct &&
8654 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8655 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8656 		if (!self) {
8657 			mutex_exit(&dtrace_lock);
8658 #if defined(sun)
8659 			mutex_exit(&mod_lock);
8660 #endif
8661 			mutex_exit(&dtrace_provider_lock);
8662 		}
8663 		return (EBUSY);
8664 	}
8665 
8666 	/*
8667 	 * Attempt to destroy the probes associated with this provider.
8668 	 */
8669 	for (i = 0; i < dtrace_nprobes; i++) {
8670 		if ((probe = dtrace_probes[i]) == NULL)
8671 			continue;
8672 
8673 		if (probe->dtpr_provider != old)
8674 			continue;
8675 
8676 		if (probe->dtpr_ecb == NULL)
8677 			continue;
8678 
8679 		/*
8680 		 * If we are trying to unregister a defunct provider, and the
8681 		 * provider was made defunct within the interval dictated by
8682 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8683 		 * attempt to reap our enablings.  To denote that the provider
8684 		 * should reattempt to unregister itself at some point in the
8685 		 * future, we will return a differentiable error code (EAGAIN
8686 		 * instead of EBUSY) in this case.
8687 		 */
8688 		if (dtrace_gethrtime() - old->dtpv_defunct >
8689 		    dtrace_unregister_defunct_reap)
8690 			noreap = 1;
8691 
8692 		if (!self) {
8693 			mutex_exit(&dtrace_lock);
8694 #if defined(sun)
8695 			mutex_exit(&mod_lock);
8696 #endif
8697 			mutex_exit(&dtrace_provider_lock);
8698 		}
8699 
8700 		if (noreap)
8701 			return (EBUSY);
8702 
8703 		(void) taskq_dispatch(dtrace_taskq,
8704 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8705 
8706 		return (EAGAIN);
8707 	}
8708 
8709 	/*
8710 	 * All of the probes for this provider are disabled; we can safely
8711 	 * remove all of them from their hash chains and from the probe array.
8712 	 */
8713 	for (i = 0; i < dtrace_nprobes; i++) {
8714 		if ((probe = dtrace_probes[i]) == NULL)
8715 			continue;
8716 
8717 		if (probe->dtpr_provider != old)
8718 			continue;
8719 
8720 		dtrace_probes[i] = NULL;
8721 
8722 		dtrace_hash_remove(dtrace_bymod, probe);
8723 		dtrace_hash_remove(dtrace_byfunc, probe);
8724 		dtrace_hash_remove(dtrace_byname, probe);
8725 
8726 		if (first == NULL) {
8727 			first = probe;
8728 			probe->dtpr_nextmod = NULL;
8729 		} else {
8730 			probe->dtpr_nextmod = first;
8731 			first = probe;
8732 		}
8733 	}
8734 
8735 	/*
8736 	 * The provider's probes have been removed from the hash chains and
8737 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8738 	 * everyone has cleared out from any probe array processing.
8739 	 */
8740 	dtrace_sync();
8741 
8742 	for (probe = first; probe != NULL; probe = first) {
8743 		first = probe->dtpr_nextmod;
8744 
8745 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8746 		    probe->dtpr_arg);
8747 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8748 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8749 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8750 #if defined(sun)
8751 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8752 #else
8753 		free_unr(dtrace_arena, probe->dtpr_id);
8754 #endif
8755 		kmem_free(probe, sizeof (dtrace_probe_t));
8756 	}
8757 
8758 	if ((prev = dtrace_provider) == old) {
8759 #if defined(sun)
8760 		ASSERT(self || dtrace_devi == NULL);
8761 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8762 #endif
8763 		dtrace_provider = old->dtpv_next;
8764 	} else {
8765 		while (prev != NULL && prev->dtpv_next != old)
8766 			prev = prev->dtpv_next;
8767 
8768 		if (prev == NULL) {
8769 			panic("attempt to unregister non-existent "
8770 			    "dtrace provider %p\n", (void *)id);
8771 		}
8772 
8773 		prev->dtpv_next = old->dtpv_next;
8774 	}
8775 
8776 	if (!self) {
8777 		mutex_exit(&dtrace_lock);
8778 #if defined(sun)
8779 		mutex_exit(&mod_lock);
8780 #endif
8781 		mutex_exit(&dtrace_provider_lock);
8782 	}
8783 
8784 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8785 	kmem_free(old, sizeof (dtrace_provider_t));
8786 
8787 	return (0);
8788 }
8789 
8790 /*
8791  * Invalidate the specified provider.  All subsequent probe lookups for the
8792  * specified provider will fail, but its probes will not be removed.
8793  */
8794 void
8795 dtrace_invalidate(dtrace_provider_id_t id)
8796 {
8797 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8798 
8799 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8800 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8801 
8802 	mutex_enter(&dtrace_provider_lock);
8803 	mutex_enter(&dtrace_lock);
8804 
8805 	pvp->dtpv_defunct = dtrace_gethrtime();
8806 
8807 	mutex_exit(&dtrace_lock);
8808 	mutex_exit(&dtrace_provider_lock);
8809 }
8810 
8811 /*
8812  * Indicate whether or not DTrace has attached.
8813  */
8814 int
8815 dtrace_attached(void)
8816 {
8817 	/*
8818 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8819 	 * attached.  (It's non-NULL because DTrace is always itself a
8820 	 * provider.)
8821 	 */
8822 	return (dtrace_provider != NULL);
8823 }
8824 
8825 /*
8826  * Remove all the unenabled probes for the given provider.  This function is
8827  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8828  * -- just as many of its associated probes as it can.
8829  */
8830 int
8831 dtrace_condense(dtrace_provider_id_t id)
8832 {
8833 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8834 	int i;
8835 	dtrace_probe_t *probe;
8836 
8837 	/*
8838 	 * Make sure this isn't the dtrace provider itself.
8839 	 */
8840 	ASSERT(prov->dtpv_pops.dtps_enable !=
8841 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8842 
8843 	mutex_enter(&dtrace_provider_lock);
8844 	mutex_enter(&dtrace_lock);
8845 
8846 	/*
8847 	 * Attempt to destroy the probes associated with this provider.
8848 	 */
8849 	for (i = 0; i < dtrace_nprobes; i++) {
8850 		if ((probe = dtrace_probes[i]) == NULL)
8851 			continue;
8852 
8853 		if (probe->dtpr_provider != prov)
8854 			continue;
8855 
8856 		if (probe->dtpr_ecb != NULL)
8857 			continue;
8858 
8859 		dtrace_probes[i] = NULL;
8860 
8861 		dtrace_hash_remove(dtrace_bymod, probe);
8862 		dtrace_hash_remove(dtrace_byfunc, probe);
8863 		dtrace_hash_remove(dtrace_byname, probe);
8864 
8865 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8866 		    probe->dtpr_arg);
8867 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8868 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8869 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8870 		kmem_free(probe, sizeof (dtrace_probe_t));
8871 #if defined(sun)
8872 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8873 #else
8874 		free_unr(dtrace_arena, i + 1);
8875 #endif
8876 	}
8877 
8878 	mutex_exit(&dtrace_lock);
8879 	mutex_exit(&dtrace_provider_lock);
8880 
8881 	return (0);
8882 }
8883 
8884 /*
8885  * DTrace Probe Management Functions
8886  *
8887  * The functions in this section perform the DTrace probe management,
8888  * including functions to create probes, look-up probes, and call into the
8889  * providers to request that probes be provided.  Some of these functions are
8890  * in the Provider-to-Framework API; these functions can be identified by the
8891  * fact that they are not declared "static".
8892  */
8893 
8894 /*
8895  * Create a probe with the specified module name, function name, and name.
8896  */
8897 dtrace_id_t
8898 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8899     const char *func, const char *name, int aframes, void *arg)
8900 {
8901 	dtrace_probe_t *probe, **probes;
8902 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8903 	dtrace_id_t id;
8904 
8905 	if (provider == dtrace_provider) {
8906 		ASSERT(MUTEX_HELD(&dtrace_lock));
8907 	} else {
8908 		mutex_enter(&dtrace_lock);
8909 	}
8910 
8911 #if defined(sun)
8912 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8913 	    VM_BESTFIT | VM_SLEEP);
8914 #else
8915 	id = alloc_unr(dtrace_arena);
8916 #endif
8917 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8918 
8919 	probe->dtpr_id = id;
8920 	probe->dtpr_gen = dtrace_probegen++;
8921 	probe->dtpr_mod = dtrace_strdup(mod);
8922 	probe->dtpr_func = dtrace_strdup(func);
8923 	probe->dtpr_name = dtrace_strdup(name);
8924 	probe->dtpr_arg = arg;
8925 	probe->dtpr_aframes = aframes;
8926 	probe->dtpr_provider = provider;
8927 
8928 	dtrace_hash_add(dtrace_bymod, probe);
8929 	dtrace_hash_add(dtrace_byfunc, probe);
8930 	dtrace_hash_add(dtrace_byname, probe);
8931 
8932 	if (id - 1 >= dtrace_nprobes) {
8933 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8934 		size_t nsize = osize << 1;
8935 
8936 		if (nsize == 0) {
8937 			ASSERT(osize == 0);
8938 			ASSERT(dtrace_probes == NULL);
8939 			nsize = sizeof (dtrace_probe_t *);
8940 		}
8941 
8942 		probes = kmem_zalloc(nsize, KM_SLEEP);
8943 
8944 		if (dtrace_probes == NULL) {
8945 			ASSERT(osize == 0);
8946 			dtrace_probes = probes;
8947 			dtrace_nprobes = 1;
8948 		} else {
8949 			dtrace_probe_t **oprobes = dtrace_probes;
8950 
8951 			bcopy(oprobes, probes, osize);
8952 			dtrace_membar_producer();
8953 			dtrace_probes = probes;
8954 
8955 			dtrace_sync();
8956 
8957 			/*
8958 			 * All CPUs are now seeing the new probes array; we can
8959 			 * safely free the old array.
8960 			 */
8961 			kmem_free(oprobes, osize);
8962 			dtrace_nprobes <<= 1;
8963 		}
8964 
8965 		ASSERT(id - 1 < dtrace_nprobes);
8966 	}
8967 
8968 	ASSERT(dtrace_probes[id - 1] == NULL);
8969 	dtrace_probes[id - 1] = probe;
8970 
8971 	if (provider != dtrace_provider)
8972 		mutex_exit(&dtrace_lock);
8973 
8974 	return (id);
8975 }
8976 
8977 static dtrace_probe_t *
8978 dtrace_probe_lookup_id(dtrace_id_t id)
8979 {
8980 	ASSERT(MUTEX_HELD(&dtrace_lock));
8981 
8982 	if (id == 0 || id > dtrace_nprobes)
8983 		return (NULL);
8984 
8985 	return (dtrace_probes[id - 1]);
8986 }
8987 
8988 static int
8989 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8990 {
8991 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8992 
8993 	return (DTRACE_MATCH_DONE);
8994 }
8995 
8996 /*
8997  * Look up a probe based on provider and one or more of module name, function
8998  * name and probe name.
8999  */
9000 dtrace_id_t
9001 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9002     char *func, char *name)
9003 {
9004 	dtrace_probekey_t pkey;
9005 	dtrace_id_t id;
9006 	int match;
9007 
9008 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9009 	pkey.dtpk_pmatch = &dtrace_match_string;
9010 	pkey.dtpk_mod = mod;
9011 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9012 	pkey.dtpk_func = func;
9013 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9014 	pkey.dtpk_name = name;
9015 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9016 	pkey.dtpk_id = DTRACE_IDNONE;
9017 
9018 	mutex_enter(&dtrace_lock);
9019 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9020 	    dtrace_probe_lookup_match, &id);
9021 	mutex_exit(&dtrace_lock);
9022 
9023 	ASSERT(match == 1 || match == 0);
9024 	return (match ? id : 0);
9025 }
9026 
9027 /*
9028  * Returns the probe argument associated with the specified probe.
9029  */
9030 void *
9031 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9032 {
9033 	dtrace_probe_t *probe;
9034 	void *rval = NULL;
9035 
9036 	mutex_enter(&dtrace_lock);
9037 
9038 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9039 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9040 		rval = probe->dtpr_arg;
9041 
9042 	mutex_exit(&dtrace_lock);
9043 
9044 	return (rval);
9045 }
9046 
9047 /*
9048  * Copy a probe into a probe description.
9049  */
9050 static void
9051 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9052 {
9053 	bzero(pdp, sizeof (dtrace_probedesc_t));
9054 	pdp->dtpd_id = prp->dtpr_id;
9055 
9056 	(void) strncpy(pdp->dtpd_provider,
9057 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9058 
9059 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9060 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9061 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9062 }
9063 
9064 /*
9065  * Called to indicate that a probe -- or probes -- should be provided by a
9066  * specfied provider.  If the specified description is NULL, the provider will
9067  * be told to provide all of its probes.  (This is done whenever a new
9068  * consumer comes along, or whenever a retained enabling is to be matched.) If
9069  * the specified description is non-NULL, the provider is given the
9070  * opportunity to dynamically provide the specified probe, allowing providers
9071  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9072  * probes.)  If the provider is NULL, the operations will be applied to all
9073  * providers; if the provider is non-NULL the operations will only be applied
9074  * to the specified provider.  The dtrace_provider_lock must be held, and the
9075  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9076  * will need to grab the dtrace_lock when it reenters the framework through
9077  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9078  */
9079 static void
9080 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9081 {
9082 #if defined(sun)
9083 	modctl_t *ctl;
9084 #endif
9085 	int all = 0;
9086 
9087 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9088 
9089 	if (prv == NULL) {
9090 		all = 1;
9091 		prv = dtrace_provider;
9092 	}
9093 
9094 	do {
9095 		/*
9096 		 * First, call the blanket provide operation.
9097 		 */
9098 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9099 
9100 #if defined(sun)
9101 		/*
9102 		 * Now call the per-module provide operation.  We will grab
9103 		 * mod_lock to prevent the list from being modified.  Note
9104 		 * that this also prevents the mod_busy bits from changing.
9105 		 * (mod_busy can only be changed with mod_lock held.)
9106 		 */
9107 		mutex_enter(&mod_lock);
9108 
9109 		ctl = &modules;
9110 		do {
9111 			if (ctl->mod_busy || ctl->mod_mp == NULL)
9112 				continue;
9113 
9114 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9115 
9116 		} while ((ctl = ctl->mod_next) != &modules);
9117 
9118 		mutex_exit(&mod_lock);
9119 #endif
9120 	} while (all && (prv = prv->dtpv_next) != NULL);
9121 }
9122 
9123 #if defined(sun)
9124 /*
9125  * Iterate over each probe, and call the Framework-to-Provider API function
9126  * denoted by offs.
9127  */
9128 static void
9129 dtrace_probe_foreach(uintptr_t offs)
9130 {
9131 	dtrace_provider_t *prov;
9132 	void (*func)(void *, dtrace_id_t, void *);
9133 	dtrace_probe_t *probe;
9134 	dtrace_icookie_t cookie;
9135 	int i;
9136 
9137 	/*
9138 	 * We disable interrupts to walk through the probe array.  This is
9139 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9140 	 * won't see stale data.
9141 	 */
9142 	cookie = dtrace_interrupt_disable();
9143 
9144 	for (i = 0; i < dtrace_nprobes; i++) {
9145 		if ((probe = dtrace_probes[i]) == NULL)
9146 			continue;
9147 
9148 		if (probe->dtpr_ecb == NULL) {
9149 			/*
9150 			 * This probe isn't enabled -- don't call the function.
9151 			 */
9152 			continue;
9153 		}
9154 
9155 		prov = probe->dtpr_provider;
9156 		func = *((void(**)(void *, dtrace_id_t, void *))
9157 		    ((uintptr_t)&prov->dtpv_pops + offs));
9158 
9159 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9160 	}
9161 
9162 	dtrace_interrupt_enable(cookie);
9163 }
9164 #endif
9165 
9166 static int
9167 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9168 {
9169 	dtrace_probekey_t pkey;
9170 	uint32_t priv;
9171 	uid_t uid;
9172 	zoneid_t zoneid;
9173 
9174 	ASSERT(MUTEX_HELD(&dtrace_lock));
9175 	dtrace_ecb_create_cache = NULL;
9176 
9177 	if (desc == NULL) {
9178 		/*
9179 		 * If we're passed a NULL description, we're being asked to
9180 		 * create an ECB with a NULL probe.
9181 		 */
9182 		(void) dtrace_ecb_create_enable(NULL, enab);
9183 		return (0);
9184 	}
9185 
9186 	dtrace_probekey(desc, &pkey);
9187 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9188 	    &priv, &uid, &zoneid);
9189 
9190 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9191 	    enab));
9192 }
9193 
9194 /*
9195  * DTrace Helper Provider Functions
9196  */
9197 static void
9198 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9199 {
9200 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9201 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9202 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9203 }
9204 
9205 static void
9206 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9207     const dof_provider_t *dofprov, char *strtab)
9208 {
9209 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9210 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9211 	    dofprov->dofpv_provattr);
9212 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9213 	    dofprov->dofpv_modattr);
9214 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9215 	    dofprov->dofpv_funcattr);
9216 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9217 	    dofprov->dofpv_nameattr);
9218 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9219 	    dofprov->dofpv_argsattr);
9220 }
9221 
9222 static void
9223 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9224 {
9225 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9226 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9227 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9228 	dof_provider_t *provider;
9229 	dof_probe_t *probe;
9230 	uint32_t *off, *enoff;
9231 	uint8_t *arg;
9232 	char *strtab;
9233 	uint_t i, nprobes;
9234 	dtrace_helper_provdesc_t dhpv;
9235 	dtrace_helper_probedesc_t dhpb;
9236 	dtrace_meta_t *meta = dtrace_meta_pid;
9237 	dtrace_mops_t *mops = &meta->dtm_mops;
9238 	void *parg;
9239 
9240 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9241 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9242 	    provider->dofpv_strtab * dof->dofh_secsize);
9243 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9244 	    provider->dofpv_probes * dof->dofh_secsize);
9245 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9246 	    provider->dofpv_prargs * dof->dofh_secsize);
9247 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9248 	    provider->dofpv_proffs * dof->dofh_secsize);
9249 
9250 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9251 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9252 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9253 	enoff = NULL;
9254 
9255 	/*
9256 	 * See dtrace_helper_provider_validate().
9257 	 */
9258 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9259 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9260 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9261 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9262 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9263 	}
9264 
9265 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9266 
9267 	/*
9268 	 * Create the provider.
9269 	 */
9270 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9271 
9272 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9273 		return;
9274 
9275 	meta->dtm_count++;
9276 
9277 	/*
9278 	 * Create the probes.
9279 	 */
9280 	for (i = 0; i < nprobes; i++) {
9281 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9282 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9283 
9284 		dhpb.dthpb_mod = dhp->dofhp_mod;
9285 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9286 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9287 		dhpb.dthpb_base = probe->dofpr_addr;
9288 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9289 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9290 		if (enoff != NULL) {
9291 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9292 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9293 		} else {
9294 			dhpb.dthpb_enoffs = NULL;
9295 			dhpb.dthpb_nenoffs = 0;
9296 		}
9297 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9298 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9299 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9300 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9301 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9302 
9303 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9304 	}
9305 }
9306 
9307 static void
9308 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9309 {
9310 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9311 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9312 	int i;
9313 
9314 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9315 
9316 	for (i = 0; i < dof->dofh_secnum; i++) {
9317 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9318 		    dof->dofh_secoff + i * dof->dofh_secsize);
9319 
9320 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9321 			continue;
9322 
9323 		dtrace_helper_provide_one(dhp, sec, pid);
9324 	}
9325 
9326 	/*
9327 	 * We may have just created probes, so we must now rematch against
9328 	 * any retained enablings.  Note that this call will acquire both
9329 	 * cpu_lock and dtrace_lock; the fact that we are holding
9330 	 * dtrace_meta_lock now is what defines the ordering with respect to
9331 	 * these three locks.
9332 	 */
9333 	dtrace_enabling_matchall();
9334 }
9335 
9336 static void
9337 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9338 {
9339 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9340 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9341 	dof_sec_t *str_sec;
9342 	dof_provider_t *provider;
9343 	char *strtab;
9344 	dtrace_helper_provdesc_t dhpv;
9345 	dtrace_meta_t *meta = dtrace_meta_pid;
9346 	dtrace_mops_t *mops = &meta->dtm_mops;
9347 
9348 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9349 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9350 	    provider->dofpv_strtab * dof->dofh_secsize);
9351 
9352 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9353 
9354 	/*
9355 	 * Create the provider.
9356 	 */
9357 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9358 
9359 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9360 
9361 	meta->dtm_count--;
9362 }
9363 
9364 static void
9365 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9366 {
9367 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9368 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9369 	int i;
9370 
9371 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9372 
9373 	for (i = 0; i < dof->dofh_secnum; i++) {
9374 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9375 		    dof->dofh_secoff + i * dof->dofh_secsize);
9376 
9377 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9378 			continue;
9379 
9380 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9381 	}
9382 }
9383 
9384 /*
9385  * DTrace Meta Provider-to-Framework API Functions
9386  *
9387  * These functions implement the Meta Provider-to-Framework API, as described
9388  * in <sys/dtrace.h>.
9389  */
9390 int
9391 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9392     dtrace_meta_provider_id_t *idp)
9393 {
9394 	dtrace_meta_t *meta;
9395 	dtrace_helpers_t *help, *next;
9396 	int i;
9397 
9398 	*idp = DTRACE_METAPROVNONE;
9399 
9400 	/*
9401 	 * We strictly don't need the name, but we hold onto it for
9402 	 * debuggability. All hail error queues!
9403 	 */
9404 	if (name == NULL) {
9405 		cmn_err(CE_WARN, "failed to register meta-provider: "
9406 		    "invalid name");
9407 		return (EINVAL);
9408 	}
9409 
9410 	if (mops == NULL ||
9411 	    mops->dtms_create_probe == NULL ||
9412 	    mops->dtms_provide_pid == NULL ||
9413 	    mops->dtms_remove_pid == NULL) {
9414 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9415 		    "invalid ops", name);
9416 		return (EINVAL);
9417 	}
9418 
9419 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9420 	meta->dtm_mops = *mops;
9421 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9422 	(void) strcpy(meta->dtm_name, name);
9423 	meta->dtm_arg = arg;
9424 
9425 	mutex_enter(&dtrace_meta_lock);
9426 	mutex_enter(&dtrace_lock);
9427 
9428 	if (dtrace_meta_pid != NULL) {
9429 		mutex_exit(&dtrace_lock);
9430 		mutex_exit(&dtrace_meta_lock);
9431 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9432 		    "user-land meta-provider exists", name);
9433 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9434 		kmem_free(meta, sizeof (dtrace_meta_t));
9435 		return (EINVAL);
9436 	}
9437 
9438 	dtrace_meta_pid = meta;
9439 	*idp = (dtrace_meta_provider_id_t)meta;
9440 
9441 	/*
9442 	 * If there are providers and probes ready to go, pass them
9443 	 * off to the new meta provider now.
9444 	 */
9445 
9446 	help = dtrace_deferred_pid;
9447 	dtrace_deferred_pid = NULL;
9448 
9449 	mutex_exit(&dtrace_lock);
9450 
9451 	while (help != NULL) {
9452 		for (i = 0; i < help->dthps_nprovs; i++) {
9453 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9454 			    help->dthps_pid);
9455 		}
9456 
9457 		next = help->dthps_next;
9458 		help->dthps_next = NULL;
9459 		help->dthps_prev = NULL;
9460 		help->dthps_deferred = 0;
9461 		help = next;
9462 	}
9463 
9464 	mutex_exit(&dtrace_meta_lock);
9465 
9466 	return (0);
9467 }
9468 
9469 int
9470 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9471 {
9472 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9473 
9474 	mutex_enter(&dtrace_meta_lock);
9475 	mutex_enter(&dtrace_lock);
9476 
9477 	if (old == dtrace_meta_pid) {
9478 		pp = &dtrace_meta_pid;
9479 	} else {
9480 		panic("attempt to unregister non-existent "
9481 		    "dtrace meta-provider %p\n", (void *)old);
9482 	}
9483 
9484 	if (old->dtm_count != 0) {
9485 		mutex_exit(&dtrace_lock);
9486 		mutex_exit(&dtrace_meta_lock);
9487 		return (EBUSY);
9488 	}
9489 
9490 	*pp = NULL;
9491 
9492 	mutex_exit(&dtrace_lock);
9493 	mutex_exit(&dtrace_meta_lock);
9494 
9495 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9496 	kmem_free(old, sizeof (dtrace_meta_t));
9497 
9498 	return (0);
9499 }
9500 
9501 
9502 /*
9503  * DTrace DIF Object Functions
9504  */
9505 static int
9506 dtrace_difo_err(uint_t pc, const char *format, ...)
9507 {
9508 	if (dtrace_err_verbose) {
9509 		va_list alist;
9510 
9511 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9512 		va_start(alist, format);
9513 		(void) vuprintf(format, alist);
9514 		va_end(alist);
9515 	}
9516 
9517 #ifdef DTRACE_ERRDEBUG
9518 	dtrace_errdebug(format);
9519 #endif
9520 	return (1);
9521 }
9522 
9523 /*
9524  * Validate a DTrace DIF object by checking the IR instructions.  The following
9525  * rules are currently enforced by dtrace_difo_validate():
9526  *
9527  * 1. Each instruction must have a valid opcode
9528  * 2. Each register, string, variable, or subroutine reference must be valid
9529  * 3. No instruction can modify register %r0 (must be zero)
9530  * 4. All instruction reserved bits must be set to zero
9531  * 5. The last instruction must be a "ret" instruction
9532  * 6. All branch targets must reference a valid instruction _after_ the branch
9533  */
9534 static int
9535 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9536     cred_t *cr)
9537 {
9538 	int err = 0, i;
9539 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9540 	int kcheckload;
9541 	uint_t pc;
9542 
9543 	kcheckload = cr == NULL ||
9544 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9545 
9546 	dp->dtdo_destructive = 0;
9547 
9548 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9549 		dif_instr_t instr = dp->dtdo_buf[pc];
9550 
9551 		uint_t r1 = DIF_INSTR_R1(instr);
9552 		uint_t r2 = DIF_INSTR_R2(instr);
9553 		uint_t rd = DIF_INSTR_RD(instr);
9554 		uint_t rs = DIF_INSTR_RS(instr);
9555 		uint_t label = DIF_INSTR_LABEL(instr);
9556 		uint_t v = DIF_INSTR_VAR(instr);
9557 		uint_t subr = DIF_INSTR_SUBR(instr);
9558 		uint_t type = DIF_INSTR_TYPE(instr);
9559 		uint_t op = DIF_INSTR_OP(instr);
9560 
9561 		switch (op) {
9562 		case DIF_OP_OR:
9563 		case DIF_OP_XOR:
9564 		case DIF_OP_AND:
9565 		case DIF_OP_SLL:
9566 		case DIF_OP_SRL:
9567 		case DIF_OP_SRA:
9568 		case DIF_OP_SUB:
9569 		case DIF_OP_ADD:
9570 		case DIF_OP_MUL:
9571 		case DIF_OP_SDIV:
9572 		case DIF_OP_UDIV:
9573 		case DIF_OP_SREM:
9574 		case DIF_OP_UREM:
9575 		case DIF_OP_COPYS:
9576 			if (r1 >= nregs)
9577 				err += efunc(pc, "invalid register %u\n", r1);
9578 			if (r2 >= nregs)
9579 				err += efunc(pc, "invalid register %u\n", r2);
9580 			if (rd >= nregs)
9581 				err += efunc(pc, "invalid register %u\n", rd);
9582 			if (rd == 0)
9583 				err += efunc(pc, "cannot write to %r0\n");
9584 			break;
9585 		case DIF_OP_NOT:
9586 		case DIF_OP_MOV:
9587 		case DIF_OP_ALLOCS:
9588 			if (r1 >= nregs)
9589 				err += efunc(pc, "invalid register %u\n", r1);
9590 			if (r2 != 0)
9591 				err += efunc(pc, "non-zero reserved bits\n");
9592 			if (rd >= nregs)
9593 				err += efunc(pc, "invalid register %u\n", rd);
9594 			if (rd == 0)
9595 				err += efunc(pc, "cannot write to %r0\n");
9596 			break;
9597 		case DIF_OP_LDSB:
9598 		case DIF_OP_LDSH:
9599 		case DIF_OP_LDSW:
9600 		case DIF_OP_LDUB:
9601 		case DIF_OP_LDUH:
9602 		case DIF_OP_LDUW:
9603 		case DIF_OP_LDX:
9604 			if (r1 >= nregs)
9605 				err += efunc(pc, "invalid register %u\n", r1);
9606 			if (r2 != 0)
9607 				err += efunc(pc, "non-zero reserved bits\n");
9608 			if (rd >= nregs)
9609 				err += efunc(pc, "invalid register %u\n", rd);
9610 			if (rd == 0)
9611 				err += efunc(pc, "cannot write to %r0\n");
9612 			if (kcheckload)
9613 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9614 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9615 			break;
9616 		case DIF_OP_RLDSB:
9617 		case DIF_OP_RLDSH:
9618 		case DIF_OP_RLDSW:
9619 		case DIF_OP_RLDUB:
9620 		case DIF_OP_RLDUH:
9621 		case DIF_OP_RLDUW:
9622 		case DIF_OP_RLDX:
9623 			if (r1 >= nregs)
9624 				err += efunc(pc, "invalid register %u\n", r1);
9625 			if (r2 != 0)
9626 				err += efunc(pc, "non-zero reserved bits\n");
9627 			if (rd >= nregs)
9628 				err += efunc(pc, "invalid register %u\n", rd);
9629 			if (rd == 0)
9630 				err += efunc(pc, "cannot write to %r0\n");
9631 			break;
9632 		case DIF_OP_ULDSB:
9633 		case DIF_OP_ULDSH:
9634 		case DIF_OP_ULDSW:
9635 		case DIF_OP_ULDUB:
9636 		case DIF_OP_ULDUH:
9637 		case DIF_OP_ULDUW:
9638 		case DIF_OP_ULDX:
9639 			if (r1 >= nregs)
9640 				err += efunc(pc, "invalid register %u\n", r1);
9641 			if (r2 != 0)
9642 				err += efunc(pc, "non-zero reserved bits\n");
9643 			if (rd >= nregs)
9644 				err += efunc(pc, "invalid register %u\n", rd);
9645 			if (rd == 0)
9646 				err += efunc(pc, "cannot write to %r0\n");
9647 			break;
9648 		case DIF_OP_STB:
9649 		case DIF_OP_STH:
9650 		case DIF_OP_STW:
9651 		case DIF_OP_STX:
9652 			if (r1 >= nregs)
9653 				err += efunc(pc, "invalid register %u\n", r1);
9654 			if (r2 != 0)
9655 				err += efunc(pc, "non-zero reserved bits\n");
9656 			if (rd >= nregs)
9657 				err += efunc(pc, "invalid register %u\n", rd);
9658 			if (rd == 0)
9659 				err += efunc(pc, "cannot write to 0 address\n");
9660 			break;
9661 		case DIF_OP_CMP:
9662 		case DIF_OP_SCMP:
9663 			if (r1 >= nregs)
9664 				err += efunc(pc, "invalid register %u\n", r1);
9665 			if (r2 >= nregs)
9666 				err += efunc(pc, "invalid register %u\n", r2);
9667 			if (rd != 0)
9668 				err += efunc(pc, "non-zero reserved bits\n");
9669 			break;
9670 		case DIF_OP_TST:
9671 			if (r1 >= nregs)
9672 				err += efunc(pc, "invalid register %u\n", r1);
9673 			if (r2 != 0 || rd != 0)
9674 				err += efunc(pc, "non-zero reserved bits\n");
9675 			break;
9676 		case DIF_OP_BA:
9677 		case DIF_OP_BE:
9678 		case DIF_OP_BNE:
9679 		case DIF_OP_BG:
9680 		case DIF_OP_BGU:
9681 		case DIF_OP_BGE:
9682 		case DIF_OP_BGEU:
9683 		case DIF_OP_BL:
9684 		case DIF_OP_BLU:
9685 		case DIF_OP_BLE:
9686 		case DIF_OP_BLEU:
9687 			if (label >= dp->dtdo_len) {
9688 				err += efunc(pc, "invalid branch target %u\n",
9689 				    label);
9690 			}
9691 			if (label <= pc) {
9692 				err += efunc(pc, "backward branch to %u\n",
9693 				    label);
9694 			}
9695 			break;
9696 		case DIF_OP_RET:
9697 			if (r1 != 0 || r2 != 0)
9698 				err += efunc(pc, "non-zero reserved bits\n");
9699 			if (rd >= nregs)
9700 				err += efunc(pc, "invalid register %u\n", rd);
9701 			break;
9702 		case DIF_OP_NOP:
9703 		case DIF_OP_POPTS:
9704 		case DIF_OP_FLUSHTS:
9705 			if (r1 != 0 || r2 != 0 || rd != 0)
9706 				err += efunc(pc, "non-zero reserved bits\n");
9707 			break;
9708 		case DIF_OP_SETX:
9709 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9710 				err += efunc(pc, "invalid integer ref %u\n",
9711 				    DIF_INSTR_INTEGER(instr));
9712 			}
9713 			if (rd >= nregs)
9714 				err += efunc(pc, "invalid register %u\n", rd);
9715 			if (rd == 0)
9716 				err += efunc(pc, "cannot write to %r0\n");
9717 			break;
9718 		case DIF_OP_SETS:
9719 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9720 				err += efunc(pc, "invalid string ref %u\n",
9721 				    DIF_INSTR_STRING(instr));
9722 			}
9723 			if (rd >= nregs)
9724 				err += efunc(pc, "invalid register %u\n", rd);
9725 			if (rd == 0)
9726 				err += efunc(pc, "cannot write to %r0\n");
9727 			break;
9728 		case DIF_OP_LDGA:
9729 		case DIF_OP_LDTA:
9730 			if (r1 > DIF_VAR_ARRAY_MAX)
9731 				err += efunc(pc, "invalid array %u\n", r1);
9732 			if (r2 >= nregs)
9733 				err += efunc(pc, "invalid register %u\n", r2);
9734 			if (rd >= nregs)
9735 				err += efunc(pc, "invalid register %u\n", rd);
9736 			if (rd == 0)
9737 				err += efunc(pc, "cannot write to %r0\n");
9738 			break;
9739 		case DIF_OP_LDGS:
9740 		case DIF_OP_LDTS:
9741 		case DIF_OP_LDLS:
9742 		case DIF_OP_LDGAA:
9743 		case DIF_OP_LDTAA:
9744 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9745 				err += efunc(pc, "invalid variable %u\n", v);
9746 			if (rd >= nregs)
9747 				err += efunc(pc, "invalid register %u\n", rd);
9748 			if (rd == 0)
9749 				err += efunc(pc, "cannot write to %r0\n");
9750 			break;
9751 		case DIF_OP_STGS:
9752 		case DIF_OP_STTS:
9753 		case DIF_OP_STLS:
9754 		case DIF_OP_STGAA:
9755 		case DIF_OP_STTAA:
9756 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9757 				err += efunc(pc, "invalid variable %u\n", v);
9758 			if (rs >= nregs)
9759 				err += efunc(pc, "invalid register %u\n", rd);
9760 			break;
9761 		case DIF_OP_CALL:
9762 			if (subr > DIF_SUBR_MAX)
9763 				err += efunc(pc, "invalid subr %u\n", subr);
9764 			if (rd >= nregs)
9765 				err += efunc(pc, "invalid register %u\n", rd);
9766 			if (rd == 0)
9767 				err += efunc(pc, "cannot write to %r0\n");
9768 
9769 			if (subr == DIF_SUBR_COPYOUT ||
9770 			    subr == DIF_SUBR_COPYOUTSTR) {
9771 				dp->dtdo_destructive = 1;
9772 			}
9773 
9774 			if (subr == DIF_SUBR_GETF) {
9775 				/*
9776 				 * If we have a getf() we need to record that
9777 				 * in our state.  Note that our state can be
9778 				 * NULL if this is a helper -- but in that
9779 				 * case, the call to getf() is itself illegal,
9780 				 * and will be caught (slightly later) when
9781 				 * the helper is validated.
9782 				 */
9783 				if (vstate->dtvs_state != NULL)
9784 					vstate->dtvs_state->dts_getf++;
9785 			}
9786 
9787 			break;
9788 		case DIF_OP_PUSHTR:
9789 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9790 				err += efunc(pc, "invalid ref type %u\n", type);
9791 			if (r2 >= nregs)
9792 				err += efunc(pc, "invalid register %u\n", r2);
9793 			if (rs >= nregs)
9794 				err += efunc(pc, "invalid register %u\n", rs);
9795 			break;
9796 		case DIF_OP_PUSHTV:
9797 			if (type != DIF_TYPE_CTF)
9798 				err += efunc(pc, "invalid val type %u\n", type);
9799 			if (r2 >= nregs)
9800 				err += efunc(pc, "invalid register %u\n", r2);
9801 			if (rs >= nregs)
9802 				err += efunc(pc, "invalid register %u\n", rs);
9803 			break;
9804 		default:
9805 			err += efunc(pc, "invalid opcode %u\n",
9806 			    DIF_INSTR_OP(instr));
9807 		}
9808 	}
9809 
9810 	if (dp->dtdo_len != 0 &&
9811 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9812 		err += efunc(dp->dtdo_len - 1,
9813 		    "expected 'ret' as last DIF instruction\n");
9814 	}
9815 
9816 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9817 		/*
9818 		 * If we're not returning by reference, the size must be either
9819 		 * 0 or the size of one of the base types.
9820 		 */
9821 		switch (dp->dtdo_rtype.dtdt_size) {
9822 		case 0:
9823 		case sizeof (uint8_t):
9824 		case sizeof (uint16_t):
9825 		case sizeof (uint32_t):
9826 		case sizeof (uint64_t):
9827 			break;
9828 
9829 		default:
9830 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9831 		}
9832 	}
9833 
9834 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9835 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9836 		dtrace_diftype_t *vt, *et;
9837 		uint_t id, ndx;
9838 
9839 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9840 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9841 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9842 			err += efunc(i, "unrecognized variable scope %d\n",
9843 			    v->dtdv_scope);
9844 			break;
9845 		}
9846 
9847 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9848 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9849 			err += efunc(i, "unrecognized variable type %d\n",
9850 			    v->dtdv_kind);
9851 			break;
9852 		}
9853 
9854 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9855 			err += efunc(i, "%d exceeds variable id limit\n", id);
9856 			break;
9857 		}
9858 
9859 		if (id < DIF_VAR_OTHER_UBASE)
9860 			continue;
9861 
9862 		/*
9863 		 * For user-defined variables, we need to check that this
9864 		 * definition is identical to any previous definition that we
9865 		 * encountered.
9866 		 */
9867 		ndx = id - DIF_VAR_OTHER_UBASE;
9868 
9869 		switch (v->dtdv_scope) {
9870 		case DIFV_SCOPE_GLOBAL:
9871 			if (ndx < vstate->dtvs_nglobals) {
9872 				dtrace_statvar_t *svar;
9873 
9874 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9875 					existing = &svar->dtsv_var;
9876 			}
9877 
9878 			break;
9879 
9880 		case DIFV_SCOPE_THREAD:
9881 			if (ndx < vstate->dtvs_ntlocals)
9882 				existing = &vstate->dtvs_tlocals[ndx];
9883 			break;
9884 
9885 		case DIFV_SCOPE_LOCAL:
9886 			if (ndx < vstate->dtvs_nlocals) {
9887 				dtrace_statvar_t *svar;
9888 
9889 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9890 					existing = &svar->dtsv_var;
9891 			}
9892 
9893 			break;
9894 		}
9895 
9896 		vt = &v->dtdv_type;
9897 
9898 		if (vt->dtdt_flags & DIF_TF_BYREF) {
9899 			if (vt->dtdt_size == 0) {
9900 				err += efunc(i, "zero-sized variable\n");
9901 				break;
9902 			}
9903 
9904 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9905 			    vt->dtdt_size > dtrace_global_maxsize) {
9906 				err += efunc(i, "oversized by-ref global\n");
9907 				break;
9908 			}
9909 		}
9910 
9911 		if (existing == NULL || existing->dtdv_id == 0)
9912 			continue;
9913 
9914 		ASSERT(existing->dtdv_id == v->dtdv_id);
9915 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
9916 
9917 		if (existing->dtdv_kind != v->dtdv_kind)
9918 			err += efunc(i, "%d changed variable kind\n", id);
9919 
9920 		et = &existing->dtdv_type;
9921 
9922 		if (vt->dtdt_flags != et->dtdt_flags) {
9923 			err += efunc(i, "%d changed variable type flags\n", id);
9924 			break;
9925 		}
9926 
9927 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9928 			err += efunc(i, "%d changed variable type size\n", id);
9929 			break;
9930 		}
9931 	}
9932 
9933 	return (err);
9934 }
9935 
9936 /*
9937  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9938  * are much more constrained than normal DIFOs.  Specifically, they may
9939  * not:
9940  *
9941  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9942  *    miscellaneous string routines
9943  * 2. Access DTrace variables other than the args[] array, and the
9944  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9945  * 3. Have thread-local variables.
9946  * 4. Have dynamic variables.
9947  */
9948 static int
9949 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9950 {
9951 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9952 	int err = 0;
9953 	uint_t pc;
9954 
9955 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9956 		dif_instr_t instr = dp->dtdo_buf[pc];
9957 
9958 		uint_t v = DIF_INSTR_VAR(instr);
9959 		uint_t subr = DIF_INSTR_SUBR(instr);
9960 		uint_t op = DIF_INSTR_OP(instr);
9961 
9962 		switch (op) {
9963 		case DIF_OP_OR:
9964 		case DIF_OP_XOR:
9965 		case DIF_OP_AND:
9966 		case DIF_OP_SLL:
9967 		case DIF_OP_SRL:
9968 		case DIF_OP_SRA:
9969 		case DIF_OP_SUB:
9970 		case DIF_OP_ADD:
9971 		case DIF_OP_MUL:
9972 		case DIF_OP_SDIV:
9973 		case DIF_OP_UDIV:
9974 		case DIF_OP_SREM:
9975 		case DIF_OP_UREM:
9976 		case DIF_OP_COPYS:
9977 		case DIF_OP_NOT:
9978 		case DIF_OP_MOV:
9979 		case DIF_OP_RLDSB:
9980 		case DIF_OP_RLDSH:
9981 		case DIF_OP_RLDSW:
9982 		case DIF_OP_RLDUB:
9983 		case DIF_OP_RLDUH:
9984 		case DIF_OP_RLDUW:
9985 		case DIF_OP_RLDX:
9986 		case DIF_OP_ULDSB:
9987 		case DIF_OP_ULDSH:
9988 		case DIF_OP_ULDSW:
9989 		case DIF_OP_ULDUB:
9990 		case DIF_OP_ULDUH:
9991 		case DIF_OP_ULDUW:
9992 		case DIF_OP_ULDX:
9993 		case DIF_OP_STB:
9994 		case DIF_OP_STH:
9995 		case DIF_OP_STW:
9996 		case DIF_OP_STX:
9997 		case DIF_OP_ALLOCS:
9998 		case DIF_OP_CMP:
9999 		case DIF_OP_SCMP:
10000 		case DIF_OP_TST:
10001 		case DIF_OP_BA:
10002 		case DIF_OP_BE:
10003 		case DIF_OP_BNE:
10004 		case DIF_OP_BG:
10005 		case DIF_OP_BGU:
10006 		case DIF_OP_BGE:
10007 		case DIF_OP_BGEU:
10008 		case DIF_OP_BL:
10009 		case DIF_OP_BLU:
10010 		case DIF_OP_BLE:
10011 		case DIF_OP_BLEU:
10012 		case DIF_OP_RET:
10013 		case DIF_OP_NOP:
10014 		case DIF_OP_POPTS:
10015 		case DIF_OP_FLUSHTS:
10016 		case DIF_OP_SETX:
10017 		case DIF_OP_SETS:
10018 		case DIF_OP_LDGA:
10019 		case DIF_OP_LDLS:
10020 		case DIF_OP_STGS:
10021 		case DIF_OP_STLS:
10022 		case DIF_OP_PUSHTR:
10023 		case DIF_OP_PUSHTV:
10024 			break;
10025 
10026 		case DIF_OP_LDGS:
10027 			if (v >= DIF_VAR_OTHER_UBASE)
10028 				break;
10029 
10030 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10031 				break;
10032 
10033 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10034 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10035 			    v == DIF_VAR_EXECARGS ||
10036 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10037 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10038 				break;
10039 
10040 			err += efunc(pc, "illegal variable %u\n", v);
10041 			break;
10042 
10043 		case DIF_OP_LDTA:
10044 		case DIF_OP_LDTS:
10045 		case DIF_OP_LDGAA:
10046 		case DIF_OP_LDTAA:
10047 			err += efunc(pc, "illegal dynamic variable load\n");
10048 			break;
10049 
10050 		case DIF_OP_STTS:
10051 		case DIF_OP_STGAA:
10052 		case DIF_OP_STTAA:
10053 			err += efunc(pc, "illegal dynamic variable store\n");
10054 			break;
10055 
10056 		case DIF_OP_CALL:
10057 			if (subr == DIF_SUBR_ALLOCA ||
10058 			    subr == DIF_SUBR_BCOPY ||
10059 			    subr == DIF_SUBR_COPYIN ||
10060 			    subr == DIF_SUBR_COPYINTO ||
10061 			    subr == DIF_SUBR_COPYINSTR ||
10062 			    subr == DIF_SUBR_INDEX ||
10063 			    subr == DIF_SUBR_INET_NTOA ||
10064 			    subr == DIF_SUBR_INET_NTOA6 ||
10065 			    subr == DIF_SUBR_INET_NTOP ||
10066 			    subr == DIF_SUBR_JSON ||
10067 			    subr == DIF_SUBR_LLTOSTR ||
10068 			    subr == DIF_SUBR_STRTOLL ||
10069 			    subr == DIF_SUBR_RINDEX ||
10070 			    subr == DIF_SUBR_STRCHR ||
10071 			    subr == DIF_SUBR_STRJOIN ||
10072 			    subr == DIF_SUBR_STRRCHR ||
10073 			    subr == DIF_SUBR_STRSTR ||
10074 			    subr == DIF_SUBR_HTONS ||
10075 			    subr == DIF_SUBR_HTONL ||
10076 			    subr == DIF_SUBR_HTONLL ||
10077 			    subr == DIF_SUBR_NTOHS ||
10078 			    subr == DIF_SUBR_NTOHL ||
10079 			    subr == DIF_SUBR_NTOHLL ||
10080 			    subr == DIF_SUBR_MEMREF ||
10081 #if !defined(sun)
10082 			    subr == DIF_SUBR_MEMSTR ||
10083 #endif
10084 			    subr == DIF_SUBR_TYPEREF)
10085 				break;
10086 
10087 			err += efunc(pc, "invalid subr %u\n", subr);
10088 			break;
10089 
10090 		default:
10091 			err += efunc(pc, "invalid opcode %u\n",
10092 			    DIF_INSTR_OP(instr));
10093 		}
10094 	}
10095 
10096 	return (err);
10097 }
10098 
10099 /*
10100  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10101  * basis; 0 if not.
10102  */
10103 static int
10104 dtrace_difo_cacheable(dtrace_difo_t *dp)
10105 {
10106 	int i;
10107 
10108 	if (dp == NULL)
10109 		return (0);
10110 
10111 	for (i = 0; i < dp->dtdo_varlen; i++) {
10112 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10113 
10114 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10115 			continue;
10116 
10117 		switch (v->dtdv_id) {
10118 		case DIF_VAR_CURTHREAD:
10119 		case DIF_VAR_PID:
10120 		case DIF_VAR_TID:
10121 		case DIF_VAR_EXECARGS:
10122 		case DIF_VAR_EXECNAME:
10123 		case DIF_VAR_ZONENAME:
10124 			break;
10125 
10126 		default:
10127 			return (0);
10128 		}
10129 	}
10130 
10131 	/*
10132 	 * This DIF object may be cacheable.  Now we need to look for any
10133 	 * array loading instructions, any memory loading instructions, or
10134 	 * any stores to thread-local variables.
10135 	 */
10136 	for (i = 0; i < dp->dtdo_len; i++) {
10137 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10138 
10139 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10140 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10141 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10142 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10143 			return (0);
10144 	}
10145 
10146 	return (1);
10147 }
10148 
10149 static void
10150 dtrace_difo_hold(dtrace_difo_t *dp)
10151 {
10152 	int i;
10153 
10154 	ASSERT(MUTEX_HELD(&dtrace_lock));
10155 
10156 	dp->dtdo_refcnt++;
10157 	ASSERT(dp->dtdo_refcnt != 0);
10158 
10159 	/*
10160 	 * We need to check this DIF object for references to the variable
10161 	 * DIF_VAR_VTIMESTAMP.
10162 	 */
10163 	for (i = 0; i < dp->dtdo_varlen; i++) {
10164 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10165 
10166 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10167 			continue;
10168 
10169 		if (dtrace_vtime_references++ == 0)
10170 			dtrace_vtime_enable();
10171 	}
10172 }
10173 
10174 /*
10175  * This routine calculates the dynamic variable chunksize for a given DIF
10176  * object.  The calculation is not fool-proof, and can probably be tricked by
10177  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10178  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10179  * if a dynamic variable size exceeds the chunksize.
10180  */
10181 static void
10182 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10183 {
10184 	uint64_t sval = 0;
10185 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10186 	const dif_instr_t *text = dp->dtdo_buf;
10187 	uint_t pc, srd = 0;
10188 	uint_t ttop = 0;
10189 	size_t size, ksize;
10190 	uint_t id, i;
10191 
10192 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10193 		dif_instr_t instr = text[pc];
10194 		uint_t op = DIF_INSTR_OP(instr);
10195 		uint_t rd = DIF_INSTR_RD(instr);
10196 		uint_t r1 = DIF_INSTR_R1(instr);
10197 		uint_t nkeys = 0;
10198 		uchar_t scope = 0;
10199 
10200 		dtrace_key_t *key = tupregs;
10201 
10202 		switch (op) {
10203 		case DIF_OP_SETX:
10204 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10205 			srd = rd;
10206 			continue;
10207 
10208 		case DIF_OP_STTS:
10209 			key = &tupregs[DIF_DTR_NREGS];
10210 			key[0].dttk_size = 0;
10211 			key[1].dttk_size = 0;
10212 			nkeys = 2;
10213 			scope = DIFV_SCOPE_THREAD;
10214 			break;
10215 
10216 		case DIF_OP_STGAA:
10217 		case DIF_OP_STTAA:
10218 			nkeys = ttop;
10219 
10220 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10221 				key[nkeys++].dttk_size = 0;
10222 
10223 			key[nkeys++].dttk_size = 0;
10224 
10225 			if (op == DIF_OP_STTAA) {
10226 				scope = DIFV_SCOPE_THREAD;
10227 			} else {
10228 				scope = DIFV_SCOPE_GLOBAL;
10229 			}
10230 
10231 			break;
10232 
10233 		case DIF_OP_PUSHTR:
10234 			if (ttop == DIF_DTR_NREGS)
10235 				return;
10236 
10237 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10238 				/*
10239 				 * If the register for the size of the "pushtr"
10240 				 * is %r0 (or the value is 0) and the type is
10241 				 * a string, we'll use the system-wide default
10242 				 * string size.
10243 				 */
10244 				tupregs[ttop++].dttk_size =
10245 				    dtrace_strsize_default;
10246 			} else {
10247 				if (srd == 0)
10248 					return;
10249 
10250 				tupregs[ttop++].dttk_size = sval;
10251 			}
10252 
10253 			break;
10254 
10255 		case DIF_OP_PUSHTV:
10256 			if (ttop == DIF_DTR_NREGS)
10257 				return;
10258 
10259 			tupregs[ttop++].dttk_size = 0;
10260 			break;
10261 
10262 		case DIF_OP_FLUSHTS:
10263 			ttop = 0;
10264 			break;
10265 
10266 		case DIF_OP_POPTS:
10267 			if (ttop != 0)
10268 				ttop--;
10269 			break;
10270 		}
10271 
10272 		sval = 0;
10273 		srd = 0;
10274 
10275 		if (nkeys == 0)
10276 			continue;
10277 
10278 		/*
10279 		 * We have a dynamic variable allocation; calculate its size.
10280 		 */
10281 		for (ksize = 0, i = 0; i < nkeys; i++)
10282 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10283 
10284 		size = sizeof (dtrace_dynvar_t);
10285 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10286 		size += ksize;
10287 
10288 		/*
10289 		 * Now we need to determine the size of the stored data.
10290 		 */
10291 		id = DIF_INSTR_VAR(instr);
10292 
10293 		for (i = 0; i < dp->dtdo_varlen; i++) {
10294 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10295 
10296 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10297 				size += v->dtdv_type.dtdt_size;
10298 				break;
10299 			}
10300 		}
10301 
10302 		if (i == dp->dtdo_varlen)
10303 			return;
10304 
10305 		/*
10306 		 * We have the size.  If this is larger than the chunk size
10307 		 * for our dynamic variable state, reset the chunk size.
10308 		 */
10309 		size = P2ROUNDUP(size, sizeof (uint64_t));
10310 
10311 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10312 			vstate->dtvs_dynvars.dtds_chunksize = size;
10313 	}
10314 }
10315 
10316 static void
10317 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10318 {
10319 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10320 	uint_t id;
10321 
10322 	ASSERT(MUTEX_HELD(&dtrace_lock));
10323 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10324 
10325 	for (i = 0; i < dp->dtdo_varlen; i++) {
10326 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10327 		dtrace_statvar_t *svar, ***svarp = NULL;
10328 		size_t dsize = 0;
10329 		uint8_t scope = v->dtdv_scope;
10330 		int *np = NULL;
10331 
10332 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10333 			continue;
10334 
10335 		id -= DIF_VAR_OTHER_UBASE;
10336 
10337 		switch (scope) {
10338 		case DIFV_SCOPE_THREAD:
10339 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10340 				dtrace_difv_t *tlocals;
10341 
10342 				if ((ntlocals = (otlocals << 1)) == 0)
10343 					ntlocals = 1;
10344 
10345 				osz = otlocals * sizeof (dtrace_difv_t);
10346 				nsz = ntlocals * sizeof (dtrace_difv_t);
10347 
10348 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10349 
10350 				if (osz != 0) {
10351 					bcopy(vstate->dtvs_tlocals,
10352 					    tlocals, osz);
10353 					kmem_free(vstate->dtvs_tlocals, osz);
10354 				}
10355 
10356 				vstate->dtvs_tlocals = tlocals;
10357 				vstate->dtvs_ntlocals = ntlocals;
10358 			}
10359 
10360 			vstate->dtvs_tlocals[id] = *v;
10361 			continue;
10362 
10363 		case DIFV_SCOPE_LOCAL:
10364 			np = &vstate->dtvs_nlocals;
10365 			svarp = &vstate->dtvs_locals;
10366 
10367 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10368 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10369 				    sizeof (uint64_t));
10370 			else
10371 				dsize = NCPU * sizeof (uint64_t);
10372 
10373 			break;
10374 
10375 		case DIFV_SCOPE_GLOBAL:
10376 			np = &vstate->dtvs_nglobals;
10377 			svarp = &vstate->dtvs_globals;
10378 
10379 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10380 				dsize = v->dtdv_type.dtdt_size +
10381 				    sizeof (uint64_t);
10382 
10383 			break;
10384 
10385 		default:
10386 			ASSERT(0);
10387 		}
10388 
10389 		while (id >= (oldsvars = *np)) {
10390 			dtrace_statvar_t **statics;
10391 			int newsvars, oldsize, newsize;
10392 
10393 			if ((newsvars = (oldsvars << 1)) == 0)
10394 				newsvars = 1;
10395 
10396 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10397 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10398 
10399 			statics = kmem_zalloc(newsize, KM_SLEEP);
10400 
10401 			if (oldsize != 0) {
10402 				bcopy(*svarp, statics, oldsize);
10403 				kmem_free(*svarp, oldsize);
10404 			}
10405 
10406 			*svarp = statics;
10407 			*np = newsvars;
10408 		}
10409 
10410 		if ((svar = (*svarp)[id]) == NULL) {
10411 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10412 			svar->dtsv_var = *v;
10413 
10414 			if ((svar->dtsv_size = dsize) != 0) {
10415 				svar->dtsv_data = (uint64_t)(uintptr_t)
10416 				    kmem_zalloc(dsize, KM_SLEEP);
10417 			}
10418 
10419 			(*svarp)[id] = svar;
10420 		}
10421 
10422 		svar->dtsv_refcnt++;
10423 	}
10424 
10425 	dtrace_difo_chunksize(dp, vstate);
10426 	dtrace_difo_hold(dp);
10427 }
10428 
10429 static dtrace_difo_t *
10430 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10431 {
10432 	dtrace_difo_t *new;
10433 	size_t sz;
10434 
10435 	ASSERT(dp->dtdo_buf != NULL);
10436 	ASSERT(dp->dtdo_refcnt != 0);
10437 
10438 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10439 
10440 	ASSERT(dp->dtdo_buf != NULL);
10441 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10442 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10443 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10444 	new->dtdo_len = dp->dtdo_len;
10445 
10446 	if (dp->dtdo_strtab != NULL) {
10447 		ASSERT(dp->dtdo_strlen != 0);
10448 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10449 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10450 		new->dtdo_strlen = dp->dtdo_strlen;
10451 	}
10452 
10453 	if (dp->dtdo_inttab != NULL) {
10454 		ASSERT(dp->dtdo_intlen != 0);
10455 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10456 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10457 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10458 		new->dtdo_intlen = dp->dtdo_intlen;
10459 	}
10460 
10461 	if (dp->dtdo_vartab != NULL) {
10462 		ASSERT(dp->dtdo_varlen != 0);
10463 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10464 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10465 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10466 		new->dtdo_varlen = dp->dtdo_varlen;
10467 	}
10468 
10469 	dtrace_difo_init(new, vstate);
10470 	return (new);
10471 }
10472 
10473 static void
10474 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10475 {
10476 	int i;
10477 
10478 	ASSERT(dp->dtdo_refcnt == 0);
10479 
10480 	for (i = 0; i < dp->dtdo_varlen; i++) {
10481 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10482 		dtrace_statvar_t *svar, **svarp = NULL;
10483 		uint_t id;
10484 		uint8_t scope = v->dtdv_scope;
10485 		int *np = NULL;
10486 
10487 		switch (scope) {
10488 		case DIFV_SCOPE_THREAD:
10489 			continue;
10490 
10491 		case DIFV_SCOPE_LOCAL:
10492 			np = &vstate->dtvs_nlocals;
10493 			svarp = vstate->dtvs_locals;
10494 			break;
10495 
10496 		case DIFV_SCOPE_GLOBAL:
10497 			np = &vstate->dtvs_nglobals;
10498 			svarp = vstate->dtvs_globals;
10499 			break;
10500 
10501 		default:
10502 			ASSERT(0);
10503 		}
10504 
10505 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10506 			continue;
10507 
10508 		id -= DIF_VAR_OTHER_UBASE;
10509 		ASSERT(id < *np);
10510 
10511 		svar = svarp[id];
10512 		ASSERT(svar != NULL);
10513 		ASSERT(svar->dtsv_refcnt > 0);
10514 
10515 		if (--svar->dtsv_refcnt > 0)
10516 			continue;
10517 
10518 		if (svar->dtsv_size != 0) {
10519 			ASSERT(svar->dtsv_data != 0);
10520 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10521 			    svar->dtsv_size);
10522 		}
10523 
10524 		kmem_free(svar, sizeof (dtrace_statvar_t));
10525 		svarp[id] = NULL;
10526 	}
10527 
10528 	if (dp->dtdo_buf != NULL)
10529 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10530 	if (dp->dtdo_inttab != NULL)
10531 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10532 	if (dp->dtdo_strtab != NULL)
10533 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10534 	if (dp->dtdo_vartab != NULL)
10535 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10536 
10537 	kmem_free(dp, sizeof (dtrace_difo_t));
10538 }
10539 
10540 static void
10541 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10542 {
10543 	int i;
10544 
10545 	ASSERT(MUTEX_HELD(&dtrace_lock));
10546 	ASSERT(dp->dtdo_refcnt != 0);
10547 
10548 	for (i = 0; i < dp->dtdo_varlen; i++) {
10549 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10550 
10551 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10552 			continue;
10553 
10554 		ASSERT(dtrace_vtime_references > 0);
10555 		if (--dtrace_vtime_references == 0)
10556 			dtrace_vtime_disable();
10557 	}
10558 
10559 	if (--dp->dtdo_refcnt == 0)
10560 		dtrace_difo_destroy(dp, vstate);
10561 }
10562 
10563 /*
10564  * DTrace Format Functions
10565  */
10566 static uint16_t
10567 dtrace_format_add(dtrace_state_t *state, char *str)
10568 {
10569 	char *fmt, **new;
10570 	uint16_t ndx, len = strlen(str) + 1;
10571 
10572 	fmt = kmem_zalloc(len, KM_SLEEP);
10573 	bcopy(str, fmt, len);
10574 
10575 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10576 		if (state->dts_formats[ndx] == NULL) {
10577 			state->dts_formats[ndx] = fmt;
10578 			return (ndx + 1);
10579 		}
10580 	}
10581 
10582 	if (state->dts_nformats == USHRT_MAX) {
10583 		/*
10584 		 * This is only likely if a denial-of-service attack is being
10585 		 * attempted.  As such, it's okay to fail silently here.
10586 		 */
10587 		kmem_free(fmt, len);
10588 		return (0);
10589 	}
10590 
10591 	/*
10592 	 * For simplicity, we always resize the formats array to be exactly the
10593 	 * number of formats.
10594 	 */
10595 	ndx = state->dts_nformats++;
10596 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10597 
10598 	if (state->dts_formats != NULL) {
10599 		ASSERT(ndx != 0);
10600 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10601 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10602 	}
10603 
10604 	state->dts_formats = new;
10605 	state->dts_formats[ndx] = fmt;
10606 
10607 	return (ndx + 1);
10608 }
10609 
10610 static void
10611 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10612 {
10613 	char *fmt;
10614 
10615 	ASSERT(state->dts_formats != NULL);
10616 	ASSERT(format <= state->dts_nformats);
10617 	ASSERT(state->dts_formats[format - 1] != NULL);
10618 
10619 	fmt = state->dts_formats[format - 1];
10620 	kmem_free(fmt, strlen(fmt) + 1);
10621 	state->dts_formats[format - 1] = NULL;
10622 }
10623 
10624 static void
10625 dtrace_format_destroy(dtrace_state_t *state)
10626 {
10627 	int i;
10628 
10629 	if (state->dts_nformats == 0) {
10630 		ASSERT(state->dts_formats == NULL);
10631 		return;
10632 	}
10633 
10634 	ASSERT(state->dts_formats != NULL);
10635 
10636 	for (i = 0; i < state->dts_nformats; i++) {
10637 		char *fmt = state->dts_formats[i];
10638 
10639 		if (fmt == NULL)
10640 			continue;
10641 
10642 		kmem_free(fmt, strlen(fmt) + 1);
10643 	}
10644 
10645 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10646 	state->dts_nformats = 0;
10647 	state->dts_formats = NULL;
10648 }
10649 
10650 /*
10651  * DTrace Predicate Functions
10652  */
10653 static dtrace_predicate_t *
10654 dtrace_predicate_create(dtrace_difo_t *dp)
10655 {
10656 	dtrace_predicate_t *pred;
10657 
10658 	ASSERT(MUTEX_HELD(&dtrace_lock));
10659 	ASSERT(dp->dtdo_refcnt != 0);
10660 
10661 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10662 	pred->dtp_difo = dp;
10663 	pred->dtp_refcnt = 1;
10664 
10665 	if (!dtrace_difo_cacheable(dp))
10666 		return (pred);
10667 
10668 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10669 		/*
10670 		 * This is only theoretically possible -- we have had 2^32
10671 		 * cacheable predicates on this machine.  We cannot allow any
10672 		 * more predicates to become cacheable:  as unlikely as it is,
10673 		 * there may be a thread caching a (now stale) predicate cache
10674 		 * ID. (N.B.: the temptation is being successfully resisted to
10675 		 * have this cmn_err() "Holy shit -- we executed this code!")
10676 		 */
10677 		return (pred);
10678 	}
10679 
10680 	pred->dtp_cacheid = dtrace_predcache_id++;
10681 
10682 	return (pred);
10683 }
10684 
10685 static void
10686 dtrace_predicate_hold(dtrace_predicate_t *pred)
10687 {
10688 	ASSERT(MUTEX_HELD(&dtrace_lock));
10689 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10690 	ASSERT(pred->dtp_refcnt > 0);
10691 
10692 	pred->dtp_refcnt++;
10693 }
10694 
10695 static void
10696 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10697 {
10698 	dtrace_difo_t *dp = pred->dtp_difo;
10699 
10700 	ASSERT(MUTEX_HELD(&dtrace_lock));
10701 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10702 	ASSERT(pred->dtp_refcnt > 0);
10703 
10704 	if (--pred->dtp_refcnt == 0) {
10705 		dtrace_difo_release(pred->dtp_difo, vstate);
10706 		kmem_free(pred, sizeof (dtrace_predicate_t));
10707 	}
10708 }
10709 
10710 /*
10711  * DTrace Action Description Functions
10712  */
10713 static dtrace_actdesc_t *
10714 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10715     uint64_t uarg, uint64_t arg)
10716 {
10717 	dtrace_actdesc_t *act;
10718 
10719 #if defined(sun)
10720 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10721 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10722 #endif
10723 
10724 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10725 	act->dtad_kind = kind;
10726 	act->dtad_ntuple = ntuple;
10727 	act->dtad_uarg = uarg;
10728 	act->dtad_arg = arg;
10729 	act->dtad_refcnt = 1;
10730 
10731 	return (act);
10732 }
10733 
10734 static void
10735 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10736 {
10737 	ASSERT(act->dtad_refcnt >= 1);
10738 	act->dtad_refcnt++;
10739 }
10740 
10741 static void
10742 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10743 {
10744 	dtrace_actkind_t kind = act->dtad_kind;
10745 	dtrace_difo_t *dp;
10746 
10747 	ASSERT(act->dtad_refcnt >= 1);
10748 
10749 	if (--act->dtad_refcnt != 0)
10750 		return;
10751 
10752 	if ((dp = act->dtad_difo) != NULL)
10753 		dtrace_difo_release(dp, vstate);
10754 
10755 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10756 		char *str = (char *)(uintptr_t)act->dtad_arg;
10757 
10758 #if defined(sun)
10759 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10760 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10761 #endif
10762 
10763 		if (str != NULL)
10764 			kmem_free(str, strlen(str) + 1);
10765 	}
10766 
10767 	kmem_free(act, sizeof (dtrace_actdesc_t));
10768 }
10769 
10770 /*
10771  * DTrace ECB Functions
10772  */
10773 static dtrace_ecb_t *
10774 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10775 {
10776 	dtrace_ecb_t *ecb;
10777 	dtrace_epid_t epid;
10778 
10779 	ASSERT(MUTEX_HELD(&dtrace_lock));
10780 
10781 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10782 	ecb->dte_predicate = NULL;
10783 	ecb->dte_probe = probe;
10784 
10785 	/*
10786 	 * The default size is the size of the default action: recording
10787 	 * the header.
10788 	 */
10789 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10790 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10791 
10792 	epid = state->dts_epid++;
10793 
10794 	if (epid - 1 >= state->dts_necbs) {
10795 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10796 		int necbs = state->dts_necbs << 1;
10797 
10798 		ASSERT(epid == state->dts_necbs + 1);
10799 
10800 		if (necbs == 0) {
10801 			ASSERT(oecbs == NULL);
10802 			necbs = 1;
10803 		}
10804 
10805 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10806 
10807 		if (oecbs != NULL)
10808 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10809 
10810 		dtrace_membar_producer();
10811 		state->dts_ecbs = ecbs;
10812 
10813 		if (oecbs != NULL) {
10814 			/*
10815 			 * If this state is active, we must dtrace_sync()
10816 			 * before we can free the old dts_ecbs array:  we're
10817 			 * coming in hot, and there may be active ring
10818 			 * buffer processing (which indexes into the dts_ecbs
10819 			 * array) on another CPU.
10820 			 */
10821 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10822 				dtrace_sync();
10823 
10824 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10825 		}
10826 
10827 		dtrace_membar_producer();
10828 		state->dts_necbs = necbs;
10829 	}
10830 
10831 	ecb->dte_state = state;
10832 
10833 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
10834 	dtrace_membar_producer();
10835 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10836 
10837 	return (ecb);
10838 }
10839 
10840 static void
10841 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10842 {
10843 	dtrace_probe_t *probe = ecb->dte_probe;
10844 
10845 	ASSERT(MUTEX_HELD(&cpu_lock));
10846 	ASSERT(MUTEX_HELD(&dtrace_lock));
10847 	ASSERT(ecb->dte_next == NULL);
10848 
10849 	if (probe == NULL) {
10850 		/*
10851 		 * This is the NULL probe -- there's nothing to do.
10852 		 */
10853 		return;
10854 	}
10855 
10856 	if (probe->dtpr_ecb == NULL) {
10857 		dtrace_provider_t *prov = probe->dtpr_provider;
10858 
10859 		/*
10860 		 * We're the first ECB on this probe.
10861 		 */
10862 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10863 
10864 		if (ecb->dte_predicate != NULL)
10865 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10866 
10867 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10868 		    probe->dtpr_id, probe->dtpr_arg);
10869 	} else {
10870 		/*
10871 		 * This probe is already active.  Swing the last pointer to
10872 		 * point to the new ECB, and issue a dtrace_sync() to assure
10873 		 * that all CPUs have seen the change.
10874 		 */
10875 		ASSERT(probe->dtpr_ecb_last != NULL);
10876 		probe->dtpr_ecb_last->dte_next = ecb;
10877 		probe->dtpr_ecb_last = ecb;
10878 		probe->dtpr_predcache = 0;
10879 
10880 		dtrace_sync();
10881 	}
10882 }
10883 
10884 static void
10885 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10886 {
10887 	dtrace_action_t *act;
10888 	uint32_t curneeded = UINT32_MAX;
10889 	uint32_t aggbase = UINT32_MAX;
10890 
10891 	/*
10892 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
10893 	 * we always record it first.)
10894 	 */
10895 	ecb->dte_size = sizeof (dtrace_rechdr_t);
10896 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10897 
10898 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10899 		dtrace_recdesc_t *rec = &act->dta_rec;
10900 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10901 
10902 		ecb->dte_alignment = MAX(ecb->dte_alignment,
10903 		    rec->dtrd_alignment);
10904 
10905 		if (DTRACEACT_ISAGG(act->dta_kind)) {
10906 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10907 
10908 			ASSERT(rec->dtrd_size != 0);
10909 			ASSERT(agg->dtag_first != NULL);
10910 			ASSERT(act->dta_prev->dta_intuple);
10911 			ASSERT(aggbase != UINT32_MAX);
10912 			ASSERT(curneeded != UINT32_MAX);
10913 
10914 			agg->dtag_base = aggbase;
10915 
10916 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10917 			rec->dtrd_offset = curneeded;
10918 			curneeded += rec->dtrd_size;
10919 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10920 
10921 			aggbase = UINT32_MAX;
10922 			curneeded = UINT32_MAX;
10923 		} else if (act->dta_intuple) {
10924 			if (curneeded == UINT32_MAX) {
10925 				/*
10926 				 * This is the first record in a tuple.  Align
10927 				 * curneeded to be at offset 4 in an 8-byte
10928 				 * aligned block.
10929 				 */
10930 				ASSERT(act->dta_prev == NULL ||
10931 				    !act->dta_prev->dta_intuple);
10932 				ASSERT3U(aggbase, ==, UINT32_MAX);
10933 				curneeded = P2PHASEUP(ecb->dte_size,
10934 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10935 
10936 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10937 				ASSERT(IS_P2ALIGNED(aggbase,
10938 				    sizeof (uint64_t)));
10939 			}
10940 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10941 			rec->dtrd_offset = curneeded;
10942 			curneeded += rec->dtrd_size;
10943 		} else {
10944 			/* tuples must be followed by an aggregation */
10945 			ASSERT(act->dta_prev == NULL ||
10946 			    !act->dta_prev->dta_intuple);
10947 
10948 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10949 			    rec->dtrd_alignment);
10950 			rec->dtrd_offset = ecb->dte_size;
10951 			ecb->dte_size += rec->dtrd_size;
10952 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10953 		}
10954 	}
10955 
10956 	if ((act = ecb->dte_action) != NULL &&
10957 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10958 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10959 		/*
10960 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10961 		 * actions store no data; set the size to 0.
10962 		 */
10963 		ecb->dte_size = 0;
10964 	}
10965 
10966 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10967 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10968 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10969 	    ecb->dte_needed);
10970 }
10971 
10972 static dtrace_action_t *
10973 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10974 {
10975 	dtrace_aggregation_t *agg;
10976 	size_t size = sizeof (uint64_t);
10977 	int ntuple = desc->dtad_ntuple;
10978 	dtrace_action_t *act;
10979 	dtrace_recdesc_t *frec;
10980 	dtrace_aggid_t aggid;
10981 	dtrace_state_t *state = ecb->dte_state;
10982 
10983 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10984 	agg->dtag_ecb = ecb;
10985 
10986 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10987 
10988 	switch (desc->dtad_kind) {
10989 	case DTRACEAGG_MIN:
10990 		agg->dtag_initial = INT64_MAX;
10991 		agg->dtag_aggregate = dtrace_aggregate_min;
10992 		break;
10993 
10994 	case DTRACEAGG_MAX:
10995 		agg->dtag_initial = INT64_MIN;
10996 		agg->dtag_aggregate = dtrace_aggregate_max;
10997 		break;
10998 
10999 	case DTRACEAGG_COUNT:
11000 		agg->dtag_aggregate = dtrace_aggregate_count;
11001 		break;
11002 
11003 	case DTRACEAGG_QUANTIZE:
11004 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11005 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11006 		    sizeof (uint64_t);
11007 		break;
11008 
11009 	case DTRACEAGG_LQUANTIZE: {
11010 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11011 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11012 
11013 		agg->dtag_initial = desc->dtad_arg;
11014 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11015 
11016 		if (step == 0 || levels == 0)
11017 			goto err;
11018 
11019 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11020 		break;
11021 	}
11022 
11023 	case DTRACEAGG_LLQUANTIZE: {
11024 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11025 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11026 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11027 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11028 		int64_t v;
11029 
11030 		agg->dtag_initial = desc->dtad_arg;
11031 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11032 
11033 		if (factor < 2 || low >= high || nsteps < factor)
11034 			goto err;
11035 
11036 		/*
11037 		 * Now check that the number of steps evenly divides a power
11038 		 * of the factor.  (This assures both integer bucket size and
11039 		 * linearity within each magnitude.)
11040 		 */
11041 		for (v = factor; v < nsteps; v *= factor)
11042 			continue;
11043 
11044 		if ((v % nsteps) || (nsteps % factor))
11045 			goto err;
11046 
11047 		size = (dtrace_aggregate_llquantize_bucket(factor,
11048 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11049 		break;
11050 	}
11051 
11052 	case DTRACEAGG_AVG:
11053 		agg->dtag_aggregate = dtrace_aggregate_avg;
11054 		size = sizeof (uint64_t) * 2;
11055 		break;
11056 
11057 	case DTRACEAGG_STDDEV:
11058 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11059 		size = sizeof (uint64_t) * 4;
11060 		break;
11061 
11062 	case DTRACEAGG_SUM:
11063 		agg->dtag_aggregate = dtrace_aggregate_sum;
11064 		break;
11065 
11066 	default:
11067 		goto err;
11068 	}
11069 
11070 	agg->dtag_action.dta_rec.dtrd_size = size;
11071 
11072 	if (ntuple == 0)
11073 		goto err;
11074 
11075 	/*
11076 	 * We must make sure that we have enough actions for the n-tuple.
11077 	 */
11078 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11079 		if (DTRACEACT_ISAGG(act->dta_kind))
11080 			break;
11081 
11082 		if (--ntuple == 0) {
11083 			/*
11084 			 * This is the action with which our n-tuple begins.
11085 			 */
11086 			agg->dtag_first = act;
11087 			goto success;
11088 		}
11089 	}
11090 
11091 	/*
11092 	 * This n-tuple is short by ntuple elements.  Return failure.
11093 	 */
11094 	ASSERT(ntuple != 0);
11095 err:
11096 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11097 	return (NULL);
11098 
11099 success:
11100 	/*
11101 	 * If the last action in the tuple has a size of zero, it's actually
11102 	 * an expression argument for the aggregating action.
11103 	 */
11104 	ASSERT(ecb->dte_action_last != NULL);
11105 	act = ecb->dte_action_last;
11106 
11107 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11108 		ASSERT(act->dta_difo != NULL);
11109 
11110 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11111 			agg->dtag_hasarg = 1;
11112 	}
11113 
11114 	/*
11115 	 * We need to allocate an id for this aggregation.
11116 	 */
11117 #if defined(sun)
11118 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11119 	    VM_BESTFIT | VM_SLEEP);
11120 #else
11121 	aggid = alloc_unr(state->dts_aggid_arena);
11122 #endif
11123 
11124 	if (aggid - 1 >= state->dts_naggregations) {
11125 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11126 		dtrace_aggregation_t **aggs;
11127 		int naggs = state->dts_naggregations << 1;
11128 		int onaggs = state->dts_naggregations;
11129 
11130 		ASSERT(aggid == state->dts_naggregations + 1);
11131 
11132 		if (naggs == 0) {
11133 			ASSERT(oaggs == NULL);
11134 			naggs = 1;
11135 		}
11136 
11137 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11138 
11139 		if (oaggs != NULL) {
11140 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11141 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11142 		}
11143 
11144 		state->dts_aggregations = aggs;
11145 		state->dts_naggregations = naggs;
11146 	}
11147 
11148 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11149 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11150 
11151 	frec = &agg->dtag_first->dta_rec;
11152 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11153 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11154 
11155 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11156 		ASSERT(!act->dta_intuple);
11157 		act->dta_intuple = 1;
11158 	}
11159 
11160 	return (&agg->dtag_action);
11161 }
11162 
11163 static void
11164 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11165 {
11166 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11167 	dtrace_state_t *state = ecb->dte_state;
11168 	dtrace_aggid_t aggid = agg->dtag_id;
11169 
11170 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11171 #if defined(sun)
11172 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11173 #else
11174 	free_unr(state->dts_aggid_arena, aggid);
11175 #endif
11176 
11177 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11178 	state->dts_aggregations[aggid - 1] = NULL;
11179 
11180 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11181 }
11182 
11183 static int
11184 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11185 {
11186 	dtrace_action_t *action, *last;
11187 	dtrace_difo_t *dp = desc->dtad_difo;
11188 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11189 	uint16_t format = 0;
11190 	dtrace_recdesc_t *rec;
11191 	dtrace_state_t *state = ecb->dte_state;
11192 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11193 	uint64_t arg = desc->dtad_arg;
11194 
11195 	ASSERT(MUTEX_HELD(&dtrace_lock));
11196 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11197 
11198 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11199 		/*
11200 		 * If this is an aggregating action, there must be neither
11201 		 * a speculate nor a commit on the action chain.
11202 		 */
11203 		dtrace_action_t *act;
11204 
11205 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11206 			if (act->dta_kind == DTRACEACT_COMMIT)
11207 				return (EINVAL);
11208 
11209 			if (act->dta_kind == DTRACEACT_SPECULATE)
11210 				return (EINVAL);
11211 		}
11212 
11213 		action = dtrace_ecb_aggregation_create(ecb, desc);
11214 
11215 		if (action == NULL)
11216 			return (EINVAL);
11217 	} else {
11218 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11219 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11220 		    dp != NULL && dp->dtdo_destructive)) {
11221 			state->dts_destructive = 1;
11222 		}
11223 
11224 		switch (desc->dtad_kind) {
11225 		case DTRACEACT_PRINTF:
11226 		case DTRACEACT_PRINTA:
11227 		case DTRACEACT_SYSTEM:
11228 		case DTRACEACT_FREOPEN:
11229 		case DTRACEACT_DIFEXPR:
11230 			/*
11231 			 * We know that our arg is a string -- turn it into a
11232 			 * format.
11233 			 */
11234 			if (arg == 0) {
11235 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11236 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11237 				format = 0;
11238 			} else {
11239 				ASSERT(arg != 0);
11240 #if defined(sun)
11241 				ASSERT(arg > KERNELBASE);
11242 #endif
11243 				format = dtrace_format_add(state,
11244 				    (char *)(uintptr_t)arg);
11245 			}
11246 
11247 			/*FALLTHROUGH*/
11248 		case DTRACEACT_LIBACT:
11249 		case DTRACEACT_TRACEMEM:
11250 		case DTRACEACT_TRACEMEM_DYNSIZE:
11251 			if (dp == NULL)
11252 				return (EINVAL);
11253 
11254 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11255 				break;
11256 
11257 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11258 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11259 					return (EINVAL);
11260 
11261 				size = opt[DTRACEOPT_STRSIZE];
11262 			}
11263 
11264 			break;
11265 
11266 		case DTRACEACT_STACK:
11267 			if ((nframes = arg) == 0) {
11268 				nframes = opt[DTRACEOPT_STACKFRAMES];
11269 				ASSERT(nframes > 0);
11270 				arg = nframes;
11271 			}
11272 
11273 			size = nframes * sizeof (pc_t);
11274 			break;
11275 
11276 		case DTRACEACT_JSTACK:
11277 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11278 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11279 
11280 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11281 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11282 
11283 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11284 
11285 			/*FALLTHROUGH*/
11286 		case DTRACEACT_USTACK:
11287 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11288 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11289 				strsize = DTRACE_USTACK_STRSIZE(arg);
11290 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11291 				ASSERT(nframes > 0);
11292 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11293 			}
11294 
11295 			/*
11296 			 * Save a slot for the pid.
11297 			 */
11298 			size = (nframes + 1) * sizeof (uint64_t);
11299 			size += DTRACE_USTACK_STRSIZE(arg);
11300 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11301 
11302 			break;
11303 
11304 		case DTRACEACT_SYM:
11305 		case DTRACEACT_MOD:
11306 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11307 			    sizeof (uint64_t)) ||
11308 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11309 				return (EINVAL);
11310 			break;
11311 
11312 		case DTRACEACT_USYM:
11313 		case DTRACEACT_UMOD:
11314 		case DTRACEACT_UADDR:
11315 			if (dp == NULL ||
11316 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11317 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11318 				return (EINVAL);
11319 
11320 			/*
11321 			 * We have a slot for the pid, plus a slot for the
11322 			 * argument.  To keep things simple (aligned with
11323 			 * bitness-neutral sizing), we store each as a 64-bit
11324 			 * quantity.
11325 			 */
11326 			size = 2 * sizeof (uint64_t);
11327 			break;
11328 
11329 		case DTRACEACT_STOP:
11330 		case DTRACEACT_BREAKPOINT:
11331 		case DTRACEACT_PANIC:
11332 			break;
11333 
11334 		case DTRACEACT_CHILL:
11335 		case DTRACEACT_DISCARD:
11336 		case DTRACEACT_RAISE:
11337 			if (dp == NULL)
11338 				return (EINVAL);
11339 			break;
11340 
11341 		case DTRACEACT_EXIT:
11342 			if (dp == NULL ||
11343 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11344 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11345 				return (EINVAL);
11346 			break;
11347 
11348 		case DTRACEACT_SPECULATE:
11349 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11350 				return (EINVAL);
11351 
11352 			if (dp == NULL)
11353 				return (EINVAL);
11354 
11355 			state->dts_speculates = 1;
11356 			break;
11357 
11358 		case DTRACEACT_PRINTM:
11359 		    	size = dp->dtdo_rtype.dtdt_size;
11360 			break;
11361 
11362 		case DTRACEACT_PRINTT:
11363 		    	size = dp->dtdo_rtype.dtdt_size;
11364 			break;
11365 
11366 		case DTRACEACT_COMMIT: {
11367 			dtrace_action_t *act = ecb->dte_action;
11368 
11369 			for (; act != NULL; act = act->dta_next) {
11370 				if (act->dta_kind == DTRACEACT_COMMIT)
11371 					return (EINVAL);
11372 			}
11373 
11374 			if (dp == NULL)
11375 				return (EINVAL);
11376 			break;
11377 		}
11378 
11379 		default:
11380 			return (EINVAL);
11381 		}
11382 
11383 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11384 			/*
11385 			 * If this is a data-storing action or a speculate,
11386 			 * we must be sure that there isn't a commit on the
11387 			 * action chain.
11388 			 */
11389 			dtrace_action_t *act = ecb->dte_action;
11390 
11391 			for (; act != NULL; act = act->dta_next) {
11392 				if (act->dta_kind == DTRACEACT_COMMIT)
11393 					return (EINVAL);
11394 			}
11395 		}
11396 
11397 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11398 		action->dta_rec.dtrd_size = size;
11399 	}
11400 
11401 	action->dta_refcnt = 1;
11402 	rec = &action->dta_rec;
11403 	size = rec->dtrd_size;
11404 
11405 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11406 		if (!(size & mask)) {
11407 			align = mask + 1;
11408 			break;
11409 		}
11410 	}
11411 
11412 	action->dta_kind = desc->dtad_kind;
11413 
11414 	if ((action->dta_difo = dp) != NULL)
11415 		dtrace_difo_hold(dp);
11416 
11417 	rec->dtrd_action = action->dta_kind;
11418 	rec->dtrd_arg = arg;
11419 	rec->dtrd_uarg = desc->dtad_uarg;
11420 	rec->dtrd_alignment = (uint16_t)align;
11421 	rec->dtrd_format = format;
11422 
11423 	if ((last = ecb->dte_action_last) != NULL) {
11424 		ASSERT(ecb->dte_action != NULL);
11425 		action->dta_prev = last;
11426 		last->dta_next = action;
11427 	} else {
11428 		ASSERT(ecb->dte_action == NULL);
11429 		ecb->dte_action = action;
11430 	}
11431 
11432 	ecb->dte_action_last = action;
11433 
11434 	return (0);
11435 }
11436 
11437 static void
11438 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11439 {
11440 	dtrace_action_t *act = ecb->dte_action, *next;
11441 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11442 	dtrace_difo_t *dp;
11443 	uint16_t format;
11444 
11445 	if (act != NULL && act->dta_refcnt > 1) {
11446 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11447 		act->dta_refcnt--;
11448 	} else {
11449 		for (; act != NULL; act = next) {
11450 			next = act->dta_next;
11451 			ASSERT(next != NULL || act == ecb->dte_action_last);
11452 			ASSERT(act->dta_refcnt == 1);
11453 
11454 			if ((format = act->dta_rec.dtrd_format) != 0)
11455 				dtrace_format_remove(ecb->dte_state, format);
11456 
11457 			if ((dp = act->dta_difo) != NULL)
11458 				dtrace_difo_release(dp, vstate);
11459 
11460 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11461 				dtrace_ecb_aggregation_destroy(ecb, act);
11462 			} else {
11463 				kmem_free(act, sizeof (dtrace_action_t));
11464 			}
11465 		}
11466 	}
11467 
11468 	ecb->dte_action = NULL;
11469 	ecb->dte_action_last = NULL;
11470 	ecb->dte_size = 0;
11471 }
11472 
11473 static void
11474 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11475 {
11476 	/*
11477 	 * We disable the ECB by removing it from its probe.
11478 	 */
11479 	dtrace_ecb_t *pecb, *prev = NULL;
11480 	dtrace_probe_t *probe = ecb->dte_probe;
11481 
11482 	ASSERT(MUTEX_HELD(&dtrace_lock));
11483 
11484 	if (probe == NULL) {
11485 		/*
11486 		 * This is the NULL probe; there is nothing to disable.
11487 		 */
11488 		return;
11489 	}
11490 
11491 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11492 		if (pecb == ecb)
11493 			break;
11494 		prev = pecb;
11495 	}
11496 
11497 	ASSERT(pecb != NULL);
11498 
11499 	if (prev == NULL) {
11500 		probe->dtpr_ecb = ecb->dte_next;
11501 	} else {
11502 		prev->dte_next = ecb->dte_next;
11503 	}
11504 
11505 	if (ecb == probe->dtpr_ecb_last) {
11506 		ASSERT(ecb->dte_next == NULL);
11507 		probe->dtpr_ecb_last = prev;
11508 	}
11509 
11510 	/*
11511 	 * The ECB has been disconnected from the probe; now sync to assure
11512 	 * that all CPUs have seen the change before returning.
11513 	 */
11514 	dtrace_sync();
11515 
11516 	if (probe->dtpr_ecb == NULL) {
11517 		/*
11518 		 * That was the last ECB on the probe; clear the predicate
11519 		 * cache ID for the probe, disable it and sync one more time
11520 		 * to assure that we'll never hit it again.
11521 		 */
11522 		dtrace_provider_t *prov = probe->dtpr_provider;
11523 
11524 		ASSERT(ecb->dte_next == NULL);
11525 		ASSERT(probe->dtpr_ecb_last == NULL);
11526 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11527 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11528 		    probe->dtpr_id, probe->dtpr_arg);
11529 		dtrace_sync();
11530 	} else {
11531 		/*
11532 		 * There is at least one ECB remaining on the probe.  If there
11533 		 * is _exactly_ one, set the probe's predicate cache ID to be
11534 		 * the predicate cache ID of the remaining ECB.
11535 		 */
11536 		ASSERT(probe->dtpr_ecb_last != NULL);
11537 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11538 
11539 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11540 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11541 
11542 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11543 
11544 			if (p != NULL)
11545 				probe->dtpr_predcache = p->dtp_cacheid;
11546 		}
11547 
11548 		ecb->dte_next = NULL;
11549 	}
11550 }
11551 
11552 static void
11553 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11554 {
11555 	dtrace_state_t *state = ecb->dte_state;
11556 	dtrace_vstate_t *vstate = &state->dts_vstate;
11557 	dtrace_predicate_t *pred;
11558 	dtrace_epid_t epid = ecb->dte_epid;
11559 
11560 	ASSERT(MUTEX_HELD(&dtrace_lock));
11561 	ASSERT(ecb->dte_next == NULL);
11562 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11563 
11564 	if ((pred = ecb->dte_predicate) != NULL)
11565 		dtrace_predicate_release(pred, vstate);
11566 
11567 	dtrace_ecb_action_remove(ecb);
11568 
11569 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11570 	state->dts_ecbs[epid - 1] = NULL;
11571 
11572 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11573 }
11574 
11575 static dtrace_ecb_t *
11576 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11577     dtrace_enabling_t *enab)
11578 {
11579 	dtrace_ecb_t *ecb;
11580 	dtrace_predicate_t *pred;
11581 	dtrace_actdesc_t *act;
11582 	dtrace_provider_t *prov;
11583 	dtrace_ecbdesc_t *desc = enab->dten_current;
11584 
11585 	ASSERT(MUTEX_HELD(&dtrace_lock));
11586 	ASSERT(state != NULL);
11587 
11588 	ecb = dtrace_ecb_add(state, probe);
11589 	ecb->dte_uarg = desc->dted_uarg;
11590 
11591 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11592 		dtrace_predicate_hold(pred);
11593 		ecb->dte_predicate = pred;
11594 	}
11595 
11596 	if (probe != NULL) {
11597 		/*
11598 		 * If the provider shows more leg than the consumer is old
11599 		 * enough to see, we need to enable the appropriate implicit
11600 		 * predicate bits to prevent the ecb from activating at
11601 		 * revealing times.
11602 		 *
11603 		 * Providers specifying DTRACE_PRIV_USER at register time
11604 		 * are stating that they need the /proc-style privilege
11605 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11606 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11607 		 */
11608 		prov = probe->dtpr_provider;
11609 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11610 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11611 			ecb->dte_cond |= DTRACE_COND_OWNER;
11612 
11613 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11614 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11615 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11616 
11617 		/*
11618 		 * If the provider shows us kernel innards and the user
11619 		 * is lacking sufficient privilege, enable the
11620 		 * DTRACE_COND_USERMODE implicit predicate.
11621 		 */
11622 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11623 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11624 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11625 	}
11626 
11627 	if (dtrace_ecb_create_cache != NULL) {
11628 		/*
11629 		 * If we have a cached ecb, we'll use its action list instead
11630 		 * of creating our own (saving both time and space).
11631 		 */
11632 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11633 		dtrace_action_t *act = cached->dte_action;
11634 
11635 		if (act != NULL) {
11636 			ASSERT(act->dta_refcnt > 0);
11637 			act->dta_refcnt++;
11638 			ecb->dte_action = act;
11639 			ecb->dte_action_last = cached->dte_action_last;
11640 			ecb->dte_needed = cached->dte_needed;
11641 			ecb->dte_size = cached->dte_size;
11642 			ecb->dte_alignment = cached->dte_alignment;
11643 		}
11644 
11645 		return (ecb);
11646 	}
11647 
11648 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11649 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11650 			dtrace_ecb_destroy(ecb);
11651 			return (NULL);
11652 		}
11653 	}
11654 
11655 	dtrace_ecb_resize(ecb);
11656 
11657 	return (dtrace_ecb_create_cache = ecb);
11658 }
11659 
11660 static int
11661 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11662 {
11663 	dtrace_ecb_t *ecb;
11664 	dtrace_enabling_t *enab = arg;
11665 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11666 
11667 	ASSERT(state != NULL);
11668 
11669 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11670 		/*
11671 		 * This probe was created in a generation for which this
11672 		 * enabling has previously created ECBs; we don't want to
11673 		 * enable it again, so just kick out.
11674 		 */
11675 		return (DTRACE_MATCH_NEXT);
11676 	}
11677 
11678 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11679 		return (DTRACE_MATCH_DONE);
11680 
11681 	dtrace_ecb_enable(ecb);
11682 	return (DTRACE_MATCH_NEXT);
11683 }
11684 
11685 static dtrace_ecb_t *
11686 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11687 {
11688 	dtrace_ecb_t *ecb;
11689 
11690 	ASSERT(MUTEX_HELD(&dtrace_lock));
11691 
11692 	if (id == 0 || id > state->dts_necbs)
11693 		return (NULL);
11694 
11695 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11696 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11697 
11698 	return (state->dts_ecbs[id - 1]);
11699 }
11700 
11701 static dtrace_aggregation_t *
11702 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11703 {
11704 	dtrace_aggregation_t *agg;
11705 
11706 	ASSERT(MUTEX_HELD(&dtrace_lock));
11707 
11708 	if (id == 0 || id > state->dts_naggregations)
11709 		return (NULL);
11710 
11711 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11712 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11713 	    agg->dtag_id == id);
11714 
11715 	return (state->dts_aggregations[id - 1]);
11716 }
11717 
11718 /*
11719  * DTrace Buffer Functions
11720  *
11721  * The following functions manipulate DTrace buffers.  Most of these functions
11722  * are called in the context of establishing or processing consumer state;
11723  * exceptions are explicitly noted.
11724  */
11725 
11726 /*
11727  * Note:  called from cross call context.  This function switches the two
11728  * buffers on a given CPU.  The atomicity of this operation is assured by
11729  * disabling interrupts while the actual switch takes place; the disabling of
11730  * interrupts serializes the execution with any execution of dtrace_probe() on
11731  * the same CPU.
11732  */
11733 static void
11734 dtrace_buffer_switch(dtrace_buffer_t *buf)
11735 {
11736 	caddr_t tomax = buf->dtb_tomax;
11737 	caddr_t xamot = buf->dtb_xamot;
11738 	dtrace_icookie_t cookie;
11739 	hrtime_t now;
11740 
11741 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11742 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11743 
11744 	cookie = dtrace_interrupt_disable();
11745 	now = dtrace_gethrtime();
11746 	buf->dtb_tomax = xamot;
11747 	buf->dtb_xamot = tomax;
11748 	buf->dtb_xamot_drops = buf->dtb_drops;
11749 	buf->dtb_xamot_offset = buf->dtb_offset;
11750 	buf->dtb_xamot_errors = buf->dtb_errors;
11751 	buf->dtb_xamot_flags = buf->dtb_flags;
11752 	buf->dtb_offset = 0;
11753 	buf->dtb_drops = 0;
11754 	buf->dtb_errors = 0;
11755 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11756 	buf->dtb_interval = now - buf->dtb_switched;
11757 	buf->dtb_switched = now;
11758 	dtrace_interrupt_enable(cookie);
11759 }
11760 
11761 /*
11762  * Note:  called from cross call context.  This function activates a buffer
11763  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11764  * is guaranteed by the disabling of interrupts.
11765  */
11766 static void
11767 dtrace_buffer_activate(dtrace_state_t *state)
11768 {
11769 	dtrace_buffer_t *buf;
11770 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11771 
11772 	buf = &state->dts_buffer[curcpu];
11773 
11774 	if (buf->dtb_tomax != NULL) {
11775 		/*
11776 		 * We might like to assert that the buffer is marked inactive,
11777 		 * but this isn't necessarily true:  the buffer for the CPU
11778 		 * that processes the BEGIN probe has its buffer activated
11779 		 * manually.  In this case, we take the (harmless) action
11780 		 * re-clearing the bit INACTIVE bit.
11781 		 */
11782 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11783 	}
11784 
11785 	dtrace_interrupt_enable(cookie);
11786 }
11787 
11788 static int
11789 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11790     processorid_t cpu, int *factor)
11791 {
11792 #if defined(sun)
11793 	cpu_t *cp;
11794 #endif
11795 	dtrace_buffer_t *buf;
11796 	int allocated = 0, desired = 0;
11797 
11798 #if defined(sun)
11799 	ASSERT(MUTEX_HELD(&cpu_lock));
11800 	ASSERT(MUTEX_HELD(&dtrace_lock));
11801 
11802 	*factor = 1;
11803 
11804 	if (size > dtrace_nonroot_maxsize &&
11805 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11806 		return (EFBIG);
11807 
11808 	cp = cpu_list;
11809 
11810 	do {
11811 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11812 			continue;
11813 
11814 		buf = &bufs[cp->cpu_id];
11815 
11816 		/*
11817 		 * If there is already a buffer allocated for this CPU, it
11818 		 * is only possible that this is a DR event.  In this case,
11819 		 */
11820 		if (buf->dtb_tomax != NULL) {
11821 			ASSERT(buf->dtb_size == size);
11822 			continue;
11823 		}
11824 
11825 		ASSERT(buf->dtb_xamot == NULL);
11826 
11827 		if ((buf->dtb_tomax = kmem_zalloc(size,
11828 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11829 			goto err;
11830 
11831 		buf->dtb_size = size;
11832 		buf->dtb_flags = flags;
11833 		buf->dtb_offset = 0;
11834 		buf->dtb_drops = 0;
11835 
11836 		if (flags & DTRACEBUF_NOSWITCH)
11837 			continue;
11838 
11839 		if ((buf->dtb_xamot = kmem_zalloc(size,
11840 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11841 			goto err;
11842 	} while ((cp = cp->cpu_next) != cpu_list);
11843 
11844 	return (0);
11845 
11846 err:
11847 	cp = cpu_list;
11848 
11849 	do {
11850 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11851 			continue;
11852 
11853 		buf = &bufs[cp->cpu_id];
11854 		desired += 2;
11855 
11856 		if (buf->dtb_xamot != NULL) {
11857 			ASSERT(buf->dtb_tomax != NULL);
11858 			ASSERT(buf->dtb_size == size);
11859 			kmem_free(buf->dtb_xamot, size);
11860 			allocated++;
11861 		}
11862 
11863 		if (buf->dtb_tomax != NULL) {
11864 			ASSERT(buf->dtb_size == size);
11865 			kmem_free(buf->dtb_tomax, size);
11866 			allocated++;
11867 		}
11868 
11869 		buf->dtb_tomax = NULL;
11870 		buf->dtb_xamot = NULL;
11871 		buf->dtb_size = 0;
11872 	} while ((cp = cp->cpu_next) != cpu_list);
11873 #else
11874 	int i;
11875 
11876 	*factor = 1;
11877 #if defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
11878 	/*
11879 	 * FreeBSD isn't good at limiting the amount of memory we
11880 	 * ask to malloc, so let's place a limit here before trying
11881 	 * to do something that might well end in tears at bedtime.
11882 	 */
11883 	if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
11884 		return (ENOMEM);
11885 #endif
11886 
11887 	ASSERT(MUTEX_HELD(&dtrace_lock));
11888 	CPU_FOREACH(i) {
11889 		if (cpu != DTRACE_CPUALL && cpu != i)
11890 			continue;
11891 
11892 		buf = &bufs[i];
11893 
11894 		/*
11895 		 * If there is already a buffer allocated for this CPU, it
11896 		 * is only possible that this is a DR event.  In this case,
11897 		 * the buffer size must match our specified size.
11898 		 */
11899 		if (buf->dtb_tomax != NULL) {
11900 			ASSERT(buf->dtb_size == size);
11901 			continue;
11902 		}
11903 
11904 		ASSERT(buf->dtb_xamot == NULL);
11905 
11906 		if ((buf->dtb_tomax = kmem_zalloc(size,
11907 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11908 			goto err;
11909 
11910 		buf->dtb_size = size;
11911 		buf->dtb_flags = flags;
11912 		buf->dtb_offset = 0;
11913 		buf->dtb_drops = 0;
11914 
11915 		if (flags & DTRACEBUF_NOSWITCH)
11916 			continue;
11917 
11918 		if ((buf->dtb_xamot = kmem_zalloc(size,
11919 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11920 			goto err;
11921 	}
11922 
11923 	return (0);
11924 
11925 err:
11926 	/*
11927 	 * Error allocating memory, so free the buffers that were
11928 	 * allocated before the failed allocation.
11929 	 */
11930 	CPU_FOREACH(i) {
11931 		if (cpu != DTRACE_CPUALL && cpu != i)
11932 			continue;
11933 
11934 		buf = &bufs[i];
11935 		desired += 2;
11936 
11937 		if (buf->dtb_xamot != NULL) {
11938 			ASSERT(buf->dtb_tomax != NULL);
11939 			ASSERT(buf->dtb_size == size);
11940 			kmem_free(buf->dtb_xamot, size);
11941 			allocated++;
11942 		}
11943 
11944 		if (buf->dtb_tomax != NULL) {
11945 			ASSERT(buf->dtb_size == size);
11946 			kmem_free(buf->dtb_tomax, size);
11947 			allocated++;
11948 		}
11949 
11950 		buf->dtb_tomax = NULL;
11951 		buf->dtb_xamot = NULL;
11952 		buf->dtb_size = 0;
11953 
11954 	}
11955 #endif
11956 	*factor = desired / (allocated > 0 ? allocated : 1);
11957 
11958 	return (ENOMEM);
11959 }
11960 
11961 /*
11962  * Note:  called from probe context.  This function just increments the drop
11963  * count on a buffer.  It has been made a function to allow for the
11964  * possibility of understanding the source of mysterious drop counts.  (A
11965  * problem for which one may be particularly disappointed that DTrace cannot
11966  * be used to understand DTrace.)
11967  */
11968 static void
11969 dtrace_buffer_drop(dtrace_buffer_t *buf)
11970 {
11971 	buf->dtb_drops++;
11972 }
11973 
11974 /*
11975  * Note:  called from probe context.  This function is called to reserve space
11976  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11977  * mstate.  Returns the new offset in the buffer, or a negative value if an
11978  * error has occurred.
11979  */
11980 static intptr_t
11981 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11982     dtrace_state_t *state, dtrace_mstate_t *mstate)
11983 {
11984 	intptr_t offs = buf->dtb_offset, soffs;
11985 	intptr_t woffs;
11986 	caddr_t tomax;
11987 	size_t total;
11988 
11989 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11990 		return (-1);
11991 
11992 	if ((tomax = buf->dtb_tomax) == NULL) {
11993 		dtrace_buffer_drop(buf);
11994 		return (-1);
11995 	}
11996 
11997 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11998 		while (offs & (align - 1)) {
11999 			/*
12000 			 * Assert that our alignment is off by a number which
12001 			 * is itself sizeof (uint32_t) aligned.
12002 			 */
12003 			ASSERT(!((align - (offs & (align - 1))) &
12004 			    (sizeof (uint32_t) - 1)));
12005 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12006 			offs += sizeof (uint32_t);
12007 		}
12008 
12009 		if ((soffs = offs + needed) > buf->dtb_size) {
12010 			dtrace_buffer_drop(buf);
12011 			return (-1);
12012 		}
12013 
12014 		if (mstate == NULL)
12015 			return (offs);
12016 
12017 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12018 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12019 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12020 
12021 		return (offs);
12022 	}
12023 
12024 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12025 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12026 		    (buf->dtb_flags & DTRACEBUF_FULL))
12027 			return (-1);
12028 		goto out;
12029 	}
12030 
12031 	total = needed + (offs & (align - 1));
12032 
12033 	/*
12034 	 * For a ring buffer, life is quite a bit more complicated.  Before
12035 	 * we can store any padding, we need to adjust our wrapping offset.
12036 	 * (If we've never before wrapped or we're not about to, no adjustment
12037 	 * is required.)
12038 	 */
12039 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12040 	    offs + total > buf->dtb_size) {
12041 		woffs = buf->dtb_xamot_offset;
12042 
12043 		if (offs + total > buf->dtb_size) {
12044 			/*
12045 			 * We can't fit in the end of the buffer.  First, a
12046 			 * sanity check that we can fit in the buffer at all.
12047 			 */
12048 			if (total > buf->dtb_size) {
12049 				dtrace_buffer_drop(buf);
12050 				return (-1);
12051 			}
12052 
12053 			/*
12054 			 * We're going to be storing at the top of the buffer,
12055 			 * so now we need to deal with the wrapped offset.  We
12056 			 * only reset our wrapped offset to 0 if it is
12057 			 * currently greater than the current offset.  If it
12058 			 * is less than the current offset, it is because a
12059 			 * previous allocation induced a wrap -- but the
12060 			 * allocation didn't subsequently take the space due
12061 			 * to an error or false predicate evaluation.  In this
12062 			 * case, we'll just leave the wrapped offset alone: if
12063 			 * the wrapped offset hasn't been advanced far enough
12064 			 * for this allocation, it will be adjusted in the
12065 			 * lower loop.
12066 			 */
12067 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12068 				if (woffs >= offs)
12069 					woffs = 0;
12070 			} else {
12071 				woffs = 0;
12072 			}
12073 
12074 			/*
12075 			 * Now we know that we're going to be storing to the
12076 			 * top of the buffer and that there is room for us
12077 			 * there.  We need to clear the buffer from the current
12078 			 * offset to the end (there may be old gunk there).
12079 			 */
12080 			while (offs < buf->dtb_size)
12081 				tomax[offs++] = 0;
12082 
12083 			/*
12084 			 * We need to set our offset to zero.  And because we
12085 			 * are wrapping, we need to set the bit indicating as
12086 			 * much.  We can also adjust our needed space back
12087 			 * down to the space required by the ECB -- we know
12088 			 * that the top of the buffer is aligned.
12089 			 */
12090 			offs = 0;
12091 			total = needed;
12092 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12093 		} else {
12094 			/*
12095 			 * There is room for us in the buffer, so we simply
12096 			 * need to check the wrapped offset.
12097 			 */
12098 			if (woffs < offs) {
12099 				/*
12100 				 * The wrapped offset is less than the offset.
12101 				 * This can happen if we allocated buffer space
12102 				 * that induced a wrap, but then we didn't
12103 				 * subsequently take the space due to an error
12104 				 * or false predicate evaluation.  This is
12105 				 * okay; we know that _this_ allocation isn't
12106 				 * going to induce a wrap.  We still can't
12107 				 * reset the wrapped offset to be zero,
12108 				 * however: the space may have been trashed in
12109 				 * the previous failed probe attempt.  But at
12110 				 * least the wrapped offset doesn't need to
12111 				 * be adjusted at all...
12112 				 */
12113 				goto out;
12114 			}
12115 		}
12116 
12117 		while (offs + total > woffs) {
12118 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12119 			size_t size;
12120 
12121 			if (epid == DTRACE_EPIDNONE) {
12122 				size = sizeof (uint32_t);
12123 			} else {
12124 				ASSERT3U(epid, <=, state->dts_necbs);
12125 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12126 
12127 				size = state->dts_ecbs[epid - 1]->dte_size;
12128 			}
12129 
12130 			ASSERT(woffs + size <= buf->dtb_size);
12131 			ASSERT(size != 0);
12132 
12133 			if (woffs + size == buf->dtb_size) {
12134 				/*
12135 				 * We've reached the end of the buffer; we want
12136 				 * to set the wrapped offset to 0 and break
12137 				 * out.  However, if the offs is 0, then we're
12138 				 * in a strange edge-condition:  the amount of
12139 				 * space that we want to reserve plus the size
12140 				 * of the record that we're overwriting is
12141 				 * greater than the size of the buffer.  This
12142 				 * is problematic because if we reserve the
12143 				 * space but subsequently don't consume it (due
12144 				 * to a failed predicate or error) the wrapped
12145 				 * offset will be 0 -- yet the EPID at offset 0
12146 				 * will not be committed.  This situation is
12147 				 * relatively easy to deal with:  if we're in
12148 				 * this case, the buffer is indistinguishable
12149 				 * from one that hasn't wrapped; we need only
12150 				 * finish the job by clearing the wrapped bit,
12151 				 * explicitly setting the offset to be 0, and
12152 				 * zero'ing out the old data in the buffer.
12153 				 */
12154 				if (offs == 0) {
12155 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12156 					buf->dtb_offset = 0;
12157 					woffs = total;
12158 
12159 					while (woffs < buf->dtb_size)
12160 						tomax[woffs++] = 0;
12161 				}
12162 
12163 				woffs = 0;
12164 				break;
12165 			}
12166 
12167 			woffs += size;
12168 		}
12169 
12170 		/*
12171 		 * We have a wrapped offset.  It may be that the wrapped offset
12172 		 * has become zero -- that's okay.
12173 		 */
12174 		buf->dtb_xamot_offset = woffs;
12175 	}
12176 
12177 out:
12178 	/*
12179 	 * Now we can plow the buffer with any necessary padding.
12180 	 */
12181 	while (offs & (align - 1)) {
12182 		/*
12183 		 * Assert that our alignment is off by a number which
12184 		 * is itself sizeof (uint32_t) aligned.
12185 		 */
12186 		ASSERT(!((align - (offs & (align - 1))) &
12187 		    (sizeof (uint32_t) - 1)));
12188 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12189 		offs += sizeof (uint32_t);
12190 	}
12191 
12192 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12193 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12194 			buf->dtb_flags |= DTRACEBUF_FULL;
12195 			return (-1);
12196 		}
12197 	}
12198 
12199 	if (mstate == NULL)
12200 		return (offs);
12201 
12202 	/*
12203 	 * For ring buffers and fill buffers, the scratch space is always
12204 	 * the inactive buffer.
12205 	 */
12206 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12207 	mstate->dtms_scratch_size = buf->dtb_size;
12208 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12209 
12210 	return (offs);
12211 }
12212 
12213 static void
12214 dtrace_buffer_polish(dtrace_buffer_t *buf)
12215 {
12216 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12217 	ASSERT(MUTEX_HELD(&dtrace_lock));
12218 
12219 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12220 		return;
12221 
12222 	/*
12223 	 * We need to polish the ring buffer.  There are three cases:
12224 	 *
12225 	 * - The first (and presumably most common) is that there is no gap
12226 	 *   between the buffer offset and the wrapped offset.  In this case,
12227 	 *   there is nothing in the buffer that isn't valid data; we can
12228 	 *   mark the buffer as polished and return.
12229 	 *
12230 	 * - The second (less common than the first but still more common
12231 	 *   than the third) is that there is a gap between the buffer offset
12232 	 *   and the wrapped offset, and the wrapped offset is larger than the
12233 	 *   buffer offset.  This can happen because of an alignment issue, or
12234 	 *   can happen because of a call to dtrace_buffer_reserve() that
12235 	 *   didn't subsequently consume the buffer space.  In this case,
12236 	 *   we need to zero the data from the buffer offset to the wrapped
12237 	 *   offset.
12238 	 *
12239 	 * - The third (and least common) is that there is a gap between the
12240 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12241 	 *   _less_ than the buffer offset.  This can only happen because a
12242 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12243 	 *   was not subsequently consumed.  In this case, we need to zero the
12244 	 *   space from the offset to the end of the buffer _and_ from the
12245 	 *   top of the buffer to the wrapped offset.
12246 	 */
12247 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12248 		bzero(buf->dtb_tomax + buf->dtb_offset,
12249 		    buf->dtb_xamot_offset - buf->dtb_offset);
12250 	}
12251 
12252 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12253 		bzero(buf->dtb_tomax + buf->dtb_offset,
12254 		    buf->dtb_size - buf->dtb_offset);
12255 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12256 	}
12257 }
12258 
12259 /*
12260  * This routine determines if data generated at the specified time has likely
12261  * been entirely consumed at user-level.  This routine is called to determine
12262  * if an ECB on a defunct probe (but for an active enabling) can be safely
12263  * disabled and destroyed.
12264  */
12265 static int
12266 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12267 {
12268 	int i;
12269 
12270 	for (i = 0; i < NCPU; i++) {
12271 		dtrace_buffer_t *buf = &bufs[i];
12272 
12273 		if (buf->dtb_size == 0)
12274 			continue;
12275 
12276 		if (buf->dtb_flags & DTRACEBUF_RING)
12277 			return (0);
12278 
12279 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12280 			return (0);
12281 
12282 		if (buf->dtb_switched - buf->dtb_interval < when)
12283 			return (0);
12284 	}
12285 
12286 	return (1);
12287 }
12288 
12289 static void
12290 dtrace_buffer_free(dtrace_buffer_t *bufs)
12291 {
12292 	int i;
12293 
12294 	for (i = 0; i < NCPU; i++) {
12295 		dtrace_buffer_t *buf = &bufs[i];
12296 
12297 		if (buf->dtb_tomax == NULL) {
12298 			ASSERT(buf->dtb_xamot == NULL);
12299 			ASSERT(buf->dtb_size == 0);
12300 			continue;
12301 		}
12302 
12303 		if (buf->dtb_xamot != NULL) {
12304 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12305 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12306 		}
12307 
12308 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12309 		buf->dtb_size = 0;
12310 		buf->dtb_tomax = NULL;
12311 		buf->dtb_xamot = NULL;
12312 	}
12313 }
12314 
12315 /*
12316  * DTrace Enabling Functions
12317  */
12318 static dtrace_enabling_t *
12319 dtrace_enabling_create(dtrace_vstate_t *vstate)
12320 {
12321 	dtrace_enabling_t *enab;
12322 
12323 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12324 	enab->dten_vstate = vstate;
12325 
12326 	return (enab);
12327 }
12328 
12329 static void
12330 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12331 {
12332 	dtrace_ecbdesc_t **ndesc;
12333 	size_t osize, nsize;
12334 
12335 	/*
12336 	 * We can't add to enablings after we've enabled them, or after we've
12337 	 * retained them.
12338 	 */
12339 	ASSERT(enab->dten_probegen == 0);
12340 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12341 
12342 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12343 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12344 		return;
12345 	}
12346 
12347 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12348 
12349 	if (enab->dten_maxdesc == 0) {
12350 		enab->dten_maxdesc = 1;
12351 	} else {
12352 		enab->dten_maxdesc <<= 1;
12353 	}
12354 
12355 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12356 
12357 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12358 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12359 	bcopy(enab->dten_desc, ndesc, osize);
12360 	if (enab->dten_desc != NULL)
12361 		kmem_free(enab->dten_desc, osize);
12362 
12363 	enab->dten_desc = ndesc;
12364 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12365 }
12366 
12367 static void
12368 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12369     dtrace_probedesc_t *pd)
12370 {
12371 	dtrace_ecbdesc_t *new;
12372 	dtrace_predicate_t *pred;
12373 	dtrace_actdesc_t *act;
12374 
12375 	/*
12376 	 * We're going to create a new ECB description that matches the
12377 	 * specified ECB in every way, but has the specified probe description.
12378 	 */
12379 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12380 
12381 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12382 		dtrace_predicate_hold(pred);
12383 
12384 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12385 		dtrace_actdesc_hold(act);
12386 
12387 	new->dted_action = ecb->dted_action;
12388 	new->dted_pred = ecb->dted_pred;
12389 	new->dted_probe = *pd;
12390 	new->dted_uarg = ecb->dted_uarg;
12391 
12392 	dtrace_enabling_add(enab, new);
12393 }
12394 
12395 static void
12396 dtrace_enabling_dump(dtrace_enabling_t *enab)
12397 {
12398 	int i;
12399 
12400 	for (i = 0; i < enab->dten_ndesc; i++) {
12401 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12402 
12403 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12404 		    desc->dtpd_provider, desc->dtpd_mod,
12405 		    desc->dtpd_func, desc->dtpd_name);
12406 	}
12407 }
12408 
12409 static void
12410 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12411 {
12412 	int i;
12413 	dtrace_ecbdesc_t *ep;
12414 	dtrace_vstate_t *vstate = enab->dten_vstate;
12415 
12416 	ASSERT(MUTEX_HELD(&dtrace_lock));
12417 
12418 	for (i = 0; i < enab->dten_ndesc; i++) {
12419 		dtrace_actdesc_t *act, *next;
12420 		dtrace_predicate_t *pred;
12421 
12422 		ep = enab->dten_desc[i];
12423 
12424 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12425 			dtrace_predicate_release(pred, vstate);
12426 
12427 		for (act = ep->dted_action; act != NULL; act = next) {
12428 			next = act->dtad_next;
12429 			dtrace_actdesc_release(act, vstate);
12430 		}
12431 
12432 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12433 	}
12434 
12435 	if (enab->dten_desc != NULL)
12436 		kmem_free(enab->dten_desc,
12437 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12438 
12439 	/*
12440 	 * If this was a retained enabling, decrement the dts_nretained count
12441 	 * and take it off of the dtrace_retained list.
12442 	 */
12443 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12444 	    dtrace_retained == enab) {
12445 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12446 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12447 		enab->dten_vstate->dtvs_state->dts_nretained--;
12448 		dtrace_retained_gen++;
12449 	}
12450 
12451 	if (enab->dten_prev == NULL) {
12452 		if (dtrace_retained == enab) {
12453 			dtrace_retained = enab->dten_next;
12454 
12455 			if (dtrace_retained != NULL)
12456 				dtrace_retained->dten_prev = NULL;
12457 		}
12458 	} else {
12459 		ASSERT(enab != dtrace_retained);
12460 		ASSERT(dtrace_retained != NULL);
12461 		enab->dten_prev->dten_next = enab->dten_next;
12462 	}
12463 
12464 	if (enab->dten_next != NULL) {
12465 		ASSERT(dtrace_retained != NULL);
12466 		enab->dten_next->dten_prev = enab->dten_prev;
12467 	}
12468 
12469 	kmem_free(enab, sizeof (dtrace_enabling_t));
12470 }
12471 
12472 static int
12473 dtrace_enabling_retain(dtrace_enabling_t *enab)
12474 {
12475 	dtrace_state_t *state;
12476 
12477 	ASSERT(MUTEX_HELD(&dtrace_lock));
12478 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12479 	ASSERT(enab->dten_vstate != NULL);
12480 
12481 	state = enab->dten_vstate->dtvs_state;
12482 	ASSERT(state != NULL);
12483 
12484 	/*
12485 	 * We only allow each state to retain dtrace_retain_max enablings.
12486 	 */
12487 	if (state->dts_nretained >= dtrace_retain_max)
12488 		return (ENOSPC);
12489 
12490 	state->dts_nretained++;
12491 	dtrace_retained_gen++;
12492 
12493 	if (dtrace_retained == NULL) {
12494 		dtrace_retained = enab;
12495 		return (0);
12496 	}
12497 
12498 	enab->dten_next = dtrace_retained;
12499 	dtrace_retained->dten_prev = enab;
12500 	dtrace_retained = enab;
12501 
12502 	return (0);
12503 }
12504 
12505 static int
12506 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12507     dtrace_probedesc_t *create)
12508 {
12509 	dtrace_enabling_t *new, *enab;
12510 	int found = 0, err = ENOENT;
12511 
12512 	ASSERT(MUTEX_HELD(&dtrace_lock));
12513 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12514 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12515 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12516 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12517 
12518 	new = dtrace_enabling_create(&state->dts_vstate);
12519 
12520 	/*
12521 	 * Iterate over all retained enablings, looking for enablings that
12522 	 * match the specified state.
12523 	 */
12524 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12525 		int i;
12526 
12527 		/*
12528 		 * dtvs_state can only be NULL for helper enablings -- and
12529 		 * helper enablings can't be retained.
12530 		 */
12531 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12532 
12533 		if (enab->dten_vstate->dtvs_state != state)
12534 			continue;
12535 
12536 		/*
12537 		 * Now iterate over each probe description; we're looking for
12538 		 * an exact match to the specified probe description.
12539 		 */
12540 		for (i = 0; i < enab->dten_ndesc; i++) {
12541 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12542 			dtrace_probedesc_t *pd = &ep->dted_probe;
12543 
12544 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12545 				continue;
12546 
12547 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12548 				continue;
12549 
12550 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12551 				continue;
12552 
12553 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12554 				continue;
12555 
12556 			/*
12557 			 * We have a winning probe!  Add it to our growing
12558 			 * enabling.
12559 			 */
12560 			found = 1;
12561 			dtrace_enabling_addlike(new, ep, create);
12562 		}
12563 	}
12564 
12565 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12566 		dtrace_enabling_destroy(new);
12567 		return (err);
12568 	}
12569 
12570 	return (0);
12571 }
12572 
12573 static void
12574 dtrace_enabling_retract(dtrace_state_t *state)
12575 {
12576 	dtrace_enabling_t *enab, *next;
12577 
12578 	ASSERT(MUTEX_HELD(&dtrace_lock));
12579 
12580 	/*
12581 	 * Iterate over all retained enablings, destroy the enablings retained
12582 	 * for the specified state.
12583 	 */
12584 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12585 		next = enab->dten_next;
12586 
12587 		/*
12588 		 * dtvs_state can only be NULL for helper enablings -- and
12589 		 * helper enablings can't be retained.
12590 		 */
12591 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12592 
12593 		if (enab->dten_vstate->dtvs_state == state) {
12594 			ASSERT(state->dts_nretained > 0);
12595 			dtrace_enabling_destroy(enab);
12596 		}
12597 	}
12598 
12599 	ASSERT(state->dts_nretained == 0);
12600 }
12601 
12602 static int
12603 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12604 {
12605 	int i = 0;
12606 	int matched = 0;
12607 
12608 	ASSERT(MUTEX_HELD(&cpu_lock));
12609 	ASSERT(MUTEX_HELD(&dtrace_lock));
12610 
12611 	for (i = 0; i < enab->dten_ndesc; i++) {
12612 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12613 
12614 		enab->dten_current = ep;
12615 		enab->dten_error = 0;
12616 
12617 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
12618 
12619 		if (enab->dten_error != 0) {
12620 			/*
12621 			 * If we get an error half-way through enabling the
12622 			 * probes, we kick out -- perhaps with some number of
12623 			 * them enabled.  Leaving enabled probes enabled may
12624 			 * be slightly confusing for user-level, but we expect
12625 			 * that no one will attempt to actually drive on in
12626 			 * the face of such errors.  If this is an anonymous
12627 			 * enabling (indicated with a NULL nmatched pointer),
12628 			 * we cmn_err() a message.  We aren't expecting to
12629 			 * get such an error -- such as it can exist at all,
12630 			 * it would be a result of corrupted DOF in the driver
12631 			 * properties.
12632 			 */
12633 			if (nmatched == NULL) {
12634 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12635 				    "error on %p: %d", (void *)ep,
12636 				    enab->dten_error);
12637 			}
12638 
12639 			return (enab->dten_error);
12640 		}
12641 	}
12642 
12643 	enab->dten_probegen = dtrace_probegen;
12644 	if (nmatched != NULL)
12645 		*nmatched = matched;
12646 
12647 	return (0);
12648 }
12649 
12650 static void
12651 dtrace_enabling_matchall(void)
12652 {
12653 	dtrace_enabling_t *enab;
12654 
12655 	mutex_enter(&cpu_lock);
12656 	mutex_enter(&dtrace_lock);
12657 
12658 	/*
12659 	 * Iterate over all retained enablings to see if any probes match
12660 	 * against them.  We only perform this operation on enablings for which
12661 	 * we have sufficient permissions by virtue of being in the global zone
12662 	 * or in the same zone as the DTrace client.  Because we can be called
12663 	 * after dtrace_detach() has been called, we cannot assert that there
12664 	 * are retained enablings.  We can safely load from dtrace_retained,
12665 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12666 	 * block pending our completion.
12667 	 */
12668 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12669 #if defined(sun)
12670 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12671 
12672 		if (INGLOBALZONE(curproc) ||
12673 		    cr != NULL && getzoneid() == crgetzoneid(cr))
12674 #endif
12675 			(void) dtrace_enabling_match(enab, NULL);
12676 	}
12677 
12678 	mutex_exit(&dtrace_lock);
12679 	mutex_exit(&cpu_lock);
12680 }
12681 
12682 /*
12683  * If an enabling is to be enabled without having matched probes (that is, if
12684  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12685  * enabling must be _primed_ by creating an ECB for every ECB description.
12686  * This must be done to assure that we know the number of speculations, the
12687  * number of aggregations, the minimum buffer size needed, etc. before we
12688  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12689  * enabling any probes, we create ECBs for every ECB decription, but with a
12690  * NULL probe -- which is exactly what this function does.
12691  */
12692 static void
12693 dtrace_enabling_prime(dtrace_state_t *state)
12694 {
12695 	dtrace_enabling_t *enab;
12696 	int i;
12697 
12698 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12699 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12700 
12701 		if (enab->dten_vstate->dtvs_state != state)
12702 			continue;
12703 
12704 		/*
12705 		 * We don't want to prime an enabling more than once, lest
12706 		 * we allow a malicious user to induce resource exhaustion.
12707 		 * (The ECBs that result from priming an enabling aren't
12708 		 * leaked -- but they also aren't deallocated until the
12709 		 * consumer state is destroyed.)
12710 		 */
12711 		if (enab->dten_primed)
12712 			continue;
12713 
12714 		for (i = 0; i < enab->dten_ndesc; i++) {
12715 			enab->dten_current = enab->dten_desc[i];
12716 			(void) dtrace_probe_enable(NULL, enab);
12717 		}
12718 
12719 		enab->dten_primed = 1;
12720 	}
12721 }
12722 
12723 /*
12724  * Called to indicate that probes should be provided due to retained
12725  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12726  * must take an initial lap through the enabling calling the dtps_provide()
12727  * entry point explicitly to allow for autocreated probes.
12728  */
12729 static void
12730 dtrace_enabling_provide(dtrace_provider_t *prv)
12731 {
12732 	int i, all = 0;
12733 	dtrace_probedesc_t desc;
12734 	dtrace_genid_t gen;
12735 
12736 	ASSERT(MUTEX_HELD(&dtrace_lock));
12737 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12738 
12739 	if (prv == NULL) {
12740 		all = 1;
12741 		prv = dtrace_provider;
12742 	}
12743 
12744 	do {
12745 		dtrace_enabling_t *enab;
12746 		void *parg = prv->dtpv_arg;
12747 
12748 retry:
12749 		gen = dtrace_retained_gen;
12750 		for (enab = dtrace_retained; enab != NULL;
12751 		    enab = enab->dten_next) {
12752 			for (i = 0; i < enab->dten_ndesc; i++) {
12753 				desc = enab->dten_desc[i]->dted_probe;
12754 				mutex_exit(&dtrace_lock);
12755 				prv->dtpv_pops.dtps_provide(parg, &desc);
12756 				mutex_enter(&dtrace_lock);
12757 				/*
12758 				 * Process the retained enablings again if
12759 				 * they have changed while we weren't holding
12760 				 * dtrace_lock.
12761 				 */
12762 				if (gen != dtrace_retained_gen)
12763 					goto retry;
12764 			}
12765 		}
12766 	} while (all && (prv = prv->dtpv_next) != NULL);
12767 
12768 	mutex_exit(&dtrace_lock);
12769 	dtrace_probe_provide(NULL, all ? NULL : prv);
12770 	mutex_enter(&dtrace_lock);
12771 }
12772 
12773 /*
12774  * Called to reap ECBs that are attached to probes from defunct providers.
12775  */
12776 static void
12777 dtrace_enabling_reap(void)
12778 {
12779 	dtrace_provider_t *prov;
12780 	dtrace_probe_t *probe;
12781 	dtrace_ecb_t *ecb;
12782 	hrtime_t when;
12783 	int i;
12784 
12785 	mutex_enter(&cpu_lock);
12786 	mutex_enter(&dtrace_lock);
12787 
12788 	for (i = 0; i < dtrace_nprobes; i++) {
12789 		if ((probe = dtrace_probes[i]) == NULL)
12790 			continue;
12791 
12792 		if (probe->dtpr_ecb == NULL)
12793 			continue;
12794 
12795 		prov = probe->dtpr_provider;
12796 
12797 		if ((when = prov->dtpv_defunct) == 0)
12798 			continue;
12799 
12800 		/*
12801 		 * We have ECBs on a defunct provider:  we want to reap these
12802 		 * ECBs to allow the provider to unregister.  The destruction
12803 		 * of these ECBs must be done carefully:  if we destroy the ECB
12804 		 * and the consumer later wishes to consume an EPID that
12805 		 * corresponds to the destroyed ECB (and if the EPID metadata
12806 		 * has not been previously consumed), the consumer will abort
12807 		 * processing on the unknown EPID.  To reduce (but not, sadly,
12808 		 * eliminate) the possibility of this, we will only destroy an
12809 		 * ECB for a defunct provider if, for the state that
12810 		 * corresponds to the ECB:
12811 		 *
12812 		 *  (a)	There is no speculative tracing (which can effectively
12813 		 *	cache an EPID for an arbitrary amount of time).
12814 		 *
12815 		 *  (b)	The principal buffers have been switched twice since the
12816 		 *	provider became defunct.
12817 		 *
12818 		 *  (c)	The aggregation buffers are of zero size or have been
12819 		 *	switched twice since the provider became defunct.
12820 		 *
12821 		 * We use dts_speculates to determine (a) and call a function
12822 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12823 		 * that as soon as we've been unable to destroy one of the ECBs
12824 		 * associated with the probe, we quit trying -- reaping is only
12825 		 * fruitful in as much as we can destroy all ECBs associated
12826 		 * with the defunct provider's probes.
12827 		 */
12828 		while ((ecb = probe->dtpr_ecb) != NULL) {
12829 			dtrace_state_t *state = ecb->dte_state;
12830 			dtrace_buffer_t *buf = state->dts_buffer;
12831 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12832 
12833 			if (state->dts_speculates)
12834 				break;
12835 
12836 			if (!dtrace_buffer_consumed(buf, when))
12837 				break;
12838 
12839 			if (!dtrace_buffer_consumed(aggbuf, when))
12840 				break;
12841 
12842 			dtrace_ecb_disable(ecb);
12843 			ASSERT(probe->dtpr_ecb != ecb);
12844 			dtrace_ecb_destroy(ecb);
12845 		}
12846 	}
12847 
12848 	mutex_exit(&dtrace_lock);
12849 	mutex_exit(&cpu_lock);
12850 }
12851 
12852 /*
12853  * DTrace DOF Functions
12854  */
12855 /*ARGSUSED*/
12856 static void
12857 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12858 {
12859 	if (dtrace_err_verbose)
12860 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12861 
12862 #ifdef DTRACE_ERRDEBUG
12863 	dtrace_errdebug(str);
12864 #endif
12865 }
12866 
12867 /*
12868  * Create DOF out of a currently enabled state.  Right now, we only create
12869  * DOF containing the run-time options -- but this could be expanded to create
12870  * complete DOF representing the enabled state.
12871  */
12872 static dof_hdr_t *
12873 dtrace_dof_create(dtrace_state_t *state)
12874 {
12875 	dof_hdr_t *dof;
12876 	dof_sec_t *sec;
12877 	dof_optdesc_t *opt;
12878 	int i, len = sizeof (dof_hdr_t) +
12879 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12880 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12881 
12882 	ASSERT(MUTEX_HELD(&dtrace_lock));
12883 
12884 	dof = kmem_zalloc(len, KM_SLEEP);
12885 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12886 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12887 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12888 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12889 
12890 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12891 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12892 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12893 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12894 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12895 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12896 
12897 	dof->dofh_flags = 0;
12898 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12899 	dof->dofh_secsize = sizeof (dof_sec_t);
12900 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12901 	dof->dofh_secoff = sizeof (dof_hdr_t);
12902 	dof->dofh_loadsz = len;
12903 	dof->dofh_filesz = len;
12904 	dof->dofh_pad = 0;
12905 
12906 	/*
12907 	 * Fill in the option section header...
12908 	 */
12909 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12910 	sec->dofs_type = DOF_SECT_OPTDESC;
12911 	sec->dofs_align = sizeof (uint64_t);
12912 	sec->dofs_flags = DOF_SECF_LOAD;
12913 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12914 
12915 	opt = (dof_optdesc_t *)((uintptr_t)sec +
12916 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12917 
12918 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12919 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12920 
12921 	for (i = 0; i < DTRACEOPT_MAX; i++) {
12922 		opt[i].dofo_option = i;
12923 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
12924 		opt[i].dofo_value = state->dts_options[i];
12925 	}
12926 
12927 	return (dof);
12928 }
12929 
12930 static dof_hdr_t *
12931 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12932 {
12933 	dof_hdr_t hdr, *dof;
12934 
12935 	ASSERT(!MUTEX_HELD(&dtrace_lock));
12936 
12937 	/*
12938 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
12939 	 */
12940 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12941 		dtrace_dof_error(NULL, "failed to copyin DOF header");
12942 		*errp = EFAULT;
12943 		return (NULL);
12944 	}
12945 
12946 	/*
12947 	 * Now we'll allocate the entire DOF and copy it in -- provided
12948 	 * that the length isn't outrageous.
12949 	 */
12950 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12951 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12952 		*errp = E2BIG;
12953 		return (NULL);
12954 	}
12955 
12956 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12957 		dtrace_dof_error(&hdr, "invalid load size");
12958 		*errp = EINVAL;
12959 		return (NULL);
12960 	}
12961 
12962 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12963 
12964 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12965 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
12966 		kmem_free(dof, hdr.dofh_loadsz);
12967 		*errp = EFAULT;
12968 		return (NULL);
12969 	}
12970 
12971 	return (dof);
12972 }
12973 
12974 #if !defined(sun)
12975 static __inline uchar_t
12976 dtrace_dof_char(char c) {
12977 	switch (c) {
12978 	case '0':
12979 	case '1':
12980 	case '2':
12981 	case '3':
12982 	case '4':
12983 	case '5':
12984 	case '6':
12985 	case '7':
12986 	case '8':
12987 	case '9':
12988 		return (c - '0');
12989 	case 'A':
12990 	case 'B':
12991 	case 'C':
12992 	case 'D':
12993 	case 'E':
12994 	case 'F':
12995 		return (c - 'A' + 10);
12996 	case 'a':
12997 	case 'b':
12998 	case 'c':
12999 	case 'd':
13000 	case 'e':
13001 	case 'f':
13002 		return (c - 'a' + 10);
13003 	}
13004 	/* Should not reach here. */
13005 	return (0);
13006 }
13007 #endif
13008 
13009 static dof_hdr_t *
13010 dtrace_dof_property(const char *name)
13011 {
13012 	uchar_t *buf;
13013 	uint64_t loadsz;
13014 	unsigned int len, i;
13015 	dof_hdr_t *dof;
13016 
13017 #if defined(sun)
13018 	/*
13019 	 * Unfortunately, array of values in .conf files are always (and
13020 	 * only) interpreted to be integer arrays.  We must read our DOF
13021 	 * as an integer array, and then squeeze it into a byte array.
13022 	 */
13023 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13024 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13025 		return (NULL);
13026 
13027 	for (i = 0; i < len; i++)
13028 		buf[i] = (uchar_t)(((int *)buf)[i]);
13029 
13030 	if (len < sizeof (dof_hdr_t)) {
13031 		ddi_prop_free(buf);
13032 		dtrace_dof_error(NULL, "truncated header");
13033 		return (NULL);
13034 	}
13035 
13036 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13037 		ddi_prop_free(buf);
13038 		dtrace_dof_error(NULL, "truncated DOF");
13039 		return (NULL);
13040 	}
13041 
13042 	if (loadsz >= dtrace_dof_maxsize) {
13043 		ddi_prop_free(buf);
13044 		dtrace_dof_error(NULL, "oversized DOF");
13045 		return (NULL);
13046 	}
13047 
13048 	dof = kmem_alloc(loadsz, KM_SLEEP);
13049 	bcopy(buf, dof, loadsz);
13050 	ddi_prop_free(buf);
13051 #else
13052 	char *p;
13053 	char *p_env;
13054 
13055 	if ((p_env = kern_getenv(name)) == NULL)
13056 		return (NULL);
13057 
13058 	len = strlen(p_env) / 2;
13059 
13060 	buf = kmem_alloc(len, KM_SLEEP);
13061 
13062 	dof = (dof_hdr_t *) buf;
13063 
13064 	p = p_env;
13065 
13066 	for (i = 0; i < len; i++) {
13067 		buf[i] = (dtrace_dof_char(p[0]) << 4) |
13068 		     dtrace_dof_char(p[1]);
13069 		p += 2;
13070 	}
13071 
13072 	freeenv(p_env);
13073 
13074 	if (len < sizeof (dof_hdr_t)) {
13075 		kmem_free(buf, 0);
13076 		dtrace_dof_error(NULL, "truncated header");
13077 		return (NULL);
13078 	}
13079 
13080 	if (len < (loadsz = dof->dofh_loadsz)) {
13081 		kmem_free(buf, 0);
13082 		dtrace_dof_error(NULL, "truncated DOF");
13083 		return (NULL);
13084 	}
13085 
13086 	if (loadsz >= dtrace_dof_maxsize) {
13087 		kmem_free(buf, 0);
13088 		dtrace_dof_error(NULL, "oversized DOF");
13089 		return (NULL);
13090 	}
13091 #endif
13092 
13093 	return (dof);
13094 }
13095 
13096 static void
13097 dtrace_dof_destroy(dof_hdr_t *dof)
13098 {
13099 	kmem_free(dof, dof->dofh_loadsz);
13100 }
13101 
13102 /*
13103  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13104  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13105  * a type other than DOF_SECT_NONE is specified, the header is checked against
13106  * this type and NULL is returned if the types do not match.
13107  */
13108 static dof_sec_t *
13109 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13110 {
13111 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13112 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13113 
13114 	if (i >= dof->dofh_secnum) {
13115 		dtrace_dof_error(dof, "referenced section index is invalid");
13116 		return (NULL);
13117 	}
13118 
13119 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13120 		dtrace_dof_error(dof, "referenced section is not loadable");
13121 		return (NULL);
13122 	}
13123 
13124 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13125 		dtrace_dof_error(dof, "referenced section is the wrong type");
13126 		return (NULL);
13127 	}
13128 
13129 	return (sec);
13130 }
13131 
13132 static dtrace_probedesc_t *
13133 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13134 {
13135 	dof_probedesc_t *probe;
13136 	dof_sec_t *strtab;
13137 	uintptr_t daddr = (uintptr_t)dof;
13138 	uintptr_t str;
13139 	size_t size;
13140 
13141 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13142 		dtrace_dof_error(dof, "invalid probe section");
13143 		return (NULL);
13144 	}
13145 
13146 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13147 		dtrace_dof_error(dof, "bad alignment in probe description");
13148 		return (NULL);
13149 	}
13150 
13151 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13152 		dtrace_dof_error(dof, "truncated probe description");
13153 		return (NULL);
13154 	}
13155 
13156 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13157 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13158 
13159 	if (strtab == NULL)
13160 		return (NULL);
13161 
13162 	str = daddr + strtab->dofs_offset;
13163 	size = strtab->dofs_size;
13164 
13165 	if (probe->dofp_provider >= strtab->dofs_size) {
13166 		dtrace_dof_error(dof, "corrupt probe provider");
13167 		return (NULL);
13168 	}
13169 
13170 	(void) strncpy(desc->dtpd_provider,
13171 	    (char *)(str + probe->dofp_provider),
13172 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13173 
13174 	if (probe->dofp_mod >= strtab->dofs_size) {
13175 		dtrace_dof_error(dof, "corrupt probe module");
13176 		return (NULL);
13177 	}
13178 
13179 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13180 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13181 
13182 	if (probe->dofp_func >= strtab->dofs_size) {
13183 		dtrace_dof_error(dof, "corrupt probe function");
13184 		return (NULL);
13185 	}
13186 
13187 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13188 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13189 
13190 	if (probe->dofp_name >= strtab->dofs_size) {
13191 		dtrace_dof_error(dof, "corrupt probe name");
13192 		return (NULL);
13193 	}
13194 
13195 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13196 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13197 
13198 	return (desc);
13199 }
13200 
13201 static dtrace_difo_t *
13202 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13203     cred_t *cr)
13204 {
13205 	dtrace_difo_t *dp;
13206 	size_t ttl = 0;
13207 	dof_difohdr_t *dofd;
13208 	uintptr_t daddr = (uintptr_t)dof;
13209 	size_t max = dtrace_difo_maxsize;
13210 	int i, l, n;
13211 
13212 	static const struct {
13213 		int section;
13214 		int bufoffs;
13215 		int lenoffs;
13216 		int entsize;
13217 		int align;
13218 		const char *msg;
13219 	} difo[] = {
13220 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13221 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13222 		sizeof (dif_instr_t), "multiple DIF sections" },
13223 
13224 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13225 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13226 		sizeof (uint64_t), "multiple integer tables" },
13227 
13228 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13229 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13230 		sizeof (char), "multiple string tables" },
13231 
13232 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13233 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13234 		sizeof (uint_t), "multiple variable tables" },
13235 
13236 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13237 	};
13238 
13239 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13240 		dtrace_dof_error(dof, "invalid DIFO header section");
13241 		return (NULL);
13242 	}
13243 
13244 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13245 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13246 		return (NULL);
13247 	}
13248 
13249 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13250 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13251 		dtrace_dof_error(dof, "bad size in DIFO header");
13252 		return (NULL);
13253 	}
13254 
13255 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13256 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13257 
13258 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13259 	dp->dtdo_rtype = dofd->dofd_rtype;
13260 
13261 	for (l = 0; l < n; l++) {
13262 		dof_sec_t *subsec;
13263 		void **bufp;
13264 		uint32_t *lenp;
13265 
13266 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13267 		    dofd->dofd_links[l])) == NULL)
13268 			goto err; /* invalid section link */
13269 
13270 		if (ttl + subsec->dofs_size > max) {
13271 			dtrace_dof_error(dof, "exceeds maximum size");
13272 			goto err;
13273 		}
13274 
13275 		ttl += subsec->dofs_size;
13276 
13277 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13278 			if (subsec->dofs_type != difo[i].section)
13279 				continue;
13280 
13281 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13282 				dtrace_dof_error(dof, "section not loaded");
13283 				goto err;
13284 			}
13285 
13286 			if (subsec->dofs_align != difo[i].align) {
13287 				dtrace_dof_error(dof, "bad alignment");
13288 				goto err;
13289 			}
13290 
13291 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13292 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13293 
13294 			if (*bufp != NULL) {
13295 				dtrace_dof_error(dof, difo[i].msg);
13296 				goto err;
13297 			}
13298 
13299 			if (difo[i].entsize != subsec->dofs_entsize) {
13300 				dtrace_dof_error(dof, "entry size mismatch");
13301 				goto err;
13302 			}
13303 
13304 			if (subsec->dofs_entsize != 0 &&
13305 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13306 				dtrace_dof_error(dof, "corrupt entry size");
13307 				goto err;
13308 			}
13309 
13310 			*lenp = subsec->dofs_size;
13311 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13312 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13313 			    *bufp, subsec->dofs_size);
13314 
13315 			if (subsec->dofs_entsize != 0)
13316 				*lenp /= subsec->dofs_entsize;
13317 
13318 			break;
13319 		}
13320 
13321 		/*
13322 		 * If we encounter a loadable DIFO sub-section that is not
13323 		 * known to us, assume this is a broken program and fail.
13324 		 */
13325 		if (difo[i].section == DOF_SECT_NONE &&
13326 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13327 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13328 			goto err;
13329 		}
13330 	}
13331 
13332 	if (dp->dtdo_buf == NULL) {
13333 		/*
13334 		 * We can't have a DIF object without DIF text.
13335 		 */
13336 		dtrace_dof_error(dof, "missing DIF text");
13337 		goto err;
13338 	}
13339 
13340 	/*
13341 	 * Before we validate the DIF object, run through the variable table
13342 	 * looking for the strings -- if any of their size are under, we'll set
13343 	 * their size to be the system-wide default string size.  Note that
13344 	 * this should _not_ happen if the "strsize" option has been set --
13345 	 * in this case, the compiler should have set the size to reflect the
13346 	 * setting of the option.
13347 	 */
13348 	for (i = 0; i < dp->dtdo_varlen; i++) {
13349 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13350 		dtrace_diftype_t *t = &v->dtdv_type;
13351 
13352 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13353 			continue;
13354 
13355 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13356 			t->dtdt_size = dtrace_strsize_default;
13357 	}
13358 
13359 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13360 		goto err;
13361 
13362 	dtrace_difo_init(dp, vstate);
13363 	return (dp);
13364 
13365 err:
13366 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13367 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13368 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13369 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13370 
13371 	kmem_free(dp, sizeof (dtrace_difo_t));
13372 	return (NULL);
13373 }
13374 
13375 static dtrace_predicate_t *
13376 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13377     cred_t *cr)
13378 {
13379 	dtrace_difo_t *dp;
13380 
13381 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13382 		return (NULL);
13383 
13384 	return (dtrace_predicate_create(dp));
13385 }
13386 
13387 static dtrace_actdesc_t *
13388 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13389     cred_t *cr)
13390 {
13391 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13392 	dof_actdesc_t *desc;
13393 	dof_sec_t *difosec;
13394 	size_t offs;
13395 	uintptr_t daddr = (uintptr_t)dof;
13396 	uint64_t arg;
13397 	dtrace_actkind_t kind;
13398 
13399 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13400 		dtrace_dof_error(dof, "invalid action section");
13401 		return (NULL);
13402 	}
13403 
13404 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13405 		dtrace_dof_error(dof, "truncated action description");
13406 		return (NULL);
13407 	}
13408 
13409 	if (sec->dofs_align != sizeof (uint64_t)) {
13410 		dtrace_dof_error(dof, "bad alignment in action description");
13411 		return (NULL);
13412 	}
13413 
13414 	if (sec->dofs_size < sec->dofs_entsize) {
13415 		dtrace_dof_error(dof, "section entry size exceeds total size");
13416 		return (NULL);
13417 	}
13418 
13419 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13420 		dtrace_dof_error(dof, "bad entry size in action description");
13421 		return (NULL);
13422 	}
13423 
13424 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13425 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13426 		return (NULL);
13427 	}
13428 
13429 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13430 		desc = (dof_actdesc_t *)(daddr +
13431 		    (uintptr_t)sec->dofs_offset + offs);
13432 		kind = (dtrace_actkind_t)desc->dofa_kind;
13433 
13434 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13435 		    (kind != DTRACEACT_PRINTA ||
13436 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13437 		    (kind == DTRACEACT_DIFEXPR &&
13438 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13439 			dof_sec_t *strtab;
13440 			char *str, *fmt;
13441 			uint64_t i;
13442 
13443 			/*
13444 			 * The argument to these actions is an index into the
13445 			 * DOF string table.  For printf()-like actions, this
13446 			 * is the format string.  For print(), this is the
13447 			 * CTF type of the expression result.
13448 			 */
13449 			if ((strtab = dtrace_dof_sect(dof,
13450 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13451 				goto err;
13452 
13453 			str = (char *)((uintptr_t)dof +
13454 			    (uintptr_t)strtab->dofs_offset);
13455 
13456 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13457 				if (str[i] == '\0')
13458 					break;
13459 			}
13460 
13461 			if (i >= strtab->dofs_size) {
13462 				dtrace_dof_error(dof, "bogus format string");
13463 				goto err;
13464 			}
13465 
13466 			if (i == desc->dofa_arg) {
13467 				dtrace_dof_error(dof, "empty format string");
13468 				goto err;
13469 			}
13470 
13471 			i -= desc->dofa_arg;
13472 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13473 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13474 			arg = (uint64_t)(uintptr_t)fmt;
13475 		} else {
13476 			if (kind == DTRACEACT_PRINTA) {
13477 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13478 				arg = 0;
13479 			} else {
13480 				arg = desc->dofa_arg;
13481 			}
13482 		}
13483 
13484 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13485 		    desc->dofa_uarg, arg);
13486 
13487 		if (last != NULL) {
13488 			last->dtad_next = act;
13489 		} else {
13490 			first = act;
13491 		}
13492 
13493 		last = act;
13494 
13495 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13496 			continue;
13497 
13498 		if ((difosec = dtrace_dof_sect(dof,
13499 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13500 			goto err;
13501 
13502 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13503 
13504 		if (act->dtad_difo == NULL)
13505 			goto err;
13506 	}
13507 
13508 	ASSERT(first != NULL);
13509 	return (first);
13510 
13511 err:
13512 	for (act = first; act != NULL; act = next) {
13513 		next = act->dtad_next;
13514 		dtrace_actdesc_release(act, vstate);
13515 	}
13516 
13517 	return (NULL);
13518 }
13519 
13520 static dtrace_ecbdesc_t *
13521 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13522     cred_t *cr)
13523 {
13524 	dtrace_ecbdesc_t *ep;
13525 	dof_ecbdesc_t *ecb;
13526 	dtrace_probedesc_t *desc;
13527 	dtrace_predicate_t *pred = NULL;
13528 
13529 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13530 		dtrace_dof_error(dof, "truncated ECB description");
13531 		return (NULL);
13532 	}
13533 
13534 	if (sec->dofs_align != sizeof (uint64_t)) {
13535 		dtrace_dof_error(dof, "bad alignment in ECB description");
13536 		return (NULL);
13537 	}
13538 
13539 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13540 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13541 
13542 	if (sec == NULL)
13543 		return (NULL);
13544 
13545 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13546 	ep->dted_uarg = ecb->dofe_uarg;
13547 	desc = &ep->dted_probe;
13548 
13549 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13550 		goto err;
13551 
13552 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13553 		if ((sec = dtrace_dof_sect(dof,
13554 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13555 			goto err;
13556 
13557 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13558 			goto err;
13559 
13560 		ep->dted_pred.dtpdd_predicate = pred;
13561 	}
13562 
13563 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13564 		if ((sec = dtrace_dof_sect(dof,
13565 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13566 			goto err;
13567 
13568 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13569 
13570 		if (ep->dted_action == NULL)
13571 			goto err;
13572 	}
13573 
13574 	return (ep);
13575 
13576 err:
13577 	if (pred != NULL)
13578 		dtrace_predicate_release(pred, vstate);
13579 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13580 	return (NULL);
13581 }
13582 
13583 /*
13584  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13585  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
13586  * site of any user SETX relocations to account for load object base address.
13587  * In the future, if we need other relocations, this function can be extended.
13588  */
13589 static int
13590 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13591 {
13592 	uintptr_t daddr = (uintptr_t)dof;
13593 	dof_relohdr_t *dofr =
13594 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13595 	dof_sec_t *ss, *rs, *ts;
13596 	dof_relodesc_t *r;
13597 	uint_t i, n;
13598 
13599 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13600 	    sec->dofs_align != sizeof (dof_secidx_t)) {
13601 		dtrace_dof_error(dof, "invalid relocation header");
13602 		return (-1);
13603 	}
13604 
13605 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13606 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13607 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13608 
13609 	if (ss == NULL || rs == NULL || ts == NULL)
13610 		return (-1); /* dtrace_dof_error() has been called already */
13611 
13612 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13613 	    rs->dofs_align != sizeof (uint64_t)) {
13614 		dtrace_dof_error(dof, "invalid relocation section");
13615 		return (-1);
13616 	}
13617 
13618 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13619 	n = rs->dofs_size / rs->dofs_entsize;
13620 
13621 	for (i = 0; i < n; i++) {
13622 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13623 
13624 		switch (r->dofr_type) {
13625 		case DOF_RELO_NONE:
13626 			break;
13627 		case DOF_RELO_SETX:
13628 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13629 			    sizeof (uint64_t) > ts->dofs_size) {
13630 				dtrace_dof_error(dof, "bad relocation offset");
13631 				return (-1);
13632 			}
13633 
13634 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13635 				dtrace_dof_error(dof, "misaligned setx relo");
13636 				return (-1);
13637 			}
13638 
13639 			*(uint64_t *)taddr += ubase;
13640 			break;
13641 		default:
13642 			dtrace_dof_error(dof, "invalid relocation type");
13643 			return (-1);
13644 		}
13645 
13646 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13647 	}
13648 
13649 	return (0);
13650 }
13651 
13652 /*
13653  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13654  * header:  it should be at the front of a memory region that is at least
13655  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13656  * size.  It need not be validated in any other way.
13657  */
13658 static int
13659 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13660     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13661 {
13662 	uint64_t len = dof->dofh_loadsz, seclen;
13663 	uintptr_t daddr = (uintptr_t)dof;
13664 	dtrace_ecbdesc_t *ep;
13665 	dtrace_enabling_t *enab;
13666 	uint_t i;
13667 
13668 	ASSERT(MUTEX_HELD(&dtrace_lock));
13669 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13670 
13671 	/*
13672 	 * Check the DOF header identification bytes.  In addition to checking
13673 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13674 	 * we can use them later without fear of regressing existing binaries.
13675 	 */
13676 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13677 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13678 		dtrace_dof_error(dof, "DOF magic string mismatch");
13679 		return (-1);
13680 	}
13681 
13682 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13683 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13684 		dtrace_dof_error(dof, "DOF has invalid data model");
13685 		return (-1);
13686 	}
13687 
13688 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13689 		dtrace_dof_error(dof, "DOF encoding mismatch");
13690 		return (-1);
13691 	}
13692 
13693 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13694 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13695 		dtrace_dof_error(dof, "DOF version mismatch");
13696 		return (-1);
13697 	}
13698 
13699 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13700 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13701 		return (-1);
13702 	}
13703 
13704 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13705 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13706 		return (-1);
13707 	}
13708 
13709 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13710 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13711 		return (-1);
13712 	}
13713 
13714 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13715 		if (dof->dofh_ident[i] != 0) {
13716 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13717 			return (-1);
13718 		}
13719 	}
13720 
13721 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13722 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13723 		return (-1);
13724 	}
13725 
13726 	if (dof->dofh_secsize == 0) {
13727 		dtrace_dof_error(dof, "zero section header size");
13728 		return (-1);
13729 	}
13730 
13731 	/*
13732 	 * Check that the section headers don't exceed the amount of DOF
13733 	 * data.  Note that we cast the section size and number of sections
13734 	 * to uint64_t's to prevent possible overflow in the multiplication.
13735 	 */
13736 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13737 
13738 	if (dof->dofh_secoff > len || seclen > len ||
13739 	    dof->dofh_secoff + seclen > len) {
13740 		dtrace_dof_error(dof, "truncated section headers");
13741 		return (-1);
13742 	}
13743 
13744 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13745 		dtrace_dof_error(dof, "misaligned section headers");
13746 		return (-1);
13747 	}
13748 
13749 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13750 		dtrace_dof_error(dof, "misaligned section size");
13751 		return (-1);
13752 	}
13753 
13754 	/*
13755 	 * Take an initial pass through the section headers to be sure that
13756 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13757 	 * set, do not permit sections relating to providers, probes, or args.
13758 	 */
13759 	for (i = 0; i < dof->dofh_secnum; i++) {
13760 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13761 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13762 
13763 		if (noprobes) {
13764 			switch (sec->dofs_type) {
13765 			case DOF_SECT_PROVIDER:
13766 			case DOF_SECT_PROBES:
13767 			case DOF_SECT_PRARGS:
13768 			case DOF_SECT_PROFFS:
13769 				dtrace_dof_error(dof, "illegal sections "
13770 				    "for enabling");
13771 				return (-1);
13772 			}
13773 		}
13774 
13775 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13776 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
13777 			dtrace_dof_error(dof, "loadable section with load "
13778 			    "flag unset");
13779 			return (-1);
13780 		}
13781 
13782 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13783 			continue; /* just ignore non-loadable sections */
13784 
13785 		if (sec->dofs_align & (sec->dofs_align - 1)) {
13786 			dtrace_dof_error(dof, "bad section alignment");
13787 			return (-1);
13788 		}
13789 
13790 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13791 			dtrace_dof_error(dof, "misaligned section");
13792 			return (-1);
13793 		}
13794 
13795 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13796 		    sec->dofs_offset + sec->dofs_size > len) {
13797 			dtrace_dof_error(dof, "corrupt section header");
13798 			return (-1);
13799 		}
13800 
13801 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13802 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13803 			dtrace_dof_error(dof, "non-terminating string table");
13804 			return (-1);
13805 		}
13806 	}
13807 
13808 	/*
13809 	 * Take a second pass through the sections and locate and perform any
13810 	 * relocations that are present.  We do this after the first pass to
13811 	 * be sure that all sections have had their headers validated.
13812 	 */
13813 	for (i = 0; i < dof->dofh_secnum; i++) {
13814 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13815 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13816 
13817 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13818 			continue; /* skip sections that are not loadable */
13819 
13820 		switch (sec->dofs_type) {
13821 		case DOF_SECT_URELHDR:
13822 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13823 				return (-1);
13824 			break;
13825 		}
13826 	}
13827 
13828 	if ((enab = *enabp) == NULL)
13829 		enab = *enabp = dtrace_enabling_create(vstate);
13830 
13831 	for (i = 0; i < dof->dofh_secnum; i++) {
13832 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13833 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13834 
13835 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13836 			continue;
13837 
13838 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13839 			dtrace_enabling_destroy(enab);
13840 			*enabp = NULL;
13841 			return (-1);
13842 		}
13843 
13844 		dtrace_enabling_add(enab, ep);
13845 	}
13846 
13847 	return (0);
13848 }
13849 
13850 /*
13851  * Process DOF for any options.  This routine assumes that the DOF has been
13852  * at least processed by dtrace_dof_slurp().
13853  */
13854 static int
13855 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13856 {
13857 	int i, rval;
13858 	uint32_t entsize;
13859 	size_t offs;
13860 	dof_optdesc_t *desc;
13861 
13862 	for (i = 0; i < dof->dofh_secnum; i++) {
13863 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13864 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13865 
13866 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13867 			continue;
13868 
13869 		if (sec->dofs_align != sizeof (uint64_t)) {
13870 			dtrace_dof_error(dof, "bad alignment in "
13871 			    "option description");
13872 			return (EINVAL);
13873 		}
13874 
13875 		if ((entsize = sec->dofs_entsize) == 0) {
13876 			dtrace_dof_error(dof, "zeroed option entry size");
13877 			return (EINVAL);
13878 		}
13879 
13880 		if (entsize < sizeof (dof_optdesc_t)) {
13881 			dtrace_dof_error(dof, "bad option entry size");
13882 			return (EINVAL);
13883 		}
13884 
13885 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13886 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13887 			    (uintptr_t)sec->dofs_offset + offs);
13888 
13889 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13890 				dtrace_dof_error(dof, "non-zero option string");
13891 				return (EINVAL);
13892 			}
13893 
13894 			if (desc->dofo_value == DTRACEOPT_UNSET) {
13895 				dtrace_dof_error(dof, "unset option");
13896 				return (EINVAL);
13897 			}
13898 
13899 			if ((rval = dtrace_state_option(state,
13900 			    desc->dofo_option, desc->dofo_value)) != 0) {
13901 				dtrace_dof_error(dof, "rejected option");
13902 				return (rval);
13903 			}
13904 		}
13905 	}
13906 
13907 	return (0);
13908 }
13909 
13910 /*
13911  * DTrace Consumer State Functions
13912  */
13913 static int
13914 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13915 {
13916 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13917 	void *base;
13918 	uintptr_t limit;
13919 	dtrace_dynvar_t *dvar, *next, *start;
13920 	int i;
13921 
13922 	ASSERT(MUTEX_HELD(&dtrace_lock));
13923 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13924 
13925 	bzero(dstate, sizeof (dtrace_dstate_t));
13926 
13927 	if ((dstate->dtds_chunksize = chunksize) == 0)
13928 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13929 
13930 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13931 		size = min;
13932 
13933 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13934 		return (ENOMEM);
13935 
13936 	dstate->dtds_size = size;
13937 	dstate->dtds_base = base;
13938 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13939 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13940 
13941 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13942 
13943 	if (hashsize != 1 && (hashsize & 1))
13944 		hashsize--;
13945 
13946 	dstate->dtds_hashsize = hashsize;
13947 	dstate->dtds_hash = dstate->dtds_base;
13948 
13949 	/*
13950 	 * Set all of our hash buckets to point to the single sink, and (if
13951 	 * it hasn't already been set), set the sink's hash value to be the
13952 	 * sink sentinel value.  The sink is needed for dynamic variable
13953 	 * lookups to know that they have iterated over an entire, valid hash
13954 	 * chain.
13955 	 */
13956 	for (i = 0; i < hashsize; i++)
13957 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13958 
13959 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13960 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13961 
13962 	/*
13963 	 * Determine number of active CPUs.  Divide free list evenly among
13964 	 * active CPUs.
13965 	 */
13966 	start = (dtrace_dynvar_t *)
13967 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13968 	limit = (uintptr_t)base + size;
13969 
13970 	maxper = (limit - (uintptr_t)start) / NCPU;
13971 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13972 
13973 #if !defined(sun)
13974 	CPU_FOREACH(i) {
13975 #else
13976 	for (i = 0; i < NCPU; i++) {
13977 #endif
13978 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13979 
13980 		/*
13981 		 * If we don't even have enough chunks to make it once through
13982 		 * NCPUs, we're just going to allocate everything to the first
13983 		 * CPU.  And if we're on the last CPU, we're going to allocate
13984 		 * whatever is left over.  In either case, we set the limit to
13985 		 * be the limit of the dynamic variable space.
13986 		 */
13987 		if (maxper == 0 || i == NCPU - 1) {
13988 			limit = (uintptr_t)base + size;
13989 			start = NULL;
13990 		} else {
13991 			limit = (uintptr_t)start + maxper;
13992 			start = (dtrace_dynvar_t *)limit;
13993 		}
13994 
13995 		ASSERT(limit <= (uintptr_t)base + size);
13996 
13997 		for (;;) {
13998 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13999 			    dstate->dtds_chunksize);
14000 
14001 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14002 				break;
14003 
14004 			dvar->dtdv_next = next;
14005 			dvar = next;
14006 		}
14007 
14008 		if (maxper == 0)
14009 			break;
14010 	}
14011 
14012 	return (0);
14013 }
14014 
14015 static void
14016 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14017 {
14018 	ASSERT(MUTEX_HELD(&cpu_lock));
14019 
14020 	if (dstate->dtds_base == NULL)
14021 		return;
14022 
14023 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14024 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14025 }
14026 
14027 static void
14028 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14029 {
14030 	/*
14031 	 * Logical XOR, where are you?
14032 	 */
14033 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14034 
14035 	if (vstate->dtvs_nglobals > 0) {
14036 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14037 		    sizeof (dtrace_statvar_t *));
14038 	}
14039 
14040 	if (vstate->dtvs_ntlocals > 0) {
14041 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14042 		    sizeof (dtrace_difv_t));
14043 	}
14044 
14045 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14046 
14047 	if (vstate->dtvs_nlocals > 0) {
14048 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14049 		    sizeof (dtrace_statvar_t *));
14050 	}
14051 }
14052 
14053 #if defined(sun)
14054 static void
14055 dtrace_state_clean(dtrace_state_t *state)
14056 {
14057 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14058 		return;
14059 
14060 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14061 	dtrace_speculation_clean(state);
14062 }
14063 
14064 static void
14065 dtrace_state_deadman(dtrace_state_t *state)
14066 {
14067 	hrtime_t now;
14068 
14069 	dtrace_sync();
14070 
14071 	now = dtrace_gethrtime();
14072 
14073 	if (state != dtrace_anon.dta_state &&
14074 	    now - state->dts_laststatus >= dtrace_deadman_user)
14075 		return;
14076 
14077 	/*
14078 	 * We must be sure that dts_alive never appears to be less than the
14079 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14080 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14081 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14082 	 * the new value.  This assures that dts_alive never appears to be
14083 	 * less than its true value, regardless of the order in which the
14084 	 * stores to the underlying storage are issued.
14085 	 */
14086 	state->dts_alive = INT64_MAX;
14087 	dtrace_membar_producer();
14088 	state->dts_alive = now;
14089 }
14090 #else
14091 static void
14092 dtrace_state_clean(void *arg)
14093 {
14094 	dtrace_state_t *state = arg;
14095 	dtrace_optval_t *opt = state->dts_options;
14096 
14097 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14098 		return;
14099 
14100 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14101 	dtrace_speculation_clean(state);
14102 
14103 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14104 	    dtrace_state_clean, state);
14105 }
14106 
14107 static void
14108 dtrace_state_deadman(void *arg)
14109 {
14110 	dtrace_state_t *state = arg;
14111 	hrtime_t now;
14112 
14113 	dtrace_sync();
14114 
14115 	dtrace_debug_output();
14116 
14117 	now = dtrace_gethrtime();
14118 
14119 	if (state != dtrace_anon.dta_state &&
14120 	    now - state->dts_laststatus >= dtrace_deadman_user)
14121 		return;
14122 
14123 	/*
14124 	 * We must be sure that dts_alive never appears to be less than the
14125 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14126 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14127 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14128 	 * the new value.  This assures that dts_alive never appears to be
14129 	 * less than its true value, regardless of the order in which the
14130 	 * stores to the underlying storage are issued.
14131 	 */
14132 	state->dts_alive = INT64_MAX;
14133 	dtrace_membar_producer();
14134 	state->dts_alive = now;
14135 
14136 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14137 	    dtrace_state_deadman, state);
14138 }
14139 #endif
14140 
14141 static dtrace_state_t *
14142 #if defined(sun)
14143 dtrace_state_create(dev_t *devp, cred_t *cr)
14144 #else
14145 dtrace_state_create(struct cdev *dev)
14146 #endif
14147 {
14148 #if defined(sun)
14149 	minor_t minor;
14150 	major_t major;
14151 #else
14152 	cred_t *cr = NULL;
14153 	int m = 0;
14154 #endif
14155 	char c[30];
14156 	dtrace_state_t *state;
14157 	dtrace_optval_t *opt;
14158 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14159 
14160 	ASSERT(MUTEX_HELD(&dtrace_lock));
14161 	ASSERT(MUTEX_HELD(&cpu_lock));
14162 
14163 #if defined(sun)
14164 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14165 	    VM_BESTFIT | VM_SLEEP);
14166 
14167 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14168 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14169 		return (NULL);
14170 	}
14171 
14172 	state = ddi_get_soft_state(dtrace_softstate, minor);
14173 #else
14174 	if (dev != NULL) {
14175 		cr = dev->si_cred;
14176 		m = dev2unit(dev);
14177 		}
14178 
14179 	/* Allocate memory for the state. */
14180 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14181 #endif
14182 
14183 	state->dts_epid = DTRACE_EPIDNONE + 1;
14184 
14185 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14186 #if defined(sun)
14187 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14188 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14189 
14190 	if (devp != NULL) {
14191 		major = getemajor(*devp);
14192 	} else {
14193 		major = ddi_driver_major(dtrace_devi);
14194 	}
14195 
14196 	state->dts_dev = makedevice(major, minor);
14197 
14198 	if (devp != NULL)
14199 		*devp = state->dts_dev;
14200 #else
14201 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14202 	state->dts_dev = dev;
14203 #endif
14204 
14205 	/*
14206 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14207 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14208 	 * other hand, it saves an additional memory reference in the probe
14209 	 * path.
14210 	 */
14211 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14212 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14213 
14214 #if defined(sun)
14215 	state->dts_cleaner = CYCLIC_NONE;
14216 	state->dts_deadman = CYCLIC_NONE;
14217 #else
14218 	callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
14219 	callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
14220 #endif
14221 	state->dts_vstate.dtvs_state = state;
14222 
14223 	for (i = 0; i < DTRACEOPT_MAX; i++)
14224 		state->dts_options[i] = DTRACEOPT_UNSET;
14225 
14226 	/*
14227 	 * Set the default options.
14228 	 */
14229 	opt = state->dts_options;
14230 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14231 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14232 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14233 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14234 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14235 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14236 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14237 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14238 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14239 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14240 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14241 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14242 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14243 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14244 
14245 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14246 
14247 	/*
14248 	 * Depending on the user credentials, we set flag bits which alter probe
14249 	 * visibility or the amount of destructiveness allowed.  In the case of
14250 	 * actual anonymous tracing, or the possession of all privileges, all of
14251 	 * the normal checks are bypassed.
14252 	 */
14253 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14254 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14255 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14256 	} else {
14257 		/*
14258 		 * Set up the credentials for this instantiation.  We take a
14259 		 * hold on the credential to prevent it from disappearing on
14260 		 * us; this in turn prevents the zone_t referenced by this
14261 		 * credential from disappearing.  This means that we can
14262 		 * examine the credential and the zone from probe context.
14263 		 */
14264 		crhold(cr);
14265 		state->dts_cred.dcr_cred = cr;
14266 
14267 		/*
14268 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14269 		 * unlocks the use of variables like pid, zonename, etc.
14270 		 */
14271 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14272 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14273 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14274 		}
14275 
14276 		/*
14277 		 * dtrace_user allows use of syscall and profile providers.
14278 		 * If the user also has proc_owner and/or proc_zone, we
14279 		 * extend the scope to include additional visibility and
14280 		 * destructive power.
14281 		 */
14282 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14283 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14284 				state->dts_cred.dcr_visible |=
14285 				    DTRACE_CRV_ALLPROC;
14286 
14287 				state->dts_cred.dcr_action |=
14288 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14289 			}
14290 
14291 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14292 				state->dts_cred.dcr_visible |=
14293 				    DTRACE_CRV_ALLZONE;
14294 
14295 				state->dts_cred.dcr_action |=
14296 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14297 			}
14298 
14299 			/*
14300 			 * If we have all privs in whatever zone this is,
14301 			 * we can do destructive things to processes which
14302 			 * have altered credentials.
14303 			 */
14304 #if defined(sun)
14305 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14306 			    cr->cr_zone->zone_privset)) {
14307 				state->dts_cred.dcr_action |=
14308 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14309 			}
14310 #endif
14311 		}
14312 
14313 		/*
14314 		 * Holding the dtrace_kernel privilege also implies that
14315 		 * the user has the dtrace_user privilege from a visibility
14316 		 * perspective.  But without further privileges, some
14317 		 * destructive actions are not available.
14318 		 */
14319 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14320 			/*
14321 			 * Make all probes in all zones visible.  However,
14322 			 * this doesn't mean that all actions become available
14323 			 * to all zones.
14324 			 */
14325 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14326 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14327 
14328 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14329 			    DTRACE_CRA_PROC;
14330 			/*
14331 			 * Holding proc_owner means that destructive actions
14332 			 * for *this* zone are allowed.
14333 			 */
14334 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14335 				state->dts_cred.dcr_action |=
14336 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14337 
14338 			/*
14339 			 * Holding proc_zone means that destructive actions
14340 			 * for this user/group ID in all zones is allowed.
14341 			 */
14342 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14343 				state->dts_cred.dcr_action |=
14344 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14345 
14346 #if defined(sun)
14347 			/*
14348 			 * If we have all privs in whatever zone this is,
14349 			 * we can do destructive things to processes which
14350 			 * have altered credentials.
14351 			 */
14352 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14353 			    cr->cr_zone->zone_privset)) {
14354 				state->dts_cred.dcr_action |=
14355 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14356 			}
14357 #endif
14358 		}
14359 
14360 		/*
14361 		 * Holding the dtrace_proc privilege gives control over fasttrap
14362 		 * and pid providers.  We need to grant wider destructive
14363 		 * privileges in the event that the user has proc_owner and/or
14364 		 * proc_zone.
14365 		 */
14366 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14367 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14368 				state->dts_cred.dcr_action |=
14369 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14370 
14371 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14372 				state->dts_cred.dcr_action |=
14373 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14374 		}
14375 	}
14376 
14377 	return (state);
14378 }
14379 
14380 static int
14381 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14382 {
14383 	dtrace_optval_t *opt = state->dts_options, size;
14384 	processorid_t cpu = 0;;
14385 	int flags = 0, rval, factor, divisor = 1;
14386 
14387 	ASSERT(MUTEX_HELD(&dtrace_lock));
14388 	ASSERT(MUTEX_HELD(&cpu_lock));
14389 	ASSERT(which < DTRACEOPT_MAX);
14390 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14391 	    (state == dtrace_anon.dta_state &&
14392 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14393 
14394 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14395 		return (0);
14396 
14397 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14398 		cpu = opt[DTRACEOPT_CPU];
14399 
14400 	if (which == DTRACEOPT_SPECSIZE)
14401 		flags |= DTRACEBUF_NOSWITCH;
14402 
14403 	if (which == DTRACEOPT_BUFSIZE) {
14404 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14405 			flags |= DTRACEBUF_RING;
14406 
14407 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14408 			flags |= DTRACEBUF_FILL;
14409 
14410 		if (state != dtrace_anon.dta_state ||
14411 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14412 			flags |= DTRACEBUF_INACTIVE;
14413 	}
14414 
14415 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14416 		/*
14417 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14418 		 * aligned, drop it down by the difference.
14419 		 */
14420 		if (size & (sizeof (uint64_t) - 1))
14421 			size -= size & (sizeof (uint64_t) - 1);
14422 
14423 		if (size < state->dts_reserve) {
14424 			/*
14425 			 * Buffers always must be large enough to accommodate
14426 			 * their prereserved space.  We return E2BIG instead
14427 			 * of ENOMEM in this case to allow for user-level
14428 			 * software to differentiate the cases.
14429 			 */
14430 			return (E2BIG);
14431 		}
14432 
14433 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14434 
14435 		if (rval != ENOMEM) {
14436 			opt[which] = size;
14437 			return (rval);
14438 		}
14439 
14440 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14441 			return (rval);
14442 
14443 		for (divisor = 2; divisor < factor; divisor <<= 1)
14444 			continue;
14445 	}
14446 
14447 	return (ENOMEM);
14448 }
14449 
14450 static int
14451 dtrace_state_buffers(dtrace_state_t *state)
14452 {
14453 	dtrace_speculation_t *spec = state->dts_speculations;
14454 	int rval, i;
14455 
14456 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14457 	    DTRACEOPT_BUFSIZE)) != 0)
14458 		return (rval);
14459 
14460 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14461 	    DTRACEOPT_AGGSIZE)) != 0)
14462 		return (rval);
14463 
14464 	for (i = 0; i < state->dts_nspeculations; i++) {
14465 		if ((rval = dtrace_state_buffer(state,
14466 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14467 			return (rval);
14468 	}
14469 
14470 	return (0);
14471 }
14472 
14473 static void
14474 dtrace_state_prereserve(dtrace_state_t *state)
14475 {
14476 	dtrace_ecb_t *ecb;
14477 	dtrace_probe_t *probe;
14478 
14479 	state->dts_reserve = 0;
14480 
14481 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14482 		return;
14483 
14484 	/*
14485 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14486 	 * prereserved space to be the space required by the END probes.
14487 	 */
14488 	probe = dtrace_probes[dtrace_probeid_end - 1];
14489 	ASSERT(probe != NULL);
14490 
14491 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14492 		if (ecb->dte_state != state)
14493 			continue;
14494 
14495 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14496 	}
14497 }
14498 
14499 static int
14500 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14501 {
14502 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14503 	dtrace_speculation_t *spec;
14504 	dtrace_buffer_t *buf;
14505 #if defined(sun)
14506 	cyc_handler_t hdlr;
14507 	cyc_time_t when;
14508 #endif
14509 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14510 	dtrace_icookie_t cookie;
14511 
14512 	mutex_enter(&cpu_lock);
14513 	mutex_enter(&dtrace_lock);
14514 
14515 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14516 		rval = EBUSY;
14517 		goto out;
14518 	}
14519 
14520 	/*
14521 	 * Before we can perform any checks, we must prime all of the
14522 	 * retained enablings that correspond to this state.
14523 	 */
14524 	dtrace_enabling_prime(state);
14525 
14526 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14527 		rval = EACCES;
14528 		goto out;
14529 	}
14530 
14531 	dtrace_state_prereserve(state);
14532 
14533 	/*
14534 	 * Now we want to do is try to allocate our speculations.
14535 	 * We do not automatically resize the number of speculations; if
14536 	 * this fails, we will fail the operation.
14537 	 */
14538 	nspec = opt[DTRACEOPT_NSPEC];
14539 	ASSERT(nspec != DTRACEOPT_UNSET);
14540 
14541 	if (nspec > INT_MAX) {
14542 		rval = ENOMEM;
14543 		goto out;
14544 	}
14545 
14546 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14547 	    KM_NOSLEEP | KM_NORMALPRI);
14548 
14549 	if (spec == NULL) {
14550 		rval = ENOMEM;
14551 		goto out;
14552 	}
14553 
14554 	state->dts_speculations = spec;
14555 	state->dts_nspeculations = (int)nspec;
14556 
14557 	for (i = 0; i < nspec; i++) {
14558 		if ((buf = kmem_zalloc(bufsize,
14559 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
14560 			rval = ENOMEM;
14561 			goto err;
14562 		}
14563 
14564 		spec[i].dtsp_buffer = buf;
14565 	}
14566 
14567 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14568 		if (dtrace_anon.dta_state == NULL) {
14569 			rval = ENOENT;
14570 			goto out;
14571 		}
14572 
14573 		if (state->dts_necbs != 0) {
14574 			rval = EALREADY;
14575 			goto out;
14576 		}
14577 
14578 		state->dts_anon = dtrace_anon_grab();
14579 		ASSERT(state->dts_anon != NULL);
14580 		state = state->dts_anon;
14581 
14582 		/*
14583 		 * We want "grabanon" to be set in the grabbed state, so we'll
14584 		 * copy that option value from the grabbing state into the
14585 		 * grabbed state.
14586 		 */
14587 		state->dts_options[DTRACEOPT_GRABANON] =
14588 		    opt[DTRACEOPT_GRABANON];
14589 
14590 		*cpu = dtrace_anon.dta_beganon;
14591 
14592 		/*
14593 		 * If the anonymous state is active (as it almost certainly
14594 		 * is if the anonymous enabling ultimately matched anything),
14595 		 * we don't allow any further option processing -- but we
14596 		 * don't return failure.
14597 		 */
14598 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14599 			goto out;
14600 	}
14601 
14602 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14603 	    opt[DTRACEOPT_AGGSIZE] != 0) {
14604 		if (state->dts_aggregations == NULL) {
14605 			/*
14606 			 * We're not going to create an aggregation buffer
14607 			 * because we don't have any ECBs that contain
14608 			 * aggregations -- set this option to 0.
14609 			 */
14610 			opt[DTRACEOPT_AGGSIZE] = 0;
14611 		} else {
14612 			/*
14613 			 * If we have an aggregation buffer, we must also have
14614 			 * a buffer to use as scratch.
14615 			 */
14616 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14617 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14618 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14619 			}
14620 		}
14621 	}
14622 
14623 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14624 	    opt[DTRACEOPT_SPECSIZE] != 0) {
14625 		if (!state->dts_speculates) {
14626 			/*
14627 			 * We're not going to create speculation buffers
14628 			 * because we don't have any ECBs that actually
14629 			 * speculate -- set the speculation size to 0.
14630 			 */
14631 			opt[DTRACEOPT_SPECSIZE] = 0;
14632 		}
14633 	}
14634 
14635 	/*
14636 	 * The bare minimum size for any buffer that we're actually going to
14637 	 * do anything to is sizeof (uint64_t).
14638 	 */
14639 	sz = sizeof (uint64_t);
14640 
14641 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14642 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14643 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14644 		/*
14645 		 * A buffer size has been explicitly set to 0 (or to a size
14646 		 * that will be adjusted to 0) and we need the space -- we
14647 		 * need to return failure.  We return ENOSPC to differentiate
14648 		 * it from failing to allocate a buffer due to failure to meet
14649 		 * the reserve (for which we return E2BIG).
14650 		 */
14651 		rval = ENOSPC;
14652 		goto out;
14653 	}
14654 
14655 	if ((rval = dtrace_state_buffers(state)) != 0)
14656 		goto err;
14657 
14658 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14659 		sz = dtrace_dstate_defsize;
14660 
14661 	do {
14662 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14663 
14664 		if (rval == 0)
14665 			break;
14666 
14667 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14668 			goto err;
14669 	} while (sz >>= 1);
14670 
14671 	opt[DTRACEOPT_DYNVARSIZE] = sz;
14672 
14673 	if (rval != 0)
14674 		goto err;
14675 
14676 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14677 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14678 
14679 	if (opt[DTRACEOPT_CLEANRATE] == 0)
14680 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14681 
14682 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14683 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14684 
14685 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14686 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14687 
14688 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14689 #if defined(sun)
14690 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14691 	hdlr.cyh_arg = state;
14692 	hdlr.cyh_level = CY_LOW_LEVEL;
14693 
14694 	when.cyt_when = 0;
14695 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14696 
14697 	state->dts_cleaner = cyclic_add(&hdlr, &when);
14698 
14699 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14700 	hdlr.cyh_arg = state;
14701 	hdlr.cyh_level = CY_LOW_LEVEL;
14702 
14703 	when.cyt_when = 0;
14704 	when.cyt_interval = dtrace_deadman_interval;
14705 
14706 	state->dts_deadman = cyclic_add(&hdlr, &when);
14707 #else
14708 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14709 	    dtrace_state_clean, state);
14710 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14711 	    dtrace_state_deadman, state);
14712 #endif
14713 
14714 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14715 
14716 #if defined(sun)
14717 	if (state->dts_getf != 0 &&
14718 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14719 		/*
14720 		 * We don't have kernel privs but we have at least one call
14721 		 * to getf(); we need to bump our zone's count, and (if
14722 		 * this is the first enabling to have an unprivileged call
14723 		 * to getf()) we need to hook into closef().
14724 		 */
14725 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14726 
14727 		if (dtrace_getf++ == 0) {
14728 			ASSERT(dtrace_closef == NULL);
14729 			dtrace_closef = dtrace_getf_barrier;
14730 		}
14731 	}
14732 #endif
14733 
14734 	/*
14735 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14736 	 * interrupts here both to record the CPU on which we fired the BEGIN
14737 	 * probe (the data from this CPU will be processed first at user
14738 	 * level) and to manually activate the buffer for this CPU.
14739 	 */
14740 	cookie = dtrace_interrupt_disable();
14741 	*cpu = curcpu;
14742 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14743 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14744 
14745 	dtrace_probe(dtrace_probeid_begin,
14746 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14747 	dtrace_interrupt_enable(cookie);
14748 	/*
14749 	 * We may have had an exit action from a BEGIN probe; only change our
14750 	 * state to ACTIVE if we're still in WARMUP.
14751 	 */
14752 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14753 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14754 
14755 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14756 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14757 
14758 	/*
14759 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14760 	 * want each CPU to transition its principal buffer out of the
14761 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14762 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14763 	 * atomically transition from processing none of a state's ECBs to
14764 	 * processing all of them.
14765 	 */
14766 	dtrace_xcall(DTRACE_CPUALL,
14767 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14768 	goto out;
14769 
14770 err:
14771 	dtrace_buffer_free(state->dts_buffer);
14772 	dtrace_buffer_free(state->dts_aggbuffer);
14773 
14774 	if ((nspec = state->dts_nspeculations) == 0) {
14775 		ASSERT(state->dts_speculations == NULL);
14776 		goto out;
14777 	}
14778 
14779 	spec = state->dts_speculations;
14780 	ASSERT(spec != NULL);
14781 
14782 	for (i = 0; i < state->dts_nspeculations; i++) {
14783 		if ((buf = spec[i].dtsp_buffer) == NULL)
14784 			break;
14785 
14786 		dtrace_buffer_free(buf);
14787 		kmem_free(buf, bufsize);
14788 	}
14789 
14790 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14791 	state->dts_nspeculations = 0;
14792 	state->dts_speculations = NULL;
14793 
14794 out:
14795 	mutex_exit(&dtrace_lock);
14796 	mutex_exit(&cpu_lock);
14797 
14798 	return (rval);
14799 }
14800 
14801 static int
14802 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14803 {
14804 	dtrace_icookie_t cookie;
14805 
14806 	ASSERT(MUTEX_HELD(&dtrace_lock));
14807 
14808 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14809 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14810 		return (EINVAL);
14811 
14812 	/*
14813 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14814 	 * to be sure that every CPU has seen it.  See below for the details
14815 	 * on why this is done.
14816 	 */
14817 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14818 	dtrace_sync();
14819 
14820 	/*
14821 	 * By this point, it is impossible for any CPU to be still processing
14822 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14823 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14824 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14825 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14826 	 * iff we're in the END probe.
14827 	 */
14828 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14829 	dtrace_sync();
14830 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14831 
14832 	/*
14833 	 * Finally, we can release the reserve and call the END probe.  We
14834 	 * disable interrupts across calling the END probe to allow us to
14835 	 * return the CPU on which we actually called the END probe.  This
14836 	 * allows user-land to be sure that this CPU's principal buffer is
14837 	 * processed last.
14838 	 */
14839 	state->dts_reserve = 0;
14840 
14841 	cookie = dtrace_interrupt_disable();
14842 	*cpu = curcpu;
14843 	dtrace_probe(dtrace_probeid_end,
14844 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14845 	dtrace_interrupt_enable(cookie);
14846 
14847 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14848 	dtrace_sync();
14849 
14850 #if defined(sun)
14851 	if (state->dts_getf != 0 &&
14852 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14853 		/*
14854 		 * We don't have kernel privs but we have at least one call
14855 		 * to getf(); we need to lower our zone's count, and (if
14856 		 * this is the last enabling to have an unprivileged call
14857 		 * to getf()) we need to clear the closef() hook.
14858 		 */
14859 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14860 		ASSERT(dtrace_closef == dtrace_getf_barrier);
14861 		ASSERT(dtrace_getf > 0);
14862 
14863 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14864 
14865 		if (--dtrace_getf == 0)
14866 			dtrace_closef = NULL;
14867 	}
14868 #endif
14869 
14870 	return (0);
14871 }
14872 
14873 static int
14874 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14875     dtrace_optval_t val)
14876 {
14877 	ASSERT(MUTEX_HELD(&dtrace_lock));
14878 
14879 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14880 		return (EBUSY);
14881 
14882 	if (option >= DTRACEOPT_MAX)
14883 		return (EINVAL);
14884 
14885 	if (option != DTRACEOPT_CPU && val < 0)
14886 		return (EINVAL);
14887 
14888 	switch (option) {
14889 	case DTRACEOPT_DESTRUCTIVE:
14890 		if (dtrace_destructive_disallow)
14891 			return (EACCES);
14892 
14893 		state->dts_cred.dcr_destructive = 1;
14894 		break;
14895 
14896 	case DTRACEOPT_BUFSIZE:
14897 	case DTRACEOPT_DYNVARSIZE:
14898 	case DTRACEOPT_AGGSIZE:
14899 	case DTRACEOPT_SPECSIZE:
14900 	case DTRACEOPT_STRSIZE:
14901 		if (val < 0)
14902 			return (EINVAL);
14903 
14904 		if (val >= LONG_MAX) {
14905 			/*
14906 			 * If this is an otherwise negative value, set it to
14907 			 * the highest multiple of 128m less than LONG_MAX.
14908 			 * Technically, we're adjusting the size without
14909 			 * regard to the buffer resizing policy, but in fact,
14910 			 * this has no effect -- if we set the buffer size to
14911 			 * ~LONG_MAX and the buffer policy is ultimately set to
14912 			 * be "manual", the buffer allocation is guaranteed to
14913 			 * fail, if only because the allocation requires two
14914 			 * buffers.  (We set the the size to the highest
14915 			 * multiple of 128m because it ensures that the size
14916 			 * will remain a multiple of a megabyte when
14917 			 * repeatedly halved -- all the way down to 15m.)
14918 			 */
14919 			val = LONG_MAX - (1 << 27) + 1;
14920 		}
14921 	}
14922 
14923 	state->dts_options[option] = val;
14924 
14925 	return (0);
14926 }
14927 
14928 static void
14929 dtrace_state_destroy(dtrace_state_t *state)
14930 {
14931 	dtrace_ecb_t *ecb;
14932 	dtrace_vstate_t *vstate = &state->dts_vstate;
14933 #if defined(sun)
14934 	minor_t minor = getminor(state->dts_dev);
14935 #endif
14936 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14937 	dtrace_speculation_t *spec = state->dts_speculations;
14938 	int nspec = state->dts_nspeculations;
14939 	uint32_t match;
14940 
14941 	ASSERT(MUTEX_HELD(&dtrace_lock));
14942 	ASSERT(MUTEX_HELD(&cpu_lock));
14943 
14944 	/*
14945 	 * First, retract any retained enablings for this state.
14946 	 */
14947 	dtrace_enabling_retract(state);
14948 	ASSERT(state->dts_nretained == 0);
14949 
14950 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14951 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14952 		/*
14953 		 * We have managed to come into dtrace_state_destroy() on a
14954 		 * hot enabling -- almost certainly because of a disorderly
14955 		 * shutdown of a consumer.  (That is, a consumer that is
14956 		 * exiting without having called dtrace_stop().) In this case,
14957 		 * we're going to set our activity to be KILLED, and then
14958 		 * issue a sync to be sure that everyone is out of probe
14959 		 * context before we start blowing away ECBs.
14960 		 */
14961 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14962 		dtrace_sync();
14963 	}
14964 
14965 	/*
14966 	 * Release the credential hold we took in dtrace_state_create().
14967 	 */
14968 	if (state->dts_cred.dcr_cred != NULL)
14969 		crfree(state->dts_cred.dcr_cred);
14970 
14971 	/*
14972 	 * Now we can safely disable and destroy any enabled probes.  Because
14973 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14974 	 * (especially if they're all enabled), we take two passes through the
14975 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14976 	 * in the second we disable whatever is left over.
14977 	 */
14978 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14979 		for (i = 0; i < state->dts_necbs; i++) {
14980 			if ((ecb = state->dts_ecbs[i]) == NULL)
14981 				continue;
14982 
14983 			if (match && ecb->dte_probe != NULL) {
14984 				dtrace_probe_t *probe = ecb->dte_probe;
14985 				dtrace_provider_t *prov = probe->dtpr_provider;
14986 
14987 				if (!(prov->dtpv_priv.dtpp_flags & match))
14988 					continue;
14989 			}
14990 
14991 			dtrace_ecb_disable(ecb);
14992 			dtrace_ecb_destroy(ecb);
14993 		}
14994 
14995 		if (!match)
14996 			break;
14997 	}
14998 
14999 	/*
15000 	 * Before we free the buffers, perform one more sync to assure that
15001 	 * every CPU is out of probe context.
15002 	 */
15003 	dtrace_sync();
15004 
15005 	dtrace_buffer_free(state->dts_buffer);
15006 	dtrace_buffer_free(state->dts_aggbuffer);
15007 
15008 	for (i = 0; i < nspec; i++)
15009 		dtrace_buffer_free(spec[i].dtsp_buffer);
15010 
15011 #if defined(sun)
15012 	if (state->dts_cleaner != CYCLIC_NONE)
15013 		cyclic_remove(state->dts_cleaner);
15014 
15015 	if (state->dts_deadman != CYCLIC_NONE)
15016 		cyclic_remove(state->dts_deadman);
15017 #else
15018 	callout_stop(&state->dts_cleaner);
15019 	callout_drain(&state->dts_cleaner);
15020 	callout_stop(&state->dts_deadman);
15021 	callout_drain(&state->dts_deadman);
15022 #endif
15023 
15024 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
15025 	dtrace_vstate_fini(vstate);
15026 	if (state->dts_ecbs != NULL)
15027 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15028 
15029 	if (state->dts_aggregations != NULL) {
15030 #ifdef DEBUG
15031 		for (i = 0; i < state->dts_naggregations; i++)
15032 			ASSERT(state->dts_aggregations[i] == NULL);
15033 #endif
15034 		ASSERT(state->dts_naggregations > 0);
15035 		kmem_free(state->dts_aggregations,
15036 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15037 	}
15038 
15039 	kmem_free(state->dts_buffer, bufsize);
15040 	kmem_free(state->dts_aggbuffer, bufsize);
15041 
15042 	for (i = 0; i < nspec; i++)
15043 		kmem_free(spec[i].dtsp_buffer, bufsize);
15044 
15045 	if (spec != NULL)
15046 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15047 
15048 	dtrace_format_destroy(state);
15049 
15050 	if (state->dts_aggid_arena != NULL) {
15051 #if defined(sun)
15052 		vmem_destroy(state->dts_aggid_arena);
15053 #else
15054 		delete_unrhdr(state->dts_aggid_arena);
15055 #endif
15056 		state->dts_aggid_arena = NULL;
15057 	}
15058 #if defined(sun)
15059 	ddi_soft_state_free(dtrace_softstate, minor);
15060 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15061 #endif
15062 }
15063 
15064 /*
15065  * DTrace Anonymous Enabling Functions
15066  */
15067 static dtrace_state_t *
15068 dtrace_anon_grab(void)
15069 {
15070 	dtrace_state_t *state;
15071 
15072 	ASSERT(MUTEX_HELD(&dtrace_lock));
15073 
15074 	if ((state = dtrace_anon.dta_state) == NULL) {
15075 		ASSERT(dtrace_anon.dta_enabling == NULL);
15076 		return (NULL);
15077 	}
15078 
15079 	ASSERT(dtrace_anon.dta_enabling != NULL);
15080 	ASSERT(dtrace_retained != NULL);
15081 
15082 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15083 	dtrace_anon.dta_enabling = NULL;
15084 	dtrace_anon.dta_state = NULL;
15085 
15086 	return (state);
15087 }
15088 
15089 static void
15090 dtrace_anon_property(void)
15091 {
15092 	int i, rv;
15093 	dtrace_state_t *state;
15094 	dof_hdr_t *dof;
15095 	char c[32];		/* enough for "dof-data-" + digits */
15096 
15097 	ASSERT(MUTEX_HELD(&dtrace_lock));
15098 	ASSERT(MUTEX_HELD(&cpu_lock));
15099 
15100 	for (i = 0; ; i++) {
15101 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15102 
15103 		dtrace_err_verbose = 1;
15104 
15105 		if ((dof = dtrace_dof_property(c)) == NULL) {
15106 			dtrace_err_verbose = 0;
15107 			break;
15108 		}
15109 
15110 #if defined(sun)
15111 		/*
15112 		 * We want to create anonymous state, so we need to transition
15113 		 * the kernel debugger to indicate that DTrace is active.  If
15114 		 * this fails (e.g. because the debugger has modified text in
15115 		 * some way), we won't continue with the processing.
15116 		 */
15117 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15118 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15119 			    "enabling ignored.");
15120 			dtrace_dof_destroy(dof);
15121 			break;
15122 		}
15123 #endif
15124 
15125 		/*
15126 		 * If we haven't allocated an anonymous state, we'll do so now.
15127 		 */
15128 		if ((state = dtrace_anon.dta_state) == NULL) {
15129 #if defined(sun)
15130 			state = dtrace_state_create(NULL, NULL);
15131 #else
15132 			state = dtrace_state_create(NULL);
15133 #endif
15134 			dtrace_anon.dta_state = state;
15135 
15136 			if (state == NULL) {
15137 				/*
15138 				 * This basically shouldn't happen:  the only
15139 				 * failure mode from dtrace_state_create() is a
15140 				 * failure of ddi_soft_state_zalloc() that
15141 				 * itself should never happen.  Still, the
15142 				 * interface allows for a failure mode, and
15143 				 * we want to fail as gracefully as possible:
15144 				 * we'll emit an error message and cease
15145 				 * processing anonymous state in this case.
15146 				 */
15147 				cmn_err(CE_WARN, "failed to create "
15148 				    "anonymous state");
15149 				dtrace_dof_destroy(dof);
15150 				break;
15151 			}
15152 		}
15153 
15154 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15155 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
15156 
15157 		if (rv == 0)
15158 			rv = dtrace_dof_options(dof, state);
15159 
15160 		dtrace_err_verbose = 0;
15161 		dtrace_dof_destroy(dof);
15162 
15163 		if (rv != 0) {
15164 			/*
15165 			 * This is malformed DOF; chuck any anonymous state
15166 			 * that we created.
15167 			 */
15168 			ASSERT(dtrace_anon.dta_enabling == NULL);
15169 			dtrace_state_destroy(state);
15170 			dtrace_anon.dta_state = NULL;
15171 			break;
15172 		}
15173 
15174 		ASSERT(dtrace_anon.dta_enabling != NULL);
15175 	}
15176 
15177 	if (dtrace_anon.dta_enabling != NULL) {
15178 		int rval;
15179 
15180 		/*
15181 		 * dtrace_enabling_retain() can only fail because we are
15182 		 * trying to retain more enablings than are allowed -- but
15183 		 * we only have one anonymous enabling, and we are guaranteed
15184 		 * to be allowed at least one retained enabling; we assert
15185 		 * that dtrace_enabling_retain() returns success.
15186 		 */
15187 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15188 		ASSERT(rval == 0);
15189 
15190 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15191 	}
15192 }
15193 
15194 /*
15195  * DTrace Helper Functions
15196  */
15197 static void
15198 dtrace_helper_trace(dtrace_helper_action_t *helper,
15199     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15200 {
15201 	uint32_t size, next, nnext, i;
15202 	dtrace_helptrace_t *ent;
15203 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15204 
15205 	if (!dtrace_helptrace_enabled)
15206 		return;
15207 
15208 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15209 
15210 	/*
15211 	 * What would a tracing framework be without its own tracing
15212 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15213 	 */
15214 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15215 	    sizeof (uint64_t) - sizeof (uint64_t);
15216 
15217 	/*
15218 	 * Iterate until we can allocate a slot in the trace buffer.
15219 	 */
15220 	do {
15221 		next = dtrace_helptrace_next;
15222 
15223 		if (next + size < dtrace_helptrace_bufsize) {
15224 			nnext = next + size;
15225 		} else {
15226 			nnext = size;
15227 		}
15228 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15229 
15230 	/*
15231 	 * We have our slot; fill it in.
15232 	 */
15233 	if (nnext == size)
15234 		next = 0;
15235 
15236 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
15237 	ent->dtht_helper = helper;
15238 	ent->dtht_where = where;
15239 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15240 
15241 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15242 	    mstate->dtms_fltoffs : -1;
15243 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15244 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15245 
15246 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15247 		dtrace_statvar_t *svar;
15248 
15249 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15250 			continue;
15251 
15252 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15253 		ent->dtht_locals[i] =
15254 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15255 	}
15256 }
15257 
15258 static uint64_t
15259 dtrace_helper(int which, dtrace_mstate_t *mstate,
15260     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15261 {
15262 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15263 	uint64_t sarg0 = mstate->dtms_arg[0];
15264 	uint64_t sarg1 = mstate->dtms_arg[1];
15265 	uint64_t rval = 0;
15266 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15267 	dtrace_helper_action_t *helper;
15268 	dtrace_vstate_t *vstate;
15269 	dtrace_difo_t *pred;
15270 	int i, trace = dtrace_helptrace_enabled;
15271 
15272 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15273 
15274 	if (helpers == NULL)
15275 		return (0);
15276 
15277 	if ((helper = helpers->dthps_actions[which]) == NULL)
15278 		return (0);
15279 
15280 	vstate = &helpers->dthps_vstate;
15281 	mstate->dtms_arg[0] = arg0;
15282 	mstate->dtms_arg[1] = arg1;
15283 
15284 	/*
15285 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15286 	 * we'll call the corresponding actions.  Note that the below calls
15287 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15288 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15289 	 * the stored DIF offset with its own (which is the desired behavior).
15290 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15291 	 * from machine state; this is okay, too.
15292 	 */
15293 	for (; helper != NULL; helper = helper->dtha_next) {
15294 		if ((pred = helper->dtha_predicate) != NULL) {
15295 			if (trace)
15296 				dtrace_helper_trace(helper, mstate, vstate, 0);
15297 
15298 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15299 				goto next;
15300 
15301 			if (*flags & CPU_DTRACE_FAULT)
15302 				goto err;
15303 		}
15304 
15305 		for (i = 0; i < helper->dtha_nactions; i++) {
15306 			if (trace)
15307 				dtrace_helper_trace(helper,
15308 				    mstate, vstate, i + 1);
15309 
15310 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15311 			    mstate, vstate, state);
15312 
15313 			if (*flags & CPU_DTRACE_FAULT)
15314 				goto err;
15315 		}
15316 
15317 next:
15318 		if (trace)
15319 			dtrace_helper_trace(helper, mstate, vstate,
15320 			    DTRACE_HELPTRACE_NEXT);
15321 	}
15322 
15323 	if (trace)
15324 		dtrace_helper_trace(helper, mstate, vstate,
15325 		    DTRACE_HELPTRACE_DONE);
15326 
15327 	/*
15328 	 * Restore the arg0 that we saved upon entry.
15329 	 */
15330 	mstate->dtms_arg[0] = sarg0;
15331 	mstate->dtms_arg[1] = sarg1;
15332 
15333 	return (rval);
15334 
15335 err:
15336 	if (trace)
15337 		dtrace_helper_trace(helper, mstate, vstate,
15338 		    DTRACE_HELPTRACE_ERR);
15339 
15340 	/*
15341 	 * Restore the arg0 that we saved upon entry.
15342 	 */
15343 	mstate->dtms_arg[0] = sarg0;
15344 	mstate->dtms_arg[1] = sarg1;
15345 
15346 	return (0);
15347 }
15348 
15349 static void
15350 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15351     dtrace_vstate_t *vstate)
15352 {
15353 	int i;
15354 
15355 	if (helper->dtha_predicate != NULL)
15356 		dtrace_difo_release(helper->dtha_predicate, vstate);
15357 
15358 	for (i = 0; i < helper->dtha_nactions; i++) {
15359 		ASSERT(helper->dtha_actions[i] != NULL);
15360 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15361 	}
15362 
15363 	kmem_free(helper->dtha_actions,
15364 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15365 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15366 }
15367 
15368 static int
15369 dtrace_helper_destroygen(int gen)
15370 {
15371 	proc_t *p = curproc;
15372 	dtrace_helpers_t *help = p->p_dtrace_helpers;
15373 	dtrace_vstate_t *vstate;
15374 	int i;
15375 
15376 	ASSERT(MUTEX_HELD(&dtrace_lock));
15377 
15378 	if (help == NULL || gen > help->dthps_generation)
15379 		return (EINVAL);
15380 
15381 	vstate = &help->dthps_vstate;
15382 
15383 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15384 		dtrace_helper_action_t *last = NULL, *h, *next;
15385 
15386 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15387 			next = h->dtha_next;
15388 
15389 			if (h->dtha_generation == gen) {
15390 				if (last != NULL) {
15391 					last->dtha_next = next;
15392 				} else {
15393 					help->dthps_actions[i] = next;
15394 				}
15395 
15396 				dtrace_helper_action_destroy(h, vstate);
15397 			} else {
15398 				last = h;
15399 			}
15400 		}
15401 	}
15402 
15403 	/*
15404 	 * Interate until we've cleared out all helper providers with the
15405 	 * given generation number.
15406 	 */
15407 	for (;;) {
15408 		dtrace_helper_provider_t *prov;
15409 
15410 		/*
15411 		 * Look for a helper provider with the right generation. We
15412 		 * have to start back at the beginning of the list each time
15413 		 * because we drop dtrace_lock. It's unlikely that we'll make
15414 		 * more than two passes.
15415 		 */
15416 		for (i = 0; i < help->dthps_nprovs; i++) {
15417 			prov = help->dthps_provs[i];
15418 
15419 			if (prov->dthp_generation == gen)
15420 				break;
15421 		}
15422 
15423 		/*
15424 		 * If there were no matches, we're done.
15425 		 */
15426 		if (i == help->dthps_nprovs)
15427 			break;
15428 
15429 		/*
15430 		 * Move the last helper provider into this slot.
15431 		 */
15432 		help->dthps_nprovs--;
15433 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15434 		help->dthps_provs[help->dthps_nprovs] = NULL;
15435 
15436 		mutex_exit(&dtrace_lock);
15437 
15438 		/*
15439 		 * If we have a meta provider, remove this helper provider.
15440 		 */
15441 		mutex_enter(&dtrace_meta_lock);
15442 		if (dtrace_meta_pid != NULL) {
15443 			ASSERT(dtrace_deferred_pid == NULL);
15444 			dtrace_helper_provider_remove(&prov->dthp_prov,
15445 			    p->p_pid);
15446 		}
15447 		mutex_exit(&dtrace_meta_lock);
15448 
15449 		dtrace_helper_provider_destroy(prov);
15450 
15451 		mutex_enter(&dtrace_lock);
15452 	}
15453 
15454 	return (0);
15455 }
15456 
15457 static int
15458 dtrace_helper_validate(dtrace_helper_action_t *helper)
15459 {
15460 	int err = 0, i;
15461 	dtrace_difo_t *dp;
15462 
15463 	if ((dp = helper->dtha_predicate) != NULL)
15464 		err += dtrace_difo_validate_helper(dp);
15465 
15466 	for (i = 0; i < helper->dtha_nactions; i++)
15467 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15468 
15469 	return (err == 0);
15470 }
15471 
15472 static int
15473 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
15474 {
15475 	dtrace_helpers_t *help;
15476 	dtrace_helper_action_t *helper, *last;
15477 	dtrace_actdesc_t *act;
15478 	dtrace_vstate_t *vstate;
15479 	dtrace_predicate_t *pred;
15480 	int count = 0, nactions = 0, i;
15481 
15482 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15483 		return (EINVAL);
15484 
15485 	help = curproc->p_dtrace_helpers;
15486 	last = help->dthps_actions[which];
15487 	vstate = &help->dthps_vstate;
15488 
15489 	for (count = 0; last != NULL; last = last->dtha_next) {
15490 		count++;
15491 		if (last->dtha_next == NULL)
15492 			break;
15493 	}
15494 
15495 	/*
15496 	 * If we already have dtrace_helper_actions_max helper actions for this
15497 	 * helper action type, we'll refuse to add a new one.
15498 	 */
15499 	if (count >= dtrace_helper_actions_max)
15500 		return (ENOSPC);
15501 
15502 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15503 	helper->dtha_generation = help->dthps_generation;
15504 
15505 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15506 		ASSERT(pred->dtp_difo != NULL);
15507 		dtrace_difo_hold(pred->dtp_difo);
15508 		helper->dtha_predicate = pred->dtp_difo;
15509 	}
15510 
15511 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15512 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15513 			goto err;
15514 
15515 		if (act->dtad_difo == NULL)
15516 			goto err;
15517 
15518 		nactions++;
15519 	}
15520 
15521 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15522 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15523 
15524 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15525 		dtrace_difo_hold(act->dtad_difo);
15526 		helper->dtha_actions[i++] = act->dtad_difo;
15527 	}
15528 
15529 	if (!dtrace_helper_validate(helper))
15530 		goto err;
15531 
15532 	if (last == NULL) {
15533 		help->dthps_actions[which] = helper;
15534 	} else {
15535 		last->dtha_next = helper;
15536 	}
15537 
15538 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15539 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15540 		dtrace_helptrace_next = 0;
15541 	}
15542 
15543 	return (0);
15544 err:
15545 	dtrace_helper_action_destroy(helper, vstate);
15546 	return (EINVAL);
15547 }
15548 
15549 static void
15550 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15551     dof_helper_t *dofhp)
15552 {
15553 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15554 
15555 	mutex_enter(&dtrace_meta_lock);
15556 	mutex_enter(&dtrace_lock);
15557 
15558 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15559 		/*
15560 		 * If the dtrace module is loaded but not attached, or if
15561 		 * there aren't isn't a meta provider registered to deal with
15562 		 * these provider descriptions, we need to postpone creating
15563 		 * the actual providers until later.
15564 		 */
15565 
15566 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15567 		    dtrace_deferred_pid != help) {
15568 			help->dthps_deferred = 1;
15569 			help->dthps_pid = p->p_pid;
15570 			help->dthps_next = dtrace_deferred_pid;
15571 			help->dthps_prev = NULL;
15572 			if (dtrace_deferred_pid != NULL)
15573 				dtrace_deferred_pid->dthps_prev = help;
15574 			dtrace_deferred_pid = help;
15575 		}
15576 
15577 		mutex_exit(&dtrace_lock);
15578 
15579 	} else if (dofhp != NULL) {
15580 		/*
15581 		 * If the dtrace module is loaded and we have a particular
15582 		 * helper provider description, pass that off to the
15583 		 * meta provider.
15584 		 */
15585 
15586 		mutex_exit(&dtrace_lock);
15587 
15588 		dtrace_helper_provide(dofhp, p->p_pid);
15589 
15590 	} else {
15591 		/*
15592 		 * Otherwise, just pass all the helper provider descriptions
15593 		 * off to the meta provider.
15594 		 */
15595 
15596 		int i;
15597 		mutex_exit(&dtrace_lock);
15598 
15599 		for (i = 0; i < help->dthps_nprovs; i++) {
15600 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15601 			    p->p_pid);
15602 		}
15603 	}
15604 
15605 	mutex_exit(&dtrace_meta_lock);
15606 }
15607 
15608 static int
15609 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15610 {
15611 	dtrace_helpers_t *help;
15612 	dtrace_helper_provider_t *hprov, **tmp_provs;
15613 	uint_t tmp_maxprovs, i;
15614 
15615 	ASSERT(MUTEX_HELD(&dtrace_lock));
15616 
15617 	help = curproc->p_dtrace_helpers;
15618 	ASSERT(help != NULL);
15619 
15620 	/*
15621 	 * If we already have dtrace_helper_providers_max helper providers,
15622 	 * we're refuse to add a new one.
15623 	 */
15624 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
15625 		return (ENOSPC);
15626 
15627 	/*
15628 	 * Check to make sure this isn't a duplicate.
15629 	 */
15630 	for (i = 0; i < help->dthps_nprovs; i++) {
15631 		if (dofhp->dofhp_dof ==
15632 		    help->dthps_provs[i]->dthp_prov.dofhp_dof)
15633 			return (EALREADY);
15634 	}
15635 
15636 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15637 	hprov->dthp_prov = *dofhp;
15638 	hprov->dthp_ref = 1;
15639 	hprov->dthp_generation = gen;
15640 
15641 	/*
15642 	 * Allocate a bigger table for helper providers if it's already full.
15643 	 */
15644 	if (help->dthps_maxprovs == help->dthps_nprovs) {
15645 		tmp_maxprovs = help->dthps_maxprovs;
15646 		tmp_provs = help->dthps_provs;
15647 
15648 		if (help->dthps_maxprovs == 0)
15649 			help->dthps_maxprovs = 2;
15650 		else
15651 			help->dthps_maxprovs *= 2;
15652 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
15653 			help->dthps_maxprovs = dtrace_helper_providers_max;
15654 
15655 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15656 
15657 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15658 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15659 
15660 		if (tmp_provs != NULL) {
15661 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15662 			    sizeof (dtrace_helper_provider_t *));
15663 			kmem_free(tmp_provs, tmp_maxprovs *
15664 			    sizeof (dtrace_helper_provider_t *));
15665 		}
15666 	}
15667 
15668 	help->dthps_provs[help->dthps_nprovs] = hprov;
15669 	help->dthps_nprovs++;
15670 
15671 	return (0);
15672 }
15673 
15674 static void
15675 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15676 {
15677 	mutex_enter(&dtrace_lock);
15678 
15679 	if (--hprov->dthp_ref == 0) {
15680 		dof_hdr_t *dof;
15681 		mutex_exit(&dtrace_lock);
15682 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15683 		dtrace_dof_destroy(dof);
15684 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15685 	} else {
15686 		mutex_exit(&dtrace_lock);
15687 	}
15688 }
15689 
15690 static int
15691 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15692 {
15693 	uintptr_t daddr = (uintptr_t)dof;
15694 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15695 	dof_provider_t *provider;
15696 	dof_probe_t *probe;
15697 	uint8_t *arg;
15698 	char *strtab, *typestr;
15699 	dof_stridx_t typeidx;
15700 	size_t typesz;
15701 	uint_t nprobes, j, k;
15702 
15703 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15704 
15705 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15706 		dtrace_dof_error(dof, "misaligned section offset");
15707 		return (-1);
15708 	}
15709 
15710 	/*
15711 	 * The section needs to be large enough to contain the DOF provider
15712 	 * structure appropriate for the given version.
15713 	 */
15714 	if (sec->dofs_size <
15715 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15716 	    offsetof(dof_provider_t, dofpv_prenoffs) :
15717 	    sizeof (dof_provider_t))) {
15718 		dtrace_dof_error(dof, "provider section too small");
15719 		return (-1);
15720 	}
15721 
15722 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15723 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15724 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15725 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15726 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15727 
15728 	if (str_sec == NULL || prb_sec == NULL ||
15729 	    arg_sec == NULL || off_sec == NULL)
15730 		return (-1);
15731 
15732 	enoff_sec = NULL;
15733 
15734 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15735 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
15736 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15737 	    provider->dofpv_prenoffs)) == NULL)
15738 		return (-1);
15739 
15740 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15741 
15742 	if (provider->dofpv_name >= str_sec->dofs_size ||
15743 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15744 		dtrace_dof_error(dof, "invalid provider name");
15745 		return (-1);
15746 	}
15747 
15748 	if (prb_sec->dofs_entsize == 0 ||
15749 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15750 		dtrace_dof_error(dof, "invalid entry size");
15751 		return (-1);
15752 	}
15753 
15754 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15755 		dtrace_dof_error(dof, "misaligned entry size");
15756 		return (-1);
15757 	}
15758 
15759 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15760 		dtrace_dof_error(dof, "invalid entry size");
15761 		return (-1);
15762 	}
15763 
15764 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15765 		dtrace_dof_error(dof, "misaligned section offset");
15766 		return (-1);
15767 	}
15768 
15769 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15770 		dtrace_dof_error(dof, "invalid entry size");
15771 		return (-1);
15772 	}
15773 
15774 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15775 
15776 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15777 
15778 	/*
15779 	 * Take a pass through the probes to check for errors.
15780 	 */
15781 	for (j = 0; j < nprobes; j++) {
15782 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15783 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15784 
15785 		if (probe->dofpr_func >= str_sec->dofs_size) {
15786 			dtrace_dof_error(dof, "invalid function name");
15787 			return (-1);
15788 		}
15789 
15790 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15791 			dtrace_dof_error(dof, "function name too long");
15792 			return (-1);
15793 		}
15794 
15795 		if (probe->dofpr_name >= str_sec->dofs_size ||
15796 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15797 			dtrace_dof_error(dof, "invalid probe name");
15798 			return (-1);
15799 		}
15800 
15801 		/*
15802 		 * The offset count must not wrap the index, and the offsets
15803 		 * must also not overflow the section's data.
15804 		 */
15805 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15806 		    probe->dofpr_offidx ||
15807 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15808 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15809 			dtrace_dof_error(dof, "invalid probe offset");
15810 			return (-1);
15811 		}
15812 
15813 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15814 			/*
15815 			 * If there's no is-enabled offset section, make sure
15816 			 * there aren't any is-enabled offsets. Otherwise
15817 			 * perform the same checks as for probe offsets
15818 			 * (immediately above).
15819 			 */
15820 			if (enoff_sec == NULL) {
15821 				if (probe->dofpr_enoffidx != 0 ||
15822 				    probe->dofpr_nenoffs != 0) {
15823 					dtrace_dof_error(dof, "is-enabled "
15824 					    "offsets with null section");
15825 					return (-1);
15826 				}
15827 			} else if (probe->dofpr_enoffidx +
15828 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15829 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15830 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15831 				dtrace_dof_error(dof, "invalid is-enabled "
15832 				    "offset");
15833 				return (-1);
15834 			}
15835 
15836 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15837 				dtrace_dof_error(dof, "zero probe and "
15838 				    "is-enabled offsets");
15839 				return (-1);
15840 			}
15841 		} else if (probe->dofpr_noffs == 0) {
15842 			dtrace_dof_error(dof, "zero probe offsets");
15843 			return (-1);
15844 		}
15845 
15846 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15847 		    probe->dofpr_argidx ||
15848 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15849 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15850 			dtrace_dof_error(dof, "invalid args");
15851 			return (-1);
15852 		}
15853 
15854 		typeidx = probe->dofpr_nargv;
15855 		typestr = strtab + probe->dofpr_nargv;
15856 		for (k = 0; k < probe->dofpr_nargc; k++) {
15857 			if (typeidx >= str_sec->dofs_size) {
15858 				dtrace_dof_error(dof, "bad "
15859 				    "native argument type");
15860 				return (-1);
15861 			}
15862 
15863 			typesz = strlen(typestr) + 1;
15864 			if (typesz > DTRACE_ARGTYPELEN) {
15865 				dtrace_dof_error(dof, "native "
15866 				    "argument type too long");
15867 				return (-1);
15868 			}
15869 			typeidx += typesz;
15870 			typestr += typesz;
15871 		}
15872 
15873 		typeidx = probe->dofpr_xargv;
15874 		typestr = strtab + probe->dofpr_xargv;
15875 		for (k = 0; k < probe->dofpr_xargc; k++) {
15876 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15877 				dtrace_dof_error(dof, "bad "
15878 				    "native argument index");
15879 				return (-1);
15880 			}
15881 
15882 			if (typeidx >= str_sec->dofs_size) {
15883 				dtrace_dof_error(dof, "bad "
15884 				    "translated argument type");
15885 				return (-1);
15886 			}
15887 
15888 			typesz = strlen(typestr) + 1;
15889 			if (typesz > DTRACE_ARGTYPELEN) {
15890 				dtrace_dof_error(dof, "translated argument "
15891 				    "type too long");
15892 				return (-1);
15893 			}
15894 
15895 			typeidx += typesz;
15896 			typestr += typesz;
15897 		}
15898 	}
15899 
15900 	return (0);
15901 }
15902 
15903 static int
15904 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15905 {
15906 	dtrace_helpers_t *help;
15907 	dtrace_vstate_t *vstate;
15908 	dtrace_enabling_t *enab = NULL;
15909 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15910 	uintptr_t daddr = (uintptr_t)dof;
15911 
15912 	ASSERT(MUTEX_HELD(&dtrace_lock));
15913 
15914 	if ((help = curproc->p_dtrace_helpers) == NULL)
15915 		help = dtrace_helpers_create(curproc);
15916 
15917 	vstate = &help->dthps_vstate;
15918 
15919 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15920 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15921 		dtrace_dof_destroy(dof);
15922 		return (rv);
15923 	}
15924 
15925 	/*
15926 	 * Look for helper providers and validate their descriptions.
15927 	 */
15928 	if (dhp != NULL) {
15929 		for (i = 0; i < dof->dofh_secnum; i++) {
15930 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15931 			    dof->dofh_secoff + i * dof->dofh_secsize);
15932 
15933 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15934 				continue;
15935 
15936 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15937 				dtrace_enabling_destroy(enab);
15938 				dtrace_dof_destroy(dof);
15939 				return (-1);
15940 			}
15941 
15942 			nprovs++;
15943 		}
15944 	}
15945 
15946 	/*
15947 	 * Now we need to walk through the ECB descriptions in the enabling.
15948 	 */
15949 	for (i = 0; i < enab->dten_ndesc; i++) {
15950 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15951 		dtrace_probedesc_t *desc = &ep->dted_probe;
15952 
15953 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15954 			continue;
15955 
15956 		if (strcmp(desc->dtpd_mod, "helper") != 0)
15957 			continue;
15958 
15959 		if (strcmp(desc->dtpd_func, "ustack") != 0)
15960 			continue;
15961 
15962 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15963 		    ep)) != 0) {
15964 			/*
15965 			 * Adding this helper action failed -- we are now going
15966 			 * to rip out the entire generation and return failure.
15967 			 */
15968 			(void) dtrace_helper_destroygen(help->dthps_generation);
15969 			dtrace_enabling_destroy(enab);
15970 			dtrace_dof_destroy(dof);
15971 			return (-1);
15972 		}
15973 
15974 		nhelpers++;
15975 	}
15976 
15977 	if (nhelpers < enab->dten_ndesc)
15978 		dtrace_dof_error(dof, "unmatched helpers");
15979 
15980 	gen = help->dthps_generation++;
15981 	dtrace_enabling_destroy(enab);
15982 
15983 	if (dhp != NULL && nprovs > 0) {
15984 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15985 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
15986 			mutex_exit(&dtrace_lock);
15987 			dtrace_helper_provider_register(curproc, help, dhp);
15988 			mutex_enter(&dtrace_lock);
15989 
15990 			destroy = 0;
15991 		}
15992 	}
15993 
15994 	if (destroy)
15995 		dtrace_dof_destroy(dof);
15996 
15997 	return (gen);
15998 }
15999 
16000 static dtrace_helpers_t *
16001 dtrace_helpers_create(proc_t *p)
16002 {
16003 	dtrace_helpers_t *help;
16004 
16005 	ASSERT(MUTEX_HELD(&dtrace_lock));
16006 	ASSERT(p->p_dtrace_helpers == NULL);
16007 
16008 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16009 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16010 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16011 
16012 	p->p_dtrace_helpers = help;
16013 	dtrace_helpers++;
16014 
16015 	return (help);
16016 }
16017 
16018 #if defined(sun)
16019 static
16020 #endif
16021 void
16022 dtrace_helpers_destroy(proc_t *p)
16023 {
16024 	dtrace_helpers_t *help;
16025 	dtrace_vstate_t *vstate;
16026 #if defined(sun)
16027 	proc_t *p = curproc;
16028 #endif
16029 	int i;
16030 
16031 	mutex_enter(&dtrace_lock);
16032 
16033 	ASSERT(p->p_dtrace_helpers != NULL);
16034 	ASSERT(dtrace_helpers > 0);
16035 
16036 	help = p->p_dtrace_helpers;
16037 	vstate = &help->dthps_vstate;
16038 
16039 	/*
16040 	 * We're now going to lose the help from this process.
16041 	 */
16042 	p->p_dtrace_helpers = NULL;
16043 	dtrace_sync();
16044 
16045 	/*
16046 	 * Destory the helper actions.
16047 	 */
16048 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16049 		dtrace_helper_action_t *h, *next;
16050 
16051 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16052 			next = h->dtha_next;
16053 			dtrace_helper_action_destroy(h, vstate);
16054 			h = next;
16055 		}
16056 	}
16057 
16058 	mutex_exit(&dtrace_lock);
16059 
16060 	/*
16061 	 * Destroy the helper providers.
16062 	 */
16063 	if (help->dthps_maxprovs > 0) {
16064 		mutex_enter(&dtrace_meta_lock);
16065 		if (dtrace_meta_pid != NULL) {
16066 			ASSERT(dtrace_deferred_pid == NULL);
16067 
16068 			for (i = 0; i < help->dthps_nprovs; i++) {
16069 				dtrace_helper_provider_remove(
16070 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
16071 			}
16072 		} else {
16073 			mutex_enter(&dtrace_lock);
16074 			ASSERT(help->dthps_deferred == 0 ||
16075 			    help->dthps_next != NULL ||
16076 			    help->dthps_prev != NULL ||
16077 			    help == dtrace_deferred_pid);
16078 
16079 			/*
16080 			 * Remove the helper from the deferred list.
16081 			 */
16082 			if (help->dthps_next != NULL)
16083 				help->dthps_next->dthps_prev = help->dthps_prev;
16084 			if (help->dthps_prev != NULL)
16085 				help->dthps_prev->dthps_next = help->dthps_next;
16086 			if (dtrace_deferred_pid == help) {
16087 				dtrace_deferred_pid = help->dthps_next;
16088 				ASSERT(help->dthps_prev == NULL);
16089 			}
16090 
16091 			mutex_exit(&dtrace_lock);
16092 		}
16093 
16094 		mutex_exit(&dtrace_meta_lock);
16095 
16096 		for (i = 0; i < help->dthps_nprovs; i++) {
16097 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16098 		}
16099 
16100 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16101 		    sizeof (dtrace_helper_provider_t *));
16102 	}
16103 
16104 	mutex_enter(&dtrace_lock);
16105 
16106 	dtrace_vstate_fini(&help->dthps_vstate);
16107 	kmem_free(help->dthps_actions,
16108 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16109 	kmem_free(help, sizeof (dtrace_helpers_t));
16110 
16111 	--dtrace_helpers;
16112 	mutex_exit(&dtrace_lock);
16113 }
16114 
16115 #if defined(sun)
16116 static
16117 #endif
16118 void
16119 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16120 {
16121 	dtrace_helpers_t *help, *newhelp;
16122 	dtrace_helper_action_t *helper, *new, *last;
16123 	dtrace_difo_t *dp;
16124 	dtrace_vstate_t *vstate;
16125 	int i, j, sz, hasprovs = 0;
16126 
16127 	mutex_enter(&dtrace_lock);
16128 	ASSERT(from->p_dtrace_helpers != NULL);
16129 	ASSERT(dtrace_helpers > 0);
16130 
16131 	help = from->p_dtrace_helpers;
16132 	newhelp = dtrace_helpers_create(to);
16133 	ASSERT(to->p_dtrace_helpers != NULL);
16134 
16135 	newhelp->dthps_generation = help->dthps_generation;
16136 	vstate = &newhelp->dthps_vstate;
16137 
16138 	/*
16139 	 * Duplicate the helper actions.
16140 	 */
16141 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16142 		if ((helper = help->dthps_actions[i]) == NULL)
16143 			continue;
16144 
16145 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16146 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16147 			    KM_SLEEP);
16148 			new->dtha_generation = helper->dtha_generation;
16149 
16150 			if ((dp = helper->dtha_predicate) != NULL) {
16151 				dp = dtrace_difo_duplicate(dp, vstate);
16152 				new->dtha_predicate = dp;
16153 			}
16154 
16155 			new->dtha_nactions = helper->dtha_nactions;
16156 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16157 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16158 
16159 			for (j = 0; j < new->dtha_nactions; j++) {
16160 				dtrace_difo_t *dp = helper->dtha_actions[j];
16161 
16162 				ASSERT(dp != NULL);
16163 				dp = dtrace_difo_duplicate(dp, vstate);
16164 				new->dtha_actions[j] = dp;
16165 			}
16166 
16167 			if (last != NULL) {
16168 				last->dtha_next = new;
16169 			} else {
16170 				newhelp->dthps_actions[i] = new;
16171 			}
16172 
16173 			last = new;
16174 		}
16175 	}
16176 
16177 	/*
16178 	 * Duplicate the helper providers and register them with the
16179 	 * DTrace framework.
16180 	 */
16181 	if (help->dthps_nprovs > 0) {
16182 		newhelp->dthps_nprovs = help->dthps_nprovs;
16183 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16184 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16185 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16186 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16187 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16188 			newhelp->dthps_provs[i]->dthp_ref++;
16189 		}
16190 
16191 		hasprovs = 1;
16192 	}
16193 
16194 	mutex_exit(&dtrace_lock);
16195 
16196 	if (hasprovs)
16197 		dtrace_helper_provider_register(to, newhelp, NULL);
16198 }
16199 
16200 /*
16201  * DTrace Hook Functions
16202  */
16203 static void
16204 dtrace_module_loaded(modctl_t *ctl)
16205 {
16206 	dtrace_provider_t *prv;
16207 
16208 	mutex_enter(&dtrace_provider_lock);
16209 #if defined(sun)
16210 	mutex_enter(&mod_lock);
16211 #endif
16212 
16213 #if defined(sun)
16214 	ASSERT(ctl->mod_busy);
16215 #endif
16216 
16217 	/*
16218 	 * We're going to call each providers per-module provide operation
16219 	 * specifying only this module.
16220 	 */
16221 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16222 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16223 
16224 #if defined(sun)
16225 	mutex_exit(&mod_lock);
16226 #endif
16227 	mutex_exit(&dtrace_provider_lock);
16228 
16229 	/*
16230 	 * If we have any retained enablings, we need to match against them.
16231 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16232 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16233 	 * module.  (In particular, this happens when loading scheduling
16234 	 * classes.)  So if we have any retained enablings, we need to dispatch
16235 	 * our task queue to do the match for us.
16236 	 */
16237 	mutex_enter(&dtrace_lock);
16238 
16239 	if (dtrace_retained == NULL) {
16240 		mutex_exit(&dtrace_lock);
16241 		return;
16242 	}
16243 
16244 	(void) taskq_dispatch(dtrace_taskq,
16245 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16246 
16247 	mutex_exit(&dtrace_lock);
16248 
16249 	/*
16250 	 * And now, for a little heuristic sleaze:  in general, we want to
16251 	 * match modules as soon as they load.  However, we cannot guarantee
16252 	 * this, because it would lead us to the lock ordering violation
16253 	 * outlined above.  The common case, of course, is that cpu_lock is
16254 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
16255 	 * long enough for the task queue to do its work.  If it's not, it's
16256 	 * not a serious problem -- it just means that the module that we
16257 	 * just loaded may not be immediately instrumentable.
16258 	 */
16259 	delay(1);
16260 }
16261 
16262 static void
16263 #if defined(sun)
16264 dtrace_module_unloaded(modctl_t *ctl)
16265 #else
16266 dtrace_module_unloaded(modctl_t *ctl, int *error)
16267 #endif
16268 {
16269 	dtrace_probe_t template, *probe, *first, *next;
16270 	dtrace_provider_t *prov;
16271 #if !defined(sun)
16272 	char modname[DTRACE_MODNAMELEN];
16273 	size_t len;
16274 #endif
16275 
16276 #if defined(sun)
16277 	template.dtpr_mod = ctl->mod_modname;
16278 #else
16279 	/* Handle the fact that ctl->filename may end in ".ko". */
16280 	strlcpy(modname, ctl->filename, sizeof(modname));
16281 	len = strlen(ctl->filename);
16282 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16283 		modname[len - 3] = '\0';
16284 	template.dtpr_mod = modname;
16285 #endif
16286 
16287 	mutex_enter(&dtrace_provider_lock);
16288 #if defined(sun)
16289 	mutex_enter(&mod_lock);
16290 #endif
16291 	mutex_enter(&dtrace_lock);
16292 
16293 #if !defined(sun)
16294 	if (ctl->nenabled > 0) {
16295 		/* Don't allow unloads if a probe is enabled. */
16296 		mutex_exit(&dtrace_provider_lock);
16297 		mutex_exit(&dtrace_lock);
16298 		*error = -1;
16299 		printf(
16300 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
16301 		return;
16302 	}
16303 #endif
16304 
16305 	if (dtrace_bymod == NULL) {
16306 		/*
16307 		 * The DTrace module is loaded (obviously) but not attached;
16308 		 * we don't have any work to do.
16309 		 */
16310 		mutex_exit(&dtrace_provider_lock);
16311 #if defined(sun)
16312 		mutex_exit(&mod_lock);
16313 #endif
16314 		mutex_exit(&dtrace_lock);
16315 		return;
16316 	}
16317 
16318 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16319 	    probe != NULL; probe = probe->dtpr_nextmod) {
16320 		if (probe->dtpr_ecb != NULL) {
16321 			mutex_exit(&dtrace_provider_lock);
16322 #if defined(sun)
16323 			mutex_exit(&mod_lock);
16324 #endif
16325 			mutex_exit(&dtrace_lock);
16326 
16327 			/*
16328 			 * This shouldn't _actually_ be possible -- we're
16329 			 * unloading a module that has an enabled probe in it.
16330 			 * (It's normally up to the provider to make sure that
16331 			 * this can't happen.)  However, because dtps_enable()
16332 			 * doesn't have a failure mode, there can be an
16333 			 * enable/unload race.  Upshot:  we don't want to
16334 			 * assert, but we're not going to disable the
16335 			 * probe, either.
16336 			 */
16337 			if (dtrace_err_verbose) {
16338 #if defined(sun)
16339 				cmn_err(CE_WARN, "unloaded module '%s' had "
16340 				    "enabled probes", ctl->mod_modname);
16341 #else
16342 				cmn_err(CE_WARN, "unloaded module '%s' had "
16343 				    "enabled probes", modname);
16344 #endif
16345 			}
16346 
16347 			return;
16348 		}
16349 	}
16350 
16351 	probe = first;
16352 
16353 	for (first = NULL; probe != NULL; probe = next) {
16354 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16355 
16356 		dtrace_probes[probe->dtpr_id - 1] = NULL;
16357 
16358 		next = probe->dtpr_nextmod;
16359 		dtrace_hash_remove(dtrace_bymod, probe);
16360 		dtrace_hash_remove(dtrace_byfunc, probe);
16361 		dtrace_hash_remove(dtrace_byname, probe);
16362 
16363 		if (first == NULL) {
16364 			first = probe;
16365 			probe->dtpr_nextmod = NULL;
16366 		} else {
16367 			probe->dtpr_nextmod = first;
16368 			first = probe;
16369 		}
16370 	}
16371 
16372 	/*
16373 	 * We've removed all of the module's probes from the hash chains and
16374 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
16375 	 * everyone has cleared out from any probe array processing.
16376 	 */
16377 	dtrace_sync();
16378 
16379 	for (probe = first; probe != NULL; probe = first) {
16380 		first = probe->dtpr_nextmod;
16381 		prov = probe->dtpr_provider;
16382 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16383 		    probe->dtpr_arg);
16384 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16385 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16386 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16387 #if defined(sun)
16388 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16389 #else
16390 		free_unr(dtrace_arena, probe->dtpr_id);
16391 #endif
16392 		kmem_free(probe, sizeof (dtrace_probe_t));
16393 	}
16394 
16395 	mutex_exit(&dtrace_lock);
16396 #if defined(sun)
16397 	mutex_exit(&mod_lock);
16398 #endif
16399 	mutex_exit(&dtrace_provider_lock);
16400 }
16401 
16402 #if !defined(sun)
16403 static void
16404 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16405 {
16406 
16407 	dtrace_module_loaded(lf);
16408 }
16409 
16410 static void
16411 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16412 {
16413 
16414 	if (*error != 0)
16415 		/* We already have an error, so don't do anything. */
16416 		return;
16417 	dtrace_module_unloaded(lf, error);
16418 }
16419 #endif
16420 
16421 #if defined(sun)
16422 static void
16423 dtrace_suspend(void)
16424 {
16425 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16426 }
16427 
16428 static void
16429 dtrace_resume(void)
16430 {
16431 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16432 }
16433 #endif
16434 
16435 static int
16436 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16437 {
16438 	ASSERT(MUTEX_HELD(&cpu_lock));
16439 	mutex_enter(&dtrace_lock);
16440 
16441 	switch (what) {
16442 	case CPU_CONFIG: {
16443 		dtrace_state_t *state;
16444 		dtrace_optval_t *opt, rs, c;
16445 
16446 		/*
16447 		 * For now, we only allocate a new buffer for anonymous state.
16448 		 */
16449 		if ((state = dtrace_anon.dta_state) == NULL)
16450 			break;
16451 
16452 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16453 			break;
16454 
16455 		opt = state->dts_options;
16456 		c = opt[DTRACEOPT_CPU];
16457 
16458 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16459 			break;
16460 
16461 		/*
16462 		 * Regardless of what the actual policy is, we're going to
16463 		 * temporarily set our resize policy to be manual.  We're
16464 		 * also going to temporarily set our CPU option to denote
16465 		 * the newly configured CPU.
16466 		 */
16467 		rs = opt[DTRACEOPT_BUFRESIZE];
16468 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16469 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16470 
16471 		(void) dtrace_state_buffers(state);
16472 
16473 		opt[DTRACEOPT_BUFRESIZE] = rs;
16474 		opt[DTRACEOPT_CPU] = c;
16475 
16476 		break;
16477 	}
16478 
16479 	case CPU_UNCONFIG:
16480 		/*
16481 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16482 		 * buffer will be freed when the consumer exits.)
16483 		 */
16484 		break;
16485 
16486 	default:
16487 		break;
16488 	}
16489 
16490 	mutex_exit(&dtrace_lock);
16491 	return (0);
16492 }
16493 
16494 #if defined(sun)
16495 static void
16496 dtrace_cpu_setup_initial(processorid_t cpu)
16497 {
16498 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16499 }
16500 #endif
16501 
16502 static void
16503 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16504 {
16505 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16506 		int osize, nsize;
16507 		dtrace_toxrange_t *range;
16508 
16509 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16510 
16511 		if (osize == 0) {
16512 			ASSERT(dtrace_toxrange == NULL);
16513 			ASSERT(dtrace_toxranges_max == 0);
16514 			dtrace_toxranges_max = 1;
16515 		} else {
16516 			dtrace_toxranges_max <<= 1;
16517 		}
16518 
16519 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16520 		range = kmem_zalloc(nsize, KM_SLEEP);
16521 
16522 		if (dtrace_toxrange != NULL) {
16523 			ASSERT(osize != 0);
16524 			bcopy(dtrace_toxrange, range, osize);
16525 			kmem_free(dtrace_toxrange, osize);
16526 		}
16527 
16528 		dtrace_toxrange = range;
16529 	}
16530 
16531 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16532 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16533 
16534 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16535 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16536 	dtrace_toxranges++;
16537 }
16538 
16539 static void
16540 dtrace_getf_barrier()
16541 {
16542 #if defined(sun)
16543 	/*
16544 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
16545 	 * that contain calls to getf(), this routine will be called on every
16546 	 * closef() before either the underlying vnode is released or the
16547 	 * file_t itself is freed.  By the time we are here, it is essential
16548 	 * that the file_t can no longer be accessed from a call to getf()
16549 	 * in probe context -- that assures that a dtrace_sync() can be used
16550 	 * to clear out any enablings referring to the old structures.
16551 	 */
16552 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
16553 	    kcred->cr_zone->zone_dtrace_getf != 0)
16554 		dtrace_sync();
16555 #endif
16556 }
16557 
16558 /*
16559  * DTrace Driver Cookbook Functions
16560  */
16561 #if defined(sun)
16562 /*ARGSUSED*/
16563 static int
16564 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16565 {
16566 	dtrace_provider_id_t id;
16567 	dtrace_state_t *state = NULL;
16568 	dtrace_enabling_t *enab;
16569 
16570 	mutex_enter(&cpu_lock);
16571 	mutex_enter(&dtrace_provider_lock);
16572 	mutex_enter(&dtrace_lock);
16573 
16574 	if (ddi_soft_state_init(&dtrace_softstate,
16575 	    sizeof (dtrace_state_t), 0) != 0) {
16576 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16577 		mutex_exit(&cpu_lock);
16578 		mutex_exit(&dtrace_provider_lock);
16579 		mutex_exit(&dtrace_lock);
16580 		return (DDI_FAILURE);
16581 	}
16582 
16583 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16584 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
16585 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16586 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
16587 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16588 		ddi_remove_minor_node(devi, NULL);
16589 		ddi_soft_state_fini(&dtrace_softstate);
16590 		mutex_exit(&cpu_lock);
16591 		mutex_exit(&dtrace_provider_lock);
16592 		mutex_exit(&dtrace_lock);
16593 		return (DDI_FAILURE);
16594 	}
16595 
16596 	ddi_report_dev(devi);
16597 	dtrace_devi = devi;
16598 
16599 	dtrace_modload = dtrace_module_loaded;
16600 	dtrace_modunload = dtrace_module_unloaded;
16601 	dtrace_cpu_init = dtrace_cpu_setup_initial;
16602 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
16603 	dtrace_helpers_fork = dtrace_helpers_duplicate;
16604 	dtrace_cpustart_init = dtrace_suspend;
16605 	dtrace_cpustart_fini = dtrace_resume;
16606 	dtrace_debugger_init = dtrace_suspend;
16607 	dtrace_debugger_fini = dtrace_resume;
16608 
16609 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16610 
16611 	ASSERT(MUTEX_HELD(&cpu_lock));
16612 
16613 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16614 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16615 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16616 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16617 	    VM_SLEEP | VMC_IDENTIFIER);
16618 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16619 	    1, INT_MAX, 0);
16620 
16621 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16622 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16623 	    NULL, NULL, NULL, NULL, NULL, 0);
16624 
16625 	ASSERT(MUTEX_HELD(&cpu_lock));
16626 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16627 	    offsetof(dtrace_probe_t, dtpr_nextmod),
16628 	    offsetof(dtrace_probe_t, dtpr_prevmod));
16629 
16630 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16631 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
16632 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
16633 
16634 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16635 	    offsetof(dtrace_probe_t, dtpr_nextname),
16636 	    offsetof(dtrace_probe_t, dtpr_prevname));
16637 
16638 	if (dtrace_retain_max < 1) {
16639 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16640 		    "setting to 1", dtrace_retain_max);
16641 		dtrace_retain_max = 1;
16642 	}
16643 
16644 	/*
16645 	 * Now discover our toxic ranges.
16646 	 */
16647 	dtrace_toxic_ranges(dtrace_toxrange_add);
16648 
16649 	/*
16650 	 * Before we register ourselves as a provider to our own framework,
16651 	 * we would like to assert that dtrace_provider is NULL -- but that's
16652 	 * not true if we were loaded as a dependency of a DTrace provider.
16653 	 * Once we've registered, we can assert that dtrace_provider is our
16654 	 * pseudo provider.
16655 	 */
16656 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
16657 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16658 
16659 	ASSERT(dtrace_provider != NULL);
16660 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16661 
16662 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16663 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16664 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16665 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
16666 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16667 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16668 
16669 	dtrace_anon_property();
16670 	mutex_exit(&cpu_lock);
16671 
16672 	/*
16673 	 * If DTrace helper tracing is enabled, we need to allocate the
16674 	 * trace buffer and initialize the values.
16675 	 */
16676 	if (dtrace_helptrace_enabled) {
16677 		ASSERT(dtrace_helptrace_buffer == NULL);
16678 		dtrace_helptrace_buffer =
16679 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16680 		dtrace_helptrace_next = 0;
16681 	}
16682 
16683 	/*
16684 	 * If there are already providers, we must ask them to provide their
16685 	 * probes, and then match any anonymous enabling against them.  Note
16686 	 * that there should be no other retained enablings at this time:
16687 	 * the only retained enablings at this time should be the anonymous
16688 	 * enabling.
16689 	 */
16690 	if (dtrace_anon.dta_enabling != NULL) {
16691 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16692 
16693 		dtrace_enabling_provide(NULL);
16694 		state = dtrace_anon.dta_state;
16695 
16696 		/*
16697 		 * We couldn't hold cpu_lock across the above call to
16698 		 * dtrace_enabling_provide(), but we must hold it to actually
16699 		 * enable the probes.  We have to drop all of our locks, pick
16700 		 * up cpu_lock, and regain our locks before matching the
16701 		 * retained anonymous enabling.
16702 		 */
16703 		mutex_exit(&dtrace_lock);
16704 		mutex_exit(&dtrace_provider_lock);
16705 
16706 		mutex_enter(&cpu_lock);
16707 		mutex_enter(&dtrace_provider_lock);
16708 		mutex_enter(&dtrace_lock);
16709 
16710 		if ((enab = dtrace_anon.dta_enabling) != NULL)
16711 			(void) dtrace_enabling_match(enab, NULL);
16712 
16713 		mutex_exit(&cpu_lock);
16714 	}
16715 
16716 	mutex_exit(&dtrace_lock);
16717 	mutex_exit(&dtrace_provider_lock);
16718 
16719 	if (state != NULL) {
16720 		/*
16721 		 * If we created any anonymous state, set it going now.
16722 		 */
16723 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16724 	}
16725 
16726 	return (DDI_SUCCESS);
16727 }
16728 #endif
16729 
16730 #if !defined(sun)
16731 static void dtrace_dtr(void *);
16732 #endif
16733 
16734 /*ARGSUSED*/
16735 static int
16736 #if defined(sun)
16737 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16738 #else
16739 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16740 #endif
16741 {
16742 	dtrace_state_t *state;
16743 	uint32_t priv;
16744 	uid_t uid;
16745 	zoneid_t zoneid;
16746 
16747 #if defined(sun)
16748 	if (getminor(*devp) == DTRACEMNRN_HELPER)
16749 		return (0);
16750 
16751 	/*
16752 	 * If this wasn't an open with the "helper" minor, then it must be
16753 	 * the "dtrace" minor.
16754 	 */
16755 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
16756 		return (ENXIO);
16757 #else
16758 	cred_t *cred_p = NULL;
16759 	cred_p = dev->si_cred;
16760 
16761 	/*
16762 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
16763 	 * caller lacks sufficient permission to do anything with DTrace.
16764 	 */
16765 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16766 	if (priv == DTRACE_PRIV_NONE) {
16767 #endif
16768 
16769 		return (EACCES);
16770 	}
16771 
16772 	/*
16773 	 * Ask all providers to provide all their probes.
16774 	 */
16775 	mutex_enter(&dtrace_provider_lock);
16776 	dtrace_probe_provide(NULL, NULL);
16777 	mutex_exit(&dtrace_provider_lock);
16778 
16779 	mutex_enter(&cpu_lock);
16780 	mutex_enter(&dtrace_lock);
16781 	dtrace_opens++;
16782 	dtrace_membar_producer();
16783 
16784 #if defined(sun)
16785 	/*
16786 	 * If the kernel debugger is active (that is, if the kernel debugger
16787 	 * modified text in some way), we won't allow the open.
16788 	 */
16789 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16790 		dtrace_opens--;
16791 		mutex_exit(&cpu_lock);
16792 		mutex_exit(&dtrace_lock);
16793 		return (EBUSY);
16794 	}
16795 
16796 	state = dtrace_state_create(devp, cred_p);
16797 #else
16798 	state = dtrace_state_create(dev);
16799 	devfs_set_cdevpriv(state, dtrace_dtr);
16800 #endif
16801 
16802 	mutex_exit(&cpu_lock);
16803 
16804 	if (state == NULL) {
16805 #if defined(sun)
16806 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16807 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16808 #else
16809 		--dtrace_opens;
16810 #endif
16811 		mutex_exit(&dtrace_lock);
16812 		return (EAGAIN);
16813 	}
16814 
16815 	mutex_exit(&dtrace_lock);
16816 
16817 	return (0);
16818 }
16819 
16820 /*ARGSUSED*/
16821 #if defined(sun)
16822 static int
16823 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16824 #else
16825 static void
16826 dtrace_dtr(void *data)
16827 #endif
16828 {
16829 #if defined(sun)
16830 	minor_t minor = getminor(dev);
16831 	dtrace_state_t *state;
16832 
16833 	if (minor == DTRACEMNRN_HELPER)
16834 		return (0);
16835 
16836 	state = ddi_get_soft_state(dtrace_softstate, minor);
16837 #else
16838 	dtrace_state_t *state = data;
16839 #endif
16840 
16841 	mutex_enter(&cpu_lock);
16842 	mutex_enter(&dtrace_lock);
16843 
16844 	if (state != NULL) {
16845 		if (state->dts_anon) {
16846 			/*
16847 			 * There is anonymous state. Destroy that first.
16848 			 */
16849 			ASSERT(dtrace_anon.dta_state == NULL);
16850 			dtrace_state_destroy(state->dts_anon);
16851 		}
16852 
16853 		dtrace_state_destroy(state);
16854 
16855 #if !defined(sun)
16856 		kmem_free(state, 0);
16857 #endif
16858 	}
16859 
16860 	ASSERT(dtrace_opens > 0);
16861 #if defined(sun)
16862 	/*
16863 	 * Only relinquish control of the kernel debugger interface when there
16864 	 * are no consumers and no anonymous enablings.
16865 	 */
16866 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16867 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16868 #else
16869 	--dtrace_opens;
16870 #endif
16871 
16872 	mutex_exit(&dtrace_lock);
16873 	mutex_exit(&cpu_lock);
16874 
16875 #if defined(sun)
16876 	return (0);
16877 #endif
16878 }
16879 
16880 #if defined(sun)
16881 /*ARGSUSED*/
16882 static int
16883 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16884 {
16885 	int rval;
16886 	dof_helper_t help, *dhp = NULL;
16887 
16888 	switch (cmd) {
16889 	case DTRACEHIOC_ADDDOF:
16890 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16891 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
16892 			return (EFAULT);
16893 		}
16894 
16895 		dhp = &help;
16896 		arg = (intptr_t)help.dofhp_dof;
16897 		/*FALLTHROUGH*/
16898 
16899 	case DTRACEHIOC_ADD: {
16900 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16901 
16902 		if (dof == NULL)
16903 			return (rval);
16904 
16905 		mutex_enter(&dtrace_lock);
16906 
16907 		/*
16908 		 * dtrace_helper_slurp() takes responsibility for the dof --
16909 		 * it may free it now or it may save it and free it later.
16910 		 */
16911 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16912 			*rv = rval;
16913 			rval = 0;
16914 		} else {
16915 			rval = EINVAL;
16916 		}
16917 
16918 		mutex_exit(&dtrace_lock);
16919 		return (rval);
16920 	}
16921 
16922 	case DTRACEHIOC_REMOVE: {
16923 		mutex_enter(&dtrace_lock);
16924 		rval = dtrace_helper_destroygen(arg);
16925 		mutex_exit(&dtrace_lock);
16926 
16927 		return (rval);
16928 	}
16929 
16930 	default:
16931 		break;
16932 	}
16933 
16934 	return (ENOTTY);
16935 }
16936 
16937 /*ARGSUSED*/
16938 static int
16939 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16940 {
16941 	minor_t minor = getminor(dev);
16942 	dtrace_state_t *state;
16943 	int rval;
16944 
16945 	if (minor == DTRACEMNRN_HELPER)
16946 		return (dtrace_ioctl_helper(cmd, arg, rv));
16947 
16948 	state = ddi_get_soft_state(dtrace_softstate, minor);
16949 
16950 	if (state->dts_anon) {
16951 		ASSERT(dtrace_anon.dta_state == NULL);
16952 		state = state->dts_anon;
16953 	}
16954 
16955 	switch (cmd) {
16956 	case DTRACEIOC_PROVIDER: {
16957 		dtrace_providerdesc_t pvd;
16958 		dtrace_provider_t *pvp;
16959 
16960 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16961 			return (EFAULT);
16962 
16963 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16964 		mutex_enter(&dtrace_provider_lock);
16965 
16966 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16967 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16968 				break;
16969 		}
16970 
16971 		mutex_exit(&dtrace_provider_lock);
16972 
16973 		if (pvp == NULL)
16974 			return (ESRCH);
16975 
16976 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16977 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16978 
16979 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16980 			return (EFAULT);
16981 
16982 		return (0);
16983 	}
16984 
16985 	case DTRACEIOC_EPROBE: {
16986 		dtrace_eprobedesc_t epdesc;
16987 		dtrace_ecb_t *ecb;
16988 		dtrace_action_t *act;
16989 		void *buf;
16990 		size_t size;
16991 		uintptr_t dest;
16992 		int nrecs;
16993 
16994 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16995 			return (EFAULT);
16996 
16997 		mutex_enter(&dtrace_lock);
16998 
16999 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17000 			mutex_exit(&dtrace_lock);
17001 			return (EINVAL);
17002 		}
17003 
17004 		if (ecb->dte_probe == NULL) {
17005 			mutex_exit(&dtrace_lock);
17006 			return (EINVAL);
17007 		}
17008 
17009 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17010 		epdesc.dtepd_uarg = ecb->dte_uarg;
17011 		epdesc.dtepd_size = ecb->dte_size;
17012 
17013 		nrecs = epdesc.dtepd_nrecs;
17014 		epdesc.dtepd_nrecs = 0;
17015 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17016 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17017 				continue;
17018 
17019 			epdesc.dtepd_nrecs++;
17020 		}
17021 
17022 		/*
17023 		 * Now that we have the size, we need to allocate a temporary
17024 		 * buffer in which to store the complete description.  We need
17025 		 * the temporary buffer to be able to drop dtrace_lock()
17026 		 * across the copyout(), below.
17027 		 */
17028 		size = sizeof (dtrace_eprobedesc_t) +
17029 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17030 
17031 		buf = kmem_alloc(size, KM_SLEEP);
17032 		dest = (uintptr_t)buf;
17033 
17034 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17035 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17036 
17037 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17038 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17039 				continue;
17040 
17041 			if (nrecs-- == 0)
17042 				break;
17043 
17044 			bcopy(&act->dta_rec, (void *)dest,
17045 			    sizeof (dtrace_recdesc_t));
17046 			dest += sizeof (dtrace_recdesc_t);
17047 		}
17048 
17049 		mutex_exit(&dtrace_lock);
17050 
17051 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17052 			kmem_free(buf, size);
17053 			return (EFAULT);
17054 		}
17055 
17056 		kmem_free(buf, size);
17057 		return (0);
17058 	}
17059 
17060 	case DTRACEIOC_AGGDESC: {
17061 		dtrace_aggdesc_t aggdesc;
17062 		dtrace_action_t *act;
17063 		dtrace_aggregation_t *agg;
17064 		int nrecs;
17065 		uint32_t offs;
17066 		dtrace_recdesc_t *lrec;
17067 		void *buf;
17068 		size_t size;
17069 		uintptr_t dest;
17070 
17071 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17072 			return (EFAULT);
17073 
17074 		mutex_enter(&dtrace_lock);
17075 
17076 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17077 			mutex_exit(&dtrace_lock);
17078 			return (EINVAL);
17079 		}
17080 
17081 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17082 
17083 		nrecs = aggdesc.dtagd_nrecs;
17084 		aggdesc.dtagd_nrecs = 0;
17085 
17086 		offs = agg->dtag_base;
17087 		lrec = &agg->dtag_action.dta_rec;
17088 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17089 
17090 		for (act = agg->dtag_first; ; act = act->dta_next) {
17091 			ASSERT(act->dta_intuple ||
17092 			    DTRACEACT_ISAGG(act->dta_kind));
17093 
17094 			/*
17095 			 * If this action has a record size of zero, it
17096 			 * denotes an argument to the aggregating action.
17097 			 * Because the presence of this record doesn't (or
17098 			 * shouldn't) affect the way the data is interpreted,
17099 			 * we don't copy it out to save user-level the
17100 			 * confusion of dealing with a zero-length record.
17101 			 */
17102 			if (act->dta_rec.dtrd_size == 0) {
17103 				ASSERT(agg->dtag_hasarg);
17104 				continue;
17105 			}
17106 
17107 			aggdesc.dtagd_nrecs++;
17108 
17109 			if (act == &agg->dtag_action)
17110 				break;
17111 		}
17112 
17113 		/*
17114 		 * Now that we have the size, we need to allocate a temporary
17115 		 * buffer in which to store the complete description.  We need
17116 		 * the temporary buffer to be able to drop dtrace_lock()
17117 		 * across the copyout(), below.
17118 		 */
17119 		size = sizeof (dtrace_aggdesc_t) +
17120 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17121 
17122 		buf = kmem_alloc(size, KM_SLEEP);
17123 		dest = (uintptr_t)buf;
17124 
17125 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17126 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17127 
17128 		for (act = agg->dtag_first; ; act = act->dta_next) {
17129 			dtrace_recdesc_t rec = act->dta_rec;
17130 
17131 			/*
17132 			 * See the comment in the above loop for why we pass
17133 			 * over zero-length records.
17134 			 */
17135 			if (rec.dtrd_size == 0) {
17136 				ASSERT(agg->dtag_hasarg);
17137 				continue;
17138 			}
17139 
17140 			if (nrecs-- == 0)
17141 				break;
17142 
17143 			rec.dtrd_offset -= offs;
17144 			bcopy(&rec, (void *)dest, sizeof (rec));
17145 			dest += sizeof (dtrace_recdesc_t);
17146 
17147 			if (act == &agg->dtag_action)
17148 				break;
17149 		}
17150 
17151 		mutex_exit(&dtrace_lock);
17152 
17153 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17154 			kmem_free(buf, size);
17155 			return (EFAULT);
17156 		}
17157 
17158 		kmem_free(buf, size);
17159 		return (0);
17160 	}
17161 
17162 	case DTRACEIOC_ENABLE: {
17163 		dof_hdr_t *dof;
17164 		dtrace_enabling_t *enab = NULL;
17165 		dtrace_vstate_t *vstate;
17166 		int err = 0;
17167 
17168 		*rv = 0;
17169 
17170 		/*
17171 		 * If a NULL argument has been passed, we take this as our
17172 		 * cue to reevaluate our enablings.
17173 		 */
17174 		if (arg == NULL) {
17175 			dtrace_enabling_matchall();
17176 
17177 			return (0);
17178 		}
17179 
17180 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17181 			return (rval);
17182 
17183 		mutex_enter(&cpu_lock);
17184 		mutex_enter(&dtrace_lock);
17185 		vstate = &state->dts_vstate;
17186 
17187 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17188 			mutex_exit(&dtrace_lock);
17189 			mutex_exit(&cpu_lock);
17190 			dtrace_dof_destroy(dof);
17191 			return (EBUSY);
17192 		}
17193 
17194 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17195 			mutex_exit(&dtrace_lock);
17196 			mutex_exit(&cpu_lock);
17197 			dtrace_dof_destroy(dof);
17198 			return (EINVAL);
17199 		}
17200 
17201 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
17202 			dtrace_enabling_destroy(enab);
17203 			mutex_exit(&dtrace_lock);
17204 			mutex_exit(&cpu_lock);
17205 			dtrace_dof_destroy(dof);
17206 			return (rval);
17207 		}
17208 
17209 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17210 			err = dtrace_enabling_retain(enab);
17211 		} else {
17212 			dtrace_enabling_destroy(enab);
17213 		}
17214 
17215 		mutex_exit(&cpu_lock);
17216 		mutex_exit(&dtrace_lock);
17217 		dtrace_dof_destroy(dof);
17218 
17219 		return (err);
17220 	}
17221 
17222 	case DTRACEIOC_REPLICATE: {
17223 		dtrace_repldesc_t desc;
17224 		dtrace_probedesc_t *match = &desc.dtrpd_match;
17225 		dtrace_probedesc_t *create = &desc.dtrpd_create;
17226 		int err;
17227 
17228 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17229 			return (EFAULT);
17230 
17231 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17232 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17233 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17234 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17235 
17236 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17237 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17238 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17239 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17240 
17241 		mutex_enter(&dtrace_lock);
17242 		err = dtrace_enabling_replicate(state, match, create);
17243 		mutex_exit(&dtrace_lock);
17244 
17245 		return (err);
17246 	}
17247 
17248 	case DTRACEIOC_PROBEMATCH:
17249 	case DTRACEIOC_PROBES: {
17250 		dtrace_probe_t *probe = NULL;
17251 		dtrace_probedesc_t desc;
17252 		dtrace_probekey_t pkey;
17253 		dtrace_id_t i;
17254 		int m = 0;
17255 		uint32_t priv;
17256 		uid_t uid;
17257 		zoneid_t zoneid;
17258 
17259 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17260 			return (EFAULT);
17261 
17262 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17263 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17264 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17265 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17266 
17267 		/*
17268 		 * Before we attempt to match this probe, we want to give
17269 		 * all providers the opportunity to provide it.
17270 		 */
17271 		if (desc.dtpd_id == DTRACE_IDNONE) {
17272 			mutex_enter(&dtrace_provider_lock);
17273 			dtrace_probe_provide(&desc, NULL);
17274 			mutex_exit(&dtrace_provider_lock);
17275 			desc.dtpd_id++;
17276 		}
17277 
17278 		if (cmd == DTRACEIOC_PROBEMATCH)  {
17279 			dtrace_probekey(&desc, &pkey);
17280 			pkey.dtpk_id = DTRACE_IDNONE;
17281 		}
17282 
17283 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17284 
17285 		mutex_enter(&dtrace_lock);
17286 
17287 		if (cmd == DTRACEIOC_PROBEMATCH) {
17288 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17289 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17290 				    (m = dtrace_match_probe(probe, &pkey,
17291 				    priv, uid, zoneid)) != 0)
17292 					break;
17293 			}
17294 
17295 			if (m < 0) {
17296 				mutex_exit(&dtrace_lock);
17297 				return (EINVAL);
17298 			}
17299 
17300 		} else {
17301 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17302 				if ((probe = dtrace_probes[i - 1]) != NULL &&
17303 				    dtrace_match_priv(probe, priv, uid, zoneid))
17304 					break;
17305 			}
17306 		}
17307 
17308 		if (probe == NULL) {
17309 			mutex_exit(&dtrace_lock);
17310 			return (ESRCH);
17311 		}
17312 
17313 		dtrace_probe_description(probe, &desc);
17314 		mutex_exit(&dtrace_lock);
17315 
17316 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17317 			return (EFAULT);
17318 
17319 		return (0);
17320 	}
17321 
17322 	case DTRACEIOC_PROBEARG: {
17323 		dtrace_argdesc_t desc;
17324 		dtrace_probe_t *probe;
17325 		dtrace_provider_t *prov;
17326 
17327 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17328 			return (EFAULT);
17329 
17330 		if (desc.dtargd_id == DTRACE_IDNONE)
17331 			return (EINVAL);
17332 
17333 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
17334 			return (EINVAL);
17335 
17336 		mutex_enter(&dtrace_provider_lock);
17337 		mutex_enter(&mod_lock);
17338 		mutex_enter(&dtrace_lock);
17339 
17340 		if (desc.dtargd_id > dtrace_nprobes) {
17341 			mutex_exit(&dtrace_lock);
17342 			mutex_exit(&mod_lock);
17343 			mutex_exit(&dtrace_provider_lock);
17344 			return (EINVAL);
17345 		}
17346 
17347 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17348 			mutex_exit(&dtrace_lock);
17349 			mutex_exit(&mod_lock);
17350 			mutex_exit(&dtrace_provider_lock);
17351 			return (EINVAL);
17352 		}
17353 
17354 		mutex_exit(&dtrace_lock);
17355 
17356 		prov = probe->dtpr_provider;
17357 
17358 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17359 			/*
17360 			 * There isn't any typed information for this probe.
17361 			 * Set the argument number to DTRACE_ARGNONE.
17362 			 */
17363 			desc.dtargd_ndx = DTRACE_ARGNONE;
17364 		} else {
17365 			desc.dtargd_native[0] = '\0';
17366 			desc.dtargd_xlate[0] = '\0';
17367 			desc.dtargd_mapping = desc.dtargd_ndx;
17368 
17369 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17370 			    probe->dtpr_id, probe->dtpr_arg, &desc);
17371 		}
17372 
17373 		mutex_exit(&mod_lock);
17374 		mutex_exit(&dtrace_provider_lock);
17375 
17376 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17377 			return (EFAULT);
17378 
17379 		return (0);
17380 	}
17381 
17382 	case DTRACEIOC_GO: {
17383 		processorid_t cpuid;
17384 		rval = dtrace_state_go(state, &cpuid);
17385 
17386 		if (rval != 0)
17387 			return (rval);
17388 
17389 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17390 			return (EFAULT);
17391 
17392 		return (0);
17393 	}
17394 
17395 	case DTRACEIOC_STOP: {
17396 		processorid_t cpuid;
17397 
17398 		mutex_enter(&dtrace_lock);
17399 		rval = dtrace_state_stop(state, &cpuid);
17400 		mutex_exit(&dtrace_lock);
17401 
17402 		if (rval != 0)
17403 			return (rval);
17404 
17405 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17406 			return (EFAULT);
17407 
17408 		return (0);
17409 	}
17410 
17411 	case DTRACEIOC_DOFGET: {
17412 		dof_hdr_t hdr, *dof;
17413 		uint64_t len;
17414 
17415 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17416 			return (EFAULT);
17417 
17418 		mutex_enter(&dtrace_lock);
17419 		dof = dtrace_dof_create(state);
17420 		mutex_exit(&dtrace_lock);
17421 
17422 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17423 		rval = copyout(dof, (void *)arg, len);
17424 		dtrace_dof_destroy(dof);
17425 
17426 		return (rval == 0 ? 0 : EFAULT);
17427 	}
17428 
17429 	case DTRACEIOC_AGGSNAP:
17430 	case DTRACEIOC_BUFSNAP: {
17431 		dtrace_bufdesc_t desc;
17432 		caddr_t cached;
17433 		dtrace_buffer_t *buf;
17434 
17435 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17436 			return (EFAULT);
17437 
17438 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17439 			return (EINVAL);
17440 
17441 		mutex_enter(&dtrace_lock);
17442 
17443 		if (cmd == DTRACEIOC_BUFSNAP) {
17444 			buf = &state->dts_buffer[desc.dtbd_cpu];
17445 		} else {
17446 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17447 		}
17448 
17449 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17450 			size_t sz = buf->dtb_offset;
17451 
17452 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17453 				mutex_exit(&dtrace_lock);
17454 				return (EBUSY);
17455 			}
17456 
17457 			/*
17458 			 * If this buffer has already been consumed, we're
17459 			 * going to indicate that there's nothing left here
17460 			 * to consume.
17461 			 */
17462 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17463 				mutex_exit(&dtrace_lock);
17464 
17465 				desc.dtbd_size = 0;
17466 				desc.dtbd_drops = 0;
17467 				desc.dtbd_errors = 0;
17468 				desc.dtbd_oldest = 0;
17469 				sz = sizeof (desc);
17470 
17471 				if (copyout(&desc, (void *)arg, sz) != 0)
17472 					return (EFAULT);
17473 
17474 				return (0);
17475 			}
17476 
17477 			/*
17478 			 * If this is a ring buffer that has wrapped, we want
17479 			 * to copy the whole thing out.
17480 			 */
17481 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17482 				dtrace_buffer_polish(buf);
17483 				sz = buf->dtb_size;
17484 			}
17485 
17486 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17487 				mutex_exit(&dtrace_lock);
17488 				return (EFAULT);
17489 			}
17490 
17491 			desc.dtbd_size = sz;
17492 			desc.dtbd_drops = buf->dtb_drops;
17493 			desc.dtbd_errors = buf->dtb_errors;
17494 			desc.dtbd_oldest = buf->dtb_xamot_offset;
17495 			desc.dtbd_timestamp = dtrace_gethrtime();
17496 
17497 			mutex_exit(&dtrace_lock);
17498 
17499 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17500 				return (EFAULT);
17501 
17502 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
17503 
17504 			return (0);
17505 		}
17506 
17507 		if (buf->dtb_tomax == NULL) {
17508 			ASSERT(buf->dtb_xamot == NULL);
17509 			mutex_exit(&dtrace_lock);
17510 			return (ENOENT);
17511 		}
17512 
17513 		cached = buf->dtb_tomax;
17514 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17515 
17516 		dtrace_xcall(desc.dtbd_cpu,
17517 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
17518 
17519 		state->dts_errors += buf->dtb_xamot_errors;
17520 
17521 		/*
17522 		 * If the buffers did not actually switch, then the cross call
17523 		 * did not take place -- presumably because the given CPU is
17524 		 * not in the ready set.  If this is the case, we'll return
17525 		 * ENOENT.
17526 		 */
17527 		if (buf->dtb_tomax == cached) {
17528 			ASSERT(buf->dtb_xamot != cached);
17529 			mutex_exit(&dtrace_lock);
17530 			return (ENOENT);
17531 		}
17532 
17533 		ASSERT(cached == buf->dtb_xamot);
17534 
17535 		/*
17536 		 * We have our snapshot; now copy it out.
17537 		 */
17538 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
17539 		    buf->dtb_xamot_offset) != 0) {
17540 			mutex_exit(&dtrace_lock);
17541 			return (EFAULT);
17542 		}
17543 
17544 		desc.dtbd_size = buf->dtb_xamot_offset;
17545 		desc.dtbd_drops = buf->dtb_xamot_drops;
17546 		desc.dtbd_errors = buf->dtb_xamot_errors;
17547 		desc.dtbd_oldest = 0;
17548 		desc.dtbd_timestamp = buf->dtb_switched;
17549 
17550 		mutex_exit(&dtrace_lock);
17551 
17552 		/*
17553 		 * Finally, copy out the buffer description.
17554 		 */
17555 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17556 			return (EFAULT);
17557 
17558 		return (0);
17559 	}
17560 
17561 	case DTRACEIOC_CONF: {
17562 		dtrace_conf_t conf;
17563 
17564 		bzero(&conf, sizeof (conf));
17565 		conf.dtc_difversion = DIF_VERSION;
17566 		conf.dtc_difintregs = DIF_DIR_NREGS;
17567 		conf.dtc_diftupregs = DIF_DTR_NREGS;
17568 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17569 
17570 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17571 			return (EFAULT);
17572 
17573 		return (0);
17574 	}
17575 
17576 	case DTRACEIOC_STATUS: {
17577 		dtrace_status_t stat;
17578 		dtrace_dstate_t *dstate;
17579 		int i, j;
17580 		uint64_t nerrs;
17581 
17582 		/*
17583 		 * See the comment in dtrace_state_deadman() for the reason
17584 		 * for setting dts_laststatus to INT64_MAX before setting
17585 		 * it to the correct value.
17586 		 */
17587 		state->dts_laststatus = INT64_MAX;
17588 		dtrace_membar_producer();
17589 		state->dts_laststatus = dtrace_gethrtime();
17590 
17591 		bzero(&stat, sizeof (stat));
17592 
17593 		mutex_enter(&dtrace_lock);
17594 
17595 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17596 			mutex_exit(&dtrace_lock);
17597 			return (ENOENT);
17598 		}
17599 
17600 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17601 			stat.dtst_exiting = 1;
17602 
17603 		nerrs = state->dts_errors;
17604 		dstate = &state->dts_vstate.dtvs_dynvars;
17605 
17606 		for (i = 0; i < NCPU; i++) {
17607 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17608 
17609 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
17610 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17611 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17612 
17613 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17614 				stat.dtst_filled++;
17615 
17616 			nerrs += state->dts_buffer[i].dtb_errors;
17617 
17618 			for (j = 0; j < state->dts_nspeculations; j++) {
17619 				dtrace_speculation_t *spec;
17620 				dtrace_buffer_t *buf;
17621 
17622 				spec = &state->dts_speculations[j];
17623 				buf = &spec->dtsp_buffer[i];
17624 				stat.dtst_specdrops += buf->dtb_xamot_drops;
17625 			}
17626 		}
17627 
17628 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
17629 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17630 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17631 		stat.dtst_dblerrors = state->dts_dblerrors;
17632 		stat.dtst_killed =
17633 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17634 		stat.dtst_errors = nerrs;
17635 
17636 		mutex_exit(&dtrace_lock);
17637 
17638 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17639 			return (EFAULT);
17640 
17641 		return (0);
17642 	}
17643 
17644 	case DTRACEIOC_FORMAT: {
17645 		dtrace_fmtdesc_t fmt;
17646 		char *str;
17647 		int len;
17648 
17649 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17650 			return (EFAULT);
17651 
17652 		mutex_enter(&dtrace_lock);
17653 
17654 		if (fmt.dtfd_format == 0 ||
17655 		    fmt.dtfd_format > state->dts_nformats) {
17656 			mutex_exit(&dtrace_lock);
17657 			return (EINVAL);
17658 		}
17659 
17660 		/*
17661 		 * Format strings are allocated contiguously and they are
17662 		 * never freed; if a format index is less than the number
17663 		 * of formats, we can assert that the format map is non-NULL
17664 		 * and that the format for the specified index is non-NULL.
17665 		 */
17666 		ASSERT(state->dts_formats != NULL);
17667 		str = state->dts_formats[fmt.dtfd_format - 1];
17668 		ASSERT(str != NULL);
17669 
17670 		len = strlen(str) + 1;
17671 
17672 		if (len > fmt.dtfd_length) {
17673 			fmt.dtfd_length = len;
17674 
17675 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17676 				mutex_exit(&dtrace_lock);
17677 				return (EINVAL);
17678 			}
17679 		} else {
17680 			if (copyout(str, fmt.dtfd_string, len) != 0) {
17681 				mutex_exit(&dtrace_lock);
17682 				return (EINVAL);
17683 			}
17684 		}
17685 
17686 		mutex_exit(&dtrace_lock);
17687 		return (0);
17688 	}
17689 
17690 	default:
17691 		break;
17692 	}
17693 
17694 	return (ENOTTY);
17695 }
17696 
17697 /*ARGSUSED*/
17698 static int
17699 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17700 {
17701 	dtrace_state_t *state;
17702 
17703 	switch (cmd) {
17704 	case DDI_DETACH:
17705 		break;
17706 
17707 	case DDI_SUSPEND:
17708 		return (DDI_SUCCESS);
17709 
17710 	default:
17711 		return (DDI_FAILURE);
17712 	}
17713 
17714 	mutex_enter(&cpu_lock);
17715 	mutex_enter(&dtrace_provider_lock);
17716 	mutex_enter(&dtrace_lock);
17717 
17718 	ASSERT(dtrace_opens == 0);
17719 
17720 	if (dtrace_helpers > 0) {
17721 		mutex_exit(&dtrace_provider_lock);
17722 		mutex_exit(&dtrace_lock);
17723 		mutex_exit(&cpu_lock);
17724 		return (DDI_FAILURE);
17725 	}
17726 
17727 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17728 		mutex_exit(&dtrace_provider_lock);
17729 		mutex_exit(&dtrace_lock);
17730 		mutex_exit(&cpu_lock);
17731 		return (DDI_FAILURE);
17732 	}
17733 
17734 	dtrace_provider = NULL;
17735 
17736 	if ((state = dtrace_anon_grab()) != NULL) {
17737 		/*
17738 		 * If there were ECBs on this state, the provider should
17739 		 * have not been allowed to detach; assert that there is
17740 		 * none.
17741 		 */
17742 		ASSERT(state->dts_necbs == 0);
17743 		dtrace_state_destroy(state);
17744 
17745 		/*
17746 		 * If we're being detached with anonymous state, we need to
17747 		 * indicate to the kernel debugger that DTrace is now inactive.
17748 		 */
17749 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17750 	}
17751 
17752 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17753 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17754 	dtrace_cpu_init = NULL;
17755 	dtrace_helpers_cleanup = NULL;
17756 	dtrace_helpers_fork = NULL;
17757 	dtrace_cpustart_init = NULL;
17758 	dtrace_cpustart_fini = NULL;
17759 	dtrace_debugger_init = NULL;
17760 	dtrace_debugger_fini = NULL;
17761 	dtrace_modload = NULL;
17762 	dtrace_modunload = NULL;
17763 
17764 	ASSERT(dtrace_getf == 0);
17765 	ASSERT(dtrace_closef == NULL);
17766 
17767 	mutex_exit(&cpu_lock);
17768 
17769 	if (dtrace_helptrace_enabled) {
17770 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17771 		dtrace_helptrace_buffer = NULL;
17772 	}
17773 
17774 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17775 	dtrace_probes = NULL;
17776 	dtrace_nprobes = 0;
17777 
17778 	dtrace_hash_destroy(dtrace_bymod);
17779 	dtrace_hash_destroy(dtrace_byfunc);
17780 	dtrace_hash_destroy(dtrace_byname);
17781 	dtrace_bymod = NULL;
17782 	dtrace_byfunc = NULL;
17783 	dtrace_byname = NULL;
17784 
17785 	kmem_cache_destroy(dtrace_state_cache);
17786 	vmem_destroy(dtrace_minor);
17787 	vmem_destroy(dtrace_arena);
17788 
17789 	if (dtrace_toxrange != NULL) {
17790 		kmem_free(dtrace_toxrange,
17791 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17792 		dtrace_toxrange = NULL;
17793 		dtrace_toxranges = 0;
17794 		dtrace_toxranges_max = 0;
17795 	}
17796 
17797 	ddi_remove_minor_node(dtrace_devi, NULL);
17798 	dtrace_devi = NULL;
17799 
17800 	ddi_soft_state_fini(&dtrace_softstate);
17801 
17802 	ASSERT(dtrace_vtime_references == 0);
17803 	ASSERT(dtrace_opens == 0);
17804 	ASSERT(dtrace_retained == NULL);
17805 
17806 	mutex_exit(&dtrace_lock);
17807 	mutex_exit(&dtrace_provider_lock);
17808 
17809 	/*
17810 	 * We don't destroy the task queue until after we have dropped our
17811 	 * locks (taskq_destroy() may block on running tasks).  To prevent
17812 	 * attempting to do work after we have effectively detached but before
17813 	 * the task queue has been destroyed, all tasks dispatched via the
17814 	 * task queue must check that DTrace is still attached before
17815 	 * performing any operation.
17816 	 */
17817 	taskq_destroy(dtrace_taskq);
17818 	dtrace_taskq = NULL;
17819 
17820 	return (DDI_SUCCESS);
17821 }
17822 #endif
17823 
17824 #if defined(sun)
17825 /*ARGSUSED*/
17826 static int
17827 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17828 {
17829 	int error;
17830 
17831 	switch (infocmd) {
17832 	case DDI_INFO_DEVT2DEVINFO:
17833 		*result = (void *)dtrace_devi;
17834 		error = DDI_SUCCESS;
17835 		break;
17836 	case DDI_INFO_DEVT2INSTANCE:
17837 		*result = (void *)0;
17838 		error = DDI_SUCCESS;
17839 		break;
17840 	default:
17841 		error = DDI_FAILURE;
17842 	}
17843 	return (error);
17844 }
17845 #endif
17846 
17847 #if defined(sun)
17848 static struct cb_ops dtrace_cb_ops = {
17849 	dtrace_open,		/* open */
17850 	dtrace_close,		/* close */
17851 	nulldev,		/* strategy */
17852 	nulldev,		/* print */
17853 	nodev,			/* dump */
17854 	nodev,			/* read */
17855 	nodev,			/* write */
17856 	dtrace_ioctl,		/* ioctl */
17857 	nodev,			/* devmap */
17858 	nodev,			/* mmap */
17859 	nodev,			/* segmap */
17860 	nochpoll,		/* poll */
17861 	ddi_prop_op,		/* cb_prop_op */
17862 	0,			/* streamtab  */
17863 	D_NEW | D_MP		/* Driver compatibility flag */
17864 };
17865 
17866 static struct dev_ops dtrace_ops = {
17867 	DEVO_REV,		/* devo_rev */
17868 	0,			/* refcnt */
17869 	dtrace_info,		/* get_dev_info */
17870 	nulldev,		/* identify */
17871 	nulldev,		/* probe */
17872 	dtrace_attach,		/* attach */
17873 	dtrace_detach,		/* detach */
17874 	nodev,			/* reset */
17875 	&dtrace_cb_ops,		/* driver operations */
17876 	NULL,			/* bus operations */
17877 	nodev			/* dev power */
17878 };
17879 
17880 static struct modldrv modldrv = {
17881 	&mod_driverops,		/* module type (this is a pseudo driver) */
17882 	"Dynamic Tracing",	/* name of module */
17883 	&dtrace_ops,		/* driver ops */
17884 };
17885 
17886 static struct modlinkage modlinkage = {
17887 	MODREV_1,
17888 	(void *)&modldrv,
17889 	NULL
17890 };
17891 
17892 int
17893 _init(void)
17894 {
17895 	return (mod_install(&modlinkage));
17896 }
17897 
17898 int
17899 _info(struct modinfo *modinfop)
17900 {
17901 	return (mod_info(&modlinkage, modinfop));
17902 }
17903 
17904 int
17905 _fini(void)
17906 {
17907 	return (mod_remove(&modlinkage));
17908 }
17909 #else
17910 
17911 static d_ioctl_t	dtrace_ioctl;
17912 static d_ioctl_t	dtrace_ioctl_helper;
17913 static void		dtrace_load(void *);
17914 static int		dtrace_unload(void);
17915 static struct cdev	*dtrace_dev;
17916 static struct cdev	*helper_dev;
17917 
17918 void dtrace_invop_init(void);
17919 void dtrace_invop_uninit(void);
17920 
17921 static struct cdevsw dtrace_cdevsw = {
17922 	.d_version	= D_VERSION,
17923 	.d_ioctl	= dtrace_ioctl,
17924 	.d_open		= dtrace_open,
17925 	.d_name		= "dtrace",
17926 };
17927 
17928 static struct cdevsw helper_cdevsw = {
17929 	.d_version	= D_VERSION,
17930 	.d_ioctl	= dtrace_ioctl_helper,
17931 	.d_name		= "helper",
17932 };
17933 
17934 #include <dtrace_anon.c>
17935 #include <dtrace_ioctl.c>
17936 #include <dtrace_load.c>
17937 #include <dtrace_modevent.c>
17938 #include <dtrace_sysctl.c>
17939 #include <dtrace_unload.c>
17940 #include <dtrace_vtime.c>
17941 #include <dtrace_hacks.c>
17942 #include <dtrace_isa.c>
17943 
17944 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
17945 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
17946 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
17947 
17948 DEV_MODULE(dtrace, dtrace_modevent, NULL);
17949 MODULE_VERSION(dtrace, 1);
17950 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
17951 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
17952 #endif
17953