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: stable/9/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c 302910 2016-07-15 19:14:28Z markj $
22  */
23 
24 /*
25  * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2012 by Delphix. All rights reserved.
28  */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 /*
33  * DTrace - Dynamic Tracing for Solaris
34  *
35  * This is the implementation of the Solaris Dynamic Tracing framework
36  * (DTrace).  The user-visible interface to DTrace is described at length in
37  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
38  * library, the in-kernel DTrace framework, and the DTrace providers are
39  * described in the block comments in the <sys/dtrace.h> header file.  The
40  * internal architecture of DTrace is described in the block comments in the
41  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
42  * implementation very much assume mastery of all of these sources; if one has
43  * an unanswered question about the implementation, one should consult them
44  * first.
45  *
46  * The functions here are ordered roughly as follows:
47  *
48  *   - Probe context functions
49  *   - Probe hashing functions
50  *   - Non-probe context utility functions
51  *   - Matching functions
52  *   - Provider-to-Framework API functions
53  *   - Probe management functions
54  *   - DIF object functions
55  *   - Format functions
56  *   - Predicate functions
57  *   - ECB functions
58  *   - Buffer functions
59  *   - Enabling functions
60  *   - DOF functions
61  *   - Anonymous enabling functions
62  *   - Consumer state functions
63  *   - Helper functions
64  *   - Hook functions
65  *   - Driver cookbook functions
66  *
67  * Each group of functions begins with a block comment labelled the "DTrace
68  * [Group] Functions", allowing one to find each block by searching forward
69  * on capital-f functions.
70  */
71 #include <sys/errno.h>
72 #if !defined(sun)
73 #include <sys/time.h>
74 #endif
75 #include <sys/stat.h>
76 #include <sys/modctl.h>
77 #include <sys/conf.h>
78 #include <sys/systm.h>
79 #if defined(sun)
80 #include <sys/ddi.h>
81 #include <sys/sunddi.h>
82 #endif
83 #include <sys/cpuvar.h>
84 #include <sys/kmem.h>
85 #if defined(sun)
86 #include <sys/strsubr.h>
87 #endif
88 #include <sys/sysmacros.h>
89 #include <sys/dtrace_impl.h>
90 #include <sys/atomic.h>
91 #include <sys/cmn_err.h>
92 #if defined(sun)
93 #include <sys/mutex_impl.h>
94 #include <sys/rwlock_impl.h>
95 #endif
96 #include <sys/ctf_api.h>
97 #if defined(sun)
98 #include <sys/panic.h>
99 #include <sys/priv_impl.h>
100 #endif
101 #include <sys/policy.h>
102 #if defined(sun)
103 #include <sys/cred_impl.h>
104 #include <sys/procfs_isa.h>
105 #endif
106 #include <sys/taskq.h>
107 #if defined(sun)
108 #include <sys/mkdev.h>
109 #include <sys/kdi.h>
110 #endif
111 #include <sys/zone.h>
112 #include <sys/socket.h>
113 #include <netinet/in.h>
114 
115 /* FreeBSD includes: */
116 #if !defined(sun)
117 #include <sys/callout.h>
118 #include <sys/ctype.h>
119 #include <sys/eventhandler.h>
120 #include <sys/limits.h>
121 #include <sys/kdb.h>
122 #include <sys/kernel.h>
123 #include <sys/malloc.h>
124 #include <sys/sysctl.h>
125 #include <sys/lock.h>
126 #include <sys/mutex.h>
127 #include <sys/rwlock.h>
128 #include <sys/sx.h>
129 #include <sys/dtrace_bsd.h>
130 #include <netinet/in.h>
131 #include "dtrace_cddl.h"
132 #include "dtrace_debug.c"
133 #endif
134 
135 /*
136  * DTrace Tunable Variables
137  *
138  * The following variables may be tuned by adding a line to /etc/system that
139  * includes both the name of the DTrace module ("dtrace") and the name of the
140  * variable.  For example:
141  *
142  *   set dtrace:dtrace_destructive_disallow = 1
143  *
144  * In general, the only variables that one should be tuning this way are those
145  * that affect system-wide DTrace behavior, and for which the default behavior
146  * is undesirable.  Most of these variables are tunable on a per-consumer
147  * basis using DTrace options, and need not be tuned on a system-wide basis.
148  * When tuning these variables, avoid pathological values; while some attempt
149  * is made to verify the integrity of these variables, they are not considered
150  * part of the supported interface to DTrace, and they are therefore not
151  * checked comprehensively.  Further, these variables should not be tuned
152  * dynamically via "mdb -kw" or other means; they should only be tuned via
153  * /etc/system.
154  */
155 int		dtrace_destructive_disallow = 0;
156 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
157 size_t		dtrace_difo_maxsize = (256 * 1024);
158 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
159 size_t		dtrace_global_maxsize = (16 * 1024);
160 size_t		dtrace_actions_max = (16 * 1024);
161 size_t		dtrace_retain_max = 1024;
162 dtrace_optval_t	dtrace_helper_actions_max = 128;
163 dtrace_optval_t	dtrace_helper_providers_max = 32;
164 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
165 size_t		dtrace_strsize_default = 256;
166 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
167 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
168 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
169 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
170 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
171 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
172 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
173 dtrace_optval_t	dtrace_nspec_default = 1;
174 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
175 dtrace_optval_t dtrace_stackframes_default = 20;
176 dtrace_optval_t dtrace_ustackframes_default = 20;
177 dtrace_optval_t dtrace_jstackframes_default = 50;
178 dtrace_optval_t dtrace_jstackstrsize_default = 512;
179 int		dtrace_msgdsize_max = 128;
180 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
181 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
182 int		dtrace_devdepth_max = 32;
183 int		dtrace_err_verbose;
184 hrtime_t	dtrace_deadman_interval = NANOSEC;
185 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
186 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
187 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
188 #if !defined(sun)
189 int		dtrace_memstr_max = 4096;
190 #endif
191 
192 /*
193  * DTrace External Variables
194  *
195  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
196  * available to DTrace consumers via the backtick (`) syntax.  One of these,
197  * dtrace_zero, is made deliberately so:  it is provided as a source of
198  * well-known, zero-filled memory.  While this variable is not documented,
199  * it is used by some translators as an implementation detail.
200  */
201 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
202 
203 /*
204  * DTrace Internal Variables
205  */
206 #if defined(sun)
207 static dev_info_t	*dtrace_devi;		/* device info */
208 #endif
209 #if defined(sun)
210 static vmem_t		*dtrace_arena;		/* probe ID arena */
211 static vmem_t		*dtrace_minor;		/* minor number arena */
212 #else
213 static taskq_t		*dtrace_taskq;		/* task queue */
214 static struct unrhdr	*dtrace_arena;		/* Probe ID number.     */
215 #endif
216 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
217 static int		dtrace_nprobes;		/* number of probes */
218 static dtrace_provider_t *dtrace_provider;	/* provider list */
219 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
220 static int		dtrace_opens;		/* number of opens */
221 static int		dtrace_helpers;		/* number of helpers */
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_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
240 #if !defined(sun)
241 static struct mtx	dtrace_unr_mtx;
242 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
243 int		dtrace_in_probe;	/* non-zero if executing a probe */
244 #if defined(__i386__) || defined(__amd64__)
245 uintptr_t	dtrace_in_probe_addr;	/* Address of invop when already in probe */
246 #endif
247 static eventhandler_tag	dtrace_kld_load_tag;
248 static eventhandler_tag	dtrace_kld_unload_try_tag;
249 #endif
250 
251 /*
252  * DTrace Locking
253  * DTrace is protected by three (relatively coarse-grained) locks:
254  *
255  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
256  *     including enabling state, probes, ECBs, consumer state, helper state,
257  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
258  *     probe context is lock-free -- synchronization is handled via the
259  *     dtrace_sync() cross call mechanism.
260  *
261  * (2) dtrace_provider_lock is required when manipulating provider state, or
262  *     when provider state must be held constant.
263  *
264  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
265  *     when meta provider state must be held constant.
266  *
267  * The lock ordering between these three locks is dtrace_meta_lock before
268  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
269  * several places where dtrace_provider_lock is held by the framework as it
270  * calls into the providers -- which then call back into the framework,
271  * grabbing dtrace_lock.)
272  *
273  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
274  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
275  * role as a coarse-grained lock; it is acquired before both of these locks.
276  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
277  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
278  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
279  * acquired _between_ dtrace_provider_lock and dtrace_lock.
280  */
281 static kmutex_t		dtrace_lock;		/* probe state lock */
282 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
283 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
284 
285 #if !defined(sun)
286 /* XXX FreeBSD hacks. */
287 #define cr_suid		cr_svuid
288 #define cr_sgid		cr_svgid
289 #define	ipaddr_t	in_addr_t
290 #define mod_modname	pathname
291 #define vuprintf	vprintf
292 #define ttoproc(_a)	((_a)->td_proc)
293 #define crgetzoneid(_a)	0
294 #define	NCPU		MAXCPU
295 #define SNOCD		0
296 #define CPU_ON_INTR(_a)	0
297 
298 #define PRIV_EFFECTIVE		(1 << 0)
299 #define PRIV_DTRACE_KERNEL	(1 << 1)
300 #define PRIV_DTRACE_PROC	(1 << 2)
301 #define PRIV_DTRACE_USER	(1 << 3)
302 #define PRIV_PROC_OWNER		(1 << 4)
303 #define PRIV_PROC_ZONE		(1 << 5)
304 #define PRIV_ALL		~0
305 
306 SYSCTL_DECL(_debug_dtrace);
307 SYSCTL_DECL(_kern_dtrace);
308 #endif
309 
310 #if defined(sun)
311 #define curcpu	CPU->cpu_id
312 #endif
313 
314 
315 /*
316  * DTrace Provider Variables
317  *
318  * These are the variables relating to DTrace as a provider (that is, the
319  * provider of the BEGIN, END, and ERROR probes).
320  */
321 static dtrace_pattr_t	dtrace_provider_attr = {
322 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
323 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
324 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
325 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
326 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
327 };
328 
329 static void
dtrace_nullop(void)330 dtrace_nullop(void)
331 {}
332 
333 static dtrace_pops_t	dtrace_provider_ops = {
334 	(void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
335 	(void (*)(void *, modctl_t *))dtrace_nullop,
336 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
337 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
338 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
339 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
340 	NULL,
341 	NULL,
342 	NULL,
343 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
344 };
345 
346 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
347 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
348 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
349 
350 /*
351  * DTrace Helper Tracing Variables
352  */
353 uint32_t dtrace_helptrace_next = 0;
354 uint32_t dtrace_helptrace_nlocals;
355 char	*dtrace_helptrace_buffer;
356 int	dtrace_helptrace_bufsize = 512 * 1024;
357 
358 #ifdef DEBUG
359 int	dtrace_helptrace_enabled = 1;
360 #else
361 int	dtrace_helptrace_enabled = 0;
362 #endif
363 
364 /*
365  * DTrace Error Hashing
366  *
367  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
368  * table.  This is very useful for checking coverage of tests that are
369  * expected to induce DIF or DOF processing errors, and may be useful for
370  * debugging problems in the DIF code generator or in DOF generation .  The
371  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
372  */
373 #ifdef DEBUG
374 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
375 static const char *dtrace_errlast;
376 static kthread_t *dtrace_errthread;
377 static kmutex_t dtrace_errlock;
378 #endif
379 
380 /*
381  * DTrace Macros and Constants
382  *
383  * These are various macros that are useful in various spots in the
384  * implementation, along with a few random constants that have no meaning
385  * outside of the implementation.  There is no real structure to this cpp
386  * mishmash -- but is there ever?
387  */
388 #define	DTRACE_HASHSTR(hash, probe)	\
389 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
390 
391 #define	DTRACE_HASHNEXT(hash, probe)	\
392 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
393 
394 #define	DTRACE_HASHPREV(hash, probe)	\
395 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
396 
397 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
398 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
399 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
400 
401 #define	DTRACE_AGGHASHSIZE_SLEW		17
402 
403 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
404 
405 /*
406  * The key for a thread-local variable consists of the lower 61 bits of the
407  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
408  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
409  * equal to a variable identifier.  This is necessary (but not sufficient) to
410  * assure that global associative arrays never collide with thread-local
411  * variables.  To guarantee that they cannot collide, we must also define the
412  * order for keying dynamic variables.  That order is:
413  *
414  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
415  *
416  * Because the variable-key and the tls-key are in orthogonal spaces, there is
417  * no way for a global variable key signature to match a thread-local key
418  * signature.
419  */
420 #if defined(sun)
421 #define	DTRACE_TLS_THRKEY(where) { \
422 	uint_t intr = 0; \
423 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
424 	for (; actv; actv >>= 1) \
425 		intr++; \
426 	ASSERT(intr < (1 << 3)); \
427 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
428 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
429 }
430 #else
431 #define	DTRACE_TLS_THRKEY(where) { \
432 	solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
433 	uint_t intr = 0; \
434 	uint_t actv = _c->cpu_intr_actv; \
435 	for (; actv; actv >>= 1) \
436 		intr++; \
437 	ASSERT(intr < (1 << 3)); \
438 	(where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
439 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
440 }
441 #endif
442 
443 #define	DT_BSWAP_8(x)	((x) & 0xff)
444 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
445 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
446 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
447 
448 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
449 
450 #define	DTRACE_STORE(type, tomax, offset, what) \
451 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
452 
453 #ifndef __x86
454 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
455 	if (addr & (size - 1)) {					\
456 		*flags |= CPU_DTRACE_BADALIGN;				\
457 		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
458 		return (0);						\
459 	}
460 #else
461 #define	DTRACE_ALIGNCHECK(addr, size, flags)
462 #endif
463 
464 /*
465  * Test whether a range of memory starting at testaddr of size testsz falls
466  * within the range of memory described by addr, sz.  We take care to avoid
467  * problems with overflow and underflow of the unsigned quantities, and
468  * disallow all negative sizes.  Ranges of size 0 are allowed.
469  */
470 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
471 	((testaddr) - (baseaddr) < (basesz) && \
472 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
473 	(testaddr) + (testsz) >= (testaddr))
474 
475 /*
476  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
477  * alloc_sz on the righthand side of the comparison in order to avoid overflow
478  * or underflow in the comparison with it.  This is simpler than the INRANGE
479  * check above, because we know that the dtms_scratch_ptr is valid in the
480  * range.  Allocations of size zero are allowed.
481  */
482 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
483 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
484 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
485 
486 #define	DTRACE_LOADFUNC(bits)						\
487 /*CSTYLED*/								\
488 uint##bits##_t								\
489 dtrace_load##bits(uintptr_t addr)					\
490 {									\
491 	size_t size = bits / NBBY;					\
492 	/*CSTYLED*/							\
493 	uint##bits##_t rval;						\
494 	int i;								\
495 	volatile uint16_t *flags = (volatile uint16_t *)		\
496 	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
497 									\
498 	DTRACE_ALIGNCHECK(addr, size, flags);				\
499 									\
500 	for (i = 0; i < dtrace_toxranges; i++) {			\
501 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
502 			continue;					\
503 									\
504 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
505 			continue;					\
506 									\
507 		/*							\
508 		 * This address falls within a toxic region; return 0.	\
509 		 */							\
510 		*flags |= CPU_DTRACE_BADADDR;				\
511 		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
512 		return (0);						\
513 	}								\
514 									\
515 	*flags |= CPU_DTRACE_NOFAULT;					\
516 	/*CSTYLED*/							\
517 	rval = *((volatile uint##bits##_t *)addr);			\
518 	*flags &= ~CPU_DTRACE_NOFAULT;					\
519 									\
520 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
521 }
522 
523 #ifdef _LP64
524 #define	dtrace_loadptr	dtrace_load64
525 #else
526 #define	dtrace_loadptr	dtrace_load32
527 #endif
528 
529 #define	DTRACE_DYNHASH_FREE	0
530 #define	DTRACE_DYNHASH_SINK	1
531 #define	DTRACE_DYNHASH_VALID	2
532 
533 #define	DTRACE_MATCH_NEXT	0
534 #define	DTRACE_MATCH_DONE	1
535 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
536 #define	DTRACE_STATE_ALIGN	64
537 
538 #define	DTRACE_FLAGS2FLT(flags)						\
539 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
540 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
541 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
542 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
543 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
544 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
545 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
546 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
547 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
548 	DTRACEFLT_UNKNOWN)
549 
550 #define	DTRACEACT_ISSTRING(act)						\
551 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
552 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
553 
554 /* Function prototype definitions: */
555 static size_t dtrace_strlen(const char *, size_t);
556 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
557 static void dtrace_enabling_provide(dtrace_provider_t *);
558 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
559 static void dtrace_enabling_matchall(void);
560 static void dtrace_enabling_reap(void);
561 static dtrace_state_t *dtrace_anon_grab(void);
562 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
563     dtrace_state_t *, uint64_t, uint64_t);
564 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
565 static void dtrace_buffer_drop(dtrace_buffer_t *);
566 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
567 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
568     dtrace_state_t *, dtrace_mstate_t *);
569 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
570     dtrace_optval_t);
571 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
572 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
573 uint16_t dtrace_load16(uintptr_t);
574 uint32_t dtrace_load32(uintptr_t);
575 uint64_t dtrace_load64(uintptr_t);
576 uint8_t dtrace_load8(uintptr_t);
577 void dtrace_dynvar_clean(dtrace_dstate_t *);
578 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
579     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
580 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
581 
582 /*
583  * DTrace Probe Context Functions
584  *
585  * These functions are called from probe context.  Because probe context is
586  * any context in which C may be called, arbitrarily locks may be held,
587  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
588  * As a result, functions called from probe context may only call other DTrace
589  * support functions -- they may not interact at all with the system at large.
590  * (Note that the ASSERT macro is made probe-context safe by redefining it in
591  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
592  * loads are to be performed from probe context, they _must_ be in terms of
593  * the safe dtrace_load*() variants.
594  *
595  * Some functions in this block are not actually called from probe context;
596  * for these functions, there will be a comment above the function reading
597  * "Note:  not called from probe context."
598  */
599 void
dtrace_panic(const char * format,...)600 dtrace_panic(const char *format, ...)
601 {
602 	va_list alist;
603 
604 	va_start(alist, format);
605 	dtrace_vpanic(format, alist);
606 	va_end(alist);
607 }
608 
609 int
dtrace_assfail(const char * a,const char * f,int l)610 dtrace_assfail(const char *a, const char *f, int l)
611 {
612 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
613 
614 	/*
615 	 * We just need something here that even the most clever compiler
616 	 * cannot optimize away.
617 	 */
618 	return (a[(uintptr_t)f]);
619 }
620 
621 /*
622  * Atomically increment a specified error counter from probe context.
623  */
624 static void
dtrace_error(uint32_t * counter)625 dtrace_error(uint32_t *counter)
626 {
627 	/*
628 	 * Most counters stored to in probe context are per-CPU counters.
629 	 * However, there are some error conditions that are sufficiently
630 	 * arcane that they don't merit per-CPU storage.  If these counters
631 	 * are incremented concurrently on different CPUs, scalability will be
632 	 * adversely affected -- but we don't expect them to be white-hot in a
633 	 * correctly constructed enabling...
634 	 */
635 	uint32_t oval, nval;
636 
637 	do {
638 		oval = *counter;
639 
640 		if ((nval = oval + 1) == 0) {
641 			/*
642 			 * If the counter would wrap, set it to 1 -- assuring
643 			 * that the counter is never zero when we have seen
644 			 * errors.  (The counter must be 32-bits because we
645 			 * aren't guaranteed a 64-bit compare&swap operation.)
646 			 * To save this code both the infamy of being fingered
647 			 * by a priggish news story and the indignity of being
648 			 * the target of a neo-puritan witch trial, we're
649 			 * carefully avoiding any colorful description of the
650 			 * likelihood of this condition -- but suffice it to
651 			 * say that it is only slightly more likely than the
652 			 * overflow of predicate cache IDs, as discussed in
653 			 * dtrace_predicate_create().
654 			 */
655 			nval = 1;
656 		}
657 	} while (dtrace_cas32(counter, oval, nval) != oval);
658 }
659 
660 /*
661  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
662  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
663  */
664 DTRACE_LOADFUNC(8)
665 DTRACE_LOADFUNC(16)
666 DTRACE_LOADFUNC(32)
667 DTRACE_LOADFUNC(64)
668 
669 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)670 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
671 {
672 	if (dest < mstate->dtms_scratch_base)
673 		return (0);
674 
675 	if (dest + size < dest)
676 		return (0);
677 
678 	if (dest + size > mstate->dtms_scratch_ptr)
679 		return (0);
680 
681 	return (1);
682 }
683 
684 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,dtrace_statvar_t ** svars,int nsvars)685 dtrace_canstore_statvar(uint64_t addr, size_t sz,
686     dtrace_statvar_t **svars, int nsvars)
687 {
688 	int i;
689 
690 	for (i = 0; i < nsvars; i++) {
691 		dtrace_statvar_t *svar = svars[i];
692 
693 		if (svar == NULL || svar->dtsv_size == 0)
694 			continue;
695 
696 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
697 			return (1);
698 	}
699 
700 	return (0);
701 }
702 
703 /*
704  * Check to see if the address is within a memory region to which a store may
705  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
706  * region.  The caller of dtrace_canstore() is responsible for performing any
707  * alignment checks that are needed before stores are actually executed.
708  */
709 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)710 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
711     dtrace_vstate_t *vstate)
712 {
713 	/*
714 	 * First, check to see if the address is in scratch space...
715 	 */
716 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
717 	    mstate->dtms_scratch_size))
718 		return (1);
719 
720 	/*
721 	 * Now check to see if it's a dynamic variable.  This check will pick
722 	 * up both thread-local variables and any global dynamically-allocated
723 	 * variables.
724 	 */
725 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
726 	    vstate->dtvs_dynvars.dtds_size)) {
727 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
728 		uintptr_t base = (uintptr_t)dstate->dtds_base +
729 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
730 		uintptr_t chunkoffs;
731 
732 		/*
733 		 * Before we assume that we can store here, we need to make
734 		 * sure that it isn't in our metadata -- storing to our
735 		 * dynamic variable metadata would corrupt our state.  For
736 		 * the range to not include any dynamic variable metadata,
737 		 * it must:
738 		 *
739 		 *	(1) Start above the hash table that is at the base of
740 		 *	the dynamic variable space
741 		 *
742 		 *	(2) Have a starting chunk offset that is beyond the
743 		 *	dtrace_dynvar_t that is at the base of every chunk
744 		 *
745 		 *	(3) Not span a chunk boundary
746 		 *
747 		 */
748 		if (addr < base)
749 			return (0);
750 
751 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
752 
753 		if (chunkoffs < sizeof (dtrace_dynvar_t))
754 			return (0);
755 
756 		if (chunkoffs + sz > dstate->dtds_chunksize)
757 			return (0);
758 
759 		return (1);
760 	}
761 
762 	/*
763 	 * Finally, check the static local and global variables.  These checks
764 	 * take the longest, so we perform them last.
765 	 */
766 	if (dtrace_canstore_statvar(addr, sz,
767 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
768 		return (1);
769 
770 	if (dtrace_canstore_statvar(addr, sz,
771 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
772 		return (1);
773 
774 	return (0);
775 }
776 
777 
778 /*
779  * Convenience routine to check to see if the address is within a memory
780  * region in which a load may be issued given the user's privilege level;
781  * if not, it sets the appropriate error flags and loads 'addr' into the
782  * illegal value slot.
783  *
784  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
785  * appropriate memory access protection.
786  */
787 static int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)788 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
789     dtrace_vstate_t *vstate)
790 {
791 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
792 
793 	/*
794 	 * If we hold the privilege to read from kernel memory, then
795 	 * everything is readable.
796 	 */
797 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
798 		return (1);
799 
800 	/*
801 	 * You can obviously read that which you can store.
802 	 */
803 	if (dtrace_canstore(addr, sz, mstate, vstate))
804 		return (1);
805 
806 	/*
807 	 * We're allowed to read from our own string table.
808 	 */
809 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
810 	    mstate->dtms_difo->dtdo_strlen))
811 		return (1);
812 
813 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
814 	*illval = addr;
815 	return (0);
816 }
817 
818 /*
819  * Convenience routine to check to see if a given string is within a memory
820  * region in which a load may be issued given the user's privilege level;
821  * this exists so that we don't need to issue unnecessary dtrace_strlen()
822  * calls in the event that the user has all privileges.
823  */
824 static int
dtrace_strcanload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)825 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
826     dtrace_vstate_t *vstate)
827 {
828 	size_t strsz;
829 
830 	/*
831 	 * If we hold the privilege to read from kernel memory, then
832 	 * everything is readable.
833 	 */
834 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
835 		return (1);
836 
837 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
838 	if (dtrace_canload(addr, strsz, mstate, vstate))
839 		return (1);
840 
841 	return (0);
842 }
843 
844 /*
845  * Convenience routine to check to see if a given variable is within a memory
846  * region in which a load may be issued given the user's privilege level.
847  */
848 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)849 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
850     dtrace_vstate_t *vstate)
851 {
852 	size_t sz;
853 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
854 
855 	/*
856 	 * If we hold the privilege to read from kernel memory, then
857 	 * everything is readable.
858 	 */
859 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
860 		return (1);
861 
862 	if (type->dtdt_kind == DIF_TYPE_STRING)
863 		sz = dtrace_strlen(src,
864 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
865 	else
866 		sz = type->dtdt_size;
867 
868 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
869 }
870 
871 /*
872  * Compare two strings using safe loads.
873  */
874 static int
dtrace_strncmp(char * s1,char * s2,size_t limit)875 dtrace_strncmp(char *s1, char *s2, size_t limit)
876 {
877 	uint8_t c1, c2;
878 	volatile uint16_t *flags;
879 
880 	if (s1 == s2 || limit == 0)
881 		return (0);
882 
883 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
884 
885 	do {
886 		if (s1 == NULL) {
887 			c1 = '\0';
888 		} else {
889 			c1 = dtrace_load8((uintptr_t)s1++);
890 		}
891 
892 		if (s2 == NULL) {
893 			c2 = '\0';
894 		} else {
895 			c2 = dtrace_load8((uintptr_t)s2++);
896 		}
897 
898 		if (c1 != c2)
899 			return (c1 - c2);
900 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
901 
902 	return (0);
903 }
904 
905 /*
906  * Compute strlen(s) for a string using safe memory accesses.  The additional
907  * len parameter is used to specify a maximum length to ensure completion.
908  */
909 static size_t
dtrace_strlen(const char * s,size_t lim)910 dtrace_strlen(const char *s, size_t lim)
911 {
912 	uint_t len;
913 
914 	for (len = 0; len != lim; len++) {
915 		if (dtrace_load8((uintptr_t)s++) == '\0')
916 			break;
917 	}
918 
919 	return (len);
920 }
921 
922 /*
923  * Check if an address falls within a toxic region.
924  */
925 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)926 dtrace_istoxic(uintptr_t kaddr, size_t size)
927 {
928 	uintptr_t taddr, tsize;
929 	int i;
930 
931 	for (i = 0; i < dtrace_toxranges; i++) {
932 		taddr = dtrace_toxrange[i].dtt_base;
933 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
934 
935 		if (kaddr - taddr < tsize) {
936 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
937 			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
938 			return (1);
939 		}
940 
941 		if (taddr - kaddr < size) {
942 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
943 			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
944 			return (1);
945 		}
946 	}
947 
948 	return (0);
949 }
950 
951 /*
952  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
953  * memory specified by the DIF program.  The dst is assumed to be safe memory
954  * that we can store to directly because it is managed by DTrace.  As with
955  * standard bcopy, overlapping copies are handled properly.
956  */
957 static void
dtrace_bcopy(const void * src,void * dst,size_t len)958 dtrace_bcopy(const void *src, void *dst, size_t len)
959 {
960 	if (len != 0) {
961 		uint8_t *s1 = dst;
962 		const uint8_t *s2 = src;
963 
964 		if (s1 <= s2) {
965 			do {
966 				*s1++ = dtrace_load8((uintptr_t)s2++);
967 			} while (--len != 0);
968 		} else {
969 			s2 += len;
970 			s1 += len;
971 
972 			do {
973 				*--s1 = dtrace_load8((uintptr_t)--s2);
974 			} while (--len != 0);
975 		}
976 	}
977 }
978 
979 /*
980  * Copy src to dst using safe memory accesses, up to either the specified
981  * length, or the point that a nul byte is encountered.  The src is assumed to
982  * be unsafe memory specified by the DIF program.  The dst is assumed to be
983  * safe memory that we can store to directly because it is managed by DTrace.
984  * Unlike dtrace_bcopy(), overlapping regions are not handled.
985  */
986 static void
dtrace_strcpy(const void * src,void * dst,size_t len)987 dtrace_strcpy(const void *src, void *dst, size_t len)
988 {
989 	if (len != 0) {
990 		uint8_t *s1 = dst, c;
991 		const uint8_t *s2 = src;
992 
993 		do {
994 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
995 		} while (--len != 0 && c != '\0');
996 	}
997 }
998 
999 /*
1000  * Copy src to dst, deriving the size and type from the specified (BYREF)
1001  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1002  * program.  The dst is assumed to be DTrace variable memory that is of the
1003  * specified type; we assume that we can store to directly.
1004  */
1005 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type)1006 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1007 {
1008 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1009 
1010 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1011 		dtrace_strcpy(src, dst, type->dtdt_size);
1012 	} else {
1013 		dtrace_bcopy(src, dst, type->dtdt_size);
1014 	}
1015 }
1016 
1017 /*
1018  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1019  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1020  * safe memory that we can access directly because it is managed by DTrace.
1021  */
1022 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1023 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1024 {
1025 	volatile uint16_t *flags;
1026 
1027 	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1028 
1029 	if (s1 == s2)
1030 		return (0);
1031 
1032 	if (s1 == NULL || s2 == NULL)
1033 		return (1);
1034 
1035 	if (s1 != s2 && len != 0) {
1036 		const uint8_t *ps1 = s1;
1037 		const uint8_t *ps2 = s2;
1038 
1039 		do {
1040 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1041 				return (1);
1042 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1043 	}
1044 	return (0);
1045 }
1046 
1047 /*
1048  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1049  * is for safe DTrace-managed memory only.
1050  */
1051 static void
dtrace_bzero(void * dst,size_t len)1052 dtrace_bzero(void *dst, size_t len)
1053 {
1054 	uchar_t *cp;
1055 
1056 	for (cp = dst; len != 0; len--)
1057 		*cp++ = 0;
1058 }
1059 
1060 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1061 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1062 {
1063 	uint64_t result[2];
1064 
1065 	result[0] = addend1[0] + addend2[0];
1066 	result[1] = addend1[1] + addend2[1] +
1067 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1068 
1069 	sum[0] = result[0];
1070 	sum[1] = result[1];
1071 }
1072 
1073 /*
1074  * Shift the 128-bit value in a by b. If b is positive, shift left.
1075  * If b is negative, shift right.
1076  */
1077 static void
dtrace_shift_128(uint64_t * a,int b)1078 dtrace_shift_128(uint64_t *a, int b)
1079 {
1080 	uint64_t mask;
1081 
1082 	if (b == 0)
1083 		return;
1084 
1085 	if (b < 0) {
1086 		b = -b;
1087 		if (b >= 64) {
1088 			a[0] = a[1] >> (b - 64);
1089 			a[1] = 0;
1090 		} else {
1091 			a[0] >>= b;
1092 			mask = 1LL << (64 - b);
1093 			mask -= 1;
1094 			a[0] |= ((a[1] & mask) << (64 - b));
1095 			a[1] >>= b;
1096 		}
1097 	} else {
1098 		if (b >= 64) {
1099 			a[1] = a[0] << (b - 64);
1100 			a[0] = 0;
1101 		} else {
1102 			a[1] <<= b;
1103 			mask = a[0] >> (64 - b);
1104 			a[1] |= mask;
1105 			a[0] <<= b;
1106 		}
1107 	}
1108 }
1109 
1110 /*
1111  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1112  * use native multiplication on those, and then re-combine into the
1113  * resulting 128-bit value.
1114  *
1115  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1116  *     hi1 * hi2 << 64 +
1117  *     hi1 * lo2 << 32 +
1118  *     hi2 * lo1 << 32 +
1119  *     lo1 * lo2
1120  */
1121 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1122 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1123 {
1124 	uint64_t hi1, hi2, lo1, lo2;
1125 	uint64_t tmp[2];
1126 
1127 	hi1 = factor1 >> 32;
1128 	hi2 = factor2 >> 32;
1129 
1130 	lo1 = factor1 & DT_MASK_LO;
1131 	lo2 = factor2 & DT_MASK_LO;
1132 
1133 	product[0] = lo1 * lo2;
1134 	product[1] = hi1 * hi2;
1135 
1136 	tmp[0] = hi1 * lo2;
1137 	tmp[1] = 0;
1138 	dtrace_shift_128(tmp, 32);
1139 	dtrace_add_128(product, tmp, product);
1140 
1141 	tmp[0] = hi2 * lo1;
1142 	tmp[1] = 0;
1143 	dtrace_shift_128(tmp, 32);
1144 	dtrace_add_128(product, tmp, product);
1145 }
1146 
1147 /*
1148  * This privilege check should be used by actions and subroutines to
1149  * verify that the user credentials of the process that enabled the
1150  * invoking ECB match the target credentials
1151  */
1152 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1153 dtrace_priv_proc_common_user(dtrace_state_t *state)
1154 {
1155 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1156 
1157 	/*
1158 	 * We should always have a non-NULL state cred here, since if cred
1159 	 * is null (anonymous tracing), we fast-path bypass this routine.
1160 	 */
1161 	ASSERT(s_cr != NULL);
1162 
1163 	if ((cr = CRED()) != NULL &&
1164 	    s_cr->cr_uid == cr->cr_uid &&
1165 	    s_cr->cr_uid == cr->cr_ruid &&
1166 	    s_cr->cr_uid == cr->cr_suid &&
1167 	    s_cr->cr_gid == cr->cr_gid &&
1168 	    s_cr->cr_gid == cr->cr_rgid &&
1169 	    s_cr->cr_gid == cr->cr_sgid)
1170 		return (1);
1171 
1172 	return (0);
1173 }
1174 
1175 /*
1176  * This privilege check should be used by actions and subroutines to
1177  * verify that the zone of the process that enabled the invoking ECB
1178  * matches the target credentials
1179  */
1180 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1181 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1182 {
1183 #if defined(sun)
1184 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1185 
1186 	/*
1187 	 * We should always have a non-NULL state cred here, since if cred
1188 	 * is null (anonymous tracing), we fast-path bypass this routine.
1189 	 */
1190 	ASSERT(s_cr != NULL);
1191 
1192 	if ((cr = CRED()) != NULL &&
1193 	    s_cr->cr_zone == cr->cr_zone)
1194 		return (1);
1195 
1196 	return (0);
1197 #else
1198 	return (1);
1199 #endif
1200 }
1201 
1202 /*
1203  * This privilege check should be used by actions and subroutines to
1204  * verify that the process has not setuid or changed credentials.
1205  */
1206 static int
dtrace_priv_proc_common_nocd(void)1207 dtrace_priv_proc_common_nocd(void)
1208 {
1209 	proc_t *proc;
1210 
1211 	if ((proc = ttoproc(curthread)) != NULL &&
1212 	    !(proc->p_flag & SNOCD))
1213 		return (1);
1214 
1215 	return (0);
1216 }
1217 
1218 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1219 dtrace_priv_proc_destructive(dtrace_state_t *state)
1220 {
1221 	int action = state->dts_cred.dcr_action;
1222 
1223 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1224 	    dtrace_priv_proc_common_zone(state) == 0)
1225 		goto bad;
1226 
1227 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1228 	    dtrace_priv_proc_common_user(state) == 0)
1229 		goto bad;
1230 
1231 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1232 	    dtrace_priv_proc_common_nocd() == 0)
1233 		goto bad;
1234 
1235 	return (1);
1236 
1237 bad:
1238 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1239 
1240 	return (0);
1241 }
1242 
1243 static int
dtrace_priv_proc_control(dtrace_state_t * state)1244 dtrace_priv_proc_control(dtrace_state_t *state)
1245 {
1246 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1247 		return (1);
1248 
1249 	if (dtrace_priv_proc_common_zone(state) &&
1250 	    dtrace_priv_proc_common_user(state) &&
1251 	    dtrace_priv_proc_common_nocd())
1252 		return (1);
1253 
1254 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1255 
1256 	return (0);
1257 }
1258 
1259 static int
dtrace_priv_proc(dtrace_state_t * state)1260 dtrace_priv_proc(dtrace_state_t *state)
1261 {
1262 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1263 		return (1);
1264 
1265 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1266 
1267 	return (0);
1268 }
1269 
1270 static int
dtrace_priv_kernel(dtrace_state_t * state)1271 dtrace_priv_kernel(dtrace_state_t *state)
1272 {
1273 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1274 		return (1);
1275 
1276 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1277 
1278 	return (0);
1279 }
1280 
1281 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1282 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1283 {
1284 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1285 		return (1);
1286 
1287 	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1288 
1289 	return (0);
1290 }
1291 
1292 /*
1293  * Note:  not called from probe context.  This function is called
1294  * asynchronously (and at a regular interval) from outside of probe context to
1295  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1296  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1297  */
1298 void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1299 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1300 {
1301 	dtrace_dynvar_t *dirty;
1302 	dtrace_dstate_percpu_t *dcpu;
1303 	int i, work = 0;
1304 
1305 	for (i = 0; i < NCPU; i++) {
1306 		dcpu = &dstate->dtds_percpu[i];
1307 
1308 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1309 
1310 		/*
1311 		 * If the dirty list is NULL, there is no dirty work to do.
1312 		 */
1313 		if (dcpu->dtdsc_dirty == NULL)
1314 			continue;
1315 
1316 		/*
1317 		 * If the clean list is non-NULL, then we're not going to do
1318 		 * any work for this CPU -- it means that there has not been
1319 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1320 		 * since the last time we cleaned house.
1321 		 */
1322 		if (dcpu->dtdsc_clean != NULL)
1323 			continue;
1324 
1325 		work = 1;
1326 
1327 		/*
1328 		 * Atomically move the dirty list aside.
1329 		 */
1330 		do {
1331 			dirty = dcpu->dtdsc_dirty;
1332 
1333 			/*
1334 			 * Before we zap the dirty list, set the rinsing list.
1335 			 * (This allows for a potential assertion in
1336 			 * dtrace_dynvar():  if a free dynamic variable appears
1337 			 * on a hash chain, either the dirty list or the
1338 			 * rinsing list for some CPU must be non-NULL.)
1339 			 */
1340 			dcpu->dtdsc_rinsing = dirty;
1341 			dtrace_membar_producer();
1342 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1343 		    dirty, NULL) != dirty);
1344 	}
1345 
1346 	if (!work) {
1347 		/*
1348 		 * We have no work to do; we can simply return.
1349 		 */
1350 		return;
1351 	}
1352 
1353 	dtrace_sync();
1354 
1355 	for (i = 0; i < NCPU; i++) {
1356 		dcpu = &dstate->dtds_percpu[i];
1357 
1358 		if (dcpu->dtdsc_rinsing == NULL)
1359 			continue;
1360 
1361 		/*
1362 		 * We are now guaranteed that no hash chain contains a pointer
1363 		 * into this dirty list; we can make it clean.
1364 		 */
1365 		ASSERT(dcpu->dtdsc_clean == NULL);
1366 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1367 		dcpu->dtdsc_rinsing = NULL;
1368 	}
1369 
1370 	/*
1371 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1372 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1373 	 * This prevents a race whereby a CPU incorrectly decides that
1374 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1375 	 * after dtrace_dynvar_clean() has completed.
1376 	 */
1377 	dtrace_sync();
1378 
1379 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1380 }
1381 
1382 /*
1383  * Depending on the value of the op parameter, this function looks-up,
1384  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1385  * allocation is requested, this function will return a pointer to a
1386  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1387  * variable can be allocated.  If NULL is returned, the appropriate counter
1388  * will be incremented.
1389  */
1390 dtrace_dynvar_t *
dtrace_dynvar(dtrace_dstate_t * dstate,uint_t nkeys,dtrace_key_t * key,size_t dsize,dtrace_dynvar_op_t op,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1391 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1392     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1393     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1394 {
1395 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1396 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1397 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1398 	processorid_t me = curcpu, cpu = me;
1399 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1400 	size_t bucket, ksize;
1401 	size_t chunksize = dstate->dtds_chunksize;
1402 	uintptr_t kdata, lock, nstate;
1403 	uint_t i;
1404 
1405 	ASSERT(nkeys != 0);
1406 
1407 	/*
1408 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1409 	 * algorithm.  For the by-value portions, we perform the algorithm in
1410 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1411 	 * bit, and seems to have only a minute effect on distribution.  For
1412 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1413 	 * over each referenced byte.  It's painful to do this, but it's much
1414 	 * better than pathological hash distribution.  The efficacy of the
1415 	 * hashing algorithm (and a comparison with other algorithms) may be
1416 	 * found by running the ::dtrace_dynstat MDB dcmd.
1417 	 */
1418 	for (i = 0; i < nkeys; i++) {
1419 		if (key[i].dttk_size == 0) {
1420 			uint64_t val = key[i].dttk_value;
1421 
1422 			hashval += (val >> 48) & 0xffff;
1423 			hashval += (hashval << 10);
1424 			hashval ^= (hashval >> 6);
1425 
1426 			hashval += (val >> 32) & 0xffff;
1427 			hashval += (hashval << 10);
1428 			hashval ^= (hashval >> 6);
1429 
1430 			hashval += (val >> 16) & 0xffff;
1431 			hashval += (hashval << 10);
1432 			hashval ^= (hashval >> 6);
1433 
1434 			hashval += val & 0xffff;
1435 			hashval += (hashval << 10);
1436 			hashval ^= (hashval >> 6);
1437 		} else {
1438 			/*
1439 			 * This is incredibly painful, but it beats the hell
1440 			 * out of the alternative.
1441 			 */
1442 			uint64_t j, size = key[i].dttk_size;
1443 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1444 
1445 			if (!dtrace_canload(base, size, mstate, vstate))
1446 				break;
1447 
1448 			for (j = 0; j < size; j++) {
1449 				hashval += dtrace_load8(base + j);
1450 				hashval += (hashval << 10);
1451 				hashval ^= (hashval >> 6);
1452 			}
1453 		}
1454 	}
1455 
1456 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1457 		return (NULL);
1458 
1459 	hashval += (hashval << 3);
1460 	hashval ^= (hashval >> 11);
1461 	hashval += (hashval << 15);
1462 
1463 	/*
1464 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1465 	 * comes out to be one of our two sentinel hash values.  If this
1466 	 * actually happens, we set the hashval to be a value known to be a
1467 	 * non-sentinel value.
1468 	 */
1469 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1470 		hashval = DTRACE_DYNHASH_VALID;
1471 
1472 	/*
1473 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1474 	 * important here, tricks can be pulled to reduce it.  (However, it's
1475 	 * critical that hash collisions be kept to an absolute minimum;
1476 	 * they're much more painful than a divide.)  It's better to have a
1477 	 * solution that generates few collisions and still keeps things
1478 	 * relatively simple.
1479 	 */
1480 	bucket = hashval % dstate->dtds_hashsize;
1481 
1482 	if (op == DTRACE_DYNVAR_DEALLOC) {
1483 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1484 
1485 		for (;;) {
1486 			while ((lock = *lockp) & 1)
1487 				continue;
1488 
1489 			if (dtrace_casptr((volatile void *)lockp,
1490 			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1491 				break;
1492 		}
1493 
1494 		dtrace_membar_producer();
1495 	}
1496 
1497 top:
1498 	prev = NULL;
1499 	lock = hash[bucket].dtdh_lock;
1500 
1501 	dtrace_membar_consumer();
1502 
1503 	start = hash[bucket].dtdh_chain;
1504 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1505 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1506 	    op != DTRACE_DYNVAR_DEALLOC));
1507 
1508 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1509 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1510 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1511 
1512 		if (dvar->dtdv_hashval != hashval) {
1513 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1514 				/*
1515 				 * We've reached the sink, and therefore the
1516 				 * end of the hash chain; we can kick out of
1517 				 * the loop knowing that we have seen a valid
1518 				 * snapshot of state.
1519 				 */
1520 				ASSERT(dvar->dtdv_next == NULL);
1521 				ASSERT(dvar == &dtrace_dynhash_sink);
1522 				break;
1523 			}
1524 
1525 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1526 				/*
1527 				 * We've gone off the rails:  somewhere along
1528 				 * the line, one of the members of this hash
1529 				 * chain was deleted.  Note that we could also
1530 				 * detect this by simply letting this loop run
1531 				 * to completion, as we would eventually hit
1532 				 * the end of the dirty list.  However, we
1533 				 * want to avoid running the length of the
1534 				 * dirty list unnecessarily (it might be quite
1535 				 * long), so we catch this as early as
1536 				 * possible by detecting the hash marker.  In
1537 				 * this case, we simply set dvar to NULL and
1538 				 * break; the conditional after the loop will
1539 				 * send us back to top.
1540 				 */
1541 				dvar = NULL;
1542 				break;
1543 			}
1544 
1545 			goto next;
1546 		}
1547 
1548 		if (dtuple->dtt_nkeys != nkeys)
1549 			goto next;
1550 
1551 		for (i = 0; i < nkeys; i++, dkey++) {
1552 			if (dkey->dttk_size != key[i].dttk_size)
1553 				goto next; /* size or type mismatch */
1554 
1555 			if (dkey->dttk_size != 0) {
1556 				if (dtrace_bcmp(
1557 				    (void *)(uintptr_t)key[i].dttk_value,
1558 				    (void *)(uintptr_t)dkey->dttk_value,
1559 				    dkey->dttk_size))
1560 					goto next;
1561 			} else {
1562 				if (dkey->dttk_value != key[i].dttk_value)
1563 					goto next;
1564 			}
1565 		}
1566 
1567 		if (op != DTRACE_DYNVAR_DEALLOC)
1568 			return (dvar);
1569 
1570 		ASSERT(dvar->dtdv_next == NULL ||
1571 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1572 
1573 		if (prev != NULL) {
1574 			ASSERT(hash[bucket].dtdh_chain != dvar);
1575 			ASSERT(start != dvar);
1576 			ASSERT(prev->dtdv_next == dvar);
1577 			prev->dtdv_next = dvar->dtdv_next;
1578 		} else {
1579 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1580 			    start, dvar->dtdv_next) != start) {
1581 				/*
1582 				 * We have failed to atomically swing the
1583 				 * hash table head pointer, presumably because
1584 				 * of a conflicting allocation on another CPU.
1585 				 * We need to reread the hash chain and try
1586 				 * again.
1587 				 */
1588 				goto top;
1589 			}
1590 		}
1591 
1592 		dtrace_membar_producer();
1593 
1594 		/*
1595 		 * Now set the hash value to indicate that it's free.
1596 		 */
1597 		ASSERT(hash[bucket].dtdh_chain != dvar);
1598 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1599 
1600 		dtrace_membar_producer();
1601 
1602 		/*
1603 		 * Set the next pointer to point at the dirty list, and
1604 		 * atomically swing the dirty pointer to the newly freed dvar.
1605 		 */
1606 		do {
1607 			next = dcpu->dtdsc_dirty;
1608 			dvar->dtdv_next = next;
1609 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1610 
1611 		/*
1612 		 * Finally, unlock this hash bucket.
1613 		 */
1614 		ASSERT(hash[bucket].dtdh_lock == lock);
1615 		ASSERT(lock & 1);
1616 		hash[bucket].dtdh_lock++;
1617 
1618 		return (NULL);
1619 next:
1620 		prev = dvar;
1621 		continue;
1622 	}
1623 
1624 	if (dvar == NULL) {
1625 		/*
1626 		 * If dvar is NULL, it is because we went off the rails:
1627 		 * one of the elements that we traversed in the hash chain
1628 		 * was deleted while we were traversing it.  In this case,
1629 		 * we assert that we aren't doing a dealloc (deallocs lock
1630 		 * the hash bucket to prevent themselves from racing with
1631 		 * one another), and retry the hash chain traversal.
1632 		 */
1633 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1634 		goto top;
1635 	}
1636 
1637 	if (op != DTRACE_DYNVAR_ALLOC) {
1638 		/*
1639 		 * If we are not to allocate a new variable, we want to
1640 		 * return NULL now.  Before we return, check that the value
1641 		 * of the lock word hasn't changed.  If it has, we may have
1642 		 * seen an inconsistent snapshot.
1643 		 */
1644 		if (op == DTRACE_DYNVAR_NOALLOC) {
1645 			if (hash[bucket].dtdh_lock != lock)
1646 				goto top;
1647 		} else {
1648 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1649 			ASSERT(hash[bucket].dtdh_lock == lock);
1650 			ASSERT(lock & 1);
1651 			hash[bucket].dtdh_lock++;
1652 		}
1653 
1654 		return (NULL);
1655 	}
1656 
1657 	/*
1658 	 * We need to allocate a new dynamic variable.  The size we need is the
1659 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1660 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1661 	 * the size of any referred-to data (dsize).  We then round the final
1662 	 * size up to the chunksize for allocation.
1663 	 */
1664 	for (ksize = 0, i = 0; i < nkeys; i++)
1665 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1666 
1667 	/*
1668 	 * This should be pretty much impossible, but could happen if, say,
1669 	 * strange DIF specified the tuple.  Ideally, this should be an
1670 	 * assertion and not an error condition -- but that requires that the
1671 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1672 	 * bullet-proof.  (That is, it must not be able to be fooled by
1673 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1674 	 * solving this would presumably not amount to solving the Halting
1675 	 * Problem -- but it still seems awfully hard.
1676 	 */
1677 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1678 	    ksize + dsize > chunksize) {
1679 		dcpu->dtdsc_drops++;
1680 		return (NULL);
1681 	}
1682 
1683 	nstate = DTRACE_DSTATE_EMPTY;
1684 
1685 	do {
1686 retry:
1687 		free = dcpu->dtdsc_free;
1688 
1689 		if (free == NULL) {
1690 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1691 			void *rval;
1692 
1693 			if (clean == NULL) {
1694 				/*
1695 				 * We're out of dynamic variable space on
1696 				 * this CPU.  Unless we have tried all CPUs,
1697 				 * we'll try to allocate from a different
1698 				 * CPU.
1699 				 */
1700 				switch (dstate->dtds_state) {
1701 				case DTRACE_DSTATE_CLEAN: {
1702 					void *sp = &dstate->dtds_state;
1703 
1704 					if (++cpu >= NCPU)
1705 						cpu = 0;
1706 
1707 					if (dcpu->dtdsc_dirty != NULL &&
1708 					    nstate == DTRACE_DSTATE_EMPTY)
1709 						nstate = DTRACE_DSTATE_DIRTY;
1710 
1711 					if (dcpu->dtdsc_rinsing != NULL)
1712 						nstate = DTRACE_DSTATE_RINSING;
1713 
1714 					dcpu = &dstate->dtds_percpu[cpu];
1715 
1716 					if (cpu != me)
1717 						goto retry;
1718 
1719 					(void) dtrace_cas32(sp,
1720 					    DTRACE_DSTATE_CLEAN, nstate);
1721 
1722 					/*
1723 					 * To increment the correct bean
1724 					 * counter, take another lap.
1725 					 */
1726 					goto retry;
1727 				}
1728 
1729 				case DTRACE_DSTATE_DIRTY:
1730 					dcpu->dtdsc_dirty_drops++;
1731 					break;
1732 
1733 				case DTRACE_DSTATE_RINSING:
1734 					dcpu->dtdsc_rinsing_drops++;
1735 					break;
1736 
1737 				case DTRACE_DSTATE_EMPTY:
1738 					dcpu->dtdsc_drops++;
1739 					break;
1740 				}
1741 
1742 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1743 				return (NULL);
1744 			}
1745 
1746 			/*
1747 			 * The clean list appears to be non-empty.  We want to
1748 			 * move the clean list to the free list; we start by
1749 			 * moving the clean pointer aside.
1750 			 */
1751 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1752 			    clean, NULL) != clean) {
1753 				/*
1754 				 * We are in one of two situations:
1755 				 *
1756 				 *  (a)	The clean list was switched to the
1757 				 *	free list by another CPU.
1758 				 *
1759 				 *  (b)	The clean list was added to by the
1760 				 *	cleansing cyclic.
1761 				 *
1762 				 * In either of these situations, we can
1763 				 * just reattempt the free list allocation.
1764 				 */
1765 				goto retry;
1766 			}
1767 
1768 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1769 
1770 			/*
1771 			 * Now we'll move the clean list to the free list.
1772 			 * It's impossible for this to fail:  the only way
1773 			 * the free list can be updated is through this
1774 			 * code path, and only one CPU can own the clean list.
1775 			 * Thus, it would only be possible for this to fail if
1776 			 * this code were racing with dtrace_dynvar_clean().
1777 			 * (That is, if dtrace_dynvar_clean() updated the clean
1778 			 * list, and we ended up racing to update the free
1779 			 * list.)  This race is prevented by the dtrace_sync()
1780 			 * in dtrace_dynvar_clean() -- which flushes the
1781 			 * owners of the clean lists out before resetting
1782 			 * the clean lists.
1783 			 */
1784 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1785 			ASSERT(rval == NULL);
1786 			goto retry;
1787 		}
1788 
1789 		dvar = free;
1790 		new_free = dvar->dtdv_next;
1791 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1792 
1793 	/*
1794 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1795 	 * tuple array and copy any referenced key data into the data space
1796 	 * following the tuple array.  As we do this, we relocate dttk_value
1797 	 * in the final tuple to point to the key data address in the chunk.
1798 	 */
1799 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1800 	dvar->dtdv_data = (void *)(kdata + ksize);
1801 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1802 
1803 	for (i = 0; i < nkeys; i++) {
1804 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1805 		size_t kesize = key[i].dttk_size;
1806 
1807 		if (kesize != 0) {
1808 			dtrace_bcopy(
1809 			    (const void *)(uintptr_t)key[i].dttk_value,
1810 			    (void *)kdata, kesize);
1811 			dkey->dttk_value = kdata;
1812 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1813 		} else {
1814 			dkey->dttk_value = key[i].dttk_value;
1815 		}
1816 
1817 		dkey->dttk_size = kesize;
1818 	}
1819 
1820 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1821 	dvar->dtdv_hashval = hashval;
1822 	dvar->dtdv_next = start;
1823 
1824 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1825 		return (dvar);
1826 
1827 	/*
1828 	 * The cas has failed.  Either another CPU is adding an element to
1829 	 * this hash chain, or another CPU is deleting an element from this
1830 	 * hash chain.  The simplest way to deal with both of these cases
1831 	 * (though not necessarily the most efficient) is to free our
1832 	 * allocated block and tail-call ourselves.  Note that the free is
1833 	 * to the dirty list and _not_ to the free list.  This is to prevent
1834 	 * races with allocators, above.
1835 	 */
1836 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1837 
1838 	dtrace_membar_producer();
1839 
1840 	do {
1841 		free = dcpu->dtdsc_dirty;
1842 		dvar->dtdv_next = free;
1843 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1844 
1845 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1846 }
1847 
1848 /*ARGSUSED*/
1849 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)1850 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1851 {
1852 	if ((int64_t)nval < (int64_t)*oval)
1853 		*oval = nval;
1854 }
1855 
1856 /*ARGSUSED*/
1857 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)1858 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1859 {
1860 	if ((int64_t)nval > (int64_t)*oval)
1861 		*oval = nval;
1862 }
1863 
1864 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)1865 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1866 {
1867 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1868 	int64_t val = (int64_t)nval;
1869 
1870 	if (val < 0) {
1871 		for (i = 0; i < zero; i++) {
1872 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1873 				quanta[i] += incr;
1874 				return;
1875 			}
1876 		}
1877 	} else {
1878 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1879 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1880 				quanta[i - 1] += incr;
1881 				return;
1882 			}
1883 		}
1884 
1885 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1886 		return;
1887 	}
1888 
1889 	ASSERT(0);
1890 }
1891 
1892 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)1893 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1894 {
1895 	uint64_t arg = *lquanta++;
1896 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1897 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1898 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1899 	int32_t val = (int32_t)nval, level;
1900 
1901 	ASSERT(step != 0);
1902 	ASSERT(levels != 0);
1903 
1904 	if (val < base) {
1905 		/*
1906 		 * This is an underflow.
1907 		 */
1908 		lquanta[0] += incr;
1909 		return;
1910 	}
1911 
1912 	level = (val - base) / step;
1913 
1914 	if (level < levels) {
1915 		lquanta[level + 1] += incr;
1916 		return;
1917 	}
1918 
1919 	/*
1920 	 * This is an overflow.
1921 	 */
1922 	lquanta[levels + 1] += incr;
1923 }
1924 
1925 static int
dtrace_aggregate_llquantize_bucket(uint16_t factor,uint16_t low,uint16_t high,uint16_t nsteps,int64_t value)1926 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
1927     uint16_t high, uint16_t nsteps, int64_t value)
1928 {
1929 	int64_t this = 1, last, next;
1930 	int base = 1, order;
1931 
1932 	ASSERT(factor <= nsteps);
1933 	ASSERT(nsteps % factor == 0);
1934 
1935 	for (order = 0; order < low; order++)
1936 		this *= factor;
1937 
1938 	/*
1939 	 * If our value is less than our factor taken to the power of the
1940 	 * low order of magnitude, it goes into the zeroth bucket.
1941 	 */
1942 	if (value < (last = this))
1943 		return (0);
1944 
1945 	for (this *= factor; order <= high; order++) {
1946 		int nbuckets = this > nsteps ? nsteps : this;
1947 
1948 		if ((next = this * factor) < this) {
1949 			/*
1950 			 * We should not generally get log/linear quantizations
1951 			 * with a high magnitude that allows 64-bits to
1952 			 * overflow, but we nonetheless protect against this
1953 			 * by explicitly checking for overflow, and clamping
1954 			 * our value accordingly.
1955 			 */
1956 			value = this - 1;
1957 		}
1958 
1959 		if (value < this) {
1960 			/*
1961 			 * If our value lies within this order of magnitude,
1962 			 * determine its position by taking the offset within
1963 			 * the order of magnitude, dividing by the bucket
1964 			 * width, and adding to our (accumulated) base.
1965 			 */
1966 			return (base + (value - last) / (this / nbuckets));
1967 		}
1968 
1969 		base += nbuckets - (nbuckets / factor);
1970 		last = this;
1971 		this = next;
1972 	}
1973 
1974 	/*
1975 	 * Our value is greater than or equal to our factor taken to the
1976 	 * power of one plus the high magnitude -- return the top bucket.
1977 	 */
1978 	return (base);
1979 }
1980 
1981 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)1982 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
1983 {
1984 	uint64_t arg = *llquanta++;
1985 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
1986 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
1987 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
1988 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
1989 
1990 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
1991 	    low, high, nsteps, nval)] += incr;
1992 }
1993 
1994 /*ARGSUSED*/
1995 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)1996 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1997 {
1998 	data[0]++;
1999 	data[1] += nval;
2000 }
2001 
2002 /*ARGSUSED*/
2003 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2004 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2005 {
2006 	int64_t snval = (int64_t)nval;
2007 	uint64_t tmp[2];
2008 
2009 	data[0]++;
2010 	data[1] += nval;
2011 
2012 	/*
2013 	 * What we want to say here is:
2014 	 *
2015 	 * data[2] += nval * nval;
2016 	 *
2017 	 * But given that nval is 64-bit, we could easily overflow, so
2018 	 * we do this as 128-bit arithmetic.
2019 	 */
2020 	if (snval < 0)
2021 		snval = -snval;
2022 
2023 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2024 	dtrace_add_128(data + 2, tmp, data + 2);
2025 }
2026 
2027 /*ARGSUSED*/
2028 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2029 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2030 {
2031 	*oval = *oval + 1;
2032 }
2033 
2034 /*ARGSUSED*/
2035 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2036 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2037 {
2038 	*oval += nval;
2039 }
2040 
2041 /*
2042  * Aggregate given the tuple in the principal data buffer, and the aggregating
2043  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2044  * buffer is specified as the buf parameter.  This routine does not return
2045  * failure; if there is no space in the aggregation buffer, the data will be
2046  * dropped, and a corresponding counter incremented.
2047  */
2048 static void
dtrace_aggregate(dtrace_aggregation_t * agg,dtrace_buffer_t * dbuf,intptr_t offset,dtrace_buffer_t * buf,uint64_t expr,uint64_t arg)2049 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2050     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2051 {
2052 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2053 	uint32_t i, ndx, size, fsize;
2054 	uint32_t align = sizeof (uint64_t) - 1;
2055 	dtrace_aggbuffer_t *agb;
2056 	dtrace_aggkey_t *key;
2057 	uint32_t hashval = 0, limit, isstr;
2058 	caddr_t tomax, data, kdata;
2059 	dtrace_actkind_t action;
2060 	dtrace_action_t *act;
2061 	uintptr_t offs;
2062 
2063 	if (buf == NULL)
2064 		return;
2065 
2066 	if (!agg->dtag_hasarg) {
2067 		/*
2068 		 * Currently, only quantize() and lquantize() take additional
2069 		 * arguments, and they have the same semantics:  an increment
2070 		 * value that defaults to 1 when not present.  If additional
2071 		 * aggregating actions take arguments, the setting of the
2072 		 * default argument value will presumably have to become more
2073 		 * sophisticated...
2074 		 */
2075 		arg = 1;
2076 	}
2077 
2078 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2079 	size = rec->dtrd_offset - agg->dtag_base;
2080 	fsize = size + rec->dtrd_size;
2081 
2082 	ASSERT(dbuf->dtb_tomax != NULL);
2083 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2084 
2085 	if ((tomax = buf->dtb_tomax) == NULL) {
2086 		dtrace_buffer_drop(buf);
2087 		return;
2088 	}
2089 
2090 	/*
2091 	 * The metastructure is always at the bottom of the buffer.
2092 	 */
2093 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2094 	    sizeof (dtrace_aggbuffer_t));
2095 
2096 	if (buf->dtb_offset == 0) {
2097 		/*
2098 		 * We just kludge up approximately 1/8th of the size to be
2099 		 * buckets.  If this guess ends up being routinely
2100 		 * off-the-mark, we may need to dynamically readjust this
2101 		 * based on past performance.
2102 		 */
2103 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2104 
2105 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2106 		    (uintptr_t)tomax || hashsize == 0) {
2107 			/*
2108 			 * We've been given a ludicrously small buffer;
2109 			 * increment our drop count and leave.
2110 			 */
2111 			dtrace_buffer_drop(buf);
2112 			return;
2113 		}
2114 
2115 		/*
2116 		 * And now, a pathetic attempt to try to get a an odd (or
2117 		 * perchance, a prime) hash size for better hash distribution.
2118 		 */
2119 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2120 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2121 
2122 		agb->dtagb_hashsize = hashsize;
2123 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2124 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2125 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2126 
2127 		for (i = 0; i < agb->dtagb_hashsize; i++)
2128 			agb->dtagb_hash[i] = NULL;
2129 	}
2130 
2131 	ASSERT(agg->dtag_first != NULL);
2132 	ASSERT(agg->dtag_first->dta_intuple);
2133 
2134 	/*
2135 	 * Calculate the hash value based on the key.  Note that we _don't_
2136 	 * include the aggid in the hashing (but we will store it as part of
2137 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2138 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2139 	 * gets good distribution in practice.  The efficacy of the hashing
2140 	 * algorithm (and a comparison with other algorithms) may be found by
2141 	 * running the ::dtrace_aggstat MDB dcmd.
2142 	 */
2143 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2144 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2145 		limit = i + act->dta_rec.dtrd_size;
2146 		ASSERT(limit <= size);
2147 		isstr = DTRACEACT_ISSTRING(act);
2148 
2149 		for (; i < limit; i++) {
2150 			hashval += data[i];
2151 			hashval += (hashval << 10);
2152 			hashval ^= (hashval >> 6);
2153 
2154 			if (isstr && data[i] == '\0')
2155 				break;
2156 		}
2157 	}
2158 
2159 	hashval += (hashval << 3);
2160 	hashval ^= (hashval >> 11);
2161 	hashval += (hashval << 15);
2162 
2163 	/*
2164 	 * Yes, the divide here is expensive -- but it's generally the least
2165 	 * of the performance issues given the amount of data that we iterate
2166 	 * over to compute hash values, compare data, etc.
2167 	 */
2168 	ndx = hashval % agb->dtagb_hashsize;
2169 
2170 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2171 		ASSERT((caddr_t)key >= tomax);
2172 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2173 
2174 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2175 			continue;
2176 
2177 		kdata = key->dtak_data;
2178 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2179 
2180 		for (act = agg->dtag_first; act->dta_intuple;
2181 		    act = act->dta_next) {
2182 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2183 			limit = i + act->dta_rec.dtrd_size;
2184 			ASSERT(limit <= size);
2185 			isstr = DTRACEACT_ISSTRING(act);
2186 
2187 			for (; i < limit; i++) {
2188 				if (kdata[i] != data[i])
2189 					goto next;
2190 
2191 				if (isstr && data[i] == '\0')
2192 					break;
2193 			}
2194 		}
2195 
2196 		if (action != key->dtak_action) {
2197 			/*
2198 			 * We are aggregating on the same value in the same
2199 			 * aggregation with two different aggregating actions.
2200 			 * (This should have been picked up in the compiler,
2201 			 * so we may be dealing with errant or devious DIF.)
2202 			 * This is an error condition; we indicate as much,
2203 			 * and return.
2204 			 */
2205 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2206 			return;
2207 		}
2208 
2209 		/*
2210 		 * This is a hit:  we need to apply the aggregator to
2211 		 * the value at this key.
2212 		 */
2213 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2214 		return;
2215 next:
2216 		continue;
2217 	}
2218 
2219 	/*
2220 	 * We didn't find it.  We need to allocate some zero-filled space,
2221 	 * link it into the hash table appropriately, and apply the aggregator
2222 	 * to the (zero-filled) value.
2223 	 */
2224 	offs = buf->dtb_offset;
2225 	while (offs & (align - 1))
2226 		offs += sizeof (uint32_t);
2227 
2228 	/*
2229 	 * If we don't have enough room to both allocate a new key _and_
2230 	 * its associated data, increment the drop count and return.
2231 	 */
2232 	if ((uintptr_t)tomax + offs + fsize >
2233 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2234 		dtrace_buffer_drop(buf);
2235 		return;
2236 	}
2237 
2238 	/*CONSTCOND*/
2239 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2240 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2241 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2242 
2243 	key->dtak_data = kdata = tomax + offs;
2244 	buf->dtb_offset = offs + fsize;
2245 
2246 	/*
2247 	 * Now copy the data across.
2248 	 */
2249 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2250 
2251 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2252 		kdata[i] = data[i];
2253 
2254 	/*
2255 	 * Because strings are not zeroed out by default, we need to iterate
2256 	 * looking for actions that store strings, and we need to explicitly
2257 	 * pad these strings out with zeroes.
2258 	 */
2259 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2260 		int nul;
2261 
2262 		if (!DTRACEACT_ISSTRING(act))
2263 			continue;
2264 
2265 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2266 		limit = i + act->dta_rec.dtrd_size;
2267 		ASSERT(limit <= size);
2268 
2269 		for (nul = 0; i < limit; i++) {
2270 			if (nul) {
2271 				kdata[i] = '\0';
2272 				continue;
2273 			}
2274 
2275 			if (data[i] != '\0')
2276 				continue;
2277 
2278 			nul = 1;
2279 		}
2280 	}
2281 
2282 	for (i = size; i < fsize; i++)
2283 		kdata[i] = 0;
2284 
2285 	key->dtak_hashval = hashval;
2286 	key->dtak_size = size;
2287 	key->dtak_action = action;
2288 	key->dtak_next = agb->dtagb_hash[ndx];
2289 	agb->dtagb_hash[ndx] = key;
2290 
2291 	/*
2292 	 * Finally, apply the aggregator.
2293 	 */
2294 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2295 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2296 }
2297 
2298 /*
2299  * Given consumer state, this routine finds a speculation in the INACTIVE
2300  * state and transitions it into the ACTIVE state.  If there is no speculation
2301  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2302  * incremented -- it is up to the caller to take appropriate action.
2303  */
2304 static int
dtrace_speculation(dtrace_state_t * state)2305 dtrace_speculation(dtrace_state_t *state)
2306 {
2307 	int i = 0;
2308 	dtrace_speculation_state_t current;
2309 	uint32_t *stat = &state->dts_speculations_unavail, count;
2310 
2311 	while (i < state->dts_nspeculations) {
2312 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2313 
2314 		current = spec->dtsp_state;
2315 
2316 		if (current != DTRACESPEC_INACTIVE) {
2317 			if (current == DTRACESPEC_COMMITTINGMANY ||
2318 			    current == DTRACESPEC_COMMITTING ||
2319 			    current == DTRACESPEC_DISCARDING)
2320 				stat = &state->dts_speculations_busy;
2321 			i++;
2322 			continue;
2323 		}
2324 
2325 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2326 		    current, DTRACESPEC_ACTIVE) == current)
2327 			return (i + 1);
2328 	}
2329 
2330 	/*
2331 	 * We couldn't find a speculation.  If we found as much as a single
2332 	 * busy speculation buffer, we'll attribute this failure as "busy"
2333 	 * instead of "unavail".
2334 	 */
2335 	do {
2336 		count = *stat;
2337 	} while (dtrace_cas32(stat, count, count + 1) != count);
2338 
2339 	return (0);
2340 }
2341 
2342 /*
2343  * This routine commits an active speculation.  If the specified speculation
2344  * is not in a valid state to perform a commit(), this routine will silently do
2345  * nothing.  The state of the specified speculation is transitioned according
2346  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2347  */
2348 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2349 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2350     dtrace_specid_t which)
2351 {
2352 	dtrace_speculation_t *spec;
2353 	dtrace_buffer_t *src, *dest;
2354 	uintptr_t daddr, saddr, dlimit, slimit;
2355 	dtrace_speculation_state_t current, new = 0;
2356 	intptr_t offs;
2357 	uint64_t timestamp;
2358 
2359 	if (which == 0)
2360 		return;
2361 
2362 	if (which > state->dts_nspeculations) {
2363 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2364 		return;
2365 	}
2366 
2367 	spec = &state->dts_speculations[which - 1];
2368 	src = &spec->dtsp_buffer[cpu];
2369 	dest = &state->dts_buffer[cpu];
2370 
2371 	do {
2372 		current = spec->dtsp_state;
2373 
2374 		if (current == DTRACESPEC_COMMITTINGMANY)
2375 			break;
2376 
2377 		switch (current) {
2378 		case DTRACESPEC_INACTIVE:
2379 		case DTRACESPEC_DISCARDING:
2380 			return;
2381 
2382 		case DTRACESPEC_COMMITTING:
2383 			/*
2384 			 * This is only possible if we are (a) commit()'ing
2385 			 * without having done a prior speculate() on this CPU
2386 			 * and (b) racing with another commit() on a different
2387 			 * CPU.  There's nothing to do -- we just assert that
2388 			 * our offset is 0.
2389 			 */
2390 			ASSERT(src->dtb_offset == 0);
2391 			return;
2392 
2393 		case DTRACESPEC_ACTIVE:
2394 			new = DTRACESPEC_COMMITTING;
2395 			break;
2396 
2397 		case DTRACESPEC_ACTIVEONE:
2398 			/*
2399 			 * This speculation is active on one CPU.  If our
2400 			 * buffer offset is non-zero, we know that the one CPU
2401 			 * must be us.  Otherwise, we are committing on a
2402 			 * different CPU from the speculate(), and we must
2403 			 * rely on being asynchronously cleaned.
2404 			 */
2405 			if (src->dtb_offset != 0) {
2406 				new = DTRACESPEC_COMMITTING;
2407 				break;
2408 			}
2409 			/*FALLTHROUGH*/
2410 
2411 		case DTRACESPEC_ACTIVEMANY:
2412 			new = DTRACESPEC_COMMITTINGMANY;
2413 			break;
2414 
2415 		default:
2416 			ASSERT(0);
2417 		}
2418 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2419 	    current, new) != current);
2420 
2421 	/*
2422 	 * We have set the state to indicate that we are committing this
2423 	 * speculation.  Now reserve the necessary space in the destination
2424 	 * buffer.
2425 	 */
2426 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2427 	    sizeof (uint64_t), state, NULL)) < 0) {
2428 		dtrace_buffer_drop(dest);
2429 		goto out;
2430 	}
2431 
2432 	/*
2433 	 * We have sufficient space to copy the speculative buffer into the
2434 	 * primary buffer.  First, modify the speculative buffer, filling
2435 	 * in the timestamp of all entries with the current time.  The data
2436 	 * must have the commit() time rather than the time it was traced,
2437 	 * so that all entries in the primary buffer are in timestamp order.
2438 	 */
2439 	timestamp = dtrace_gethrtime();
2440 	saddr = (uintptr_t)src->dtb_tomax;
2441 	slimit = saddr + src->dtb_offset;
2442 	while (saddr < slimit) {
2443 		size_t size;
2444 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2445 
2446 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2447 			saddr += sizeof (dtrace_epid_t);
2448 			continue;
2449 		}
2450 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2451 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2452 
2453 		ASSERT3U(saddr + size, <=, slimit);
2454 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2455 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2456 
2457 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2458 
2459 		saddr += size;
2460 	}
2461 
2462 	/*
2463 	 * Copy the buffer across.  (Note that this is a
2464 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2465 	 * a serious performance issue, a high-performance DTrace-specific
2466 	 * bcopy() should obviously be invented.)
2467 	 */
2468 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2469 	dlimit = daddr + src->dtb_offset;
2470 	saddr = (uintptr_t)src->dtb_tomax;
2471 
2472 	/*
2473 	 * First, the aligned portion.
2474 	 */
2475 	while (dlimit - daddr >= sizeof (uint64_t)) {
2476 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2477 
2478 		daddr += sizeof (uint64_t);
2479 		saddr += sizeof (uint64_t);
2480 	}
2481 
2482 	/*
2483 	 * Now any left-over bit...
2484 	 */
2485 	while (dlimit - daddr)
2486 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2487 
2488 	/*
2489 	 * Finally, commit the reserved space in the destination buffer.
2490 	 */
2491 	dest->dtb_offset = offs + src->dtb_offset;
2492 
2493 out:
2494 	/*
2495 	 * If we're lucky enough to be the only active CPU on this speculation
2496 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2497 	 */
2498 	if (current == DTRACESPEC_ACTIVE ||
2499 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2500 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2501 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2502 
2503 		ASSERT(rval == DTRACESPEC_COMMITTING);
2504 	}
2505 
2506 	src->dtb_offset = 0;
2507 	src->dtb_xamot_drops += src->dtb_drops;
2508 	src->dtb_drops = 0;
2509 }
2510 
2511 /*
2512  * This routine discards an active speculation.  If the specified speculation
2513  * is not in a valid state to perform a discard(), this routine will silently
2514  * do nothing.  The state of the specified speculation is transitioned
2515  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2516  */
2517 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2518 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2519     dtrace_specid_t which)
2520 {
2521 	dtrace_speculation_t *spec;
2522 	dtrace_speculation_state_t current, new = 0;
2523 	dtrace_buffer_t *buf;
2524 
2525 	if (which == 0)
2526 		return;
2527 
2528 	if (which > state->dts_nspeculations) {
2529 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2530 		return;
2531 	}
2532 
2533 	spec = &state->dts_speculations[which - 1];
2534 	buf = &spec->dtsp_buffer[cpu];
2535 
2536 	do {
2537 		current = spec->dtsp_state;
2538 
2539 		switch (current) {
2540 		case DTRACESPEC_INACTIVE:
2541 		case DTRACESPEC_COMMITTINGMANY:
2542 		case DTRACESPEC_COMMITTING:
2543 		case DTRACESPEC_DISCARDING:
2544 			return;
2545 
2546 		case DTRACESPEC_ACTIVE:
2547 		case DTRACESPEC_ACTIVEMANY:
2548 			new = DTRACESPEC_DISCARDING;
2549 			break;
2550 
2551 		case DTRACESPEC_ACTIVEONE:
2552 			if (buf->dtb_offset != 0) {
2553 				new = DTRACESPEC_INACTIVE;
2554 			} else {
2555 				new = DTRACESPEC_DISCARDING;
2556 			}
2557 			break;
2558 
2559 		default:
2560 			ASSERT(0);
2561 		}
2562 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2563 	    current, new) != current);
2564 
2565 	buf->dtb_offset = 0;
2566 	buf->dtb_drops = 0;
2567 }
2568 
2569 /*
2570  * Note:  not called from probe context.  This function is called
2571  * asynchronously from cross call context to clean any speculations that are
2572  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2573  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2574  * speculation.
2575  */
2576 static void
dtrace_speculation_clean_here(dtrace_state_t * state)2577 dtrace_speculation_clean_here(dtrace_state_t *state)
2578 {
2579 	dtrace_icookie_t cookie;
2580 	processorid_t cpu = curcpu;
2581 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2582 	dtrace_specid_t i;
2583 
2584 	cookie = dtrace_interrupt_disable();
2585 
2586 	if (dest->dtb_tomax == NULL) {
2587 		dtrace_interrupt_enable(cookie);
2588 		return;
2589 	}
2590 
2591 	for (i = 0; i < state->dts_nspeculations; i++) {
2592 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2593 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2594 
2595 		if (src->dtb_tomax == NULL)
2596 			continue;
2597 
2598 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2599 			src->dtb_offset = 0;
2600 			continue;
2601 		}
2602 
2603 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2604 			continue;
2605 
2606 		if (src->dtb_offset == 0)
2607 			continue;
2608 
2609 		dtrace_speculation_commit(state, cpu, i + 1);
2610 	}
2611 
2612 	dtrace_interrupt_enable(cookie);
2613 }
2614 
2615 /*
2616  * Note:  not called from probe context.  This function is called
2617  * asynchronously (and at a regular interval) to clean any speculations that
2618  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2619  * is work to be done, it cross calls all CPUs to perform that work;
2620  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2621  * INACTIVE state until they have been cleaned by all CPUs.
2622  */
2623 static void
dtrace_speculation_clean(dtrace_state_t * state)2624 dtrace_speculation_clean(dtrace_state_t *state)
2625 {
2626 	int work = 0, rv;
2627 	dtrace_specid_t i;
2628 
2629 	for (i = 0; i < state->dts_nspeculations; i++) {
2630 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2631 
2632 		ASSERT(!spec->dtsp_cleaning);
2633 
2634 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2635 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2636 			continue;
2637 
2638 		work++;
2639 		spec->dtsp_cleaning = 1;
2640 	}
2641 
2642 	if (!work)
2643 		return;
2644 
2645 	dtrace_xcall(DTRACE_CPUALL,
2646 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2647 
2648 	/*
2649 	 * We now know that all CPUs have committed or discarded their
2650 	 * speculation buffers, as appropriate.  We can now set the state
2651 	 * to inactive.
2652 	 */
2653 	for (i = 0; i < state->dts_nspeculations; i++) {
2654 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2655 		dtrace_speculation_state_t current, new;
2656 
2657 		if (!spec->dtsp_cleaning)
2658 			continue;
2659 
2660 		current = spec->dtsp_state;
2661 		ASSERT(current == DTRACESPEC_DISCARDING ||
2662 		    current == DTRACESPEC_COMMITTINGMANY);
2663 
2664 		new = DTRACESPEC_INACTIVE;
2665 
2666 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2667 		ASSERT(rv == current);
2668 		spec->dtsp_cleaning = 0;
2669 	}
2670 }
2671 
2672 /*
2673  * Called as part of a speculate() to get the speculative buffer associated
2674  * with a given speculation.  Returns NULL if the specified speculation is not
2675  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2676  * the active CPU is not the specified CPU -- the speculation will be
2677  * atomically transitioned into the ACTIVEMANY state.
2678  */
2679 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)2680 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2681     dtrace_specid_t which)
2682 {
2683 	dtrace_speculation_t *spec;
2684 	dtrace_speculation_state_t current, new = 0;
2685 	dtrace_buffer_t *buf;
2686 
2687 	if (which == 0)
2688 		return (NULL);
2689 
2690 	if (which > state->dts_nspeculations) {
2691 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2692 		return (NULL);
2693 	}
2694 
2695 	spec = &state->dts_speculations[which - 1];
2696 	buf = &spec->dtsp_buffer[cpuid];
2697 
2698 	do {
2699 		current = spec->dtsp_state;
2700 
2701 		switch (current) {
2702 		case DTRACESPEC_INACTIVE:
2703 		case DTRACESPEC_COMMITTINGMANY:
2704 		case DTRACESPEC_DISCARDING:
2705 			return (NULL);
2706 
2707 		case DTRACESPEC_COMMITTING:
2708 			ASSERT(buf->dtb_offset == 0);
2709 			return (NULL);
2710 
2711 		case DTRACESPEC_ACTIVEONE:
2712 			/*
2713 			 * This speculation is currently active on one CPU.
2714 			 * Check the offset in the buffer; if it's non-zero,
2715 			 * that CPU must be us (and we leave the state alone).
2716 			 * If it's zero, assume that we're starting on a new
2717 			 * CPU -- and change the state to indicate that the
2718 			 * speculation is active on more than one CPU.
2719 			 */
2720 			if (buf->dtb_offset != 0)
2721 				return (buf);
2722 
2723 			new = DTRACESPEC_ACTIVEMANY;
2724 			break;
2725 
2726 		case DTRACESPEC_ACTIVEMANY:
2727 			return (buf);
2728 
2729 		case DTRACESPEC_ACTIVE:
2730 			new = DTRACESPEC_ACTIVEONE;
2731 			break;
2732 
2733 		default:
2734 			ASSERT(0);
2735 		}
2736 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2737 	    current, new) != current);
2738 
2739 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2740 	return (buf);
2741 }
2742 
2743 /*
2744  * Return a string.  In the event that the user lacks the privilege to access
2745  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2746  * don't fail access checking.
2747  *
2748  * dtrace_dif_variable() uses this routine as a helper for various
2749  * builtin values such as 'execname' and 'probefunc.'
2750  */
2751 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)2752 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2753     dtrace_mstate_t *mstate)
2754 {
2755 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2756 	uintptr_t ret;
2757 	size_t strsz;
2758 
2759 	/*
2760 	 * The easy case: this probe is allowed to read all of memory, so
2761 	 * we can just return this as a vanilla pointer.
2762 	 */
2763 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2764 		return (addr);
2765 
2766 	/*
2767 	 * This is the tougher case: we copy the string in question from
2768 	 * kernel memory into scratch memory and return it that way: this
2769 	 * ensures that we won't trip up when access checking tests the
2770 	 * BYREF return value.
2771 	 */
2772 	strsz = dtrace_strlen((char *)addr, size) + 1;
2773 
2774 	if (mstate->dtms_scratch_ptr + strsz >
2775 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2776 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2777 		return (0);
2778 	}
2779 
2780 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2781 	    strsz);
2782 	ret = mstate->dtms_scratch_ptr;
2783 	mstate->dtms_scratch_ptr += strsz;
2784 	return (ret);
2785 }
2786 
2787 /*
2788  * Return a string from a memoy address which is known to have one or
2789  * more concatenated, individually zero terminated, sub-strings.
2790  * In the event that the user lacks the privilege to access
2791  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2792  * don't fail access checking.
2793  *
2794  * dtrace_dif_variable() uses this routine as a helper for various
2795  * builtin values such as 'execargs'.
2796  */
2797 static uintptr_t
dtrace_dif_varstrz(uintptr_t addr,size_t strsz,dtrace_state_t * state,dtrace_mstate_t * mstate)2798 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
2799     dtrace_mstate_t *mstate)
2800 {
2801 	char *p;
2802 	size_t i;
2803 	uintptr_t ret;
2804 
2805 	if (mstate->dtms_scratch_ptr + strsz >
2806 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2807 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2808 		return (0);
2809 	}
2810 
2811 	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2812 	    strsz);
2813 
2814 	/* Replace sub-string termination characters with a space. */
2815 	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
2816 	    p++, i++)
2817 		if (*p == '\0')
2818 			*p = ' ';
2819 
2820 	ret = mstate->dtms_scratch_ptr;
2821 	mstate->dtms_scratch_ptr += strsz;
2822 	return (ret);
2823 }
2824 
2825 /*
2826  * This function implements the DIF emulator's variable lookups.  The emulator
2827  * passes a reserved variable identifier and optional built-in array index.
2828  */
2829 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)2830 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2831     uint64_t ndx)
2832 {
2833 	/*
2834 	 * If we're accessing one of the uncached arguments, we'll turn this
2835 	 * into a reference in the args array.
2836 	 */
2837 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2838 		ndx = v - DIF_VAR_ARG0;
2839 		v = DIF_VAR_ARGS;
2840 	}
2841 
2842 	switch (v) {
2843 	case DIF_VAR_ARGS:
2844 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2845 		if (ndx >= sizeof (mstate->dtms_arg) /
2846 		    sizeof (mstate->dtms_arg[0])) {
2847 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2848 			dtrace_provider_t *pv;
2849 			uint64_t val;
2850 
2851 			pv = mstate->dtms_probe->dtpr_provider;
2852 			if (pv->dtpv_pops.dtps_getargval != NULL)
2853 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2854 				    mstate->dtms_probe->dtpr_id,
2855 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2856 			else
2857 				val = dtrace_getarg(ndx, aframes);
2858 
2859 			/*
2860 			 * This is regrettably required to keep the compiler
2861 			 * from tail-optimizing the call to dtrace_getarg().
2862 			 * The condition always evaluates to true, but the
2863 			 * compiler has no way of figuring that out a priori.
2864 			 * (None of this would be necessary if the compiler
2865 			 * could be relied upon to _always_ tail-optimize
2866 			 * the call to dtrace_getarg() -- but it can't.)
2867 			 */
2868 			if (mstate->dtms_probe != NULL)
2869 				return (val);
2870 
2871 			ASSERT(0);
2872 		}
2873 
2874 		return (mstate->dtms_arg[ndx]);
2875 
2876 #if defined(sun)
2877 	case DIF_VAR_UREGS: {
2878 		klwp_t *lwp;
2879 
2880 		if (!dtrace_priv_proc(state))
2881 			return (0);
2882 
2883 		if ((lwp = curthread->t_lwp) == NULL) {
2884 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2885 			cpu_core[curcpu].cpuc_dtrace_illval = NULL;
2886 			return (0);
2887 		}
2888 
2889 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2890 		return (0);
2891 	}
2892 #else
2893 	case DIF_VAR_UREGS: {
2894 		struct trapframe *tframe;
2895 
2896 		if (!dtrace_priv_proc(state))
2897 			return (0);
2898 
2899 		if ((tframe = curthread->td_frame) == NULL) {
2900 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2901 			cpu_core[curcpu].cpuc_dtrace_illval = 0;
2902 			return (0);
2903 		}
2904 
2905 		return (dtrace_getreg(tframe, ndx));
2906 	}
2907 #endif
2908 
2909 	case DIF_VAR_CURTHREAD:
2910 		if (!dtrace_priv_kernel(state))
2911 			return (0);
2912 		return ((uint64_t)(uintptr_t)curthread);
2913 
2914 	case DIF_VAR_TIMESTAMP:
2915 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2916 			mstate->dtms_timestamp = dtrace_gethrtime();
2917 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2918 		}
2919 		return (mstate->dtms_timestamp);
2920 
2921 	case DIF_VAR_VTIMESTAMP:
2922 		ASSERT(dtrace_vtime_references != 0);
2923 		return (curthread->t_dtrace_vtime);
2924 
2925 	case DIF_VAR_WALLTIMESTAMP:
2926 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2927 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2928 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2929 		}
2930 		return (mstate->dtms_walltimestamp);
2931 
2932 #if defined(sun)
2933 	case DIF_VAR_IPL:
2934 		if (!dtrace_priv_kernel(state))
2935 			return (0);
2936 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2937 			mstate->dtms_ipl = dtrace_getipl();
2938 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2939 		}
2940 		return (mstate->dtms_ipl);
2941 #endif
2942 
2943 	case DIF_VAR_EPID:
2944 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2945 		return (mstate->dtms_epid);
2946 
2947 	case DIF_VAR_ID:
2948 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2949 		return (mstate->dtms_probe->dtpr_id);
2950 
2951 	case DIF_VAR_STACKDEPTH:
2952 		if (!dtrace_priv_kernel(state))
2953 			return (0);
2954 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2955 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2956 
2957 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2958 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2959 		}
2960 		return (mstate->dtms_stackdepth);
2961 
2962 	case DIF_VAR_USTACKDEPTH:
2963 		if (!dtrace_priv_proc(state))
2964 			return (0);
2965 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2966 			/*
2967 			 * See comment in DIF_VAR_PID.
2968 			 */
2969 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2970 			    CPU_ON_INTR(CPU)) {
2971 				mstate->dtms_ustackdepth = 0;
2972 			} else {
2973 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2974 				mstate->dtms_ustackdepth =
2975 				    dtrace_getustackdepth();
2976 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2977 			}
2978 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2979 		}
2980 		return (mstate->dtms_ustackdepth);
2981 
2982 	case DIF_VAR_CALLER:
2983 		if (!dtrace_priv_kernel(state))
2984 			return (0);
2985 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2986 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2987 
2988 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2989 				/*
2990 				 * If this is an unanchored probe, we are
2991 				 * required to go through the slow path:
2992 				 * dtrace_caller() only guarantees correct
2993 				 * results for anchored probes.
2994 				 */
2995 				pc_t caller[2] = {0, 0};
2996 
2997 				dtrace_getpcstack(caller, 2, aframes,
2998 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2999 				mstate->dtms_caller = caller[1];
3000 			} else if ((mstate->dtms_caller =
3001 			    dtrace_caller(aframes)) == -1) {
3002 				/*
3003 				 * We have failed to do this the quick way;
3004 				 * we must resort to the slower approach of
3005 				 * calling dtrace_getpcstack().
3006 				 */
3007 				pc_t caller = 0;
3008 
3009 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3010 				mstate->dtms_caller = caller;
3011 			}
3012 
3013 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3014 		}
3015 		return (mstate->dtms_caller);
3016 
3017 	case DIF_VAR_UCALLER:
3018 		if (!dtrace_priv_proc(state))
3019 			return (0);
3020 
3021 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3022 			uint64_t ustack[3];
3023 
3024 			/*
3025 			 * dtrace_getupcstack() fills in the first uint64_t
3026 			 * with the current PID.  The second uint64_t will
3027 			 * be the program counter at user-level.  The third
3028 			 * uint64_t will contain the caller, which is what
3029 			 * we're after.
3030 			 */
3031 			ustack[2] = 0;
3032 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3033 			dtrace_getupcstack(ustack, 3);
3034 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3035 			mstate->dtms_ucaller = ustack[2];
3036 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3037 		}
3038 
3039 		return (mstate->dtms_ucaller);
3040 
3041 	case DIF_VAR_PROBEPROV:
3042 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3043 		return (dtrace_dif_varstr(
3044 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3045 		    state, mstate));
3046 
3047 	case DIF_VAR_PROBEMOD:
3048 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3049 		return (dtrace_dif_varstr(
3050 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3051 		    state, mstate));
3052 
3053 	case DIF_VAR_PROBEFUNC:
3054 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3055 		return (dtrace_dif_varstr(
3056 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3057 		    state, mstate));
3058 
3059 	case DIF_VAR_PROBENAME:
3060 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3061 		return (dtrace_dif_varstr(
3062 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3063 		    state, mstate));
3064 
3065 	case DIF_VAR_PID:
3066 		if (!dtrace_priv_proc(state))
3067 			return (0);
3068 
3069 #if defined(sun)
3070 		/*
3071 		 * Note that we are assuming that an unanchored probe is
3072 		 * always due to a high-level interrupt.  (And we're assuming
3073 		 * that there is only a single high level interrupt.)
3074 		 */
3075 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3076 			return (pid0.pid_id);
3077 
3078 		/*
3079 		 * It is always safe to dereference one's own t_procp pointer:
3080 		 * it always points to a valid, allocated proc structure.
3081 		 * Further, it is always safe to dereference the p_pidp member
3082 		 * of one's own proc structure.  (These are truisms becuase
3083 		 * threads and processes don't clean up their own state --
3084 		 * they leave that task to whomever reaps them.)
3085 		 */
3086 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3087 #else
3088 		return ((uint64_t)curproc->p_pid);
3089 #endif
3090 
3091 	case DIF_VAR_PPID:
3092 		if (!dtrace_priv_proc(state))
3093 			return (0);
3094 
3095 #if defined(sun)
3096 		/*
3097 		 * See comment in DIF_VAR_PID.
3098 		 */
3099 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3100 			return (pid0.pid_id);
3101 
3102 		/*
3103 		 * It is always safe to dereference one's own t_procp pointer:
3104 		 * it always points to a valid, allocated proc structure.
3105 		 * (This is true because threads don't clean up their own
3106 		 * state -- they leave that task to whomever reaps them.)
3107 		 */
3108 		return ((uint64_t)curthread->t_procp->p_ppid);
3109 #else
3110 		if (curproc->p_pid == proc0.p_pid)
3111 			return (curproc->p_pid);
3112 		else
3113 			return (curproc->p_pptr->p_pid);
3114 #endif
3115 
3116 	case DIF_VAR_TID:
3117 #if defined(sun)
3118 		/*
3119 		 * See comment in DIF_VAR_PID.
3120 		 */
3121 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3122 			return (0);
3123 #endif
3124 
3125 		return ((uint64_t)curthread->t_tid);
3126 
3127 	case DIF_VAR_EXECARGS: {
3128 		struct pargs *p_args = curthread->td_proc->p_args;
3129 
3130 		if (p_args == NULL)
3131 			return(0);
3132 
3133 		return (dtrace_dif_varstrz(
3134 		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3135 	}
3136 
3137 	case DIF_VAR_EXECNAME:
3138 #if defined(sun)
3139 		if (!dtrace_priv_proc(state))
3140 			return (0);
3141 
3142 		/*
3143 		 * See comment in DIF_VAR_PID.
3144 		 */
3145 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3146 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3147 
3148 		/*
3149 		 * It is always safe to dereference one's own t_procp pointer:
3150 		 * it always points to a valid, allocated proc structure.
3151 		 * (This is true because threads don't clean up their own
3152 		 * state -- they leave that task to whomever reaps them.)
3153 		 */
3154 		return (dtrace_dif_varstr(
3155 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3156 		    state, mstate));
3157 #else
3158 		return (dtrace_dif_varstr(
3159 		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3160 #endif
3161 
3162 	case DIF_VAR_ZONENAME:
3163 #if defined(sun)
3164 		if (!dtrace_priv_proc(state))
3165 			return (0);
3166 
3167 		/*
3168 		 * See comment in DIF_VAR_PID.
3169 		 */
3170 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3171 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3172 
3173 		/*
3174 		 * It is always safe to dereference one's own t_procp pointer:
3175 		 * it always points to a valid, allocated proc structure.
3176 		 * (This is true because threads don't clean up their own
3177 		 * state -- they leave that task to whomever reaps them.)
3178 		 */
3179 		return (dtrace_dif_varstr(
3180 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3181 		    state, mstate));
3182 #else
3183 		return (0);
3184 #endif
3185 
3186 	case DIF_VAR_UID:
3187 		if (!dtrace_priv_proc(state))
3188 			return (0);
3189 
3190 #if defined(sun)
3191 		/*
3192 		 * See comment in DIF_VAR_PID.
3193 		 */
3194 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3195 			return ((uint64_t)p0.p_cred->cr_uid);
3196 #endif
3197 
3198 		/*
3199 		 * It is always safe to dereference one's own t_procp pointer:
3200 		 * it always points to a valid, allocated proc structure.
3201 		 * (This is true because threads don't clean up their own
3202 		 * state -- they leave that task to whomever reaps them.)
3203 		 *
3204 		 * Additionally, it is safe to dereference one's own process
3205 		 * credential, since this is never NULL after process birth.
3206 		 */
3207 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3208 
3209 	case DIF_VAR_GID:
3210 		if (!dtrace_priv_proc(state))
3211 			return (0);
3212 
3213 #if defined(sun)
3214 		/*
3215 		 * See comment in DIF_VAR_PID.
3216 		 */
3217 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3218 			return ((uint64_t)p0.p_cred->cr_gid);
3219 #endif
3220 
3221 		/*
3222 		 * It is always safe to dereference one's own t_procp pointer:
3223 		 * it always points to a valid, allocated proc structure.
3224 		 * (This is true because threads don't clean up their own
3225 		 * state -- they leave that task to whomever reaps them.)
3226 		 *
3227 		 * Additionally, it is safe to dereference one's own process
3228 		 * credential, since this is never NULL after process birth.
3229 		 */
3230 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3231 
3232 	case DIF_VAR_ERRNO: {
3233 #if defined(sun)
3234 		klwp_t *lwp;
3235 		if (!dtrace_priv_proc(state))
3236 			return (0);
3237 
3238 		/*
3239 		 * See comment in DIF_VAR_PID.
3240 		 */
3241 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3242 			return (0);
3243 
3244 		/*
3245 		 * It is always safe to dereference one's own t_lwp pointer in
3246 		 * the event that this pointer is non-NULL.  (This is true
3247 		 * because threads and lwps don't clean up their own state --
3248 		 * they leave that task to whomever reaps them.)
3249 		 */
3250 		if ((lwp = curthread->t_lwp) == NULL)
3251 			return (0);
3252 
3253 		return ((uint64_t)lwp->lwp_errno);
3254 #else
3255 		return (curthread->td_errno);
3256 #endif
3257 	}
3258 #if !defined(sun)
3259 	case DIF_VAR_CPU: {
3260 		return curcpu;
3261 	}
3262 #endif
3263 	default:
3264 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3265 		return (0);
3266 	}
3267 }
3268 
3269 /*
3270  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3271  * Notice that we don't bother validating the proper number of arguments or
3272  * their types in the tuple stack.  This isn't needed because all argument
3273  * interpretation is safe because of our load safety -- the worst that can
3274  * happen is that a bogus program can obtain bogus results.
3275  */
3276 static void
dtrace_dif_subr(uint_t subr,uint_t rd,uint64_t * regs,dtrace_key_t * tupregs,int nargs,dtrace_mstate_t * mstate,dtrace_state_t * state)3277 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3278     dtrace_key_t *tupregs, int nargs,
3279     dtrace_mstate_t *mstate, dtrace_state_t *state)
3280 {
3281 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3282 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3283 	dtrace_vstate_t *vstate = &state->dts_vstate;
3284 
3285 #if defined(sun)
3286 	union {
3287 		mutex_impl_t mi;
3288 		uint64_t mx;
3289 	} m;
3290 
3291 	union {
3292 		krwlock_t ri;
3293 		uintptr_t rw;
3294 	} r;
3295 #else
3296 	struct thread *lowner;
3297 	union {
3298 		struct lock_object *li;
3299 		uintptr_t lx;
3300 	} l;
3301 #endif
3302 
3303 	switch (subr) {
3304 	case DIF_SUBR_RAND:
3305 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3306 		break;
3307 
3308 #if defined(sun)
3309 	case DIF_SUBR_MUTEX_OWNED:
3310 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3311 		    mstate, vstate)) {
3312 			regs[rd] = 0;
3313 			break;
3314 		}
3315 
3316 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3317 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3318 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3319 		else
3320 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3321 		break;
3322 
3323 	case DIF_SUBR_MUTEX_OWNER:
3324 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3325 		    mstate, vstate)) {
3326 			regs[rd] = 0;
3327 			break;
3328 		}
3329 
3330 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3331 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3332 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3333 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3334 		else
3335 			regs[rd] = 0;
3336 		break;
3337 
3338 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3339 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3340 		    mstate, vstate)) {
3341 			regs[rd] = 0;
3342 			break;
3343 		}
3344 
3345 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3346 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3347 		break;
3348 
3349 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3350 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3351 		    mstate, vstate)) {
3352 			regs[rd] = 0;
3353 			break;
3354 		}
3355 
3356 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3357 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3358 		break;
3359 
3360 	case DIF_SUBR_RW_READ_HELD: {
3361 		uintptr_t tmp;
3362 
3363 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3364 		    mstate, vstate)) {
3365 			regs[rd] = 0;
3366 			break;
3367 		}
3368 
3369 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3370 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3371 		break;
3372 	}
3373 
3374 	case DIF_SUBR_RW_WRITE_HELD:
3375 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3376 		    mstate, vstate)) {
3377 			regs[rd] = 0;
3378 			break;
3379 		}
3380 
3381 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3382 		regs[rd] = _RW_WRITE_HELD(&r.ri);
3383 		break;
3384 
3385 	case DIF_SUBR_RW_ISWRITER:
3386 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3387 		    mstate, vstate)) {
3388 			regs[rd] = 0;
3389 			break;
3390 		}
3391 
3392 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3393 		regs[rd] = _RW_ISWRITER(&r.ri);
3394 		break;
3395 
3396 #else
3397 	case DIF_SUBR_MUTEX_OWNED:
3398 		if (!dtrace_canload(tupregs[0].dttk_value,
3399 			sizeof (struct lock_object), mstate, vstate)) {
3400 			regs[rd] = 0;
3401 			break;
3402 		}
3403 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3404 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3405 		break;
3406 
3407 	case DIF_SUBR_MUTEX_OWNER:
3408 		if (!dtrace_canload(tupregs[0].dttk_value,
3409 			sizeof (struct lock_object), mstate, vstate)) {
3410 			regs[rd] = 0;
3411 			break;
3412 		}
3413 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3414 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3415 		regs[rd] = (uintptr_t)lowner;
3416 		break;
3417 
3418 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3419 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3420 		    mstate, vstate)) {
3421 			regs[rd] = 0;
3422 			break;
3423 		}
3424 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3425 		/* XXX - should be only LC_SLEEPABLE? */
3426 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3427 		    (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3428 		break;
3429 
3430 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3431 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3432 		    mstate, vstate)) {
3433 			regs[rd] = 0;
3434 			break;
3435 		}
3436 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3437 		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3438 		break;
3439 
3440 	case DIF_SUBR_RW_READ_HELD:
3441 	case DIF_SUBR_SX_SHARED_HELD:
3442 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3443 		    mstate, vstate)) {
3444 			regs[rd] = 0;
3445 			break;
3446 		}
3447 		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3448 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3449 		    lowner == NULL;
3450 		break;
3451 
3452 	case DIF_SUBR_RW_WRITE_HELD:
3453 	case DIF_SUBR_SX_EXCLUSIVE_HELD:
3454 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3455 		    mstate, vstate)) {
3456 			regs[rd] = 0;
3457 			break;
3458 		}
3459 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3460 		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3461 		regs[rd] = (lowner == curthread);
3462 		break;
3463 
3464 	case DIF_SUBR_RW_ISWRITER:
3465 	case DIF_SUBR_SX_ISEXCLUSIVE:
3466 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3467 		    mstate, vstate)) {
3468 			regs[rd] = 0;
3469 			break;
3470 		}
3471 		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3472 		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3473 		    lowner != NULL;
3474 		break;
3475 #endif /* ! defined(sun) */
3476 
3477 	case DIF_SUBR_BCOPY: {
3478 		/*
3479 		 * We need to be sure that the destination is in the scratch
3480 		 * region -- no other region is allowed.
3481 		 */
3482 		uintptr_t src = tupregs[0].dttk_value;
3483 		uintptr_t dest = tupregs[1].dttk_value;
3484 		size_t size = tupregs[2].dttk_value;
3485 
3486 		if (!dtrace_inscratch(dest, size, mstate)) {
3487 			*flags |= CPU_DTRACE_BADADDR;
3488 			*illval = regs[rd];
3489 			break;
3490 		}
3491 
3492 		if (!dtrace_canload(src, size, mstate, vstate)) {
3493 			regs[rd] = 0;
3494 			break;
3495 		}
3496 
3497 		dtrace_bcopy((void *)src, (void *)dest, size);
3498 		break;
3499 	}
3500 
3501 	case DIF_SUBR_ALLOCA:
3502 	case DIF_SUBR_COPYIN: {
3503 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3504 		uint64_t size =
3505 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3506 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3507 
3508 		/*
3509 		 * This action doesn't require any credential checks since
3510 		 * probes will not activate in user contexts to which the
3511 		 * enabling user does not have permissions.
3512 		 */
3513 
3514 		/*
3515 		 * Rounding up the user allocation size could have overflowed
3516 		 * a large, bogus allocation (like -1ULL) to 0.
3517 		 */
3518 		if (scratch_size < size ||
3519 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
3520 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3521 			regs[rd] = 0;
3522 			break;
3523 		}
3524 
3525 		if (subr == DIF_SUBR_COPYIN) {
3526 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3527 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3528 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3529 		}
3530 
3531 		mstate->dtms_scratch_ptr += scratch_size;
3532 		regs[rd] = dest;
3533 		break;
3534 	}
3535 
3536 	case DIF_SUBR_COPYINTO: {
3537 		uint64_t size = tupregs[1].dttk_value;
3538 		uintptr_t dest = tupregs[2].dttk_value;
3539 
3540 		/*
3541 		 * This action doesn't require any credential checks since
3542 		 * probes will not activate in user contexts to which the
3543 		 * enabling user does not have permissions.
3544 		 */
3545 		if (!dtrace_inscratch(dest, size, mstate)) {
3546 			*flags |= CPU_DTRACE_BADADDR;
3547 			*illval = regs[rd];
3548 			break;
3549 		}
3550 
3551 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3552 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3553 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3554 		break;
3555 	}
3556 
3557 	case DIF_SUBR_COPYINSTR: {
3558 		uintptr_t dest = mstate->dtms_scratch_ptr;
3559 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3560 
3561 		if (nargs > 1 && tupregs[1].dttk_value < size)
3562 			size = tupregs[1].dttk_value + 1;
3563 
3564 		/*
3565 		 * This action doesn't require any credential checks since
3566 		 * probes will not activate in user contexts to which the
3567 		 * enabling user does not have permissions.
3568 		 */
3569 		if (!DTRACE_INSCRATCH(mstate, size)) {
3570 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3571 			regs[rd] = 0;
3572 			break;
3573 		}
3574 
3575 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3576 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3577 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3578 
3579 		((char *)dest)[size - 1] = '\0';
3580 		mstate->dtms_scratch_ptr += size;
3581 		regs[rd] = dest;
3582 		break;
3583 	}
3584 
3585 #if defined(sun)
3586 	case DIF_SUBR_MSGSIZE:
3587 	case DIF_SUBR_MSGDSIZE: {
3588 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3589 		uintptr_t wptr, rptr;
3590 		size_t count = 0;
3591 		int cont = 0;
3592 
3593 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3594 
3595 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3596 			    vstate)) {
3597 				regs[rd] = 0;
3598 				break;
3599 			}
3600 
3601 			wptr = dtrace_loadptr(baddr +
3602 			    offsetof(mblk_t, b_wptr));
3603 
3604 			rptr = dtrace_loadptr(baddr +
3605 			    offsetof(mblk_t, b_rptr));
3606 
3607 			if (wptr < rptr) {
3608 				*flags |= CPU_DTRACE_BADADDR;
3609 				*illval = tupregs[0].dttk_value;
3610 				break;
3611 			}
3612 
3613 			daddr = dtrace_loadptr(baddr +
3614 			    offsetof(mblk_t, b_datap));
3615 
3616 			baddr = dtrace_loadptr(baddr +
3617 			    offsetof(mblk_t, b_cont));
3618 
3619 			/*
3620 			 * We want to prevent against denial-of-service here,
3621 			 * so we're only going to search the list for
3622 			 * dtrace_msgdsize_max mblks.
3623 			 */
3624 			if (cont++ > dtrace_msgdsize_max) {
3625 				*flags |= CPU_DTRACE_ILLOP;
3626 				break;
3627 			}
3628 
3629 			if (subr == DIF_SUBR_MSGDSIZE) {
3630 				if (dtrace_load8(daddr +
3631 				    offsetof(dblk_t, db_type)) != M_DATA)
3632 					continue;
3633 			}
3634 
3635 			count += wptr - rptr;
3636 		}
3637 
3638 		if (!(*flags & CPU_DTRACE_FAULT))
3639 			regs[rd] = count;
3640 
3641 		break;
3642 	}
3643 #endif
3644 
3645 	case DIF_SUBR_PROGENYOF: {
3646 		pid_t pid = tupregs[0].dttk_value;
3647 		proc_t *p;
3648 		int rval = 0;
3649 
3650 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3651 
3652 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3653 #if defined(sun)
3654 			if (p->p_pidp->pid_id == pid) {
3655 #else
3656 			if (p->p_pid == pid) {
3657 #endif
3658 				rval = 1;
3659 				break;
3660 			}
3661 		}
3662 
3663 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3664 
3665 		regs[rd] = rval;
3666 		break;
3667 	}
3668 
3669 	case DIF_SUBR_SPECULATION:
3670 		regs[rd] = dtrace_speculation(state);
3671 		break;
3672 
3673 	case DIF_SUBR_COPYOUT: {
3674 		uintptr_t kaddr = tupregs[0].dttk_value;
3675 		uintptr_t uaddr = tupregs[1].dttk_value;
3676 		uint64_t size = tupregs[2].dttk_value;
3677 
3678 		if (!dtrace_destructive_disallow &&
3679 		    dtrace_priv_proc_control(state) &&
3680 		    !dtrace_istoxic(kaddr, size)) {
3681 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3682 			dtrace_copyout(kaddr, uaddr, size, flags);
3683 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3684 		}
3685 		break;
3686 	}
3687 
3688 	case DIF_SUBR_COPYOUTSTR: {
3689 		uintptr_t kaddr = tupregs[0].dttk_value;
3690 		uintptr_t uaddr = tupregs[1].dttk_value;
3691 		uint64_t size = tupregs[2].dttk_value;
3692 
3693 		if (!dtrace_destructive_disallow &&
3694 		    dtrace_priv_proc_control(state) &&
3695 		    !dtrace_istoxic(kaddr, size)) {
3696 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3697 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3698 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3699 		}
3700 		break;
3701 	}
3702 
3703 	case DIF_SUBR_STRLEN: {
3704 		size_t sz;
3705 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3706 		sz = dtrace_strlen((char *)addr,
3707 		    state->dts_options[DTRACEOPT_STRSIZE]);
3708 
3709 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3710 			regs[rd] = 0;
3711 			break;
3712 		}
3713 
3714 		regs[rd] = sz;
3715 
3716 		break;
3717 	}
3718 
3719 	case DIF_SUBR_STRCHR:
3720 	case DIF_SUBR_STRRCHR: {
3721 		/*
3722 		 * We're going to iterate over the string looking for the
3723 		 * specified character.  We will iterate until we have reached
3724 		 * the string length or we have found the character.  If this
3725 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3726 		 * of the specified character instead of the first.
3727 		 */
3728 		uintptr_t saddr = tupregs[0].dttk_value;
3729 		uintptr_t addr = tupregs[0].dttk_value;
3730 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3731 		char c, target = (char)tupregs[1].dttk_value;
3732 
3733 		for (regs[rd] = 0; addr < limit; addr++) {
3734 			if ((c = dtrace_load8(addr)) == target) {
3735 				regs[rd] = addr;
3736 
3737 				if (subr == DIF_SUBR_STRCHR)
3738 					break;
3739 			}
3740 
3741 			if (c == '\0')
3742 				break;
3743 		}
3744 
3745 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3746 			regs[rd] = 0;
3747 			break;
3748 		}
3749 
3750 		break;
3751 	}
3752 
3753 	case DIF_SUBR_STRSTR:
3754 	case DIF_SUBR_INDEX:
3755 	case DIF_SUBR_RINDEX: {
3756 		/*
3757 		 * We're going to iterate over the string looking for the
3758 		 * specified string.  We will iterate until we have reached
3759 		 * the string length or we have found the string.  (Yes, this
3760 		 * is done in the most naive way possible -- but considering
3761 		 * that the string we're searching for is likely to be
3762 		 * relatively short, the complexity of Rabin-Karp or similar
3763 		 * hardly seems merited.)
3764 		 */
3765 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3766 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3767 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3768 		size_t len = dtrace_strlen(addr, size);
3769 		size_t sublen = dtrace_strlen(substr, size);
3770 		char *limit = addr + len, *orig = addr;
3771 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3772 		int inc = 1;
3773 
3774 		regs[rd] = notfound;
3775 
3776 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3777 			regs[rd] = 0;
3778 			break;
3779 		}
3780 
3781 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3782 		    vstate)) {
3783 			regs[rd] = 0;
3784 			break;
3785 		}
3786 
3787 		/*
3788 		 * strstr() and index()/rindex() have similar semantics if
3789 		 * both strings are the empty string: strstr() returns a
3790 		 * pointer to the (empty) string, and index() and rindex()
3791 		 * both return index 0 (regardless of any position argument).
3792 		 */
3793 		if (sublen == 0 && len == 0) {
3794 			if (subr == DIF_SUBR_STRSTR)
3795 				regs[rd] = (uintptr_t)addr;
3796 			else
3797 				regs[rd] = 0;
3798 			break;
3799 		}
3800 
3801 		if (subr != DIF_SUBR_STRSTR) {
3802 			if (subr == DIF_SUBR_RINDEX) {
3803 				limit = orig - 1;
3804 				addr += len;
3805 				inc = -1;
3806 			}
3807 
3808 			/*
3809 			 * Both index() and rindex() take an optional position
3810 			 * argument that denotes the starting position.
3811 			 */
3812 			if (nargs == 3) {
3813 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3814 
3815 				/*
3816 				 * If the position argument to index() is
3817 				 * negative, Perl implicitly clamps it at
3818 				 * zero.  This semantic is a little surprising
3819 				 * given the special meaning of negative
3820 				 * positions to similar Perl functions like
3821 				 * substr(), but it appears to reflect a
3822 				 * notion that index() can start from a
3823 				 * negative index and increment its way up to
3824 				 * the string.  Given this notion, Perl's
3825 				 * rindex() is at least self-consistent in
3826 				 * that it implicitly clamps positions greater
3827 				 * than the string length to be the string
3828 				 * length.  Where Perl completely loses
3829 				 * coherence, however, is when the specified
3830 				 * substring is the empty string ("").  In
3831 				 * this case, even if the position is
3832 				 * negative, rindex() returns 0 -- and even if
3833 				 * the position is greater than the length,
3834 				 * index() returns the string length.  These
3835 				 * semantics violate the notion that index()
3836 				 * should never return a value less than the
3837 				 * specified position and that rindex() should
3838 				 * never return a value greater than the
3839 				 * specified position.  (One assumes that
3840 				 * these semantics are artifacts of Perl's
3841 				 * implementation and not the results of
3842 				 * deliberate design -- it beggars belief that
3843 				 * even Larry Wall could desire such oddness.)
3844 				 * While in the abstract one would wish for
3845 				 * consistent position semantics across
3846 				 * substr(), index() and rindex() -- or at the
3847 				 * very least self-consistent position
3848 				 * semantics for index() and rindex() -- we
3849 				 * instead opt to keep with the extant Perl
3850 				 * semantics, in all their broken glory.  (Do
3851 				 * we have more desire to maintain Perl's
3852 				 * semantics than Perl does?  Probably.)
3853 				 */
3854 				if (subr == DIF_SUBR_RINDEX) {
3855 					if (pos < 0) {
3856 						if (sublen == 0)
3857 							regs[rd] = 0;
3858 						break;
3859 					}
3860 
3861 					if (pos > len)
3862 						pos = len;
3863 				} else {
3864 					if (pos < 0)
3865 						pos = 0;
3866 
3867 					if (pos >= len) {
3868 						if (sublen == 0)
3869 							regs[rd] = len;
3870 						break;
3871 					}
3872 				}
3873 
3874 				addr = orig + pos;
3875 			}
3876 		}
3877 
3878 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3879 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3880 				if (subr != DIF_SUBR_STRSTR) {
3881 					/*
3882 					 * As D index() and rindex() are
3883 					 * modeled on Perl (and not on awk),
3884 					 * we return a zero-based (and not a
3885 					 * one-based) index.  (For you Perl
3886 					 * weenies: no, we're not going to add
3887 					 * $[ -- and shouldn't you be at a con
3888 					 * or something?)
3889 					 */
3890 					regs[rd] = (uintptr_t)(addr - orig);
3891 					break;
3892 				}
3893 
3894 				ASSERT(subr == DIF_SUBR_STRSTR);
3895 				regs[rd] = (uintptr_t)addr;
3896 				break;
3897 			}
3898 		}
3899 
3900 		break;
3901 	}
3902 
3903 	case DIF_SUBR_STRTOK: {
3904 		uintptr_t addr = tupregs[0].dttk_value;
3905 		uintptr_t tokaddr = tupregs[1].dttk_value;
3906 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3907 		uintptr_t limit, toklimit = tokaddr + size;
3908 		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
3909 		char *dest = (char *)mstate->dtms_scratch_ptr;
3910 		int i;
3911 
3912 		/*
3913 		 * Check both the token buffer and (later) the input buffer,
3914 		 * since both could be non-scratch addresses.
3915 		 */
3916 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3917 			regs[rd] = 0;
3918 			break;
3919 		}
3920 
3921 		if (!DTRACE_INSCRATCH(mstate, size)) {
3922 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3923 			regs[rd] = 0;
3924 			break;
3925 		}
3926 
3927 		if (addr == 0) {
3928 			/*
3929 			 * If the address specified is NULL, we use our saved
3930 			 * strtok pointer from the mstate.  Note that this
3931 			 * means that the saved strtok pointer is _only_
3932 			 * valid within multiple enablings of the same probe --
3933 			 * it behaves like an implicit clause-local variable.
3934 			 */
3935 			addr = mstate->dtms_strtok;
3936 		} else {
3937 			/*
3938 			 * If the user-specified address is non-NULL we must
3939 			 * access check it.  This is the only time we have
3940 			 * a chance to do so, since this address may reside
3941 			 * in the string table of this clause-- future calls
3942 			 * (when we fetch addr from mstate->dtms_strtok)
3943 			 * would fail this access check.
3944 			 */
3945 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3946 				regs[rd] = 0;
3947 				break;
3948 			}
3949 		}
3950 
3951 		/*
3952 		 * First, zero the token map, and then process the token
3953 		 * string -- setting a bit in the map for every character
3954 		 * found in the token string.
3955 		 */
3956 		for (i = 0; i < sizeof (tokmap); i++)
3957 			tokmap[i] = 0;
3958 
3959 		for (; tokaddr < toklimit; tokaddr++) {
3960 			if ((c = dtrace_load8(tokaddr)) == '\0')
3961 				break;
3962 
3963 			ASSERT((c >> 3) < sizeof (tokmap));
3964 			tokmap[c >> 3] |= (1 << (c & 0x7));
3965 		}
3966 
3967 		for (limit = addr + size; addr < limit; addr++) {
3968 			/*
3969 			 * We're looking for a character that is _not_ contained
3970 			 * in the token string.
3971 			 */
3972 			if ((c = dtrace_load8(addr)) == '\0')
3973 				break;
3974 
3975 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3976 				break;
3977 		}
3978 
3979 		if (c == '\0') {
3980 			/*
3981 			 * We reached the end of the string without finding
3982 			 * any character that was not in the token string.
3983 			 * We return NULL in this case, and we set the saved
3984 			 * address to NULL as well.
3985 			 */
3986 			regs[rd] = 0;
3987 			mstate->dtms_strtok = 0;
3988 			break;
3989 		}
3990 
3991 		/*
3992 		 * From here on, we're copying into the destination string.
3993 		 */
3994 		for (i = 0; addr < limit && i < size - 1; addr++) {
3995 			if ((c = dtrace_load8(addr)) == '\0')
3996 				break;
3997 
3998 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3999 				break;
4000 
4001 			ASSERT(i < size);
4002 			dest[i++] = c;
4003 		}
4004 
4005 		ASSERT(i < size);
4006 		dest[i] = '\0';
4007 		regs[rd] = (uintptr_t)dest;
4008 		mstate->dtms_scratch_ptr += size;
4009 		mstate->dtms_strtok = addr;
4010 		break;
4011 	}
4012 
4013 	case DIF_SUBR_SUBSTR: {
4014 		uintptr_t s = tupregs[0].dttk_value;
4015 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4016 		char *d = (char *)mstate->dtms_scratch_ptr;
4017 		int64_t index = (int64_t)tupregs[1].dttk_value;
4018 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4019 		size_t len = dtrace_strlen((char *)s, size);
4020 		int64_t i = 0;
4021 
4022 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4023 			regs[rd] = 0;
4024 			break;
4025 		}
4026 
4027 		if (!DTRACE_INSCRATCH(mstate, size)) {
4028 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4029 			regs[rd] = 0;
4030 			break;
4031 		}
4032 
4033 		if (nargs <= 2)
4034 			remaining = (int64_t)size;
4035 
4036 		if (index < 0) {
4037 			index += len;
4038 
4039 			if (index < 0 && index + remaining > 0) {
4040 				remaining += index;
4041 				index = 0;
4042 			}
4043 		}
4044 
4045 		if (index >= len || index < 0) {
4046 			remaining = 0;
4047 		} else if (remaining < 0) {
4048 			remaining += len - index;
4049 		} else if (index + remaining > size) {
4050 			remaining = size - index;
4051 		}
4052 
4053 		for (i = 0; i < remaining; i++) {
4054 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4055 				break;
4056 		}
4057 
4058 		d[i] = '\0';
4059 
4060 		mstate->dtms_scratch_ptr += size;
4061 		regs[rd] = (uintptr_t)d;
4062 		break;
4063 	}
4064 
4065 	case DIF_SUBR_TOUPPER:
4066 	case DIF_SUBR_TOLOWER: {
4067 		uintptr_t s = tupregs[0].dttk_value;
4068 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4069 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4070 		size_t len = dtrace_strlen((char *)s, size);
4071 		char lower, upper, convert;
4072 		int64_t i;
4073 
4074 		if (subr == DIF_SUBR_TOUPPER) {
4075 			lower = 'a';
4076 			upper = 'z';
4077 			convert = 'A';
4078 		} else {
4079 			lower = 'A';
4080 			upper = 'Z';
4081 			convert = 'a';
4082 		}
4083 
4084 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4085 			regs[rd] = 0;
4086 			break;
4087 		}
4088 
4089 		if (!DTRACE_INSCRATCH(mstate, size)) {
4090 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4091 			regs[rd] = 0;
4092 			break;
4093 		}
4094 
4095 		for (i = 0; i < size - 1; i++) {
4096 			if ((c = dtrace_load8(s + i)) == '\0')
4097 				break;
4098 
4099 			if (c >= lower && c <= upper)
4100 				c = convert + (c - lower);
4101 
4102 			dest[i] = c;
4103 		}
4104 
4105 		ASSERT(i < size);
4106 		dest[i] = '\0';
4107 		regs[rd] = (uintptr_t)dest;
4108 		mstate->dtms_scratch_ptr += size;
4109 		break;
4110 	}
4111 
4112 #if defined(sun)
4113 	case DIF_SUBR_GETMAJOR:
4114 #ifdef _LP64
4115 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4116 #else
4117 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4118 #endif
4119 		break;
4120 
4121 	case DIF_SUBR_GETMINOR:
4122 #ifdef _LP64
4123 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4124 #else
4125 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4126 #endif
4127 		break;
4128 
4129 	case DIF_SUBR_DDI_PATHNAME: {
4130 		/*
4131 		 * This one is a galactic mess.  We are going to roughly
4132 		 * emulate ddi_pathname(), but it's made more complicated
4133 		 * by the fact that we (a) want to include the minor name and
4134 		 * (b) must proceed iteratively instead of recursively.
4135 		 */
4136 		uintptr_t dest = mstate->dtms_scratch_ptr;
4137 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4138 		char *start = (char *)dest, *end = start + size - 1;
4139 		uintptr_t daddr = tupregs[0].dttk_value;
4140 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4141 		char *s;
4142 		int i, len, depth = 0;
4143 
4144 		/*
4145 		 * Due to all the pointer jumping we do and context we must
4146 		 * rely upon, we just mandate that the user must have kernel
4147 		 * read privileges to use this routine.
4148 		 */
4149 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4150 			*flags |= CPU_DTRACE_KPRIV;
4151 			*illval = daddr;
4152 			regs[rd] = 0;
4153 		}
4154 
4155 		if (!DTRACE_INSCRATCH(mstate, size)) {
4156 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4157 			regs[rd] = 0;
4158 			break;
4159 		}
4160 
4161 		*end = '\0';
4162 
4163 		/*
4164 		 * We want to have a name for the minor.  In order to do this,
4165 		 * we need to walk the minor list from the devinfo.  We want
4166 		 * to be sure that we don't infinitely walk a circular list,
4167 		 * so we check for circularity by sending a scout pointer
4168 		 * ahead two elements for every element that we iterate over;
4169 		 * if the list is circular, these will ultimately point to the
4170 		 * same element.  You may recognize this little trick as the
4171 		 * answer to a stupid interview question -- one that always
4172 		 * seems to be asked by those who had to have it laboriously
4173 		 * explained to them, and who can't even concisely describe
4174 		 * the conditions under which one would be forced to resort to
4175 		 * this technique.  Needless to say, those conditions are
4176 		 * found here -- and probably only here.  Is this the only use
4177 		 * of this infamous trick in shipping, production code?  If it
4178 		 * isn't, it probably should be...
4179 		 */
4180 		if (minor != -1) {
4181 			uintptr_t maddr = dtrace_loadptr(daddr +
4182 			    offsetof(struct dev_info, devi_minor));
4183 
4184 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4185 			uintptr_t name = offsetof(struct ddi_minor_data,
4186 			    d_minor) + offsetof(struct ddi_minor, name);
4187 			uintptr_t dev = offsetof(struct ddi_minor_data,
4188 			    d_minor) + offsetof(struct ddi_minor, dev);
4189 			uintptr_t scout;
4190 
4191 			if (maddr != NULL)
4192 				scout = dtrace_loadptr(maddr + next);
4193 
4194 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4195 				uint64_t m;
4196 #ifdef _LP64
4197 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4198 #else
4199 				m = dtrace_load32(maddr + dev) & MAXMIN;
4200 #endif
4201 				if (m != minor) {
4202 					maddr = dtrace_loadptr(maddr + next);
4203 
4204 					if (scout == NULL)
4205 						continue;
4206 
4207 					scout = dtrace_loadptr(scout + next);
4208 
4209 					if (scout == NULL)
4210 						continue;
4211 
4212 					scout = dtrace_loadptr(scout + next);
4213 
4214 					if (scout == NULL)
4215 						continue;
4216 
4217 					if (scout == maddr) {
4218 						*flags |= CPU_DTRACE_ILLOP;
4219 						break;
4220 					}
4221 
4222 					continue;
4223 				}
4224 
4225 				/*
4226 				 * We have the minor data.  Now we need to
4227 				 * copy the minor's name into the end of the
4228 				 * pathname.
4229 				 */
4230 				s = (char *)dtrace_loadptr(maddr + name);
4231 				len = dtrace_strlen(s, size);
4232 
4233 				if (*flags & CPU_DTRACE_FAULT)
4234 					break;
4235 
4236 				if (len != 0) {
4237 					if ((end -= (len + 1)) < start)
4238 						break;
4239 
4240 					*end = ':';
4241 				}
4242 
4243 				for (i = 1; i <= len; i++)
4244 					end[i] = dtrace_load8((uintptr_t)s++);
4245 				break;
4246 			}
4247 		}
4248 
4249 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4250 			ddi_node_state_t devi_state;
4251 
4252 			devi_state = dtrace_load32(daddr +
4253 			    offsetof(struct dev_info, devi_node_state));
4254 
4255 			if (*flags & CPU_DTRACE_FAULT)
4256 				break;
4257 
4258 			if (devi_state >= DS_INITIALIZED) {
4259 				s = (char *)dtrace_loadptr(daddr +
4260 				    offsetof(struct dev_info, devi_addr));
4261 				len = dtrace_strlen(s, size);
4262 
4263 				if (*flags & CPU_DTRACE_FAULT)
4264 					break;
4265 
4266 				if (len != 0) {
4267 					if ((end -= (len + 1)) < start)
4268 						break;
4269 
4270 					*end = '@';
4271 				}
4272 
4273 				for (i = 1; i <= len; i++)
4274 					end[i] = dtrace_load8((uintptr_t)s++);
4275 			}
4276 
4277 			/*
4278 			 * Now for the node name...
4279 			 */
4280 			s = (char *)dtrace_loadptr(daddr +
4281 			    offsetof(struct dev_info, devi_node_name));
4282 
4283 			daddr = dtrace_loadptr(daddr +
4284 			    offsetof(struct dev_info, devi_parent));
4285 
4286 			/*
4287 			 * If our parent is NULL (that is, if we're the root
4288 			 * node), we're going to use the special path
4289 			 * "devices".
4290 			 */
4291 			if (daddr == 0)
4292 				s = "devices";
4293 
4294 			len = dtrace_strlen(s, size);
4295 			if (*flags & CPU_DTRACE_FAULT)
4296 				break;
4297 
4298 			if ((end -= (len + 1)) < start)
4299 				break;
4300 
4301 			for (i = 1; i <= len; i++)
4302 				end[i] = dtrace_load8((uintptr_t)s++);
4303 			*end = '/';
4304 
4305 			if (depth++ > dtrace_devdepth_max) {
4306 				*flags |= CPU_DTRACE_ILLOP;
4307 				break;
4308 			}
4309 		}
4310 
4311 		if (end < start)
4312 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4313 
4314 		if (daddr == 0) {
4315 			regs[rd] = (uintptr_t)end;
4316 			mstate->dtms_scratch_ptr += size;
4317 		}
4318 
4319 		break;
4320 	}
4321 #endif
4322 
4323 	case DIF_SUBR_STRJOIN: {
4324 		char *d = (char *)mstate->dtms_scratch_ptr;
4325 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4326 		uintptr_t s1 = tupregs[0].dttk_value;
4327 		uintptr_t s2 = tupregs[1].dttk_value;
4328 		int i = 0;
4329 
4330 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4331 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4332 			regs[rd] = 0;
4333 			break;
4334 		}
4335 
4336 		if (!DTRACE_INSCRATCH(mstate, size)) {
4337 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4338 			regs[rd] = 0;
4339 			break;
4340 		}
4341 
4342 		for (;;) {
4343 			if (i >= size) {
4344 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4345 				regs[rd] = 0;
4346 				break;
4347 			}
4348 
4349 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4350 				i--;
4351 				break;
4352 			}
4353 		}
4354 
4355 		for (;;) {
4356 			if (i >= size) {
4357 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4358 				regs[rd] = 0;
4359 				break;
4360 			}
4361 
4362 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4363 				break;
4364 		}
4365 
4366 		if (i < size) {
4367 			mstate->dtms_scratch_ptr += i;
4368 			regs[rd] = (uintptr_t)d;
4369 		}
4370 
4371 		break;
4372 	}
4373 
4374 	case DIF_SUBR_LLTOSTR: {
4375 		int64_t i = (int64_t)tupregs[0].dttk_value;
4376 		uint64_t val, digit;
4377 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4378 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4379 		int base = 10;
4380 
4381 		if (nargs > 1) {
4382 			if ((base = tupregs[1].dttk_value) <= 1 ||
4383 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4384 				*flags |= CPU_DTRACE_ILLOP;
4385 				break;
4386 			}
4387 		}
4388 
4389 		val = (base == 10 && i < 0) ? i * -1 : i;
4390 
4391 		if (!DTRACE_INSCRATCH(mstate, size)) {
4392 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4393 			regs[rd] = 0;
4394 			break;
4395 		}
4396 
4397 		for (*end-- = '\0'; val; val /= base) {
4398 			if ((digit = val % base) <= '9' - '0') {
4399 				*end-- = '0' + digit;
4400 			} else {
4401 				*end-- = 'a' + (digit - ('9' - '0') - 1);
4402 			}
4403 		}
4404 
4405 		if (i == 0 && base == 16)
4406 			*end-- = '0';
4407 
4408 		if (base == 16)
4409 			*end-- = 'x';
4410 
4411 		if (i == 0 || base == 8 || base == 16)
4412 			*end-- = '0';
4413 
4414 		if (i < 0 && base == 10)
4415 			*end-- = '-';
4416 
4417 		regs[rd] = (uintptr_t)end + 1;
4418 		mstate->dtms_scratch_ptr += size;
4419 		break;
4420 	}
4421 
4422 	case DIF_SUBR_HTONS:
4423 	case DIF_SUBR_NTOHS:
4424 #if BYTE_ORDER == BIG_ENDIAN
4425 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
4426 #else
4427 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4428 #endif
4429 		break;
4430 
4431 
4432 	case DIF_SUBR_HTONL:
4433 	case DIF_SUBR_NTOHL:
4434 #if BYTE_ORDER == BIG_ENDIAN
4435 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
4436 #else
4437 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4438 #endif
4439 		break;
4440 
4441 
4442 	case DIF_SUBR_HTONLL:
4443 	case DIF_SUBR_NTOHLL:
4444 #if BYTE_ORDER == BIG_ENDIAN
4445 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
4446 #else
4447 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4448 #endif
4449 		break;
4450 
4451 
4452 	case DIF_SUBR_DIRNAME:
4453 	case DIF_SUBR_BASENAME: {
4454 		char *dest = (char *)mstate->dtms_scratch_ptr;
4455 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4456 		uintptr_t src = tupregs[0].dttk_value;
4457 		int i, j, len = dtrace_strlen((char *)src, size);
4458 		int lastbase = -1, firstbase = -1, lastdir = -1;
4459 		int start, end;
4460 
4461 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4462 			regs[rd] = 0;
4463 			break;
4464 		}
4465 
4466 		if (!DTRACE_INSCRATCH(mstate, size)) {
4467 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4468 			regs[rd] = 0;
4469 			break;
4470 		}
4471 
4472 		/*
4473 		 * The basename and dirname for a zero-length string is
4474 		 * defined to be "."
4475 		 */
4476 		if (len == 0) {
4477 			len = 1;
4478 			src = (uintptr_t)".";
4479 		}
4480 
4481 		/*
4482 		 * Start from the back of the string, moving back toward the
4483 		 * front until we see a character that isn't a slash.  That
4484 		 * character is the last character in the basename.
4485 		 */
4486 		for (i = len - 1; i >= 0; i--) {
4487 			if (dtrace_load8(src + i) != '/')
4488 				break;
4489 		}
4490 
4491 		if (i >= 0)
4492 			lastbase = i;
4493 
4494 		/*
4495 		 * Starting from the last character in the basename, move
4496 		 * towards the front until we find a slash.  The character
4497 		 * that we processed immediately before that is the first
4498 		 * character in the basename.
4499 		 */
4500 		for (; i >= 0; i--) {
4501 			if (dtrace_load8(src + i) == '/')
4502 				break;
4503 		}
4504 
4505 		if (i >= 0)
4506 			firstbase = i + 1;
4507 
4508 		/*
4509 		 * Now keep going until we find a non-slash character.  That
4510 		 * character is the last character in the dirname.
4511 		 */
4512 		for (; i >= 0; i--) {
4513 			if (dtrace_load8(src + i) != '/')
4514 				break;
4515 		}
4516 
4517 		if (i >= 0)
4518 			lastdir = i;
4519 
4520 		ASSERT(!(lastbase == -1 && firstbase != -1));
4521 		ASSERT(!(firstbase == -1 && lastdir != -1));
4522 
4523 		if (lastbase == -1) {
4524 			/*
4525 			 * We didn't find a non-slash character.  We know that
4526 			 * the length is non-zero, so the whole string must be
4527 			 * slashes.  In either the dirname or the basename
4528 			 * case, we return '/'.
4529 			 */
4530 			ASSERT(firstbase == -1);
4531 			firstbase = lastbase = lastdir = 0;
4532 		}
4533 
4534 		if (firstbase == -1) {
4535 			/*
4536 			 * The entire string consists only of a basename
4537 			 * component.  If we're looking for dirname, we need
4538 			 * to change our string to be just "."; if we're
4539 			 * looking for a basename, we'll just set the first
4540 			 * character of the basename to be 0.
4541 			 */
4542 			if (subr == DIF_SUBR_DIRNAME) {
4543 				ASSERT(lastdir == -1);
4544 				src = (uintptr_t)".";
4545 				lastdir = 0;
4546 			} else {
4547 				firstbase = 0;
4548 			}
4549 		}
4550 
4551 		if (subr == DIF_SUBR_DIRNAME) {
4552 			if (lastdir == -1) {
4553 				/*
4554 				 * We know that we have a slash in the name --
4555 				 * or lastdir would be set to 0, above.  And
4556 				 * because lastdir is -1, we know that this
4557 				 * slash must be the first character.  (That
4558 				 * is, the full string must be of the form
4559 				 * "/basename".)  In this case, the last
4560 				 * character of the directory name is 0.
4561 				 */
4562 				lastdir = 0;
4563 			}
4564 
4565 			start = 0;
4566 			end = lastdir;
4567 		} else {
4568 			ASSERT(subr == DIF_SUBR_BASENAME);
4569 			ASSERT(firstbase != -1 && lastbase != -1);
4570 			start = firstbase;
4571 			end = lastbase;
4572 		}
4573 
4574 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4575 			dest[j] = dtrace_load8(src + i);
4576 
4577 		dest[j] = '\0';
4578 		regs[rd] = (uintptr_t)dest;
4579 		mstate->dtms_scratch_ptr += size;
4580 		break;
4581 	}
4582 
4583 	case DIF_SUBR_CLEANPATH: {
4584 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4585 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4586 		uintptr_t src = tupregs[0].dttk_value;
4587 		int i = 0, j = 0;
4588 
4589 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
4590 			regs[rd] = 0;
4591 			break;
4592 		}
4593 
4594 		if (!DTRACE_INSCRATCH(mstate, size)) {
4595 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4596 			regs[rd] = 0;
4597 			break;
4598 		}
4599 
4600 		/*
4601 		 * Move forward, loading each character.
4602 		 */
4603 		do {
4604 			c = dtrace_load8(src + i++);
4605 next:
4606 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4607 				break;
4608 
4609 			if (c != '/') {
4610 				dest[j++] = c;
4611 				continue;
4612 			}
4613 
4614 			c = dtrace_load8(src + i++);
4615 
4616 			if (c == '/') {
4617 				/*
4618 				 * We have two slashes -- we can just advance
4619 				 * to the next character.
4620 				 */
4621 				goto next;
4622 			}
4623 
4624 			if (c != '.') {
4625 				/*
4626 				 * This is not "." and it's not ".." -- we can
4627 				 * just store the "/" and this character and
4628 				 * drive on.
4629 				 */
4630 				dest[j++] = '/';
4631 				dest[j++] = c;
4632 				continue;
4633 			}
4634 
4635 			c = dtrace_load8(src + i++);
4636 
4637 			if (c == '/') {
4638 				/*
4639 				 * This is a "/./" component.  We're not going
4640 				 * to store anything in the destination buffer;
4641 				 * we're just going to go to the next component.
4642 				 */
4643 				goto next;
4644 			}
4645 
4646 			if (c != '.') {
4647 				/*
4648 				 * This is not ".." -- we can just store the
4649 				 * "/." and this character and continue
4650 				 * processing.
4651 				 */
4652 				dest[j++] = '/';
4653 				dest[j++] = '.';
4654 				dest[j++] = c;
4655 				continue;
4656 			}
4657 
4658 			c = dtrace_load8(src + i++);
4659 
4660 			if (c != '/' && c != '\0') {
4661 				/*
4662 				 * This is not ".." -- it's "..[mumble]".
4663 				 * We'll store the "/.." and this character
4664 				 * and continue processing.
4665 				 */
4666 				dest[j++] = '/';
4667 				dest[j++] = '.';
4668 				dest[j++] = '.';
4669 				dest[j++] = c;
4670 				continue;
4671 			}
4672 
4673 			/*
4674 			 * This is "/../" or "/..\0".  We need to back up
4675 			 * our destination pointer until we find a "/".
4676 			 */
4677 			i--;
4678 			while (j != 0 && dest[--j] != '/')
4679 				continue;
4680 
4681 			if (c == '\0')
4682 				dest[++j] = '/';
4683 		} while (c != '\0');
4684 
4685 		dest[j] = '\0';
4686 		regs[rd] = (uintptr_t)dest;
4687 		mstate->dtms_scratch_ptr += size;
4688 		break;
4689 	}
4690 
4691 	case DIF_SUBR_INET_NTOA:
4692 	case DIF_SUBR_INET_NTOA6:
4693 	case DIF_SUBR_INET_NTOP: {
4694 		size_t size;
4695 		int af, argi, i;
4696 		char *base, *end;
4697 
4698 		if (subr == DIF_SUBR_INET_NTOP) {
4699 			af = (int)tupregs[0].dttk_value;
4700 			argi = 1;
4701 		} else {
4702 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4703 			argi = 0;
4704 		}
4705 
4706 		if (af == AF_INET) {
4707 			ipaddr_t ip4;
4708 			uint8_t *ptr8, val;
4709 
4710 			/*
4711 			 * Safely load the IPv4 address.
4712 			 */
4713 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4714 
4715 			/*
4716 			 * Check an IPv4 string will fit in scratch.
4717 			 */
4718 			size = INET_ADDRSTRLEN;
4719 			if (!DTRACE_INSCRATCH(mstate, size)) {
4720 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4721 				regs[rd] = 0;
4722 				break;
4723 			}
4724 			base = (char *)mstate->dtms_scratch_ptr;
4725 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4726 
4727 			/*
4728 			 * Stringify as a dotted decimal quad.
4729 			 */
4730 			*end-- = '\0';
4731 			ptr8 = (uint8_t *)&ip4;
4732 			for (i = 3; i >= 0; i--) {
4733 				val = ptr8[i];
4734 
4735 				if (val == 0) {
4736 					*end-- = '0';
4737 				} else {
4738 					for (; val; val /= 10) {
4739 						*end-- = '0' + (val % 10);
4740 					}
4741 				}
4742 
4743 				if (i > 0)
4744 					*end-- = '.';
4745 			}
4746 			ASSERT(end + 1 >= base);
4747 
4748 		} else if (af == AF_INET6) {
4749 			struct in6_addr ip6;
4750 			int firstzero, tryzero, numzero, v6end;
4751 			uint16_t val;
4752 			const char digits[] = "0123456789abcdef";
4753 
4754 			/*
4755 			 * Stringify using RFC 1884 convention 2 - 16 bit
4756 			 * hexadecimal values with a zero-run compression.
4757 			 * Lower case hexadecimal digits are used.
4758 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4759 			 * The IPv4 embedded form is returned for inet_ntop,
4760 			 * just the IPv4 string is returned for inet_ntoa6.
4761 			 */
4762 
4763 			/*
4764 			 * Safely load the IPv6 address.
4765 			 */
4766 			dtrace_bcopy(
4767 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4768 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4769 
4770 			/*
4771 			 * Check an IPv6 string will fit in scratch.
4772 			 */
4773 			size = INET6_ADDRSTRLEN;
4774 			if (!DTRACE_INSCRATCH(mstate, size)) {
4775 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4776 				regs[rd] = 0;
4777 				break;
4778 			}
4779 			base = (char *)mstate->dtms_scratch_ptr;
4780 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4781 			*end-- = '\0';
4782 
4783 			/*
4784 			 * Find the longest run of 16 bit zero values
4785 			 * for the single allowed zero compression - "::".
4786 			 */
4787 			firstzero = -1;
4788 			tryzero = -1;
4789 			numzero = 1;
4790 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4791 #if defined(sun)
4792 				if (ip6._S6_un._S6_u8[i] == 0 &&
4793 #else
4794 				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4795 #endif
4796 				    tryzero == -1 && i % 2 == 0) {
4797 					tryzero = i;
4798 					continue;
4799 				}
4800 
4801 				if (tryzero != -1 &&
4802 #if defined(sun)
4803 				    (ip6._S6_un._S6_u8[i] != 0 ||
4804 #else
4805 				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
4806 #endif
4807 				    i == sizeof (struct in6_addr) - 1)) {
4808 
4809 					if (i - tryzero <= numzero) {
4810 						tryzero = -1;
4811 						continue;
4812 					}
4813 
4814 					firstzero = tryzero;
4815 					numzero = i - i % 2 - tryzero;
4816 					tryzero = -1;
4817 
4818 #if defined(sun)
4819 					if (ip6._S6_un._S6_u8[i] == 0 &&
4820 #else
4821 					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4822 #endif
4823 					    i == sizeof (struct in6_addr) - 1)
4824 						numzero += 2;
4825 				}
4826 			}
4827 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4828 
4829 			/*
4830 			 * Check for an IPv4 embedded address.
4831 			 */
4832 			v6end = sizeof (struct in6_addr) - 2;
4833 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4834 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4835 				for (i = sizeof (struct in6_addr) - 1;
4836 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4837 					ASSERT(end >= base);
4838 
4839 #if defined(sun)
4840 					val = ip6._S6_un._S6_u8[i];
4841 #else
4842 					val = ip6.__u6_addr.__u6_addr8[i];
4843 #endif
4844 
4845 					if (val == 0) {
4846 						*end-- = '0';
4847 					} else {
4848 						for (; val; val /= 10) {
4849 							*end-- = '0' + val % 10;
4850 						}
4851 					}
4852 
4853 					if (i > DTRACE_V4MAPPED_OFFSET)
4854 						*end-- = '.';
4855 				}
4856 
4857 				if (subr == DIF_SUBR_INET_NTOA6)
4858 					goto inetout;
4859 
4860 				/*
4861 				 * Set v6end to skip the IPv4 address that
4862 				 * we have already stringified.
4863 				 */
4864 				v6end = 10;
4865 			}
4866 
4867 			/*
4868 			 * Build the IPv6 string by working through the
4869 			 * address in reverse.
4870 			 */
4871 			for (i = v6end; i >= 0; i -= 2) {
4872 				ASSERT(end >= base);
4873 
4874 				if (i == firstzero + numzero - 2) {
4875 					*end-- = ':';
4876 					*end-- = ':';
4877 					i -= numzero - 2;
4878 					continue;
4879 				}
4880 
4881 				if (i < 14 && i != firstzero - 2)
4882 					*end-- = ':';
4883 
4884 #if defined(sun)
4885 				val = (ip6._S6_un._S6_u8[i] << 8) +
4886 				    ip6._S6_un._S6_u8[i + 1];
4887 #else
4888 				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
4889 				    ip6.__u6_addr.__u6_addr8[i + 1];
4890 #endif
4891 
4892 				if (val == 0) {
4893 					*end-- = '0';
4894 				} else {
4895 					for (; val; val /= 16) {
4896 						*end-- = digits[val % 16];
4897 					}
4898 				}
4899 			}
4900 			ASSERT(end + 1 >= base);
4901 
4902 		} else {
4903 			/*
4904 			 * The user didn't use AH_INET or AH_INET6.
4905 			 */
4906 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4907 			regs[rd] = 0;
4908 			break;
4909 		}
4910 
4911 inetout:	regs[rd] = (uintptr_t)end + 1;
4912 		mstate->dtms_scratch_ptr += size;
4913 		break;
4914 	}
4915 
4916 	case DIF_SUBR_MEMREF: {
4917 		uintptr_t size = 2 * sizeof(uintptr_t);
4918 		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4919 		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
4920 
4921 		/* address and length */
4922 		memref[0] = tupregs[0].dttk_value;
4923 		memref[1] = tupregs[1].dttk_value;
4924 
4925 		regs[rd] = (uintptr_t) memref;
4926 		mstate->dtms_scratch_ptr += scratch_size;
4927 		break;
4928 	}
4929 
4930 #if !defined(sun)
4931 	case DIF_SUBR_MEMSTR: {
4932 		char *str = (char *)mstate->dtms_scratch_ptr;
4933 		uintptr_t mem = tupregs[0].dttk_value;
4934 		char c = tupregs[1].dttk_value;
4935 		size_t size = tupregs[2].dttk_value;
4936 		uint8_t n;
4937 		int i;
4938 
4939 		regs[rd] = 0;
4940 
4941 		if (size == 0)
4942 			break;
4943 
4944 		if (!dtrace_canload(mem, size - 1, mstate, vstate))
4945 			break;
4946 
4947 		if (!DTRACE_INSCRATCH(mstate, size)) {
4948 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4949 			break;
4950 		}
4951 
4952 		if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
4953 			*flags |= CPU_DTRACE_ILLOP;
4954 			break;
4955 		}
4956 
4957 		for (i = 0; i < size - 1; i++) {
4958 			n = dtrace_load8(mem++);
4959 			str[i] = (n == 0) ? c : n;
4960 		}
4961 		str[size - 1] = 0;
4962 
4963 		regs[rd] = (uintptr_t)str;
4964 		mstate->dtms_scratch_ptr += size;
4965 		break;
4966 	}
4967 #endif
4968 
4969 	case DIF_SUBR_TYPEREF: {
4970 		uintptr_t size = 4 * sizeof(uintptr_t);
4971 		uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4972 		size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
4973 
4974 		/* address, num_elements, type_str, type_len */
4975 		typeref[0] = tupregs[0].dttk_value;
4976 		typeref[1] = tupregs[1].dttk_value;
4977 		typeref[2] = tupregs[2].dttk_value;
4978 		typeref[3] = tupregs[3].dttk_value;
4979 
4980 		regs[rd] = (uintptr_t) typeref;
4981 		mstate->dtms_scratch_ptr += scratch_size;
4982 		break;
4983 	}
4984 	}
4985 }
4986 
4987 /*
4988  * Emulate the execution of DTrace IR instructions specified by the given
4989  * DIF object.  This function is deliberately void of assertions as all of
4990  * the necessary checks are handled by a call to dtrace_difo_validate().
4991  */
4992 static uint64_t
4993 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4994     dtrace_vstate_t *vstate, dtrace_state_t *state)
4995 {
4996 	const dif_instr_t *text = difo->dtdo_buf;
4997 	const uint_t textlen = difo->dtdo_len;
4998 	const char *strtab = difo->dtdo_strtab;
4999 	const uint64_t *inttab = difo->dtdo_inttab;
5000 
5001 	uint64_t rval = 0;
5002 	dtrace_statvar_t *svar;
5003 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5004 	dtrace_difv_t *v;
5005 	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5006 	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5007 
5008 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5009 	uint64_t regs[DIF_DIR_NREGS];
5010 	uint64_t *tmp;
5011 
5012 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5013 	int64_t cc_r;
5014 	uint_t pc = 0, id, opc = 0;
5015 	uint8_t ttop = 0;
5016 	dif_instr_t instr;
5017 	uint_t r1, r2, rd;
5018 
5019 	/*
5020 	 * We stash the current DIF object into the machine state: we need it
5021 	 * for subsequent access checking.
5022 	 */
5023 	mstate->dtms_difo = difo;
5024 
5025 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5026 
5027 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5028 		opc = pc;
5029 
5030 		instr = text[pc++];
5031 		r1 = DIF_INSTR_R1(instr);
5032 		r2 = DIF_INSTR_R2(instr);
5033 		rd = DIF_INSTR_RD(instr);
5034 
5035 		switch (DIF_INSTR_OP(instr)) {
5036 		case DIF_OP_OR:
5037 			regs[rd] = regs[r1] | regs[r2];
5038 			break;
5039 		case DIF_OP_XOR:
5040 			regs[rd] = regs[r1] ^ regs[r2];
5041 			break;
5042 		case DIF_OP_AND:
5043 			regs[rd] = regs[r1] & regs[r2];
5044 			break;
5045 		case DIF_OP_SLL:
5046 			regs[rd] = regs[r1] << regs[r2];
5047 			break;
5048 		case DIF_OP_SRL:
5049 			regs[rd] = regs[r1] >> regs[r2];
5050 			break;
5051 		case DIF_OP_SUB:
5052 			regs[rd] = regs[r1] - regs[r2];
5053 			break;
5054 		case DIF_OP_ADD:
5055 			regs[rd] = regs[r1] + regs[r2];
5056 			break;
5057 		case DIF_OP_MUL:
5058 			regs[rd] = regs[r1] * regs[r2];
5059 			break;
5060 		case DIF_OP_SDIV:
5061 			if (regs[r2] == 0) {
5062 				regs[rd] = 0;
5063 				*flags |= CPU_DTRACE_DIVZERO;
5064 			} else {
5065 				regs[rd] = (int64_t)regs[r1] /
5066 				    (int64_t)regs[r2];
5067 			}
5068 			break;
5069 
5070 		case DIF_OP_UDIV:
5071 			if (regs[r2] == 0) {
5072 				regs[rd] = 0;
5073 				*flags |= CPU_DTRACE_DIVZERO;
5074 			} else {
5075 				regs[rd] = regs[r1] / regs[r2];
5076 			}
5077 			break;
5078 
5079 		case DIF_OP_SREM:
5080 			if (regs[r2] == 0) {
5081 				regs[rd] = 0;
5082 				*flags |= CPU_DTRACE_DIVZERO;
5083 			} else {
5084 				regs[rd] = (int64_t)regs[r1] %
5085 				    (int64_t)regs[r2];
5086 			}
5087 			break;
5088 
5089 		case DIF_OP_UREM:
5090 			if (regs[r2] == 0) {
5091 				regs[rd] = 0;
5092 				*flags |= CPU_DTRACE_DIVZERO;
5093 			} else {
5094 				regs[rd] = regs[r1] % regs[r2];
5095 			}
5096 			break;
5097 
5098 		case DIF_OP_NOT:
5099 			regs[rd] = ~regs[r1];
5100 			break;
5101 		case DIF_OP_MOV:
5102 			regs[rd] = regs[r1];
5103 			break;
5104 		case DIF_OP_CMP:
5105 			cc_r = regs[r1] - regs[r2];
5106 			cc_n = cc_r < 0;
5107 			cc_z = cc_r == 0;
5108 			cc_v = 0;
5109 			cc_c = regs[r1] < regs[r2];
5110 			break;
5111 		case DIF_OP_TST:
5112 			cc_n = cc_v = cc_c = 0;
5113 			cc_z = regs[r1] == 0;
5114 			break;
5115 		case DIF_OP_BA:
5116 			pc = DIF_INSTR_LABEL(instr);
5117 			break;
5118 		case DIF_OP_BE:
5119 			if (cc_z)
5120 				pc = DIF_INSTR_LABEL(instr);
5121 			break;
5122 		case DIF_OP_BNE:
5123 			if (cc_z == 0)
5124 				pc = DIF_INSTR_LABEL(instr);
5125 			break;
5126 		case DIF_OP_BG:
5127 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5128 				pc = DIF_INSTR_LABEL(instr);
5129 			break;
5130 		case DIF_OP_BGU:
5131 			if ((cc_c | cc_z) == 0)
5132 				pc = DIF_INSTR_LABEL(instr);
5133 			break;
5134 		case DIF_OP_BGE:
5135 			if ((cc_n ^ cc_v) == 0)
5136 				pc = DIF_INSTR_LABEL(instr);
5137 			break;
5138 		case DIF_OP_BGEU:
5139 			if (cc_c == 0)
5140 				pc = DIF_INSTR_LABEL(instr);
5141 			break;
5142 		case DIF_OP_BL:
5143 			if (cc_n ^ cc_v)
5144 				pc = DIF_INSTR_LABEL(instr);
5145 			break;
5146 		case DIF_OP_BLU:
5147 			if (cc_c)
5148 				pc = DIF_INSTR_LABEL(instr);
5149 			break;
5150 		case DIF_OP_BLE:
5151 			if (cc_z | (cc_n ^ cc_v))
5152 				pc = DIF_INSTR_LABEL(instr);
5153 			break;
5154 		case DIF_OP_BLEU:
5155 			if (cc_c | cc_z)
5156 				pc = DIF_INSTR_LABEL(instr);
5157 			break;
5158 		case DIF_OP_RLDSB:
5159 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5160 				*flags |= CPU_DTRACE_KPRIV;
5161 				*illval = regs[r1];
5162 				break;
5163 			}
5164 			/*FALLTHROUGH*/
5165 		case DIF_OP_LDSB:
5166 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5167 			break;
5168 		case DIF_OP_RLDSH:
5169 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5170 				*flags |= CPU_DTRACE_KPRIV;
5171 				*illval = regs[r1];
5172 				break;
5173 			}
5174 			/*FALLTHROUGH*/
5175 		case DIF_OP_LDSH:
5176 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5177 			break;
5178 		case DIF_OP_RLDSW:
5179 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5180 				*flags |= CPU_DTRACE_KPRIV;
5181 				*illval = regs[r1];
5182 				break;
5183 			}
5184 			/*FALLTHROUGH*/
5185 		case DIF_OP_LDSW:
5186 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5187 			break;
5188 		case DIF_OP_RLDUB:
5189 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5190 				*flags |= CPU_DTRACE_KPRIV;
5191 				*illval = regs[r1];
5192 				break;
5193 			}
5194 			/*FALLTHROUGH*/
5195 		case DIF_OP_LDUB:
5196 			regs[rd] = dtrace_load8(regs[r1]);
5197 			break;
5198 		case DIF_OP_RLDUH:
5199 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5200 				*flags |= CPU_DTRACE_KPRIV;
5201 				*illval = regs[r1];
5202 				break;
5203 			}
5204 			/*FALLTHROUGH*/
5205 		case DIF_OP_LDUH:
5206 			regs[rd] = dtrace_load16(regs[r1]);
5207 			break;
5208 		case DIF_OP_RLDUW:
5209 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5210 				*flags |= CPU_DTRACE_KPRIV;
5211 				*illval = regs[r1];
5212 				break;
5213 			}
5214 			/*FALLTHROUGH*/
5215 		case DIF_OP_LDUW:
5216 			regs[rd] = dtrace_load32(regs[r1]);
5217 			break;
5218 		case DIF_OP_RLDX:
5219 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5220 				*flags |= CPU_DTRACE_KPRIV;
5221 				*illval = regs[r1];
5222 				break;
5223 			}
5224 			/*FALLTHROUGH*/
5225 		case DIF_OP_LDX:
5226 			regs[rd] = dtrace_load64(regs[r1]);
5227 			break;
5228 		case DIF_OP_ULDSB:
5229 			regs[rd] = (int8_t)
5230 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5231 			break;
5232 		case DIF_OP_ULDSH:
5233 			regs[rd] = (int16_t)
5234 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5235 			break;
5236 		case DIF_OP_ULDSW:
5237 			regs[rd] = (int32_t)
5238 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5239 			break;
5240 		case DIF_OP_ULDUB:
5241 			regs[rd] =
5242 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5243 			break;
5244 		case DIF_OP_ULDUH:
5245 			regs[rd] =
5246 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5247 			break;
5248 		case DIF_OP_ULDUW:
5249 			regs[rd] =
5250 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5251 			break;
5252 		case DIF_OP_ULDX:
5253 			regs[rd] =
5254 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5255 			break;
5256 		case DIF_OP_RET:
5257 			rval = regs[rd];
5258 			pc = textlen;
5259 			break;
5260 		case DIF_OP_NOP:
5261 			break;
5262 		case DIF_OP_SETX:
5263 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5264 			break;
5265 		case DIF_OP_SETS:
5266 			regs[rd] = (uint64_t)(uintptr_t)
5267 			    (strtab + DIF_INSTR_STRING(instr));
5268 			break;
5269 		case DIF_OP_SCMP: {
5270 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5271 			uintptr_t s1 = regs[r1];
5272 			uintptr_t s2 = regs[r2];
5273 
5274 			if (s1 != 0 &&
5275 			    !dtrace_strcanload(s1, sz, mstate, vstate))
5276 				break;
5277 			if (s2 != 0 &&
5278 			    !dtrace_strcanload(s2, sz, mstate, vstate))
5279 				break;
5280 
5281 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5282 
5283 			cc_n = cc_r < 0;
5284 			cc_z = cc_r == 0;
5285 			cc_v = cc_c = 0;
5286 			break;
5287 		}
5288 		case DIF_OP_LDGA:
5289 			regs[rd] = dtrace_dif_variable(mstate, state,
5290 			    r1, regs[r2]);
5291 			break;
5292 		case DIF_OP_LDGS:
5293 			id = DIF_INSTR_VAR(instr);
5294 
5295 			if (id >= DIF_VAR_OTHER_UBASE) {
5296 				uintptr_t a;
5297 
5298 				id -= DIF_VAR_OTHER_UBASE;
5299 				svar = vstate->dtvs_globals[id];
5300 				ASSERT(svar != NULL);
5301 				v = &svar->dtsv_var;
5302 
5303 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5304 					regs[rd] = svar->dtsv_data;
5305 					break;
5306 				}
5307 
5308 				a = (uintptr_t)svar->dtsv_data;
5309 
5310 				if (*(uint8_t *)a == UINT8_MAX) {
5311 					/*
5312 					 * If the 0th byte is set to UINT8_MAX
5313 					 * then this is to be treated as a
5314 					 * reference to a NULL variable.
5315 					 */
5316 					regs[rd] = 0;
5317 				} else {
5318 					regs[rd] = a + sizeof (uint64_t);
5319 				}
5320 
5321 				break;
5322 			}
5323 
5324 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5325 			break;
5326 
5327 		case DIF_OP_STGS:
5328 			id = DIF_INSTR_VAR(instr);
5329 
5330 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5331 			id -= DIF_VAR_OTHER_UBASE;
5332 
5333 			svar = vstate->dtvs_globals[id];
5334 			ASSERT(svar != NULL);
5335 			v = &svar->dtsv_var;
5336 
5337 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5338 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5339 
5340 				ASSERT(a != 0);
5341 				ASSERT(svar->dtsv_size != 0);
5342 
5343 				if (regs[rd] == 0) {
5344 					*(uint8_t *)a = UINT8_MAX;
5345 					break;
5346 				} else {
5347 					*(uint8_t *)a = 0;
5348 					a += sizeof (uint64_t);
5349 				}
5350 				if (!dtrace_vcanload(
5351 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5352 				    mstate, vstate))
5353 					break;
5354 
5355 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5356 				    (void *)a, &v->dtdv_type);
5357 				break;
5358 			}
5359 
5360 			svar->dtsv_data = regs[rd];
5361 			break;
5362 
5363 		case DIF_OP_LDTA:
5364 			/*
5365 			 * There are no DTrace built-in thread-local arrays at
5366 			 * present.  This opcode is saved for future work.
5367 			 */
5368 			*flags |= CPU_DTRACE_ILLOP;
5369 			regs[rd] = 0;
5370 			break;
5371 
5372 		case DIF_OP_LDLS:
5373 			id = DIF_INSTR_VAR(instr);
5374 
5375 			if (id < DIF_VAR_OTHER_UBASE) {
5376 				/*
5377 				 * For now, this has no meaning.
5378 				 */
5379 				regs[rd] = 0;
5380 				break;
5381 			}
5382 
5383 			id -= DIF_VAR_OTHER_UBASE;
5384 
5385 			ASSERT(id < vstate->dtvs_nlocals);
5386 			ASSERT(vstate->dtvs_locals != NULL);
5387 
5388 			svar = vstate->dtvs_locals[id];
5389 			ASSERT(svar != NULL);
5390 			v = &svar->dtsv_var;
5391 
5392 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5393 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5394 				size_t sz = v->dtdv_type.dtdt_size;
5395 
5396 				sz += sizeof (uint64_t);
5397 				ASSERT(svar->dtsv_size == NCPU * sz);
5398 				a += curcpu * sz;
5399 
5400 				if (*(uint8_t *)a == UINT8_MAX) {
5401 					/*
5402 					 * If the 0th byte is set to UINT8_MAX
5403 					 * then this is to be treated as a
5404 					 * reference to a NULL variable.
5405 					 */
5406 					regs[rd] = 0;
5407 				} else {
5408 					regs[rd] = a + sizeof (uint64_t);
5409 				}
5410 
5411 				break;
5412 			}
5413 
5414 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5415 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5416 			regs[rd] = tmp[curcpu];
5417 			break;
5418 
5419 		case DIF_OP_STLS:
5420 			id = DIF_INSTR_VAR(instr);
5421 
5422 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5423 			id -= DIF_VAR_OTHER_UBASE;
5424 			ASSERT(id < vstate->dtvs_nlocals);
5425 
5426 			ASSERT(vstate->dtvs_locals != NULL);
5427 			svar = vstate->dtvs_locals[id];
5428 			ASSERT(svar != NULL);
5429 			v = &svar->dtsv_var;
5430 
5431 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5432 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5433 				size_t sz = v->dtdv_type.dtdt_size;
5434 
5435 				sz += sizeof (uint64_t);
5436 				ASSERT(svar->dtsv_size == NCPU * sz);
5437 				a += curcpu * sz;
5438 
5439 				if (regs[rd] == 0) {
5440 					*(uint8_t *)a = UINT8_MAX;
5441 					break;
5442 				} else {
5443 					*(uint8_t *)a = 0;
5444 					a += sizeof (uint64_t);
5445 				}
5446 
5447 				if (!dtrace_vcanload(
5448 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5449 				    mstate, vstate))
5450 					break;
5451 
5452 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5453 				    (void *)a, &v->dtdv_type);
5454 				break;
5455 			}
5456 
5457 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5458 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5459 			tmp[curcpu] = regs[rd];
5460 			break;
5461 
5462 		case DIF_OP_LDTS: {
5463 			dtrace_dynvar_t *dvar;
5464 			dtrace_key_t *key;
5465 
5466 			id = DIF_INSTR_VAR(instr);
5467 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5468 			id -= DIF_VAR_OTHER_UBASE;
5469 			v = &vstate->dtvs_tlocals[id];
5470 
5471 			key = &tupregs[DIF_DTR_NREGS];
5472 			key[0].dttk_value = (uint64_t)id;
5473 			key[0].dttk_size = 0;
5474 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5475 			key[1].dttk_size = 0;
5476 
5477 			dvar = dtrace_dynvar(dstate, 2, key,
5478 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5479 			    mstate, vstate);
5480 
5481 			if (dvar == NULL) {
5482 				regs[rd] = 0;
5483 				break;
5484 			}
5485 
5486 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5487 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5488 			} else {
5489 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5490 			}
5491 
5492 			break;
5493 		}
5494 
5495 		case DIF_OP_STTS: {
5496 			dtrace_dynvar_t *dvar;
5497 			dtrace_key_t *key;
5498 
5499 			id = DIF_INSTR_VAR(instr);
5500 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5501 			id -= DIF_VAR_OTHER_UBASE;
5502 
5503 			key = &tupregs[DIF_DTR_NREGS];
5504 			key[0].dttk_value = (uint64_t)id;
5505 			key[0].dttk_size = 0;
5506 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5507 			key[1].dttk_size = 0;
5508 			v = &vstate->dtvs_tlocals[id];
5509 
5510 			dvar = dtrace_dynvar(dstate, 2, key,
5511 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5512 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5513 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5514 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5515 
5516 			/*
5517 			 * Given that we're storing to thread-local data,
5518 			 * we need to flush our predicate cache.
5519 			 */
5520 			curthread->t_predcache = 0;
5521 
5522 			if (dvar == NULL)
5523 				break;
5524 
5525 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5526 				if (!dtrace_vcanload(
5527 				    (void *)(uintptr_t)regs[rd],
5528 				    &v->dtdv_type, mstate, vstate))
5529 					break;
5530 
5531 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5532 				    dvar->dtdv_data, &v->dtdv_type);
5533 			} else {
5534 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5535 			}
5536 
5537 			break;
5538 		}
5539 
5540 		case DIF_OP_SRA:
5541 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
5542 			break;
5543 
5544 		case DIF_OP_CALL:
5545 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5546 			    regs, tupregs, ttop, mstate, state);
5547 			break;
5548 
5549 		case DIF_OP_PUSHTR:
5550 			if (ttop == DIF_DTR_NREGS) {
5551 				*flags |= CPU_DTRACE_TUPOFLOW;
5552 				break;
5553 			}
5554 
5555 			if (r1 == DIF_TYPE_STRING) {
5556 				/*
5557 				 * If this is a string type and the size is 0,
5558 				 * we'll use the system-wide default string
5559 				 * size.  Note that we are _not_ looking at
5560 				 * the value of the DTRACEOPT_STRSIZE option;
5561 				 * had this been set, we would expect to have
5562 				 * a non-zero size value in the "pushtr".
5563 				 */
5564 				tupregs[ttop].dttk_size =
5565 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
5566 				    regs[r2] ? regs[r2] :
5567 				    dtrace_strsize_default) + 1;
5568 			} else {
5569 				tupregs[ttop].dttk_size = regs[r2];
5570 			}
5571 
5572 			tupregs[ttop++].dttk_value = regs[rd];
5573 			break;
5574 
5575 		case DIF_OP_PUSHTV:
5576 			if (ttop == DIF_DTR_NREGS) {
5577 				*flags |= CPU_DTRACE_TUPOFLOW;
5578 				break;
5579 			}
5580 
5581 			tupregs[ttop].dttk_value = regs[rd];
5582 			tupregs[ttop++].dttk_size = 0;
5583 			break;
5584 
5585 		case DIF_OP_POPTS:
5586 			if (ttop != 0)
5587 				ttop--;
5588 			break;
5589 
5590 		case DIF_OP_FLUSHTS:
5591 			ttop = 0;
5592 			break;
5593 
5594 		case DIF_OP_LDGAA:
5595 		case DIF_OP_LDTAA: {
5596 			dtrace_dynvar_t *dvar;
5597 			dtrace_key_t *key = tupregs;
5598 			uint_t nkeys = ttop;
5599 
5600 			id = DIF_INSTR_VAR(instr);
5601 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5602 			id -= DIF_VAR_OTHER_UBASE;
5603 
5604 			key[nkeys].dttk_value = (uint64_t)id;
5605 			key[nkeys++].dttk_size = 0;
5606 
5607 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5608 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5609 				key[nkeys++].dttk_size = 0;
5610 				v = &vstate->dtvs_tlocals[id];
5611 			} else {
5612 				v = &vstate->dtvs_globals[id]->dtsv_var;
5613 			}
5614 
5615 			dvar = dtrace_dynvar(dstate, nkeys, key,
5616 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5617 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5618 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5619 
5620 			if (dvar == NULL) {
5621 				regs[rd] = 0;
5622 				break;
5623 			}
5624 
5625 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5626 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5627 			} else {
5628 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5629 			}
5630 
5631 			break;
5632 		}
5633 
5634 		case DIF_OP_STGAA:
5635 		case DIF_OP_STTAA: {
5636 			dtrace_dynvar_t *dvar;
5637 			dtrace_key_t *key = tupregs;
5638 			uint_t nkeys = ttop;
5639 
5640 			id = DIF_INSTR_VAR(instr);
5641 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5642 			id -= DIF_VAR_OTHER_UBASE;
5643 
5644 			key[nkeys].dttk_value = (uint64_t)id;
5645 			key[nkeys++].dttk_size = 0;
5646 
5647 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5648 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5649 				key[nkeys++].dttk_size = 0;
5650 				v = &vstate->dtvs_tlocals[id];
5651 			} else {
5652 				v = &vstate->dtvs_globals[id]->dtsv_var;
5653 			}
5654 
5655 			dvar = dtrace_dynvar(dstate, nkeys, key,
5656 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5657 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5658 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5659 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5660 
5661 			if (dvar == NULL)
5662 				break;
5663 
5664 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5665 				if (!dtrace_vcanload(
5666 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5667 				    mstate, vstate))
5668 					break;
5669 
5670 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5671 				    dvar->dtdv_data, &v->dtdv_type);
5672 			} else {
5673 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5674 			}
5675 
5676 			break;
5677 		}
5678 
5679 		case DIF_OP_ALLOCS: {
5680 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5681 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5682 
5683 			/*
5684 			 * Rounding up the user allocation size could have
5685 			 * overflowed large, bogus allocations (like -1ULL) to
5686 			 * 0.
5687 			 */
5688 			if (size < regs[r1] ||
5689 			    !DTRACE_INSCRATCH(mstate, size)) {
5690 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5691 				regs[rd] = 0;
5692 				break;
5693 			}
5694 
5695 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5696 			mstate->dtms_scratch_ptr += size;
5697 			regs[rd] = ptr;
5698 			break;
5699 		}
5700 
5701 		case DIF_OP_COPYS:
5702 			if (!dtrace_canstore(regs[rd], regs[r2],
5703 			    mstate, vstate)) {
5704 				*flags |= CPU_DTRACE_BADADDR;
5705 				*illval = regs[rd];
5706 				break;
5707 			}
5708 
5709 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5710 				break;
5711 
5712 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5713 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5714 			break;
5715 
5716 		case DIF_OP_STB:
5717 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5718 				*flags |= CPU_DTRACE_BADADDR;
5719 				*illval = regs[rd];
5720 				break;
5721 			}
5722 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5723 			break;
5724 
5725 		case DIF_OP_STH:
5726 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5727 				*flags |= CPU_DTRACE_BADADDR;
5728 				*illval = regs[rd];
5729 				break;
5730 			}
5731 			if (regs[rd] & 1) {
5732 				*flags |= CPU_DTRACE_BADALIGN;
5733 				*illval = regs[rd];
5734 				break;
5735 			}
5736 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5737 			break;
5738 
5739 		case DIF_OP_STW:
5740 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5741 				*flags |= CPU_DTRACE_BADADDR;
5742 				*illval = regs[rd];
5743 				break;
5744 			}
5745 			if (regs[rd] & 3) {
5746 				*flags |= CPU_DTRACE_BADALIGN;
5747 				*illval = regs[rd];
5748 				break;
5749 			}
5750 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5751 			break;
5752 
5753 		case DIF_OP_STX:
5754 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5755 				*flags |= CPU_DTRACE_BADADDR;
5756 				*illval = regs[rd];
5757 				break;
5758 			}
5759 			if (regs[rd] & 7) {
5760 				*flags |= CPU_DTRACE_BADALIGN;
5761 				*illval = regs[rd];
5762 				break;
5763 			}
5764 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5765 			break;
5766 		}
5767 	}
5768 
5769 	if (!(*flags & CPU_DTRACE_FAULT))
5770 		return (rval);
5771 
5772 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5773 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5774 
5775 	return (0);
5776 }
5777 
5778 static void
5779 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5780 {
5781 	dtrace_probe_t *probe = ecb->dte_probe;
5782 	dtrace_provider_t *prov = probe->dtpr_provider;
5783 	char c[DTRACE_FULLNAMELEN + 80], *str;
5784 	char *msg = "dtrace: breakpoint action at probe ";
5785 	char *ecbmsg = " (ecb ";
5786 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5787 	uintptr_t val = (uintptr_t)ecb;
5788 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5789 
5790 	if (dtrace_destructive_disallow)
5791 		return;
5792 
5793 	/*
5794 	 * It's impossible to be taking action on the NULL probe.
5795 	 */
5796 	ASSERT(probe != NULL);
5797 
5798 	/*
5799 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5800 	 * print the provider name, module name, function name and name of
5801 	 * the probe, along with the hex address of the ECB with the breakpoint
5802 	 * action -- all of which we must place in the character buffer by
5803 	 * hand.
5804 	 */
5805 	while (*msg != '\0')
5806 		c[i++] = *msg++;
5807 
5808 	for (str = prov->dtpv_name; *str != '\0'; str++)
5809 		c[i++] = *str;
5810 	c[i++] = ':';
5811 
5812 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5813 		c[i++] = *str;
5814 	c[i++] = ':';
5815 
5816 	for (str = probe->dtpr_func; *str != '\0'; str++)
5817 		c[i++] = *str;
5818 	c[i++] = ':';
5819 
5820 	for (str = probe->dtpr_name; *str != '\0'; str++)
5821 		c[i++] = *str;
5822 
5823 	while (*ecbmsg != '\0')
5824 		c[i++] = *ecbmsg++;
5825 
5826 	while (shift >= 0) {
5827 		mask = (uintptr_t)0xf << shift;
5828 
5829 		if (val >= ((uintptr_t)1 << shift))
5830 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5831 		shift -= 4;
5832 	}
5833 
5834 	c[i++] = ')';
5835 	c[i] = '\0';
5836 
5837 #if defined(sun)
5838 	debug_enter(c);
5839 #else
5840 	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
5841 #endif
5842 }
5843 
5844 static void
5845 dtrace_action_panic(dtrace_ecb_t *ecb)
5846 {
5847 	dtrace_probe_t *probe = ecb->dte_probe;
5848 
5849 	/*
5850 	 * It's impossible to be taking action on the NULL probe.
5851 	 */
5852 	ASSERT(probe != NULL);
5853 
5854 	if (dtrace_destructive_disallow)
5855 		return;
5856 
5857 	if (dtrace_panicked != NULL)
5858 		return;
5859 
5860 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5861 		return;
5862 
5863 	/*
5864 	 * We won the right to panic.  (We want to be sure that only one
5865 	 * thread calls panic() from dtrace_probe(), and that panic() is
5866 	 * called exactly once.)
5867 	 */
5868 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5869 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5870 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5871 }
5872 
5873 static void
5874 dtrace_action_raise(uint64_t sig)
5875 {
5876 	if (dtrace_destructive_disallow)
5877 		return;
5878 
5879 	if (sig >= NSIG) {
5880 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5881 		return;
5882 	}
5883 
5884 #if defined(sun)
5885 	/*
5886 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5887 	 * invocations of the raise() action.
5888 	 */
5889 	if (curthread->t_dtrace_sig == 0)
5890 		curthread->t_dtrace_sig = (uint8_t)sig;
5891 
5892 	curthread->t_sig_check = 1;
5893 	aston(curthread);
5894 #else
5895 	struct proc *p = curproc;
5896 	PROC_LOCK(p);
5897 	kern_psignal(p, sig);
5898 	PROC_UNLOCK(p);
5899 #endif
5900 }
5901 
5902 static void
5903 dtrace_action_stop(void)
5904 {
5905 	if (dtrace_destructive_disallow)
5906 		return;
5907 
5908 #if defined(sun)
5909 	if (!curthread->t_dtrace_stop) {
5910 		curthread->t_dtrace_stop = 1;
5911 		curthread->t_sig_check = 1;
5912 		aston(curthread);
5913 	}
5914 #else
5915 	struct proc *p = curproc;
5916 	PROC_LOCK(p);
5917 	kern_psignal(p, SIGSTOP);
5918 	PROC_UNLOCK(p);
5919 #endif
5920 }
5921 
5922 static void
5923 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5924 {
5925 	hrtime_t now;
5926 	volatile uint16_t *flags;
5927 #if defined(sun)
5928 	cpu_t *cpu = CPU;
5929 #else
5930 	cpu_t *cpu = &solaris_cpu[curcpu];
5931 #endif
5932 
5933 	if (dtrace_destructive_disallow)
5934 		return;
5935 
5936 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5937 
5938 	now = dtrace_gethrtime();
5939 
5940 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5941 		/*
5942 		 * We need to advance the mark to the current time.
5943 		 */
5944 		cpu->cpu_dtrace_chillmark = now;
5945 		cpu->cpu_dtrace_chilled = 0;
5946 	}
5947 
5948 	/*
5949 	 * Now check to see if the requested chill time would take us over
5950 	 * the maximum amount of time allowed in the chill interval.  (Or
5951 	 * worse, if the calculation itself induces overflow.)
5952 	 */
5953 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5954 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5955 		*flags |= CPU_DTRACE_ILLOP;
5956 		return;
5957 	}
5958 
5959 	while (dtrace_gethrtime() - now < val)
5960 		continue;
5961 
5962 	/*
5963 	 * Normally, we assure that the value of the variable "timestamp" does
5964 	 * not change within an ECB.  The presence of chill() represents an
5965 	 * exception to this rule, however.
5966 	 */
5967 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5968 	cpu->cpu_dtrace_chilled += val;
5969 }
5970 
5971 static void
5972 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5973     uint64_t *buf, uint64_t arg)
5974 {
5975 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5976 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5977 	uint64_t *pcs = &buf[1], *fps;
5978 	char *str = (char *)&pcs[nframes];
5979 	int size, offs = 0, i, j;
5980 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5981 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5982 	char *sym;
5983 
5984 	/*
5985 	 * Should be taking a faster path if string space has not been
5986 	 * allocated.
5987 	 */
5988 	ASSERT(strsize != 0);
5989 
5990 	/*
5991 	 * We will first allocate some temporary space for the frame pointers.
5992 	 */
5993 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5994 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5995 	    (nframes * sizeof (uint64_t));
5996 
5997 	if (!DTRACE_INSCRATCH(mstate, size)) {
5998 		/*
5999 		 * Not enough room for our frame pointers -- need to indicate
6000 		 * that we ran out of scratch space.
6001 		 */
6002 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6003 		return;
6004 	}
6005 
6006 	mstate->dtms_scratch_ptr += size;
6007 	saved = mstate->dtms_scratch_ptr;
6008 
6009 	/*
6010 	 * Now get a stack with both program counters and frame pointers.
6011 	 */
6012 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6013 	dtrace_getufpstack(buf, fps, nframes + 1);
6014 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6015 
6016 	/*
6017 	 * If that faulted, we're cooked.
6018 	 */
6019 	if (*flags & CPU_DTRACE_FAULT)
6020 		goto out;
6021 
6022 	/*
6023 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6024 	 * each iteration, we restore the scratch pointer.
6025 	 */
6026 	for (i = 0; i < nframes; i++) {
6027 		mstate->dtms_scratch_ptr = saved;
6028 
6029 		if (offs >= strsize)
6030 			break;
6031 
6032 		sym = (char *)(uintptr_t)dtrace_helper(
6033 		    DTRACE_HELPER_ACTION_USTACK,
6034 		    mstate, state, pcs[i], fps[i]);
6035 
6036 		/*
6037 		 * If we faulted while running the helper, we're going to
6038 		 * clear the fault and null out the corresponding string.
6039 		 */
6040 		if (*flags & CPU_DTRACE_FAULT) {
6041 			*flags &= ~CPU_DTRACE_FAULT;
6042 			str[offs++] = '\0';
6043 			continue;
6044 		}
6045 
6046 		if (sym == NULL) {
6047 			str[offs++] = '\0';
6048 			continue;
6049 		}
6050 
6051 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6052 
6053 		/*
6054 		 * Now copy in the string that the helper returned to us.
6055 		 */
6056 		for (j = 0; offs + j < strsize; j++) {
6057 			if ((str[offs + j] = sym[j]) == '\0')
6058 				break;
6059 		}
6060 
6061 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6062 
6063 		offs += j + 1;
6064 	}
6065 
6066 	if (offs >= strsize) {
6067 		/*
6068 		 * If we didn't have room for all of the strings, we don't
6069 		 * abort processing -- this needn't be a fatal error -- but we
6070 		 * still want to increment a counter (dts_stkstroverflows) to
6071 		 * allow this condition to be warned about.  (If this is from
6072 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6073 		 */
6074 		dtrace_error(&state->dts_stkstroverflows);
6075 	}
6076 
6077 	while (offs < strsize)
6078 		str[offs++] = '\0';
6079 
6080 out:
6081 	mstate->dtms_scratch_ptr = old;
6082 }
6083 
6084 /*
6085  * If you're looking for the epicenter of DTrace, you just found it.  This
6086  * is the function called by the provider to fire a probe -- from which all
6087  * subsequent probe-context DTrace activity emanates.
6088  */
6089 void
6090 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6091     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6092 {
6093 	processorid_t cpuid;
6094 	dtrace_icookie_t cookie;
6095 	dtrace_probe_t *probe;
6096 	dtrace_mstate_t mstate;
6097 	dtrace_ecb_t *ecb;
6098 	dtrace_action_t *act;
6099 	intptr_t offs;
6100 	size_t size;
6101 	int vtime, onintr;
6102 	volatile uint16_t *flags;
6103 	hrtime_t now;
6104 
6105 	if (panicstr != NULL)
6106 		return;
6107 
6108 #if defined(sun)
6109 	/*
6110 	 * Kick out immediately if this CPU is still being born (in which case
6111 	 * curthread will be set to -1) or the current thread can't allow
6112 	 * probes in its current context.
6113 	 */
6114 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6115 		return;
6116 #endif
6117 
6118 	cookie = dtrace_interrupt_disable();
6119 	probe = dtrace_probes[id - 1];
6120 	cpuid = curcpu;
6121 	onintr = CPU_ON_INTR(CPU);
6122 
6123 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6124 	    probe->dtpr_predcache == curthread->t_predcache) {
6125 		/*
6126 		 * We have hit in the predicate cache; we know that
6127 		 * this predicate would evaluate to be false.
6128 		 */
6129 		dtrace_interrupt_enable(cookie);
6130 		return;
6131 	}
6132 
6133 #if defined(sun)
6134 	if (panic_quiesce) {
6135 #else
6136 	if (panicstr != NULL) {
6137 #endif
6138 		/*
6139 		 * We don't trace anything if we're panicking.
6140 		 */
6141 		dtrace_interrupt_enable(cookie);
6142 		return;
6143 	}
6144 
6145 	now = dtrace_gethrtime();
6146 	vtime = dtrace_vtime_references != 0;
6147 
6148 	if (vtime && curthread->t_dtrace_start)
6149 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6150 
6151 	mstate.dtms_difo = NULL;
6152 	mstate.dtms_probe = probe;
6153 	mstate.dtms_strtok = 0;
6154 	mstate.dtms_arg[0] = arg0;
6155 	mstate.dtms_arg[1] = arg1;
6156 	mstate.dtms_arg[2] = arg2;
6157 	mstate.dtms_arg[3] = arg3;
6158 	mstate.dtms_arg[4] = arg4;
6159 
6160 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6161 
6162 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6163 		dtrace_predicate_t *pred = ecb->dte_predicate;
6164 		dtrace_state_t *state = ecb->dte_state;
6165 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6166 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6167 		dtrace_vstate_t *vstate = &state->dts_vstate;
6168 		dtrace_provider_t *prov = probe->dtpr_provider;
6169 		uint64_t tracememsize = 0;
6170 		int committed = 0;
6171 		caddr_t tomax;
6172 
6173 		/*
6174 		 * A little subtlety with the following (seemingly innocuous)
6175 		 * declaration of the automatic 'val':  by looking at the
6176 		 * code, you might think that it could be declared in the
6177 		 * action processing loop, below.  (That is, it's only used in
6178 		 * the action processing loop.)  However, it must be declared
6179 		 * out of that scope because in the case of DIF expression
6180 		 * arguments to aggregating actions, one iteration of the
6181 		 * action loop will use the last iteration's value.
6182 		 */
6183 		uint64_t val = 0;
6184 
6185 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6186 		*flags &= ~CPU_DTRACE_ERROR;
6187 
6188 		if (prov == dtrace_provider) {
6189 			/*
6190 			 * If dtrace itself is the provider of this probe,
6191 			 * we're only going to continue processing the ECB if
6192 			 * arg0 (the dtrace_state_t) is equal to the ECB's
6193 			 * creating state.  (This prevents disjoint consumers
6194 			 * from seeing one another's metaprobes.)
6195 			 */
6196 			if (arg0 != (uint64_t)(uintptr_t)state)
6197 				continue;
6198 		}
6199 
6200 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6201 			/*
6202 			 * We're not currently active.  If our provider isn't
6203 			 * the dtrace pseudo provider, we're not interested.
6204 			 */
6205 			if (prov != dtrace_provider)
6206 				continue;
6207 
6208 			/*
6209 			 * Now we must further check if we are in the BEGIN
6210 			 * probe.  If we are, we will only continue processing
6211 			 * if we're still in WARMUP -- if one BEGIN enabling
6212 			 * has invoked the exit() action, we don't want to
6213 			 * evaluate subsequent BEGIN enablings.
6214 			 */
6215 			if (probe->dtpr_id == dtrace_probeid_begin &&
6216 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6217 				ASSERT(state->dts_activity ==
6218 				    DTRACE_ACTIVITY_DRAINING);
6219 				continue;
6220 			}
6221 		}
6222 
6223 		if (ecb->dte_cond) {
6224 			/*
6225 			 * If the dte_cond bits indicate that this
6226 			 * consumer is only allowed to see user-mode firings
6227 			 * of this probe, call the provider's dtps_usermode()
6228 			 * entry point to check that the probe was fired
6229 			 * while in a user context. Skip this ECB if that's
6230 			 * not the case.
6231 			 */
6232 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6233 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6234 			    probe->dtpr_id, probe->dtpr_arg) == 0)
6235 				continue;
6236 
6237 #if defined(sun)
6238 			/*
6239 			 * This is more subtle than it looks. We have to be
6240 			 * absolutely certain that CRED() isn't going to
6241 			 * change out from under us so it's only legit to
6242 			 * examine that structure if we're in constrained
6243 			 * situations. Currently, the only times we'll this
6244 			 * check is if a non-super-user has enabled the
6245 			 * profile or syscall providers -- providers that
6246 			 * allow visibility of all processes. For the
6247 			 * profile case, the check above will ensure that
6248 			 * we're examining a user context.
6249 			 */
6250 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
6251 				cred_t *cr;
6252 				cred_t *s_cr =
6253 				    ecb->dte_state->dts_cred.dcr_cred;
6254 				proc_t *proc;
6255 
6256 				ASSERT(s_cr != NULL);
6257 
6258 				if ((cr = CRED()) == NULL ||
6259 				    s_cr->cr_uid != cr->cr_uid ||
6260 				    s_cr->cr_uid != cr->cr_ruid ||
6261 				    s_cr->cr_uid != cr->cr_suid ||
6262 				    s_cr->cr_gid != cr->cr_gid ||
6263 				    s_cr->cr_gid != cr->cr_rgid ||
6264 				    s_cr->cr_gid != cr->cr_sgid ||
6265 				    (proc = ttoproc(curthread)) == NULL ||
6266 				    (proc->p_flag & SNOCD))
6267 					continue;
6268 			}
6269 
6270 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6271 				cred_t *cr;
6272 				cred_t *s_cr =
6273 				    ecb->dte_state->dts_cred.dcr_cred;
6274 
6275 				ASSERT(s_cr != NULL);
6276 
6277 				if ((cr = CRED()) == NULL ||
6278 				    s_cr->cr_zone->zone_id !=
6279 				    cr->cr_zone->zone_id)
6280 					continue;
6281 			}
6282 #endif
6283 		}
6284 
6285 		if (now - state->dts_alive > dtrace_deadman_timeout) {
6286 			/*
6287 			 * We seem to be dead.  Unless we (a) have kernel
6288 			 * destructive permissions (b) have explicitly enabled
6289 			 * destructive actions and (c) destructive actions have
6290 			 * not been disabled, we're going to transition into
6291 			 * the KILLED state, from which no further processing
6292 			 * on this state will be performed.
6293 			 */
6294 			if (!dtrace_priv_kernel_destructive(state) ||
6295 			    !state->dts_cred.dcr_destructive ||
6296 			    dtrace_destructive_disallow) {
6297 				void *activity = &state->dts_activity;
6298 				dtrace_activity_t current;
6299 
6300 				do {
6301 					current = state->dts_activity;
6302 				} while (dtrace_cas32(activity, current,
6303 				    DTRACE_ACTIVITY_KILLED) != current);
6304 
6305 				continue;
6306 			}
6307 		}
6308 
6309 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6310 		    ecb->dte_alignment, state, &mstate)) < 0)
6311 			continue;
6312 
6313 		tomax = buf->dtb_tomax;
6314 		ASSERT(tomax != NULL);
6315 
6316 		if (ecb->dte_size != 0) {
6317 			dtrace_rechdr_t dtrh;
6318 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6319 				mstate.dtms_timestamp = dtrace_gethrtime();
6320 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6321 			}
6322 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6323 			dtrh.dtrh_epid = ecb->dte_epid;
6324 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6325 			    mstate.dtms_timestamp);
6326 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6327 		}
6328 
6329 		mstate.dtms_epid = ecb->dte_epid;
6330 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
6331 
6332 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6333 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6334 		else
6335 			mstate.dtms_access = 0;
6336 
6337 		if (pred != NULL) {
6338 			dtrace_difo_t *dp = pred->dtp_difo;
6339 			uint64_t rval;
6340 
6341 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6342 
6343 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6344 				dtrace_cacheid_t cid = probe->dtpr_predcache;
6345 
6346 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
6347 					/*
6348 					 * Update the predicate cache...
6349 					 */
6350 					ASSERT(cid == pred->dtp_cacheid);
6351 					curthread->t_predcache = cid;
6352 				}
6353 
6354 				continue;
6355 			}
6356 		}
6357 
6358 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6359 		    act != NULL; act = act->dta_next) {
6360 			size_t valoffs;
6361 			dtrace_difo_t *dp;
6362 			dtrace_recdesc_t *rec = &act->dta_rec;
6363 
6364 			size = rec->dtrd_size;
6365 			valoffs = offs + rec->dtrd_offset;
6366 
6367 			if (DTRACEACT_ISAGG(act->dta_kind)) {
6368 				uint64_t v = 0xbad;
6369 				dtrace_aggregation_t *agg;
6370 
6371 				agg = (dtrace_aggregation_t *)act;
6372 
6373 				if ((dp = act->dta_difo) != NULL)
6374 					v = dtrace_dif_emulate(dp,
6375 					    &mstate, vstate, state);
6376 
6377 				if (*flags & CPU_DTRACE_ERROR)
6378 					continue;
6379 
6380 				/*
6381 				 * Note that we always pass the expression
6382 				 * value from the previous iteration of the
6383 				 * action loop.  This value will only be used
6384 				 * if there is an expression argument to the
6385 				 * aggregating action, denoted by the
6386 				 * dtag_hasarg field.
6387 				 */
6388 				dtrace_aggregate(agg, buf,
6389 				    offs, aggbuf, v, val);
6390 				continue;
6391 			}
6392 
6393 			switch (act->dta_kind) {
6394 			case DTRACEACT_STOP:
6395 				if (dtrace_priv_proc_destructive(state))
6396 					dtrace_action_stop();
6397 				continue;
6398 
6399 			case DTRACEACT_BREAKPOINT:
6400 				if (dtrace_priv_kernel_destructive(state))
6401 					dtrace_action_breakpoint(ecb);
6402 				continue;
6403 
6404 			case DTRACEACT_PANIC:
6405 				if (dtrace_priv_kernel_destructive(state))
6406 					dtrace_action_panic(ecb);
6407 				continue;
6408 
6409 			case DTRACEACT_STACK:
6410 				if (!dtrace_priv_kernel(state))
6411 					continue;
6412 
6413 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6414 				    size / sizeof (pc_t), probe->dtpr_aframes,
6415 				    DTRACE_ANCHORED(probe) ? NULL :
6416 				    (uint32_t *)arg0);
6417 				continue;
6418 
6419 			case DTRACEACT_JSTACK:
6420 			case DTRACEACT_USTACK:
6421 				if (!dtrace_priv_proc(state))
6422 					continue;
6423 
6424 				/*
6425 				 * See comment in DIF_VAR_PID.
6426 				 */
6427 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6428 				    CPU_ON_INTR(CPU)) {
6429 					int depth = DTRACE_USTACK_NFRAMES(
6430 					    rec->dtrd_arg) + 1;
6431 
6432 					dtrace_bzero((void *)(tomax + valoffs),
6433 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6434 					    + depth * sizeof (uint64_t));
6435 
6436 					continue;
6437 				}
6438 
6439 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6440 				    curproc->p_dtrace_helpers != NULL) {
6441 					/*
6442 					 * This is the slow path -- we have
6443 					 * allocated string space, and we're
6444 					 * getting the stack of a process that
6445 					 * has helpers.  Call into a separate
6446 					 * routine to perform this processing.
6447 					 */
6448 					dtrace_action_ustack(&mstate, state,
6449 					    (uint64_t *)(tomax + valoffs),
6450 					    rec->dtrd_arg);
6451 					continue;
6452 				}
6453 
6454 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6455 				dtrace_getupcstack((uint64_t *)
6456 				    (tomax + valoffs),
6457 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6458 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6459 				continue;
6460 
6461 			default:
6462 				break;
6463 			}
6464 
6465 			dp = act->dta_difo;
6466 			ASSERT(dp != NULL);
6467 
6468 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6469 
6470 			if (*flags & CPU_DTRACE_ERROR)
6471 				continue;
6472 
6473 			switch (act->dta_kind) {
6474 			case DTRACEACT_SPECULATE: {
6475 				dtrace_rechdr_t *dtrh;
6476 
6477 				ASSERT(buf == &state->dts_buffer[cpuid]);
6478 				buf = dtrace_speculation_buffer(state,
6479 				    cpuid, val);
6480 
6481 				if (buf == NULL) {
6482 					*flags |= CPU_DTRACE_DROP;
6483 					continue;
6484 				}
6485 
6486 				offs = dtrace_buffer_reserve(buf,
6487 				    ecb->dte_needed, ecb->dte_alignment,
6488 				    state, NULL);
6489 
6490 				if (offs < 0) {
6491 					*flags |= CPU_DTRACE_DROP;
6492 					continue;
6493 				}
6494 
6495 				tomax = buf->dtb_tomax;
6496 				ASSERT(tomax != NULL);
6497 
6498 				if (ecb->dte_size == 0)
6499 					continue;
6500 
6501 				ASSERT3U(ecb->dte_size, >=,
6502 				    sizeof (dtrace_rechdr_t));
6503 				dtrh = ((void *)(tomax + offs));
6504 				dtrh->dtrh_epid = ecb->dte_epid;
6505 				/*
6506 				 * When the speculation is committed, all of
6507 				 * the records in the speculative buffer will
6508 				 * have their timestamps set to the commit
6509 				 * time.  Until then, it is set to a sentinel
6510 				 * value, for debugability.
6511 				 */
6512 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6513 				continue;
6514 			}
6515 
6516 			case DTRACEACT_PRINTM: {
6517 				/* The DIF returns a 'memref'. */
6518 				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6519 
6520 				/* Get the size from the memref. */
6521 				size = memref[1];
6522 
6523 				/*
6524 				 * Check if the size exceeds the allocated
6525 				 * buffer size.
6526 				 */
6527 				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6528 					/* Flag a drop! */
6529 					*flags |= CPU_DTRACE_DROP;
6530 					continue;
6531 				}
6532 
6533 				/* Store the size in the buffer first. */
6534 				DTRACE_STORE(uintptr_t, tomax,
6535 				    valoffs, size);
6536 
6537 				/*
6538 				 * Offset the buffer address to the start
6539 				 * of the data.
6540 				 */
6541 				valoffs += sizeof(uintptr_t);
6542 
6543 				/*
6544 				 * Reset to the memory address rather than
6545 				 * the memref array, then let the BYREF
6546 				 * code below do the work to store the
6547 				 * memory data in the buffer.
6548 				 */
6549 				val = memref[0];
6550 				break;
6551 			}
6552 
6553 			case DTRACEACT_PRINTT: {
6554 				/* The DIF returns a 'typeref'. */
6555 				uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6556 				char c = '\0' + 1;
6557 				size_t s;
6558 
6559 				/*
6560 				 * Get the type string length and round it
6561 				 * up so that the data that follows is
6562 				 * aligned for easy access.
6563 				 */
6564 				size_t typs = strlen((char *) typeref[2]) + 1;
6565 				typs = roundup(typs,  sizeof(uintptr_t));
6566 
6567 				/*
6568 				 *Get the size from the typeref using the
6569 				 * number of elements and the type size.
6570 				 */
6571 				size = typeref[1] * typeref[3];
6572 
6573 				/*
6574 				 * Check if the size exceeds the allocated
6575 				 * buffer size.
6576 				 */
6577 				if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6578 					/* Flag a drop! */
6579 					*flags |= CPU_DTRACE_DROP;
6580 
6581 				}
6582 
6583 				/* Store the size in the buffer first. */
6584 				DTRACE_STORE(uintptr_t, tomax,
6585 				    valoffs, size);
6586 				valoffs += sizeof(uintptr_t);
6587 
6588 				/* Store the type size in the buffer. */
6589 				DTRACE_STORE(uintptr_t, tomax,
6590 				    valoffs, typeref[3]);
6591 				valoffs += sizeof(uintptr_t);
6592 
6593 				val = typeref[2];
6594 
6595 				for (s = 0; s < typs; s++) {
6596 					if (c != '\0')
6597 						c = dtrace_load8(val++);
6598 
6599 					DTRACE_STORE(uint8_t, tomax,
6600 					    valoffs++, c);
6601 				}
6602 
6603 				/*
6604 				 * Reset to the memory address rather than
6605 				 * the typeref array, then let the BYREF
6606 				 * code below do the work to store the
6607 				 * memory data in the buffer.
6608 				 */
6609 				val = typeref[0];
6610 				break;
6611 			}
6612 
6613 			case DTRACEACT_CHILL:
6614 				if (dtrace_priv_kernel_destructive(state))
6615 					dtrace_action_chill(&mstate, val);
6616 				continue;
6617 
6618 			case DTRACEACT_RAISE:
6619 				if (dtrace_priv_proc_destructive(state))
6620 					dtrace_action_raise(val);
6621 				continue;
6622 
6623 			case DTRACEACT_COMMIT:
6624 				ASSERT(!committed);
6625 
6626 				/*
6627 				 * We need to commit our buffer state.
6628 				 */
6629 				if (ecb->dte_size)
6630 					buf->dtb_offset = offs + ecb->dte_size;
6631 				buf = &state->dts_buffer[cpuid];
6632 				dtrace_speculation_commit(state, cpuid, val);
6633 				committed = 1;
6634 				continue;
6635 
6636 			case DTRACEACT_DISCARD:
6637 				dtrace_speculation_discard(state, cpuid, val);
6638 				continue;
6639 
6640 			case DTRACEACT_DIFEXPR:
6641 			case DTRACEACT_LIBACT:
6642 			case DTRACEACT_PRINTF:
6643 			case DTRACEACT_PRINTA:
6644 			case DTRACEACT_SYSTEM:
6645 			case DTRACEACT_FREOPEN:
6646 			case DTRACEACT_TRACEMEM:
6647 				break;
6648 
6649 			case DTRACEACT_TRACEMEM_DYNSIZE:
6650 				tracememsize = val;
6651 				break;
6652 
6653 			case DTRACEACT_SYM:
6654 			case DTRACEACT_MOD:
6655 				if (!dtrace_priv_kernel(state))
6656 					continue;
6657 				break;
6658 
6659 			case DTRACEACT_USYM:
6660 			case DTRACEACT_UMOD:
6661 			case DTRACEACT_UADDR: {
6662 #if defined(sun)
6663 				struct pid *pid = curthread->t_procp->p_pidp;
6664 #endif
6665 
6666 				if (!dtrace_priv_proc(state))
6667 					continue;
6668 
6669 				DTRACE_STORE(uint64_t, tomax,
6670 #if defined(sun)
6671 				    valoffs, (uint64_t)pid->pid_id);
6672 #else
6673 				    valoffs, (uint64_t) curproc->p_pid);
6674 #endif
6675 				DTRACE_STORE(uint64_t, tomax,
6676 				    valoffs + sizeof (uint64_t), val);
6677 
6678 				continue;
6679 			}
6680 
6681 			case DTRACEACT_EXIT: {
6682 				/*
6683 				 * For the exit action, we are going to attempt
6684 				 * to atomically set our activity to be
6685 				 * draining.  If this fails (either because
6686 				 * another CPU has beat us to the exit action,
6687 				 * or because our current activity is something
6688 				 * other than ACTIVE or WARMUP), we will
6689 				 * continue.  This assures that the exit action
6690 				 * can be successfully recorded at most once
6691 				 * when we're in the ACTIVE state.  If we're
6692 				 * encountering the exit() action while in
6693 				 * COOLDOWN, however, we want to honor the new
6694 				 * status code.  (We know that we're the only
6695 				 * thread in COOLDOWN, so there is no race.)
6696 				 */
6697 				void *activity = &state->dts_activity;
6698 				dtrace_activity_t current = state->dts_activity;
6699 
6700 				if (current == DTRACE_ACTIVITY_COOLDOWN)
6701 					break;
6702 
6703 				if (current != DTRACE_ACTIVITY_WARMUP)
6704 					current = DTRACE_ACTIVITY_ACTIVE;
6705 
6706 				if (dtrace_cas32(activity, current,
6707 				    DTRACE_ACTIVITY_DRAINING) != current) {
6708 					*flags |= CPU_DTRACE_DROP;
6709 					continue;
6710 				}
6711 
6712 				break;
6713 			}
6714 
6715 			default:
6716 				ASSERT(0);
6717 			}
6718 
6719 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6720 				uintptr_t end = valoffs + size;
6721 
6722 				if (tracememsize != 0 &&
6723 				    valoffs + tracememsize < end) {
6724 					end = valoffs + tracememsize;
6725 					tracememsize = 0;
6726 				}
6727 
6728 				if (!dtrace_vcanload((void *)(uintptr_t)val,
6729 				    &dp->dtdo_rtype, &mstate, vstate))
6730 					continue;
6731 
6732 				/*
6733 				 * If this is a string, we're going to only
6734 				 * load until we find the zero byte -- after
6735 				 * which we'll store zero bytes.
6736 				 */
6737 				if (dp->dtdo_rtype.dtdt_kind ==
6738 				    DIF_TYPE_STRING) {
6739 					char c = '\0' + 1;
6740 					int intuple = act->dta_intuple;
6741 					size_t s;
6742 
6743 					for (s = 0; s < size; s++) {
6744 						if (c != '\0')
6745 							c = dtrace_load8(val++);
6746 
6747 						DTRACE_STORE(uint8_t, tomax,
6748 						    valoffs++, c);
6749 
6750 						if (c == '\0' && intuple)
6751 							break;
6752 					}
6753 
6754 					continue;
6755 				}
6756 
6757 				while (valoffs < end) {
6758 					DTRACE_STORE(uint8_t, tomax, valoffs++,
6759 					    dtrace_load8(val++));
6760 				}
6761 
6762 				continue;
6763 			}
6764 
6765 			switch (size) {
6766 			case 0:
6767 				break;
6768 
6769 			case sizeof (uint8_t):
6770 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
6771 				break;
6772 			case sizeof (uint16_t):
6773 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
6774 				break;
6775 			case sizeof (uint32_t):
6776 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
6777 				break;
6778 			case sizeof (uint64_t):
6779 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
6780 				break;
6781 			default:
6782 				/*
6783 				 * Any other size should have been returned by
6784 				 * reference, not by value.
6785 				 */
6786 				ASSERT(0);
6787 				break;
6788 			}
6789 		}
6790 
6791 		if (*flags & CPU_DTRACE_DROP)
6792 			continue;
6793 
6794 		if (*flags & CPU_DTRACE_FAULT) {
6795 			int ndx;
6796 			dtrace_action_t *err;
6797 
6798 			buf->dtb_errors++;
6799 
6800 			if (probe->dtpr_id == dtrace_probeid_error) {
6801 				/*
6802 				 * There's nothing we can do -- we had an
6803 				 * error on the error probe.  We bump an
6804 				 * error counter to at least indicate that
6805 				 * this condition happened.
6806 				 */
6807 				dtrace_error(&state->dts_dblerrors);
6808 				continue;
6809 			}
6810 
6811 			if (vtime) {
6812 				/*
6813 				 * Before recursing on dtrace_probe(), we
6814 				 * need to explicitly clear out our start
6815 				 * time to prevent it from being accumulated
6816 				 * into t_dtrace_vtime.
6817 				 */
6818 				curthread->t_dtrace_start = 0;
6819 			}
6820 
6821 			/*
6822 			 * Iterate over the actions to figure out which action
6823 			 * we were processing when we experienced the error.
6824 			 * Note that act points _past_ the faulting action; if
6825 			 * act is ecb->dte_action, the fault was in the
6826 			 * predicate, if it's ecb->dte_action->dta_next it's
6827 			 * in action #1, and so on.
6828 			 */
6829 			for (err = ecb->dte_action, ndx = 0;
6830 			    err != act; err = err->dta_next, ndx++)
6831 				continue;
6832 
6833 			dtrace_probe_error(state, ecb->dte_epid, ndx,
6834 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6835 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6836 			    cpu_core[cpuid].cpuc_dtrace_illval);
6837 
6838 			continue;
6839 		}
6840 
6841 		if (!committed)
6842 			buf->dtb_offset = offs + ecb->dte_size;
6843 	}
6844 
6845 	if (vtime)
6846 		curthread->t_dtrace_start = dtrace_gethrtime();
6847 
6848 	dtrace_interrupt_enable(cookie);
6849 }
6850 
6851 /*
6852  * DTrace Probe Hashing Functions
6853  *
6854  * The functions in this section (and indeed, the functions in remaining
6855  * sections) are not _called_ from probe context.  (Any exceptions to this are
6856  * marked with a "Note:".)  Rather, they are called from elsewhere in the
6857  * DTrace framework to look-up probes in, add probes to and remove probes from
6858  * the DTrace probe hashes.  (Each probe is hashed by each element of the
6859  * probe tuple -- allowing for fast lookups, regardless of what was
6860  * specified.)
6861  */
6862 static uint_t
6863 dtrace_hash_str(const char *p)
6864 {
6865 	unsigned int g;
6866 	uint_t hval = 0;
6867 
6868 	while (*p) {
6869 		hval = (hval << 4) + *p++;
6870 		if ((g = (hval & 0xf0000000)) != 0)
6871 			hval ^= g >> 24;
6872 		hval &= ~g;
6873 	}
6874 	return (hval);
6875 }
6876 
6877 static dtrace_hash_t *
6878 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6879 {
6880 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6881 
6882 	hash->dth_stroffs = stroffs;
6883 	hash->dth_nextoffs = nextoffs;
6884 	hash->dth_prevoffs = prevoffs;
6885 
6886 	hash->dth_size = 1;
6887 	hash->dth_mask = hash->dth_size - 1;
6888 
6889 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6890 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6891 
6892 	return (hash);
6893 }
6894 
6895 static void
6896 dtrace_hash_destroy(dtrace_hash_t *hash)
6897 {
6898 #ifdef DEBUG
6899 	int i;
6900 
6901 	for (i = 0; i < hash->dth_size; i++)
6902 		ASSERT(hash->dth_tab[i] == NULL);
6903 #endif
6904 
6905 	kmem_free(hash->dth_tab,
6906 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6907 	kmem_free(hash, sizeof (dtrace_hash_t));
6908 }
6909 
6910 static void
6911 dtrace_hash_resize(dtrace_hash_t *hash)
6912 {
6913 	int size = hash->dth_size, i, ndx;
6914 	int new_size = hash->dth_size << 1;
6915 	int new_mask = new_size - 1;
6916 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6917 
6918 	ASSERT((new_size & new_mask) == 0);
6919 
6920 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6921 
6922 	for (i = 0; i < size; i++) {
6923 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6924 			dtrace_probe_t *probe = bucket->dthb_chain;
6925 
6926 			ASSERT(probe != NULL);
6927 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6928 
6929 			next = bucket->dthb_next;
6930 			bucket->dthb_next = new_tab[ndx];
6931 			new_tab[ndx] = bucket;
6932 		}
6933 	}
6934 
6935 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6936 	hash->dth_tab = new_tab;
6937 	hash->dth_size = new_size;
6938 	hash->dth_mask = new_mask;
6939 }
6940 
6941 static void
6942 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6943 {
6944 	int hashval = DTRACE_HASHSTR(hash, new);
6945 	int ndx = hashval & hash->dth_mask;
6946 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6947 	dtrace_probe_t **nextp, **prevp;
6948 
6949 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6950 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6951 			goto add;
6952 	}
6953 
6954 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6955 		dtrace_hash_resize(hash);
6956 		dtrace_hash_add(hash, new);
6957 		return;
6958 	}
6959 
6960 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6961 	bucket->dthb_next = hash->dth_tab[ndx];
6962 	hash->dth_tab[ndx] = bucket;
6963 	hash->dth_nbuckets++;
6964 
6965 add:
6966 	nextp = DTRACE_HASHNEXT(hash, new);
6967 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6968 	*nextp = bucket->dthb_chain;
6969 
6970 	if (bucket->dthb_chain != NULL) {
6971 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6972 		ASSERT(*prevp == NULL);
6973 		*prevp = new;
6974 	}
6975 
6976 	bucket->dthb_chain = new;
6977 	bucket->dthb_len++;
6978 }
6979 
6980 static dtrace_probe_t *
6981 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6982 {
6983 	int hashval = DTRACE_HASHSTR(hash, template);
6984 	int ndx = hashval & hash->dth_mask;
6985 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6986 
6987 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6988 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6989 			return (bucket->dthb_chain);
6990 	}
6991 
6992 	return (NULL);
6993 }
6994 
6995 static int
6996 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6997 {
6998 	int hashval = DTRACE_HASHSTR(hash, template);
6999 	int ndx = hashval & hash->dth_mask;
7000 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7001 
7002 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7003 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7004 			return (bucket->dthb_len);
7005 	}
7006 
7007 	return (0);
7008 }
7009 
7010 static void
7011 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7012 {
7013 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7014 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7015 
7016 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7017 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7018 
7019 	/*
7020 	 * Find the bucket that we're removing this probe from.
7021 	 */
7022 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7023 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7024 			break;
7025 	}
7026 
7027 	ASSERT(bucket != NULL);
7028 
7029 	if (*prevp == NULL) {
7030 		if (*nextp == NULL) {
7031 			/*
7032 			 * The removed probe was the only probe on this
7033 			 * bucket; we need to remove the bucket.
7034 			 */
7035 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7036 
7037 			ASSERT(bucket->dthb_chain == probe);
7038 			ASSERT(b != NULL);
7039 
7040 			if (b == bucket) {
7041 				hash->dth_tab[ndx] = bucket->dthb_next;
7042 			} else {
7043 				while (b->dthb_next != bucket)
7044 					b = b->dthb_next;
7045 				b->dthb_next = bucket->dthb_next;
7046 			}
7047 
7048 			ASSERT(hash->dth_nbuckets > 0);
7049 			hash->dth_nbuckets--;
7050 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7051 			return;
7052 		}
7053 
7054 		bucket->dthb_chain = *nextp;
7055 	} else {
7056 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7057 	}
7058 
7059 	if (*nextp != NULL)
7060 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7061 }
7062 
7063 /*
7064  * DTrace Utility Functions
7065  *
7066  * These are random utility functions that are _not_ called from probe context.
7067  */
7068 static int
7069 dtrace_badattr(const dtrace_attribute_t *a)
7070 {
7071 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7072 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7073 	    a->dtat_class > DTRACE_CLASS_MAX);
7074 }
7075 
7076 /*
7077  * Return a duplicate copy of a string.  If the specified string is NULL,
7078  * this function returns a zero-length string.
7079  */
7080 static char *
7081 dtrace_strdup(const char *str)
7082 {
7083 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7084 
7085 	if (str != NULL)
7086 		(void) strcpy(new, str);
7087 
7088 	return (new);
7089 }
7090 
7091 #define	DTRACE_ISALPHA(c)	\
7092 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7093 
7094 static int
7095 dtrace_badname(const char *s)
7096 {
7097 	char c;
7098 
7099 	if (s == NULL || (c = *s++) == '\0')
7100 		return (0);
7101 
7102 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7103 		return (1);
7104 
7105 	while ((c = *s++) != '\0') {
7106 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7107 		    c != '-' && c != '_' && c != '.' && c != '`')
7108 			return (1);
7109 	}
7110 
7111 	return (0);
7112 }
7113 
7114 static void
7115 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7116 {
7117 	uint32_t priv;
7118 
7119 #if defined(sun)
7120 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7121 		/*
7122 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7123 		 */
7124 		priv = DTRACE_PRIV_ALL;
7125 	} else {
7126 		*uidp = crgetuid(cr);
7127 		*zoneidp = crgetzoneid(cr);
7128 
7129 		priv = 0;
7130 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7131 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7132 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7133 			priv |= DTRACE_PRIV_USER;
7134 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7135 			priv |= DTRACE_PRIV_PROC;
7136 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7137 			priv |= DTRACE_PRIV_OWNER;
7138 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7139 			priv |= DTRACE_PRIV_ZONEOWNER;
7140 	}
7141 #else
7142 	priv = DTRACE_PRIV_ALL;
7143 #endif
7144 
7145 	*privp = priv;
7146 }
7147 
7148 #ifdef DTRACE_ERRDEBUG
7149 static void
7150 dtrace_errdebug(const char *str)
7151 {
7152 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7153 	int occupied = 0;
7154 
7155 	mutex_enter(&dtrace_errlock);
7156 	dtrace_errlast = str;
7157 	dtrace_errthread = curthread;
7158 
7159 	while (occupied++ < DTRACE_ERRHASHSZ) {
7160 		if (dtrace_errhash[hval].dter_msg == str) {
7161 			dtrace_errhash[hval].dter_count++;
7162 			goto out;
7163 		}
7164 
7165 		if (dtrace_errhash[hval].dter_msg != NULL) {
7166 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7167 			continue;
7168 		}
7169 
7170 		dtrace_errhash[hval].dter_msg = str;
7171 		dtrace_errhash[hval].dter_count = 1;
7172 		goto out;
7173 	}
7174 
7175 	panic("dtrace: undersized error hash");
7176 out:
7177 	mutex_exit(&dtrace_errlock);
7178 }
7179 #endif
7180 
7181 /*
7182  * DTrace Matching Functions
7183  *
7184  * These functions are used to match groups of probes, given some elements of
7185  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7186  */
7187 static int
7188 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7189     zoneid_t zoneid)
7190 {
7191 	if (priv != DTRACE_PRIV_ALL) {
7192 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7193 		uint32_t match = priv & ppriv;
7194 
7195 		/*
7196 		 * No PRIV_DTRACE_* privileges...
7197 		 */
7198 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7199 		    DTRACE_PRIV_KERNEL)) == 0)
7200 			return (0);
7201 
7202 		/*
7203 		 * No matching bits, but there were bits to match...
7204 		 */
7205 		if (match == 0 && ppriv != 0)
7206 			return (0);
7207 
7208 		/*
7209 		 * Need to have permissions to the process, but don't...
7210 		 */
7211 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7212 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7213 			return (0);
7214 		}
7215 
7216 		/*
7217 		 * Need to be in the same zone unless we possess the
7218 		 * privilege to examine all zones.
7219 		 */
7220 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7221 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7222 			return (0);
7223 		}
7224 	}
7225 
7226 	return (1);
7227 }
7228 
7229 /*
7230  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7231  * consists of input pattern strings and an ops-vector to evaluate them.
7232  * This function returns >0 for match, 0 for no match, and <0 for error.
7233  */
7234 static int
7235 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7236     uint32_t priv, uid_t uid, zoneid_t zoneid)
7237 {
7238 	dtrace_provider_t *pvp = prp->dtpr_provider;
7239 	int rv;
7240 
7241 	if (pvp->dtpv_defunct)
7242 		return (0);
7243 
7244 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7245 		return (rv);
7246 
7247 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7248 		return (rv);
7249 
7250 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7251 		return (rv);
7252 
7253 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7254 		return (rv);
7255 
7256 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7257 		return (0);
7258 
7259 	return (rv);
7260 }
7261 
7262 /*
7263  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7264  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7265  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7266  * In addition, all of the recursion cases except for '*' matching have been
7267  * unwound.  For '*', we still implement recursive evaluation, but a depth
7268  * counter is maintained and matching is aborted if we recurse too deep.
7269  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7270  */
7271 static int
7272 dtrace_match_glob(const char *s, const char *p, int depth)
7273 {
7274 	const char *olds;
7275 	char s1, c;
7276 	int gs;
7277 
7278 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7279 		return (-1);
7280 
7281 	if (s == NULL)
7282 		s = ""; /* treat NULL as empty string */
7283 
7284 top:
7285 	olds = s;
7286 	s1 = *s++;
7287 
7288 	if (p == NULL)
7289 		return (0);
7290 
7291 	if ((c = *p++) == '\0')
7292 		return (s1 == '\0');
7293 
7294 	switch (c) {
7295 	case '[': {
7296 		int ok = 0, notflag = 0;
7297 		char lc = '\0';
7298 
7299 		if (s1 == '\0')
7300 			return (0);
7301 
7302 		if (*p == '!') {
7303 			notflag = 1;
7304 			p++;
7305 		}
7306 
7307 		if ((c = *p++) == '\0')
7308 			return (0);
7309 
7310 		do {
7311 			if (c == '-' && lc != '\0' && *p != ']') {
7312 				if ((c = *p++) == '\0')
7313 					return (0);
7314 				if (c == '\\' && (c = *p++) == '\0')
7315 					return (0);
7316 
7317 				if (notflag) {
7318 					if (s1 < lc || s1 > c)
7319 						ok++;
7320 					else
7321 						return (0);
7322 				} else if (lc <= s1 && s1 <= c)
7323 					ok++;
7324 
7325 			} else if (c == '\\' && (c = *p++) == '\0')
7326 				return (0);
7327 
7328 			lc = c; /* save left-hand 'c' for next iteration */
7329 
7330 			if (notflag) {
7331 				if (s1 != c)
7332 					ok++;
7333 				else
7334 					return (0);
7335 			} else if (s1 == c)
7336 				ok++;
7337 
7338 			if ((c = *p++) == '\0')
7339 				return (0);
7340 
7341 		} while (c != ']');
7342 
7343 		if (ok)
7344 			goto top;
7345 
7346 		return (0);
7347 	}
7348 
7349 	case '\\':
7350 		if ((c = *p++) == '\0')
7351 			return (0);
7352 		/*FALLTHRU*/
7353 
7354 	default:
7355 		if (c != s1)
7356 			return (0);
7357 		/*FALLTHRU*/
7358 
7359 	case '?':
7360 		if (s1 != '\0')
7361 			goto top;
7362 		return (0);
7363 
7364 	case '*':
7365 		while (*p == '*')
7366 			p++; /* consecutive *'s are identical to a single one */
7367 
7368 		if (*p == '\0')
7369 			return (1);
7370 
7371 		for (s = olds; *s != '\0'; s++) {
7372 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7373 				return (gs);
7374 		}
7375 
7376 		return (0);
7377 	}
7378 }
7379 
7380 /*ARGSUSED*/
7381 static int
7382 dtrace_match_string(const char *s, const char *p, int depth)
7383 {
7384 	return (s != NULL && strcmp(s, p) == 0);
7385 }
7386 
7387 /*ARGSUSED*/
7388 static int
7389 dtrace_match_nul(const char *s, const char *p, int depth)
7390 {
7391 	return (1); /* always match the empty pattern */
7392 }
7393 
7394 /*ARGSUSED*/
7395 static int
7396 dtrace_match_nonzero(const char *s, const char *p, int depth)
7397 {
7398 	return (s != NULL && s[0] != '\0');
7399 }
7400 
7401 static int
7402 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7403     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7404 {
7405 	dtrace_probe_t template, *probe;
7406 	dtrace_hash_t *hash = NULL;
7407 	int len, best = INT_MAX, nmatched = 0;
7408 	dtrace_id_t i;
7409 
7410 	ASSERT(MUTEX_HELD(&dtrace_lock));
7411 
7412 	/*
7413 	 * If the probe ID is specified in the key, just lookup by ID and
7414 	 * invoke the match callback once if a matching probe is found.
7415 	 */
7416 	if (pkp->dtpk_id != DTRACE_IDNONE) {
7417 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7418 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7419 			(void) (*matched)(probe, arg);
7420 			nmatched++;
7421 		}
7422 		return (nmatched);
7423 	}
7424 
7425 	template.dtpr_mod = (char *)pkp->dtpk_mod;
7426 	template.dtpr_func = (char *)pkp->dtpk_func;
7427 	template.dtpr_name = (char *)pkp->dtpk_name;
7428 
7429 	/*
7430 	 * We want to find the most distinct of the module name, function
7431 	 * name, and name.  So for each one that is not a glob pattern or
7432 	 * empty string, we perform a lookup in the corresponding hash and
7433 	 * use the hash table with the fewest collisions to do our search.
7434 	 */
7435 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
7436 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7437 		best = len;
7438 		hash = dtrace_bymod;
7439 	}
7440 
7441 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
7442 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7443 		best = len;
7444 		hash = dtrace_byfunc;
7445 	}
7446 
7447 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
7448 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7449 		best = len;
7450 		hash = dtrace_byname;
7451 	}
7452 
7453 	/*
7454 	 * If we did not select a hash table, iterate over every probe and
7455 	 * invoke our callback for each one that matches our input probe key.
7456 	 */
7457 	if (hash == NULL) {
7458 		for (i = 0; i < dtrace_nprobes; i++) {
7459 			if ((probe = dtrace_probes[i]) == NULL ||
7460 			    dtrace_match_probe(probe, pkp, priv, uid,
7461 			    zoneid) <= 0)
7462 				continue;
7463 
7464 			nmatched++;
7465 
7466 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7467 				break;
7468 		}
7469 
7470 		return (nmatched);
7471 	}
7472 
7473 	/*
7474 	 * If we selected a hash table, iterate over each probe of the same key
7475 	 * name and invoke the callback for every probe that matches the other
7476 	 * attributes of our input probe key.
7477 	 */
7478 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7479 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
7480 
7481 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7482 			continue;
7483 
7484 		nmatched++;
7485 
7486 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7487 			break;
7488 	}
7489 
7490 	return (nmatched);
7491 }
7492 
7493 /*
7494  * Return the function pointer dtrace_probecmp() should use to compare the
7495  * specified pattern with a string.  For NULL or empty patterns, we select
7496  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7497  * For non-empty non-glob strings, we use dtrace_match_string().
7498  */
7499 static dtrace_probekey_f *
7500 dtrace_probekey_func(const char *p)
7501 {
7502 	char c;
7503 
7504 	if (p == NULL || *p == '\0')
7505 		return (&dtrace_match_nul);
7506 
7507 	while ((c = *p++) != '\0') {
7508 		if (c == '[' || c == '?' || c == '*' || c == '\\')
7509 			return (&dtrace_match_glob);
7510 	}
7511 
7512 	return (&dtrace_match_string);
7513 }
7514 
7515 /*
7516  * Build a probe comparison key for use with dtrace_match_probe() from the
7517  * given probe description.  By convention, a null key only matches anchored
7518  * probes: if each field is the empty string, reset dtpk_fmatch to
7519  * dtrace_match_nonzero().
7520  */
7521 static void
7522 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7523 {
7524 	pkp->dtpk_prov = pdp->dtpd_provider;
7525 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7526 
7527 	pkp->dtpk_mod = pdp->dtpd_mod;
7528 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7529 
7530 	pkp->dtpk_func = pdp->dtpd_func;
7531 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7532 
7533 	pkp->dtpk_name = pdp->dtpd_name;
7534 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7535 
7536 	pkp->dtpk_id = pdp->dtpd_id;
7537 
7538 	if (pkp->dtpk_id == DTRACE_IDNONE &&
7539 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7540 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7541 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7542 	    pkp->dtpk_nmatch == &dtrace_match_nul)
7543 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7544 }
7545 
7546 /*
7547  * DTrace Provider-to-Framework API Functions
7548  *
7549  * These functions implement much of the Provider-to-Framework API, as
7550  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7551  * the functions in the API for probe management (found below), and
7552  * dtrace_probe() itself (found above).
7553  */
7554 
7555 /*
7556  * Register the calling provider with the DTrace framework.  This should
7557  * generally be called by DTrace providers in their attach(9E) entry point.
7558  */
7559 int
7560 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7561     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7562 {
7563 	dtrace_provider_t *provider;
7564 
7565 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7566 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7567 		    "arguments", name ? name : "<NULL>");
7568 		return (EINVAL);
7569 	}
7570 
7571 	if (name[0] == '\0' || dtrace_badname(name)) {
7572 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7573 		    "provider name", name);
7574 		return (EINVAL);
7575 	}
7576 
7577 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7578 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7579 	    pops->dtps_destroy == NULL ||
7580 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7581 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7582 		    "provider ops", name);
7583 		return (EINVAL);
7584 	}
7585 
7586 	if (dtrace_badattr(&pap->dtpa_provider) ||
7587 	    dtrace_badattr(&pap->dtpa_mod) ||
7588 	    dtrace_badattr(&pap->dtpa_func) ||
7589 	    dtrace_badattr(&pap->dtpa_name) ||
7590 	    dtrace_badattr(&pap->dtpa_args)) {
7591 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7592 		    "provider attributes", name);
7593 		return (EINVAL);
7594 	}
7595 
7596 	if (priv & ~DTRACE_PRIV_ALL) {
7597 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7598 		    "privilege attributes", name);
7599 		return (EINVAL);
7600 	}
7601 
7602 	if ((priv & DTRACE_PRIV_KERNEL) &&
7603 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7604 	    pops->dtps_usermode == NULL) {
7605 		cmn_err(CE_WARN, "failed to register provider '%s': need "
7606 		    "dtps_usermode() op for given privilege attributes", name);
7607 		return (EINVAL);
7608 	}
7609 
7610 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7611 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7612 	(void) strcpy(provider->dtpv_name, name);
7613 
7614 	provider->dtpv_attr = *pap;
7615 	provider->dtpv_priv.dtpp_flags = priv;
7616 	if (cr != NULL) {
7617 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7618 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7619 	}
7620 	provider->dtpv_pops = *pops;
7621 
7622 	if (pops->dtps_provide == NULL) {
7623 		ASSERT(pops->dtps_provide_module != NULL);
7624 		provider->dtpv_pops.dtps_provide =
7625 		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7626 	}
7627 
7628 	if (pops->dtps_provide_module == NULL) {
7629 		ASSERT(pops->dtps_provide != NULL);
7630 		provider->dtpv_pops.dtps_provide_module =
7631 		    (void (*)(void *, modctl_t *))dtrace_nullop;
7632 	}
7633 
7634 	if (pops->dtps_suspend == NULL) {
7635 		ASSERT(pops->dtps_resume == NULL);
7636 		provider->dtpv_pops.dtps_suspend =
7637 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7638 		provider->dtpv_pops.dtps_resume =
7639 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7640 	}
7641 
7642 	provider->dtpv_arg = arg;
7643 	*idp = (dtrace_provider_id_t)provider;
7644 
7645 	if (pops == &dtrace_provider_ops) {
7646 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7647 		ASSERT(MUTEX_HELD(&dtrace_lock));
7648 		ASSERT(dtrace_anon.dta_enabling == NULL);
7649 
7650 		/*
7651 		 * We make sure that the DTrace provider is at the head of
7652 		 * the provider chain.
7653 		 */
7654 		provider->dtpv_next = dtrace_provider;
7655 		dtrace_provider = provider;
7656 		return (0);
7657 	}
7658 
7659 	mutex_enter(&dtrace_provider_lock);
7660 	mutex_enter(&dtrace_lock);
7661 
7662 	/*
7663 	 * If there is at least one provider registered, we'll add this
7664 	 * provider after the first provider.
7665 	 */
7666 	if (dtrace_provider != NULL) {
7667 		provider->dtpv_next = dtrace_provider->dtpv_next;
7668 		dtrace_provider->dtpv_next = provider;
7669 	} else {
7670 		dtrace_provider = provider;
7671 	}
7672 
7673 	if (dtrace_retained != NULL) {
7674 		dtrace_enabling_provide(provider);
7675 
7676 		/*
7677 		 * Now we need to call dtrace_enabling_matchall() -- which
7678 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
7679 		 * to drop all of our locks before calling into it...
7680 		 */
7681 		mutex_exit(&dtrace_lock);
7682 		mutex_exit(&dtrace_provider_lock);
7683 		dtrace_enabling_matchall();
7684 
7685 		return (0);
7686 	}
7687 
7688 	mutex_exit(&dtrace_lock);
7689 	mutex_exit(&dtrace_provider_lock);
7690 
7691 	return (0);
7692 }
7693 
7694 /*
7695  * Unregister the specified provider from the DTrace framework.  This should
7696  * generally be called by DTrace providers in their detach(9E) entry point.
7697  */
7698 int
7699 dtrace_unregister(dtrace_provider_id_t id)
7700 {
7701 	dtrace_provider_t *old = (dtrace_provider_t *)id;
7702 	dtrace_provider_t *prev = NULL;
7703 	int i, self = 0, noreap = 0;
7704 	dtrace_probe_t *probe, *first = NULL;
7705 
7706 	if (old->dtpv_pops.dtps_enable ==
7707 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7708 		/*
7709 		 * If DTrace itself is the provider, we're called with locks
7710 		 * already held.
7711 		 */
7712 		ASSERT(old == dtrace_provider);
7713 #if defined(sun)
7714 		ASSERT(dtrace_devi != NULL);
7715 #endif
7716 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7717 		ASSERT(MUTEX_HELD(&dtrace_lock));
7718 		self = 1;
7719 
7720 		if (dtrace_provider->dtpv_next != NULL) {
7721 			/*
7722 			 * There's another provider here; return failure.
7723 			 */
7724 			return (EBUSY);
7725 		}
7726 	} else {
7727 		mutex_enter(&dtrace_provider_lock);
7728 #if defined(sun)
7729 		mutex_enter(&mod_lock);
7730 #endif
7731 		mutex_enter(&dtrace_lock);
7732 	}
7733 
7734 	/*
7735 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7736 	 * probes, we refuse to let providers slither away, unless this
7737 	 * provider has already been explicitly invalidated.
7738 	 */
7739 	if (!old->dtpv_defunct &&
7740 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7741 	    dtrace_anon.dta_state->dts_necbs > 0))) {
7742 		if (!self) {
7743 			mutex_exit(&dtrace_lock);
7744 #if defined(sun)
7745 			mutex_exit(&mod_lock);
7746 #endif
7747 			mutex_exit(&dtrace_provider_lock);
7748 		}
7749 		return (EBUSY);
7750 	}
7751 
7752 	/*
7753 	 * Attempt to destroy the probes associated with this provider.
7754 	 */
7755 	for (i = 0; i < dtrace_nprobes; i++) {
7756 		if ((probe = dtrace_probes[i]) == NULL)
7757 			continue;
7758 
7759 		if (probe->dtpr_provider != old)
7760 			continue;
7761 
7762 		if (probe->dtpr_ecb == NULL)
7763 			continue;
7764 
7765 		/*
7766 		 * If we are trying to unregister a defunct provider, and the
7767 		 * provider was made defunct within the interval dictated by
7768 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7769 		 * attempt to reap our enablings.  To denote that the provider
7770 		 * should reattempt to unregister itself at some point in the
7771 		 * future, we will return a differentiable error code (EAGAIN
7772 		 * instead of EBUSY) in this case.
7773 		 */
7774 		if (dtrace_gethrtime() - old->dtpv_defunct >
7775 		    dtrace_unregister_defunct_reap)
7776 			noreap = 1;
7777 
7778 		if (!self) {
7779 			mutex_exit(&dtrace_lock);
7780 #if defined(sun)
7781 			mutex_exit(&mod_lock);
7782 #endif
7783 			mutex_exit(&dtrace_provider_lock);
7784 		}
7785 
7786 		if (noreap)
7787 			return (EBUSY);
7788 
7789 		(void) taskq_dispatch(dtrace_taskq,
7790 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7791 
7792 		return (EAGAIN);
7793 	}
7794 
7795 	/*
7796 	 * All of the probes for this provider are disabled; we can safely
7797 	 * remove all of them from their hash chains and from the probe array.
7798 	 */
7799 	for (i = 0; i < dtrace_nprobes; i++) {
7800 		if ((probe = dtrace_probes[i]) == NULL)
7801 			continue;
7802 
7803 		if (probe->dtpr_provider != old)
7804 			continue;
7805 
7806 		dtrace_probes[i] = NULL;
7807 
7808 		dtrace_hash_remove(dtrace_bymod, probe);
7809 		dtrace_hash_remove(dtrace_byfunc, probe);
7810 		dtrace_hash_remove(dtrace_byname, probe);
7811 
7812 		if (first == NULL) {
7813 			first = probe;
7814 			probe->dtpr_nextmod = NULL;
7815 		} else {
7816 			probe->dtpr_nextmod = first;
7817 			first = probe;
7818 		}
7819 	}
7820 
7821 	/*
7822 	 * The provider's probes have been removed from the hash chains and
7823 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
7824 	 * everyone has cleared out from any probe array processing.
7825 	 */
7826 	dtrace_sync();
7827 
7828 	for (probe = first; probe != NULL; probe = first) {
7829 		first = probe->dtpr_nextmod;
7830 
7831 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7832 		    probe->dtpr_arg);
7833 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7834 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7835 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7836 #if defined(sun)
7837 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7838 #else
7839 		free_unr(dtrace_arena, probe->dtpr_id);
7840 #endif
7841 		kmem_free(probe, sizeof (dtrace_probe_t));
7842 	}
7843 
7844 	if ((prev = dtrace_provider) == old) {
7845 #if defined(sun)
7846 		ASSERT(self || dtrace_devi == NULL);
7847 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7848 #endif
7849 		dtrace_provider = old->dtpv_next;
7850 	} else {
7851 		while (prev != NULL && prev->dtpv_next != old)
7852 			prev = prev->dtpv_next;
7853 
7854 		if (prev == NULL) {
7855 			panic("attempt to unregister non-existent "
7856 			    "dtrace provider %p\n", (void *)id);
7857 		}
7858 
7859 		prev->dtpv_next = old->dtpv_next;
7860 	}
7861 
7862 	if (!self) {
7863 		mutex_exit(&dtrace_lock);
7864 #if defined(sun)
7865 		mutex_exit(&mod_lock);
7866 #endif
7867 		mutex_exit(&dtrace_provider_lock);
7868 	}
7869 
7870 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7871 	kmem_free(old, sizeof (dtrace_provider_t));
7872 
7873 	return (0);
7874 }
7875 
7876 /*
7877  * Invalidate the specified provider.  All subsequent probe lookups for the
7878  * specified provider will fail, but its probes will not be removed.
7879  */
7880 void
7881 dtrace_invalidate(dtrace_provider_id_t id)
7882 {
7883 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7884 
7885 	ASSERT(pvp->dtpv_pops.dtps_enable !=
7886 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7887 
7888 	mutex_enter(&dtrace_provider_lock);
7889 	mutex_enter(&dtrace_lock);
7890 
7891 	pvp->dtpv_defunct = dtrace_gethrtime();
7892 
7893 	mutex_exit(&dtrace_lock);
7894 	mutex_exit(&dtrace_provider_lock);
7895 }
7896 
7897 /*
7898  * Indicate whether or not DTrace has attached.
7899  */
7900 int
7901 dtrace_attached(void)
7902 {
7903 	/*
7904 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7905 	 * attached.  (It's non-NULL because DTrace is always itself a
7906 	 * provider.)
7907 	 */
7908 	return (dtrace_provider != NULL);
7909 }
7910 
7911 /*
7912  * Remove all the unenabled probes for the given provider.  This function is
7913  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7914  * -- just as many of its associated probes as it can.
7915  */
7916 int
7917 dtrace_condense(dtrace_provider_id_t id)
7918 {
7919 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7920 	int i;
7921 	dtrace_probe_t *probe;
7922 
7923 	/*
7924 	 * Make sure this isn't the dtrace provider itself.
7925 	 */
7926 	ASSERT(prov->dtpv_pops.dtps_enable !=
7927 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7928 
7929 	mutex_enter(&dtrace_provider_lock);
7930 	mutex_enter(&dtrace_lock);
7931 
7932 	/*
7933 	 * Attempt to destroy the probes associated with this provider.
7934 	 */
7935 	for (i = 0; i < dtrace_nprobes; i++) {
7936 		if ((probe = dtrace_probes[i]) == NULL)
7937 			continue;
7938 
7939 		if (probe->dtpr_provider != prov)
7940 			continue;
7941 
7942 		if (probe->dtpr_ecb != NULL)
7943 			continue;
7944 
7945 		dtrace_probes[i] = NULL;
7946 
7947 		dtrace_hash_remove(dtrace_bymod, probe);
7948 		dtrace_hash_remove(dtrace_byfunc, probe);
7949 		dtrace_hash_remove(dtrace_byname, probe);
7950 
7951 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7952 		    probe->dtpr_arg);
7953 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7954 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7955 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7956 		kmem_free(probe, sizeof (dtrace_probe_t));
7957 #if defined(sun)
7958 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7959 #else
7960 		free_unr(dtrace_arena, i + 1);
7961 #endif
7962 	}
7963 
7964 	mutex_exit(&dtrace_lock);
7965 	mutex_exit(&dtrace_provider_lock);
7966 
7967 	return (0);
7968 }
7969 
7970 /*
7971  * DTrace Probe Management Functions
7972  *
7973  * The functions in this section perform the DTrace probe management,
7974  * including functions to create probes, look-up probes, and call into the
7975  * providers to request that probes be provided.  Some of these functions are
7976  * in the Provider-to-Framework API; these functions can be identified by the
7977  * fact that they are not declared "static".
7978  */
7979 
7980 /*
7981  * Create a probe with the specified module name, function name, and name.
7982  */
7983 dtrace_id_t
7984 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7985     const char *func, const char *name, int aframes, void *arg)
7986 {
7987 	dtrace_probe_t *probe, **probes;
7988 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7989 	dtrace_id_t id;
7990 
7991 	if (provider == dtrace_provider) {
7992 		ASSERT(MUTEX_HELD(&dtrace_lock));
7993 	} else {
7994 		mutex_enter(&dtrace_lock);
7995 	}
7996 
7997 #if defined(sun)
7998 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7999 	    VM_BESTFIT | VM_SLEEP);
8000 #else
8001 	id = alloc_unr(dtrace_arena);
8002 #endif
8003 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8004 
8005 	probe->dtpr_id = id;
8006 	probe->dtpr_gen = dtrace_probegen++;
8007 	probe->dtpr_mod = dtrace_strdup(mod);
8008 	probe->dtpr_func = dtrace_strdup(func);
8009 	probe->dtpr_name = dtrace_strdup(name);
8010 	probe->dtpr_arg = arg;
8011 	probe->dtpr_aframes = aframes;
8012 	probe->dtpr_provider = provider;
8013 
8014 	dtrace_hash_add(dtrace_bymod, probe);
8015 	dtrace_hash_add(dtrace_byfunc, probe);
8016 	dtrace_hash_add(dtrace_byname, probe);
8017 
8018 	if (id - 1 >= dtrace_nprobes) {
8019 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8020 		size_t nsize = osize << 1;
8021 
8022 		if (nsize == 0) {
8023 			ASSERT(osize == 0);
8024 			ASSERT(dtrace_probes == NULL);
8025 			nsize = sizeof (dtrace_probe_t *);
8026 		}
8027 
8028 		probes = kmem_zalloc(nsize, KM_SLEEP);
8029 
8030 		if (dtrace_probes == NULL) {
8031 			ASSERT(osize == 0);
8032 			dtrace_probes = probes;
8033 			dtrace_nprobes = 1;
8034 		} else {
8035 			dtrace_probe_t **oprobes = dtrace_probes;
8036 
8037 			bcopy(oprobes, probes, osize);
8038 			dtrace_membar_producer();
8039 			dtrace_probes = probes;
8040 
8041 			dtrace_sync();
8042 
8043 			/*
8044 			 * All CPUs are now seeing the new probes array; we can
8045 			 * safely free the old array.
8046 			 */
8047 			kmem_free(oprobes, osize);
8048 			dtrace_nprobes <<= 1;
8049 		}
8050 
8051 		ASSERT(id - 1 < dtrace_nprobes);
8052 	}
8053 
8054 	ASSERT(dtrace_probes[id - 1] == NULL);
8055 	dtrace_probes[id - 1] = probe;
8056 
8057 	if (provider != dtrace_provider)
8058 		mutex_exit(&dtrace_lock);
8059 
8060 	return (id);
8061 }
8062 
8063 static dtrace_probe_t *
8064 dtrace_probe_lookup_id(dtrace_id_t id)
8065 {
8066 	ASSERT(MUTEX_HELD(&dtrace_lock));
8067 
8068 	if (id == 0 || id > dtrace_nprobes)
8069 		return (NULL);
8070 
8071 	return (dtrace_probes[id - 1]);
8072 }
8073 
8074 static int
8075 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8076 {
8077 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8078 
8079 	return (DTRACE_MATCH_DONE);
8080 }
8081 
8082 /*
8083  * Look up a probe based on provider and one or more of module name, function
8084  * name and probe name.
8085  */
8086 dtrace_id_t
8087 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8088     char *func, char *name)
8089 {
8090 	dtrace_probekey_t pkey;
8091 	dtrace_id_t id;
8092 	int match;
8093 
8094 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8095 	pkey.dtpk_pmatch = &dtrace_match_string;
8096 	pkey.dtpk_mod = mod;
8097 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8098 	pkey.dtpk_func = func;
8099 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8100 	pkey.dtpk_name = name;
8101 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8102 	pkey.dtpk_id = DTRACE_IDNONE;
8103 
8104 	mutex_enter(&dtrace_lock);
8105 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8106 	    dtrace_probe_lookup_match, &id);
8107 	mutex_exit(&dtrace_lock);
8108 
8109 	ASSERT(match == 1 || match == 0);
8110 	return (match ? id : 0);
8111 }
8112 
8113 /*
8114  * Returns the probe argument associated with the specified probe.
8115  */
8116 void *
8117 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8118 {
8119 	dtrace_probe_t *probe;
8120 	void *rval = NULL;
8121 
8122 	mutex_enter(&dtrace_lock);
8123 
8124 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8125 	    probe->dtpr_provider == (dtrace_provider_t *)id)
8126 		rval = probe->dtpr_arg;
8127 
8128 	mutex_exit(&dtrace_lock);
8129 
8130 	return (rval);
8131 }
8132 
8133 /*
8134  * Copy a probe into a probe description.
8135  */
8136 static void
8137 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8138 {
8139 	bzero(pdp, sizeof (dtrace_probedesc_t));
8140 	pdp->dtpd_id = prp->dtpr_id;
8141 
8142 	(void) strncpy(pdp->dtpd_provider,
8143 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8144 
8145 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8146 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8147 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8148 }
8149 
8150 /*
8151  * Called to indicate that a probe -- or probes -- should be provided by a
8152  * specfied provider.  If the specified description is NULL, the provider will
8153  * be told to provide all of its probes.  (This is done whenever a new
8154  * consumer comes along, or whenever a retained enabling is to be matched.) If
8155  * the specified description is non-NULL, the provider is given the
8156  * opportunity to dynamically provide the specified probe, allowing providers
8157  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8158  * probes.)  If the provider is NULL, the operations will be applied to all
8159  * providers; if the provider is non-NULL the operations will only be applied
8160  * to the specified provider.  The dtrace_provider_lock must be held, and the
8161  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8162  * will need to grab the dtrace_lock when it reenters the framework through
8163  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8164  */
8165 static void
8166 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8167 {
8168 #if defined(sun)
8169 	modctl_t *ctl;
8170 #endif
8171 	int all = 0;
8172 
8173 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8174 
8175 	if (prv == NULL) {
8176 		all = 1;
8177 		prv = dtrace_provider;
8178 	}
8179 
8180 	do {
8181 		/*
8182 		 * First, call the blanket provide operation.
8183 		 */
8184 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8185 
8186 #if defined(sun)
8187 		/*
8188 		 * Now call the per-module provide operation.  We will grab
8189 		 * mod_lock to prevent the list from being modified.  Note
8190 		 * that this also prevents the mod_busy bits from changing.
8191 		 * (mod_busy can only be changed with mod_lock held.)
8192 		 */
8193 		mutex_enter(&mod_lock);
8194 
8195 		ctl = &modules;
8196 		do {
8197 			if (ctl->mod_busy || ctl->mod_mp == NULL)
8198 				continue;
8199 
8200 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8201 
8202 		} while ((ctl = ctl->mod_next) != &modules);
8203 
8204 		mutex_exit(&mod_lock);
8205 #endif
8206 	} while (all && (prv = prv->dtpv_next) != NULL);
8207 }
8208 
8209 #if defined(sun)
8210 /*
8211  * Iterate over each probe, and call the Framework-to-Provider API function
8212  * denoted by offs.
8213  */
8214 static void
8215 dtrace_probe_foreach(uintptr_t offs)
8216 {
8217 	dtrace_provider_t *prov;
8218 	void (*func)(void *, dtrace_id_t, void *);
8219 	dtrace_probe_t *probe;
8220 	dtrace_icookie_t cookie;
8221 	int i;
8222 
8223 	/*
8224 	 * We disable interrupts to walk through the probe array.  This is
8225 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8226 	 * won't see stale data.
8227 	 */
8228 	cookie = dtrace_interrupt_disable();
8229 
8230 	for (i = 0; i < dtrace_nprobes; i++) {
8231 		if ((probe = dtrace_probes[i]) == NULL)
8232 			continue;
8233 
8234 		if (probe->dtpr_ecb == NULL) {
8235 			/*
8236 			 * This probe isn't enabled -- don't call the function.
8237 			 */
8238 			continue;
8239 		}
8240 
8241 		prov = probe->dtpr_provider;
8242 		func = *((void(**)(void *, dtrace_id_t, void *))
8243 		    ((uintptr_t)&prov->dtpv_pops + offs));
8244 
8245 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8246 	}
8247 
8248 	dtrace_interrupt_enable(cookie);
8249 }
8250 #endif
8251 
8252 static int
8253 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8254 {
8255 	dtrace_probekey_t pkey;
8256 	uint32_t priv;
8257 	uid_t uid;
8258 	zoneid_t zoneid;
8259 
8260 	ASSERT(MUTEX_HELD(&dtrace_lock));
8261 	dtrace_ecb_create_cache = NULL;
8262 
8263 	if (desc == NULL) {
8264 		/*
8265 		 * If we're passed a NULL description, we're being asked to
8266 		 * create an ECB with a NULL probe.
8267 		 */
8268 		(void) dtrace_ecb_create_enable(NULL, enab);
8269 		return (0);
8270 	}
8271 
8272 	dtrace_probekey(desc, &pkey);
8273 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8274 	    &priv, &uid, &zoneid);
8275 
8276 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8277 	    enab));
8278 }
8279 
8280 /*
8281  * DTrace Helper Provider Functions
8282  */
8283 static void
8284 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8285 {
8286 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8287 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8288 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8289 }
8290 
8291 static void
8292 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8293     const dof_provider_t *dofprov, char *strtab)
8294 {
8295 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8296 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8297 	    dofprov->dofpv_provattr);
8298 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8299 	    dofprov->dofpv_modattr);
8300 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8301 	    dofprov->dofpv_funcattr);
8302 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8303 	    dofprov->dofpv_nameattr);
8304 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8305 	    dofprov->dofpv_argsattr);
8306 }
8307 
8308 static void
8309 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8310 {
8311 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8312 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8313 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8314 	dof_provider_t *provider;
8315 	dof_probe_t *probe;
8316 	uint32_t *off, *enoff;
8317 	uint8_t *arg;
8318 	char *strtab;
8319 	uint_t i, nprobes;
8320 	dtrace_helper_provdesc_t dhpv;
8321 	dtrace_helper_probedesc_t dhpb;
8322 	dtrace_meta_t *meta = dtrace_meta_pid;
8323 	dtrace_mops_t *mops = &meta->dtm_mops;
8324 	void *parg;
8325 
8326 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8327 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8328 	    provider->dofpv_strtab * dof->dofh_secsize);
8329 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8330 	    provider->dofpv_probes * dof->dofh_secsize);
8331 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8332 	    provider->dofpv_prargs * dof->dofh_secsize);
8333 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8334 	    provider->dofpv_proffs * dof->dofh_secsize);
8335 
8336 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8337 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8338 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8339 	enoff = NULL;
8340 
8341 	/*
8342 	 * See dtrace_helper_provider_validate().
8343 	 */
8344 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8345 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8346 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8347 		    provider->dofpv_prenoffs * dof->dofh_secsize);
8348 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8349 	}
8350 
8351 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8352 
8353 	/*
8354 	 * Create the provider.
8355 	 */
8356 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8357 
8358 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8359 		return;
8360 
8361 	meta->dtm_count++;
8362 
8363 	/*
8364 	 * Create the probes.
8365 	 */
8366 	for (i = 0; i < nprobes; i++) {
8367 		probe = (dof_probe_t *)(uintptr_t)(daddr +
8368 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8369 
8370 		dhpb.dthpb_mod = dhp->dofhp_mod;
8371 		dhpb.dthpb_func = strtab + probe->dofpr_func;
8372 		dhpb.dthpb_name = strtab + probe->dofpr_name;
8373 		dhpb.dthpb_base = probe->dofpr_addr;
8374 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
8375 		dhpb.dthpb_noffs = probe->dofpr_noffs;
8376 		if (enoff != NULL) {
8377 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8378 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8379 		} else {
8380 			dhpb.dthpb_enoffs = NULL;
8381 			dhpb.dthpb_nenoffs = 0;
8382 		}
8383 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
8384 		dhpb.dthpb_nargc = probe->dofpr_nargc;
8385 		dhpb.dthpb_xargc = probe->dofpr_xargc;
8386 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8387 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8388 
8389 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8390 	}
8391 }
8392 
8393 static void
8394 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8395 {
8396 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8397 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8398 	int i;
8399 
8400 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8401 
8402 	for (i = 0; i < dof->dofh_secnum; i++) {
8403 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8404 		    dof->dofh_secoff + i * dof->dofh_secsize);
8405 
8406 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8407 			continue;
8408 
8409 		dtrace_helper_provide_one(dhp, sec, pid);
8410 	}
8411 
8412 	/*
8413 	 * We may have just created probes, so we must now rematch against
8414 	 * any retained enablings.  Note that this call will acquire both
8415 	 * cpu_lock and dtrace_lock; the fact that we are holding
8416 	 * dtrace_meta_lock now is what defines the ordering with respect to
8417 	 * these three locks.
8418 	 */
8419 	dtrace_enabling_matchall();
8420 }
8421 
8422 static void
8423 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8424 {
8425 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8426 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8427 	dof_sec_t *str_sec;
8428 	dof_provider_t *provider;
8429 	char *strtab;
8430 	dtrace_helper_provdesc_t dhpv;
8431 	dtrace_meta_t *meta = dtrace_meta_pid;
8432 	dtrace_mops_t *mops = &meta->dtm_mops;
8433 
8434 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8435 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8436 	    provider->dofpv_strtab * dof->dofh_secsize);
8437 
8438 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8439 
8440 	/*
8441 	 * Create the provider.
8442 	 */
8443 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8444 
8445 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8446 
8447 	meta->dtm_count--;
8448 }
8449 
8450 static void
8451 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8452 {
8453 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8454 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8455 	int i;
8456 
8457 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8458 
8459 	for (i = 0; i < dof->dofh_secnum; i++) {
8460 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8461 		    dof->dofh_secoff + i * dof->dofh_secsize);
8462 
8463 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8464 			continue;
8465 
8466 		dtrace_helper_provider_remove_one(dhp, sec, pid);
8467 	}
8468 }
8469 
8470 /*
8471  * DTrace Meta Provider-to-Framework API Functions
8472  *
8473  * These functions implement the Meta Provider-to-Framework API, as described
8474  * in <sys/dtrace.h>.
8475  */
8476 int
8477 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8478     dtrace_meta_provider_id_t *idp)
8479 {
8480 	dtrace_meta_t *meta;
8481 	dtrace_helpers_t *help, *next;
8482 	int i;
8483 
8484 	*idp = DTRACE_METAPROVNONE;
8485 
8486 	/*
8487 	 * We strictly don't need the name, but we hold onto it for
8488 	 * debuggability. All hail error queues!
8489 	 */
8490 	if (name == NULL) {
8491 		cmn_err(CE_WARN, "failed to register meta-provider: "
8492 		    "invalid name");
8493 		return (EINVAL);
8494 	}
8495 
8496 	if (mops == NULL ||
8497 	    mops->dtms_create_probe == NULL ||
8498 	    mops->dtms_provide_pid == NULL ||
8499 	    mops->dtms_remove_pid == NULL) {
8500 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8501 		    "invalid ops", name);
8502 		return (EINVAL);
8503 	}
8504 
8505 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8506 	meta->dtm_mops = *mops;
8507 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8508 	(void) strcpy(meta->dtm_name, name);
8509 	meta->dtm_arg = arg;
8510 
8511 	mutex_enter(&dtrace_meta_lock);
8512 	mutex_enter(&dtrace_lock);
8513 
8514 	if (dtrace_meta_pid != NULL) {
8515 		mutex_exit(&dtrace_lock);
8516 		mutex_exit(&dtrace_meta_lock);
8517 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8518 		    "user-land meta-provider exists", name);
8519 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8520 		kmem_free(meta, sizeof (dtrace_meta_t));
8521 		return (EINVAL);
8522 	}
8523 
8524 	dtrace_meta_pid = meta;
8525 	*idp = (dtrace_meta_provider_id_t)meta;
8526 
8527 	/*
8528 	 * If there are providers and probes ready to go, pass them
8529 	 * off to the new meta provider now.
8530 	 */
8531 
8532 	help = dtrace_deferred_pid;
8533 	dtrace_deferred_pid = NULL;
8534 
8535 	mutex_exit(&dtrace_lock);
8536 
8537 	while (help != NULL) {
8538 		for (i = 0; i < help->dthps_nprovs; i++) {
8539 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8540 			    help->dthps_pid);
8541 		}
8542 
8543 		next = help->dthps_next;
8544 		help->dthps_next = NULL;
8545 		help->dthps_prev = NULL;
8546 		help->dthps_deferred = 0;
8547 		help = next;
8548 	}
8549 
8550 	mutex_exit(&dtrace_meta_lock);
8551 
8552 	return (0);
8553 }
8554 
8555 int
8556 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8557 {
8558 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8559 
8560 	mutex_enter(&dtrace_meta_lock);
8561 	mutex_enter(&dtrace_lock);
8562 
8563 	if (old == dtrace_meta_pid) {
8564 		pp = &dtrace_meta_pid;
8565 	} else {
8566 		panic("attempt to unregister non-existent "
8567 		    "dtrace meta-provider %p\n", (void *)old);
8568 	}
8569 
8570 	if (old->dtm_count != 0) {
8571 		mutex_exit(&dtrace_lock);
8572 		mutex_exit(&dtrace_meta_lock);
8573 		return (EBUSY);
8574 	}
8575 
8576 	*pp = NULL;
8577 
8578 	mutex_exit(&dtrace_lock);
8579 	mutex_exit(&dtrace_meta_lock);
8580 
8581 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8582 	kmem_free(old, sizeof (dtrace_meta_t));
8583 
8584 	return (0);
8585 }
8586 
8587 
8588 /*
8589  * DTrace DIF Object Functions
8590  */
8591 static int
8592 dtrace_difo_err(uint_t pc, const char *format, ...)
8593 {
8594 	if (dtrace_err_verbose) {
8595 		va_list alist;
8596 
8597 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
8598 		va_start(alist, format);
8599 		(void) vuprintf(format, alist);
8600 		va_end(alist);
8601 	}
8602 
8603 #ifdef DTRACE_ERRDEBUG
8604 	dtrace_errdebug(format);
8605 #endif
8606 	return (1);
8607 }
8608 
8609 /*
8610  * Validate a DTrace DIF object by checking the IR instructions.  The following
8611  * rules are currently enforced by dtrace_difo_validate():
8612  *
8613  * 1. Each instruction must have a valid opcode
8614  * 2. Each register, string, variable, or subroutine reference must be valid
8615  * 3. No instruction can modify register %r0 (must be zero)
8616  * 4. All instruction reserved bits must be set to zero
8617  * 5. The last instruction must be a "ret" instruction
8618  * 6. All branch targets must reference a valid instruction _after_ the branch
8619  */
8620 static int
8621 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8622     cred_t *cr)
8623 {
8624 	int err = 0, i;
8625 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8626 	int kcheckload;
8627 	uint_t pc;
8628 
8629 	kcheckload = cr == NULL ||
8630 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8631 
8632 	dp->dtdo_destructive = 0;
8633 
8634 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8635 		dif_instr_t instr = dp->dtdo_buf[pc];
8636 
8637 		uint_t r1 = DIF_INSTR_R1(instr);
8638 		uint_t r2 = DIF_INSTR_R2(instr);
8639 		uint_t rd = DIF_INSTR_RD(instr);
8640 		uint_t rs = DIF_INSTR_RS(instr);
8641 		uint_t label = DIF_INSTR_LABEL(instr);
8642 		uint_t v = DIF_INSTR_VAR(instr);
8643 		uint_t subr = DIF_INSTR_SUBR(instr);
8644 		uint_t type = DIF_INSTR_TYPE(instr);
8645 		uint_t op = DIF_INSTR_OP(instr);
8646 
8647 		switch (op) {
8648 		case DIF_OP_OR:
8649 		case DIF_OP_XOR:
8650 		case DIF_OP_AND:
8651 		case DIF_OP_SLL:
8652 		case DIF_OP_SRL:
8653 		case DIF_OP_SRA:
8654 		case DIF_OP_SUB:
8655 		case DIF_OP_ADD:
8656 		case DIF_OP_MUL:
8657 		case DIF_OP_SDIV:
8658 		case DIF_OP_UDIV:
8659 		case DIF_OP_SREM:
8660 		case DIF_OP_UREM:
8661 		case DIF_OP_COPYS:
8662 			if (r1 >= nregs)
8663 				err += efunc(pc, "invalid register %u\n", r1);
8664 			if (r2 >= nregs)
8665 				err += efunc(pc, "invalid register %u\n", r2);
8666 			if (rd >= nregs)
8667 				err += efunc(pc, "invalid register %u\n", rd);
8668 			if (rd == 0)
8669 				err += efunc(pc, "cannot write to %r0\n");
8670 			break;
8671 		case DIF_OP_NOT:
8672 		case DIF_OP_MOV:
8673 		case DIF_OP_ALLOCS:
8674 			if (r1 >= nregs)
8675 				err += efunc(pc, "invalid register %u\n", r1);
8676 			if (r2 != 0)
8677 				err += efunc(pc, "non-zero reserved bits\n");
8678 			if (rd >= nregs)
8679 				err += efunc(pc, "invalid register %u\n", rd);
8680 			if (rd == 0)
8681 				err += efunc(pc, "cannot write to %r0\n");
8682 			break;
8683 		case DIF_OP_LDSB:
8684 		case DIF_OP_LDSH:
8685 		case DIF_OP_LDSW:
8686 		case DIF_OP_LDUB:
8687 		case DIF_OP_LDUH:
8688 		case DIF_OP_LDUW:
8689 		case DIF_OP_LDX:
8690 			if (r1 >= nregs)
8691 				err += efunc(pc, "invalid register %u\n", r1);
8692 			if (r2 != 0)
8693 				err += efunc(pc, "non-zero reserved bits\n");
8694 			if (rd >= nregs)
8695 				err += efunc(pc, "invalid register %u\n", rd);
8696 			if (rd == 0)
8697 				err += efunc(pc, "cannot write to %r0\n");
8698 			if (kcheckload)
8699 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8700 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8701 			break;
8702 		case DIF_OP_RLDSB:
8703 		case DIF_OP_RLDSH:
8704 		case DIF_OP_RLDSW:
8705 		case DIF_OP_RLDUB:
8706 		case DIF_OP_RLDUH:
8707 		case DIF_OP_RLDUW:
8708 		case DIF_OP_RLDX:
8709 			if (r1 >= nregs)
8710 				err += efunc(pc, "invalid register %u\n", r1);
8711 			if (r2 != 0)
8712 				err += efunc(pc, "non-zero reserved bits\n");
8713 			if (rd >= nregs)
8714 				err += efunc(pc, "invalid register %u\n", rd);
8715 			if (rd == 0)
8716 				err += efunc(pc, "cannot write to %r0\n");
8717 			break;
8718 		case DIF_OP_ULDSB:
8719 		case DIF_OP_ULDSH:
8720 		case DIF_OP_ULDSW:
8721 		case DIF_OP_ULDUB:
8722 		case DIF_OP_ULDUH:
8723 		case DIF_OP_ULDUW:
8724 		case DIF_OP_ULDX:
8725 			if (r1 >= nregs)
8726 				err += efunc(pc, "invalid register %u\n", r1);
8727 			if (r2 != 0)
8728 				err += efunc(pc, "non-zero reserved bits\n");
8729 			if (rd >= nregs)
8730 				err += efunc(pc, "invalid register %u\n", rd);
8731 			if (rd == 0)
8732 				err += efunc(pc, "cannot write to %r0\n");
8733 			break;
8734 		case DIF_OP_STB:
8735 		case DIF_OP_STH:
8736 		case DIF_OP_STW:
8737 		case DIF_OP_STX:
8738 			if (r1 >= nregs)
8739 				err += efunc(pc, "invalid register %u\n", r1);
8740 			if (r2 != 0)
8741 				err += efunc(pc, "non-zero reserved bits\n");
8742 			if (rd >= nregs)
8743 				err += efunc(pc, "invalid register %u\n", rd);
8744 			if (rd == 0)
8745 				err += efunc(pc, "cannot write to 0 address\n");
8746 			break;
8747 		case DIF_OP_CMP:
8748 		case DIF_OP_SCMP:
8749 			if (r1 >= nregs)
8750 				err += efunc(pc, "invalid register %u\n", r1);
8751 			if (r2 >= nregs)
8752 				err += efunc(pc, "invalid register %u\n", r2);
8753 			if (rd != 0)
8754 				err += efunc(pc, "non-zero reserved bits\n");
8755 			break;
8756 		case DIF_OP_TST:
8757 			if (r1 >= nregs)
8758 				err += efunc(pc, "invalid register %u\n", r1);
8759 			if (r2 != 0 || rd != 0)
8760 				err += efunc(pc, "non-zero reserved bits\n");
8761 			break;
8762 		case DIF_OP_BA:
8763 		case DIF_OP_BE:
8764 		case DIF_OP_BNE:
8765 		case DIF_OP_BG:
8766 		case DIF_OP_BGU:
8767 		case DIF_OP_BGE:
8768 		case DIF_OP_BGEU:
8769 		case DIF_OP_BL:
8770 		case DIF_OP_BLU:
8771 		case DIF_OP_BLE:
8772 		case DIF_OP_BLEU:
8773 			if (label >= dp->dtdo_len) {
8774 				err += efunc(pc, "invalid branch target %u\n",
8775 				    label);
8776 			}
8777 			if (label <= pc) {
8778 				err += efunc(pc, "backward branch to %u\n",
8779 				    label);
8780 			}
8781 			break;
8782 		case DIF_OP_RET:
8783 			if (r1 != 0 || r2 != 0)
8784 				err += efunc(pc, "non-zero reserved bits\n");
8785 			if (rd >= nregs)
8786 				err += efunc(pc, "invalid register %u\n", rd);
8787 			break;
8788 		case DIF_OP_NOP:
8789 		case DIF_OP_POPTS:
8790 		case DIF_OP_FLUSHTS:
8791 			if (r1 != 0 || r2 != 0 || rd != 0)
8792 				err += efunc(pc, "non-zero reserved bits\n");
8793 			break;
8794 		case DIF_OP_SETX:
8795 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8796 				err += efunc(pc, "invalid integer ref %u\n",
8797 				    DIF_INSTR_INTEGER(instr));
8798 			}
8799 			if (rd >= nregs)
8800 				err += efunc(pc, "invalid register %u\n", rd);
8801 			if (rd == 0)
8802 				err += efunc(pc, "cannot write to %r0\n");
8803 			break;
8804 		case DIF_OP_SETS:
8805 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8806 				err += efunc(pc, "invalid string ref %u\n",
8807 				    DIF_INSTR_STRING(instr));
8808 			}
8809 			if (rd >= nregs)
8810 				err += efunc(pc, "invalid register %u\n", rd);
8811 			if (rd == 0)
8812 				err += efunc(pc, "cannot write to %r0\n");
8813 			break;
8814 		case DIF_OP_LDGA:
8815 		case DIF_OP_LDTA:
8816 			if (r1 > DIF_VAR_ARRAY_MAX)
8817 				err += efunc(pc, "invalid array %u\n", r1);
8818 			if (r2 >= nregs)
8819 				err += efunc(pc, "invalid register %u\n", r2);
8820 			if (rd >= nregs)
8821 				err += efunc(pc, "invalid register %u\n", rd);
8822 			if (rd == 0)
8823 				err += efunc(pc, "cannot write to %r0\n");
8824 			break;
8825 		case DIF_OP_LDGS:
8826 		case DIF_OP_LDTS:
8827 		case DIF_OP_LDLS:
8828 		case DIF_OP_LDGAA:
8829 		case DIF_OP_LDTAA:
8830 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8831 				err += efunc(pc, "invalid variable %u\n", v);
8832 			if (rd >= nregs)
8833 				err += efunc(pc, "invalid register %u\n", rd);
8834 			if (rd == 0)
8835 				err += efunc(pc, "cannot write to %r0\n");
8836 			break;
8837 		case DIF_OP_STGS:
8838 		case DIF_OP_STTS:
8839 		case DIF_OP_STLS:
8840 		case DIF_OP_STGAA:
8841 		case DIF_OP_STTAA:
8842 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8843 				err += efunc(pc, "invalid variable %u\n", v);
8844 			if (rs >= nregs)
8845 				err += efunc(pc, "invalid register %u\n", rd);
8846 			break;
8847 		case DIF_OP_CALL:
8848 			if (subr > DIF_SUBR_MAX)
8849 				err += efunc(pc, "invalid subr %u\n", subr);
8850 			if (rd >= nregs)
8851 				err += efunc(pc, "invalid register %u\n", rd);
8852 			if (rd == 0)
8853 				err += efunc(pc, "cannot write to %r0\n");
8854 
8855 			if (subr == DIF_SUBR_COPYOUT ||
8856 			    subr == DIF_SUBR_COPYOUTSTR) {
8857 				dp->dtdo_destructive = 1;
8858 			}
8859 			break;
8860 		case DIF_OP_PUSHTR:
8861 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8862 				err += efunc(pc, "invalid ref type %u\n", type);
8863 			if (r2 >= nregs)
8864 				err += efunc(pc, "invalid register %u\n", r2);
8865 			if (rs >= nregs)
8866 				err += efunc(pc, "invalid register %u\n", rs);
8867 			break;
8868 		case DIF_OP_PUSHTV:
8869 			if (type != DIF_TYPE_CTF)
8870 				err += efunc(pc, "invalid val type %u\n", type);
8871 			if (r2 >= nregs)
8872 				err += efunc(pc, "invalid register %u\n", r2);
8873 			if (rs >= nregs)
8874 				err += efunc(pc, "invalid register %u\n", rs);
8875 			break;
8876 		default:
8877 			err += efunc(pc, "invalid opcode %u\n",
8878 			    DIF_INSTR_OP(instr));
8879 		}
8880 	}
8881 
8882 	if (dp->dtdo_len != 0 &&
8883 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8884 		err += efunc(dp->dtdo_len - 1,
8885 		    "expected 'ret' as last DIF instruction\n");
8886 	}
8887 
8888 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8889 		/*
8890 		 * If we're not returning by reference, the size must be either
8891 		 * 0 or the size of one of the base types.
8892 		 */
8893 		switch (dp->dtdo_rtype.dtdt_size) {
8894 		case 0:
8895 		case sizeof (uint8_t):
8896 		case sizeof (uint16_t):
8897 		case sizeof (uint32_t):
8898 		case sizeof (uint64_t):
8899 			break;
8900 
8901 		default:
8902 			err += efunc(dp->dtdo_len - 1, "bad return size");
8903 		}
8904 	}
8905 
8906 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8907 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8908 		dtrace_diftype_t *vt, *et;
8909 		uint_t id, ndx;
8910 
8911 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8912 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8913 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8914 			err += efunc(i, "unrecognized variable scope %d\n",
8915 			    v->dtdv_scope);
8916 			break;
8917 		}
8918 
8919 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8920 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8921 			err += efunc(i, "unrecognized variable type %d\n",
8922 			    v->dtdv_kind);
8923 			break;
8924 		}
8925 
8926 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8927 			err += efunc(i, "%d exceeds variable id limit\n", id);
8928 			break;
8929 		}
8930 
8931 		if (id < DIF_VAR_OTHER_UBASE)
8932 			continue;
8933 
8934 		/*
8935 		 * For user-defined variables, we need to check that this
8936 		 * definition is identical to any previous definition that we
8937 		 * encountered.
8938 		 */
8939 		ndx = id - DIF_VAR_OTHER_UBASE;
8940 
8941 		switch (v->dtdv_scope) {
8942 		case DIFV_SCOPE_GLOBAL:
8943 			if (ndx < vstate->dtvs_nglobals) {
8944 				dtrace_statvar_t *svar;
8945 
8946 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8947 					existing = &svar->dtsv_var;
8948 			}
8949 
8950 			break;
8951 
8952 		case DIFV_SCOPE_THREAD:
8953 			if (ndx < vstate->dtvs_ntlocals)
8954 				existing = &vstate->dtvs_tlocals[ndx];
8955 			break;
8956 
8957 		case DIFV_SCOPE_LOCAL:
8958 			if (ndx < vstate->dtvs_nlocals) {
8959 				dtrace_statvar_t *svar;
8960 
8961 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8962 					existing = &svar->dtsv_var;
8963 			}
8964 
8965 			break;
8966 		}
8967 
8968 		vt = &v->dtdv_type;
8969 
8970 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8971 			if (vt->dtdt_size == 0) {
8972 				err += efunc(i, "zero-sized variable\n");
8973 				break;
8974 			}
8975 
8976 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8977 			    vt->dtdt_size > dtrace_global_maxsize) {
8978 				err += efunc(i, "oversized by-ref global\n");
8979 				break;
8980 			}
8981 		}
8982 
8983 		if (existing == NULL || existing->dtdv_id == 0)
8984 			continue;
8985 
8986 		ASSERT(existing->dtdv_id == v->dtdv_id);
8987 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8988 
8989 		if (existing->dtdv_kind != v->dtdv_kind)
8990 			err += efunc(i, "%d changed variable kind\n", id);
8991 
8992 		et = &existing->dtdv_type;
8993 
8994 		if (vt->dtdt_flags != et->dtdt_flags) {
8995 			err += efunc(i, "%d changed variable type flags\n", id);
8996 			break;
8997 		}
8998 
8999 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9000 			err += efunc(i, "%d changed variable type size\n", id);
9001 			break;
9002 		}
9003 	}
9004 
9005 	return (err);
9006 }
9007 
9008 /*
9009  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9010  * are much more constrained than normal DIFOs.  Specifically, they may
9011  * not:
9012  *
9013  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9014  *    miscellaneous string routines
9015  * 2. Access DTrace variables other than the args[] array, and the
9016  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9017  * 3. Have thread-local variables.
9018  * 4. Have dynamic variables.
9019  */
9020 static int
9021 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9022 {
9023 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9024 	int err = 0;
9025 	uint_t pc;
9026 
9027 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9028 		dif_instr_t instr = dp->dtdo_buf[pc];
9029 
9030 		uint_t v = DIF_INSTR_VAR(instr);
9031 		uint_t subr = DIF_INSTR_SUBR(instr);
9032 		uint_t op = DIF_INSTR_OP(instr);
9033 
9034 		switch (op) {
9035 		case DIF_OP_OR:
9036 		case DIF_OP_XOR:
9037 		case DIF_OP_AND:
9038 		case DIF_OP_SLL:
9039 		case DIF_OP_SRL:
9040 		case DIF_OP_SRA:
9041 		case DIF_OP_SUB:
9042 		case DIF_OP_ADD:
9043 		case DIF_OP_MUL:
9044 		case DIF_OP_SDIV:
9045 		case DIF_OP_UDIV:
9046 		case DIF_OP_SREM:
9047 		case DIF_OP_UREM:
9048 		case DIF_OP_COPYS:
9049 		case DIF_OP_NOT:
9050 		case DIF_OP_MOV:
9051 		case DIF_OP_RLDSB:
9052 		case DIF_OP_RLDSH:
9053 		case DIF_OP_RLDSW:
9054 		case DIF_OP_RLDUB:
9055 		case DIF_OP_RLDUH:
9056 		case DIF_OP_RLDUW:
9057 		case DIF_OP_RLDX:
9058 		case DIF_OP_ULDSB:
9059 		case DIF_OP_ULDSH:
9060 		case DIF_OP_ULDSW:
9061 		case DIF_OP_ULDUB:
9062 		case DIF_OP_ULDUH:
9063 		case DIF_OP_ULDUW:
9064 		case DIF_OP_ULDX:
9065 		case DIF_OP_STB:
9066 		case DIF_OP_STH:
9067 		case DIF_OP_STW:
9068 		case DIF_OP_STX:
9069 		case DIF_OP_ALLOCS:
9070 		case DIF_OP_CMP:
9071 		case DIF_OP_SCMP:
9072 		case DIF_OP_TST:
9073 		case DIF_OP_BA:
9074 		case DIF_OP_BE:
9075 		case DIF_OP_BNE:
9076 		case DIF_OP_BG:
9077 		case DIF_OP_BGU:
9078 		case DIF_OP_BGE:
9079 		case DIF_OP_BGEU:
9080 		case DIF_OP_BL:
9081 		case DIF_OP_BLU:
9082 		case DIF_OP_BLE:
9083 		case DIF_OP_BLEU:
9084 		case DIF_OP_RET:
9085 		case DIF_OP_NOP:
9086 		case DIF_OP_POPTS:
9087 		case DIF_OP_FLUSHTS:
9088 		case DIF_OP_SETX:
9089 		case DIF_OP_SETS:
9090 		case DIF_OP_LDGA:
9091 		case DIF_OP_LDLS:
9092 		case DIF_OP_STGS:
9093 		case DIF_OP_STLS:
9094 		case DIF_OP_PUSHTR:
9095 		case DIF_OP_PUSHTV:
9096 			break;
9097 
9098 		case DIF_OP_LDGS:
9099 			if (v >= DIF_VAR_OTHER_UBASE)
9100 				break;
9101 
9102 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9103 				break;
9104 
9105 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9106 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9107 			    v == DIF_VAR_EXECARGS ||
9108 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9109 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9110 				break;
9111 
9112 			err += efunc(pc, "illegal variable %u\n", v);
9113 			break;
9114 
9115 		case DIF_OP_LDTA:
9116 		case DIF_OP_LDTS:
9117 		case DIF_OP_LDGAA:
9118 		case DIF_OP_LDTAA:
9119 			err += efunc(pc, "illegal dynamic variable load\n");
9120 			break;
9121 
9122 		case DIF_OP_STTS:
9123 		case DIF_OP_STGAA:
9124 		case DIF_OP_STTAA:
9125 			err += efunc(pc, "illegal dynamic variable store\n");
9126 			break;
9127 
9128 		case DIF_OP_CALL:
9129 			if (subr == DIF_SUBR_ALLOCA ||
9130 			    subr == DIF_SUBR_BCOPY ||
9131 			    subr == DIF_SUBR_COPYIN ||
9132 			    subr == DIF_SUBR_COPYINTO ||
9133 			    subr == DIF_SUBR_COPYINSTR ||
9134 			    subr == DIF_SUBR_INDEX ||
9135 			    subr == DIF_SUBR_INET_NTOA ||
9136 			    subr == DIF_SUBR_INET_NTOA6 ||
9137 			    subr == DIF_SUBR_INET_NTOP ||
9138 			    subr == DIF_SUBR_LLTOSTR ||
9139 			    subr == DIF_SUBR_RINDEX ||
9140 			    subr == DIF_SUBR_STRCHR ||
9141 			    subr == DIF_SUBR_STRJOIN ||
9142 			    subr == DIF_SUBR_STRRCHR ||
9143 			    subr == DIF_SUBR_STRSTR ||
9144 			    subr == DIF_SUBR_HTONS ||
9145 			    subr == DIF_SUBR_HTONL ||
9146 			    subr == DIF_SUBR_HTONLL ||
9147 			    subr == DIF_SUBR_NTOHS ||
9148 			    subr == DIF_SUBR_NTOHL ||
9149 			    subr == DIF_SUBR_NTOHLL ||
9150 			    subr == DIF_SUBR_MEMREF ||
9151 #if !defined(sun)
9152 			    subr == DIF_SUBR_MEMSTR ||
9153 #endif
9154 			    subr == DIF_SUBR_TYPEREF)
9155 				break;
9156 
9157 			err += efunc(pc, "invalid subr %u\n", subr);
9158 			break;
9159 
9160 		default:
9161 			err += efunc(pc, "invalid opcode %u\n",
9162 			    DIF_INSTR_OP(instr));
9163 		}
9164 	}
9165 
9166 	return (err);
9167 }
9168 
9169 /*
9170  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9171  * basis; 0 if not.
9172  */
9173 static int
9174 dtrace_difo_cacheable(dtrace_difo_t *dp)
9175 {
9176 	int i;
9177 
9178 	if (dp == NULL)
9179 		return (0);
9180 
9181 	for (i = 0; i < dp->dtdo_varlen; i++) {
9182 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9183 
9184 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9185 			continue;
9186 
9187 		switch (v->dtdv_id) {
9188 		case DIF_VAR_CURTHREAD:
9189 		case DIF_VAR_PID:
9190 		case DIF_VAR_TID:
9191 		case DIF_VAR_EXECARGS:
9192 		case DIF_VAR_EXECNAME:
9193 		case DIF_VAR_ZONENAME:
9194 			break;
9195 
9196 		default:
9197 			return (0);
9198 		}
9199 	}
9200 
9201 	/*
9202 	 * This DIF object may be cacheable.  Now we need to look for any
9203 	 * array loading instructions, any memory loading instructions, or
9204 	 * any stores to thread-local variables.
9205 	 */
9206 	for (i = 0; i < dp->dtdo_len; i++) {
9207 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9208 
9209 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9210 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9211 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9212 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9213 			return (0);
9214 	}
9215 
9216 	return (1);
9217 }
9218 
9219 static void
9220 dtrace_difo_hold(dtrace_difo_t *dp)
9221 {
9222 	int i;
9223 
9224 	ASSERT(MUTEX_HELD(&dtrace_lock));
9225 
9226 	dp->dtdo_refcnt++;
9227 	ASSERT(dp->dtdo_refcnt != 0);
9228 
9229 	/*
9230 	 * We need to check this DIF object for references to the variable
9231 	 * DIF_VAR_VTIMESTAMP.
9232 	 */
9233 	for (i = 0; i < dp->dtdo_varlen; i++) {
9234 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9235 
9236 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9237 			continue;
9238 
9239 		if (dtrace_vtime_references++ == 0)
9240 			dtrace_vtime_enable();
9241 	}
9242 }
9243 
9244 /*
9245  * This routine calculates the dynamic variable chunksize for a given DIF
9246  * object.  The calculation is not fool-proof, and can probably be tricked by
9247  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9248  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9249  * if a dynamic variable size exceeds the chunksize.
9250  */
9251 static void
9252 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9253 {
9254 	uint64_t sval = 0;
9255 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9256 	const dif_instr_t *text = dp->dtdo_buf;
9257 	uint_t pc, srd = 0;
9258 	uint_t ttop = 0;
9259 	size_t size, ksize;
9260 	uint_t id, i;
9261 
9262 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9263 		dif_instr_t instr = text[pc];
9264 		uint_t op = DIF_INSTR_OP(instr);
9265 		uint_t rd = DIF_INSTR_RD(instr);
9266 		uint_t r1 = DIF_INSTR_R1(instr);
9267 		uint_t nkeys = 0;
9268 		uchar_t scope = 0;
9269 
9270 		dtrace_key_t *key = tupregs;
9271 
9272 		switch (op) {
9273 		case DIF_OP_SETX:
9274 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9275 			srd = rd;
9276 			continue;
9277 
9278 		case DIF_OP_STTS:
9279 			key = &tupregs[DIF_DTR_NREGS];
9280 			key[0].dttk_size = 0;
9281 			key[1].dttk_size = 0;
9282 			nkeys = 2;
9283 			scope = DIFV_SCOPE_THREAD;
9284 			break;
9285 
9286 		case DIF_OP_STGAA:
9287 		case DIF_OP_STTAA:
9288 			nkeys = ttop;
9289 
9290 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9291 				key[nkeys++].dttk_size = 0;
9292 
9293 			key[nkeys++].dttk_size = 0;
9294 
9295 			if (op == DIF_OP_STTAA) {
9296 				scope = DIFV_SCOPE_THREAD;
9297 			} else {
9298 				scope = DIFV_SCOPE_GLOBAL;
9299 			}
9300 
9301 			break;
9302 
9303 		case DIF_OP_PUSHTR:
9304 			if (ttop == DIF_DTR_NREGS)
9305 				return;
9306 
9307 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9308 				/*
9309 				 * If the register for the size of the "pushtr"
9310 				 * is %r0 (or the value is 0) and the type is
9311 				 * a string, we'll use the system-wide default
9312 				 * string size.
9313 				 */
9314 				tupregs[ttop++].dttk_size =
9315 				    dtrace_strsize_default;
9316 			} else {
9317 				if (srd == 0)
9318 					return;
9319 
9320 				tupregs[ttop++].dttk_size = sval;
9321 			}
9322 
9323 			break;
9324 
9325 		case DIF_OP_PUSHTV:
9326 			if (ttop == DIF_DTR_NREGS)
9327 				return;
9328 
9329 			tupregs[ttop++].dttk_size = 0;
9330 			break;
9331 
9332 		case DIF_OP_FLUSHTS:
9333 			ttop = 0;
9334 			break;
9335 
9336 		case DIF_OP_POPTS:
9337 			if (ttop != 0)
9338 				ttop--;
9339 			break;
9340 		}
9341 
9342 		sval = 0;
9343 		srd = 0;
9344 
9345 		if (nkeys == 0)
9346 			continue;
9347 
9348 		/*
9349 		 * We have a dynamic variable allocation; calculate its size.
9350 		 */
9351 		for (ksize = 0, i = 0; i < nkeys; i++)
9352 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9353 
9354 		size = sizeof (dtrace_dynvar_t);
9355 		size += sizeof (dtrace_key_t) * (nkeys - 1);
9356 		size += ksize;
9357 
9358 		/*
9359 		 * Now we need to determine the size of the stored data.
9360 		 */
9361 		id = DIF_INSTR_VAR(instr);
9362 
9363 		for (i = 0; i < dp->dtdo_varlen; i++) {
9364 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
9365 
9366 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
9367 				size += v->dtdv_type.dtdt_size;
9368 				break;
9369 			}
9370 		}
9371 
9372 		if (i == dp->dtdo_varlen)
9373 			return;
9374 
9375 		/*
9376 		 * We have the size.  If this is larger than the chunk size
9377 		 * for our dynamic variable state, reset the chunk size.
9378 		 */
9379 		size = P2ROUNDUP(size, sizeof (uint64_t));
9380 
9381 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
9382 			vstate->dtvs_dynvars.dtds_chunksize = size;
9383 	}
9384 }
9385 
9386 static void
9387 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9388 {
9389 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
9390 	uint_t id;
9391 
9392 	ASSERT(MUTEX_HELD(&dtrace_lock));
9393 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9394 
9395 	for (i = 0; i < dp->dtdo_varlen; i++) {
9396 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9397 		dtrace_statvar_t *svar, ***svarp = NULL;
9398 		size_t dsize = 0;
9399 		uint8_t scope = v->dtdv_scope;
9400 		int *np = NULL;
9401 
9402 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9403 			continue;
9404 
9405 		id -= DIF_VAR_OTHER_UBASE;
9406 
9407 		switch (scope) {
9408 		case DIFV_SCOPE_THREAD:
9409 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9410 				dtrace_difv_t *tlocals;
9411 
9412 				if ((ntlocals = (otlocals << 1)) == 0)
9413 					ntlocals = 1;
9414 
9415 				osz = otlocals * sizeof (dtrace_difv_t);
9416 				nsz = ntlocals * sizeof (dtrace_difv_t);
9417 
9418 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
9419 
9420 				if (osz != 0) {
9421 					bcopy(vstate->dtvs_tlocals,
9422 					    tlocals, osz);
9423 					kmem_free(vstate->dtvs_tlocals, osz);
9424 				}
9425 
9426 				vstate->dtvs_tlocals = tlocals;
9427 				vstate->dtvs_ntlocals = ntlocals;
9428 			}
9429 
9430 			vstate->dtvs_tlocals[id] = *v;
9431 			continue;
9432 
9433 		case DIFV_SCOPE_LOCAL:
9434 			np = &vstate->dtvs_nlocals;
9435 			svarp = &vstate->dtvs_locals;
9436 
9437 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9438 				dsize = NCPU * (v->dtdv_type.dtdt_size +
9439 				    sizeof (uint64_t));
9440 			else
9441 				dsize = NCPU * sizeof (uint64_t);
9442 
9443 			break;
9444 
9445 		case DIFV_SCOPE_GLOBAL:
9446 			np = &vstate->dtvs_nglobals;
9447 			svarp = &vstate->dtvs_globals;
9448 
9449 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9450 				dsize = v->dtdv_type.dtdt_size +
9451 				    sizeof (uint64_t);
9452 
9453 			break;
9454 
9455 		default:
9456 			ASSERT(0);
9457 		}
9458 
9459 		while (id >= (oldsvars = *np)) {
9460 			dtrace_statvar_t **statics;
9461 			int newsvars, oldsize, newsize;
9462 
9463 			if ((newsvars = (oldsvars << 1)) == 0)
9464 				newsvars = 1;
9465 
9466 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9467 			newsize = newsvars * sizeof (dtrace_statvar_t *);
9468 
9469 			statics = kmem_zalloc(newsize, KM_SLEEP);
9470 
9471 			if (oldsize != 0) {
9472 				bcopy(*svarp, statics, oldsize);
9473 				kmem_free(*svarp, oldsize);
9474 			}
9475 
9476 			*svarp = statics;
9477 			*np = newsvars;
9478 		}
9479 
9480 		if ((svar = (*svarp)[id]) == NULL) {
9481 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9482 			svar->dtsv_var = *v;
9483 
9484 			if ((svar->dtsv_size = dsize) != 0) {
9485 				svar->dtsv_data = (uint64_t)(uintptr_t)
9486 				    kmem_zalloc(dsize, KM_SLEEP);
9487 			}
9488 
9489 			(*svarp)[id] = svar;
9490 		}
9491 
9492 		svar->dtsv_refcnt++;
9493 	}
9494 
9495 	dtrace_difo_chunksize(dp, vstate);
9496 	dtrace_difo_hold(dp);
9497 }
9498 
9499 static dtrace_difo_t *
9500 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9501 {
9502 	dtrace_difo_t *new;
9503 	size_t sz;
9504 
9505 	ASSERT(dp->dtdo_buf != NULL);
9506 	ASSERT(dp->dtdo_refcnt != 0);
9507 
9508 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9509 
9510 	ASSERT(dp->dtdo_buf != NULL);
9511 	sz = dp->dtdo_len * sizeof (dif_instr_t);
9512 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9513 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9514 	new->dtdo_len = dp->dtdo_len;
9515 
9516 	if (dp->dtdo_strtab != NULL) {
9517 		ASSERT(dp->dtdo_strlen != 0);
9518 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9519 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9520 		new->dtdo_strlen = dp->dtdo_strlen;
9521 	}
9522 
9523 	if (dp->dtdo_inttab != NULL) {
9524 		ASSERT(dp->dtdo_intlen != 0);
9525 		sz = dp->dtdo_intlen * sizeof (uint64_t);
9526 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9527 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9528 		new->dtdo_intlen = dp->dtdo_intlen;
9529 	}
9530 
9531 	if (dp->dtdo_vartab != NULL) {
9532 		ASSERT(dp->dtdo_varlen != 0);
9533 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9534 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9535 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9536 		new->dtdo_varlen = dp->dtdo_varlen;
9537 	}
9538 
9539 	dtrace_difo_init(new, vstate);
9540 	return (new);
9541 }
9542 
9543 static void
9544 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9545 {
9546 	int i;
9547 
9548 	ASSERT(dp->dtdo_refcnt == 0);
9549 
9550 	for (i = 0; i < dp->dtdo_varlen; i++) {
9551 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9552 		dtrace_statvar_t *svar, **svarp = NULL;
9553 		uint_t id;
9554 		uint8_t scope = v->dtdv_scope;
9555 		int *np = NULL;
9556 
9557 		switch (scope) {
9558 		case DIFV_SCOPE_THREAD:
9559 			continue;
9560 
9561 		case DIFV_SCOPE_LOCAL:
9562 			np = &vstate->dtvs_nlocals;
9563 			svarp = vstate->dtvs_locals;
9564 			break;
9565 
9566 		case DIFV_SCOPE_GLOBAL:
9567 			np = &vstate->dtvs_nglobals;
9568 			svarp = vstate->dtvs_globals;
9569 			break;
9570 
9571 		default:
9572 			ASSERT(0);
9573 		}
9574 
9575 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9576 			continue;
9577 
9578 		id -= DIF_VAR_OTHER_UBASE;
9579 		ASSERT(id < *np);
9580 
9581 		svar = svarp[id];
9582 		ASSERT(svar != NULL);
9583 		ASSERT(svar->dtsv_refcnt > 0);
9584 
9585 		if (--svar->dtsv_refcnt > 0)
9586 			continue;
9587 
9588 		if (svar->dtsv_size != 0) {
9589 			ASSERT(svar->dtsv_data != 0);
9590 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
9591 			    svar->dtsv_size);
9592 		}
9593 
9594 		kmem_free(svar, sizeof (dtrace_statvar_t));
9595 		svarp[id] = NULL;
9596 	}
9597 
9598 	if (dp->dtdo_buf != NULL)
9599 		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9600 	if (dp->dtdo_inttab != NULL)
9601 		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9602 	if (dp->dtdo_strtab != NULL)
9603 		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9604 	if (dp->dtdo_vartab != NULL)
9605 		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9606 
9607 	kmem_free(dp, sizeof (dtrace_difo_t));
9608 }
9609 
9610 static void
9611 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9612 {
9613 	int i;
9614 
9615 	ASSERT(MUTEX_HELD(&dtrace_lock));
9616 	ASSERT(dp->dtdo_refcnt != 0);
9617 
9618 	for (i = 0; i < dp->dtdo_varlen; i++) {
9619 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9620 
9621 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9622 			continue;
9623 
9624 		ASSERT(dtrace_vtime_references > 0);
9625 		if (--dtrace_vtime_references == 0)
9626 			dtrace_vtime_disable();
9627 	}
9628 
9629 	if (--dp->dtdo_refcnt == 0)
9630 		dtrace_difo_destroy(dp, vstate);
9631 }
9632 
9633 /*
9634  * DTrace Format Functions
9635  */
9636 static uint16_t
9637 dtrace_format_add(dtrace_state_t *state, char *str)
9638 {
9639 	char *fmt, **new;
9640 	uint16_t ndx, len = strlen(str) + 1;
9641 
9642 	fmt = kmem_zalloc(len, KM_SLEEP);
9643 	bcopy(str, fmt, len);
9644 
9645 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9646 		if (state->dts_formats[ndx] == NULL) {
9647 			state->dts_formats[ndx] = fmt;
9648 			return (ndx + 1);
9649 		}
9650 	}
9651 
9652 	if (state->dts_nformats == USHRT_MAX) {
9653 		/*
9654 		 * This is only likely if a denial-of-service attack is being
9655 		 * attempted.  As such, it's okay to fail silently here.
9656 		 */
9657 		kmem_free(fmt, len);
9658 		return (0);
9659 	}
9660 
9661 	/*
9662 	 * For simplicity, we always resize the formats array to be exactly the
9663 	 * number of formats.
9664 	 */
9665 	ndx = state->dts_nformats++;
9666 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9667 
9668 	if (state->dts_formats != NULL) {
9669 		ASSERT(ndx != 0);
9670 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
9671 		kmem_free(state->dts_formats, ndx * sizeof (char *));
9672 	}
9673 
9674 	state->dts_formats = new;
9675 	state->dts_formats[ndx] = fmt;
9676 
9677 	return (ndx + 1);
9678 }
9679 
9680 static void
9681 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9682 {
9683 	char *fmt;
9684 
9685 	ASSERT(state->dts_formats != NULL);
9686 	ASSERT(format <= state->dts_nformats);
9687 	ASSERT(state->dts_formats[format - 1] != NULL);
9688 
9689 	fmt = state->dts_formats[format - 1];
9690 	kmem_free(fmt, strlen(fmt) + 1);
9691 	state->dts_formats[format - 1] = NULL;
9692 }
9693 
9694 static void
9695 dtrace_format_destroy(dtrace_state_t *state)
9696 {
9697 	int i;
9698 
9699 	if (state->dts_nformats == 0) {
9700 		ASSERT(state->dts_formats == NULL);
9701 		return;
9702 	}
9703 
9704 	ASSERT(state->dts_formats != NULL);
9705 
9706 	for (i = 0; i < state->dts_nformats; i++) {
9707 		char *fmt = state->dts_formats[i];
9708 
9709 		if (fmt == NULL)
9710 			continue;
9711 
9712 		kmem_free(fmt, strlen(fmt) + 1);
9713 	}
9714 
9715 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9716 	state->dts_nformats = 0;
9717 	state->dts_formats = NULL;
9718 }
9719 
9720 /*
9721  * DTrace Predicate Functions
9722  */
9723 static dtrace_predicate_t *
9724 dtrace_predicate_create(dtrace_difo_t *dp)
9725 {
9726 	dtrace_predicate_t *pred;
9727 
9728 	ASSERT(MUTEX_HELD(&dtrace_lock));
9729 	ASSERT(dp->dtdo_refcnt != 0);
9730 
9731 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9732 	pred->dtp_difo = dp;
9733 	pred->dtp_refcnt = 1;
9734 
9735 	if (!dtrace_difo_cacheable(dp))
9736 		return (pred);
9737 
9738 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9739 		/*
9740 		 * This is only theoretically possible -- we have had 2^32
9741 		 * cacheable predicates on this machine.  We cannot allow any
9742 		 * more predicates to become cacheable:  as unlikely as it is,
9743 		 * there may be a thread caching a (now stale) predicate cache
9744 		 * ID. (N.B.: the temptation is being successfully resisted to
9745 		 * have this cmn_err() "Holy shit -- we executed this code!")
9746 		 */
9747 		return (pred);
9748 	}
9749 
9750 	pred->dtp_cacheid = dtrace_predcache_id++;
9751 
9752 	return (pred);
9753 }
9754 
9755 static void
9756 dtrace_predicate_hold(dtrace_predicate_t *pred)
9757 {
9758 	ASSERT(MUTEX_HELD(&dtrace_lock));
9759 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9760 	ASSERT(pred->dtp_refcnt > 0);
9761 
9762 	pred->dtp_refcnt++;
9763 }
9764 
9765 static void
9766 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9767 {
9768 	dtrace_difo_t *dp = pred->dtp_difo;
9769 
9770 	ASSERT(MUTEX_HELD(&dtrace_lock));
9771 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9772 	ASSERT(pred->dtp_refcnt > 0);
9773 
9774 	if (--pred->dtp_refcnt == 0) {
9775 		dtrace_difo_release(pred->dtp_difo, vstate);
9776 		kmem_free(pred, sizeof (dtrace_predicate_t));
9777 	}
9778 }
9779 
9780 /*
9781  * DTrace Action Description Functions
9782  */
9783 static dtrace_actdesc_t *
9784 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9785     uint64_t uarg, uint64_t arg)
9786 {
9787 	dtrace_actdesc_t *act;
9788 
9789 #if defined(sun)
9790 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9791 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9792 #endif
9793 
9794 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9795 	act->dtad_kind = kind;
9796 	act->dtad_ntuple = ntuple;
9797 	act->dtad_uarg = uarg;
9798 	act->dtad_arg = arg;
9799 	act->dtad_refcnt = 1;
9800 
9801 	return (act);
9802 }
9803 
9804 static void
9805 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9806 {
9807 	ASSERT(act->dtad_refcnt >= 1);
9808 	act->dtad_refcnt++;
9809 }
9810 
9811 static void
9812 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9813 {
9814 	dtrace_actkind_t kind = act->dtad_kind;
9815 	dtrace_difo_t *dp;
9816 
9817 	ASSERT(act->dtad_refcnt >= 1);
9818 
9819 	if (--act->dtad_refcnt != 0)
9820 		return;
9821 
9822 	if ((dp = act->dtad_difo) != NULL)
9823 		dtrace_difo_release(dp, vstate);
9824 
9825 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
9826 		char *str = (char *)(uintptr_t)act->dtad_arg;
9827 
9828 #if defined(sun)
9829 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9830 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9831 #endif
9832 
9833 		if (str != NULL)
9834 			kmem_free(str, strlen(str) + 1);
9835 	}
9836 
9837 	kmem_free(act, sizeof (dtrace_actdesc_t));
9838 }
9839 
9840 /*
9841  * DTrace ECB Functions
9842  */
9843 static dtrace_ecb_t *
9844 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9845 {
9846 	dtrace_ecb_t *ecb;
9847 	dtrace_epid_t epid;
9848 
9849 	ASSERT(MUTEX_HELD(&dtrace_lock));
9850 
9851 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9852 	ecb->dte_predicate = NULL;
9853 	ecb->dte_probe = probe;
9854 
9855 	/*
9856 	 * The default size is the size of the default action: recording
9857 	 * the header.
9858 	 */
9859 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9860 	ecb->dte_alignment = sizeof (dtrace_epid_t);
9861 
9862 	epid = state->dts_epid++;
9863 
9864 	if (epid - 1 >= state->dts_necbs) {
9865 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9866 		int necbs = state->dts_necbs << 1;
9867 
9868 		ASSERT(epid == state->dts_necbs + 1);
9869 
9870 		if (necbs == 0) {
9871 			ASSERT(oecbs == NULL);
9872 			necbs = 1;
9873 		}
9874 
9875 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9876 
9877 		if (oecbs != NULL)
9878 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9879 
9880 		dtrace_membar_producer();
9881 		state->dts_ecbs = ecbs;
9882 
9883 		if (oecbs != NULL) {
9884 			/*
9885 			 * If this state is active, we must dtrace_sync()
9886 			 * before we can free the old dts_ecbs array:  we're
9887 			 * coming in hot, and there may be active ring
9888 			 * buffer processing (which indexes into the dts_ecbs
9889 			 * array) on another CPU.
9890 			 */
9891 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9892 				dtrace_sync();
9893 
9894 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9895 		}
9896 
9897 		dtrace_membar_producer();
9898 		state->dts_necbs = necbs;
9899 	}
9900 
9901 	ecb->dte_state = state;
9902 
9903 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
9904 	dtrace_membar_producer();
9905 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9906 
9907 	return (ecb);
9908 }
9909 
9910 static void
9911 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9912 {
9913 	dtrace_probe_t *probe = ecb->dte_probe;
9914 
9915 	ASSERT(MUTEX_HELD(&cpu_lock));
9916 	ASSERT(MUTEX_HELD(&dtrace_lock));
9917 	ASSERT(ecb->dte_next == NULL);
9918 
9919 	if (probe == NULL) {
9920 		/*
9921 		 * This is the NULL probe -- there's nothing to do.
9922 		 */
9923 		return;
9924 	}
9925 
9926 	if (probe->dtpr_ecb == NULL) {
9927 		dtrace_provider_t *prov = probe->dtpr_provider;
9928 
9929 		/*
9930 		 * We're the first ECB on this probe.
9931 		 */
9932 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9933 
9934 		if (ecb->dte_predicate != NULL)
9935 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9936 
9937 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9938 		    probe->dtpr_id, probe->dtpr_arg);
9939 	} else {
9940 		/*
9941 		 * This probe is already active.  Swing the last pointer to
9942 		 * point to the new ECB, and issue a dtrace_sync() to assure
9943 		 * that all CPUs have seen the change.
9944 		 */
9945 		ASSERT(probe->dtpr_ecb_last != NULL);
9946 		probe->dtpr_ecb_last->dte_next = ecb;
9947 		probe->dtpr_ecb_last = ecb;
9948 		probe->dtpr_predcache = 0;
9949 
9950 		dtrace_sync();
9951 	}
9952 }
9953 
9954 static void
9955 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9956 {
9957 	dtrace_action_t *act;
9958 	uint32_t curneeded = UINT32_MAX;
9959 	uint32_t aggbase = UINT32_MAX;
9960 
9961 	/*
9962 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
9963 	 * we always record it first.)
9964 	 */
9965 	ecb->dte_size = sizeof (dtrace_rechdr_t);
9966 	ecb->dte_alignment = sizeof (dtrace_epid_t);
9967 
9968 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9969 		dtrace_recdesc_t *rec = &act->dta_rec;
9970 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9971 
9972 		ecb->dte_alignment = MAX(ecb->dte_alignment,
9973 		    rec->dtrd_alignment);
9974 
9975 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9976 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9977 
9978 			ASSERT(rec->dtrd_size != 0);
9979 			ASSERT(agg->dtag_first != NULL);
9980 			ASSERT(act->dta_prev->dta_intuple);
9981 			ASSERT(aggbase != UINT32_MAX);
9982 			ASSERT(curneeded != UINT32_MAX);
9983 
9984 			agg->dtag_base = aggbase;
9985 
9986 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9987 			rec->dtrd_offset = curneeded;
9988 			curneeded += rec->dtrd_size;
9989 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9990 
9991 			aggbase = UINT32_MAX;
9992 			curneeded = UINT32_MAX;
9993 		} else if (act->dta_intuple) {
9994 			if (curneeded == UINT32_MAX) {
9995 				/*
9996 				 * This is the first record in a tuple.  Align
9997 				 * curneeded to be at offset 4 in an 8-byte
9998 				 * aligned block.
9999 				 */
10000 				ASSERT(act->dta_prev == NULL ||
10001 				    !act->dta_prev->dta_intuple);
10002 				ASSERT3U(aggbase, ==, UINT32_MAX);
10003 				curneeded = P2PHASEUP(ecb->dte_size,
10004 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10005 
10006 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10007 				ASSERT(IS_P2ALIGNED(aggbase,
10008 				    sizeof (uint64_t)));
10009 			}
10010 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10011 			rec->dtrd_offset = curneeded;
10012 			curneeded += rec->dtrd_size;
10013 		} else {
10014 			/* tuples must be followed by an aggregation */
10015 			ASSERT(act->dta_prev == NULL ||
10016 			    !act->dta_prev->dta_intuple);
10017 
10018 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10019 			    rec->dtrd_alignment);
10020 			rec->dtrd_offset = ecb->dte_size;
10021 			ecb->dte_size += rec->dtrd_size;
10022 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10023 		}
10024 	}
10025 
10026 	if ((act = ecb->dte_action) != NULL &&
10027 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10028 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10029 		/*
10030 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10031 		 * actions store no data; set the size to 0.
10032 		 */
10033 		ecb->dte_size = 0;
10034 	}
10035 
10036 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10037 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10038 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10039 	    ecb->dte_needed);
10040 }
10041 
10042 static dtrace_action_t *
10043 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10044 {
10045 	dtrace_aggregation_t *agg;
10046 	size_t size = sizeof (uint64_t);
10047 	int ntuple = desc->dtad_ntuple;
10048 	dtrace_action_t *act;
10049 	dtrace_recdesc_t *frec;
10050 	dtrace_aggid_t aggid;
10051 	dtrace_state_t *state = ecb->dte_state;
10052 
10053 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10054 	agg->dtag_ecb = ecb;
10055 
10056 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10057 
10058 	switch (desc->dtad_kind) {
10059 	case DTRACEAGG_MIN:
10060 		agg->dtag_initial = INT64_MAX;
10061 		agg->dtag_aggregate = dtrace_aggregate_min;
10062 		break;
10063 
10064 	case DTRACEAGG_MAX:
10065 		agg->dtag_initial = INT64_MIN;
10066 		agg->dtag_aggregate = dtrace_aggregate_max;
10067 		break;
10068 
10069 	case DTRACEAGG_COUNT:
10070 		agg->dtag_aggregate = dtrace_aggregate_count;
10071 		break;
10072 
10073 	case DTRACEAGG_QUANTIZE:
10074 		agg->dtag_aggregate = dtrace_aggregate_quantize;
10075 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10076 		    sizeof (uint64_t);
10077 		break;
10078 
10079 	case DTRACEAGG_LQUANTIZE: {
10080 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10081 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10082 
10083 		agg->dtag_initial = desc->dtad_arg;
10084 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10085 
10086 		if (step == 0 || levels == 0)
10087 			goto err;
10088 
10089 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10090 		break;
10091 	}
10092 
10093 	case DTRACEAGG_LLQUANTIZE: {
10094 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10095 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10096 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10097 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10098 		int64_t v;
10099 
10100 		agg->dtag_initial = desc->dtad_arg;
10101 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10102 
10103 		if (factor < 2 || low >= high || nsteps < factor)
10104 			goto err;
10105 
10106 		/*
10107 		 * Now check that the number of steps evenly divides a power
10108 		 * of the factor.  (This assures both integer bucket size and
10109 		 * linearity within each magnitude.)
10110 		 */
10111 		for (v = factor; v < nsteps; v *= factor)
10112 			continue;
10113 
10114 		if ((v % nsteps) || (nsteps % factor))
10115 			goto err;
10116 
10117 		size = (dtrace_aggregate_llquantize_bucket(factor,
10118 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10119 		break;
10120 	}
10121 
10122 	case DTRACEAGG_AVG:
10123 		agg->dtag_aggregate = dtrace_aggregate_avg;
10124 		size = sizeof (uint64_t) * 2;
10125 		break;
10126 
10127 	case DTRACEAGG_STDDEV:
10128 		agg->dtag_aggregate = dtrace_aggregate_stddev;
10129 		size = sizeof (uint64_t) * 4;
10130 		break;
10131 
10132 	case DTRACEAGG_SUM:
10133 		agg->dtag_aggregate = dtrace_aggregate_sum;
10134 		break;
10135 
10136 	default:
10137 		goto err;
10138 	}
10139 
10140 	agg->dtag_action.dta_rec.dtrd_size = size;
10141 
10142 	if (ntuple == 0)
10143 		goto err;
10144 
10145 	/*
10146 	 * We must make sure that we have enough actions for the n-tuple.
10147 	 */
10148 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10149 		if (DTRACEACT_ISAGG(act->dta_kind))
10150 			break;
10151 
10152 		if (--ntuple == 0) {
10153 			/*
10154 			 * This is the action with which our n-tuple begins.
10155 			 */
10156 			agg->dtag_first = act;
10157 			goto success;
10158 		}
10159 	}
10160 
10161 	/*
10162 	 * This n-tuple is short by ntuple elements.  Return failure.
10163 	 */
10164 	ASSERT(ntuple != 0);
10165 err:
10166 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10167 	return (NULL);
10168 
10169 success:
10170 	/*
10171 	 * If the last action in the tuple has a size of zero, it's actually
10172 	 * an expression argument for the aggregating action.
10173 	 */
10174 	ASSERT(ecb->dte_action_last != NULL);
10175 	act = ecb->dte_action_last;
10176 
10177 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10178 		ASSERT(act->dta_difo != NULL);
10179 
10180 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10181 			agg->dtag_hasarg = 1;
10182 	}
10183 
10184 	/*
10185 	 * We need to allocate an id for this aggregation.
10186 	 */
10187 #if defined(sun)
10188 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10189 	    VM_BESTFIT | VM_SLEEP);
10190 #else
10191 	aggid = alloc_unr(state->dts_aggid_arena);
10192 #endif
10193 
10194 	if (aggid - 1 >= state->dts_naggregations) {
10195 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10196 		dtrace_aggregation_t **aggs;
10197 		int naggs = state->dts_naggregations << 1;
10198 		int onaggs = state->dts_naggregations;
10199 
10200 		ASSERT(aggid == state->dts_naggregations + 1);
10201 
10202 		if (naggs == 0) {
10203 			ASSERT(oaggs == NULL);
10204 			naggs = 1;
10205 		}
10206 
10207 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10208 
10209 		if (oaggs != NULL) {
10210 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10211 			kmem_free(oaggs, onaggs * sizeof (*aggs));
10212 		}
10213 
10214 		state->dts_aggregations = aggs;
10215 		state->dts_naggregations = naggs;
10216 	}
10217 
10218 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10219 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10220 
10221 	frec = &agg->dtag_first->dta_rec;
10222 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10223 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10224 
10225 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10226 		ASSERT(!act->dta_intuple);
10227 		act->dta_intuple = 1;
10228 	}
10229 
10230 	return (&agg->dtag_action);
10231 }
10232 
10233 static void
10234 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10235 {
10236 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10237 	dtrace_state_t *state = ecb->dte_state;
10238 	dtrace_aggid_t aggid = agg->dtag_id;
10239 
10240 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10241 #if defined(sun)
10242 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10243 #else
10244 	free_unr(state->dts_aggid_arena, aggid);
10245 #endif
10246 
10247 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10248 	state->dts_aggregations[aggid - 1] = NULL;
10249 
10250 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10251 }
10252 
10253 static int
10254 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10255 {
10256 	dtrace_action_t *action, *last;
10257 	dtrace_difo_t *dp = desc->dtad_difo;
10258 	uint32_t size = 0, align = sizeof (uint8_t), mask;
10259 	uint16_t format = 0;
10260 	dtrace_recdesc_t *rec;
10261 	dtrace_state_t *state = ecb->dte_state;
10262 	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10263 	uint64_t arg = desc->dtad_arg;
10264 
10265 	ASSERT(MUTEX_HELD(&dtrace_lock));
10266 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10267 
10268 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10269 		/*
10270 		 * If this is an aggregating action, there must be neither
10271 		 * a speculate nor a commit on the action chain.
10272 		 */
10273 		dtrace_action_t *act;
10274 
10275 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10276 			if (act->dta_kind == DTRACEACT_COMMIT)
10277 				return (EINVAL);
10278 
10279 			if (act->dta_kind == DTRACEACT_SPECULATE)
10280 				return (EINVAL);
10281 		}
10282 
10283 		action = dtrace_ecb_aggregation_create(ecb, desc);
10284 
10285 		if (action == NULL)
10286 			return (EINVAL);
10287 	} else {
10288 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10289 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10290 		    dp != NULL && dp->dtdo_destructive)) {
10291 			state->dts_destructive = 1;
10292 		}
10293 
10294 		switch (desc->dtad_kind) {
10295 		case DTRACEACT_PRINTF:
10296 		case DTRACEACT_PRINTA:
10297 		case DTRACEACT_SYSTEM:
10298 		case DTRACEACT_FREOPEN:
10299 		case DTRACEACT_DIFEXPR:
10300 			/*
10301 			 * We know that our arg is a string -- turn it into a
10302 			 * format.
10303 			 */
10304 			if (arg == 0) {
10305 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10306 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
10307 				format = 0;
10308 			} else {
10309 				ASSERT(arg != 0);
10310 #if defined(sun)
10311 				ASSERT(arg > KERNELBASE);
10312 #endif
10313 				format = dtrace_format_add(state,
10314 				    (char *)(uintptr_t)arg);
10315 			}
10316 
10317 			/*FALLTHROUGH*/
10318 		case DTRACEACT_LIBACT:
10319 		case DTRACEACT_TRACEMEM:
10320 		case DTRACEACT_TRACEMEM_DYNSIZE:
10321 			if (dp == NULL)
10322 				return (EINVAL);
10323 
10324 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10325 				break;
10326 
10327 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10328 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10329 					return (EINVAL);
10330 
10331 				size = opt[DTRACEOPT_STRSIZE];
10332 			}
10333 
10334 			break;
10335 
10336 		case DTRACEACT_STACK:
10337 			if ((nframes = arg) == 0) {
10338 				nframes = opt[DTRACEOPT_STACKFRAMES];
10339 				ASSERT(nframes > 0);
10340 				arg = nframes;
10341 			}
10342 
10343 			size = nframes * sizeof (pc_t);
10344 			break;
10345 
10346 		case DTRACEACT_JSTACK:
10347 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10348 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10349 
10350 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10351 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
10352 
10353 			arg = DTRACE_USTACK_ARG(nframes, strsize);
10354 
10355 			/*FALLTHROUGH*/
10356 		case DTRACEACT_USTACK:
10357 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
10358 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10359 				strsize = DTRACE_USTACK_STRSIZE(arg);
10360 				nframes = opt[DTRACEOPT_USTACKFRAMES];
10361 				ASSERT(nframes > 0);
10362 				arg = DTRACE_USTACK_ARG(nframes, strsize);
10363 			}
10364 
10365 			/*
10366 			 * Save a slot for the pid.
10367 			 */
10368 			size = (nframes + 1) * sizeof (uint64_t);
10369 			size += DTRACE_USTACK_STRSIZE(arg);
10370 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10371 
10372 			break;
10373 
10374 		case DTRACEACT_SYM:
10375 		case DTRACEACT_MOD:
10376 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10377 			    sizeof (uint64_t)) ||
10378 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10379 				return (EINVAL);
10380 			break;
10381 
10382 		case DTRACEACT_USYM:
10383 		case DTRACEACT_UMOD:
10384 		case DTRACEACT_UADDR:
10385 			if (dp == NULL ||
10386 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10387 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10388 				return (EINVAL);
10389 
10390 			/*
10391 			 * We have a slot for the pid, plus a slot for the
10392 			 * argument.  To keep things simple (aligned with
10393 			 * bitness-neutral sizing), we store each as a 64-bit
10394 			 * quantity.
10395 			 */
10396 			size = 2 * sizeof (uint64_t);
10397 			break;
10398 
10399 		case DTRACEACT_STOP:
10400 		case DTRACEACT_BREAKPOINT:
10401 		case DTRACEACT_PANIC:
10402 			break;
10403 
10404 		case DTRACEACT_CHILL:
10405 		case DTRACEACT_DISCARD:
10406 		case DTRACEACT_RAISE:
10407 			if (dp == NULL)
10408 				return (EINVAL);
10409 			break;
10410 
10411 		case DTRACEACT_EXIT:
10412 			if (dp == NULL ||
10413 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10414 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10415 				return (EINVAL);
10416 			break;
10417 
10418 		case DTRACEACT_SPECULATE:
10419 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10420 				return (EINVAL);
10421 
10422 			if (dp == NULL)
10423 				return (EINVAL);
10424 
10425 			state->dts_speculates = 1;
10426 			break;
10427 
10428 		case DTRACEACT_PRINTM:
10429 		    	size = dp->dtdo_rtype.dtdt_size;
10430 			break;
10431 
10432 		case DTRACEACT_PRINTT:
10433 		    	size = dp->dtdo_rtype.dtdt_size;
10434 			break;
10435 
10436 		case DTRACEACT_COMMIT: {
10437 			dtrace_action_t *act = ecb->dte_action;
10438 
10439 			for (; act != NULL; act = act->dta_next) {
10440 				if (act->dta_kind == DTRACEACT_COMMIT)
10441 					return (EINVAL);
10442 			}
10443 
10444 			if (dp == NULL)
10445 				return (EINVAL);
10446 			break;
10447 		}
10448 
10449 		default:
10450 			return (EINVAL);
10451 		}
10452 
10453 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10454 			/*
10455 			 * If this is a data-storing action or a speculate,
10456 			 * we must be sure that there isn't a commit on the
10457 			 * action chain.
10458 			 */
10459 			dtrace_action_t *act = ecb->dte_action;
10460 
10461 			for (; act != NULL; act = act->dta_next) {
10462 				if (act->dta_kind == DTRACEACT_COMMIT)
10463 					return (EINVAL);
10464 			}
10465 		}
10466 
10467 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10468 		action->dta_rec.dtrd_size = size;
10469 	}
10470 
10471 	action->dta_refcnt = 1;
10472 	rec = &action->dta_rec;
10473 	size = rec->dtrd_size;
10474 
10475 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10476 		if (!(size & mask)) {
10477 			align = mask + 1;
10478 			break;
10479 		}
10480 	}
10481 
10482 	action->dta_kind = desc->dtad_kind;
10483 
10484 	if ((action->dta_difo = dp) != NULL)
10485 		dtrace_difo_hold(dp);
10486 
10487 	rec->dtrd_action = action->dta_kind;
10488 	rec->dtrd_arg = arg;
10489 	rec->dtrd_uarg = desc->dtad_uarg;
10490 	rec->dtrd_alignment = (uint16_t)align;
10491 	rec->dtrd_format = format;
10492 
10493 	if ((last = ecb->dte_action_last) != NULL) {
10494 		ASSERT(ecb->dte_action != NULL);
10495 		action->dta_prev = last;
10496 		last->dta_next = action;
10497 	} else {
10498 		ASSERT(ecb->dte_action == NULL);
10499 		ecb->dte_action = action;
10500 	}
10501 
10502 	ecb->dte_action_last = action;
10503 
10504 	return (0);
10505 }
10506 
10507 static void
10508 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10509 {
10510 	dtrace_action_t *act = ecb->dte_action, *next;
10511 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10512 	dtrace_difo_t *dp;
10513 	uint16_t format;
10514 
10515 	if (act != NULL && act->dta_refcnt > 1) {
10516 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10517 		act->dta_refcnt--;
10518 	} else {
10519 		for (; act != NULL; act = next) {
10520 			next = act->dta_next;
10521 			ASSERT(next != NULL || act == ecb->dte_action_last);
10522 			ASSERT(act->dta_refcnt == 1);
10523 
10524 			if ((format = act->dta_rec.dtrd_format) != 0)
10525 				dtrace_format_remove(ecb->dte_state, format);
10526 
10527 			if ((dp = act->dta_difo) != NULL)
10528 				dtrace_difo_release(dp, vstate);
10529 
10530 			if (DTRACEACT_ISAGG(act->dta_kind)) {
10531 				dtrace_ecb_aggregation_destroy(ecb, act);
10532 			} else {
10533 				kmem_free(act, sizeof (dtrace_action_t));
10534 			}
10535 		}
10536 	}
10537 
10538 	ecb->dte_action = NULL;
10539 	ecb->dte_action_last = NULL;
10540 	ecb->dte_size = 0;
10541 }
10542 
10543 static void
10544 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10545 {
10546 	/*
10547 	 * We disable the ECB by removing it from its probe.
10548 	 */
10549 	dtrace_ecb_t *pecb, *prev = NULL;
10550 	dtrace_probe_t *probe = ecb->dte_probe;
10551 
10552 	ASSERT(MUTEX_HELD(&dtrace_lock));
10553 
10554 	if (probe == NULL) {
10555 		/*
10556 		 * This is the NULL probe; there is nothing to disable.
10557 		 */
10558 		return;
10559 	}
10560 
10561 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10562 		if (pecb == ecb)
10563 			break;
10564 		prev = pecb;
10565 	}
10566 
10567 	ASSERT(pecb != NULL);
10568 
10569 	if (prev == NULL) {
10570 		probe->dtpr_ecb = ecb->dte_next;
10571 	} else {
10572 		prev->dte_next = ecb->dte_next;
10573 	}
10574 
10575 	if (ecb == probe->dtpr_ecb_last) {
10576 		ASSERT(ecb->dte_next == NULL);
10577 		probe->dtpr_ecb_last = prev;
10578 	}
10579 
10580 	/*
10581 	 * The ECB has been disconnected from the probe; now sync to assure
10582 	 * that all CPUs have seen the change before returning.
10583 	 */
10584 	dtrace_sync();
10585 
10586 	if (probe->dtpr_ecb == NULL) {
10587 		/*
10588 		 * That was the last ECB on the probe; clear the predicate
10589 		 * cache ID for the probe, disable it and sync one more time
10590 		 * to assure that we'll never hit it again.
10591 		 */
10592 		dtrace_provider_t *prov = probe->dtpr_provider;
10593 
10594 		ASSERT(ecb->dte_next == NULL);
10595 		ASSERT(probe->dtpr_ecb_last == NULL);
10596 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10597 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10598 		    probe->dtpr_id, probe->dtpr_arg);
10599 		dtrace_sync();
10600 	} else {
10601 		/*
10602 		 * There is at least one ECB remaining on the probe.  If there
10603 		 * is _exactly_ one, set the probe's predicate cache ID to be
10604 		 * the predicate cache ID of the remaining ECB.
10605 		 */
10606 		ASSERT(probe->dtpr_ecb_last != NULL);
10607 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10608 
10609 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10610 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10611 
10612 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
10613 
10614 			if (p != NULL)
10615 				probe->dtpr_predcache = p->dtp_cacheid;
10616 		}
10617 
10618 		ecb->dte_next = NULL;
10619 	}
10620 }
10621 
10622 static void
10623 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10624 {
10625 	dtrace_state_t *state = ecb->dte_state;
10626 	dtrace_vstate_t *vstate = &state->dts_vstate;
10627 	dtrace_predicate_t *pred;
10628 	dtrace_epid_t epid = ecb->dte_epid;
10629 
10630 	ASSERT(MUTEX_HELD(&dtrace_lock));
10631 	ASSERT(ecb->dte_next == NULL);
10632 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10633 
10634 	if ((pred = ecb->dte_predicate) != NULL)
10635 		dtrace_predicate_release(pred, vstate);
10636 
10637 	dtrace_ecb_action_remove(ecb);
10638 
10639 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
10640 	state->dts_ecbs[epid - 1] = NULL;
10641 
10642 	kmem_free(ecb, sizeof (dtrace_ecb_t));
10643 }
10644 
10645 static dtrace_ecb_t *
10646 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10647     dtrace_enabling_t *enab)
10648 {
10649 	dtrace_ecb_t *ecb;
10650 	dtrace_predicate_t *pred;
10651 	dtrace_actdesc_t *act;
10652 	dtrace_provider_t *prov;
10653 	dtrace_ecbdesc_t *desc = enab->dten_current;
10654 
10655 	ASSERT(MUTEX_HELD(&dtrace_lock));
10656 	ASSERT(state != NULL);
10657 
10658 	ecb = dtrace_ecb_add(state, probe);
10659 	ecb->dte_uarg = desc->dted_uarg;
10660 
10661 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10662 		dtrace_predicate_hold(pred);
10663 		ecb->dte_predicate = pred;
10664 	}
10665 
10666 	if (probe != NULL) {
10667 		/*
10668 		 * If the provider shows more leg than the consumer is old
10669 		 * enough to see, we need to enable the appropriate implicit
10670 		 * predicate bits to prevent the ecb from activating at
10671 		 * revealing times.
10672 		 *
10673 		 * Providers specifying DTRACE_PRIV_USER at register time
10674 		 * are stating that they need the /proc-style privilege
10675 		 * model to be enforced, and this is what DTRACE_COND_OWNER
10676 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10677 		 */
10678 		prov = probe->dtpr_provider;
10679 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10680 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10681 			ecb->dte_cond |= DTRACE_COND_OWNER;
10682 
10683 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10684 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10685 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10686 
10687 		/*
10688 		 * If the provider shows us kernel innards and the user
10689 		 * is lacking sufficient privilege, enable the
10690 		 * DTRACE_COND_USERMODE implicit predicate.
10691 		 */
10692 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10693 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10694 			ecb->dte_cond |= DTRACE_COND_USERMODE;
10695 	}
10696 
10697 	if (dtrace_ecb_create_cache != NULL) {
10698 		/*
10699 		 * If we have a cached ecb, we'll use its action list instead
10700 		 * of creating our own (saving both time and space).
10701 		 */
10702 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10703 		dtrace_action_t *act = cached->dte_action;
10704 
10705 		if (act != NULL) {
10706 			ASSERT(act->dta_refcnt > 0);
10707 			act->dta_refcnt++;
10708 			ecb->dte_action = act;
10709 			ecb->dte_action_last = cached->dte_action_last;
10710 			ecb->dte_needed = cached->dte_needed;
10711 			ecb->dte_size = cached->dte_size;
10712 			ecb->dte_alignment = cached->dte_alignment;
10713 		}
10714 
10715 		return (ecb);
10716 	}
10717 
10718 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10719 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10720 			dtrace_ecb_destroy(ecb);
10721 			return (NULL);
10722 		}
10723 	}
10724 
10725 	dtrace_ecb_resize(ecb);
10726 
10727 	return (dtrace_ecb_create_cache = ecb);
10728 }
10729 
10730 static int
10731 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10732 {
10733 	dtrace_ecb_t *ecb;
10734 	dtrace_enabling_t *enab = arg;
10735 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10736 
10737 	ASSERT(state != NULL);
10738 
10739 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10740 		/*
10741 		 * This probe was created in a generation for which this
10742 		 * enabling has previously created ECBs; we don't want to
10743 		 * enable it again, so just kick out.
10744 		 */
10745 		return (DTRACE_MATCH_NEXT);
10746 	}
10747 
10748 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10749 		return (DTRACE_MATCH_DONE);
10750 
10751 	dtrace_ecb_enable(ecb);
10752 	return (DTRACE_MATCH_NEXT);
10753 }
10754 
10755 static dtrace_ecb_t *
10756 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10757 {
10758 	dtrace_ecb_t *ecb;
10759 
10760 	ASSERT(MUTEX_HELD(&dtrace_lock));
10761 
10762 	if (id == 0 || id > state->dts_necbs)
10763 		return (NULL);
10764 
10765 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10766 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10767 
10768 	return (state->dts_ecbs[id - 1]);
10769 }
10770 
10771 static dtrace_aggregation_t *
10772 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10773 {
10774 	dtrace_aggregation_t *agg;
10775 
10776 	ASSERT(MUTEX_HELD(&dtrace_lock));
10777 
10778 	if (id == 0 || id > state->dts_naggregations)
10779 		return (NULL);
10780 
10781 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10782 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10783 	    agg->dtag_id == id);
10784 
10785 	return (state->dts_aggregations[id - 1]);
10786 }
10787 
10788 /*
10789  * DTrace Buffer Functions
10790  *
10791  * The following functions manipulate DTrace buffers.  Most of these functions
10792  * are called in the context of establishing or processing consumer state;
10793  * exceptions are explicitly noted.
10794  */
10795 
10796 /*
10797  * Note:  called from cross call context.  This function switches the two
10798  * buffers on a given CPU.  The atomicity of this operation is assured by
10799  * disabling interrupts while the actual switch takes place; the disabling of
10800  * interrupts serializes the execution with any execution of dtrace_probe() on
10801  * the same CPU.
10802  */
10803 static void
10804 dtrace_buffer_switch(dtrace_buffer_t *buf)
10805 {
10806 	caddr_t tomax = buf->dtb_tomax;
10807 	caddr_t xamot = buf->dtb_xamot;
10808 	dtrace_icookie_t cookie;
10809 	hrtime_t now;
10810 
10811 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10812 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10813 
10814 	cookie = dtrace_interrupt_disable();
10815 	now = dtrace_gethrtime();
10816 	buf->dtb_tomax = xamot;
10817 	buf->dtb_xamot = tomax;
10818 	buf->dtb_xamot_drops = buf->dtb_drops;
10819 	buf->dtb_xamot_offset = buf->dtb_offset;
10820 	buf->dtb_xamot_errors = buf->dtb_errors;
10821 	buf->dtb_xamot_flags = buf->dtb_flags;
10822 	buf->dtb_offset = 0;
10823 	buf->dtb_drops = 0;
10824 	buf->dtb_errors = 0;
10825 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10826 	buf->dtb_interval = now - buf->dtb_switched;
10827 	buf->dtb_switched = now;
10828 	dtrace_interrupt_enable(cookie);
10829 }
10830 
10831 /*
10832  * Note:  called from cross call context.  This function activates a buffer
10833  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10834  * is guaranteed by the disabling of interrupts.
10835  */
10836 static void
10837 dtrace_buffer_activate(dtrace_state_t *state)
10838 {
10839 	dtrace_buffer_t *buf;
10840 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
10841 
10842 	buf = &state->dts_buffer[curcpu];
10843 
10844 	if (buf->dtb_tomax != NULL) {
10845 		/*
10846 		 * We might like to assert that the buffer is marked inactive,
10847 		 * but this isn't necessarily true:  the buffer for the CPU
10848 		 * that processes the BEGIN probe has its buffer activated
10849 		 * manually.  In this case, we take the (harmless) action
10850 		 * re-clearing the bit INACTIVE bit.
10851 		 */
10852 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10853 	}
10854 
10855 	dtrace_interrupt_enable(cookie);
10856 }
10857 
10858 static int
10859 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10860     processorid_t cpu, int *factor)
10861 {
10862 #if defined(sun)
10863 	cpu_t *cp;
10864 #endif
10865 	dtrace_buffer_t *buf;
10866 	int allocated = 0, desired = 0;
10867 
10868 #if defined(sun)
10869 	ASSERT(MUTEX_HELD(&cpu_lock));
10870 	ASSERT(MUTEX_HELD(&dtrace_lock));
10871 
10872 	*factor = 1;
10873 
10874 	if (size > dtrace_nonroot_maxsize &&
10875 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10876 		return (EFBIG);
10877 
10878 	cp = cpu_list;
10879 
10880 	do {
10881 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10882 			continue;
10883 
10884 		buf = &bufs[cp->cpu_id];
10885 
10886 		/*
10887 		 * If there is already a buffer allocated for this CPU, it
10888 		 * is only possible that this is a DR event.  In this case,
10889 		 */
10890 		if (buf->dtb_tomax != NULL) {
10891 			ASSERT(buf->dtb_size == size);
10892 			continue;
10893 		}
10894 
10895 		ASSERT(buf->dtb_xamot == NULL);
10896 
10897 		if ((buf->dtb_tomax = kmem_zalloc(size,
10898 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10899 			goto err;
10900 
10901 		buf->dtb_size = size;
10902 		buf->dtb_flags = flags;
10903 		buf->dtb_offset = 0;
10904 		buf->dtb_drops = 0;
10905 
10906 		if (flags & DTRACEBUF_NOSWITCH)
10907 			continue;
10908 
10909 		if ((buf->dtb_xamot = kmem_zalloc(size,
10910 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10911 			goto err;
10912 	} while ((cp = cp->cpu_next) != cpu_list);
10913 
10914 	return (0);
10915 
10916 err:
10917 	cp = cpu_list;
10918 
10919 	do {
10920 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10921 			continue;
10922 
10923 		buf = &bufs[cp->cpu_id];
10924 		desired += 2;
10925 
10926 		if (buf->dtb_xamot != NULL) {
10927 			ASSERT(buf->dtb_tomax != NULL);
10928 			ASSERT(buf->dtb_size == size);
10929 			kmem_free(buf->dtb_xamot, size);
10930 			allocated++;
10931 		}
10932 
10933 		if (buf->dtb_tomax != NULL) {
10934 			ASSERT(buf->dtb_size == size);
10935 			kmem_free(buf->dtb_tomax, size);
10936 			allocated++;
10937 		}
10938 
10939 		buf->dtb_tomax = NULL;
10940 		buf->dtb_xamot = NULL;
10941 		buf->dtb_size = 0;
10942 	} while ((cp = cp->cpu_next) != cpu_list);
10943 #else
10944 	int i;
10945 
10946 	*factor = 1;
10947 #if defined(__amd64__)
10948 	/*
10949 	 * FreeBSD isn't good at limiting the amount of memory we
10950 	 * ask to malloc, so let's place a limit here before trying
10951 	 * to do something that might well end in tears at bedtime.
10952 	 */
10953 	if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
10954 		return (ENOMEM);
10955 #endif
10956 
10957 	ASSERT(MUTEX_HELD(&dtrace_lock));
10958 	CPU_FOREACH(i) {
10959 		if (cpu != DTRACE_CPUALL && cpu != i)
10960 			continue;
10961 
10962 		buf = &bufs[i];
10963 
10964 		/*
10965 		 * If there is already a buffer allocated for this CPU, it
10966 		 * is only possible that this is a DR event.  In this case,
10967 		 * the buffer size must match our specified size.
10968 		 */
10969 		if (buf->dtb_tomax != NULL) {
10970 			ASSERT(buf->dtb_size == size);
10971 			continue;
10972 		}
10973 
10974 		ASSERT(buf->dtb_xamot == NULL);
10975 
10976 		if ((buf->dtb_tomax = kmem_zalloc(size,
10977 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10978 			goto err;
10979 
10980 		buf->dtb_size = size;
10981 		buf->dtb_flags = flags;
10982 		buf->dtb_offset = 0;
10983 		buf->dtb_drops = 0;
10984 
10985 		if (flags & DTRACEBUF_NOSWITCH)
10986 			continue;
10987 
10988 		if ((buf->dtb_xamot = kmem_zalloc(size,
10989 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10990 			goto err;
10991 	}
10992 
10993 	return (0);
10994 
10995 err:
10996 	/*
10997 	 * Error allocating memory, so free the buffers that were
10998 	 * allocated before the failed allocation.
10999 	 */
11000 	CPU_FOREACH(i) {
11001 		if (cpu != DTRACE_CPUALL && cpu != i)
11002 			continue;
11003 
11004 		buf = &bufs[i];
11005 		desired += 2;
11006 
11007 		if (buf->dtb_xamot != NULL) {
11008 			ASSERT(buf->dtb_tomax != NULL);
11009 			ASSERT(buf->dtb_size == size);
11010 			kmem_free(buf->dtb_xamot, size);
11011 			allocated++;
11012 		}
11013 
11014 		if (buf->dtb_tomax != NULL) {
11015 			ASSERT(buf->dtb_size == size);
11016 			kmem_free(buf->dtb_tomax, size);
11017 			allocated++;
11018 		}
11019 
11020 		buf->dtb_tomax = NULL;
11021 		buf->dtb_xamot = NULL;
11022 		buf->dtb_size = 0;
11023 
11024 	}
11025 #endif
11026 	*factor = desired / (allocated > 0 ? allocated : 1);
11027 
11028 	return (ENOMEM);
11029 }
11030 
11031 /*
11032  * Note:  called from probe context.  This function just increments the drop
11033  * count on a buffer.  It has been made a function to allow for the
11034  * possibility of understanding the source of mysterious drop counts.  (A
11035  * problem for which one may be particularly disappointed that DTrace cannot
11036  * be used to understand DTrace.)
11037  */
11038 static void
11039 dtrace_buffer_drop(dtrace_buffer_t *buf)
11040 {
11041 	buf->dtb_drops++;
11042 }
11043 
11044 /*
11045  * Note:  called from probe context.  This function is called to reserve space
11046  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11047  * mstate.  Returns the new offset in the buffer, or a negative value if an
11048  * error has occurred.
11049  */
11050 static intptr_t
11051 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11052     dtrace_state_t *state, dtrace_mstate_t *mstate)
11053 {
11054 	intptr_t offs = buf->dtb_offset, soffs;
11055 	intptr_t woffs;
11056 	caddr_t tomax;
11057 	size_t total;
11058 
11059 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11060 		return (-1);
11061 
11062 	if ((tomax = buf->dtb_tomax) == NULL) {
11063 		dtrace_buffer_drop(buf);
11064 		return (-1);
11065 	}
11066 
11067 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11068 		while (offs & (align - 1)) {
11069 			/*
11070 			 * Assert that our alignment is off by a number which
11071 			 * is itself sizeof (uint32_t) aligned.
11072 			 */
11073 			ASSERT(!((align - (offs & (align - 1))) &
11074 			    (sizeof (uint32_t) - 1)));
11075 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11076 			offs += sizeof (uint32_t);
11077 		}
11078 
11079 		if ((soffs = offs + needed) > buf->dtb_size) {
11080 			dtrace_buffer_drop(buf);
11081 			return (-1);
11082 		}
11083 
11084 		if (mstate == NULL)
11085 			return (offs);
11086 
11087 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11088 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11089 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11090 
11091 		return (offs);
11092 	}
11093 
11094 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11095 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11096 		    (buf->dtb_flags & DTRACEBUF_FULL))
11097 			return (-1);
11098 		goto out;
11099 	}
11100 
11101 	total = needed + (offs & (align - 1));
11102 
11103 	/*
11104 	 * For a ring buffer, life is quite a bit more complicated.  Before
11105 	 * we can store any padding, we need to adjust our wrapping offset.
11106 	 * (If we've never before wrapped or we're not about to, no adjustment
11107 	 * is required.)
11108 	 */
11109 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11110 	    offs + total > buf->dtb_size) {
11111 		woffs = buf->dtb_xamot_offset;
11112 
11113 		if (offs + total > buf->dtb_size) {
11114 			/*
11115 			 * We can't fit in the end of the buffer.  First, a
11116 			 * sanity check that we can fit in the buffer at all.
11117 			 */
11118 			if (total > buf->dtb_size) {
11119 				dtrace_buffer_drop(buf);
11120 				return (-1);
11121 			}
11122 
11123 			/*
11124 			 * We're going to be storing at the top of the buffer,
11125 			 * so now we need to deal with the wrapped offset.  We
11126 			 * only reset our wrapped offset to 0 if it is
11127 			 * currently greater than the current offset.  If it
11128 			 * is less than the current offset, it is because a
11129 			 * previous allocation induced a wrap -- but the
11130 			 * allocation didn't subsequently take the space due
11131 			 * to an error or false predicate evaluation.  In this
11132 			 * case, we'll just leave the wrapped offset alone: if
11133 			 * the wrapped offset hasn't been advanced far enough
11134 			 * for this allocation, it will be adjusted in the
11135 			 * lower loop.
11136 			 */
11137 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11138 				if (woffs >= offs)
11139 					woffs = 0;
11140 			} else {
11141 				woffs = 0;
11142 			}
11143 
11144 			/*
11145 			 * Now we know that we're going to be storing to the
11146 			 * top of the buffer and that there is room for us
11147 			 * there.  We need to clear the buffer from the current
11148 			 * offset to the end (there may be old gunk there).
11149 			 */
11150 			while (offs < buf->dtb_size)
11151 				tomax[offs++] = 0;
11152 
11153 			/*
11154 			 * We need to set our offset to zero.  And because we
11155 			 * are wrapping, we need to set the bit indicating as
11156 			 * much.  We can also adjust our needed space back
11157 			 * down to the space required by the ECB -- we know
11158 			 * that the top of the buffer is aligned.
11159 			 */
11160 			offs = 0;
11161 			total = needed;
11162 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11163 		} else {
11164 			/*
11165 			 * There is room for us in the buffer, so we simply
11166 			 * need to check the wrapped offset.
11167 			 */
11168 			if (woffs < offs) {
11169 				/*
11170 				 * The wrapped offset is less than the offset.
11171 				 * This can happen if we allocated buffer space
11172 				 * that induced a wrap, but then we didn't
11173 				 * subsequently take the space due to an error
11174 				 * or false predicate evaluation.  This is
11175 				 * okay; we know that _this_ allocation isn't
11176 				 * going to induce a wrap.  We still can't
11177 				 * reset the wrapped offset to be zero,
11178 				 * however: the space may have been trashed in
11179 				 * the previous failed probe attempt.  But at
11180 				 * least the wrapped offset doesn't need to
11181 				 * be adjusted at all...
11182 				 */
11183 				goto out;
11184 			}
11185 		}
11186 
11187 		while (offs + total > woffs) {
11188 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11189 			size_t size;
11190 
11191 			if (epid == DTRACE_EPIDNONE) {
11192 				size = sizeof (uint32_t);
11193 			} else {
11194 				ASSERT3U(epid, <=, state->dts_necbs);
11195 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11196 
11197 				size = state->dts_ecbs[epid - 1]->dte_size;
11198 			}
11199 
11200 			ASSERT(woffs + size <= buf->dtb_size);
11201 			ASSERT(size != 0);
11202 
11203 			if (woffs + size == buf->dtb_size) {
11204 				/*
11205 				 * We've reached the end of the buffer; we want
11206 				 * to set the wrapped offset to 0 and break
11207 				 * out.  However, if the offs is 0, then we're
11208 				 * in a strange edge-condition:  the amount of
11209 				 * space that we want to reserve plus the size
11210 				 * of the record that we're overwriting is
11211 				 * greater than the size of the buffer.  This
11212 				 * is problematic because if we reserve the
11213 				 * space but subsequently don't consume it (due
11214 				 * to a failed predicate or error) the wrapped
11215 				 * offset will be 0 -- yet the EPID at offset 0
11216 				 * will not be committed.  This situation is
11217 				 * relatively easy to deal with:  if we're in
11218 				 * this case, the buffer is indistinguishable
11219 				 * from one that hasn't wrapped; we need only
11220 				 * finish the job by clearing the wrapped bit,
11221 				 * explicitly setting the offset to be 0, and
11222 				 * zero'ing out the old data in the buffer.
11223 				 */
11224 				if (offs == 0) {
11225 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11226 					buf->dtb_offset = 0;
11227 					woffs = total;
11228 
11229 					while (woffs < buf->dtb_size)
11230 						tomax[woffs++] = 0;
11231 				}
11232 
11233 				woffs = 0;
11234 				break;
11235 			}
11236 
11237 			woffs += size;
11238 		}
11239 
11240 		/*
11241 		 * We have a wrapped offset.  It may be that the wrapped offset
11242 		 * has become zero -- that's okay.
11243 		 */
11244 		buf->dtb_xamot_offset = woffs;
11245 	}
11246 
11247 out:
11248 	/*
11249 	 * Now we can plow the buffer with any necessary padding.
11250 	 */
11251 	while (offs & (align - 1)) {
11252 		/*
11253 		 * Assert that our alignment is off by a number which
11254 		 * is itself sizeof (uint32_t) aligned.
11255 		 */
11256 		ASSERT(!((align - (offs & (align - 1))) &
11257 		    (sizeof (uint32_t) - 1)));
11258 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11259 		offs += sizeof (uint32_t);
11260 	}
11261 
11262 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11263 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11264 			buf->dtb_flags |= DTRACEBUF_FULL;
11265 			return (-1);
11266 		}
11267 	}
11268 
11269 	if (mstate == NULL)
11270 		return (offs);
11271 
11272 	/*
11273 	 * For ring buffers and fill buffers, the scratch space is always
11274 	 * the inactive buffer.
11275 	 */
11276 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11277 	mstate->dtms_scratch_size = buf->dtb_size;
11278 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11279 
11280 	return (offs);
11281 }
11282 
11283 static void
11284 dtrace_buffer_polish(dtrace_buffer_t *buf)
11285 {
11286 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11287 	ASSERT(MUTEX_HELD(&dtrace_lock));
11288 
11289 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11290 		return;
11291 
11292 	/*
11293 	 * We need to polish the ring buffer.  There are three cases:
11294 	 *
11295 	 * - The first (and presumably most common) is that there is no gap
11296 	 *   between the buffer offset and the wrapped offset.  In this case,
11297 	 *   there is nothing in the buffer that isn't valid data; we can
11298 	 *   mark the buffer as polished and return.
11299 	 *
11300 	 * - The second (less common than the first but still more common
11301 	 *   than the third) is that there is a gap between the buffer offset
11302 	 *   and the wrapped offset, and the wrapped offset is larger than the
11303 	 *   buffer offset.  This can happen because of an alignment issue, or
11304 	 *   can happen because of a call to dtrace_buffer_reserve() that
11305 	 *   didn't subsequently consume the buffer space.  In this case,
11306 	 *   we need to zero the data from the buffer offset to the wrapped
11307 	 *   offset.
11308 	 *
11309 	 * - The third (and least common) is that there is a gap between the
11310 	 *   buffer offset and the wrapped offset, but the wrapped offset is
11311 	 *   _less_ than the buffer offset.  This can only happen because a
11312 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11313 	 *   was not subsequently consumed.  In this case, we need to zero the
11314 	 *   space from the offset to the end of the buffer _and_ from the
11315 	 *   top of the buffer to the wrapped offset.
11316 	 */
11317 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11318 		bzero(buf->dtb_tomax + buf->dtb_offset,
11319 		    buf->dtb_xamot_offset - buf->dtb_offset);
11320 	}
11321 
11322 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11323 		bzero(buf->dtb_tomax + buf->dtb_offset,
11324 		    buf->dtb_size - buf->dtb_offset);
11325 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11326 	}
11327 }
11328 
11329 /*
11330  * This routine determines if data generated at the specified time has likely
11331  * been entirely consumed at user-level.  This routine is called to determine
11332  * if an ECB on a defunct probe (but for an active enabling) can be safely
11333  * disabled and destroyed.
11334  */
11335 static int
11336 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11337 {
11338 	int i;
11339 
11340 	for (i = 0; i < NCPU; i++) {
11341 		dtrace_buffer_t *buf = &bufs[i];
11342 
11343 		if (buf->dtb_size == 0)
11344 			continue;
11345 
11346 		if (buf->dtb_flags & DTRACEBUF_RING)
11347 			return (0);
11348 
11349 		if (!buf->dtb_switched && buf->dtb_offset != 0)
11350 			return (0);
11351 
11352 		if (buf->dtb_switched - buf->dtb_interval < when)
11353 			return (0);
11354 	}
11355 
11356 	return (1);
11357 }
11358 
11359 static void
11360 dtrace_buffer_free(dtrace_buffer_t *bufs)
11361 {
11362 	int i;
11363 
11364 	for (i = 0; i < NCPU; i++) {
11365 		dtrace_buffer_t *buf = &bufs[i];
11366 
11367 		if (buf->dtb_tomax == NULL) {
11368 			ASSERT(buf->dtb_xamot == NULL);
11369 			ASSERT(buf->dtb_size == 0);
11370 			continue;
11371 		}
11372 
11373 		if (buf->dtb_xamot != NULL) {
11374 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11375 			kmem_free(buf->dtb_xamot, buf->dtb_size);
11376 		}
11377 
11378 		kmem_free(buf->dtb_tomax, buf->dtb_size);
11379 		buf->dtb_size = 0;
11380 		buf->dtb_tomax = NULL;
11381 		buf->dtb_xamot = NULL;
11382 	}
11383 }
11384 
11385 /*
11386  * DTrace Enabling Functions
11387  */
11388 static dtrace_enabling_t *
11389 dtrace_enabling_create(dtrace_vstate_t *vstate)
11390 {
11391 	dtrace_enabling_t *enab;
11392 
11393 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11394 	enab->dten_vstate = vstate;
11395 
11396 	return (enab);
11397 }
11398 
11399 static void
11400 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11401 {
11402 	dtrace_ecbdesc_t **ndesc;
11403 	size_t osize, nsize;
11404 
11405 	/*
11406 	 * We can't add to enablings after we've enabled them, or after we've
11407 	 * retained them.
11408 	 */
11409 	ASSERT(enab->dten_probegen == 0);
11410 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11411 
11412 	if (enab->dten_ndesc < enab->dten_maxdesc) {
11413 		enab->dten_desc[enab->dten_ndesc++] = ecb;
11414 		return;
11415 	}
11416 
11417 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11418 
11419 	if (enab->dten_maxdesc == 0) {
11420 		enab->dten_maxdesc = 1;
11421 	} else {
11422 		enab->dten_maxdesc <<= 1;
11423 	}
11424 
11425 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11426 
11427 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11428 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
11429 	bcopy(enab->dten_desc, ndesc, osize);
11430 	if (enab->dten_desc != NULL)
11431 		kmem_free(enab->dten_desc, osize);
11432 
11433 	enab->dten_desc = ndesc;
11434 	enab->dten_desc[enab->dten_ndesc++] = ecb;
11435 }
11436 
11437 static void
11438 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11439     dtrace_probedesc_t *pd)
11440 {
11441 	dtrace_ecbdesc_t *new;
11442 	dtrace_predicate_t *pred;
11443 	dtrace_actdesc_t *act;
11444 
11445 	/*
11446 	 * We're going to create a new ECB description that matches the
11447 	 * specified ECB in every way, but has the specified probe description.
11448 	 */
11449 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11450 
11451 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11452 		dtrace_predicate_hold(pred);
11453 
11454 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11455 		dtrace_actdesc_hold(act);
11456 
11457 	new->dted_action = ecb->dted_action;
11458 	new->dted_pred = ecb->dted_pred;
11459 	new->dted_probe = *pd;
11460 	new->dted_uarg = ecb->dted_uarg;
11461 
11462 	dtrace_enabling_add(enab, new);
11463 }
11464 
11465 static void
11466 dtrace_enabling_dump(dtrace_enabling_t *enab)
11467 {
11468 	int i;
11469 
11470 	for (i = 0; i < enab->dten_ndesc; i++) {
11471 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11472 
11473 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11474 		    desc->dtpd_provider, desc->dtpd_mod,
11475 		    desc->dtpd_func, desc->dtpd_name);
11476 	}
11477 }
11478 
11479 static void
11480 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11481 {
11482 	int i;
11483 	dtrace_ecbdesc_t *ep;
11484 	dtrace_vstate_t *vstate = enab->dten_vstate;
11485 
11486 	ASSERT(MUTEX_HELD(&dtrace_lock));
11487 
11488 	for (i = 0; i < enab->dten_ndesc; i++) {
11489 		dtrace_actdesc_t *act, *next;
11490 		dtrace_predicate_t *pred;
11491 
11492 		ep = enab->dten_desc[i];
11493 
11494 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11495 			dtrace_predicate_release(pred, vstate);
11496 
11497 		for (act = ep->dted_action; act != NULL; act = next) {
11498 			next = act->dtad_next;
11499 			dtrace_actdesc_release(act, vstate);
11500 		}
11501 
11502 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11503 	}
11504 
11505 	if (enab->dten_desc != NULL)
11506 		kmem_free(enab->dten_desc,
11507 		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11508 
11509 	/*
11510 	 * If this was a retained enabling, decrement the dts_nretained count
11511 	 * and take it off of the dtrace_retained list.
11512 	 */
11513 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11514 	    dtrace_retained == enab) {
11515 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11516 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11517 		enab->dten_vstate->dtvs_state->dts_nretained--;
11518 	}
11519 
11520 	if (enab->dten_prev == NULL) {
11521 		if (dtrace_retained == enab) {
11522 			dtrace_retained = enab->dten_next;
11523 
11524 			if (dtrace_retained != NULL)
11525 				dtrace_retained->dten_prev = NULL;
11526 		}
11527 	} else {
11528 		ASSERT(enab != dtrace_retained);
11529 		ASSERT(dtrace_retained != NULL);
11530 		enab->dten_prev->dten_next = enab->dten_next;
11531 	}
11532 
11533 	if (enab->dten_next != NULL) {
11534 		ASSERT(dtrace_retained != NULL);
11535 		enab->dten_next->dten_prev = enab->dten_prev;
11536 	}
11537 
11538 	kmem_free(enab, sizeof (dtrace_enabling_t));
11539 }
11540 
11541 static int
11542 dtrace_enabling_retain(dtrace_enabling_t *enab)
11543 {
11544 	dtrace_state_t *state;
11545 
11546 	ASSERT(MUTEX_HELD(&dtrace_lock));
11547 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11548 	ASSERT(enab->dten_vstate != NULL);
11549 
11550 	state = enab->dten_vstate->dtvs_state;
11551 	ASSERT(state != NULL);
11552 
11553 	/*
11554 	 * We only allow each state to retain dtrace_retain_max enablings.
11555 	 */
11556 	if (state->dts_nretained >= dtrace_retain_max)
11557 		return (ENOSPC);
11558 
11559 	state->dts_nretained++;
11560 
11561 	if (dtrace_retained == NULL) {
11562 		dtrace_retained = enab;
11563 		return (0);
11564 	}
11565 
11566 	enab->dten_next = dtrace_retained;
11567 	dtrace_retained->dten_prev = enab;
11568 	dtrace_retained = enab;
11569 
11570 	return (0);
11571 }
11572 
11573 static int
11574 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11575     dtrace_probedesc_t *create)
11576 {
11577 	dtrace_enabling_t *new, *enab;
11578 	int found = 0, err = ENOENT;
11579 
11580 	ASSERT(MUTEX_HELD(&dtrace_lock));
11581 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11582 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11583 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11584 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11585 
11586 	new = dtrace_enabling_create(&state->dts_vstate);
11587 
11588 	/*
11589 	 * Iterate over all retained enablings, looking for enablings that
11590 	 * match the specified state.
11591 	 */
11592 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11593 		int i;
11594 
11595 		/*
11596 		 * dtvs_state can only be NULL for helper enablings -- and
11597 		 * helper enablings can't be retained.
11598 		 */
11599 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11600 
11601 		if (enab->dten_vstate->dtvs_state != state)
11602 			continue;
11603 
11604 		/*
11605 		 * Now iterate over each probe description; we're looking for
11606 		 * an exact match to the specified probe description.
11607 		 */
11608 		for (i = 0; i < enab->dten_ndesc; i++) {
11609 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11610 			dtrace_probedesc_t *pd = &ep->dted_probe;
11611 
11612 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11613 				continue;
11614 
11615 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11616 				continue;
11617 
11618 			if (strcmp(pd->dtpd_func, match->dtpd_func))
11619 				continue;
11620 
11621 			if (strcmp(pd->dtpd_name, match->dtpd_name))
11622 				continue;
11623 
11624 			/*
11625 			 * We have a winning probe!  Add it to our growing
11626 			 * enabling.
11627 			 */
11628 			found = 1;
11629 			dtrace_enabling_addlike(new, ep, create);
11630 		}
11631 	}
11632 
11633 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11634 		dtrace_enabling_destroy(new);
11635 		return (err);
11636 	}
11637 
11638 	return (0);
11639 }
11640 
11641 static void
11642 dtrace_enabling_retract(dtrace_state_t *state)
11643 {
11644 	dtrace_enabling_t *enab, *next;
11645 
11646 	ASSERT(MUTEX_HELD(&dtrace_lock));
11647 
11648 	/*
11649 	 * Iterate over all retained enablings, destroy the enablings retained
11650 	 * for the specified state.
11651 	 */
11652 	for (enab = dtrace_retained; enab != NULL; enab = next) {
11653 		next = enab->dten_next;
11654 
11655 		/*
11656 		 * dtvs_state can only be NULL for helper enablings -- and
11657 		 * helper enablings can't be retained.
11658 		 */
11659 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11660 
11661 		if (enab->dten_vstate->dtvs_state == state) {
11662 			ASSERT(state->dts_nretained > 0);
11663 			dtrace_enabling_destroy(enab);
11664 		}
11665 	}
11666 
11667 	ASSERT(state->dts_nretained == 0);
11668 }
11669 
11670 static int
11671 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11672 {
11673 	int i = 0;
11674 	int matched = 0;
11675 
11676 	ASSERT(MUTEX_HELD(&cpu_lock));
11677 	ASSERT(MUTEX_HELD(&dtrace_lock));
11678 
11679 	for (i = 0; i < enab->dten_ndesc; i++) {
11680 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11681 
11682 		enab->dten_current = ep;
11683 		enab->dten_error = 0;
11684 
11685 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
11686 
11687 		if (enab->dten_error != 0) {
11688 			/*
11689 			 * If we get an error half-way through enabling the
11690 			 * probes, we kick out -- perhaps with some number of
11691 			 * them enabled.  Leaving enabled probes enabled may
11692 			 * be slightly confusing for user-level, but we expect
11693 			 * that no one will attempt to actually drive on in
11694 			 * the face of such errors.  If this is an anonymous
11695 			 * enabling (indicated with a NULL nmatched pointer),
11696 			 * we cmn_err() a message.  We aren't expecting to
11697 			 * get such an error -- such as it can exist at all,
11698 			 * it would be a result of corrupted DOF in the driver
11699 			 * properties.
11700 			 */
11701 			if (nmatched == NULL) {
11702 				cmn_err(CE_WARN, "dtrace_enabling_match() "
11703 				    "error on %p: %d", (void *)ep,
11704 				    enab->dten_error);
11705 			}
11706 
11707 			return (enab->dten_error);
11708 		}
11709 	}
11710 
11711 	enab->dten_probegen = dtrace_probegen;
11712 	if (nmatched != NULL)
11713 		*nmatched = matched;
11714 
11715 	return (0);
11716 }
11717 
11718 static void
11719 dtrace_enabling_matchall(void)
11720 {
11721 	dtrace_enabling_t *enab;
11722 
11723 	mutex_enter(&cpu_lock);
11724 	mutex_enter(&dtrace_lock);
11725 
11726 	/*
11727 	 * Iterate over all retained enablings to see if any probes match
11728 	 * against them.  We only perform this operation on enablings for which
11729 	 * we have sufficient permissions by virtue of being in the global zone
11730 	 * or in the same zone as the DTrace client.  Because we can be called
11731 	 * after dtrace_detach() has been called, we cannot assert that there
11732 	 * are retained enablings.  We can safely load from dtrace_retained,
11733 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
11734 	 * block pending our completion.
11735 	 */
11736 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11737 #if defined(sun)
11738 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11739 
11740 		if (INGLOBALZONE(curproc) ||
11741 		    cr != NULL && getzoneid() == crgetzoneid(cr))
11742 #endif
11743 			(void) dtrace_enabling_match(enab, NULL);
11744 	}
11745 
11746 	mutex_exit(&dtrace_lock);
11747 	mutex_exit(&cpu_lock);
11748 }
11749 
11750 /*
11751  * If an enabling is to be enabled without having matched probes (that is, if
11752  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11753  * enabling must be _primed_ by creating an ECB for every ECB description.
11754  * This must be done to assure that we know the number of speculations, the
11755  * number of aggregations, the minimum buffer size needed, etc. before we
11756  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11757  * enabling any probes, we create ECBs for every ECB decription, but with a
11758  * NULL probe -- which is exactly what this function does.
11759  */
11760 static void
11761 dtrace_enabling_prime(dtrace_state_t *state)
11762 {
11763 	dtrace_enabling_t *enab;
11764 	int i;
11765 
11766 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11767 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11768 
11769 		if (enab->dten_vstate->dtvs_state != state)
11770 			continue;
11771 
11772 		/*
11773 		 * We don't want to prime an enabling more than once, lest
11774 		 * we allow a malicious user to induce resource exhaustion.
11775 		 * (The ECBs that result from priming an enabling aren't
11776 		 * leaked -- but they also aren't deallocated until the
11777 		 * consumer state is destroyed.)
11778 		 */
11779 		if (enab->dten_primed)
11780 			continue;
11781 
11782 		for (i = 0; i < enab->dten_ndesc; i++) {
11783 			enab->dten_current = enab->dten_desc[i];
11784 			(void) dtrace_probe_enable(NULL, enab);
11785 		}
11786 
11787 		enab->dten_primed = 1;
11788 	}
11789 }
11790 
11791 /*
11792  * Called to indicate that probes should be provided due to retained
11793  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11794  * must take an initial lap through the enabling calling the dtps_provide()
11795  * entry point explicitly to allow for autocreated probes.
11796  */
11797 static void
11798 dtrace_enabling_provide(dtrace_provider_t *prv)
11799 {
11800 	int i, all = 0;
11801 	dtrace_probedesc_t desc;
11802 
11803 	ASSERT(MUTEX_HELD(&dtrace_lock));
11804 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11805 
11806 	if (prv == NULL) {
11807 		all = 1;
11808 		prv = dtrace_provider;
11809 	}
11810 
11811 	do {
11812 		dtrace_enabling_t *enab = dtrace_retained;
11813 		void *parg = prv->dtpv_arg;
11814 
11815 		for (; enab != NULL; enab = enab->dten_next) {
11816 			for (i = 0; i < enab->dten_ndesc; i++) {
11817 				desc = enab->dten_desc[i]->dted_probe;
11818 				mutex_exit(&dtrace_lock);
11819 				prv->dtpv_pops.dtps_provide(parg, &desc);
11820 				mutex_enter(&dtrace_lock);
11821 			}
11822 		}
11823 	} while (all && (prv = prv->dtpv_next) != NULL);
11824 
11825 	mutex_exit(&dtrace_lock);
11826 	dtrace_probe_provide(NULL, all ? NULL : prv);
11827 	mutex_enter(&dtrace_lock);
11828 }
11829 
11830 /*
11831  * Called to reap ECBs that are attached to probes from defunct providers.
11832  */
11833 static void
11834 dtrace_enabling_reap(void)
11835 {
11836 	dtrace_provider_t *prov;
11837 	dtrace_probe_t *probe;
11838 	dtrace_ecb_t *ecb;
11839 	hrtime_t when;
11840 	int i;
11841 
11842 	mutex_enter(&cpu_lock);
11843 	mutex_enter(&dtrace_lock);
11844 
11845 	for (i = 0; i < dtrace_nprobes; i++) {
11846 		if ((probe = dtrace_probes[i]) == NULL)
11847 			continue;
11848 
11849 		if (probe->dtpr_ecb == NULL)
11850 			continue;
11851 
11852 		prov = probe->dtpr_provider;
11853 
11854 		if ((when = prov->dtpv_defunct) == 0)
11855 			continue;
11856 
11857 		/*
11858 		 * We have ECBs on a defunct provider:  we want to reap these
11859 		 * ECBs to allow the provider to unregister.  The destruction
11860 		 * of these ECBs must be done carefully:  if we destroy the ECB
11861 		 * and the consumer later wishes to consume an EPID that
11862 		 * corresponds to the destroyed ECB (and if the EPID metadata
11863 		 * has not been previously consumed), the consumer will abort
11864 		 * processing on the unknown EPID.  To reduce (but not, sadly,
11865 		 * eliminate) the possibility of this, we will only destroy an
11866 		 * ECB for a defunct provider if, for the state that
11867 		 * corresponds to the ECB:
11868 		 *
11869 		 *  (a)	There is no speculative tracing (which can effectively
11870 		 *	cache an EPID for an arbitrary amount of time).
11871 		 *
11872 		 *  (b)	The principal buffers have been switched twice since the
11873 		 *	provider became defunct.
11874 		 *
11875 		 *  (c)	The aggregation buffers are of zero size or have been
11876 		 *	switched twice since the provider became defunct.
11877 		 *
11878 		 * We use dts_speculates to determine (a) and call a function
11879 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
11880 		 * that as soon as we've been unable to destroy one of the ECBs
11881 		 * associated with the probe, we quit trying -- reaping is only
11882 		 * fruitful in as much as we can destroy all ECBs associated
11883 		 * with the defunct provider's probes.
11884 		 */
11885 		while ((ecb = probe->dtpr_ecb) != NULL) {
11886 			dtrace_state_t *state = ecb->dte_state;
11887 			dtrace_buffer_t *buf = state->dts_buffer;
11888 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11889 
11890 			if (state->dts_speculates)
11891 				break;
11892 
11893 			if (!dtrace_buffer_consumed(buf, when))
11894 				break;
11895 
11896 			if (!dtrace_buffer_consumed(aggbuf, when))
11897 				break;
11898 
11899 			dtrace_ecb_disable(ecb);
11900 			ASSERT(probe->dtpr_ecb != ecb);
11901 			dtrace_ecb_destroy(ecb);
11902 		}
11903 	}
11904 
11905 	mutex_exit(&dtrace_lock);
11906 	mutex_exit(&cpu_lock);
11907 }
11908 
11909 /*
11910  * DTrace DOF Functions
11911  */
11912 /*ARGSUSED*/
11913 static void
11914 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11915 {
11916 	if (dtrace_err_verbose)
11917 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
11918 
11919 #ifdef DTRACE_ERRDEBUG
11920 	dtrace_errdebug(str);
11921 #endif
11922 }
11923 
11924 /*
11925  * Create DOF out of a currently enabled state.  Right now, we only create
11926  * DOF containing the run-time options -- but this could be expanded to create
11927  * complete DOF representing the enabled state.
11928  */
11929 static dof_hdr_t *
11930 dtrace_dof_create(dtrace_state_t *state)
11931 {
11932 	dof_hdr_t *dof;
11933 	dof_sec_t *sec;
11934 	dof_optdesc_t *opt;
11935 	int i, len = sizeof (dof_hdr_t) +
11936 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11937 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11938 
11939 	ASSERT(MUTEX_HELD(&dtrace_lock));
11940 
11941 	dof = kmem_zalloc(len, KM_SLEEP);
11942 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11943 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11944 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11945 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11946 
11947 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11948 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11949 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11950 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11951 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11952 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11953 
11954 	dof->dofh_flags = 0;
11955 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
11956 	dof->dofh_secsize = sizeof (dof_sec_t);
11957 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
11958 	dof->dofh_secoff = sizeof (dof_hdr_t);
11959 	dof->dofh_loadsz = len;
11960 	dof->dofh_filesz = len;
11961 	dof->dofh_pad = 0;
11962 
11963 	/*
11964 	 * Fill in the option section header...
11965 	 */
11966 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11967 	sec->dofs_type = DOF_SECT_OPTDESC;
11968 	sec->dofs_align = sizeof (uint64_t);
11969 	sec->dofs_flags = DOF_SECF_LOAD;
11970 	sec->dofs_entsize = sizeof (dof_optdesc_t);
11971 
11972 	opt = (dof_optdesc_t *)((uintptr_t)sec +
11973 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11974 
11975 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11976 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11977 
11978 	for (i = 0; i < DTRACEOPT_MAX; i++) {
11979 		opt[i].dofo_option = i;
11980 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
11981 		opt[i].dofo_value = state->dts_options[i];
11982 	}
11983 
11984 	return (dof);
11985 }
11986 
11987 static dof_hdr_t *
11988 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11989 {
11990 	dof_hdr_t hdr, *dof;
11991 
11992 	ASSERT(!MUTEX_HELD(&dtrace_lock));
11993 
11994 	/*
11995 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
11996 	 */
11997 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11998 		dtrace_dof_error(NULL, "failed to copyin DOF header");
11999 		*errp = EFAULT;
12000 		return (NULL);
12001 	}
12002 
12003 	/*
12004 	 * Now we'll allocate the entire DOF and copy it in -- provided
12005 	 * that the length isn't outrageous.
12006 	 */
12007 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12008 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12009 		*errp = E2BIG;
12010 		return (NULL);
12011 	}
12012 
12013 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12014 		dtrace_dof_error(&hdr, "invalid load size");
12015 		*errp = EINVAL;
12016 		return (NULL);
12017 	}
12018 
12019 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12020 
12021 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
12022 		kmem_free(dof, hdr.dofh_loadsz);
12023 		*errp = EFAULT;
12024 		return (NULL);
12025 	}
12026 
12027 	return (dof);
12028 }
12029 
12030 #if !defined(sun)
12031 static __inline uchar_t
12032 dtrace_dof_char(char c) {
12033 	switch (c) {
12034 	case '0':
12035 	case '1':
12036 	case '2':
12037 	case '3':
12038 	case '4':
12039 	case '5':
12040 	case '6':
12041 	case '7':
12042 	case '8':
12043 	case '9':
12044 		return (c - '0');
12045 	case 'A':
12046 	case 'B':
12047 	case 'C':
12048 	case 'D':
12049 	case 'E':
12050 	case 'F':
12051 		return (c - 'A' + 10);
12052 	case 'a':
12053 	case 'b':
12054 	case 'c':
12055 	case 'd':
12056 	case 'e':
12057 	case 'f':
12058 		return (c - 'a' + 10);
12059 	}
12060 	/* Should not reach here. */
12061 	return (0);
12062 }
12063 #endif
12064 
12065 static dof_hdr_t *
12066 dtrace_dof_property(const char *name)
12067 {
12068 	uchar_t *buf;
12069 	uint64_t loadsz;
12070 	unsigned int len, i;
12071 	dof_hdr_t *dof;
12072 
12073 #if defined(sun)
12074 	/*
12075 	 * Unfortunately, array of values in .conf files are always (and
12076 	 * only) interpreted to be integer arrays.  We must read our DOF
12077 	 * as an integer array, and then squeeze it into a byte array.
12078 	 */
12079 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12080 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12081 		return (NULL);
12082 
12083 	for (i = 0; i < len; i++)
12084 		buf[i] = (uchar_t)(((int *)buf)[i]);
12085 
12086 	if (len < sizeof (dof_hdr_t)) {
12087 		ddi_prop_free(buf);
12088 		dtrace_dof_error(NULL, "truncated header");
12089 		return (NULL);
12090 	}
12091 
12092 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12093 		ddi_prop_free(buf);
12094 		dtrace_dof_error(NULL, "truncated DOF");
12095 		return (NULL);
12096 	}
12097 
12098 	if (loadsz >= dtrace_dof_maxsize) {
12099 		ddi_prop_free(buf);
12100 		dtrace_dof_error(NULL, "oversized DOF");
12101 		return (NULL);
12102 	}
12103 
12104 	dof = kmem_alloc(loadsz, KM_SLEEP);
12105 	bcopy(buf, dof, loadsz);
12106 	ddi_prop_free(buf);
12107 #else
12108 	char *p;
12109 	char *p_env;
12110 
12111 	if ((p_env = getenv(name)) == NULL)
12112 		return (NULL);
12113 
12114 	len = strlen(p_env) / 2;
12115 
12116 	buf = kmem_alloc(len, KM_SLEEP);
12117 
12118 	dof = (dof_hdr_t *) buf;
12119 
12120 	p = p_env;
12121 
12122 	for (i = 0; i < len; i++) {
12123 		buf[i] = (dtrace_dof_char(p[0]) << 4) |
12124 		     dtrace_dof_char(p[1]);
12125 		p += 2;
12126 	}
12127 
12128 	freeenv(p_env);
12129 
12130 	if (len < sizeof (dof_hdr_t)) {
12131 		kmem_free(buf, 0);
12132 		dtrace_dof_error(NULL, "truncated header");
12133 		return (NULL);
12134 	}
12135 
12136 	if (len < (loadsz = dof->dofh_loadsz)) {
12137 		kmem_free(buf, 0);
12138 		dtrace_dof_error(NULL, "truncated DOF");
12139 		return (NULL);
12140 	}
12141 
12142 	if (loadsz >= dtrace_dof_maxsize) {
12143 		kmem_free(buf, 0);
12144 		dtrace_dof_error(NULL, "oversized DOF");
12145 		return (NULL);
12146 	}
12147 #endif
12148 
12149 	return (dof);
12150 }
12151 
12152 static void
12153 dtrace_dof_destroy(dof_hdr_t *dof)
12154 {
12155 	kmem_free(dof, dof->dofh_loadsz);
12156 }
12157 
12158 /*
12159  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12160  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12161  * a type other than DOF_SECT_NONE is specified, the header is checked against
12162  * this type and NULL is returned if the types do not match.
12163  */
12164 static dof_sec_t *
12165 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12166 {
12167 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12168 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12169 
12170 	if (i >= dof->dofh_secnum) {
12171 		dtrace_dof_error(dof, "referenced section index is invalid");
12172 		return (NULL);
12173 	}
12174 
12175 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12176 		dtrace_dof_error(dof, "referenced section is not loadable");
12177 		return (NULL);
12178 	}
12179 
12180 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12181 		dtrace_dof_error(dof, "referenced section is the wrong type");
12182 		return (NULL);
12183 	}
12184 
12185 	return (sec);
12186 }
12187 
12188 static dtrace_probedesc_t *
12189 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12190 {
12191 	dof_probedesc_t *probe;
12192 	dof_sec_t *strtab;
12193 	uintptr_t daddr = (uintptr_t)dof;
12194 	uintptr_t str;
12195 	size_t size;
12196 
12197 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12198 		dtrace_dof_error(dof, "invalid probe section");
12199 		return (NULL);
12200 	}
12201 
12202 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12203 		dtrace_dof_error(dof, "bad alignment in probe description");
12204 		return (NULL);
12205 	}
12206 
12207 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12208 		dtrace_dof_error(dof, "truncated probe description");
12209 		return (NULL);
12210 	}
12211 
12212 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12213 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12214 
12215 	if (strtab == NULL)
12216 		return (NULL);
12217 
12218 	str = daddr + strtab->dofs_offset;
12219 	size = strtab->dofs_size;
12220 
12221 	if (probe->dofp_provider >= strtab->dofs_size) {
12222 		dtrace_dof_error(dof, "corrupt probe provider");
12223 		return (NULL);
12224 	}
12225 
12226 	(void) strncpy(desc->dtpd_provider,
12227 	    (char *)(str + probe->dofp_provider),
12228 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12229 
12230 	if (probe->dofp_mod >= strtab->dofs_size) {
12231 		dtrace_dof_error(dof, "corrupt probe module");
12232 		return (NULL);
12233 	}
12234 
12235 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12236 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12237 
12238 	if (probe->dofp_func >= strtab->dofs_size) {
12239 		dtrace_dof_error(dof, "corrupt probe function");
12240 		return (NULL);
12241 	}
12242 
12243 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12244 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12245 
12246 	if (probe->dofp_name >= strtab->dofs_size) {
12247 		dtrace_dof_error(dof, "corrupt probe name");
12248 		return (NULL);
12249 	}
12250 
12251 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12252 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12253 
12254 	return (desc);
12255 }
12256 
12257 static dtrace_difo_t *
12258 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12259     cred_t *cr)
12260 {
12261 	dtrace_difo_t *dp;
12262 	size_t ttl = 0;
12263 	dof_difohdr_t *dofd;
12264 	uintptr_t daddr = (uintptr_t)dof;
12265 	size_t max = dtrace_difo_maxsize;
12266 	int i, l, n;
12267 
12268 	static const struct {
12269 		int section;
12270 		int bufoffs;
12271 		int lenoffs;
12272 		int entsize;
12273 		int align;
12274 		const char *msg;
12275 	} difo[] = {
12276 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12277 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12278 		sizeof (dif_instr_t), "multiple DIF sections" },
12279 
12280 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12281 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12282 		sizeof (uint64_t), "multiple integer tables" },
12283 
12284 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12285 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12286 		sizeof (char), "multiple string tables" },
12287 
12288 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12289 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12290 		sizeof (uint_t), "multiple variable tables" },
12291 
12292 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12293 	};
12294 
12295 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12296 		dtrace_dof_error(dof, "invalid DIFO header section");
12297 		return (NULL);
12298 	}
12299 
12300 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12301 		dtrace_dof_error(dof, "bad alignment in DIFO header");
12302 		return (NULL);
12303 	}
12304 
12305 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12306 	    sec->dofs_size % sizeof (dof_secidx_t)) {
12307 		dtrace_dof_error(dof, "bad size in DIFO header");
12308 		return (NULL);
12309 	}
12310 
12311 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12312 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12313 
12314 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12315 	dp->dtdo_rtype = dofd->dofd_rtype;
12316 
12317 	for (l = 0; l < n; l++) {
12318 		dof_sec_t *subsec;
12319 		void **bufp;
12320 		uint32_t *lenp;
12321 
12322 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12323 		    dofd->dofd_links[l])) == NULL)
12324 			goto err; /* invalid section link */
12325 
12326 		if (ttl + subsec->dofs_size > max) {
12327 			dtrace_dof_error(dof, "exceeds maximum size");
12328 			goto err;
12329 		}
12330 
12331 		ttl += subsec->dofs_size;
12332 
12333 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12334 			if (subsec->dofs_type != difo[i].section)
12335 				continue;
12336 
12337 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12338 				dtrace_dof_error(dof, "section not loaded");
12339 				goto err;
12340 			}
12341 
12342 			if (subsec->dofs_align != difo[i].align) {
12343 				dtrace_dof_error(dof, "bad alignment");
12344 				goto err;
12345 			}
12346 
12347 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12348 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12349 
12350 			if (*bufp != NULL) {
12351 				dtrace_dof_error(dof, difo[i].msg);
12352 				goto err;
12353 			}
12354 
12355 			if (difo[i].entsize != subsec->dofs_entsize) {
12356 				dtrace_dof_error(dof, "entry size mismatch");
12357 				goto err;
12358 			}
12359 
12360 			if (subsec->dofs_entsize != 0 &&
12361 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12362 				dtrace_dof_error(dof, "corrupt entry size");
12363 				goto err;
12364 			}
12365 
12366 			*lenp = subsec->dofs_size;
12367 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12368 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12369 			    *bufp, subsec->dofs_size);
12370 
12371 			if (subsec->dofs_entsize != 0)
12372 				*lenp /= subsec->dofs_entsize;
12373 
12374 			break;
12375 		}
12376 
12377 		/*
12378 		 * If we encounter a loadable DIFO sub-section that is not
12379 		 * known to us, assume this is a broken program and fail.
12380 		 */
12381 		if (difo[i].section == DOF_SECT_NONE &&
12382 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12383 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12384 			goto err;
12385 		}
12386 	}
12387 
12388 	if (dp->dtdo_buf == NULL) {
12389 		/*
12390 		 * We can't have a DIF object without DIF text.
12391 		 */
12392 		dtrace_dof_error(dof, "missing DIF text");
12393 		goto err;
12394 	}
12395 
12396 	/*
12397 	 * Before we validate the DIF object, run through the variable table
12398 	 * looking for the strings -- if any of their size are under, we'll set
12399 	 * their size to be the system-wide default string size.  Note that
12400 	 * this should _not_ happen if the "strsize" option has been set --
12401 	 * in this case, the compiler should have set the size to reflect the
12402 	 * setting of the option.
12403 	 */
12404 	for (i = 0; i < dp->dtdo_varlen; i++) {
12405 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
12406 		dtrace_diftype_t *t = &v->dtdv_type;
12407 
12408 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12409 			continue;
12410 
12411 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12412 			t->dtdt_size = dtrace_strsize_default;
12413 	}
12414 
12415 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12416 		goto err;
12417 
12418 	dtrace_difo_init(dp, vstate);
12419 	return (dp);
12420 
12421 err:
12422 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12423 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12424 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12425 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12426 
12427 	kmem_free(dp, sizeof (dtrace_difo_t));
12428 	return (NULL);
12429 }
12430 
12431 static dtrace_predicate_t *
12432 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12433     cred_t *cr)
12434 {
12435 	dtrace_difo_t *dp;
12436 
12437 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12438 		return (NULL);
12439 
12440 	return (dtrace_predicate_create(dp));
12441 }
12442 
12443 static dtrace_actdesc_t *
12444 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12445     cred_t *cr)
12446 {
12447 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12448 	dof_actdesc_t *desc;
12449 	dof_sec_t *difosec;
12450 	size_t offs;
12451 	uintptr_t daddr = (uintptr_t)dof;
12452 	uint64_t arg;
12453 	dtrace_actkind_t kind;
12454 
12455 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
12456 		dtrace_dof_error(dof, "invalid action section");
12457 		return (NULL);
12458 	}
12459 
12460 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12461 		dtrace_dof_error(dof, "truncated action description");
12462 		return (NULL);
12463 	}
12464 
12465 	if (sec->dofs_align != sizeof (uint64_t)) {
12466 		dtrace_dof_error(dof, "bad alignment in action description");
12467 		return (NULL);
12468 	}
12469 
12470 	if (sec->dofs_size < sec->dofs_entsize) {
12471 		dtrace_dof_error(dof, "section entry size exceeds total size");
12472 		return (NULL);
12473 	}
12474 
12475 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12476 		dtrace_dof_error(dof, "bad entry size in action description");
12477 		return (NULL);
12478 	}
12479 
12480 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12481 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12482 		return (NULL);
12483 	}
12484 
12485 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12486 		desc = (dof_actdesc_t *)(daddr +
12487 		    (uintptr_t)sec->dofs_offset + offs);
12488 		kind = (dtrace_actkind_t)desc->dofa_kind;
12489 
12490 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12491 		    (kind != DTRACEACT_PRINTA ||
12492 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12493 		    (kind == DTRACEACT_DIFEXPR &&
12494 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
12495 			dof_sec_t *strtab;
12496 			char *str, *fmt;
12497 			uint64_t i;
12498 
12499 			/*
12500 			 * The argument to these actions is an index into the
12501 			 * DOF string table.  For printf()-like actions, this
12502 			 * is the format string.  For print(), this is the
12503 			 * CTF type of the expression result.
12504 			 */
12505 			if ((strtab = dtrace_dof_sect(dof,
12506 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12507 				goto err;
12508 
12509 			str = (char *)((uintptr_t)dof +
12510 			    (uintptr_t)strtab->dofs_offset);
12511 
12512 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12513 				if (str[i] == '\0')
12514 					break;
12515 			}
12516 
12517 			if (i >= strtab->dofs_size) {
12518 				dtrace_dof_error(dof, "bogus format string");
12519 				goto err;
12520 			}
12521 
12522 			if (i == desc->dofa_arg) {
12523 				dtrace_dof_error(dof, "empty format string");
12524 				goto err;
12525 			}
12526 
12527 			i -= desc->dofa_arg;
12528 			fmt = kmem_alloc(i + 1, KM_SLEEP);
12529 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
12530 			arg = (uint64_t)(uintptr_t)fmt;
12531 		} else {
12532 			if (kind == DTRACEACT_PRINTA) {
12533 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12534 				arg = 0;
12535 			} else {
12536 				arg = desc->dofa_arg;
12537 			}
12538 		}
12539 
12540 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12541 		    desc->dofa_uarg, arg);
12542 
12543 		if (last != NULL) {
12544 			last->dtad_next = act;
12545 		} else {
12546 			first = act;
12547 		}
12548 
12549 		last = act;
12550 
12551 		if (desc->dofa_difo == DOF_SECIDX_NONE)
12552 			continue;
12553 
12554 		if ((difosec = dtrace_dof_sect(dof,
12555 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12556 			goto err;
12557 
12558 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12559 
12560 		if (act->dtad_difo == NULL)
12561 			goto err;
12562 	}
12563 
12564 	ASSERT(first != NULL);
12565 	return (first);
12566 
12567 err:
12568 	for (act = first; act != NULL; act = next) {
12569 		next = act->dtad_next;
12570 		dtrace_actdesc_release(act, vstate);
12571 	}
12572 
12573 	return (NULL);
12574 }
12575 
12576 static dtrace_ecbdesc_t *
12577 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12578     cred_t *cr)
12579 {
12580 	dtrace_ecbdesc_t *ep;
12581 	dof_ecbdesc_t *ecb;
12582 	dtrace_probedesc_t *desc;
12583 	dtrace_predicate_t *pred = NULL;
12584 
12585 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12586 		dtrace_dof_error(dof, "truncated ECB description");
12587 		return (NULL);
12588 	}
12589 
12590 	if (sec->dofs_align != sizeof (uint64_t)) {
12591 		dtrace_dof_error(dof, "bad alignment in ECB description");
12592 		return (NULL);
12593 	}
12594 
12595 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12596 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12597 
12598 	if (sec == NULL)
12599 		return (NULL);
12600 
12601 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12602 	ep->dted_uarg = ecb->dofe_uarg;
12603 	desc = &ep->dted_probe;
12604 
12605 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12606 		goto err;
12607 
12608 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12609 		if ((sec = dtrace_dof_sect(dof,
12610 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12611 			goto err;
12612 
12613 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12614 			goto err;
12615 
12616 		ep->dted_pred.dtpdd_predicate = pred;
12617 	}
12618 
12619 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12620 		if ((sec = dtrace_dof_sect(dof,
12621 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12622 			goto err;
12623 
12624 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12625 
12626 		if (ep->dted_action == NULL)
12627 			goto err;
12628 	}
12629 
12630 	return (ep);
12631 
12632 err:
12633 	if (pred != NULL)
12634 		dtrace_predicate_release(pred, vstate);
12635 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12636 	return (NULL);
12637 }
12638 
12639 /*
12640  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12641  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12642  * site of any user SETX relocations to account for load object base address.
12643  * In the future, if we need other relocations, this function can be extended.
12644  */
12645 static int
12646 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12647 {
12648 	uintptr_t daddr = (uintptr_t)dof;
12649 	dof_relohdr_t *dofr =
12650 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12651 	dof_sec_t *ss, *rs, *ts;
12652 	dof_relodesc_t *r;
12653 	uint_t i, n;
12654 
12655 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12656 	    sec->dofs_align != sizeof (dof_secidx_t)) {
12657 		dtrace_dof_error(dof, "invalid relocation header");
12658 		return (-1);
12659 	}
12660 
12661 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12662 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12663 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12664 
12665 	if (ss == NULL || rs == NULL || ts == NULL)
12666 		return (-1); /* dtrace_dof_error() has been called already */
12667 
12668 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12669 	    rs->dofs_align != sizeof (uint64_t)) {
12670 		dtrace_dof_error(dof, "invalid relocation section");
12671 		return (-1);
12672 	}
12673 
12674 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12675 	n = rs->dofs_size / rs->dofs_entsize;
12676 
12677 	for (i = 0; i < n; i++) {
12678 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12679 
12680 		switch (r->dofr_type) {
12681 		case DOF_RELO_NONE:
12682 			break;
12683 		case DOF_RELO_SETX:
12684 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12685 			    sizeof (uint64_t) > ts->dofs_size) {
12686 				dtrace_dof_error(dof, "bad relocation offset");
12687 				return (-1);
12688 			}
12689 
12690 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12691 				dtrace_dof_error(dof, "misaligned setx relo");
12692 				return (-1);
12693 			}
12694 
12695 			*(uint64_t *)taddr += ubase;
12696 			break;
12697 		default:
12698 			dtrace_dof_error(dof, "invalid relocation type");
12699 			return (-1);
12700 		}
12701 
12702 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12703 	}
12704 
12705 	return (0);
12706 }
12707 
12708 /*
12709  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12710  * header:  it should be at the front of a memory region that is at least
12711  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12712  * size.  It need not be validated in any other way.
12713  */
12714 static int
12715 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12716     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12717 {
12718 	uint64_t len = dof->dofh_loadsz, seclen;
12719 	uintptr_t daddr = (uintptr_t)dof;
12720 	dtrace_ecbdesc_t *ep;
12721 	dtrace_enabling_t *enab;
12722 	uint_t i;
12723 
12724 	ASSERT(MUTEX_HELD(&dtrace_lock));
12725 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12726 
12727 	/*
12728 	 * Check the DOF header identification bytes.  In addition to checking
12729 	 * valid settings, we also verify that unused bits/bytes are zeroed so
12730 	 * we can use them later without fear of regressing existing binaries.
12731 	 */
12732 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12733 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12734 		dtrace_dof_error(dof, "DOF magic string mismatch");
12735 		return (-1);
12736 	}
12737 
12738 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12739 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12740 		dtrace_dof_error(dof, "DOF has invalid data model");
12741 		return (-1);
12742 	}
12743 
12744 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12745 		dtrace_dof_error(dof, "DOF encoding mismatch");
12746 		return (-1);
12747 	}
12748 
12749 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12750 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12751 		dtrace_dof_error(dof, "DOF version mismatch");
12752 		return (-1);
12753 	}
12754 
12755 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12756 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12757 		return (-1);
12758 	}
12759 
12760 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12761 		dtrace_dof_error(dof, "DOF uses too many integer registers");
12762 		return (-1);
12763 	}
12764 
12765 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12766 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
12767 		return (-1);
12768 	}
12769 
12770 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12771 		if (dof->dofh_ident[i] != 0) {
12772 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
12773 			return (-1);
12774 		}
12775 	}
12776 
12777 	if (dof->dofh_flags & ~DOF_FL_VALID) {
12778 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
12779 		return (-1);
12780 	}
12781 
12782 	if (dof->dofh_secsize == 0) {
12783 		dtrace_dof_error(dof, "zero section header size");
12784 		return (-1);
12785 	}
12786 
12787 	/*
12788 	 * Check that the section headers don't exceed the amount of DOF
12789 	 * data.  Note that we cast the section size and number of sections
12790 	 * to uint64_t's to prevent possible overflow in the multiplication.
12791 	 */
12792 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12793 
12794 	if (dof->dofh_secoff > len || seclen > len ||
12795 	    dof->dofh_secoff + seclen > len) {
12796 		dtrace_dof_error(dof, "truncated section headers");
12797 		return (-1);
12798 	}
12799 
12800 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12801 		dtrace_dof_error(dof, "misaligned section headers");
12802 		return (-1);
12803 	}
12804 
12805 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12806 		dtrace_dof_error(dof, "misaligned section size");
12807 		return (-1);
12808 	}
12809 
12810 	/*
12811 	 * Take an initial pass through the section headers to be sure that
12812 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
12813 	 * set, do not permit sections relating to providers, probes, or args.
12814 	 */
12815 	for (i = 0; i < dof->dofh_secnum; i++) {
12816 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12817 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12818 
12819 		if (noprobes) {
12820 			switch (sec->dofs_type) {
12821 			case DOF_SECT_PROVIDER:
12822 			case DOF_SECT_PROBES:
12823 			case DOF_SECT_PRARGS:
12824 			case DOF_SECT_PROFFS:
12825 				dtrace_dof_error(dof, "illegal sections "
12826 				    "for enabling");
12827 				return (-1);
12828 			}
12829 		}
12830 
12831 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12832 			continue; /* just ignore non-loadable sections */
12833 
12834 		if (sec->dofs_align & (sec->dofs_align - 1)) {
12835 			dtrace_dof_error(dof, "bad section alignment");
12836 			return (-1);
12837 		}
12838 
12839 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
12840 			dtrace_dof_error(dof, "misaligned section");
12841 			return (-1);
12842 		}
12843 
12844 		if (sec->dofs_offset > len || sec->dofs_size > len ||
12845 		    sec->dofs_offset + sec->dofs_size > len) {
12846 			dtrace_dof_error(dof, "corrupt section header");
12847 			return (-1);
12848 		}
12849 
12850 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12851 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12852 			dtrace_dof_error(dof, "non-terminating string table");
12853 			return (-1);
12854 		}
12855 	}
12856 
12857 	/*
12858 	 * Take a second pass through the sections and locate and perform any
12859 	 * relocations that are present.  We do this after the first pass to
12860 	 * be sure that all sections have had their headers validated.
12861 	 */
12862 	for (i = 0; i < dof->dofh_secnum; i++) {
12863 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12864 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12865 
12866 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12867 			continue; /* skip sections that are not loadable */
12868 
12869 		switch (sec->dofs_type) {
12870 		case DOF_SECT_URELHDR:
12871 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12872 				return (-1);
12873 			break;
12874 		}
12875 	}
12876 
12877 	if ((enab = *enabp) == NULL)
12878 		enab = *enabp = dtrace_enabling_create(vstate);
12879 
12880 	for (i = 0; i < dof->dofh_secnum; i++) {
12881 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12882 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12883 
12884 		if (sec->dofs_type != DOF_SECT_ECBDESC)
12885 			continue;
12886 
12887 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12888 			dtrace_enabling_destroy(enab);
12889 			*enabp = NULL;
12890 			return (-1);
12891 		}
12892 
12893 		dtrace_enabling_add(enab, ep);
12894 	}
12895 
12896 	return (0);
12897 }
12898 
12899 /*
12900  * Process DOF for any options.  This routine assumes that the DOF has been
12901  * at least processed by dtrace_dof_slurp().
12902  */
12903 static int
12904 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12905 {
12906 	int i, rval;
12907 	uint32_t entsize;
12908 	size_t offs;
12909 	dof_optdesc_t *desc;
12910 
12911 	for (i = 0; i < dof->dofh_secnum; i++) {
12912 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12913 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12914 
12915 		if (sec->dofs_type != DOF_SECT_OPTDESC)
12916 			continue;
12917 
12918 		if (sec->dofs_align != sizeof (uint64_t)) {
12919 			dtrace_dof_error(dof, "bad alignment in "
12920 			    "option description");
12921 			return (EINVAL);
12922 		}
12923 
12924 		if ((entsize = sec->dofs_entsize) == 0) {
12925 			dtrace_dof_error(dof, "zeroed option entry size");
12926 			return (EINVAL);
12927 		}
12928 
12929 		if (entsize < sizeof (dof_optdesc_t)) {
12930 			dtrace_dof_error(dof, "bad option entry size");
12931 			return (EINVAL);
12932 		}
12933 
12934 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12935 			desc = (dof_optdesc_t *)((uintptr_t)dof +
12936 			    (uintptr_t)sec->dofs_offset + offs);
12937 
12938 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12939 				dtrace_dof_error(dof, "non-zero option string");
12940 				return (EINVAL);
12941 			}
12942 
12943 			if (desc->dofo_value == DTRACEOPT_UNSET) {
12944 				dtrace_dof_error(dof, "unset option");
12945 				return (EINVAL);
12946 			}
12947 
12948 			if ((rval = dtrace_state_option(state,
12949 			    desc->dofo_option, desc->dofo_value)) != 0) {
12950 				dtrace_dof_error(dof, "rejected option");
12951 				return (rval);
12952 			}
12953 		}
12954 	}
12955 
12956 	return (0);
12957 }
12958 
12959 /*
12960  * DTrace Consumer State Functions
12961  */
12962 static int
12963 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12964 {
12965 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12966 	void *base;
12967 	uintptr_t limit;
12968 	dtrace_dynvar_t *dvar, *next, *start;
12969 	int i;
12970 
12971 	ASSERT(MUTEX_HELD(&dtrace_lock));
12972 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12973 
12974 	bzero(dstate, sizeof (dtrace_dstate_t));
12975 
12976 	if ((dstate->dtds_chunksize = chunksize) == 0)
12977 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12978 
12979 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12980 		size = min;
12981 
12982 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12983 		return (ENOMEM);
12984 
12985 	dstate->dtds_size = size;
12986 	dstate->dtds_base = base;
12987 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12988 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12989 
12990 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12991 
12992 	if (hashsize != 1 && (hashsize & 1))
12993 		hashsize--;
12994 
12995 	dstate->dtds_hashsize = hashsize;
12996 	dstate->dtds_hash = dstate->dtds_base;
12997 
12998 	/*
12999 	 * Set all of our hash buckets to point to the single sink, and (if
13000 	 * it hasn't already been set), set the sink's hash value to be the
13001 	 * sink sentinel value.  The sink is needed for dynamic variable
13002 	 * lookups to know that they have iterated over an entire, valid hash
13003 	 * chain.
13004 	 */
13005 	for (i = 0; i < hashsize; i++)
13006 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13007 
13008 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13009 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13010 
13011 	/*
13012 	 * Determine number of active CPUs.  Divide free list evenly among
13013 	 * active CPUs.
13014 	 */
13015 	start = (dtrace_dynvar_t *)
13016 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13017 	limit = (uintptr_t)base + size;
13018 
13019 	maxper = (limit - (uintptr_t)start) / NCPU;
13020 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13021 
13022 #if !defined(sun)
13023 	CPU_FOREACH(i) {
13024 #else
13025 	for (i = 0; i < NCPU; i++) {
13026 #endif
13027 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13028 
13029 		/*
13030 		 * If we don't even have enough chunks to make it once through
13031 		 * NCPUs, we're just going to allocate everything to the first
13032 		 * CPU.  And if we're on the last CPU, we're going to allocate
13033 		 * whatever is left over.  In either case, we set the limit to
13034 		 * be the limit of the dynamic variable space.
13035 		 */
13036 		if (maxper == 0 || i == NCPU - 1) {
13037 			limit = (uintptr_t)base + size;
13038 			start = NULL;
13039 		} else {
13040 			limit = (uintptr_t)start + maxper;
13041 			start = (dtrace_dynvar_t *)limit;
13042 		}
13043 
13044 		ASSERT(limit <= (uintptr_t)base + size);
13045 
13046 		for (;;) {
13047 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13048 			    dstate->dtds_chunksize);
13049 
13050 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13051 				break;
13052 
13053 			dvar->dtdv_next = next;
13054 			dvar = next;
13055 		}
13056 
13057 		if (maxper == 0)
13058 			break;
13059 	}
13060 
13061 	return (0);
13062 }
13063 
13064 static void
13065 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13066 {
13067 	ASSERT(MUTEX_HELD(&cpu_lock));
13068 
13069 	if (dstate->dtds_base == NULL)
13070 		return;
13071 
13072 	kmem_free(dstate->dtds_base, dstate->dtds_size);
13073 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13074 }
13075 
13076 static void
13077 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13078 {
13079 	/*
13080 	 * Logical XOR, where are you?
13081 	 */
13082 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13083 
13084 	if (vstate->dtvs_nglobals > 0) {
13085 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13086 		    sizeof (dtrace_statvar_t *));
13087 	}
13088 
13089 	if (vstate->dtvs_ntlocals > 0) {
13090 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13091 		    sizeof (dtrace_difv_t));
13092 	}
13093 
13094 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13095 
13096 	if (vstate->dtvs_nlocals > 0) {
13097 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13098 		    sizeof (dtrace_statvar_t *));
13099 	}
13100 }
13101 
13102 #if defined(sun)
13103 static void
13104 dtrace_state_clean(dtrace_state_t *state)
13105 {
13106 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13107 		return;
13108 
13109 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13110 	dtrace_speculation_clean(state);
13111 }
13112 
13113 static void
13114 dtrace_state_deadman(dtrace_state_t *state)
13115 {
13116 	hrtime_t now;
13117 
13118 	dtrace_sync();
13119 
13120 	now = dtrace_gethrtime();
13121 
13122 	if (state != dtrace_anon.dta_state &&
13123 	    now - state->dts_laststatus >= dtrace_deadman_user)
13124 		return;
13125 
13126 	/*
13127 	 * We must be sure that dts_alive never appears to be less than the
13128 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13129 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13130 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13131 	 * the new value.  This assures that dts_alive never appears to be
13132 	 * less than its true value, regardless of the order in which the
13133 	 * stores to the underlying storage are issued.
13134 	 */
13135 	state->dts_alive = INT64_MAX;
13136 	dtrace_membar_producer();
13137 	state->dts_alive = now;
13138 }
13139 #else
13140 static void
13141 dtrace_state_clean(void *arg)
13142 {
13143 	dtrace_state_t *state = arg;
13144 	dtrace_optval_t *opt = state->dts_options;
13145 
13146 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13147 		return;
13148 
13149 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13150 	dtrace_speculation_clean(state);
13151 
13152 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13153 	    dtrace_state_clean, state);
13154 }
13155 
13156 static void
13157 dtrace_state_deadman(void *arg)
13158 {
13159 	dtrace_state_t *state = arg;
13160 	hrtime_t now;
13161 
13162 	dtrace_sync();
13163 
13164 	dtrace_debug_output();
13165 
13166 	now = dtrace_gethrtime();
13167 
13168 	if (state != dtrace_anon.dta_state &&
13169 	    now - state->dts_laststatus >= dtrace_deadman_user)
13170 		return;
13171 
13172 	/*
13173 	 * We must be sure that dts_alive never appears to be less than the
13174 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13175 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13176 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13177 	 * the new value.  This assures that dts_alive never appears to be
13178 	 * less than its true value, regardless of the order in which the
13179 	 * stores to the underlying storage are issued.
13180 	 */
13181 	state->dts_alive = INT64_MAX;
13182 	dtrace_membar_producer();
13183 	state->dts_alive = now;
13184 
13185 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13186 	    dtrace_state_deadman, state);
13187 }
13188 #endif
13189 
13190 static dtrace_state_t *
13191 #if defined(sun)
13192 dtrace_state_create(dev_t *devp, cred_t *cr)
13193 #else
13194 dtrace_state_create(struct cdev *dev)
13195 #endif
13196 {
13197 #if defined(sun)
13198 	minor_t minor;
13199 	major_t major;
13200 #else
13201 	cred_t *cr = NULL;
13202 	int m = 0;
13203 #endif
13204 	char c[30];
13205 	dtrace_state_t *state;
13206 	dtrace_optval_t *opt;
13207 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13208 
13209 	ASSERT(MUTEX_HELD(&dtrace_lock));
13210 	ASSERT(MUTEX_HELD(&cpu_lock));
13211 
13212 #if defined(sun)
13213 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13214 	    VM_BESTFIT | VM_SLEEP);
13215 
13216 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13217 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13218 		return (NULL);
13219 	}
13220 
13221 	state = ddi_get_soft_state(dtrace_softstate, minor);
13222 #else
13223 	if (dev != NULL) {
13224 		cr = dev->si_cred;
13225 		m = dev2unit(dev);
13226 		}
13227 
13228 	/* Allocate memory for the state. */
13229 	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13230 #endif
13231 
13232 	state->dts_epid = DTRACE_EPIDNONE + 1;
13233 
13234 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13235 #if defined(sun)
13236 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13237 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13238 
13239 	if (devp != NULL) {
13240 		major = getemajor(*devp);
13241 	} else {
13242 		major = ddi_driver_major(dtrace_devi);
13243 	}
13244 
13245 	state->dts_dev = makedevice(major, minor);
13246 
13247 	if (devp != NULL)
13248 		*devp = state->dts_dev;
13249 #else
13250 	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13251 	state->dts_dev = dev;
13252 #endif
13253 
13254 	/*
13255 	 * We allocate NCPU buffers.  On the one hand, this can be quite
13256 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13257 	 * other hand, it saves an additional memory reference in the probe
13258 	 * path.
13259 	 */
13260 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13261 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13262 
13263 #if defined(sun)
13264 	state->dts_cleaner = CYCLIC_NONE;
13265 	state->dts_deadman = CYCLIC_NONE;
13266 #else
13267 	callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13268 	callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13269 #endif
13270 	state->dts_vstate.dtvs_state = state;
13271 
13272 	for (i = 0; i < DTRACEOPT_MAX; i++)
13273 		state->dts_options[i] = DTRACEOPT_UNSET;
13274 
13275 	/*
13276 	 * Set the default options.
13277 	 */
13278 	opt = state->dts_options;
13279 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13280 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13281 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13282 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13283 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13284 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13285 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13286 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13287 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13288 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13289 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13290 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13291 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13292 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13293 
13294 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13295 
13296 	/*
13297 	 * Depending on the user credentials, we set flag bits which alter probe
13298 	 * visibility or the amount of destructiveness allowed.  In the case of
13299 	 * actual anonymous tracing, or the possession of all privileges, all of
13300 	 * the normal checks are bypassed.
13301 	 */
13302 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13303 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13304 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13305 	} else {
13306 		/*
13307 		 * Set up the credentials for this instantiation.  We take a
13308 		 * hold on the credential to prevent it from disappearing on
13309 		 * us; this in turn prevents the zone_t referenced by this
13310 		 * credential from disappearing.  This means that we can
13311 		 * examine the credential and the zone from probe context.
13312 		 */
13313 		crhold(cr);
13314 		state->dts_cred.dcr_cred = cr;
13315 
13316 		/*
13317 		 * CRA_PROC means "we have *some* privilege for dtrace" and
13318 		 * unlocks the use of variables like pid, zonename, etc.
13319 		 */
13320 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13321 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13322 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13323 		}
13324 
13325 		/*
13326 		 * dtrace_user allows use of syscall and profile providers.
13327 		 * If the user also has proc_owner and/or proc_zone, we
13328 		 * extend the scope to include additional visibility and
13329 		 * destructive power.
13330 		 */
13331 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13332 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13333 				state->dts_cred.dcr_visible |=
13334 				    DTRACE_CRV_ALLPROC;
13335 
13336 				state->dts_cred.dcr_action |=
13337 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13338 			}
13339 
13340 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13341 				state->dts_cred.dcr_visible |=
13342 				    DTRACE_CRV_ALLZONE;
13343 
13344 				state->dts_cred.dcr_action |=
13345 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13346 			}
13347 
13348 			/*
13349 			 * If we have all privs in whatever zone this is,
13350 			 * we can do destructive things to processes which
13351 			 * have altered credentials.
13352 			 */
13353 #if defined(sun)
13354 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13355 			    cr->cr_zone->zone_privset)) {
13356 				state->dts_cred.dcr_action |=
13357 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13358 			}
13359 #endif
13360 		}
13361 
13362 		/*
13363 		 * Holding the dtrace_kernel privilege also implies that
13364 		 * the user has the dtrace_user privilege from a visibility
13365 		 * perspective.  But without further privileges, some
13366 		 * destructive actions are not available.
13367 		 */
13368 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13369 			/*
13370 			 * Make all probes in all zones visible.  However,
13371 			 * this doesn't mean that all actions become available
13372 			 * to all zones.
13373 			 */
13374 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13375 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13376 
13377 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13378 			    DTRACE_CRA_PROC;
13379 			/*
13380 			 * Holding proc_owner means that destructive actions
13381 			 * for *this* zone are allowed.
13382 			 */
13383 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13384 				state->dts_cred.dcr_action |=
13385 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13386 
13387 			/*
13388 			 * Holding proc_zone means that destructive actions
13389 			 * for this user/group ID in all zones is allowed.
13390 			 */
13391 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13392 				state->dts_cred.dcr_action |=
13393 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13394 
13395 #if defined(sun)
13396 			/*
13397 			 * If we have all privs in whatever zone this is,
13398 			 * we can do destructive things to processes which
13399 			 * have altered credentials.
13400 			 */
13401 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13402 			    cr->cr_zone->zone_privset)) {
13403 				state->dts_cred.dcr_action |=
13404 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13405 			}
13406 #endif
13407 		}
13408 
13409 		/*
13410 		 * Holding the dtrace_proc privilege gives control over fasttrap
13411 		 * and pid providers.  We need to grant wider destructive
13412 		 * privileges in the event that the user has proc_owner and/or
13413 		 * proc_zone.
13414 		 */
13415 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13416 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13417 				state->dts_cred.dcr_action |=
13418 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13419 
13420 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13421 				state->dts_cred.dcr_action |=
13422 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13423 		}
13424 	}
13425 
13426 	return (state);
13427 }
13428 
13429 static int
13430 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13431 {
13432 	dtrace_optval_t *opt = state->dts_options, size;
13433 	processorid_t cpu = 0;;
13434 	int flags = 0, rval, factor, divisor = 1;
13435 
13436 	ASSERT(MUTEX_HELD(&dtrace_lock));
13437 	ASSERT(MUTEX_HELD(&cpu_lock));
13438 	ASSERT(which < DTRACEOPT_MAX);
13439 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13440 	    (state == dtrace_anon.dta_state &&
13441 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13442 
13443 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13444 		return (0);
13445 
13446 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13447 		cpu = opt[DTRACEOPT_CPU];
13448 
13449 	if (which == DTRACEOPT_SPECSIZE)
13450 		flags |= DTRACEBUF_NOSWITCH;
13451 
13452 	if (which == DTRACEOPT_BUFSIZE) {
13453 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13454 			flags |= DTRACEBUF_RING;
13455 
13456 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13457 			flags |= DTRACEBUF_FILL;
13458 
13459 		if (state != dtrace_anon.dta_state ||
13460 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13461 			flags |= DTRACEBUF_INACTIVE;
13462 	}
13463 
13464 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13465 		/*
13466 		 * The size must be 8-byte aligned.  If the size is not 8-byte
13467 		 * aligned, drop it down by the difference.
13468 		 */
13469 		if (size & (sizeof (uint64_t) - 1))
13470 			size -= size & (sizeof (uint64_t) - 1);
13471 
13472 		if (size < state->dts_reserve) {
13473 			/*
13474 			 * Buffers always must be large enough to accommodate
13475 			 * their prereserved space.  We return E2BIG instead
13476 			 * of ENOMEM in this case to allow for user-level
13477 			 * software to differentiate the cases.
13478 			 */
13479 			return (E2BIG);
13480 		}
13481 
13482 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13483 
13484 		if (rval != ENOMEM) {
13485 			opt[which] = size;
13486 			return (rval);
13487 		}
13488 
13489 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13490 			return (rval);
13491 
13492 		for (divisor = 2; divisor < factor; divisor <<= 1)
13493 			continue;
13494 	}
13495 
13496 	return (ENOMEM);
13497 }
13498 
13499 static int
13500 dtrace_state_buffers(dtrace_state_t *state)
13501 {
13502 	dtrace_speculation_t *spec = state->dts_speculations;
13503 	int rval, i;
13504 
13505 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13506 	    DTRACEOPT_BUFSIZE)) != 0)
13507 		return (rval);
13508 
13509 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13510 	    DTRACEOPT_AGGSIZE)) != 0)
13511 		return (rval);
13512 
13513 	for (i = 0; i < state->dts_nspeculations; i++) {
13514 		if ((rval = dtrace_state_buffer(state,
13515 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13516 			return (rval);
13517 	}
13518 
13519 	return (0);
13520 }
13521 
13522 static void
13523 dtrace_state_prereserve(dtrace_state_t *state)
13524 {
13525 	dtrace_ecb_t *ecb;
13526 	dtrace_probe_t *probe;
13527 
13528 	state->dts_reserve = 0;
13529 
13530 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13531 		return;
13532 
13533 	/*
13534 	 * If our buffer policy is a "fill" buffer policy, we need to set the
13535 	 * prereserved space to be the space required by the END probes.
13536 	 */
13537 	probe = dtrace_probes[dtrace_probeid_end - 1];
13538 	ASSERT(probe != NULL);
13539 
13540 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13541 		if (ecb->dte_state != state)
13542 			continue;
13543 
13544 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13545 	}
13546 }
13547 
13548 static int
13549 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13550 {
13551 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
13552 	dtrace_speculation_t *spec;
13553 	dtrace_buffer_t *buf;
13554 #if defined(sun)
13555 	cyc_handler_t hdlr;
13556 	cyc_time_t when;
13557 #endif
13558 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13559 	dtrace_icookie_t cookie;
13560 
13561 	mutex_enter(&cpu_lock);
13562 	mutex_enter(&dtrace_lock);
13563 
13564 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13565 		rval = EBUSY;
13566 		goto out;
13567 	}
13568 
13569 	/*
13570 	 * Before we can perform any checks, we must prime all of the
13571 	 * retained enablings that correspond to this state.
13572 	 */
13573 	dtrace_enabling_prime(state);
13574 
13575 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13576 		rval = EACCES;
13577 		goto out;
13578 	}
13579 
13580 	dtrace_state_prereserve(state);
13581 
13582 	/*
13583 	 * Now we want to do is try to allocate our speculations.
13584 	 * We do not automatically resize the number of speculations; if
13585 	 * this fails, we will fail the operation.
13586 	 */
13587 	nspec = opt[DTRACEOPT_NSPEC];
13588 	ASSERT(nspec != DTRACEOPT_UNSET);
13589 
13590 	if (nspec > INT_MAX) {
13591 		rval = ENOMEM;
13592 		goto out;
13593 	}
13594 
13595 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13596 	    KM_NOSLEEP | KM_NORMALPRI);
13597 
13598 	if (spec == NULL) {
13599 		rval = ENOMEM;
13600 		goto out;
13601 	}
13602 
13603 	state->dts_speculations = spec;
13604 	state->dts_nspeculations = (int)nspec;
13605 
13606 	for (i = 0; i < nspec; i++) {
13607 		if ((buf = kmem_zalloc(bufsize,
13608 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13609 			rval = ENOMEM;
13610 			goto err;
13611 		}
13612 
13613 		spec[i].dtsp_buffer = buf;
13614 	}
13615 
13616 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13617 		if (dtrace_anon.dta_state == NULL) {
13618 			rval = ENOENT;
13619 			goto out;
13620 		}
13621 
13622 		if (state->dts_necbs != 0) {
13623 			rval = EALREADY;
13624 			goto out;
13625 		}
13626 
13627 		state->dts_anon = dtrace_anon_grab();
13628 		ASSERT(state->dts_anon != NULL);
13629 		state = state->dts_anon;
13630 
13631 		/*
13632 		 * We want "grabanon" to be set in the grabbed state, so we'll
13633 		 * copy that option value from the grabbing state into the
13634 		 * grabbed state.
13635 		 */
13636 		state->dts_options[DTRACEOPT_GRABANON] =
13637 		    opt[DTRACEOPT_GRABANON];
13638 
13639 		*cpu = dtrace_anon.dta_beganon;
13640 
13641 		/*
13642 		 * If the anonymous state is active (as it almost certainly
13643 		 * is if the anonymous enabling ultimately matched anything),
13644 		 * we don't allow any further option processing -- but we
13645 		 * don't return failure.
13646 		 */
13647 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13648 			goto out;
13649 	}
13650 
13651 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13652 	    opt[DTRACEOPT_AGGSIZE] != 0) {
13653 		if (state->dts_aggregations == NULL) {
13654 			/*
13655 			 * We're not going to create an aggregation buffer
13656 			 * because we don't have any ECBs that contain
13657 			 * aggregations -- set this option to 0.
13658 			 */
13659 			opt[DTRACEOPT_AGGSIZE] = 0;
13660 		} else {
13661 			/*
13662 			 * If we have an aggregation buffer, we must also have
13663 			 * a buffer to use as scratch.
13664 			 */
13665 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13666 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13667 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13668 			}
13669 		}
13670 	}
13671 
13672 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13673 	    opt[DTRACEOPT_SPECSIZE] != 0) {
13674 		if (!state->dts_speculates) {
13675 			/*
13676 			 * We're not going to create speculation buffers
13677 			 * because we don't have any ECBs that actually
13678 			 * speculate -- set the speculation size to 0.
13679 			 */
13680 			opt[DTRACEOPT_SPECSIZE] = 0;
13681 		}
13682 	}
13683 
13684 	/*
13685 	 * The bare minimum size for any buffer that we're actually going to
13686 	 * do anything to is sizeof (uint64_t).
13687 	 */
13688 	sz = sizeof (uint64_t);
13689 
13690 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13691 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13692 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13693 		/*
13694 		 * A buffer size has been explicitly set to 0 (or to a size
13695 		 * that will be adjusted to 0) and we need the space -- we
13696 		 * need to return failure.  We return ENOSPC to differentiate
13697 		 * it from failing to allocate a buffer due to failure to meet
13698 		 * the reserve (for which we return E2BIG).
13699 		 */
13700 		rval = ENOSPC;
13701 		goto out;
13702 	}
13703 
13704 	if ((rval = dtrace_state_buffers(state)) != 0)
13705 		goto err;
13706 
13707 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13708 		sz = dtrace_dstate_defsize;
13709 
13710 	do {
13711 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13712 
13713 		if (rval == 0)
13714 			break;
13715 
13716 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13717 			goto err;
13718 	} while (sz >>= 1);
13719 
13720 	opt[DTRACEOPT_DYNVARSIZE] = sz;
13721 
13722 	if (rval != 0)
13723 		goto err;
13724 
13725 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13726 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13727 
13728 	if (opt[DTRACEOPT_CLEANRATE] == 0)
13729 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13730 
13731 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13732 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13733 
13734 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13735 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13736 
13737 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13738 #if defined(sun)
13739 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13740 	hdlr.cyh_arg = state;
13741 	hdlr.cyh_level = CY_LOW_LEVEL;
13742 
13743 	when.cyt_when = 0;
13744 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13745 
13746 	state->dts_cleaner = cyclic_add(&hdlr, &when);
13747 
13748 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13749 	hdlr.cyh_arg = state;
13750 	hdlr.cyh_level = CY_LOW_LEVEL;
13751 
13752 	when.cyt_when = 0;
13753 	when.cyt_interval = dtrace_deadman_interval;
13754 
13755 	state->dts_deadman = cyclic_add(&hdlr, &when);
13756 #else
13757 	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13758 	    dtrace_state_clean, state);
13759 	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13760 	    dtrace_state_deadman, state);
13761 #endif
13762 
13763 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13764 
13765 	/*
13766 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
13767 	 * interrupts here both to record the CPU on which we fired the BEGIN
13768 	 * probe (the data from this CPU will be processed first at user
13769 	 * level) and to manually activate the buffer for this CPU.
13770 	 */
13771 	cookie = dtrace_interrupt_disable();
13772 	*cpu = curcpu;
13773 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13774 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13775 
13776 	dtrace_probe(dtrace_probeid_begin,
13777 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13778 	dtrace_interrupt_enable(cookie);
13779 	/*
13780 	 * We may have had an exit action from a BEGIN probe; only change our
13781 	 * state to ACTIVE if we're still in WARMUP.
13782 	 */
13783 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13784 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13785 
13786 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13787 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13788 
13789 	/*
13790 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13791 	 * want each CPU to transition its principal buffer out of the
13792 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13793 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13794 	 * atomically transition from processing none of a state's ECBs to
13795 	 * processing all of them.
13796 	 */
13797 	dtrace_xcall(DTRACE_CPUALL,
13798 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
13799 	goto out;
13800 
13801 err:
13802 	dtrace_buffer_free(state->dts_buffer);
13803 	dtrace_buffer_free(state->dts_aggbuffer);
13804 
13805 	if ((nspec = state->dts_nspeculations) == 0) {
13806 		ASSERT(state->dts_speculations == NULL);
13807 		goto out;
13808 	}
13809 
13810 	spec = state->dts_speculations;
13811 	ASSERT(spec != NULL);
13812 
13813 	for (i = 0; i < state->dts_nspeculations; i++) {
13814 		if ((buf = spec[i].dtsp_buffer) == NULL)
13815 			break;
13816 
13817 		dtrace_buffer_free(buf);
13818 		kmem_free(buf, bufsize);
13819 	}
13820 
13821 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13822 	state->dts_nspeculations = 0;
13823 	state->dts_speculations = NULL;
13824 
13825 out:
13826 	mutex_exit(&dtrace_lock);
13827 	mutex_exit(&cpu_lock);
13828 
13829 	return (rval);
13830 }
13831 
13832 static int
13833 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13834 {
13835 	dtrace_icookie_t cookie;
13836 
13837 	ASSERT(MUTEX_HELD(&dtrace_lock));
13838 
13839 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13840 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13841 		return (EINVAL);
13842 
13843 	/*
13844 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13845 	 * to be sure that every CPU has seen it.  See below for the details
13846 	 * on why this is done.
13847 	 */
13848 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13849 	dtrace_sync();
13850 
13851 	/*
13852 	 * By this point, it is impossible for any CPU to be still processing
13853 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13854 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13855 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13856 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13857 	 * iff we're in the END probe.
13858 	 */
13859 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13860 	dtrace_sync();
13861 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13862 
13863 	/*
13864 	 * Finally, we can release the reserve and call the END probe.  We
13865 	 * disable interrupts across calling the END probe to allow us to
13866 	 * return the CPU on which we actually called the END probe.  This
13867 	 * allows user-land to be sure that this CPU's principal buffer is
13868 	 * processed last.
13869 	 */
13870 	state->dts_reserve = 0;
13871 
13872 	cookie = dtrace_interrupt_disable();
13873 	*cpu = curcpu;
13874 	dtrace_probe(dtrace_probeid_end,
13875 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13876 	dtrace_interrupt_enable(cookie);
13877 
13878 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13879 	dtrace_sync();
13880 
13881 	return (0);
13882 }
13883 
13884 static int
13885 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13886     dtrace_optval_t val)
13887 {
13888 	ASSERT(MUTEX_HELD(&dtrace_lock));
13889 
13890 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13891 		return (EBUSY);
13892 
13893 	if (option >= DTRACEOPT_MAX)
13894 		return (EINVAL);
13895 
13896 	if (option != DTRACEOPT_CPU && val < 0)
13897 		return (EINVAL);
13898 
13899 	switch (option) {
13900 	case DTRACEOPT_DESTRUCTIVE:
13901 		if (dtrace_destructive_disallow)
13902 			return (EACCES);
13903 
13904 		state->dts_cred.dcr_destructive = 1;
13905 		break;
13906 
13907 	case DTRACEOPT_BUFSIZE:
13908 	case DTRACEOPT_DYNVARSIZE:
13909 	case DTRACEOPT_AGGSIZE:
13910 	case DTRACEOPT_SPECSIZE:
13911 	case DTRACEOPT_STRSIZE:
13912 		if (val < 0)
13913 			return (EINVAL);
13914 
13915 		if (val >= LONG_MAX) {
13916 			/*
13917 			 * If this is an otherwise negative value, set it to
13918 			 * the highest multiple of 128m less than LONG_MAX.
13919 			 * Technically, we're adjusting the size without
13920 			 * regard to the buffer resizing policy, but in fact,
13921 			 * this has no effect -- if we set the buffer size to
13922 			 * ~LONG_MAX and the buffer policy is ultimately set to
13923 			 * be "manual", the buffer allocation is guaranteed to
13924 			 * fail, if only because the allocation requires two
13925 			 * buffers.  (We set the the size to the highest
13926 			 * multiple of 128m because it ensures that the size
13927 			 * will remain a multiple of a megabyte when
13928 			 * repeatedly halved -- all the way down to 15m.)
13929 			 */
13930 			val = LONG_MAX - (1 << 27) + 1;
13931 		}
13932 	}
13933 
13934 	state->dts_options[option] = val;
13935 
13936 	return (0);
13937 }
13938 
13939 static void
13940 dtrace_state_destroy(dtrace_state_t *state)
13941 {
13942 	dtrace_ecb_t *ecb;
13943 	dtrace_vstate_t *vstate = &state->dts_vstate;
13944 #if defined(sun)
13945 	minor_t minor = getminor(state->dts_dev);
13946 #endif
13947 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13948 	dtrace_speculation_t *spec = state->dts_speculations;
13949 	int nspec = state->dts_nspeculations;
13950 	uint32_t match;
13951 
13952 	ASSERT(MUTEX_HELD(&dtrace_lock));
13953 	ASSERT(MUTEX_HELD(&cpu_lock));
13954 
13955 	/*
13956 	 * First, retract any retained enablings for this state.
13957 	 */
13958 	dtrace_enabling_retract(state);
13959 	ASSERT(state->dts_nretained == 0);
13960 
13961 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13962 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13963 		/*
13964 		 * We have managed to come into dtrace_state_destroy() on a
13965 		 * hot enabling -- almost certainly because of a disorderly
13966 		 * shutdown of a consumer.  (That is, a consumer that is
13967 		 * exiting without having called dtrace_stop().) In this case,
13968 		 * we're going to set our activity to be KILLED, and then
13969 		 * issue a sync to be sure that everyone is out of probe
13970 		 * context before we start blowing away ECBs.
13971 		 */
13972 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
13973 		dtrace_sync();
13974 	}
13975 
13976 	/*
13977 	 * Release the credential hold we took in dtrace_state_create().
13978 	 */
13979 	if (state->dts_cred.dcr_cred != NULL)
13980 		crfree(state->dts_cred.dcr_cred);
13981 
13982 	/*
13983 	 * Now we can safely disable and destroy any enabled probes.  Because
13984 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13985 	 * (especially if they're all enabled), we take two passes through the
13986 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13987 	 * in the second we disable whatever is left over.
13988 	 */
13989 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13990 		for (i = 0; i < state->dts_necbs; i++) {
13991 			if ((ecb = state->dts_ecbs[i]) == NULL)
13992 				continue;
13993 
13994 			if (match && ecb->dte_probe != NULL) {
13995 				dtrace_probe_t *probe = ecb->dte_probe;
13996 				dtrace_provider_t *prov = probe->dtpr_provider;
13997 
13998 				if (!(prov->dtpv_priv.dtpp_flags & match))
13999 					continue;
14000 			}
14001 
14002 			dtrace_ecb_disable(ecb);
14003 			dtrace_ecb_destroy(ecb);
14004 		}
14005 
14006 		if (!match)
14007 			break;
14008 	}
14009 
14010 	/*
14011 	 * Before we free the buffers, perform one more sync to assure that
14012 	 * every CPU is out of probe context.
14013 	 */
14014 	dtrace_sync();
14015 
14016 	dtrace_buffer_free(state->dts_buffer);
14017 	dtrace_buffer_free(state->dts_aggbuffer);
14018 
14019 	for (i = 0; i < nspec; i++)
14020 		dtrace_buffer_free(spec[i].dtsp_buffer);
14021 
14022 #if defined(sun)
14023 	if (state->dts_cleaner != CYCLIC_NONE)
14024 		cyclic_remove(state->dts_cleaner);
14025 
14026 	if (state->dts_deadman != CYCLIC_NONE)
14027 		cyclic_remove(state->dts_deadman);
14028 #else
14029 	callout_stop(&state->dts_cleaner);
14030 	callout_drain(&state->dts_cleaner);
14031 	callout_stop(&state->dts_deadman);
14032 	callout_drain(&state->dts_deadman);
14033 #endif
14034 
14035 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14036 	dtrace_vstate_fini(vstate);
14037 	if (state->dts_ecbs != NULL)
14038 		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14039 
14040 	if (state->dts_aggregations != NULL) {
14041 #ifdef DEBUG
14042 		for (i = 0; i < state->dts_naggregations; i++)
14043 			ASSERT(state->dts_aggregations[i] == NULL);
14044 #endif
14045 		ASSERT(state->dts_naggregations > 0);
14046 		kmem_free(state->dts_aggregations,
14047 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14048 	}
14049 
14050 	kmem_free(state->dts_buffer, bufsize);
14051 	kmem_free(state->dts_aggbuffer, bufsize);
14052 
14053 	for (i = 0; i < nspec; i++)
14054 		kmem_free(spec[i].dtsp_buffer, bufsize);
14055 
14056 	if (spec != NULL)
14057 		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14058 
14059 	dtrace_format_destroy(state);
14060 
14061 	if (state->dts_aggid_arena != NULL) {
14062 #if defined(sun)
14063 		vmem_destroy(state->dts_aggid_arena);
14064 #else
14065 		delete_unrhdr(state->dts_aggid_arena);
14066 #endif
14067 		state->dts_aggid_arena = NULL;
14068 	}
14069 #if defined(sun)
14070 	ddi_soft_state_free(dtrace_softstate, minor);
14071 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14072 #endif
14073 }
14074 
14075 /*
14076  * DTrace Anonymous Enabling Functions
14077  */
14078 static dtrace_state_t *
14079 dtrace_anon_grab(void)
14080 {
14081 	dtrace_state_t *state;
14082 
14083 	ASSERT(MUTEX_HELD(&dtrace_lock));
14084 
14085 	if ((state = dtrace_anon.dta_state) == NULL) {
14086 		ASSERT(dtrace_anon.dta_enabling == NULL);
14087 		return (NULL);
14088 	}
14089 
14090 	ASSERT(dtrace_anon.dta_enabling != NULL);
14091 	ASSERT(dtrace_retained != NULL);
14092 
14093 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14094 	dtrace_anon.dta_enabling = NULL;
14095 	dtrace_anon.dta_state = NULL;
14096 
14097 	return (state);
14098 }
14099 
14100 static void
14101 dtrace_anon_property(void)
14102 {
14103 	int i, rv;
14104 	dtrace_state_t *state;
14105 	dof_hdr_t *dof;
14106 	char c[32];		/* enough for "dof-data-" + digits */
14107 
14108 	ASSERT(MUTEX_HELD(&dtrace_lock));
14109 	ASSERT(MUTEX_HELD(&cpu_lock));
14110 
14111 	for (i = 0; ; i++) {
14112 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14113 
14114 		dtrace_err_verbose = 1;
14115 
14116 		if ((dof = dtrace_dof_property(c)) == NULL) {
14117 			dtrace_err_verbose = 0;
14118 			break;
14119 		}
14120 
14121 #if defined(sun)
14122 		/*
14123 		 * We want to create anonymous state, so we need to transition
14124 		 * the kernel debugger to indicate that DTrace is active.  If
14125 		 * this fails (e.g. because the debugger has modified text in
14126 		 * some way), we won't continue with the processing.
14127 		 */
14128 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14129 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14130 			    "enabling ignored.");
14131 			dtrace_dof_destroy(dof);
14132 			break;
14133 		}
14134 #endif
14135 
14136 		/*
14137 		 * If we haven't allocated an anonymous state, we'll do so now.
14138 		 */
14139 		if ((state = dtrace_anon.dta_state) == NULL) {
14140 #if defined(sun)
14141 			state = dtrace_state_create(NULL, NULL);
14142 #else
14143 			state = dtrace_state_create(NULL);
14144 #endif
14145 			dtrace_anon.dta_state = state;
14146 
14147 			if (state == NULL) {
14148 				/*
14149 				 * This basically shouldn't happen:  the only
14150 				 * failure mode from dtrace_state_create() is a
14151 				 * failure of ddi_soft_state_zalloc() that
14152 				 * itself should never happen.  Still, the
14153 				 * interface allows for a failure mode, and
14154 				 * we want to fail as gracefully as possible:
14155 				 * we'll emit an error message and cease
14156 				 * processing anonymous state in this case.
14157 				 */
14158 				cmn_err(CE_WARN, "failed to create "
14159 				    "anonymous state");
14160 				dtrace_dof_destroy(dof);
14161 				break;
14162 			}
14163 		}
14164 
14165 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14166 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14167 
14168 		if (rv == 0)
14169 			rv = dtrace_dof_options(dof, state);
14170 
14171 		dtrace_err_verbose = 0;
14172 		dtrace_dof_destroy(dof);
14173 
14174 		if (rv != 0) {
14175 			/*
14176 			 * This is malformed DOF; chuck any anonymous state
14177 			 * that we created.
14178 			 */
14179 			ASSERT(dtrace_anon.dta_enabling == NULL);
14180 			dtrace_state_destroy(state);
14181 			dtrace_anon.dta_state = NULL;
14182 			break;
14183 		}
14184 
14185 		ASSERT(dtrace_anon.dta_enabling != NULL);
14186 	}
14187 
14188 	if (dtrace_anon.dta_enabling != NULL) {
14189 		int rval;
14190 
14191 		/*
14192 		 * dtrace_enabling_retain() can only fail because we are
14193 		 * trying to retain more enablings than are allowed -- but
14194 		 * we only have one anonymous enabling, and we are guaranteed
14195 		 * to be allowed at least one retained enabling; we assert
14196 		 * that dtrace_enabling_retain() returns success.
14197 		 */
14198 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14199 		ASSERT(rval == 0);
14200 
14201 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14202 	}
14203 }
14204 
14205 /*
14206  * DTrace Helper Functions
14207  */
14208 static void
14209 dtrace_helper_trace(dtrace_helper_action_t *helper,
14210     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14211 {
14212 	uint32_t size, next, nnext, i;
14213 	dtrace_helptrace_t *ent;
14214 	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14215 
14216 	if (!dtrace_helptrace_enabled)
14217 		return;
14218 
14219 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14220 
14221 	/*
14222 	 * What would a tracing framework be without its own tracing
14223 	 * framework?  (Well, a hell of a lot simpler, for starters...)
14224 	 */
14225 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14226 	    sizeof (uint64_t) - sizeof (uint64_t);
14227 
14228 	/*
14229 	 * Iterate until we can allocate a slot in the trace buffer.
14230 	 */
14231 	do {
14232 		next = dtrace_helptrace_next;
14233 
14234 		if (next + size < dtrace_helptrace_bufsize) {
14235 			nnext = next + size;
14236 		} else {
14237 			nnext = size;
14238 		}
14239 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14240 
14241 	/*
14242 	 * We have our slot; fill it in.
14243 	 */
14244 	if (nnext == size)
14245 		next = 0;
14246 
14247 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14248 	ent->dtht_helper = helper;
14249 	ent->dtht_where = where;
14250 	ent->dtht_nlocals = vstate->dtvs_nlocals;
14251 
14252 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14253 	    mstate->dtms_fltoffs : -1;
14254 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14255 	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14256 
14257 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14258 		dtrace_statvar_t *svar;
14259 
14260 		if ((svar = vstate->dtvs_locals[i]) == NULL)
14261 			continue;
14262 
14263 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14264 		ent->dtht_locals[i] =
14265 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14266 	}
14267 }
14268 
14269 static uint64_t
14270 dtrace_helper(int which, dtrace_mstate_t *mstate,
14271     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14272 {
14273 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14274 	uint64_t sarg0 = mstate->dtms_arg[0];
14275 	uint64_t sarg1 = mstate->dtms_arg[1];
14276 	uint64_t rval = 0;
14277 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14278 	dtrace_helper_action_t *helper;
14279 	dtrace_vstate_t *vstate;
14280 	dtrace_difo_t *pred;
14281 	int i, trace = dtrace_helptrace_enabled;
14282 
14283 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14284 
14285 	if (helpers == NULL)
14286 		return (0);
14287 
14288 	if ((helper = helpers->dthps_actions[which]) == NULL)
14289 		return (0);
14290 
14291 	vstate = &helpers->dthps_vstate;
14292 	mstate->dtms_arg[0] = arg0;
14293 	mstate->dtms_arg[1] = arg1;
14294 
14295 	/*
14296 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14297 	 * we'll call the corresponding actions.  Note that the below calls
14298 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14299 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14300 	 * the stored DIF offset with its own (which is the desired behavior).
14301 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14302 	 * from machine state; this is okay, too.
14303 	 */
14304 	for (; helper != NULL; helper = helper->dtha_next) {
14305 		if ((pred = helper->dtha_predicate) != NULL) {
14306 			if (trace)
14307 				dtrace_helper_trace(helper, mstate, vstate, 0);
14308 
14309 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14310 				goto next;
14311 
14312 			if (*flags & CPU_DTRACE_FAULT)
14313 				goto err;
14314 		}
14315 
14316 		for (i = 0; i < helper->dtha_nactions; i++) {
14317 			if (trace)
14318 				dtrace_helper_trace(helper,
14319 				    mstate, vstate, i + 1);
14320 
14321 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14322 			    mstate, vstate, state);
14323 
14324 			if (*flags & CPU_DTRACE_FAULT)
14325 				goto err;
14326 		}
14327 
14328 next:
14329 		if (trace)
14330 			dtrace_helper_trace(helper, mstate, vstate,
14331 			    DTRACE_HELPTRACE_NEXT);
14332 	}
14333 
14334 	if (trace)
14335 		dtrace_helper_trace(helper, mstate, vstate,
14336 		    DTRACE_HELPTRACE_DONE);
14337 
14338 	/*
14339 	 * Restore the arg0 that we saved upon entry.
14340 	 */
14341 	mstate->dtms_arg[0] = sarg0;
14342 	mstate->dtms_arg[1] = sarg1;
14343 
14344 	return (rval);
14345 
14346 err:
14347 	if (trace)
14348 		dtrace_helper_trace(helper, mstate, vstate,
14349 		    DTRACE_HELPTRACE_ERR);
14350 
14351 	/*
14352 	 * Restore the arg0 that we saved upon entry.
14353 	 */
14354 	mstate->dtms_arg[0] = sarg0;
14355 	mstate->dtms_arg[1] = sarg1;
14356 
14357 	return (0);
14358 }
14359 
14360 static void
14361 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14362     dtrace_vstate_t *vstate)
14363 {
14364 	int i;
14365 
14366 	if (helper->dtha_predicate != NULL)
14367 		dtrace_difo_release(helper->dtha_predicate, vstate);
14368 
14369 	for (i = 0; i < helper->dtha_nactions; i++) {
14370 		ASSERT(helper->dtha_actions[i] != NULL);
14371 		dtrace_difo_release(helper->dtha_actions[i], vstate);
14372 	}
14373 
14374 	kmem_free(helper->dtha_actions,
14375 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14376 	kmem_free(helper, sizeof (dtrace_helper_action_t));
14377 }
14378 
14379 static int
14380 dtrace_helper_destroygen(int gen)
14381 {
14382 	proc_t *p = curproc;
14383 	dtrace_helpers_t *help = p->p_dtrace_helpers;
14384 	dtrace_vstate_t *vstate;
14385 	int i;
14386 
14387 	ASSERT(MUTEX_HELD(&dtrace_lock));
14388 
14389 	if (help == NULL || gen > help->dthps_generation)
14390 		return (EINVAL);
14391 
14392 	vstate = &help->dthps_vstate;
14393 
14394 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14395 		dtrace_helper_action_t *last = NULL, *h, *next;
14396 
14397 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14398 			next = h->dtha_next;
14399 
14400 			if (h->dtha_generation == gen) {
14401 				if (last != NULL) {
14402 					last->dtha_next = next;
14403 				} else {
14404 					help->dthps_actions[i] = next;
14405 				}
14406 
14407 				dtrace_helper_action_destroy(h, vstate);
14408 			} else {
14409 				last = h;
14410 			}
14411 		}
14412 	}
14413 
14414 	/*
14415 	 * Interate until we've cleared out all helper providers with the
14416 	 * given generation number.
14417 	 */
14418 	for (;;) {
14419 		dtrace_helper_provider_t *prov;
14420 
14421 		/*
14422 		 * Look for a helper provider with the right generation. We
14423 		 * have to start back at the beginning of the list each time
14424 		 * because we drop dtrace_lock. It's unlikely that we'll make
14425 		 * more than two passes.
14426 		 */
14427 		for (i = 0; i < help->dthps_nprovs; i++) {
14428 			prov = help->dthps_provs[i];
14429 
14430 			if (prov->dthp_generation == gen)
14431 				break;
14432 		}
14433 
14434 		/*
14435 		 * If there were no matches, we're done.
14436 		 */
14437 		if (i == help->dthps_nprovs)
14438 			break;
14439 
14440 		/*
14441 		 * Move the last helper provider into this slot.
14442 		 */
14443 		help->dthps_nprovs--;
14444 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14445 		help->dthps_provs[help->dthps_nprovs] = NULL;
14446 
14447 		mutex_exit(&dtrace_lock);
14448 
14449 		/*
14450 		 * If we have a meta provider, remove this helper provider.
14451 		 */
14452 		mutex_enter(&dtrace_meta_lock);
14453 		if (dtrace_meta_pid != NULL) {
14454 			ASSERT(dtrace_deferred_pid == NULL);
14455 			dtrace_helper_provider_remove(&prov->dthp_prov,
14456 			    p->p_pid);
14457 		}
14458 		mutex_exit(&dtrace_meta_lock);
14459 
14460 		dtrace_helper_provider_destroy(prov);
14461 
14462 		mutex_enter(&dtrace_lock);
14463 	}
14464 
14465 	return (0);
14466 }
14467 
14468 static int
14469 dtrace_helper_validate(dtrace_helper_action_t *helper)
14470 {
14471 	int err = 0, i;
14472 	dtrace_difo_t *dp;
14473 
14474 	if ((dp = helper->dtha_predicate) != NULL)
14475 		err += dtrace_difo_validate_helper(dp);
14476 
14477 	for (i = 0; i < helper->dtha_nactions; i++)
14478 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14479 
14480 	return (err == 0);
14481 }
14482 
14483 static int
14484 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14485 {
14486 	dtrace_helpers_t *help;
14487 	dtrace_helper_action_t *helper, *last;
14488 	dtrace_actdesc_t *act;
14489 	dtrace_vstate_t *vstate;
14490 	dtrace_predicate_t *pred;
14491 	int count = 0, nactions = 0, i;
14492 
14493 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14494 		return (EINVAL);
14495 
14496 	help = curproc->p_dtrace_helpers;
14497 	last = help->dthps_actions[which];
14498 	vstate = &help->dthps_vstate;
14499 
14500 	for (count = 0; last != NULL; last = last->dtha_next) {
14501 		count++;
14502 		if (last->dtha_next == NULL)
14503 			break;
14504 	}
14505 
14506 	/*
14507 	 * If we already have dtrace_helper_actions_max helper actions for this
14508 	 * helper action type, we'll refuse to add a new one.
14509 	 */
14510 	if (count >= dtrace_helper_actions_max)
14511 		return (ENOSPC);
14512 
14513 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14514 	helper->dtha_generation = help->dthps_generation;
14515 
14516 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14517 		ASSERT(pred->dtp_difo != NULL);
14518 		dtrace_difo_hold(pred->dtp_difo);
14519 		helper->dtha_predicate = pred->dtp_difo;
14520 	}
14521 
14522 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14523 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
14524 			goto err;
14525 
14526 		if (act->dtad_difo == NULL)
14527 			goto err;
14528 
14529 		nactions++;
14530 	}
14531 
14532 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14533 	    (helper->dtha_nactions = nactions), KM_SLEEP);
14534 
14535 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14536 		dtrace_difo_hold(act->dtad_difo);
14537 		helper->dtha_actions[i++] = act->dtad_difo;
14538 	}
14539 
14540 	if (!dtrace_helper_validate(helper))
14541 		goto err;
14542 
14543 	if (last == NULL) {
14544 		help->dthps_actions[which] = helper;
14545 	} else {
14546 		last->dtha_next = helper;
14547 	}
14548 
14549 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14550 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14551 		dtrace_helptrace_next = 0;
14552 	}
14553 
14554 	return (0);
14555 err:
14556 	dtrace_helper_action_destroy(helper, vstate);
14557 	return (EINVAL);
14558 }
14559 
14560 static void
14561 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14562     dof_helper_t *dofhp)
14563 {
14564 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14565 
14566 	mutex_enter(&dtrace_meta_lock);
14567 	mutex_enter(&dtrace_lock);
14568 
14569 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14570 		/*
14571 		 * If the dtrace module is loaded but not attached, or if
14572 		 * there aren't isn't a meta provider registered to deal with
14573 		 * these provider descriptions, we need to postpone creating
14574 		 * the actual providers until later.
14575 		 */
14576 
14577 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14578 		    dtrace_deferred_pid != help) {
14579 			help->dthps_deferred = 1;
14580 			help->dthps_pid = p->p_pid;
14581 			help->dthps_next = dtrace_deferred_pid;
14582 			help->dthps_prev = NULL;
14583 			if (dtrace_deferred_pid != NULL)
14584 				dtrace_deferred_pid->dthps_prev = help;
14585 			dtrace_deferred_pid = help;
14586 		}
14587 
14588 		mutex_exit(&dtrace_lock);
14589 
14590 	} else if (dofhp != NULL) {
14591 		/*
14592 		 * If the dtrace module is loaded and we have a particular
14593 		 * helper provider description, pass that off to the
14594 		 * meta provider.
14595 		 */
14596 
14597 		mutex_exit(&dtrace_lock);
14598 
14599 		dtrace_helper_provide(dofhp, p->p_pid);
14600 
14601 	} else {
14602 		/*
14603 		 * Otherwise, just pass all the helper provider descriptions
14604 		 * off to the meta provider.
14605 		 */
14606 
14607 		int i;
14608 		mutex_exit(&dtrace_lock);
14609 
14610 		for (i = 0; i < help->dthps_nprovs; i++) {
14611 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14612 			    p->p_pid);
14613 		}
14614 	}
14615 
14616 	mutex_exit(&dtrace_meta_lock);
14617 }
14618 
14619 static int
14620 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14621 {
14622 	dtrace_helpers_t *help;
14623 	dtrace_helper_provider_t *hprov, **tmp_provs;
14624 	uint_t tmp_maxprovs, i;
14625 
14626 	ASSERT(MUTEX_HELD(&dtrace_lock));
14627 
14628 	help = curproc->p_dtrace_helpers;
14629 	ASSERT(help != NULL);
14630 
14631 	/*
14632 	 * If we already have dtrace_helper_providers_max helper providers,
14633 	 * we're refuse to add a new one.
14634 	 */
14635 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
14636 		return (ENOSPC);
14637 
14638 	/*
14639 	 * Check to make sure this isn't a duplicate.
14640 	 */
14641 	for (i = 0; i < help->dthps_nprovs; i++) {
14642 		if (dofhp->dofhp_dof ==
14643 		    help->dthps_provs[i]->dthp_prov.dofhp_dof)
14644 			return (EALREADY);
14645 	}
14646 
14647 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14648 	hprov->dthp_prov = *dofhp;
14649 	hprov->dthp_ref = 1;
14650 	hprov->dthp_generation = gen;
14651 
14652 	/*
14653 	 * Allocate a bigger table for helper providers if it's already full.
14654 	 */
14655 	if (help->dthps_maxprovs == help->dthps_nprovs) {
14656 		tmp_maxprovs = help->dthps_maxprovs;
14657 		tmp_provs = help->dthps_provs;
14658 
14659 		if (help->dthps_maxprovs == 0)
14660 			help->dthps_maxprovs = 2;
14661 		else
14662 			help->dthps_maxprovs *= 2;
14663 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
14664 			help->dthps_maxprovs = dtrace_helper_providers_max;
14665 
14666 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14667 
14668 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14669 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14670 
14671 		if (tmp_provs != NULL) {
14672 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14673 			    sizeof (dtrace_helper_provider_t *));
14674 			kmem_free(tmp_provs, tmp_maxprovs *
14675 			    sizeof (dtrace_helper_provider_t *));
14676 		}
14677 	}
14678 
14679 	help->dthps_provs[help->dthps_nprovs] = hprov;
14680 	help->dthps_nprovs++;
14681 
14682 	return (0);
14683 }
14684 
14685 static void
14686 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14687 {
14688 	mutex_enter(&dtrace_lock);
14689 
14690 	if (--hprov->dthp_ref == 0) {
14691 		dof_hdr_t *dof;
14692 		mutex_exit(&dtrace_lock);
14693 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14694 		dtrace_dof_destroy(dof);
14695 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14696 	} else {
14697 		mutex_exit(&dtrace_lock);
14698 	}
14699 }
14700 
14701 static int
14702 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14703 {
14704 	uintptr_t daddr = (uintptr_t)dof;
14705 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14706 	dof_provider_t *provider;
14707 	dof_probe_t *probe;
14708 	uint8_t *arg;
14709 	char *strtab, *typestr;
14710 	dof_stridx_t typeidx;
14711 	size_t typesz;
14712 	uint_t nprobes, j, k;
14713 
14714 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14715 
14716 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14717 		dtrace_dof_error(dof, "misaligned section offset");
14718 		return (-1);
14719 	}
14720 
14721 	/*
14722 	 * The section needs to be large enough to contain the DOF provider
14723 	 * structure appropriate for the given version.
14724 	 */
14725 	if (sec->dofs_size <
14726 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14727 	    offsetof(dof_provider_t, dofpv_prenoffs) :
14728 	    sizeof (dof_provider_t))) {
14729 		dtrace_dof_error(dof, "provider section too small");
14730 		return (-1);
14731 	}
14732 
14733 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14734 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14735 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14736 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14737 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14738 
14739 	if (str_sec == NULL || prb_sec == NULL ||
14740 	    arg_sec == NULL || off_sec == NULL)
14741 		return (-1);
14742 
14743 	enoff_sec = NULL;
14744 
14745 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14746 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
14747 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14748 	    provider->dofpv_prenoffs)) == NULL)
14749 		return (-1);
14750 
14751 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14752 
14753 	if (provider->dofpv_name >= str_sec->dofs_size ||
14754 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14755 		dtrace_dof_error(dof, "invalid provider name");
14756 		return (-1);
14757 	}
14758 
14759 	if (prb_sec->dofs_entsize == 0 ||
14760 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
14761 		dtrace_dof_error(dof, "invalid entry size");
14762 		return (-1);
14763 	}
14764 
14765 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14766 		dtrace_dof_error(dof, "misaligned entry size");
14767 		return (-1);
14768 	}
14769 
14770 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14771 		dtrace_dof_error(dof, "invalid entry size");
14772 		return (-1);
14773 	}
14774 
14775 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14776 		dtrace_dof_error(dof, "misaligned section offset");
14777 		return (-1);
14778 	}
14779 
14780 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14781 		dtrace_dof_error(dof, "invalid entry size");
14782 		return (-1);
14783 	}
14784 
14785 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14786 
14787 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14788 
14789 	/*
14790 	 * Take a pass through the probes to check for errors.
14791 	 */
14792 	for (j = 0; j < nprobes; j++) {
14793 		probe = (dof_probe_t *)(uintptr_t)(daddr +
14794 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14795 
14796 		if (probe->dofpr_func >= str_sec->dofs_size) {
14797 			dtrace_dof_error(dof, "invalid function name");
14798 			return (-1);
14799 		}
14800 
14801 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14802 			dtrace_dof_error(dof, "function name too long");
14803 			return (-1);
14804 		}
14805 
14806 		if (probe->dofpr_name >= str_sec->dofs_size ||
14807 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14808 			dtrace_dof_error(dof, "invalid probe name");
14809 			return (-1);
14810 		}
14811 
14812 		/*
14813 		 * The offset count must not wrap the index, and the offsets
14814 		 * must also not overflow the section's data.
14815 		 */
14816 		if (probe->dofpr_offidx + probe->dofpr_noffs <
14817 		    probe->dofpr_offidx ||
14818 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
14819 		    off_sec->dofs_entsize > off_sec->dofs_size) {
14820 			dtrace_dof_error(dof, "invalid probe offset");
14821 			return (-1);
14822 		}
14823 
14824 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14825 			/*
14826 			 * If there's no is-enabled offset section, make sure
14827 			 * there aren't any is-enabled offsets. Otherwise
14828 			 * perform the same checks as for probe offsets
14829 			 * (immediately above).
14830 			 */
14831 			if (enoff_sec == NULL) {
14832 				if (probe->dofpr_enoffidx != 0 ||
14833 				    probe->dofpr_nenoffs != 0) {
14834 					dtrace_dof_error(dof, "is-enabled "
14835 					    "offsets with null section");
14836 					return (-1);
14837 				}
14838 			} else if (probe->dofpr_enoffidx +
14839 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14840 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14841 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14842 				dtrace_dof_error(dof, "invalid is-enabled "
14843 				    "offset");
14844 				return (-1);
14845 			}
14846 
14847 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14848 				dtrace_dof_error(dof, "zero probe and "
14849 				    "is-enabled offsets");
14850 				return (-1);
14851 			}
14852 		} else if (probe->dofpr_noffs == 0) {
14853 			dtrace_dof_error(dof, "zero probe offsets");
14854 			return (-1);
14855 		}
14856 
14857 		if (probe->dofpr_argidx + probe->dofpr_xargc <
14858 		    probe->dofpr_argidx ||
14859 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
14860 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
14861 			dtrace_dof_error(dof, "invalid args");
14862 			return (-1);
14863 		}
14864 
14865 		typeidx = probe->dofpr_nargv;
14866 		typestr = strtab + probe->dofpr_nargv;
14867 		for (k = 0; k < probe->dofpr_nargc; k++) {
14868 			if (typeidx >= str_sec->dofs_size) {
14869 				dtrace_dof_error(dof, "bad "
14870 				    "native argument type");
14871 				return (-1);
14872 			}
14873 
14874 			typesz = strlen(typestr) + 1;
14875 			if (typesz > DTRACE_ARGTYPELEN) {
14876 				dtrace_dof_error(dof, "native "
14877 				    "argument type too long");
14878 				return (-1);
14879 			}
14880 			typeidx += typesz;
14881 			typestr += typesz;
14882 		}
14883 
14884 		typeidx = probe->dofpr_xargv;
14885 		typestr = strtab + probe->dofpr_xargv;
14886 		for (k = 0; k < probe->dofpr_xargc; k++) {
14887 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14888 				dtrace_dof_error(dof, "bad "
14889 				    "native argument index");
14890 				return (-1);
14891 			}
14892 
14893 			if (typeidx >= str_sec->dofs_size) {
14894 				dtrace_dof_error(dof, "bad "
14895 				    "translated argument type");
14896 				return (-1);
14897 			}
14898 
14899 			typesz = strlen(typestr) + 1;
14900 			if (typesz > DTRACE_ARGTYPELEN) {
14901 				dtrace_dof_error(dof, "translated argument "
14902 				    "type too long");
14903 				return (-1);
14904 			}
14905 
14906 			typeidx += typesz;
14907 			typestr += typesz;
14908 		}
14909 	}
14910 
14911 	return (0);
14912 }
14913 
14914 static int
14915 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14916 {
14917 	dtrace_helpers_t *help;
14918 	dtrace_vstate_t *vstate;
14919 	dtrace_enabling_t *enab = NULL;
14920 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14921 	uintptr_t daddr = (uintptr_t)dof;
14922 
14923 	ASSERT(MUTEX_HELD(&dtrace_lock));
14924 
14925 	if ((help = curproc->p_dtrace_helpers) == NULL)
14926 		help = dtrace_helpers_create(curproc);
14927 
14928 	vstate = &help->dthps_vstate;
14929 
14930 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14931 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14932 		dtrace_dof_destroy(dof);
14933 		return (rv);
14934 	}
14935 
14936 	/*
14937 	 * Look for helper providers and validate their descriptions.
14938 	 */
14939 	if (dhp != NULL) {
14940 		for (i = 0; i < dof->dofh_secnum; i++) {
14941 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14942 			    dof->dofh_secoff + i * dof->dofh_secsize);
14943 
14944 			if (sec->dofs_type != DOF_SECT_PROVIDER)
14945 				continue;
14946 
14947 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
14948 				dtrace_enabling_destroy(enab);
14949 				dtrace_dof_destroy(dof);
14950 				return (-1);
14951 			}
14952 
14953 			nprovs++;
14954 		}
14955 	}
14956 
14957 	/*
14958 	 * Now we need to walk through the ECB descriptions in the enabling.
14959 	 */
14960 	for (i = 0; i < enab->dten_ndesc; i++) {
14961 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14962 		dtrace_probedesc_t *desc = &ep->dted_probe;
14963 
14964 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14965 			continue;
14966 
14967 		if (strcmp(desc->dtpd_mod, "helper") != 0)
14968 			continue;
14969 
14970 		if (strcmp(desc->dtpd_func, "ustack") != 0)
14971 			continue;
14972 
14973 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14974 		    ep)) != 0) {
14975 			/*
14976 			 * Adding this helper action failed -- we are now going
14977 			 * to rip out the entire generation and return failure.
14978 			 */
14979 			(void) dtrace_helper_destroygen(help->dthps_generation);
14980 			dtrace_enabling_destroy(enab);
14981 			dtrace_dof_destroy(dof);
14982 			return (-1);
14983 		}
14984 
14985 		nhelpers++;
14986 	}
14987 
14988 	if (nhelpers < enab->dten_ndesc)
14989 		dtrace_dof_error(dof, "unmatched helpers");
14990 
14991 	gen = help->dthps_generation++;
14992 	dtrace_enabling_destroy(enab);
14993 
14994 	if (dhp != NULL && nprovs > 0) {
14995 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14996 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
14997 			mutex_exit(&dtrace_lock);
14998 			dtrace_helper_provider_register(curproc, help, dhp);
14999 			mutex_enter(&dtrace_lock);
15000 
15001 			destroy = 0;
15002 		}
15003 	}
15004 
15005 	if (destroy)
15006 		dtrace_dof_destroy(dof);
15007 
15008 	return (gen);
15009 }
15010 
15011 static dtrace_helpers_t *
15012 dtrace_helpers_create(proc_t *p)
15013 {
15014 	dtrace_helpers_t *help;
15015 
15016 	ASSERT(MUTEX_HELD(&dtrace_lock));
15017 	ASSERT(p->p_dtrace_helpers == NULL);
15018 
15019 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15020 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15021 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15022 
15023 	p->p_dtrace_helpers = help;
15024 	dtrace_helpers++;
15025 
15026 	return (help);
15027 }
15028 
15029 #if defined(sun)
15030 static
15031 #endif
15032 void
15033 dtrace_helpers_destroy(proc_t *p)
15034 {
15035 	dtrace_helpers_t *help;
15036 	dtrace_vstate_t *vstate;
15037 #if defined(sun)
15038 	proc_t *p = curproc;
15039 #endif
15040 	int i;
15041 
15042 	mutex_enter(&dtrace_lock);
15043 
15044 	ASSERT(p->p_dtrace_helpers != NULL);
15045 	ASSERT(dtrace_helpers > 0);
15046 
15047 	help = p->p_dtrace_helpers;
15048 	vstate = &help->dthps_vstate;
15049 
15050 	/*
15051 	 * We're now going to lose the help from this process.
15052 	 */
15053 	p->p_dtrace_helpers = NULL;
15054 	dtrace_sync();
15055 
15056 	/*
15057 	 * Destory the helper actions.
15058 	 */
15059 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15060 		dtrace_helper_action_t *h, *next;
15061 
15062 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15063 			next = h->dtha_next;
15064 			dtrace_helper_action_destroy(h, vstate);
15065 			h = next;
15066 		}
15067 	}
15068 
15069 	mutex_exit(&dtrace_lock);
15070 
15071 	/*
15072 	 * Destroy the helper providers.
15073 	 */
15074 	if (help->dthps_maxprovs > 0) {
15075 		mutex_enter(&dtrace_meta_lock);
15076 		if (dtrace_meta_pid != NULL) {
15077 			ASSERT(dtrace_deferred_pid == NULL);
15078 
15079 			for (i = 0; i < help->dthps_nprovs; i++) {
15080 				dtrace_helper_provider_remove(
15081 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15082 			}
15083 		} else {
15084 			mutex_enter(&dtrace_lock);
15085 			ASSERT(help->dthps_deferred == 0 ||
15086 			    help->dthps_next != NULL ||
15087 			    help->dthps_prev != NULL ||
15088 			    help == dtrace_deferred_pid);
15089 
15090 			/*
15091 			 * Remove the helper from the deferred list.
15092 			 */
15093 			if (help->dthps_next != NULL)
15094 				help->dthps_next->dthps_prev = help->dthps_prev;
15095 			if (help->dthps_prev != NULL)
15096 				help->dthps_prev->dthps_next = help->dthps_next;
15097 			if (dtrace_deferred_pid == help) {
15098 				dtrace_deferred_pid = help->dthps_next;
15099 				ASSERT(help->dthps_prev == NULL);
15100 			}
15101 
15102 			mutex_exit(&dtrace_lock);
15103 		}
15104 
15105 		mutex_exit(&dtrace_meta_lock);
15106 
15107 		for (i = 0; i < help->dthps_nprovs; i++) {
15108 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15109 		}
15110 
15111 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15112 		    sizeof (dtrace_helper_provider_t *));
15113 	}
15114 
15115 	mutex_enter(&dtrace_lock);
15116 
15117 	dtrace_vstate_fini(&help->dthps_vstate);
15118 	kmem_free(help->dthps_actions,
15119 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15120 	kmem_free(help, sizeof (dtrace_helpers_t));
15121 
15122 	--dtrace_helpers;
15123 	mutex_exit(&dtrace_lock);
15124 }
15125 
15126 #if defined(sun)
15127 static
15128 #endif
15129 void
15130 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15131 {
15132 	dtrace_helpers_t *help, *newhelp;
15133 	dtrace_helper_action_t *helper, *new, *last;
15134 	dtrace_difo_t *dp;
15135 	dtrace_vstate_t *vstate;
15136 	int i, j, sz, hasprovs = 0;
15137 
15138 	mutex_enter(&dtrace_lock);
15139 	ASSERT(from->p_dtrace_helpers != NULL);
15140 	ASSERT(dtrace_helpers > 0);
15141 
15142 	help = from->p_dtrace_helpers;
15143 	newhelp = dtrace_helpers_create(to);
15144 	ASSERT(to->p_dtrace_helpers != NULL);
15145 
15146 	newhelp->dthps_generation = help->dthps_generation;
15147 	vstate = &newhelp->dthps_vstate;
15148 
15149 	/*
15150 	 * Duplicate the helper actions.
15151 	 */
15152 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15153 		if ((helper = help->dthps_actions[i]) == NULL)
15154 			continue;
15155 
15156 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15157 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15158 			    KM_SLEEP);
15159 			new->dtha_generation = helper->dtha_generation;
15160 
15161 			if ((dp = helper->dtha_predicate) != NULL) {
15162 				dp = dtrace_difo_duplicate(dp, vstate);
15163 				new->dtha_predicate = dp;
15164 			}
15165 
15166 			new->dtha_nactions = helper->dtha_nactions;
15167 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15168 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15169 
15170 			for (j = 0; j < new->dtha_nactions; j++) {
15171 				dtrace_difo_t *dp = helper->dtha_actions[j];
15172 
15173 				ASSERT(dp != NULL);
15174 				dp = dtrace_difo_duplicate(dp, vstate);
15175 				new->dtha_actions[j] = dp;
15176 			}
15177 
15178 			if (last != NULL) {
15179 				last->dtha_next = new;
15180 			} else {
15181 				newhelp->dthps_actions[i] = new;
15182 			}
15183 
15184 			last = new;
15185 		}
15186 	}
15187 
15188 	/*
15189 	 * Duplicate the helper providers and register them with the
15190 	 * DTrace framework.
15191 	 */
15192 	if (help->dthps_nprovs > 0) {
15193 		newhelp->dthps_nprovs = help->dthps_nprovs;
15194 		newhelp->dthps_maxprovs = help->dthps_nprovs;
15195 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15196 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15197 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15198 			newhelp->dthps_provs[i] = help->dthps_provs[i];
15199 			newhelp->dthps_provs[i]->dthp_ref++;
15200 		}
15201 
15202 		hasprovs = 1;
15203 	}
15204 
15205 	mutex_exit(&dtrace_lock);
15206 
15207 	if (hasprovs)
15208 		dtrace_helper_provider_register(to, newhelp, NULL);
15209 }
15210 
15211 /*
15212  * DTrace Hook Functions
15213  */
15214 static void
15215 dtrace_module_loaded(modctl_t *ctl)
15216 {
15217 	dtrace_provider_t *prv;
15218 
15219 	mutex_enter(&dtrace_provider_lock);
15220 #if defined(sun)
15221 	mutex_enter(&mod_lock);
15222 #endif
15223 
15224 #if defined(sun)
15225 	ASSERT(ctl->mod_busy);
15226 #endif
15227 
15228 	/*
15229 	 * We're going to call each providers per-module provide operation
15230 	 * specifying only this module.
15231 	 */
15232 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15233 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15234 
15235 #if defined(sun)
15236 	mutex_exit(&mod_lock);
15237 #endif
15238 	mutex_exit(&dtrace_provider_lock);
15239 
15240 	/*
15241 	 * If we have any retained enablings, we need to match against them.
15242 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15243 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15244 	 * module.  (In particular, this happens when loading scheduling
15245 	 * classes.)  So if we have any retained enablings, we need to dispatch
15246 	 * our task queue to do the match for us.
15247 	 */
15248 	mutex_enter(&dtrace_lock);
15249 
15250 	if (dtrace_retained == NULL) {
15251 		mutex_exit(&dtrace_lock);
15252 		return;
15253 	}
15254 
15255 	(void) taskq_dispatch(dtrace_taskq,
15256 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15257 
15258 	mutex_exit(&dtrace_lock);
15259 
15260 	/*
15261 	 * And now, for a little heuristic sleaze:  in general, we want to
15262 	 * match modules as soon as they load.  However, we cannot guarantee
15263 	 * this, because it would lead us to the lock ordering violation
15264 	 * outlined above.  The common case, of course, is that cpu_lock is
15265 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15266 	 * long enough for the task queue to do its work.  If it's not, it's
15267 	 * not a serious problem -- it just means that the module that we
15268 	 * just loaded may not be immediately instrumentable.
15269 	 */
15270 	delay(1);
15271 }
15272 
15273 static void
15274 #if defined(sun)
15275 dtrace_module_unloaded(modctl_t *ctl)
15276 #else
15277 dtrace_module_unloaded(modctl_t *ctl, int *error)
15278 #endif
15279 {
15280 	dtrace_probe_t template, *probe, *first, *next;
15281 	dtrace_provider_t *prov;
15282 #if !defined(sun)
15283 	char modname[DTRACE_MODNAMELEN];
15284 	size_t len;
15285 #endif
15286 
15287 #if defined(sun)
15288 	template.dtpr_mod = ctl->mod_modname;
15289 #else
15290 	/* Handle the fact that ctl->filename may end in ".ko". */
15291 	strlcpy(modname, ctl->filename, sizeof(modname));
15292 	len = strlen(ctl->filename);
15293 	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15294 		modname[len - 3] = '\0';
15295 	template.dtpr_mod = modname;
15296 #endif
15297 
15298 	mutex_enter(&dtrace_provider_lock);
15299 #if defined(sun)
15300 	mutex_enter(&mod_lock);
15301 #endif
15302 	mutex_enter(&dtrace_lock);
15303 
15304 #if !defined(sun)
15305 	if (ctl->nenabled > 0) {
15306 		/* Don't allow unloads if a probe is enabled. */
15307 		mutex_exit(&dtrace_provider_lock);
15308 		mutex_exit(&dtrace_lock);
15309 		*error = -1;
15310 		printf(
15311 	"kldunload: attempt to unload module that has DTrace probes enabled\n");
15312 		return;
15313 	}
15314 #endif
15315 
15316 	if (dtrace_bymod == NULL) {
15317 		/*
15318 		 * The DTrace module is loaded (obviously) but not attached;
15319 		 * we don't have any work to do.
15320 		 */
15321 		mutex_exit(&dtrace_provider_lock);
15322 #if defined(sun)
15323 		mutex_exit(&mod_lock);
15324 #endif
15325 		mutex_exit(&dtrace_lock);
15326 		return;
15327 	}
15328 
15329 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15330 	    probe != NULL; probe = probe->dtpr_nextmod) {
15331 		if (probe->dtpr_ecb != NULL) {
15332 			mutex_exit(&dtrace_provider_lock);
15333 #if defined(sun)
15334 			mutex_exit(&mod_lock);
15335 #endif
15336 			mutex_exit(&dtrace_lock);
15337 
15338 			/*
15339 			 * This shouldn't _actually_ be possible -- we're
15340 			 * unloading a module that has an enabled probe in it.
15341 			 * (It's normally up to the provider to make sure that
15342 			 * this can't happen.)  However, because dtps_enable()
15343 			 * doesn't have a failure mode, there can be an
15344 			 * enable/unload race.  Upshot:  we don't want to
15345 			 * assert, but we're not going to disable the
15346 			 * probe, either.
15347 			 */
15348 			if (dtrace_err_verbose) {
15349 #if defined(sun)
15350 				cmn_err(CE_WARN, "unloaded module '%s' had "
15351 				    "enabled probes", ctl->mod_modname);
15352 #else
15353 				cmn_err(CE_WARN, "unloaded module '%s' had "
15354 				    "enabled probes", modname);
15355 #endif
15356 			}
15357 
15358 			return;
15359 		}
15360 	}
15361 
15362 	probe = first;
15363 
15364 	for (first = NULL; probe != NULL; probe = next) {
15365 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15366 
15367 		dtrace_probes[probe->dtpr_id - 1] = NULL;
15368 
15369 		next = probe->dtpr_nextmod;
15370 		dtrace_hash_remove(dtrace_bymod, probe);
15371 		dtrace_hash_remove(dtrace_byfunc, probe);
15372 		dtrace_hash_remove(dtrace_byname, probe);
15373 
15374 		if (first == NULL) {
15375 			first = probe;
15376 			probe->dtpr_nextmod = NULL;
15377 		} else {
15378 			probe->dtpr_nextmod = first;
15379 			first = probe;
15380 		}
15381 	}
15382 
15383 	/*
15384 	 * We've removed all of the module's probes from the hash chains and
15385 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15386 	 * everyone has cleared out from any probe array processing.
15387 	 */
15388 	dtrace_sync();
15389 
15390 	for (probe = first; probe != NULL; probe = first) {
15391 		first = probe->dtpr_nextmod;
15392 		prov = probe->dtpr_provider;
15393 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15394 		    probe->dtpr_arg);
15395 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15396 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15397 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15398 #if defined(sun)
15399 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15400 #else
15401 		free_unr(dtrace_arena, probe->dtpr_id);
15402 #endif
15403 		kmem_free(probe, sizeof (dtrace_probe_t));
15404 	}
15405 
15406 	mutex_exit(&dtrace_lock);
15407 #if defined(sun)
15408 	mutex_exit(&mod_lock);
15409 #endif
15410 	mutex_exit(&dtrace_provider_lock);
15411 }
15412 
15413 #if !defined(sun)
15414 static void
15415 dtrace_kld_load(void *arg __unused, linker_file_t lf)
15416 {
15417 
15418 	dtrace_module_loaded(lf);
15419 }
15420 
15421 static void
15422 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
15423 {
15424 
15425 	if (*error != 0)
15426 		/* We already have an error, so don't do anything. */
15427 		return;
15428 	dtrace_module_unloaded(lf, error);
15429 }
15430 #endif
15431 
15432 #if defined(sun)
15433 static void
15434 dtrace_suspend(void)
15435 {
15436 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15437 }
15438 
15439 static void
15440 dtrace_resume(void)
15441 {
15442 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15443 }
15444 #endif
15445 
15446 static int
15447 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15448 {
15449 	ASSERT(MUTEX_HELD(&cpu_lock));
15450 	mutex_enter(&dtrace_lock);
15451 
15452 	switch (what) {
15453 	case CPU_CONFIG: {
15454 		dtrace_state_t *state;
15455 		dtrace_optval_t *opt, rs, c;
15456 
15457 		/*
15458 		 * For now, we only allocate a new buffer for anonymous state.
15459 		 */
15460 		if ((state = dtrace_anon.dta_state) == NULL)
15461 			break;
15462 
15463 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15464 			break;
15465 
15466 		opt = state->dts_options;
15467 		c = opt[DTRACEOPT_CPU];
15468 
15469 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15470 			break;
15471 
15472 		/*
15473 		 * Regardless of what the actual policy is, we're going to
15474 		 * temporarily set our resize policy to be manual.  We're
15475 		 * also going to temporarily set our CPU option to denote
15476 		 * the newly configured CPU.
15477 		 */
15478 		rs = opt[DTRACEOPT_BUFRESIZE];
15479 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15480 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15481 
15482 		(void) dtrace_state_buffers(state);
15483 
15484 		opt[DTRACEOPT_BUFRESIZE] = rs;
15485 		opt[DTRACEOPT_CPU] = c;
15486 
15487 		break;
15488 	}
15489 
15490 	case CPU_UNCONFIG:
15491 		/*
15492 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
15493 		 * buffer will be freed when the consumer exits.)
15494 		 */
15495 		break;
15496 
15497 	default:
15498 		break;
15499 	}
15500 
15501 	mutex_exit(&dtrace_lock);
15502 	return (0);
15503 }
15504 
15505 #if defined(sun)
15506 static void
15507 dtrace_cpu_setup_initial(processorid_t cpu)
15508 {
15509 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15510 }
15511 #endif
15512 
15513 static void
15514 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15515 {
15516 	if (dtrace_toxranges >= dtrace_toxranges_max) {
15517 		int osize, nsize;
15518 		dtrace_toxrange_t *range;
15519 
15520 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15521 
15522 		if (osize == 0) {
15523 			ASSERT(dtrace_toxrange == NULL);
15524 			ASSERT(dtrace_toxranges_max == 0);
15525 			dtrace_toxranges_max = 1;
15526 		} else {
15527 			dtrace_toxranges_max <<= 1;
15528 		}
15529 
15530 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15531 		range = kmem_zalloc(nsize, KM_SLEEP);
15532 
15533 		if (dtrace_toxrange != NULL) {
15534 			ASSERT(osize != 0);
15535 			bcopy(dtrace_toxrange, range, osize);
15536 			kmem_free(dtrace_toxrange, osize);
15537 		}
15538 
15539 		dtrace_toxrange = range;
15540 	}
15541 
15542 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15543 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15544 
15545 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15546 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15547 	dtrace_toxranges++;
15548 }
15549 
15550 /*
15551  * DTrace Driver Cookbook Functions
15552  */
15553 #if defined(sun)
15554 /*ARGSUSED*/
15555 static int
15556 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15557 {
15558 	dtrace_provider_id_t id;
15559 	dtrace_state_t *state = NULL;
15560 	dtrace_enabling_t *enab;
15561 
15562 	mutex_enter(&cpu_lock);
15563 	mutex_enter(&dtrace_provider_lock);
15564 	mutex_enter(&dtrace_lock);
15565 
15566 	if (ddi_soft_state_init(&dtrace_softstate,
15567 	    sizeof (dtrace_state_t), 0) != 0) {
15568 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15569 		mutex_exit(&cpu_lock);
15570 		mutex_exit(&dtrace_provider_lock);
15571 		mutex_exit(&dtrace_lock);
15572 		return (DDI_FAILURE);
15573 	}
15574 
15575 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15576 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15577 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15578 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15579 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15580 		ddi_remove_minor_node(devi, NULL);
15581 		ddi_soft_state_fini(&dtrace_softstate);
15582 		mutex_exit(&cpu_lock);
15583 		mutex_exit(&dtrace_provider_lock);
15584 		mutex_exit(&dtrace_lock);
15585 		return (DDI_FAILURE);
15586 	}
15587 
15588 	ddi_report_dev(devi);
15589 	dtrace_devi = devi;
15590 
15591 	dtrace_modload = dtrace_module_loaded;
15592 	dtrace_modunload = dtrace_module_unloaded;
15593 	dtrace_cpu_init = dtrace_cpu_setup_initial;
15594 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
15595 	dtrace_helpers_fork = dtrace_helpers_duplicate;
15596 	dtrace_cpustart_init = dtrace_suspend;
15597 	dtrace_cpustart_fini = dtrace_resume;
15598 	dtrace_debugger_init = dtrace_suspend;
15599 	dtrace_debugger_fini = dtrace_resume;
15600 
15601 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15602 
15603 	ASSERT(MUTEX_HELD(&cpu_lock));
15604 
15605 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15606 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15607 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15608 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15609 	    VM_SLEEP | VMC_IDENTIFIER);
15610 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15611 	    1, INT_MAX, 0);
15612 
15613 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15614 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15615 	    NULL, NULL, NULL, NULL, NULL, 0);
15616 
15617 	ASSERT(MUTEX_HELD(&cpu_lock));
15618 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15619 	    offsetof(dtrace_probe_t, dtpr_nextmod),
15620 	    offsetof(dtrace_probe_t, dtpr_prevmod));
15621 
15622 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15623 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
15624 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
15625 
15626 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15627 	    offsetof(dtrace_probe_t, dtpr_nextname),
15628 	    offsetof(dtrace_probe_t, dtpr_prevname));
15629 
15630 	if (dtrace_retain_max < 1) {
15631 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15632 		    "setting to 1", dtrace_retain_max);
15633 		dtrace_retain_max = 1;
15634 	}
15635 
15636 	/*
15637 	 * Now discover our toxic ranges.
15638 	 */
15639 	dtrace_toxic_ranges(dtrace_toxrange_add);
15640 
15641 	/*
15642 	 * Before we register ourselves as a provider to our own framework,
15643 	 * we would like to assert that dtrace_provider is NULL -- but that's
15644 	 * not true if we were loaded as a dependency of a DTrace provider.
15645 	 * Once we've registered, we can assert that dtrace_provider is our
15646 	 * pseudo provider.
15647 	 */
15648 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
15649 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15650 
15651 	ASSERT(dtrace_provider != NULL);
15652 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15653 
15654 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15655 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15656 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15657 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
15658 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15659 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15660 
15661 	dtrace_anon_property();
15662 	mutex_exit(&cpu_lock);
15663 
15664 	/*
15665 	 * If DTrace helper tracing is enabled, we need to allocate the
15666 	 * trace buffer and initialize the values.
15667 	 */
15668 	if (dtrace_helptrace_enabled) {
15669 		ASSERT(dtrace_helptrace_buffer == NULL);
15670 		dtrace_helptrace_buffer =
15671 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15672 		dtrace_helptrace_next = 0;
15673 	}
15674 
15675 	/*
15676 	 * If there are already providers, we must ask them to provide their
15677 	 * probes, and then match any anonymous enabling against them.  Note
15678 	 * that there should be no other retained enablings at this time:
15679 	 * the only retained enablings at this time should be the anonymous
15680 	 * enabling.
15681 	 */
15682 	if (dtrace_anon.dta_enabling != NULL) {
15683 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15684 
15685 		dtrace_enabling_provide(NULL);
15686 		state = dtrace_anon.dta_state;
15687 
15688 		/*
15689 		 * We couldn't hold cpu_lock across the above call to
15690 		 * dtrace_enabling_provide(), but we must hold it to actually
15691 		 * enable the probes.  We have to drop all of our locks, pick
15692 		 * up cpu_lock, and regain our locks before matching the
15693 		 * retained anonymous enabling.
15694 		 */
15695 		mutex_exit(&dtrace_lock);
15696 		mutex_exit(&dtrace_provider_lock);
15697 
15698 		mutex_enter(&cpu_lock);
15699 		mutex_enter(&dtrace_provider_lock);
15700 		mutex_enter(&dtrace_lock);
15701 
15702 		if ((enab = dtrace_anon.dta_enabling) != NULL)
15703 			(void) dtrace_enabling_match(enab, NULL);
15704 
15705 		mutex_exit(&cpu_lock);
15706 	}
15707 
15708 	mutex_exit(&dtrace_lock);
15709 	mutex_exit(&dtrace_provider_lock);
15710 
15711 	if (state != NULL) {
15712 		/*
15713 		 * If we created any anonymous state, set it going now.
15714 		 */
15715 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15716 	}
15717 
15718 	return (DDI_SUCCESS);
15719 }
15720 #endif
15721 
15722 #if !defined(sun)
15723 #if __FreeBSD_version >= 800039
15724 static void
15725 dtrace_dtr(void *data __unused)
15726 {
15727 }
15728 #endif
15729 #endif
15730 
15731 /*ARGSUSED*/
15732 static int
15733 #if defined(sun)
15734 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15735 #else
15736 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
15737 #endif
15738 {
15739 	dtrace_state_t *state;
15740 	uint32_t priv;
15741 	uid_t uid;
15742 	zoneid_t zoneid;
15743 
15744 #if defined(sun)
15745 	if (getminor(*devp) == DTRACEMNRN_HELPER)
15746 		return (0);
15747 
15748 	/*
15749 	 * If this wasn't an open with the "helper" minor, then it must be
15750 	 * the "dtrace" minor.
15751 	 */
15752 	if (getminor(*devp) == DTRACEMNRN_DTRACE)
15753 		return (ENXIO);
15754 #else
15755 	cred_t *cred_p = NULL;
15756 
15757 #if __FreeBSD_version < 800039
15758 	/*
15759 	 * The first minor device is the one that is cloned so there is
15760 	 * nothing more to do here.
15761 	 */
15762 	if (dev2unit(dev) == 0)
15763 		return 0;
15764 
15765 	/*
15766 	 * Devices are cloned, so if the DTrace state has already
15767 	 * been allocated, that means this device belongs to a
15768 	 * different client. Each client should open '/dev/dtrace'
15769 	 * to get a cloned device.
15770 	 */
15771 	if (dev->si_drv1 != NULL)
15772 		return (EBUSY);
15773 #endif
15774 
15775 	cred_p = dev->si_cred;
15776 #endif
15777 
15778 	/*
15779 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
15780 	 * caller lacks sufficient permission to do anything with DTrace.
15781 	 */
15782 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15783 	if (priv == DTRACE_PRIV_NONE) {
15784 #if !defined(sun)
15785 #if __FreeBSD_version < 800039
15786 		/* Destroy the cloned device. */
15787                 destroy_dev(dev);
15788 #endif
15789 #endif
15790 
15791 		return (EACCES);
15792 	}
15793 
15794 	/*
15795 	 * Ask all providers to provide all their probes.
15796 	 */
15797 	mutex_enter(&dtrace_provider_lock);
15798 	dtrace_probe_provide(NULL, NULL);
15799 	mutex_exit(&dtrace_provider_lock);
15800 
15801 	mutex_enter(&cpu_lock);
15802 	mutex_enter(&dtrace_lock);
15803 	dtrace_opens++;
15804 	dtrace_membar_producer();
15805 
15806 #if defined(sun)
15807 	/*
15808 	 * If the kernel debugger is active (that is, if the kernel debugger
15809 	 * modified text in some way), we won't allow the open.
15810 	 */
15811 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15812 		dtrace_opens--;
15813 		mutex_exit(&cpu_lock);
15814 		mutex_exit(&dtrace_lock);
15815 		return (EBUSY);
15816 	}
15817 
15818 	state = dtrace_state_create(devp, cred_p);
15819 #else
15820 	state = dtrace_state_create(dev);
15821 #if __FreeBSD_version < 800039
15822 	dev->si_drv1 = state;
15823 #else
15824 	devfs_set_cdevpriv(state, dtrace_dtr);
15825 #endif
15826 #endif
15827 
15828 	mutex_exit(&cpu_lock);
15829 
15830 	if (state == NULL) {
15831 #if defined(sun)
15832 		if (--dtrace_opens == 0)
15833 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15834 #else
15835 		--dtrace_opens;
15836 #endif
15837 		mutex_exit(&dtrace_lock);
15838 #if !defined(sun)
15839 #if __FreeBSD_version < 800039
15840 		/* Destroy the cloned device. */
15841                 destroy_dev(dev);
15842 #endif
15843 #endif
15844 		return (EAGAIN);
15845 	}
15846 
15847 	mutex_exit(&dtrace_lock);
15848 
15849 	return (0);
15850 }
15851 
15852 /*ARGSUSED*/
15853 static int
15854 #if defined(sun)
15855 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15856 #else
15857 dtrace_close(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
15858 #endif
15859 {
15860 #if defined(sun)
15861 	minor_t minor = getminor(dev);
15862 	dtrace_state_t *state;
15863 
15864 	if (minor == DTRACEMNRN_HELPER)
15865 		return (0);
15866 
15867 	state = ddi_get_soft_state(dtrace_softstate, minor);
15868 #else
15869 #if __FreeBSD_version < 800039
15870 	dtrace_state_t *state = dev->si_drv1;
15871 
15872 	/* Check if this is not a cloned device. */
15873 	if (dev2unit(dev) == 0)
15874 		return (0);
15875 #else
15876 	dtrace_state_t *state;
15877 	devfs_get_cdevpriv((void **) &state);
15878 #endif
15879 
15880 #endif
15881 
15882 	mutex_enter(&cpu_lock);
15883 	mutex_enter(&dtrace_lock);
15884 
15885 	if (state != NULL) {
15886 		if (state->dts_anon) {
15887 			/*
15888 			 * There is anonymous state. Destroy that first.
15889 			 */
15890 			ASSERT(dtrace_anon.dta_state == NULL);
15891 			dtrace_state_destroy(state->dts_anon);
15892 		}
15893 
15894 		dtrace_state_destroy(state);
15895 
15896 #if !defined(sun)
15897 		kmem_free(state, 0);
15898 #if __FreeBSD_version < 800039
15899 		dev->si_drv1 = NULL;
15900 #endif
15901 #endif
15902 	}
15903 
15904 	ASSERT(dtrace_opens > 0);
15905 #if defined(sun)
15906 	if (--dtrace_opens == 0)
15907 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15908 #else
15909 	--dtrace_opens;
15910 #endif
15911 
15912 	mutex_exit(&dtrace_lock);
15913 	mutex_exit(&cpu_lock);
15914 
15915 #if __FreeBSD_version < 800039
15916 	/* Schedule this cloned device to be destroyed. */
15917 	destroy_dev_sched(dev);
15918 #endif
15919 
15920 	return (0);
15921 }
15922 
15923 #if defined(sun)
15924 /*ARGSUSED*/
15925 static int
15926 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15927 {
15928 	int rval;
15929 	dof_helper_t help, *dhp = NULL;
15930 
15931 	switch (cmd) {
15932 	case DTRACEHIOC_ADDDOF:
15933 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15934 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
15935 			return (EFAULT);
15936 		}
15937 
15938 		dhp = &help;
15939 		arg = (intptr_t)help.dofhp_dof;
15940 		/*FALLTHROUGH*/
15941 
15942 	case DTRACEHIOC_ADD: {
15943 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15944 
15945 		if (dof == NULL)
15946 			return (rval);
15947 
15948 		mutex_enter(&dtrace_lock);
15949 
15950 		/*
15951 		 * dtrace_helper_slurp() takes responsibility for the dof --
15952 		 * it may free it now or it may save it and free it later.
15953 		 */
15954 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15955 			*rv = rval;
15956 			rval = 0;
15957 		} else {
15958 			rval = EINVAL;
15959 		}
15960 
15961 		mutex_exit(&dtrace_lock);
15962 		return (rval);
15963 	}
15964 
15965 	case DTRACEHIOC_REMOVE: {
15966 		mutex_enter(&dtrace_lock);
15967 		rval = dtrace_helper_destroygen(arg);
15968 		mutex_exit(&dtrace_lock);
15969 
15970 		return (rval);
15971 	}
15972 
15973 	default:
15974 		break;
15975 	}
15976 
15977 	return (ENOTTY);
15978 }
15979 
15980 /*ARGSUSED*/
15981 static int
15982 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15983 {
15984 	minor_t minor = getminor(dev);
15985 	dtrace_state_t *state;
15986 	int rval;
15987 
15988 	if (minor == DTRACEMNRN_HELPER)
15989 		return (dtrace_ioctl_helper(cmd, arg, rv));
15990 
15991 	state = ddi_get_soft_state(dtrace_softstate, minor);
15992 
15993 	if (state->dts_anon) {
15994 		ASSERT(dtrace_anon.dta_state == NULL);
15995 		state = state->dts_anon;
15996 	}
15997 
15998 	switch (cmd) {
15999 	case DTRACEIOC_PROVIDER: {
16000 		dtrace_providerdesc_t pvd;
16001 		dtrace_provider_t *pvp;
16002 
16003 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16004 			return (EFAULT);
16005 
16006 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16007 		mutex_enter(&dtrace_provider_lock);
16008 
16009 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16010 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16011 				break;
16012 		}
16013 
16014 		mutex_exit(&dtrace_provider_lock);
16015 
16016 		if (pvp == NULL)
16017 			return (ESRCH);
16018 
16019 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16020 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16021 
16022 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16023 			return (EFAULT);
16024 
16025 		return (0);
16026 	}
16027 
16028 	case DTRACEIOC_EPROBE: {
16029 		dtrace_eprobedesc_t epdesc;
16030 		dtrace_ecb_t *ecb;
16031 		dtrace_action_t *act;
16032 		void *buf;
16033 		size_t size;
16034 		uintptr_t dest;
16035 		int nrecs;
16036 
16037 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16038 			return (EFAULT);
16039 
16040 		mutex_enter(&dtrace_lock);
16041 
16042 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16043 			mutex_exit(&dtrace_lock);
16044 			return (EINVAL);
16045 		}
16046 
16047 		if (ecb->dte_probe == NULL) {
16048 			mutex_exit(&dtrace_lock);
16049 			return (EINVAL);
16050 		}
16051 
16052 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16053 		epdesc.dtepd_uarg = ecb->dte_uarg;
16054 		epdesc.dtepd_size = ecb->dte_size;
16055 
16056 		nrecs = epdesc.dtepd_nrecs;
16057 		epdesc.dtepd_nrecs = 0;
16058 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16059 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16060 				continue;
16061 
16062 			epdesc.dtepd_nrecs++;
16063 		}
16064 
16065 		/*
16066 		 * Now that we have the size, we need to allocate a temporary
16067 		 * buffer in which to store the complete description.  We need
16068 		 * the temporary buffer to be able to drop dtrace_lock()
16069 		 * across the copyout(), below.
16070 		 */
16071 		size = sizeof (dtrace_eprobedesc_t) +
16072 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16073 
16074 		buf = kmem_alloc(size, KM_SLEEP);
16075 		dest = (uintptr_t)buf;
16076 
16077 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16078 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16079 
16080 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16081 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16082 				continue;
16083 
16084 			if (nrecs-- == 0)
16085 				break;
16086 
16087 			bcopy(&act->dta_rec, (void *)dest,
16088 			    sizeof (dtrace_recdesc_t));
16089 			dest += sizeof (dtrace_recdesc_t);
16090 		}
16091 
16092 		mutex_exit(&dtrace_lock);
16093 
16094 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16095 			kmem_free(buf, size);
16096 			return (EFAULT);
16097 		}
16098 
16099 		kmem_free(buf, size);
16100 		return (0);
16101 	}
16102 
16103 	case DTRACEIOC_AGGDESC: {
16104 		dtrace_aggdesc_t aggdesc;
16105 		dtrace_action_t *act;
16106 		dtrace_aggregation_t *agg;
16107 		int nrecs;
16108 		uint32_t offs;
16109 		dtrace_recdesc_t *lrec;
16110 		void *buf;
16111 		size_t size;
16112 		uintptr_t dest;
16113 
16114 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16115 			return (EFAULT);
16116 
16117 		mutex_enter(&dtrace_lock);
16118 
16119 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16120 			mutex_exit(&dtrace_lock);
16121 			return (EINVAL);
16122 		}
16123 
16124 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16125 
16126 		nrecs = aggdesc.dtagd_nrecs;
16127 		aggdesc.dtagd_nrecs = 0;
16128 
16129 		offs = agg->dtag_base;
16130 		lrec = &agg->dtag_action.dta_rec;
16131 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16132 
16133 		for (act = agg->dtag_first; ; act = act->dta_next) {
16134 			ASSERT(act->dta_intuple ||
16135 			    DTRACEACT_ISAGG(act->dta_kind));
16136 
16137 			/*
16138 			 * If this action has a record size of zero, it
16139 			 * denotes an argument to the aggregating action.
16140 			 * Because the presence of this record doesn't (or
16141 			 * shouldn't) affect the way the data is interpreted,
16142 			 * we don't copy it out to save user-level the
16143 			 * confusion of dealing with a zero-length record.
16144 			 */
16145 			if (act->dta_rec.dtrd_size == 0) {
16146 				ASSERT(agg->dtag_hasarg);
16147 				continue;
16148 			}
16149 
16150 			aggdesc.dtagd_nrecs++;
16151 
16152 			if (act == &agg->dtag_action)
16153 				break;
16154 		}
16155 
16156 		/*
16157 		 * Now that we have the size, we need to allocate a temporary
16158 		 * buffer in which to store the complete description.  We need
16159 		 * the temporary buffer to be able to drop dtrace_lock()
16160 		 * across the copyout(), below.
16161 		 */
16162 		size = sizeof (dtrace_aggdesc_t) +
16163 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16164 
16165 		buf = kmem_alloc(size, KM_SLEEP);
16166 		dest = (uintptr_t)buf;
16167 
16168 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16169 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16170 
16171 		for (act = agg->dtag_first; ; act = act->dta_next) {
16172 			dtrace_recdesc_t rec = act->dta_rec;
16173 
16174 			/*
16175 			 * See the comment in the above loop for why we pass
16176 			 * over zero-length records.
16177 			 */
16178 			if (rec.dtrd_size == 0) {
16179 				ASSERT(agg->dtag_hasarg);
16180 				continue;
16181 			}
16182 
16183 			if (nrecs-- == 0)
16184 				break;
16185 
16186 			rec.dtrd_offset -= offs;
16187 			bcopy(&rec, (void *)dest, sizeof (rec));
16188 			dest += sizeof (dtrace_recdesc_t);
16189 
16190 			if (act == &agg->dtag_action)
16191 				break;
16192 		}
16193 
16194 		mutex_exit(&dtrace_lock);
16195 
16196 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16197 			kmem_free(buf, size);
16198 			return (EFAULT);
16199 		}
16200 
16201 		kmem_free(buf, size);
16202 		return (0);
16203 	}
16204 
16205 	case DTRACEIOC_ENABLE: {
16206 		dof_hdr_t *dof;
16207 		dtrace_enabling_t *enab = NULL;
16208 		dtrace_vstate_t *vstate;
16209 		int err = 0;
16210 
16211 		*rv = 0;
16212 
16213 		/*
16214 		 * If a NULL argument has been passed, we take this as our
16215 		 * cue to reevaluate our enablings.
16216 		 */
16217 		if (arg == NULL) {
16218 			dtrace_enabling_matchall();
16219 
16220 			return (0);
16221 		}
16222 
16223 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16224 			return (rval);
16225 
16226 		mutex_enter(&cpu_lock);
16227 		mutex_enter(&dtrace_lock);
16228 		vstate = &state->dts_vstate;
16229 
16230 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16231 			mutex_exit(&dtrace_lock);
16232 			mutex_exit(&cpu_lock);
16233 			dtrace_dof_destroy(dof);
16234 			return (EBUSY);
16235 		}
16236 
16237 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16238 			mutex_exit(&dtrace_lock);
16239 			mutex_exit(&cpu_lock);
16240 			dtrace_dof_destroy(dof);
16241 			return (EINVAL);
16242 		}
16243 
16244 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16245 			dtrace_enabling_destroy(enab);
16246 			mutex_exit(&dtrace_lock);
16247 			mutex_exit(&cpu_lock);
16248 			dtrace_dof_destroy(dof);
16249 			return (rval);
16250 		}
16251 
16252 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16253 			err = dtrace_enabling_retain(enab);
16254 		} else {
16255 			dtrace_enabling_destroy(enab);
16256 		}
16257 
16258 		mutex_exit(&cpu_lock);
16259 		mutex_exit(&dtrace_lock);
16260 		dtrace_dof_destroy(dof);
16261 
16262 		return (err);
16263 	}
16264 
16265 	case DTRACEIOC_REPLICATE: {
16266 		dtrace_repldesc_t desc;
16267 		dtrace_probedesc_t *match = &desc.dtrpd_match;
16268 		dtrace_probedesc_t *create = &desc.dtrpd_create;
16269 		int err;
16270 
16271 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16272 			return (EFAULT);
16273 
16274 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16275 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16276 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16277 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16278 
16279 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16280 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16281 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16282 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16283 
16284 		mutex_enter(&dtrace_lock);
16285 		err = dtrace_enabling_replicate(state, match, create);
16286 		mutex_exit(&dtrace_lock);
16287 
16288 		return (err);
16289 	}
16290 
16291 	case DTRACEIOC_PROBEMATCH:
16292 	case DTRACEIOC_PROBES: {
16293 		dtrace_probe_t *probe = NULL;
16294 		dtrace_probedesc_t desc;
16295 		dtrace_probekey_t pkey;
16296 		dtrace_id_t i;
16297 		int m = 0;
16298 		uint32_t priv;
16299 		uid_t uid;
16300 		zoneid_t zoneid;
16301 
16302 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16303 			return (EFAULT);
16304 
16305 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16306 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16307 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16308 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16309 
16310 		/*
16311 		 * Before we attempt to match this probe, we want to give
16312 		 * all providers the opportunity to provide it.
16313 		 */
16314 		if (desc.dtpd_id == DTRACE_IDNONE) {
16315 			mutex_enter(&dtrace_provider_lock);
16316 			dtrace_probe_provide(&desc, NULL);
16317 			mutex_exit(&dtrace_provider_lock);
16318 			desc.dtpd_id++;
16319 		}
16320 
16321 		if (cmd == DTRACEIOC_PROBEMATCH)  {
16322 			dtrace_probekey(&desc, &pkey);
16323 			pkey.dtpk_id = DTRACE_IDNONE;
16324 		}
16325 
16326 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16327 
16328 		mutex_enter(&dtrace_lock);
16329 
16330 		if (cmd == DTRACEIOC_PROBEMATCH) {
16331 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16332 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16333 				    (m = dtrace_match_probe(probe, &pkey,
16334 				    priv, uid, zoneid)) != 0)
16335 					break;
16336 			}
16337 
16338 			if (m < 0) {
16339 				mutex_exit(&dtrace_lock);
16340 				return (EINVAL);
16341 			}
16342 
16343 		} else {
16344 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16345 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16346 				    dtrace_match_priv(probe, priv, uid, zoneid))
16347 					break;
16348 			}
16349 		}
16350 
16351 		if (probe == NULL) {
16352 			mutex_exit(&dtrace_lock);
16353 			return (ESRCH);
16354 		}
16355 
16356 		dtrace_probe_description(probe, &desc);
16357 		mutex_exit(&dtrace_lock);
16358 
16359 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16360 			return (EFAULT);
16361 
16362 		return (0);
16363 	}
16364 
16365 	case DTRACEIOC_PROBEARG: {
16366 		dtrace_argdesc_t desc;
16367 		dtrace_probe_t *probe;
16368 		dtrace_provider_t *prov;
16369 
16370 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16371 			return (EFAULT);
16372 
16373 		if (desc.dtargd_id == DTRACE_IDNONE)
16374 			return (EINVAL);
16375 
16376 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16377 			return (EINVAL);
16378 
16379 		mutex_enter(&dtrace_provider_lock);
16380 		mutex_enter(&mod_lock);
16381 		mutex_enter(&dtrace_lock);
16382 
16383 		if (desc.dtargd_id > dtrace_nprobes) {
16384 			mutex_exit(&dtrace_lock);
16385 			mutex_exit(&mod_lock);
16386 			mutex_exit(&dtrace_provider_lock);
16387 			return (EINVAL);
16388 		}
16389 
16390 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16391 			mutex_exit(&dtrace_lock);
16392 			mutex_exit(&mod_lock);
16393 			mutex_exit(&dtrace_provider_lock);
16394 			return (EINVAL);
16395 		}
16396 
16397 		mutex_exit(&dtrace_lock);
16398 
16399 		prov = probe->dtpr_provider;
16400 
16401 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16402 			/*
16403 			 * There isn't any typed information for this probe.
16404 			 * Set the argument number to DTRACE_ARGNONE.
16405 			 */
16406 			desc.dtargd_ndx = DTRACE_ARGNONE;
16407 		} else {
16408 			desc.dtargd_native[0] = '\0';
16409 			desc.dtargd_xlate[0] = '\0';
16410 			desc.dtargd_mapping = desc.dtargd_ndx;
16411 
16412 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16413 			    probe->dtpr_id, probe->dtpr_arg, &desc);
16414 		}
16415 
16416 		mutex_exit(&mod_lock);
16417 		mutex_exit(&dtrace_provider_lock);
16418 
16419 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16420 			return (EFAULT);
16421 
16422 		return (0);
16423 	}
16424 
16425 	case DTRACEIOC_GO: {
16426 		processorid_t cpuid;
16427 		rval = dtrace_state_go(state, &cpuid);
16428 
16429 		if (rval != 0)
16430 			return (rval);
16431 
16432 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16433 			return (EFAULT);
16434 
16435 		return (0);
16436 	}
16437 
16438 	case DTRACEIOC_STOP: {
16439 		processorid_t cpuid;
16440 
16441 		mutex_enter(&dtrace_lock);
16442 		rval = dtrace_state_stop(state, &cpuid);
16443 		mutex_exit(&dtrace_lock);
16444 
16445 		if (rval != 0)
16446 			return (rval);
16447 
16448 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16449 			return (EFAULT);
16450 
16451 		return (0);
16452 	}
16453 
16454 	case DTRACEIOC_DOFGET: {
16455 		dof_hdr_t hdr, *dof;
16456 		uint64_t len;
16457 
16458 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16459 			return (EFAULT);
16460 
16461 		mutex_enter(&dtrace_lock);
16462 		dof = dtrace_dof_create(state);
16463 		mutex_exit(&dtrace_lock);
16464 
16465 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16466 		rval = copyout(dof, (void *)arg, len);
16467 		dtrace_dof_destroy(dof);
16468 
16469 		return (rval == 0 ? 0 : EFAULT);
16470 	}
16471 
16472 	case DTRACEIOC_AGGSNAP:
16473 	case DTRACEIOC_BUFSNAP: {
16474 		dtrace_bufdesc_t desc;
16475 		caddr_t cached;
16476 		dtrace_buffer_t *buf;
16477 
16478 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16479 			return (EFAULT);
16480 
16481 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16482 			return (EINVAL);
16483 
16484 		mutex_enter(&dtrace_lock);
16485 
16486 		if (cmd == DTRACEIOC_BUFSNAP) {
16487 			buf = &state->dts_buffer[desc.dtbd_cpu];
16488 		} else {
16489 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16490 		}
16491 
16492 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16493 			size_t sz = buf->dtb_offset;
16494 
16495 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16496 				mutex_exit(&dtrace_lock);
16497 				return (EBUSY);
16498 			}
16499 
16500 			/*
16501 			 * If this buffer has already been consumed, we're
16502 			 * going to indicate that there's nothing left here
16503 			 * to consume.
16504 			 */
16505 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16506 				mutex_exit(&dtrace_lock);
16507 
16508 				desc.dtbd_size = 0;
16509 				desc.dtbd_drops = 0;
16510 				desc.dtbd_errors = 0;
16511 				desc.dtbd_oldest = 0;
16512 				sz = sizeof (desc);
16513 
16514 				if (copyout(&desc, (void *)arg, sz) != 0)
16515 					return (EFAULT);
16516 
16517 				return (0);
16518 			}
16519 
16520 			/*
16521 			 * If this is a ring buffer that has wrapped, we want
16522 			 * to copy the whole thing out.
16523 			 */
16524 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16525 				dtrace_buffer_polish(buf);
16526 				sz = buf->dtb_size;
16527 			}
16528 
16529 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16530 				mutex_exit(&dtrace_lock);
16531 				return (EFAULT);
16532 			}
16533 
16534 			desc.dtbd_size = sz;
16535 			desc.dtbd_drops = buf->dtb_drops;
16536 			desc.dtbd_errors = buf->dtb_errors;
16537 			desc.dtbd_oldest = buf->dtb_xamot_offset;
16538 			desc.dtbd_timestamp = dtrace_gethrtime();
16539 
16540 			mutex_exit(&dtrace_lock);
16541 
16542 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16543 				return (EFAULT);
16544 
16545 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
16546 
16547 			return (0);
16548 		}
16549 
16550 		if (buf->dtb_tomax == NULL) {
16551 			ASSERT(buf->dtb_xamot == NULL);
16552 			mutex_exit(&dtrace_lock);
16553 			return (ENOENT);
16554 		}
16555 
16556 		cached = buf->dtb_tomax;
16557 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16558 
16559 		dtrace_xcall(desc.dtbd_cpu,
16560 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
16561 
16562 		state->dts_errors += buf->dtb_xamot_errors;
16563 
16564 		/*
16565 		 * If the buffers did not actually switch, then the cross call
16566 		 * did not take place -- presumably because the given CPU is
16567 		 * not in the ready set.  If this is the case, we'll return
16568 		 * ENOENT.
16569 		 */
16570 		if (buf->dtb_tomax == cached) {
16571 			ASSERT(buf->dtb_xamot != cached);
16572 			mutex_exit(&dtrace_lock);
16573 			return (ENOENT);
16574 		}
16575 
16576 		ASSERT(cached == buf->dtb_xamot);
16577 
16578 		/*
16579 		 * We have our snapshot; now copy it out.
16580 		 */
16581 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
16582 		    buf->dtb_xamot_offset) != 0) {
16583 			mutex_exit(&dtrace_lock);
16584 			return (EFAULT);
16585 		}
16586 
16587 		desc.dtbd_size = buf->dtb_xamot_offset;
16588 		desc.dtbd_drops = buf->dtb_xamot_drops;
16589 		desc.dtbd_errors = buf->dtb_xamot_errors;
16590 		desc.dtbd_oldest = 0;
16591 		desc.dtbd_timestamp = buf->dtb_switched;
16592 
16593 		mutex_exit(&dtrace_lock);
16594 
16595 		/*
16596 		 * Finally, copy out the buffer description.
16597 		 */
16598 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16599 			return (EFAULT);
16600 
16601 		return (0);
16602 	}
16603 
16604 	case DTRACEIOC_CONF: {
16605 		dtrace_conf_t conf;
16606 
16607 		bzero(&conf, sizeof (conf));
16608 		conf.dtc_difversion = DIF_VERSION;
16609 		conf.dtc_difintregs = DIF_DIR_NREGS;
16610 		conf.dtc_diftupregs = DIF_DTR_NREGS;
16611 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16612 
16613 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16614 			return (EFAULT);
16615 
16616 		return (0);
16617 	}
16618 
16619 	case DTRACEIOC_STATUS: {
16620 		dtrace_status_t stat;
16621 		dtrace_dstate_t *dstate;
16622 		int i, j;
16623 		uint64_t nerrs;
16624 
16625 		/*
16626 		 * See the comment in dtrace_state_deadman() for the reason
16627 		 * for setting dts_laststatus to INT64_MAX before setting
16628 		 * it to the correct value.
16629 		 */
16630 		state->dts_laststatus = INT64_MAX;
16631 		dtrace_membar_producer();
16632 		state->dts_laststatus = dtrace_gethrtime();
16633 
16634 		bzero(&stat, sizeof (stat));
16635 
16636 		mutex_enter(&dtrace_lock);
16637 
16638 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16639 			mutex_exit(&dtrace_lock);
16640 			return (ENOENT);
16641 		}
16642 
16643 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16644 			stat.dtst_exiting = 1;
16645 
16646 		nerrs = state->dts_errors;
16647 		dstate = &state->dts_vstate.dtvs_dynvars;
16648 
16649 		for (i = 0; i < NCPU; i++) {
16650 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16651 
16652 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
16653 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16654 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16655 
16656 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16657 				stat.dtst_filled++;
16658 
16659 			nerrs += state->dts_buffer[i].dtb_errors;
16660 
16661 			for (j = 0; j < state->dts_nspeculations; j++) {
16662 				dtrace_speculation_t *spec;
16663 				dtrace_buffer_t *buf;
16664 
16665 				spec = &state->dts_speculations[j];
16666 				buf = &spec->dtsp_buffer[i];
16667 				stat.dtst_specdrops += buf->dtb_xamot_drops;
16668 			}
16669 		}
16670 
16671 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
16672 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16673 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16674 		stat.dtst_dblerrors = state->dts_dblerrors;
16675 		stat.dtst_killed =
16676 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16677 		stat.dtst_errors = nerrs;
16678 
16679 		mutex_exit(&dtrace_lock);
16680 
16681 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16682 			return (EFAULT);
16683 
16684 		return (0);
16685 	}
16686 
16687 	case DTRACEIOC_FORMAT: {
16688 		dtrace_fmtdesc_t fmt;
16689 		char *str;
16690 		int len;
16691 
16692 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16693 			return (EFAULT);
16694 
16695 		mutex_enter(&dtrace_lock);
16696 
16697 		if (fmt.dtfd_format == 0 ||
16698 		    fmt.dtfd_format > state->dts_nformats) {
16699 			mutex_exit(&dtrace_lock);
16700 			return (EINVAL);
16701 		}
16702 
16703 		/*
16704 		 * Format strings are allocated contiguously and they are
16705 		 * never freed; if a format index is less than the number
16706 		 * of formats, we can assert that the format map is non-NULL
16707 		 * and that the format for the specified index is non-NULL.
16708 		 */
16709 		ASSERT(state->dts_formats != NULL);
16710 		str = state->dts_formats[fmt.dtfd_format - 1];
16711 		ASSERT(str != NULL);
16712 
16713 		len = strlen(str) + 1;
16714 
16715 		if (len > fmt.dtfd_length) {
16716 			fmt.dtfd_length = len;
16717 
16718 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16719 				mutex_exit(&dtrace_lock);
16720 				return (EINVAL);
16721 			}
16722 		} else {
16723 			if (copyout(str, fmt.dtfd_string, len) != 0) {
16724 				mutex_exit(&dtrace_lock);
16725 				return (EINVAL);
16726 			}
16727 		}
16728 
16729 		mutex_exit(&dtrace_lock);
16730 		return (0);
16731 	}
16732 
16733 	default:
16734 		break;
16735 	}
16736 
16737 	return (ENOTTY);
16738 }
16739 
16740 /*ARGSUSED*/
16741 static int
16742 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16743 {
16744 	dtrace_state_t *state;
16745 
16746 	switch (cmd) {
16747 	case DDI_DETACH:
16748 		break;
16749 
16750 	case DDI_SUSPEND:
16751 		return (DDI_SUCCESS);
16752 
16753 	default:
16754 		return (DDI_FAILURE);
16755 	}
16756 
16757 	mutex_enter(&cpu_lock);
16758 	mutex_enter(&dtrace_provider_lock);
16759 	mutex_enter(&dtrace_lock);
16760 
16761 	ASSERT(dtrace_opens == 0);
16762 
16763 	if (dtrace_helpers > 0) {
16764 		mutex_exit(&dtrace_provider_lock);
16765 		mutex_exit(&dtrace_lock);
16766 		mutex_exit(&cpu_lock);
16767 		return (DDI_FAILURE);
16768 	}
16769 
16770 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16771 		mutex_exit(&dtrace_provider_lock);
16772 		mutex_exit(&dtrace_lock);
16773 		mutex_exit(&cpu_lock);
16774 		return (DDI_FAILURE);
16775 	}
16776 
16777 	dtrace_provider = NULL;
16778 
16779 	if ((state = dtrace_anon_grab()) != NULL) {
16780 		/*
16781 		 * If there were ECBs on this state, the provider should
16782 		 * have not been allowed to detach; assert that there is
16783 		 * none.
16784 		 */
16785 		ASSERT(state->dts_necbs == 0);
16786 		dtrace_state_destroy(state);
16787 
16788 		/*
16789 		 * If we're being detached with anonymous state, we need to
16790 		 * indicate to the kernel debugger that DTrace is now inactive.
16791 		 */
16792 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16793 	}
16794 
16795 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16796 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16797 	dtrace_cpu_init = NULL;
16798 	dtrace_helpers_cleanup = NULL;
16799 	dtrace_helpers_fork = NULL;
16800 	dtrace_cpustart_init = NULL;
16801 	dtrace_cpustart_fini = NULL;
16802 	dtrace_debugger_init = NULL;
16803 	dtrace_debugger_fini = NULL;
16804 	dtrace_modload = NULL;
16805 	dtrace_modunload = NULL;
16806 
16807 	mutex_exit(&cpu_lock);
16808 
16809 	if (dtrace_helptrace_enabled) {
16810 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16811 		dtrace_helptrace_buffer = NULL;
16812 	}
16813 
16814 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16815 	dtrace_probes = NULL;
16816 	dtrace_nprobes = 0;
16817 
16818 	dtrace_hash_destroy(dtrace_bymod);
16819 	dtrace_hash_destroy(dtrace_byfunc);
16820 	dtrace_hash_destroy(dtrace_byname);
16821 	dtrace_bymod = NULL;
16822 	dtrace_byfunc = NULL;
16823 	dtrace_byname = NULL;
16824 
16825 	kmem_cache_destroy(dtrace_state_cache);
16826 	vmem_destroy(dtrace_minor);
16827 	vmem_destroy(dtrace_arena);
16828 
16829 	if (dtrace_toxrange != NULL) {
16830 		kmem_free(dtrace_toxrange,
16831 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16832 		dtrace_toxrange = NULL;
16833 		dtrace_toxranges = 0;
16834 		dtrace_toxranges_max = 0;
16835 	}
16836 
16837 	ddi_remove_minor_node(dtrace_devi, NULL);
16838 	dtrace_devi = NULL;
16839 
16840 	ddi_soft_state_fini(&dtrace_softstate);
16841 
16842 	ASSERT(dtrace_vtime_references == 0);
16843 	ASSERT(dtrace_opens == 0);
16844 	ASSERT(dtrace_retained == NULL);
16845 
16846 	mutex_exit(&dtrace_lock);
16847 	mutex_exit(&dtrace_provider_lock);
16848 
16849 	/*
16850 	 * We don't destroy the task queue until after we have dropped our
16851 	 * locks (taskq_destroy() may block on running tasks).  To prevent
16852 	 * attempting to do work after we have effectively detached but before
16853 	 * the task queue has been destroyed, all tasks dispatched via the
16854 	 * task queue must check that DTrace is still attached before
16855 	 * performing any operation.
16856 	 */
16857 	taskq_destroy(dtrace_taskq);
16858 	dtrace_taskq = NULL;
16859 
16860 	return (DDI_SUCCESS);
16861 }
16862 #endif
16863 
16864 #if defined(sun)
16865 /*ARGSUSED*/
16866 static int
16867 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16868 {
16869 	int error;
16870 
16871 	switch (infocmd) {
16872 	case DDI_INFO_DEVT2DEVINFO:
16873 		*result = (void *)dtrace_devi;
16874 		error = DDI_SUCCESS;
16875 		break;
16876 	case DDI_INFO_DEVT2INSTANCE:
16877 		*result = (void *)0;
16878 		error = DDI_SUCCESS;
16879 		break;
16880 	default:
16881 		error = DDI_FAILURE;
16882 	}
16883 	return (error);
16884 }
16885 #endif
16886 
16887 #if defined(sun)
16888 static struct cb_ops dtrace_cb_ops = {
16889 	dtrace_open,		/* open */
16890 	dtrace_close,		/* close */
16891 	nulldev,		/* strategy */
16892 	nulldev,		/* print */
16893 	nodev,			/* dump */
16894 	nodev,			/* read */
16895 	nodev,			/* write */
16896 	dtrace_ioctl,		/* ioctl */
16897 	nodev,			/* devmap */
16898 	nodev,			/* mmap */
16899 	nodev,			/* segmap */
16900 	nochpoll,		/* poll */
16901 	ddi_prop_op,		/* cb_prop_op */
16902 	0,			/* streamtab  */
16903 	D_NEW | D_MP		/* Driver compatibility flag */
16904 };
16905 
16906 static struct dev_ops dtrace_ops = {
16907 	DEVO_REV,		/* devo_rev */
16908 	0,			/* refcnt */
16909 	dtrace_info,		/* get_dev_info */
16910 	nulldev,		/* identify */
16911 	nulldev,		/* probe */
16912 	dtrace_attach,		/* attach */
16913 	dtrace_detach,		/* detach */
16914 	nodev,			/* reset */
16915 	&dtrace_cb_ops,		/* driver operations */
16916 	NULL,			/* bus operations */
16917 	nodev			/* dev power */
16918 };
16919 
16920 static struct modldrv modldrv = {
16921 	&mod_driverops,		/* module type (this is a pseudo driver) */
16922 	"Dynamic Tracing",	/* name of module */
16923 	&dtrace_ops,		/* driver ops */
16924 };
16925 
16926 static struct modlinkage modlinkage = {
16927 	MODREV_1,
16928 	(void *)&modldrv,
16929 	NULL
16930 };
16931 
16932 int
16933 _init(void)
16934 {
16935 	return (mod_install(&modlinkage));
16936 }
16937 
16938 int
16939 _info(struct modinfo *modinfop)
16940 {
16941 	return (mod_info(&modlinkage, modinfop));
16942 }
16943 
16944 int
16945 _fini(void)
16946 {
16947 	return (mod_remove(&modlinkage));
16948 }
16949 #else
16950 
16951 static d_ioctl_t	dtrace_ioctl;
16952 static d_ioctl_t	dtrace_ioctl_helper;
16953 static void		dtrace_load(void *);
16954 static int		dtrace_unload(void);
16955 #if __FreeBSD_version < 800039
16956 static void		dtrace_clone(void *, struct ucred *, char *, int , struct cdev **);
16957 static struct clonedevs	*dtrace_clones;		/* Ptr to the array of cloned devices. */
16958 static eventhandler_tag	eh_tag;			/* Event handler tag. */
16959 #else
16960 static struct cdev	*dtrace_dev;
16961 static struct cdev	*helper_dev;
16962 #endif
16963 
16964 void dtrace_invop_init(void);
16965 void dtrace_invop_uninit(void);
16966 
16967 static struct cdevsw dtrace_cdevsw = {
16968 	.d_version	= D_VERSION,
16969 	.d_flags	= D_TRACKCLOSE | D_NEEDMINOR,
16970 	.d_close	= dtrace_close,
16971 	.d_ioctl	= dtrace_ioctl,
16972 	.d_open		= dtrace_open,
16973 	.d_name		= "dtrace",
16974 };
16975 
16976 static struct cdevsw helper_cdevsw = {
16977 	.d_version	= D_VERSION,
16978 	.d_flags	= D_TRACKCLOSE | D_NEEDMINOR,
16979 	.d_ioctl	= dtrace_ioctl_helper,
16980 	.d_name		= "helper",
16981 };
16982 
16983 #include <dtrace_anon.c>
16984 #if __FreeBSD_version < 800039
16985 #include <dtrace_clone.c>
16986 #endif
16987 #include <dtrace_ioctl.c>
16988 #include <dtrace_load.c>
16989 #include <dtrace_modevent.c>
16990 #include <dtrace_sysctl.c>
16991 #include <dtrace_unload.c>
16992 #include <dtrace_vtime.c>
16993 #include <dtrace_hacks.c>
16994 #include <dtrace_isa.c>
16995 
16996 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
16997 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
16998 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
16999 
17000 DEV_MODULE(dtrace, dtrace_modevent, NULL);
17001 MODULE_VERSION(dtrace, 1);
17002 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
17003 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
17004 #endif
17005