xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision fe73c3d8)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2019 Joyent, Inc.
25  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
26  * Copyright 2023 Oxide Computer Company
27  */
28 
29 /*
30  * DTrace - Dynamic Tracing for Solaris
31  *
32  * This is the implementation of the Solaris Dynamic Tracing framework
33  * (DTrace).  The user-visible interface to DTrace is described at length in
34  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
35  * library, the in-kernel DTrace framework, and the DTrace providers are
36  * described in the block comments in the <sys/dtrace.h> header file.  The
37  * internal architecture of DTrace is described in the block comments in the
38  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
39  * implementation very much assume mastery of all of these sources; if one has
40  * an unanswered question about the implementation, one should consult them
41  * first.
42  *
43  * The functions here are ordered roughly as follows:
44  *
45  *   - Probe context functions
46  *   - Probe hashing functions
47  *   - Non-probe context utility functions
48  *   - Matching functions
49  *   - Provider-to-Framework API functions
50  *   - Probe management functions
51  *   - DIF object functions
52  *   - Format functions
53  *   - Predicate functions
54  *   - ECB functions
55  *   - Buffer functions
56  *   - Enabling functions
57  *   - DOF functions
58  *   - Anonymous enabling functions
59  *   - Consumer state functions
60  *   - Helper functions
61  *   - Hook functions
62  *   - Driver cookbook functions
63  *
64  * Each group of functions begins with a block comment labelled the "DTrace
65  * [Group] Functions", allowing one to find each block by searching forward
66  * on capital-f functions.
67  */
68 #include <sys/errno.h>
69 #include <sys/stat.h>
70 #include <sys/modctl.h>
71 #include <sys/conf.h>
72 #include <sys/systm.h>
73 #include <sys/ddi.h>
74 #include <sys/sunddi.h>
75 #include <sys/cpuvar.h>
76 #include <sys/kmem.h>
77 #include <sys/strsubr.h>
78 #include <sys/sysmacros.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/atomic.h>
81 #include <sys/cmn_err.h>
82 #include <sys/mutex_impl.h>
83 #include <sys/rwlock_impl.h>
84 #include <sys/ctf_api.h>
85 #include <sys/panic.h>
86 #include <sys/priv_impl.h>
87 #include <sys/policy.h>
88 #include <sys/cred_impl.h>
89 #include <sys/procfs_isa.h>
90 #include <sys/taskq.h>
91 #include <sys/mkdev.h>
92 #include <sys/kdi.h>
93 #include <sys/zone.h>
94 #include <sys/socket.h>
95 #include <netinet/in.h>
96 #include "strtolctype.h"
97 
98 /*
99  * DTrace Tunable Variables
100  *
101  * The following variables may be tuned by adding a line to /etc/system that
102  * includes both the name of the DTrace module ("dtrace") and the name of the
103  * variable.  For example:
104  *
105  *   set dtrace:dtrace_destructive_disallow = 1
106  *
107  * In general, the only variables that one should be tuning this way are those
108  * that affect system-wide DTrace behavior, and for which the default behavior
109  * is undesirable.  Most of these variables are tunable on a per-consumer
110  * basis using DTrace options, and need not be tuned on a system-wide basis.
111  * When tuning these variables, avoid pathological values; while some attempt
112  * is made to verify the integrity of these variables, they are not considered
113  * part of the supported interface to DTrace, and they are therefore not
114  * checked comprehensively.  Further, these variables should not be tuned
115  * dynamically via "mdb -kw" or other means; they should only be tuned via
116  * /etc/system.
117  */
118 int		dtrace_destructive_disallow = 0;
119 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
120 size_t		dtrace_difo_maxsize = (256 * 1024);
121 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
122 size_t		dtrace_statvar_maxsize = (16 * 1024);
123 size_t		dtrace_actions_max = (16 * 1024);
124 size_t		dtrace_retain_max = 1024;
125 dtrace_optval_t	dtrace_helper_actions_max = 1024;
126 dtrace_optval_t	dtrace_helper_providers_max = 32;
127 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
128 size_t		dtrace_strsize_default = 256;
129 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
130 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
131 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
132 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
134 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
135 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
136 dtrace_optval_t	dtrace_nspec_default = 1;
137 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
138 dtrace_optval_t dtrace_stackframes_default = 20;
139 dtrace_optval_t dtrace_ustackframes_default = 20;
140 dtrace_optval_t dtrace_jstackframes_default = 50;
141 dtrace_optval_t dtrace_jstackstrsize_default = 512;
142 int		dtrace_msgdsize_max = 128;
143 hrtime_t	dtrace_chill_max = MSEC2NSEC(500);		/* 500 ms */
144 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
145 int		dtrace_devdepth_max = 32;
146 int		dtrace_err_verbose;
147 hrtime_t	dtrace_deadman_interval = NANOSEC;
148 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
149 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
150 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
151 
152 /*
153  * DTrace External Variables
154  *
155  * As dtrace(4D) is a kernel module, any DTrace variables are obviously
156  * available to DTrace consumers via the backtick (`) syntax.  One of these,
157  * dtrace_zero, is made deliberately so:  it is provided as a source of
158  * well-known, zero-filled memory.  While this variable is not documented,
159  * it is used by some translators as an implementation detail.
160  */
161 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
162 
163 /*
164  * DTrace Internal Variables
165  */
166 static dev_info_t	*dtrace_devi;		/* device info */
167 static vmem_t		*dtrace_arena;		/* probe ID arena */
168 static vmem_t		*dtrace_minor;		/* minor number arena */
169 static taskq_t		*dtrace_taskq;		/* task queue */
170 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
171 static int		dtrace_nprobes;		/* number of probes */
172 static dtrace_provider_t *dtrace_provider;	/* provider list */
173 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
174 static int		dtrace_opens;		/* number of opens */
175 static int		dtrace_helpers;		/* number of helpers */
176 static int		dtrace_getf;		/* number of unpriv getf()s */
177 static void		*dtrace_softstate;	/* softstate pointer */
178 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
179 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
180 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
181 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
182 static int		dtrace_toxranges;	/* number of toxic ranges */
183 static int		dtrace_toxranges_max;	/* size of toxic range array */
184 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
185 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
186 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
187 static kthread_t	*dtrace_panicked;	/* panicking thread */
188 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
189 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
190 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
191 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
192 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
193 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
194 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
195 
196 /*
197  * DTrace Locking
198  * DTrace is protected by three (relatively coarse-grained) locks:
199  *
200  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
201  *     including enabling state, probes, ECBs, consumer state, helper state,
202  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
203  *     probe context is lock-free -- synchronization is handled via the
204  *     dtrace_sync() cross call mechanism.
205  *
206  * (2) dtrace_provider_lock is required when manipulating provider state, or
207  *     when provider state must be held constant.
208  *
209  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
210  *     when meta provider state must be held constant.
211  *
212  * The lock ordering between these three locks is dtrace_meta_lock before
213  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
214  * several places where dtrace_provider_lock is held by the framework as it
215  * calls into the providers -- which then call back into the framework,
216  * grabbing dtrace_lock.)
217  *
218  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
219  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
220  * role as a coarse-grained lock; it is acquired before both of these locks.
221  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
222  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
223  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
224  * acquired _between_ dtrace_provider_lock and dtrace_lock.
225  */
226 static kmutex_t		dtrace_lock;		/* probe state lock */
227 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
228 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
229 
230 /*
231  * DTrace Provider Variables
232  *
233  * These are the variables relating to DTrace as a provider (that is, the
234  * provider of the BEGIN, END, and ERROR probes).
235  */
236 static dtrace_pattr_t	dtrace_provider_attr = {
237 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
238 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
239 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
240 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
241 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
242 };
243 
244 static void
dtrace_nullop_provide(void * arg __unused,const dtrace_probedesc_t * spec __unused)245 dtrace_nullop_provide(void *arg __unused,
246     const dtrace_probedesc_t *spec __unused)
247 {
248 }
249 
250 static void
dtrace_nullop_module(void * arg __unused,struct modctl * mp __unused)251 dtrace_nullop_module(void *arg __unused, struct modctl *mp __unused)
252 {
253 }
254 
255 static void
dtrace_nullop(void * arg __unused,dtrace_id_t id __unused,void * parg __unused)256 dtrace_nullop(void *arg __unused, dtrace_id_t id __unused, void *parg __unused)
257 {
258 }
259 
260 static int
dtrace_enable_nullop(void * arg __unused,dtrace_id_t id __unused,void * parg __unused)261 dtrace_enable_nullop(void *arg __unused, dtrace_id_t id __unused,
262     void *parg __unused)
263 {
264 	return (0);
265 }
266 
267 static dtrace_pops_t	dtrace_provider_ops = {
268 	.dtps_provide = dtrace_nullop_provide,
269 	.dtps_provide_module = dtrace_nullop_module,
270 	.dtps_enable = dtrace_enable_nullop,
271 	.dtps_disable = dtrace_nullop,
272 	.dtps_suspend = dtrace_nullop,
273 	.dtps_resume = dtrace_nullop,
274 	.dtps_getargdesc = NULL,
275 	.dtps_getargval = NULL,
276 	.dtps_mode = NULL,
277 	.dtps_destroy = dtrace_nullop
278 };
279 
280 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
281 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
282 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
283 
284 /*
285  * DTrace Helper Tracing Variables
286  *
287  * These variables should be set dynamically to enable helper tracing.  The
288  * only variables that should be set are dtrace_helptrace_enable (which should
289  * be set to a non-zero value to allocate helper tracing buffers on the next
290  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
291  * non-zero value to deallocate helper tracing buffers on the next close of
292  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
293  * buffer size may also be set via dtrace_helptrace_bufsize.
294  */
295 int			dtrace_helptrace_enable = 0;
296 int			dtrace_helptrace_disable = 0;
297 int			dtrace_helptrace_bufsize = 16 * 1024 * 1024;
298 uint32_t		dtrace_helptrace_nlocals;
299 static dtrace_helptrace_t *dtrace_helptrace_buffer;
300 static uint32_t		dtrace_helptrace_next = 0;
301 static int		dtrace_helptrace_wrapped = 0;
302 
303 /*
304  * DTrace Error Hashing
305  *
306  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
307  * table.  This is very useful for checking coverage of tests that are
308  * expected to induce DIF or DOF processing errors, and may be useful for
309  * debugging problems in the DIF code generator or in DOF generation .  The
310  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
311  */
312 #ifdef DEBUG
313 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
314 static const char *dtrace_errlast;
315 static kthread_t *dtrace_errthread;
316 static kmutex_t dtrace_errlock;
317 #endif
318 
319 /*
320  * DTrace Macros and Constants
321  *
322  * These are various macros that are useful in various spots in the
323  * implementation, along with a few random constants that have no meaning
324  * outside of the implementation.  There is no real structure to this cpp
325  * mishmash -- but is there ever?
326  */
327 #define	DTRACE_HASHSTR(hash, probe)	\
328 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
329 
330 #define	DTRACE_HASHNEXT(hash, probe)	\
331 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
332 
333 #define	DTRACE_HASHPREV(hash, probe)	\
334 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
335 
336 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
337 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
338 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
339 
340 #define	DTRACE_AGGHASHSIZE_SLEW		17
341 
342 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
343 
344 /*
345  * The key for a thread-local variable consists of the lower 61 bits of the
346  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
347  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
348  * equal to a variable identifier.  This is necessary (but not sufficient) to
349  * assure that global associative arrays never collide with thread-local
350  * variables.  To guarantee that they cannot collide, we must also define the
351  * order for keying dynamic variables.  That order is:
352  *
353  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
354  *
355  * Because the variable-key and the tls-key are in orthogonal spaces, there is
356  * no way for a global variable key signature to match a thread-local key
357  * signature.
358  */
359 #define	DTRACE_TLS_THRKEY(where) { \
360 	uint_t intr = 0; \
361 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
362 	for (; actv; actv >>= 1) \
363 		intr++; \
364 	ASSERT(intr < (1 << 3)); \
365 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
366 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
367 }
368 
369 #define	DT_BSWAP_8(x)	((x) & 0xff)
370 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
371 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
372 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
373 
374 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
375 
376 #define	DTRACE_STORE(type, tomax, offset, what) \
377 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
378 
379 #ifndef __x86
380 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
381 	if (addr & (size - 1)) {					\
382 		*flags |= CPU_DTRACE_BADALIGN;				\
383 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
384 		return (0);						\
385 	}
386 #else
387 #define	DTRACE_ALIGNCHECK(addr, size, flags)
388 #endif
389 
390 /*
391  * Test whether a range of memory starting at testaddr of size testsz falls
392  * within the range of memory described by addr, sz.  We take care to avoid
393  * problems with overflow and underflow of the unsigned quantities, and
394  * disallow all negative sizes.  Ranges of size 0 are allowed.
395  */
396 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
397 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
398 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
399 	(testaddr) + (testsz) >= (testaddr))
400 
401 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
402 do {									\
403 	if ((remp) != NULL) {						\
404 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
405 	}								\
406 _NOTE(CONSTCOND) } while (0)
407 
408 
409 /*
410  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
411  * alloc_sz on the righthand side of the comparison in order to avoid overflow
412  * or underflow in the comparison with it.  This is simpler than the INRANGE
413  * check above, because we know that the dtms_scratch_ptr is valid in the
414  * range.  Allocations of size zero are allowed.
415  */
416 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
417 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
418 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
419 
420 #define	DTRACE_LOADFUNC(bits)						\
421 /*CSTYLED*/								\
422 uint##bits##_t								\
423 dtrace_load##bits(uintptr_t addr)					\
424 {									\
425 	size_t size = bits / NBBY;					\
426 	/*CSTYLED*/							\
427 	uint##bits##_t rval;						\
428 	int i;								\
429 	volatile uint16_t *flags = (volatile uint16_t *)		\
430 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
431 									\
432 	DTRACE_ALIGNCHECK(addr, size, flags);				\
433 									\
434 	for (i = 0; i < dtrace_toxranges; i++) {			\
435 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
436 			continue;					\
437 									\
438 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
439 			continue;					\
440 									\
441 		/*							\
442 		 * This address falls within a toxic region; return 0.	\
443 		 */							\
444 		*flags |= CPU_DTRACE_BADADDR;				\
445 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
446 		return (0);						\
447 	}								\
448 									\
449 	*flags |= CPU_DTRACE_NOFAULT;					\
450 	/*CSTYLED*/							\
451 	rval = *((volatile uint##bits##_t *)addr);			\
452 	*flags &= ~CPU_DTRACE_NOFAULT;					\
453 									\
454 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
455 }
456 
457 #ifdef _LP64
458 #define	dtrace_loadptr	dtrace_load64
459 #else
460 #define	dtrace_loadptr	dtrace_load32
461 #endif
462 
463 #define	DTRACE_DYNHASH_FREE	0
464 #define	DTRACE_DYNHASH_SINK	1
465 #define	DTRACE_DYNHASH_VALID	2
466 
467 #define	DTRACE_MATCH_FAIL	-1
468 #define	DTRACE_MATCH_NEXT	0
469 #define	DTRACE_MATCH_DONE	1
470 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
471 #define	DTRACE_STATE_ALIGN	64
472 
473 #define	DTRACE_FLAGS2FLT(flags)						\
474 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
475 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
476 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
477 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
478 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
479 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
480 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
481 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
482 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
483 	DTRACEFLT_UNKNOWN)
484 
485 #define	DTRACEACT_ISSTRING(act)						\
486 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
487 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
488 
489 static size_t dtrace_strlen(const char *, size_t);
490 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
491 static void dtrace_enabling_provide(dtrace_provider_t *);
492 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
493 static void dtrace_enabling_matchall(void);
494 static void dtrace_enabling_reap(void);
495 static dtrace_state_t *dtrace_anon_grab(void);
496 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
497     dtrace_state_t *, uint64_t, uint64_t);
498 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
499 static void dtrace_buffer_drop(dtrace_buffer_t *);
500 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
501 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
502     dtrace_state_t *, dtrace_mstate_t *);
503 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
504     dtrace_optval_t);
505 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
506 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
507 static int dtrace_priv_proc(dtrace_state_t *, dtrace_mstate_t *);
508 static void dtrace_getf_barrier(void);
509 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
510     dtrace_mstate_t *, dtrace_vstate_t *);
511 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
512     dtrace_mstate_t *, dtrace_vstate_t *);
513 
514 /*
515  * DTrace Probe Context Functions
516  *
517  * These functions are called from probe context.  Because probe context is
518  * any context in which C may be called, arbitrarily locks may be held,
519  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
520  * As a result, functions called from probe context may only call other DTrace
521  * support functions -- they may not interact at all with the system at large.
522  * (Note that the ASSERT macro is made probe-context safe by redefining it in
523  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
524  * loads are to be performed from probe context, they _must_ be in terms of
525  * the safe dtrace_load*() variants.
526  *
527  * Some functions in this block are not actually called from probe context;
528  * for these functions, there will be a comment above the function reading
529  * "Note:  not called from probe context."
530  */
531 void
dtrace_panic(const char * format,...)532 dtrace_panic(const char *format, ...)
533 {
534 	va_list alist;
535 
536 	va_start(alist, format);
537 	dtrace_vpanic(format, alist);
538 	va_end(alist);
539 }
540 
541 int
dtrace_assfail(const char * a,const char * f,int l)542 dtrace_assfail(const char *a, const char *f, int l)
543 {
544 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
545 
546 	/*
547 	 * We just need something here that even the most clever compiler
548 	 * cannot optimize away.
549 	 */
550 	return (a[(uintptr_t)f]);
551 }
552 
553 /*
554  * Atomically increment a specified error counter from probe context.
555  */
556 static void
dtrace_error(uint32_t * counter)557 dtrace_error(uint32_t *counter)
558 {
559 	/*
560 	 * Most counters stored to in probe context are per-CPU counters.
561 	 * However, there are some error conditions that are sufficiently
562 	 * arcane that they don't merit per-CPU storage.  If these counters
563 	 * are incremented concurrently on different CPUs, scalability will be
564 	 * adversely affected -- but we don't expect them to be white-hot in a
565 	 * correctly constructed enabling...
566 	 */
567 	uint32_t oval, nval;
568 
569 	do {
570 		oval = *counter;
571 
572 		if ((nval = oval + 1) == 0) {
573 			/*
574 			 * If the counter would wrap, set it to 1 -- assuring
575 			 * that the counter is never zero when we have seen
576 			 * errors.  (The counter must be 32-bits because we
577 			 * aren't guaranteed a 64-bit compare&swap operation.)
578 			 * To save this code both the infamy of being fingered
579 			 * by a priggish news story and the indignity of being
580 			 * the target of a neo-puritan witch trial, we're
581 			 * carefully avoiding any colorful description of the
582 			 * likelihood of this condition -- but suffice it to
583 			 * say that it is only slightly more likely than the
584 			 * overflow of predicate cache IDs, as discussed in
585 			 * dtrace_predicate_create().
586 			 */
587 			nval = 1;
588 		}
589 	} while (dtrace_cas32(counter, oval, nval) != oval);
590 }
591 
592 /*
593  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
594  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
595  */
596 /* BEGIN CSTYLED */
597 DTRACE_LOADFUNC(8)
598 DTRACE_LOADFUNC(16)
599 DTRACE_LOADFUNC(32)
600 DTRACE_LOADFUNC(64)
601 /* END CSTYLED */
602 
603 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)604 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
605 {
606 	if (dest < mstate->dtms_scratch_base)
607 		return (0);
608 
609 	if (dest + size < dest)
610 		return (0);
611 
612 	if (dest + size > mstate->dtms_scratch_ptr)
613 		return (0);
614 
615 	return (1);
616 }
617 
618 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)619 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
620     dtrace_statvar_t **svars, int nsvars)
621 {
622 	int i;
623 	size_t maxglobalsize, maxlocalsize;
624 
625 	if (nsvars == 0)
626 		return (0);
627 
628 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
629 	maxlocalsize = maxglobalsize * NCPU;
630 
631 	for (i = 0; i < nsvars; i++) {
632 		dtrace_statvar_t *svar = svars[i];
633 		uint8_t scope;
634 		size_t size;
635 
636 		if (svar == NULL || (size = svar->dtsv_size) == 0)
637 			continue;
638 
639 		scope = svar->dtsv_var.dtdv_scope;
640 
641 		/*
642 		 * We verify that our size is valid in the spirit of providing
643 		 * defense in depth:  we want to prevent attackers from using
644 		 * DTrace to escalate an orthogonal kernel heap corruption bug
645 		 * into the ability to store to arbitrary locations in memory.
646 		 */
647 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
648 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
649 
650 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
651 		    svar->dtsv_size)) {
652 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
653 			    svar->dtsv_size);
654 			return (1);
655 		}
656 	}
657 
658 	return (0);
659 }
660 
661 /*
662  * Check to see if the address is within a memory region to which a store may
663  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
664  * region.  The caller of dtrace_canstore() is responsible for performing any
665  * alignment checks that are needed before stores are actually executed.
666  */
667 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)668 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
669     dtrace_vstate_t *vstate)
670 {
671 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
672 }
673 
674 /*
675  * Implementation of dtrace_canstore which communicates the upper bound of the
676  * allowed memory region.
677  */
678 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)679 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
680     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
681 {
682 	/*
683 	 * First, check to see if the address is in scratch space...
684 	 */
685 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
686 	    mstate->dtms_scratch_size)) {
687 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
688 		    mstate->dtms_scratch_size);
689 		return (1);
690 	}
691 
692 	/*
693 	 * Now check to see if it's a dynamic variable.  This check will pick
694 	 * up both thread-local variables and any global dynamically-allocated
695 	 * variables.
696 	 */
697 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
698 	    vstate->dtvs_dynvars.dtds_size)) {
699 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
700 		uintptr_t base = (uintptr_t)dstate->dtds_base +
701 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
702 		uintptr_t chunkoffs;
703 		dtrace_dynvar_t *dvar;
704 
705 		/*
706 		 * Before we assume that we can store here, we need to make
707 		 * sure that it isn't in our metadata -- storing to our
708 		 * dynamic variable metadata would corrupt our state.  For
709 		 * the range to not include any dynamic variable metadata,
710 		 * it must:
711 		 *
712 		 *	(1) Start above the hash table that is at the base of
713 		 *	the dynamic variable space
714 		 *
715 		 *	(2) Have a starting chunk offset that is beyond the
716 		 *	dtrace_dynvar_t that is at the base of every chunk
717 		 *
718 		 *	(3) Not span a chunk boundary
719 		 *
720 		 *	(4) Not be in the tuple space of a dynamic variable
721 		 *
722 		 */
723 		if (addr < base)
724 			return (0);
725 
726 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
727 
728 		if (chunkoffs < sizeof (dtrace_dynvar_t))
729 			return (0);
730 
731 		if (chunkoffs + sz > dstate->dtds_chunksize)
732 			return (0);
733 
734 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
735 
736 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
737 			return (0);
738 
739 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
740 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
741 			return (0);
742 
743 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
744 		return (1);
745 	}
746 
747 	/*
748 	 * Finally, check the static local and global variables.  These checks
749 	 * take the longest, so we perform them last.
750 	 */
751 	if (dtrace_canstore_statvar(addr, sz, remain,
752 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
753 		return (1);
754 
755 	if (dtrace_canstore_statvar(addr, sz, remain,
756 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
757 		return (1);
758 
759 	return (0);
760 }
761 
762 
763 /*
764  * Convenience routine to check to see if the address is within a memory
765  * region in which a load may be issued given the user's privilege level;
766  * if not, it sets the appropriate error flags and loads 'addr' into the
767  * illegal value slot.
768  *
769  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
770  * appropriate memory access protection.
771  */
772 static int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)773 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
774     dtrace_vstate_t *vstate)
775 {
776 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
777 }
778 
779 /*
780  * Implementation of dtrace_canload which communicates the upper bound of the
781  * allowed memory region.
782  */
783 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)784 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
785     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
786 {
787 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
788 	file_t *fp;
789 
790 	/*
791 	 * If we hold the privilege to read from kernel memory, then
792 	 * everything is readable.
793 	 */
794 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
795 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
796 		return (1);
797 	}
798 
799 	/*
800 	 * You can obviously read that which you can store.
801 	 */
802 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
803 		return (1);
804 
805 	/*
806 	 * We're allowed to read from our own string table.
807 	 */
808 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
809 	    mstate->dtms_difo->dtdo_strlen)) {
810 		DTRACE_RANGE_REMAIN(remain, addr,
811 		    mstate->dtms_difo->dtdo_strtab,
812 		    mstate->dtms_difo->dtdo_strlen);
813 		return (1);
814 	}
815 
816 	if (vstate->dtvs_state != NULL &&
817 	    dtrace_priv_proc(vstate->dtvs_state, mstate)) {
818 		proc_t *p;
819 
820 		/*
821 		 * When we have privileges to the current process, there are
822 		 * several context-related kernel structures that are safe to
823 		 * read, even absent the privilege to read from kernel memory.
824 		 * These reads are safe because these structures contain only
825 		 * state that (1) we're permitted to read, (2) is harmless or
826 		 * (3) contains pointers to additional kernel state that we're
827 		 * not permitted to read (and as such, do not present an
828 		 * opportunity for privilege escalation).  Finally (and
829 		 * critically), because of the nature of their relation with
830 		 * the current thread context, the memory associated with these
831 		 * structures cannot change over the duration of probe context,
832 		 * and it is therefore impossible for this memory to be
833 		 * deallocated and reallocated as something else while it's
834 		 * being operated upon.
835 		 */
836 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
837 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
838 			    sizeof (kthread_t));
839 			return (1);
840 		}
841 
842 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
843 		    sz, curthread->t_procp, sizeof (proc_t))) {
844 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
845 			    sizeof (proc_t));
846 			return (1);
847 		}
848 
849 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
850 		    curthread->t_cred, sizeof (cred_t))) {
851 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
852 			    sizeof (cred_t));
853 			return (1);
854 		}
855 
856 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
857 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
858 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
859 			    sizeof (pid_t));
860 			return (1);
861 		}
862 
863 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
864 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
865 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
866 			    offsetof(cpu_t, cpu_pause_thread));
867 			return (1);
868 		}
869 	}
870 
871 	if ((fp = mstate->dtms_getf) != NULL) {
872 		uintptr_t psz = sizeof (void *);
873 		vnode_t *vp;
874 		vnodeops_t *op;
875 
876 		/*
877 		 * When getf() returns a file_t, the enabling is implicitly
878 		 * granted the (transient) right to read the returned file_t
879 		 * as well as the v_path and v_op->vnop_name of the underlying
880 		 * vnode.  These accesses are allowed after a successful
881 		 * getf() because the members that they refer to cannot change
882 		 * once set -- and the barrier logic in the kernel's closef()
883 		 * path assures that the file_t and its referenced vode_t
884 		 * cannot themselves be stale (that is, it impossible for
885 		 * either dtms_getf itself or its f_vnode member to reference
886 		 * freed memory).
887 		 */
888 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
889 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
890 			return (1);
891 		}
892 
893 		if ((vp = fp->f_vnode) != NULL) {
894 			size_t slen;
895 
896 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
897 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
898 				    psz);
899 				return (1);
900 			}
901 
902 			slen = strlen(vp->v_path) + 1;
903 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
904 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
905 				    slen);
906 				return (1);
907 			}
908 
909 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
910 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
911 				    psz);
912 				return (1);
913 			}
914 
915 			if ((op = vp->v_op) != NULL &&
916 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
917 				DTRACE_RANGE_REMAIN(remain, addr,
918 				    &op->vnop_name, psz);
919 				return (1);
920 			}
921 
922 			if (op != NULL && op->vnop_name != NULL &&
923 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
924 			    (slen = strlen(op->vnop_name) + 1))) {
925 				DTRACE_RANGE_REMAIN(remain, addr,
926 				    op->vnop_name, slen);
927 				return (1);
928 			}
929 		}
930 	}
931 
932 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
933 	*illval = addr;
934 	return (0);
935 }
936 
937 /*
938  * Convenience routine to check to see if a given string is within a memory
939  * region in which a load may be issued given the user's privilege level;
940  * this exists so that we don't need to issue unnecessary dtrace_strlen()
941  * calls in the event that the user has all privileges.
942  */
943 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)944 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
945     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
946 {
947 	size_t rsize;
948 
949 	/*
950 	 * If we hold the privilege to read from kernel memory, then
951 	 * everything is readable.
952 	 */
953 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
954 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
955 		return (1);
956 	}
957 
958 	/*
959 	 * Even if the caller is uninterested in querying the remaining valid
960 	 * range, it is required to ensure that the access is allowed.
961 	 */
962 	if (remain == NULL) {
963 		remain = &rsize;
964 	}
965 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
966 		size_t strsz;
967 		/*
968 		 * Perform the strlen after determining the length of the
969 		 * memory region which is accessible.  This prevents timing
970 		 * information from being used to find NULs in memory which is
971 		 * not accessible to the caller.
972 		 */
973 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
974 		    MIN(sz, *remain));
975 		if (strsz <= *remain) {
976 			return (1);
977 		}
978 	}
979 
980 	return (0);
981 }
982 
983 /*
984  * Convenience routine to check to see if a given variable is within a memory
985  * region in which a load may be issued given the user's privilege level.
986  */
987 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)988 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
989     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
990 {
991 	size_t sz;
992 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
993 
994 	/*
995 	 * Calculate the max size before performing any checks since even
996 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
997 	 * return the max length via 'remain'.
998 	 */
999 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1000 		dtrace_state_t *state = vstate->dtvs_state;
1001 
1002 		if (state != NULL) {
1003 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1004 		} else {
1005 			/*
1006 			 * In helper context, we have a NULL state; fall back
1007 			 * to using the system-wide default for the string size
1008 			 * in this case.
1009 			 */
1010 			sz = dtrace_strsize_default;
1011 		}
1012 	} else {
1013 		sz = type->dtdt_size;
1014 	}
1015 
1016 	/*
1017 	 * If we hold the privilege to read from kernel memory, then
1018 	 * everything is readable.
1019 	 */
1020 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1021 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1022 		return (1);
1023 	}
1024 
1025 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1026 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1027 		    vstate));
1028 	}
1029 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1030 	    vstate));
1031 }
1032 
1033 /*
1034  * Convert a string to a signed integer using safe loads.
1035  *
1036  * NOTE: This function uses various macros from strtolctype.h to manipulate
1037  * digit values, etc -- these have all been checked to ensure they make
1038  * no additional function calls.
1039  */
1040 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1041 dtrace_strtoll(char *input, int base, size_t limit)
1042 {
1043 	uintptr_t pos = (uintptr_t)input;
1044 	int64_t val = 0;
1045 	int x;
1046 	boolean_t neg = B_FALSE;
1047 	char c, cc, ccc;
1048 	uintptr_t end = pos + limit;
1049 
1050 	/*
1051 	 * Consume any whitespace preceding digits.
1052 	 */
1053 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1054 		pos++;
1055 
1056 	/*
1057 	 * Handle an explicit sign if one is present.
1058 	 */
1059 	if (c == '-' || c == '+') {
1060 		if (c == '-')
1061 			neg = B_TRUE;
1062 		c = dtrace_load8(++pos);
1063 	}
1064 
1065 	/*
1066 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1067 	 * if present.
1068 	 */
1069 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1070 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1071 		pos += 2;
1072 		c = ccc;
1073 	}
1074 
1075 	/*
1076 	 * Read in contiguous digits until the first non-digit character.
1077 	 */
1078 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1079 	    c = dtrace_load8(++pos))
1080 		val = val * base + x;
1081 
1082 	return (neg ? -val : val);
1083 }
1084 
1085 /*
1086  * Compare two strings using safe loads.
1087  */
1088 static int
dtrace_strncmp(char * s1,char * s2,size_t limit)1089 dtrace_strncmp(char *s1, char *s2, size_t limit)
1090 {
1091 	uint8_t c1, c2;
1092 	volatile uint16_t *flags;
1093 
1094 	if (s1 == s2 || limit == 0)
1095 		return (0);
1096 
1097 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1098 
1099 	do {
1100 		if (s1 == NULL) {
1101 			c1 = '\0';
1102 		} else {
1103 			c1 = dtrace_load8((uintptr_t)s1++);
1104 		}
1105 
1106 		if (s2 == NULL) {
1107 			c2 = '\0';
1108 		} else {
1109 			c2 = dtrace_load8((uintptr_t)s2++);
1110 		}
1111 
1112 		if (c1 != c2)
1113 			return (c1 - c2);
1114 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1115 
1116 	return (0);
1117 }
1118 
1119 /*
1120  * Compute strlen(s) for a string using safe memory accesses.  The additional
1121  * len parameter is used to specify a maximum length to ensure completion.
1122  */
1123 static size_t
dtrace_strlen(const char * s,size_t lim)1124 dtrace_strlen(const char *s, size_t lim)
1125 {
1126 	uint_t len;
1127 
1128 	for (len = 0; len != lim; len++) {
1129 		if (dtrace_load8((uintptr_t)s++) == '\0')
1130 			break;
1131 	}
1132 
1133 	return (len);
1134 }
1135 
1136 /*
1137  * Check if an address falls within a toxic region.
1138  */
1139 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1140 dtrace_istoxic(uintptr_t kaddr, size_t size)
1141 {
1142 	uintptr_t taddr, tsize;
1143 	int i;
1144 
1145 	for (i = 0; i < dtrace_toxranges; i++) {
1146 		taddr = dtrace_toxrange[i].dtt_base;
1147 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1148 
1149 		if (kaddr - taddr < tsize) {
1150 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1151 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1152 			return (1);
1153 		}
1154 
1155 		if (taddr - kaddr < size) {
1156 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1157 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1158 			return (1);
1159 		}
1160 	}
1161 
1162 	return (0);
1163 }
1164 
1165 /*
1166  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1167  * memory specified by the DIF program.  The dst is assumed to be safe memory
1168  * that we can store to directly because it is managed by DTrace.  As with
1169  * standard bcopy, overlapping copies are handled properly.
1170  */
1171 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1172 dtrace_bcopy(const void *src, void *dst, size_t len)
1173 {
1174 	if (len != 0) {
1175 		uint8_t *s1 = dst;
1176 		const uint8_t *s2 = src;
1177 
1178 		if (s1 <= s2) {
1179 			do {
1180 				*s1++ = dtrace_load8((uintptr_t)s2++);
1181 			} while (--len != 0);
1182 		} else {
1183 			s2 += len;
1184 			s1 += len;
1185 
1186 			do {
1187 				*--s1 = dtrace_load8((uintptr_t)--s2);
1188 			} while (--len != 0);
1189 		}
1190 	}
1191 }
1192 
1193 /*
1194  * Copy src to dst using safe memory accesses, up to either the specified
1195  * length, or the point that a nul byte is encountered.  The src is assumed to
1196  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1197  * safe memory that we can store to directly because it is managed by DTrace.
1198  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1199  */
1200 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1201 dtrace_strcpy(const void *src, void *dst, size_t len)
1202 {
1203 	if (len != 0) {
1204 		uint8_t *s1 = dst, c;
1205 		const uint8_t *s2 = src;
1206 
1207 		do {
1208 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1209 		} while (--len != 0 && c != '\0');
1210 	}
1211 }
1212 
1213 /*
1214  * Copy src to dst, deriving the size and type from the specified (BYREF)
1215  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1216  * program.  The dst is assumed to be DTrace variable memory that is of the
1217  * specified type; we assume that we can store to directly.
1218  */
1219 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1220 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1221 {
1222 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1223 
1224 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1225 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1226 	} else {
1227 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1228 	}
1229 }
1230 
1231 /*
1232  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1233  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1234  * safe memory that we can access directly because it is managed by DTrace.
1235  */
1236 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1237 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1238 {
1239 	volatile uint16_t *flags;
1240 
1241 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1242 
1243 	if (s1 == s2)
1244 		return (0);
1245 
1246 	if (s1 == NULL || s2 == NULL)
1247 		return (1);
1248 
1249 	if (s1 != s2 && len != 0) {
1250 		const uint8_t *ps1 = s1;
1251 		const uint8_t *ps2 = s2;
1252 
1253 		do {
1254 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1255 				return (1);
1256 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1257 	}
1258 	return (0);
1259 }
1260 
1261 /*
1262  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1263  * is for safe DTrace-managed memory only.
1264  */
1265 static void
dtrace_bzero(void * dst,size_t len)1266 dtrace_bzero(void *dst, size_t len)
1267 {
1268 	uchar_t *cp;
1269 
1270 	for (cp = dst; len != 0; len--)
1271 		*cp++ = 0;
1272 }
1273 
1274 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1275 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1276 {
1277 	uint64_t result[2];
1278 
1279 	result[0] = addend1[0] + addend2[0];
1280 	result[1] = addend1[1] + addend2[1] +
1281 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1282 
1283 	sum[0] = result[0];
1284 	sum[1] = result[1];
1285 }
1286 
1287 /*
1288  * Shift the 128-bit value in a by b. If b is positive, shift left.
1289  * If b is negative, shift right.
1290  */
1291 static void
dtrace_shift_128(uint64_t * a,int b)1292 dtrace_shift_128(uint64_t *a, int b)
1293 {
1294 	uint64_t mask;
1295 
1296 	if (b == 0)
1297 		return;
1298 
1299 	if (b < 0) {
1300 		b = -b;
1301 		if (b >= 64) {
1302 			a[0] = a[1] >> (b - 64);
1303 			a[1] = 0;
1304 		} else {
1305 			a[0] >>= b;
1306 			mask = 1LL << (64 - b);
1307 			mask -= 1;
1308 			a[0] |= ((a[1] & mask) << (64 - b));
1309 			a[1] >>= b;
1310 		}
1311 	} else {
1312 		if (b >= 64) {
1313 			a[1] = a[0] << (b - 64);
1314 			a[0] = 0;
1315 		} else {
1316 			a[1] <<= b;
1317 			mask = a[0] >> (64 - b);
1318 			a[1] |= mask;
1319 			a[0] <<= b;
1320 		}
1321 	}
1322 }
1323 
1324 /*
1325  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1326  * use native multiplication on those, and then re-combine into the
1327  * resulting 128-bit value.
1328  *
1329  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1330  *     hi1 * hi2 << 64 +
1331  *     hi1 * lo2 << 32 +
1332  *     hi2 * lo1 << 32 +
1333  *     lo1 * lo2
1334  */
1335 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1336 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1337 {
1338 	uint64_t hi1, hi2, lo1, lo2;
1339 	uint64_t tmp[2];
1340 
1341 	hi1 = factor1 >> 32;
1342 	hi2 = factor2 >> 32;
1343 
1344 	lo1 = factor1 & DT_MASK_LO;
1345 	lo2 = factor2 & DT_MASK_LO;
1346 
1347 	product[0] = lo1 * lo2;
1348 	product[1] = hi1 * hi2;
1349 
1350 	tmp[0] = hi1 * lo2;
1351 	tmp[1] = 0;
1352 	dtrace_shift_128(tmp, 32);
1353 	dtrace_add_128(product, tmp, product);
1354 
1355 	tmp[0] = hi2 * lo1;
1356 	tmp[1] = 0;
1357 	dtrace_shift_128(tmp, 32);
1358 	dtrace_add_128(product, tmp, product);
1359 }
1360 
1361 /*
1362  * This privilege check should be used by actions and subroutines to
1363  * verify that the user credentials of the process that enabled the
1364  * invoking ECB match the target credentials
1365  */
1366 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1367 dtrace_priv_proc_common_user(dtrace_state_t *state)
1368 {
1369 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1370 
1371 	/*
1372 	 * We should always have a non-NULL state cred here, since if cred
1373 	 * is null (anonymous tracing), we fast-path bypass this routine.
1374 	 */
1375 	ASSERT(s_cr != NULL);
1376 
1377 	if ((cr = CRED()) != NULL &&
1378 	    s_cr->cr_uid == cr->cr_uid &&
1379 	    s_cr->cr_uid == cr->cr_ruid &&
1380 	    s_cr->cr_uid == cr->cr_suid &&
1381 	    s_cr->cr_gid == cr->cr_gid &&
1382 	    s_cr->cr_gid == cr->cr_rgid &&
1383 	    s_cr->cr_gid == cr->cr_sgid)
1384 		return (1);
1385 
1386 	return (0);
1387 }
1388 
1389 /*
1390  * This privilege check should be used by actions and subroutines to
1391  * verify that the zone of the process that enabled the invoking ECB
1392  * matches the target credentials
1393  */
1394 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1395 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1396 {
1397 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1398 
1399 	/*
1400 	 * We should always have a non-NULL state cred here, since if cred
1401 	 * is null (anonymous tracing), we fast-path bypass this routine.
1402 	 */
1403 	ASSERT(s_cr != NULL);
1404 
1405 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1406 		return (1);
1407 
1408 	return (0);
1409 }
1410 
1411 /*
1412  * This privilege check should be used by actions and subroutines to
1413  * verify that the process has not setuid or changed credentials.
1414  */
1415 static int
dtrace_priv_proc_common_nocd()1416 dtrace_priv_proc_common_nocd()
1417 {
1418 	proc_t *proc;
1419 
1420 	if ((proc = ttoproc(curthread)) != NULL &&
1421 	    !(proc->p_flag & SNOCD))
1422 		return (1);
1423 
1424 	return (0);
1425 }
1426 
1427 static int
dtrace_priv_proc_destructive(dtrace_state_t * state,dtrace_mstate_t * mstate)1428 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1429 {
1430 	int action = state->dts_cred.dcr_action;
1431 
1432 	if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1433 		goto bad;
1434 
1435 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1436 	    dtrace_priv_proc_common_zone(state) == 0)
1437 		goto bad;
1438 
1439 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1440 	    dtrace_priv_proc_common_user(state) == 0)
1441 		goto bad;
1442 
1443 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1444 	    dtrace_priv_proc_common_nocd() == 0)
1445 		goto bad;
1446 
1447 	return (1);
1448 
1449 bad:
1450 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1451 
1452 	return (0);
1453 }
1454 
1455 static int
dtrace_priv_proc_control(dtrace_state_t * state,dtrace_mstate_t * mstate)1456 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1457 {
1458 	if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1459 		if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1460 			return (1);
1461 
1462 		if (dtrace_priv_proc_common_zone(state) &&
1463 		    dtrace_priv_proc_common_user(state) &&
1464 		    dtrace_priv_proc_common_nocd())
1465 			return (1);
1466 	}
1467 
1468 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1469 
1470 	return (0);
1471 }
1472 
1473 static int
dtrace_priv_proc(dtrace_state_t * state,dtrace_mstate_t * mstate)1474 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1475 {
1476 	if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1477 	    (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1478 		return (1);
1479 
1480 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1481 
1482 	return (0);
1483 }
1484 
1485 static int
dtrace_priv_kernel(dtrace_state_t * state)1486 dtrace_priv_kernel(dtrace_state_t *state)
1487 {
1488 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1489 		return (1);
1490 
1491 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1492 
1493 	return (0);
1494 }
1495 
1496 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1497 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1498 {
1499 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1500 		return (1);
1501 
1502 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1503 
1504 	return (0);
1505 }
1506 
1507 /*
1508  * Determine if the dte_cond of the specified ECB allows for processing of
1509  * the current probe to continue.  Note that this routine may allow continued
1510  * processing, but with access(es) stripped from the mstate's dtms_access
1511  * field.
1512  */
1513 static int
dtrace_priv_probe(dtrace_state_t * state,dtrace_mstate_t * mstate,dtrace_ecb_t * ecb)1514 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1515     dtrace_ecb_t *ecb)
1516 {
1517 	dtrace_probe_t *probe = ecb->dte_probe;
1518 	dtrace_provider_t *prov = probe->dtpr_provider;
1519 	dtrace_pops_t *pops = &prov->dtpv_pops;
1520 	int mode = DTRACE_MODE_NOPRIV_DROP;
1521 
1522 	ASSERT(ecb->dte_cond);
1523 
1524 	if (pops->dtps_mode != NULL) {
1525 		mode = pops->dtps_mode(prov->dtpv_arg,
1526 		    probe->dtpr_id, probe->dtpr_arg);
1527 
1528 		ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1529 		ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1530 		    DTRACE_MODE_NOPRIV_DROP));
1531 	}
1532 
1533 	/*
1534 	 * If the dte_cond bits indicate that this consumer is only allowed to
1535 	 * see user-mode firings of this probe, check that the probe was fired
1536 	 * while in a user context.  If that's not the case, use the policy
1537 	 * specified by the provider to determine if we drop the probe or
1538 	 * merely restrict operation.
1539 	 */
1540 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1541 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1542 
1543 		if (!(mode & DTRACE_MODE_USER)) {
1544 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1545 				return (0);
1546 
1547 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1548 		}
1549 	}
1550 
1551 	/*
1552 	 * This is more subtle than it looks. We have to be absolutely certain
1553 	 * that CRED() isn't going to change out from under us so it's only
1554 	 * legit to examine that structure if we're in constrained situations.
1555 	 * Currently, the only times we'll this check is if a non-super-user
1556 	 * has enabled the profile or syscall providers -- providers that
1557 	 * allow visibility of all processes. For the profile case, the check
1558 	 * above will ensure that we're examining a user context.
1559 	 */
1560 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1561 		cred_t *cr;
1562 		cred_t *s_cr = state->dts_cred.dcr_cred;
1563 		proc_t *proc;
1564 
1565 		ASSERT(s_cr != NULL);
1566 
1567 		if ((cr = CRED()) == NULL ||
1568 		    s_cr->cr_uid != cr->cr_uid ||
1569 		    s_cr->cr_uid != cr->cr_ruid ||
1570 		    s_cr->cr_uid != cr->cr_suid ||
1571 		    s_cr->cr_gid != cr->cr_gid ||
1572 		    s_cr->cr_gid != cr->cr_rgid ||
1573 		    s_cr->cr_gid != cr->cr_sgid ||
1574 		    (proc = ttoproc(curthread)) == NULL ||
1575 		    (proc->p_flag & SNOCD)) {
1576 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1577 				return (0);
1578 
1579 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1580 		}
1581 	}
1582 
1583 	/*
1584 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1585 	 * in our zone, check to see if our mode policy is to restrict rather
1586 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1587 	 * and DTRACE_ACCESS_ARGS
1588 	 */
1589 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1590 		cred_t *cr;
1591 		cred_t *s_cr = state->dts_cred.dcr_cred;
1592 
1593 		ASSERT(s_cr != NULL);
1594 
1595 		if ((cr = CRED()) == NULL ||
1596 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1597 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1598 				return (0);
1599 
1600 			mstate->dtms_access &=
1601 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1602 		}
1603 	}
1604 
1605 	/*
1606 	 * By merits of being in this code path at all, we have limited
1607 	 * privileges.  If the provider has indicated that limited privileges
1608 	 * are to denote restricted operation, strip off the ability to access
1609 	 * arguments.
1610 	 */
1611 	if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1612 		mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1613 
1614 	return (1);
1615 }
1616 
1617 /*
1618  * Note:  not called from probe context.  This function is called
1619  * asynchronously (and at a regular interval) from outside of probe context to
1620  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1621  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1622  */
1623 void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1624 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1625 {
1626 	dtrace_dynvar_t *dirty;
1627 	dtrace_dstate_percpu_t *dcpu;
1628 	dtrace_dynvar_t **rinsep;
1629 	int i, j, work = 0;
1630 
1631 	for (i = 0; i < NCPU; i++) {
1632 		dcpu = &dstate->dtds_percpu[i];
1633 		rinsep = &dcpu->dtdsc_rinsing;
1634 
1635 		/*
1636 		 * If the dirty list is NULL, there is no dirty work to do.
1637 		 */
1638 		if (dcpu->dtdsc_dirty == NULL)
1639 			continue;
1640 
1641 		if (dcpu->dtdsc_rinsing != NULL) {
1642 			/*
1643 			 * If the rinsing list is non-NULL, then it is because
1644 			 * this CPU was selected to accept another CPU's
1645 			 * dirty list -- and since that time, dirty buffers
1646 			 * have accumulated.  This is a highly unlikely
1647 			 * condition, but we choose to ignore the dirty
1648 			 * buffers -- they'll be picked up a future cleanse.
1649 			 */
1650 			continue;
1651 		}
1652 
1653 		if (dcpu->dtdsc_clean != NULL) {
1654 			/*
1655 			 * If the clean list is non-NULL, then we're in a
1656 			 * situation where a CPU has done deallocations (we
1657 			 * have a non-NULL dirty list) but no allocations (we
1658 			 * also have a non-NULL clean list).  We can't simply
1659 			 * move the dirty list into the clean list on this
1660 			 * CPU, yet we also don't want to allow this condition
1661 			 * to persist, lest a short clean list prevent a
1662 			 * massive dirty list from being cleaned (which in
1663 			 * turn could lead to otherwise avoidable dynamic
1664 			 * drops).  To deal with this, we look for some CPU
1665 			 * with a NULL clean list, NULL dirty list, and NULL
1666 			 * rinsing list -- and then we borrow this CPU to
1667 			 * rinse our dirty list.
1668 			 */
1669 			for (j = 0; j < NCPU; j++) {
1670 				dtrace_dstate_percpu_t *rinser;
1671 
1672 				rinser = &dstate->dtds_percpu[j];
1673 
1674 				if (rinser->dtdsc_rinsing != NULL)
1675 					continue;
1676 
1677 				if (rinser->dtdsc_dirty != NULL)
1678 					continue;
1679 
1680 				if (rinser->dtdsc_clean != NULL)
1681 					continue;
1682 
1683 				rinsep = &rinser->dtdsc_rinsing;
1684 				break;
1685 			}
1686 
1687 			if (j == NCPU) {
1688 				/*
1689 				 * We were unable to find another CPU that
1690 				 * could accept this dirty list -- we are
1691 				 * therefore unable to clean it now.
1692 				 */
1693 				dtrace_dynvar_failclean++;
1694 				continue;
1695 			}
1696 		}
1697 
1698 		work = 1;
1699 
1700 		/*
1701 		 * Atomically move the dirty list aside.
1702 		 */
1703 		do {
1704 			dirty = dcpu->dtdsc_dirty;
1705 
1706 			/*
1707 			 * Before we zap the dirty list, set the rinsing list.
1708 			 * (This allows for a potential assertion in
1709 			 * dtrace_dynvar():  if a free dynamic variable appears
1710 			 * on a hash chain, either the dirty list or the
1711 			 * rinsing list for some CPU must be non-NULL.)
1712 			 */
1713 			*rinsep = dirty;
1714 			dtrace_membar_producer();
1715 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1716 		    dirty, NULL) != dirty);
1717 	}
1718 
1719 	if (!work) {
1720 		/*
1721 		 * We have no work to do; we can simply return.
1722 		 */
1723 		return;
1724 	}
1725 
1726 	dtrace_sync();
1727 
1728 	for (i = 0; i < NCPU; i++) {
1729 		dcpu = &dstate->dtds_percpu[i];
1730 
1731 		if (dcpu->dtdsc_rinsing == NULL)
1732 			continue;
1733 
1734 		/*
1735 		 * We are now guaranteed that no hash chain contains a pointer
1736 		 * into this dirty list; we can make it clean.
1737 		 */
1738 		ASSERT(dcpu->dtdsc_clean == NULL);
1739 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1740 		dcpu->dtdsc_rinsing = NULL;
1741 	}
1742 
1743 	/*
1744 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1745 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1746 	 * This prevents a race whereby a CPU incorrectly decides that
1747 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1748 	 * after dtrace_dynvar_clean() has completed.
1749 	 */
1750 	dtrace_sync();
1751 
1752 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1753 }
1754 
1755 /*
1756  * Depending on the value of the op parameter, this function looks-up,
1757  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1758  * allocation is requested, this function will return a pointer to a
1759  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1760  * variable can be allocated.  If NULL is returned, the appropriate counter
1761  * will be incremented.
1762  */
1763 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)1764 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1765     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1766     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1767 {
1768 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1769 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1770 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1771 	processorid_t me = CPU->cpu_id, cpu = me;
1772 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1773 	size_t bucket, ksize;
1774 	size_t chunksize = dstate->dtds_chunksize;
1775 	uintptr_t kdata, lock, nstate;
1776 	uint_t i;
1777 
1778 	ASSERT(nkeys != 0);
1779 
1780 	/*
1781 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1782 	 * algorithm.  For the by-value portions, we perform the algorithm in
1783 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1784 	 * bit, and seems to have only a minute effect on distribution.  For
1785 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1786 	 * over each referenced byte.  It's painful to do this, but it's much
1787 	 * better than pathological hash distribution.  The efficacy of the
1788 	 * hashing algorithm (and a comparison with other algorithms) may be
1789 	 * found by running the ::dtrace_dynstat MDB dcmd.
1790 	 */
1791 	for (i = 0; i < nkeys; i++) {
1792 		if (key[i].dttk_size == 0) {
1793 			uint64_t val = key[i].dttk_value;
1794 
1795 			hashval += (val >> 48) & 0xffff;
1796 			hashval += (hashval << 10);
1797 			hashval ^= (hashval >> 6);
1798 
1799 			hashval += (val >> 32) & 0xffff;
1800 			hashval += (hashval << 10);
1801 			hashval ^= (hashval >> 6);
1802 
1803 			hashval += (val >> 16) & 0xffff;
1804 			hashval += (hashval << 10);
1805 			hashval ^= (hashval >> 6);
1806 
1807 			hashval += val & 0xffff;
1808 			hashval += (hashval << 10);
1809 			hashval ^= (hashval >> 6);
1810 		} else {
1811 			/*
1812 			 * This is incredibly painful, but it beats the hell
1813 			 * out of the alternative.
1814 			 */
1815 			uint64_t j, size = key[i].dttk_size;
1816 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1817 
1818 			if (!dtrace_canload(base, size, mstate, vstate))
1819 				break;
1820 
1821 			for (j = 0; j < size; j++) {
1822 				hashval += dtrace_load8(base + j);
1823 				hashval += (hashval << 10);
1824 				hashval ^= (hashval >> 6);
1825 			}
1826 		}
1827 	}
1828 
1829 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1830 		return (NULL);
1831 
1832 	hashval += (hashval << 3);
1833 	hashval ^= (hashval >> 11);
1834 	hashval += (hashval << 15);
1835 
1836 	/*
1837 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1838 	 * comes out to be one of our two sentinel hash values.  If this
1839 	 * actually happens, we set the hashval to be a value known to be a
1840 	 * non-sentinel value.
1841 	 */
1842 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1843 		hashval = DTRACE_DYNHASH_VALID;
1844 
1845 	/*
1846 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1847 	 * important here, tricks can be pulled to reduce it.  (However, it's
1848 	 * critical that hash collisions be kept to an absolute minimum;
1849 	 * they're much more painful than a divide.)  It's better to have a
1850 	 * solution that generates few collisions and still keeps things
1851 	 * relatively simple.
1852 	 */
1853 	bucket = hashval % dstate->dtds_hashsize;
1854 
1855 	if (op == DTRACE_DYNVAR_DEALLOC) {
1856 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1857 
1858 		for (;;) {
1859 			while ((lock = *lockp) & 1)
1860 				continue;
1861 
1862 			if (dtrace_casptr((void *)lockp,
1863 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1864 				break;
1865 		}
1866 
1867 		dtrace_membar_producer();
1868 	}
1869 
1870 top:
1871 	prev = NULL;
1872 	lock = hash[bucket].dtdh_lock;
1873 
1874 	dtrace_membar_consumer();
1875 
1876 	start = hash[bucket].dtdh_chain;
1877 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1878 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1879 	    op != DTRACE_DYNVAR_DEALLOC));
1880 
1881 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1882 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1883 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1884 
1885 		if (dvar->dtdv_hashval != hashval) {
1886 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1887 				/*
1888 				 * We've reached the sink, and therefore the
1889 				 * end of the hash chain; we can kick out of
1890 				 * the loop knowing that we have seen a valid
1891 				 * snapshot of state.
1892 				 */
1893 				ASSERT(dvar->dtdv_next == NULL);
1894 				ASSERT(dvar == &dtrace_dynhash_sink);
1895 				break;
1896 			}
1897 
1898 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1899 				/*
1900 				 * We've gone off the rails:  somewhere along
1901 				 * the line, one of the members of this hash
1902 				 * chain was deleted.  Note that we could also
1903 				 * detect this by simply letting this loop run
1904 				 * to completion, as we would eventually hit
1905 				 * the end of the dirty list.  However, we
1906 				 * want to avoid running the length of the
1907 				 * dirty list unnecessarily (it might be quite
1908 				 * long), so we catch this as early as
1909 				 * possible by detecting the hash marker.  In
1910 				 * this case, we simply set dvar to NULL and
1911 				 * break; the conditional after the loop will
1912 				 * send us back to top.
1913 				 */
1914 				dvar = NULL;
1915 				break;
1916 			}
1917 
1918 			goto next;
1919 		}
1920 
1921 		if (dtuple->dtt_nkeys != nkeys)
1922 			goto next;
1923 
1924 		for (i = 0; i < nkeys; i++, dkey++) {
1925 			if (dkey->dttk_size != key[i].dttk_size)
1926 				goto next; /* size or type mismatch */
1927 
1928 			if (dkey->dttk_size != 0) {
1929 				if (dtrace_bcmp(
1930 				    (void *)(uintptr_t)key[i].dttk_value,
1931 				    (void *)(uintptr_t)dkey->dttk_value,
1932 				    dkey->dttk_size))
1933 					goto next;
1934 			} else {
1935 				if (dkey->dttk_value != key[i].dttk_value)
1936 					goto next;
1937 			}
1938 		}
1939 
1940 		if (op != DTRACE_DYNVAR_DEALLOC)
1941 			return (dvar);
1942 
1943 		ASSERT(dvar->dtdv_next == NULL ||
1944 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1945 
1946 		if (prev != NULL) {
1947 			ASSERT(hash[bucket].dtdh_chain != dvar);
1948 			ASSERT(start != dvar);
1949 			ASSERT(prev->dtdv_next == dvar);
1950 			prev->dtdv_next = dvar->dtdv_next;
1951 		} else {
1952 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1953 			    start, dvar->dtdv_next) != start) {
1954 				/*
1955 				 * We have failed to atomically swing the
1956 				 * hash table head pointer, presumably because
1957 				 * of a conflicting allocation on another CPU.
1958 				 * We need to reread the hash chain and try
1959 				 * again.
1960 				 */
1961 				goto top;
1962 			}
1963 		}
1964 
1965 		dtrace_membar_producer();
1966 
1967 		/*
1968 		 * Now set the hash value to indicate that it's free.
1969 		 */
1970 		ASSERT(hash[bucket].dtdh_chain != dvar);
1971 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1972 
1973 		dtrace_membar_producer();
1974 
1975 		/*
1976 		 * Set the next pointer to point at the dirty list, and
1977 		 * atomically swing the dirty pointer to the newly freed dvar.
1978 		 */
1979 		do {
1980 			next = dcpu->dtdsc_dirty;
1981 			dvar->dtdv_next = next;
1982 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1983 
1984 		/*
1985 		 * Finally, unlock this hash bucket.
1986 		 */
1987 		ASSERT(hash[bucket].dtdh_lock == lock);
1988 		ASSERT(lock & 1);
1989 		hash[bucket].dtdh_lock++;
1990 
1991 		return (NULL);
1992 next:
1993 		prev = dvar;
1994 		continue;
1995 	}
1996 
1997 	if (dvar == NULL) {
1998 		/*
1999 		 * If dvar is NULL, it is because we went off the rails:
2000 		 * one of the elements that we traversed in the hash chain
2001 		 * was deleted while we were traversing it.  In this case,
2002 		 * we assert that we aren't doing a dealloc (deallocs lock
2003 		 * the hash bucket to prevent themselves from racing with
2004 		 * one another), and retry the hash chain traversal.
2005 		 */
2006 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2007 		goto top;
2008 	}
2009 
2010 	if (op != DTRACE_DYNVAR_ALLOC) {
2011 		/*
2012 		 * If we are not to allocate a new variable, we want to
2013 		 * return NULL now.  Before we return, check that the value
2014 		 * of the lock word hasn't changed.  If it has, we may have
2015 		 * seen an inconsistent snapshot.
2016 		 */
2017 		if (op == DTRACE_DYNVAR_NOALLOC) {
2018 			if (hash[bucket].dtdh_lock != lock)
2019 				goto top;
2020 		} else {
2021 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2022 			ASSERT(hash[bucket].dtdh_lock == lock);
2023 			ASSERT(lock & 1);
2024 			hash[bucket].dtdh_lock++;
2025 		}
2026 
2027 		return (NULL);
2028 	}
2029 
2030 	/*
2031 	 * We need to allocate a new dynamic variable.  The size we need is the
2032 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2033 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2034 	 * the size of any referred-to data (dsize).  We then round the final
2035 	 * size up to the chunksize for allocation.
2036 	 */
2037 	for (ksize = 0, i = 0; i < nkeys; i++)
2038 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2039 
2040 	/*
2041 	 * This should be pretty much impossible, but could happen if, say,
2042 	 * strange DIF specified the tuple.  Ideally, this should be an
2043 	 * assertion and not an error condition -- but that requires that the
2044 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2045 	 * bullet-proof.  (That is, it must not be able to be fooled by
2046 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2047 	 * solving this would presumably not amount to solving the Halting
2048 	 * Problem -- but it still seems awfully hard.
2049 	 */
2050 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2051 	    ksize + dsize > chunksize) {
2052 		dcpu->dtdsc_drops++;
2053 		return (NULL);
2054 	}
2055 
2056 	nstate = DTRACE_DSTATE_EMPTY;
2057 
2058 	do {
2059 retry:
2060 		free = dcpu->dtdsc_free;
2061 
2062 		if (free == NULL) {
2063 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2064 			void *rval;
2065 
2066 			if (clean == NULL) {
2067 				/*
2068 				 * We're out of dynamic variable space on
2069 				 * this CPU.  Unless we have tried all CPUs,
2070 				 * we'll try to allocate from a different
2071 				 * CPU.
2072 				 */
2073 				switch (dstate->dtds_state) {
2074 				case DTRACE_DSTATE_CLEAN: {
2075 					void *sp = &dstate->dtds_state;
2076 
2077 					if (++cpu >= NCPU)
2078 						cpu = 0;
2079 
2080 					if (dcpu->dtdsc_dirty != NULL &&
2081 					    nstate == DTRACE_DSTATE_EMPTY)
2082 						nstate = DTRACE_DSTATE_DIRTY;
2083 
2084 					if (dcpu->dtdsc_rinsing != NULL)
2085 						nstate = DTRACE_DSTATE_RINSING;
2086 
2087 					dcpu = &dstate->dtds_percpu[cpu];
2088 
2089 					if (cpu != me)
2090 						goto retry;
2091 
2092 					(void) dtrace_cas32(sp,
2093 					    DTRACE_DSTATE_CLEAN, nstate);
2094 
2095 					/*
2096 					 * To increment the correct bean
2097 					 * counter, take another lap.
2098 					 */
2099 					goto retry;
2100 				}
2101 
2102 				case DTRACE_DSTATE_DIRTY:
2103 					dcpu->dtdsc_dirty_drops++;
2104 					break;
2105 
2106 				case DTRACE_DSTATE_RINSING:
2107 					dcpu->dtdsc_rinsing_drops++;
2108 					break;
2109 
2110 				case DTRACE_DSTATE_EMPTY:
2111 					dcpu->dtdsc_drops++;
2112 					break;
2113 				}
2114 
2115 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2116 				return (NULL);
2117 			}
2118 
2119 			/*
2120 			 * The clean list appears to be non-empty.  We want to
2121 			 * move the clean list to the free list; we start by
2122 			 * moving the clean pointer aside.
2123 			 */
2124 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2125 			    clean, NULL) != clean) {
2126 				/*
2127 				 * We are in one of two situations:
2128 				 *
2129 				 *  (a)	The clean list was switched to the
2130 				 *	free list by another CPU.
2131 				 *
2132 				 *  (b)	The clean list was added to by the
2133 				 *	cleansing cyclic.
2134 				 *
2135 				 * In either of these situations, we can
2136 				 * just reattempt the free list allocation.
2137 				 */
2138 				goto retry;
2139 			}
2140 
2141 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2142 
2143 			/*
2144 			 * Now we'll move the clean list to our free list.
2145 			 * It's impossible for this to fail:  the only way
2146 			 * the free list can be updated is through this
2147 			 * code path, and only one CPU can own the clean list.
2148 			 * Thus, it would only be possible for this to fail if
2149 			 * this code were racing with dtrace_dynvar_clean().
2150 			 * (That is, if dtrace_dynvar_clean() updated the clean
2151 			 * list, and we ended up racing to update the free
2152 			 * list.)  This race is prevented by the dtrace_sync()
2153 			 * in dtrace_dynvar_clean() -- which flushes the
2154 			 * owners of the clean lists out before resetting
2155 			 * the clean lists.
2156 			 */
2157 			dcpu = &dstate->dtds_percpu[me];
2158 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2159 			ASSERT(rval == NULL);
2160 			goto retry;
2161 		}
2162 
2163 		dvar = free;
2164 		new_free = dvar->dtdv_next;
2165 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2166 
2167 	/*
2168 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2169 	 * tuple array and copy any referenced key data into the data space
2170 	 * following the tuple array.  As we do this, we relocate dttk_value
2171 	 * in the final tuple to point to the key data address in the chunk.
2172 	 */
2173 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2174 	dvar->dtdv_data = (void *)(kdata + ksize);
2175 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2176 
2177 	for (i = 0; i < nkeys; i++) {
2178 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2179 		size_t kesize = key[i].dttk_size;
2180 
2181 		if (kesize != 0) {
2182 			dtrace_bcopy(
2183 			    (const void *)(uintptr_t)key[i].dttk_value,
2184 			    (void *)kdata, kesize);
2185 			dkey->dttk_value = kdata;
2186 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2187 		} else {
2188 			dkey->dttk_value = key[i].dttk_value;
2189 		}
2190 
2191 		dkey->dttk_size = kesize;
2192 	}
2193 
2194 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2195 	dvar->dtdv_hashval = hashval;
2196 	dvar->dtdv_next = start;
2197 
2198 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2199 		return (dvar);
2200 
2201 	/*
2202 	 * The cas has failed.  Either another CPU is adding an element to
2203 	 * this hash chain, or another CPU is deleting an element from this
2204 	 * hash chain.  The simplest way to deal with both of these cases
2205 	 * (though not necessarily the most efficient) is to free our
2206 	 * allocated block and re-attempt it all.  Note that the free is
2207 	 * to the dirty list and _not_ to the free list.  This is to prevent
2208 	 * races with allocators, above.
2209 	 */
2210 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2211 
2212 	dtrace_membar_producer();
2213 
2214 	do {
2215 		free = dcpu->dtdsc_dirty;
2216 		dvar->dtdv_next = free;
2217 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2218 
2219 	goto top;
2220 }
2221 
2222 /*ARGSUSED*/
2223 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2224 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2225 {
2226 	if ((int64_t)nval < (int64_t)*oval)
2227 		*oval = nval;
2228 }
2229 
2230 /*ARGSUSED*/
2231 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2232 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2233 {
2234 	if ((int64_t)nval > (int64_t)*oval)
2235 		*oval = nval;
2236 }
2237 
2238 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2239 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2240 {
2241 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2242 	int64_t val = (int64_t)nval;
2243 
2244 	if (val < 0) {
2245 		for (i = 0; i < zero; i++) {
2246 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2247 				quanta[i] += incr;
2248 				return;
2249 			}
2250 		}
2251 	} else {
2252 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2253 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2254 				quanta[i - 1] += incr;
2255 				return;
2256 			}
2257 		}
2258 
2259 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2260 		return;
2261 	}
2262 
2263 	ASSERT(0);
2264 }
2265 
2266 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2267 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2268 {
2269 	uint64_t arg = *lquanta++;
2270 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2271 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2272 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2273 	int32_t val = (int32_t)nval, level;
2274 
2275 	ASSERT(step != 0);
2276 	ASSERT(levels != 0);
2277 
2278 	if (val < base) {
2279 		/*
2280 		 * This is an underflow.
2281 		 */
2282 		lquanta[0] += incr;
2283 		return;
2284 	}
2285 
2286 	level = (val - base) / step;
2287 
2288 	if (level < levels) {
2289 		lquanta[level + 1] += incr;
2290 		return;
2291 	}
2292 
2293 	/*
2294 	 * This is an overflow.
2295 	 */
2296 	lquanta[levels + 1] += incr;
2297 }
2298 
2299 static int
dtrace_aggregate_llquantize_bucket(uint16_t factor,uint16_t low,uint16_t high,uint16_t nsteps,int64_t value)2300 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2301     uint16_t high, uint16_t nsteps, int64_t value)
2302 {
2303 	int64_t this = 1, last, next;
2304 	int base = 1, order;
2305 
2306 	ASSERT(factor <= nsteps);
2307 	ASSERT(nsteps % factor == 0);
2308 
2309 	for (order = 0; order < low; order++)
2310 		this *= factor;
2311 
2312 	/*
2313 	 * If our value is less than our factor taken to the power of the
2314 	 * low order of magnitude, it goes into the zeroth bucket.
2315 	 */
2316 	if (value < (last = this))
2317 		return (0);
2318 
2319 	for (this *= factor; order <= high; order++) {
2320 		int nbuckets = this > nsteps ? nsteps : this;
2321 
2322 		if ((next = this * factor) < this) {
2323 			/*
2324 			 * We should not generally get log/linear quantizations
2325 			 * with a high magnitude that allows 64-bits to
2326 			 * overflow, but we nonetheless protect against this
2327 			 * by explicitly checking for overflow, and clamping
2328 			 * our value accordingly.
2329 			 */
2330 			value = this - 1;
2331 		}
2332 
2333 		if (value < this) {
2334 			/*
2335 			 * If our value lies within this order of magnitude,
2336 			 * determine its position by taking the offset within
2337 			 * the order of magnitude, dividing by the bucket
2338 			 * width, and adding to our (accumulated) base.
2339 			 */
2340 			return (base + (value - last) / (this / nbuckets));
2341 		}
2342 
2343 		base += nbuckets - (nbuckets / factor);
2344 		last = this;
2345 		this = next;
2346 	}
2347 
2348 	/*
2349 	 * Our value is greater than or equal to our factor taken to the
2350 	 * power of one plus the high magnitude -- return the top bucket.
2351 	 */
2352 	return (base);
2353 }
2354 
2355 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2356 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2357 {
2358 	uint64_t arg = *llquanta++;
2359 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2360 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2361 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2362 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2363 
2364 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2365 	    low, high, nsteps, nval)] += incr;
2366 }
2367 
2368 /*ARGSUSED*/
2369 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2370 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2371 {
2372 	data[0]++;
2373 	data[1] += nval;
2374 }
2375 
2376 /*ARGSUSED*/
2377 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2378 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2379 {
2380 	int64_t snval = (int64_t)nval;
2381 	uint64_t tmp[2];
2382 
2383 	data[0]++;
2384 	data[1] += nval;
2385 
2386 	/*
2387 	 * What we want to say here is:
2388 	 *
2389 	 * data[2] += nval * nval;
2390 	 *
2391 	 * But given that nval is 64-bit, we could easily overflow, so
2392 	 * we do this as 128-bit arithmetic.
2393 	 */
2394 	if (snval < 0)
2395 		snval = -snval;
2396 
2397 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2398 	dtrace_add_128(data + 2, tmp, data + 2);
2399 }
2400 
2401 /*ARGSUSED*/
2402 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2403 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2404 {
2405 	*oval = *oval + 1;
2406 }
2407 
2408 /*ARGSUSED*/
2409 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2410 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2411 {
2412 	*oval += nval;
2413 }
2414 
2415 /*
2416  * Aggregate given the tuple in the principal data buffer, and the aggregating
2417  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2418  * buffer is specified as the buf parameter.  This routine does not return
2419  * failure; if there is no space in the aggregation buffer, the data will be
2420  * dropped, and a corresponding counter incremented.
2421  */
2422 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)2423 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2424     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2425 {
2426 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2427 	uint32_t i, ndx, size, fsize;
2428 	uint32_t align = sizeof (uint64_t) - 1;
2429 	dtrace_aggbuffer_t *agb;
2430 	dtrace_aggkey_t *key;
2431 	uint32_t hashval = 0, limit, isstr;
2432 	caddr_t tomax, data, kdata;
2433 	dtrace_actkind_t action;
2434 	dtrace_action_t *act;
2435 	uintptr_t offs;
2436 
2437 	if (buf == NULL)
2438 		return;
2439 
2440 	if (!agg->dtag_hasarg) {
2441 		/*
2442 		 * Currently, only quantize() and lquantize() take additional
2443 		 * arguments, and they have the same semantics:  an increment
2444 		 * value that defaults to 1 when not present.  If additional
2445 		 * aggregating actions take arguments, the setting of the
2446 		 * default argument value will presumably have to become more
2447 		 * sophisticated...
2448 		 */
2449 		arg = 1;
2450 	}
2451 
2452 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2453 	size = rec->dtrd_offset - agg->dtag_base;
2454 	fsize = size + rec->dtrd_size;
2455 
2456 	ASSERT(dbuf->dtb_tomax != NULL);
2457 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2458 
2459 	if ((tomax = buf->dtb_tomax) == NULL) {
2460 		dtrace_buffer_drop(buf);
2461 		return;
2462 	}
2463 
2464 	/*
2465 	 * The metastructure is always at the bottom of the buffer.
2466 	 */
2467 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2468 	    sizeof (dtrace_aggbuffer_t));
2469 
2470 	if (buf->dtb_offset == 0) {
2471 		/*
2472 		 * We just kludge up approximately 1/8th of the size to be
2473 		 * buckets.  If this guess ends up being routinely
2474 		 * off-the-mark, we may need to dynamically readjust this
2475 		 * based on past performance.
2476 		 */
2477 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2478 
2479 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2480 		    (uintptr_t)tomax || hashsize == 0) {
2481 			/*
2482 			 * We've been given a ludicrously small buffer;
2483 			 * increment our drop count and leave.
2484 			 */
2485 			dtrace_buffer_drop(buf);
2486 			return;
2487 		}
2488 
2489 		/*
2490 		 * And now, a pathetic attempt to try to get a an odd (or
2491 		 * perchance, a prime) hash size for better hash distribution.
2492 		 */
2493 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2494 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2495 
2496 		agb->dtagb_hashsize = hashsize;
2497 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2498 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2499 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2500 
2501 		for (i = 0; i < agb->dtagb_hashsize; i++)
2502 			agb->dtagb_hash[i] = NULL;
2503 	}
2504 
2505 	ASSERT(agg->dtag_first != NULL);
2506 	ASSERT(agg->dtag_first->dta_intuple);
2507 
2508 	/*
2509 	 * Calculate the hash value based on the key.  Note that we _don't_
2510 	 * include the aggid in the hashing (but we will store it as part of
2511 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2512 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2513 	 * gets good distribution in practice.  The efficacy of the hashing
2514 	 * algorithm (and a comparison with other algorithms) may be found by
2515 	 * running the ::dtrace_aggstat MDB dcmd.
2516 	 */
2517 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2518 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2519 		limit = i + act->dta_rec.dtrd_size;
2520 		ASSERT(limit <= size);
2521 		isstr = DTRACEACT_ISSTRING(act);
2522 
2523 		for (; i < limit; i++) {
2524 			hashval += data[i];
2525 			hashval += (hashval << 10);
2526 			hashval ^= (hashval >> 6);
2527 
2528 			if (isstr && data[i] == '\0')
2529 				break;
2530 		}
2531 	}
2532 
2533 	hashval += (hashval << 3);
2534 	hashval ^= (hashval >> 11);
2535 	hashval += (hashval << 15);
2536 
2537 	/*
2538 	 * Yes, the divide here is expensive -- but it's generally the least
2539 	 * of the performance issues given the amount of data that we iterate
2540 	 * over to compute hash values, compare data, etc.
2541 	 */
2542 	ndx = hashval % agb->dtagb_hashsize;
2543 
2544 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2545 		ASSERT((caddr_t)key >= tomax);
2546 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2547 
2548 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2549 			continue;
2550 
2551 		kdata = key->dtak_data;
2552 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2553 
2554 		for (act = agg->dtag_first; act->dta_intuple;
2555 		    act = act->dta_next) {
2556 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2557 			limit = i + act->dta_rec.dtrd_size;
2558 			ASSERT(limit <= size);
2559 			isstr = DTRACEACT_ISSTRING(act);
2560 
2561 			for (; i < limit; i++) {
2562 				if (kdata[i] != data[i])
2563 					goto next;
2564 
2565 				if (isstr && data[i] == '\0')
2566 					break;
2567 			}
2568 		}
2569 
2570 		if (action != key->dtak_action) {
2571 			/*
2572 			 * We are aggregating on the same value in the same
2573 			 * aggregation with two different aggregating actions.
2574 			 * (This should have been picked up in the compiler,
2575 			 * so we may be dealing with errant or devious DIF.)
2576 			 * This is an error condition; we indicate as much,
2577 			 * and return.
2578 			 */
2579 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2580 			return;
2581 		}
2582 
2583 		/*
2584 		 * This is a hit:  we need to apply the aggregator to
2585 		 * the value at this key.
2586 		 */
2587 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2588 		return;
2589 next:
2590 		continue;
2591 	}
2592 
2593 	/*
2594 	 * We didn't find it.  We need to allocate some zero-filled space,
2595 	 * link it into the hash table appropriately, and apply the aggregator
2596 	 * to the (zero-filled) value.
2597 	 */
2598 	offs = buf->dtb_offset;
2599 	while (offs & (align - 1))
2600 		offs += sizeof (uint32_t);
2601 
2602 	/*
2603 	 * If we don't have enough room to both allocate a new key _and_
2604 	 * its associated data, increment the drop count and return.
2605 	 */
2606 	if ((uintptr_t)tomax + offs + fsize >
2607 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2608 		dtrace_buffer_drop(buf);
2609 		return;
2610 	}
2611 
2612 	/*CONSTCOND*/
2613 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2614 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2615 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2616 
2617 	key->dtak_data = kdata = tomax + offs;
2618 	buf->dtb_offset = offs + fsize;
2619 
2620 	/*
2621 	 * Now copy the data across.
2622 	 */
2623 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2624 
2625 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2626 		kdata[i] = data[i];
2627 
2628 	/*
2629 	 * Because strings are not zeroed out by default, we need to iterate
2630 	 * looking for actions that store strings, and we need to explicitly
2631 	 * pad these strings out with zeroes.
2632 	 */
2633 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2634 		int nul;
2635 
2636 		if (!DTRACEACT_ISSTRING(act))
2637 			continue;
2638 
2639 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2640 		limit = i + act->dta_rec.dtrd_size;
2641 		ASSERT(limit <= size);
2642 
2643 		for (nul = 0; i < limit; i++) {
2644 			if (nul) {
2645 				kdata[i] = '\0';
2646 				continue;
2647 			}
2648 
2649 			if (data[i] != '\0')
2650 				continue;
2651 
2652 			nul = 1;
2653 		}
2654 	}
2655 
2656 	for (i = size; i < fsize; i++)
2657 		kdata[i] = 0;
2658 
2659 	key->dtak_hashval = hashval;
2660 	key->dtak_size = size;
2661 	key->dtak_action = action;
2662 	key->dtak_next = agb->dtagb_hash[ndx];
2663 	agb->dtagb_hash[ndx] = key;
2664 
2665 	/*
2666 	 * Finally, apply the aggregator.
2667 	 */
2668 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2669 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2670 }
2671 
2672 /*
2673  * Given consumer state, this routine finds a speculation in the INACTIVE
2674  * state and transitions it into the ACTIVE state.  If there is no speculation
2675  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2676  * incremented -- it is up to the caller to take appropriate action.
2677  */
2678 static int
dtrace_speculation(dtrace_state_t * state)2679 dtrace_speculation(dtrace_state_t *state)
2680 {
2681 	int i = 0;
2682 	dtrace_speculation_state_t current;
2683 	uint32_t *stat = &state->dts_speculations_unavail, count;
2684 
2685 	while (i < state->dts_nspeculations) {
2686 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2687 
2688 		current = spec->dtsp_state;
2689 
2690 		if (current != DTRACESPEC_INACTIVE) {
2691 			if (current == DTRACESPEC_COMMITTINGMANY ||
2692 			    current == DTRACESPEC_COMMITTING ||
2693 			    current == DTRACESPEC_DISCARDING)
2694 				stat = &state->dts_speculations_busy;
2695 			i++;
2696 			continue;
2697 		}
2698 
2699 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2700 		    current, DTRACESPEC_ACTIVE) == current)
2701 			return (i + 1);
2702 	}
2703 
2704 	/*
2705 	 * We couldn't find a speculation.  If we found as much as a single
2706 	 * busy speculation buffer, we'll attribute this failure as "busy"
2707 	 * instead of "unavail".
2708 	 */
2709 	do {
2710 		count = *stat;
2711 	} while (dtrace_cas32(stat, count, count + 1) != count);
2712 
2713 	return (0);
2714 }
2715 
2716 /*
2717  * This routine commits an active speculation.  If the specified speculation
2718  * is not in a valid state to perform a commit(), this routine will silently do
2719  * nothing.  The state of the specified speculation is transitioned according
2720  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2721  */
2722 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2723 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2724     dtrace_specid_t which)
2725 {
2726 	dtrace_speculation_t *spec;
2727 	dtrace_buffer_t *src, *dest;
2728 	uintptr_t daddr, saddr, dlimit, slimit;
2729 	dtrace_speculation_state_t current, new;
2730 	intptr_t offs;
2731 	uint64_t timestamp;
2732 
2733 	if (which == 0)
2734 		return;
2735 
2736 	if (which > state->dts_nspeculations) {
2737 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2738 		return;
2739 	}
2740 
2741 	spec = &state->dts_speculations[which - 1];
2742 	src = &spec->dtsp_buffer[cpu];
2743 	dest = &state->dts_buffer[cpu];
2744 
2745 	do {
2746 		current = spec->dtsp_state;
2747 
2748 		if (current == DTRACESPEC_COMMITTINGMANY)
2749 			break;
2750 
2751 		switch (current) {
2752 		case DTRACESPEC_INACTIVE:
2753 		case DTRACESPEC_DISCARDING:
2754 			return;
2755 
2756 		case DTRACESPEC_COMMITTING:
2757 			/*
2758 			 * This is only possible if we are (a) commit()'ing
2759 			 * without having done a prior speculate() on this CPU
2760 			 * and (b) racing with another commit() on a different
2761 			 * CPU.  There's nothing to do -- we just assert that
2762 			 * our offset is 0.
2763 			 */
2764 			ASSERT(src->dtb_offset == 0);
2765 			return;
2766 
2767 		case DTRACESPEC_ACTIVE:
2768 			new = DTRACESPEC_COMMITTING;
2769 			break;
2770 
2771 		case DTRACESPEC_ACTIVEONE:
2772 			/*
2773 			 * This speculation is active on one CPU.  If our
2774 			 * buffer offset is non-zero, we know that the one CPU
2775 			 * must be us.  Otherwise, we are committing on a
2776 			 * different CPU from the speculate(), and we must
2777 			 * rely on being asynchronously cleaned.
2778 			 */
2779 			if (src->dtb_offset != 0) {
2780 				new = DTRACESPEC_COMMITTING;
2781 				break;
2782 			}
2783 			/*FALLTHROUGH*/
2784 
2785 		case DTRACESPEC_ACTIVEMANY:
2786 			new = DTRACESPEC_COMMITTINGMANY;
2787 			break;
2788 
2789 		default:
2790 			ASSERT(0);
2791 		}
2792 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2793 	    current, new) != current);
2794 
2795 	/*
2796 	 * We have set the state to indicate that we are committing this
2797 	 * speculation.  Now reserve the necessary space in the destination
2798 	 * buffer.
2799 	 */
2800 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2801 	    sizeof (uint64_t), state, NULL)) < 0) {
2802 		dtrace_buffer_drop(dest);
2803 		goto out;
2804 	}
2805 
2806 	/*
2807 	 * We have sufficient space to copy the speculative buffer into the
2808 	 * primary buffer.  First, modify the speculative buffer, filling
2809 	 * in the timestamp of all entries with the current time.  The data
2810 	 * must have the commit() time rather than the time it was traced,
2811 	 * so that all entries in the primary buffer are in timestamp order.
2812 	 */
2813 	timestamp = dtrace_gethrtime();
2814 	saddr = (uintptr_t)src->dtb_tomax;
2815 	slimit = saddr + src->dtb_offset;
2816 	while (saddr < slimit) {
2817 		size_t size;
2818 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2819 
2820 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2821 			saddr += sizeof (dtrace_epid_t);
2822 			continue;
2823 		}
2824 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2825 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2826 
2827 		ASSERT3U(saddr + size, <=, slimit);
2828 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2829 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2830 
2831 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2832 
2833 		saddr += size;
2834 	}
2835 
2836 	/*
2837 	 * Copy the buffer across.  (Note that this is a
2838 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2839 	 * a serious performance issue, a high-performance DTrace-specific
2840 	 * bcopy() should obviously be invented.)
2841 	 */
2842 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2843 	dlimit = daddr + src->dtb_offset;
2844 	saddr = (uintptr_t)src->dtb_tomax;
2845 
2846 	/*
2847 	 * First, the aligned portion.
2848 	 */
2849 	while (dlimit - daddr >= sizeof (uint64_t)) {
2850 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2851 
2852 		daddr += sizeof (uint64_t);
2853 		saddr += sizeof (uint64_t);
2854 	}
2855 
2856 	/*
2857 	 * Now any left-over bit...
2858 	 */
2859 	while (dlimit - daddr)
2860 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2861 
2862 	/*
2863 	 * Finally, commit the reserved space in the destination buffer.
2864 	 */
2865 	dest->dtb_offset = offs + src->dtb_offset;
2866 
2867 out:
2868 	/*
2869 	 * If we're lucky enough to be the only active CPU on this speculation
2870 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2871 	 */
2872 	if (current == DTRACESPEC_ACTIVE ||
2873 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2874 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2875 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2876 
2877 		ASSERT(rval == DTRACESPEC_COMMITTING);
2878 	}
2879 
2880 	src->dtb_offset = 0;
2881 	src->dtb_xamot_drops += src->dtb_drops;
2882 	src->dtb_drops = 0;
2883 }
2884 
2885 /*
2886  * This routine discards an active speculation.  If the specified speculation
2887  * is not in a valid state to perform a discard(), this routine will silently
2888  * do nothing.  The state of the specified speculation is transitioned
2889  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2890  */
2891 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2892 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2893     dtrace_specid_t which)
2894 {
2895 	dtrace_speculation_t *spec;
2896 	dtrace_speculation_state_t current, new;
2897 	dtrace_buffer_t *buf;
2898 
2899 	if (which == 0)
2900 		return;
2901 
2902 	if (which > state->dts_nspeculations) {
2903 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2904 		return;
2905 	}
2906 
2907 	spec = &state->dts_speculations[which - 1];
2908 	buf = &spec->dtsp_buffer[cpu];
2909 
2910 	do {
2911 		current = spec->dtsp_state;
2912 
2913 		switch (current) {
2914 		case DTRACESPEC_INACTIVE:
2915 		case DTRACESPEC_COMMITTINGMANY:
2916 		case DTRACESPEC_COMMITTING:
2917 		case DTRACESPEC_DISCARDING:
2918 			return;
2919 
2920 		case DTRACESPEC_ACTIVE:
2921 		case DTRACESPEC_ACTIVEMANY:
2922 			new = DTRACESPEC_DISCARDING;
2923 			break;
2924 
2925 		case DTRACESPEC_ACTIVEONE:
2926 			if (buf->dtb_offset != 0) {
2927 				new = DTRACESPEC_INACTIVE;
2928 			} else {
2929 				new = DTRACESPEC_DISCARDING;
2930 			}
2931 			break;
2932 
2933 		default:
2934 			ASSERT(0);
2935 		}
2936 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2937 	    current, new) != current);
2938 
2939 	buf->dtb_offset = 0;
2940 	buf->dtb_drops = 0;
2941 }
2942 
2943 /*
2944  * Note:  not called from probe context.  This function is called
2945  * asynchronously from cross call context to clean any speculations that are
2946  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2947  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2948  * speculation.
2949  */
2950 static void
dtrace_speculation_clean_here(dtrace_state_t * state)2951 dtrace_speculation_clean_here(dtrace_state_t *state)
2952 {
2953 	dtrace_icookie_t cookie;
2954 	processorid_t cpu = CPU->cpu_id;
2955 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2956 	dtrace_specid_t i;
2957 
2958 	cookie = dtrace_interrupt_disable();
2959 
2960 	if (dest->dtb_tomax == NULL) {
2961 		dtrace_interrupt_enable(cookie);
2962 		return;
2963 	}
2964 
2965 	for (i = 0; i < state->dts_nspeculations; i++) {
2966 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2967 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2968 
2969 		if (src->dtb_tomax == NULL)
2970 			continue;
2971 
2972 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2973 			src->dtb_offset = 0;
2974 			continue;
2975 		}
2976 
2977 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2978 			continue;
2979 
2980 		if (src->dtb_offset == 0)
2981 			continue;
2982 
2983 		dtrace_speculation_commit(state, cpu, i + 1);
2984 	}
2985 
2986 	dtrace_interrupt_enable(cookie);
2987 }
2988 
2989 /*
2990  * Note:  not called from probe context.  This function is called
2991  * asynchronously (and at a regular interval) to clean any speculations that
2992  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2993  * is work to be done, it cross calls all CPUs to perform that work;
2994  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2995  * INACTIVE state until they have been cleaned by all CPUs.
2996  */
2997 static void
dtrace_speculation_clean(dtrace_state_t * state)2998 dtrace_speculation_clean(dtrace_state_t *state)
2999 {
3000 	int work = 0, rv;
3001 	dtrace_specid_t i;
3002 
3003 	for (i = 0; i < state->dts_nspeculations; i++) {
3004 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3005 
3006 		ASSERT(!spec->dtsp_cleaning);
3007 
3008 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3009 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3010 			continue;
3011 
3012 		work++;
3013 		spec->dtsp_cleaning = 1;
3014 	}
3015 
3016 	if (!work)
3017 		return;
3018 
3019 	dtrace_xcall(DTRACE_CPUALL,
3020 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3021 
3022 	/*
3023 	 * We now know that all CPUs have committed or discarded their
3024 	 * speculation buffers, as appropriate.  We can now set the state
3025 	 * to inactive.
3026 	 */
3027 	for (i = 0; i < state->dts_nspeculations; i++) {
3028 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3029 		dtrace_speculation_state_t current, new;
3030 
3031 		if (!spec->dtsp_cleaning)
3032 			continue;
3033 
3034 		current = spec->dtsp_state;
3035 		ASSERT(current == DTRACESPEC_DISCARDING ||
3036 		    current == DTRACESPEC_COMMITTINGMANY);
3037 
3038 		new = DTRACESPEC_INACTIVE;
3039 
3040 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3041 		ASSERT(rv == current);
3042 		spec->dtsp_cleaning = 0;
3043 	}
3044 }
3045 
3046 /*
3047  * Called as part of a speculate() to get the speculative buffer associated
3048  * with a given speculation.  Returns NULL if the specified speculation is not
3049  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3050  * the active CPU is not the specified CPU -- the speculation will be
3051  * atomically transitioned into the ACTIVEMANY state.
3052  */
3053 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3054 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3055     dtrace_specid_t which)
3056 {
3057 	dtrace_speculation_t *spec;
3058 	dtrace_speculation_state_t current, new;
3059 	dtrace_buffer_t *buf;
3060 
3061 	if (which == 0)
3062 		return (NULL);
3063 
3064 	if (which > state->dts_nspeculations) {
3065 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3066 		return (NULL);
3067 	}
3068 
3069 	spec = &state->dts_speculations[which - 1];
3070 	buf = &spec->dtsp_buffer[cpuid];
3071 
3072 	do {
3073 		current = spec->dtsp_state;
3074 
3075 		switch (current) {
3076 		case DTRACESPEC_INACTIVE:
3077 		case DTRACESPEC_COMMITTINGMANY:
3078 		case DTRACESPEC_DISCARDING:
3079 			return (NULL);
3080 
3081 		case DTRACESPEC_COMMITTING:
3082 			ASSERT(buf->dtb_offset == 0);
3083 			return (NULL);
3084 
3085 		case DTRACESPEC_ACTIVEONE:
3086 			/*
3087 			 * This speculation is currently active on one CPU.
3088 			 * Check the offset in the buffer; if it's non-zero,
3089 			 * that CPU must be us (and we leave the state alone).
3090 			 * If it's zero, assume that we're starting on a new
3091 			 * CPU -- and change the state to indicate that the
3092 			 * speculation is active on more than one CPU.
3093 			 */
3094 			if (buf->dtb_offset != 0)
3095 				return (buf);
3096 
3097 			new = DTRACESPEC_ACTIVEMANY;
3098 			break;
3099 
3100 		case DTRACESPEC_ACTIVEMANY:
3101 			return (buf);
3102 
3103 		case DTRACESPEC_ACTIVE:
3104 			new = DTRACESPEC_ACTIVEONE;
3105 			break;
3106 
3107 		default:
3108 			ASSERT(0);
3109 		}
3110 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3111 	    current, new) != current);
3112 
3113 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3114 	return (buf);
3115 }
3116 
3117 /*
3118  * Return a string.  In the event that the user lacks the privilege to access
3119  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3120  * don't fail access checking.
3121  *
3122  * dtrace_dif_variable() uses this routine as a helper for various
3123  * builtin values such as 'execname' and 'probefunc.'
3124  */
3125 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3126 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3127     dtrace_mstate_t *mstate)
3128 {
3129 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3130 	uintptr_t ret;
3131 	size_t strsz;
3132 
3133 	/*
3134 	 * The easy case: this probe is allowed to read all of memory, so
3135 	 * we can just return this as a vanilla pointer.
3136 	 */
3137 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3138 		return (addr);
3139 
3140 	/*
3141 	 * This is the tougher case: we copy the string in question from
3142 	 * kernel memory into scratch memory and return it that way: this
3143 	 * ensures that we won't trip up when access checking tests the
3144 	 * BYREF return value.
3145 	 */
3146 	strsz = dtrace_strlen((char *)addr, size) + 1;
3147 
3148 	if (mstate->dtms_scratch_ptr + strsz >
3149 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3150 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3151 		return (0);
3152 	}
3153 
3154 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3155 	    strsz);
3156 	ret = mstate->dtms_scratch_ptr;
3157 	mstate->dtms_scratch_ptr += strsz;
3158 	return (ret);
3159 }
3160 
3161 /*
3162  * This function implements the DIF emulator's variable lookups.  The emulator
3163  * passes a reserved variable identifier and optional built-in array index.
3164  */
3165 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3166 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3167     uint64_t ndx)
3168 {
3169 	/*
3170 	 * If we're accessing one of the uncached arguments, we'll turn this
3171 	 * into a reference in the args array.
3172 	 */
3173 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3174 		ndx = v - DIF_VAR_ARG0;
3175 		v = DIF_VAR_ARGS;
3176 	}
3177 
3178 	switch (v) {
3179 	case DIF_VAR_ARGS:
3180 		if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3181 			cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3182 			    CPU_DTRACE_KPRIV;
3183 			return (0);
3184 		}
3185 
3186 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3187 		if (ndx >= sizeof (mstate->dtms_arg) /
3188 		    sizeof (mstate->dtms_arg[0])) {
3189 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3190 			dtrace_provider_t *pv;
3191 			uint64_t val;
3192 
3193 			pv = mstate->dtms_probe->dtpr_provider;
3194 			if (pv->dtpv_pops.dtps_getargval != NULL)
3195 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3196 				    mstate->dtms_probe->dtpr_id,
3197 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3198 			else
3199 				val = dtrace_getarg(ndx, aframes);
3200 
3201 			/*
3202 			 * This is regrettably required to keep the compiler
3203 			 * from tail-optimizing the call to dtrace_getarg().
3204 			 * The condition always evaluates to true, but the
3205 			 * compiler has no way of figuring that out a priori.
3206 			 * (None of this would be necessary if the compiler
3207 			 * could be relied upon to _always_ tail-optimize
3208 			 * the call to dtrace_getarg() -- but it can't.)
3209 			 */
3210 			if (mstate->dtms_probe != NULL)
3211 				return (val);
3212 
3213 			ASSERT(0);
3214 		}
3215 
3216 		return (mstate->dtms_arg[ndx]);
3217 
3218 	case DIF_VAR_UREGS: {
3219 		klwp_t *lwp;
3220 
3221 		if (!dtrace_priv_proc(state, mstate))
3222 			return (0);
3223 
3224 		if ((lwp = curthread->t_lwp) == NULL) {
3225 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3226 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3227 			return (0);
3228 		}
3229 
3230 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3231 	}
3232 
3233 	case DIF_VAR_VMREGS: {
3234 		uint64_t rval;
3235 
3236 		if (!dtrace_priv_kernel(state))
3237 			return (0);
3238 
3239 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3240 
3241 		rval = dtrace_getvmreg(ndx,
3242 		    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3243 
3244 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3245 
3246 		return (rval);
3247 	}
3248 
3249 	case DIF_VAR_CURTHREAD:
3250 		if (!dtrace_priv_proc(state, mstate))
3251 			return (0);
3252 		return ((uint64_t)(uintptr_t)curthread);
3253 
3254 	case DIF_VAR_TIMESTAMP:
3255 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3256 			mstate->dtms_timestamp = dtrace_gethrtime();
3257 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3258 		}
3259 		return (mstate->dtms_timestamp);
3260 
3261 	case DIF_VAR_VTIMESTAMP:
3262 		ASSERT(dtrace_vtime_references != 0);
3263 		return (curthread->t_dtrace_vtime);
3264 
3265 	case DIF_VAR_WALLTIMESTAMP:
3266 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3267 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3268 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3269 		}
3270 		return (mstate->dtms_walltimestamp);
3271 
3272 	case DIF_VAR_IPL:
3273 		if (!dtrace_priv_kernel(state))
3274 			return (0);
3275 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3276 			mstate->dtms_ipl = dtrace_getipl();
3277 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3278 		}
3279 		return (mstate->dtms_ipl);
3280 
3281 	case DIF_VAR_EPID:
3282 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3283 		return (mstate->dtms_epid);
3284 
3285 	case DIF_VAR_ID:
3286 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3287 		return (mstate->dtms_probe->dtpr_id);
3288 
3289 	case DIF_VAR_STACKDEPTH:
3290 		if (!dtrace_priv_kernel(state))
3291 			return (0);
3292 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3293 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3294 
3295 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3296 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3297 		}
3298 		return (mstate->dtms_stackdepth);
3299 
3300 	case DIF_VAR_USTACKDEPTH:
3301 		if (!dtrace_priv_proc(state, mstate))
3302 			return (0);
3303 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3304 			/*
3305 			 * See comment in DIF_VAR_PID.
3306 			 */
3307 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3308 			    CPU_ON_INTR(CPU)) {
3309 				mstate->dtms_ustackdepth = 0;
3310 			} else {
3311 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3312 				mstate->dtms_ustackdepth =
3313 				    dtrace_getustackdepth();
3314 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3315 			}
3316 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3317 		}
3318 		return (mstate->dtms_ustackdepth);
3319 
3320 	case DIF_VAR_CALLER:
3321 		if (!dtrace_priv_kernel(state))
3322 			return (0);
3323 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3324 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3325 
3326 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3327 				/*
3328 				 * If this is an unanchored probe, we are
3329 				 * required to go through the slow path:
3330 				 * dtrace_caller() only guarantees correct
3331 				 * results for anchored probes.
3332 				 */
3333 				pc_t caller[2];
3334 
3335 				dtrace_getpcstack(caller, 2, aframes,
3336 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3337 				mstate->dtms_caller = caller[1];
3338 			} else if ((mstate->dtms_caller =
3339 			    dtrace_caller(aframes)) == -1) {
3340 				/*
3341 				 * We have failed to do this the quick way;
3342 				 * we must resort to the slower approach of
3343 				 * calling dtrace_getpcstack().
3344 				 */
3345 				pc_t caller;
3346 
3347 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3348 				mstate->dtms_caller = caller;
3349 			}
3350 
3351 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3352 		}
3353 		return (mstate->dtms_caller);
3354 
3355 	case DIF_VAR_UCALLER:
3356 		if (!dtrace_priv_proc(state, mstate))
3357 			return (0);
3358 
3359 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3360 			uint64_t ustack[3];
3361 
3362 			/*
3363 			 * dtrace_getupcstack() fills in the first uint64_t
3364 			 * with the current PID.  The second uint64_t will
3365 			 * be the program counter at user-level.  The third
3366 			 * uint64_t will contain the caller, which is what
3367 			 * we're after.
3368 			 */
3369 			ustack[2] = 0;
3370 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3371 			dtrace_getupcstack(ustack, 3);
3372 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3373 			mstate->dtms_ucaller = ustack[2];
3374 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3375 		}
3376 
3377 		return (mstate->dtms_ucaller);
3378 
3379 	case DIF_VAR_PROBEPROV:
3380 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3381 		return (dtrace_dif_varstr(
3382 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3383 		    state, mstate));
3384 
3385 	case DIF_VAR_PROBEMOD:
3386 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3387 		return (dtrace_dif_varstr(
3388 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3389 		    state, mstate));
3390 
3391 	case DIF_VAR_PROBEFUNC:
3392 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3393 		return (dtrace_dif_varstr(
3394 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3395 		    state, mstate));
3396 
3397 	case DIF_VAR_PROBENAME:
3398 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3399 		return (dtrace_dif_varstr(
3400 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3401 		    state, mstate));
3402 
3403 	case DIF_VAR_PID:
3404 		if (!dtrace_priv_proc(state, mstate))
3405 			return (0);
3406 
3407 		/*
3408 		 * Note that we are assuming that an unanchored probe is
3409 		 * always due to a high-level interrupt.  (And we're assuming
3410 		 * that there is only a single high level interrupt.)
3411 		 */
3412 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3413 			return (pid0.pid_id);
3414 
3415 		/*
3416 		 * It is always safe to dereference one's own t_procp pointer:
3417 		 * it always points to a valid, allocated proc structure.
3418 		 * Further, it is always safe to dereference the p_pidp member
3419 		 * of one's own proc structure.  (These are truisms becuase
3420 		 * threads and processes don't clean up their own state --
3421 		 * they leave that task to whomever reaps them.)
3422 		 */
3423 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3424 
3425 	case DIF_VAR_PPID:
3426 		if (!dtrace_priv_proc(state, mstate))
3427 			return (0);
3428 
3429 		/*
3430 		 * See comment in DIF_VAR_PID.
3431 		 */
3432 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3433 			return (pid0.pid_id);
3434 
3435 		/*
3436 		 * It is always safe to dereference one's own t_procp pointer:
3437 		 * it always points to a valid, allocated proc structure.
3438 		 * (This is true because threads don't clean up their own
3439 		 * state -- they leave that task to whomever reaps them.)
3440 		 */
3441 		return ((uint64_t)curthread->t_procp->p_ppid);
3442 
3443 	case DIF_VAR_TID:
3444 		/*
3445 		 * See comment in DIF_VAR_PID.
3446 		 */
3447 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3448 			return (0);
3449 
3450 		return ((uint64_t)curthread->t_tid);
3451 
3452 	case DIF_VAR_EXECNAME:
3453 		if (!dtrace_priv_proc(state, mstate))
3454 			return (0);
3455 
3456 		/*
3457 		 * See comment in DIF_VAR_PID.
3458 		 */
3459 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3460 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3461 
3462 		/*
3463 		 * It is always safe to dereference one's own t_procp pointer:
3464 		 * it always points to a valid, allocated proc structure.
3465 		 * (This is true because threads don't clean up their own
3466 		 * state -- they leave that task to whomever reaps them.)
3467 		 */
3468 		return (dtrace_dif_varstr(
3469 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3470 		    state, mstate));
3471 
3472 	case DIF_VAR_ZONENAME:
3473 		if (!dtrace_priv_proc(state, mstate))
3474 			return (0);
3475 
3476 		/*
3477 		 * See comment in DIF_VAR_PID.
3478 		 */
3479 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3480 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3481 
3482 		/*
3483 		 * It is always safe to dereference one's own t_procp pointer:
3484 		 * it always points to a valid, allocated proc structure.
3485 		 * (This is true because threads don't clean up their own
3486 		 * state -- they leave that task to whomever reaps them.)
3487 		 */
3488 		return (dtrace_dif_varstr(
3489 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3490 		    state, mstate));
3491 
3492 	case DIF_VAR_UID:
3493 		if (!dtrace_priv_proc(state, mstate))
3494 			return (0);
3495 
3496 		/*
3497 		 * See comment in DIF_VAR_PID.
3498 		 */
3499 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3500 			return ((uint64_t)p0.p_cred->cr_uid);
3501 
3502 		/*
3503 		 * It is always safe to dereference one's own t_procp pointer:
3504 		 * it always points to a valid, allocated proc structure.
3505 		 * (This is true because threads don't clean up their own
3506 		 * state -- they leave that task to whomever reaps them.)
3507 		 *
3508 		 * Additionally, it is safe to dereference one's own process
3509 		 * credential, since this is never NULL after process birth.
3510 		 */
3511 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3512 
3513 	case DIF_VAR_GID:
3514 		if (!dtrace_priv_proc(state, mstate))
3515 			return (0);
3516 
3517 		/*
3518 		 * See comment in DIF_VAR_PID.
3519 		 */
3520 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3521 			return ((uint64_t)p0.p_cred->cr_gid);
3522 
3523 		/*
3524 		 * It is always safe to dereference one's own t_procp pointer:
3525 		 * it always points to a valid, allocated proc structure.
3526 		 * (This is true because threads don't clean up their own
3527 		 * state -- they leave that task to whomever reaps them.)
3528 		 *
3529 		 * Additionally, it is safe to dereference one's own process
3530 		 * credential, since this is never NULL after process birth.
3531 		 */
3532 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3533 
3534 	case DIF_VAR_ERRNO: {
3535 		klwp_t *lwp;
3536 		if (!dtrace_priv_proc(state, mstate))
3537 			return (0);
3538 
3539 		/*
3540 		 * See comment in DIF_VAR_PID.
3541 		 */
3542 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3543 			return (0);
3544 
3545 		/*
3546 		 * It is always safe to dereference one's own t_lwp pointer in
3547 		 * the event that this pointer is non-NULL.  (This is true
3548 		 * because threads and lwps don't clean up their own state --
3549 		 * they leave that task to whomever reaps them.)
3550 		 */
3551 		if ((lwp = curthread->t_lwp) == NULL)
3552 			return (0);
3553 
3554 		return ((uint64_t)lwp->lwp_errno);
3555 	}
3556 
3557 	case DIF_VAR_THREADNAME:
3558 		/*
3559 		 * See comment in DIF_VAR_PID.
3560 		 */
3561 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3562 			return (0);
3563 
3564 		if (curthread->t_name == NULL)
3565 			return (0);
3566 
3567 		/*
3568 		 * Once set, ->t_name itself is never changed: any updates are
3569 		 * made to the same buffer that we are pointing out.  So we are
3570 		 * safe to dereference it here.
3571 		 */
3572 		return (dtrace_dif_varstr((uintptr_t)curthread->t_name,
3573 		    state, mstate));
3574 
3575 	default:
3576 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3577 		return (0);
3578 	}
3579 }
3580 
3581 static void
dtrace_dif_variable_write(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx,uint64_t data)3582 dtrace_dif_variable_write(dtrace_mstate_t *mstate, dtrace_state_t *state,
3583     uint64_t v, uint64_t ndx, uint64_t data)
3584 {
3585 	switch (v) {
3586 	case DIF_VAR_UREGS: {
3587 		klwp_t *lwp;
3588 
3589 		if (dtrace_destructive_disallow ||
3590 		    !dtrace_priv_proc_control(state, mstate)) {
3591 			return;
3592 		}
3593 
3594 		if ((lwp = curthread->t_lwp) == NULL) {
3595 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3596 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3597 			return;
3598 		}
3599 
3600 		dtrace_setreg(lwp->lwp_regs, ndx, data);
3601 		return;
3602 	}
3603 
3604 	default:
3605 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3606 		return;
3607 	}
3608 }
3609 
3610 typedef enum dtrace_json_state {
3611 	DTRACE_JSON_REST = 1,
3612 	DTRACE_JSON_OBJECT,
3613 	DTRACE_JSON_STRING,
3614 	DTRACE_JSON_STRING_ESCAPE,
3615 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3616 	DTRACE_JSON_COLON,
3617 	DTRACE_JSON_COMMA,
3618 	DTRACE_JSON_VALUE,
3619 	DTRACE_JSON_IDENTIFIER,
3620 	DTRACE_JSON_NUMBER,
3621 	DTRACE_JSON_NUMBER_FRAC,
3622 	DTRACE_JSON_NUMBER_EXP,
3623 	DTRACE_JSON_COLLECT_OBJECT
3624 } dtrace_json_state_t;
3625 
3626 /*
3627  * This function possesses just enough knowledge about JSON to extract a single
3628  * value from a JSON string and store it in the scratch buffer.  It is able
3629  * to extract nested object values, and members of arrays by index.
3630  *
3631  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3632  * be looked up as we descend into the object tree.  e.g.
3633  *
3634  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3635  *       with nelems = 5.
3636  *
3637  * The run time of this function must be bounded above by strsize to limit the
3638  * amount of work done in probe context.  As such, it is implemented as a
3639  * simple state machine, reading one character at a time using safe loads
3640  * until we find the requested element, hit a parsing error or run off the
3641  * end of the object or string.
3642  *
3643  * As there is no way for a subroutine to return an error without interrupting
3644  * clause execution, we simply return NULL in the event of a missing key or any
3645  * other error condition.  Each NULL return in this function is commented with
3646  * the error condition it represents -- parsing or otherwise.
3647  *
3648  * The set of states for the state machine closely matches the JSON
3649  * specification (http://json.org/).  Briefly:
3650  *
3651  *   DTRACE_JSON_REST:
3652  *     Skip whitespace until we find either a top-level Object, moving
3653  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3654  *
3655  *   DTRACE_JSON_OBJECT:
3656  *     Locate the next key String in an Object.  Sets a flag to denote
3657  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3658  *
3659  *   DTRACE_JSON_COLON:
3660  *     Skip whitespace until we find the colon that separates key Strings
3661  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3662  *
3663  *   DTRACE_JSON_VALUE:
3664  *     Detects the type of the next value (String, Number, Identifier, Object
3665  *     or Array) and routes to the states that process that type.  Here we also
3666  *     deal with the element selector list if we are requested to traverse down
3667  *     into the object tree.
3668  *
3669  *   DTRACE_JSON_COMMA:
3670  *     Skip whitespace until we find the comma that separates key-value pairs
3671  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3672  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3673  *     states return to this state at the end of their value, unless otherwise
3674  *     noted.
3675  *
3676  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3677  *     Processes a Number literal from the JSON, including any exponent
3678  *     component that may be present.  Numbers are returned as strings, which
3679  *     may be passed to strtoll() if an integer is required.
3680  *
3681  *   DTRACE_JSON_IDENTIFIER:
3682  *     Processes a "true", "false" or "null" literal in the JSON.
3683  *
3684  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3685  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3686  *     Processes a String literal from the JSON, whether the String denotes
3687  *     a key, a value or part of a larger Object.  Handles all escape sequences
3688  *     present in the specification, including four-digit unicode characters,
3689  *     but merely includes the escape sequence without converting it to the
3690  *     actual escaped character.  If the String is flagged as a key, we
3691  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3692  *
3693  *   DTRACE_JSON_COLLECT_OBJECT:
3694  *     This state collects an entire Object (or Array), correctly handling
3695  *     embedded strings.  If the full element selector list matches this nested
3696  *     object, we return the Object in full as a string.  If not, we use this
3697  *     state to skip to the next value at this level and continue processing.
3698  *
3699  * NOTE: This function uses various macros from strtolctype.h to manipulate
3700  * digit values, etc -- these have all been checked to ensure they make
3701  * no additional function calls.
3702  */
3703 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3704 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3705     char *dest)
3706 {
3707 	dtrace_json_state_t state = DTRACE_JSON_REST;
3708 	int64_t array_elem = INT64_MIN;
3709 	int64_t array_pos = 0;
3710 	uint8_t escape_unicount = 0;
3711 	boolean_t string_is_key = B_FALSE;
3712 	boolean_t collect_object = B_FALSE;
3713 	boolean_t found_key = B_FALSE;
3714 	boolean_t in_array = B_FALSE;
3715 	uint32_t braces = 0, brackets = 0;
3716 	char *elem = elemlist;
3717 	char *dd = dest;
3718 	uintptr_t cur;
3719 
3720 	for (cur = json; cur < json + size; cur++) {
3721 		char cc = dtrace_load8(cur);
3722 		if (cc == '\0')
3723 			return (NULL);
3724 
3725 		switch (state) {
3726 		case DTRACE_JSON_REST:
3727 			if (isspace(cc))
3728 				break;
3729 
3730 			if (cc == '{') {
3731 				state = DTRACE_JSON_OBJECT;
3732 				break;
3733 			}
3734 
3735 			if (cc == '[') {
3736 				in_array = B_TRUE;
3737 				array_pos = 0;
3738 				array_elem = dtrace_strtoll(elem, 10, size);
3739 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3740 				state = DTRACE_JSON_VALUE;
3741 				break;
3742 			}
3743 
3744 			/*
3745 			 * ERROR: expected to find a top-level object or array.
3746 			 */
3747 			return (NULL);
3748 		case DTRACE_JSON_OBJECT:
3749 			if (isspace(cc))
3750 				break;
3751 
3752 			if (cc == '"') {
3753 				state = DTRACE_JSON_STRING;
3754 				string_is_key = B_TRUE;
3755 				break;
3756 			}
3757 
3758 			/*
3759 			 * ERROR: either the object did not start with a key
3760 			 * string, or we've run off the end of the object
3761 			 * without finding the requested key.
3762 			 */
3763 			return (NULL);
3764 		case DTRACE_JSON_STRING:
3765 			if (cc == '\\') {
3766 				*dd++ = '\\';
3767 				state = DTRACE_JSON_STRING_ESCAPE;
3768 				break;
3769 			}
3770 
3771 			if (cc == '"') {
3772 				if (collect_object) {
3773 					/*
3774 					 * We don't reset the dest here, as
3775 					 * the string is part of a larger
3776 					 * object being collected.
3777 					 */
3778 					*dd++ = cc;
3779 					collect_object = B_FALSE;
3780 					state = DTRACE_JSON_COLLECT_OBJECT;
3781 					break;
3782 				}
3783 				*dd = '\0';
3784 				dd = dest; /* reset string buffer */
3785 				if (string_is_key) {
3786 					if (dtrace_strncmp(dest, elem,
3787 					    size) == 0)
3788 						found_key = B_TRUE;
3789 				} else if (found_key) {
3790 					if (nelems > 1) {
3791 						/*
3792 						 * We expected an object, not
3793 						 * this string.
3794 						 */
3795 						return (NULL);
3796 					}
3797 					return (dest);
3798 				}
3799 				state = string_is_key ? DTRACE_JSON_COLON :
3800 				    DTRACE_JSON_COMMA;
3801 				string_is_key = B_FALSE;
3802 				break;
3803 			}
3804 
3805 			*dd++ = cc;
3806 			break;
3807 		case DTRACE_JSON_STRING_ESCAPE:
3808 			*dd++ = cc;
3809 			if (cc == 'u') {
3810 				escape_unicount = 0;
3811 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3812 			} else {
3813 				state = DTRACE_JSON_STRING;
3814 			}
3815 			break;
3816 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3817 			if (!isxdigit(cc)) {
3818 				/*
3819 				 * ERROR: invalid unicode escape, expected
3820 				 * four valid hexidecimal digits.
3821 				 */
3822 				return (NULL);
3823 			}
3824 
3825 			*dd++ = cc;
3826 			if (++escape_unicount == 4)
3827 				state = DTRACE_JSON_STRING;
3828 			break;
3829 		case DTRACE_JSON_COLON:
3830 			if (isspace(cc))
3831 				break;
3832 
3833 			if (cc == ':') {
3834 				state = DTRACE_JSON_VALUE;
3835 				break;
3836 			}
3837 
3838 			/*
3839 			 * ERROR: expected a colon.
3840 			 */
3841 			return (NULL);
3842 		case DTRACE_JSON_COMMA:
3843 			if (isspace(cc))
3844 				break;
3845 
3846 			if (cc == ',') {
3847 				if (in_array) {
3848 					state = DTRACE_JSON_VALUE;
3849 					if (++array_pos == array_elem)
3850 						found_key = B_TRUE;
3851 				} else {
3852 					state = DTRACE_JSON_OBJECT;
3853 				}
3854 				break;
3855 			}
3856 
3857 			/*
3858 			 * ERROR: either we hit an unexpected character, or
3859 			 * we reached the end of the object or array without
3860 			 * finding the requested key.
3861 			 */
3862 			return (NULL);
3863 		case DTRACE_JSON_IDENTIFIER:
3864 			if (islower(cc)) {
3865 				*dd++ = cc;
3866 				break;
3867 			}
3868 
3869 			*dd = '\0';
3870 			dd = dest; /* reset string buffer */
3871 
3872 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3873 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3874 			    dtrace_strncmp(dest, "null", 5) == 0) {
3875 				if (found_key) {
3876 					if (nelems > 1) {
3877 						/*
3878 						 * ERROR: We expected an object,
3879 						 * not this identifier.
3880 						 */
3881 						return (NULL);
3882 					}
3883 					return (dest);
3884 				} else {
3885 					cur--;
3886 					state = DTRACE_JSON_COMMA;
3887 					break;
3888 				}
3889 			}
3890 
3891 			/*
3892 			 * ERROR: we did not recognise the identifier as one
3893 			 * of those in the JSON specification.
3894 			 */
3895 			return (NULL);
3896 		case DTRACE_JSON_NUMBER:
3897 			if (cc == '.') {
3898 				*dd++ = cc;
3899 				state = DTRACE_JSON_NUMBER_FRAC;
3900 				break;
3901 			}
3902 
3903 			if (cc == 'x' || cc == 'X') {
3904 				/*
3905 				 * ERROR: specification explicitly excludes
3906 				 * hexidecimal or octal numbers.
3907 				 */
3908 				return (NULL);
3909 			}
3910 
3911 			/* FALLTHRU */
3912 		case DTRACE_JSON_NUMBER_FRAC:
3913 			if (cc == 'e' || cc == 'E') {
3914 				*dd++ = cc;
3915 				state = DTRACE_JSON_NUMBER_EXP;
3916 				break;
3917 			}
3918 
3919 			if (cc == '+' || cc == '-') {
3920 				/*
3921 				 * ERROR: expect sign as part of exponent only.
3922 				 */
3923 				return (NULL);
3924 			}
3925 			/* FALLTHRU */
3926 		case DTRACE_JSON_NUMBER_EXP:
3927 			if (isdigit(cc) || cc == '+' || cc == '-') {
3928 				*dd++ = cc;
3929 				break;
3930 			}
3931 
3932 			*dd = '\0';
3933 			dd = dest; /* reset string buffer */
3934 			if (found_key) {
3935 				if (nelems > 1) {
3936 					/*
3937 					 * ERROR: We expected an object, not
3938 					 * this number.
3939 					 */
3940 					return (NULL);
3941 				}
3942 				return (dest);
3943 			}
3944 
3945 			cur--;
3946 			state = DTRACE_JSON_COMMA;
3947 			break;
3948 		case DTRACE_JSON_VALUE:
3949 			if (isspace(cc))
3950 				break;
3951 
3952 			if (cc == '{' || cc == '[') {
3953 				if (nelems > 1 && found_key) {
3954 					in_array = cc == '[' ? B_TRUE : B_FALSE;
3955 					/*
3956 					 * If our element selector directs us
3957 					 * to descend into this nested object,
3958 					 * then move to the next selector
3959 					 * element in the list and restart the
3960 					 * state machine.
3961 					 */
3962 					while (*elem != '\0')
3963 						elem++;
3964 					elem++; /* skip the inter-element NUL */
3965 					nelems--;
3966 					dd = dest;
3967 					if (in_array) {
3968 						state = DTRACE_JSON_VALUE;
3969 						array_pos = 0;
3970 						array_elem = dtrace_strtoll(
3971 						    elem, 10, size);
3972 						found_key = array_elem == 0 ?
3973 						    B_TRUE : B_FALSE;
3974 					} else {
3975 						found_key = B_FALSE;
3976 						state = DTRACE_JSON_OBJECT;
3977 					}
3978 					break;
3979 				}
3980 
3981 				/*
3982 				 * Otherwise, we wish to either skip this
3983 				 * nested object or return it in full.
3984 				 */
3985 				if (cc == '[')
3986 					brackets = 1;
3987 				else
3988 					braces = 1;
3989 				*dd++ = cc;
3990 				state = DTRACE_JSON_COLLECT_OBJECT;
3991 				break;
3992 			}
3993 
3994 			if (cc == '"') {
3995 				state = DTRACE_JSON_STRING;
3996 				break;
3997 			}
3998 
3999 			if (islower(cc)) {
4000 				/*
4001 				 * Here we deal with true, false and null.
4002 				 */
4003 				*dd++ = cc;
4004 				state = DTRACE_JSON_IDENTIFIER;
4005 				break;
4006 			}
4007 
4008 			if (cc == '-' || isdigit(cc)) {
4009 				*dd++ = cc;
4010 				state = DTRACE_JSON_NUMBER;
4011 				break;
4012 			}
4013 
4014 			/*
4015 			 * ERROR: unexpected character at start of value.
4016 			 */
4017 			return (NULL);
4018 		case DTRACE_JSON_COLLECT_OBJECT:
4019 			if (cc == '\0')
4020 				/*
4021 				 * ERROR: unexpected end of input.
4022 				 */
4023 				return (NULL);
4024 
4025 			*dd++ = cc;
4026 			if (cc == '"') {
4027 				collect_object = B_TRUE;
4028 				state = DTRACE_JSON_STRING;
4029 				break;
4030 			}
4031 
4032 			if (cc == ']') {
4033 				if (brackets-- == 0) {
4034 					/*
4035 					 * ERROR: unbalanced brackets.
4036 					 */
4037 					return (NULL);
4038 				}
4039 			} else if (cc == '}') {
4040 				if (braces-- == 0) {
4041 					/*
4042 					 * ERROR: unbalanced braces.
4043 					 */
4044 					return (NULL);
4045 				}
4046 			} else if (cc == '{') {
4047 				braces++;
4048 			} else if (cc == '[') {
4049 				brackets++;
4050 			}
4051 
4052 			if (brackets == 0 && braces == 0) {
4053 				if (found_key) {
4054 					*dd = '\0';
4055 					return (dest);
4056 				}
4057 				dd = dest; /* reset string buffer */
4058 				state = DTRACE_JSON_COMMA;
4059 			}
4060 			break;
4061 		}
4062 	}
4063 	return (NULL);
4064 }
4065 
4066 /*
4067  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4068  * Notice that we don't bother validating the proper number of arguments or
4069  * their types in the tuple stack.  This isn't needed because all argument
4070  * interpretation is safe because of our load safety -- the worst that can
4071  * happen is that a bogus program can obtain bogus results.
4072  */
4073 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)4074 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4075     dtrace_key_t *tupregs, int nargs,
4076     dtrace_mstate_t *mstate, dtrace_state_t *state)
4077 {
4078 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4079 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4080 	dtrace_vstate_t *vstate = &state->dts_vstate;
4081 
4082 	union {
4083 		mutex_impl_t mi;
4084 		uint64_t mx;
4085 	} m;
4086 
4087 	union {
4088 		krwlock_t ri;
4089 		uintptr_t rw;
4090 	} r;
4091 
4092 	switch (subr) {
4093 	case DIF_SUBR_RAND:
4094 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4095 		break;
4096 
4097 	case DIF_SUBR_MUTEX_OWNED:
4098 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4099 		    mstate, vstate)) {
4100 			regs[rd] = 0;
4101 			break;
4102 		}
4103 
4104 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4105 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4106 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4107 		else
4108 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4109 		break;
4110 
4111 	case DIF_SUBR_MUTEX_OWNER:
4112 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4113 		    mstate, vstate)) {
4114 			regs[rd] = 0;
4115 			break;
4116 		}
4117 
4118 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4119 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4120 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4121 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4122 		else
4123 			regs[rd] = 0;
4124 		break;
4125 
4126 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4127 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4128 		    mstate, vstate)) {
4129 			regs[rd] = 0;
4130 			break;
4131 		}
4132 
4133 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4134 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4135 		break;
4136 
4137 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4138 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4139 		    mstate, vstate)) {
4140 			regs[rd] = 0;
4141 			break;
4142 		}
4143 
4144 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4145 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4146 		break;
4147 
4148 	case DIF_SUBR_RW_READ_HELD: {
4149 		uintptr_t tmp;
4150 
4151 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4152 		    mstate, vstate)) {
4153 			regs[rd] = 0;
4154 			break;
4155 		}
4156 
4157 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4158 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4159 		break;
4160 	}
4161 
4162 	case DIF_SUBR_RW_WRITE_HELD:
4163 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4164 		    mstate, vstate)) {
4165 			regs[rd] = 0;
4166 			break;
4167 		}
4168 
4169 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4170 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4171 		break;
4172 
4173 	case DIF_SUBR_RW_ISWRITER:
4174 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4175 		    mstate, vstate)) {
4176 			regs[rd] = 0;
4177 			break;
4178 		}
4179 
4180 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4181 		regs[rd] = _RW_ISWRITER(&r.ri);
4182 		break;
4183 
4184 	case DIF_SUBR_BCOPY: {
4185 		/*
4186 		 * We need to be sure that the destination is in the scratch
4187 		 * region -- no other region is allowed.
4188 		 */
4189 		uintptr_t src = tupregs[0].dttk_value;
4190 		uintptr_t dest = tupregs[1].dttk_value;
4191 		size_t size = tupregs[2].dttk_value;
4192 
4193 		if (!dtrace_inscratch(dest, size, mstate)) {
4194 			*flags |= CPU_DTRACE_BADADDR;
4195 			*illval = regs[rd];
4196 			break;
4197 		}
4198 
4199 		if (!dtrace_canload(src, size, mstate, vstate)) {
4200 			regs[rd] = 0;
4201 			break;
4202 		}
4203 
4204 		dtrace_bcopy((void *)src, (void *)dest, size);
4205 		break;
4206 	}
4207 
4208 	case DIF_SUBR_ALLOCA:
4209 	case DIF_SUBR_COPYIN: {
4210 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4211 		uint64_t size =
4212 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4213 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4214 
4215 		/*
4216 		 * This action doesn't require any credential checks since
4217 		 * probes will not activate in user contexts to which the
4218 		 * enabling user does not have permissions.
4219 		 */
4220 
4221 		/*
4222 		 * Rounding up the user allocation size could have overflowed
4223 		 * a large, bogus allocation (like -1ULL) to 0.
4224 		 */
4225 		if (scratch_size < size ||
4226 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4227 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4228 			regs[rd] = 0;
4229 			break;
4230 		}
4231 
4232 		if (subr == DIF_SUBR_COPYIN) {
4233 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4234 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4235 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4236 		}
4237 
4238 		mstate->dtms_scratch_ptr += scratch_size;
4239 		regs[rd] = dest;
4240 		break;
4241 	}
4242 
4243 	case DIF_SUBR_COPYINTO: {
4244 		uint64_t size = tupregs[1].dttk_value;
4245 		uintptr_t dest = tupregs[2].dttk_value;
4246 
4247 		/*
4248 		 * This action doesn't require any credential checks since
4249 		 * probes will not activate in user contexts to which the
4250 		 * enabling user does not have permissions.
4251 		 */
4252 		if (!dtrace_inscratch(dest, size, mstate)) {
4253 			*flags |= CPU_DTRACE_BADADDR;
4254 			*illval = regs[rd];
4255 			break;
4256 		}
4257 
4258 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4259 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4260 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4261 		break;
4262 	}
4263 
4264 	case DIF_SUBR_COPYINSTR: {
4265 		uintptr_t dest = mstate->dtms_scratch_ptr;
4266 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4267 
4268 		if (nargs > 1 && tupregs[1].dttk_value < size)
4269 			size = tupregs[1].dttk_value + 1;
4270 
4271 		/*
4272 		 * This action doesn't require any credential checks since
4273 		 * probes will not activate in user contexts to which the
4274 		 * enabling user does not have permissions.
4275 		 */
4276 		if (!DTRACE_INSCRATCH(mstate, size)) {
4277 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4278 			regs[rd] = 0;
4279 			break;
4280 		}
4281 
4282 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4283 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4284 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4285 
4286 		((char *)dest)[size - 1] = '\0';
4287 		mstate->dtms_scratch_ptr += size;
4288 		regs[rd] = dest;
4289 		break;
4290 	}
4291 
4292 	case DIF_SUBR_MSGSIZE:
4293 	case DIF_SUBR_MSGDSIZE: {
4294 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4295 		uintptr_t wptr, rptr;
4296 		size_t count = 0;
4297 		int cont = 0;
4298 
4299 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4300 
4301 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4302 			    vstate)) {
4303 				regs[rd] = 0;
4304 				break;
4305 			}
4306 
4307 			wptr = dtrace_loadptr(baddr +
4308 			    offsetof(mblk_t, b_wptr));
4309 
4310 			rptr = dtrace_loadptr(baddr +
4311 			    offsetof(mblk_t, b_rptr));
4312 
4313 			if (wptr < rptr) {
4314 				*flags |= CPU_DTRACE_BADADDR;
4315 				*illval = tupregs[0].dttk_value;
4316 				break;
4317 			}
4318 
4319 			daddr = dtrace_loadptr(baddr +
4320 			    offsetof(mblk_t, b_datap));
4321 
4322 			baddr = dtrace_loadptr(baddr +
4323 			    offsetof(mblk_t, b_cont));
4324 
4325 			/*
4326 			 * We want to prevent against denial-of-service here,
4327 			 * so we're only going to search the list for
4328 			 * dtrace_msgdsize_max mblks.
4329 			 */
4330 			if (cont++ > dtrace_msgdsize_max) {
4331 				*flags |= CPU_DTRACE_ILLOP;
4332 				break;
4333 			}
4334 
4335 			if (subr == DIF_SUBR_MSGDSIZE) {
4336 				if (dtrace_load8(daddr +
4337 				    offsetof(dblk_t, db_type)) != M_DATA)
4338 					continue;
4339 			}
4340 
4341 			count += wptr - rptr;
4342 		}
4343 
4344 		if (!(*flags & CPU_DTRACE_FAULT))
4345 			regs[rd] = count;
4346 
4347 		break;
4348 	}
4349 
4350 	case DIF_SUBR_PROGENYOF: {
4351 		pid_t pid = tupregs[0].dttk_value;
4352 		proc_t *p;
4353 		int rval = 0;
4354 
4355 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4356 
4357 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4358 			if (p->p_pidp->pid_id == pid) {
4359 				rval = 1;
4360 				break;
4361 			}
4362 		}
4363 
4364 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4365 
4366 		regs[rd] = rval;
4367 		break;
4368 	}
4369 
4370 	case DIF_SUBR_SPECULATION:
4371 		regs[rd] = dtrace_speculation(state);
4372 		break;
4373 
4374 	case DIF_SUBR_COPYOUT: {
4375 		uintptr_t kaddr = tupregs[0].dttk_value;
4376 		uintptr_t uaddr = tupregs[1].dttk_value;
4377 		uint64_t size = tupregs[2].dttk_value;
4378 
4379 		if (!dtrace_destructive_disallow &&
4380 		    dtrace_priv_proc_control(state, mstate) &&
4381 		    !dtrace_istoxic(kaddr, size) &&
4382 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4383 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4384 			dtrace_copyout(kaddr, uaddr, size, flags);
4385 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4386 		}
4387 		break;
4388 	}
4389 
4390 	case DIF_SUBR_COPYOUTSTR: {
4391 		uintptr_t kaddr = tupregs[0].dttk_value;
4392 		uintptr_t uaddr = tupregs[1].dttk_value;
4393 		uint64_t size = tupregs[2].dttk_value;
4394 		size_t lim;
4395 
4396 		if (!dtrace_destructive_disallow &&
4397 		    dtrace_priv_proc_control(state, mstate) &&
4398 		    !dtrace_istoxic(kaddr, size) &&
4399 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4400 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4401 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4402 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4403 		}
4404 		break;
4405 	}
4406 
4407 	case DIF_SUBR_STRLEN: {
4408 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4409 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4410 		size_t lim;
4411 
4412 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4413 			regs[rd] = 0;
4414 			break;
4415 		}
4416 		regs[rd] = dtrace_strlen((char *)addr, lim);
4417 
4418 		break;
4419 	}
4420 
4421 	case DIF_SUBR_STRCHR:
4422 	case DIF_SUBR_STRRCHR: {
4423 		/*
4424 		 * We're going to iterate over the string looking for the
4425 		 * specified character.  We will iterate until we have reached
4426 		 * the string length or we have found the character.  If this
4427 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4428 		 * of the specified character instead of the first.
4429 		 */
4430 		uintptr_t addr = tupregs[0].dttk_value;
4431 		uintptr_t addr_limit;
4432 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4433 		size_t lim;
4434 		char c, target = (char)tupregs[1].dttk_value;
4435 
4436 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4437 			regs[rd] = 0;
4438 			break;
4439 		}
4440 		addr_limit = addr + lim;
4441 
4442 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4443 			if ((c = dtrace_load8(addr)) == target) {
4444 				regs[rd] = addr;
4445 
4446 				if (subr == DIF_SUBR_STRCHR)
4447 					break;
4448 			}
4449 			if (c == '\0')
4450 				break;
4451 		}
4452 
4453 		break;
4454 	}
4455 
4456 	case DIF_SUBR_STRSTR:
4457 	case DIF_SUBR_INDEX:
4458 	case DIF_SUBR_RINDEX: {
4459 		/*
4460 		 * We're going to iterate over the string looking for the
4461 		 * specified string.  We will iterate until we have reached
4462 		 * the string length or we have found the string.  (Yes, this
4463 		 * is done in the most naive way possible -- but considering
4464 		 * that the string we're searching for is likely to be
4465 		 * relatively short, the complexity of Rabin-Karp or similar
4466 		 * hardly seems merited.)
4467 		 */
4468 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4469 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4470 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4471 		size_t len = dtrace_strlen(addr, size);
4472 		size_t sublen = dtrace_strlen(substr, size);
4473 		char *limit = addr + len, *orig = addr;
4474 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4475 		int inc = 1;
4476 
4477 		regs[rd] = notfound;
4478 
4479 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4480 			regs[rd] = 0;
4481 			break;
4482 		}
4483 
4484 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4485 		    vstate)) {
4486 			regs[rd] = 0;
4487 			break;
4488 		}
4489 
4490 		/*
4491 		 * strstr() and index()/rindex() have similar semantics if
4492 		 * both strings are the empty string: strstr() returns a
4493 		 * pointer to the (empty) string, and index() and rindex()
4494 		 * both return index 0 (regardless of any position argument).
4495 		 */
4496 		if (sublen == 0 && len == 0) {
4497 			if (subr == DIF_SUBR_STRSTR)
4498 				regs[rd] = (uintptr_t)addr;
4499 			else
4500 				regs[rd] = 0;
4501 			break;
4502 		}
4503 
4504 		if (subr != DIF_SUBR_STRSTR) {
4505 			if (subr == DIF_SUBR_RINDEX) {
4506 				limit = orig - 1;
4507 				addr += len;
4508 				inc = -1;
4509 			}
4510 
4511 			/*
4512 			 * Both index() and rindex() take an optional position
4513 			 * argument that denotes the starting position.
4514 			 */
4515 			if (nargs == 3) {
4516 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4517 
4518 				/*
4519 				 * If the position argument to index() is
4520 				 * negative, Perl implicitly clamps it at
4521 				 * zero.  This semantic is a little surprising
4522 				 * given the special meaning of negative
4523 				 * positions to similar Perl functions like
4524 				 * substr(), but it appears to reflect a
4525 				 * notion that index() can start from a
4526 				 * negative index and increment its way up to
4527 				 * the string.  Given this notion, Perl's
4528 				 * rindex() is at least self-consistent in
4529 				 * that it implicitly clamps positions greater
4530 				 * than the string length to be the string
4531 				 * length.  Where Perl completely loses
4532 				 * coherence, however, is when the specified
4533 				 * substring is the empty string ("").  In
4534 				 * this case, even if the position is
4535 				 * negative, rindex() returns 0 -- and even if
4536 				 * the position is greater than the length,
4537 				 * index() returns the string length.  These
4538 				 * semantics violate the notion that index()
4539 				 * should never return a value less than the
4540 				 * specified position and that rindex() should
4541 				 * never return a value greater than the
4542 				 * specified position.  (One assumes that
4543 				 * these semantics are artifacts of Perl's
4544 				 * implementation and not the results of
4545 				 * deliberate design -- it beggars belief that
4546 				 * even Larry Wall could desire such oddness.)
4547 				 * While in the abstract one would wish for
4548 				 * consistent position semantics across
4549 				 * substr(), index() and rindex() -- or at the
4550 				 * very least self-consistent position
4551 				 * semantics for index() and rindex() -- we
4552 				 * instead opt to keep with the extant Perl
4553 				 * semantics, in all their broken glory.  (Do
4554 				 * we have more desire to maintain Perl's
4555 				 * semantics than Perl does?  Probably.)
4556 				 */
4557 				if (subr == DIF_SUBR_RINDEX) {
4558 					if (pos < 0) {
4559 						if (sublen == 0)
4560 							regs[rd] = 0;
4561 						break;
4562 					}
4563 
4564 					if (pos > len)
4565 						pos = len;
4566 				} else {
4567 					if (pos < 0)
4568 						pos = 0;
4569 
4570 					if (pos >= len) {
4571 						if (sublen == 0)
4572 							regs[rd] = len;
4573 						break;
4574 					}
4575 				}
4576 
4577 				addr = orig + pos;
4578 			}
4579 		}
4580 
4581 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4582 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4583 				if (subr != DIF_SUBR_STRSTR) {
4584 					/*
4585 					 * As D index() and rindex() are
4586 					 * modeled on Perl (and not on awk),
4587 					 * we return a zero-based (and not a
4588 					 * one-based) index.  (For you Perl
4589 					 * weenies: no, we're not going to add
4590 					 * $[ -- and shouldn't you be at a con
4591 					 * or something?)
4592 					 */
4593 					regs[rd] = (uintptr_t)(addr - orig);
4594 					break;
4595 				}
4596 
4597 				ASSERT(subr == DIF_SUBR_STRSTR);
4598 				regs[rd] = (uintptr_t)addr;
4599 				break;
4600 			}
4601 		}
4602 
4603 		break;
4604 	}
4605 
4606 	case DIF_SUBR_STRTOK: {
4607 		uintptr_t addr = tupregs[0].dttk_value;
4608 		uintptr_t tokaddr = tupregs[1].dttk_value;
4609 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4610 		uintptr_t limit, toklimit;
4611 		size_t clim;
4612 		uint8_t c, tokmap[32];	 /* 256 / 8 */
4613 		char *dest = (char *)mstate->dtms_scratch_ptr;
4614 		int i;
4615 
4616 		/*
4617 		 * Check both the token buffer and (later) the input buffer,
4618 		 * since both could be non-scratch addresses.
4619 		 */
4620 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4621 			regs[rd] = 0;
4622 			break;
4623 		}
4624 		toklimit = tokaddr + clim;
4625 
4626 		if (!DTRACE_INSCRATCH(mstate, size)) {
4627 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4628 			regs[rd] = 0;
4629 			break;
4630 		}
4631 
4632 		if (addr == 0) {
4633 			/*
4634 			 * If the address specified is NULL, we use our saved
4635 			 * strtok pointer from the mstate.  Note that this
4636 			 * means that the saved strtok pointer is _only_
4637 			 * valid within multiple enablings of the same probe --
4638 			 * it behaves like an implicit clause-local variable.
4639 			 */
4640 			addr = mstate->dtms_strtok;
4641 			limit = mstate->dtms_strtok_limit;
4642 		} else {
4643 			/*
4644 			 * If the user-specified address is non-NULL we must
4645 			 * access check it.  This is the only time we have
4646 			 * a chance to do so, since this address may reside
4647 			 * in the string table of this clause-- future calls
4648 			 * (when we fetch addr from mstate->dtms_strtok)
4649 			 * would fail this access check.
4650 			 */
4651 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4652 			    vstate)) {
4653 				regs[rd] = 0;
4654 				break;
4655 			}
4656 			limit = addr + clim;
4657 		}
4658 
4659 		/*
4660 		 * First, zero the token map, and then process the token
4661 		 * string -- setting a bit in the map for every character
4662 		 * found in the token string.
4663 		 */
4664 		for (i = 0; i < sizeof (tokmap); i++)
4665 			tokmap[i] = 0;
4666 
4667 		for (; tokaddr < toklimit; tokaddr++) {
4668 			if ((c = dtrace_load8(tokaddr)) == '\0')
4669 				break;
4670 
4671 			ASSERT((c >> 3) < sizeof (tokmap));
4672 			tokmap[c >> 3] |= (1 << (c & 0x7));
4673 		}
4674 
4675 		for (; addr < limit; addr++) {
4676 			/*
4677 			 * We're looking for a character that is _not_
4678 			 * contained in the token string.
4679 			 */
4680 			if ((c = dtrace_load8(addr)) == '\0')
4681 				break;
4682 
4683 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4684 				break;
4685 		}
4686 
4687 		if (c == '\0') {
4688 			/*
4689 			 * We reached the end of the string without finding
4690 			 * any character that was not in the token string.
4691 			 * We return NULL in this case, and we set the saved
4692 			 * address to NULL as well.
4693 			 */
4694 			regs[rd] = 0;
4695 			mstate->dtms_strtok = 0;
4696 			mstate->dtms_strtok_limit = 0;
4697 			break;
4698 		}
4699 
4700 		/*
4701 		 * From here on, we're copying into the destination string.
4702 		 */
4703 		for (i = 0; addr < limit && i < size - 1; addr++) {
4704 			if ((c = dtrace_load8(addr)) == '\0')
4705 				break;
4706 
4707 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4708 				break;
4709 
4710 			ASSERT(i < size);
4711 			dest[i++] = c;
4712 		}
4713 
4714 		ASSERT(i < size);
4715 		dest[i] = '\0';
4716 		regs[rd] = (uintptr_t)dest;
4717 		mstate->dtms_scratch_ptr += size;
4718 		mstate->dtms_strtok = addr;
4719 		mstate->dtms_strtok_limit = limit;
4720 		break;
4721 	}
4722 
4723 	case DIF_SUBR_SUBSTR: {
4724 		uintptr_t s = tupregs[0].dttk_value;
4725 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4726 		char *d = (char *)mstate->dtms_scratch_ptr;
4727 		int64_t index = (int64_t)tupregs[1].dttk_value;
4728 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4729 		size_t len = dtrace_strlen((char *)s, size);
4730 		int64_t i;
4731 
4732 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4733 			regs[rd] = 0;
4734 			break;
4735 		}
4736 
4737 		if (!DTRACE_INSCRATCH(mstate, size)) {
4738 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4739 			regs[rd] = 0;
4740 			break;
4741 		}
4742 
4743 		if (nargs <= 2)
4744 			remaining = (int64_t)size;
4745 
4746 		if (index < 0) {
4747 			index += len;
4748 
4749 			if (index < 0 && index + remaining > 0) {
4750 				remaining += index;
4751 				index = 0;
4752 			}
4753 		}
4754 
4755 		if (index >= len || index < 0) {
4756 			remaining = 0;
4757 		} else if (remaining < 0) {
4758 			remaining += len - index;
4759 		} else if (index + remaining > size) {
4760 			remaining = size - index;
4761 		}
4762 
4763 		for (i = 0; i < remaining; i++) {
4764 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4765 				break;
4766 		}
4767 
4768 		d[i] = '\0';
4769 
4770 		mstate->dtms_scratch_ptr += size;
4771 		regs[rd] = (uintptr_t)d;
4772 		break;
4773 	}
4774 
4775 	case DIF_SUBR_JSON: {
4776 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4777 		uintptr_t json = tupregs[0].dttk_value;
4778 		size_t jsonlen = dtrace_strlen((char *)json, size);
4779 		uintptr_t elem = tupregs[1].dttk_value;
4780 		size_t elemlen = dtrace_strlen((char *)elem, size);
4781 
4782 		char *dest = (char *)mstate->dtms_scratch_ptr;
4783 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4784 		char *ee = elemlist;
4785 		int nelems = 1;
4786 		uintptr_t cur;
4787 
4788 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4789 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4790 			regs[rd] = 0;
4791 			break;
4792 		}
4793 
4794 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4795 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4796 			regs[rd] = 0;
4797 			break;
4798 		}
4799 
4800 		/*
4801 		 * Read the element selector and split it up into a packed list
4802 		 * of strings.
4803 		 */
4804 		for (cur = elem; cur < elem + elemlen; cur++) {
4805 			char cc = dtrace_load8(cur);
4806 
4807 			if (cur == elem && cc == '[') {
4808 				/*
4809 				 * If the first element selector key is
4810 				 * actually an array index then ignore the
4811 				 * bracket.
4812 				 */
4813 				continue;
4814 			}
4815 
4816 			if (cc == ']')
4817 				continue;
4818 
4819 			if (cc == '.' || cc == '[') {
4820 				nelems++;
4821 				cc = '\0';
4822 			}
4823 
4824 			*ee++ = cc;
4825 		}
4826 		*ee++ = '\0';
4827 
4828 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4829 		    nelems, dest)) != 0)
4830 			mstate->dtms_scratch_ptr += jsonlen + 1;
4831 		break;
4832 	}
4833 
4834 	case DIF_SUBR_TOUPPER:
4835 	case DIF_SUBR_TOLOWER: {
4836 		uintptr_t s = tupregs[0].dttk_value;
4837 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4838 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4839 		size_t len = dtrace_strlen((char *)s, size);
4840 		char lower, upper, convert;
4841 		int64_t i;
4842 
4843 		if (subr == DIF_SUBR_TOUPPER) {
4844 			lower = 'a';
4845 			upper = 'z';
4846 			convert = 'A';
4847 		} else {
4848 			lower = 'A';
4849 			upper = 'Z';
4850 			convert = 'a';
4851 		}
4852 
4853 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4854 			regs[rd] = 0;
4855 			break;
4856 		}
4857 
4858 		if (!DTRACE_INSCRATCH(mstate, size)) {
4859 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4860 			regs[rd] = 0;
4861 			break;
4862 		}
4863 
4864 		for (i = 0; i < size - 1; i++) {
4865 			if ((c = dtrace_load8(s + i)) == '\0')
4866 				break;
4867 
4868 			if (c >= lower && c <= upper)
4869 				c = convert + (c - lower);
4870 
4871 			dest[i] = c;
4872 		}
4873 
4874 		ASSERT(i < size);
4875 		dest[i] = '\0';
4876 		regs[rd] = (uintptr_t)dest;
4877 		mstate->dtms_scratch_ptr += size;
4878 		break;
4879 	}
4880 
4881 case DIF_SUBR_GETMAJOR:
4882 #ifdef _LP64
4883 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4884 #else
4885 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4886 #endif
4887 		break;
4888 
4889 	case DIF_SUBR_GETMINOR:
4890 #ifdef _LP64
4891 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4892 #else
4893 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4894 #endif
4895 		break;
4896 
4897 	case DIF_SUBR_DDI_PATHNAME: {
4898 		/*
4899 		 * This one is a galactic mess.  We are going to roughly
4900 		 * emulate ddi_pathname(), but it's made more complicated
4901 		 * by the fact that we (a) want to include the minor name and
4902 		 * (b) must proceed iteratively instead of recursively.
4903 		 */
4904 		uintptr_t dest = mstate->dtms_scratch_ptr;
4905 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4906 		char *start = (char *)dest, *end = start + size - 1;
4907 		uintptr_t daddr = tupregs[0].dttk_value;
4908 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4909 		char *s;
4910 		int i, len, depth = 0;
4911 
4912 		/*
4913 		 * Due to all the pointer jumping we do and context we must
4914 		 * rely upon, we just mandate that the user must have kernel
4915 		 * read privileges to use this routine.
4916 		 */
4917 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4918 			*flags |= CPU_DTRACE_KPRIV;
4919 			*illval = daddr;
4920 			regs[rd] = 0;
4921 		}
4922 
4923 		if (!DTRACE_INSCRATCH(mstate, size)) {
4924 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4925 			regs[rd] = 0;
4926 			break;
4927 		}
4928 
4929 		*end = '\0';
4930 
4931 		/*
4932 		 * We want to have a name for the minor.  In order to do this,
4933 		 * we need to walk the minor list from the devinfo.  We want
4934 		 * to be sure that we don't infinitely walk a circular list,
4935 		 * so we check for circularity by sending a scout pointer
4936 		 * ahead two elements for every element that we iterate over;
4937 		 * if the list is circular, these will ultimately point to the
4938 		 * same element.  You may recognize this little trick as the
4939 		 * answer to a stupid interview question -- one that always
4940 		 * seems to be asked by those who had to have it laboriously
4941 		 * explained to them, and who can't even concisely describe
4942 		 * the conditions under which one would be forced to resort to
4943 		 * this technique.  Needless to say, those conditions are
4944 		 * found here -- and probably only here.  Is this the only use
4945 		 * of this infamous trick in shipping, production code?  If it
4946 		 * isn't, it probably should be...
4947 		 */
4948 		if (minor != -1) {
4949 			uintptr_t maddr = dtrace_loadptr(daddr +
4950 			    offsetof(struct dev_info, devi_minor));
4951 
4952 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4953 			uintptr_t name = offsetof(struct ddi_minor_data,
4954 			    d_minor) + offsetof(struct ddi_minor, name);
4955 			uintptr_t dev = offsetof(struct ddi_minor_data,
4956 			    d_minor) + offsetof(struct ddi_minor, dev);
4957 			uintptr_t scout;
4958 
4959 			if (maddr != 0)
4960 				scout = dtrace_loadptr(maddr + next);
4961 
4962 			while (maddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4963 				uint64_t m;
4964 #ifdef _LP64
4965 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4966 #else
4967 				m = dtrace_load32(maddr + dev) & MAXMIN;
4968 #endif
4969 				if (m != minor) {
4970 					maddr = dtrace_loadptr(maddr + next);
4971 
4972 					if (scout == 0)
4973 						continue;
4974 
4975 					scout = dtrace_loadptr(scout + next);
4976 
4977 					if (scout == 0)
4978 						continue;
4979 
4980 					scout = dtrace_loadptr(scout + next);
4981 
4982 					if (scout == 0)
4983 						continue;
4984 
4985 					if (scout == maddr) {
4986 						*flags |= CPU_DTRACE_ILLOP;
4987 						break;
4988 					}
4989 
4990 					continue;
4991 				}
4992 
4993 				/*
4994 				 * We have the minor data.  Now we need to
4995 				 * copy the minor's name into the end of the
4996 				 * pathname.
4997 				 */
4998 				s = (char *)dtrace_loadptr(maddr + name);
4999 				len = dtrace_strlen(s, size);
5000 
5001 				if (*flags & CPU_DTRACE_FAULT)
5002 					break;
5003 
5004 				if (len != 0) {
5005 					if ((end -= (len + 1)) < start)
5006 						break;
5007 
5008 					*end = ':';
5009 				}
5010 
5011 				for (i = 1; i <= len; i++)
5012 					end[i] = dtrace_load8((uintptr_t)s++);
5013 				break;
5014 			}
5015 		}
5016 
5017 		while (daddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
5018 			ddi_node_state_t devi_state;
5019 
5020 			devi_state = dtrace_load32(daddr +
5021 			    offsetof(struct dev_info, devi_node_state));
5022 
5023 			if (*flags & CPU_DTRACE_FAULT)
5024 				break;
5025 
5026 			if (devi_state >= DS_INITIALIZED) {
5027 				s = (char *)dtrace_loadptr(daddr +
5028 				    offsetof(struct dev_info, devi_addr));
5029 				len = dtrace_strlen(s, size);
5030 
5031 				if (*flags & CPU_DTRACE_FAULT)
5032 					break;
5033 
5034 				if (len != 0) {
5035 					if ((end -= (len + 1)) < start)
5036 						break;
5037 
5038 					*end = '@';
5039 				}
5040 
5041 				for (i = 1; i <= len; i++)
5042 					end[i] = dtrace_load8((uintptr_t)s++);
5043 			}
5044 
5045 			/*
5046 			 * Now for the node name...
5047 			 */
5048 			s = (char *)dtrace_loadptr(daddr +
5049 			    offsetof(struct dev_info, devi_node_name));
5050 
5051 			daddr = dtrace_loadptr(daddr +
5052 			    offsetof(struct dev_info, devi_parent));
5053 
5054 			/*
5055 			 * If our parent is NULL (that is, if we're the root
5056 			 * node), we're going to use the special path
5057 			 * "devices".
5058 			 */
5059 			if (daddr == 0)
5060 				s = "devices";
5061 
5062 			len = dtrace_strlen(s, size);
5063 			if (*flags & CPU_DTRACE_FAULT)
5064 				break;
5065 
5066 			if ((end -= (len + 1)) < start)
5067 				break;
5068 
5069 			for (i = 1; i <= len; i++)
5070 				end[i] = dtrace_load8((uintptr_t)s++);
5071 			*end = '/';
5072 
5073 			if (depth++ > dtrace_devdepth_max) {
5074 				*flags |= CPU_DTRACE_ILLOP;
5075 				break;
5076 			}
5077 		}
5078 
5079 		if (end < start)
5080 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5081 
5082 		if (daddr == 0) {
5083 			regs[rd] = (uintptr_t)end;
5084 			mstate->dtms_scratch_ptr += size;
5085 		}
5086 
5087 		break;
5088 	}
5089 
5090 	case DIF_SUBR_STRJOIN: {
5091 		char *d = (char *)mstate->dtms_scratch_ptr;
5092 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5093 		uintptr_t s1 = tupregs[0].dttk_value;
5094 		uintptr_t s2 = tupregs[1].dttk_value;
5095 		int i = 0, j = 0;
5096 		size_t lim1, lim2;
5097 		char c;
5098 
5099 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5100 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5101 			regs[rd] = 0;
5102 			break;
5103 		}
5104 
5105 		if (!DTRACE_INSCRATCH(mstate, size)) {
5106 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5107 			regs[rd] = 0;
5108 			break;
5109 		}
5110 
5111 		for (;;) {
5112 			if (i >= size) {
5113 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5114 				regs[rd] = 0;
5115 				break;
5116 			}
5117 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5118 			if ((d[i++] = c) == '\0') {
5119 				i--;
5120 				break;
5121 			}
5122 		}
5123 
5124 		for (;;) {
5125 			if (i >= size) {
5126 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5127 				regs[rd] = 0;
5128 				break;
5129 			}
5130 
5131 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5132 			if ((d[i++] = c) == '\0')
5133 				break;
5134 		}
5135 
5136 		if (i < size) {
5137 			mstate->dtms_scratch_ptr += i;
5138 			regs[rd] = (uintptr_t)d;
5139 		}
5140 
5141 		break;
5142 	}
5143 
5144 	case DIF_SUBR_STRTOLL: {
5145 		uintptr_t s = tupregs[0].dttk_value;
5146 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5147 		size_t lim;
5148 		int base = 10;
5149 
5150 		if (nargs > 1) {
5151 			if ((base = tupregs[1].dttk_value) <= 1 ||
5152 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5153 				*flags |= CPU_DTRACE_ILLOP;
5154 				break;
5155 			}
5156 		}
5157 
5158 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5159 			regs[rd] = INT64_MIN;
5160 			break;
5161 		}
5162 
5163 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5164 		break;
5165 	}
5166 
5167 	case DIF_SUBR_LLTOSTR: {
5168 		int64_t i = (int64_t)tupregs[0].dttk_value;
5169 		uint64_t val, digit;
5170 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5171 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5172 		int base = 10;
5173 
5174 		if (nargs > 1) {
5175 			if ((base = tupregs[1].dttk_value) <= 1 ||
5176 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5177 				*flags |= CPU_DTRACE_ILLOP;
5178 				break;
5179 			}
5180 		}
5181 
5182 		val = (base == 10 && i < 0) ? i * -1 : i;
5183 
5184 		if (!DTRACE_INSCRATCH(mstate, size)) {
5185 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5186 			regs[rd] = 0;
5187 			break;
5188 		}
5189 
5190 		for (*end-- = '\0'; val; val /= base) {
5191 			if ((digit = val % base) <= '9' - '0') {
5192 				*end-- = '0' + digit;
5193 			} else {
5194 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5195 			}
5196 		}
5197 
5198 		if (i == 0 && base == 16)
5199 			*end-- = '0';
5200 
5201 		if (base == 16)
5202 			*end-- = 'x';
5203 
5204 		if (i == 0 || base == 8 || base == 16)
5205 			*end-- = '0';
5206 
5207 		if (i < 0 && base == 10)
5208 			*end-- = '-';
5209 
5210 		regs[rd] = (uintptr_t)end + 1;
5211 		mstate->dtms_scratch_ptr += size;
5212 		break;
5213 	}
5214 
5215 	case DIF_SUBR_HTONS:
5216 	case DIF_SUBR_NTOHS:
5217 #ifdef _BIG_ENDIAN
5218 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5219 #else
5220 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5221 #endif
5222 		break;
5223 
5224 
5225 	case DIF_SUBR_HTONL:
5226 	case DIF_SUBR_NTOHL:
5227 #ifdef _BIG_ENDIAN
5228 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5229 #else
5230 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5231 #endif
5232 		break;
5233 
5234 
5235 	case DIF_SUBR_HTONLL:
5236 	case DIF_SUBR_NTOHLL:
5237 #ifdef _BIG_ENDIAN
5238 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5239 #else
5240 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5241 #endif
5242 		break;
5243 
5244 
5245 	case DIF_SUBR_DIRNAME:
5246 	case DIF_SUBR_BASENAME: {
5247 		char *dest = (char *)mstate->dtms_scratch_ptr;
5248 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5249 		uintptr_t src = tupregs[0].dttk_value;
5250 		int i, j, len = dtrace_strlen((char *)src, size);
5251 		int lastbase = -1, firstbase = -1, lastdir = -1;
5252 		int start, end;
5253 
5254 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5255 			regs[rd] = 0;
5256 			break;
5257 		}
5258 
5259 		if (!DTRACE_INSCRATCH(mstate, size)) {
5260 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5261 			regs[rd] = 0;
5262 			break;
5263 		}
5264 
5265 		/*
5266 		 * The basename and dirname for a zero-length string is
5267 		 * defined to be "."
5268 		 */
5269 		if (len == 0) {
5270 			len = 1;
5271 			src = (uintptr_t)".";
5272 		}
5273 
5274 		/*
5275 		 * Start from the back of the string, moving back toward the
5276 		 * front until we see a character that isn't a slash.  That
5277 		 * character is the last character in the basename.
5278 		 */
5279 		for (i = len - 1; i >= 0; i--) {
5280 			if (dtrace_load8(src + i) != '/')
5281 				break;
5282 		}
5283 
5284 		if (i >= 0)
5285 			lastbase = i;
5286 
5287 		/*
5288 		 * Starting from the last character in the basename, move
5289 		 * towards the front until we find a slash.  The character
5290 		 * that we processed immediately before that is the first
5291 		 * character in the basename.
5292 		 */
5293 		for (; i >= 0; i--) {
5294 			if (dtrace_load8(src + i) == '/')
5295 				break;
5296 		}
5297 
5298 		if (i >= 0)
5299 			firstbase = i + 1;
5300 
5301 		/*
5302 		 * Now keep going until we find a non-slash character.  That
5303 		 * character is the last character in the dirname.
5304 		 */
5305 		for (; i >= 0; i--) {
5306 			if (dtrace_load8(src + i) != '/')
5307 				break;
5308 		}
5309 
5310 		if (i >= 0)
5311 			lastdir = i;
5312 
5313 		ASSERT(!(lastbase == -1 && firstbase != -1));
5314 		ASSERT(!(firstbase == -1 && lastdir != -1));
5315 
5316 		if (lastbase == -1) {
5317 			/*
5318 			 * We didn't find a non-slash character.  We know that
5319 			 * the length is non-zero, so the whole string must be
5320 			 * slashes.  In either the dirname or the basename
5321 			 * case, we return '/'.
5322 			 */
5323 			ASSERT(firstbase == -1);
5324 			firstbase = lastbase = lastdir = 0;
5325 		}
5326 
5327 		if (firstbase == -1) {
5328 			/*
5329 			 * The entire string consists only of a basename
5330 			 * component.  If we're looking for dirname, we need
5331 			 * to change our string to be just "."; if we're
5332 			 * looking for a basename, we'll just set the first
5333 			 * character of the basename to be 0.
5334 			 */
5335 			if (subr == DIF_SUBR_DIRNAME) {
5336 				ASSERT(lastdir == -1);
5337 				src = (uintptr_t)".";
5338 				lastdir = 0;
5339 			} else {
5340 				firstbase = 0;
5341 			}
5342 		}
5343 
5344 		if (subr == DIF_SUBR_DIRNAME) {
5345 			if (lastdir == -1) {
5346 				/*
5347 				 * We know that we have a slash in the name --
5348 				 * or lastdir would be set to 0, above.  And
5349 				 * because lastdir is -1, we know that this
5350 				 * slash must be the first character.  (That
5351 				 * is, the full string must be of the form
5352 				 * "/basename".)  In this case, the last
5353 				 * character of the directory name is 0.
5354 				 */
5355 				lastdir = 0;
5356 			}
5357 
5358 			start = 0;
5359 			end = lastdir;
5360 		} else {
5361 			ASSERT(subr == DIF_SUBR_BASENAME);
5362 			ASSERT(firstbase != -1 && lastbase != -1);
5363 			start = firstbase;
5364 			end = lastbase;
5365 		}
5366 
5367 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5368 			dest[j] = dtrace_load8(src + i);
5369 
5370 		dest[j] = '\0';
5371 		regs[rd] = (uintptr_t)dest;
5372 		mstate->dtms_scratch_ptr += size;
5373 		break;
5374 	}
5375 
5376 	case DIF_SUBR_GETF: {
5377 		uintptr_t fd = tupregs[0].dttk_value;
5378 		uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5379 		file_t *fp;
5380 
5381 		if (!dtrace_priv_proc(state, mstate)) {
5382 			regs[rd] = 0;
5383 			break;
5384 		}
5385 
5386 		/*
5387 		 * This is safe because fi_nfiles only increases, and the
5388 		 * fi_list array is not freed when the array size doubles.
5389 		 * (See the comment in flist_grow() for details on the
5390 		 * management of the u_finfo structure.)
5391 		 */
5392 		fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5393 
5394 		mstate->dtms_getf = fp;
5395 		regs[rd] = (uintptr_t)fp;
5396 		break;
5397 	}
5398 
5399 	case DIF_SUBR_CLEANPATH: {
5400 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5401 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5402 		uintptr_t src = tupregs[0].dttk_value;
5403 		size_t lim;
5404 		int i = 0, j = 0;
5405 		zone_t *z;
5406 
5407 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5408 			regs[rd] = 0;
5409 			break;
5410 		}
5411 
5412 		if (!DTRACE_INSCRATCH(mstate, size)) {
5413 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5414 			regs[rd] = 0;
5415 			break;
5416 		}
5417 
5418 		/*
5419 		 * Move forward, loading each character.
5420 		 */
5421 		do {
5422 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5423 next:
5424 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5425 				break;
5426 
5427 			if (c != '/') {
5428 				dest[j++] = c;
5429 				continue;
5430 			}
5431 
5432 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5433 
5434 			if (c == '/') {
5435 				/*
5436 				 * We have two slashes -- we can just advance
5437 				 * to the next character.
5438 				 */
5439 				goto next;
5440 			}
5441 
5442 			if (c != '.') {
5443 				/*
5444 				 * This is not "." and it's not ".." -- we can
5445 				 * just store the "/" and this character and
5446 				 * drive on.
5447 				 */
5448 				dest[j++] = '/';
5449 				dest[j++] = c;
5450 				continue;
5451 			}
5452 
5453 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5454 
5455 			if (c == '/') {
5456 				/*
5457 				 * This is a "/./" component.  We're not going
5458 				 * to store anything in the destination buffer;
5459 				 * we're just going to go to the next component.
5460 				 */
5461 				goto next;
5462 			}
5463 
5464 			if (c != '.') {
5465 				/*
5466 				 * This is not ".." -- we can just store the
5467 				 * "/." and this character and continue
5468 				 * processing.
5469 				 */
5470 				dest[j++] = '/';
5471 				dest[j++] = '.';
5472 				dest[j++] = c;
5473 				continue;
5474 			}
5475 
5476 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5477 
5478 			if (c != '/' && c != '\0') {
5479 				/*
5480 				 * This is not ".." -- it's "..[mumble]".
5481 				 * We'll store the "/.." and this character
5482 				 * and continue processing.
5483 				 */
5484 				dest[j++] = '/';
5485 				dest[j++] = '.';
5486 				dest[j++] = '.';
5487 				dest[j++] = c;
5488 				continue;
5489 			}
5490 
5491 			/*
5492 			 * This is "/../" or "/..\0".  We need to back up
5493 			 * our destination pointer until we find a "/".
5494 			 */
5495 			i--;
5496 			while (j != 0 && dest[--j] != '/')
5497 				continue;
5498 
5499 			if (c == '\0')
5500 				dest[++j] = '/';
5501 		} while (c != '\0');
5502 
5503 		dest[j] = '\0';
5504 
5505 		if (mstate->dtms_getf != NULL &&
5506 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5507 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5508 			/*
5509 			 * If we've done a getf() as a part of this ECB and we
5510 			 * don't have kernel access (and we're not in the global
5511 			 * zone), check if the path we cleaned up begins with
5512 			 * the zone's root path, and trim it off if so.  Note
5513 			 * that this is an output cleanliness issue, not a
5514 			 * security issue: knowing one's zone root path does
5515 			 * not enable privilege escalation.
5516 			 */
5517 			if (strstr(dest, z->zone_rootpath) == dest)
5518 				dest += strlen(z->zone_rootpath) - 1;
5519 		}
5520 
5521 		regs[rd] = (uintptr_t)dest;
5522 		mstate->dtms_scratch_ptr += size;
5523 		break;
5524 	}
5525 
5526 	case DIF_SUBR_INET_NTOA:
5527 	case DIF_SUBR_INET_NTOA6:
5528 	case DIF_SUBR_INET_NTOP: {
5529 		size_t size;
5530 		int af, argi, i;
5531 		char *base, *end;
5532 
5533 		if (subr == DIF_SUBR_INET_NTOP) {
5534 			af = (int)tupregs[0].dttk_value;
5535 			argi = 1;
5536 		} else {
5537 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5538 			argi = 0;
5539 		}
5540 
5541 		if (af == AF_INET) {
5542 			ipaddr_t ip4;
5543 			uint8_t *ptr8, val;
5544 
5545 			if (!dtrace_canload(tupregs[argi].dttk_value,
5546 			    sizeof (ipaddr_t), mstate, vstate)) {
5547 				regs[rd] = 0;
5548 				break;
5549 			}
5550 
5551 			/*
5552 			 * Safely load the IPv4 address.
5553 			 */
5554 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5555 
5556 			/*
5557 			 * Check an IPv4 string will fit in scratch.
5558 			 */
5559 			size = INET_ADDRSTRLEN;
5560 			if (!DTRACE_INSCRATCH(mstate, size)) {
5561 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5562 				regs[rd] = 0;
5563 				break;
5564 			}
5565 			base = (char *)mstate->dtms_scratch_ptr;
5566 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5567 
5568 			/*
5569 			 * Stringify as a dotted decimal quad.
5570 			 */
5571 			*end-- = '\0';
5572 			ptr8 = (uint8_t *)&ip4;
5573 			for (i = 3; i >= 0; i--) {
5574 				val = ptr8[i];
5575 
5576 				if (val == 0) {
5577 					*end-- = '0';
5578 				} else {
5579 					for (; val; val /= 10) {
5580 						*end-- = '0' + (val % 10);
5581 					}
5582 				}
5583 
5584 				if (i > 0)
5585 					*end-- = '.';
5586 			}
5587 			ASSERT(end + 1 >= base);
5588 
5589 		} else if (af == AF_INET6) {
5590 			struct in6_addr ip6;
5591 			int firstzero, tryzero, numzero, v6end;
5592 			uint16_t val;
5593 			const char digits[] = "0123456789abcdef";
5594 
5595 			/*
5596 			 * Stringify using RFC 1884 convention 2 - 16 bit
5597 			 * hexadecimal values with a zero-run compression.
5598 			 * Lower case hexadecimal digits are used.
5599 			 *	eg, fe80::214:4fff:fe0b:76c8.
5600 			 * The IPv4 embedded form is returned for inet_ntop,
5601 			 * just the IPv4 string is returned for inet_ntoa6.
5602 			 */
5603 
5604 			if (!dtrace_canload(tupregs[argi].dttk_value,
5605 			    sizeof (struct in6_addr), mstate, vstate)) {
5606 				regs[rd] = 0;
5607 				break;
5608 			}
5609 
5610 			/*
5611 			 * Safely load the IPv6 address.
5612 			 */
5613 			dtrace_bcopy(
5614 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5615 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5616 
5617 			/*
5618 			 * Check an IPv6 string will fit in scratch.
5619 			 */
5620 			size = INET6_ADDRSTRLEN;
5621 			if (!DTRACE_INSCRATCH(mstate, size)) {
5622 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5623 				regs[rd] = 0;
5624 				break;
5625 			}
5626 			base = (char *)mstate->dtms_scratch_ptr;
5627 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5628 			*end-- = '\0';
5629 
5630 			/*
5631 			 * Find the longest run of 16 bit zero values
5632 			 * for the single allowed zero compression - "::".
5633 			 */
5634 			firstzero = -1;
5635 			tryzero = -1;
5636 			numzero = 1;
5637 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5638 				if (ip6._S6_un._S6_u8[i] == 0 &&
5639 				    tryzero == -1 && i % 2 == 0) {
5640 					tryzero = i;
5641 					continue;
5642 				}
5643 
5644 				if (tryzero != -1 &&
5645 				    (ip6._S6_un._S6_u8[i] != 0 ||
5646 				    i == sizeof (struct in6_addr) - 1)) {
5647 
5648 					if (i - tryzero <= numzero) {
5649 						tryzero = -1;
5650 						continue;
5651 					}
5652 
5653 					firstzero = tryzero;
5654 					numzero = i - i % 2 - tryzero;
5655 					tryzero = -1;
5656 
5657 					if (ip6._S6_un._S6_u8[i] == 0 &&
5658 					    i == sizeof (struct in6_addr) - 1)
5659 						numzero += 2;
5660 				}
5661 			}
5662 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5663 
5664 			/*
5665 			 * Check for an IPv4 embedded address.
5666 			 */
5667 			v6end = sizeof (struct in6_addr) - 2;
5668 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5669 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5670 				for (i = sizeof (struct in6_addr) - 1;
5671 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5672 					ASSERT(end >= base);
5673 
5674 					val = ip6._S6_un._S6_u8[i];
5675 
5676 					if (val == 0) {
5677 						*end-- = '0';
5678 					} else {
5679 						for (; val; val /= 10) {
5680 							*end-- = '0' + val % 10;
5681 						}
5682 					}
5683 
5684 					if (i > DTRACE_V4MAPPED_OFFSET)
5685 						*end-- = '.';
5686 				}
5687 
5688 				if (subr == DIF_SUBR_INET_NTOA6)
5689 					goto inetout;
5690 
5691 				/*
5692 				 * Set v6end to skip the IPv4 address that
5693 				 * we have already stringified.
5694 				 */
5695 				v6end = 10;
5696 			}
5697 
5698 			/*
5699 			 * Build the IPv6 string by working through the
5700 			 * address in reverse.
5701 			 */
5702 			for (i = v6end; i >= 0; i -= 2) {
5703 				ASSERT(end >= base);
5704 
5705 				if (i == firstzero + numzero - 2) {
5706 					*end-- = ':';
5707 					*end-- = ':';
5708 					i -= numzero - 2;
5709 					continue;
5710 				}
5711 
5712 				if (i < 14 && i != firstzero - 2)
5713 					*end-- = ':';
5714 
5715 				val = (ip6._S6_un._S6_u8[i] << 8) +
5716 				    ip6._S6_un._S6_u8[i + 1];
5717 
5718 				if (val == 0) {
5719 					*end-- = '0';
5720 				} else {
5721 					for (; val; val /= 16) {
5722 						*end-- = digits[val % 16];
5723 					}
5724 				}
5725 			}
5726 			ASSERT(end + 1 >= base);
5727 
5728 		} else {
5729 			/*
5730 			 * The user didn't use AH_INET or AH_INET6.
5731 			 */
5732 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5733 			regs[rd] = 0;
5734 			break;
5735 		}
5736 
5737 inetout:	regs[rd] = (uintptr_t)end + 1;
5738 		mstate->dtms_scratch_ptr += size;
5739 		break;
5740 	}
5741 
5742 	}
5743 }
5744 
5745 /*
5746  * Emulate the execution of DTrace IR instructions specified by the given
5747  * DIF object.  This function is deliberately void of assertions as all of
5748  * the necessary checks are handled by a call to dtrace_difo_validate().
5749  */
5750 static uint64_t
dtrace_dif_emulate(dtrace_difo_t * difo,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,dtrace_state_t * state)5751 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5752     dtrace_vstate_t *vstate, dtrace_state_t *state)
5753 {
5754 	const dif_instr_t *text = difo->dtdo_buf;
5755 	const uint_t textlen = difo->dtdo_len;
5756 	const char *strtab = difo->dtdo_strtab;
5757 	const uint64_t *inttab = difo->dtdo_inttab;
5758 
5759 	uint64_t rval = 0;
5760 	dtrace_statvar_t *svar;
5761 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5762 	dtrace_difv_t *v;
5763 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5764 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5765 
5766 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5767 	uint64_t regs[DIF_DIR_NREGS];
5768 	uint64_t *tmp;
5769 
5770 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5771 	int64_t cc_r;
5772 	uint_t pc = 0, id, opc;
5773 	uint8_t ttop = 0;
5774 	dif_instr_t instr;
5775 	uint_t r1, r2, rd;
5776 
5777 	/*
5778 	 * We stash the current DIF object into the machine state: we need it
5779 	 * for subsequent access checking.
5780 	 */
5781 	mstate->dtms_difo = difo;
5782 
5783 	regs[DIF_REG_R0] = 0;		/* %r0 is fixed at zero */
5784 
5785 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5786 		opc = pc;
5787 
5788 		instr = text[pc++];
5789 		r1 = DIF_INSTR_R1(instr);
5790 		r2 = DIF_INSTR_R2(instr);
5791 		rd = DIF_INSTR_RD(instr);
5792 
5793 		switch (DIF_INSTR_OP(instr)) {
5794 		case DIF_OP_OR:
5795 			regs[rd] = regs[r1] | regs[r2];
5796 			break;
5797 		case DIF_OP_XOR:
5798 			regs[rd] = regs[r1] ^ regs[r2];
5799 			break;
5800 		case DIF_OP_AND:
5801 			regs[rd] = regs[r1] & regs[r2];
5802 			break;
5803 		case DIF_OP_SLL:
5804 			regs[rd] = regs[r1] << regs[r2];
5805 			break;
5806 		case DIF_OP_SRL:
5807 			regs[rd] = regs[r1] >> regs[r2];
5808 			break;
5809 		case DIF_OP_SUB:
5810 			regs[rd] = regs[r1] - regs[r2];
5811 			break;
5812 		case DIF_OP_ADD:
5813 			regs[rd] = regs[r1] + regs[r2];
5814 			break;
5815 		case DIF_OP_MUL:
5816 			regs[rd] = regs[r1] * regs[r2];
5817 			break;
5818 		case DIF_OP_SDIV:
5819 			if (regs[r2] == 0) {
5820 				regs[rd] = 0;
5821 				*flags |= CPU_DTRACE_DIVZERO;
5822 			} else {
5823 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5824 				regs[rd] = (int64_t)regs[r1] /
5825 				    (int64_t)regs[r2];
5826 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5827 			}
5828 			break;
5829 
5830 		case DIF_OP_UDIV:
5831 			if (regs[r2] == 0) {
5832 				regs[rd] = 0;
5833 				*flags |= CPU_DTRACE_DIVZERO;
5834 			} else {
5835 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5836 				regs[rd] = regs[r1] / regs[r2];
5837 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5838 			}
5839 			break;
5840 
5841 		case DIF_OP_SREM:
5842 			if (regs[r2] == 0) {
5843 				regs[rd] = 0;
5844 				*flags |= CPU_DTRACE_DIVZERO;
5845 			} else {
5846 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5847 				regs[rd] = (int64_t)regs[r1] %
5848 				    (int64_t)regs[r2];
5849 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5850 			}
5851 			break;
5852 
5853 		case DIF_OP_UREM:
5854 			if (regs[r2] == 0) {
5855 				regs[rd] = 0;
5856 				*flags |= CPU_DTRACE_DIVZERO;
5857 			} else {
5858 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5859 				regs[rd] = regs[r1] % regs[r2];
5860 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5861 			}
5862 			break;
5863 
5864 		case DIF_OP_NOT:
5865 			regs[rd] = ~regs[r1];
5866 			break;
5867 		case DIF_OP_MOV:
5868 			regs[rd] = regs[r1];
5869 			break;
5870 		case DIF_OP_CMP:
5871 			cc_r = regs[r1] - regs[r2];
5872 			cc_n = cc_r < 0;
5873 			cc_z = cc_r == 0;
5874 			cc_v = 0;
5875 			cc_c = regs[r1] < regs[r2];
5876 			break;
5877 		case DIF_OP_TST:
5878 			cc_n = cc_v = cc_c = 0;
5879 			cc_z = regs[r1] == 0;
5880 			break;
5881 		case DIF_OP_BA:
5882 			pc = DIF_INSTR_LABEL(instr);
5883 			break;
5884 		case DIF_OP_BE:
5885 			if (cc_z)
5886 				pc = DIF_INSTR_LABEL(instr);
5887 			break;
5888 		case DIF_OP_BNE:
5889 			if (cc_z == 0)
5890 				pc = DIF_INSTR_LABEL(instr);
5891 			break;
5892 		case DIF_OP_BG:
5893 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5894 				pc = DIF_INSTR_LABEL(instr);
5895 			break;
5896 		case DIF_OP_BGU:
5897 			if ((cc_c | cc_z) == 0)
5898 				pc = DIF_INSTR_LABEL(instr);
5899 			break;
5900 		case DIF_OP_BGE:
5901 			if ((cc_n ^ cc_v) == 0)
5902 				pc = DIF_INSTR_LABEL(instr);
5903 			break;
5904 		case DIF_OP_BGEU:
5905 			if (cc_c == 0)
5906 				pc = DIF_INSTR_LABEL(instr);
5907 			break;
5908 		case DIF_OP_BL:
5909 			if (cc_n ^ cc_v)
5910 				pc = DIF_INSTR_LABEL(instr);
5911 			break;
5912 		case DIF_OP_BLU:
5913 			if (cc_c)
5914 				pc = DIF_INSTR_LABEL(instr);
5915 			break;
5916 		case DIF_OP_BLE:
5917 			if (cc_z | (cc_n ^ cc_v))
5918 				pc = DIF_INSTR_LABEL(instr);
5919 			break;
5920 		case DIF_OP_BLEU:
5921 			if (cc_c | cc_z)
5922 				pc = DIF_INSTR_LABEL(instr);
5923 			break;
5924 		case DIF_OP_RLDSB:
5925 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5926 				break;
5927 			/*FALLTHROUGH*/
5928 		case DIF_OP_LDSB:
5929 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5930 			break;
5931 		case DIF_OP_RLDSH:
5932 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5933 				break;
5934 			/*FALLTHROUGH*/
5935 		case DIF_OP_LDSH:
5936 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5937 			break;
5938 		case DIF_OP_RLDSW:
5939 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5940 				break;
5941 			/*FALLTHROUGH*/
5942 		case DIF_OP_LDSW:
5943 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5944 			break;
5945 		case DIF_OP_RLDUB:
5946 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5947 				break;
5948 			/*FALLTHROUGH*/
5949 		case DIF_OP_LDUB:
5950 			regs[rd] = dtrace_load8(regs[r1]);
5951 			break;
5952 		case DIF_OP_RLDUH:
5953 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5954 				break;
5955 			/*FALLTHROUGH*/
5956 		case DIF_OP_LDUH:
5957 			regs[rd] = dtrace_load16(regs[r1]);
5958 			break;
5959 		case DIF_OP_RLDUW:
5960 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5961 				break;
5962 			/*FALLTHROUGH*/
5963 		case DIF_OP_LDUW:
5964 			regs[rd] = dtrace_load32(regs[r1]);
5965 			break;
5966 		case DIF_OP_RLDX:
5967 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5968 				break;
5969 			/*FALLTHROUGH*/
5970 		case DIF_OP_LDX:
5971 			regs[rd] = dtrace_load64(regs[r1]);
5972 			break;
5973 		case DIF_OP_ULDSB:
5974 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5975 			regs[rd] = (int8_t)
5976 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5977 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5978 			break;
5979 		case DIF_OP_ULDSH:
5980 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5981 			regs[rd] = (int16_t)
5982 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5983 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5984 			break;
5985 		case DIF_OP_ULDSW:
5986 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5987 			regs[rd] = (int32_t)
5988 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5989 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5990 			break;
5991 		case DIF_OP_ULDUB:
5992 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5993 			regs[rd] =
5994 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5995 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5996 			break;
5997 		case DIF_OP_ULDUH:
5998 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5999 			regs[rd] =
6000 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6001 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6002 			break;
6003 		case DIF_OP_ULDUW:
6004 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6005 			regs[rd] =
6006 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6007 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6008 			break;
6009 		case DIF_OP_ULDX:
6010 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6011 			regs[rd] =
6012 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6013 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6014 			break;
6015 		case DIF_OP_RET:
6016 			rval = regs[rd];
6017 			pc = textlen;
6018 			break;
6019 		case DIF_OP_NOP:
6020 			break;
6021 		case DIF_OP_SETX:
6022 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6023 			break;
6024 		case DIF_OP_SETS:
6025 			regs[rd] = (uint64_t)(uintptr_t)
6026 			    (strtab + DIF_INSTR_STRING(instr));
6027 			break;
6028 		case DIF_OP_SCMP: {
6029 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6030 			uintptr_t s1 = regs[r1];
6031 			uintptr_t s2 = regs[r2];
6032 			size_t lim1 = SIZE_MAX, lim2 = SIZE_MAX;
6033 
6034 			if (s1 != 0 &&
6035 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6036 				break;
6037 			if (s2 != 0 &&
6038 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6039 				break;
6040 
6041 			/*
6042 			 * If s1 or s2 is NULL, we will take the limit that
6043 			 * corresponds with the non-NULL string.  If they are
6044 			 * both NULL, we will pass SIZE_MAX as the limit --
6045 			 * but in this case dtrace_strncmp() will return
6046 			 * success without examining the limit.
6047 			 */
6048 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6049 			    MIN(lim1, lim2));
6050 
6051 			cc_n = cc_r < 0;
6052 			cc_z = cc_r == 0;
6053 			cc_v = cc_c = 0;
6054 			break;
6055 		}
6056 		case DIF_OP_LDGA:
6057 			regs[rd] = dtrace_dif_variable(mstate, state,
6058 			    r1, regs[r2]);
6059 			break;
6060 		case DIF_OP_LDGS:
6061 			id = DIF_INSTR_VAR(instr);
6062 
6063 			if (id >= DIF_VAR_OTHER_UBASE) {
6064 				uintptr_t a;
6065 
6066 				id -= DIF_VAR_OTHER_UBASE;
6067 				svar = vstate->dtvs_globals[id];
6068 				ASSERT(svar != NULL);
6069 				v = &svar->dtsv_var;
6070 
6071 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6072 					regs[rd] = svar->dtsv_data;
6073 					break;
6074 				}
6075 
6076 				a = (uintptr_t)svar->dtsv_data;
6077 
6078 				if (*(uint8_t *)a == UINT8_MAX) {
6079 					/*
6080 					 * If the 0th byte is set to UINT8_MAX
6081 					 * then this is to be treated as a
6082 					 * reference to a NULL variable.
6083 					 */
6084 					regs[rd] = 0;
6085 				} else {
6086 					regs[rd] = a + sizeof (uint64_t);
6087 				}
6088 
6089 				break;
6090 			}
6091 
6092 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6093 			break;
6094 
6095 		case DIF_OP_STGA:
6096 			dtrace_dif_variable_write(mstate, state, r1, regs[r2],
6097 			    regs[rd]);
6098 			break;
6099 
6100 		case DIF_OP_STGS:
6101 			id = DIF_INSTR_VAR(instr);
6102 
6103 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6104 			id -= DIF_VAR_OTHER_UBASE;
6105 
6106 			VERIFY(id < vstate->dtvs_nglobals);
6107 			svar = vstate->dtvs_globals[id];
6108 			ASSERT(svar != NULL);
6109 			v = &svar->dtsv_var;
6110 
6111 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6112 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6113 				size_t lim;
6114 
6115 				ASSERT(a != (uintptr_t)NULL);
6116 				ASSERT(svar->dtsv_size != 0);
6117 
6118 				if (regs[rd] == 0) {
6119 					*(uint8_t *)a = UINT8_MAX;
6120 					break;
6121 				} else {
6122 					*(uint8_t *)a = 0;
6123 					a += sizeof (uint64_t);
6124 				}
6125 				if (!dtrace_vcanload(
6126 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6127 				    &lim, mstate, vstate))
6128 					break;
6129 
6130 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6131 				    (void *)a, &v->dtdv_type, lim);
6132 				break;
6133 			}
6134 
6135 			svar->dtsv_data = regs[rd];
6136 			break;
6137 
6138 		case DIF_OP_LDTA:
6139 			/*
6140 			 * There are no DTrace built-in thread-local arrays at
6141 			 * present.  This opcode is saved for future work.
6142 			 */
6143 			*flags |= CPU_DTRACE_ILLOP;
6144 			regs[rd] = 0;
6145 			break;
6146 
6147 		case DIF_OP_LDLS:
6148 			id = DIF_INSTR_VAR(instr);
6149 
6150 			if (id < DIF_VAR_OTHER_UBASE) {
6151 				/*
6152 				 * For now, this has no meaning.
6153 				 */
6154 				regs[rd] = 0;
6155 				break;
6156 			}
6157 
6158 			id -= DIF_VAR_OTHER_UBASE;
6159 
6160 			ASSERT(id < vstate->dtvs_nlocals);
6161 			ASSERT(vstate->dtvs_locals != NULL);
6162 
6163 			svar = vstate->dtvs_locals[id];
6164 			ASSERT(svar != NULL);
6165 			v = &svar->dtsv_var;
6166 
6167 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6168 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6169 				size_t sz = v->dtdv_type.dtdt_size;
6170 
6171 				sz += sizeof (uint64_t);
6172 				ASSERT(svar->dtsv_size == NCPU * sz);
6173 				a += CPU->cpu_id * sz;
6174 
6175 				if (*(uint8_t *)a == UINT8_MAX) {
6176 					/*
6177 					 * If the 0th byte is set to UINT8_MAX
6178 					 * then this is to be treated as a
6179 					 * reference to a NULL variable.
6180 					 */
6181 					regs[rd] = 0;
6182 				} else {
6183 					regs[rd] = a + sizeof (uint64_t);
6184 				}
6185 
6186 				break;
6187 			}
6188 
6189 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6190 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6191 			regs[rd] = tmp[CPU->cpu_id];
6192 			break;
6193 
6194 		case DIF_OP_STLS:
6195 			id = DIF_INSTR_VAR(instr);
6196 
6197 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6198 			id -= DIF_VAR_OTHER_UBASE;
6199 			VERIFY(id < vstate->dtvs_nlocals);
6200 
6201 			ASSERT(vstate->dtvs_locals != NULL);
6202 			svar = vstate->dtvs_locals[id];
6203 			ASSERT(svar != NULL);
6204 			v = &svar->dtsv_var;
6205 
6206 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6207 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6208 				size_t sz = v->dtdv_type.dtdt_size;
6209 				size_t lim;
6210 
6211 				sz += sizeof (uint64_t);
6212 				ASSERT(svar->dtsv_size == NCPU * sz);
6213 				a += CPU->cpu_id * sz;
6214 
6215 				if (regs[rd] == 0) {
6216 					*(uint8_t *)a = UINT8_MAX;
6217 					break;
6218 				} else {
6219 					*(uint8_t *)a = 0;
6220 					a += sizeof (uint64_t);
6221 				}
6222 
6223 				if (!dtrace_vcanload(
6224 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6225 				    &lim, mstate, vstate))
6226 					break;
6227 
6228 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6229 				    (void *)a, &v->dtdv_type, lim);
6230 				break;
6231 			}
6232 
6233 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6234 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6235 			tmp[CPU->cpu_id] = regs[rd];
6236 			break;
6237 
6238 		case DIF_OP_LDTS: {
6239 			dtrace_dynvar_t *dvar;
6240 			dtrace_key_t *key;
6241 
6242 			id = DIF_INSTR_VAR(instr);
6243 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6244 			id -= DIF_VAR_OTHER_UBASE;
6245 			v = &vstate->dtvs_tlocals[id];
6246 
6247 			key = &tupregs[DIF_DTR_NREGS];
6248 			key[0].dttk_value = (uint64_t)id;
6249 			key[0].dttk_size = 0;
6250 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6251 			key[1].dttk_size = 0;
6252 
6253 			dvar = dtrace_dynvar(dstate, 2, key,
6254 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6255 			    mstate, vstate);
6256 
6257 			if (dvar == NULL) {
6258 				regs[rd] = 0;
6259 				break;
6260 			}
6261 
6262 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6263 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6264 			} else {
6265 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6266 			}
6267 
6268 			break;
6269 		}
6270 
6271 		case DIF_OP_STTS: {
6272 			dtrace_dynvar_t *dvar;
6273 			dtrace_key_t *key;
6274 
6275 			id = DIF_INSTR_VAR(instr);
6276 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6277 			id -= DIF_VAR_OTHER_UBASE;
6278 			VERIFY(id < vstate->dtvs_ntlocals);
6279 
6280 			key = &tupregs[DIF_DTR_NREGS];
6281 			key[0].dttk_value = (uint64_t)id;
6282 			key[0].dttk_size = 0;
6283 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6284 			key[1].dttk_size = 0;
6285 			v = &vstate->dtvs_tlocals[id];
6286 
6287 			dvar = dtrace_dynvar(dstate, 2, key,
6288 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6289 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6290 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6291 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6292 
6293 			/*
6294 			 * Given that we're storing to thread-local data,
6295 			 * we need to flush our predicate cache.
6296 			 */
6297 			curthread->t_predcache = DTRACE_CACHEIDNONE;
6298 
6299 			if (dvar == NULL)
6300 				break;
6301 
6302 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6303 				size_t lim;
6304 
6305 				if (!dtrace_vcanload(
6306 				    (void *)(uintptr_t)regs[rd],
6307 				    &v->dtdv_type, &lim, mstate, vstate))
6308 					break;
6309 
6310 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6311 				    dvar->dtdv_data, &v->dtdv_type, lim);
6312 			} else {
6313 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6314 			}
6315 
6316 			break;
6317 		}
6318 
6319 		case DIF_OP_SRA:
6320 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6321 			break;
6322 
6323 		case DIF_OP_CALL:
6324 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6325 			    regs, tupregs, ttop, mstate, state);
6326 			break;
6327 
6328 		case DIF_OP_PUSHTR:
6329 			if (ttop == DIF_DTR_NREGS) {
6330 				*flags |= CPU_DTRACE_TUPOFLOW;
6331 				break;
6332 			}
6333 
6334 			if (r1 == DIF_TYPE_STRING) {
6335 				/*
6336 				 * If this is a string type and the size is 0,
6337 				 * we'll use the system-wide default string
6338 				 * size.  Note that we are _not_ looking at
6339 				 * the value of the DTRACEOPT_STRSIZE option;
6340 				 * had this been set, we would expect to have
6341 				 * a non-zero size value in the "pushtr".
6342 				 */
6343 				tupregs[ttop].dttk_size =
6344 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6345 				    regs[r2] ? regs[r2] :
6346 				    dtrace_strsize_default) + 1;
6347 			} else {
6348 				if (regs[r2] > LONG_MAX) {
6349 					*flags |= CPU_DTRACE_ILLOP;
6350 					break;
6351 				}
6352 
6353 				tupregs[ttop].dttk_size = regs[r2];
6354 			}
6355 
6356 			tupregs[ttop++].dttk_value = regs[rd];
6357 			break;
6358 
6359 		case DIF_OP_PUSHTV:
6360 			if (ttop == DIF_DTR_NREGS) {
6361 				*flags |= CPU_DTRACE_TUPOFLOW;
6362 				break;
6363 			}
6364 
6365 			tupregs[ttop].dttk_value = regs[rd];
6366 			tupregs[ttop++].dttk_size = 0;
6367 			break;
6368 
6369 		case DIF_OP_POPTS:
6370 			if (ttop != 0)
6371 				ttop--;
6372 			break;
6373 
6374 		case DIF_OP_FLUSHTS:
6375 			ttop = 0;
6376 			break;
6377 
6378 		case DIF_OP_LDGAA:
6379 		case DIF_OP_LDTAA: {
6380 			dtrace_dynvar_t *dvar;
6381 			dtrace_key_t *key = tupregs;
6382 			uint_t nkeys = ttop;
6383 
6384 			id = DIF_INSTR_VAR(instr);
6385 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6386 			id -= DIF_VAR_OTHER_UBASE;
6387 
6388 			key[nkeys].dttk_value = (uint64_t)id;
6389 			key[nkeys++].dttk_size = 0;
6390 
6391 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6392 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6393 				key[nkeys++].dttk_size = 0;
6394 				VERIFY(id < vstate->dtvs_ntlocals);
6395 				v = &vstate->dtvs_tlocals[id];
6396 			} else {
6397 				VERIFY(id < vstate->dtvs_nglobals);
6398 				v = &vstate->dtvs_globals[id]->dtsv_var;
6399 			}
6400 
6401 			dvar = dtrace_dynvar(dstate, nkeys, key,
6402 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6403 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6404 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6405 
6406 			if (dvar == NULL) {
6407 				regs[rd] = 0;
6408 				break;
6409 			}
6410 
6411 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6412 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6413 			} else {
6414 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6415 			}
6416 
6417 			break;
6418 		}
6419 
6420 		case DIF_OP_STGAA:
6421 		case DIF_OP_STTAA: {
6422 			dtrace_dynvar_t *dvar;
6423 			dtrace_key_t *key = tupregs;
6424 			uint_t nkeys = ttop;
6425 
6426 			id = DIF_INSTR_VAR(instr);
6427 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6428 			id -= DIF_VAR_OTHER_UBASE;
6429 
6430 			key[nkeys].dttk_value = (uint64_t)id;
6431 			key[nkeys++].dttk_size = 0;
6432 
6433 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6434 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6435 				key[nkeys++].dttk_size = 0;
6436 				VERIFY(id < vstate->dtvs_ntlocals);
6437 				v = &vstate->dtvs_tlocals[id];
6438 			} else {
6439 				VERIFY(id < vstate->dtvs_nglobals);
6440 				v = &vstate->dtvs_globals[id]->dtsv_var;
6441 			}
6442 
6443 			dvar = dtrace_dynvar(dstate, nkeys, key,
6444 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6445 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6446 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6447 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6448 
6449 			if (dvar == NULL)
6450 				break;
6451 
6452 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6453 				size_t lim;
6454 
6455 				if (!dtrace_vcanload(
6456 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6457 				    &lim, mstate, vstate))
6458 					break;
6459 
6460 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6461 				    dvar->dtdv_data, &v->dtdv_type, lim);
6462 			} else {
6463 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6464 			}
6465 
6466 			break;
6467 		}
6468 
6469 		case DIF_OP_ALLOCS: {
6470 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6471 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6472 
6473 			/*
6474 			 * Rounding up the user allocation size could have
6475 			 * overflowed large, bogus allocations (like -1ULL) to
6476 			 * 0.
6477 			 */
6478 			if (size < regs[r1] ||
6479 			    !DTRACE_INSCRATCH(mstate, size)) {
6480 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6481 				regs[rd] = 0;
6482 				break;
6483 			}
6484 
6485 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6486 			mstate->dtms_scratch_ptr += size;
6487 			regs[rd] = ptr;
6488 			break;
6489 		}
6490 
6491 		case DIF_OP_COPYS:
6492 			if (!dtrace_canstore(regs[rd], regs[r2],
6493 			    mstate, vstate)) {
6494 				*flags |= CPU_DTRACE_BADADDR;
6495 				*illval = regs[rd];
6496 				break;
6497 			}
6498 
6499 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6500 				break;
6501 
6502 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6503 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6504 			break;
6505 
6506 		case DIF_OP_STB:
6507 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6508 				*flags |= CPU_DTRACE_BADADDR;
6509 				*illval = regs[rd];
6510 				break;
6511 			}
6512 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6513 			break;
6514 
6515 		case DIF_OP_STH:
6516 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6517 				*flags |= CPU_DTRACE_BADADDR;
6518 				*illval = regs[rd];
6519 				break;
6520 			}
6521 			if (regs[rd] & 1) {
6522 				*flags |= CPU_DTRACE_BADALIGN;
6523 				*illval = regs[rd];
6524 				break;
6525 			}
6526 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6527 			break;
6528 
6529 		case DIF_OP_STW:
6530 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6531 				*flags |= CPU_DTRACE_BADADDR;
6532 				*illval = regs[rd];
6533 				break;
6534 			}
6535 			if (regs[rd] & 3) {
6536 				*flags |= CPU_DTRACE_BADALIGN;
6537 				*illval = regs[rd];
6538 				break;
6539 			}
6540 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6541 			break;
6542 
6543 		case DIF_OP_STX:
6544 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6545 				*flags |= CPU_DTRACE_BADADDR;
6546 				*illval = regs[rd];
6547 				break;
6548 			}
6549 			if (regs[rd] & 7) {
6550 				*flags |= CPU_DTRACE_BADALIGN;
6551 				*illval = regs[rd];
6552 				break;
6553 			}
6554 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6555 			break;
6556 		}
6557 	}
6558 
6559 	if (!(*flags & CPU_DTRACE_FAULT))
6560 		return (rval);
6561 
6562 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6563 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6564 
6565 	return (0);
6566 }
6567 
6568 static void
dtrace_action_breakpoint(dtrace_ecb_t * ecb)6569 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6570 {
6571 	dtrace_probe_t *probe = ecb->dte_probe;
6572 	dtrace_provider_t *prov = probe->dtpr_provider;
6573 	char c[DTRACE_FULLNAMELEN + 80], *str;
6574 	char *msg = "dtrace: breakpoint action at probe ";
6575 	char *ecbmsg = " (ecb ";
6576 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6577 	uintptr_t val = (uintptr_t)ecb;
6578 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6579 
6580 	if (dtrace_destructive_disallow)
6581 		return;
6582 
6583 	/*
6584 	 * It's impossible to be taking action on the NULL probe.
6585 	 */
6586 	ASSERT(probe != NULL);
6587 
6588 	/*
6589 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6590 	 * print the provider name, module name, function name and name of
6591 	 * the probe, along with the hex address of the ECB with the breakpoint
6592 	 * action -- all of which we must place in the character buffer by
6593 	 * hand.
6594 	 */
6595 	while (*msg != '\0')
6596 		c[i++] = *msg++;
6597 
6598 	for (str = prov->dtpv_name; *str != '\0'; str++)
6599 		c[i++] = *str;
6600 	c[i++] = ':';
6601 
6602 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6603 		c[i++] = *str;
6604 	c[i++] = ':';
6605 
6606 	for (str = probe->dtpr_func; *str != '\0'; str++)
6607 		c[i++] = *str;
6608 	c[i++] = ':';
6609 
6610 	for (str = probe->dtpr_name; *str != '\0'; str++)
6611 		c[i++] = *str;
6612 
6613 	while (*ecbmsg != '\0')
6614 		c[i++] = *ecbmsg++;
6615 
6616 	while (shift >= 0) {
6617 		mask = (uintptr_t)0xf << shift;
6618 
6619 		if (val >= ((uintptr_t)1 << shift))
6620 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6621 		shift -= 4;
6622 	}
6623 
6624 	c[i++] = ')';
6625 	c[i] = '\0';
6626 
6627 	debug_enter(c);
6628 }
6629 
6630 static void
dtrace_action_panic(dtrace_ecb_t * ecb)6631 dtrace_action_panic(dtrace_ecb_t *ecb)
6632 {
6633 	dtrace_probe_t *probe = ecb->dte_probe;
6634 
6635 	/*
6636 	 * It's impossible to be taking action on the NULL probe.
6637 	 */
6638 	ASSERT(probe != NULL);
6639 
6640 	if (dtrace_destructive_disallow)
6641 		return;
6642 
6643 	if (dtrace_panicked != NULL)
6644 		return;
6645 
6646 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6647 		return;
6648 
6649 	/*
6650 	 * We won the right to panic.  (We want to be sure that only one
6651 	 * thread calls panic() from dtrace_probe(), and that panic() is
6652 	 * called exactly once.)
6653 	 */
6654 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6655 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6656 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6657 }
6658 
6659 static void
dtrace_action_raise(uint64_t sig)6660 dtrace_action_raise(uint64_t sig)
6661 {
6662 	if (dtrace_destructive_disallow)
6663 		return;
6664 
6665 	if (sig >= NSIG) {
6666 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6667 		return;
6668 	}
6669 
6670 	/*
6671 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6672 	 * invocations of the raise() action.
6673 	 */
6674 	if (curthread->t_dtrace_sig == 0)
6675 		curthread->t_dtrace_sig = (uint8_t)sig;
6676 
6677 	curthread->t_sig_check = 1;
6678 	aston(curthread);
6679 }
6680 
6681 static void
dtrace_action_stop(void)6682 dtrace_action_stop(void)
6683 {
6684 	if (dtrace_destructive_disallow)
6685 		return;
6686 
6687 	if (!curthread->t_dtrace_stop) {
6688 		curthread->t_dtrace_stop = 1;
6689 		curthread->t_sig_check = 1;
6690 		aston(curthread);
6691 	}
6692 }
6693 
6694 static void
dtrace_action_chill(dtrace_mstate_t * mstate,hrtime_t val)6695 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6696 {
6697 	hrtime_t now;
6698 	volatile uint16_t *flags;
6699 	cpu_t *cpu = CPU;
6700 
6701 	if (dtrace_destructive_disallow)
6702 		return;
6703 
6704 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6705 
6706 	now = dtrace_gethrtime();
6707 
6708 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6709 		/*
6710 		 * We need to advance the mark to the current time.
6711 		 */
6712 		cpu->cpu_dtrace_chillmark = now;
6713 		cpu->cpu_dtrace_chilled = 0;
6714 	}
6715 
6716 	/*
6717 	 * Now check to see if the requested chill time would take us over
6718 	 * the maximum amount of time allowed in the chill interval.  (Or
6719 	 * worse, if the calculation itself induces overflow.)
6720 	 */
6721 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6722 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6723 		*flags |= CPU_DTRACE_ILLOP;
6724 		return;
6725 	}
6726 
6727 	while (dtrace_gethrtime() - now < val)
6728 		continue;
6729 
6730 	/*
6731 	 * Normally, we assure that the value of the variable "timestamp" does
6732 	 * not change within an ECB.  The presence of chill() represents an
6733 	 * exception to this rule, however.
6734 	 */
6735 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6736 	cpu->cpu_dtrace_chilled += val;
6737 }
6738 
6739 static void
dtrace_action_ustack(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t * buf,uint64_t arg)6740 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6741     uint64_t *buf, uint64_t arg)
6742 {
6743 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6744 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6745 	uint64_t *pcs = &buf[1], *fps;
6746 	char *str = (char *)&pcs[nframes];
6747 	int size, offs = 0, i, j;
6748 	size_t rem;
6749 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6750 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6751 	char *sym;
6752 
6753 	/*
6754 	 * Should be taking a faster path if string space has not been
6755 	 * allocated.
6756 	 */
6757 	ASSERT(strsize != 0);
6758 
6759 	/*
6760 	 * We will first allocate some temporary space for the frame pointers.
6761 	 */
6762 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6763 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6764 	    (nframes * sizeof (uint64_t));
6765 
6766 	if (!DTRACE_INSCRATCH(mstate, size)) {
6767 		/*
6768 		 * Not enough room for our frame pointers -- need to indicate
6769 		 * that we ran out of scratch space.
6770 		 */
6771 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6772 		return;
6773 	}
6774 
6775 	mstate->dtms_scratch_ptr += size;
6776 	saved = mstate->dtms_scratch_ptr;
6777 
6778 	/*
6779 	 * Now get a stack with both program counters and frame pointers.
6780 	 */
6781 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6782 	dtrace_getufpstack(buf, fps, nframes + 1);
6783 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6784 
6785 	/*
6786 	 * If that faulted, we're cooked.
6787 	 */
6788 	if (*flags & CPU_DTRACE_FAULT)
6789 		goto out;
6790 
6791 	/*
6792 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6793 	 * each iteration, we restore the scratch pointer.
6794 	 */
6795 	for (i = 0; i < nframes; i++) {
6796 		mstate->dtms_scratch_ptr = saved;
6797 
6798 		if (offs >= strsize)
6799 			break;
6800 
6801 		sym = (char *)(uintptr_t)dtrace_helper(
6802 		    DTRACE_HELPER_ACTION_USTACK,
6803 		    mstate, state, pcs[i], fps[i]);
6804 
6805 		/*
6806 		 * If we faulted while running the helper, we're going to
6807 		 * clear the fault and null out the corresponding string.
6808 		 */
6809 		if (*flags & CPU_DTRACE_FAULT) {
6810 			*flags &= ~CPU_DTRACE_FAULT;
6811 			str[offs++] = '\0';
6812 			continue;
6813 		}
6814 
6815 		if (sym == NULL) {
6816 			str[offs++] = '\0';
6817 			continue;
6818 		}
6819 
6820 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
6821 		    &(state->dts_vstate))) {
6822 			str[offs++] = '\0';
6823 			continue;
6824 		}
6825 
6826 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6827 
6828 		/*
6829 		 * Now copy in the string that the helper returned to us.
6830 		 */
6831 		for (j = 0; offs + j < strsize && j < rem; j++) {
6832 			if ((str[offs + j] = sym[j]) == '\0')
6833 				break;
6834 		}
6835 
6836 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6837 
6838 		offs += j + 1;
6839 	}
6840 
6841 	if (offs >= strsize) {
6842 		/*
6843 		 * If we didn't have room for all of the strings, we don't
6844 		 * abort processing -- this needn't be a fatal error -- but we
6845 		 * still want to increment a counter (dts_stkstroverflows) to
6846 		 * allow this condition to be warned about.  (If this is from
6847 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6848 		 */
6849 		dtrace_error(&state->dts_stkstroverflows);
6850 	}
6851 
6852 	while (offs < strsize)
6853 		str[offs++] = '\0';
6854 
6855 out:
6856 	mstate->dtms_scratch_ptr = old;
6857 }
6858 
6859 static void
dtrace_store_by_ref(dtrace_difo_t * dp,caddr_t tomax,size_t size,size_t * valoffsp,uint64_t * valp,uint64_t end,int intuple,int dtkind)6860 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6861     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6862 {
6863 	volatile uint16_t *flags;
6864 	uint64_t val = *valp;
6865 	size_t valoffs = *valoffsp;
6866 
6867 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6868 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6869 
6870 	/*
6871 	 * If this is a string, we're going to only load until we find the zero
6872 	 * byte -- after which we'll store zero bytes.
6873 	 */
6874 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6875 		char c = '\0' + 1;
6876 		size_t s;
6877 
6878 		for (s = 0; s < size; s++) {
6879 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6880 				c = dtrace_load8(val++);
6881 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6882 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6883 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6884 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6885 				if (*flags & CPU_DTRACE_FAULT)
6886 					break;
6887 			}
6888 
6889 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6890 
6891 			if (c == '\0' && intuple)
6892 				break;
6893 		}
6894 	} else {
6895 		uint8_t c;
6896 		while (valoffs < end) {
6897 			if (dtkind == DIF_TF_BYREF) {
6898 				c = dtrace_load8(val++);
6899 			} else if (dtkind == DIF_TF_BYUREF) {
6900 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6901 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6902 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6903 				if (*flags & CPU_DTRACE_FAULT)
6904 					break;
6905 			}
6906 
6907 			DTRACE_STORE(uint8_t, tomax,
6908 			    valoffs++, c);
6909 		}
6910 	}
6911 
6912 	*valp = val;
6913 	*valoffsp = valoffs;
6914 }
6915 
6916 /*
6917  * If you're looking for the epicenter of DTrace, you just found it.  This
6918  * is the function called by the provider to fire a probe -- from which all
6919  * subsequent probe-context DTrace activity emanates.
6920  */
6921 void
dtrace_probe(dtrace_id_t id,uintptr_t arg0,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4)6922 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6923     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6924 {
6925 	processorid_t cpuid;
6926 	dtrace_icookie_t cookie;
6927 	dtrace_probe_t *probe;
6928 	dtrace_mstate_t mstate;
6929 	dtrace_ecb_t *ecb;
6930 	dtrace_action_t *act;
6931 	intptr_t offs;
6932 	size_t size;
6933 	int vtime, onintr;
6934 	volatile uint16_t *flags;
6935 	hrtime_t now, end;
6936 
6937 	/*
6938 	 * Kick out immediately if this CPU is still being born (in which case
6939 	 * curthread will be set to -1) or the current thread can't allow
6940 	 * probes in its current context.
6941 	 */
6942 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6943 		return;
6944 
6945 	cookie = dtrace_interrupt_disable();
6946 
6947 	/*
6948 	 * Also refuse to process any probe firings that might happen on a
6949 	 * disabled CPU.
6950 	 */
6951 	if (CPU->cpu_flags & CPU_DISABLED) {
6952 		dtrace_interrupt_enable(cookie);
6953 		return;
6954 	}
6955 
6956 	probe = dtrace_probes[id - 1];
6957 	cpuid = CPU->cpu_id;
6958 	onintr = CPU_ON_INTR(CPU);
6959 
6960 	CPU->cpu_dtrace_probes++;
6961 
6962 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6963 	    probe->dtpr_predcache == curthread->t_predcache) {
6964 		/*
6965 		 * We have hit in the predicate cache; we know that
6966 		 * this predicate would evaluate to be false.
6967 		 */
6968 		dtrace_interrupt_enable(cookie);
6969 		return;
6970 	}
6971 
6972 	if (panic_quiesce) {
6973 		/*
6974 		 * We don't trace anything if we're panicking.
6975 		 */
6976 		dtrace_interrupt_enable(cookie);
6977 		return;
6978 	}
6979 
6980 	now = dtrace_gethrtime();
6981 	vtime = dtrace_vtime_references != 0;
6982 
6983 	if (vtime && curthread->t_dtrace_start)
6984 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6985 
6986 	mstate.dtms_difo = NULL;
6987 	mstate.dtms_probe = probe;
6988 	mstate.dtms_strtok = 0;
6989 	mstate.dtms_arg[0] = arg0;
6990 	mstate.dtms_arg[1] = arg1;
6991 	mstate.dtms_arg[2] = arg2;
6992 	mstate.dtms_arg[3] = arg3;
6993 	mstate.dtms_arg[4] = arg4;
6994 
6995 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6996 
6997 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6998 		dtrace_predicate_t *pred = ecb->dte_predicate;
6999 		dtrace_state_t *state = ecb->dte_state;
7000 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7001 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7002 		dtrace_vstate_t *vstate = &state->dts_vstate;
7003 		dtrace_provider_t *prov = probe->dtpr_provider;
7004 		uint64_t tracememsize = 0;
7005 		int committed = 0;
7006 		caddr_t tomax;
7007 
7008 		/*
7009 		 * A little subtlety with the following (seemingly innocuous)
7010 		 * declaration of the automatic 'val':  by looking at the
7011 		 * code, you might think that it could be declared in the
7012 		 * action processing loop, below.  (That is, it's only used in
7013 		 * the action processing loop.)  However, it must be declared
7014 		 * out of that scope because in the case of DIF expression
7015 		 * arguments to aggregating actions, one iteration of the
7016 		 * action loop will use the last iteration's value.
7017 		 */
7018 #ifdef lint
7019 		uint64_t val = 0;
7020 #else
7021 		uint64_t val;
7022 #endif
7023 
7024 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7025 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
7026 		mstate.dtms_getf = NULL;
7027 
7028 		*flags &= ~CPU_DTRACE_ERROR;
7029 
7030 		if (prov == dtrace_provider) {
7031 			/*
7032 			 * If dtrace itself is the provider of this probe,
7033 			 * we're only going to continue processing the ECB if
7034 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7035 			 * creating state.  (This prevents disjoint consumers
7036 			 * from seeing one another's metaprobes.)
7037 			 */
7038 			if (arg0 != (uint64_t)(uintptr_t)state)
7039 				continue;
7040 		}
7041 
7042 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7043 			/*
7044 			 * We're not currently active.  If our provider isn't
7045 			 * the dtrace pseudo provider, we're not interested.
7046 			 */
7047 			if (prov != dtrace_provider)
7048 				continue;
7049 
7050 			/*
7051 			 * Now we must further check if we are in the BEGIN
7052 			 * probe.  If we are, we will only continue processing
7053 			 * if we're still in WARMUP -- if one BEGIN enabling
7054 			 * has invoked the exit() action, we don't want to
7055 			 * evaluate subsequent BEGIN enablings.
7056 			 */
7057 			if (probe->dtpr_id == dtrace_probeid_begin &&
7058 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7059 				ASSERT(state->dts_activity ==
7060 				    DTRACE_ACTIVITY_DRAINING);
7061 				continue;
7062 			}
7063 		}
7064 
7065 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
7066 			continue;
7067 
7068 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7069 			/*
7070 			 * We seem to be dead.  Unless we (a) have kernel
7071 			 * destructive permissions (b) have explicitly enabled
7072 			 * destructive actions and (c) destructive actions have
7073 			 * not been disabled, we're going to transition into
7074 			 * the KILLED state, from which no further processing
7075 			 * on this state will be performed.
7076 			 */
7077 			if (!dtrace_priv_kernel_destructive(state) ||
7078 			    !state->dts_cred.dcr_destructive ||
7079 			    dtrace_destructive_disallow) {
7080 				void *activity = &state->dts_activity;
7081 				dtrace_activity_t current;
7082 
7083 				do {
7084 					current = state->dts_activity;
7085 				} while (dtrace_cas32(activity, current,
7086 				    DTRACE_ACTIVITY_KILLED) != current);
7087 
7088 				continue;
7089 			}
7090 		}
7091 
7092 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7093 		    ecb->dte_alignment, state, &mstate)) < 0)
7094 			continue;
7095 
7096 		tomax = buf->dtb_tomax;
7097 		ASSERT(tomax != NULL);
7098 
7099 		if (ecb->dte_size != 0) {
7100 			dtrace_rechdr_t dtrh;
7101 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7102 				mstate.dtms_timestamp = dtrace_gethrtime();
7103 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7104 			}
7105 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7106 			dtrh.dtrh_epid = ecb->dte_epid;
7107 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7108 			    mstate.dtms_timestamp);
7109 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7110 		}
7111 
7112 		mstate.dtms_epid = ecb->dte_epid;
7113 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7114 
7115 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7116 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
7117 
7118 		if (pred != NULL) {
7119 			dtrace_difo_t *dp = pred->dtp_difo;
7120 			uint64_t rval;
7121 
7122 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7123 
7124 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7125 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7126 
7127 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7128 					/*
7129 					 * Update the predicate cache...
7130 					 */
7131 					ASSERT(cid == pred->dtp_cacheid);
7132 					curthread->t_predcache = cid;
7133 				}
7134 
7135 				continue;
7136 			}
7137 		}
7138 
7139 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7140 		    act != NULL; act = act->dta_next) {
7141 			size_t valoffs;
7142 			dtrace_difo_t *dp;
7143 			dtrace_recdesc_t *rec = &act->dta_rec;
7144 
7145 			size = rec->dtrd_size;
7146 			valoffs = offs + rec->dtrd_offset;
7147 
7148 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7149 				uint64_t v = 0xbad;
7150 				dtrace_aggregation_t *agg;
7151 
7152 				agg = (dtrace_aggregation_t *)act;
7153 
7154 				if ((dp = act->dta_difo) != NULL)
7155 					v = dtrace_dif_emulate(dp,
7156 					    &mstate, vstate, state);
7157 
7158 				if (*flags & CPU_DTRACE_ERROR)
7159 					continue;
7160 
7161 				/*
7162 				 * Note that we always pass the expression
7163 				 * value from the previous iteration of the
7164 				 * action loop.  This value will only be used
7165 				 * if there is an expression argument to the
7166 				 * aggregating action, denoted by the
7167 				 * dtag_hasarg field.
7168 				 */
7169 				dtrace_aggregate(agg, buf,
7170 				    offs, aggbuf, v, val);
7171 				continue;
7172 			}
7173 
7174 			switch (act->dta_kind) {
7175 			case DTRACEACT_STOP:
7176 				if (dtrace_priv_proc_destructive(state,
7177 				    &mstate))
7178 					dtrace_action_stop();
7179 				continue;
7180 
7181 			case DTRACEACT_BREAKPOINT:
7182 				if (dtrace_priv_kernel_destructive(state))
7183 					dtrace_action_breakpoint(ecb);
7184 				continue;
7185 
7186 			case DTRACEACT_PANIC:
7187 				if (dtrace_priv_kernel_destructive(state))
7188 					dtrace_action_panic(ecb);
7189 				continue;
7190 
7191 			case DTRACEACT_STACK:
7192 				if (!dtrace_priv_kernel(state))
7193 					continue;
7194 
7195 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7196 				    size / sizeof (pc_t), probe->dtpr_aframes,
7197 				    DTRACE_ANCHORED(probe) ? NULL :
7198 				    (uint32_t *)arg0);
7199 
7200 				continue;
7201 
7202 			case DTRACEACT_JSTACK:
7203 			case DTRACEACT_USTACK:
7204 				if (!dtrace_priv_proc(state, &mstate))
7205 					continue;
7206 
7207 				/*
7208 				 * See comment in DIF_VAR_PID.
7209 				 */
7210 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7211 				    CPU_ON_INTR(CPU)) {
7212 					int depth = DTRACE_USTACK_NFRAMES(
7213 					    rec->dtrd_arg) + 1;
7214 
7215 					dtrace_bzero((void *)(tomax + valoffs),
7216 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7217 					    + depth * sizeof (uint64_t));
7218 
7219 					continue;
7220 				}
7221 
7222 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7223 				    curproc->p_dtrace_helpers != NULL) {
7224 					/*
7225 					 * This is the slow path -- we have
7226 					 * allocated string space, and we're
7227 					 * getting the stack of a process that
7228 					 * has helpers.  Call into a separate
7229 					 * routine to perform this processing.
7230 					 */
7231 					dtrace_action_ustack(&mstate, state,
7232 					    (uint64_t *)(tomax + valoffs),
7233 					    rec->dtrd_arg);
7234 					continue;
7235 				}
7236 
7237 				/*
7238 				 * Clear the string space, since there's no
7239 				 * helper to do it for us.
7240 				 */
7241 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
7242 					int depth = DTRACE_USTACK_NFRAMES(
7243 					    rec->dtrd_arg);
7244 					size_t strsize = DTRACE_USTACK_STRSIZE(
7245 					    rec->dtrd_arg);
7246 					uint64_t *buf = (uint64_t *)(tomax +
7247 					    valoffs);
7248 					void *strspace = &buf[depth + 1];
7249 
7250 					dtrace_bzero(strspace,
7251 					    MIN(depth, strsize));
7252 				}
7253 
7254 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7255 				dtrace_getupcstack((uint64_t *)
7256 				    (tomax + valoffs),
7257 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7258 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7259 				continue;
7260 
7261 			default:
7262 				break;
7263 			}
7264 
7265 			dp = act->dta_difo;
7266 			ASSERT(dp != NULL);
7267 
7268 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7269 
7270 			if (*flags & CPU_DTRACE_ERROR)
7271 				continue;
7272 
7273 			switch (act->dta_kind) {
7274 			case DTRACEACT_SPECULATE: {
7275 				dtrace_rechdr_t *dtrh;
7276 
7277 				ASSERT(buf == &state->dts_buffer[cpuid]);
7278 				buf = dtrace_speculation_buffer(state,
7279 				    cpuid, val);
7280 
7281 				if (buf == NULL) {
7282 					*flags |= CPU_DTRACE_DROP;
7283 					continue;
7284 				}
7285 
7286 				offs = dtrace_buffer_reserve(buf,
7287 				    ecb->dte_needed, ecb->dte_alignment,
7288 				    state, NULL);
7289 
7290 				if (offs < 0) {
7291 					*flags |= CPU_DTRACE_DROP;
7292 					continue;
7293 				}
7294 
7295 				tomax = buf->dtb_tomax;
7296 				ASSERT(tomax != NULL);
7297 
7298 				if (ecb->dte_size == 0)
7299 					continue;
7300 
7301 				ASSERT3U(ecb->dte_size, >=,
7302 				    sizeof (dtrace_rechdr_t));
7303 				dtrh = ((void *)(tomax + offs));
7304 				dtrh->dtrh_epid = ecb->dte_epid;
7305 				/*
7306 				 * When the speculation is committed, all of
7307 				 * the records in the speculative buffer will
7308 				 * have their timestamps set to the commit
7309 				 * time.  Until then, it is set to a sentinel
7310 				 * value, for debugability.
7311 				 */
7312 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7313 				continue;
7314 			}
7315 
7316 			case DTRACEACT_CHILL:
7317 				if (dtrace_priv_kernel_destructive(state))
7318 					dtrace_action_chill(&mstate, val);
7319 				continue;
7320 
7321 			case DTRACEACT_RAISE:
7322 				if (dtrace_priv_proc_destructive(state,
7323 				    &mstate))
7324 					dtrace_action_raise(val);
7325 				continue;
7326 
7327 			case DTRACEACT_COMMIT:
7328 				ASSERT(!committed);
7329 
7330 				/*
7331 				 * We need to commit our buffer state.
7332 				 */
7333 				if (ecb->dte_size)
7334 					buf->dtb_offset = offs + ecb->dte_size;
7335 				buf = &state->dts_buffer[cpuid];
7336 				dtrace_speculation_commit(state, cpuid, val);
7337 				committed = 1;
7338 				continue;
7339 
7340 			case DTRACEACT_DISCARD:
7341 				dtrace_speculation_discard(state, cpuid, val);
7342 				continue;
7343 
7344 			case DTRACEACT_DIFEXPR:
7345 			case DTRACEACT_LIBACT:
7346 			case DTRACEACT_PRINTF:
7347 			case DTRACEACT_PRINTA:
7348 			case DTRACEACT_SYSTEM:
7349 			case DTRACEACT_FREOPEN:
7350 			case DTRACEACT_TRACEMEM:
7351 				break;
7352 
7353 			case DTRACEACT_TRACEMEM_DYNSIZE:
7354 				tracememsize = val;
7355 				break;
7356 
7357 			case DTRACEACT_SYM:
7358 			case DTRACEACT_MOD:
7359 				if (!dtrace_priv_kernel(state))
7360 					continue;
7361 				break;
7362 
7363 			case DTRACEACT_USYM:
7364 			case DTRACEACT_UMOD:
7365 			case DTRACEACT_UADDR: {
7366 				struct pid *pid = curthread->t_procp->p_pidp;
7367 
7368 				if (!dtrace_priv_proc(state, &mstate))
7369 					continue;
7370 
7371 				DTRACE_STORE(uint64_t, tomax,
7372 				    valoffs, (uint64_t)pid->pid_id);
7373 				DTRACE_STORE(uint64_t, tomax,
7374 				    valoffs + sizeof (uint64_t), val);
7375 
7376 				continue;
7377 			}
7378 
7379 			case DTRACEACT_EXIT: {
7380 				/*
7381 				 * For the exit action, we are going to attempt
7382 				 * to atomically set our activity to be
7383 				 * draining.  If this fails (either because
7384 				 * another CPU has beat us to the exit action,
7385 				 * or because our current activity is something
7386 				 * other than ACTIVE or WARMUP), we will
7387 				 * continue.  This assures that the exit action
7388 				 * can be successfully recorded at most once
7389 				 * when we're in the ACTIVE state.  If we're
7390 				 * encountering the exit() action while in
7391 				 * COOLDOWN, however, we want to honor the new
7392 				 * status code.  (We know that we're the only
7393 				 * thread in COOLDOWN, so there is no race.)
7394 				 */
7395 				void *activity = &state->dts_activity;
7396 				dtrace_activity_t current = state->dts_activity;
7397 
7398 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7399 					break;
7400 
7401 				if (current != DTRACE_ACTIVITY_WARMUP)
7402 					current = DTRACE_ACTIVITY_ACTIVE;
7403 
7404 				if (dtrace_cas32(activity, current,
7405 				    DTRACE_ACTIVITY_DRAINING) != current) {
7406 					*flags |= CPU_DTRACE_DROP;
7407 					continue;
7408 				}
7409 
7410 				break;
7411 			}
7412 
7413 			default:
7414 				ASSERT(0);
7415 			}
7416 
7417 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7418 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7419 				uintptr_t end = valoffs + size;
7420 
7421 				if (tracememsize != 0 &&
7422 				    valoffs + tracememsize < end) {
7423 					end = valoffs + tracememsize;
7424 					tracememsize = 0;
7425 				}
7426 
7427 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7428 				    !dtrace_vcanload((void *)(uintptr_t)val,
7429 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7430 					continue;
7431 
7432 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7433 				    &val, end, act->dta_intuple,
7434 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7435 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7436 				continue;
7437 			}
7438 
7439 			switch (size) {
7440 			case 0:
7441 				break;
7442 
7443 			case sizeof (uint8_t):
7444 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7445 				break;
7446 			case sizeof (uint16_t):
7447 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7448 				break;
7449 			case sizeof (uint32_t):
7450 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7451 				break;
7452 			case sizeof (uint64_t):
7453 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7454 				break;
7455 			default:
7456 				/*
7457 				 * Any other size should have been returned by
7458 				 * reference, not by value.
7459 				 */
7460 				ASSERT(0);
7461 				break;
7462 			}
7463 		}
7464 
7465 		if (*flags & CPU_DTRACE_DROP)
7466 			continue;
7467 
7468 		if (*flags & CPU_DTRACE_FAULT) {
7469 			int ndx;
7470 			dtrace_action_t *err;
7471 
7472 			buf->dtb_errors++;
7473 
7474 			if (probe->dtpr_id == dtrace_probeid_error) {
7475 				/*
7476 				 * There's nothing we can do -- we had an
7477 				 * error on the error probe.  We bump an
7478 				 * error counter to at least indicate that
7479 				 * this condition happened.
7480 				 */
7481 				dtrace_error(&state->dts_dblerrors);
7482 				continue;
7483 			}
7484 
7485 			if (vtime) {
7486 				/*
7487 				 * Before recursing on dtrace_probe(), we
7488 				 * need to explicitly clear out our start
7489 				 * time to prevent it from being accumulated
7490 				 * into t_dtrace_vtime.
7491 				 */
7492 				curthread->t_dtrace_start = 0;
7493 			}
7494 
7495 			/*
7496 			 * Iterate over the actions to figure out which action
7497 			 * we were processing when we experienced the error.
7498 			 * Note that act points _past_ the faulting action; if
7499 			 * act is ecb->dte_action, the fault was in the
7500 			 * predicate, if it's ecb->dte_action->dta_next it's
7501 			 * in action #1, and so on.
7502 			 */
7503 			for (err = ecb->dte_action, ndx = 0;
7504 			    err != act; err = err->dta_next, ndx++)
7505 				continue;
7506 
7507 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7508 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7509 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7510 			    cpu_core[cpuid].cpuc_dtrace_illval);
7511 
7512 			continue;
7513 		}
7514 
7515 		if (!committed)
7516 			buf->dtb_offset = offs + ecb->dte_size;
7517 	}
7518 
7519 	end = dtrace_gethrtime();
7520 	if (vtime)
7521 		curthread->t_dtrace_start = end;
7522 
7523 	CPU->cpu_dtrace_nsec += end - now;
7524 
7525 	dtrace_interrupt_enable(cookie);
7526 }
7527 
7528 /*
7529  * DTrace Probe Hashing Functions
7530  *
7531  * The functions in this section (and indeed, the functions in remaining
7532  * sections) are not _called_ from probe context.  (Any exceptions to this are
7533  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7534  * DTrace framework to look-up probes in, add probes to and remove probes from
7535  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7536  * probe tuple -- allowing for fast lookups, regardless of what was
7537  * specified.)
7538  */
7539 static uint_t
dtrace_hash_str(char * p)7540 dtrace_hash_str(char *p)
7541 {
7542 	unsigned int g;
7543 	uint_t hval = 0;
7544 
7545 	while (*p) {
7546 		hval = (hval << 4) + *p++;
7547 		if ((g = (hval & 0xf0000000)) != 0)
7548 			hval ^= g >> 24;
7549 		hval &= ~g;
7550 	}
7551 	return (hval);
7552 }
7553 
7554 static dtrace_hash_t *
dtrace_hash_create(uintptr_t stroffs,uintptr_t nextoffs,uintptr_t prevoffs)7555 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7556 {
7557 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7558 
7559 	hash->dth_stroffs = stroffs;
7560 	hash->dth_nextoffs = nextoffs;
7561 	hash->dth_prevoffs = prevoffs;
7562 
7563 	hash->dth_size = 1;
7564 	hash->dth_mask = hash->dth_size - 1;
7565 
7566 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7567 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7568 
7569 	return (hash);
7570 }
7571 
7572 static void
dtrace_hash_destroy(dtrace_hash_t * hash)7573 dtrace_hash_destroy(dtrace_hash_t *hash)
7574 {
7575 #ifdef DEBUG
7576 	int i;
7577 
7578 	for (i = 0; i < hash->dth_size; i++)
7579 		ASSERT(hash->dth_tab[i] == NULL);
7580 #endif
7581 
7582 	kmem_free(hash->dth_tab,
7583 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7584 	kmem_free(hash, sizeof (dtrace_hash_t));
7585 }
7586 
7587 static void
dtrace_hash_resize(dtrace_hash_t * hash)7588 dtrace_hash_resize(dtrace_hash_t *hash)
7589 {
7590 	int size = hash->dth_size, i, ndx;
7591 	int new_size = hash->dth_size << 1;
7592 	int new_mask = new_size - 1;
7593 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7594 
7595 	ASSERT((new_size & new_mask) == 0);
7596 
7597 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7598 
7599 	for (i = 0; i < size; i++) {
7600 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7601 			dtrace_probe_t *probe = bucket->dthb_chain;
7602 
7603 			ASSERT(probe != NULL);
7604 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7605 
7606 			next = bucket->dthb_next;
7607 			bucket->dthb_next = new_tab[ndx];
7608 			new_tab[ndx] = bucket;
7609 		}
7610 	}
7611 
7612 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7613 	hash->dth_tab = new_tab;
7614 	hash->dth_size = new_size;
7615 	hash->dth_mask = new_mask;
7616 }
7617 
7618 static void
dtrace_hash_add(dtrace_hash_t * hash,dtrace_probe_t * new)7619 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7620 {
7621 	int hashval = DTRACE_HASHSTR(hash, new);
7622 	int ndx = hashval & hash->dth_mask;
7623 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7624 	dtrace_probe_t **nextp, **prevp;
7625 
7626 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7627 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7628 			goto add;
7629 	}
7630 
7631 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7632 		dtrace_hash_resize(hash);
7633 		dtrace_hash_add(hash, new);
7634 		return;
7635 	}
7636 
7637 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7638 	bucket->dthb_next = hash->dth_tab[ndx];
7639 	hash->dth_tab[ndx] = bucket;
7640 	hash->dth_nbuckets++;
7641 
7642 add:
7643 	nextp = DTRACE_HASHNEXT(hash, new);
7644 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7645 	*nextp = bucket->dthb_chain;
7646 
7647 	if (bucket->dthb_chain != NULL) {
7648 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7649 		ASSERT(*prevp == NULL);
7650 		*prevp = new;
7651 	}
7652 
7653 	bucket->dthb_chain = new;
7654 	bucket->dthb_len++;
7655 }
7656 
7657 static dtrace_probe_t *
dtrace_hash_lookup(dtrace_hash_t * hash,dtrace_probe_t * template)7658 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7659 {
7660 	int hashval = DTRACE_HASHSTR(hash, template);
7661 	int ndx = hashval & hash->dth_mask;
7662 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7663 
7664 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7665 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7666 			return (bucket->dthb_chain);
7667 	}
7668 
7669 	return (NULL);
7670 }
7671 
7672 static int
dtrace_hash_collisions(dtrace_hash_t * hash,dtrace_probe_t * template)7673 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7674 {
7675 	int hashval = DTRACE_HASHSTR(hash, template);
7676 	int ndx = hashval & hash->dth_mask;
7677 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7678 
7679 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7680 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7681 			return (bucket->dthb_len);
7682 	}
7683 
7684 	return (0);
7685 }
7686 
7687 static void
dtrace_hash_remove(dtrace_hash_t * hash,dtrace_probe_t * probe)7688 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7689 {
7690 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7691 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7692 
7693 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7694 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7695 
7696 	/*
7697 	 * Find the bucket that we're removing this probe from.
7698 	 */
7699 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7700 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7701 			break;
7702 	}
7703 
7704 	ASSERT(bucket != NULL);
7705 
7706 	if (*prevp == NULL) {
7707 		if (*nextp == NULL) {
7708 			/*
7709 			 * The removed probe was the only probe on this
7710 			 * bucket; we need to remove the bucket.
7711 			 */
7712 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7713 
7714 			ASSERT(bucket->dthb_chain == probe);
7715 			ASSERT(b != NULL);
7716 
7717 			if (b == bucket) {
7718 				hash->dth_tab[ndx] = bucket->dthb_next;
7719 			} else {
7720 				while (b->dthb_next != bucket)
7721 					b = b->dthb_next;
7722 				b->dthb_next = bucket->dthb_next;
7723 			}
7724 
7725 			ASSERT(hash->dth_nbuckets > 0);
7726 			hash->dth_nbuckets--;
7727 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7728 			return;
7729 		}
7730 
7731 		bucket->dthb_chain = *nextp;
7732 	} else {
7733 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7734 	}
7735 
7736 	if (*nextp != NULL)
7737 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7738 }
7739 
7740 /*
7741  * DTrace Utility Functions
7742  *
7743  * These are random utility functions that are _not_ called from probe context.
7744  */
7745 static int
dtrace_badattr(const dtrace_attribute_t * a)7746 dtrace_badattr(const dtrace_attribute_t *a)
7747 {
7748 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7749 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7750 	    a->dtat_class > DTRACE_CLASS_MAX);
7751 }
7752 
7753 /*
7754  * Return a duplicate copy of a string.  If the specified string is NULL,
7755  * this function returns a zero-length string.
7756  */
7757 static char *
dtrace_strdup(const char * str)7758 dtrace_strdup(const char *str)
7759 {
7760 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7761 
7762 	if (str != NULL)
7763 		(void) strcpy(new, str);
7764 
7765 	return (new);
7766 }
7767 
7768 #define	DTRACE_ISALPHA(c)	\
7769 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7770 
7771 static int
dtrace_badname(const char * s)7772 dtrace_badname(const char *s)
7773 {
7774 	char c;
7775 
7776 	if (s == NULL || (c = *s++) == '\0')
7777 		return (0);
7778 
7779 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7780 		return (1);
7781 
7782 	while ((c = *s++) != '\0') {
7783 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7784 		    c != '-' && c != '_' && c != '.' && c != '`')
7785 			return (1);
7786 	}
7787 
7788 	return (0);
7789 }
7790 
7791 static void
dtrace_cred2priv(cred_t * cr,uint32_t * privp,uid_t * uidp,zoneid_t * zoneidp)7792 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7793 {
7794 	uint32_t priv;
7795 
7796 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7797 		/*
7798 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7799 		 */
7800 		priv = DTRACE_PRIV_ALL;
7801 	} else {
7802 		*uidp = crgetuid(cr);
7803 		*zoneidp = crgetzoneid(cr);
7804 
7805 		priv = 0;
7806 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7807 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7808 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7809 			priv |= DTRACE_PRIV_USER;
7810 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7811 			priv |= DTRACE_PRIV_PROC;
7812 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7813 			priv |= DTRACE_PRIV_OWNER;
7814 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7815 			priv |= DTRACE_PRIV_ZONEOWNER;
7816 	}
7817 
7818 	*privp = priv;
7819 }
7820 
7821 #ifdef DTRACE_ERRDEBUG
7822 static void
dtrace_errdebug(const char * str)7823 dtrace_errdebug(const char *str)
7824 {
7825 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7826 	int occupied = 0;
7827 
7828 	mutex_enter(&dtrace_errlock);
7829 	dtrace_errlast = str;
7830 	dtrace_errthread = curthread;
7831 
7832 	while (occupied++ < DTRACE_ERRHASHSZ) {
7833 		if (dtrace_errhash[hval].dter_msg == str) {
7834 			dtrace_errhash[hval].dter_count++;
7835 			goto out;
7836 		}
7837 
7838 		if (dtrace_errhash[hval].dter_msg != NULL) {
7839 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7840 			continue;
7841 		}
7842 
7843 		dtrace_errhash[hval].dter_msg = str;
7844 		dtrace_errhash[hval].dter_count = 1;
7845 		goto out;
7846 	}
7847 
7848 	panic("dtrace: undersized error hash");
7849 out:
7850 	mutex_exit(&dtrace_errlock);
7851 }
7852 #endif
7853 
7854 /*
7855  * DTrace Matching Functions
7856  *
7857  * These functions are used to match groups of probes, given some elements of
7858  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7859  */
7860 static int
dtrace_match_priv(const dtrace_probe_t * prp,uint32_t priv,uid_t uid,zoneid_t zoneid)7861 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7862     zoneid_t zoneid)
7863 {
7864 	if (priv != DTRACE_PRIV_ALL) {
7865 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7866 		uint32_t match = priv & ppriv;
7867 
7868 		/*
7869 		 * No PRIV_DTRACE_* privileges...
7870 		 */
7871 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7872 		    DTRACE_PRIV_KERNEL)) == 0)
7873 			return (0);
7874 
7875 		/*
7876 		 * No matching bits, but there were bits to match...
7877 		 */
7878 		if (match == 0 && ppriv != 0)
7879 			return (0);
7880 
7881 		/*
7882 		 * Need to have permissions to the process, but don't...
7883 		 */
7884 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7885 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7886 			return (0);
7887 		}
7888 
7889 		/*
7890 		 * Need to be in the same zone unless we possess the
7891 		 * privilege to examine all zones.
7892 		 */
7893 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7894 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7895 			return (0);
7896 		}
7897 	}
7898 
7899 	return (1);
7900 }
7901 
7902 /*
7903  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7904  * consists of input pattern strings and an ops-vector to evaluate them.
7905  * This function returns >0 for match, 0 for no match, and <0 for error.
7906  */
7907 static int
dtrace_match_probe(const dtrace_probe_t * prp,const dtrace_probekey_t * pkp,uint32_t priv,uid_t uid,zoneid_t zoneid)7908 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7909     uint32_t priv, uid_t uid, zoneid_t zoneid)
7910 {
7911 	dtrace_provider_t *pvp = prp->dtpr_provider;
7912 	int rv;
7913 
7914 	if (pvp->dtpv_defunct)
7915 		return (0);
7916 
7917 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7918 		return (rv);
7919 
7920 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7921 		return (rv);
7922 
7923 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7924 		return (rv);
7925 
7926 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7927 		return (rv);
7928 
7929 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7930 		return (0);
7931 
7932 	return (rv);
7933 }
7934 
7935 /*
7936  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7937  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7938  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7939  * In addition, all of the recursion cases except for '*' matching have been
7940  * unwound.  For '*', we still implement recursive evaluation, but a depth
7941  * counter is maintained and matching is aborted if we recurse too deep.
7942  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7943  */
7944 static int
dtrace_match_glob(const char * s,const char * p,int depth)7945 dtrace_match_glob(const char *s, const char *p, int depth)
7946 {
7947 	const char *olds;
7948 	char s1, c;
7949 	int gs;
7950 
7951 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7952 		return (-1);
7953 
7954 	if (s == NULL)
7955 		s = ""; /* treat NULL as empty string */
7956 
7957 top:
7958 	olds = s;
7959 	s1 = *s++;
7960 
7961 	if (p == NULL)
7962 		return (0);
7963 
7964 	if ((c = *p++) == '\0')
7965 		return (s1 == '\0');
7966 
7967 	switch (c) {
7968 	case '[': {
7969 		int ok = 0, notflag = 0;
7970 		char lc = '\0';
7971 
7972 		if (s1 == '\0')
7973 			return (0);
7974 
7975 		if (*p == '!') {
7976 			notflag = 1;
7977 			p++;
7978 		}
7979 
7980 		if ((c = *p++) == '\0')
7981 			return (0);
7982 
7983 		do {
7984 			if (c == '-' && lc != '\0' && *p != ']') {
7985 				if ((c = *p++) == '\0')
7986 					return (0);
7987 				if (c == '\\' && (c = *p++) == '\0')
7988 					return (0);
7989 
7990 				if (notflag) {
7991 					if (s1 < lc || s1 > c)
7992 						ok++;
7993 					else
7994 						return (0);
7995 				} else if (lc <= s1 && s1 <= c)
7996 					ok++;
7997 
7998 			} else if (c == '\\' && (c = *p++) == '\0')
7999 				return (0);
8000 
8001 			lc = c; /* save left-hand 'c' for next iteration */
8002 
8003 			if (notflag) {
8004 				if (s1 != c)
8005 					ok++;
8006 				else
8007 					return (0);
8008 			} else if (s1 == c)
8009 				ok++;
8010 
8011 			if ((c = *p++) == '\0')
8012 				return (0);
8013 
8014 		} while (c != ']');
8015 
8016 		if (ok)
8017 			goto top;
8018 
8019 		return (0);
8020 	}
8021 
8022 	case '\\':
8023 		if ((c = *p++) == '\0')
8024 			return (0);
8025 		/*FALLTHRU*/
8026 
8027 	default:
8028 		if (c != s1)
8029 			return (0);
8030 		/*FALLTHRU*/
8031 
8032 	case '?':
8033 		if (s1 != '\0')
8034 			goto top;
8035 		return (0);
8036 
8037 	case '*':
8038 		while (*p == '*')
8039 			p++; /* consecutive *'s are identical to a single one */
8040 
8041 		if (*p == '\0')
8042 			return (1);
8043 
8044 		for (s = olds; *s != '\0'; s++) {
8045 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8046 				return (gs);
8047 		}
8048 
8049 		return (0);
8050 	}
8051 }
8052 
8053 /*ARGSUSED*/
8054 static int
dtrace_match_string(const char * s,const char * p,int depth)8055 dtrace_match_string(const char *s, const char *p, int depth)
8056 {
8057 	return (s != NULL && strcmp(s, p) == 0);
8058 }
8059 
8060 /*ARGSUSED*/
8061 static int
dtrace_match_nul(const char * s,const char * p,int depth)8062 dtrace_match_nul(const char *s, const char *p, int depth)
8063 {
8064 	return (1); /* always match the empty pattern */
8065 }
8066 
8067 /*ARGSUSED*/
8068 static int
dtrace_match_nonzero(const char * s,const char * p,int depth)8069 dtrace_match_nonzero(const char *s, const char *p, int depth)
8070 {
8071 	return (s != NULL && s[0] != '\0');
8072 }
8073 
8074 static int
dtrace_match(const dtrace_probekey_t * pkp,uint32_t priv,uid_t uid,zoneid_t zoneid,int (* matched)(dtrace_probe_t *,void *),void * arg)8075 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8076     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8077 {
8078 	dtrace_probe_t template, *probe;
8079 	dtrace_hash_t *hash = NULL;
8080 	int len, rc, best = INT_MAX, nmatched = 0;
8081 	dtrace_id_t i;
8082 
8083 	ASSERT(MUTEX_HELD(&dtrace_lock));
8084 
8085 	/*
8086 	 * If the probe ID is specified in the key, just lookup by ID and
8087 	 * invoke the match callback once if a matching probe is found.
8088 	 */
8089 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8090 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8091 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8092 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
8093 				return (DTRACE_MATCH_FAIL);
8094 			nmatched++;
8095 		}
8096 		return (nmatched);
8097 	}
8098 
8099 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8100 	template.dtpr_func = (char *)pkp->dtpk_func;
8101 	template.dtpr_name = (char *)pkp->dtpk_name;
8102 
8103 	/*
8104 	 * We want to find the most distinct of the module name, function
8105 	 * name, and name.  So for each one that is not a glob pattern or
8106 	 * empty string, we perform a lookup in the corresponding hash and
8107 	 * use the hash table with the fewest collisions to do our search.
8108 	 */
8109 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8110 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8111 		best = len;
8112 		hash = dtrace_bymod;
8113 	}
8114 
8115 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8116 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8117 		best = len;
8118 		hash = dtrace_byfunc;
8119 	}
8120 
8121 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8122 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8123 		best = len;
8124 		hash = dtrace_byname;
8125 	}
8126 
8127 	/*
8128 	 * If we did not select a hash table, iterate over every probe and
8129 	 * invoke our callback for each one that matches our input probe key.
8130 	 */
8131 	if (hash == NULL) {
8132 		for (i = 0; i < dtrace_nprobes; i++) {
8133 			if ((probe = dtrace_probes[i]) == NULL ||
8134 			    dtrace_match_probe(probe, pkp, priv, uid,
8135 			    zoneid) <= 0)
8136 				continue;
8137 
8138 			nmatched++;
8139 
8140 			if ((rc = (*matched)(probe, arg)) !=
8141 			    DTRACE_MATCH_NEXT) {
8142 				if (rc == DTRACE_MATCH_FAIL)
8143 					return (DTRACE_MATCH_FAIL);
8144 				break;
8145 			}
8146 		}
8147 
8148 		return (nmatched);
8149 	}
8150 
8151 	/*
8152 	 * If we selected a hash table, iterate over each probe of the same key
8153 	 * name and invoke the callback for every probe that matches the other
8154 	 * attributes of our input probe key.
8155 	 */
8156 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8157 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8158 
8159 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8160 			continue;
8161 
8162 		nmatched++;
8163 
8164 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
8165 			if (rc == DTRACE_MATCH_FAIL)
8166 				return (DTRACE_MATCH_FAIL);
8167 			break;
8168 		}
8169 	}
8170 
8171 	return (nmatched);
8172 }
8173 
8174 /*
8175  * Return the function pointer dtrace_probecmp() should use to compare the
8176  * specified pattern with a string.  For NULL or empty patterns, we select
8177  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8178  * For non-empty non-glob strings, we use dtrace_match_string().
8179  */
8180 static dtrace_probekey_f *
dtrace_probekey_func(const char * p)8181 dtrace_probekey_func(const char *p)
8182 {
8183 	char c;
8184 
8185 	if (p == NULL || *p == '\0')
8186 		return (&dtrace_match_nul);
8187 
8188 	while ((c = *p++) != '\0') {
8189 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8190 			return (&dtrace_match_glob);
8191 	}
8192 
8193 	return (&dtrace_match_string);
8194 }
8195 
8196 /*
8197  * Build a probe comparison key for use with dtrace_match_probe() from the
8198  * given probe description.  By convention, a null key only matches anchored
8199  * probes: if each field is the empty string, reset dtpk_fmatch to
8200  * dtrace_match_nonzero().
8201  */
8202 static void
dtrace_probekey(const dtrace_probedesc_t * pdp,dtrace_probekey_t * pkp)8203 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8204 {
8205 	pkp->dtpk_prov = pdp->dtpd_provider;
8206 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8207 
8208 	pkp->dtpk_mod = pdp->dtpd_mod;
8209 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8210 
8211 	pkp->dtpk_func = pdp->dtpd_func;
8212 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8213 
8214 	pkp->dtpk_name = pdp->dtpd_name;
8215 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8216 
8217 	pkp->dtpk_id = pdp->dtpd_id;
8218 
8219 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8220 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8221 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8222 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8223 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8224 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8225 }
8226 
8227 /*
8228  * DTrace Provider-to-Framework API Functions
8229  *
8230  * These functions implement much of the Provider-to-Framework API, as
8231  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8232  * the functions in the API for probe management (found below), and
8233  * dtrace_probe() itself (found above).
8234  */
8235 
8236 /*
8237  * Register the calling provider with the DTrace framework.  This should
8238  * generally be called by DTrace providers in their attach(9E) entry point.
8239  */
8240 int
dtrace_register(const char * name,const dtrace_pattr_t * pap,uint32_t priv,cred_t * cr,const dtrace_pops_t * pops,void * arg,dtrace_provider_id_t * idp)8241 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8242     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8243 {
8244 	dtrace_provider_t *provider;
8245 
8246 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8247 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8248 		    "arguments", name ? name : "<NULL>");
8249 		return (EINVAL);
8250 	}
8251 
8252 	if (name[0] == '\0' || dtrace_badname(name)) {
8253 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8254 		    "provider name", name);
8255 		return (EINVAL);
8256 	}
8257 
8258 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8259 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8260 	    pops->dtps_destroy == NULL ||
8261 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8262 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8263 		    "provider ops", name);
8264 		return (EINVAL);
8265 	}
8266 
8267 	if (dtrace_badattr(&pap->dtpa_provider) ||
8268 	    dtrace_badattr(&pap->dtpa_mod) ||
8269 	    dtrace_badattr(&pap->dtpa_func) ||
8270 	    dtrace_badattr(&pap->dtpa_name) ||
8271 	    dtrace_badattr(&pap->dtpa_args)) {
8272 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8273 		    "provider attributes", name);
8274 		return (EINVAL);
8275 	}
8276 
8277 	if (priv & ~DTRACE_PRIV_ALL) {
8278 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8279 		    "privilege attributes", name);
8280 		return (EINVAL);
8281 	}
8282 
8283 	if ((priv & DTRACE_PRIV_KERNEL) &&
8284 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8285 	    pops->dtps_mode == NULL) {
8286 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8287 		    "dtps_mode() op for given privilege attributes", name);
8288 		return (EINVAL);
8289 	}
8290 
8291 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8292 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8293 	(void) strcpy(provider->dtpv_name, name);
8294 
8295 	provider->dtpv_attr = *pap;
8296 	provider->dtpv_priv.dtpp_flags = priv;
8297 	if (cr != NULL) {
8298 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8299 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8300 	}
8301 	provider->dtpv_pops = *pops;
8302 
8303 	if (pops->dtps_provide == NULL) {
8304 		ASSERT(pops->dtps_provide_module != NULL);
8305 		provider->dtpv_pops.dtps_provide = dtrace_nullop_provide;
8306 	}
8307 
8308 	if (pops->dtps_provide_module == NULL) {
8309 		ASSERT(pops->dtps_provide != NULL);
8310 		provider->dtpv_pops.dtps_provide_module = dtrace_nullop_module;
8311 	}
8312 
8313 	if (pops->dtps_suspend == NULL) {
8314 		ASSERT(pops->dtps_resume == NULL);
8315 		provider->dtpv_pops.dtps_suspend = dtrace_nullop;
8316 		provider->dtpv_pops.dtps_resume = dtrace_nullop;
8317 	}
8318 
8319 	provider->dtpv_arg = arg;
8320 	*idp = (dtrace_provider_id_t)provider;
8321 
8322 	if (pops == &dtrace_provider_ops) {
8323 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8324 		ASSERT(MUTEX_HELD(&dtrace_lock));
8325 		ASSERT(dtrace_anon.dta_enabling == NULL);
8326 
8327 		/*
8328 		 * We make sure that the DTrace provider is at the head of
8329 		 * the provider chain.
8330 		 */
8331 		provider->dtpv_next = dtrace_provider;
8332 		dtrace_provider = provider;
8333 		return (0);
8334 	}
8335 
8336 	mutex_enter(&dtrace_provider_lock);
8337 	mutex_enter(&dtrace_lock);
8338 
8339 	/*
8340 	 * If there is at least one provider registered, we'll add this
8341 	 * provider after the first provider.
8342 	 */
8343 	if (dtrace_provider != NULL) {
8344 		provider->dtpv_next = dtrace_provider->dtpv_next;
8345 		dtrace_provider->dtpv_next = provider;
8346 	} else {
8347 		dtrace_provider = provider;
8348 	}
8349 
8350 	if (dtrace_retained != NULL) {
8351 		dtrace_enabling_provide(provider);
8352 
8353 		/*
8354 		 * Now we need to call dtrace_enabling_matchall() -- which
8355 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8356 		 * to drop all of our locks before calling into it...
8357 		 */
8358 		mutex_exit(&dtrace_lock);
8359 		mutex_exit(&dtrace_provider_lock);
8360 		dtrace_enabling_matchall();
8361 
8362 		return (0);
8363 	}
8364 
8365 	mutex_exit(&dtrace_lock);
8366 	mutex_exit(&dtrace_provider_lock);
8367 
8368 	return (0);
8369 }
8370 
8371 /*
8372  * Unregister the specified provider from the DTrace framework.  This should
8373  * generally be called by DTrace providers in their detach(9E) entry point.
8374  */
8375 int
dtrace_unregister(dtrace_provider_id_t id)8376 dtrace_unregister(dtrace_provider_id_t id)
8377 {
8378 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8379 	dtrace_provider_t *prev = NULL;
8380 	int i, self = 0, noreap = 0;
8381 	dtrace_probe_t *probe, *first = NULL;
8382 
8383 	if (old->dtpv_pops.dtps_enable == dtrace_enable_nullop) {
8384 		/*
8385 		 * If DTrace itself is the provider, we're called with locks
8386 		 * already held.
8387 		 */
8388 		ASSERT(old == dtrace_provider);
8389 		ASSERT(dtrace_devi != NULL);
8390 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8391 		ASSERT(MUTEX_HELD(&dtrace_lock));
8392 		self = 1;
8393 
8394 		if (dtrace_provider->dtpv_next != NULL) {
8395 			/*
8396 			 * There's another provider here; return failure.
8397 			 */
8398 			return (EBUSY);
8399 		}
8400 	} else {
8401 		mutex_enter(&dtrace_provider_lock);
8402 		mutex_enter(&mod_lock);
8403 		mutex_enter(&dtrace_lock);
8404 	}
8405 
8406 	/*
8407 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8408 	 * probes, we refuse to let providers slither away, unless this
8409 	 * provider has already been explicitly invalidated.
8410 	 */
8411 	if (!old->dtpv_defunct &&
8412 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8413 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8414 		if (!self) {
8415 			mutex_exit(&dtrace_lock);
8416 			mutex_exit(&mod_lock);
8417 			mutex_exit(&dtrace_provider_lock);
8418 		}
8419 		return (EBUSY);
8420 	}
8421 
8422 	/*
8423 	 * Attempt to destroy the probes associated with this provider.
8424 	 */
8425 	for (i = 0; i < dtrace_nprobes; i++) {
8426 		if ((probe = dtrace_probes[i]) == NULL)
8427 			continue;
8428 
8429 		if (probe->dtpr_provider != old)
8430 			continue;
8431 
8432 		if (probe->dtpr_ecb == NULL)
8433 			continue;
8434 
8435 		/*
8436 		 * If we are trying to unregister a defunct provider, and the
8437 		 * provider was made defunct within the interval dictated by
8438 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8439 		 * attempt to reap our enablings.  To denote that the provider
8440 		 * should reattempt to unregister itself at some point in the
8441 		 * future, we will return a differentiable error code (EAGAIN
8442 		 * instead of EBUSY) in this case.
8443 		 */
8444 		if (dtrace_gethrtime() - old->dtpv_defunct >
8445 		    dtrace_unregister_defunct_reap)
8446 			noreap = 1;
8447 
8448 		if (!self) {
8449 			mutex_exit(&dtrace_lock);
8450 			mutex_exit(&mod_lock);
8451 			mutex_exit(&dtrace_provider_lock);
8452 		}
8453 
8454 		if (noreap)
8455 			return (EBUSY);
8456 
8457 		(void) taskq_dispatch(dtrace_taskq,
8458 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8459 
8460 		return (EAGAIN);
8461 	}
8462 
8463 	/*
8464 	 * All of the probes for this provider are disabled; we can safely
8465 	 * remove all of them from their hash chains and from the probe array.
8466 	 */
8467 	for (i = 0; i < dtrace_nprobes; i++) {
8468 		if ((probe = dtrace_probes[i]) == NULL)
8469 			continue;
8470 
8471 		if (probe->dtpr_provider != old)
8472 			continue;
8473 
8474 		dtrace_probes[i] = NULL;
8475 
8476 		dtrace_hash_remove(dtrace_bymod, probe);
8477 		dtrace_hash_remove(dtrace_byfunc, probe);
8478 		dtrace_hash_remove(dtrace_byname, probe);
8479 
8480 		if (first == NULL) {
8481 			first = probe;
8482 			probe->dtpr_nextmod = NULL;
8483 		} else {
8484 			probe->dtpr_nextmod = first;
8485 			first = probe;
8486 		}
8487 	}
8488 
8489 	/*
8490 	 * The provider's probes have been removed from the hash chains and
8491 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8492 	 * everyone has cleared out from any probe array processing.
8493 	 */
8494 	dtrace_sync();
8495 
8496 	for (probe = first; probe != NULL; probe = first) {
8497 		first = probe->dtpr_nextmod;
8498 
8499 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8500 		    probe->dtpr_arg);
8501 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8502 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8503 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8504 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8505 		kmem_free(probe, sizeof (dtrace_probe_t));
8506 	}
8507 
8508 	if ((prev = dtrace_provider) == old) {
8509 		ASSERT(self || dtrace_devi == NULL);
8510 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8511 		dtrace_provider = old->dtpv_next;
8512 	} else {
8513 		while (prev != NULL && prev->dtpv_next != old)
8514 			prev = prev->dtpv_next;
8515 
8516 		if (prev == NULL) {
8517 			panic("attempt to unregister non-existent "
8518 			    "dtrace provider %p\n", (void *)id);
8519 		}
8520 
8521 		prev->dtpv_next = old->dtpv_next;
8522 	}
8523 
8524 	if (!self) {
8525 		mutex_exit(&dtrace_lock);
8526 		mutex_exit(&mod_lock);
8527 		mutex_exit(&dtrace_provider_lock);
8528 	}
8529 
8530 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8531 	kmem_free(old, sizeof (dtrace_provider_t));
8532 
8533 	return (0);
8534 }
8535 
8536 /*
8537  * Invalidate the specified provider.  All subsequent probe lookups for the
8538  * specified provider will fail, but its probes will not be removed.
8539  */
8540 void
dtrace_invalidate(dtrace_provider_id_t id)8541 dtrace_invalidate(dtrace_provider_id_t id)
8542 {
8543 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8544 
8545 	ASSERT(pvp->dtpv_pops.dtps_enable != dtrace_enable_nullop);
8546 
8547 	mutex_enter(&dtrace_provider_lock);
8548 	mutex_enter(&dtrace_lock);
8549 
8550 	pvp->dtpv_defunct = dtrace_gethrtime();
8551 
8552 	mutex_exit(&dtrace_lock);
8553 	mutex_exit(&dtrace_provider_lock);
8554 }
8555 
8556 /*
8557  * Indicate whether or not DTrace has attached.
8558  */
8559 int
dtrace_attached(void)8560 dtrace_attached(void)
8561 {
8562 	/*
8563 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8564 	 * attached.  (It's non-NULL because DTrace is always itself a
8565 	 * provider.)
8566 	 */
8567 	return (dtrace_provider != NULL);
8568 }
8569 
8570 /*
8571  * Remove all the unenabled probes for the given provider.  This function is
8572  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8573  * -- just as many of its associated probes as it can.
8574  */
8575 int
dtrace_condense(dtrace_provider_id_t id)8576 dtrace_condense(dtrace_provider_id_t id)
8577 {
8578 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8579 	int i;
8580 	dtrace_probe_t *probe;
8581 
8582 	/*
8583 	 * Make sure this isn't the dtrace provider itself.
8584 	 */
8585 	ASSERT(prov->dtpv_pops.dtps_enable != dtrace_enable_nullop);
8586 
8587 	mutex_enter(&dtrace_provider_lock);
8588 	mutex_enter(&dtrace_lock);
8589 
8590 	/*
8591 	 * Attempt to destroy the probes associated with this provider.
8592 	 */
8593 	for (i = 0; i < dtrace_nprobes; i++) {
8594 		if ((probe = dtrace_probes[i]) == NULL)
8595 			continue;
8596 
8597 		if (probe->dtpr_provider != prov)
8598 			continue;
8599 
8600 		if (probe->dtpr_ecb != NULL)
8601 			continue;
8602 
8603 		dtrace_probes[i] = NULL;
8604 
8605 		dtrace_hash_remove(dtrace_bymod, probe);
8606 		dtrace_hash_remove(dtrace_byfunc, probe);
8607 		dtrace_hash_remove(dtrace_byname, probe);
8608 
8609 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8610 		    probe->dtpr_arg);
8611 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8612 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8613 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8614 		kmem_free(probe, sizeof (dtrace_probe_t));
8615 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8616 	}
8617 
8618 	mutex_exit(&dtrace_lock);
8619 	mutex_exit(&dtrace_provider_lock);
8620 
8621 	return (0);
8622 }
8623 
8624 /*
8625  * DTrace Probe Management Functions
8626  *
8627  * The functions in this section perform the DTrace probe management,
8628  * including functions to create probes, look-up probes, and call into the
8629  * providers to request that probes be provided.  Some of these functions are
8630  * in the Provider-to-Framework API; these functions can be identified by the
8631  * fact that they are not declared "static".
8632  */
8633 
8634 /*
8635  * Create a probe with the specified module name, function name, and name.
8636  */
8637 dtrace_id_t
dtrace_probe_create(dtrace_provider_id_t prov,const char * mod,const char * func,const char * name,int aframes,void * arg)8638 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8639     const char *func, const char *name, int aframes, void *arg)
8640 {
8641 	dtrace_probe_t *probe, **probes;
8642 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8643 	dtrace_id_t id;
8644 
8645 	if (provider == dtrace_provider) {
8646 		ASSERT(MUTEX_HELD(&dtrace_lock));
8647 	} else {
8648 		mutex_enter(&dtrace_lock);
8649 	}
8650 
8651 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8652 	    VM_BESTFIT | VM_SLEEP);
8653 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8654 
8655 	probe->dtpr_id = id;
8656 	probe->dtpr_gen = dtrace_probegen++;
8657 	probe->dtpr_mod = dtrace_strdup(mod);
8658 	probe->dtpr_func = dtrace_strdup(func);
8659 	probe->dtpr_name = dtrace_strdup(name);
8660 	probe->dtpr_arg = arg;
8661 	probe->dtpr_aframes = aframes;
8662 	probe->dtpr_provider = provider;
8663 
8664 	dtrace_hash_add(dtrace_bymod, probe);
8665 	dtrace_hash_add(dtrace_byfunc, probe);
8666 	dtrace_hash_add(dtrace_byname, probe);
8667 
8668 	if (id - 1 >= dtrace_nprobes) {
8669 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8670 		size_t nsize = osize << 1;
8671 
8672 		if (nsize == 0) {
8673 			ASSERT(osize == 0);
8674 			ASSERT(dtrace_probes == NULL);
8675 			nsize = sizeof (dtrace_probe_t *);
8676 		}
8677 
8678 		probes = kmem_zalloc(nsize, KM_SLEEP);
8679 
8680 		if (dtrace_probes == NULL) {
8681 			ASSERT(osize == 0);
8682 			dtrace_probes = probes;
8683 			dtrace_nprobes = 1;
8684 		} else {
8685 			dtrace_probe_t **oprobes = dtrace_probes;
8686 
8687 			bcopy(oprobes, probes, osize);
8688 			dtrace_membar_producer();
8689 			dtrace_probes = probes;
8690 
8691 			dtrace_sync();
8692 
8693 			/*
8694 			 * All CPUs are now seeing the new probes array; we can
8695 			 * safely free the old array.
8696 			 */
8697 			kmem_free(oprobes, osize);
8698 			dtrace_nprobes <<= 1;
8699 		}
8700 
8701 		ASSERT(id - 1 < dtrace_nprobes);
8702 	}
8703 
8704 	ASSERT(dtrace_probes[id - 1] == NULL);
8705 	dtrace_probes[id - 1] = probe;
8706 
8707 	if (provider != dtrace_provider)
8708 		mutex_exit(&dtrace_lock);
8709 
8710 	return (id);
8711 }
8712 
8713 static dtrace_probe_t *
dtrace_probe_lookup_id(dtrace_id_t id)8714 dtrace_probe_lookup_id(dtrace_id_t id)
8715 {
8716 	ASSERT(MUTEX_HELD(&dtrace_lock));
8717 
8718 	if (id == 0 || id > dtrace_nprobes)
8719 		return (NULL);
8720 
8721 	return (dtrace_probes[id - 1]);
8722 }
8723 
8724 static int
dtrace_probe_lookup_match(dtrace_probe_t * probe,void * arg)8725 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8726 {
8727 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8728 
8729 	return (DTRACE_MATCH_DONE);
8730 }
8731 
8732 /*
8733  * Look up a probe based on provider and one or more of module name, function
8734  * name and probe name.
8735  */
8736 dtrace_id_t
dtrace_probe_lookup(dtrace_provider_id_t prid,const char * mod,const char * func,const char * name)8737 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8738     const char *func, const char *name)
8739 {
8740 	dtrace_probekey_t pkey;
8741 	dtrace_id_t id;
8742 	int match;
8743 
8744 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8745 	pkey.dtpk_pmatch = &dtrace_match_string;
8746 	pkey.dtpk_mod = mod;
8747 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8748 	pkey.dtpk_func = func;
8749 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8750 	pkey.dtpk_name = name;
8751 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8752 	pkey.dtpk_id = DTRACE_IDNONE;
8753 
8754 	mutex_enter(&dtrace_lock);
8755 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8756 	    dtrace_probe_lookup_match, &id);
8757 	mutex_exit(&dtrace_lock);
8758 
8759 	ASSERT(match == 1 || match == 0);
8760 	return (match ? id : 0);
8761 }
8762 
8763 /*
8764  * Returns the probe argument associated with the specified probe.
8765  */
8766 void *
dtrace_probe_arg(dtrace_provider_id_t id,dtrace_id_t pid)8767 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8768 {
8769 	dtrace_probe_t *probe;
8770 	void *rval = NULL;
8771 
8772 	mutex_enter(&dtrace_lock);
8773 
8774 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8775 	    probe->dtpr_provider == (dtrace_provider_t *)id)
8776 		rval = probe->dtpr_arg;
8777 
8778 	mutex_exit(&dtrace_lock);
8779 
8780 	return (rval);
8781 }
8782 
8783 /*
8784  * Copy a probe into a probe description.
8785  */
8786 static void
dtrace_probe_description(const dtrace_probe_t * prp,dtrace_probedesc_t * pdp)8787 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8788 {
8789 	bzero(pdp, sizeof (dtrace_probedesc_t));
8790 	pdp->dtpd_id = prp->dtpr_id;
8791 
8792 	(void) strncpy(pdp->dtpd_provider,
8793 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8794 
8795 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8796 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8797 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8798 }
8799 
8800 /*
8801  * Called to indicate that a probe -- or probes -- should be provided by a
8802  * specfied provider.  If the specified description is NULL, the provider will
8803  * be told to provide all of its probes.  (This is done whenever a new
8804  * consumer comes along, or whenever a retained enabling is to be matched.) If
8805  * the specified description is non-NULL, the provider is given the
8806  * opportunity to dynamically provide the specified probe, allowing providers
8807  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8808  * probes.)  If the provider is NULL, the operations will be applied to all
8809  * providers; if the provider is non-NULL the operations will only be applied
8810  * to the specified provider.  The dtrace_provider_lock must be held, and the
8811  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8812  * will need to grab the dtrace_lock when it reenters the framework through
8813  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8814  */
8815 static void
dtrace_probe_provide(dtrace_probedesc_t * desc,dtrace_provider_t * prv)8816 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8817 {
8818 	struct modctl *ctl;
8819 	int all = 0;
8820 
8821 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8822 
8823 	if (prv == NULL) {
8824 		all = 1;
8825 		prv = dtrace_provider;
8826 	}
8827 
8828 	do {
8829 		/*
8830 		 * First, call the blanket provide operation.
8831 		 */
8832 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8833 
8834 		/*
8835 		 * Now call the per-module provide operation.  We will grab
8836 		 * mod_lock to prevent the list from being modified.  Note
8837 		 * that this also prevents the mod_busy bits from changing.
8838 		 * (mod_busy can only be changed with mod_lock held.)
8839 		 */
8840 		mutex_enter(&mod_lock);
8841 
8842 		ctl = &modules;
8843 		do {
8844 			if (ctl->mod_busy || ctl->mod_mp == NULL)
8845 				continue;
8846 
8847 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8848 
8849 		} while ((ctl = ctl->mod_next) != &modules);
8850 
8851 		mutex_exit(&mod_lock);
8852 	} while (all && (prv = prv->dtpv_next) != NULL);
8853 }
8854 
8855 /*
8856  * Iterate over each probe, and call the Framework-to-Provider API function
8857  * denoted by offs.
8858  */
8859 static void
dtrace_probe_foreach(uintptr_t offs)8860 dtrace_probe_foreach(uintptr_t offs)
8861 {
8862 	dtrace_provider_t *prov;
8863 	void (*func)(void *, dtrace_id_t, void *);
8864 	dtrace_probe_t *probe;
8865 	dtrace_icookie_t cookie;
8866 	int i;
8867 
8868 	/*
8869 	 * We disable interrupts to walk through the probe array.  This is
8870 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8871 	 * won't see stale data.
8872 	 */
8873 	cookie = dtrace_interrupt_disable();
8874 
8875 	for (i = 0; i < dtrace_nprobes; i++) {
8876 		if ((probe = dtrace_probes[i]) == NULL)
8877 			continue;
8878 
8879 		if (probe->dtpr_ecb == NULL) {
8880 			/*
8881 			 * This probe isn't enabled -- don't call the function.
8882 			 */
8883 			continue;
8884 		}
8885 
8886 		prov = probe->dtpr_provider;
8887 		func = *((void(**)(void *, dtrace_id_t, void *))
8888 		    ((uintptr_t)&prov->dtpv_pops + offs));
8889 
8890 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8891 	}
8892 
8893 	dtrace_interrupt_enable(cookie);
8894 }
8895 
8896 static int
dtrace_probe_enable(const dtrace_probedesc_t * desc,dtrace_enabling_t * enab)8897 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8898 {
8899 	dtrace_probekey_t pkey;
8900 	uint32_t priv;
8901 	uid_t uid;
8902 	zoneid_t zoneid;
8903 
8904 	ASSERT(MUTEX_HELD(&dtrace_lock));
8905 	dtrace_ecb_create_cache = NULL;
8906 
8907 	if (desc == NULL) {
8908 		/*
8909 		 * If we're passed a NULL description, we're being asked to
8910 		 * create an ECB with a NULL probe.
8911 		 */
8912 		(void) dtrace_ecb_create_enable(NULL, enab);
8913 		return (0);
8914 	}
8915 
8916 	dtrace_probekey(desc, &pkey);
8917 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8918 	    &priv, &uid, &zoneid);
8919 
8920 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8921 	    enab));
8922 }
8923 
8924 /*
8925  * DTrace Helper Provider Functions
8926  */
8927 static void
dtrace_dofattr2attr(dtrace_attribute_t * attr,const dof_attr_t dofattr)8928 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8929 {
8930 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8931 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8932 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8933 }
8934 
8935 static void
dtrace_dofprov2hprov(dtrace_helper_provdesc_t * hprov,const dof_provider_t * dofprov,char * strtab)8936 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8937     const dof_provider_t *dofprov, char *strtab)
8938 {
8939 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8940 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8941 	    dofprov->dofpv_provattr);
8942 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8943 	    dofprov->dofpv_modattr);
8944 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8945 	    dofprov->dofpv_funcattr);
8946 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8947 	    dofprov->dofpv_nameattr);
8948 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8949 	    dofprov->dofpv_argsattr);
8950 }
8951 
8952 static void
dtrace_helper_provide_one(dof_helper_t * dhp,dof_sec_t * sec,pid_t pid)8953 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8954 {
8955 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8956 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8957 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8958 	dof_provider_t *provider;
8959 	dof_probe_t *probe;
8960 	uint32_t *off, *enoff;
8961 	uint8_t *arg;
8962 	char *strtab;
8963 	uint_t i, nprobes;
8964 	dtrace_helper_provdesc_t dhpv;
8965 	dtrace_helper_probedesc_t dhpb;
8966 	dtrace_meta_t *meta = dtrace_meta_pid;
8967 	dtrace_mops_t *mops = &meta->dtm_mops;
8968 	void *parg;
8969 
8970 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8971 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8972 	    provider->dofpv_strtab * dof->dofh_secsize);
8973 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8974 	    provider->dofpv_probes * dof->dofh_secsize);
8975 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8976 	    provider->dofpv_prargs * dof->dofh_secsize);
8977 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8978 	    provider->dofpv_proffs * dof->dofh_secsize);
8979 
8980 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8981 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8982 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8983 	enoff = NULL;
8984 
8985 	/*
8986 	 * See dtrace_helper_provider_validate().
8987 	 */
8988 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8989 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8990 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8991 		    provider->dofpv_prenoffs * dof->dofh_secsize);
8992 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8993 	}
8994 
8995 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8996 
8997 	/*
8998 	 * Create the provider.
8999 	 */
9000 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9001 
9002 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9003 		return;
9004 
9005 	meta->dtm_count++;
9006 
9007 	/*
9008 	 * Create the probes.
9009 	 */
9010 	for (i = 0; i < nprobes; i++) {
9011 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9012 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9013 
9014 		dhpb.dthpb_mod = dhp->dofhp_mod;
9015 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9016 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9017 		dhpb.dthpb_base = probe->dofpr_addr;
9018 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9019 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9020 		if (enoff != NULL) {
9021 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9022 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9023 		} else {
9024 			dhpb.dthpb_enoffs = NULL;
9025 			dhpb.dthpb_nenoffs = 0;
9026 		}
9027 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9028 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9029 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9030 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9031 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9032 
9033 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9034 	}
9035 }
9036 
9037 static void
dtrace_helper_provide(dof_helper_t * dhp,pid_t pid)9038 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9039 {
9040 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9041 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9042 	int i;
9043 
9044 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9045 
9046 	for (i = 0; i < dof->dofh_secnum; i++) {
9047 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9048 		    dof->dofh_secoff + i * dof->dofh_secsize);
9049 
9050 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9051 			continue;
9052 
9053 		dtrace_helper_provide_one(dhp, sec, pid);
9054 	}
9055 
9056 	/*
9057 	 * We may have just created probes, so we must now rematch against
9058 	 * any retained enablings.  Note that this call will acquire both
9059 	 * cpu_lock and dtrace_lock; the fact that we are holding
9060 	 * dtrace_meta_lock now is what defines the ordering with respect to
9061 	 * these three locks.
9062 	 */
9063 	dtrace_enabling_matchall();
9064 }
9065 
9066 static void
dtrace_helper_provider_remove_one(dof_helper_t * dhp,dof_sec_t * sec,pid_t pid)9067 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9068 {
9069 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9070 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9071 	dof_sec_t *str_sec;
9072 	dof_provider_t *provider;
9073 	char *strtab;
9074 	dtrace_helper_provdesc_t dhpv;
9075 	dtrace_meta_t *meta = dtrace_meta_pid;
9076 	dtrace_mops_t *mops = &meta->dtm_mops;
9077 
9078 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9079 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9080 	    provider->dofpv_strtab * dof->dofh_secsize);
9081 
9082 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9083 
9084 	/*
9085 	 * Create the provider.
9086 	 */
9087 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9088 
9089 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9090 
9091 	meta->dtm_count--;
9092 }
9093 
9094 static void
dtrace_helper_provider_remove(dof_helper_t * dhp,pid_t pid)9095 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9096 {
9097 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9098 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9099 	int i;
9100 
9101 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9102 
9103 	for (i = 0; i < dof->dofh_secnum; i++) {
9104 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9105 		    dof->dofh_secoff + i * dof->dofh_secsize);
9106 
9107 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9108 			continue;
9109 
9110 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9111 	}
9112 }
9113 
9114 /*
9115  * DTrace Meta Provider-to-Framework API Functions
9116  *
9117  * These functions implement the Meta Provider-to-Framework API, as described
9118  * in <sys/dtrace.h>.
9119  */
9120 int
dtrace_meta_register(const char * name,const dtrace_mops_t * mops,void * arg,dtrace_meta_provider_id_t * idp)9121 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9122     dtrace_meta_provider_id_t *idp)
9123 {
9124 	dtrace_meta_t *meta;
9125 	dtrace_helpers_t *help, *next;
9126 	int i;
9127 
9128 	*idp = DTRACE_METAPROVNONE;
9129 
9130 	/*
9131 	 * We strictly don't need the name, but we hold onto it for
9132 	 * debuggability. All hail error queues!
9133 	 */
9134 	if (name == NULL) {
9135 		cmn_err(CE_WARN, "failed to register meta-provider: "
9136 		    "invalid name");
9137 		return (EINVAL);
9138 	}
9139 
9140 	if (mops == NULL ||
9141 	    mops->dtms_create_probe == NULL ||
9142 	    mops->dtms_provide_pid == NULL ||
9143 	    mops->dtms_remove_pid == NULL) {
9144 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9145 		    "invalid ops", name);
9146 		return (EINVAL);
9147 	}
9148 
9149 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9150 	meta->dtm_mops = *mops;
9151 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9152 	(void) strcpy(meta->dtm_name, name);
9153 	meta->dtm_arg = arg;
9154 
9155 	mutex_enter(&dtrace_meta_lock);
9156 	mutex_enter(&dtrace_lock);
9157 
9158 	if (dtrace_meta_pid != NULL) {
9159 		mutex_exit(&dtrace_lock);
9160 		mutex_exit(&dtrace_meta_lock);
9161 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9162 		    "user-land meta-provider exists", name);
9163 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9164 		kmem_free(meta, sizeof (dtrace_meta_t));
9165 		return (EINVAL);
9166 	}
9167 
9168 	dtrace_meta_pid = meta;
9169 	*idp = (dtrace_meta_provider_id_t)meta;
9170 
9171 	/*
9172 	 * If there are providers and probes ready to go, pass them
9173 	 * off to the new meta provider now.
9174 	 */
9175 
9176 	help = dtrace_deferred_pid;
9177 	dtrace_deferred_pid = NULL;
9178 
9179 	mutex_exit(&dtrace_lock);
9180 
9181 	while (help != NULL) {
9182 		for (i = 0; i < help->dthps_nprovs; i++) {
9183 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9184 			    help->dthps_pid);
9185 		}
9186 
9187 		next = help->dthps_next;
9188 		help->dthps_next = NULL;
9189 		help->dthps_prev = NULL;
9190 		help->dthps_deferred = 0;
9191 		help = next;
9192 	}
9193 
9194 	mutex_exit(&dtrace_meta_lock);
9195 
9196 	return (0);
9197 }
9198 
9199 int
dtrace_meta_unregister(dtrace_meta_provider_id_t id)9200 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9201 {
9202 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9203 
9204 	mutex_enter(&dtrace_meta_lock);
9205 	mutex_enter(&dtrace_lock);
9206 
9207 	if (old == dtrace_meta_pid) {
9208 		pp = &dtrace_meta_pid;
9209 	} else {
9210 		panic("attempt to unregister non-existent "
9211 		    "dtrace meta-provider %p\n", (void *)old);
9212 	}
9213 
9214 	if (old->dtm_count != 0) {
9215 		mutex_exit(&dtrace_lock);
9216 		mutex_exit(&dtrace_meta_lock);
9217 		return (EBUSY);
9218 	}
9219 
9220 	*pp = NULL;
9221 
9222 	mutex_exit(&dtrace_lock);
9223 	mutex_exit(&dtrace_meta_lock);
9224 
9225 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9226 	kmem_free(old, sizeof (dtrace_meta_t));
9227 
9228 	return (0);
9229 }
9230 
9231 
9232 /*
9233  * DTrace DIF Object Functions
9234  */
9235 static int
dtrace_difo_err(uint_t pc,const char * format,...)9236 dtrace_difo_err(uint_t pc, const char *format, ...)
9237 {
9238 	if (dtrace_err_verbose) {
9239 		va_list alist;
9240 
9241 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9242 		va_start(alist, format);
9243 		(void) vuprintf(format, alist);
9244 		va_end(alist);
9245 	}
9246 
9247 #ifdef DTRACE_ERRDEBUG
9248 	dtrace_errdebug(format);
9249 #endif
9250 	return (1);
9251 }
9252 
9253 /*
9254  * Validate a DTrace DIF object by checking the IR instructions.  The following
9255  * rules are currently enforced by dtrace_difo_validate():
9256  *
9257  * 1. Each instruction must have a valid opcode
9258  * 2. Each register, string, variable, or subroutine reference must be valid
9259  * 3. No instruction can modify register %r0 (must be zero)
9260  * 4. All instruction reserved bits must be set to zero
9261  * 5. The last instruction must be a "ret" instruction
9262  * 6. All branch targets must reference a valid instruction _after_ the branch
9263  */
9264 static int
dtrace_difo_validate(dtrace_difo_t * dp,dtrace_vstate_t * vstate,uint_t nregs,cred_t * cr)9265 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9266     cred_t *cr)
9267 {
9268 	int err = 0, i;
9269 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9270 	int kcheckload;
9271 	uint_t pc;
9272 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9273 
9274 	kcheckload = cr == NULL ||
9275 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9276 
9277 	dp->dtdo_destructive = 0;
9278 
9279 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9280 		dif_instr_t instr = dp->dtdo_buf[pc];
9281 
9282 		uint_t r1 = DIF_INSTR_R1(instr);
9283 		uint_t r2 = DIF_INSTR_R2(instr);
9284 		uint_t rd = DIF_INSTR_RD(instr);
9285 		uint_t rs = DIF_INSTR_RS(instr);
9286 		uint_t label = DIF_INSTR_LABEL(instr);
9287 		uint_t v = DIF_INSTR_VAR(instr);
9288 		uint_t subr = DIF_INSTR_SUBR(instr);
9289 		uint_t type = DIF_INSTR_TYPE(instr);
9290 		uint_t op = DIF_INSTR_OP(instr);
9291 
9292 		switch (op) {
9293 		case DIF_OP_OR:
9294 		case DIF_OP_XOR:
9295 		case DIF_OP_AND:
9296 		case DIF_OP_SLL:
9297 		case DIF_OP_SRL:
9298 		case DIF_OP_SRA:
9299 		case DIF_OP_SUB:
9300 		case DIF_OP_ADD:
9301 		case DIF_OP_MUL:
9302 		case DIF_OP_SDIV:
9303 		case DIF_OP_UDIV:
9304 		case DIF_OP_SREM:
9305 		case DIF_OP_UREM:
9306 		case DIF_OP_COPYS:
9307 			if (r1 >= nregs)
9308 				err += efunc(pc, "invalid register %u\n", r1);
9309 			if (r2 >= nregs)
9310 				err += efunc(pc, "invalid register %u\n", r2);
9311 			if (rd >= nregs)
9312 				err += efunc(pc, "invalid register %u\n", rd);
9313 			if (rd == 0)
9314 				err += efunc(pc, "cannot write to %%r0\n");
9315 			break;
9316 		case DIF_OP_NOT:
9317 		case DIF_OP_MOV:
9318 		case DIF_OP_ALLOCS:
9319 			if (r1 >= nregs)
9320 				err += efunc(pc, "invalid register %u\n", r1);
9321 			if (r2 != 0)
9322 				err += efunc(pc, "non-zero reserved bits\n");
9323 			if (rd >= nregs)
9324 				err += efunc(pc, "invalid register %u\n", rd);
9325 			if (rd == 0)
9326 				err += efunc(pc, "cannot write to %%r0\n");
9327 			break;
9328 		case DIF_OP_LDSB:
9329 		case DIF_OP_LDSH:
9330 		case DIF_OP_LDSW:
9331 		case DIF_OP_LDUB:
9332 		case DIF_OP_LDUH:
9333 		case DIF_OP_LDUW:
9334 		case DIF_OP_LDX:
9335 			if (r1 >= nregs)
9336 				err += efunc(pc, "invalid register %u\n", r1);
9337 			if (r2 != 0)
9338 				err += efunc(pc, "non-zero reserved bits\n");
9339 			if (rd >= nregs)
9340 				err += efunc(pc, "invalid register %u\n", rd);
9341 			if (rd == 0)
9342 				err += efunc(pc, "cannot write to %%r0\n");
9343 			if (kcheckload)
9344 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9345 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9346 			break;
9347 		case DIF_OP_RLDSB:
9348 		case DIF_OP_RLDSH:
9349 		case DIF_OP_RLDSW:
9350 		case DIF_OP_RLDUB:
9351 		case DIF_OP_RLDUH:
9352 		case DIF_OP_RLDUW:
9353 		case DIF_OP_RLDX:
9354 			if (r1 >= nregs)
9355 				err += efunc(pc, "invalid register %u\n", r1);
9356 			if (r2 != 0)
9357 				err += efunc(pc, "non-zero reserved bits\n");
9358 			if (rd >= nregs)
9359 				err += efunc(pc, "invalid register %u\n", rd);
9360 			if (rd == 0)
9361 				err += efunc(pc, "cannot write to %%r0\n");
9362 			break;
9363 		case DIF_OP_ULDSB:
9364 		case DIF_OP_ULDSH:
9365 		case DIF_OP_ULDSW:
9366 		case DIF_OP_ULDUB:
9367 		case DIF_OP_ULDUH:
9368 		case DIF_OP_ULDUW:
9369 		case DIF_OP_ULDX:
9370 			if (r1 >= nregs)
9371 				err += efunc(pc, "invalid register %u\n", r1);
9372 			if (r2 != 0)
9373 				err += efunc(pc, "non-zero reserved bits\n");
9374 			if (rd >= nregs)
9375 				err += efunc(pc, "invalid register %u\n", rd);
9376 			if (rd == 0)
9377 				err += efunc(pc, "cannot write to %%r0\n");
9378 			break;
9379 		case DIF_OP_STB:
9380 		case DIF_OP_STH:
9381 		case DIF_OP_STW:
9382 		case DIF_OP_STX:
9383 			if (r1 >= nregs)
9384 				err += efunc(pc, "invalid register %u\n", r1);
9385 			if (r2 != 0)
9386 				err += efunc(pc, "non-zero reserved bits\n");
9387 			if (rd >= nregs)
9388 				err += efunc(pc, "invalid register %u\n", rd);
9389 			if (rd == 0)
9390 				err += efunc(pc, "cannot write to 0 address\n");
9391 			break;
9392 		case DIF_OP_CMP:
9393 		case DIF_OP_SCMP:
9394 			if (r1 >= nregs)
9395 				err += efunc(pc, "invalid register %u\n", r1);
9396 			if (r2 >= nregs)
9397 				err += efunc(pc, "invalid register %u\n", r2);
9398 			if (rd != 0)
9399 				err += efunc(pc, "non-zero reserved bits\n");
9400 			break;
9401 		case DIF_OP_TST:
9402 			if (r1 >= nregs)
9403 				err += efunc(pc, "invalid register %u\n", r1);
9404 			if (r2 != 0 || rd != 0)
9405 				err += efunc(pc, "non-zero reserved bits\n");
9406 			break;
9407 		case DIF_OP_BA:
9408 		case DIF_OP_BE:
9409 		case DIF_OP_BNE:
9410 		case DIF_OP_BG:
9411 		case DIF_OP_BGU:
9412 		case DIF_OP_BGE:
9413 		case DIF_OP_BGEU:
9414 		case DIF_OP_BL:
9415 		case DIF_OP_BLU:
9416 		case DIF_OP_BLE:
9417 		case DIF_OP_BLEU:
9418 			if (label >= dp->dtdo_len) {
9419 				err += efunc(pc, "invalid branch target %u\n",
9420 				    label);
9421 			}
9422 			if (label <= pc) {
9423 				err += efunc(pc, "backward branch to %u\n",
9424 				    label);
9425 			}
9426 			break;
9427 		case DIF_OP_RET:
9428 			if (r1 != 0 || r2 != 0)
9429 				err += efunc(pc, "non-zero reserved bits\n");
9430 			if (rd >= nregs)
9431 				err += efunc(pc, "invalid register %u\n", rd);
9432 			break;
9433 		case DIF_OP_NOP:
9434 		case DIF_OP_POPTS:
9435 		case DIF_OP_FLUSHTS:
9436 			if (r1 != 0 || r2 != 0 || rd != 0)
9437 				err += efunc(pc, "non-zero reserved bits\n");
9438 			break;
9439 		case DIF_OP_SETX:
9440 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9441 				err += efunc(pc, "invalid integer ref %u\n",
9442 				    DIF_INSTR_INTEGER(instr));
9443 			}
9444 			if (rd >= nregs)
9445 				err += efunc(pc, "invalid register %u\n", rd);
9446 			if (rd == 0)
9447 				err += efunc(pc, "cannot write to %%r0\n");
9448 			break;
9449 		case DIF_OP_SETS:
9450 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9451 				err += efunc(pc, "invalid string ref %u\n",
9452 				    DIF_INSTR_STRING(instr));
9453 			}
9454 			if (rd >= nregs)
9455 				err += efunc(pc, "invalid register %u\n", rd);
9456 			if (rd == 0)
9457 				err += efunc(pc, "cannot write to %%r0\n");
9458 			break;
9459 		case DIF_OP_LDGA:
9460 		case DIF_OP_LDTA:
9461 			if (r1 > DIF_VAR_ARRAY_MAX)
9462 				err += efunc(pc, "invalid array %u\n", r1);
9463 			if (r2 >= nregs)
9464 				err += efunc(pc, "invalid register %u\n", r2);
9465 			if (rd >= nregs)
9466 				err += efunc(pc, "invalid register %u\n", rd);
9467 			if (rd == 0)
9468 				err += efunc(pc, "cannot write to %%r0\n");
9469 			break;
9470 		case DIF_OP_STGA:
9471 			if (r1 > DIF_VAR_ARRAY_MAX)
9472 				err += efunc(pc, "invalid array %u\n", r1);
9473 			if (r2 >= nregs)
9474 				err += efunc(pc, "invalid register %u\n", r2);
9475 			if (rd >= nregs)
9476 				err += efunc(pc, "invalid register %u\n", rd);
9477 			dp->dtdo_destructive = 1;
9478 			break;
9479 		case DIF_OP_LDGS:
9480 		case DIF_OP_LDTS:
9481 		case DIF_OP_LDLS:
9482 		case DIF_OP_LDGAA:
9483 		case DIF_OP_LDTAA:
9484 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9485 				err += efunc(pc, "invalid variable %u\n", v);
9486 			if (rd >= nregs)
9487 				err += efunc(pc, "invalid register %u\n", rd);
9488 			if (rd == 0)
9489 				err += efunc(pc, "cannot write to %%r0\n");
9490 			break;
9491 		case DIF_OP_STGS:
9492 		case DIF_OP_STTS:
9493 		case DIF_OP_STLS:
9494 		case DIF_OP_STGAA:
9495 		case DIF_OP_STTAA:
9496 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9497 				err += efunc(pc, "invalid variable %u\n", v);
9498 			if (rs >= nregs)
9499 				err += efunc(pc, "invalid register %u\n", rd);
9500 			break;
9501 		case DIF_OP_CALL:
9502 			if (subr > DIF_SUBR_MAX)
9503 				err += efunc(pc, "invalid subr %u\n", subr);
9504 			if (rd >= nregs)
9505 				err += efunc(pc, "invalid register %u\n", rd);
9506 			if (rd == 0)
9507 				err += efunc(pc, "cannot write to %%r0\n");
9508 
9509 			if (subr == DIF_SUBR_COPYOUT ||
9510 			    subr == DIF_SUBR_COPYOUTSTR) {
9511 				dp->dtdo_destructive = 1;
9512 			}
9513 
9514 			if (subr == DIF_SUBR_GETF) {
9515 				/*
9516 				 * If we have a getf() we need to record that
9517 				 * in our state.  Note that our state can be
9518 				 * NULL if this is a helper -- but in that
9519 				 * case, the call to getf() is itself illegal,
9520 				 * and will be caught (slightly later) when
9521 				 * the helper is validated.
9522 				 */
9523 				if (vstate->dtvs_state != NULL)
9524 					vstate->dtvs_state->dts_getf++;
9525 			}
9526 
9527 			break;
9528 		case DIF_OP_PUSHTR:
9529 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9530 				err += efunc(pc, "invalid ref type %u\n", type);
9531 			if (r2 >= nregs)
9532 				err += efunc(pc, "invalid register %u\n", r2);
9533 			if (rs >= nregs)
9534 				err += efunc(pc, "invalid register %u\n", rs);
9535 			break;
9536 		case DIF_OP_PUSHTV:
9537 			if (type != DIF_TYPE_CTF)
9538 				err += efunc(pc, "invalid val type %u\n", type);
9539 			if (r2 >= nregs)
9540 				err += efunc(pc, "invalid register %u\n", r2);
9541 			if (rs >= nregs)
9542 				err += efunc(pc, "invalid register %u\n", rs);
9543 			break;
9544 		default:
9545 			err += efunc(pc, "invalid opcode %u\n",
9546 			    DIF_INSTR_OP(instr));
9547 		}
9548 	}
9549 
9550 	if (dp->dtdo_len != 0 &&
9551 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9552 		err += efunc(dp->dtdo_len - 1,
9553 		    "expected 'ret' as last DIF instruction\n");
9554 	}
9555 
9556 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9557 		/*
9558 		 * If we're not returning by reference, the size must be either
9559 		 * 0 or the size of one of the base types.
9560 		 */
9561 		switch (dp->dtdo_rtype.dtdt_size) {
9562 		case 0:
9563 		case sizeof (uint8_t):
9564 		case sizeof (uint16_t):
9565 		case sizeof (uint32_t):
9566 		case sizeof (uint64_t):
9567 			break;
9568 
9569 		default:
9570 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9571 		}
9572 	}
9573 
9574 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9575 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9576 		dtrace_diftype_t *vt, *et;
9577 		uint_t id, ndx;
9578 
9579 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9580 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9581 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9582 			err += efunc(i, "unrecognized variable scope %d\n",
9583 			    v->dtdv_scope);
9584 			break;
9585 		}
9586 
9587 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9588 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9589 			err += efunc(i, "unrecognized variable type %d\n",
9590 			    v->dtdv_kind);
9591 			break;
9592 		}
9593 
9594 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9595 			err += efunc(i, "%d exceeds variable id limit\n", id);
9596 			break;
9597 		}
9598 
9599 		if (id < DIF_VAR_OTHER_UBASE)
9600 			continue;
9601 
9602 		/*
9603 		 * For user-defined variables, we need to check that this
9604 		 * definition is identical to any previous definition that we
9605 		 * encountered.
9606 		 */
9607 		ndx = id - DIF_VAR_OTHER_UBASE;
9608 
9609 		switch (v->dtdv_scope) {
9610 		case DIFV_SCOPE_GLOBAL:
9611 			if (maxglobal == -1 || ndx > maxglobal)
9612 				maxglobal = ndx;
9613 
9614 			if (ndx < vstate->dtvs_nglobals) {
9615 				dtrace_statvar_t *svar;
9616 
9617 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9618 					existing = &svar->dtsv_var;
9619 			}
9620 
9621 			break;
9622 
9623 		case DIFV_SCOPE_THREAD:
9624 			if (maxtlocal == -1 || ndx > maxtlocal)
9625 				maxtlocal = ndx;
9626 
9627 			if (ndx < vstate->dtvs_ntlocals)
9628 				existing = &vstate->dtvs_tlocals[ndx];
9629 			break;
9630 
9631 		case DIFV_SCOPE_LOCAL:
9632 			if (maxlocal == -1 || ndx > maxlocal)
9633 				maxlocal = ndx;
9634 
9635 			if (ndx < vstate->dtvs_nlocals) {
9636 				dtrace_statvar_t *svar;
9637 
9638 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9639 					existing = &svar->dtsv_var;
9640 			}
9641 
9642 			break;
9643 		}
9644 
9645 		vt = &v->dtdv_type;
9646 
9647 		if (vt->dtdt_flags & DIF_TF_BYREF) {
9648 			if (vt->dtdt_size == 0) {
9649 				err += efunc(i, "zero-sized variable\n");
9650 				break;
9651 			}
9652 
9653 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9654 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9655 			    vt->dtdt_size > dtrace_statvar_maxsize) {
9656 				err += efunc(i, "oversized by-ref static\n");
9657 				break;
9658 			}
9659 		}
9660 
9661 		if (existing == NULL || existing->dtdv_id == 0)
9662 			continue;
9663 
9664 		ASSERT(existing->dtdv_id == v->dtdv_id);
9665 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
9666 
9667 		if (existing->dtdv_kind != v->dtdv_kind)
9668 			err += efunc(i, "%d changed variable kind\n", id);
9669 
9670 		et = &existing->dtdv_type;
9671 
9672 		if (vt->dtdt_flags != et->dtdt_flags) {
9673 			err += efunc(i, "%d changed variable type flags\n", id);
9674 			break;
9675 		}
9676 
9677 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9678 			err += efunc(i, "%d changed variable type size\n", id);
9679 			break;
9680 		}
9681 	}
9682 
9683 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9684 		dif_instr_t instr = dp->dtdo_buf[pc];
9685 
9686 		uint_t v = DIF_INSTR_VAR(instr);
9687 		uint_t op = DIF_INSTR_OP(instr);
9688 
9689 		switch (op) {
9690 		case DIF_OP_LDGS:
9691 		case DIF_OP_LDGAA:
9692 		case DIF_OP_STGS:
9693 		case DIF_OP_STGAA:
9694 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
9695 				err += efunc(pc, "invalid variable %u\n", v);
9696 			break;
9697 		case DIF_OP_LDTS:
9698 		case DIF_OP_LDTAA:
9699 		case DIF_OP_STTS:
9700 		case DIF_OP_STTAA:
9701 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
9702 				err += efunc(pc, "invalid variable %u\n", v);
9703 			break;
9704 		case DIF_OP_LDLS:
9705 		case DIF_OP_STLS:
9706 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
9707 				err += efunc(pc, "invalid variable %u\n", v);
9708 			break;
9709 		default:
9710 			break;
9711 		}
9712 	}
9713 
9714 	return (err);
9715 }
9716 
9717 /*
9718  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9719  * are much more constrained than normal DIFOs.  Specifically, they may
9720  * not:
9721  *
9722  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9723  *    miscellaneous string routines
9724  * 2. Access DTrace variables other than the args[] array, and the
9725  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9726  * 3. Have thread-local variables.
9727  * 4. Have dynamic variables.
9728  */
9729 static int
dtrace_difo_validate_helper(dtrace_difo_t * dp)9730 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9731 {
9732 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9733 	int err = 0;
9734 	uint_t pc;
9735 
9736 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9737 		dif_instr_t instr = dp->dtdo_buf[pc];
9738 
9739 		uint_t v = DIF_INSTR_VAR(instr);
9740 		uint_t subr = DIF_INSTR_SUBR(instr);
9741 		uint_t op = DIF_INSTR_OP(instr);
9742 
9743 		switch (op) {
9744 		case DIF_OP_OR:
9745 		case DIF_OP_XOR:
9746 		case DIF_OP_AND:
9747 		case DIF_OP_SLL:
9748 		case DIF_OP_SRL:
9749 		case DIF_OP_SRA:
9750 		case DIF_OP_SUB:
9751 		case DIF_OP_ADD:
9752 		case DIF_OP_MUL:
9753 		case DIF_OP_SDIV:
9754 		case DIF_OP_UDIV:
9755 		case DIF_OP_SREM:
9756 		case DIF_OP_UREM:
9757 		case DIF_OP_COPYS:
9758 		case DIF_OP_NOT:
9759 		case DIF_OP_MOV:
9760 		case DIF_OP_RLDSB:
9761 		case DIF_OP_RLDSH:
9762 		case DIF_OP_RLDSW:
9763 		case DIF_OP_RLDUB:
9764 		case DIF_OP_RLDUH:
9765 		case DIF_OP_RLDUW:
9766 		case DIF_OP_RLDX:
9767 		case DIF_OP_ULDSB:
9768 		case DIF_OP_ULDSH:
9769 		case DIF_OP_ULDSW:
9770 		case DIF_OP_ULDUB:
9771 		case DIF_OP_ULDUH:
9772 		case DIF_OP_ULDUW:
9773 		case DIF_OP_ULDX:
9774 		case DIF_OP_STB:
9775 		case DIF_OP_STH:
9776 		case DIF_OP_STW:
9777 		case DIF_OP_STX:
9778 		case DIF_OP_ALLOCS:
9779 		case DIF_OP_CMP:
9780 		case DIF_OP_SCMP:
9781 		case DIF_OP_TST:
9782 		case DIF_OP_BA:
9783 		case DIF_OP_BE:
9784 		case DIF_OP_BNE:
9785 		case DIF_OP_BG:
9786 		case DIF_OP_BGU:
9787 		case DIF_OP_BGE:
9788 		case DIF_OP_BGEU:
9789 		case DIF_OP_BL:
9790 		case DIF_OP_BLU:
9791 		case DIF_OP_BLE:
9792 		case DIF_OP_BLEU:
9793 		case DIF_OP_RET:
9794 		case DIF_OP_NOP:
9795 		case DIF_OP_POPTS:
9796 		case DIF_OP_FLUSHTS:
9797 		case DIF_OP_SETX:
9798 		case DIF_OP_SETS:
9799 		case DIF_OP_LDGA:
9800 		case DIF_OP_LDLS:
9801 		case DIF_OP_STGS:
9802 		case DIF_OP_STLS:
9803 		case DIF_OP_PUSHTR:
9804 		case DIF_OP_PUSHTV:
9805 			break;
9806 
9807 		case DIF_OP_LDGS:
9808 			if (v >= DIF_VAR_OTHER_UBASE)
9809 				break;
9810 
9811 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9812 				break;
9813 
9814 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9815 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9816 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9817 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9818 				break;
9819 
9820 			err += efunc(pc, "illegal variable %u\n", v);
9821 			break;
9822 
9823 		case DIF_OP_LDTA:
9824 			if (v < DIF_VAR_OTHER_UBASE) {
9825 				err += efunc(pc, "illegal variable load\n");
9826 				break;
9827 			}
9828 			/* FALLTHROUGH */
9829 		case DIF_OP_LDTS:
9830 		case DIF_OP_LDGAA:
9831 		case DIF_OP_LDTAA:
9832 			err += efunc(pc, "illegal dynamic variable load\n");
9833 			break;
9834 
9835 		case DIF_OP_STGA:
9836 			if (v < DIF_VAR_OTHER_UBASE) {
9837 				err += efunc(pc, "illegal variable store\n");
9838 				break;
9839 			}
9840 			/* FALLTHROUGH */
9841 		case DIF_OP_STTS:
9842 		case DIF_OP_STGAA:
9843 		case DIF_OP_STTAA:
9844 			err += efunc(pc, "illegal dynamic variable store\n");
9845 			break;
9846 
9847 		case DIF_OP_CALL:
9848 			if (subr == DIF_SUBR_ALLOCA ||
9849 			    subr == DIF_SUBR_BCOPY ||
9850 			    subr == DIF_SUBR_COPYIN ||
9851 			    subr == DIF_SUBR_COPYINTO ||
9852 			    subr == DIF_SUBR_COPYINSTR ||
9853 			    subr == DIF_SUBR_INDEX ||
9854 			    subr == DIF_SUBR_INET_NTOA ||
9855 			    subr == DIF_SUBR_INET_NTOA6 ||
9856 			    subr == DIF_SUBR_INET_NTOP ||
9857 			    subr == DIF_SUBR_JSON ||
9858 			    subr == DIF_SUBR_LLTOSTR ||
9859 			    subr == DIF_SUBR_STRTOLL ||
9860 			    subr == DIF_SUBR_RINDEX ||
9861 			    subr == DIF_SUBR_STRCHR ||
9862 			    subr == DIF_SUBR_STRJOIN ||
9863 			    subr == DIF_SUBR_STRRCHR ||
9864 			    subr == DIF_SUBR_STRSTR ||
9865 			    subr == DIF_SUBR_HTONS ||
9866 			    subr == DIF_SUBR_HTONL ||
9867 			    subr == DIF_SUBR_HTONLL ||
9868 			    subr == DIF_SUBR_NTOHS ||
9869 			    subr == DIF_SUBR_NTOHL ||
9870 			    subr == DIF_SUBR_NTOHLL)
9871 				break;
9872 
9873 			err += efunc(pc, "invalid subr %u\n", subr);
9874 			break;
9875 
9876 		default:
9877 			err += efunc(pc, "invalid opcode %u\n",
9878 			    DIF_INSTR_OP(instr));
9879 		}
9880 	}
9881 
9882 	return (err);
9883 }
9884 
9885 /*
9886  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9887  * basis; 0 if not.
9888  */
9889 static int
dtrace_difo_cacheable(dtrace_difo_t * dp)9890 dtrace_difo_cacheable(dtrace_difo_t *dp)
9891 {
9892 	int i;
9893 
9894 	if (dp == NULL)
9895 		return (0);
9896 
9897 	for (i = 0; i < dp->dtdo_varlen; i++) {
9898 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9899 
9900 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9901 			continue;
9902 
9903 		switch (v->dtdv_id) {
9904 		case DIF_VAR_CURTHREAD:
9905 		case DIF_VAR_PID:
9906 		case DIF_VAR_TID:
9907 		case DIF_VAR_EXECNAME:
9908 		case DIF_VAR_ZONENAME:
9909 			break;
9910 
9911 		default:
9912 			return (0);
9913 		}
9914 	}
9915 
9916 	/*
9917 	 * This DIF object may be cacheable.  Now we need to look for any
9918 	 * array loading instructions, any memory loading instructions, or
9919 	 * any stores to thread-local variables.
9920 	 */
9921 	for (i = 0; i < dp->dtdo_len; i++) {
9922 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9923 
9924 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9925 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9926 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9927 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9928 			return (0);
9929 	}
9930 
9931 	return (1);
9932 }
9933 
9934 static void
dtrace_difo_hold(dtrace_difo_t * dp)9935 dtrace_difo_hold(dtrace_difo_t *dp)
9936 {
9937 	int i;
9938 
9939 	ASSERT(MUTEX_HELD(&dtrace_lock));
9940 
9941 	dp->dtdo_refcnt++;
9942 	ASSERT(dp->dtdo_refcnt != 0);
9943 
9944 	/*
9945 	 * We need to check this DIF object for references to the variable
9946 	 * DIF_VAR_VTIMESTAMP.
9947 	 */
9948 	for (i = 0; i < dp->dtdo_varlen; i++) {
9949 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9950 
9951 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9952 			continue;
9953 
9954 		if (dtrace_vtime_references++ == 0)
9955 			dtrace_vtime_enable();
9956 	}
9957 }
9958 
9959 /*
9960  * This routine calculates the dynamic variable chunksize for a given DIF
9961  * object.  The calculation is not fool-proof, and can probably be tricked by
9962  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9963  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9964  * if a dynamic variable size exceeds the chunksize.
9965  */
9966 static void
dtrace_difo_chunksize(dtrace_difo_t * dp,dtrace_vstate_t * vstate)9967 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9968 {
9969 	uint64_t sval;
9970 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9971 	const dif_instr_t *text = dp->dtdo_buf;
9972 	uint_t pc, srd = 0;
9973 	uint_t ttop = 0;
9974 	size_t size, ksize;
9975 	uint_t id, i;
9976 
9977 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9978 		dif_instr_t instr = text[pc];
9979 		uint_t op = DIF_INSTR_OP(instr);
9980 		uint_t rd = DIF_INSTR_RD(instr);
9981 		uint_t r1 = DIF_INSTR_R1(instr);
9982 		uint_t nkeys = 0;
9983 		uchar_t scope;
9984 
9985 		dtrace_key_t *key = tupregs;
9986 
9987 		switch (op) {
9988 		case DIF_OP_SETX:
9989 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9990 			srd = rd;
9991 			continue;
9992 
9993 		case DIF_OP_STTS:
9994 			key = &tupregs[DIF_DTR_NREGS];
9995 			key[0].dttk_size = 0;
9996 			key[1].dttk_size = 0;
9997 			nkeys = 2;
9998 			scope = DIFV_SCOPE_THREAD;
9999 			break;
10000 
10001 		case DIF_OP_STGAA:
10002 		case DIF_OP_STTAA:
10003 			nkeys = ttop;
10004 
10005 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10006 				key[nkeys++].dttk_size = 0;
10007 
10008 			key[nkeys++].dttk_size = 0;
10009 
10010 			if (op == DIF_OP_STTAA) {
10011 				scope = DIFV_SCOPE_THREAD;
10012 			} else {
10013 				scope = DIFV_SCOPE_GLOBAL;
10014 			}
10015 
10016 			break;
10017 
10018 		case DIF_OP_PUSHTR:
10019 			if (ttop == DIF_DTR_NREGS)
10020 				return;
10021 
10022 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10023 				/*
10024 				 * If the register for the size of the "pushtr"
10025 				 * is %r0 (or the value is 0) and the type is
10026 				 * a string, we'll use the system-wide default
10027 				 * string size.
10028 				 */
10029 				tupregs[ttop++].dttk_size =
10030 				    dtrace_strsize_default;
10031 			} else {
10032 				if (srd == 0)
10033 					return;
10034 
10035 				if (sval > LONG_MAX)
10036 					return;
10037 
10038 				tupregs[ttop++].dttk_size = sval;
10039 			}
10040 
10041 			break;
10042 
10043 		case DIF_OP_PUSHTV:
10044 			if (ttop == DIF_DTR_NREGS)
10045 				return;
10046 
10047 			tupregs[ttop++].dttk_size = 0;
10048 			break;
10049 
10050 		case DIF_OP_FLUSHTS:
10051 			ttop = 0;
10052 			break;
10053 
10054 		case DIF_OP_POPTS:
10055 			if (ttop != 0)
10056 				ttop--;
10057 			break;
10058 		}
10059 
10060 		sval = 0;
10061 		srd = 0;
10062 
10063 		if (nkeys == 0)
10064 			continue;
10065 
10066 		/*
10067 		 * We have a dynamic variable allocation; calculate its size.
10068 		 */
10069 		for (ksize = 0, i = 0; i < nkeys; i++)
10070 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10071 
10072 		size = sizeof (dtrace_dynvar_t);
10073 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10074 		size += ksize;
10075 
10076 		/*
10077 		 * Now we need to determine the size of the stored data.
10078 		 */
10079 		id = DIF_INSTR_VAR(instr);
10080 
10081 		for (i = 0; i < dp->dtdo_varlen; i++) {
10082 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10083 
10084 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10085 				size += v->dtdv_type.dtdt_size;
10086 				break;
10087 			}
10088 		}
10089 
10090 		if (i == dp->dtdo_varlen)
10091 			return;
10092 
10093 		/*
10094 		 * We have the size.  If this is larger than the chunk size
10095 		 * for our dynamic variable state, reset the chunk size.
10096 		 */
10097 		size = P2ROUNDUP(size, sizeof (uint64_t));
10098 
10099 		/*
10100 		 * Before setting the chunk size, check that we're not going
10101 		 * to set it to a negative value...
10102 		 */
10103 		if (size > LONG_MAX)
10104 			return;
10105 
10106 		/*
10107 		 * ...and make certain that we didn't badly overflow.
10108 		 */
10109 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10110 			return;
10111 
10112 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10113 			vstate->dtvs_dynvars.dtds_chunksize = size;
10114 	}
10115 }
10116 
10117 static void
dtrace_difo_init(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10118 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10119 {
10120 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10121 	uint_t id;
10122 
10123 	ASSERT(MUTEX_HELD(&dtrace_lock));
10124 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10125 
10126 	for (i = 0; i < dp->dtdo_varlen; i++) {
10127 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10128 		dtrace_statvar_t *svar, ***svarp;
10129 		size_t dsize = 0;
10130 		uint8_t scope = v->dtdv_scope;
10131 		int *np;
10132 
10133 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10134 			continue;
10135 
10136 		id -= DIF_VAR_OTHER_UBASE;
10137 
10138 		switch (scope) {
10139 		case DIFV_SCOPE_THREAD:
10140 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10141 				dtrace_difv_t *tlocals;
10142 
10143 				if ((ntlocals = (otlocals << 1)) == 0)
10144 					ntlocals = 1;
10145 
10146 				osz = otlocals * sizeof (dtrace_difv_t);
10147 				nsz = ntlocals * sizeof (dtrace_difv_t);
10148 
10149 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10150 
10151 				if (osz != 0) {
10152 					bcopy(vstate->dtvs_tlocals,
10153 					    tlocals, osz);
10154 					kmem_free(vstate->dtvs_tlocals, osz);
10155 				}
10156 
10157 				vstate->dtvs_tlocals = tlocals;
10158 				vstate->dtvs_ntlocals = ntlocals;
10159 			}
10160 
10161 			vstate->dtvs_tlocals[id] = *v;
10162 			continue;
10163 
10164 		case DIFV_SCOPE_LOCAL:
10165 			np = &vstate->dtvs_nlocals;
10166 			svarp = &vstate->dtvs_locals;
10167 
10168 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10169 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10170 				    sizeof (uint64_t));
10171 			else
10172 				dsize = NCPU * sizeof (uint64_t);
10173 
10174 			break;
10175 
10176 		case DIFV_SCOPE_GLOBAL:
10177 			np = &vstate->dtvs_nglobals;
10178 			svarp = &vstate->dtvs_globals;
10179 
10180 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10181 				dsize = v->dtdv_type.dtdt_size +
10182 				    sizeof (uint64_t);
10183 
10184 			break;
10185 
10186 		default:
10187 			ASSERT(0);
10188 		}
10189 
10190 		while (id >= (oldsvars = *np)) {
10191 			dtrace_statvar_t **statics;
10192 			int newsvars, oldsize, newsize;
10193 
10194 			if ((newsvars = (oldsvars << 1)) == 0)
10195 				newsvars = 1;
10196 
10197 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10198 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10199 
10200 			statics = kmem_zalloc(newsize, KM_SLEEP);
10201 
10202 			if (oldsize != 0) {
10203 				bcopy(*svarp, statics, oldsize);
10204 				kmem_free(*svarp, oldsize);
10205 			}
10206 
10207 			*svarp = statics;
10208 			*np = newsvars;
10209 		}
10210 
10211 		if ((svar = (*svarp)[id]) == NULL) {
10212 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10213 			svar->dtsv_var = *v;
10214 
10215 			if ((svar->dtsv_size = dsize) != 0) {
10216 				svar->dtsv_data = (uint64_t)(uintptr_t)
10217 				    kmem_zalloc(dsize, KM_SLEEP);
10218 			}
10219 
10220 			(*svarp)[id] = svar;
10221 		}
10222 
10223 		svar->dtsv_refcnt++;
10224 	}
10225 
10226 	dtrace_difo_chunksize(dp, vstate);
10227 	dtrace_difo_hold(dp);
10228 }
10229 
10230 static dtrace_difo_t *
dtrace_difo_duplicate(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10231 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10232 {
10233 	dtrace_difo_t *new;
10234 	size_t sz;
10235 
10236 	ASSERT(dp->dtdo_buf != NULL);
10237 	ASSERT(dp->dtdo_refcnt != 0);
10238 
10239 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10240 
10241 	ASSERT(dp->dtdo_buf != NULL);
10242 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10243 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10244 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10245 	new->dtdo_len = dp->dtdo_len;
10246 
10247 	if (dp->dtdo_strtab != NULL) {
10248 		ASSERT(dp->dtdo_strlen != 0);
10249 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10250 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10251 		new->dtdo_strlen = dp->dtdo_strlen;
10252 	}
10253 
10254 	if (dp->dtdo_inttab != NULL) {
10255 		ASSERT(dp->dtdo_intlen != 0);
10256 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10257 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10258 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10259 		new->dtdo_intlen = dp->dtdo_intlen;
10260 	}
10261 
10262 	if (dp->dtdo_vartab != NULL) {
10263 		ASSERT(dp->dtdo_varlen != 0);
10264 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10265 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10266 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10267 		new->dtdo_varlen = dp->dtdo_varlen;
10268 	}
10269 
10270 	dtrace_difo_init(new, vstate);
10271 	return (new);
10272 }
10273 
10274 static void
dtrace_difo_destroy(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10275 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10276 {
10277 	int i;
10278 
10279 	ASSERT(dp->dtdo_refcnt == 0);
10280 
10281 	for (i = 0; i < dp->dtdo_varlen; i++) {
10282 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10283 		dtrace_statvar_t *svar, **svarp;
10284 		uint_t id;
10285 		uint8_t scope = v->dtdv_scope;
10286 		int *np;
10287 
10288 		switch (scope) {
10289 		case DIFV_SCOPE_THREAD:
10290 			continue;
10291 
10292 		case DIFV_SCOPE_LOCAL:
10293 			np = &vstate->dtvs_nlocals;
10294 			svarp = vstate->dtvs_locals;
10295 			break;
10296 
10297 		case DIFV_SCOPE_GLOBAL:
10298 			np = &vstate->dtvs_nglobals;
10299 			svarp = vstate->dtvs_globals;
10300 			break;
10301 
10302 		default:
10303 			ASSERT(0);
10304 		}
10305 
10306 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10307 			continue;
10308 
10309 		id -= DIF_VAR_OTHER_UBASE;
10310 		ASSERT(id < *np);
10311 
10312 		svar = svarp[id];
10313 		ASSERT(svar != NULL);
10314 		ASSERT(svar->dtsv_refcnt > 0);
10315 
10316 		if (--svar->dtsv_refcnt > 0)
10317 			continue;
10318 
10319 		if (svar->dtsv_size != 0) {
10320 			ASSERT(svar->dtsv_data != 0);
10321 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10322 			    svar->dtsv_size);
10323 		}
10324 
10325 		kmem_free(svar, sizeof (dtrace_statvar_t));
10326 		svarp[id] = NULL;
10327 	}
10328 
10329 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10330 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10331 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10332 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10333 
10334 	kmem_free(dp, sizeof (dtrace_difo_t));
10335 }
10336 
10337 static void
dtrace_difo_release(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10338 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10339 {
10340 	int i;
10341 
10342 	ASSERT(MUTEX_HELD(&dtrace_lock));
10343 	ASSERT(dp->dtdo_refcnt != 0);
10344 
10345 	for (i = 0; i < dp->dtdo_varlen; i++) {
10346 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10347 
10348 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10349 			continue;
10350 
10351 		ASSERT(dtrace_vtime_references > 0);
10352 		if (--dtrace_vtime_references == 0)
10353 			dtrace_vtime_disable();
10354 	}
10355 
10356 	if (--dp->dtdo_refcnt == 0)
10357 		dtrace_difo_destroy(dp, vstate);
10358 }
10359 
10360 /*
10361  * DTrace Format Functions
10362  */
10363 static uint16_t
dtrace_format_add(dtrace_state_t * state,char * str)10364 dtrace_format_add(dtrace_state_t *state, char *str)
10365 {
10366 	char *fmt, **new;
10367 	uint16_t ndx, len = strlen(str) + 1;
10368 
10369 	fmt = kmem_zalloc(len, KM_SLEEP);
10370 	bcopy(str, fmt, len);
10371 
10372 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10373 		if (state->dts_formats[ndx] == NULL) {
10374 			state->dts_formats[ndx] = fmt;
10375 			return (ndx + 1);
10376 		}
10377 	}
10378 
10379 	if (state->dts_nformats == USHRT_MAX) {
10380 		/*
10381 		 * This is only likely if a denial-of-service attack is being
10382 		 * attempted.  As such, it's okay to fail silently here.
10383 		 */
10384 		kmem_free(fmt, len);
10385 		return (0);
10386 	}
10387 
10388 	/*
10389 	 * For simplicity, we always resize the formats array to be exactly the
10390 	 * number of formats.
10391 	 */
10392 	ndx = state->dts_nformats++;
10393 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10394 
10395 	if (state->dts_formats != NULL) {
10396 		ASSERT(ndx != 0);
10397 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10398 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10399 	}
10400 
10401 	state->dts_formats = new;
10402 	state->dts_formats[ndx] = fmt;
10403 
10404 	return (ndx + 1);
10405 }
10406 
10407 static void
dtrace_format_remove(dtrace_state_t * state,uint16_t format)10408 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10409 {
10410 	char *fmt;
10411 
10412 	ASSERT(state->dts_formats != NULL);
10413 	ASSERT(format <= state->dts_nformats);
10414 	ASSERT(state->dts_formats[format - 1] != NULL);
10415 
10416 	fmt = state->dts_formats[format - 1];
10417 	kmem_free(fmt, strlen(fmt) + 1);
10418 	state->dts_formats[format - 1] = NULL;
10419 }
10420 
10421 static void
dtrace_format_destroy(dtrace_state_t * state)10422 dtrace_format_destroy(dtrace_state_t *state)
10423 {
10424 	int i;
10425 
10426 	if (state->dts_nformats == 0) {
10427 		ASSERT(state->dts_formats == NULL);
10428 		return;
10429 	}
10430 
10431 	ASSERT(state->dts_formats != NULL);
10432 
10433 	for (i = 0; i < state->dts_nformats; i++) {
10434 		char *fmt = state->dts_formats[i];
10435 
10436 		if (fmt == NULL)
10437 			continue;
10438 
10439 		kmem_free(fmt, strlen(fmt) + 1);
10440 	}
10441 
10442 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10443 	state->dts_nformats = 0;
10444 	state->dts_formats = NULL;
10445 }
10446 
10447 /*
10448  * DTrace Predicate Functions
10449  */
10450 static dtrace_predicate_t *
dtrace_predicate_create(dtrace_difo_t * dp)10451 dtrace_predicate_create(dtrace_difo_t *dp)
10452 {
10453 	dtrace_predicate_t *pred;
10454 
10455 	ASSERT(MUTEX_HELD(&dtrace_lock));
10456 	ASSERT(dp->dtdo_refcnt != 0);
10457 
10458 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10459 	pred->dtp_difo = dp;
10460 	pred->dtp_refcnt = 1;
10461 
10462 	if (!dtrace_difo_cacheable(dp))
10463 		return (pred);
10464 
10465 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10466 		/*
10467 		 * This is only theoretically possible -- we have had 2^32
10468 		 * cacheable predicates on this machine.  We cannot allow any
10469 		 * more predicates to become cacheable:  as unlikely as it is,
10470 		 * there may be a thread caching a (now stale) predicate cache
10471 		 * ID. (N.B.: the temptation is being successfully resisted to
10472 		 * have this cmn_err() "Holy shit -- we executed this code!")
10473 		 */
10474 		return (pred);
10475 	}
10476 
10477 	pred->dtp_cacheid = dtrace_predcache_id++;
10478 
10479 	return (pred);
10480 }
10481 
10482 static void
dtrace_predicate_hold(dtrace_predicate_t * pred)10483 dtrace_predicate_hold(dtrace_predicate_t *pred)
10484 {
10485 	ASSERT(MUTEX_HELD(&dtrace_lock));
10486 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10487 	ASSERT(pred->dtp_refcnt > 0);
10488 
10489 	pred->dtp_refcnt++;
10490 }
10491 
10492 static void
dtrace_predicate_release(dtrace_predicate_t * pred,dtrace_vstate_t * vstate)10493 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10494 {
10495 	dtrace_difo_t *dp = pred->dtp_difo;
10496 
10497 	ASSERT(MUTEX_HELD(&dtrace_lock));
10498 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10499 	ASSERT(pred->dtp_refcnt > 0);
10500 
10501 	if (--pred->dtp_refcnt == 0) {
10502 		dtrace_difo_release(pred->dtp_difo, vstate);
10503 		kmem_free(pred, sizeof (dtrace_predicate_t));
10504 	}
10505 }
10506 
10507 /*
10508  * DTrace Action Description Functions
10509  */
10510 static dtrace_actdesc_t *
dtrace_actdesc_create(dtrace_actkind_t kind,uint32_t ntuple,uint64_t uarg,uint64_t arg)10511 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10512     uint64_t uarg, uint64_t arg)
10513 {
10514 	dtrace_actdesc_t *act;
10515 
10516 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
10517 	    arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
10518 
10519 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10520 	act->dtad_kind = kind;
10521 	act->dtad_ntuple = ntuple;
10522 	act->dtad_uarg = uarg;
10523 	act->dtad_arg = arg;
10524 	act->dtad_refcnt = 1;
10525 
10526 	return (act);
10527 }
10528 
10529 static void
dtrace_actdesc_hold(dtrace_actdesc_t * act)10530 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10531 {
10532 	ASSERT(act->dtad_refcnt >= 1);
10533 	act->dtad_refcnt++;
10534 }
10535 
10536 static void
dtrace_actdesc_release(dtrace_actdesc_t * act,dtrace_vstate_t * vstate)10537 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10538 {
10539 	dtrace_actkind_t kind = act->dtad_kind;
10540 	dtrace_difo_t *dp;
10541 
10542 	ASSERT(act->dtad_refcnt >= 1);
10543 
10544 	if (--act->dtad_refcnt != 0)
10545 		return;
10546 
10547 	if ((dp = act->dtad_difo) != NULL)
10548 		dtrace_difo_release(dp, vstate);
10549 
10550 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10551 		char *str = (char *)(uintptr_t)act->dtad_arg;
10552 
10553 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10554 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10555 
10556 		if (str != NULL)
10557 			kmem_free(str, strlen(str) + 1);
10558 	}
10559 
10560 	kmem_free(act, sizeof (dtrace_actdesc_t));
10561 }
10562 
10563 /*
10564  * DTrace ECB Functions
10565  */
10566 static dtrace_ecb_t *
dtrace_ecb_add(dtrace_state_t * state,dtrace_probe_t * probe)10567 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10568 {
10569 	dtrace_ecb_t *ecb;
10570 	dtrace_epid_t epid;
10571 
10572 	ASSERT(MUTEX_HELD(&dtrace_lock));
10573 
10574 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10575 	ecb->dte_predicate = NULL;
10576 	ecb->dte_probe = probe;
10577 
10578 	/*
10579 	 * The default size is the size of the default action: recording
10580 	 * the header.
10581 	 */
10582 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10583 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10584 
10585 	epid = state->dts_epid++;
10586 
10587 	if (epid - 1 >= state->dts_necbs) {
10588 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10589 		int necbs = state->dts_necbs << 1;
10590 
10591 		ASSERT(epid == state->dts_necbs + 1);
10592 
10593 		if (necbs == 0) {
10594 			ASSERT(oecbs == NULL);
10595 			necbs = 1;
10596 		}
10597 
10598 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10599 
10600 		if (oecbs != NULL)
10601 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10602 
10603 		dtrace_membar_producer();
10604 		state->dts_ecbs = ecbs;
10605 
10606 		if (oecbs != NULL) {
10607 			/*
10608 			 * If this state is active, we must dtrace_sync()
10609 			 * before we can free the old dts_ecbs array:  we're
10610 			 * coming in hot, and there may be active ring
10611 			 * buffer processing (which indexes into the dts_ecbs
10612 			 * array) on another CPU.
10613 			 */
10614 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10615 				dtrace_sync();
10616 
10617 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10618 		}
10619 
10620 		dtrace_membar_producer();
10621 		state->dts_necbs = necbs;
10622 	}
10623 
10624 	ecb->dte_state = state;
10625 
10626 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
10627 	dtrace_membar_producer();
10628 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10629 
10630 	return (ecb);
10631 }
10632 
10633 static int
dtrace_ecb_enable(dtrace_ecb_t * ecb)10634 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10635 {
10636 	dtrace_probe_t *probe = ecb->dte_probe;
10637 
10638 	ASSERT(MUTEX_HELD(&cpu_lock));
10639 	ASSERT(MUTEX_HELD(&dtrace_lock));
10640 	ASSERT(ecb->dte_next == NULL);
10641 
10642 	if (probe == NULL) {
10643 		/*
10644 		 * This is the NULL probe -- there's nothing to do.
10645 		 */
10646 		return (0);
10647 	}
10648 
10649 	if (probe->dtpr_ecb == NULL) {
10650 		dtrace_provider_t *prov = probe->dtpr_provider;
10651 
10652 		/*
10653 		 * We're the first ECB on this probe.
10654 		 */
10655 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10656 
10657 		if (ecb->dte_predicate != NULL)
10658 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10659 
10660 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10661 		    probe->dtpr_id, probe->dtpr_arg));
10662 	} else {
10663 		/*
10664 		 * This probe is already active.  Swing the last pointer to
10665 		 * point to the new ECB and invalidate the predicate cache.
10666 		 * (It will be up to the caller to call dtrace_sync() to
10667 		 * assure that all CPUs have seen the change.)
10668 		 */
10669 		ASSERT(probe->dtpr_ecb_last != NULL);
10670 		probe->dtpr_ecb_last->dte_next = ecb;
10671 		probe->dtpr_ecb_last = ecb;
10672 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10673 		return (0);
10674 	}
10675 }
10676 
10677 static int
dtrace_ecb_resize(dtrace_ecb_t * ecb)10678 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10679 {
10680 	dtrace_action_t *act;
10681 	uint32_t curneeded = UINT32_MAX;
10682 	uint32_t aggbase = UINT32_MAX;
10683 
10684 	/*
10685 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
10686 	 * we always record it first.)
10687 	 */
10688 	ecb->dte_size = sizeof (dtrace_rechdr_t);
10689 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10690 
10691 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10692 		dtrace_recdesc_t *rec = &act->dta_rec;
10693 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10694 
10695 		ecb->dte_alignment = MAX(ecb->dte_alignment,
10696 		    rec->dtrd_alignment);
10697 
10698 		if (DTRACEACT_ISAGG(act->dta_kind)) {
10699 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10700 
10701 			ASSERT(rec->dtrd_size != 0);
10702 			ASSERT(agg->dtag_first != NULL);
10703 			ASSERT(act->dta_prev->dta_intuple);
10704 			ASSERT(aggbase != UINT32_MAX);
10705 			ASSERT(curneeded != UINT32_MAX);
10706 
10707 			agg->dtag_base = aggbase;
10708 
10709 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10710 			rec->dtrd_offset = curneeded;
10711 			if (curneeded + rec->dtrd_size < curneeded)
10712 				return (EINVAL);
10713 			curneeded += rec->dtrd_size;
10714 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10715 
10716 			aggbase = UINT32_MAX;
10717 			curneeded = UINT32_MAX;
10718 		} else if (act->dta_intuple) {
10719 			if (curneeded == UINT32_MAX) {
10720 				/*
10721 				 * This is the first record in a tuple.  Align
10722 				 * curneeded to be at offset 4 in an 8-byte
10723 				 * aligned block.
10724 				 */
10725 				ASSERT(act->dta_prev == NULL ||
10726 				    !act->dta_prev->dta_intuple);
10727 				ASSERT3U(aggbase, ==, UINT32_MAX);
10728 				curneeded = P2PHASEUP(ecb->dte_size,
10729 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10730 
10731 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10732 				ASSERT(IS_P2ALIGNED(aggbase,
10733 				    sizeof (uint64_t)));
10734 			}
10735 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10736 			rec->dtrd_offset = curneeded;
10737 			if (curneeded + rec->dtrd_size < curneeded)
10738 				return (EINVAL);
10739 			curneeded += rec->dtrd_size;
10740 		} else {
10741 			/* tuples must be followed by an aggregation */
10742 			ASSERT(act->dta_prev == NULL ||
10743 			    !act->dta_prev->dta_intuple);
10744 
10745 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10746 			    rec->dtrd_alignment);
10747 			rec->dtrd_offset = ecb->dte_size;
10748 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
10749 				return (EINVAL);
10750 			ecb->dte_size += rec->dtrd_size;
10751 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10752 		}
10753 	}
10754 
10755 	if ((act = ecb->dte_action) != NULL &&
10756 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10757 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10758 		/*
10759 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10760 		 * actions store no data; set the size to 0.
10761 		 */
10762 		ecb->dte_size = 0;
10763 	}
10764 
10765 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10766 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10767 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10768 	    ecb->dte_needed);
10769 	return (0);
10770 }
10771 
10772 static dtrace_action_t *
dtrace_ecb_aggregation_create(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)10773 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10774 {
10775 	dtrace_aggregation_t *agg;
10776 	size_t size = sizeof (uint64_t);
10777 	int ntuple = desc->dtad_ntuple;
10778 	dtrace_action_t *act;
10779 	dtrace_recdesc_t *frec;
10780 	dtrace_aggid_t aggid;
10781 	dtrace_state_t *state = ecb->dte_state;
10782 
10783 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10784 	agg->dtag_ecb = ecb;
10785 
10786 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10787 
10788 	switch (desc->dtad_kind) {
10789 	case DTRACEAGG_MIN:
10790 		agg->dtag_initial = INT64_MAX;
10791 		agg->dtag_aggregate = dtrace_aggregate_min;
10792 		break;
10793 
10794 	case DTRACEAGG_MAX:
10795 		agg->dtag_initial = INT64_MIN;
10796 		agg->dtag_aggregate = dtrace_aggregate_max;
10797 		break;
10798 
10799 	case DTRACEAGG_COUNT:
10800 		agg->dtag_aggregate = dtrace_aggregate_count;
10801 		break;
10802 
10803 	case DTRACEAGG_QUANTIZE:
10804 		agg->dtag_aggregate = dtrace_aggregate_quantize;
10805 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10806 		    sizeof (uint64_t);
10807 		break;
10808 
10809 	case DTRACEAGG_LQUANTIZE: {
10810 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10811 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10812 
10813 		agg->dtag_initial = desc->dtad_arg;
10814 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10815 
10816 		if (step == 0 || levels == 0)
10817 			goto err;
10818 
10819 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10820 		break;
10821 	}
10822 
10823 	case DTRACEAGG_LLQUANTIZE: {
10824 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10825 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10826 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10827 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10828 		int64_t v;
10829 
10830 		agg->dtag_initial = desc->dtad_arg;
10831 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10832 
10833 		if (factor < 2 || low >= high || nsteps < factor)
10834 			goto err;
10835 
10836 		/*
10837 		 * Now check that the number of steps evenly divides a power
10838 		 * of the factor.  (This assures both integer bucket size and
10839 		 * linearity within each magnitude.)
10840 		 */
10841 		for (v = factor; v < nsteps; v *= factor)
10842 			continue;
10843 
10844 		if ((v % nsteps) || (nsteps % factor))
10845 			goto err;
10846 
10847 		size = (dtrace_aggregate_llquantize_bucket(factor,
10848 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10849 		break;
10850 	}
10851 
10852 	case DTRACEAGG_AVG:
10853 		agg->dtag_aggregate = dtrace_aggregate_avg;
10854 		size = sizeof (uint64_t) * 2;
10855 		break;
10856 
10857 	case DTRACEAGG_STDDEV:
10858 		agg->dtag_aggregate = dtrace_aggregate_stddev;
10859 		size = sizeof (uint64_t) * 4;
10860 		break;
10861 
10862 	case DTRACEAGG_SUM:
10863 		agg->dtag_aggregate = dtrace_aggregate_sum;
10864 		break;
10865 
10866 	default:
10867 		goto err;
10868 	}
10869 
10870 	agg->dtag_action.dta_rec.dtrd_size = size;
10871 
10872 	if (ntuple == 0)
10873 		goto err;
10874 
10875 	/*
10876 	 * We must make sure that we have enough actions for the n-tuple.
10877 	 */
10878 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10879 		if (DTRACEACT_ISAGG(act->dta_kind))
10880 			break;
10881 
10882 		if (--ntuple == 0) {
10883 			/*
10884 			 * This is the action with which our n-tuple begins.
10885 			 */
10886 			agg->dtag_first = act;
10887 			goto success;
10888 		}
10889 	}
10890 
10891 	/*
10892 	 * This n-tuple is short by ntuple elements.  Return failure.
10893 	 */
10894 	ASSERT(ntuple != 0);
10895 err:
10896 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10897 	return (NULL);
10898 
10899 success:
10900 	/*
10901 	 * If the last action in the tuple has a size of zero, it's actually
10902 	 * an expression argument for the aggregating action.
10903 	 */
10904 	ASSERT(ecb->dte_action_last != NULL);
10905 	act = ecb->dte_action_last;
10906 
10907 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10908 		ASSERT(act->dta_difo != NULL);
10909 
10910 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10911 			agg->dtag_hasarg = 1;
10912 	}
10913 
10914 	/*
10915 	 * We need to allocate an id for this aggregation.
10916 	 */
10917 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10918 	    VM_BESTFIT | VM_SLEEP);
10919 
10920 	if (aggid - 1 >= state->dts_naggregations) {
10921 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10922 		dtrace_aggregation_t **aggs;
10923 		int naggs = state->dts_naggregations << 1;
10924 		int onaggs = state->dts_naggregations;
10925 
10926 		ASSERT(aggid == state->dts_naggregations + 1);
10927 
10928 		if (naggs == 0) {
10929 			ASSERT(oaggs == NULL);
10930 			naggs = 1;
10931 		}
10932 
10933 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10934 
10935 		if (oaggs != NULL) {
10936 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10937 			kmem_free(oaggs, onaggs * sizeof (*aggs));
10938 		}
10939 
10940 		state->dts_aggregations = aggs;
10941 		state->dts_naggregations = naggs;
10942 	}
10943 
10944 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10945 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10946 
10947 	frec = &agg->dtag_first->dta_rec;
10948 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10949 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10950 
10951 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10952 		ASSERT(!act->dta_intuple);
10953 		act->dta_intuple = 1;
10954 	}
10955 
10956 	return (&agg->dtag_action);
10957 }
10958 
10959 static void
dtrace_ecb_aggregation_destroy(dtrace_ecb_t * ecb,dtrace_action_t * act)10960 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10961 {
10962 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10963 	dtrace_state_t *state = ecb->dte_state;
10964 	dtrace_aggid_t aggid = agg->dtag_id;
10965 
10966 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10967 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10968 
10969 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10970 	state->dts_aggregations[aggid - 1] = NULL;
10971 
10972 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10973 }
10974 
10975 static int
dtrace_ecb_action_add(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)10976 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10977 {
10978 	dtrace_action_t *action, *last;
10979 	dtrace_difo_t *dp = desc->dtad_difo;
10980 	uint32_t size = 0, align = sizeof (uint8_t), mask;
10981 	uint16_t format = 0;
10982 	dtrace_recdesc_t *rec;
10983 	dtrace_state_t *state = ecb->dte_state;
10984 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10985 	uint64_t arg = desc->dtad_arg;
10986 
10987 	ASSERT(MUTEX_HELD(&dtrace_lock));
10988 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10989 
10990 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10991 		/*
10992 		 * If this is an aggregating action, there must be neither
10993 		 * a speculate nor a commit on the action chain.
10994 		 */
10995 		dtrace_action_t *act;
10996 
10997 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10998 			if (act->dta_kind == DTRACEACT_COMMIT)
10999 				return (EINVAL);
11000 
11001 			if (act->dta_kind == DTRACEACT_SPECULATE)
11002 				return (EINVAL);
11003 		}
11004 
11005 		action = dtrace_ecb_aggregation_create(ecb, desc);
11006 
11007 		if (action == NULL)
11008 			return (EINVAL);
11009 	} else {
11010 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11011 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11012 		    dp != NULL && dp->dtdo_destructive)) {
11013 			state->dts_destructive = 1;
11014 		}
11015 
11016 		switch (desc->dtad_kind) {
11017 		case DTRACEACT_PRINTF:
11018 		case DTRACEACT_PRINTA:
11019 		case DTRACEACT_SYSTEM:
11020 		case DTRACEACT_FREOPEN:
11021 		case DTRACEACT_DIFEXPR:
11022 			/*
11023 			 * We know that our arg is a string -- turn it into a
11024 			 * format.
11025 			 */
11026 			if (arg == 0) {
11027 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11028 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11029 				format = 0;
11030 			} else {
11031 				ASSERT(arg != 0);
11032 				ASSERT(arg > KERNELBASE);
11033 				format = dtrace_format_add(state,
11034 				    (char *)(uintptr_t)arg);
11035 			}
11036 
11037 			/*FALLTHROUGH*/
11038 		case DTRACEACT_LIBACT:
11039 		case DTRACEACT_TRACEMEM:
11040 		case DTRACEACT_TRACEMEM_DYNSIZE:
11041 			if (dp == NULL)
11042 				return (EINVAL);
11043 
11044 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11045 				break;
11046 
11047 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11048 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11049 					return (EINVAL);
11050 
11051 				size = opt[DTRACEOPT_STRSIZE];
11052 			}
11053 
11054 			break;
11055 
11056 		case DTRACEACT_STACK:
11057 			if ((nframes = arg) == 0) {
11058 				nframes = opt[DTRACEOPT_STACKFRAMES];
11059 				ASSERT(nframes > 0);
11060 				arg = nframes;
11061 			}
11062 
11063 			size = nframes * sizeof (pc_t);
11064 			break;
11065 
11066 		case DTRACEACT_JSTACK:
11067 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11068 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11069 
11070 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11071 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11072 
11073 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11074 
11075 			/*FALLTHROUGH*/
11076 		case DTRACEACT_USTACK:
11077 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11078 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11079 				strsize = DTRACE_USTACK_STRSIZE(arg);
11080 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11081 				ASSERT(nframes > 0);
11082 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11083 			}
11084 
11085 			/*
11086 			 * Save a slot for the pid.
11087 			 */
11088 			size = (nframes + 1) * sizeof (uint64_t);
11089 			size += DTRACE_USTACK_STRSIZE(arg);
11090 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11091 
11092 			break;
11093 
11094 		case DTRACEACT_SYM:
11095 		case DTRACEACT_MOD:
11096 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11097 			    sizeof (uint64_t)) ||
11098 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11099 				return (EINVAL);
11100 			break;
11101 
11102 		case DTRACEACT_USYM:
11103 		case DTRACEACT_UMOD:
11104 		case DTRACEACT_UADDR:
11105 			if (dp == NULL ||
11106 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11107 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11108 				return (EINVAL);
11109 
11110 			/*
11111 			 * We have a slot for the pid, plus a slot for the
11112 			 * argument.  To keep things simple (aligned with
11113 			 * bitness-neutral sizing), we store each as a 64-bit
11114 			 * quantity.
11115 			 */
11116 			size = 2 * sizeof (uint64_t);
11117 			break;
11118 
11119 		case DTRACEACT_STOP:
11120 		case DTRACEACT_BREAKPOINT:
11121 		case DTRACEACT_PANIC:
11122 			break;
11123 
11124 		case DTRACEACT_CHILL:
11125 		case DTRACEACT_DISCARD:
11126 		case DTRACEACT_RAISE:
11127 			if (dp == NULL)
11128 				return (EINVAL);
11129 			break;
11130 
11131 		case DTRACEACT_EXIT:
11132 			if (dp == NULL ||
11133 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11134 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11135 				return (EINVAL);
11136 			break;
11137 
11138 		case DTRACEACT_SPECULATE:
11139 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11140 				return (EINVAL);
11141 
11142 			if (dp == NULL)
11143 				return (EINVAL);
11144 
11145 			state->dts_speculates = 1;
11146 			break;
11147 
11148 		case DTRACEACT_COMMIT: {
11149 			dtrace_action_t *act = ecb->dte_action;
11150 
11151 			for (; act != NULL; act = act->dta_next) {
11152 				if (act->dta_kind == DTRACEACT_COMMIT)
11153 					return (EINVAL);
11154 			}
11155 
11156 			if (dp == NULL)
11157 				return (EINVAL);
11158 			break;
11159 		}
11160 
11161 		default:
11162 			return (EINVAL);
11163 		}
11164 
11165 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11166 			/*
11167 			 * If this is a data-storing action or a speculate,
11168 			 * we must be sure that there isn't a commit on the
11169 			 * action chain.
11170 			 */
11171 			dtrace_action_t *act = ecb->dte_action;
11172 
11173 			for (; act != NULL; act = act->dta_next) {
11174 				if (act->dta_kind == DTRACEACT_COMMIT)
11175 					return (EINVAL);
11176 			}
11177 		}
11178 
11179 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11180 		action->dta_rec.dtrd_size = size;
11181 	}
11182 
11183 	action->dta_refcnt = 1;
11184 	rec = &action->dta_rec;
11185 	size = rec->dtrd_size;
11186 
11187 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11188 		if (!(size & mask)) {
11189 			align = mask + 1;
11190 			break;
11191 		}
11192 	}
11193 
11194 	action->dta_kind = desc->dtad_kind;
11195 
11196 	if ((action->dta_difo = dp) != NULL)
11197 		dtrace_difo_hold(dp);
11198 
11199 	rec->dtrd_action = action->dta_kind;
11200 	rec->dtrd_arg = arg;
11201 	rec->dtrd_uarg = desc->dtad_uarg;
11202 	rec->dtrd_alignment = (uint16_t)align;
11203 	rec->dtrd_format = format;
11204 
11205 	if ((last = ecb->dte_action_last) != NULL) {
11206 		ASSERT(ecb->dte_action != NULL);
11207 		action->dta_prev = last;
11208 		last->dta_next = action;
11209 	} else {
11210 		ASSERT(ecb->dte_action == NULL);
11211 		ecb->dte_action = action;
11212 	}
11213 
11214 	ecb->dte_action_last = action;
11215 
11216 	return (0);
11217 }
11218 
11219 static void
dtrace_ecb_action_remove(dtrace_ecb_t * ecb)11220 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11221 {
11222 	dtrace_action_t *act = ecb->dte_action, *next;
11223 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11224 	dtrace_difo_t *dp;
11225 	uint16_t format;
11226 
11227 	if (act != NULL && act->dta_refcnt > 1) {
11228 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11229 		act->dta_refcnt--;
11230 	} else {
11231 		for (; act != NULL; act = next) {
11232 			next = act->dta_next;
11233 			ASSERT(next != NULL || act == ecb->dte_action_last);
11234 			ASSERT(act->dta_refcnt == 1);
11235 
11236 			if ((format = act->dta_rec.dtrd_format) != 0)
11237 				dtrace_format_remove(ecb->dte_state, format);
11238 
11239 			if ((dp = act->dta_difo) != NULL)
11240 				dtrace_difo_release(dp, vstate);
11241 
11242 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11243 				dtrace_ecb_aggregation_destroy(ecb, act);
11244 			} else {
11245 				kmem_free(act, sizeof (dtrace_action_t));
11246 			}
11247 		}
11248 	}
11249 
11250 	ecb->dte_action = NULL;
11251 	ecb->dte_action_last = NULL;
11252 	ecb->dte_size = 0;
11253 }
11254 
11255 static void
dtrace_ecb_disable(dtrace_ecb_t * ecb)11256 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11257 {
11258 	/*
11259 	 * We disable the ECB by removing it from its probe.
11260 	 */
11261 	dtrace_ecb_t *pecb, *prev = NULL;
11262 	dtrace_probe_t *probe = ecb->dte_probe;
11263 
11264 	ASSERT(MUTEX_HELD(&dtrace_lock));
11265 
11266 	if (probe == NULL) {
11267 		/*
11268 		 * This is the NULL probe; there is nothing to disable.
11269 		 */
11270 		return;
11271 	}
11272 
11273 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11274 		if (pecb == ecb)
11275 			break;
11276 		prev = pecb;
11277 	}
11278 
11279 	if (pecb == NULL) {
11280 		/*
11281 		 * This is okay:  it means that this ECB was never actually
11282 		 * enabled (that is, we are in the process of ripping our
11283 		 * state down sometime after creating ECBs but before enabling
11284 		 * them); we have nothing to do, so just return.
11285 		 */
11286 		return;
11287 	}
11288 
11289 	if (prev == NULL) {
11290 		probe->dtpr_ecb = ecb->dte_next;
11291 	} else {
11292 		prev->dte_next = ecb->dte_next;
11293 	}
11294 
11295 	if (ecb == probe->dtpr_ecb_last) {
11296 		ASSERT(ecb->dte_next == NULL);
11297 		probe->dtpr_ecb_last = prev;
11298 	}
11299 
11300 	if (probe->dtpr_ecb == NULL) {
11301 		/*
11302 		 * That was the last ECB on the probe; clear the predicate
11303 		 * cache ID for the probe and disable it.
11304 		 */
11305 		dtrace_provider_t *prov = probe->dtpr_provider;
11306 
11307 		ASSERT(ecb->dte_next == NULL);
11308 		ASSERT(probe->dtpr_ecb_last == NULL);
11309 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11310 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11311 		    probe->dtpr_id, probe->dtpr_arg);
11312 	} else {
11313 		/*
11314 		 * There is at least one ECB remaining on the probe.  If there
11315 		 * is _exactly_ one, set the probe's predicate cache ID to be
11316 		 * the predicate cache ID of the remaining ECB.
11317 		 */
11318 		ASSERT(probe->dtpr_ecb_last != NULL);
11319 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11320 
11321 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11322 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11323 
11324 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11325 
11326 			if (p != NULL)
11327 				probe->dtpr_predcache = p->dtp_cacheid;
11328 		}
11329 
11330 		ecb->dte_next = NULL;
11331 	}
11332 }
11333 
11334 /*
11335  * Destroy an ECB.  It's up to the caller to be sure that no CPU is still
11336  * seeing this ECB (i.e., by having issued a dtrace_sync() after having
11337  * disabled it).
11338  */
11339 static void
dtrace_ecb_destroy(dtrace_ecb_t * ecb)11340 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11341 {
11342 	dtrace_state_t *state = ecb->dte_state;
11343 	dtrace_vstate_t *vstate = &state->dts_vstate;
11344 	dtrace_predicate_t *pred;
11345 	dtrace_epid_t epid = ecb->dte_epid;
11346 
11347 	ASSERT(MUTEX_HELD(&dtrace_lock));
11348 	ASSERT(ecb->dte_next == NULL);
11349 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11350 
11351 	if ((pred = ecb->dte_predicate) != NULL)
11352 		dtrace_predicate_release(pred, vstate);
11353 
11354 	dtrace_ecb_action_remove(ecb);
11355 
11356 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11357 	state->dts_ecbs[epid - 1] = NULL;
11358 
11359 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11360 }
11361 
11362 static dtrace_ecb_t *
dtrace_ecb_create(dtrace_state_t * state,dtrace_probe_t * probe,dtrace_enabling_t * enab)11363 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11364     dtrace_enabling_t *enab)
11365 {
11366 	dtrace_ecb_t *ecb;
11367 	dtrace_predicate_t *pred;
11368 	dtrace_actdesc_t *act;
11369 	dtrace_provider_t *prov;
11370 	dtrace_ecbdesc_t *desc = enab->dten_current;
11371 
11372 	ASSERT(MUTEX_HELD(&dtrace_lock));
11373 	ASSERT(state != NULL);
11374 
11375 	ecb = dtrace_ecb_add(state, probe);
11376 	ecb->dte_uarg = desc->dted_uarg;
11377 
11378 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11379 		dtrace_predicate_hold(pred);
11380 		ecb->dte_predicate = pred;
11381 	}
11382 
11383 	if (probe != NULL) {
11384 		/*
11385 		 * If the provider shows more leg than the consumer is old
11386 		 * enough to see, we need to enable the appropriate implicit
11387 		 * predicate bits to prevent the ecb from activating at
11388 		 * revealing times.
11389 		 *
11390 		 * Providers specifying DTRACE_PRIV_USER at register time
11391 		 * are stating that they need the /proc-style privilege
11392 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11393 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11394 		 */
11395 		prov = probe->dtpr_provider;
11396 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11397 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11398 			ecb->dte_cond |= DTRACE_COND_OWNER;
11399 
11400 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11401 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11402 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11403 
11404 		/*
11405 		 * If the provider shows us kernel innards and the user
11406 		 * is lacking sufficient privilege, enable the
11407 		 * DTRACE_COND_USERMODE implicit predicate.
11408 		 */
11409 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11410 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11411 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11412 	}
11413 
11414 	if (dtrace_ecb_create_cache != NULL) {
11415 		/*
11416 		 * If we have a cached ecb, we'll use its action list instead
11417 		 * of creating our own (saving both time and space).
11418 		 */
11419 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11420 		dtrace_action_t *act = cached->dte_action;
11421 
11422 		if (act != NULL) {
11423 			ASSERT(act->dta_refcnt > 0);
11424 			act->dta_refcnt++;
11425 			ecb->dte_action = act;
11426 			ecb->dte_action_last = cached->dte_action_last;
11427 			ecb->dte_needed = cached->dte_needed;
11428 			ecb->dte_size = cached->dte_size;
11429 			ecb->dte_alignment = cached->dte_alignment;
11430 		}
11431 
11432 		return (ecb);
11433 	}
11434 
11435 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11436 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11437 			dtrace_ecb_destroy(ecb);
11438 			return (NULL);
11439 		}
11440 	}
11441 
11442 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11443 		dtrace_ecb_destroy(ecb);
11444 		return (NULL);
11445 	}
11446 
11447 	return (dtrace_ecb_create_cache = ecb);
11448 }
11449 
11450 static int
dtrace_ecb_create_enable(dtrace_probe_t * probe,void * arg)11451 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11452 {
11453 	dtrace_ecb_t *ecb;
11454 	dtrace_enabling_t *enab = arg;
11455 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11456 
11457 	ASSERT(state != NULL);
11458 
11459 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11460 		/*
11461 		 * This probe was created in a generation for which this
11462 		 * enabling has previously created ECBs; we don't want to
11463 		 * enable it again, so just kick out.
11464 		 */
11465 		return (DTRACE_MATCH_NEXT);
11466 	}
11467 
11468 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11469 		return (DTRACE_MATCH_DONE);
11470 
11471 	/*
11472 	 * If we can, we want to defer actually enabling the probe until
11473 	 * immediately before transitioning the state to be active: there is
11474 	 * still a lot of work to do before then (e.g., all per-state buffer
11475 	 * allocation), and for enablings with a heavy probe effect (e.g.,
11476 	 * enabling every FBT probe), that work can become debilitatingly slow
11477 	 * (and pointlessly so because the state isn't even active).
11478 	 *
11479 	 * So we default to not enabling our newly created ECB, with two
11480 	 * exceptions:
11481 	 *
11482 	 *  (1)	If the state is currently active, we need to enable the ECB
11483 	 *	immediately
11484 	 *
11485 	 *  (2)	If the probe is provided by DTrace itself, we choose to enable
11486 	 *	the ECB now to assure that we can easily determine our
11487 	 *	dts_reserve before allocating buffers.
11488 	 */
11489 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE ||
11490 	    (probe != NULL && probe->dtpr_provider == dtrace_provider)) {
11491 		if (dtrace_ecb_enable(ecb) < 0) {
11492 			return (DTRACE_MATCH_FAIL);
11493 		}
11494 
11495 		/*
11496 		 * As we have changed ECB state on potentially an active
11497 		 * consumer, issue a dtrace_sync() to assure that all CPUs
11498 		 * have seen it.
11499 		 */
11500 		dtrace_sync();
11501 	}
11502 
11503 	return (DTRACE_MATCH_NEXT);
11504 }
11505 
11506 static dtrace_ecb_t *
dtrace_epid2ecb(dtrace_state_t * state,dtrace_epid_t id)11507 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11508 {
11509 	dtrace_ecb_t *ecb;
11510 
11511 	ASSERT(MUTEX_HELD(&dtrace_lock));
11512 
11513 	if (id == 0 || id > state->dts_necbs)
11514 		return (NULL);
11515 
11516 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11517 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11518 
11519 	return (state->dts_ecbs[id - 1]);
11520 }
11521 
11522 static dtrace_aggregation_t *
dtrace_aggid2agg(dtrace_state_t * state,dtrace_aggid_t id)11523 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11524 {
11525 	dtrace_aggregation_t *agg;
11526 
11527 	ASSERT(MUTEX_HELD(&dtrace_lock));
11528 
11529 	if (id == 0 || id > state->dts_naggregations)
11530 		return (NULL);
11531 
11532 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11533 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11534 	    agg->dtag_id == id);
11535 
11536 	return (state->dts_aggregations[id - 1]);
11537 }
11538 
11539 /*
11540  * DTrace Buffer Functions
11541  *
11542  * The following functions manipulate DTrace buffers.  Most of these functions
11543  * are called in the context of establishing or processing consumer state;
11544  * exceptions are explicitly noted.
11545  */
11546 
11547 /*
11548  * Note:  called from cross call context.  This function switches the two
11549  * buffers on a given CPU.  The atomicity of this operation is assured by
11550  * disabling interrupts while the actual switch takes place; the disabling of
11551  * interrupts serializes the execution with any execution of dtrace_probe() on
11552  * the same CPU.
11553  */
11554 static void
dtrace_buffer_switch(dtrace_buffer_t * buf)11555 dtrace_buffer_switch(dtrace_buffer_t *buf)
11556 {
11557 	caddr_t tomax = buf->dtb_tomax;
11558 	caddr_t xamot = buf->dtb_xamot;
11559 	dtrace_icookie_t cookie;
11560 	hrtime_t now;
11561 
11562 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11563 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11564 
11565 	cookie = dtrace_interrupt_disable();
11566 	now = dtrace_gethrtime();
11567 	buf->dtb_tomax = xamot;
11568 	buf->dtb_xamot = tomax;
11569 	buf->dtb_xamot_drops = buf->dtb_drops;
11570 	buf->dtb_xamot_offset = buf->dtb_offset;
11571 	buf->dtb_xamot_errors = buf->dtb_errors;
11572 	buf->dtb_xamot_flags = buf->dtb_flags;
11573 	buf->dtb_offset = 0;
11574 	buf->dtb_drops = 0;
11575 	buf->dtb_errors = 0;
11576 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11577 	buf->dtb_interval = now - buf->dtb_switched;
11578 	buf->dtb_switched = now;
11579 	dtrace_interrupt_enable(cookie);
11580 }
11581 
11582 /*
11583  * Note:  called from cross call context.  This function activates a buffer
11584  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11585  * is guaranteed by the disabling of interrupts.
11586  */
11587 static void
dtrace_buffer_activate(dtrace_state_t * state)11588 dtrace_buffer_activate(dtrace_state_t *state)
11589 {
11590 	dtrace_buffer_t *buf;
11591 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11592 
11593 	buf = &state->dts_buffer[CPU->cpu_id];
11594 
11595 	if (buf->dtb_tomax != NULL) {
11596 		/*
11597 		 * We might like to assert that the buffer is marked inactive,
11598 		 * but this isn't necessarily true:  the buffer for the CPU
11599 		 * that processes the BEGIN probe has its buffer activated
11600 		 * manually.  In this case, we take the (harmless) action
11601 		 * re-clearing the bit INACTIVE bit.
11602 		 */
11603 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11604 	}
11605 
11606 	dtrace_interrupt_enable(cookie);
11607 }
11608 
11609 static int
dtrace_buffer_alloc(dtrace_buffer_t * bufs,size_t size,int flags,processorid_t cpu,int * factor)11610 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11611     processorid_t cpu, int *factor)
11612 {
11613 	cpu_t *cp;
11614 	dtrace_buffer_t *buf;
11615 	int allocated = 0, desired = 0;
11616 
11617 	ASSERT(MUTEX_HELD(&cpu_lock));
11618 	ASSERT(MUTEX_HELD(&dtrace_lock));
11619 
11620 	*factor = 1;
11621 
11622 	if (size > dtrace_nonroot_maxsize &&
11623 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11624 		return (EFBIG);
11625 
11626 	cp = cpu_list;
11627 
11628 	do {
11629 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11630 			continue;
11631 
11632 		buf = &bufs[cp->cpu_id];
11633 
11634 		/*
11635 		 * If there is already a buffer allocated for this CPU, it
11636 		 * is only possible that this is a DR event.  In this case,
11637 		 * the buffer size must match our specified size.
11638 		 */
11639 		if (buf->dtb_tomax != NULL) {
11640 			ASSERT(buf->dtb_size == size);
11641 			continue;
11642 		}
11643 
11644 		ASSERT(buf->dtb_xamot == NULL);
11645 
11646 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP_LAZY)) ==
11647 		    NULL)
11648 			goto err;
11649 
11650 		buf->dtb_size = size;
11651 		buf->dtb_flags = flags;
11652 		buf->dtb_offset = 0;
11653 		buf->dtb_drops = 0;
11654 
11655 		if (flags & DTRACEBUF_NOSWITCH)
11656 			continue;
11657 
11658 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP_LAZY)) ==
11659 		    NULL)
11660 			goto err;
11661 	} while ((cp = cp->cpu_next) != cpu_list);
11662 
11663 	return (0);
11664 
11665 err:
11666 	cp = cpu_list;
11667 
11668 	do {
11669 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11670 			continue;
11671 
11672 		buf = &bufs[cp->cpu_id];
11673 		desired += 2;
11674 
11675 		if (buf->dtb_xamot != NULL) {
11676 			ASSERT(buf->dtb_tomax != NULL);
11677 			ASSERT(buf->dtb_size == size);
11678 			kmem_free(buf->dtb_xamot, size);
11679 			allocated++;
11680 		}
11681 
11682 		if (buf->dtb_tomax != NULL) {
11683 			ASSERT(buf->dtb_size == size);
11684 			kmem_free(buf->dtb_tomax, size);
11685 			allocated++;
11686 		}
11687 
11688 		buf->dtb_tomax = NULL;
11689 		buf->dtb_xamot = NULL;
11690 		buf->dtb_size = 0;
11691 	} while ((cp = cp->cpu_next) != cpu_list);
11692 
11693 	*factor = desired / (allocated > 0 ? allocated : 1);
11694 
11695 	return (ENOMEM);
11696 }
11697 
11698 /*
11699  * Note:  called from probe context.  This function just increments the drop
11700  * count on a buffer.  It has been made a function to allow for the
11701  * possibility of understanding the source of mysterious drop counts.  (A
11702  * problem for which one may be particularly disappointed that DTrace cannot
11703  * be used to understand DTrace.)
11704  */
11705 static void
dtrace_buffer_drop(dtrace_buffer_t * buf)11706 dtrace_buffer_drop(dtrace_buffer_t *buf)
11707 {
11708 	buf->dtb_drops++;
11709 }
11710 
11711 /*
11712  * Note:  called from probe context.  This function is called to reserve space
11713  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11714  * mstate.  Returns the new offset in the buffer, or a negative value if an
11715  * error has occurred.
11716  */
11717 static intptr_t
dtrace_buffer_reserve(dtrace_buffer_t * buf,size_t needed,size_t align,dtrace_state_t * state,dtrace_mstate_t * mstate)11718 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11719     dtrace_state_t *state, dtrace_mstate_t *mstate)
11720 {
11721 	intptr_t offs = buf->dtb_offset, soffs;
11722 	intptr_t woffs;
11723 	caddr_t tomax;
11724 	size_t total;
11725 
11726 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11727 		return (-1);
11728 
11729 	if ((tomax = buf->dtb_tomax) == NULL) {
11730 		dtrace_buffer_drop(buf);
11731 		return (-1);
11732 	}
11733 
11734 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11735 		while (offs & (align - 1)) {
11736 			/*
11737 			 * Assert that our alignment is off by a number which
11738 			 * is itself sizeof (uint32_t) aligned.
11739 			 */
11740 			ASSERT(!((align - (offs & (align - 1))) &
11741 			    (sizeof (uint32_t) - 1)));
11742 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11743 			offs += sizeof (uint32_t);
11744 		}
11745 
11746 		if ((soffs = offs + needed) > buf->dtb_size) {
11747 			dtrace_buffer_drop(buf);
11748 			return (-1);
11749 		}
11750 
11751 		if (mstate == NULL)
11752 			return (offs);
11753 
11754 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11755 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11756 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11757 
11758 		return (offs);
11759 	}
11760 
11761 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11762 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11763 		    (buf->dtb_flags & DTRACEBUF_FULL))
11764 			return (-1);
11765 		goto out;
11766 	}
11767 
11768 	total = needed + (offs & (align - 1));
11769 
11770 	/*
11771 	 * For a ring buffer, life is quite a bit more complicated.  Before
11772 	 * we can store any padding, we need to adjust our wrapping offset.
11773 	 * (If we've never before wrapped or we're not about to, no adjustment
11774 	 * is required.)
11775 	 */
11776 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11777 	    offs + total > buf->dtb_size) {
11778 		woffs = buf->dtb_xamot_offset;
11779 
11780 		if (offs + total > buf->dtb_size) {
11781 			/*
11782 			 * We can't fit in the end of the buffer.  First, a
11783 			 * sanity check that we can fit in the buffer at all.
11784 			 */
11785 			if (total > buf->dtb_size) {
11786 				dtrace_buffer_drop(buf);
11787 				return (-1);
11788 			}
11789 
11790 			/*
11791 			 * We're going to be storing at the top of the buffer,
11792 			 * so now we need to deal with the wrapped offset.  We
11793 			 * only reset our wrapped offset to 0 if it is
11794 			 * currently greater than the current offset.  If it
11795 			 * is less than the current offset, it is because a
11796 			 * previous allocation induced a wrap -- but the
11797 			 * allocation didn't subsequently take the space due
11798 			 * to an error or false predicate evaluation.  In this
11799 			 * case, we'll just leave the wrapped offset alone: if
11800 			 * the wrapped offset hasn't been advanced far enough
11801 			 * for this allocation, it will be adjusted in the
11802 			 * lower loop.
11803 			 */
11804 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11805 				if (woffs >= offs)
11806 					woffs = 0;
11807 			} else {
11808 				woffs = 0;
11809 			}
11810 
11811 			/*
11812 			 * Now we know that we're going to be storing to the
11813 			 * top of the buffer and that there is room for us
11814 			 * there.  We need to clear the buffer from the current
11815 			 * offset to the end (there may be old gunk there).
11816 			 */
11817 			while (offs < buf->dtb_size)
11818 				tomax[offs++] = 0;
11819 
11820 			/*
11821 			 * We need to set our offset to zero.  And because we
11822 			 * are wrapping, we need to set the bit indicating as
11823 			 * much.  We can also adjust our needed space back
11824 			 * down to the space required by the ECB -- we know
11825 			 * that the top of the buffer is aligned.
11826 			 */
11827 			offs = 0;
11828 			total = needed;
11829 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11830 		} else {
11831 			/*
11832 			 * There is room for us in the buffer, so we simply
11833 			 * need to check the wrapped offset.
11834 			 */
11835 			if (woffs < offs) {
11836 				/*
11837 				 * The wrapped offset is less than the offset.
11838 				 * This can happen if we allocated buffer space
11839 				 * that induced a wrap, but then we didn't
11840 				 * subsequently take the space due to an error
11841 				 * or false predicate evaluation.  This is
11842 				 * okay; we know that _this_ allocation isn't
11843 				 * going to induce a wrap.  We still can't
11844 				 * reset the wrapped offset to be zero,
11845 				 * however: the space may have been trashed in
11846 				 * the previous failed probe attempt.  But at
11847 				 * least the wrapped offset doesn't need to
11848 				 * be adjusted at all...
11849 				 */
11850 				goto out;
11851 			}
11852 		}
11853 
11854 		while (offs + total > woffs) {
11855 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11856 			size_t size;
11857 
11858 			if (epid == DTRACE_EPIDNONE) {
11859 				size = sizeof (uint32_t);
11860 			} else {
11861 				ASSERT3U(epid, <=, state->dts_necbs);
11862 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11863 
11864 				size = state->dts_ecbs[epid - 1]->dte_size;
11865 			}
11866 
11867 			ASSERT(woffs + size <= buf->dtb_size);
11868 			ASSERT(size != 0);
11869 
11870 			if (woffs + size == buf->dtb_size) {
11871 				/*
11872 				 * We've reached the end of the buffer; we want
11873 				 * to set the wrapped offset to 0 and break
11874 				 * out.  However, if the offs is 0, then we're
11875 				 * in a strange edge-condition:  the amount of
11876 				 * space that we want to reserve plus the size
11877 				 * of the record that we're overwriting is
11878 				 * greater than the size of the buffer.  This
11879 				 * is problematic because if we reserve the
11880 				 * space but subsequently don't consume it (due
11881 				 * to a failed predicate or error) the wrapped
11882 				 * offset will be 0 -- yet the EPID at offset 0
11883 				 * will not be committed.  This situation is
11884 				 * relatively easy to deal with:  if we're in
11885 				 * this case, the buffer is indistinguishable
11886 				 * from one that hasn't wrapped; we need only
11887 				 * finish the job by clearing the wrapped bit,
11888 				 * explicitly setting the offset to be 0, and
11889 				 * zero'ing out the old data in the buffer.
11890 				 */
11891 				if (offs == 0) {
11892 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11893 					buf->dtb_offset = 0;
11894 					woffs = total;
11895 
11896 					while (woffs < buf->dtb_size)
11897 						tomax[woffs++] = 0;
11898 				}
11899 
11900 				woffs = 0;
11901 				break;
11902 			}
11903 
11904 			woffs += size;
11905 		}
11906 
11907 		/*
11908 		 * We have a wrapped offset.  It may be that the wrapped offset
11909 		 * has become zero -- that's okay.
11910 		 */
11911 		buf->dtb_xamot_offset = woffs;
11912 	}
11913 
11914 out:
11915 	/*
11916 	 * Now we can plow the buffer with any necessary padding.
11917 	 */
11918 	while (offs & (align - 1)) {
11919 		/*
11920 		 * Assert that our alignment is off by a number which
11921 		 * is itself sizeof (uint32_t) aligned.
11922 		 */
11923 		ASSERT(!((align - (offs & (align - 1))) &
11924 		    (sizeof (uint32_t) - 1)));
11925 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11926 		offs += sizeof (uint32_t);
11927 	}
11928 
11929 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11930 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11931 			buf->dtb_flags |= DTRACEBUF_FULL;
11932 			return (-1);
11933 		}
11934 	}
11935 
11936 	if (mstate == NULL)
11937 		return (offs);
11938 
11939 	/*
11940 	 * For ring buffers and fill buffers, the scratch space is always
11941 	 * the inactive buffer.
11942 	 */
11943 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11944 	mstate->dtms_scratch_size = buf->dtb_size;
11945 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11946 
11947 	return (offs);
11948 }
11949 
11950 static void
dtrace_buffer_polish(dtrace_buffer_t * buf)11951 dtrace_buffer_polish(dtrace_buffer_t *buf)
11952 {
11953 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11954 	ASSERT(MUTEX_HELD(&dtrace_lock));
11955 
11956 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11957 		return;
11958 
11959 	/*
11960 	 * We need to polish the ring buffer.  There are three cases:
11961 	 *
11962 	 * - The first (and presumably most common) is that there is no gap
11963 	 *   between the buffer offset and the wrapped offset.  In this case,
11964 	 *   there is nothing in the buffer that isn't valid data; we can
11965 	 *   mark the buffer as polished and return.
11966 	 *
11967 	 * - The second (less common than the first but still more common
11968 	 *   than the third) is that there is a gap between the buffer offset
11969 	 *   and the wrapped offset, and the wrapped offset is larger than the
11970 	 *   buffer offset.  This can happen because of an alignment issue, or
11971 	 *   can happen because of a call to dtrace_buffer_reserve() that
11972 	 *   didn't subsequently consume the buffer space.  In this case,
11973 	 *   we need to zero the data from the buffer offset to the wrapped
11974 	 *   offset.
11975 	 *
11976 	 * - The third (and least common) is that there is a gap between the
11977 	 *   buffer offset and the wrapped offset, but the wrapped offset is
11978 	 *   _less_ than the buffer offset.  This can only happen because a
11979 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11980 	 *   was not subsequently consumed.  In this case, we need to zero the
11981 	 *   space from the offset to the end of the buffer _and_ from the
11982 	 *   top of the buffer to the wrapped offset.
11983 	 */
11984 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11985 		bzero(buf->dtb_tomax + buf->dtb_offset,
11986 		    buf->dtb_xamot_offset - buf->dtb_offset);
11987 	}
11988 
11989 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11990 		bzero(buf->dtb_tomax + buf->dtb_offset,
11991 		    buf->dtb_size - buf->dtb_offset);
11992 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11993 	}
11994 }
11995 
11996 /*
11997  * This routine determines if data generated at the specified time has likely
11998  * been entirely consumed at user-level.  This routine is called to determine
11999  * if an ECB on a defunct probe (but for an active enabling) can be safely
12000  * disabled and destroyed.
12001  */
12002 static int
dtrace_buffer_consumed(dtrace_buffer_t * bufs,hrtime_t when)12003 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12004 {
12005 	int i;
12006 
12007 	for (i = 0; i < NCPU; i++) {
12008 		dtrace_buffer_t *buf = &bufs[i];
12009 
12010 		if (buf->dtb_size == 0)
12011 			continue;
12012 
12013 		if (buf->dtb_flags & DTRACEBUF_RING)
12014 			return (0);
12015 
12016 		if (!buf->dtb_switched && buf->dtb_offset != 0)
12017 			return (0);
12018 
12019 		if (buf->dtb_switched - buf->dtb_interval < when)
12020 			return (0);
12021 	}
12022 
12023 	return (1);
12024 }
12025 
12026 static void
dtrace_buffer_free(dtrace_buffer_t * bufs)12027 dtrace_buffer_free(dtrace_buffer_t *bufs)
12028 {
12029 	int i;
12030 
12031 	for (i = 0; i < NCPU; i++) {
12032 		dtrace_buffer_t *buf = &bufs[i];
12033 
12034 		if (buf->dtb_tomax == NULL) {
12035 			ASSERT(buf->dtb_xamot == NULL);
12036 			ASSERT(buf->dtb_size == 0);
12037 			continue;
12038 		}
12039 
12040 		if (buf->dtb_xamot != NULL) {
12041 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12042 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12043 		}
12044 
12045 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12046 		buf->dtb_size = 0;
12047 		buf->dtb_tomax = NULL;
12048 		buf->dtb_xamot = NULL;
12049 	}
12050 }
12051 
12052 /*
12053  * DTrace Enabling Functions
12054  */
12055 static dtrace_enabling_t *
dtrace_enabling_create(dtrace_vstate_t * vstate)12056 dtrace_enabling_create(dtrace_vstate_t *vstate)
12057 {
12058 	dtrace_enabling_t *enab;
12059 
12060 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12061 	enab->dten_vstate = vstate;
12062 
12063 	return (enab);
12064 }
12065 
12066 static void
dtrace_enabling_add(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb)12067 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12068 {
12069 	dtrace_ecbdesc_t **ndesc;
12070 	size_t osize, nsize;
12071 
12072 	/*
12073 	 * We can't add to enablings after we've enabled them, or after we've
12074 	 * retained them.
12075 	 */
12076 	ASSERT(enab->dten_probegen == 0);
12077 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12078 
12079 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12080 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12081 		return;
12082 	}
12083 
12084 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12085 
12086 	if (enab->dten_maxdesc == 0) {
12087 		enab->dten_maxdesc = 1;
12088 	} else {
12089 		enab->dten_maxdesc <<= 1;
12090 	}
12091 
12092 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12093 
12094 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12095 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12096 	bcopy(enab->dten_desc, ndesc, osize);
12097 	kmem_free(enab->dten_desc, osize);
12098 
12099 	enab->dten_desc = ndesc;
12100 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12101 }
12102 
12103 static void
dtrace_enabling_addlike(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb,dtrace_probedesc_t * pd)12104 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12105     dtrace_probedesc_t *pd)
12106 {
12107 	dtrace_ecbdesc_t *new;
12108 	dtrace_predicate_t *pred;
12109 	dtrace_actdesc_t *act;
12110 
12111 	/*
12112 	 * We're going to create a new ECB description that matches the
12113 	 * specified ECB in every way, but has the specified probe description.
12114 	 */
12115 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12116 
12117 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12118 		dtrace_predicate_hold(pred);
12119 
12120 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12121 		dtrace_actdesc_hold(act);
12122 
12123 	new->dted_action = ecb->dted_action;
12124 	new->dted_pred = ecb->dted_pred;
12125 	new->dted_probe = *pd;
12126 	new->dted_uarg = ecb->dted_uarg;
12127 
12128 	dtrace_enabling_add(enab, new);
12129 }
12130 
12131 static void
dtrace_enabling_dump(dtrace_enabling_t * enab)12132 dtrace_enabling_dump(dtrace_enabling_t *enab)
12133 {
12134 	int i;
12135 
12136 	for (i = 0; i < enab->dten_ndesc; i++) {
12137 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12138 
12139 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12140 		    desc->dtpd_provider, desc->dtpd_mod,
12141 		    desc->dtpd_func, desc->dtpd_name);
12142 	}
12143 }
12144 
12145 static void
dtrace_enabling_destroy(dtrace_enabling_t * enab)12146 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12147 {
12148 	int i;
12149 	dtrace_ecbdesc_t *ep;
12150 	dtrace_vstate_t *vstate = enab->dten_vstate;
12151 
12152 	ASSERT(MUTEX_HELD(&dtrace_lock));
12153 
12154 	for (i = 0; i < enab->dten_ndesc; i++) {
12155 		dtrace_actdesc_t *act, *next;
12156 		dtrace_predicate_t *pred;
12157 
12158 		ep = enab->dten_desc[i];
12159 
12160 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12161 			dtrace_predicate_release(pred, vstate);
12162 
12163 		for (act = ep->dted_action; act != NULL; act = next) {
12164 			next = act->dtad_next;
12165 			dtrace_actdesc_release(act, vstate);
12166 		}
12167 
12168 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12169 	}
12170 
12171 	kmem_free(enab->dten_desc,
12172 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12173 
12174 	/*
12175 	 * If this was a retained enabling, decrement the dts_nretained count
12176 	 * and take it off of the dtrace_retained list.
12177 	 */
12178 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12179 	    dtrace_retained == enab) {
12180 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12181 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12182 		enab->dten_vstate->dtvs_state->dts_nretained--;
12183 		dtrace_retained_gen++;
12184 	}
12185 
12186 	if (enab->dten_prev == NULL) {
12187 		if (dtrace_retained == enab) {
12188 			dtrace_retained = enab->dten_next;
12189 
12190 			if (dtrace_retained != NULL)
12191 				dtrace_retained->dten_prev = NULL;
12192 		}
12193 	} else {
12194 		ASSERT(enab != dtrace_retained);
12195 		ASSERT(dtrace_retained != NULL);
12196 		enab->dten_prev->dten_next = enab->dten_next;
12197 	}
12198 
12199 	if (enab->dten_next != NULL) {
12200 		ASSERT(dtrace_retained != NULL);
12201 		enab->dten_next->dten_prev = enab->dten_prev;
12202 	}
12203 
12204 	kmem_free(enab, sizeof (dtrace_enabling_t));
12205 }
12206 
12207 static int
dtrace_enabling_retain(dtrace_enabling_t * enab)12208 dtrace_enabling_retain(dtrace_enabling_t *enab)
12209 {
12210 	dtrace_state_t *state;
12211 
12212 	ASSERT(MUTEX_HELD(&dtrace_lock));
12213 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12214 	ASSERT(enab->dten_vstate != NULL);
12215 
12216 	state = enab->dten_vstate->dtvs_state;
12217 	ASSERT(state != NULL);
12218 
12219 	/*
12220 	 * We only allow each state to retain dtrace_retain_max enablings.
12221 	 */
12222 	if (state->dts_nretained >= dtrace_retain_max)
12223 		return (ENOSPC);
12224 
12225 	state->dts_nretained++;
12226 	dtrace_retained_gen++;
12227 
12228 	if (dtrace_retained == NULL) {
12229 		dtrace_retained = enab;
12230 		return (0);
12231 	}
12232 
12233 	enab->dten_next = dtrace_retained;
12234 	dtrace_retained->dten_prev = enab;
12235 	dtrace_retained = enab;
12236 
12237 	return (0);
12238 }
12239 
12240 static int
dtrace_enabling_replicate(dtrace_state_t * state,dtrace_probedesc_t * match,dtrace_probedesc_t * create)12241 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12242     dtrace_probedesc_t *create)
12243 {
12244 	dtrace_enabling_t *new, *enab;
12245 	int found = 0, err = ENOENT;
12246 
12247 	ASSERT(MUTEX_HELD(&dtrace_lock));
12248 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12249 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12250 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12251 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12252 
12253 	new = dtrace_enabling_create(&state->dts_vstate);
12254 
12255 	/*
12256 	 * Iterate over all retained enablings, looking for enablings that
12257 	 * match the specified state.
12258 	 */
12259 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12260 		int i;
12261 
12262 		/*
12263 		 * dtvs_state can only be NULL for helper enablings -- and
12264 		 * helper enablings can't be retained.
12265 		 */
12266 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12267 
12268 		if (enab->dten_vstate->dtvs_state != state)
12269 			continue;
12270 
12271 		/*
12272 		 * Now iterate over each probe description; we're looking for
12273 		 * an exact match to the specified probe description.
12274 		 */
12275 		for (i = 0; i < enab->dten_ndesc; i++) {
12276 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12277 			dtrace_probedesc_t *pd = &ep->dted_probe;
12278 
12279 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12280 				continue;
12281 
12282 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12283 				continue;
12284 
12285 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12286 				continue;
12287 
12288 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12289 				continue;
12290 
12291 			/*
12292 			 * We have a winning probe!  Add it to our growing
12293 			 * enabling.
12294 			 */
12295 			found = 1;
12296 			dtrace_enabling_addlike(new, ep, create);
12297 		}
12298 	}
12299 
12300 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12301 		dtrace_enabling_destroy(new);
12302 		return (err);
12303 	}
12304 
12305 	return (0);
12306 }
12307 
12308 static void
dtrace_enabling_retract(dtrace_state_t * state)12309 dtrace_enabling_retract(dtrace_state_t *state)
12310 {
12311 	dtrace_enabling_t *enab, *next;
12312 
12313 	ASSERT(MUTEX_HELD(&dtrace_lock));
12314 
12315 	/*
12316 	 * Iterate over all retained enablings, destroy the enablings retained
12317 	 * for the specified state.
12318 	 */
12319 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12320 		next = enab->dten_next;
12321 
12322 		/*
12323 		 * dtvs_state can only be NULL for helper enablings -- and
12324 		 * helper enablings can't be retained.
12325 		 */
12326 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12327 
12328 		if (enab->dten_vstate->dtvs_state == state) {
12329 			ASSERT(state->dts_nretained > 0);
12330 			dtrace_enabling_destroy(enab);
12331 		}
12332 	}
12333 
12334 	ASSERT(state->dts_nretained == 0);
12335 }
12336 
12337 static int
dtrace_enabling_match(dtrace_enabling_t * enab,int * nmatched)12338 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12339 {
12340 	int i = 0;
12341 	int total_matched = 0, matched = 0;
12342 
12343 	ASSERT(MUTEX_HELD(&cpu_lock));
12344 	ASSERT(MUTEX_HELD(&dtrace_lock));
12345 
12346 	for (i = 0; i < enab->dten_ndesc; i++) {
12347 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12348 
12349 		enab->dten_current = ep;
12350 		enab->dten_error = 0;
12351 
12352 		/*
12353 		 * If a provider failed to enable a probe then get out and
12354 		 * let the consumer know we failed.
12355 		 */
12356 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
12357 			return (EBUSY);
12358 
12359 		total_matched += matched;
12360 
12361 		if (enab->dten_error != 0) {
12362 			/*
12363 			 * If we get an error half-way through enabling the
12364 			 * probes, we kick out -- perhaps with some number of
12365 			 * them enabled.  Leaving enabled probes enabled may
12366 			 * be slightly confusing for user-level, but we expect
12367 			 * that no one will attempt to actually drive on in
12368 			 * the face of such errors.  If this is an anonymous
12369 			 * enabling (indicated with a NULL nmatched pointer),
12370 			 * we cmn_err() a message.  We aren't expecting to
12371 			 * get such an error -- such as it can exist at all,
12372 			 * it would be a result of corrupted DOF in the driver
12373 			 * properties.
12374 			 */
12375 			if (nmatched == NULL) {
12376 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12377 				    "error on %p: %d", (void *)ep,
12378 				    enab->dten_error);
12379 			}
12380 
12381 			return (enab->dten_error);
12382 		}
12383 	}
12384 
12385 	enab->dten_probegen = dtrace_probegen;
12386 	if (nmatched != NULL)
12387 		*nmatched = total_matched;
12388 
12389 	return (0);
12390 }
12391 
12392 static void
dtrace_enabling_matchall(void)12393 dtrace_enabling_matchall(void)
12394 {
12395 	dtrace_enabling_t *enab;
12396 
12397 	mutex_enter(&cpu_lock);
12398 	mutex_enter(&dtrace_lock);
12399 
12400 	/*
12401 	 * Iterate over all retained enablings to see if any probes match
12402 	 * against them.  We only perform this operation on enablings for which
12403 	 * we have sufficient permissions by virtue of being in the global zone
12404 	 * or in the same zone as the DTrace client.  Because we can be called
12405 	 * after dtrace_detach() has been called, we cannot assert that there
12406 	 * are retained enablings.  We can safely load from dtrace_retained,
12407 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12408 	 * block pending our completion.
12409 	 */
12410 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12411 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
12412 		cred_t *cr = dcr->dcr_cred;
12413 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
12414 
12415 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
12416 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
12417 			(void) dtrace_enabling_match(enab, NULL);
12418 	}
12419 
12420 	mutex_exit(&dtrace_lock);
12421 	mutex_exit(&cpu_lock);
12422 }
12423 
12424 /*
12425  * If an enabling is to be enabled without having matched probes (that is, if
12426  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12427  * enabling must be _primed_ by creating an ECB for every ECB description.
12428  * This must be done to assure that we know the number of speculations, the
12429  * number of aggregations, the minimum buffer size needed, etc. before we
12430  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12431  * enabling any probes, we create ECBs for every ECB decription, but with a
12432  * NULL probe -- which is exactly what this function does.
12433  */
12434 static void
dtrace_enabling_prime(dtrace_state_t * state)12435 dtrace_enabling_prime(dtrace_state_t *state)
12436 {
12437 	dtrace_enabling_t *enab;
12438 	int i;
12439 
12440 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12441 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12442 
12443 		if (enab->dten_vstate->dtvs_state != state)
12444 			continue;
12445 
12446 		/*
12447 		 * We don't want to prime an enabling more than once, lest
12448 		 * we allow a malicious user to induce resource exhaustion.
12449 		 * (The ECBs that result from priming an enabling aren't
12450 		 * leaked -- but they also aren't deallocated until the
12451 		 * consumer state is destroyed.)
12452 		 */
12453 		if (enab->dten_primed)
12454 			continue;
12455 
12456 		for (i = 0; i < enab->dten_ndesc; i++) {
12457 			enab->dten_current = enab->dten_desc[i];
12458 			(void) dtrace_probe_enable(NULL, enab);
12459 		}
12460 
12461 		enab->dten_primed = 1;
12462 	}
12463 }
12464 
12465 /*
12466  * Called to indicate that probes should be provided due to retained
12467  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12468  * must take an initial lap through the enabling calling the dtps_provide()
12469  * entry point explicitly to allow for autocreated probes.
12470  */
12471 static void
dtrace_enabling_provide(dtrace_provider_t * prv)12472 dtrace_enabling_provide(dtrace_provider_t *prv)
12473 {
12474 	int i, all = 0;
12475 	dtrace_probedesc_t desc;
12476 	dtrace_genid_t gen;
12477 
12478 	ASSERT(MUTEX_HELD(&dtrace_lock));
12479 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12480 
12481 	if (prv == NULL) {
12482 		all = 1;
12483 		prv = dtrace_provider;
12484 	}
12485 
12486 	do {
12487 		dtrace_enabling_t *enab;
12488 		void *parg = prv->dtpv_arg;
12489 
12490 retry:
12491 		gen = dtrace_retained_gen;
12492 		for (enab = dtrace_retained; enab != NULL;
12493 		    enab = enab->dten_next) {
12494 			for (i = 0; i < enab->dten_ndesc; i++) {
12495 				desc = enab->dten_desc[i]->dted_probe;
12496 				mutex_exit(&dtrace_lock);
12497 				prv->dtpv_pops.dtps_provide(parg, &desc);
12498 				mutex_enter(&dtrace_lock);
12499 				/*
12500 				 * Process the retained enablings again if
12501 				 * they have changed while we weren't holding
12502 				 * dtrace_lock.
12503 				 */
12504 				if (gen != dtrace_retained_gen)
12505 					goto retry;
12506 			}
12507 		}
12508 	} while (all && (prv = prv->dtpv_next) != NULL);
12509 
12510 	mutex_exit(&dtrace_lock);
12511 	dtrace_probe_provide(NULL, all ? NULL : prv);
12512 	mutex_enter(&dtrace_lock);
12513 }
12514 
12515 /*
12516  * Called to reap ECBs that are attached to probes from defunct providers.
12517  */
12518 static void
dtrace_enabling_reap(void)12519 dtrace_enabling_reap(void)
12520 {
12521 	dtrace_provider_t *prov;
12522 	dtrace_probe_t *probe;
12523 	dtrace_ecb_t *ecb;
12524 	hrtime_t when;
12525 	int i;
12526 
12527 	mutex_enter(&cpu_lock);
12528 	mutex_enter(&dtrace_lock);
12529 
12530 	for (i = 0; i < dtrace_nprobes; i++) {
12531 		if ((probe = dtrace_probes[i]) == NULL)
12532 			continue;
12533 
12534 		if (probe->dtpr_ecb == NULL)
12535 			continue;
12536 
12537 		prov = probe->dtpr_provider;
12538 
12539 		if ((when = prov->dtpv_defunct) == 0)
12540 			continue;
12541 
12542 		/*
12543 		 * We have ECBs on a defunct provider:  we want to reap these
12544 		 * ECBs to allow the provider to unregister.  The destruction
12545 		 * of these ECBs must be done carefully:  if we destroy the ECB
12546 		 * and the consumer later wishes to consume an EPID that
12547 		 * corresponds to the destroyed ECB (and if the EPID metadata
12548 		 * has not been previously consumed), the consumer will abort
12549 		 * processing on the unknown EPID.  To reduce (but not, sadly,
12550 		 * eliminate) the possibility of this, we will only destroy an
12551 		 * ECB for a defunct provider if, for the state that
12552 		 * corresponds to the ECB:
12553 		 *
12554 		 *  (a)	There is no speculative tracing (which can effectively
12555 		 *	cache an EPID for an arbitrary amount of time).
12556 		 *
12557 		 *  (b)	The principal buffers have been switched twice since the
12558 		 *	provider became defunct.
12559 		 *
12560 		 *  (c)	The aggregation buffers are of zero size or have been
12561 		 *	switched twice since the provider became defunct.
12562 		 *
12563 		 * We use dts_speculates to determine (a) and call a function
12564 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12565 		 * that as soon as we've been unable to destroy one of the ECBs
12566 		 * associated with the probe, we quit trying -- reaping is only
12567 		 * fruitful in as much as we can destroy all ECBs associated
12568 		 * with the defunct provider's probes.
12569 		 */
12570 		while ((ecb = probe->dtpr_ecb) != NULL) {
12571 			dtrace_state_t *state = ecb->dte_state;
12572 			dtrace_buffer_t *buf = state->dts_buffer;
12573 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12574 
12575 			if (state->dts_speculates)
12576 				break;
12577 
12578 			if (!dtrace_buffer_consumed(buf, when))
12579 				break;
12580 
12581 			if (!dtrace_buffer_consumed(aggbuf, when))
12582 				break;
12583 
12584 			dtrace_ecb_disable(ecb);
12585 			ASSERT(probe->dtpr_ecb != ecb);
12586 
12587 			/*
12588 			 * Before we can destroy the ECB, we need to issue a
12589 			 * sync to assure that no CPU is processing it.
12590 			 */
12591 			dtrace_sync();
12592 			dtrace_ecb_destroy(ecb);
12593 		}
12594 	}
12595 
12596 	mutex_exit(&dtrace_lock);
12597 	mutex_exit(&cpu_lock);
12598 }
12599 
12600 /*
12601  * DTrace DOF Functions
12602  */
12603 /*ARGSUSED*/
12604 static void
dtrace_dof_error(dof_hdr_t * dof,const char * str)12605 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12606 {
12607 	if (dtrace_err_verbose)
12608 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12609 
12610 #ifdef DTRACE_ERRDEBUG
12611 	dtrace_errdebug(str);
12612 #endif
12613 }
12614 
12615 /*
12616  * Create DOF out of a currently enabled state.  Right now, we only create
12617  * DOF containing the run-time options -- but this could be expanded to create
12618  * complete DOF representing the enabled state.
12619  */
12620 static dof_hdr_t *
dtrace_dof_create(dtrace_state_t * state)12621 dtrace_dof_create(dtrace_state_t *state)
12622 {
12623 	dof_hdr_t *dof;
12624 	dof_sec_t *sec;
12625 	dof_optdesc_t *opt;
12626 	int i, len = sizeof (dof_hdr_t) +
12627 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12628 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12629 
12630 	ASSERT(MUTEX_HELD(&dtrace_lock));
12631 
12632 	dof = kmem_zalloc(len, KM_SLEEP);
12633 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12634 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12635 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12636 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12637 
12638 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12639 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12640 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12641 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12642 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12643 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12644 
12645 	dof->dofh_flags = 0;
12646 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12647 	dof->dofh_secsize = sizeof (dof_sec_t);
12648 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12649 	dof->dofh_secoff = sizeof (dof_hdr_t);
12650 	dof->dofh_loadsz = len;
12651 	dof->dofh_filesz = len;
12652 	dof->dofh_pad = 0;
12653 
12654 	/*
12655 	 * Fill in the option section header...
12656 	 */
12657 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12658 	sec->dofs_type = DOF_SECT_OPTDESC;
12659 	sec->dofs_align = sizeof (uint64_t);
12660 	sec->dofs_flags = DOF_SECF_LOAD;
12661 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12662 
12663 	opt = (dof_optdesc_t *)((uintptr_t)sec +
12664 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12665 
12666 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12667 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12668 
12669 	for (i = 0; i < DTRACEOPT_MAX; i++) {
12670 		opt[i].dofo_option = i;
12671 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
12672 		opt[i].dofo_value = state->dts_options[i];
12673 	}
12674 
12675 	return (dof);
12676 }
12677 
12678 static dof_hdr_t *
dtrace_dof_copyin(uintptr_t uarg,int * errp)12679 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12680 {
12681 	dof_hdr_t hdr, *dof;
12682 
12683 	ASSERT(!MUTEX_HELD(&dtrace_lock));
12684 
12685 	/*
12686 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
12687 	 */
12688 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12689 		dtrace_dof_error(NULL, "failed to copyin DOF header");
12690 		*errp = EFAULT;
12691 		return (NULL);
12692 	}
12693 
12694 	/*
12695 	 * Now we'll allocate the entire DOF and copy it in -- provided
12696 	 * that the length isn't outrageous.
12697 	 */
12698 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12699 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12700 		*errp = E2BIG;
12701 		return (NULL);
12702 	}
12703 
12704 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12705 		dtrace_dof_error(&hdr, "invalid load size");
12706 		*errp = EINVAL;
12707 		return (NULL);
12708 	}
12709 
12710 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12711 
12712 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12713 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
12714 		kmem_free(dof, hdr.dofh_loadsz);
12715 		*errp = EFAULT;
12716 		return (NULL);
12717 	}
12718 
12719 	return (dof);
12720 }
12721 
12722 static dof_hdr_t *
dtrace_dof_property(const char * name)12723 dtrace_dof_property(const char *name)
12724 {
12725 	uchar_t *buf;
12726 	uint64_t loadsz;
12727 	unsigned int len, i;
12728 	dof_hdr_t *dof;
12729 
12730 	/*
12731 	 * Unfortunately, array of values in .conf files are always (and
12732 	 * only) interpreted to be integer arrays.  We must read our DOF
12733 	 * as an integer array, and then squeeze it into a byte array.
12734 	 */
12735 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12736 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12737 		return (NULL);
12738 
12739 	for (i = 0; i < len; i++)
12740 		buf[i] = (uchar_t)(((int *)buf)[i]);
12741 
12742 	if (len < sizeof (dof_hdr_t)) {
12743 		ddi_prop_free(buf);
12744 		dtrace_dof_error(NULL, "truncated header");
12745 		return (NULL);
12746 	}
12747 
12748 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12749 		ddi_prop_free(buf);
12750 		dtrace_dof_error(NULL, "truncated DOF");
12751 		return (NULL);
12752 	}
12753 
12754 	if (loadsz >= dtrace_dof_maxsize) {
12755 		ddi_prop_free(buf);
12756 		dtrace_dof_error(NULL, "oversized DOF");
12757 		return (NULL);
12758 	}
12759 
12760 	dof = kmem_alloc(loadsz, KM_SLEEP);
12761 	bcopy(buf, dof, loadsz);
12762 	ddi_prop_free(buf);
12763 
12764 	return (dof);
12765 }
12766 
12767 static void
dtrace_dof_destroy(dof_hdr_t * dof)12768 dtrace_dof_destroy(dof_hdr_t *dof)
12769 {
12770 	kmem_free(dof, dof->dofh_loadsz);
12771 }
12772 
12773 /*
12774  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12775  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12776  * a type other than DOF_SECT_NONE is specified, the header is checked against
12777  * this type and NULL is returned if the types do not match.
12778  */
12779 static dof_sec_t *
dtrace_dof_sect(dof_hdr_t * dof,uint32_t type,dof_secidx_t i)12780 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12781 {
12782 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12783 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12784 
12785 	if (i >= dof->dofh_secnum) {
12786 		dtrace_dof_error(dof, "referenced section index is invalid");
12787 		return (NULL);
12788 	}
12789 
12790 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12791 		dtrace_dof_error(dof, "referenced section is not loadable");
12792 		return (NULL);
12793 	}
12794 
12795 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12796 		dtrace_dof_error(dof, "referenced section is the wrong type");
12797 		return (NULL);
12798 	}
12799 
12800 	return (sec);
12801 }
12802 
12803 static dtrace_probedesc_t *
dtrace_dof_probedesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_probedesc_t * desc)12804 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12805 {
12806 	dof_probedesc_t *probe;
12807 	dof_sec_t *strtab;
12808 	uintptr_t daddr = (uintptr_t)dof;
12809 	uintptr_t str;
12810 	size_t size;
12811 
12812 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12813 		dtrace_dof_error(dof, "invalid probe section");
12814 		return (NULL);
12815 	}
12816 
12817 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12818 		dtrace_dof_error(dof, "bad alignment in probe description");
12819 		return (NULL);
12820 	}
12821 
12822 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12823 		dtrace_dof_error(dof, "truncated probe description");
12824 		return (NULL);
12825 	}
12826 
12827 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12828 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12829 
12830 	if (strtab == NULL)
12831 		return (NULL);
12832 
12833 	str = daddr + strtab->dofs_offset;
12834 	size = strtab->dofs_size;
12835 
12836 	if (probe->dofp_provider >= strtab->dofs_size) {
12837 		dtrace_dof_error(dof, "corrupt probe provider");
12838 		return (NULL);
12839 	}
12840 
12841 	(void) strncpy(desc->dtpd_provider,
12842 	    (char *)(str + probe->dofp_provider),
12843 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12844 
12845 	if (probe->dofp_mod >= strtab->dofs_size) {
12846 		dtrace_dof_error(dof, "corrupt probe module");
12847 		return (NULL);
12848 	}
12849 
12850 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12851 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12852 
12853 	if (probe->dofp_func >= strtab->dofs_size) {
12854 		dtrace_dof_error(dof, "corrupt probe function");
12855 		return (NULL);
12856 	}
12857 
12858 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12859 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12860 
12861 	if (probe->dofp_name >= strtab->dofs_size) {
12862 		dtrace_dof_error(dof, "corrupt probe name");
12863 		return (NULL);
12864 	}
12865 
12866 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12867 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12868 
12869 	return (desc);
12870 }
12871 
12872 static dtrace_difo_t *
dtrace_dof_difo(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)12873 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12874     cred_t *cr)
12875 {
12876 	dtrace_difo_t *dp;
12877 	size_t ttl = 0;
12878 	dof_difohdr_t *dofd;
12879 	uintptr_t daddr = (uintptr_t)dof;
12880 	size_t max = dtrace_difo_maxsize;
12881 	int i, l, n;
12882 
12883 	static const struct {
12884 		int section;
12885 		int bufoffs;
12886 		int lenoffs;
12887 		int entsize;
12888 		int align;
12889 		const char *msg;
12890 	} difo[] = {
12891 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12892 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12893 		sizeof (dif_instr_t), "multiple DIF sections" },
12894 
12895 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12896 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12897 		sizeof (uint64_t), "multiple integer tables" },
12898 
12899 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12900 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12901 		sizeof (char), "multiple string tables" },
12902 
12903 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12904 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12905 		sizeof (uint_t), "multiple variable tables" },
12906 
12907 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12908 	};
12909 
12910 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12911 		dtrace_dof_error(dof, "invalid DIFO header section");
12912 		return (NULL);
12913 	}
12914 
12915 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12916 		dtrace_dof_error(dof, "bad alignment in DIFO header");
12917 		return (NULL);
12918 	}
12919 
12920 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12921 	    sec->dofs_size % sizeof (dof_secidx_t)) {
12922 		dtrace_dof_error(dof, "bad size in DIFO header");
12923 		return (NULL);
12924 	}
12925 
12926 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12927 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12928 
12929 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12930 	dp->dtdo_rtype = dofd->dofd_rtype;
12931 
12932 	for (l = 0; l < n; l++) {
12933 		dof_sec_t *subsec;
12934 		void **bufp;
12935 		uint32_t *lenp;
12936 
12937 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12938 		    dofd->dofd_links[l])) == NULL)
12939 			goto err; /* invalid section link */
12940 
12941 		if (ttl + subsec->dofs_size > max) {
12942 			dtrace_dof_error(dof, "exceeds maximum size");
12943 			goto err;
12944 		}
12945 
12946 		ttl += subsec->dofs_size;
12947 
12948 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12949 			if (subsec->dofs_type != difo[i].section)
12950 				continue;
12951 
12952 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12953 				dtrace_dof_error(dof, "section not loaded");
12954 				goto err;
12955 			}
12956 
12957 			if (subsec->dofs_align != difo[i].align) {
12958 				dtrace_dof_error(dof, "bad alignment");
12959 				goto err;
12960 			}
12961 
12962 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12963 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12964 
12965 			if (*bufp != NULL) {
12966 				dtrace_dof_error(dof, difo[i].msg);
12967 				goto err;
12968 			}
12969 
12970 			if (difo[i].entsize != subsec->dofs_entsize) {
12971 				dtrace_dof_error(dof, "entry size mismatch");
12972 				goto err;
12973 			}
12974 
12975 			if (subsec->dofs_entsize != 0 &&
12976 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12977 				dtrace_dof_error(dof, "corrupt entry size");
12978 				goto err;
12979 			}
12980 
12981 			*lenp = subsec->dofs_size;
12982 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12983 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12984 			    *bufp, subsec->dofs_size);
12985 
12986 			if (subsec->dofs_entsize != 0)
12987 				*lenp /= subsec->dofs_entsize;
12988 
12989 			break;
12990 		}
12991 
12992 		/*
12993 		 * If we encounter a loadable DIFO sub-section that is not
12994 		 * known to us, assume this is a broken program and fail.
12995 		 */
12996 		if (difo[i].section == DOF_SECT_NONE &&
12997 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12998 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12999 			goto err;
13000 		}
13001 	}
13002 
13003 	if (dp->dtdo_buf == NULL) {
13004 		/*
13005 		 * We can't have a DIF object without DIF text.
13006 		 */
13007 		dtrace_dof_error(dof, "missing DIF text");
13008 		goto err;
13009 	}
13010 
13011 	/*
13012 	 * Before we validate the DIF object, run through the variable table
13013 	 * looking for the strings -- if any of their size are under, we'll set
13014 	 * their size to be the system-wide default string size.  Note that
13015 	 * this should _not_ happen if the "strsize" option has been set --
13016 	 * in this case, the compiler should have set the size to reflect the
13017 	 * setting of the option.
13018 	 */
13019 	for (i = 0; i < dp->dtdo_varlen; i++) {
13020 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13021 		dtrace_diftype_t *t = &v->dtdv_type;
13022 
13023 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13024 			continue;
13025 
13026 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13027 			t->dtdt_size = dtrace_strsize_default;
13028 	}
13029 
13030 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13031 		goto err;
13032 
13033 	dtrace_difo_init(dp, vstate);
13034 	return (dp);
13035 
13036 err:
13037 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13038 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13039 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13040 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13041 
13042 	kmem_free(dp, sizeof (dtrace_difo_t));
13043 	return (NULL);
13044 }
13045 
13046 static dtrace_predicate_t *
dtrace_dof_predicate(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13047 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13048     cred_t *cr)
13049 {
13050 	dtrace_difo_t *dp;
13051 
13052 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13053 		return (NULL);
13054 
13055 	return (dtrace_predicate_create(dp));
13056 }
13057 
13058 static dtrace_actdesc_t *
dtrace_dof_actdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13059 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13060     cred_t *cr)
13061 {
13062 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13063 	dof_actdesc_t *desc;
13064 	dof_sec_t *difosec;
13065 	size_t offs;
13066 	uintptr_t daddr = (uintptr_t)dof;
13067 	uint64_t arg;
13068 	dtrace_actkind_t kind;
13069 
13070 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13071 		dtrace_dof_error(dof, "invalid action section");
13072 		return (NULL);
13073 	}
13074 
13075 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13076 		dtrace_dof_error(dof, "truncated action description");
13077 		return (NULL);
13078 	}
13079 
13080 	if (sec->dofs_align != sizeof (uint64_t)) {
13081 		dtrace_dof_error(dof, "bad alignment in action description");
13082 		return (NULL);
13083 	}
13084 
13085 	if (sec->dofs_size < sec->dofs_entsize) {
13086 		dtrace_dof_error(dof, "section entry size exceeds total size");
13087 		return (NULL);
13088 	}
13089 
13090 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13091 		dtrace_dof_error(dof, "bad entry size in action description");
13092 		return (NULL);
13093 	}
13094 
13095 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13096 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13097 		return (NULL);
13098 	}
13099 
13100 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13101 		desc = (dof_actdesc_t *)(daddr +
13102 		    (uintptr_t)sec->dofs_offset + offs);
13103 		kind = (dtrace_actkind_t)desc->dofa_kind;
13104 
13105 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13106 		    (kind != DTRACEACT_PRINTA ||
13107 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13108 		    (kind == DTRACEACT_DIFEXPR &&
13109 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13110 			dof_sec_t *strtab;
13111 			char *str, *fmt;
13112 			uint64_t i;
13113 
13114 			/*
13115 			 * The argument to these actions is an index into the
13116 			 * DOF string table.  For printf()-like actions, this
13117 			 * is the format string.  For print(), this is the
13118 			 * CTF type of the expression result.
13119 			 */
13120 			if ((strtab = dtrace_dof_sect(dof,
13121 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13122 				goto err;
13123 
13124 			str = (char *)((uintptr_t)dof +
13125 			    (uintptr_t)strtab->dofs_offset);
13126 
13127 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13128 				if (str[i] == '\0')
13129 					break;
13130 			}
13131 
13132 			if (i >= strtab->dofs_size) {
13133 				dtrace_dof_error(dof, "bogus format string");
13134 				goto err;
13135 			}
13136 
13137 			if (i == desc->dofa_arg) {
13138 				dtrace_dof_error(dof, "empty format string");
13139 				goto err;
13140 			}
13141 
13142 			i -= desc->dofa_arg;
13143 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13144 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13145 			arg = (uint64_t)(uintptr_t)fmt;
13146 		} else {
13147 			if (kind == DTRACEACT_PRINTA) {
13148 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13149 				arg = 0;
13150 			} else {
13151 				arg = desc->dofa_arg;
13152 			}
13153 		}
13154 
13155 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13156 		    desc->dofa_uarg, arg);
13157 
13158 		if (last != NULL) {
13159 			last->dtad_next = act;
13160 		} else {
13161 			first = act;
13162 		}
13163 
13164 		last = act;
13165 
13166 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13167 			continue;
13168 
13169 		if ((difosec = dtrace_dof_sect(dof,
13170 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13171 			goto err;
13172 
13173 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13174 
13175 		if (act->dtad_difo == NULL)
13176 			goto err;
13177 	}
13178 
13179 	ASSERT(first != NULL);
13180 	return (first);
13181 
13182 err:
13183 	for (act = first; act != NULL; act = next) {
13184 		next = act->dtad_next;
13185 		dtrace_actdesc_release(act, vstate);
13186 	}
13187 
13188 	return (NULL);
13189 }
13190 
13191 static dtrace_ecbdesc_t *
dtrace_dof_ecbdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13192 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13193     cred_t *cr)
13194 {
13195 	dtrace_ecbdesc_t *ep;
13196 	dof_ecbdesc_t *ecb;
13197 	dtrace_probedesc_t *desc;
13198 	dtrace_predicate_t *pred = NULL;
13199 
13200 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13201 		dtrace_dof_error(dof, "truncated ECB description");
13202 		return (NULL);
13203 	}
13204 
13205 	if (sec->dofs_align != sizeof (uint64_t)) {
13206 		dtrace_dof_error(dof, "bad alignment in ECB description");
13207 		return (NULL);
13208 	}
13209 
13210 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13211 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13212 
13213 	if (sec == NULL)
13214 		return (NULL);
13215 
13216 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13217 	ep->dted_uarg = ecb->dofe_uarg;
13218 	desc = &ep->dted_probe;
13219 
13220 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13221 		goto err;
13222 
13223 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13224 		if ((sec = dtrace_dof_sect(dof,
13225 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13226 			goto err;
13227 
13228 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13229 			goto err;
13230 
13231 		ep->dted_pred.dtpdd_predicate = pred;
13232 	}
13233 
13234 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13235 		if ((sec = dtrace_dof_sect(dof,
13236 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13237 			goto err;
13238 
13239 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13240 
13241 		if (ep->dted_action == NULL)
13242 			goto err;
13243 	}
13244 
13245 	return (ep);
13246 
13247 err:
13248 	if (pred != NULL)
13249 		dtrace_predicate_release(pred, vstate);
13250 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13251 	return (NULL);
13252 }
13253 
13254 /*
13255  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13256  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
13257  * site of any user SETX relocations to account for load object base address.
13258  * In the future, if we need other relocations, this function can be extended.
13259  */
13260 static int
dtrace_dof_relocate(dof_hdr_t * dof,dof_sec_t * sec,uint64_t ubase)13261 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13262 {
13263 	uintptr_t daddr = (uintptr_t)dof;
13264 	uintptr_t ts_end;
13265 	dof_relohdr_t *dofr =
13266 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13267 	dof_sec_t *ss, *rs, *ts;
13268 	dof_relodesc_t *r;
13269 	uint_t i, n;
13270 
13271 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13272 	    sec->dofs_align != sizeof (dof_secidx_t)) {
13273 		dtrace_dof_error(dof, "invalid relocation header");
13274 		return (-1);
13275 	}
13276 
13277 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13278 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13279 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13280 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
13281 
13282 	if (ss == NULL || rs == NULL || ts == NULL)
13283 		return (-1); /* dtrace_dof_error() has been called already */
13284 
13285 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13286 	    rs->dofs_align != sizeof (uint64_t)) {
13287 		dtrace_dof_error(dof, "invalid relocation section");
13288 		return (-1);
13289 	}
13290 
13291 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13292 	n = rs->dofs_size / rs->dofs_entsize;
13293 
13294 	for (i = 0; i < n; i++) {
13295 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13296 
13297 		switch (r->dofr_type) {
13298 		case DOF_RELO_NONE:
13299 			break;
13300 		case DOF_RELO_SETX:
13301 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13302 			    sizeof (uint64_t) > ts->dofs_size) {
13303 				dtrace_dof_error(dof, "bad relocation offset");
13304 				return (-1);
13305 			}
13306 
13307 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
13308 				dtrace_dof_error(dof, "bad relocation offset");
13309 				return (-1);
13310 			}
13311 
13312 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13313 				dtrace_dof_error(dof, "misaligned setx relo");
13314 				return (-1);
13315 			}
13316 
13317 			*(uint64_t *)taddr += ubase;
13318 			break;
13319 		default:
13320 			dtrace_dof_error(dof, "invalid relocation type");
13321 			return (-1);
13322 		}
13323 
13324 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13325 	}
13326 
13327 	return (0);
13328 }
13329 
13330 /*
13331  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13332  * header:  it should be at the front of a memory region that is at least
13333  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13334  * size.  It need not be validated in any other way.
13335  */
13336 static int
dtrace_dof_slurp(dof_hdr_t * dof,dtrace_vstate_t * vstate,cred_t * cr,dtrace_enabling_t ** enabp,uint64_t ubase,int noprobes)13337 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13338     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13339 {
13340 	uint64_t len = dof->dofh_loadsz, seclen;
13341 	uintptr_t daddr = (uintptr_t)dof;
13342 	dtrace_ecbdesc_t *ep;
13343 	dtrace_enabling_t *enab;
13344 	uint_t i;
13345 
13346 	ASSERT(MUTEX_HELD(&dtrace_lock));
13347 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13348 
13349 	/*
13350 	 * Check the DOF header identification bytes.  In addition to checking
13351 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13352 	 * we can use them later without fear of regressing existing binaries.
13353 	 */
13354 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13355 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13356 		dtrace_dof_error(dof, "DOF magic string mismatch");
13357 		return (-1);
13358 	}
13359 
13360 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13361 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13362 		dtrace_dof_error(dof, "DOF has invalid data model");
13363 		return (-1);
13364 	}
13365 
13366 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13367 		dtrace_dof_error(dof, "DOF encoding mismatch");
13368 		return (-1);
13369 	}
13370 
13371 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13372 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13373 		dtrace_dof_error(dof, "DOF version mismatch");
13374 		return (-1);
13375 	}
13376 
13377 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13378 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13379 		return (-1);
13380 	}
13381 
13382 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13383 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13384 		return (-1);
13385 	}
13386 
13387 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13388 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13389 		return (-1);
13390 	}
13391 
13392 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13393 		if (dof->dofh_ident[i] != 0) {
13394 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13395 			return (-1);
13396 		}
13397 	}
13398 
13399 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13400 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13401 		return (-1);
13402 	}
13403 
13404 	if (dof->dofh_secsize == 0) {
13405 		dtrace_dof_error(dof, "zero section header size");
13406 		return (-1);
13407 	}
13408 
13409 	/*
13410 	 * Check that the section headers don't exceed the amount of DOF
13411 	 * data.  Note that we cast the section size and number of sections
13412 	 * to uint64_t's to prevent possible overflow in the multiplication.
13413 	 */
13414 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13415 
13416 	if (dof->dofh_secoff > len || seclen > len ||
13417 	    dof->dofh_secoff + seclen > len) {
13418 		dtrace_dof_error(dof, "truncated section headers");
13419 		return (-1);
13420 	}
13421 
13422 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13423 		dtrace_dof_error(dof, "misaligned section headers");
13424 		return (-1);
13425 	}
13426 
13427 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13428 		dtrace_dof_error(dof, "misaligned section size");
13429 		return (-1);
13430 	}
13431 
13432 	/*
13433 	 * Take an initial pass through the section headers to be sure that
13434 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13435 	 * set, do not permit sections relating to providers, probes, or args.
13436 	 */
13437 	for (i = 0; i < dof->dofh_secnum; i++) {
13438 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13439 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13440 
13441 		if (noprobes) {
13442 			switch (sec->dofs_type) {
13443 			case DOF_SECT_PROVIDER:
13444 			case DOF_SECT_PROBES:
13445 			case DOF_SECT_PRARGS:
13446 			case DOF_SECT_PROFFS:
13447 				dtrace_dof_error(dof, "illegal sections "
13448 				    "for enabling");
13449 				return (-1);
13450 			}
13451 		}
13452 
13453 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13454 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
13455 			dtrace_dof_error(dof, "loadable section with load "
13456 			    "flag unset");
13457 			return (-1);
13458 		}
13459 
13460 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13461 			continue; /* just ignore non-loadable sections */
13462 
13463 		if (!ISP2(sec->dofs_align)) {
13464 			dtrace_dof_error(dof, "bad section alignment");
13465 			return (-1);
13466 		}
13467 
13468 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13469 			dtrace_dof_error(dof, "misaligned section");
13470 			return (-1);
13471 		}
13472 
13473 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13474 		    sec->dofs_offset + sec->dofs_size > len) {
13475 			dtrace_dof_error(dof, "corrupt section header");
13476 			return (-1);
13477 		}
13478 
13479 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13480 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13481 			dtrace_dof_error(dof, "non-terminating string table");
13482 			return (-1);
13483 		}
13484 	}
13485 
13486 	/*
13487 	 * Take a second pass through the sections and locate and perform any
13488 	 * relocations that are present.  We do this after the first pass to
13489 	 * be sure that all sections have had their headers validated.
13490 	 */
13491 	for (i = 0; i < dof->dofh_secnum; i++) {
13492 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13493 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13494 
13495 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13496 			continue; /* skip sections that are not loadable */
13497 
13498 		switch (sec->dofs_type) {
13499 		case DOF_SECT_URELHDR:
13500 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13501 				return (-1);
13502 			break;
13503 		}
13504 	}
13505 
13506 	if ((enab = *enabp) == NULL)
13507 		enab = *enabp = dtrace_enabling_create(vstate);
13508 
13509 	for (i = 0; i < dof->dofh_secnum; i++) {
13510 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13511 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13512 
13513 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13514 			continue;
13515 
13516 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13517 			dtrace_enabling_destroy(enab);
13518 			*enabp = NULL;
13519 			return (-1);
13520 		}
13521 
13522 		dtrace_enabling_add(enab, ep);
13523 	}
13524 
13525 	return (0);
13526 }
13527 
13528 /*
13529  * Process DOF for any options.  This routine assumes that the DOF has been
13530  * at least processed by dtrace_dof_slurp().
13531  */
13532 static int
dtrace_dof_options(dof_hdr_t * dof,dtrace_state_t * state)13533 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13534 {
13535 	int i, rval;
13536 	uint32_t entsize;
13537 	size_t offs;
13538 	dof_optdesc_t *desc;
13539 
13540 	for (i = 0; i < dof->dofh_secnum; i++) {
13541 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13542 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13543 
13544 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13545 			continue;
13546 
13547 		if (sec->dofs_align != sizeof (uint64_t)) {
13548 			dtrace_dof_error(dof, "bad alignment in "
13549 			    "option description");
13550 			return (EINVAL);
13551 		}
13552 
13553 		if ((entsize = sec->dofs_entsize) == 0) {
13554 			dtrace_dof_error(dof, "zeroed option entry size");
13555 			return (EINVAL);
13556 		}
13557 
13558 		if (entsize < sizeof (dof_optdesc_t)) {
13559 			dtrace_dof_error(dof, "bad option entry size");
13560 			return (EINVAL);
13561 		}
13562 
13563 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13564 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13565 			    (uintptr_t)sec->dofs_offset + offs);
13566 
13567 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13568 				dtrace_dof_error(dof, "non-zero option string");
13569 				return (EINVAL);
13570 			}
13571 
13572 			if (desc->dofo_value == DTRACEOPT_UNSET) {
13573 				dtrace_dof_error(dof, "unset option");
13574 				return (EINVAL);
13575 			}
13576 
13577 			if ((rval = dtrace_state_option(state,
13578 			    desc->dofo_option, desc->dofo_value)) != 0) {
13579 				dtrace_dof_error(dof, "rejected option");
13580 				return (rval);
13581 			}
13582 		}
13583 	}
13584 
13585 	return (0);
13586 }
13587 
13588 /*
13589  * DTrace Consumer State Functions
13590  */
13591 int
dtrace_dstate_init(dtrace_dstate_t * dstate,size_t size)13592 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13593 {
13594 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13595 	void *base;
13596 	uintptr_t limit;
13597 	dtrace_dynvar_t *dvar, *next, *start;
13598 	int i;
13599 
13600 	ASSERT(MUTEX_HELD(&dtrace_lock));
13601 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13602 
13603 	bzero(dstate, sizeof (dtrace_dstate_t));
13604 
13605 	if ((dstate->dtds_chunksize = chunksize) == 0)
13606 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13607 
13608 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
13609 
13610 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13611 		size = min;
13612 
13613 	if ((base = kmem_zalloc(size, KM_NOSLEEP_LAZY)) == NULL)
13614 		return (ENOMEM);
13615 
13616 	dstate->dtds_size = size;
13617 	dstate->dtds_base = base;
13618 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13619 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13620 
13621 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13622 
13623 	if (hashsize != 1 && (hashsize & 1))
13624 		hashsize--;
13625 
13626 	dstate->dtds_hashsize = hashsize;
13627 	dstate->dtds_hash = dstate->dtds_base;
13628 
13629 	/*
13630 	 * Set all of our hash buckets to point to the single sink, and (if
13631 	 * it hasn't already been set), set the sink's hash value to be the
13632 	 * sink sentinel value.  The sink is needed for dynamic variable
13633 	 * lookups to know that they have iterated over an entire, valid hash
13634 	 * chain.
13635 	 */
13636 	for (i = 0; i < hashsize; i++)
13637 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13638 
13639 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13640 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13641 
13642 	/*
13643 	 * Determine number of active CPUs.  Divide free list evenly among
13644 	 * active CPUs.
13645 	 */
13646 	start = (dtrace_dynvar_t *)
13647 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13648 	limit = (uintptr_t)base + size;
13649 
13650 	VERIFY((uintptr_t)start < limit);
13651 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13652 
13653 	maxper = (limit - (uintptr_t)start) / NCPU;
13654 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13655 
13656 	for (i = 0; i < NCPU; i++) {
13657 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13658 
13659 		/*
13660 		 * If we don't even have enough chunks to make it once through
13661 		 * NCPUs, we're just going to allocate everything to the first
13662 		 * CPU.  And if we're on the last CPU, we're going to allocate
13663 		 * whatever is left over.  In either case, we set the limit to
13664 		 * be the limit of the dynamic variable space.
13665 		 */
13666 		if (maxper == 0 || i == NCPU - 1) {
13667 			limit = (uintptr_t)base + size;
13668 			start = NULL;
13669 		} else {
13670 			limit = (uintptr_t)start + maxper;
13671 			start = (dtrace_dynvar_t *)limit;
13672 		}
13673 
13674 		VERIFY(limit <= (uintptr_t)base + size);
13675 
13676 		for (;;) {
13677 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13678 			    dstate->dtds_chunksize);
13679 
13680 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13681 				break;
13682 
13683 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
13684 			    (uintptr_t)dvar <= (uintptr_t)base + size);
13685 			dvar->dtdv_next = next;
13686 			dvar = next;
13687 		}
13688 
13689 		if (maxper == 0)
13690 			break;
13691 	}
13692 
13693 	return (0);
13694 }
13695 
13696 void
dtrace_dstate_fini(dtrace_dstate_t * dstate)13697 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13698 {
13699 	ASSERT(MUTEX_HELD(&cpu_lock));
13700 
13701 	if (dstate->dtds_base == NULL)
13702 		return;
13703 
13704 	kmem_free(dstate->dtds_base, dstate->dtds_size);
13705 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13706 }
13707 
13708 static void
dtrace_vstate_fini(dtrace_vstate_t * vstate)13709 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13710 {
13711 	/*
13712 	 * Logical XOR, where are you?
13713 	 */
13714 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13715 
13716 	if (vstate->dtvs_nglobals > 0) {
13717 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13718 		    sizeof (dtrace_statvar_t *));
13719 	}
13720 
13721 	if (vstate->dtvs_ntlocals > 0) {
13722 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13723 		    sizeof (dtrace_difv_t));
13724 	}
13725 
13726 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13727 
13728 	if (vstate->dtvs_nlocals > 0) {
13729 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13730 		    sizeof (dtrace_statvar_t *));
13731 	}
13732 }
13733 
13734 static void
dtrace_state_clean(dtrace_state_t * state)13735 dtrace_state_clean(dtrace_state_t *state)
13736 {
13737 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13738 		return;
13739 
13740 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13741 	dtrace_speculation_clean(state);
13742 }
13743 
13744 static void
dtrace_state_deadman(dtrace_state_t * state)13745 dtrace_state_deadman(dtrace_state_t *state)
13746 {
13747 	hrtime_t now;
13748 
13749 	dtrace_sync();
13750 
13751 	now = dtrace_gethrtime();
13752 
13753 	if (state != dtrace_anon.dta_state &&
13754 	    now - state->dts_laststatus >= dtrace_deadman_user)
13755 		return;
13756 
13757 	/*
13758 	 * We must be sure that dts_alive never appears to be less than the
13759 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13760 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13761 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13762 	 * the new value.  This assures that dts_alive never appears to be
13763 	 * less than its true value, regardless of the order in which the
13764 	 * stores to the underlying storage are issued.
13765 	 */
13766 	state->dts_alive = INT64_MAX;
13767 	dtrace_membar_producer();
13768 	state->dts_alive = now;
13769 }
13770 
13771 dtrace_state_t *
dtrace_state_create(dev_t * devp,cred_t * cr)13772 dtrace_state_create(dev_t *devp, cred_t *cr)
13773 {
13774 	minor_t minor;
13775 	major_t major;
13776 	char c[30];
13777 	dtrace_state_t *state;
13778 	dtrace_optval_t *opt;
13779 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13780 
13781 	ASSERT(MUTEX_HELD(&dtrace_lock));
13782 	ASSERT(MUTEX_HELD(&cpu_lock));
13783 
13784 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13785 	    VM_BESTFIT | VM_SLEEP);
13786 
13787 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13788 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13789 		return (NULL);
13790 	}
13791 
13792 	state = ddi_get_soft_state(dtrace_softstate, minor);
13793 	state->dts_epid = DTRACE_EPIDNONE + 1;
13794 
13795 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13796 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13797 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13798 
13799 	if (devp != NULL) {
13800 		major = getemajor(*devp);
13801 	} else {
13802 		major = ddi_driver_major(dtrace_devi);
13803 	}
13804 
13805 	state->dts_dev = makedevice(major, minor);
13806 
13807 	if (devp != NULL)
13808 		*devp = state->dts_dev;
13809 
13810 	/*
13811 	 * We allocate NCPU buffers.  On the one hand, this can be quite
13812 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13813 	 * other hand, it saves an additional memory reference in the probe
13814 	 * path.
13815 	 */
13816 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13817 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13818 	state->dts_cleaner = CYCLIC_NONE;
13819 	state->dts_deadman = CYCLIC_NONE;
13820 	state->dts_vstate.dtvs_state = state;
13821 
13822 	for (i = 0; i < DTRACEOPT_MAX; i++)
13823 		state->dts_options[i] = DTRACEOPT_UNSET;
13824 
13825 	/*
13826 	 * Set the default options.
13827 	 */
13828 	opt = state->dts_options;
13829 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13830 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13831 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13832 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13833 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13834 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13835 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13836 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13837 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13838 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13839 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13840 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13841 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13842 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13843 
13844 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13845 
13846 	/*
13847 	 * Depending on the user credentials, we set flag bits which alter probe
13848 	 * visibility or the amount of destructiveness allowed.  In the case of
13849 	 * actual anonymous tracing, or the possession of all privileges, all of
13850 	 * the normal checks are bypassed.
13851 	 */
13852 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13853 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13854 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13855 	} else {
13856 		/*
13857 		 * Set up the credentials for this instantiation.  We take a
13858 		 * hold on the credential to prevent it from disappearing on
13859 		 * us; this in turn prevents the zone_t referenced by this
13860 		 * credential from disappearing.  This means that we can
13861 		 * examine the credential and the zone from probe context.
13862 		 */
13863 		crhold(cr);
13864 		state->dts_cred.dcr_cred = cr;
13865 
13866 		/*
13867 		 * CRA_PROC means "we have *some* privilege for dtrace" and
13868 		 * unlocks the use of variables like pid, zonename, etc.
13869 		 */
13870 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13871 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13872 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13873 		}
13874 
13875 		/*
13876 		 * dtrace_user allows use of syscall and profile providers.
13877 		 * If the user also has proc_owner and/or proc_zone, we
13878 		 * extend the scope to include additional visibility and
13879 		 * destructive power.
13880 		 */
13881 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13882 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13883 				state->dts_cred.dcr_visible |=
13884 				    DTRACE_CRV_ALLPROC;
13885 
13886 				state->dts_cred.dcr_action |=
13887 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13888 			}
13889 
13890 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13891 				state->dts_cred.dcr_visible |=
13892 				    DTRACE_CRV_ALLZONE;
13893 
13894 				state->dts_cred.dcr_action |=
13895 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13896 			}
13897 
13898 			/*
13899 			 * If we have all privs in whatever zone this is,
13900 			 * we can do destructive things to processes which
13901 			 * have altered credentials.
13902 			 */
13903 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13904 			    cr->cr_zone->zone_privset)) {
13905 				state->dts_cred.dcr_action |=
13906 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13907 			}
13908 		}
13909 
13910 		/*
13911 		 * Holding the dtrace_kernel privilege also implies that
13912 		 * the user has the dtrace_user privilege from a visibility
13913 		 * perspective.  But without further privileges, some
13914 		 * destructive actions are not available.
13915 		 */
13916 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13917 			/*
13918 			 * Make all probes in all zones visible.  However,
13919 			 * this doesn't mean that all actions become available
13920 			 * to all zones.
13921 			 */
13922 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13923 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13924 
13925 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13926 			    DTRACE_CRA_PROC;
13927 			/*
13928 			 * Holding proc_owner means that destructive actions
13929 			 * for *this* zone are allowed.
13930 			 */
13931 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13932 				state->dts_cred.dcr_action |=
13933 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13934 
13935 			/*
13936 			 * Holding proc_zone means that destructive actions
13937 			 * for this user/group ID in all zones is allowed.
13938 			 */
13939 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13940 				state->dts_cred.dcr_action |=
13941 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13942 
13943 			/*
13944 			 * If we have all privs in whatever zone this is,
13945 			 * we can do destructive things to processes which
13946 			 * have altered credentials.
13947 			 */
13948 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13949 			    cr->cr_zone->zone_privset)) {
13950 				state->dts_cred.dcr_action |=
13951 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13952 			}
13953 		}
13954 
13955 		/*
13956 		 * Holding the dtrace_proc privilege gives control over fasttrap
13957 		 * and pid providers.  We need to grant wider destructive
13958 		 * privileges in the event that the user has proc_owner and/or
13959 		 * proc_zone.
13960 		 */
13961 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13962 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13963 				state->dts_cred.dcr_action |=
13964 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13965 
13966 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13967 				state->dts_cred.dcr_action |=
13968 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13969 		}
13970 	}
13971 
13972 	return (state);
13973 }
13974 
13975 static int
dtrace_state_buffer(dtrace_state_t * state,dtrace_buffer_t * buf,int which)13976 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13977 {
13978 	dtrace_optval_t *opt = state->dts_options, size;
13979 	processorid_t cpu;
13980 	int flags = 0, rval, factor, divisor = 1;
13981 
13982 	ASSERT(MUTEX_HELD(&dtrace_lock));
13983 	ASSERT(MUTEX_HELD(&cpu_lock));
13984 	ASSERT(which < DTRACEOPT_MAX);
13985 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13986 	    (state == dtrace_anon.dta_state &&
13987 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13988 
13989 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13990 		return (0);
13991 
13992 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13993 		cpu = opt[DTRACEOPT_CPU];
13994 
13995 	if (which == DTRACEOPT_SPECSIZE)
13996 		flags |= DTRACEBUF_NOSWITCH;
13997 
13998 	if (which == DTRACEOPT_BUFSIZE) {
13999 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14000 			flags |= DTRACEBUF_RING;
14001 
14002 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14003 			flags |= DTRACEBUF_FILL;
14004 
14005 		if (state != dtrace_anon.dta_state ||
14006 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14007 			flags |= DTRACEBUF_INACTIVE;
14008 	}
14009 
14010 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14011 		/*
14012 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14013 		 * aligned, drop it down by the difference.
14014 		 */
14015 		if (size & (sizeof (uint64_t) - 1))
14016 			size -= size & (sizeof (uint64_t) - 1);
14017 
14018 		if (size < state->dts_reserve) {
14019 			/*
14020 			 * Buffers always must be large enough to accommodate
14021 			 * their prereserved space.  We return E2BIG instead
14022 			 * of ENOMEM in this case to allow for user-level
14023 			 * software to differentiate the cases.
14024 			 */
14025 			return (E2BIG);
14026 		}
14027 
14028 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14029 
14030 		if (rval != ENOMEM) {
14031 			opt[which] = size;
14032 			return (rval);
14033 		}
14034 
14035 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14036 			return (rval);
14037 
14038 		for (divisor = 2; divisor < factor; divisor <<= 1)
14039 			continue;
14040 	}
14041 
14042 	return (ENOMEM);
14043 }
14044 
14045 static int
dtrace_state_buffers(dtrace_state_t * state)14046 dtrace_state_buffers(dtrace_state_t *state)
14047 {
14048 	dtrace_speculation_t *spec = state->dts_speculations;
14049 	int rval, i;
14050 
14051 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14052 	    DTRACEOPT_BUFSIZE)) != 0)
14053 		return (rval);
14054 
14055 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14056 	    DTRACEOPT_AGGSIZE)) != 0)
14057 		return (rval);
14058 
14059 	for (i = 0; i < state->dts_nspeculations; i++) {
14060 		if ((rval = dtrace_state_buffer(state,
14061 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14062 			return (rval);
14063 	}
14064 
14065 	return (0);
14066 }
14067 
14068 static void
dtrace_state_prereserve(dtrace_state_t * state)14069 dtrace_state_prereserve(dtrace_state_t *state)
14070 {
14071 	dtrace_ecb_t *ecb;
14072 	dtrace_probe_t *probe;
14073 
14074 	state->dts_reserve = 0;
14075 
14076 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14077 		return;
14078 
14079 	/*
14080 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14081 	 * prereserved space to be the space required by the END probes.
14082 	 */
14083 	probe = dtrace_probes[dtrace_probeid_end - 1];
14084 	ASSERT(probe != NULL);
14085 
14086 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14087 		if (ecb->dte_state != state)
14088 			continue;
14089 
14090 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14091 	}
14092 }
14093 
14094 static int
dtrace_state_go(dtrace_state_t * state,processorid_t * cpu)14095 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14096 {
14097 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14098 	dtrace_speculation_t *spec;
14099 	dtrace_buffer_t *buf;
14100 	cyc_handler_t hdlr;
14101 	cyc_time_t when;
14102 	int rval = 0, i, j, bufsize = NCPU * sizeof (dtrace_buffer_t);
14103 	dtrace_icookie_t cookie;
14104 
14105 	mutex_enter(&cpu_lock);
14106 	mutex_enter(&dtrace_lock);
14107 
14108 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14109 		rval = EBUSY;
14110 		goto out;
14111 	}
14112 
14113 	/*
14114 	 * Before we can perform any checks, we must prime all of the
14115 	 * retained enablings that correspond to this state.
14116 	 */
14117 	dtrace_enabling_prime(state);
14118 
14119 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14120 		rval = EACCES;
14121 		goto out;
14122 	}
14123 
14124 	dtrace_state_prereserve(state);
14125 
14126 	/*
14127 	 * Now we want to do is try to allocate our speculations.
14128 	 * We do not automatically resize the number of speculations; if
14129 	 * this fails, we will fail the operation.
14130 	 */
14131 	nspec = opt[DTRACEOPT_NSPEC];
14132 	ASSERT(nspec != DTRACEOPT_UNSET);
14133 
14134 	if (nspec > INT_MAX) {
14135 		rval = ENOMEM;
14136 		goto out;
14137 	}
14138 
14139 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14140 	    KM_NOSLEEP_LAZY);
14141 
14142 	if (spec == NULL) {
14143 		rval = ENOMEM;
14144 		goto out;
14145 	}
14146 
14147 	state->dts_speculations = spec;
14148 	state->dts_nspeculations = (int)nspec;
14149 
14150 	for (i = 0; i < nspec; i++) {
14151 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP_LAZY)) == NULL) {
14152 			rval = ENOMEM;
14153 			goto err;
14154 		}
14155 
14156 		spec[i].dtsp_buffer = buf;
14157 	}
14158 
14159 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14160 		if (dtrace_anon.dta_state == NULL) {
14161 			rval = ENOENT;
14162 			goto out;
14163 		}
14164 
14165 		if (state->dts_necbs != 0) {
14166 			rval = EALREADY;
14167 			goto out;
14168 		}
14169 
14170 		state->dts_anon = dtrace_anon_grab();
14171 		ASSERT(state->dts_anon != NULL);
14172 		state = state->dts_anon;
14173 
14174 		/*
14175 		 * We want "grabanon" to be set in the grabbed state, so we'll
14176 		 * copy that option value from the grabbing state into the
14177 		 * grabbed state.
14178 		 */
14179 		state->dts_options[DTRACEOPT_GRABANON] =
14180 		    opt[DTRACEOPT_GRABANON];
14181 
14182 		*cpu = dtrace_anon.dta_beganon;
14183 
14184 		/*
14185 		 * If the anonymous state is active (as it almost certainly
14186 		 * is if the anonymous enabling ultimately matched anything),
14187 		 * we don't allow any further option processing -- but we
14188 		 * don't return failure.
14189 		 */
14190 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14191 			goto out;
14192 	}
14193 
14194 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14195 	    opt[DTRACEOPT_AGGSIZE] != 0) {
14196 		if (state->dts_aggregations == NULL) {
14197 			/*
14198 			 * We're not going to create an aggregation buffer
14199 			 * because we don't have any ECBs that contain
14200 			 * aggregations -- set this option to 0.
14201 			 */
14202 			opt[DTRACEOPT_AGGSIZE] = 0;
14203 		} else {
14204 			/*
14205 			 * If we have an aggregation buffer, we must also have
14206 			 * a buffer to use as scratch.
14207 			 */
14208 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14209 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14210 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14211 			}
14212 		}
14213 	}
14214 
14215 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14216 	    opt[DTRACEOPT_SPECSIZE] != 0) {
14217 		if (!state->dts_speculates) {
14218 			/*
14219 			 * We're not going to create speculation buffers
14220 			 * because we don't have any ECBs that actually
14221 			 * speculate -- set the speculation size to 0.
14222 			 */
14223 			opt[DTRACEOPT_SPECSIZE] = 0;
14224 		}
14225 	}
14226 
14227 	/*
14228 	 * The bare minimum size for any buffer that we're actually going to
14229 	 * do anything to is sizeof (uint64_t).
14230 	 */
14231 	sz = sizeof (uint64_t);
14232 
14233 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14234 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14235 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14236 		/*
14237 		 * A buffer size has been explicitly set to 0 (or to a size
14238 		 * that will be adjusted to 0) and we need the space -- we
14239 		 * need to return failure.  We return ENOSPC to differentiate
14240 		 * it from failing to allocate a buffer due to failure to meet
14241 		 * the reserve (for which we return E2BIG).
14242 		 */
14243 		rval = ENOSPC;
14244 		goto out;
14245 	}
14246 
14247 	if ((rval = dtrace_state_buffers(state)) != 0)
14248 		goto err;
14249 
14250 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14251 		sz = dtrace_dstate_defsize;
14252 
14253 	do {
14254 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14255 
14256 		if (rval == 0)
14257 			break;
14258 
14259 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14260 			goto err;
14261 	} while (sz >>= 1);
14262 
14263 	opt[DTRACEOPT_DYNVARSIZE] = sz;
14264 
14265 	if (rval != 0)
14266 		goto err;
14267 
14268 	/*
14269 	 * We are almost ready to go!  As a final step, we are going to
14270 	 * actually enable our ECBs.  (We wait to do this until now to
14271 	 * minimize the amount of DTrace itself that we run through with
14272 	 * potentially many probes enabled.)  Once everything is enabled, we
14273 	 * are at the point of no return:  our state will be made active.
14274 	 */
14275 	for (i = 0; i < state->dts_necbs; i++) {
14276 		dtrace_ecb_t *ecb;
14277 		dtrace_probe_t *probe;
14278 
14279 		if ((ecb = state->dts_ecbs[i]) == NULL)
14280 			continue;
14281 
14282 		/*
14283 		 * Any ECB on a DTrace-provided probe has already been
14284 		 * enabled; skip over it.
14285 		 */
14286 		if ((probe = ecb->dte_probe) != NULL &&
14287 		    probe->dtpr_provider == dtrace_provider) {
14288 			continue;
14289 		}
14290 
14291 		if (dtrace_ecb_enable(ecb) < 0) {
14292 			/*
14293 			 * In the unlikely event that a provider is failing to
14294 			 * enable the probe, disable all of the ECBs that we
14295 			 * have enabled and kick out with a distinctive error
14296 			 * code.
14297 			 */
14298 			for (j = i - 1; j >= 0; j--) {
14299 				if ((ecb = state->dts_ecbs[j]) == NULL)
14300 					continue;
14301 
14302 				/*
14303 				 * And skip back over any ECB that corresponds
14304 				 * to a DTrace-provided probe...
14305 				 */
14306 				if ((probe = ecb->dte_probe) != NULL &&
14307 				    probe->dtpr_provider == dtrace_provider) {
14308 					continue;
14309 				}
14310 
14311 				dtrace_ecb_disable(ecb);
14312 			}
14313 
14314 			rval = EIO;
14315 			goto err;
14316 		}
14317 	}
14318 
14319 	/*
14320 	 * We have just enabled a bunch of ECBs; make sure that all CPUs
14321 	 * have seen it before progressing.
14322 	 */
14323 	dtrace_sync();
14324 
14325 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14326 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14327 
14328 	if (opt[DTRACEOPT_CLEANRATE] == 0)
14329 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14330 
14331 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14332 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14333 
14334 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14335 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14336 
14337 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14338 	hdlr.cyh_arg = state;
14339 	hdlr.cyh_level = CY_LOW_LEVEL;
14340 
14341 	when.cyt_when = 0;
14342 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14343 
14344 	state->dts_cleaner = cyclic_add(&hdlr, &when);
14345 
14346 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14347 	hdlr.cyh_arg = state;
14348 	hdlr.cyh_level = CY_LOW_LEVEL;
14349 
14350 	when.cyt_when = 0;
14351 	when.cyt_interval = dtrace_deadman_interval;
14352 
14353 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14354 	state->dts_deadman = cyclic_add(&hdlr, &when);
14355 
14356 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14357 
14358 	if (state->dts_getf != 0 &&
14359 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14360 		/*
14361 		 * We don't have kernel privs but we have at least one call
14362 		 * to getf(); we need to bump our zone's count, and (if
14363 		 * this is the first enabling to have an unprivileged call
14364 		 * to getf()) we need to hook into closef().
14365 		 */
14366 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14367 
14368 		if (dtrace_getf++ == 0) {
14369 			ASSERT(dtrace_closef == NULL);
14370 			dtrace_closef = dtrace_getf_barrier;
14371 		}
14372 	}
14373 
14374 	/*
14375 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14376 	 * interrupts here both to record the CPU on which we fired the BEGIN
14377 	 * probe (the data from this CPU will be processed first at user
14378 	 * level) and to manually activate the buffer for this CPU.
14379 	 */
14380 	cookie = dtrace_interrupt_disable();
14381 	*cpu = CPU->cpu_id;
14382 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14383 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14384 
14385 	dtrace_probe(dtrace_probeid_begin,
14386 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14387 	dtrace_interrupt_enable(cookie);
14388 	/*
14389 	 * We may have had an exit action from a BEGIN probe; only change our
14390 	 * state to ACTIVE if we're still in WARMUP.
14391 	 */
14392 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14393 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14394 
14395 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14396 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14397 
14398 	/*
14399 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14400 	 * want each CPU to transition its principal buffer out of the
14401 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14402 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14403 	 * atomically transition from processing none of a state's ECBs to
14404 	 * processing all of them.
14405 	 */
14406 	dtrace_xcall(DTRACE_CPUALL,
14407 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14408 	goto out;
14409 
14410 err:
14411 	dtrace_buffer_free(state->dts_buffer);
14412 	dtrace_buffer_free(state->dts_aggbuffer);
14413 
14414 	if ((nspec = state->dts_nspeculations) == 0) {
14415 		ASSERT(state->dts_speculations == NULL);
14416 		goto out;
14417 	}
14418 
14419 	spec = state->dts_speculations;
14420 	ASSERT(spec != NULL);
14421 
14422 	for (i = 0; i < state->dts_nspeculations; i++) {
14423 		if ((buf = spec[i].dtsp_buffer) == NULL)
14424 			break;
14425 
14426 		dtrace_buffer_free(buf);
14427 		kmem_free(buf, bufsize);
14428 	}
14429 
14430 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14431 	state->dts_nspeculations = 0;
14432 	state->dts_speculations = NULL;
14433 
14434 out:
14435 	mutex_exit(&dtrace_lock);
14436 	mutex_exit(&cpu_lock);
14437 
14438 	return (rval);
14439 }
14440 
14441 static int
dtrace_state_stop(dtrace_state_t * state,processorid_t * cpu)14442 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14443 {
14444 	dtrace_icookie_t cookie;
14445 
14446 	ASSERT(MUTEX_HELD(&dtrace_lock));
14447 
14448 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14449 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14450 		return (EINVAL);
14451 
14452 	/*
14453 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14454 	 * to be sure that every CPU has seen it.  See below for the details
14455 	 * on why this is done.
14456 	 */
14457 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14458 	dtrace_sync();
14459 
14460 	/*
14461 	 * By this point, it is impossible for any CPU to be still processing
14462 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14463 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14464 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14465 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14466 	 * iff we're in the END probe.
14467 	 */
14468 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14469 	dtrace_sync();
14470 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14471 
14472 	/*
14473 	 * Finally, we can release the reserve and call the END probe.  We
14474 	 * disable interrupts across calling the END probe to allow us to
14475 	 * return the CPU on which we actually called the END probe.  This
14476 	 * allows user-land to be sure that this CPU's principal buffer is
14477 	 * processed last.
14478 	 */
14479 	state->dts_reserve = 0;
14480 
14481 	cookie = dtrace_interrupt_disable();
14482 	*cpu = CPU->cpu_id;
14483 	dtrace_probe(dtrace_probeid_end,
14484 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14485 	dtrace_interrupt_enable(cookie);
14486 
14487 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14488 	dtrace_sync();
14489 
14490 	if (state->dts_getf != 0 &&
14491 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14492 		/*
14493 		 * We don't have kernel privs but we have at least one call
14494 		 * to getf(); we need to lower our zone's count, and (if
14495 		 * this is the last enabling to have an unprivileged call
14496 		 * to getf()) we need to clear the closef() hook.
14497 		 */
14498 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14499 		ASSERT(dtrace_closef == dtrace_getf_barrier);
14500 		ASSERT(dtrace_getf > 0);
14501 
14502 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14503 
14504 		if (--dtrace_getf == 0)
14505 			dtrace_closef = NULL;
14506 	}
14507 
14508 	return (0);
14509 }
14510 
14511 static int
dtrace_state_option(dtrace_state_t * state,dtrace_optid_t option,dtrace_optval_t val)14512 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14513     dtrace_optval_t val)
14514 {
14515 	ASSERT(MUTEX_HELD(&dtrace_lock));
14516 
14517 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14518 		return (EBUSY);
14519 
14520 	if (option >= DTRACEOPT_MAX)
14521 		return (EINVAL);
14522 
14523 	if (option != DTRACEOPT_CPU && val < 0)
14524 		return (EINVAL);
14525 
14526 	switch (option) {
14527 	case DTRACEOPT_DESTRUCTIVE:
14528 		if (dtrace_destructive_disallow)
14529 			return (EACCES);
14530 
14531 		state->dts_cred.dcr_destructive = 1;
14532 		break;
14533 
14534 	case DTRACEOPT_BUFSIZE:
14535 	case DTRACEOPT_DYNVARSIZE:
14536 	case DTRACEOPT_AGGSIZE:
14537 	case DTRACEOPT_SPECSIZE:
14538 	case DTRACEOPT_STRSIZE:
14539 		if (val < 0)
14540 			return (EINVAL);
14541 
14542 		if (val >= LONG_MAX) {
14543 			/*
14544 			 * If this is an otherwise negative value, set it to
14545 			 * the highest multiple of 128m less than LONG_MAX.
14546 			 * Technically, we're adjusting the size without
14547 			 * regard to the buffer resizing policy, but in fact,
14548 			 * this has no effect -- if we set the buffer size to
14549 			 * ~LONG_MAX and the buffer policy is ultimately set to
14550 			 * be "manual", the buffer allocation is guaranteed to
14551 			 * fail, if only because the allocation requires two
14552 			 * buffers.  (We set the the size to the highest
14553 			 * multiple of 128m because it ensures that the size
14554 			 * will remain a multiple of a megabyte when
14555 			 * repeatedly halved -- all the way down to 15m.)
14556 			 */
14557 			val = LONG_MAX - (1 << 27) + 1;
14558 		}
14559 	}
14560 
14561 	state->dts_options[option] = val;
14562 
14563 	return (0);
14564 }
14565 
14566 static void
dtrace_state_destroy(dtrace_state_t * state)14567 dtrace_state_destroy(dtrace_state_t *state)
14568 {
14569 	dtrace_ecb_t *ecb;
14570 	dtrace_vstate_t *vstate = &state->dts_vstate;
14571 	minor_t minor = getminor(state->dts_dev);
14572 	int i, pass, bufsize = NCPU * sizeof (dtrace_buffer_t);
14573 	dtrace_speculation_t *spec = state->dts_speculations;
14574 	int nspec = state->dts_nspeculations;
14575 
14576 	ASSERT(MUTEX_HELD(&dtrace_lock));
14577 	ASSERT(MUTEX_HELD(&cpu_lock));
14578 
14579 	/*
14580 	 * First, retract any retained enablings for this state.
14581 	 */
14582 	dtrace_enabling_retract(state);
14583 	ASSERT(state->dts_nretained == 0);
14584 
14585 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14586 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14587 		/*
14588 		 * We have managed to come into dtrace_state_destroy() on a
14589 		 * hot enabling -- almost certainly because of a disorderly
14590 		 * shutdown of a consumer.  (That is, a consumer that is
14591 		 * exiting without having called dtrace_stop().) In this case,
14592 		 * we're going to set our activity to be KILLED, and then
14593 		 * issue a sync to be sure that everyone is out of probe
14594 		 * context before we start blowing away ECBs.
14595 		 */
14596 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14597 		dtrace_sync();
14598 	}
14599 
14600 	/*
14601 	 * Release the credential hold we took in dtrace_state_create().
14602 	 */
14603 	if (state->dts_cred.dcr_cred != NULL)
14604 		crfree(state->dts_cred.dcr_cred);
14605 
14606 	/*
14607 	 * Now we can safely disable and destroy any enabled probes.  We want
14608 	 * to optimize for system performance here, which paradoxically is
14609 	 * going to result in more work:  the enabled probe effect of kernel
14610 	 * probes can be high, and if we have any of those enabled, we want
14611 	 * to get them out of the way first.  In addition, we want to minimize
14612 	 * calls to dtrace_sync() while there remain any kernel probes
14613 	 * enabled:  that code path requires cross calling all CPUs, and -- if
14614 	 * instrumented -- can result in debilitatingly slow execution times on
14615 	 * high CPU machines.  So we take four passes through the ECBs here:
14616 	 *
14617 	 *   1. Disable ECBs on DTRACE_PRIV_KERNEL probes
14618 	 *   2. Destroy ECBs on DTRACE_PRIV_KERNEL probes
14619 	 *   3. Disable ECBs on non-DTRACE_PRIV_KERNEL probes
14620 	 *   4. Destroy ECBs on non-DTRACE_PRIV_KERNEL probes
14621 	 *
14622 	 * (Channeling the benevolent spirits of Aho, Weinberger, and Kernighan,
14623 	 * we number our passes from 1 rather than 0.)
14624 	 */
14625 	for (pass = 1; pass <= 4; pass++) {
14626 		boolean_t only_kernel = (pass == 1 || pass == 2);
14627 		boolean_t destroy = (pass == 2 || pass == 4);
14628 
14629 		if (destroy) {
14630 			dtrace_sync();
14631 		}
14632 
14633 		for (i = 0; i < state->dts_necbs; i++) {
14634 			if ((ecb = state->dts_ecbs[i]) == NULL)
14635 				continue;
14636 
14637 			if (only_kernel && ecb->dte_probe != NULL) {
14638 				dtrace_probe_t *probe = ecb->dte_probe;
14639 				dtrace_provider_t *prov = probe->dtpr_provider;
14640 				const uint32_t match = DTRACE_PRIV_KERNEL;
14641 
14642 				if (!(prov->dtpv_priv.dtpp_flags & match))
14643 					continue;
14644 			}
14645 
14646 			if (!destroy) {
14647 				dtrace_ecb_disable(ecb);
14648 			} else {
14649 				dtrace_ecb_destroy(ecb);
14650 			}
14651 		}
14652 	}
14653 
14654 	/*
14655 	 * Before we free the buffers, perform one more sync to assure that
14656 	 * every CPU is out of probe context.
14657 	 */
14658 	dtrace_sync();
14659 
14660 	dtrace_buffer_free(state->dts_buffer);
14661 	dtrace_buffer_free(state->dts_aggbuffer);
14662 
14663 	for (i = 0; i < nspec; i++)
14664 		dtrace_buffer_free(spec[i].dtsp_buffer);
14665 
14666 	if (state->dts_cleaner != CYCLIC_NONE)
14667 		cyclic_remove(state->dts_cleaner);
14668 
14669 	if (state->dts_deadman != CYCLIC_NONE)
14670 		cyclic_remove(state->dts_deadman);
14671 
14672 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14673 	dtrace_vstate_fini(vstate);
14674 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14675 
14676 	if (state->dts_aggregations != NULL) {
14677 #ifdef DEBUG
14678 		for (i = 0; i < state->dts_naggregations; i++)
14679 			ASSERT(state->dts_aggregations[i] == NULL);
14680 #endif
14681 		ASSERT(state->dts_naggregations > 0);
14682 		kmem_free(state->dts_aggregations,
14683 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14684 	}
14685 
14686 	kmem_free(state->dts_buffer, bufsize);
14687 	kmem_free(state->dts_aggbuffer, bufsize);
14688 
14689 	for (i = 0; i < nspec; i++)
14690 		kmem_free(spec[i].dtsp_buffer, bufsize);
14691 
14692 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14693 
14694 	dtrace_format_destroy(state);
14695 
14696 	vmem_destroy(state->dts_aggid_arena);
14697 	ddi_soft_state_free(dtrace_softstate, minor);
14698 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14699 }
14700 
14701 /*
14702  * DTrace Anonymous Enabling Functions
14703  */
14704 static dtrace_state_t *
dtrace_anon_grab(void)14705 dtrace_anon_grab(void)
14706 {
14707 	dtrace_state_t *state;
14708 
14709 	ASSERT(MUTEX_HELD(&dtrace_lock));
14710 
14711 	if ((state = dtrace_anon.dta_state) == NULL) {
14712 		ASSERT(dtrace_anon.dta_enabling == NULL);
14713 		return (NULL);
14714 	}
14715 
14716 	ASSERT(dtrace_anon.dta_enabling != NULL);
14717 	ASSERT(dtrace_retained != NULL);
14718 
14719 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14720 	dtrace_anon.dta_enabling = NULL;
14721 	dtrace_anon.dta_state = NULL;
14722 
14723 	return (state);
14724 }
14725 
14726 static void
dtrace_anon_property(void)14727 dtrace_anon_property(void)
14728 {
14729 	int i, rv;
14730 	dtrace_state_t *state;
14731 	dof_hdr_t *dof;
14732 	char c[32];		/* enough for "dof-data-" + digits */
14733 
14734 	ASSERT(MUTEX_HELD(&dtrace_lock));
14735 	ASSERT(MUTEX_HELD(&cpu_lock));
14736 
14737 	for (i = 0; ; i++) {
14738 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14739 
14740 		dtrace_err_verbose = 1;
14741 
14742 		if ((dof = dtrace_dof_property(c)) == NULL) {
14743 			dtrace_err_verbose = 0;
14744 			break;
14745 		}
14746 
14747 		/*
14748 		 * We want to create anonymous state, so we need to transition
14749 		 * the kernel debugger to indicate that DTrace is active.  If
14750 		 * this fails (e.g. because the debugger has modified text in
14751 		 * some way), we won't continue with the processing.
14752 		 */
14753 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14754 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14755 			    "enabling ignored.");
14756 			dtrace_dof_destroy(dof);
14757 			break;
14758 		}
14759 
14760 		/*
14761 		 * If we haven't allocated an anonymous state, we'll do so now.
14762 		 */
14763 		if ((state = dtrace_anon.dta_state) == NULL) {
14764 			state = dtrace_state_create(NULL, NULL);
14765 			dtrace_anon.dta_state = state;
14766 
14767 			if (state == NULL) {
14768 				/*
14769 				 * This basically shouldn't happen:  the only
14770 				 * failure mode from dtrace_state_create() is a
14771 				 * failure of ddi_soft_state_zalloc() that
14772 				 * itself should never happen.  Still, the
14773 				 * interface allows for a failure mode, and
14774 				 * we want to fail as gracefully as possible:
14775 				 * we'll emit an error message and cease
14776 				 * processing anonymous state in this case.
14777 				 */
14778 				cmn_err(CE_WARN, "failed to create "
14779 				    "anonymous state");
14780 				dtrace_dof_destroy(dof);
14781 				break;
14782 			}
14783 		}
14784 
14785 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14786 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14787 
14788 		if (rv == 0)
14789 			rv = dtrace_dof_options(dof, state);
14790 
14791 		dtrace_err_verbose = 0;
14792 		dtrace_dof_destroy(dof);
14793 
14794 		if (rv != 0) {
14795 			/*
14796 			 * This is malformed DOF; chuck any anonymous state
14797 			 * that we created.
14798 			 */
14799 			ASSERT(dtrace_anon.dta_enabling == NULL);
14800 			dtrace_state_destroy(state);
14801 			dtrace_anon.dta_state = NULL;
14802 			break;
14803 		}
14804 
14805 		ASSERT(dtrace_anon.dta_enabling != NULL);
14806 	}
14807 
14808 	if (dtrace_anon.dta_enabling != NULL) {
14809 		int rval;
14810 
14811 		/*
14812 		 * dtrace_enabling_retain() can only fail because we are
14813 		 * trying to retain more enablings than are allowed -- but
14814 		 * we only have one anonymous enabling, and we are guaranteed
14815 		 * to be allowed at least one retained enabling; we assert
14816 		 * that dtrace_enabling_retain() returns success.
14817 		 */
14818 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14819 		ASSERT(rval == 0);
14820 
14821 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14822 	}
14823 }
14824 
14825 /*
14826  * DTrace Helper Functions
14827  */
14828 static void
dtrace_helper_trace(dtrace_helper_action_t * helper,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,int where)14829 dtrace_helper_trace(dtrace_helper_action_t *helper,
14830     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14831 {
14832 	uint32_t size, next, nnext, i;
14833 	dtrace_helptrace_t *ent, *buffer;
14834 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14835 
14836 	if ((buffer = dtrace_helptrace_buffer) == NULL)
14837 		return;
14838 
14839 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14840 
14841 	/*
14842 	 * What would a tracing framework be without its own tracing
14843 	 * framework?  (Well, a hell of a lot simpler, for starters...)
14844 	 */
14845 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14846 	    sizeof (uint64_t) - sizeof (uint64_t);
14847 
14848 	/*
14849 	 * Iterate until we can allocate a slot in the trace buffer.
14850 	 */
14851 	do {
14852 		next = dtrace_helptrace_next;
14853 
14854 		if (next + size < dtrace_helptrace_bufsize) {
14855 			nnext = next + size;
14856 		} else {
14857 			nnext = size;
14858 		}
14859 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14860 
14861 	/*
14862 	 * We have our slot; fill it in.
14863 	 */
14864 	if (nnext == size) {
14865 		dtrace_helptrace_wrapped++;
14866 		next = 0;
14867 	}
14868 
14869 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14870 	ent->dtht_helper = helper;
14871 	ent->dtht_where = where;
14872 	ent->dtht_nlocals = vstate->dtvs_nlocals;
14873 
14874 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14875 	    mstate->dtms_fltoffs : -1;
14876 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14877 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14878 
14879 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14880 		dtrace_statvar_t *svar;
14881 
14882 		if ((svar = vstate->dtvs_locals[i]) == NULL)
14883 			continue;
14884 
14885 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14886 		ent->dtht_locals[i] =
14887 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14888 	}
14889 }
14890 
14891 static uint64_t
dtrace_helper(int which,dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t arg0,uint64_t arg1)14892 dtrace_helper(int which, dtrace_mstate_t *mstate,
14893     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14894 {
14895 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14896 	uint64_t sarg0 = mstate->dtms_arg[0];
14897 	uint64_t sarg1 = mstate->dtms_arg[1];
14898 	uint64_t rval;
14899 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14900 	dtrace_helper_action_t *helper;
14901 	dtrace_vstate_t *vstate;
14902 	dtrace_difo_t *pred;
14903 	int i, trace = dtrace_helptrace_buffer != NULL;
14904 
14905 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14906 
14907 	if (helpers == NULL)
14908 		return (0);
14909 
14910 	if ((helper = helpers->dthps_actions[which]) == NULL)
14911 		return (0);
14912 
14913 	vstate = &helpers->dthps_vstate;
14914 	mstate->dtms_arg[0] = arg0;
14915 	mstate->dtms_arg[1] = arg1;
14916 
14917 	/*
14918 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14919 	 * we'll call the corresponding actions.  Note that the below calls
14920 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14921 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14922 	 * the stored DIF offset with its own (which is the desired behavior).
14923 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14924 	 * from machine state; this is okay, too.
14925 	 */
14926 	for (; helper != NULL; helper = helper->dtha_next) {
14927 		if ((pred = helper->dtha_predicate) != NULL) {
14928 			if (trace)
14929 				dtrace_helper_trace(helper, mstate, vstate, 0);
14930 
14931 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14932 				goto next;
14933 
14934 			if (*flags & CPU_DTRACE_FAULT)
14935 				goto err;
14936 		}
14937 
14938 		for (i = 0; i < helper->dtha_nactions; i++) {
14939 			if (trace)
14940 				dtrace_helper_trace(helper,
14941 				    mstate, vstate, i + 1);
14942 
14943 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14944 			    mstate, vstate, state);
14945 
14946 			if (*flags & CPU_DTRACE_FAULT)
14947 				goto err;
14948 		}
14949 
14950 next:
14951 		if (trace)
14952 			dtrace_helper_trace(helper, mstate, vstate,
14953 			    DTRACE_HELPTRACE_NEXT);
14954 	}
14955 
14956 	if (trace)
14957 		dtrace_helper_trace(helper, mstate, vstate,
14958 		    DTRACE_HELPTRACE_DONE);
14959 
14960 	/*
14961 	 * Restore the arg0 that we saved upon entry.
14962 	 */
14963 	mstate->dtms_arg[0] = sarg0;
14964 	mstate->dtms_arg[1] = sarg1;
14965 
14966 	return (rval);
14967 
14968 err:
14969 	if (trace)
14970 		dtrace_helper_trace(helper, mstate, vstate,
14971 		    DTRACE_HELPTRACE_ERR);
14972 
14973 	/*
14974 	 * Restore the arg0 that we saved upon entry.
14975 	 */
14976 	mstate->dtms_arg[0] = sarg0;
14977 	mstate->dtms_arg[1] = sarg1;
14978 
14979 	return (0);
14980 }
14981 
14982 static void
dtrace_helper_action_destroy(dtrace_helper_action_t * helper,dtrace_vstate_t * vstate)14983 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14984     dtrace_vstate_t *vstate)
14985 {
14986 	int i;
14987 
14988 	if (helper->dtha_predicate != NULL)
14989 		dtrace_difo_release(helper->dtha_predicate, vstate);
14990 
14991 	for (i = 0; i < helper->dtha_nactions; i++) {
14992 		ASSERT(helper->dtha_actions[i] != NULL);
14993 		dtrace_difo_release(helper->dtha_actions[i], vstate);
14994 	}
14995 
14996 	kmem_free(helper->dtha_actions,
14997 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14998 	kmem_free(helper, sizeof (dtrace_helper_action_t));
14999 }
15000 
15001 static int
dtrace_helper_destroygen(int gen)15002 dtrace_helper_destroygen(int gen)
15003 {
15004 	proc_t *p = curproc;
15005 	dtrace_helpers_t *help = p->p_dtrace_helpers;
15006 	dtrace_vstate_t *vstate;
15007 	int i;
15008 
15009 	ASSERT(MUTEX_HELD(&dtrace_lock));
15010 
15011 	if (help == NULL || gen > help->dthps_generation)
15012 		return (EINVAL);
15013 
15014 	vstate = &help->dthps_vstate;
15015 
15016 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15017 		dtrace_helper_action_t *last = NULL, *h, *next;
15018 
15019 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15020 			next = h->dtha_next;
15021 
15022 			if (h->dtha_generation == gen) {
15023 				if (last != NULL) {
15024 					last->dtha_next = next;
15025 				} else {
15026 					help->dthps_actions[i] = next;
15027 				}
15028 
15029 				dtrace_helper_action_destroy(h, vstate);
15030 			} else {
15031 				last = h;
15032 			}
15033 		}
15034 	}
15035 
15036 	/*
15037 	 * Interate until we've cleared out all helper providers with the
15038 	 * given generation number.
15039 	 */
15040 	for (;;) {
15041 		dtrace_helper_provider_t *prov;
15042 
15043 		/*
15044 		 * Look for a helper provider with the right generation. We
15045 		 * have to start back at the beginning of the list each time
15046 		 * because we drop dtrace_lock. It's unlikely that we'll make
15047 		 * more than two passes.
15048 		 */
15049 		for (i = 0; i < help->dthps_nprovs; i++) {
15050 			prov = help->dthps_provs[i];
15051 
15052 			if (prov->dthp_generation == gen)
15053 				break;
15054 		}
15055 
15056 		/*
15057 		 * If there were no matches, we're done.
15058 		 */
15059 		if (i == help->dthps_nprovs)
15060 			break;
15061 
15062 		/*
15063 		 * Move the last helper provider into this slot.
15064 		 */
15065 		help->dthps_nprovs--;
15066 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15067 		help->dthps_provs[help->dthps_nprovs] = NULL;
15068 
15069 		mutex_exit(&dtrace_lock);
15070 
15071 		/*
15072 		 * If we have a meta provider, remove this helper provider.
15073 		 */
15074 		mutex_enter(&dtrace_meta_lock);
15075 		if (dtrace_meta_pid != NULL) {
15076 			ASSERT(dtrace_deferred_pid == NULL);
15077 			dtrace_helper_provider_remove(&prov->dthp_prov,
15078 			    p->p_pid);
15079 		}
15080 		mutex_exit(&dtrace_meta_lock);
15081 
15082 		dtrace_helper_provider_destroy(prov);
15083 
15084 		mutex_enter(&dtrace_lock);
15085 	}
15086 
15087 	return (0);
15088 }
15089 
15090 static int
dtrace_helper_validate(dtrace_helper_action_t * helper)15091 dtrace_helper_validate(dtrace_helper_action_t *helper)
15092 {
15093 	int err = 0, i;
15094 	dtrace_difo_t *dp;
15095 
15096 	if ((dp = helper->dtha_predicate) != NULL)
15097 		err += dtrace_difo_validate_helper(dp);
15098 
15099 	for (i = 0; i < helper->dtha_nactions; i++)
15100 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15101 
15102 	return (err == 0);
15103 }
15104 
15105 static int
dtrace_helper_action_add(int which,dtrace_ecbdesc_t * ep)15106 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
15107 {
15108 	dtrace_helpers_t *help;
15109 	dtrace_helper_action_t *helper, *last;
15110 	dtrace_actdesc_t *act;
15111 	dtrace_vstate_t *vstate;
15112 	dtrace_predicate_t *pred;
15113 	int count = 0, nactions = 0, i;
15114 
15115 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15116 		return (EINVAL);
15117 
15118 	help = curproc->p_dtrace_helpers;
15119 	last = help->dthps_actions[which];
15120 	vstate = &help->dthps_vstate;
15121 
15122 	for (count = 0; last != NULL; last = last->dtha_next) {
15123 		count++;
15124 		if (last->dtha_next == NULL)
15125 			break;
15126 	}
15127 
15128 	/*
15129 	 * If we already have dtrace_helper_actions_max helper actions for this
15130 	 * helper action type, we'll refuse to add a new one.
15131 	 */
15132 	if (count >= dtrace_helper_actions_max)
15133 		return (ENOSPC);
15134 
15135 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15136 	helper->dtha_generation = help->dthps_generation;
15137 
15138 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15139 		ASSERT(pred->dtp_difo != NULL);
15140 		dtrace_difo_hold(pred->dtp_difo);
15141 		helper->dtha_predicate = pred->dtp_difo;
15142 	}
15143 
15144 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15145 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15146 			goto err;
15147 
15148 		if (act->dtad_difo == NULL)
15149 			goto err;
15150 
15151 		nactions++;
15152 	}
15153 
15154 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15155 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15156 
15157 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15158 		dtrace_difo_hold(act->dtad_difo);
15159 		helper->dtha_actions[i++] = act->dtad_difo;
15160 	}
15161 
15162 	if (!dtrace_helper_validate(helper))
15163 		goto err;
15164 
15165 	if (last == NULL) {
15166 		help->dthps_actions[which] = helper;
15167 	} else {
15168 		last->dtha_next = helper;
15169 	}
15170 
15171 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15172 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15173 		dtrace_helptrace_next = 0;
15174 	}
15175 
15176 	return (0);
15177 err:
15178 	dtrace_helper_action_destroy(helper, vstate);
15179 	return (EINVAL);
15180 }
15181 
15182 static void
dtrace_helper_provider_register(proc_t * p,dtrace_helpers_t * help,dof_helper_t * dofhp)15183 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15184     dof_helper_t *dofhp)
15185 {
15186 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15187 
15188 	mutex_enter(&dtrace_meta_lock);
15189 	mutex_enter(&dtrace_lock);
15190 
15191 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15192 		/*
15193 		 * If the dtrace module is loaded but not attached, or if
15194 		 * there aren't isn't a meta provider registered to deal with
15195 		 * these provider descriptions, we need to postpone creating
15196 		 * the actual providers until later.
15197 		 */
15198 
15199 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15200 		    dtrace_deferred_pid != help) {
15201 			help->dthps_deferred = 1;
15202 			help->dthps_pid = p->p_pid;
15203 			help->dthps_next = dtrace_deferred_pid;
15204 			help->dthps_prev = NULL;
15205 			if (dtrace_deferred_pid != NULL)
15206 				dtrace_deferred_pid->dthps_prev = help;
15207 			dtrace_deferred_pid = help;
15208 		}
15209 
15210 		mutex_exit(&dtrace_lock);
15211 
15212 	} else if (dofhp != NULL) {
15213 		/*
15214 		 * If the dtrace module is loaded and we have a particular
15215 		 * helper provider description, pass that off to the
15216 		 * meta provider.
15217 		 */
15218 
15219 		mutex_exit(&dtrace_lock);
15220 
15221 		dtrace_helper_provide(dofhp, p->p_pid);
15222 
15223 	} else {
15224 		/*
15225 		 * Otherwise, just pass all the helper provider descriptions
15226 		 * off to the meta provider.
15227 		 */
15228 
15229 		int i;
15230 		mutex_exit(&dtrace_lock);
15231 
15232 		for (i = 0; i < help->dthps_nprovs; i++) {
15233 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15234 			    p->p_pid);
15235 		}
15236 	}
15237 
15238 	mutex_exit(&dtrace_meta_lock);
15239 }
15240 
15241 static int
dtrace_helper_provider_add(dof_helper_t * dofhp,int gen)15242 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15243 {
15244 	dtrace_helpers_t *help;
15245 	dtrace_helper_provider_t *hprov, **tmp_provs;
15246 	uint_t tmp_maxprovs, i;
15247 
15248 	ASSERT(MUTEX_HELD(&dtrace_lock));
15249 
15250 	help = curproc->p_dtrace_helpers;
15251 	ASSERT(help != NULL);
15252 
15253 	/*
15254 	 * If we already have dtrace_helper_providers_max helper providers,
15255 	 * we're refuse to add a new one.
15256 	 */
15257 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
15258 		return (ENOSPC);
15259 
15260 	/*
15261 	 * Check to make sure this isn't a duplicate.
15262 	 */
15263 	for (i = 0; i < help->dthps_nprovs; i++) {
15264 		if (dofhp->dofhp_addr ==
15265 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
15266 			return (EALREADY);
15267 	}
15268 
15269 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15270 	hprov->dthp_prov = *dofhp;
15271 	hprov->dthp_ref = 1;
15272 	hprov->dthp_generation = gen;
15273 
15274 	/*
15275 	 * Allocate a bigger table for helper providers if it's already full.
15276 	 */
15277 	if (help->dthps_maxprovs == help->dthps_nprovs) {
15278 		tmp_maxprovs = help->dthps_maxprovs;
15279 		tmp_provs = help->dthps_provs;
15280 
15281 		if (help->dthps_maxprovs == 0)
15282 			help->dthps_maxprovs = 2;
15283 		else
15284 			help->dthps_maxprovs *= 2;
15285 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
15286 			help->dthps_maxprovs = dtrace_helper_providers_max;
15287 
15288 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15289 
15290 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15291 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15292 
15293 		if (tmp_provs != NULL) {
15294 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15295 			    sizeof (dtrace_helper_provider_t *));
15296 			kmem_free(tmp_provs, tmp_maxprovs *
15297 			    sizeof (dtrace_helper_provider_t *));
15298 		}
15299 	}
15300 
15301 	help->dthps_provs[help->dthps_nprovs] = hprov;
15302 	help->dthps_nprovs++;
15303 
15304 	return (0);
15305 }
15306 
15307 static void
dtrace_helper_provider_destroy(dtrace_helper_provider_t * hprov)15308 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15309 {
15310 	mutex_enter(&dtrace_lock);
15311 
15312 	if (--hprov->dthp_ref == 0) {
15313 		dof_hdr_t *dof;
15314 		mutex_exit(&dtrace_lock);
15315 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15316 		dtrace_dof_destroy(dof);
15317 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15318 	} else {
15319 		mutex_exit(&dtrace_lock);
15320 	}
15321 }
15322 
15323 static int
dtrace_helper_provider_validate(dof_hdr_t * dof,dof_sec_t * sec)15324 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15325 {
15326 	uintptr_t daddr = (uintptr_t)dof;
15327 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15328 	dof_provider_t *provider;
15329 	dof_probe_t *probe;
15330 	uint8_t *arg;
15331 	char *strtab, *typestr;
15332 	dof_stridx_t typeidx;
15333 	size_t typesz;
15334 	uint_t nprobes, j, k;
15335 
15336 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15337 
15338 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15339 		dtrace_dof_error(dof, "misaligned section offset");
15340 		return (-1);
15341 	}
15342 
15343 	/*
15344 	 * The section needs to be large enough to contain the DOF provider
15345 	 * structure appropriate for the given version.
15346 	 */
15347 	if (sec->dofs_size <
15348 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15349 	    offsetof(dof_provider_t, dofpv_prenoffs) :
15350 	    sizeof (dof_provider_t))) {
15351 		dtrace_dof_error(dof, "provider section too small");
15352 		return (-1);
15353 	}
15354 
15355 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15356 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15357 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15358 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15359 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15360 
15361 	if (str_sec == NULL || prb_sec == NULL ||
15362 	    arg_sec == NULL || off_sec == NULL)
15363 		return (-1);
15364 
15365 	enoff_sec = NULL;
15366 
15367 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15368 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
15369 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15370 	    provider->dofpv_prenoffs)) == NULL)
15371 		return (-1);
15372 
15373 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15374 
15375 	if (provider->dofpv_name >= str_sec->dofs_size ||
15376 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15377 		dtrace_dof_error(dof, "invalid provider name");
15378 		return (-1);
15379 	}
15380 
15381 	if (prb_sec->dofs_entsize == 0 ||
15382 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15383 		dtrace_dof_error(dof, "invalid entry size");
15384 		return (-1);
15385 	}
15386 
15387 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15388 		dtrace_dof_error(dof, "misaligned entry size");
15389 		return (-1);
15390 	}
15391 
15392 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15393 		dtrace_dof_error(dof, "invalid entry size");
15394 		return (-1);
15395 	}
15396 
15397 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15398 		dtrace_dof_error(dof, "misaligned section offset");
15399 		return (-1);
15400 	}
15401 
15402 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15403 		dtrace_dof_error(dof, "invalid entry size");
15404 		return (-1);
15405 	}
15406 
15407 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15408 
15409 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15410 
15411 	/*
15412 	 * Take a pass through the probes to check for errors.
15413 	 */
15414 	for (j = 0; j < nprobes; j++) {
15415 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15416 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15417 
15418 		if (probe->dofpr_func >= str_sec->dofs_size) {
15419 			dtrace_dof_error(dof, "invalid function name");
15420 			return (-1);
15421 		}
15422 
15423 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15424 			dtrace_dof_error(dof, "function name too long");
15425 			return (-1);
15426 		}
15427 
15428 		if (probe->dofpr_name >= str_sec->dofs_size ||
15429 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15430 			dtrace_dof_error(dof, "invalid probe name");
15431 			return (-1);
15432 		}
15433 
15434 		/*
15435 		 * The offset count must not wrap the index, and the offsets
15436 		 * must also not overflow the section's data.
15437 		 */
15438 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15439 		    probe->dofpr_offidx ||
15440 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15441 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15442 			dtrace_dof_error(dof, "invalid probe offset");
15443 			return (-1);
15444 		}
15445 
15446 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15447 			/*
15448 			 * If there's no is-enabled offset section, make sure
15449 			 * there aren't any is-enabled offsets. Otherwise
15450 			 * perform the same checks as for probe offsets
15451 			 * (immediately above).
15452 			 */
15453 			if (enoff_sec == NULL) {
15454 				if (probe->dofpr_enoffidx != 0 ||
15455 				    probe->dofpr_nenoffs != 0) {
15456 					dtrace_dof_error(dof, "is-enabled "
15457 					    "offsets with null section");
15458 					return (-1);
15459 				}
15460 			} else if (probe->dofpr_enoffidx +
15461 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15462 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15463 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15464 				dtrace_dof_error(dof, "invalid is-enabled "
15465 				    "offset");
15466 				return (-1);
15467 			}
15468 
15469 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15470 				dtrace_dof_error(dof, "zero probe and "
15471 				    "is-enabled offsets");
15472 				return (-1);
15473 			}
15474 		} else if (probe->dofpr_noffs == 0) {
15475 			dtrace_dof_error(dof, "zero probe offsets");
15476 			return (-1);
15477 		}
15478 
15479 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15480 		    probe->dofpr_argidx ||
15481 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15482 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15483 			dtrace_dof_error(dof, "invalid args");
15484 			return (-1);
15485 		}
15486 
15487 		typeidx = probe->dofpr_nargv;
15488 		typestr = strtab + probe->dofpr_nargv;
15489 		for (k = 0; k < probe->dofpr_nargc; k++) {
15490 			if (typeidx >= str_sec->dofs_size) {
15491 				dtrace_dof_error(dof, "bad "
15492 				    "native argument type");
15493 				return (-1);
15494 			}
15495 
15496 			typesz = strlen(typestr) + 1;
15497 			if (typesz > DTRACE_ARGTYPELEN) {
15498 				dtrace_dof_error(dof, "native "
15499 				    "argument type too long");
15500 				return (-1);
15501 			}
15502 			typeidx += typesz;
15503 			typestr += typesz;
15504 		}
15505 
15506 		typeidx = probe->dofpr_xargv;
15507 		typestr = strtab + probe->dofpr_xargv;
15508 		for (k = 0; k < probe->dofpr_xargc; k++) {
15509 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15510 				dtrace_dof_error(dof, "bad "
15511 				    "native argument index");
15512 				return (-1);
15513 			}
15514 
15515 			if (typeidx >= str_sec->dofs_size) {
15516 				dtrace_dof_error(dof, "bad "
15517 				    "translated argument type");
15518 				return (-1);
15519 			}
15520 
15521 			typesz = strlen(typestr) + 1;
15522 			if (typesz > DTRACE_ARGTYPELEN) {
15523 				dtrace_dof_error(dof, "translated argument "
15524 				    "type too long");
15525 				return (-1);
15526 			}
15527 
15528 			typeidx += typesz;
15529 			typestr += typesz;
15530 		}
15531 	}
15532 
15533 	return (0);
15534 }
15535 
15536 static int
dtrace_helper_slurp(dof_hdr_t * dof,dof_helper_t * dhp)15537 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15538 {
15539 	dtrace_helpers_t *help;
15540 	dtrace_vstate_t *vstate;
15541 	dtrace_enabling_t *enab = NULL;
15542 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15543 	uintptr_t daddr = (uintptr_t)dof;
15544 
15545 	ASSERT(MUTEX_HELD(&dtrace_lock));
15546 
15547 	if ((help = curproc->p_dtrace_helpers) == NULL)
15548 		help = dtrace_helpers_create(curproc);
15549 
15550 	vstate = &help->dthps_vstate;
15551 
15552 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15553 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15554 		dtrace_dof_destroy(dof);
15555 		return (rv);
15556 	}
15557 
15558 	/*
15559 	 * Look for helper providers and validate their descriptions.
15560 	 */
15561 	if (dhp != NULL) {
15562 		for (i = 0; i < dof->dofh_secnum; i++) {
15563 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15564 			    dof->dofh_secoff + i * dof->dofh_secsize);
15565 
15566 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15567 				continue;
15568 
15569 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15570 				dtrace_enabling_destroy(enab);
15571 				dtrace_dof_destroy(dof);
15572 				return (-1);
15573 			}
15574 
15575 			nprovs++;
15576 		}
15577 	}
15578 
15579 	/*
15580 	 * Now we need to walk through the ECB descriptions in the enabling.
15581 	 */
15582 	for (i = 0; i < enab->dten_ndesc; i++) {
15583 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15584 		dtrace_probedesc_t *desc = &ep->dted_probe;
15585 
15586 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15587 			continue;
15588 
15589 		if (strcmp(desc->dtpd_mod, "helper") != 0)
15590 			continue;
15591 
15592 		if (strcmp(desc->dtpd_func, "ustack") != 0)
15593 			continue;
15594 
15595 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15596 		    ep)) != 0) {
15597 			/*
15598 			 * Adding this helper action failed -- we are now going
15599 			 * to rip out the entire generation and return failure.
15600 			 */
15601 			(void) dtrace_helper_destroygen(help->dthps_generation);
15602 			dtrace_enabling_destroy(enab);
15603 			dtrace_dof_destroy(dof);
15604 			return (-1);
15605 		}
15606 
15607 		nhelpers++;
15608 	}
15609 
15610 	if (nhelpers < enab->dten_ndesc)
15611 		dtrace_dof_error(dof, "unmatched helpers");
15612 
15613 	gen = help->dthps_generation++;
15614 	dtrace_enabling_destroy(enab);
15615 
15616 	if (dhp != NULL && nprovs > 0) {
15617 		/*
15618 		 * Now that this is in-kernel, we change the sense of the
15619 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
15620 		 * and dofhp_addr denotes the address at user-level.
15621 		 */
15622 		dhp->dofhp_addr = dhp->dofhp_dof;
15623 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15624 
15625 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
15626 			mutex_exit(&dtrace_lock);
15627 			dtrace_helper_provider_register(curproc, help, dhp);
15628 			mutex_enter(&dtrace_lock);
15629 
15630 			destroy = 0;
15631 		}
15632 	}
15633 
15634 	if (destroy)
15635 		dtrace_dof_destroy(dof);
15636 
15637 	return (gen);
15638 }
15639 
15640 static dtrace_helpers_t *
dtrace_helpers_create(proc_t * p)15641 dtrace_helpers_create(proc_t *p)
15642 {
15643 	dtrace_helpers_t *help;
15644 
15645 	ASSERT(MUTEX_HELD(&dtrace_lock));
15646 	ASSERT(p->p_dtrace_helpers == NULL);
15647 
15648 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15649 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15650 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15651 
15652 	p->p_dtrace_helpers = help;
15653 	dtrace_helpers++;
15654 
15655 	return (help);
15656 }
15657 
15658 static void
dtrace_helpers_destroy(proc_t * p)15659 dtrace_helpers_destroy(proc_t *p)
15660 {
15661 	dtrace_helpers_t *help;
15662 	dtrace_vstate_t *vstate;
15663 	int i;
15664 
15665 	mutex_enter(&dtrace_lock);
15666 
15667 	ASSERT(p->p_dtrace_helpers != NULL);
15668 	ASSERT(dtrace_helpers > 0);
15669 
15670 	help = p->p_dtrace_helpers;
15671 	vstate = &help->dthps_vstate;
15672 
15673 	/*
15674 	 * We're now going to lose the help from this process.
15675 	 */
15676 	p->p_dtrace_helpers = NULL;
15677 	if (p == curproc) {
15678 		dtrace_sync();
15679 	} else {
15680 		/*
15681 		 * It is sometimes necessary to clean up dtrace helpers from a
15682 		 * an incomplete child process as part of a failed fork
15683 		 * operation.  In such situations, a dtrace_sync() call should
15684 		 * be unnecessary as the process should be devoid of threads,
15685 		 * much less any in probe context.
15686 		 */
15687 		VERIFY(p->p_stat == SIDL);
15688 	}
15689 
15690 	/*
15691 	 * Destroy the helper actions.
15692 	 */
15693 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15694 		dtrace_helper_action_t *h, *next;
15695 
15696 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15697 			next = h->dtha_next;
15698 			dtrace_helper_action_destroy(h, vstate);
15699 			h = next;
15700 		}
15701 	}
15702 
15703 	mutex_exit(&dtrace_lock);
15704 
15705 	/*
15706 	 * Destroy the helper providers.
15707 	 */
15708 	if (help->dthps_maxprovs > 0) {
15709 		mutex_enter(&dtrace_meta_lock);
15710 		if (dtrace_meta_pid != NULL) {
15711 			ASSERT(dtrace_deferred_pid == NULL);
15712 
15713 			for (i = 0; i < help->dthps_nprovs; i++) {
15714 				dtrace_helper_provider_remove(
15715 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15716 			}
15717 		} else {
15718 			mutex_enter(&dtrace_lock);
15719 			ASSERT(help->dthps_deferred == 0 ||
15720 			    help->dthps_next != NULL ||
15721 			    help->dthps_prev != NULL ||
15722 			    help == dtrace_deferred_pid);
15723 
15724 			/*
15725 			 * Remove the helper from the deferred list.
15726 			 */
15727 			if (help->dthps_next != NULL)
15728 				help->dthps_next->dthps_prev = help->dthps_prev;
15729 			if (help->dthps_prev != NULL)
15730 				help->dthps_prev->dthps_next = help->dthps_next;
15731 			if (dtrace_deferred_pid == help) {
15732 				dtrace_deferred_pid = help->dthps_next;
15733 				ASSERT(help->dthps_prev == NULL);
15734 			}
15735 
15736 			mutex_exit(&dtrace_lock);
15737 		}
15738 
15739 		mutex_exit(&dtrace_meta_lock);
15740 
15741 		for (i = 0; i < help->dthps_nprovs; i++) {
15742 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15743 		}
15744 
15745 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15746 		    sizeof (dtrace_helper_provider_t *));
15747 	}
15748 
15749 	mutex_enter(&dtrace_lock);
15750 
15751 	dtrace_vstate_fini(&help->dthps_vstate);
15752 	kmem_free(help->dthps_actions,
15753 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15754 	kmem_free(help, sizeof (dtrace_helpers_t));
15755 
15756 	--dtrace_helpers;
15757 	mutex_exit(&dtrace_lock);
15758 }
15759 
15760 static void
dtrace_helpers_duplicate(proc_t * from,proc_t * to)15761 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15762 {
15763 	dtrace_helpers_t *help, *newhelp;
15764 	dtrace_helper_action_t *helper, *new, *last;
15765 	dtrace_difo_t *dp;
15766 	dtrace_vstate_t *vstate;
15767 	int i, j, sz, hasprovs = 0;
15768 
15769 	mutex_enter(&dtrace_lock);
15770 	ASSERT(from->p_dtrace_helpers != NULL);
15771 	ASSERT(dtrace_helpers > 0);
15772 
15773 	help = from->p_dtrace_helpers;
15774 	newhelp = dtrace_helpers_create(to);
15775 	ASSERT(to->p_dtrace_helpers != NULL);
15776 
15777 	newhelp->dthps_generation = help->dthps_generation;
15778 	vstate = &newhelp->dthps_vstate;
15779 
15780 	/*
15781 	 * Duplicate the helper actions.
15782 	 */
15783 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15784 		if ((helper = help->dthps_actions[i]) == NULL)
15785 			continue;
15786 
15787 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15788 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15789 			    KM_SLEEP);
15790 			new->dtha_generation = helper->dtha_generation;
15791 
15792 			if ((dp = helper->dtha_predicate) != NULL) {
15793 				dp = dtrace_difo_duplicate(dp, vstate);
15794 				new->dtha_predicate = dp;
15795 			}
15796 
15797 			new->dtha_nactions = helper->dtha_nactions;
15798 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15799 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15800 
15801 			for (j = 0; j < new->dtha_nactions; j++) {
15802 				dtrace_difo_t *dp = helper->dtha_actions[j];
15803 
15804 				ASSERT(dp != NULL);
15805 				dp = dtrace_difo_duplicate(dp, vstate);
15806 				new->dtha_actions[j] = dp;
15807 			}
15808 
15809 			if (last != NULL) {
15810 				last->dtha_next = new;
15811 			} else {
15812 				newhelp->dthps_actions[i] = new;
15813 			}
15814 
15815 			last = new;
15816 		}
15817 	}
15818 
15819 	/*
15820 	 * Duplicate the helper providers and register them with the
15821 	 * DTrace framework.
15822 	 */
15823 	if (help->dthps_nprovs > 0) {
15824 		newhelp->dthps_nprovs = help->dthps_nprovs;
15825 		newhelp->dthps_maxprovs = help->dthps_nprovs;
15826 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15827 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15828 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15829 			newhelp->dthps_provs[i] = help->dthps_provs[i];
15830 			newhelp->dthps_provs[i]->dthp_ref++;
15831 		}
15832 
15833 		hasprovs = 1;
15834 	}
15835 
15836 	mutex_exit(&dtrace_lock);
15837 
15838 	if (hasprovs)
15839 		dtrace_helper_provider_register(to, newhelp, NULL);
15840 }
15841 
15842 /*
15843  * DTrace Hook Functions
15844  */
15845 static void
dtrace_module_loaded(struct modctl * ctl)15846 dtrace_module_loaded(struct modctl *ctl)
15847 {
15848 	dtrace_provider_t *prv;
15849 
15850 	mutex_enter(&dtrace_provider_lock);
15851 	mutex_enter(&mod_lock);
15852 
15853 	ASSERT(ctl->mod_busy);
15854 
15855 	/*
15856 	 * We're going to call each providers per-module provide operation
15857 	 * specifying only this module.
15858 	 */
15859 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15860 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15861 
15862 	mutex_exit(&mod_lock);
15863 	mutex_exit(&dtrace_provider_lock);
15864 
15865 	/*
15866 	 * If we have any retained enablings, we need to match against them.
15867 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15868 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15869 	 * module.  (In particular, this happens when loading scheduling
15870 	 * classes.)  So if we have any retained enablings, we need to dispatch
15871 	 * our task queue to do the match for us.
15872 	 */
15873 	mutex_enter(&dtrace_lock);
15874 
15875 	if (dtrace_retained == NULL) {
15876 		mutex_exit(&dtrace_lock);
15877 		return;
15878 	}
15879 
15880 	(void) taskq_dispatch(dtrace_taskq,
15881 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15882 
15883 	mutex_exit(&dtrace_lock);
15884 
15885 	/*
15886 	 * And now, for a little heuristic sleaze:  in general, we want to
15887 	 * match modules as soon as they load.  However, we cannot guarantee
15888 	 * this, because it would lead us to the lock ordering violation
15889 	 * outlined above.  The common case, of course, is that cpu_lock is
15890 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15891 	 * long enough for the task queue to do its work.  If it's not, it's
15892 	 * not a serious problem -- it just means that the module that we
15893 	 * just loaded may not be immediately instrumentable.
15894 	 */
15895 	delay(1);
15896 }
15897 
15898 static void
dtrace_module_unloaded(struct modctl * ctl)15899 dtrace_module_unloaded(struct modctl *ctl)
15900 {
15901 	dtrace_probe_t template, *probe, *first, *next;
15902 	dtrace_provider_t *prov;
15903 
15904 	template.dtpr_mod = ctl->mod_modname;
15905 
15906 	mutex_enter(&dtrace_provider_lock);
15907 	mutex_enter(&mod_lock);
15908 	mutex_enter(&dtrace_lock);
15909 
15910 	if (dtrace_bymod == NULL) {
15911 		/*
15912 		 * The DTrace module is loaded (obviously) but not attached;
15913 		 * we don't have any work to do.
15914 		 */
15915 		mutex_exit(&dtrace_provider_lock);
15916 		mutex_exit(&mod_lock);
15917 		mutex_exit(&dtrace_lock);
15918 		return;
15919 	}
15920 
15921 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15922 	    probe != NULL; probe = probe->dtpr_nextmod) {
15923 		if (probe->dtpr_ecb != NULL) {
15924 			mutex_exit(&dtrace_provider_lock);
15925 			mutex_exit(&mod_lock);
15926 			mutex_exit(&dtrace_lock);
15927 
15928 			/*
15929 			 * This shouldn't _actually_ be possible -- we're
15930 			 * unloading a module that has an enabled probe in it.
15931 			 * (It's normally up to the provider to make sure that
15932 			 * this can't happen.)  However, because dtps_enable()
15933 			 * doesn't have a failure mode, there can be an
15934 			 * enable/unload race.  Upshot:  we don't want to
15935 			 * assert, but we're not going to disable the
15936 			 * probe, either.
15937 			 */
15938 			if (dtrace_err_verbose) {
15939 				cmn_err(CE_WARN, "unloaded module '%s' had "
15940 				    "enabled probes", ctl->mod_modname);
15941 			}
15942 
15943 			return;
15944 		}
15945 	}
15946 
15947 	probe = first;
15948 
15949 	for (first = NULL; probe != NULL; probe = next) {
15950 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15951 
15952 		dtrace_probes[probe->dtpr_id - 1] = NULL;
15953 
15954 		next = probe->dtpr_nextmod;
15955 		dtrace_hash_remove(dtrace_bymod, probe);
15956 		dtrace_hash_remove(dtrace_byfunc, probe);
15957 		dtrace_hash_remove(dtrace_byname, probe);
15958 
15959 		if (first == NULL) {
15960 			first = probe;
15961 			probe->dtpr_nextmod = NULL;
15962 		} else {
15963 			probe->dtpr_nextmod = first;
15964 			first = probe;
15965 		}
15966 	}
15967 
15968 	/*
15969 	 * We've removed all of the module's probes from the hash chains and
15970 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15971 	 * everyone has cleared out from any probe array processing.
15972 	 */
15973 	dtrace_sync();
15974 
15975 	for (probe = first; probe != NULL; probe = first) {
15976 		first = probe->dtpr_nextmod;
15977 		prov = probe->dtpr_provider;
15978 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15979 		    probe->dtpr_arg);
15980 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15981 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15982 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15983 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15984 		kmem_free(probe, sizeof (dtrace_probe_t));
15985 	}
15986 
15987 	mutex_exit(&dtrace_lock);
15988 	mutex_exit(&mod_lock);
15989 	mutex_exit(&dtrace_provider_lock);
15990 }
15991 
15992 void
dtrace_suspend(void)15993 dtrace_suspend(void)
15994 {
15995 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15996 }
15997 
15998 void
dtrace_resume(void)15999 dtrace_resume(void)
16000 {
16001 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16002 }
16003 
16004 static int
dtrace_cpu_setup(cpu_setup_t what,processorid_t cpu,void * ptr __unused)16005 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu, void *ptr __unused)
16006 {
16007 	ASSERT(MUTEX_HELD(&cpu_lock));
16008 	mutex_enter(&dtrace_lock);
16009 
16010 	switch (what) {
16011 	case CPU_CONFIG: {
16012 		dtrace_state_t *state;
16013 		dtrace_optval_t *opt, rs, c;
16014 
16015 		/*
16016 		 * For now, we only allocate a new buffer for anonymous state.
16017 		 */
16018 		if ((state = dtrace_anon.dta_state) == NULL)
16019 			break;
16020 
16021 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16022 			break;
16023 
16024 		opt = state->dts_options;
16025 		c = opt[DTRACEOPT_CPU];
16026 
16027 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16028 			break;
16029 
16030 		/*
16031 		 * Regardless of what the actual policy is, we're going to
16032 		 * temporarily set our resize policy to be manual.  We're
16033 		 * also going to temporarily set our CPU option to denote
16034 		 * the newly configured CPU.
16035 		 */
16036 		rs = opt[DTRACEOPT_BUFRESIZE];
16037 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16038 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16039 
16040 		(void) dtrace_state_buffers(state);
16041 
16042 		opt[DTRACEOPT_BUFRESIZE] = rs;
16043 		opt[DTRACEOPT_CPU] = c;
16044 
16045 		break;
16046 	}
16047 
16048 	case CPU_UNCONFIG:
16049 		/*
16050 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
16051 		 * buffer will be freed when the consumer exits.)
16052 		 */
16053 		break;
16054 
16055 	default:
16056 		break;
16057 	}
16058 
16059 	mutex_exit(&dtrace_lock);
16060 	return (0);
16061 }
16062 
16063 static void
dtrace_cpu_setup_initial(processorid_t cpu)16064 dtrace_cpu_setup_initial(processorid_t cpu)
16065 {
16066 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu, NULL);
16067 }
16068 
16069 static void
dtrace_toxrange_add(uintptr_t base,uintptr_t limit)16070 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16071 {
16072 	if (dtrace_toxranges >= dtrace_toxranges_max) {
16073 		int osize, nsize;
16074 		dtrace_toxrange_t *range;
16075 
16076 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16077 
16078 		if (osize == 0) {
16079 			ASSERT(dtrace_toxrange == NULL);
16080 			ASSERT(dtrace_toxranges_max == 0);
16081 			dtrace_toxranges_max = 1;
16082 		} else {
16083 			dtrace_toxranges_max <<= 1;
16084 		}
16085 
16086 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16087 		range = kmem_zalloc(nsize, KM_SLEEP);
16088 
16089 		if (dtrace_toxrange != NULL) {
16090 			ASSERT(osize != 0);
16091 			bcopy(dtrace_toxrange, range, osize);
16092 			kmem_free(dtrace_toxrange, osize);
16093 		}
16094 
16095 		dtrace_toxrange = range;
16096 	}
16097 
16098 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == (uintptr_t)NULL);
16099 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == (uintptr_t)NULL);
16100 
16101 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16102 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16103 	dtrace_toxranges++;
16104 }
16105 
16106 static void
dtrace_getf_barrier()16107 dtrace_getf_barrier()
16108 {
16109 	/*
16110 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
16111 	 * that contain calls to getf(), this routine will be called on every
16112 	 * closef() before either the underlying vnode is released or the
16113 	 * file_t itself is freed.  By the time we are here, it is essential
16114 	 * that the file_t can no longer be accessed from a call to getf()
16115 	 * in probe context -- that assures that a dtrace_sync() can be used
16116 	 * to clear out any enablings referring to the old structures.
16117 	 */
16118 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
16119 	    kcred->cr_zone->zone_dtrace_getf != 0)
16120 		dtrace_sync();
16121 }
16122 
16123 /*
16124  * DTrace Driver Cookbook Functions
16125  */
16126 /*ARGSUSED*/
16127 static int
dtrace_attach(dev_info_t * devi,ddi_attach_cmd_t cmd)16128 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16129 {
16130 	dtrace_provider_id_t id;
16131 	dtrace_state_t *state = NULL;
16132 	dtrace_enabling_t *enab;
16133 
16134 	mutex_enter(&cpu_lock);
16135 	mutex_enter(&dtrace_provider_lock);
16136 	mutex_enter(&dtrace_lock);
16137 
16138 	if (ddi_soft_state_init(&dtrace_softstate,
16139 	    sizeof (dtrace_state_t), 0) != 0) {
16140 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16141 		mutex_exit(&cpu_lock);
16142 		mutex_exit(&dtrace_provider_lock);
16143 		mutex_exit(&dtrace_lock);
16144 		return (DDI_FAILURE);
16145 	}
16146 
16147 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16148 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, 0) == DDI_FAILURE ||
16149 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16150 	    DTRACEMNRN_HELPER, DDI_PSEUDO, 0) == DDI_FAILURE) {
16151 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16152 		ddi_remove_minor_node(devi, NULL);
16153 		ddi_soft_state_fini(&dtrace_softstate);
16154 		mutex_exit(&cpu_lock);
16155 		mutex_exit(&dtrace_provider_lock);
16156 		mutex_exit(&dtrace_lock);
16157 		return (DDI_FAILURE);
16158 	}
16159 
16160 	ddi_report_dev(devi);
16161 	dtrace_devi = devi;
16162 
16163 	dtrace_modload = dtrace_module_loaded;
16164 	dtrace_modunload = dtrace_module_unloaded;
16165 	dtrace_cpu_init = dtrace_cpu_setup_initial;
16166 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
16167 	dtrace_helpers_fork = dtrace_helpers_duplicate;
16168 	dtrace_cpustart_init = dtrace_suspend;
16169 	dtrace_cpustart_fini = dtrace_resume;
16170 	dtrace_debugger_init = dtrace_suspend;
16171 	dtrace_debugger_fini = dtrace_resume;
16172 
16173 	register_cpu_setup_func(dtrace_cpu_setup, NULL);
16174 
16175 	ASSERT(MUTEX_HELD(&cpu_lock));
16176 
16177 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16178 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16179 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16180 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16181 	    VM_SLEEP | VMC_IDENTIFIER);
16182 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16183 	    1, INT_MAX, 0);
16184 
16185 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16186 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16187 	    NULL, NULL, NULL, NULL, NULL, 0);
16188 
16189 	ASSERT(MUTEX_HELD(&cpu_lock));
16190 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16191 	    offsetof(dtrace_probe_t, dtpr_nextmod),
16192 	    offsetof(dtrace_probe_t, dtpr_prevmod));
16193 
16194 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16195 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
16196 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
16197 
16198 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16199 	    offsetof(dtrace_probe_t, dtpr_nextname),
16200 	    offsetof(dtrace_probe_t, dtpr_prevname));
16201 
16202 	if (dtrace_retain_max < 1) {
16203 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16204 		    "setting to 1", dtrace_retain_max);
16205 		dtrace_retain_max = 1;
16206 	}
16207 
16208 	/*
16209 	 * Now discover our toxic ranges.
16210 	 */
16211 	dtrace_toxic_ranges(dtrace_toxrange_add);
16212 
16213 	/*
16214 	 * Before we register ourselves as a provider to our own framework,
16215 	 * we would like to assert that dtrace_provider is NULL -- but that's
16216 	 * not true if we were loaded as a dependency of a DTrace provider.
16217 	 * Once we've registered, we can assert that dtrace_provider is our
16218 	 * pseudo provider.
16219 	 */
16220 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
16221 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16222 
16223 	ASSERT(dtrace_provider != NULL);
16224 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16225 
16226 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16227 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16228 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16229 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
16230 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16231 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16232 
16233 	dtrace_anon_property();
16234 	mutex_exit(&cpu_lock);
16235 
16236 	/*
16237 	 * If there are already providers, we must ask them to provide their
16238 	 * probes, and then match any anonymous enabling against them.  Note
16239 	 * that there should be no other retained enablings at this time:
16240 	 * the only retained enablings at this time should be the anonymous
16241 	 * enabling.
16242 	 */
16243 	if (dtrace_anon.dta_enabling != NULL) {
16244 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16245 
16246 		dtrace_enabling_provide(NULL);
16247 		state = dtrace_anon.dta_state;
16248 
16249 		/*
16250 		 * We couldn't hold cpu_lock across the above call to
16251 		 * dtrace_enabling_provide(), but we must hold it to actually
16252 		 * enable the probes.  We have to drop all of our locks, pick
16253 		 * up cpu_lock, and regain our locks before matching the
16254 		 * retained anonymous enabling.
16255 		 */
16256 		mutex_exit(&dtrace_lock);
16257 		mutex_exit(&dtrace_provider_lock);
16258 
16259 		mutex_enter(&cpu_lock);
16260 		mutex_enter(&dtrace_provider_lock);
16261 		mutex_enter(&dtrace_lock);
16262 
16263 		if ((enab = dtrace_anon.dta_enabling) != NULL)
16264 			(void) dtrace_enabling_match(enab, NULL);
16265 
16266 		mutex_exit(&cpu_lock);
16267 	}
16268 
16269 	mutex_exit(&dtrace_lock);
16270 	mutex_exit(&dtrace_provider_lock);
16271 
16272 	if (state != NULL) {
16273 		/*
16274 		 * If we created any anonymous state, set it going now.
16275 		 */
16276 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16277 	}
16278 
16279 	return (DDI_SUCCESS);
16280 }
16281 
16282 /*ARGSUSED*/
16283 static int
dtrace_open(dev_t * devp,int flag,int otyp,cred_t * cred_p)16284 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16285 {
16286 	dtrace_state_t *state;
16287 	uint32_t priv;
16288 	uid_t uid;
16289 	zoneid_t zoneid;
16290 
16291 	if (getminor(*devp) == DTRACEMNRN_HELPER)
16292 		return (0);
16293 
16294 	/*
16295 	 * If this wasn't an open with the "helper" minor, then it must be
16296 	 * the "dtrace" minor.
16297 	 */
16298 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
16299 		return (ENXIO);
16300 
16301 	/*
16302 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
16303 	 * caller lacks sufficient permission to do anything with DTrace.
16304 	 */
16305 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16306 	if (priv == DTRACE_PRIV_NONE)
16307 		return (EACCES);
16308 
16309 	/*
16310 	 * Ask all providers to provide all their probes.
16311 	 */
16312 	mutex_enter(&dtrace_provider_lock);
16313 	dtrace_probe_provide(NULL, NULL);
16314 	mutex_exit(&dtrace_provider_lock);
16315 
16316 	mutex_enter(&cpu_lock);
16317 	mutex_enter(&dtrace_lock);
16318 	dtrace_opens++;
16319 	dtrace_membar_producer();
16320 
16321 	/*
16322 	 * If the kernel debugger is active (that is, if the kernel debugger
16323 	 * modified text in some way), we won't allow the open.
16324 	 */
16325 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16326 		dtrace_opens--;
16327 		mutex_exit(&cpu_lock);
16328 		mutex_exit(&dtrace_lock);
16329 		return (EBUSY);
16330 	}
16331 
16332 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
16333 		/*
16334 		 * If DTrace helper tracing is enabled, we need to allocate the
16335 		 * trace buffer and initialize the values.
16336 		 */
16337 		dtrace_helptrace_buffer =
16338 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16339 		dtrace_helptrace_next = 0;
16340 		dtrace_helptrace_wrapped = 0;
16341 		dtrace_helptrace_enable = 0;
16342 	}
16343 
16344 	state = dtrace_state_create(devp, cred_p);
16345 	mutex_exit(&cpu_lock);
16346 
16347 	if (state == NULL) {
16348 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16349 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16350 		mutex_exit(&dtrace_lock);
16351 		return (EAGAIN);
16352 	}
16353 
16354 	mutex_exit(&dtrace_lock);
16355 
16356 	return (0);
16357 }
16358 
16359 /*ARGSUSED*/
16360 static int
dtrace_close(dev_t dev,int flag,int otyp,cred_t * cred_p)16361 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16362 {
16363 	minor_t minor = getminor(dev);
16364 	dtrace_state_t *state;
16365 	dtrace_helptrace_t *buf = NULL;
16366 
16367 	if (minor == DTRACEMNRN_HELPER)
16368 		return (0);
16369 
16370 	state = ddi_get_soft_state(dtrace_softstate, minor);
16371 
16372 	mutex_enter(&cpu_lock);
16373 	mutex_enter(&dtrace_lock);
16374 
16375 	if (state->dts_anon) {
16376 		/*
16377 		 * There is anonymous state. Destroy that first.
16378 		 */
16379 		ASSERT(dtrace_anon.dta_state == NULL);
16380 		dtrace_state_destroy(state->dts_anon);
16381 	}
16382 
16383 	if (dtrace_helptrace_disable) {
16384 		/*
16385 		 * If we have been told to disable helper tracing, set the
16386 		 * buffer to NULL before calling into dtrace_state_destroy();
16387 		 * we take advantage of its dtrace_sync() to know that no
16388 		 * CPU is in probe context with enabled helper tracing
16389 		 * after it returns.
16390 		 */
16391 		buf = dtrace_helptrace_buffer;
16392 		dtrace_helptrace_buffer = NULL;
16393 	}
16394 
16395 	dtrace_state_destroy(state);
16396 	ASSERT(dtrace_opens > 0);
16397 
16398 	/*
16399 	 * Only relinquish control of the kernel debugger interface when there
16400 	 * are no consumers and no anonymous enablings.
16401 	 */
16402 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16403 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16404 
16405 	if (buf != NULL) {
16406 		kmem_free(buf, dtrace_helptrace_bufsize);
16407 		dtrace_helptrace_disable = 0;
16408 	}
16409 
16410 	mutex_exit(&dtrace_lock);
16411 	mutex_exit(&cpu_lock);
16412 
16413 	return (0);
16414 }
16415 
16416 /*ARGSUSED*/
16417 static int
dtrace_ioctl_helper(int cmd,intptr_t arg,int * rv)16418 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16419 {
16420 	int rval;
16421 	dof_helper_t help, *dhp = NULL;
16422 
16423 	switch (cmd) {
16424 	case DTRACEHIOC_ADDDOF:
16425 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16426 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
16427 			return (EFAULT);
16428 		}
16429 
16430 		dhp = &help;
16431 		arg = (intptr_t)help.dofhp_dof;
16432 		/*FALLTHROUGH*/
16433 
16434 	case DTRACEHIOC_ADD: {
16435 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16436 
16437 		if (dof == NULL)
16438 			return (rval);
16439 
16440 		mutex_enter(&dtrace_lock);
16441 
16442 		/*
16443 		 * dtrace_helper_slurp() takes responsibility for the dof --
16444 		 * it may free it now or it may save it and free it later.
16445 		 */
16446 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16447 			*rv = rval;
16448 			rval = 0;
16449 		} else {
16450 			rval = EINVAL;
16451 		}
16452 
16453 		mutex_exit(&dtrace_lock);
16454 		return (rval);
16455 	}
16456 
16457 	case DTRACEHIOC_REMOVE: {
16458 		mutex_enter(&dtrace_lock);
16459 		rval = dtrace_helper_destroygen(arg);
16460 		mutex_exit(&dtrace_lock);
16461 
16462 		return (rval);
16463 	}
16464 
16465 	default:
16466 		break;
16467 	}
16468 
16469 	return (ENOTTY);
16470 }
16471 
16472 /*ARGSUSED*/
16473 static int
dtrace_ioctl(dev_t dev,int cmd,intptr_t arg,int md,cred_t * cr,int * rv)16474 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16475 {
16476 	minor_t minor = getminor(dev);
16477 	dtrace_state_t *state;
16478 	int rval;
16479 
16480 	if (minor == DTRACEMNRN_HELPER)
16481 		return (dtrace_ioctl_helper(cmd, arg, rv));
16482 
16483 	state = ddi_get_soft_state(dtrace_softstate, minor);
16484 
16485 	if (state->dts_anon) {
16486 		ASSERT(dtrace_anon.dta_state == NULL);
16487 		state = state->dts_anon;
16488 	}
16489 
16490 	switch (cmd) {
16491 	case DTRACEIOC_PROVIDER: {
16492 		dtrace_providerdesc_t pvd;
16493 		dtrace_provider_t *pvp;
16494 
16495 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16496 			return (EFAULT);
16497 
16498 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16499 		mutex_enter(&dtrace_provider_lock);
16500 
16501 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16502 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16503 				break;
16504 		}
16505 
16506 		mutex_exit(&dtrace_provider_lock);
16507 
16508 		if (pvp == NULL)
16509 			return (ESRCH);
16510 
16511 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16512 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16513 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16514 			return (EFAULT);
16515 
16516 		return (0);
16517 	}
16518 
16519 	case DTRACEIOC_EPROBE: {
16520 		dtrace_eprobedesc_t epdesc;
16521 		dtrace_ecb_t *ecb;
16522 		dtrace_action_t *act;
16523 		void *buf;
16524 		size_t size;
16525 		uintptr_t dest;
16526 		int nrecs;
16527 
16528 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16529 			return (EFAULT);
16530 
16531 		mutex_enter(&dtrace_lock);
16532 
16533 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16534 			mutex_exit(&dtrace_lock);
16535 			return (EINVAL);
16536 		}
16537 
16538 		if (ecb->dte_probe == NULL) {
16539 			mutex_exit(&dtrace_lock);
16540 			return (EINVAL);
16541 		}
16542 
16543 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16544 		epdesc.dtepd_uarg = ecb->dte_uarg;
16545 		epdesc.dtepd_size = ecb->dte_size;
16546 
16547 		nrecs = epdesc.dtepd_nrecs;
16548 		epdesc.dtepd_nrecs = 0;
16549 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16550 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16551 				continue;
16552 
16553 			epdesc.dtepd_nrecs++;
16554 		}
16555 
16556 		/*
16557 		 * Now that we have the size, we need to allocate a temporary
16558 		 * buffer in which to store the complete description.  We need
16559 		 * the temporary buffer to be able to drop dtrace_lock()
16560 		 * across the copyout(), below.
16561 		 */
16562 		size = sizeof (dtrace_eprobedesc_t) +
16563 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16564 
16565 		buf = kmem_alloc(size, KM_SLEEP);
16566 		dest = (uintptr_t)buf;
16567 
16568 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16569 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16570 
16571 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16572 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16573 				continue;
16574 
16575 			if (nrecs-- == 0)
16576 				break;
16577 
16578 			bcopy(&act->dta_rec, (void *)dest,
16579 			    sizeof (dtrace_recdesc_t));
16580 			dest += sizeof (dtrace_recdesc_t);
16581 		}
16582 
16583 		mutex_exit(&dtrace_lock);
16584 
16585 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16586 			kmem_free(buf, size);
16587 			return (EFAULT);
16588 		}
16589 
16590 		kmem_free(buf, size);
16591 		return (0);
16592 	}
16593 
16594 	case DTRACEIOC_AGGDESC: {
16595 		dtrace_aggdesc_t aggdesc;
16596 		dtrace_action_t *act;
16597 		dtrace_aggregation_t *agg;
16598 		int nrecs;
16599 		uint32_t offs;
16600 		dtrace_recdesc_t *lrec;
16601 		void *buf;
16602 		size_t size;
16603 		uintptr_t dest;
16604 
16605 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16606 			return (EFAULT);
16607 
16608 		mutex_enter(&dtrace_lock);
16609 
16610 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16611 			mutex_exit(&dtrace_lock);
16612 			return (EINVAL);
16613 		}
16614 
16615 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16616 
16617 		nrecs = aggdesc.dtagd_nrecs;
16618 		aggdesc.dtagd_nrecs = 0;
16619 
16620 		offs = agg->dtag_base;
16621 		lrec = &agg->dtag_action.dta_rec;
16622 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16623 
16624 		for (act = agg->dtag_first; ; act = act->dta_next) {
16625 			ASSERT(act->dta_intuple ||
16626 			    DTRACEACT_ISAGG(act->dta_kind));
16627 
16628 			/*
16629 			 * If this action has a record size of zero, it
16630 			 * denotes an argument to the aggregating action.
16631 			 * Because the presence of this record doesn't (or
16632 			 * shouldn't) affect the way the data is interpreted,
16633 			 * we don't copy it out to save user-level the
16634 			 * confusion of dealing with a zero-length record.
16635 			 */
16636 			if (act->dta_rec.dtrd_size == 0) {
16637 				ASSERT(agg->dtag_hasarg);
16638 				continue;
16639 			}
16640 
16641 			aggdesc.dtagd_nrecs++;
16642 
16643 			if (act == &agg->dtag_action)
16644 				break;
16645 		}
16646 
16647 		/*
16648 		 * Now that we have the size, we need to allocate a temporary
16649 		 * buffer in which to store the complete description.  We need
16650 		 * the temporary buffer to be able to drop dtrace_lock()
16651 		 * across the copyout(), below.
16652 		 */
16653 		size = sizeof (dtrace_aggdesc_t) +
16654 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16655 
16656 		buf = kmem_alloc(size, KM_SLEEP);
16657 		dest = (uintptr_t)buf;
16658 
16659 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16660 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16661 
16662 		for (act = agg->dtag_first; ; act = act->dta_next) {
16663 			dtrace_recdesc_t rec = act->dta_rec;
16664 
16665 			/*
16666 			 * See the comment in the above loop for why we pass
16667 			 * over zero-length records.
16668 			 */
16669 			if (rec.dtrd_size == 0) {
16670 				ASSERT(agg->dtag_hasarg);
16671 				continue;
16672 			}
16673 
16674 			if (nrecs-- == 0)
16675 				break;
16676 
16677 			rec.dtrd_offset -= offs;
16678 			bcopy(&rec, (void *)dest, sizeof (rec));
16679 			dest += sizeof (dtrace_recdesc_t);
16680 
16681 			if (act == &agg->dtag_action)
16682 				break;
16683 		}
16684 
16685 		mutex_exit(&dtrace_lock);
16686 
16687 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16688 			kmem_free(buf, size);
16689 			return (EFAULT);
16690 		}
16691 
16692 		kmem_free(buf, size);
16693 		return (0);
16694 	}
16695 
16696 	case DTRACEIOC_ENABLE: {
16697 		dof_hdr_t *dof;
16698 		dtrace_enabling_t *enab = NULL;
16699 		dtrace_vstate_t *vstate;
16700 		int err = 0;
16701 
16702 		*rv = 0;
16703 
16704 		/*
16705 		 * If a NULL argument has been passed, we take this as our
16706 		 * cue to reevaluate our enablings.
16707 		 */
16708 		if (arg == 0) {
16709 			dtrace_enabling_matchall();
16710 
16711 			return (0);
16712 		}
16713 
16714 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16715 			return (rval);
16716 
16717 		mutex_enter(&cpu_lock);
16718 		mutex_enter(&dtrace_lock);
16719 		vstate = &state->dts_vstate;
16720 
16721 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16722 			mutex_exit(&dtrace_lock);
16723 			mutex_exit(&cpu_lock);
16724 			dtrace_dof_destroy(dof);
16725 			return (EBUSY);
16726 		}
16727 
16728 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16729 			mutex_exit(&dtrace_lock);
16730 			mutex_exit(&cpu_lock);
16731 			dtrace_dof_destroy(dof);
16732 			return (EINVAL);
16733 		}
16734 
16735 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16736 			dtrace_enabling_destroy(enab);
16737 			mutex_exit(&dtrace_lock);
16738 			mutex_exit(&cpu_lock);
16739 			dtrace_dof_destroy(dof);
16740 			return (rval);
16741 		}
16742 
16743 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16744 			err = dtrace_enabling_retain(enab);
16745 		} else {
16746 			dtrace_enabling_destroy(enab);
16747 		}
16748 
16749 		mutex_exit(&cpu_lock);
16750 		mutex_exit(&dtrace_lock);
16751 		dtrace_dof_destroy(dof);
16752 
16753 		return (err);
16754 	}
16755 
16756 	case DTRACEIOC_REPLICATE: {
16757 		dtrace_repldesc_t desc;
16758 		dtrace_probedesc_t *match = &desc.dtrpd_match;
16759 		dtrace_probedesc_t *create = &desc.dtrpd_create;
16760 		int err;
16761 
16762 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16763 			return (EFAULT);
16764 
16765 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16766 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16767 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16768 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16769 
16770 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16771 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16772 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16773 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16774 
16775 		mutex_enter(&dtrace_lock);
16776 		err = dtrace_enabling_replicate(state, match, create);
16777 		mutex_exit(&dtrace_lock);
16778 
16779 		return (err);
16780 	}
16781 
16782 	case DTRACEIOC_PROBEMATCH:
16783 	case DTRACEIOC_PROBES: {
16784 		dtrace_probe_t *probe = NULL;
16785 		dtrace_probedesc_t desc;
16786 		dtrace_probekey_t pkey;
16787 		dtrace_id_t i;
16788 		int m = 0;
16789 		uint32_t priv;
16790 		uid_t uid;
16791 		zoneid_t zoneid;
16792 
16793 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16794 			return (EFAULT);
16795 
16796 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16797 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16798 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16799 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16800 
16801 		/*
16802 		 * Before we attempt to match this probe, we want to give
16803 		 * all providers the opportunity to provide it.
16804 		 */
16805 		if (desc.dtpd_id == DTRACE_IDNONE) {
16806 			mutex_enter(&dtrace_provider_lock);
16807 			dtrace_probe_provide(&desc, NULL);
16808 			mutex_exit(&dtrace_provider_lock);
16809 			desc.dtpd_id++;
16810 		}
16811 
16812 		if (cmd == DTRACEIOC_PROBEMATCH)  {
16813 			dtrace_probekey(&desc, &pkey);
16814 			pkey.dtpk_id = DTRACE_IDNONE;
16815 		}
16816 
16817 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16818 
16819 		mutex_enter(&dtrace_lock);
16820 
16821 		if (cmd == DTRACEIOC_PROBEMATCH) {
16822 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16823 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16824 				    (m = dtrace_match_probe(probe, &pkey,
16825 				    priv, uid, zoneid)) != 0)
16826 					break;
16827 			}
16828 
16829 			if (m < 0) {
16830 				mutex_exit(&dtrace_lock);
16831 				return (EINVAL);
16832 			}
16833 
16834 		} else {
16835 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16836 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16837 				    dtrace_match_priv(probe, priv, uid, zoneid))
16838 					break;
16839 			}
16840 		}
16841 
16842 		if (probe == NULL) {
16843 			mutex_exit(&dtrace_lock);
16844 			return (ESRCH);
16845 		}
16846 
16847 		dtrace_probe_description(probe, &desc);
16848 		mutex_exit(&dtrace_lock);
16849 
16850 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16851 			return (EFAULT);
16852 
16853 		return (0);
16854 	}
16855 
16856 	case DTRACEIOC_PROBEARG: {
16857 		dtrace_argdesc_t desc;
16858 		dtrace_probe_t *probe;
16859 		dtrace_provider_t *prov;
16860 
16861 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16862 			return (EFAULT);
16863 
16864 		if (desc.dtargd_id == DTRACE_IDNONE)
16865 			return (EINVAL);
16866 
16867 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16868 			return (EINVAL);
16869 
16870 		mutex_enter(&dtrace_provider_lock);
16871 		mutex_enter(&mod_lock);
16872 		mutex_enter(&dtrace_lock);
16873 
16874 		if (desc.dtargd_id > dtrace_nprobes) {
16875 			mutex_exit(&dtrace_lock);
16876 			mutex_exit(&mod_lock);
16877 			mutex_exit(&dtrace_provider_lock);
16878 			return (EINVAL);
16879 		}
16880 
16881 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16882 			mutex_exit(&dtrace_lock);
16883 			mutex_exit(&mod_lock);
16884 			mutex_exit(&dtrace_provider_lock);
16885 			return (EINVAL);
16886 		}
16887 
16888 		mutex_exit(&dtrace_lock);
16889 
16890 		prov = probe->dtpr_provider;
16891 
16892 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16893 			/*
16894 			 * There isn't any typed information for this probe.
16895 			 * Set the argument number to DTRACE_ARGNONE.
16896 			 */
16897 			desc.dtargd_ndx = DTRACE_ARGNONE;
16898 		} else {
16899 			desc.dtargd_native[0] = '\0';
16900 			desc.dtargd_xlate[0] = '\0';
16901 			desc.dtargd_mapping = desc.dtargd_ndx;
16902 
16903 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16904 			    probe->dtpr_id, probe->dtpr_arg, &desc);
16905 		}
16906 
16907 		mutex_exit(&mod_lock);
16908 		mutex_exit(&dtrace_provider_lock);
16909 
16910 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16911 			return (EFAULT);
16912 
16913 		return (0);
16914 	}
16915 
16916 	case DTRACEIOC_GO: {
16917 		processorid_t cpuid;
16918 		rval = dtrace_state_go(state, &cpuid);
16919 
16920 		if (rval != 0)
16921 			return (rval);
16922 
16923 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16924 			return (EFAULT);
16925 
16926 		return (0);
16927 	}
16928 
16929 	case DTRACEIOC_STOP: {
16930 		processorid_t cpuid;
16931 
16932 		mutex_enter(&dtrace_lock);
16933 		rval = dtrace_state_stop(state, &cpuid);
16934 		mutex_exit(&dtrace_lock);
16935 
16936 		if (rval != 0)
16937 			return (rval);
16938 
16939 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16940 			return (EFAULT);
16941 
16942 		return (0);
16943 	}
16944 
16945 	case DTRACEIOC_DOFGET: {
16946 		dof_hdr_t hdr, *dof;
16947 		uint64_t len;
16948 
16949 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16950 			return (EFAULT);
16951 
16952 		mutex_enter(&dtrace_lock);
16953 		dof = dtrace_dof_create(state);
16954 		mutex_exit(&dtrace_lock);
16955 
16956 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16957 		rval = copyout(dof, (void *)arg, len);
16958 		dtrace_dof_destroy(dof);
16959 
16960 		return (rval == 0 ? 0 : EFAULT);
16961 	}
16962 
16963 	case DTRACEIOC_AGGSNAP:
16964 	case DTRACEIOC_BUFSNAP: {
16965 		dtrace_bufdesc_t desc;
16966 		caddr_t cached;
16967 		dtrace_buffer_t *buf;
16968 
16969 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16970 			return (EFAULT);
16971 
16972 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16973 			return (EINVAL);
16974 
16975 		mutex_enter(&dtrace_lock);
16976 
16977 		if (cmd == DTRACEIOC_BUFSNAP) {
16978 			buf = &state->dts_buffer[desc.dtbd_cpu];
16979 		} else {
16980 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16981 		}
16982 
16983 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16984 			size_t sz = buf->dtb_offset;
16985 
16986 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16987 				mutex_exit(&dtrace_lock);
16988 				return (EBUSY);
16989 			}
16990 
16991 			/*
16992 			 * If this buffer has already been consumed, we're
16993 			 * going to indicate that there's nothing left here
16994 			 * to consume.
16995 			 */
16996 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16997 				mutex_exit(&dtrace_lock);
16998 
16999 				desc.dtbd_size = 0;
17000 				desc.dtbd_drops = 0;
17001 				desc.dtbd_errors = 0;
17002 				desc.dtbd_oldest = 0;
17003 				sz = sizeof (desc);
17004 
17005 				if (copyout(&desc, (void *)arg, sz) != 0)
17006 					return (EFAULT);
17007 
17008 				return (0);
17009 			}
17010 
17011 			/*
17012 			 * If this is a ring buffer that has wrapped, we want
17013 			 * to copy the whole thing out.
17014 			 */
17015 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17016 				dtrace_buffer_polish(buf);
17017 				sz = buf->dtb_size;
17018 			}
17019 
17020 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17021 				mutex_exit(&dtrace_lock);
17022 				return (EFAULT);
17023 			}
17024 
17025 			desc.dtbd_size = sz;
17026 			desc.dtbd_drops = buf->dtb_drops;
17027 			desc.dtbd_errors = buf->dtb_errors;
17028 			desc.dtbd_oldest = buf->dtb_xamot_offset;
17029 			desc.dtbd_timestamp = dtrace_gethrtime();
17030 
17031 			mutex_exit(&dtrace_lock);
17032 
17033 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17034 				return (EFAULT);
17035 
17036 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
17037 
17038 			return (0);
17039 		}
17040 
17041 		if (buf->dtb_tomax == NULL) {
17042 			ASSERT(buf->dtb_xamot == NULL);
17043 			mutex_exit(&dtrace_lock);
17044 			return (ENOENT);
17045 		}
17046 
17047 		cached = buf->dtb_tomax;
17048 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17049 
17050 		dtrace_xcall(desc.dtbd_cpu,
17051 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
17052 
17053 		state->dts_errors += buf->dtb_xamot_errors;
17054 
17055 		/*
17056 		 * If the buffers did not actually switch, then the cross call
17057 		 * did not take place -- presumably because the given CPU is
17058 		 * not in the ready set.  If this is the case, we'll return
17059 		 * ENOENT.
17060 		 */
17061 		if (buf->dtb_tomax == cached) {
17062 			ASSERT(buf->dtb_xamot != cached);
17063 			mutex_exit(&dtrace_lock);
17064 			return (ENOENT);
17065 		}
17066 
17067 		ASSERT(cached == buf->dtb_xamot);
17068 
17069 		/*
17070 		 * We have our snapshot; now copy it out.
17071 		 */
17072 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
17073 		    buf->dtb_xamot_offset) != 0) {
17074 			mutex_exit(&dtrace_lock);
17075 			return (EFAULT);
17076 		}
17077 
17078 		desc.dtbd_size = buf->dtb_xamot_offset;
17079 		desc.dtbd_drops = buf->dtb_xamot_drops;
17080 		desc.dtbd_errors = buf->dtb_xamot_errors;
17081 		desc.dtbd_oldest = 0;
17082 		desc.dtbd_timestamp = buf->dtb_switched;
17083 
17084 		mutex_exit(&dtrace_lock);
17085 
17086 		/*
17087 		 * Finally, copy out the buffer description.
17088 		 */
17089 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17090 			return (EFAULT);
17091 
17092 		return (0);
17093 	}
17094 
17095 	case DTRACEIOC_CONF: {
17096 		dtrace_conf_t conf;
17097 
17098 		bzero(&conf, sizeof (conf));
17099 		conf.dtc_difversion = DIF_VERSION;
17100 		conf.dtc_difintregs = DIF_DIR_NREGS;
17101 		conf.dtc_diftupregs = DIF_DTR_NREGS;
17102 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17103 
17104 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17105 			return (EFAULT);
17106 
17107 		return (0);
17108 	}
17109 
17110 	case DTRACEIOC_STATUS: {
17111 		dtrace_status_t stat;
17112 		dtrace_dstate_t *dstate;
17113 		int i, j;
17114 		uint64_t nerrs;
17115 
17116 		/*
17117 		 * See the comment in dtrace_state_deadman() for the reason
17118 		 * for setting dts_laststatus to INT64_MAX before setting
17119 		 * it to the correct value.
17120 		 */
17121 		state->dts_laststatus = INT64_MAX;
17122 		dtrace_membar_producer();
17123 		state->dts_laststatus = dtrace_gethrtime();
17124 
17125 		bzero(&stat, sizeof (stat));
17126 
17127 		mutex_enter(&dtrace_lock);
17128 
17129 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17130 			mutex_exit(&dtrace_lock);
17131 			return (ENOENT);
17132 		}
17133 
17134 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17135 			stat.dtst_exiting = 1;
17136 
17137 		nerrs = state->dts_errors;
17138 		dstate = &state->dts_vstate.dtvs_dynvars;
17139 
17140 		for (i = 0; i < NCPU; i++) {
17141 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17142 
17143 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
17144 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17145 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17146 
17147 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17148 				stat.dtst_filled++;
17149 
17150 			nerrs += state->dts_buffer[i].dtb_errors;
17151 
17152 			for (j = 0; j < state->dts_nspeculations; j++) {
17153 				dtrace_speculation_t *spec;
17154 				dtrace_buffer_t *buf;
17155 
17156 				spec = &state->dts_speculations[j];
17157 				buf = &spec->dtsp_buffer[i];
17158 				stat.dtst_specdrops += buf->dtb_xamot_drops;
17159 			}
17160 		}
17161 
17162 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
17163 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17164 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17165 		stat.dtst_dblerrors = state->dts_dblerrors;
17166 		stat.dtst_killed =
17167 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17168 		stat.dtst_errors = nerrs;
17169 
17170 		mutex_exit(&dtrace_lock);
17171 
17172 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17173 			return (EFAULT);
17174 
17175 		return (0);
17176 	}
17177 
17178 	case DTRACEIOC_FORMAT: {
17179 		dtrace_fmtdesc_t fmt;
17180 		char *str;
17181 		int len;
17182 
17183 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17184 			return (EFAULT);
17185 
17186 		mutex_enter(&dtrace_lock);
17187 
17188 		if (fmt.dtfd_format == 0 ||
17189 		    fmt.dtfd_format > state->dts_nformats) {
17190 			mutex_exit(&dtrace_lock);
17191 			return (EINVAL);
17192 		}
17193 
17194 		/*
17195 		 * Format strings are allocated contiguously and they are
17196 		 * never freed; if a format index is less than the number
17197 		 * of formats, we can assert that the format map is non-NULL
17198 		 * and that the format for the specified index is non-NULL.
17199 		 */
17200 		ASSERT(state->dts_formats != NULL);
17201 		str = state->dts_formats[fmt.dtfd_format - 1];
17202 		ASSERT(str != NULL);
17203 
17204 		len = strlen(str) + 1;
17205 
17206 		if (len > fmt.dtfd_length) {
17207 			fmt.dtfd_length = len;
17208 
17209 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17210 				mutex_exit(&dtrace_lock);
17211 				return (EINVAL);
17212 			}
17213 		} else {
17214 			if (copyout(str, fmt.dtfd_string, len) != 0) {
17215 				mutex_exit(&dtrace_lock);
17216 				return (EINVAL);
17217 			}
17218 		}
17219 
17220 		mutex_exit(&dtrace_lock);
17221 		return (0);
17222 	}
17223 
17224 	default:
17225 		break;
17226 	}
17227 
17228 	return (ENOTTY);
17229 }
17230 
17231 /*ARGSUSED*/
17232 static int
dtrace_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)17233 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17234 {
17235 	dtrace_state_t *state;
17236 
17237 	switch (cmd) {
17238 	case DDI_DETACH:
17239 		break;
17240 
17241 	case DDI_SUSPEND:
17242 		return (DDI_SUCCESS);
17243 
17244 	default:
17245 		return (DDI_FAILURE);
17246 	}
17247 
17248 	mutex_enter(&cpu_lock);
17249 	mutex_enter(&dtrace_provider_lock);
17250 	mutex_enter(&dtrace_lock);
17251 
17252 	ASSERT(dtrace_opens == 0);
17253 
17254 	if (dtrace_helpers > 0) {
17255 		mutex_exit(&dtrace_provider_lock);
17256 		mutex_exit(&dtrace_lock);
17257 		mutex_exit(&cpu_lock);
17258 		return (DDI_FAILURE);
17259 	}
17260 
17261 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17262 		mutex_exit(&dtrace_provider_lock);
17263 		mutex_exit(&dtrace_lock);
17264 		mutex_exit(&cpu_lock);
17265 		return (DDI_FAILURE);
17266 	}
17267 
17268 	dtrace_provider = NULL;
17269 
17270 	if ((state = dtrace_anon_grab()) != NULL) {
17271 		/*
17272 		 * If there were ECBs on this state, the provider should
17273 		 * have not been allowed to detach; assert that there is
17274 		 * none.
17275 		 */
17276 		ASSERT(state->dts_necbs == 0);
17277 		dtrace_state_destroy(state);
17278 
17279 		/*
17280 		 * If we're being detached with anonymous state, we need to
17281 		 * indicate to the kernel debugger that DTrace is now inactive.
17282 		 */
17283 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17284 	}
17285 
17286 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17287 	unregister_cpu_setup_func(dtrace_cpu_setup, NULL);
17288 	dtrace_cpu_init = NULL;
17289 	dtrace_helpers_cleanup = NULL;
17290 	dtrace_helpers_fork = NULL;
17291 	dtrace_cpustart_init = NULL;
17292 	dtrace_cpustart_fini = NULL;
17293 	dtrace_debugger_init = NULL;
17294 	dtrace_debugger_fini = NULL;
17295 	dtrace_modload = NULL;
17296 	dtrace_modunload = NULL;
17297 
17298 	ASSERT(dtrace_getf == 0);
17299 	ASSERT(dtrace_closef == NULL);
17300 
17301 	mutex_exit(&cpu_lock);
17302 
17303 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17304 	dtrace_probes = NULL;
17305 	dtrace_nprobes = 0;
17306 
17307 	dtrace_hash_destroy(dtrace_bymod);
17308 	dtrace_hash_destroy(dtrace_byfunc);
17309 	dtrace_hash_destroy(dtrace_byname);
17310 	dtrace_bymod = NULL;
17311 	dtrace_byfunc = NULL;
17312 	dtrace_byname = NULL;
17313 
17314 	kmem_cache_destroy(dtrace_state_cache);
17315 	vmem_destroy(dtrace_minor);
17316 	vmem_destroy(dtrace_arena);
17317 
17318 	if (dtrace_toxrange != NULL) {
17319 		kmem_free(dtrace_toxrange,
17320 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17321 		dtrace_toxrange = NULL;
17322 		dtrace_toxranges = 0;
17323 		dtrace_toxranges_max = 0;
17324 	}
17325 
17326 	ddi_remove_minor_node(dtrace_devi, NULL);
17327 	dtrace_devi = NULL;
17328 
17329 	ddi_soft_state_fini(&dtrace_softstate);
17330 
17331 	ASSERT(dtrace_vtime_references == 0);
17332 	ASSERT(dtrace_opens == 0);
17333 	ASSERT(dtrace_retained == NULL);
17334 
17335 	mutex_exit(&dtrace_lock);
17336 	mutex_exit(&dtrace_provider_lock);
17337 
17338 	/*
17339 	 * We don't destroy the task queue until after we have dropped our
17340 	 * locks (taskq_destroy() may block on running tasks).  To prevent
17341 	 * attempting to do work after we have effectively detached but before
17342 	 * the task queue has been destroyed, all tasks dispatched via the
17343 	 * task queue must check that DTrace is still attached before
17344 	 * performing any operation.
17345 	 */
17346 	taskq_destroy(dtrace_taskq);
17347 	dtrace_taskq = NULL;
17348 
17349 	return (DDI_SUCCESS);
17350 }
17351 
17352 /*ARGSUSED*/
17353 static int
dtrace_info(dev_info_t * dip,ddi_info_cmd_t infocmd,void * arg,void ** result)17354 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17355 {
17356 	int error;
17357 
17358 	switch (infocmd) {
17359 	case DDI_INFO_DEVT2DEVINFO:
17360 		*result = (void *)dtrace_devi;
17361 		error = DDI_SUCCESS;
17362 		break;
17363 	case DDI_INFO_DEVT2INSTANCE:
17364 		*result = (void *)0;
17365 		error = DDI_SUCCESS;
17366 		break;
17367 	default:
17368 		error = DDI_FAILURE;
17369 	}
17370 	return (error);
17371 }
17372 
17373 static struct cb_ops dtrace_cb_ops = {
17374 	dtrace_open,		/* open */
17375 	dtrace_close,		/* close */
17376 	nulldev,		/* strategy */
17377 	nulldev,		/* print */
17378 	nodev,			/* dump */
17379 	nodev,			/* read */
17380 	nodev,			/* write */
17381 	dtrace_ioctl,		/* ioctl */
17382 	nodev,			/* devmap */
17383 	nodev,			/* mmap */
17384 	nodev,			/* segmap */
17385 	nochpoll,		/* poll */
17386 	ddi_prop_op,		/* cb_prop_op */
17387 	0,			/* streamtab  */
17388 	D_NEW | D_MP		/* Driver compatibility flag */
17389 };
17390 
17391 static struct dev_ops dtrace_ops = {
17392 	DEVO_REV,		/* devo_rev */
17393 	0,			/* refcnt */
17394 	dtrace_info,		/* get_dev_info */
17395 	nulldev,		/* identify */
17396 	nulldev,		/* probe */
17397 	dtrace_attach,		/* attach */
17398 	dtrace_detach,		/* detach */
17399 	nodev,			/* reset */
17400 	&dtrace_cb_ops,		/* driver operations */
17401 	NULL,			/* bus operations */
17402 	nodev,			/* dev power */
17403 	ddi_quiesce_not_needed,		/* quiesce */
17404 };
17405 
17406 static struct modldrv modldrv = {
17407 	&mod_driverops,		/* module type (this is a pseudo driver) */
17408 	"Dynamic Tracing",	/* name of module */
17409 	&dtrace_ops,		/* driver ops */
17410 };
17411 
17412 static struct modlinkage modlinkage = {
17413 	MODREV_1,
17414 	(void *)&modldrv,
17415 	NULL
17416 };
17417 
17418 int
_init(void)17419 _init(void)
17420 {
17421 	return (mod_install(&modlinkage));
17422 }
17423 
17424 int
_info(struct modinfo * modinfop)17425 _info(struct modinfo *modinfop)
17426 {
17427 	return (mod_info(&modlinkage, modinfop));
17428 }
17429 
17430 int
_fini(void)17431 _fini(void)
17432 {
17433 	return (mod_remove(&modlinkage));
17434 }
17435