xref: /xnu-8020.140.41/bsd/dev/dtrace/dtrace.c (revision 27b03b360a988dfd3dfdf34262bb0042026747cc)
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  * Portions Copyright (c) 2013, 2016, Joyent, Inc. All rights reserved.
24  * Portions Copyright (c) 2013 by Delphix. All rights reserved.
25  */
26 
27 /*
28  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
29  * Use is subject to license terms.
30  */
31 
32 /*
33  * DTrace - Dynamic Tracing for Solaris
34  *
35  * This is the implementation of the Solaris Dynamic Tracing framework
36  * (DTrace).  The user-visible interface to DTrace is described at length in
37  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
38  * library, the in-kernel DTrace framework, and the DTrace providers are
39  * described in the block comments in the <sys/dtrace.h> header file.  The
40  * internal architecture of DTrace is described in the block comments in the
41  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
42  * implementation very much assume mastery of all of these sources; if one has
43  * an unanswered question about the implementation, one should consult them
44  * first.
45  *
46  * The functions here are ordered roughly as follows:
47  *
48  *   - Probe context functions
49  *   - Probe hashing functions
50  *   - Non-probe context utility functions
51  *   - Matching functions
52  *   - Provider-to-Framework API functions
53  *   - Probe management functions
54  *   - DIF object functions
55  *   - Format functions
56  *   - Predicate functions
57  *   - ECB functions
58  *   - Buffer functions
59  *   - Enabling functions
60  *   - DOF functions
61  *   - Anonymous enabling functions
62  *   - Process functions
63  *   - Consumer state functions
64  *   - Helper functions
65  *   - Hook functions
66  *   - Driver cookbook functions
67  *
68  * Each group of functions begins with a block comment labelled the "DTrace
69  * [Group] Functions", allowing one to find each block by searching forward
70  * on capital-f functions.
71  */
72 #include <sys/errno.h>
73 #include <sys/types.h>
74 #include <sys/stat.h>
75 #include <sys/conf.h>
76 #include <sys/random.h>
77 #include <sys/systm.h>
78 #include <sys/dtrace_impl.h>
79 #include <sys/param.h>
80 #include <sys/proc_internal.h>
81 #include <sys/ioctl.h>
82 #include <sys/fcntl.h>
83 #include <miscfs/devfs/devfs.h>
84 #include <sys/malloc.h>
85 #include <sys/kernel_types.h>
86 #include <sys/proc_internal.h>
87 #include <sys/uio_internal.h>
88 #include <sys/kauth.h>
89 #include <vm/pmap.h>
90 #include <sys/user.h>
91 #include <mach/exception_types.h>
92 #include <sys/signalvar.h>
93 #include <mach/task.h>
94 #include <kern/ast.h>
95 #include <kern/hvg_hypercall.h>
96 #include <kern/sched_prim.h>
97 #include <kern/task.h>
98 #include <kern/zalloc.h>
99 #include <netinet/in.h>
100 #include <libkern/sysctl.h>
101 #include <sys/kdebug.h>
102 #include <sys/sdt_impl.h>
103 
104 #if MONOTONIC
105 #include <kern/monotonic.h>
106 #include <machine/monotonic.h>
107 #endif /* MONOTONIC */
108 
109 #include "dtrace_xoroshiro128_plus.h"
110 
111 #include <IOKit/IOPlatformExpert.h>
112 
113 #include <kern/cpu_data.h>
114 
115 extern addr64_t kvtophys(vm_offset_t va);
116 
117 extern uint32_t pmap_find_phys(void *, uint64_t);
118 extern boolean_t pmap_valid_page(uint32_t);
119 extern void OSKextRegisterKextsWithDTrace(void);
120 extern kmod_info_t g_kernel_kmod_info;
121 extern void commpage_update_dof(boolean_t enabled);
122 
123 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
124 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
125 
126 #define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
127 
128 extern void dtrace_suspend(void);
129 extern void dtrace_resume(void);
130 extern void dtrace_early_init(void);
131 extern int dtrace_keep_kernel_symbols(void);
132 extern void dtrace_init(void);
133 extern void helper_init(void);
134 extern void fasttrap_init(void);
135 
136 static int  dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
137 extern void dtrace_lazy_dofs_destroy(proc_t *);
138 extern void dtrace_postinit(void);
139 
140 extern void dtrace_proc_fork(proc_t*, proc_t*, int);
141 extern void dtrace_proc_exec(proc_t*);
142 extern void dtrace_proc_exit(proc_t*);
143 
144 /*
145  * DTrace Tunable Variables
146  *
147  * The following variables may be dynamically tuned by using sysctl(8), the
148  * variables being stored in the kern.dtrace namespace.  For example:
149  * 	sysctl kern.dtrace.dof_maxsize = 1048575 	# 1M
150  *
151  * In general, the only variables that one should be tuning this way are those
152  * that affect system-wide DTrace behavior, and for which the default behavior
153  * is undesirable.  Most of these variables are tunable on a per-consumer
154  * basis using DTrace options, and need not be tuned on a system-wide basis.
155  * When tuning these variables, avoid pathological values; while some attempt
156  * is made to verify the integrity of these variables, they are not considered
157  * part of the supported interface to DTrace, and they are therefore not
158  * checked comprehensively.
159  */
160 uint64_t	dtrace_buffer_memory_maxsize = 0;		/* initialized in dtrace_init */
161 uint64_t	dtrace_buffer_memory_inuse = 0;
162 int		dtrace_destructive_disallow = 1;
163 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
164 size_t		dtrace_difo_maxsize = (256 * 1024);
165 dtrace_optval_t	dtrace_dof_maxsize = (512 * 1024);
166 dtrace_optval_t	dtrace_statvar_maxsize = (16 * 1024);
167 dtrace_optval_t	dtrace_statvar_maxsize_max = (16 * 10 * 1024);
168 size_t		dtrace_actions_max = (16 * 1024);
169 size_t		dtrace_retain_max = 1024;
170 dtrace_optval_t	dtrace_helper_actions_max = 32;
171 dtrace_optval_t	dtrace_helper_providers_max = 64;
172 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
173 size_t		dtrace_strsize_default = 256;
174 dtrace_optval_t	dtrace_strsize_min = 8;
175 dtrace_optval_t	dtrace_strsize_max = 65536;
176 dtrace_optval_t	dtrace_cleanrate_default = 990099000;		/* 1.1 hz */
177 dtrace_optval_t	dtrace_cleanrate_min = 20000000;			/* 50 hz */
178 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
179 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
180 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
181 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
182 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
183 dtrace_optval_t	dtrace_nspec_default = 1;
184 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
185 dtrace_optval_t dtrace_stackframes_default = 20;
186 dtrace_optval_t dtrace_ustackframes_default = 20;
187 dtrace_optval_t dtrace_jstackframes_default = 50;
188 dtrace_optval_t dtrace_jstackstrsize_default = 512;
189 dtrace_optval_t dtrace_buflimit_default = 75;
190 dtrace_optval_t dtrace_buflimit_min = 1;
191 dtrace_optval_t dtrace_buflimit_max = 99;
192 size_t		dtrace_nprobes_default = 4;
193 int		dtrace_msgdsize_max = 128;
194 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
195 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
196 int		dtrace_devdepth_max = 32;
197 int		dtrace_err_verbose;
198 hrtime_t	dtrace_deadman_interval = NANOSEC;
199 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
200 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
201 
202 /*
203  * DTrace External Variables
204  *
205  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
206  * available to DTrace consumers via the backtick (`) syntax.  One of these,
207  * dtrace_zero, is made deliberately so:  it is provided as a source of
208  * well-known, zero-filled memory.  While this variable is not documented,
209  * it is used by some translators as an implementation detail.
210  */
211 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
212 unsigned int	dtrace_max_cpus = 0;		/* number of enabled cpus */
213 /*
214  * DTrace Internal Variables
215  */
216 static dev_info_t	*dtrace_devi;		/* device info */
217 static vmem_t		*dtrace_arena;		/* probe ID arena */
218 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
219 static int		dtrace_nprobes;		/* number of probes */
220 static dtrace_provider_t *dtrace_provider;	/* provider list */
221 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
222 static int		dtrace_opens;		/* number of opens */
223 static int		dtrace_helpers;		/* number of helpers */
224 static dtrace_hash_t	*dtrace_strings;
225 static dtrace_hash_t	*dtrace_byprov;		/* probes hashed by provider */
226 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
227 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
228 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
229 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
230 static int		dtrace_toxranges;	/* number of toxic ranges */
231 static int		dtrace_toxranges_max;	/* size of toxic range array */
232 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
233 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
234 static kthread_t	*dtrace_panicked;	/* panicking thread */
235 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
236 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
237 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
238 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
239 static dtrace_genid_t   dtrace_retained_gen;    /* current retained enab gen */
240 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
241 
242 static int		dtrace_dof_mode;	/* See dtrace_impl.h for a description of Darwin's dof modes. */
243 
244 			/*
245 			 * This does't quite fit as an internal variable, as it must be accessed in
246 			 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
247 			 */
248 int			dtrace_kernel_symbol_mode;	/* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
249 static uint32_t		dtrace_wake_clients;
250 static uint8_t      dtrace_kerneluuid[16];	/* the 128-bit uuid */
251 
252 /*
253  * To save memory, some common memory allocations are given a
254  * unique zone. For example, dtrace_probe_t is 72 bytes in size,
255  * which means it would fall into the kalloc.128 bucket. With
256  * 20k elements allocated, the space saved is substantial.
257  */
258 
259 static ZONE_DEFINE_TYPE(dtrace_probe_t_zone, "dtrace.dtrace_probe_t",
260     dtrace_probe_t, ZC_PGZ_USE_GUARDS);
261 
262 static ZONE_DEFINE(dtrace_state_pcpu_zone, "dtrace.dtrace_dstate_percpu_t",
263     sizeof(dtrace_dstate_percpu_t), ZC_PERCPU);
264 
265 static int dtrace_module_unloaded(struct kmod_info *kmod);
266 
267 /*
268  * DTrace Locking
269  * DTrace is protected by three (relatively coarse-grained) locks:
270  *
271  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
272  *     including enabling state, probes, ECBs, consumer state, helper state,
273  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
274  *     probe context is lock-free -- synchronization is handled via the
275  *     dtrace_sync() cross call mechanism.
276  *
277  * (2) dtrace_provider_lock is required when manipulating provider state, or
278  *     when provider state must be held constant.
279  *
280  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
281  *     when meta provider state must be held constant.
282  *
283  * The lock ordering between these three locks is dtrace_meta_lock before
284  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
285  * several places where dtrace_provider_lock is held by the framework as it
286  * calls into the providers -- which then call back into the framework,
287  * grabbing dtrace_lock.)
288  *
289  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
290  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
291  * role as a coarse-grained lock; it is acquired before both of these locks.
292  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
293  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
294  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
295  * acquired _between_ dtrace_provider_lock and dtrace_lock.
296  */
297 
298 
299 /*
300  * APPLE NOTE:
301  *
302  * For porting purposes, all kmutex_t vars have been changed
303  * to lck_mtx_t, which require explicit initialization.
304  *
305  * kmutex_t becomes lck_mtx_t
306  * mutex_enter() becomes lck_mtx_lock()
307  * mutex_exit() becomes lck_mtx_unlock()
308  *
309  * Lock asserts are changed like this:
310  *
311  * ASSERT(MUTEX_HELD(&cpu_lock));
312  *	becomes:
313  * LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
314  *
315  */
316 static LCK_MTX_DECLARE_ATTR(dtrace_lock,
317     &dtrace_lck_grp, &dtrace_lck_attr);		/* probe state lock */
318 static LCK_MTX_DECLARE_ATTR(dtrace_provider_lock,
319     &dtrace_lck_grp, &dtrace_lck_attr);	/* provider state lock */
320 static LCK_MTX_DECLARE_ATTR(dtrace_meta_lock,
321     &dtrace_lck_grp, &dtrace_lck_attr);	/* meta-provider state lock */
322 static LCK_RW_DECLARE_ATTR(dtrace_dof_mode_lock,
323     &dtrace_lck_grp, &dtrace_lck_attr);	/* dof mode lock */
324 
325 /*
326  * DTrace Provider Variables
327  *
328  * These are the variables relating to DTrace as a provider (that is, the
329  * provider of the BEGIN, END, and ERROR probes).
330  */
331 static dtrace_pattr_t	dtrace_provider_attr = {
332 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
333 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
334 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
335 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
336 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
337 };
338 
339 static void
dtrace_provide_nullop(void * arg,const dtrace_probedesc_t * desc)340 dtrace_provide_nullop(void *arg, const dtrace_probedesc_t *desc)
341 {
342 #pragma unused(arg, desc)
343 }
344 
345 static void
dtrace_provide_module_nullop(void * arg,struct modctl * ctl)346 dtrace_provide_module_nullop(void *arg, struct modctl *ctl)
347 {
348 #pragma unused(arg, ctl)
349 }
350 
351 static int
dtrace_enable_nullop(void * arg,dtrace_id_t id,void * parg)352 dtrace_enable_nullop(void *arg, dtrace_id_t id, void *parg)
353 {
354 #pragma unused(arg, id, parg)
355     return (0);
356 }
357 
358 static void
dtrace_disable_nullop(void * arg,dtrace_id_t id,void * parg)359 dtrace_disable_nullop(void *arg, dtrace_id_t id, void *parg)
360 {
361 #pragma unused(arg, id, parg)
362 }
363 
364 static void
dtrace_suspend_nullop(void * arg,dtrace_id_t id,void * parg)365 dtrace_suspend_nullop(void *arg, dtrace_id_t id, void *parg)
366 {
367 #pragma unused(arg, id, parg)
368 }
369 
370 static void
dtrace_resume_nullop(void * arg,dtrace_id_t id,void * parg)371 dtrace_resume_nullop(void *arg, dtrace_id_t id, void *parg)
372 {
373 #pragma unused(arg, id, parg)
374 }
375 
376 static void
dtrace_destroy_nullop(void * arg,dtrace_id_t id,void * parg)377 dtrace_destroy_nullop(void *arg, dtrace_id_t id, void *parg)
378 {
379 #pragma unused(arg, id, parg)
380 }
381 
382 
383 static dtrace_pops_t dtrace_provider_ops = {
384 	.dtps_provide = dtrace_provide_nullop,
385 	.dtps_provide_module =	dtrace_provide_module_nullop,
386 	.dtps_enable =	dtrace_enable_nullop,
387 	.dtps_disable =	dtrace_disable_nullop,
388 	.dtps_suspend =	dtrace_suspend_nullop,
389 	.dtps_resume =	dtrace_resume_nullop,
390 	.dtps_getargdesc =	NULL,
391 	.dtps_getargval =	NULL,
392 	.dtps_usermode =	NULL,
393 	.dtps_destroy =	dtrace_destroy_nullop,
394 };
395 
396 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
397 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
398 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
399 
400 /*
401  * DTrace Helper Tracing Variables
402  */
403 uint32_t dtrace_helptrace_next = 0;
404 uint32_t dtrace_helptrace_nlocals;
405 char	*dtrace_helptrace_buffer;
406 size_t	dtrace_helptrace_bufsize = 512 * 1024;
407 
408 #if DEBUG
409 int	dtrace_helptrace_enabled = 1;
410 #else
411 int	dtrace_helptrace_enabled = 0;
412 #endif
413 
414 #if defined (__arm64__)
415 /*
416  * The ioctl for adding helper DOF is based on the
417  * size of a user_addr_t.  We need to recognize both
418  * U32 and U64 as the same action.
419  */
420 #define DTRACEHIOC_ADDDOF_U32       _IOW('h', 4, user32_addr_t)
421 #define DTRACEHIOC_ADDDOF_U64       _IOW('h', 4, user64_addr_t)
422 #endif  /* __arm64__ */
423 
424 /*
425  * DTrace Error Hashing
426  *
427  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
428  * table.  This is very useful for checking coverage of tests that are
429  * expected to induce DIF or DOF processing errors, and may be useful for
430  * debugging problems in the DIF code generator or in DOF generation .  The
431  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
432  */
433 #if DEBUG
434 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
435 static const char *dtrace_errlast;
436 static kthread_t *dtrace_errthread;
437 static LCK_MTX_DECLARE_ATTR(dtrace_errlock, &dtrace_lck_grp, &dtrace_lck_attr);
438 #endif
439 
440 /*
441  * DTrace Macros and Constants
442  *
443  * These are various macros that are useful in various spots in the
444  * implementation, along with a few random constants that have no meaning
445  * outside of the implementation.  There is no real structure to this cpp
446  * mishmash -- but is there ever?
447  */
448 
449 #define	DTRACE_GETSTR(hash, elm)	\
450 	(hash->dth_getstr(elm, hash->dth_stroffs))
451 
452 #define	DTRACE_HASHSTR(hash, elm)	\
453 	dtrace_hash_str(DTRACE_GETSTR(hash, elm))
454 
455 #define	DTRACE_HASHNEXT(hash, elm)	\
456 	(void**)((uintptr_t)(elm) + (hash)->dth_nextoffs)
457 
458 #define	DTRACE_HASHPREV(hash, elm)	\
459 	(void**)((uintptr_t)(elm) + (hash)->dth_prevoffs)
460 
461 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
462 	(strcmp(DTRACE_GETSTR(hash, lhs), \
463 	    DTRACE_GETSTR(hash, rhs)) == 0)
464 
465 #define	DTRACE_AGGHASHSIZE_SLEW		17
466 
467 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
468 
469 /*
470  * The key for a thread-local variable needs to be unique to a single
471  * thread over the lifetime of the system, and not overlap with any variable
472  * IDs. So we take thread's thread_id, a unique 64-bit number that is never
473  * reused after the thread exits, and add DIF_VARIABLE_MAX to it, which
474  * guarantees that it won’t overlap any variable IDs. We also want to treat
475  * running in interrupt context as independent of thread-context. So if
476  * interrupts are active, we set the 63rd bit, otherwise it’s cleared.
477  *
478  * This is necessary (but not sufficient) to assure that global associative
479  * arrays never collide with thread-local variables. To guarantee that they
480  * cannot collide, we must also define the order for keying dynamic variables.
481  *
482  * That order is:
483  *
484  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
485  *
486  * Because the variable-key and the tls-key are in orthogonal spaces, there is
487  * no way for a global variable key signature to match a thread-local key
488  * signature.
489  */
490 #if defined (__x86_64__) || defined(__arm__) || defined(__arm64__)
491 #define	DTRACE_TLS_THRKEY(where) {                                           \
492 	uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
493 	uint64_t thr = thread_tid(current_thread());                             \
494 	ASSERT(intr < 2);                                                        \
495 	(where) = ((thr + DIF_VARIABLE_MAX) & (~((uint64_t)1 << 63))) |          \
496 		((uint64_t)intr << 63);                                              \
497 }
498 #else
499 #error Unknown architecture
500 #endif
501 
502 #define	DT_BSWAP_8(x)	((x) & 0xff)
503 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
504 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
505 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
506 
507 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
508 
509 #define	DTRACE_STORE(type, tomax, offset, what) \
510 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
511 
512 
513 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
514 	if (addr & (MIN(size,4) - 1)) {					\
515 		*flags |= CPU_DTRACE_BADALIGN;				\
516 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
517 		return (0);						\
518 	}
519 
520 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
521 do {									\
522 	if ((remp) != NULL) {						\
523 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
524 	}								\
525 } while (0)
526 
527 
528 /*
529  * Test whether a range of memory starting at testaddr of size testsz falls
530  * within the range of memory described by addr, sz.  We take care to avoid
531  * problems with overflow and underflow of the unsigned quantities, and
532  * disallow all negative sizes.  Ranges of size 0 are allowed.
533  */
534 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
535 	((testaddr) - (baseaddr) < (basesz) && \
536 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
537 	(testaddr) + (testsz) >= (testaddr))
538 
539 /*
540  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
541  * alloc_sz on the righthand side of the comparison in order to avoid overflow
542  * or underflow in the comparison with it.  This is simpler than the INRANGE
543  * check above, because we know that the dtms_scratch_ptr is valid in the
544  * range.  Allocations of size zero are allowed.
545  */
546 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
547 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
548 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
549 
550 #if defined (__x86_64__) || (defined (__arm__) || defined (__arm64__))
551 #define	DTRACE_LOADFUNC(bits)						\
552 /*CSTYLED*/								\
553 uint##bits##_t dtrace_load##bits(uintptr_t addr);			\
554 									\
555 extern int dtrace_nofault_copy##bits(uintptr_t, uint##bits##_t *);	\
556 									\
557 uint##bits##_t								\
558 dtrace_load##bits(uintptr_t addr)					\
559 {									\
560 	size_t size = bits / NBBY;					\
561 	/*CSTYLED*/							\
562 	uint##bits##_t rval = 0;					\
563 	int i;								\
564 	volatile uint16_t *flags = (volatile uint16_t *)		\
565 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
566 									\
567 	DTRACE_ALIGNCHECK(addr, size, flags);				\
568 									\
569 	for (i = 0; i < dtrace_toxranges; i++) {			\
570 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
571 			continue;					\
572 									\
573 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
574 			continue;					\
575 									\
576 		/*							\
577 		 * This address falls within a toxic region; return 0.	\
578 		 */							\
579 		*flags |= CPU_DTRACE_BADADDR;				\
580 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
581 		return (0);						\
582 	}								\
583 									\
584 	{								\
585 	*flags |= CPU_DTRACE_NOFAULT;					\
586 	/*CSTYLED*/							\
587 	/*                                                              \
588 	* PR6394061 - avoid device memory that is unpredictably		\
589 	* mapped and unmapped                                   	\
590 	*/								\
591 	if (!pmap_valid_page(pmap_find_phys(kernel_pmap, addr)) ||	\
592 	    dtrace_nofault_copy##bits(addr, &rval)) {			\
593 		*flags |= CPU_DTRACE_BADADDR;				\
594 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
595 		return (0);						\
596 	}								\
597 									\
598 	*flags &= ~CPU_DTRACE_NOFAULT;					\
599 	}								\
600 									\
601 	return (rval);							\
602 }
603 #else /* all other architectures */
604 #error Unknown Architecture
605 #endif
606 
607 #ifdef __LP64__
608 #define	dtrace_loadptr	dtrace_load64
609 #else
610 #define	dtrace_loadptr	dtrace_load32
611 #endif
612 
613 #define	DTRACE_DYNHASH_FREE	0
614 #define	DTRACE_DYNHASH_SINK	1
615 #define	DTRACE_DYNHASH_VALID	2
616 
617 #define DTRACE_MATCH_FAIL       -1
618 #define	DTRACE_MATCH_NEXT	0
619 #define	DTRACE_MATCH_DONE	1
620 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
621 #define	DTRACE_STATE_ALIGN	64
622 
623 #define	DTRACE_FLAGS2FLT(flags)						\
624 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
625 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
626 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
627 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
628 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
629 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
630 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
631 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
632 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
633 	DTRACEFLT_UNKNOWN)
634 
635 #define	DTRACEACT_ISSTRING(act)						\
636 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
637 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
638 
639 
640 static size_t dtrace_strlen(const char *, size_t);
641 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
642 static void dtrace_enabling_provide(dtrace_provider_t *);
643 static int dtrace_enabling_match(dtrace_enabling_t *, int *, dtrace_match_cond_t *cond);
644 static void dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond);
645 static void dtrace_enabling_matchall(void);
646 static dtrace_state_t *dtrace_anon_grab(void);
647 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
648     dtrace_state_t *, uint64_t, uint64_t);
649 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
650 static void dtrace_buffer_drop(dtrace_buffer_t *);
651 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
652     dtrace_state_t *, dtrace_mstate_t *);
653 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
654     dtrace_optval_t);
655 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *, void *);
656 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
657 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
658 	dtrace_mstate_t *, dtrace_vstate_t *);
659 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
660 	dtrace_mstate_t *, dtrace_vstate_t *);
661 
662 
663 /*
664  * DTrace sysctl handlers
665  *
666  * These declarations and functions are used for a deeper DTrace configuration.
667  * Most of them are not per-consumer basis and may impact the other DTrace
668  * consumers.  Correctness may not be supported for all the variables, so you
669  * should be careful about what values you are using.
670  */
671 
672 SYSCTL_DECL(_kern_dtrace);
673 SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
674 
675 static int
676 sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
677 {
678 #pragma unused(oidp, arg2)
679 	int changed, error;
680 	int value = *(int *) arg1;
681 
682 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
683 	if (error || !changed)
684 		return (error);
685 
686 	if (value != 0 && value != 1)
687 		return (ERANGE);
688 
689 	lck_mtx_lock(&dtrace_lock);
690 		dtrace_err_verbose = value;
691 	lck_mtx_unlock(&dtrace_lock);
692 
693 	return (0);
694 }
695 
696 /*
697  * kern.dtrace.err_verbose
698  *
699  * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
700  * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
701  */
702 SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
703 	CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
704 	&dtrace_err_verbose, 0,
705 	sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
706 
707 static int
708 sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
709 {
710 #pragma unused(oidp, arg2, req)
711 	int changed, error;
712 	uint64_t value = *(uint64_t *) arg1;
713 
714 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
715 	if (error || !changed)
716 		return (error);
717 
718 	if (value <= dtrace_buffer_memory_inuse)
719 		return (ERANGE);
720 
721 	lck_mtx_lock(&dtrace_lock);
722 		dtrace_buffer_memory_maxsize = value;
723 	lck_mtx_unlock(&dtrace_lock);
724 
725 	return (0);
726 }
727 
728 /*
729  * kern.dtrace.buffer_memory_maxsize
730  *
731  * Set DTrace maximal size in bytes used by all the consumers' state buffers.  By default
732  * the limit is PHYS_MEM / 3 for *all* consumers.  Attempting to set a null, a negative value
733  * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
734  */
735 SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
736 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
737 	&dtrace_buffer_memory_maxsize, 0,
738 	sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
739 
740 /*
741  * kern.dtrace.buffer_memory_inuse
742  *
743  * Current state buffer memory used, in bytes, by all the DTrace consumers.
744  * This value is read-only.
745  */
746 SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
747 	&dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
748 
749 static int
750 sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
751 {
752 #pragma unused(oidp, arg2, req)
753 	int changed, error;
754 	size_t value = *(size_t*) arg1;
755 
756 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
757 	if (error || !changed)
758 		return (error);
759 
760 	if (value <= 0)
761 		return (ERANGE);
762 
763 	lck_mtx_lock(&dtrace_lock);
764 		dtrace_difo_maxsize = value;
765 	lck_mtx_unlock(&dtrace_lock);
766 
767 	return (0);
768 }
769 
770 /*
771  * kern.dtrace.difo_maxsize
772  *
773  * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
774  * to get the default value.  Attempting to set a null or negative size will
775  * result in a failure.
776  */
777 SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
778 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
779 	&dtrace_difo_maxsize, 0,
780 	sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
781 
782 static int
783 sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
784 {
785 #pragma unused(oidp, arg2, req)
786 	int changed, error;
787 	dtrace_optval_t value = *(dtrace_optval_t *) arg1;
788 
789 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
790 	if (error || !changed)
791 		return (error);
792 
793 	if (value <= 0)
794 		return (ERANGE);
795 
796 	if (value >= dtrace_copy_maxsize())
797 		return (ERANGE);
798 
799 	lck_mtx_lock(&dtrace_lock);
800 		dtrace_dof_maxsize = value;
801 	lck_mtx_unlock(&dtrace_lock);
802 
803 	return (0);
804 }
805 
806 /*
807  * kern.dtrace.dof_maxsize
808  *
809  * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
810  * get the default value.  Attempting to set a null or negative size will result
811  * in a failure.
812  */
813 SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
814 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
815 	&dtrace_dof_maxsize, 0,
816 	sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
817 
818 static int
819 sysctl_dtrace_statvar_maxsize SYSCTL_HANDLER_ARGS
820 {
821 #pragma unused(oidp, arg2, req)
822 	int changed, error;
823 	dtrace_optval_t value = *(dtrace_optval_t*) arg1;
824 
825 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
826 	if (error || !changed)
827 		return (error);
828 
829 	if (value <= 0)
830 		return (ERANGE);
831 	if (value > dtrace_statvar_maxsize_max)
832 		return (ERANGE);
833 
834 	lck_mtx_lock(&dtrace_lock);
835 		dtrace_statvar_maxsize = value;
836 	lck_mtx_unlock(&dtrace_lock);
837 
838 	return (0);
839 }
840 
841 /*
842  * kern.dtrace.global_maxsize
843  *
844  * Set the variable max size in bytes, check the definition of
845  * dtrace_statvar_maxsize to get the default value.  Attempting to set a null,
846  * too high or negative size will result in a failure.
847  */
848 SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
849 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
850 	&dtrace_statvar_maxsize, 0,
851 	sysctl_dtrace_statvar_maxsize, "Q", "dtrace statvar maxsize");
852 
853 
854 /*
855  * kern.dtrace.provide_private_probes
856  *
857  * Set whether the providers must provide the private probes.  This is
858  * kept as compatibility as they are always provided.
859  */
860 SYSCTL_INT(_kern_dtrace, OID_AUTO, provide_private_probes,
861 	CTLFLAG_RD | CTLFLAG_LOCKED,
862 	(int *)NULL, 1, "provider must provide the private probes");
863 
864 /*
865  * kern.dtrace.dof_mode
866  *
867  * Returns the current DOF mode.
868  * This value is read-only.
869  */
870 SYSCTL_INT(_kern_dtrace, OID_AUTO, dof_mode, CTLFLAG_RD | CTLFLAG_LOCKED,
871 	&dtrace_dof_mode, 0, "dtrace dof mode");
872 
873 /*
874  * DTrace Probe Context Functions
875  *
876  * These functions are called from probe context.  Because probe context is
877  * any context in which C may be called, arbitrarily locks may be held,
878  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
879  * As a result, functions called from probe context may only call other DTrace
880  * support functions -- they may not interact at all with the system at large.
881  * (Note that the ASSERT macro is made probe-context safe by redefining it in
882  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
883  * loads are to be performed from probe context, they _must_ be in terms of
884  * the safe dtrace_load*() variants.
885  *
886  * Some functions in this block are not actually called from probe context;
887  * for these functions, there will be a comment above the function reading
888  * "Note:  not called from probe context."
889  */
890 
891 int
dtrace_assfail(const char * a,const char * f,int l)892 dtrace_assfail(const char *a, const char *f, int l)
893 {
894 	panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
895 
896 	/*
897 	 * We just need something here that even the most clever compiler
898 	 * cannot optimize away.
899 	 */
900 	return (a[(uintptr_t)f]);
901 }
902 
903 /*
904  * Atomically increment a specified error counter from probe context.
905  */
906 static void
dtrace_error(uint32_t * counter)907 dtrace_error(uint32_t *counter)
908 {
909 	/*
910 	 * Most counters stored to in probe context are per-CPU counters.
911 	 * However, there are some error conditions that are sufficiently
912 	 * arcane that they don't merit per-CPU storage.  If these counters
913 	 * are incremented concurrently on different CPUs, scalability will be
914 	 * adversely affected -- but we don't expect them to be white-hot in a
915 	 * correctly constructed enabling...
916 	 */
917 	uint32_t oval, nval;
918 
919 	do {
920 		oval = *counter;
921 
922 		if ((nval = oval + 1) == 0) {
923 			/*
924 			 * If the counter would wrap, set it to 1 -- assuring
925 			 * that the counter is never zero when we have seen
926 			 * errors.  (The counter must be 32-bits because we
927 			 * aren't guaranteed a 64-bit compare&swap operation.)
928 			 * To save this code both the infamy of being fingered
929 			 * by a priggish news story and the indignity of being
930 			 * the target of a neo-puritan witch trial, we're
931 			 * carefully avoiding any colorful description of the
932 			 * likelihood of this condition -- but suffice it to
933 			 * say that it is only slightly more likely than the
934 			 * overflow of predicate cache IDs, as discussed in
935 			 * dtrace_predicate_create().
936 			 */
937 			nval = 1;
938 		}
939 	} while (dtrace_cas32(counter, oval, nval) != oval);
940 }
941 
942 /*
943  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
944  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
945  */
946 DTRACE_LOADFUNC(8)
947 DTRACE_LOADFUNC(16)
948 DTRACE_LOADFUNC(32)
949 DTRACE_LOADFUNC(64)
950 
951 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)952 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
953 {
954 	if (dest < mstate->dtms_scratch_base)
955 		return (0);
956 
957 	if (dest + size < dest)
958 		return (0);
959 
960 	if (dest + size > mstate->dtms_scratch_ptr)
961 		return (0);
962 
963 	return (1);
964 }
965 
966 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)967 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
968     dtrace_statvar_t **svars, int nsvars)
969 {
970 	int i;
971 
972 	size_t maxglobalsize, maxlocalsize;
973 
974 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
975 	maxlocalsize = (maxglobalsize) * NCPU;
976 
977 	if (nsvars == 0)
978 		return (0);
979 
980 	for (i = 0; i < nsvars; i++) {
981 		dtrace_statvar_t *svar = svars[i];
982 		uint8_t scope;
983 		size_t size;
984 
985 		if (svar == NULL || (size = svar->dtsv_size) == 0)
986 			continue;
987 
988 		scope = svar->dtsv_var.dtdv_scope;
989 
990 		/**
991 		 * We verify that our size is valid in the spirit of providing
992 		 * defense in depth:  we want to prevent attackers from using
993 		 * DTrace to escalate an orthogonal kernel heap corruption bug
994 		 * into the ability to store to arbitrary locations in memory.
995 		 */
996 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
997 			(scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
998 
999 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size)) {
1000 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
1001 				svar->dtsv_size);
1002 			return (1);
1003 		}
1004 	}
1005 
1006 	return (0);
1007 }
1008 
1009 /*
1010  * Check to see if the address is within a memory region to which a store may
1011  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
1012  * region.  The caller of dtrace_canstore() is responsible for performing any
1013  * alignment checks that are needed before stores are actually executed.
1014  */
1015 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1016 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1017     dtrace_vstate_t *vstate)
1018 {
1019 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
1020 }
1021 /*
1022  * Implementation of dtrace_canstore which communicates the upper bound of the
1023  * allowed memory region.
1024  */
1025 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1026 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
1027 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1028 {
1029 	/*
1030 	 * First, check to see if the address is in scratch space...
1031 	 */
1032 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
1033 	    mstate->dtms_scratch_size)) {
1034 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
1035 			mstate->dtms_scratch_size);
1036 		return (1);
1037 	}
1038 	/*
1039 	 * Now check to see if it's a dynamic variable.  This check will pick
1040 	 * up both thread-local variables and any global dynamically-allocated
1041 	 * variables.
1042 	 */
1043 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
1044 	    vstate->dtvs_dynvars.dtds_size)) {
1045 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
1046 		uintptr_t base = (uintptr_t)dstate->dtds_base +
1047 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
1048 		uintptr_t chunkoffs;
1049 		dtrace_dynvar_t *dvar;
1050 
1051 		/*
1052 		 * Before we assume that we can store here, we need to make
1053 		 * sure that it isn't in our metadata -- storing to our
1054 		 * dynamic variable metadata would corrupt our state.  For
1055 		 * the range to not include any dynamic variable metadata,
1056 		 * it must:
1057 		 *
1058 		 *	(1) Start above the hash table that is at the base of
1059 		 *	the dynamic variable space
1060 		 *
1061 		 *	(2) Have a starting chunk offset that is beyond the
1062 		 *	dtrace_dynvar_t that is at the base of every chunk
1063 		 *
1064 		 *	(3) Not span a chunk boundary
1065 		 *
1066 		 *	(4) Not be in the tuple space of a dynamic variable
1067 		 *
1068 		 */
1069 		if (addr < base)
1070 			return (0);
1071 
1072 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
1073 
1074 		if (chunkoffs < sizeof (dtrace_dynvar_t))
1075 			return (0);
1076 
1077 		if (chunkoffs + sz > dstate->dtds_chunksize)
1078 			return (0);
1079 
1080 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
1081 
1082 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
1083 			return (0);
1084 
1085 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
1086 			((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
1087 			return (0);
1088 
1089 		return (1);
1090 	}
1091 
1092 	/*
1093 	 * Finally, check the static local and global variables.  These checks
1094 	 * take the longest, so we perform them last.
1095 	 */
1096 	if (dtrace_canstore_statvar(addr, sz, remain,
1097 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
1098 		return (1);
1099 
1100 	if (dtrace_canstore_statvar(addr, sz, remain,
1101 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
1102 		return (1);
1103 
1104 	return (0);
1105 }
1106 
1107 
1108 /*
1109  * Convenience routine to check to see if the address is within a memory
1110  * region in which a load may be issued given the user's privilege level;
1111  * if not, it sets the appropriate error flags and loads 'addr' into the
1112  * illegal value slot.
1113  *
1114  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
1115  * appropriate memory access protection.
1116  */
1117 int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1118 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1119     dtrace_vstate_t *vstate)
1120 {
1121 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
1122 }
1123 
1124 /*
1125  * Implementation of dtrace_canload which communicates the upper bound of the
1126  * allowed memory region.
1127  */
1128 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1129 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
1130 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1131 {
1132 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
1133 
1134 	/*
1135 	 * If we hold the privilege to read from kernel memory, then
1136 	 * everything is readable.
1137 	 */
1138 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1139 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1140 		return (1);
1141 	}
1142 
1143 	/*
1144 	 * You can obviously read that which you can store.
1145 	 */
1146 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
1147 		return (1);
1148 
1149 	/*
1150 	 * We're allowed to read from our own string table.
1151 	 */
1152 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
1153 	    mstate->dtms_difo->dtdo_strlen)) {
1154 		DTRACE_RANGE_REMAIN(remain, addr,
1155 			mstate->dtms_difo->dtdo_strtab,
1156 			mstate->dtms_difo->dtdo_strlen);
1157 		return (1);
1158 	}
1159 
1160 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1161 	*illval = addr;
1162 	return (0);
1163 }
1164 
1165 /*
1166  * Convenience routine to check to see if a given string is within a memory
1167  * region in which a load may be issued given the user's privilege level;
1168  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1169  * calls in the event that the user has all privileges.
1170  */
1171 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1172 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1173 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1174 {
1175 	size_t rsize = 0;
1176 
1177 	/*
1178 	 * If we hold the privilege to read from kernel memory, then
1179 	 * everything is readable.
1180 	 */
1181 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1182 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1183 		return (1);
1184 	}
1185 
1186 	/*
1187 	 * Even if the caller is uninterested in querying the remaining valid
1188 	 * range, it is required to ensure that the access is allowed.
1189 	 */
1190 	if (remain == NULL) {
1191 		remain = &rsize;
1192 	}
1193 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1194 		size_t strsz;
1195 		/*
1196 		 * Perform the strlen after determining the length of the
1197 		 * memory region which is accessible.  This prevents timing
1198 		 * information from being used to find NULs in memory which is
1199 		 * not accessible to the caller.
1200 		 */
1201 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1202 			MIN(sz, *remain));
1203 		if (strsz <= *remain) {
1204 			return (1);
1205 		}
1206 	}
1207 
1208 	return (0);
1209 }
1210 
1211 /*
1212  * Convenience routine to check to see if a given variable is within a memory
1213  * region in which a load may be issued given the user's privilege level.
1214  */
1215 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1216 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1217 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1218 {
1219 	size_t sz;
1220 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1221 
1222 	/*
1223 	 * Calculate the max size before performing any checks since even
1224 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1225 	 * return the max length via 'remain'.
1226 	 */
1227 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1228 		dtrace_state_t *state = vstate->dtvs_state;
1229 
1230 		if (state != NULL) {
1231 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1232 		} else {
1233 			/*
1234 			 * In helper context, we have a NULL state; fall back
1235 			 * to using the system-wide default for the string size
1236 			 * in this case.
1237 			 */
1238 			sz = dtrace_strsize_default;
1239 		}
1240 	} else {
1241 		sz = type->dtdt_size;
1242 	}
1243 
1244 	/*
1245 	 * If we hold the privilege to read from kernel memory, then
1246 	 * everything is readable.
1247 	 */
1248 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1249 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1250 		return (1);
1251 	}
1252 
1253 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1254 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1255 			vstate));
1256 	}
1257 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1258 		vstate));
1259 }
1260 
1261 #define	isdigit(ch)	((ch) >= '0' && (ch) <= '9')
1262 #define	islower(ch)	((ch) >= 'a' && (ch) <= 'z')
1263 #define	isspace(ch)	(((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \
1264 			((ch) == '\t') || ((ch) == '\f'))
1265 #define	isxdigit(ch)	(isdigit(ch) || ((ch) >= 'a' && (ch) <= 'f') || \
1266 			((ch) >= 'A' && (ch) <= 'F'))
1267 #define	lisalnum(x)	\
1268 	(isdigit(x) || ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))
1269 
1270 #define	DIGIT(x)	\
1271 	(isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
1272 
1273 /*
1274  * Convert a string to a signed integer using safe loads.
1275  */
1276 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1277 dtrace_strtoll(char *input, int base, size_t limit)
1278 {
1279 	uintptr_t pos = (uintptr_t)input;
1280 	int64_t val = 0;
1281 	int x;
1282 	boolean_t neg = B_FALSE;
1283 	char c, cc, ccc;
1284 	uintptr_t end = pos + limit;
1285 
1286 	/*
1287 	 * Consume any whitespace preceding digits.
1288 	 */
1289 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1290 		pos++;
1291 
1292 	/*
1293 	 * Handle an explicit sign if one is present.
1294 	 */
1295 	if (c == '-' || c == '+') {
1296 		if (c == '-')
1297 			neg = B_TRUE;
1298 		c = dtrace_load8(++pos);
1299 	}
1300 
1301 	/*
1302 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1303 	 * if present.
1304 	 */
1305 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1306 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1307 		pos += 2;
1308 		c = ccc;
1309 	}
1310 
1311 	/*
1312 	 * Read in contiguous digits until the first non-digit character.
1313 	 */
1314 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1315 	    c = dtrace_load8(++pos))
1316 		val = val * base + x;
1317 
1318 	return (neg ? -val : val);
1319 }
1320 
1321 
1322 /*
1323  * Compare two strings using safe loads.
1324  */
1325 static int
dtrace_strncmp(const char * s1,const char * s2,size_t limit)1326 dtrace_strncmp(const char *s1, const char *s2, size_t limit)
1327 {
1328 	uint8_t c1, c2;
1329 	volatile uint16_t *flags;
1330 
1331 	if (s1 == s2 || limit == 0)
1332 		return (0);
1333 
1334 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1335 
1336 	do {
1337 		if (s1 == NULL) {
1338 			c1 = '\0';
1339 		} else {
1340 			c1 = dtrace_load8((uintptr_t)s1++);
1341 		}
1342 
1343 		if (s2 == NULL) {
1344 			c2 = '\0';
1345 		} else {
1346 			c2 = dtrace_load8((uintptr_t)s2++);
1347 		}
1348 
1349 		if (c1 != c2)
1350 			return (c1 - c2);
1351 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1352 
1353 	return (0);
1354 }
1355 
1356 /*
1357  * Compute strlen(s) for a string using safe memory accesses.  The additional
1358  * len parameter is used to specify a maximum length to ensure completion.
1359  */
1360 static size_t
dtrace_strlen(const char * s,size_t lim)1361 dtrace_strlen(const char *s, size_t lim)
1362 {
1363 	uint_t len;
1364 
1365 	for (len = 0; len != lim; len++) {
1366 		if (dtrace_load8((uintptr_t)s++) == '\0')
1367 			break;
1368 	}
1369 
1370 	return (len);
1371 }
1372 
1373 /*
1374  * Check if an address falls within a toxic region.
1375  */
1376 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1377 dtrace_istoxic(uintptr_t kaddr, size_t size)
1378 {
1379 	uintptr_t taddr, tsize;
1380 	int i;
1381 
1382 	for (i = 0; i < dtrace_toxranges; i++) {
1383 		taddr = dtrace_toxrange[i].dtt_base;
1384 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1385 
1386 		if (kaddr - taddr < tsize) {
1387 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1388 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1389 			return (1);
1390 		}
1391 
1392 		if (taddr - kaddr < size) {
1393 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1394 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1395 			return (1);
1396 		}
1397 	}
1398 
1399 	return (0);
1400 }
1401 
1402 /*
1403  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1404  * memory specified by the DIF program.  The dst is assumed to be safe memory
1405  * that we can store to directly because it is managed by DTrace.  As with
1406  * standard bcopy, overlapping copies are handled properly.
1407  */
1408 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1409 dtrace_bcopy(const void *src, void *dst, size_t len)
1410 {
1411 	if (len != 0) {
1412 		uint8_t *s1 = dst;
1413 		const uint8_t *s2 = src;
1414 
1415 		if (s1 <= s2) {
1416 			do {
1417 				*s1++ = dtrace_load8((uintptr_t)s2++);
1418 			} while (--len != 0);
1419 		} else {
1420 			s2 += len;
1421 			s1 += len;
1422 
1423 			do {
1424 				*--s1 = dtrace_load8((uintptr_t)--s2);
1425 			} while (--len != 0);
1426 		}
1427 	}
1428 }
1429 
1430 /*
1431  * Copy src to dst using safe memory accesses, up to either the specified
1432  * length, or the point that a nul byte is encountered.  The src is assumed to
1433  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1434  * safe memory that we can store to directly because it is managed by DTrace.
1435  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1436  */
1437 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1438 dtrace_strcpy(const void *src, void *dst, size_t len)
1439 {
1440 	if (len != 0) {
1441 		uint8_t *s1 = dst, c;
1442 		const uint8_t *s2 = src;
1443 
1444 		do {
1445 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1446 		} while (--len != 0 && c != '\0');
1447 	}
1448 }
1449 
1450 /*
1451  * Copy src to dst, deriving the size and type from the specified (BYREF)
1452  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1453  * program.  The dst is assumed to be DTrace variable memory that is of the
1454  * specified type; we assume that we can store to directly.
1455  */
1456 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1457 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1458 {
1459 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1460 
1461 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1462 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1463 	} else {
1464 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1465 	}
1466 }
1467 
1468 /*
1469  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1470  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1471  * safe memory that we can access directly because it is managed by DTrace.
1472  */
1473 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1474 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1475 {
1476 	volatile uint16_t *flags;
1477 
1478 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1479 
1480 	if (s1 == s2)
1481 		return (0);
1482 
1483 	if (s1 == NULL || s2 == NULL)
1484 		return (1);
1485 
1486 	if (s1 != s2 && len != 0) {
1487 		const uint8_t *ps1 = s1;
1488 		const uint8_t *ps2 = s2;
1489 
1490 		do {
1491 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1492 				return (1);
1493 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1494 	}
1495 	return (0);
1496 }
1497 
1498 /*
1499  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1500  * is for safe DTrace-managed memory only.
1501  */
1502 static void
dtrace_bzero(void * dst,size_t len)1503 dtrace_bzero(void *dst, size_t len)
1504 {
1505 	uchar_t *cp;
1506 
1507 	for (cp = dst; len != 0; len--)
1508 		*cp++ = 0;
1509 }
1510 
1511 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1512 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1513 {
1514 	uint64_t result[2];
1515 
1516 	result[0] = addend1[0] + addend2[0];
1517 	result[1] = addend1[1] + addend2[1] +
1518 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1519 
1520 	sum[0] = result[0];
1521 	sum[1] = result[1];
1522 }
1523 
1524 /*
1525  * Shift the 128-bit value in a by b. If b is positive, shift left.
1526  * If b is negative, shift right.
1527  */
1528 static void
dtrace_shift_128(uint64_t * a,int b)1529 dtrace_shift_128(uint64_t *a, int b)
1530 {
1531 	uint64_t mask;
1532 
1533 	if (b == 0)
1534 		return;
1535 
1536 	if (b < 0) {
1537 		b = -b;
1538 		if (b >= 64) {
1539 			a[0] = a[1] >> (b - 64);
1540 			a[1] = 0;
1541 		} else {
1542 			a[0] >>= b;
1543 			mask = 1LL << (64 - b);
1544 			mask -= 1;
1545 			a[0] |= ((a[1] & mask) << (64 - b));
1546 			a[1] >>= b;
1547 		}
1548 	} else {
1549 		if (b >= 64) {
1550 			a[1] = a[0] << (b - 64);
1551 			a[0] = 0;
1552 		} else {
1553 			a[1] <<= b;
1554 			mask = a[0] >> (64 - b);
1555 			a[1] |= mask;
1556 			a[0] <<= b;
1557 		}
1558 	}
1559 }
1560 
1561 /*
1562  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1563  * use native multiplication on those, and then re-combine into the
1564  * resulting 128-bit value.
1565  *
1566  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1567  *     hi1 * hi2 << 64 +
1568  *     hi1 * lo2 << 32 +
1569  *     hi2 * lo1 << 32 +
1570  *     lo1 * lo2
1571  */
1572 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1573 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1574 {
1575 	uint64_t hi1, hi2, lo1, lo2;
1576 	uint64_t tmp[2];
1577 
1578 	hi1 = factor1 >> 32;
1579 	hi2 = factor2 >> 32;
1580 
1581 	lo1 = factor1 & DT_MASK_LO;
1582 	lo2 = factor2 & DT_MASK_LO;
1583 
1584 	product[0] = lo1 * lo2;
1585 	product[1] = hi1 * hi2;
1586 
1587 	tmp[0] = hi1 * lo2;
1588 	tmp[1] = 0;
1589 	dtrace_shift_128(tmp, 32);
1590 	dtrace_add_128(product, tmp, product);
1591 
1592 	tmp[0] = hi2 * lo1;
1593 	tmp[1] = 0;
1594 	dtrace_shift_128(tmp, 32);
1595 	dtrace_add_128(product, tmp, product);
1596 }
1597 
1598 /*
1599  * This privilege check should be used by actions and subroutines to
1600  * verify that the user credentials of the process that enabled the
1601  * invoking ECB match the target credentials
1602  */
1603 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1604 dtrace_priv_proc_common_user(dtrace_state_t *state)
1605 {
1606 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1607 
1608 	/*
1609 	 * We should always have a non-NULL state cred here, since if cred
1610 	 * is null (anonymous tracing), we fast-path bypass this routine.
1611 	 */
1612 	ASSERT(s_cr != NULL);
1613 
1614 	if ((cr = dtrace_CRED()) != NULL &&
1615 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1616 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1617 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1618 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1619 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1620 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1621 		return (1);
1622 
1623 	return (0);
1624 }
1625 
1626 /*
1627  * This privilege check should be used by actions and subroutines to
1628  * verify that the zone of the process that enabled the invoking ECB
1629  * matches the target credentials
1630  */
1631 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1632 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1633 {
1634 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1635 #pragma unused(cr, s_cr, state) /* __APPLE__ */
1636 
1637 	/*
1638 	 * We should always have a non-NULL state cred here, since if cred
1639 	 * is null (anonymous tracing), we fast-path bypass this routine.
1640 	 */
1641 	ASSERT(s_cr != NULL);
1642 
1643 	return 1; /* APPLE NOTE: Darwin doesn't do zones. */
1644 }
1645 
1646 /*
1647  * This privilege check should be used by actions and subroutines to
1648  * verify that the process has not setuid or changed credentials.
1649  */
1650 static int
dtrace_priv_proc_common_nocd(void)1651 dtrace_priv_proc_common_nocd(void)
1652 {
1653 	return 1; /* Darwin omits "No Core Dump" flag. */
1654 }
1655 
1656 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1657 dtrace_priv_proc_destructive(dtrace_state_t *state)
1658 {
1659 	int action = state->dts_cred.dcr_action;
1660 
1661 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1662 		goto bad;
1663 
1664 	if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1665 		goto bad;
1666 
1667 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1668 	    dtrace_priv_proc_common_zone(state) == 0)
1669 		goto bad;
1670 
1671 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1672 	    dtrace_priv_proc_common_user(state) == 0)
1673 		goto bad;
1674 
1675 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1676 	    dtrace_priv_proc_common_nocd() == 0)
1677 		goto bad;
1678 
1679 	return (1);
1680 
1681 bad:
1682 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1683 
1684 	return (0);
1685 }
1686 
1687 static int
dtrace_priv_proc_control(dtrace_state_t * state)1688 dtrace_priv_proc_control(dtrace_state_t *state)
1689 {
1690 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1691 		goto bad;
1692 
1693 	if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1694 		goto bad;
1695 
1696 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1697 		return (1);
1698 
1699 	if (dtrace_priv_proc_common_zone(state) &&
1700 	    dtrace_priv_proc_common_user(state) &&
1701 	    dtrace_priv_proc_common_nocd())
1702 		return (1);
1703 
1704 bad:
1705 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1706 
1707 	return (0);
1708 }
1709 
1710 static int
dtrace_priv_proc(dtrace_state_t * state)1711 dtrace_priv_proc(dtrace_state_t *state)
1712 {
1713 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1714 		goto bad;
1715 
1716 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed() && !dtrace_can_attach_to_proc(current_proc()))
1717 		goto bad;
1718 
1719 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1720 		return (1);
1721 
1722 bad:
1723 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1724 
1725 	return (0);
1726 }
1727 
1728 /*
1729  * The P_LNOATTACH check is an Apple specific check.
1730  * We need a version of dtrace_priv_proc() that omits
1731  * that check for PID and EXECNAME accesses
1732  */
1733 static int
dtrace_priv_proc_relaxed(dtrace_state_t * state)1734 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1735 {
1736 
1737 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1738 		return (1);
1739 
1740 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1741 
1742 	return (0);
1743 }
1744 
1745 static int
dtrace_priv_kernel(dtrace_state_t * state)1746 dtrace_priv_kernel(dtrace_state_t *state)
1747 {
1748 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed())
1749 		goto bad;
1750 
1751 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1752 		return (1);
1753 
1754 bad:
1755 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1756 
1757 	return (0);
1758 }
1759 
1760 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1761 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1762 {
1763 	if (dtrace_is_restricted())
1764 		goto bad;
1765 
1766 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1767 		return (1);
1768 
1769 bad:
1770 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1771 
1772 	return (0);
1773 }
1774 
1775 /*
1776  * Note:  not called from probe context.  This function is called
1777  * asynchronously (and at a regular interval) from outside of probe context to
1778  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1779  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1780  */
1781 static void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1782 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1783 {
1784 	dtrace_dynvar_t *dirty;
1785 	int work = 0;
1786 
1787 	zpercpu_foreach(dcpu, dstate->dtds_percpu) {
1788 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1789 
1790 		/*
1791 		 * If the dirty list is NULL, there is no dirty work to do.
1792 		 */
1793 		if (dcpu->dtdsc_dirty == NULL)
1794 			continue;
1795 
1796 		/*
1797 		 * If the clean list is non-NULL, then we're not going to do
1798 		 * any work for this CPU -- it means that there has not been
1799 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1800 		 * since the last time we cleaned house.
1801 		 */
1802 		if (dcpu->dtdsc_clean != NULL)
1803 			continue;
1804 
1805 		work = 1;
1806 
1807 		/*
1808 		 * Atomically move the dirty list aside.
1809 		 */
1810 		do {
1811 			dirty = dcpu->dtdsc_dirty;
1812 
1813 			/*
1814 			 * Before we zap the dirty list, set the rinsing list.
1815 			 * (This allows for a potential assertion in
1816 			 * dtrace_dynvar():  if a free dynamic variable appears
1817 			 * on a hash chain, either the dirty list or the
1818 			 * rinsing list for some CPU must be non-NULL.)
1819 			 */
1820 			dcpu->dtdsc_rinsing = dirty;
1821 			dtrace_membar_producer();
1822 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1823 		    dirty, NULL) != dirty);
1824 	}
1825 
1826 	if (!work) {
1827 		/*
1828 		 * We have no work to do; we can simply return.
1829 		 */
1830 		return;
1831 	}
1832 
1833 	dtrace_sync();
1834 
1835 	zpercpu_foreach(dcpu, dstate->dtds_percpu) {
1836 		if (dcpu->dtdsc_rinsing == NULL)
1837 			continue;
1838 
1839 		/*
1840 		 * We are now guaranteed that no hash chain contains a pointer
1841 		 * into this dirty list; we can make it clean.
1842 		 */
1843 		ASSERT(dcpu->dtdsc_clean == NULL);
1844 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1845 		dcpu->dtdsc_rinsing = NULL;
1846 	}
1847 
1848 	/*
1849 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1850 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1851 	 * This prevents a race whereby a CPU incorrectly decides that
1852 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1853 	 * after dtrace_dynvar_clean() has completed.
1854 	 */
1855 	dtrace_sync();
1856 
1857 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1858 }
1859 
1860 /*
1861  * Depending on the value of the op parameter, this function looks-up,
1862  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1863  * allocation is requested, this function will return a pointer to a
1864  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1865  * variable can be allocated.  If NULL is returned, the appropriate counter
1866  * will be incremented.
1867  */
1868 static 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)1869 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1870     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1871     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1872 {
1873 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1874 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1875 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1876 	processorid_t me = CPU->cpu_id, cpu = me;
1877 	dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, me);
1878 	size_t bucket, ksize;
1879 	size_t chunksize = dstate->dtds_chunksize;
1880 	uintptr_t kdata, lock, nstate;
1881 	uint_t i;
1882 
1883 	ASSERT(nkeys != 0);
1884 
1885 	/*
1886 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1887 	 * algorithm.  For the by-value portions, we perform the algorithm in
1888 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1889 	 * bit, and seems to have only a minute effect on distribution.  For
1890 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1891 	 * over each referenced byte.  It's painful to do this, but it's much
1892 	 * better than pathological hash distribution.  The efficacy of the
1893 	 * hashing algorithm (and a comparison with other algorithms) may be
1894 	 * found by running the ::dtrace_dynstat MDB dcmd.
1895 	 */
1896 	for (i = 0; i < nkeys; i++) {
1897 		if (key[i].dttk_size == 0) {
1898 			uint64_t val = key[i].dttk_value;
1899 
1900 			hashval += (val >> 48) & 0xffff;
1901 			hashval += (hashval << 10);
1902 			hashval ^= (hashval >> 6);
1903 
1904 			hashval += (val >> 32) & 0xffff;
1905 			hashval += (hashval << 10);
1906 			hashval ^= (hashval >> 6);
1907 
1908 			hashval += (val >> 16) & 0xffff;
1909 			hashval += (hashval << 10);
1910 			hashval ^= (hashval >> 6);
1911 
1912 			hashval += val & 0xffff;
1913 			hashval += (hashval << 10);
1914 			hashval ^= (hashval >> 6);
1915 		} else {
1916 			/*
1917 			 * This is incredibly painful, but it beats the hell
1918 			 * out of the alternative.
1919 			 */
1920 			uint64_t j, size = key[i].dttk_size;
1921 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1922 
1923 			if (!dtrace_canload(base, size, mstate, vstate))
1924 				break;
1925 
1926 			for (j = 0; j < size; j++) {
1927 				hashval += dtrace_load8(base + j);
1928 				hashval += (hashval << 10);
1929 				hashval ^= (hashval >> 6);
1930 			}
1931 		}
1932 	}
1933 
1934 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1935 		return (NULL);
1936 
1937 	hashval += (hashval << 3);
1938 	hashval ^= (hashval >> 11);
1939 	hashval += (hashval << 15);
1940 
1941 	/*
1942 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1943 	 * comes out to be one of our two sentinel hash values.  If this
1944 	 * actually happens, we set the hashval to be a value known to be a
1945 	 * non-sentinel value.
1946 	 */
1947 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1948 		hashval = DTRACE_DYNHASH_VALID;
1949 
1950 	/*
1951 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1952 	 * important here, tricks can be pulled to reduce it.  (However, it's
1953 	 * critical that hash collisions be kept to an absolute minimum;
1954 	 * they're much more painful than a divide.)  It's better to have a
1955 	 * solution that generates few collisions and still keeps things
1956 	 * relatively simple.
1957 	 */
1958 	bucket = hashval % dstate->dtds_hashsize;
1959 
1960 	if (op == DTRACE_DYNVAR_DEALLOC) {
1961 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1962 
1963 		for (;;) {
1964 			while ((lock = *lockp) & 1)
1965 				continue;
1966 
1967 			if (dtrace_casptr((void *)(uintptr_t)lockp,
1968 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1969 				break;
1970 		}
1971 
1972 		dtrace_membar_producer();
1973 	}
1974 
1975 top:
1976 	prev = NULL;
1977 	lock = hash[bucket].dtdh_lock;
1978 
1979 	dtrace_membar_consumer();
1980 
1981 	start = hash[bucket].dtdh_chain;
1982 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1983 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1984 	    op != DTRACE_DYNVAR_DEALLOC));
1985 
1986 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1987 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1988 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1989 
1990 		if (dvar->dtdv_hashval != hashval) {
1991 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1992 				/*
1993 				 * We've reached the sink, and therefore the
1994 				 * end of the hash chain; we can kick out of
1995 				 * the loop knowing that we have seen a valid
1996 				 * snapshot of state.
1997 				 */
1998 				ASSERT(dvar->dtdv_next == NULL);
1999 				ASSERT(dvar == &dtrace_dynhash_sink);
2000 				break;
2001 			}
2002 
2003 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2004 				/*
2005 				 * We've gone off the rails:  somewhere along
2006 				 * the line, one of the members of this hash
2007 				 * chain was deleted.  Note that we could also
2008 				 * detect this by simply letting this loop run
2009 				 * to completion, as we would eventually hit
2010 				 * the end of the dirty list.  However, we
2011 				 * want to avoid running the length of the
2012 				 * dirty list unnecessarily (it might be quite
2013 				 * long), so we catch this as early as
2014 				 * possible by detecting the hash marker.  In
2015 				 * this case, we simply set dvar to NULL and
2016 				 * break; the conditional after the loop will
2017 				 * send us back to top.
2018 				 */
2019 				dvar = NULL;
2020 				break;
2021 			}
2022 
2023 			goto next;
2024 		}
2025 
2026 		if (dtuple->dtt_nkeys != nkeys)
2027 			goto next;
2028 
2029 		for (i = 0; i < nkeys; i++, dkey++) {
2030 			if (dkey->dttk_size != key[i].dttk_size)
2031 				goto next; /* size or type mismatch */
2032 
2033 			if (dkey->dttk_size != 0) {
2034 				if (dtrace_bcmp(
2035 				    (void *)(uintptr_t)key[i].dttk_value,
2036 				    (void *)(uintptr_t)dkey->dttk_value,
2037 				    dkey->dttk_size))
2038 					goto next;
2039 			} else {
2040 				if (dkey->dttk_value != key[i].dttk_value)
2041 					goto next;
2042 			}
2043 		}
2044 
2045 		if (op != DTRACE_DYNVAR_DEALLOC)
2046 			return (dvar);
2047 
2048 		ASSERT(dvar->dtdv_next == NULL ||
2049 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2050 
2051 		if (prev != NULL) {
2052 			ASSERT(hash[bucket].dtdh_chain != dvar);
2053 			ASSERT(start != dvar);
2054 			ASSERT(prev->dtdv_next == dvar);
2055 			prev->dtdv_next = dvar->dtdv_next;
2056 		} else {
2057 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2058 			    start, dvar->dtdv_next) != start) {
2059 				/*
2060 				 * We have failed to atomically swing the
2061 				 * hash table head pointer, presumably because
2062 				 * of a conflicting allocation on another CPU.
2063 				 * We need to reread the hash chain and try
2064 				 * again.
2065 				 */
2066 				goto top;
2067 			}
2068 		}
2069 
2070 		dtrace_membar_producer();
2071 
2072 		/*
2073 		 * Now set the hash value to indicate that it's free.
2074 		 */
2075 		ASSERT(hash[bucket].dtdh_chain != dvar);
2076 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2077 
2078 		dtrace_membar_producer();
2079 
2080 		/*
2081 		 * Set the next pointer to point at the dirty list, and
2082 		 * atomically swing the dirty pointer to the newly freed dvar.
2083 		 */
2084 		do {
2085 			next = dcpu->dtdsc_dirty;
2086 			dvar->dtdv_next = next;
2087 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2088 
2089 		/*
2090 		 * Finally, unlock this hash bucket.
2091 		 */
2092 		ASSERT(hash[bucket].dtdh_lock == lock);
2093 		ASSERT(lock & 1);
2094 		hash[bucket].dtdh_lock++;
2095 
2096 		return (NULL);
2097 next:
2098 		prev = dvar;
2099 		continue;
2100 	}
2101 
2102 	if (dvar == NULL) {
2103 		/*
2104 		 * If dvar is NULL, it is because we went off the rails:
2105 		 * one of the elements that we traversed in the hash chain
2106 		 * was deleted while we were traversing it.  In this case,
2107 		 * we assert that we aren't doing a dealloc (deallocs lock
2108 		 * the hash bucket to prevent themselves from racing with
2109 		 * one another), and retry the hash chain traversal.
2110 		 */
2111 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2112 		goto top;
2113 	}
2114 
2115 	if (op != DTRACE_DYNVAR_ALLOC) {
2116 		/*
2117 		 * If we are not to allocate a new variable, we want to
2118 		 * return NULL now.  Before we return, check that the value
2119 		 * of the lock word hasn't changed.  If it has, we may have
2120 		 * seen an inconsistent snapshot.
2121 		 */
2122 		if (op == DTRACE_DYNVAR_NOALLOC) {
2123 			if (hash[bucket].dtdh_lock != lock)
2124 				goto top;
2125 		} else {
2126 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2127 			ASSERT(hash[bucket].dtdh_lock == lock);
2128 			ASSERT(lock & 1);
2129 			hash[bucket].dtdh_lock++;
2130 		}
2131 
2132 		return (NULL);
2133 	}
2134 
2135 	/*
2136 	 * We need to allocate a new dynamic variable.  The size we need is the
2137 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2138 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2139 	 * the size of any referred-to data (dsize).  We then round the final
2140 	 * size up to the chunksize for allocation.
2141 	 */
2142 	for (ksize = 0, i = 0; i < nkeys; i++)
2143 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2144 
2145 	/*
2146 	 * This should be pretty much impossible, but could happen if, say,
2147 	 * strange DIF specified the tuple.  Ideally, this should be an
2148 	 * assertion and not an error condition -- but that requires that the
2149 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2150 	 * bullet-proof.  (That is, it must not be able to be fooled by
2151 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2152 	 * solving this would presumably not amount to solving the Halting
2153 	 * Problem -- but it still seems awfully hard.
2154 	 */
2155 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2156 	    ksize + dsize > chunksize) {
2157 		dcpu->dtdsc_drops++;
2158 		return (NULL);
2159 	}
2160 
2161 	nstate = DTRACE_DSTATE_EMPTY;
2162 
2163 	do {
2164 retry:
2165 		free = dcpu->dtdsc_free;
2166 
2167 		if (free == NULL) {
2168 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2169 			void *rval;
2170 
2171 			if (clean == NULL) {
2172 				/*
2173 				 * We're out of dynamic variable space on
2174 				 * this CPU.  Unless we have tried all CPUs,
2175 				 * we'll try to allocate from a different
2176 				 * CPU.
2177 				 */
2178 				switch (dstate->dtds_state) {
2179 				case DTRACE_DSTATE_CLEAN: {
2180 					void *sp = &dstate->dtds_state;
2181 
2182 					if (++cpu >= (int)NCPU)
2183 						cpu = 0;
2184 
2185 					if (dcpu->dtdsc_dirty != NULL &&
2186 					    nstate == DTRACE_DSTATE_EMPTY)
2187 						nstate = DTRACE_DSTATE_DIRTY;
2188 
2189 					if (dcpu->dtdsc_rinsing != NULL)
2190 						nstate = DTRACE_DSTATE_RINSING;
2191 
2192 					dcpu = zpercpu_get_cpu(dstate->dtds_percpu, cpu);
2193 
2194 					if (cpu != me)
2195 						goto retry;
2196 
2197 					(void) dtrace_cas32(sp,
2198 					    DTRACE_DSTATE_CLEAN, nstate);
2199 
2200 					/*
2201 					 * To increment the correct bean
2202 					 * counter, take another lap.
2203 					 */
2204 					goto retry;
2205 				}
2206 
2207 				case DTRACE_DSTATE_DIRTY:
2208 					dcpu->dtdsc_dirty_drops++;
2209 					break;
2210 
2211 				case DTRACE_DSTATE_RINSING:
2212 					dcpu->dtdsc_rinsing_drops++;
2213 					break;
2214 
2215 				case DTRACE_DSTATE_EMPTY:
2216 					dcpu->dtdsc_drops++;
2217 					break;
2218 				}
2219 
2220 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2221 				return (NULL);
2222 			}
2223 
2224 			/*
2225 			 * The clean list appears to be non-empty.  We want to
2226 			 * move the clean list to the free list; we start by
2227 			 * moving the clean pointer aside.
2228 			 */
2229 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2230 			    clean, NULL) != clean) {
2231 				/*
2232 				 * We are in one of two situations:
2233 				 *
2234 				 *  (a)	The clean list was switched to the
2235 				 *	free list by another CPU.
2236 				 *
2237 				 *  (b)	The clean list was added to by the
2238 				 *	cleansing cyclic.
2239 				 *
2240 				 * In either of these situations, we can
2241 				 * just reattempt the free list allocation.
2242 				 */
2243 				goto retry;
2244 			}
2245 
2246 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2247 
2248 			/*
2249 			 * Now we'll move the clean list to the free list.
2250 			 * It's impossible for this to fail:  the only way
2251 			 * the free list can be updated is through this
2252 			 * code path, and only one CPU can own the clean list.
2253 			 * Thus, it would only be possible for this to fail if
2254 			 * this code were racing with dtrace_dynvar_clean().
2255 			 * (That is, if dtrace_dynvar_clean() updated the clean
2256 			 * list, and we ended up racing to update the free
2257 			 * list.)  This race is prevented by the dtrace_sync()
2258 			 * in dtrace_dynvar_clean() -- which flushes the
2259 			 * owners of the clean lists out before resetting
2260 			 * the clean lists.
2261 			 */
2262 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2263 			ASSERT(rval == NULL);
2264 			goto retry;
2265 		}
2266 
2267 		dvar = free;
2268 		new_free = dvar->dtdv_next;
2269 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2270 
2271 	/*
2272 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2273 	 * tuple array and copy any referenced key data into the data space
2274 	 * following the tuple array.  As we do this, we relocate dttk_value
2275 	 * in the final tuple to point to the key data address in the chunk.
2276 	 */
2277 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2278 	dvar->dtdv_data = (void *)(kdata + ksize);
2279 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2280 
2281 	for (i = 0; i < nkeys; i++) {
2282 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2283 		size_t kesize = key[i].dttk_size;
2284 
2285 		if (kesize != 0) {
2286 			dtrace_bcopy(
2287 			    (const void *)(uintptr_t)key[i].dttk_value,
2288 			    (void *)kdata, kesize);
2289 			dkey->dttk_value = kdata;
2290 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2291 		} else {
2292 			dkey->dttk_value = key[i].dttk_value;
2293 		}
2294 
2295 		dkey->dttk_size = kesize;
2296 	}
2297 
2298 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2299 	dvar->dtdv_hashval = hashval;
2300 	dvar->dtdv_next = start;
2301 
2302 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2303 		return (dvar);
2304 
2305 	/*
2306 	 * The cas has failed.  Either another CPU is adding an element to
2307 	 * this hash chain, or another CPU is deleting an element from this
2308 	 * hash chain.  The simplest way to deal with both of these cases
2309 	 * (though not necessarily the most efficient) is to free our
2310 	 * allocated block and tail-call ourselves.  Note that the free is
2311 	 * to the dirty list and _not_ to the free list.  This is to prevent
2312 	 * races with allocators, above.
2313 	 */
2314 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2315 
2316 	dtrace_membar_producer();
2317 
2318 	do {
2319 		free = dcpu->dtdsc_dirty;
2320 		dvar->dtdv_next = free;
2321 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2322 
2323 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2324 }
2325 
2326 /*ARGSUSED*/
2327 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2328 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2329 {
2330 #pragma unused(arg) /* __APPLE__ */
2331 	if ((int64_t)nval < (int64_t)*oval)
2332 		*oval = nval;
2333 }
2334 
2335 /*ARGSUSED*/
2336 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2337 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2338 {
2339 #pragma unused(arg) /* __APPLE__ */
2340 	if ((int64_t)nval > (int64_t)*oval)
2341 		*oval = nval;
2342 }
2343 
2344 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2345 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2346 {
2347 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2348 	int64_t val = (int64_t)nval;
2349 
2350 	if (val < 0) {
2351 		for (i = 0; i < zero; i++) {
2352 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2353 				quanta[i] += incr;
2354 				return;
2355 			}
2356 		}
2357 	} else {
2358 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2359 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2360 				quanta[i - 1] += incr;
2361 				return;
2362 			}
2363 		}
2364 
2365 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2366 		return;
2367 	}
2368 
2369 	ASSERT(0);
2370 }
2371 
2372 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2373 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2374 {
2375 	uint64_t arg = *lquanta++;
2376 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2377 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2378 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2379 	int32_t val = (int32_t)nval, level;
2380 
2381 	ASSERT(step != 0);
2382 	ASSERT(levels != 0);
2383 
2384 	if (val < base) {
2385 		/*
2386 		 * This is an underflow.
2387 		 */
2388 		lquanta[0] += incr;
2389 		return;
2390 	}
2391 
2392 	level = (val - base) / step;
2393 
2394 	if (level < levels) {
2395 		lquanta[level + 1] += incr;
2396 		return;
2397 	}
2398 
2399 	/*
2400 	 * This is an overflow.
2401 	 */
2402 	lquanta[levels + 1] += incr;
2403 }
2404 
2405 static int
dtrace_aggregate_llquantize_bucket(int16_t factor,int16_t low,int16_t high,int16_t nsteps,int64_t value)2406 dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2407                                    int16_t nsteps, int64_t value)
2408 {
2409 	int64_t this = 1, last, next;
2410 	int base = 1, order;
2411 
2412 	for (order = 0; order < low; ++order)
2413 		this *= factor;
2414 
2415 	/*
2416 	 * If our value is less than our factor taken to the power of the
2417 	 * low order of magnitude, it goes into the zeroth bucket.
2418 	 */
2419 	if (value < this)
2420 		return 0;
2421 	else
2422 		last = this;
2423 
2424 	for (this *= factor; order <= high; ++order) {
2425 		int nbuckets = this > nsteps ? nsteps : this;
2426 
2427 		/*
2428 		 * We should not generally get log/linear quantizations
2429 		 * with a high magnitude that allows 64-bits to
2430 		 * overflow, but we nonetheless protect against this
2431 		 * by explicitly checking for overflow, and clamping
2432 		 * our value accordingly.
2433 		 */
2434 		next = this * factor;
2435 		if (next < this) {
2436 			value = this - 1;
2437 		}
2438 
2439 		/*
2440 		 * If our value lies within this order of magnitude,
2441 		 * determine its position by taking the offset within
2442 		 * the order of magnitude, dividing by the bucket
2443 		 * width, and adding to our (accumulated) base.
2444 		 */
2445 		if (value < this) {
2446 			return (base + (value - last) / (this / nbuckets));
2447 		}
2448 
2449 		base += nbuckets - (nbuckets / factor);
2450 		last = this;
2451 		this = next;
2452 	}
2453 
2454 	/*
2455 	 * Our value is greater than or equal to our factor taken to the
2456 	 * power of one plus the high magnitude -- return the top bucket.
2457 	 */
2458 	return base;
2459 }
2460 
2461 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2462 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2463 {
2464 	uint64_t arg    = *llquanta++;
2465 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2466 	uint16_t low    = DTRACE_LLQUANTIZE_LOW(arg);
2467 	uint16_t high   = DTRACE_LLQUANTIZE_HIGH(arg);
2468 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2469 
2470 	llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2471 }
2472 
2473 /*ARGSUSED*/
2474 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2475 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2476 {
2477 #pragma unused(arg) /* __APPLE__ */
2478 	data[0]++;
2479 	data[1] += nval;
2480 }
2481 
2482 /*ARGSUSED*/
2483 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2484 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2485 {
2486 #pragma unused(arg) /* __APPLE__ */
2487 	int64_t snval = (int64_t)nval;
2488 	uint64_t tmp[2];
2489 
2490 	data[0]++;
2491 	data[1] += nval;
2492 
2493 	/*
2494 	 * What we want to say here is:
2495 	 *
2496 	 * data[2] += nval * nval;
2497 	 *
2498 	 * But given that nval is 64-bit, we could easily overflow, so
2499 	 * we do this as 128-bit arithmetic.
2500 	 */
2501 	if (snval < 0)
2502 		snval = -snval;
2503 
2504 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2505 	dtrace_add_128(data + 2, tmp, data + 2);
2506 }
2507 
2508 /*ARGSUSED*/
2509 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2510 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2511 {
2512 #pragma unused(nval, arg) /* __APPLE__ */
2513 	*oval = *oval + 1;
2514 }
2515 
2516 /*ARGSUSED*/
2517 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2518 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2519 {
2520 #pragma unused(arg) /* __APPLE__ */
2521 	*oval += nval;
2522 }
2523 
2524 /*
2525  * Aggregate given the tuple in the principal data buffer, and the aggregating
2526  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2527  * buffer is specified as the buf parameter.  This routine does not return
2528  * failure; if there is no space in the aggregation buffer, the data will be
2529  * dropped, and a corresponding counter incremented.
2530  */
2531 __attribute__((noinline))
2532 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)2533 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2534     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2535 {
2536 #pragma unused(arg)
2537 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2538 	uint32_t i, ndx, size, fsize;
2539 	uint32_t align = sizeof (uint64_t) - 1;
2540 	dtrace_aggbuffer_t *agb;
2541 	dtrace_aggkey_t *key;
2542 	uint32_t hashval = 0, limit, isstr;
2543 	caddr_t tomax, data, kdata;
2544 	dtrace_actkind_t action;
2545 	dtrace_action_t *act;
2546 	uintptr_t offs;
2547 
2548 	if (buf == NULL)
2549 		return;
2550 
2551 	if (!agg->dtag_hasarg) {
2552 		/*
2553 		 * Currently, only quantize() and lquantize() take additional
2554 		 * arguments, and they have the same semantics:  an increment
2555 		 * value that defaults to 1 when not present.  If additional
2556 		 * aggregating actions take arguments, the setting of the
2557 		 * default argument value will presumably have to become more
2558 		 * sophisticated...
2559 		 */
2560 		arg = 1;
2561 	}
2562 
2563 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2564 	size = rec->dtrd_offset - agg->dtag_base;
2565 	fsize = size + rec->dtrd_size;
2566 
2567 	ASSERT(dbuf->dtb_tomax != NULL);
2568 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2569 
2570 	if ((tomax = buf->dtb_tomax) == NULL) {
2571 		dtrace_buffer_drop(buf);
2572 		return;
2573 	}
2574 
2575 	/*
2576 	 * The metastructure is always at the bottom of the buffer.
2577 	 */
2578 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2579 	    sizeof (dtrace_aggbuffer_t));
2580 
2581 	if (buf->dtb_offset == 0) {
2582 		/*
2583 		 * We just kludge up approximately 1/8th of the size to be
2584 		 * buckets.  If this guess ends up being routinely
2585 		 * off-the-mark, we may need to dynamically readjust this
2586 		 * based on past performance.
2587 		 */
2588 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2589 
2590 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2591 		    (uintptr_t)tomax || hashsize == 0) {
2592 			/*
2593 			 * We've been given a ludicrously small buffer;
2594 			 * increment our drop count and leave.
2595 			 */
2596 			dtrace_buffer_drop(buf);
2597 			return;
2598 		}
2599 
2600 		/*
2601 		 * And now, a pathetic attempt to try to get a an odd (or
2602 		 * perchance, a prime) hash size for better hash distribution.
2603 		 */
2604 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2605 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2606 
2607 		agb->dtagb_hashsize = hashsize;
2608 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2609 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2610 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2611 
2612 		for (i = 0; i < agb->dtagb_hashsize; i++)
2613 			agb->dtagb_hash[i] = NULL;
2614 	}
2615 
2616 	ASSERT(agg->dtag_first != NULL);
2617 	ASSERT(agg->dtag_first->dta_intuple);
2618 
2619 	/*
2620 	 * Calculate the hash value based on the key.  Note that we _don't_
2621 	 * include the aggid in the hashing (but we will store it as part of
2622 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2623 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2624 	 * gets good distribution in practice.  The efficacy of the hashing
2625 	 * algorithm (and a comparison with other algorithms) may be found by
2626 	 * running the ::dtrace_aggstat MDB dcmd.
2627 	 */
2628 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2629 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2630 		limit = i + act->dta_rec.dtrd_size;
2631 		ASSERT(limit <= size);
2632 		isstr = DTRACEACT_ISSTRING(act);
2633 
2634 		for (; i < limit; i++) {
2635 			hashval += data[i];
2636 			hashval += (hashval << 10);
2637 			hashval ^= (hashval >> 6);
2638 
2639 			if (isstr && data[i] == '\0')
2640 				break;
2641 		}
2642 	}
2643 
2644 	hashval += (hashval << 3);
2645 	hashval ^= (hashval >> 11);
2646 	hashval += (hashval << 15);
2647 
2648 	/*
2649 	 * Yes, the divide here is expensive -- but it's generally the least
2650 	 * of the performance issues given the amount of data that we iterate
2651 	 * over to compute hash values, compare data, etc.
2652 	 */
2653 	ndx = hashval % agb->dtagb_hashsize;
2654 
2655 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2656 		ASSERT((caddr_t)key >= tomax);
2657 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2658 
2659 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2660 			continue;
2661 
2662 		kdata = key->dtak_data;
2663 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2664 
2665 		for (act = agg->dtag_first; act->dta_intuple;
2666 		    act = act->dta_next) {
2667 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2668 			limit = i + act->dta_rec.dtrd_size;
2669 			ASSERT(limit <= size);
2670 			isstr = DTRACEACT_ISSTRING(act);
2671 
2672 			for (; i < limit; i++) {
2673 				if (kdata[i] != data[i])
2674 					goto next;
2675 
2676 				if (isstr && data[i] == '\0')
2677 					break;
2678 			}
2679 		}
2680 
2681 		if (action != key->dtak_action) {
2682 			/*
2683 			 * We are aggregating on the same value in the same
2684 			 * aggregation with two different aggregating actions.
2685 			 * (This should have been picked up in the compiler,
2686 			 * so we may be dealing with errant or devious DIF.)
2687 			 * This is an error condition; we indicate as much,
2688 			 * and return.
2689 			 */
2690 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2691 			return;
2692 		}
2693 
2694 		/*
2695 		 * This is a hit:  we need to apply the aggregator to
2696 		 * the value at this key.
2697 		 */
2698 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2699 		return;
2700 next:
2701 		continue;
2702 	}
2703 
2704 	/*
2705 	 * We didn't find it.  We need to allocate some zero-filled space,
2706 	 * link it into the hash table appropriately, and apply the aggregator
2707 	 * to the (zero-filled) value.
2708 	 */
2709 	offs = buf->dtb_offset;
2710 	while (offs & (align - 1))
2711 		offs += sizeof (uint32_t);
2712 
2713 	/*
2714 	 * If we don't have enough room to both allocate a new key _and_
2715 	 * its associated data, increment the drop count and return.
2716 	 */
2717 	if ((uintptr_t)tomax + offs + fsize >
2718 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2719 		dtrace_buffer_drop(buf);
2720 		return;
2721 	}
2722 
2723 	/*CONSTCOND*/
2724 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2725 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2726 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2727 
2728 	key->dtak_data = kdata = tomax + offs;
2729 	buf->dtb_offset = offs + fsize;
2730 
2731 	/*
2732 	 * Now copy the data across.
2733 	 */
2734 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2735 
2736 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2737 		kdata[i] = data[i];
2738 
2739 	/*
2740 	 * Because strings are not zeroed out by default, we need to iterate
2741 	 * looking for actions that store strings, and we need to explicitly
2742 	 * pad these strings out with zeroes.
2743 	 */
2744 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2745 		int nul;
2746 
2747 		if (!DTRACEACT_ISSTRING(act))
2748 			continue;
2749 
2750 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2751 		limit = i + act->dta_rec.dtrd_size;
2752 		ASSERT(limit <= size);
2753 
2754 		for (nul = 0; i < limit; i++) {
2755 			if (nul) {
2756 				kdata[i] = '\0';
2757 				continue;
2758 			}
2759 
2760 			if (data[i] != '\0')
2761 				continue;
2762 
2763 			nul = 1;
2764 		}
2765 	}
2766 
2767 	for (i = size; i < fsize; i++)
2768 		kdata[i] = 0;
2769 
2770 	key->dtak_hashval = hashval;
2771 	key->dtak_size = size;
2772 	key->dtak_action = action;
2773 	key->dtak_next = agb->dtagb_hash[ndx];
2774 	agb->dtagb_hash[ndx] = key;
2775 
2776 	/*
2777 	 * Finally, apply the aggregator.
2778 	 */
2779 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2780 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2781 }
2782 
2783 /*
2784  * Given consumer state, this routine finds a speculation in the INACTIVE
2785  * state and transitions it into the ACTIVE state.  If there is no speculation
2786  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2787  * incremented -- it is up to the caller to take appropriate action.
2788  */
2789 static int
dtrace_speculation(dtrace_state_t * state)2790 dtrace_speculation(dtrace_state_t *state)
2791 {
2792 	int i = 0;
2793 	dtrace_speculation_state_t current;
2794 	uint32_t *stat = &state->dts_speculations_unavail, count;
2795 
2796 	while (i < state->dts_nspeculations) {
2797 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2798 
2799 		current = spec->dtsp_state;
2800 
2801 		if (current != DTRACESPEC_INACTIVE) {
2802 			if (current == DTRACESPEC_COMMITTINGMANY ||
2803 			    current == DTRACESPEC_COMMITTING ||
2804 			    current == DTRACESPEC_DISCARDING)
2805 				stat = &state->dts_speculations_busy;
2806 			i++;
2807 			continue;
2808 		}
2809 
2810 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2811 		    current, DTRACESPEC_ACTIVE) == current)
2812 			return (i + 1);
2813 	}
2814 
2815 	/*
2816 	 * We couldn't find a speculation.  If we found as much as a single
2817 	 * busy speculation buffer, we'll attribute this failure as "busy"
2818 	 * instead of "unavail".
2819 	 */
2820 	do {
2821 		count = *stat;
2822 	} while (dtrace_cas32(stat, count, count + 1) != count);
2823 
2824 	return (0);
2825 }
2826 
2827 /*
2828  * This routine commits an active speculation.  If the specified speculation
2829  * is not in a valid state to perform a commit(), this routine will silently do
2830  * nothing.  The state of the specified speculation is transitioned according
2831  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2832  */
2833 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2834 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2835     dtrace_specid_t which)
2836 {
2837 	dtrace_speculation_t *spec;
2838 	dtrace_buffer_t *src, *dest;
2839 	uintptr_t daddr, saddr, dlimit, slimit;
2840 	dtrace_speculation_state_t current,  new = DTRACESPEC_INACTIVE;
2841 	intptr_t offs;
2842 	uint64_t timestamp;
2843 
2844 	if (which == 0)
2845 		return;
2846 
2847 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
2848 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2849 		return;
2850 	}
2851 
2852 	spec = &state->dts_speculations[which - 1];
2853 	src = &spec->dtsp_buffer[cpu];
2854 	dest = &state->dts_buffer[cpu];
2855 
2856 	do {
2857 		current = spec->dtsp_state;
2858 
2859 		if (current == DTRACESPEC_COMMITTINGMANY)
2860 			break;
2861 
2862 		switch (current) {
2863 		case DTRACESPEC_INACTIVE:
2864 		case DTRACESPEC_DISCARDING:
2865 			return;
2866 
2867 		case DTRACESPEC_COMMITTING:
2868 			/*
2869 			 * This is only possible if we are (a) commit()'ing
2870 			 * without having done a prior speculate() on this CPU
2871 			 * and (b) racing with another commit() on a different
2872 			 * CPU.  There's nothing to do -- we just assert that
2873 			 * our offset is 0.
2874 			 */
2875 			ASSERT(src->dtb_offset == 0);
2876 			return;
2877 
2878 		case DTRACESPEC_ACTIVE:
2879 			new = DTRACESPEC_COMMITTING;
2880 			break;
2881 
2882 		case DTRACESPEC_ACTIVEONE:
2883 			/*
2884 			 * This speculation is active on one CPU.  If our
2885 			 * buffer offset is non-zero, we know that the one CPU
2886 			 * must be us.  Otherwise, we are committing on a
2887 			 * different CPU from the speculate(), and we must
2888 			 * rely on being asynchronously cleaned.
2889 			 */
2890 			if (src->dtb_offset != 0) {
2891 				new = DTRACESPEC_COMMITTING;
2892 				break;
2893 			}
2894 			OS_FALLTHROUGH;
2895 
2896 		case DTRACESPEC_ACTIVEMANY:
2897 			new = DTRACESPEC_COMMITTINGMANY;
2898 			break;
2899 
2900 		default:
2901 			ASSERT(0);
2902 		}
2903 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2904 	    current, new) != current);
2905 
2906 	/*
2907 	 * We have set the state to indicate that we are committing this
2908 	 * speculation.  Now reserve the necessary space in the destination
2909 	 * buffer.
2910 	 */
2911 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2912 	    sizeof (uint64_t), state, NULL)) < 0) {
2913 		dtrace_buffer_drop(dest);
2914 		goto out;
2915 	}
2916 
2917 	/*
2918 	 * We have sufficient space to copy the speculative buffer into the
2919 	 * primary buffer.  First, modify the speculative buffer, filling
2920 	 * in the timestamp of all entries with the current time.  The data
2921 	 * must have the commit() time rather than the time it was traced,
2922 	 * so that all entries in the primary buffer are in timestamp order.
2923 	 */
2924 	timestamp = dtrace_gethrtime();
2925 	saddr = (uintptr_t)src->dtb_tomax;
2926 	slimit = saddr + src->dtb_offset;
2927 	while (saddr < slimit) {
2928 		size_t size;
2929 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2930 
2931 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2932 			saddr += sizeof (dtrace_epid_t);
2933 			continue;
2934 		}
2935 
2936 		ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2937 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2938 
2939 		ASSERT(saddr + size <= slimit);
2940 		ASSERT(size >= sizeof(dtrace_rechdr_t));
2941 		ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2942 
2943 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2944 
2945 		saddr += size;
2946 	}
2947 
2948 	/*
2949 	 * Copy the buffer across.  (Note that this is a
2950 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2951 	 * a serious performance issue, a high-performance DTrace-specific
2952 	 * bcopy() should obviously be invented.)
2953 	 */
2954 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2955 	dlimit = daddr + src->dtb_offset;
2956 	saddr = (uintptr_t)src->dtb_tomax;
2957 
2958 	/*
2959 	 * First, the aligned portion.
2960 	 */
2961 	while (dlimit - daddr >= sizeof (uint64_t)) {
2962 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2963 
2964 		daddr += sizeof (uint64_t);
2965 		saddr += sizeof (uint64_t);
2966 	}
2967 
2968 	/*
2969 	 * Now any left-over bit...
2970 	 */
2971 	while (dlimit - daddr)
2972 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2973 
2974 	/*
2975 	 * Finally, commit the reserved space in the destination buffer.
2976 	 */
2977 	dest->dtb_offset = offs + src->dtb_offset;
2978 
2979 out:
2980 	/*
2981 	 * If we're lucky enough to be the only active CPU on this speculation
2982 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2983 	 */
2984 	if (current == DTRACESPEC_ACTIVE ||
2985 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2986 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2987 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2988 #pragma unused(rval) /* __APPLE__ */
2989 
2990 		ASSERT(rval == DTRACESPEC_COMMITTING);
2991 	}
2992 
2993 	src->dtb_offset = 0;
2994 	src->dtb_xamot_drops += src->dtb_drops;
2995 	src->dtb_drops = 0;
2996 }
2997 
2998 /*
2999  * This routine discards an active speculation.  If the specified speculation
3000  * is not in a valid state to perform a discard(), this routine will silently
3001  * do nothing.  The state of the specified speculation is transitioned
3002  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3003  */
3004 __attribute__((noinline))
3005 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)3006 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3007     dtrace_specid_t which)
3008 {
3009 	dtrace_speculation_t *spec;
3010 	dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
3011 	dtrace_buffer_t *buf;
3012 
3013 	if (which == 0)
3014 		return;
3015 
3016 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
3017 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3018 		return;
3019 	}
3020 
3021 	spec = &state->dts_speculations[which - 1];
3022 	buf = &spec->dtsp_buffer[cpu];
3023 
3024 	do {
3025 		current = spec->dtsp_state;
3026 
3027 		switch (current) {
3028 		case DTRACESPEC_INACTIVE:
3029 		case DTRACESPEC_COMMITTINGMANY:
3030 		case DTRACESPEC_COMMITTING:
3031 		case DTRACESPEC_DISCARDING:
3032 			return;
3033 
3034 		case DTRACESPEC_ACTIVE:
3035 		case DTRACESPEC_ACTIVEMANY:
3036 			new = DTRACESPEC_DISCARDING;
3037 			break;
3038 
3039 		case DTRACESPEC_ACTIVEONE:
3040 			if (buf->dtb_offset != 0) {
3041 				new = DTRACESPEC_INACTIVE;
3042 			} else {
3043 				new = DTRACESPEC_DISCARDING;
3044 			}
3045 			break;
3046 
3047 		default:
3048 			ASSERT(0);
3049 		}
3050 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3051 	    current, new) != current);
3052 
3053 	buf->dtb_offset = 0;
3054 	buf->dtb_drops = 0;
3055 }
3056 
3057 /*
3058  * Note:  not called from probe context.  This function is called
3059  * asynchronously from cross call context to clean any speculations that are
3060  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3061  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3062  * speculation.
3063  */
3064 static void
dtrace_speculation_clean_here(dtrace_state_t * state)3065 dtrace_speculation_clean_here(dtrace_state_t *state)
3066 {
3067 	dtrace_icookie_t cookie;
3068 	processorid_t cpu = CPU->cpu_id;
3069 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3070 	dtrace_specid_t i;
3071 
3072 	cookie = dtrace_interrupt_disable();
3073 
3074 	if (dest->dtb_tomax == NULL) {
3075 		dtrace_interrupt_enable(cookie);
3076 		return;
3077 	}
3078 
3079 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3080 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3081 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3082 
3083 		if (src->dtb_tomax == NULL)
3084 			continue;
3085 
3086 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3087 			src->dtb_offset = 0;
3088 			continue;
3089 		}
3090 
3091 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3092 			continue;
3093 
3094 		if (src->dtb_offset == 0)
3095 			continue;
3096 
3097 		dtrace_speculation_commit(state, cpu, i + 1);
3098 	}
3099 
3100 	dtrace_interrupt_enable(cookie);
3101 }
3102 
3103 /*
3104  * Note:  not called from probe context.  This function is called
3105  * asynchronously (and at a regular interval) to clean any speculations that
3106  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3107  * is work to be done, it cross calls all CPUs to perform that work;
3108  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3109  * INACTIVE state until they have been cleaned by all CPUs.
3110  */
3111 static void
dtrace_speculation_clean(dtrace_state_t * state)3112 dtrace_speculation_clean(dtrace_state_t *state)
3113 {
3114 	int work = 0;
3115 	uint32_t rv;
3116 	dtrace_specid_t i;
3117 
3118 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3119 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3120 
3121 		ASSERT(!spec->dtsp_cleaning);
3122 
3123 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3124 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3125 			continue;
3126 
3127 		work++;
3128 		spec->dtsp_cleaning = 1;
3129 	}
3130 
3131 	if (!work)
3132 		return;
3133 
3134 	dtrace_xcall(DTRACE_CPUALL,
3135 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3136 
3137 	/*
3138 	 * We now know that all CPUs have committed or discarded their
3139 	 * speculation buffers, as appropriate.  We can now set the state
3140 	 * to inactive.
3141 	 */
3142 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3143 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3144 		dtrace_speculation_state_t current, new;
3145 
3146 		if (!spec->dtsp_cleaning)
3147 			continue;
3148 
3149 		current = spec->dtsp_state;
3150 		ASSERT(current == DTRACESPEC_DISCARDING ||
3151 		    current == DTRACESPEC_COMMITTINGMANY);
3152 
3153 		new = DTRACESPEC_INACTIVE;
3154 
3155 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3156 		ASSERT(rv == current);
3157 		spec->dtsp_cleaning = 0;
3158 	}
3159 }
3160 
3161 /*
3162  * Called as part of a speculate() to get the speculative buffer associated
3163  * with a given speculation.  Returns NULL if the specified speculation is not
3164  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3165  * the active CPU is not the specified CPU -- the speculation will be
3166  * atomically transitioned into the ACTIVEMANY state.
3167  */
3168 __attribute__((noinline))
3169 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3170 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3171     dtrace_specid_t which)
3172 {
3173 	dtrace_speculation_t *spec;
3174 	dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
3175 	dtrace_buffer_t *buf;
3176 
3177 	if (which == 0)
3178 		return (NULL);
3179 
3180 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
3181 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3182 		return (NULL);
3183 	}
3184 
3185 	spec = &state->dts_speculations[which - 1];
3186 	buf = &spec->dtsp_buffer[cpuid];
3187 
3188 	do {
3189 		current = spec->dtsp_state;
3190 
3191 		switch (current) {
3192 		case DTRACESPEC_INACTIVE:
3193 		case DTRACESPEC_COMMITTINGMANY:
3194 		case DTRACESPEC_DISCARDING:
3195 			return (NULL);
3196 
3197 		case DTRACESPEC_COMMITTING:
3198 			ASSERT(buf->dtb_offset == 0);
3199 			return (NULL);
3200 
3201 		case DTRACESPEC_ACTIVEONE:
3202 			/*
3203 			 * This speculation is currently active on one CPU.
3204 			 * Check the offset in the buffer; if it's non-zero,
3205 			 * that CPU must be us (and we leave the state alone).
3206 			 * If it's zero, assume that we're starting on a new
3207 			 * CPU -- and change the state to indicate that the
3208 			 * speculation is active on more than one CPU.
3209 			 */
3210 			if (buf->dtb_offset != 0)
3211 				return (buf);
3212 
3213 			new = DTRACESPEC_ACTIVEMANY;
3214 			break;
3215 
3216 		case DTRACESPEC_ACTIVEMANY:
3217 			return (buf);
3218 
3219 		case DTRACESPEC_ACTIVE:
3220 			new = DTRACESPEC_ACTIVEONE;
3221 			break;
3222 
3223 		default:
3224 			ASSERT(0);
3225 		}
3226 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3227 	    current, new) != current);
3228 
3229 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3230 	return (buf);
3231 }
3232 
3233 /*
3234  * Return a string.  In the event that the user lacks the privilege to access
3235  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3236  * don't fail access checking.
3237  *
3238  * dtrace_dif_variable() uses this routine as a helper for various
3239  * builtin values such as 'execname' and 'probefunc.'
3240  */
3241 static
3242 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3243 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3244     dtrace_mstate_t *mstate)
3245 {
3246 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3247 	uintptr_t ret;
3248 	size_t strsz;
3249 
3250 	/*
3251 	 * The easy case: this probe is allowed to read all of memory, so
3252 	 * we can just return this as a vanilla pointer.
3253 	 */
3254 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3255 		return (addr);
3256 
3257 	/*
3258 	 * This is the tougher case: we copy the string in question from
3259 	 * kernel memory into scratch memory and return it that way: this
3260 	 * ensures that we won't trip up when access checking tests the
3261 	 * BYREF return value.
3262 	 */
3263 	strsz = dtrace_strlen((char *)addr, size) + 1;
3264 
3265 	if (mstate->dtms_scratch_ptr + strsz >
3266 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3267 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3268 		return (0);
3269 	}
3270 
3271 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3272 	    strsz);
3273 	ret = mstate->dtms_scratch_ptr;
3274 	mstate->dtms_scratch_ptr += strsz;
3275 	return (ret);
3276 }
3277 
3278 /*
3279  * This function implements the DIF emulator's variable lookups.  The emulator
3280  * passes a reserved variable identifier and optional built-in array index.
3281  */
3282 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3283 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3284     uint64_t ndx)
3285 {
3286 	/*
3287 	 * If we're accessing one of the uncached arguments, we'll turn this
3288 	 * into a reference in the args array.
3289 	 */
3290 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3291 		ndx = v - DIF_VAR_ARG0;
3292 		v = DIF_VAR_ARGS;
3293 	}
3294 
3295 	switch (v) {
3296 	case DIF_VAR_ARGS:
3297 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3298 		if (ndx >= sizeof (mstate->dtms_arg) /
3299 		    sizeof (mstate->dtms_arg[0])) {
3300 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3301 			dtrace_vstate_t *vstate = &state->dts_vstate;
3302 			dtrace_provider_t *pv;
3303 			uint64_t val;
3304 
3305 			pv = mstate->dtms_probe->dtpr_provider;
3306 			if (pv->dtpv_pops.dtps_getargval != NULL)
3307 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3308 				    mstate->dtms_probe->dtpr_id,
3309 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3310 			/* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
3311 			else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
3312 			        return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
3313 			}
3314 
3315 			else
3316 				val = dtrace_getarg(ndx, aframes, mstate, vstate);
3317 
3318 			/*
3319 			 * This is regrettably required to keep the compiler
3320 			 * from tail-optimizing the call to dtrace_getarg().
3321 			 * The condition always evaluates to true, but the
3322 			 * compiler has no way of figuring that out a priori.
3323 			 * (None of this would be necessary if the compiler
3324 			 * could be relied upon to _always_ tail-optimize
3325 			 * the call to dtrace_getarg() -- but it can't.)
3326 			 */
3327 			if (mstate->dtms_probe != NULL)
3328 				return (val);
3329 
3330 			ASSERT(0);
3331 		}
3332 
3333 		return (mstate->dtms_arg[ndx]);
3334 
3335 	case DIF_VAR_UREGS: {
3336 		thread_t thread;
3337 
3338 		if (!dtrace_priv_proc(state))
3339 			return (0);
3340 
3341 		if ((thread = current_thread()) == NULL) {
3342 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3343 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3344 			return (0);
3345 		}
3346 
3347 		return (dtrace_getreg(find_user_regs(thread), ndx));
3348 	}
3349 
3350 	case DIF_VAR_VMREGS: {
3351 		uint64_t rval;
3352 
3353 		if (!dtrace_priv_kernel(state))
3354 			return (0);
3355 
3356 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3357 
3358 		rval = dtrace_getvmreg(ndx);
3359 
3360 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3361 
3362 		return (rval);
3363 	}
3364 
3365 	case DIF_VAR_CURTHREAD:
3366 		if (!dtrace_priv_kernel(state))
3367 			return (0);
3368 
3369 		return ((uint64_t)(uintptr_t)current_thread());
3370 
3371 	case DIF_VAR_TIMESTAMP:
3372 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3373 			mstate->dtms_timestamp = dtrace_gethrtime();
3374 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3375 		}
3376 		return (mstate->dtms_timestamp);
3377 
3378 	case DIF_VAR_VTIMESTAMP:
3379 		ASSERT(dtrace_vtime_references != 0);
3380 		return (dtrace_get_thread_vtime(current_thread()));
3381 
3382 	case DIF_VAR_WALLTIMESTAMP:
3383 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3384 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3385 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3386 		}
3387 		return (mstate->dtms_walltimestamp);
3388 
3389 	case DIF_VAR_MACHTIMESTAMP:
3390 		if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3391 			mstate->dtms_machtimestamp = mach_absolute_time();
3392 			mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3393 		}
3394 		return (mstate->dtms_machtimestamp);
3395 
3396 	case DIF_VAR_MACHCTIMESTAMP:
3397 		if (!(mstate->dtms_present & DTRACE_MSTATE_MACHCTIMESTAMP)) {
3398 			mstate->dtms_machctimestamp = mach_continuous_time();
3399 			mstate->dtms_present |= DTRACE_MSTATE_MACHCTIMESTAMP;
3400 		}
3401 		return (mstate->dtms_machctimestamp);
3402 
3403 
3404 	case DIF_VAR_CPU:
3405 		return ((uint64_t) dtrace_get_thread_last_cpu_id(current_thread()));
3406 
3407 	case DIF_VAR_IPL:
3408 		if (!dtrace_priv_kernel(state))
3409 			return (0);
3410 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3411 			mstate->dtms_ipl = dtrace_getipl();
3412 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3413 		}
3414 		return (mstate->dtms_ipl);
3415 
3416 	case DIF_VAR_EPID:
3417 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3418 		return (mstate->dtms_epid);
3419 
3420 	case DIF_VAR_ID:
3421 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3422 		return (mstate->dtms_probe->dtpr_id);
3423 
3424 	case DIF_VAR_STACKDEPTH:
3425 		if (!dtrace_priv_kernel(state))
3426 			return (0);
3427 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3428 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3429 
3430 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3431 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3432 		}
3433 		return (mstate->dtms_stackdepth);
3434 
3435 	case DIF_VAR_USTACKDEPTH:
3436 		if (!dtrace_priv_proc(state))
3437 			return (0);
3438 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3439 			/*
3440 			 * See comment in DIF_VAR_PID.
3441 			 */
3442 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3443 			    CPU_ON_INTR(CPU)) {
3444 				mstate->dtms_ustackdepth = 0;
3445 			} else {
3446 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3447 				mstate->dtms_ustackdepth =
3448 				    dtrace_getustackdepth();
3449 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3450 			}
3451 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3452 		}
3453 		return (mstate->dtms_ustackdepth);
3454 
3455 	case DIF_VAR_CALLER:
3456 		if (!dtrace_priv_kernel(state))
3457 			return (0);
3458 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3459 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3460 
3461 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3462 				/*
3463 				 * If this is an unanchored probe, we are
3464 				 * required to go through the slow path:
3465 				 * dtrace_caller() only guarantees correct
3466 				 * results for anchored probes.
3467 				 */
3468 				pc_t caller[2];
3469 
3470 				dtrace_getpcstack(caller, 2, aframes,
3471 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3472 				mstate->dtms_caller = caller[1];
3473 			} else if ((mstate->dtms_caller =
3474 				dtrace_caller(aframes)) == (uintptr_t)-1) {
3475 				/*
3476 				 * We have failed to do this the quick way;
3477 				 * we must resort to the slower approach of
3478 				 * calling dtrace_getpcstack().
3479 				 */
3480 				pc_t caller;
3481 
3482 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3483 				mstate->dtms_caller = caller;
3484 			}
3485 
3486 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3487 		}
3488 		return (mstate->dtms_caller);
3489 
3490 	case DIF_VAR_UCALLER:
3491 		if (!dtrace_priv_proc(state))
3492 			return (0);
3493 
3494 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3495 			uint64_t ustack[3];
3496 
3497 			/*
3498 			 * dtrace_getupcstack() fills in the first uint64_t
3499 			 * with the current PID.  The second uint64_t will
3500 			 * be the program counter at user-level.  The third
3501 			 * uint64_t will contain the caller, which is what
3502 			 * we're after.
3503 			 */
3504 			ustack[2] = 0;
3505 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3506 			dtrace_getupcstack(ustack, 3);
3507 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3508 			mstate->dtms_ucaller = ustack[2];
3509 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3510 		}
3511 
3512 		return (mstate->dtms_ucaller);
3513 
3514 	case DIF_VAR_PROBEPROV:
3515 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3516 		return (dtrace_dif_varstr(
3517 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3518 		    state, mstate));
3519 
3520 	case DIF_VAR_PROBEMOD:
3521 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3522 		return (dtrace_dif_varstr(
3523 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3524 		    state, mstate));
3525 
3526 	case DIF_VAR_PROBEFUNC:
3527 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3528 		return (dtrace_dif_varstr(
3529 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3530 		    state, mstate));
3531 
3532 	case DIF_VAR_PROBENAME:
3533 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3534 		return (dtrace_dif_varstr(
3535 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3536 		    state, mstate));
3537 
3538 	case DIF_VAR_PID:
3539 		if (!dtrace_priv_proc_relaxed(state))
3540 			return (0);
3541 
3542 		/*
3543 		 * Note that we are assuming that an unanchored probe is
3544 		 * always due to a high-level interrupt.  (And we're assuming
3545 		 * that there is only a single high level interrupt.)
3546 		 */
3547 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3548 			/* Anchored probe that fires while on an interrupt accrues to process 0 */
3549 			return 0;
3550 
3551 		return ((uint64_t)dtrace_proc_selfpid());
3552 
3553 	case DIF_VAR_PPID:
3554 		if (!dtrace_priv_proc_relaxed(state))
3555 			return (0);
3556 
3557 		/*
3558 		 * See comment in DIF_VAR_PID.
3559 		 */
3560 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3561 			return (0);
3562 
3563 		return ((uint64_t)dtrace_proc_selfppid());
3564 
3565 	case DIF_VAR_TID:
3566 		/* We do not need to check for null current_thread() */
3567 		return thread_tid(current_thread()); /* globally unique */
3568 
3569 	case DIF_VAR_PTHREAD_SELF:
3570 		if (!dtrace_priv_proc(state))
3571 			return (0);
3572 
3573 		/* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3574 		return 0;
3575 
3576 	case DIF_VAR_DISPATCHQADDR:
3577 		if (!dtrace_priv_proc(state))
3578 			return (0);
3579 
3580 		/* We do not need to check for null current_thread() */
3581 		return thread_dispatchqaddr(current_thread());
3582 
3583 	case DIF_VAR_EXECNAME:
3584 	{
3585 		char *xname = (char *)mstate->dtms_scratch_ptr;
3586 		char *pname = proc_best_name(curproc);
3587 		size_t scratch_size = sizeof(proc_name_t);
3588 
3589 		/* The scratch allocation's lifetime is that of the clause. */
3590 		if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3591 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3592 			return 0;
3593 		}
3594 
3595 		if (!dtrace_priv_proc_relaxed(state))
3596 			return (0);
3597 
3598 		mstate->dtms_scratch_ptr += scratch_size;
3599 		strlcpy(xname, pname, scratch_size);
3600 
3601 		return ((uint64_t)(uintptr_t)xname);
3602 	}
3603 
3604 
3605 	case DIF_VAR_ZONENAME:
3606 	{
3607 		/* scratch_size is equal to length('global') + 1 for the null-terminator. */
3608 		char *zname = (char *)mstate->dtms_scratch_ptr;
3609 		size_t scratch_size = 6 + 1;
3610 
3611 		if (!dtrace_priv_proc(state))
3612 			return (0);
3613 
3614 		/* The scratch allocation's lifetime is that of the clause. */
3615 		if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3616 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3617 			return 0;
3618 		}
3619 
3620 		mstate->dtms_scratch_ptr += scratch_size;
3621 
3622 		/* The kernel does not provide zonename, it will always return 'global'. */
3623 		strlcpy(zname, "global", scratch_size);
3624 
3625 		return ((uint64_t)(uintptr_t)zname);
3626 	}
3627 
3628 #if MONOTONIC
3629 	case DIF_VAR_CPUINSTRS:
3630 		return mt_cur_cpu_instrs();
3631 
3632 	case DIF_VAR_CPUCYCLES:
3633 		return mt_cur_cpu_cycles();
3634 
3635 	case DIF_VAR_VINSTRS:
3636 		return mt_cur_thread_instrs();
3637 
3638 	case DIF_VAR_VCYCLES:
3639 		return mt_cur_thread_cycles();
3640 #else /* MONOTONIC */
3641 	case DIF_VAR_CPUINSTRS: /* FALLTHROUGH */
3642 	case DIF_VAR_CPUCYCLES: /* FALLTHROUGH */
3643 	case DIF_VAR_VINSTRS: /* FALLTHROUGH */
3644 	case DIF_VAR_VCYCLES: /* FALLTHROUGH */
3645 		return 0;
3646 #endif /* !MONOTONIC */
3647 
3648 	case DIF_VAR_UID:
3649 		if (!dtrace_priv_proc_relaxed(state))
3650 			return (0);
3651 
3652 		/*
3653 		 * See comment in DIF_VAR_PID.
3654 		 */
3655 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3656 			return (0);
3657 
3658 		return ((uint64_t) dtrace_proc_selfruid());
3659 
3660 	case DIF_VAR_GID:
3661 		if (!dtrace_priv_proc(state))
3662 			return (0);
3663 
3664 		/*
3665 		 * See comment in DIF_VAR_PID.
3666 		 */
3667 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3668 			return (0);
3669 
3670 		if (dtrace_CRED() != NULL)
3671 			/* Credential does not require lazy initialization. */
3672 			return ((uint64_t)kauth_getgid());
3673 		else {
3674 			/* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3675 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3676 			return -1ULL;
3677 		}
3678 
3679 	case DIF_VAR_ERRNO: {
3680 		uthread_t uthread = current_uthread();
3681 		if (!dtrace_priv_proc(state))
3682 			return (0);
3683 
3684 		/*
3685 		 * See comment in DIF_VAR_PID.
3686 		 */
3687 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3688 			return (0);
3689 
3690 		if (uthread)
3691 			return (uint64_t)uthread->t_dtrace_errno;
3692 		else {
3693 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3694 			return -1ULL;
3695 		}
3696 	}
3697 
3698 	default:
3699 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3700 		return (0);
3701 	}
3702 }
3703 
3704 typedef enum dtrace_json_state {
3705 	DTRACE_JSON_REST = 1,
3706 	DTRACE_JSON_OBJECT,
3707 	DTRACE_JSON_STRING,
3708 	DTRACE_JSON_STRING_ESCAPE,
3709 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3710 	DTRACE_JSON_COLON,
3711 	DTRACE_JSON_COMMA,
3712 	DTRACE_JSON_VALUE,
3713 	DTRACE_JSON_IDENTIFIER,
3714 	DTRACE_JSON_NUMBER,
3715 	DTRACE_JSON_NUMBER_FRAC,
3716 	DTRACE_JSON_NUMBER_EXP,
3717 	DTRACE_JSON_COLLECT_OBJECT
3718 } dtrace_json_state_t;
3719 
3720 /*
3721  * This function possesses just enough knowledge about JSON to extract a single
3722  * value from a JSON string and store it in the scratch buffer.  It is able
3723  * to extract nested object values, and members of arrays by index.
3724  *
3725  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3726  * be looked up as we descend into the object tree.  e.g.
3727  *
3728  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3729  *       with nelems = 5.
3730  *
3731  * The run time of this function must be bounded above by strsize to limit the
3732  * amount of work done in probe context.  As such, it is implemented as a
3733  * simple state machine, reading one character at a time using safe loads
3734  * until we find the requested element, hit a parsing error or run off the
3735  * end of the object or string.
3736  *
3737  * As there is no way for a subroutine to return an error without interrupting
3738  * clause execution, we simply return NULL in the event of a missing key or any
3739  * other error condition.  Each NULL return in this function is commented with
3740  * the error condition it represents -- parsing or otherwise.
3741  *
3742  * The set of states for the state machine closely matches the JSON
3743  * specification (http://json.org/).  Briefly:
3744  *
3745  *   DTRACE_JSON_REST:
3746  *     Skip whitespace until we find either a top-level Object, moving
3747  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3748  *
3749  *   DTRACE_JSON_OBJECT:
3750  *     Locate the next key String in an Object.  Sets a flag to denote
3751  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3752  *
3753  *   DTRACE_JSON_COLON:
3754  *     Skip whitespace until we find the colon that separates key Strings
3755  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3756  *
3757  *   DTRACE_JSON_VALUE:
3758  *     Detects the type of the next value (String, Number, Identifier, Object
3759  *     or Array) and routes to the states that process that type.  Here we also
3760  *     deal with the element selector list if we are requested to traverse down
3761  *     into the object tree.
3762  *
3763  *   DTRACE_JSON_COMMA:
3764  *     Skip whitespace until we find the comma that separates key-value pairs
3765  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3766  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3767  *     states return to this state at the end of their value, unless otherwise
3768  *     noted.
3769  *
3770  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3771  *     Processes a Number literal from the JSON, including any exponent
3772  *     component that may be present.  Numbers are returned as strings, which
3773  *     may be passed to strtoll() if an integer is required.
3774  *
3775  *   DTRACE_JSON_IDENTIFIER:
3776  *     Processes a "true", "false" or "null" literal in the JSON.
3777  *
3778  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3779  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3780  *     Processes a String literal from the JSON, whether the String denotes
3781  *     a key, a value or part of a larger Object.  Handles all escape sequences
3782  *     present in the specification, including four-digit unicode characters,
3783  *     but merely includes the escape sequence without converting it to the
3784  *     actual escaped character.  If the String is flagged as a key, we
3785  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3786  *
3787  *   DTRACE_JSON_COLLECT_OBJECT:
3788  *     This state collects an entire Object (or Array), correctly handling
3789  *     embedded strings.  If the full element selector list matches this nested
3790  *     object, we return the Object in full as a string.  If not, we use this
3791  *     state to skip to the next value at this level and continue processing.
3792  */
3793 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3794 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3795     char *dest)
3796 {
3797 	dtrace_json_state_t state = DTRACE_JSON_REST;
3798 	int64_t array_elem = INT64_MIN;
3799 	int64_t array_pos = 0;
3800 	uint8_t escape_unicount = 0;
3801 	boolean_t string_is_key = B_FALSE;
3802 	boolean_t collect_object = B_FALSE;
3803 	boolean_t found_key = B_FALSE;
3804 	boolean_t in_array = B_FALSE;
3805 	uint32_t braces = 0, brackets = 0;
3806 	char *elem = elemlist;
3807 	char *dd = dest;
3808 	uintptr_t cur;
3809 
3810 	for (cur = json; cur < json + size; cur++) {
3811 		char cc = dtrace_load8(cur);
3812 		if (cc == '\0')
3813 			return (NULL);
3814 
3815 		switch (state) {
3816 		case DTRACE_JSON_REST:
3817 			if (isspace(cc))
3818 				break;
3819 
3820 			if (cc == '{') {
3821 				state = DTRACE_JSON_OBJECT;
3822 				break;
3823 			}
3824 
3825 			if (cc == '[') {
3826 				in_array = B_TRUE;
3827 				array_pos = 0;
3828 				array_elem = dtrace_strtoll(elem, 10, size);
3829 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3830 				state = DTRACE_JSON_VALUE;
3831 				break;
3832 			}
3833 
3834 			/*
3835 			 * ERROR: expected to find a top-level object or array.
3836 			 */
3837 			return (NULL);
3838 		case DTRACE_JSON_OBJECT:
3839 			if (isspace(cc))
3840 				break;
3841 
3842 			if (cc == '"') {
3843 				state = DTRACE_JSON_STRING;
3844 				string_is_key = B_TRUE;
3845 				break;
3846 			}
3847 
3848 			/*
3849 			 * ERROR: either the object did not start with a key
3850 			 * string, or we've run off the end of the object
3851 			 * without finding the requested key.
3852 			 */
3853 			return (NULL);
3854 		case DTRACE_JSON_STRING:
3855 			if (cc == '\\') {
3856 				*dd++ = '\\';
3857 				state = DTRACE_JSON_STRING_ESCAPE;
3858 				break;
3859 			}
3860 
3861 			if (cc == '"') {
3862 				if (collect_object) {
3863 					/*
3864 					 * We don't reset the dest here, as
3865 					 * the string is part of a larger
3866 					 * object being collected.
3867 					 */
3868 					*dd++ = cc;
3869 					collect_object = B_FALSE;
3870 					state = DTRACE_JSON_COLLECT_OBJECT;
3871 					break;
3872 				}
3873 				*dd = '\0';
3874 				dd = dest; /* reset string buffer */
3875 				if (string_is_key) {
3876 					if (dtrace_strncmp(dest, elem,
3877 					    size) == 0)
3878 						found_key = B_TRUE;
3879 				} else if (found_key) {
3880 					if (nelems > 1) {
3881 						/*
3882 						 * We expected an object, not
3883 						 * this string.
3884 						 */
3885 						return (NULL);
3886 					}
3887 					return (dest);
3888 				}
3889 				state = string_is_key ? DTRACE_JSON_COLON :
3890 				    DTRACE_JSON_COMMA;
3891 				string_is_key = B_FALSE;
3892 				break;
3893 			}
3894 
3895 			*dd++ = cc;
3896 			break;
3897 		case DTRACE_JSON_STRING_ESCAPE:
3898 			*dd++ = cc;
3899 			if (cc == 'u') {
3900 				escape_unicount = 0;
3901 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3902 			} else {
3903 				state = DTRACE_JSON_STRING;
3904 			}
3905 			break;
3906 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3907 			if (!isxdigit(cc)) {
3908 				/*
3909 				 * ERROR: invalid unicode escape, expected
3910 				 * four valid hexidecimal digits.
3911 				 */
3912 				return (NULL);
3913 			}
3914 
3915 			*dd++ = cc;
3916 			if (++escape_unicount == 4)
3917 				state = DTRACE_JSON_STRING;
3918 			break;
3919 		case DTRACE_JSON_COLON:
3920 			if (isspace(cc))
3921 				break;
3922 
3923 			if (cc == ':') {
3924 				state = DTRACE_JSON_VALUE;
3925 				break;
3926 			}
3927 
3928 			/*
3929 			 * ERROR: expected a colon.
3930 			 */
3931 			return (NULL);
3932 		case DTRACE_JSON_COMMA:
3933 			if (isspace(cc))
3934 				break;
3935 
3936 			if (cc == ',') {
3937 				if (in_array) {
3938 					state = DTRACE_JSON_VALUE;
3939 					if (++array_pos == array_elem)
3940 						found_key = B_TRUE;
3941 				} else {
3942 					state = DTRACE_JSON_OBJECT;
3943 				}
3944 				break;
3945 			}
3946 
3947 			/*
3948 			 * ERROR: either we hit an unexpected character, or
3949 			 * we reached the end of the object or array without
3950 			 * finding the requested key.
3951 			 */
3952 			return (NULL);
3953 		case DTRACE_JSON_IDENTIFIER:
3954 			if (islower(cc)) {
3955 				*dd++ = cc;
3956 				break;
3957 			}
3958 
3959 			*dd = '\0';
3960 			dd = dest; /* reset string buffer */
3961 
3962 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3963 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3964 			    dtrace_strncmp(dest, "null", 5) == 0) {
3965 				if (found_key) {
3966 					if (nelems > 1) {
3967 						/*
3968 						 * ERROR: We expected an object,
3969 						 * not this identifier.
3970 						 */
3971 						return (NULL);
3972 					}
3973 					return (dest);
3974 				} else {
3975 					cur--;
3976 					state = DTRACE_JSON_COMMA;
3977 					break;
3978 				}
3979 			}
3980 
3981 			/*
3982 			 * ERROR: we did not recognise the identifier as one
3983 			 * of those in the JSON specification.
3984 			 */
3985 			return (NULL);
3986 		case DTRACE_JSON_NUMBER:
3987 			if (cc == '.') {
3988 				*dd++ = cc;
3989 				state = DTRACE_JSON_NUMBER_FRAC;
3990 				break;
3991 			}
3992 
3993 			if (cc == 'x' || cc == 'X') {
3994 				/*
3995 				 * ERROR: specification explicitly excludes
3996 				 * hexidecimal or octal numbers.
3997 				 */
3998 				return (NULL);
3999 			}
4000 
4001 			OS_FALLTHROUGH;
4002 		case DTRACE_JSON_NUMBER_FRAC:
4003 			if (cc == 'e' || cc == 'E') {
4004 				*dd++ = cc;
4005 				state = DTRACE_JSON_NUMBER_EXP;
4006 				break;
4007 			}
4008 
4009 			if (cc == '+' || cc == '-') {
4010 				/*
4011 				 * ERROR: expect sign as part of exponent only.
4012 				 */
4013 				return (NULL);
4014 			}
4015 			OS_FALLTHROUGH;
4016 		case DTRACE_JSON_NUMBER_EXP:
4017 			if (isdigit(cc) || cc == '+' || cc == '-') {
4018 				*dd++ = cc;
4019 				break;
4020 			}
4021 
4022 			*dd = '\0';
4023 			dd = dest; /* reset string buffer */
4024 			if (found_key) {
4025 				if (nelems > 1) {
4026 					/*
4027 					 * ERROR: We expected an object, not
4028 					 * this number.
4029 					 */
4030 					return (NULL);
4031 				}
4032 				return (dest);
4033 			}
4034 
4035 			cur--;
4036 			state = DTRACE_JSON_COMMA;
4037 			break;
4038 		case DTRACE_JSON_VALUE:
4039 			if (isspace(cc))
4040 				break;
4041 
4042 			if (cc == '{' || cc == '[') {
4043 				if (nelems > 1 && found_key) {
4044 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4045 					/*
4046 					 * If our element selector directs us
4047 					 * to descend into this nested object,
4048 					 * then move to the next selector
4049 					 * element in the list and restart the
4050 					 * state machine.
4051 					 */
4052 					while (*elem != '\0')
4053 						elem++;
4054 					elem++; /* skip the inter-element NUL */
4055 					nelems--;
4056 					dd = dest;
4057 					if (in_array) {
4058 						state = DTRACE_JSON_VALUE;
4059 						array_pos = 0;
4060 						array_elem = dtrace_strtoll(
4061 						    elem, 10, size);
4062 						found_key = array_elem == 0 ?
4063 						    B_TRUE : B_FALSE;
4064 					} else {
4065 						found_key = B_FALSE;
4066 						state = DTRACE_JSON_OBJECT;
4067 					}
4068 					break;
4069 				}
4070 
4071 				/*
4072 				 * Otherwise, we wish to either skip this
4073 				 * nested object or return it in full.
4074 				 */
4075 				if (cc == '[')
4076 					brackets = 1;
4077 				else
4078 					braces = 1;
4079 				*dd++ = cc;
4080 				state = DTRACE_JSON_COLLECT_OBJECT;
4081 				break;
4082 			}
4083 
4084 			if (cc == '"') {
4085 				state = DTRACE_JSON_STRING;
4086 				break;
4087 			}
4088 
4089 			if (islower(cc)) {
4090 				/*
4091 				 * Here we deal with true, false and null.
4092 				 */
4093 				*dd++ = cc;
4094 				state = DTRACE_JSON_IDENTIFIER;
4095 				break;
4096 			}
4097 
4098 			if (cc == '-' || isdigit(cc)) {
4099 				*dd++ = cc;
4100 				state = DTRACE_JSON_NUMBER;
4101 				break;
4102 			}
4103 
4104 			/*
4105 			 * ERROR: unexpected character at start of value.
4106 			 */
4107 			return (NULL);
4108 		case DTRACE_JSON_COLLECT_OBJECT:
4109 			if (cc == '\0')
4110 				/*
4111 				 * ERROR: unexpected end of input.
4112 				 */
4113 				return (NULL);
4114 
4115 			*dd++ = cc;
4116 			if (cc == '"') {
4117 				collect_object = B_TRUE;
4118 				state = DTRACE_JSON_STRING;
4119 				break;
4120 			}
4121 
4122 			if (cc == ']') {
4123 				if (brackets-- == 0) {
4124 					/*
4125 					 * ERROR: unbalanced brackets.
4126 					 */
4127 					return (NULL);
4128 				}
4129 			} else if (cc == '}') {
4130 				if (braces-- == 0) {
4131 					/*
4132 					 * ERROR: unbalanced braces.
4133 					 */
4134 					return (NULL);
4135 				}
4136 			} else if (cc == '{') {
4137 				braces++;
4138 			} else if (cc == '[') {
4139 				brackets++;
4140 			}
4141 
4142 			if (brackets == 0 && braces == 0) {
4143 				if (found_key) {
4144 					*dd = '\0';
4145 					return (dest);
4146 				}
4147 				dd = dest; /* reset string buffer */
4148 				state = DTRACE_JSON_COMMA;
4149 			}
4150 			break;
4151 		}
4152 	}
4153 	return (NULL);
4154 }
4155 
4156 /*
4157  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4158  * Notice that we don't bother validating the proper number of arguments or
4159  * their types in the tuple stack.  This isn't needed because all argument
4160  * interpretation is safe because of our load safety -- the worst that can
4161  * happen is that a bogus program can obtain bogus results.
4162  */
4163 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)4164 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4165     dtrace_key_t *tupregs, int nargs,
4166     dtrace_mstate_t *mstate, dtrace_state_t *state)
4167 {
4168 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4169 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4170 	dtrace_vstate_t *vstate = &state->dts_vstate;
4171 
4172 #if !defined(__APPLE__)
4173 	union {
4174 		mutex_impl_t mi;
4175 		uint64_t mx;
4176 	} m;
4177 
4178 	union {
4179 		krwlock_t ri;
4180 		uintptr_t rw;
4181 	} r;
4182 #else
4183 /* FIXME: awaits lock/mutex work */
4184 #endif /* __APPLE__ */
4185 
4186 	switch (subr) {
4187 	case DIF_SUBR_RAND:
4188 		regs[rd] = dtrace_xoroshiro128_plus_next(
4189 		    state->dts_rstate[CPU->cpu_id]);
4190 		break;
4191 
4192 #if !defined(__APPLE__)
4193 	case DIF_SUBR_MUTEX_OWNED:
4194 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4195 		    mstate, vstate)) {
4196 			regs[rd] = 0;
4197 			break;
4198 		}
4199 
4200 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4201 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4202 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4203 		else
4204 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4205 		break;
4206 
4207 	case DIF_SUBR_MUTEX_OWNER:
4208 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4209 		    mstate, vstate)) {
4210 			regs[rd] = 0;
4211 			break;
4212 		}
4213 
4214 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4215 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4216 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4217 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4218 		else
4219 			regs[rd] = 0;
4220 		break;
4221 
4222 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4223 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4224 		    mstate, vstate)) {
4225 			regs[rd] = 0;
4226 			break;
4227 		}
4228 
4229 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4230 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4231 		break;
4232 
4233 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4234 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4235 		    mstate, vstate)) {
4236 			regs[rd] = 0;
4237 			break;
4238 		}
4239 
4240 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4241 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4242 		break;
4243 
4244 	case DIF_SUBR_RW_READ_HELD: {
4245 		uintptr_t tmp;
4246 
4247 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4248 		    mstate, vstate)) {
4249 			regs[rd] = 0;
4250 			break;
4251 		}
4252 
4253 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4254 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4255 		break;
4256 	}
4257 
4258 	case DIF_SUBR_RW_WRITE_HELD:
4259 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4260 		    mstate, vstate)) {
4261 			regs[rd] = 0;
4262 			break;
4263 		}
4264 
4265 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4266 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4267 		break;
4268 
4269 	case DIF_SUBR_RW_ISWRITER:
4270 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4271 		    mstate, vstate)) {
4272 			regs[rd] = 0;
4273 			break;
4274 		}
4275 
4276 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4277 		regs[rd] = _RW_ISWRITER(&r.ri);
4278 		break;
4279 #else
4280 /* FIXME: awaits lock/mutex work */
4281 #endif /* __APPLE__ */
4282 
4283 	case DIF_SUBR_BCOPY: {
4284 		/*
4285 		 * We need to be sure that the destination is in the scratch
4286 		 * region -- no other region is allowed.
4287 		 */
4288 		uintptr_t src = tupregs[0].dttk_value;
4289 		uintptr_t dest = tupregs[1].dttk_value;
4290 		size_t size = tupregs[2].dttk_value;
4291 
4292 		if (!dtrace_inscratch(dest, size, mstate)) {
4293 			*flags |= CPU_DTRACE_BADADDR;
4294 			*illval = regs[rd];
4295 			break;
4296 		}
4297 
4298 		if (!dtrace_canload(src, size, mstate, vstate)) {
4299 			regs[rd] = 0;
4300 			break;
4301 		}
4302 
4303 		dtrace_bcopy((void *)src, (void *)dest, size);
4304 		break;
4305 	}
4306 
4307 	case DIF_SUBR_ALLOCA:
4308 	case DIF_SUBR_COPYIN: {
4309 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4310 		uint64_t size =
4311 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4312 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4313 
4314 		/*
4315 		 * Check whether the user can access kernel memory
4316 		 */
4317 		if (dtrace_priv_kernel(state) == 0) {
4318 			DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
4319 			regs[rd] = 0;
4320 			break;
4321 		}
4322 		/*
4323 		 * This action doesn't require any credential checks since
4324 		 * probes will not activate in user contexts to which the
4325 		 * enabling user does not have permissions.
4326 		 */
4327 
4328 		/*
4329 		 * Rounding up the user allocation size could have overflowed
4330 		 * a large, bogus allocation (like -1ULL) to 0.
4331 		 */
4332 		if (scratch_size < size ||
4333 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4334 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4335 			regs[rd] = 0;
4336 			break;
4337 		}
4338 
4339 		if (subr == DIF_SUBR_COPYIN) {
4340 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4341 			if (dtrace_priv_proc(state))
4342 				dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4343 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4344 		}
4345 
4346 		mstate->dtms_scratch_ptr += scratch_size;
4347 		regs[rd] = dest;
4348 		break;
4349 	}
4350 
4351 	case DIF_SUBR_COPYINTO: {
4352 		uint64_t size = tupregs[1].dttk_value;
4353 		uintptr_t dest = tupregs[2].dttk_value;
4354 
4355 		/*
4356 		 * This action doesn't require any credential checks since
4357 		 * probes will not activate in user contexts to which the
4358 		 * enabling user does not have permissions.
4359 		 */
4360 		if (!dtrace_inscratch(dest, size, mstate)) {
4361 			*flags |= CPU_DTRACE_BADADDR;
4362 			*illval = regs[rd];
4363 			break;
4364 		}
4365 
4366 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4367 		if (dtrace_priv_proc(state))
4368 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4369 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4370 		break;
4371 	}
4372 
4373 	case DIF_SUBR_COPYINSTR: {
4374 		uintptr_t dest = mstate->dtms_scratch_ptr;
4375 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4376 
4377 		if (nargs > 1 && tupregs[1].dttk_value < size)
4378 			size = tupregs[1].dttk_value + 1;
4379 
4380 		/*
4381 		 * This action doesn't require any credential checks since
4382 		 * probes will not activate in user contexts to which the
4383 		 * enabling user does not have permissions.
4384 		 */
4385 		if (!DTRACE_INSCRATCH(mstate, size)) {
4386 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4387 			regs[rd] = 0;
4388 			break;
4389 		}
4390 
4391 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4392 		if (dtrace_priv_proc(state))
4393 			dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4394 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4395 
4396 		((char *)dest)[size - 1] = '\0';
4397 		mstate->dtms_scratch_ptr += size;
4398 		regs[rd] = dest;
4399 		break;
4400 	}
4401 
4402 	case DIF_SUBR_MSGSIZE:
4403 	case DIF_SUBR_MSGDSIZE: {
4404 		/* Darwin does not implement SysV streams messages */
4405 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4406 		regs[rd] = 0;
4407 		break;
4408 	}
4409 
4410 	case DIF_SUBR_PROGENYOF: {
4411 		pid_t pid = tupregs[0].dttk_value;
4412 		struct proc *p = current_proc();
4413 		int rval = 0, lim = nprocs;
4414 
4415 		while(p && (lim-- > 0)) {
4416 			pid_t ppid;
4417 
4418 			ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
4419 			if (*flags & CPU_DTRACE_FAULT)
4420 				break;
4421 
4422 			if (ppid == pid) {
4423 				rval = 1;
4424 				break;
4425 			}
4426 
4427 			if (ppid == 0)
4428 				break; /* Can't climb process tree any further. */
4429 
4430 			p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
4431 #if __has_feature(ptrauth_calls)
4432 			p = ptrauth_strip(p, ptrauth_key_process_independent_data);
4433 #endif
4434 			if (*flags & CPU_DTRACE_FAULT)
4435 				break;
4436 		}
4437 
4438 		regs[rd] = rval;
4439 		break;
4440 	}
4441 
4442 	case DIF_SUBR_SPECULATION:
4443 		regs[rd] = dtrace_speculation(state);
4444 		break;
4445 
4446 
4447 	case DIF_SUBR_COPYOUT: {
4448 		uintptr_t kaddr = tupregs[0].dttk_value;
4449 		user_addr_t uaddr = tupregs[1].dttk_value;
4450 		uint64_t size = tupregs[2].dttk_value;
4451 
4452 		if (!dtrace_destructive_disallow &&
4453 		    dtrace_priv_proc_control(state) &&
4454 		    !dtrace_istoxic(kaddr, size) &&
4455 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4456 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4457 			dtrace_copyout(kaddr, uaddr, size, flags);
4458 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4459 		}
4460 		break;
4461 	}
4462 
4463 	case DIF_SUBR_COPYOUTSTR: {
4464 		uintptr_t kaddr = tupregs[0].dttk_value;
4465 		user_addr_t uaddr = tupregs[1].dttk_value;
4466 		uint64_t size = tupregs[2].dttk_value;
4467 		size_t lim;
4468 
4469 		if (!dtrace_destructive_disallow &&
4470 		    dtrace_priv_proc_control(state) &&
4471 		    !dtrace_istoxic(kaddr, size) &&
4472 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4473 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4474 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4475 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4476 		}
4477 		break;
4478 	}
4479 
4480 	case DIF_SUBR_STRLEN: {
4481 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4482 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4483 		size_t lim;
4484 
4485 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4486 			regs[rd] = 0;
4487 			break;
4488 		}
4489 
4490 		regs[rd] = dtrace_strlen((char *)addr, lim);
4491 
4492 		break;
4493 	}
4494 
4495 	case DIF_SUBR_STRCHR:
4496 	case DIF_SUBR_STRRCHR: {
4497 		/*
4498 		 * We're going to iterate over the string looking for the
4499 		 * specified character.  We will iterate until we have reached
4500 		 * the string length or we have found the character.  If this
4501 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4502 		 * of the specified character instead of the first.
4503 		 */
4504 		uintptr_t addr = tupregs[0].dttk_value;
4505 		uintptr_t addr_limit;
4506 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4507 		size_t lim;
4508 		char c, target = (char)tupregs[1].dttk_value;
4509 
4510 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4511 			regs[rd] = 0;
4512 			break;
4513 		}
4514 		addr_limit = addr + lim;
4515 
4516 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4517 			if ((c = dtrace_load8(addr)) == target) {
4518 				regs[rd] = addr;
4519 
4520 				if (subr == DIF_SUBR_STRCHR)
4521 					break;
4522 			}
4523 
4524 			if (c == '\0')
4525 				break;
4526 		}
4527 
4528 		break;
4529 	}
4530 
4531 	case DIF_SUBR_STRSTR:
4532 	case DIF_SUBR_INDEX:
4533 	case DIF_SUBR_RINDEX: {
4534 		/*
4535 		 * We're going to iterate over the string looking for the
4536 		 * specified string.  We will iterate until we have reached
4537 		 * the string length or we have found the string.  (Yes, this
4538 		 * is done in the most naive way possible -- but considering
4539 		 * that the string we're searching for is likely to be
4540 		 * relatively short, the complexity of Rabin-Karp or similar
4541 		 * hardly seems merited.)
4542 		 */
4543 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4544 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4545 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4546 		size_t len = dtrace_strlen(addr, size);
4547 		size_t sublen = dtrace_strlen(substr, size);
4548 		char *limit = addr + len, *orig = addr;
4549 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4550 		int inc = 1;
4551 
4552 		regs[rd] = notfound;
4553 
4554 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4555 			regs[rd] = 0;
4556 			break;
4557 		}
4558 
4559 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4560 		    vstate)) {
4561 			regs[rd] = 0;
4562 			break;
4563 		}
4564 
4565 		/*
4566 		 * strstr() and index()/rindex() have similar semantics if
4567 		 * both strings are the empty string: strstr() returns a
4568 		 * pointer to the (empty) string, and index() and rindex()
4569 		 * both return index 0 (regardless of any position argument).
4570 		 */
4571 		if (sublen == 0 && len == 0) {
4572 			if (subr == DIF_SUBR_STRSTR)
4573 				regs[rd] = (uintptr_t)addr;
4574 			else
4575 				regs[rd] = 0;
4576 			break;
4577 		}
4578 
4579 		if (subr != DIF_SUBR_STRSTR) {
4580 			if (subr == DIF_SUBR_RINDEX) {
4581 				limit = orig - 1;
4582 				addr += len;
4583 				inc = -1;
4584 			}
4585 
4586 			/*
4587 			 * Both index() and rindex() take an optional position
4588 			 * argument that denotes the starting position.
4589 			 */
4590 			if (nargs == 3) {
4591 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4592 
4593 				/*
4594 				 * If the position argument to index() is
4595 				 * negative, Perl implicitly clamps it at
4596 				 * zero.  This semantic is a little surprising
4597 				 * given the special meaning of negative
4598 				 * positions to similar Perl functions like
4599 				 * substr(), but it appears to reflect a
4600 				 * notion that index() can start from a
4601 				 * negative index and increment its way up to
4602 				 * the string.  Given this notion, Perl's
4603 				 * rindex() is at least self-consistent in
4604 				 * that it implicitly clamps positions greater
4605 				 * than the string length to be the string
4606 				 * length.  Where Perl completely loses
4607 				 * coherence, however, is when the specified
4608 				 * substring is the empty string ("").  In
4609 				 * this case, even if the position is
4610 				 * negative, rindex() returns 0 -- and even if
4611 				 * the position is greater than the length,
4612 				 * index() returns the string length.  These
4613 				 * semantics violate the notion that index()
4614 				 * should never return a value less than the
4615 				 * specified position and that rindex() should
4616 				 * never return a value greater than the
4617 				 * specified position.  (One assumes that
4618 				 * these semantics are artifacts of Perl's
4619 				 * implementation and not the results of
4620 				 * deliberate design -- it beggars belief that
4621 				 * even Larry Wall could desire such oddness.)
4622 				 * While in the abstract one would wish for
4623 				 * consistent position semantics across
4624 				 * substr(), index() and rindex() -- or at the
4625 				 * very least self-consistent position
4626 				 * semantics for index() and rindex() -- we
4627 				 * instead opt to keep with the extant Perl
4628 				 * semantics, in all their broken glory.  (Do
4629 				 * we have more desire to maintain Perl's
4630 				 * semantics than Perl does?  Probably.)
4631 				 */
4632 				if (subr == DIF_SUBR_RINDEX) {
4633 					if (pos < 0) {
4634 						if (sublen == 0)
4635 							regs[rd] = 0;
4636 						break;
4637 					}
4638 
4639 					if ((size_t)pos > len)
4640 						pos = len;
4641 				} else {
4642 					if (pos < 0)
4643 						pos = 0;
4644 
4645 					if ((size_t)pos >= len) {
4646 						if (sublen == 0)
4647 							regs[rd] = len;
4648 						break;
4649 					}
4650 				}
4651 
4652 				addr = orig + pos;
4653 			}
4654 		}
4655 
4656 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4657 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4658 				if (subr != DIF_SUBR_STRSTR) {
4659 					/*
4660 					 * As D index() and rindex() are
4661 					 * modeled on Perl (and not on awk),
4662 					 * we return a zero-based (and not a
4663 					 * one-based) index.  (For you Perl
4664 					 * weenies: no, we're not going to add
4665 					 * $[ -- and shouldn't you be at a con
4666 					 * or something?)
4667 					 */
4668 					regs[rd] = (uintptr_t)(addr - orig);
4669 					break;
4670 				}
4671 
4672 				ASSERT(subr == DIF_SUBR_STRSTR);
4673 				regs[rd] = (uintptr_t)addr;
4674 				break;
4675 			}
4676 		}
4677 
4678 		break;
4679 	}
4680 
4681 	case DIF_SUBR_STRTOK: {
4682 		uintptr_t addr = tupregs[0].dttk_value;
4683 		uintptr_t tokaddr = tupregs[1].dttk_value;
4684 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4685 		uintptr_t limit, toklimit;
4686 		size_t clim;
4687 		char *dest = (char *)mstate->dtms_scratch_ptr;
4688 		uint8_t c='\0', tokmap[32];	 /* 256 / 8 */
4689 		uint64_t i = 0;
4690 
4691 		/*
4692 		 * Check both the token buffer and (later) the input buffer,
4693 		 * since both could be non-scratch addresses.
4694 		 */
4695 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4696 			regs[rd] = 0;
4697 			break;
4698 		}
4699 		toklimit = tokaddr + clim;
4700 
4701 		if (!DTRACE_INSCRATCH(mstate, size)) {
4702 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4703 			regs[rd] = 0;
4704 			break;
4705 		}
4706 
4707 		if (addr == 0) {
4708 			/*
4709 			 * If the address specified is NULL, we use our saved
4710 			 * strtok pointer from the mstate.  Note that this
4711 			 * means that the saved strtok pointer is _only_
4712 			 * valid within multiple enablings of the same probe --
4713 			 * it behaves like an implicit clause-local variable.
4714 			 */
4715 			addr = mstate->dtms_strtok;
4716 			limit = mstate->dtms_strtok_limit;
4717 		} else {
4718 			/*
4719 			 * If the user-specified address is non-NULL we must
4720 			 * access check it.  This is the only time we have
4721 			 * a chance to do so, since this address may reside
4722 			 * in the string table of this clause-- future calls
4723 			 * (when we fetch addr from mstate->dtms_strtok)
4724 			 * would fail this access check.
4725 			 */
4726 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4727 				vstate)) {
4728 				regs[rd] = 0;
4729 				break;
4730 			}
4731 			limit = addr + clim;
4732 		}
4733 
4734 		/*
4735 		 * First, zero the token map, and then process the token
4736 		 * string -- setting a bit in the map for every character
4737 		 * found in the token string.
4738 		 */
4739 		for (i = 0; i < (int)sizeof (tokmap); i++)
4740 			tokmap[i] = 0;
4741 
4742 		for (; tokaddr < toklimit; tokaddr++) {
4743 			if ((c = dtrace_load8(tokaddr)) == '\0')
4744 				break;
4745 
4746 			ASSERT((c >> 3) < sizeof (tokmap));
4747 			tokmap[c >> 3] |= (1 << (c & 0x7));
4748 		}
4749 
4750 		for (; addr < limit; addr++) {
4751 			/*
4752 			 * We're looking for a character that is _not_
4753 			 * contained in the token string.
4754 			 */
4755 			if ((c = dtrace_load8(addr)) == '\0')
4756 				break;
4757 
4758 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4759 				break;
4760 		}
4761 
4762 		if (c == '\0') {
4763 			/*
4764 			 * We reached the end of the string without finding
4765 			 * any character that was not in the token string.
4766 			 * We return NULL in this case, and we set the saved
4767 			 * address to NULL as well.
4768 			 */
4769 			regs[rd] = 0;
4770 			mstate->dtms_strtok = 0;
4771 			mstate->dtms_strtok_limit = 0;
4772 			break;
4773 		}
4774 
4775 		/*
4776 		 * From here on, we're copying into the destination string.
4777 		 */
4778 		for (i = 0; addr < limit && i < size - 1; addr++) {
4779 			if ((c = dtrace_load8(addr)) == '\0')
4780 				break;
4781 
4782 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4783 				break;
4784 
4785 			ASSERT(i < size);
4786 			dest[i++] = c;
4787 		}
4788 
4789 		ASSERT(i < size);
4790 		dest[i] = '\0';
4791 		regs[rd] = (uintptr_t)dest;
4792 		mstate->dtms_scratch_ptr += size;
4793 		mstate->dtms_strtok = addr;
4794 		mstate->dtms_strtok_limit = limit;
4795 		break;
4796 	}
4797 
4798 	case DIF_SUBR_SUBSTR: {
4799 		uintptr_t s = tupregs[0].dttk_value;
4800 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4801 		char *d = (char *)mstate->dtms_scratch_ptr;
4802 		int64_t index = (int64_t)tupregs[1].dttk_value;
4803 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4804 		size_t len = dtrace_strlen((char *)s, size);
4805 		int64_t i = 0;
4806 
4807 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4808 			regs[rd] = 0;
4809 			break;
4810 		}
4811 
4812 		if (!DTRACE_INSCRATCH(mstate, size)) {
4813 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4814 			regs[rd] = 0;
4815 			break;
4816 		}
4817 
4818 		if (nargs <= 2)
4819 			remaining = (int64_t)size;
4820 
4821 		if (index < 0) {
4822 			index += len;
4823 
4824 			if (index < 0 && index + remaining > 0) {
4825 				remaining += index;
4826 				index = 0;
4827 			}
4828 		}
4829 
4830 		if ((size_t)index >= len || index < 0) {
4831 			remaining = 0;
4832 		} else if (remaining < 0) {
4833 			remaining += len - index;
4834 		} else if ((uint64_t)index + (uint64_t)remaining > size) {
4835 			remaining = size - index;
4836 		}
4837 
4838 		for (i = 0; i < remaining; i++) {
4839 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4840 				break;
4841 			}
4842 
4843 		d[i] = '\0';
4844 
4845 		mstate->dtms_scratch_ptr += size;
4846 		regs[rd] = (uintptr_t)d;
4847 		break;
4848 	}
4849 
4850 	case DIF_SUBR_GETMAJOR:
4851 		regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4852 		break;
4853 
4854 	case DIF_SUBR_GETMINOR:
4855 		regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4856 		break;
4857 
4858 	case DIF_SUBR_DDI_PATHNAME: {
4859 		/* APPLE NOTE: currently unsupported on Darwin */
4860 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4861 		regs[rd] = 0;
4862 		break;
4863 	}
4864 
4865 	case DIF_SUBR_STRJOIN: {
4866 		char *d = (char *)mstate->dtms_scratch_ptr;
4867 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4868 		uintptr_t s1 = tupregs[0].dttk_value;
4869 		uintptr_t s2 = tupregs[1].dttk_value;
4870 		uint64_t i = 0, j = 0;
4871 		size_t lim1, lim2;
4872 		char c;
4873 
4874 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
4875 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
4876 			regs[rd] = 0;
4877 			break;
4878 		}
4879 
4880 		if (!DTRACE_INSCRATCH(mstate, size)) {
4881 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4882 			regs[rd] = 0;
4883 			break;
4884 		}
4885 
4886 		for (;;) {
4887 			if (i >= size) {
4888 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4889 				regs[rd] = 0;
4890 				break;
4891 			}
4892 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
4893 			if ((d[i++] = c) == '\0') {
4894 				i--;
4895 				break;
4896 			}
4897 		}
4898 
4899 		for (;;) {
4900 			if (i >= size) {
4901 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4902 				regs[rd] = 0;
4903 				break;
4904 			}
4905 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
4906 			if ((d[i++] = c) == '\0')
4907 				break;
4908 		}
4909 
4910 		if (i < size) {
4911 			mstate->dtms_scratch_ptr += i;
4912 			regs[rd] = (uintptr_t)d;
4913 		}
4914 
4915 		break;
4916 	}
4917 
4918 	case DIF_SUBR_STRTOLL: {
4919 		uintptr_t s = tupregs[0].dttk_value;
4920 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4921 		size_t lim;
4922 		int base = 10;
4923 
4924 		if (nargs > 1) {
4925 			if ((base = tupregs[1].dttk_value) <= 1 ||
4926 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4927 				*flags |= CPU_DTRACE_ILLOP;
4928 				break;
4929 			}
4930 		}
4931 
4932 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
4933 			regs[rd] = INT64_MIN;
4934 			break;
4935 		}
4936 
4937 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
4938 		break;
4939 	}
4940 
4941 	case DIF_SUBR_LLTOSTR: {
4942 		int64_t i = (int64_t)tupregs[0].dttk_value;
4943 		uint64_t val, digit;
4944 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4945 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4946 		int base = 10;
4947 
4948 		if (nargs > 1) {
4949 			if ((base = tupregs[1].dttk_value) <= 1 ||
4950 			     base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4951 				*flags |= CPU_DTRACE_ILLOP;
4952 				break;
4953 			}
4954 		}
4955 
4956 		val = (base == 10 && i < 0) ? i * -1 : i;
4957 
4958 		if (!DTRACE_INSCRATCH(mstate, size)) {
4959 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4960 			regs[rd] = 0;
4961 			break;
4962 		}
4963 
4964 		for (*end-- = '\0'; val; val /= base) {
4965 			if ((digit = val % base) <= '9' - '0') {
4966 				*end-- = '0' + digit;
4967 			} else {
4968 				*end-- = 'a' + (digit - ('9' - '0') - 1);
4969 			}
4970 		}
4971 
4972 		if (i == 0 && base == 16)
4973 			*end-- = '0';
4974 
4975 		if (base == 16)
4976 			*end-- = 'x';
4977 
4978 		if (i == 0 || base == 8 || base == 16)
4979 			*end-- = '0';
4980 
4981 		if (i < 0 && base == 10)
4982 			*end-- = '-';
4983 
4984 		regs[rd] = (uintptr_t)end + 1;
4985 		mstate->dtms_scratch_ptr += size;
4986 		break;
4987 	}
4988 
4989 	case DIF_SUBR_HTONS:
4990 	case DIF_SUBR_NTOHS:
4991 #ifdef _BIG_ENDIAN
4992 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
4993 #else
4994 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4995 #endif
4996 		break;
4997 
4998 
4999 	case DIF_SUBR_HTONL:
5000 	case DIF_SUBR_NTOHL:
5001 #ifdef _BIG_ENDIAN
5002 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5003 #else
5004 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5005 #endif
5006 		break;
5007 
5008 
5009 	case DIF_SUBR_HTONLL:
5010 	case DIF_SUBR_NTOHLL:
5011 #ifdef _BIG_ENDIAN
5012 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5013 #else
5014 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5015 #endif
5016 		break;
5017 
5018 
5019 	case DIF_SUBR_DIRNAME:
5020 	case DIF_SUBR_BASENAME: {
5021 		char *dest = (char *)mstate->dtms_scratch_ptr;
5022 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5023 		uintptr_t src = tupregs[0].dttk_value;
5024 		int i, j, len = dtrace_strlen((char *)src, size);
5025 		int lastbase = -1, firstbase = -1, lastdir = -1;
5026 		int start, end;
5027 
5028 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5029 			regs[rd] = 0;
5030 			break;
5031 		}
5032 
5033 		if (!DTRACE_INSCRATCH(mstate, size)) {
5034 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5035 			regs[rd] = 0;
5036 			break;
5037 		}
5038 
5039 		/*
5040 		 * The basename and dirname for a zero-length string is
5041 		 * defined to be "."
5042 		 */
5043 		if (len == 0) {
5044 			len = 1;
5045 			src = (uintptr_t)".";
5046 		}
5047 
5048 		/*
5049 		 * Start from the back of the string, moving back toward the
5050 		 * front until we see a character that isn't a slash.  That
5051 		 * character is the last character in the basename.
5052 		 */
5053 		for (i = len - 1; i >= 0; i--) {
5054 			if (dtrace_load8(src + i) != '/')
5055 				break;
5056 		}
5057 
5058 		if (i >= 0)
5059 			lastbase = i;
5060 
5061 		/*
5062 		 * Starting from the last character in the basename, move
5063 		 * towards the front until we find a slash.  The character
5064 		 * that we processed immediately before that is the first
5065 		 * character in the basename.
5066 		 */
5067 		for (; i >= 0; i--) {
5068 			if (dtrace_load8(src + i) == '/')
5069 				break;
5070 		}
5071 
5072 		if (i >= 0)
5073 			firstbase = i + 1;
5074 
5075 		/*
5076 		 * Now keep going until we find a non-slash character.  That
5077 		 * character is the last character in the dirname.
5078 		 */
5079 		for (; i >= 0; i--) {
5080 			if (dtrace_load8(src + i) != '/')
5081 				break;
5082 		}
5083 
5084 		if (i >= 0)
5085 			lastdir = i;
5086 
5087 		ASSERT(!(lastbase == -1 && firstbase != -1));
5088 		ASSERT(!(firstbase == -1 && lastdir != -1));
5089 
5090 		if (lastbase == -1) {
5091 			/*
5092 			 * We didn't find a non-slash character.  We know that
5093 			 * the length is non-zero, so the whole string must be
5094 			 * slashes.  In either the dirname or the basename
5095 			 * case, we return '/'.
5096 			 */
5097 			ASSERT(firstbase == -1);
5098 			firstbase = lastbase = lastdir = 0;
5099 		}
5100 
5101 		if (firstbase == -1) {
5102 			/*
5103 			 * The entire string consists only of a basename
5104 			 * component.  If we're looking for dirname, we need
5105 			 * to change our string to be just "."; if we're
5106 			 * looking for a basename, we'll just set the first
5107 			 * character of the basename to be 0.
5108 			 */
5109 			if (subr == DIF_SUBR_DIRNAME) {
5110 				ASSERT(lastdir == -1);
5111 				src = (uintptr_t)".";
5112 				lastdir = 0;
5113 			} else {
5114 				firstbase = 0;
5115 			}
5116 		}
5117 
5118 		if (subr == DIF_SUBR_DIRNAME) {
5119 			if (lastdir == -1) {
5120 				/*
5121 				 * We know that we have a slash in the name --
5122 				 * or lastdir would be set to 0, above.  And
5123 				 * because lastdir is -1, we know that this
5124 				 * slash must be the first character.  (That
5125 				 * is, the full string must be of the form
5126 				 * "/basename".)  In this case, the last
5127 				 * character of the directory name is 0.
5128 				 */
5129 				lastdir = 0;
5130 			}
5131 
5132 			start = 0;
5133 			end = lastdir;
5134 		} else {
5135 			ASSERT(subr == DIF_SUBR_BASENAME);
5136 			ASSERT(firstbase != -1 && lastbase != -1);
5137 			start = firstbase;
5138 			end = lastbase;
5139 		}
5140 
5141 		for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
5142 			dest[j] = dtrace_load8(src + i);
5143 
5144 		dest[j] = '\0';
5145 		regs[rd] = (uintptr_t)dest;
5146 		mstate->dtms_scratch_ptr += size;
5147 		break;
5148 	}
5149 
5150 	case DIF_SUBR_CLEANPATH: {
5151 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5152 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5153 		uintptr_t src = tupregs[0].dttk_value;
5154 		size_t lim;
5155 		size_t i = 0, j = 0;
5156 
5157 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5158 			regs[rd] = 0;
5159 			break;
5160 		}
5161 
5162 		if (!DTRACE_INSCRATCH(mstate, size)) {
5163 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5164 			regs[rd] = 0;
5165 			break;
5166 		}
5167 
5168 		/*
5169 		 * Move forward, loading each character.
5170 		 */
5171 		do {
5172 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5173 next:
5174 			if ((uint64_t)(j + 5) >= size)	/* 5 = strlen("/..c\0") */
5175 				break;
5176 
5177 			if (c != '/') {
5178 				dest[j++] = c;
5179 				continue;
5180 			}
5181 
5182 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5183 
5184 			if (c == '/') {
5185 				/*
5186 				 * We have two slashes -- we can just advance
5187 				 * to the next character.
5188 				 */
5189 				goto next;
5190 			}
5191 
5192 			if (c != '.') {
5193 				/*
5194 				 * This is not "." and it's not ".." -- we can
5195 				 * just store the "/" and this character and
5196 				 * drive on.
5197 				 */
5198 				dest[j++] = '/';
5199 				dest[j++] = c;
5200 				continue;
5201 			}
5202 
5203 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5204 
5205 			if (c == '/') {
5206 				/*
5207 				 * This is a "/./" component.  We're not going
5208 				 * to store anything in the destination buffer;
5209 				 * we're just going to go to the next component.
5210 				 */
5211 				goto next;
5212 			}
5213 
5214 			if (c != '.') {
5215 				/*
5216 				 * This is not ".." -- we can just store the
5217 				 * "/." and this character and continue
5218 				 * processing.
5219 				 */
5220 				dest[j++] = '/';
5221 				dest[j++] = '.';
5222 				dest[j++] = c;
5223 				continue;
5224 			}
5225 
5226 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5227 
5228 			if (c != '/' && c != '\0') {
5229 				/*
5230 				 * This is not ".." -- it's "..[mumble]".
5231 				 * We'll store the "/.." and this character
5232 				 * and continue processing.
5233 				 */
5234 				dest[j++] = '/';
5235 				dest[j++] = '.';
5236 				dest[j++] = '.';
5237 				dest[j++] = c;
5238 				continue;
5239 			}
5240 
5241 			/*
5242 			 * This is "/../" or "/..\0".  We need to back up
5243 			 * our destination pointer until we find a "/".
5244 			 */
5245 			i--;
5246 			while (j != 0 && dest[--j] != '/')
5247 				continue;
5248 
5249 			if (c == '\0')
5250 				dest[++j] = '/';
5251 		} while (c != '\0');
5252 
5253 		dest[j] = '\0';
5254 		regs[rd] = (uintptr_t)dest;
5255 		mstate->dtms_scratch_ptr += size;
5256 		break;
5257 	}
5258 
5259 	case DIF_SUBR_INET_NTOA:
5260 	case DIF_SUBR_INET_NTOA6:
5261 	case DIF_SUBR_INET_NTOP: {
5262 		size_t size;
5263 		int af, argi, i;
5264 		char *base, *end;
5265 
5266 		if (subr == DIF_SUBR_INET_NTOP) {
5267 			af = (int)tupregs[0].dttk_value;
5268 			argi = 1;
5269 		} else {
5270 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5271 			argi = 0;
5272 		}
5273 
5274 		if (af == AF_INET) {
5275 #if !defined(__APPLE__)
5276 			ipaddr_t ip4;
5277 #else
5278 			uint32_t ip4;
5279 #endif /* __APPLE__ */
5280 			uint8_t *ptr8, val;
5281 
5282 			/*
5283 			 * Safely load the IPv4 address.
5284 			 */
5285 #if !defined(__APPLE__)
5286 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5287 #else
5288 			if (!dtrace_canload(tupregs[argi].dttk_value, sizeof(ip4),
5289 				mstate, vstate)) {
5290 				regs[rd] = 0;
5291 				break;
5292 			}
5293 
5294 			dtrace_bcopy(
5295 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5296 			    (void *)(uintptr_t)&ip4, sizeof (ip4));
5297 #endif /* __APPLE__ */
5298 			/*
5299 			 * Check an IPv4 string will fit in scratch.
5300 			 */
5301 #if !defined(__APPLE__)
5302 			size = INET_ADDRSTRLEN;
5303 #else
5304 			size = MAX_IPv4_STR_LEN;
5305 #endif /* __APPLE__ */
5306 			if (!DTRACE_INSCRATCH(mstate, size)) {
5307 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5308 				regs[rd] = 0;
5309 				break;
5310 			}
5311 			base = (char *)mstate->dtms_scratch_ptr;
5312 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5313 
5314 			/*
5315 			 * Stringify as a dotted decimal quad.
5316 			 */
5317 			*end-- = '\0';
5318 			ptr8 = (uint8_t *)&ip4;
5319 			for (i = 3; i >= 0; i--) {
5320 				val = ptr8[i];
5321 
5322 				if (val == 0) {
5323 					*end-- = '0';
5324 				} else {
5325 					for (; val; val /= 10) {
5326 						*end-- = '0' + (val % 10);
5327 					}
5328 				}
5329 
5330 				if (i > 0)
5331 					*end-- = '.';
5332 			}
5333 			ASSERT(end + 1 >= base);
5334 
5335 		} else if (af == AF_INET6) {
5336 #if defined(__APPLE__)
5337 #define _S6_un __u6_addr
5338 #define _S6_u8 __u6_addr8
5339 #endif /* __APPLE__ */
5340 			struct in6_addr ip6;
5341 			int firstzero, tryzero, numzero, v6end;
5342 			uint16_t val;
5343 			const char digits[] = "0123456789abcdef";
5344 
5345 			/*
5346 			 * Stringify using RFC 1884 convention 2 - 16 bit
5347 			 * hexadecimal values with a zero-run compression.
5348 			 * Lower case hexadecimal digits are used.
5349 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5350 			 * The IPv4 embedded form is returned for inet_ntop,
5351 			 * just the IPv4 string is returned for inet_ntoa6.
5352 			 */
5353 
5354 			if (!dtrace_canload(tupregs[argi].dttk_value,
5355 				sizeof(struct in6_addr), mstate, vstate)) {
5356 				regs[rd] = 0;
5357 				break;
5358 			}
5359 
5360 			/*
5361 			 * Safely load the IPv6 address.
5362 			 */
5363 			dtrace_bcopy(
5364 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5365 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5366 
5367 			/*
5368 			 * Check an IPv6 string will fit in scratch.
5369 			 */
5370 			size = INET6_ADDRSTRLEN;
5371 			if (!DTRACE_INSCRATCH(mstate, size)) {
5372 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5373 				regs[rd] = 0;
5374 				break;
5375 			}
5376 			base = (char *)mstate->dtms_scratch_ptr;
5377 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5378 			*end-- = '\0';
5379 
5380 			/*
5381 			 * Find the longest run of 16 bit zero values
5382 			 * for the single allowed zero compression - "::".
5383 			 */
5384 			firstzero = -1;
5385 			tryzero = -1;
5386 			numzero = 1;
5387 			for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
5388 				if (ip6._S6_un._S6_u8[i] == 0 &&
5389 				    tryzero == -1 && i % 2 == 0) {
5390 					tryzero = i;
5391 					continue;
5392 				}
5393 
5394 				if (tryzero != -1 &&
5395 				    (ip6._S6_un._S6_u8[i] != 0 ||
5396 				    i == sizeof (struct in6_addr) - 1)) {
5397 
5398 					if (i - tryzero <= numzero) {
5399 						tryzero = -1;
5400 						continue;
5401 					}
5402 
5403 					firstzero = tryzero;
5404 					numzero = i - i % 2 - tryzero;
5405 					tryzero = -1;
5406 
5407 					if (ip6._S6_un._S6_u8[i] == 0 &&
5408 					    i == sizeof (struct in6_addr) - 1)
5409 						numzero += 2;
5410 				}
5411 			}
5412 			ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
5413 
5414 			/*
5415 			 * Check for an IPv4 embedded address.
5416 			 */
5417 			v6end = sizeof (struct in6_addr) - 2;
5418 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5419 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5420 				for (i = sizeof (struct in6_addr) - 1;
5421 				     i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
5422 					ASSERT(end >= base);
5423 
5424 					val = ip6._S6_un._S6_u8[i];
5425 
5426 					if (val == 0) {
5427 						*end-- = '0';
5428 					} else {
5429 						for (; val; val /= 10) {
5430 							*end-- = '0' + val % 10;
5431 						}
5432 					}
5433 
5434 					if (i > (int)DTRACE_V4MAPPED_OFFSET)
5435 						*end-- = '.';
5436 				}
5437 
5438 				if (subr == DIF_SUBR_INET_NTOA6)
5439 					goto inetout;
5440 
5441 				/*
5442 				 * Set v6end to skip the IPv4 address that
5443 				 * we have already stringified.
5444 				 */
5445 				v6end = 10;
5446 			}
5447 
5448 			/*
5449 			 * Build the IPv6 string by working through the
5450 			 * address in reverse.
5451 			 */
5452 			for (i = v6end; i >= 0; i -= 2) {
5453 				ASSERT(end >= base);
5454 
5455 				if (i == firstzero + numzero - 2) {
5456 					*end-- = ':';
5457 					*end-- = ':';
5458 					i -= numzero - 2;
5459 					continue;
5460 				}
5461 
5462 				if (i < 14 && i != firstzero - 2)
5463 					*end-- = ':';
5464 
5465 				val = (ip6._S6_un._S6_u8[i] << 8) +
5466 				    ip6._S6_un._S6_u8[i + 1];
5467 
5468 				if (val == 0) {
5469 					*end-- = '0';
5470 				} else {
5471 					for (; val; val /= 16) {
5472 						*end-- = digits[val % 16];
5473 					}
5474 				}
5475 			}
5476 			ASSERT(end + 1 >= base);
5477 
5478 #if defined(__APPLE__)
5479 #undef _S6_un
5480 #undef _S6_u8
5481 #endif /* __APPLE__ */
5482 		} else {
5483 			/*
5484 			 * The user didn't use AH_INET or AH_INET6.
5485 			 */
5486 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5487 			regs[rd] = 0;
5488 			break;
5489 		}
5490 
5491 inetout:	regs[rd] = (uintptr_t)end + 1;
5492 		mstate->dtms_scratch_ptr += size;
5493 		break;
5494 	}
5495 
5496 	case DIF_SUBR_JSON: {
5497 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5498 		uintptr_t json = tupregs[0].dttk_value;
5499 		size_t jsonlen = dtrace_strlen((char *)json, size);
5500 		uintptr_t elem = tupregs[1].dttk_value;
5501 		size_t elemlen = dtrace_strlen((char *)elem, size);
5502 
5503 		char *dest = (char *)mstate->dtms_scratch_ptr;
5504 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5505 		char *ee = elemlist;
5506 		int nelems = 1;
5507 		uintptr_t cur;
5508 
5509 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5510 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5511 			regs[rd] = 0;
5512 			break;
5513 		}
5514 
5515 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5516 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5517 			regs[rd] = 0;
5518 			break;
5519 		}
5520 
5521 		/*
5522 		 * Read the element selector and split it up into a packed list
5523 		 * of strings.
5524 		 */
5525 		for (cur = elem; cur < elem + elemlen; cur++) {
5526 			char cc = dtrace_load8(cur);
5527 
5528 			if (cur == elem && cc == '[') {
5529 				/*
5530 				 * If the first element selector key is
5531 				 * actually an array index then ignore the
5532 				 * bracket.
5533 				 */
5534 				continue;
5535 			}
5536 
5537 			if (cc == ']')
5538 				continue;
5539 
5540 			if (cc == '.' || cc == '[') {
5541 				nelems++;
5542 				cc = '\0';
5543 			}
5544 
5545 			*ee++ = cc;
5546 		}
5547 		*ee++ = '\0';
5548 
5549 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5550 		    nelems, dest)) != 0)
5551 			mstate->dtms_scratch_ptr += jsonlen + 1;
5552 		break;
5553 	}
5554 
5555 	case DIF_SUBR_TOUPPER:
5556 	case DIF_SUBR_TOLOWER: {
5557 		uintptr_t src = tupregs[0].dttk_value;
5558 		char *dest = (char *)mstate->dtms_scratch_ptr;
5559 		char lower, upper, base, c;
5560 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5561 		size_t len = dtrace_strlen((char*) src, size);
5562 		size_t i = 0;
5563 
5564 		lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
5565 		upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
5566 		base  = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
5567 
5568 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5569 			regs[rd] = 0;
5570 			break;
5571 		}
5572 
5573 		if (!DTRACE_INSCRATCH(mstate, size)) {
5574 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5575 			regs[rd] = 0;
5576 			break;
5577 		}
5578 
5579 		for (i = 0; i < size - 1; ++i) {
5580 			if ((c = dtrace_load8(src + i)) == '\0')
5581 				break;
5582 			if (c >= lower && c <= upper)
5583 				c = base + (c - lower);
5584 			dest[i] = c;
5585 		}
5586 
5587 		ASSERT(i < size);
5588 
5589 		dest[i] = '\0';
5590 		regs[rd] = (uintptr_t) dest;
5591 		mstate->dtms_scratch_ptr += size;
5592 
5593 		break;
5594 	}
5595 
5596 	case DIF_SUBR_STRIP:
5597 		if (!dtrace_is_valid_ptrauth_key(tupregs[1].dttk_value)) {
5598 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5599 			break;
5600 		}
5601 		regs[rd] = (uint64_t)dtrace_ptrauth_strip(
5602 		    (void*)tupregs[0].dttk_value, tupregs[1].dttk_value);
5603 		break;
5604 
5605 #if defined(__APPLE__)
5606 	case DIF_SUBR_VM_KERNEL_ADDRPERM: {
5607 		if (!dtrace_priv_kernel(state)) {
5608 			regs[rd] = 0;
5609 		} else {
5610 			regs[rd] = VM_KERNEL_ADDRPERM((vm_offset_t) tupregs[0].dttk_value);
5611 		}
5612 
5613 		break;
5614 	}
5615 
5616 	case DIF_SUBR_KDEBUG_TRACE: {
5617 		uint32_t debugid;
5618 		uintptr_t args[4] = {0};
5619 		int i;
5620 
5621 		if (nargs < 2 || nargs > 5) {
5622 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5623 			break;
5624 		}
5625 
5626 		if (dtrace_destructive_disallow ||
5627 		    !dtrace_priv_kernel_destructive(state)) {
5628 			return;
5629 		}
5630 
5631 		debugid = tupregs[0].dttk_value;
5632 		for (i = 0; i < nargs - 1; i++)
5633 			args[i] = tupregs[i + 1].dttk_value;
5634 
5635 		kernel_debug(debugid, args[0], args[1], args[2], args[3], 0);
5636 
5637 		break;
5638 	}
5639 
5640 	case DIF_SUBR_KDEBUG_TRACE_STRING: {
5641 		if (nargs != 3) {
5642 			break;
5643 		}
5644 
5645 		if (dtrace_destructive_disallow ||
5646 		    !dtrace_priv_kernel_destructive(state)) {
5647 			return;
5648 		}
5649 
5650 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5651 		uint32_t debugid = tupregs[0].dttk_value;
5652 		uint64_t str_id = tupregs[1].dttk_value;
5653 		uintptr_t src = tupregs[2].dttk_value;
5654 		size_t lim;
5655 		char buf[size];
5656 		char* str = NULL;
5657 
5658 		if (src != (uintptr_t)0) {
5659 			str = buf;
5660 			if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5661 				break;
5662 			}
5663 			dtrace_strcpy((void*)src, buf, size);
5664 		}
5665 
5666 		(void)kernel_debug_string(debugid, &str_id, str);
5667 		regs[rd] = str_id;
5668 
5669 		break;
5670 	}
5671 
5672 	case DIF_SUBR_MTONS:
5673 		absolutetime_to_nanoseconds(tupregs[0].dttk_value, &regs[rd]);
5674 
5675 		break;
5676 	case DIF_SUBR_PHYSMEM_READ: {
5677 #if DEBUG || DEVELOPMENT
5678 		if (dtrace_destructive_disallow ||
5679 		    !dtrace_priv_kernel_destructive(state)) {
5680 			return;
5681 		}
5682 		regs[rd] = dtrace_physmem_read(tupregs[0].dttk_value,
5683 		    tupregs[1].dttk_value);
5684 #else
5685 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5686 #endif /* DEBUG || DEVELOPMENT */
5687 		break;
5688 	}
5689 	case DIF_SUBR_PHYSMEM_WRITE: {
5690 #if DEBUG || DEVELOPMENT
5691 		if (dtrace_destructive_disallow ||
5692 		    !dtrace_priv_kernel_destructive(state)) {
5693 			return;
5694 		}
5695 
5696 		dtrace_physmem_write(tupregs[0].dttk_value,
5697 		    tupregs[1].dttk_value, (size_t)tupregs[2].dttk_value);
5698 #else
5699 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5700 #endif /* DEBUG || DEVELOPMENT */
5701 		break;
5702 	}
5703 
5704 	case DIF_SUBR_KVTOPHYS: {
5705 #if DEBUG || DEVELOPMENT
5706 		regs[rd] = kvtophys(tupregs[0].dttk_value);
5707 #else
5708 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5709 #endif /* DEBUG || DEVELOPMENT */
5710 		break;
5711 	}
5712 
5713 	case DIF_SUBR_LIVEDUMP: {
5714 #if DEBUG || DEVELOPMENT
5715 		if (dtrace_destructive_disallow ||
5716 		    !dtrace_priv_kernel_destructive(state)) {
5717 			break;
5718 		}
5719 
5720 		/* For the moment, there is only one type of livedump. */
5721 		if (nargs != 1 || tupregs[0].dttk_value != 0) {
5722 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5723 			break;
5724 		}
5725 
5726 		char *dest = (char *)mstate->dtms_scratch_ptr;
5727 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5728 
5729 		if (!DTRACE_INSCRATCH(mstate, size)) {
5730 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5731 			regs[rd] = 0;
5732 			break;
5733 		}
5734 
5735 		dtrace_livedump(dest, size);
5736 		regs[rd] = (uintptr_t) dest;
5737 		mstate->dtms_scratch_ptr += strlen(dest) + 1;
5738 #else
5739 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5740 #endif /* DEBUG || DEVELOPMENT */
5741 		break;
5742 	}
5743 #endif /* defined(__APPLE__) */
5744 
5745 	}
5746 }
5747 
5748 /*
5749  * Emulate the execution of DTrace IR instructions specified by the given
5750  * DIF object.  This function is deliberately void of assertions as all of
5751  * the necessary checks are handled by a call to dtrace_difo_validate().
5752  */
5753 static uint64_t
dtrace_dif_emulate(dtrace_difo_t * difo,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,dtrace_state_t * state)5754 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5755     dtrace_vstate_t *vstate, dtrace_state_t *state)
5756 {
5757 	const dif_instr_t *text = difo->dtdo_buf;
5758 	const uint_t textlen = difo->dtdo_len;
5759 	const char *strtab = difo->dtdo_strtab;
5760 	const uint64_t *inttab = difo->dtdo_inttab;
5761 
5762 	uint64_t rval = 0;
5763 	dtrace_statvar_t *svar;
5764 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5765 	dtrace_difv_t *v;
5766 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5767 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5768 
5769 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5770 	uint64_t regs[DIF_DIR_NREGS];
5771 	uint64_t *tmp;
5772 
5773 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5774 	int64_t cc_r;
5775 	uint_t pc = 0, id, opc = 0;
5776 	uint8_t ttop = 0;
5777 	dif_instr_t instr;
5778 	uint_t r1, r2, rd;
5779 
5780 	/*
5781 	 * We stash the current DIF object into the machine state: we need it
5782 	 * for subsequent access checking.
5783 	 */
5784 	mstate->dtms_difo = difo;
5785 
5786 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5787 
5788 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5789 		opc = pc;
5790 
5791 		instr = text[pc++];
5792 		r1 = DIF_INSTR_R1(instr);
5793 		r2 = DIF_INSTR_R2(instr);
5794 		rd = DIF_INSTR_RD(instr);
5795 
5796 		switch (DIF_INSTR_OP(instr)) {
5797 		case DIF_OP_OR:
5798 			regs[rd] = regs[r1] | regs[r2];
5799 			break;
5800 		case DIF_OP_XOR:
5801 			regs[rd] = regs[r1] ^ regs[r2];
5802 			break;
5803 		case DIF_OP_AND:
5804 			regs[rd] = regs[r1] & regs[r2];
5805 			break;
5806 		case DIF_OP_SLL:
5807 			regs[rd] = regs[r1] << regs[r2];
5808 			break;
5809 		case DIF_OP_SRL:
5810 			regs[rd] = regs[r1] >> regs[r2];
5811 			break;
5812 		case DIF_OP_SUB:
5813 			regs[rd] = regs[r1] - regs[r2];
5814 			break;
5815 		case DIF_OP_ADD:
5816 			regs[rd] = regs[r1] + regs[r2];
5817 			break;
5818 		case DIF_OP_MUL:
5819 			regs[rd] = regs[r1] * regs[r2];
5820 			break;
5821 		case DIF_OP_SDIV:
5822 			if (regs[r2] == 0) {
5823 				regs[rd] = 0;
5824 				*flags |= CPU_DTRACE_DIVZERO;
5825 			} else {
5826 				regs[rd] = (int64_t)regs[r1] /
5827 				    (int64_t)regs[r2];
5828 			}
5829 			break;
5830 
5831 		case DIF_OP_UDIV:
5832 			if (regs[r2] == 0) {
5833 				regs[rd] = 0;
5834 				*flags |= CPU_DTRACE_DIVZERO;
5835 			} else {
5836 				regs[rd] = regs[r1] / regs[r2];
5837 			}
5838 			break;
5839 
5840 		case DIF_OP_SREM:
5841 			if (regs[r2] == 0) {
5842 				regs[rd] = 0;
5843 				*flags |= CPU_DTRACE_DIVZERO;
5844 			} else {
5845 				regs[rd] = (int64_t)regs[r1] %
5846 				    (int64_t)regs[r2];
5847 			}
5848 			break;
5849 
5850 		case DIF_OP_UREM:
5851 			if (regs[r2] == 0) {
5852 				regs[rd] = 0;
5853 				*flags |= CPU_DTRACE_DIVZERO;
5854 			} else {
5855 				regs[rd] = regs[r1] % regs[r2];
5856 			}
5857 			break;
5858 
5859 		case DIF_OP_NOT:
5860 			regs[rd] = ~regs[r1];
5861 			break;
5862 		case DIF_OP_MOV:
5863 			regs[rd] = regs[r1];
5864 			break;
5865 		case DIF_OP_CMP:
5866 			cc_r = regs[r1] - regs[r2];
5867 			cc_n = cc_r < 0;
5868 			cc_z = cc_r == 0;
5869 			cc_v = 0;
5870 			cc_c = regs[r1] < regs[r2];
5871 			break;
5872 		case DIF_OP_TST:
5873 			cc_n = cc_v = cc_c = 0;
5874 			cc_z = regs[r1] == 0;
5875 			break;
5876 		case DIF_OP_BA:
5877 			pc = DIF_INSTR_LABEL(instr);
5878 			break;
5879 		case DIF_OP_BE:
5880 			if (cc_z)
5881 				pc = DIF_INSTR_LABEL(instr);
5882 			break;
5883 		case DIF_OP_BNE:
5884 			if (cc_z == 0)
5885 				pc = DIF_INSTR_LABEL(instr);
5886 			break;
5887 		case DIF_OP_BG:
5888 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5889 				pc = DIF_INSTR_LABEL(instr);
5890 			break;
5891 		case DIF_OP_BGU:
5892 			if ((cc_c | cc_z) == 0)
5893 				pc = DIF_INSTR_LABEL(instr);
5894 			break;
5895 		case DIF_OP_BGE:
5896 			if ((cc_n ^ cc_v) == 0)
5897 				pc = DIF_INSTR_LABEL(instr);
5898 			break;
5899 		case DIF_OP_BGEU:
5900 			if (cc_c == 0)
5901 				pc = DIF_INSTR_LABEL(instr);
5902 			break;
5903 		case DIF_OP_BL:
5904 			if (cc_n ^ cc_v)
5905 				pc = DIF_INSTR_LABEL(instr);
5906 			break;
5907 		case DIF_OP_BLU:
5908 			if (cc_c)
5909 				pc = DIF_INSTR_LABEL(instr);
5910 			break;
5911 		case DIF_OP_BLE:
5912 			if (cc_z | (cc_n ^ cc_v))
5913 				pc = DIF_INSTR_LABEL(instr);
5914 			break;
5915 		case DIF_OP_BLEU:
5916 			if (cc_c | cc_z)
5917 				pc = DIF_INSTR_LABEL(instr);
5918 			break;
5919 		case DIF_OP_RLDSB:
5920 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5921 				*flags |= CPU_DTRACE_KPRIV;
5922 				*illval = regs[r1];
5923 				break;
5924 			}
5925 			OS_FALLTHROUGH;
5926 		case DIF_OP_LDSB:
5927 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5928 			break;
5929 		case DIF_OP_RLDSH:
5930 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5931 				*flags |= CPU_DTRACE_KPRIV;
5932 				*illval = regs[r1];
5933 				break;
5934 			}
5935 			OS_FALLTHROUGH;
5936 		case DIF_OP_LDSH:
5937 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5938 			break;
5939 		case DIF_OP_RLDSW:
5940 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5941 				*flags |= CPU_DTRACE_KPRIV;
5942 				*illval = regs[r1];
5943 				break;
5944 			}
5945 			OS_FALLTHROUGH;
5946 		case DIF_OP_LDSW:
5947 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5948 			break;
5949 		case DIF_OP_RLDUB:
5950 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5951 				*flags |= CPU_DTRACE_KPRIV;
5952 				*illval = regs[r1];
5953 				break;
5954 			}
5955 			OS_FALLTHROUGH;
5956 		case DIF_OP_LDUB:
5957 			regs[rd] = dtrace_load8(regs[r1]);
5958 			break;
5959 		case DIF_OP_RLDUH:
5960 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5961 				*flags |= CPU_DTRACE_KPRIV;
5962 				*illval = regs[r1];
5963 				break;
5964 			}
5965 			OS_FALLTHROUGH;
5966 		case DIF_OP_LDUH:
5967 			regs[rd] = dtrace_load16(regs[r1]);
5968 			break;
5969 		case DIF_OP_RLDUW:
5970 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5971 				*flags |= CPU_DTRACE_KPRIV;
5972 				*illval = regs[r1];
5973 				break;
5974 			}
5975 			OS_FALLTHROUGH;
5976 		case DIF_OP_LDUW:
5977 			regs[rd] = dtrace_load32(regs[r1]);
5978 			break;
5979 		case DIF_OP_RLDX:
5980 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5981 				*flags |= CPU_DTRACE_KPRIV;
5982 				*illval = regs[r1];
5983 				break;
5984 			}
5985 			OS_FALLTHROUGH;
5986 		case DIF_OP_LDX:
5987 			regs[rd] = dtrace_load64(regs[r1]);
5988 			break;
5989 /*
5990  * Darwin 32-bit kernel may fetch from 64-bit user.
5991  * Do not cast regs to uintptr_t
5992  * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
5993  * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
5994  */
5995 		case DIF_OP_ULDSB:
5996 			regs[rd] = (int8_t)
5997 			    dtrace_fuword8(regs[r1]);
5998 			break;
5999 		case DIF_OP_ULDSH:
6000 			regs[rd] = (int16_t)
6001 			    dtrace_fuword16(regs[r1]);
6002 			break;
6003 		case DIF_OP_ULDSW:
6004 			regs[rd] = (int32_t)
6005 			    dtrace_fuword32(regs[r1]);
6006 			break;
6007 		case DIF_OP_ULDUB:
6008 			regs[rd] =
6009 			    dtrace_fuword8(regs[r1]);
6010 			break;
6011 		case DIF_OP_ULDUH:
6012 			regs[rd] =
6013 			    dtrace_fuword16(regs[r1]);
6014 			break;
6015 		case DIF_OP_ULDUW:
6016 			regs[rd] =
6017 			    dtrace_fuword32(regs[r1]);
6018 			break;
6019 		case DIF_OP_ULDX:
6020 			regs[rd] =
6021 			    dtrace_fuword64(regs[r1]);
6022 			break;
6023 		case DIF_OP_RET:
6024 			rval = regs[rd];
6025 			pc = textlen;
6026 			break;
6027 		case DIF_OP_NOP:
6028 			break;
6029 		case DIF_OP_SETX:
6030 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6031 			break;
6032 		case DIF_OP_SETS:
6033 			regs[rd] = (uint64_t)(uintptr_t)
6034 			    (strtab + DIF_INSTR_STRING(instr));
6035 			break;
6036 		case DIF_OP_SCMP: {
6037 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6038 			uintptr_t s1 = regs[r1];
6039 			uintptr_t s2 = regs[r2];
6040 			size_t lim1 = sz, lim2 = sz;
6041 
6042 			if (s1 != 0 &&
6043 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6044 				break;
6045 			if (s2 != 0 &&
6046 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6047 				break;
6048 
6049 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6050 				MIN(lim1, lim2));
6051 
6052 			cc_n = cc_r < 0;
6053 			cc_z = cc_r == 0;
6054 			cc_v = cc_c = 0;
6055 			break;
6056 		}
6057 		case DIF_OP_LDGA:
6058 			regs[rd] = dtrace_dif_variable(mstate, state,
6059 			    r1, regs[r2]);
6060 			break;
6061 		case DIF_OP_LDGS:
6062 			id = DIF_INSTR_VAR(instr);
6063 
6064 			if (id >= DIF_VAR_OTHER_UBASE) {
6065 				uintptr_t a;
6066 
6067 				id -= DIF_VAR_OTHER_UBASE;
6068 				svar = vstate->dtvs_globals[id];
6069 				ASSERT(svar != NULL);
6070 				v = &svar->dtsv_var;
6071 
6072 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6073 					regs[rd] = svar->dtsv_data;
6074 					break;
6075 				}
6076 
6077 				a = (uintptr_t)svar->dtsv_data;
6078 
6079 				if (*(uint8_t *)a == UINT8_MAX) {
6080 					/*
6081 					 * If the 0th byte is set to UINT8_MAX
6082 					 * then this is to be treated as a
6083 					 * reference to a NULL variable.
6084 					 */
6085 					regs[rd] = 0;
6086 				} else {
6087 					regs[rd] = a + sizeof (uint64_t);
6088 				}
6089 
6090 				break;
6091 			}
6092 
6093 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6094 			break;
6095 
6096 		case DIF_OP_STGS:
6097 			id = DIF_INSTR_VAR(instr);
6098 
6099 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6100 			id -= DIF_VAR_OTHER_UBASE;
6101 
6102 			VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6103 			svar = vstate->dtvs_globals[id];
6104 			ASSERT(svar != NULL);
6105 			v = &svar->dtsv_var;
6106 
6107 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6108 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6109 				size_t lim = 0;
6110 
6111 				ASSERT(a != 0);
6112 				ASSERT(svar->dtsv_size != 0);
6113 
6114 				if (regs[rd] == 0) {
6115 					*(uint8_t *)a = UINT8_MAX;
6116 					break;
6117 				} else {
6118 					*(uint8_t *)a = 0;
6119 					a += sizeof (uint64_t);
6120 				}
6121 				if (!dtrace_vcanload(
6122 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6123 					&lim, mstate, vstate))
6124 					break;
6125 
6126 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6127 				    (void *)a, &v->dtdv_type, lim);
6128 				break;
6129 			}
6130 
6131 			svar->dtsv_data = regs[rd];
6132 			break;
6133 
6134 		case DIF_OP_LDTA:
6135 			/*
6136 			 * There are no DTrace built-in thread-local arrays at
6137 			 * present.  This opcode is saved for future work.
6138 			 */
6139 			*flags |= CPU_DTRACE_ILLOP;
6140 			regs[rd] = 0;
6141 			break;
6142 
6143 		case DIF_OP_LDLS:
6144 			id = DIF_INSTR_VAR(instr);
6145 
6146 			if (id < DIF_VAR_OTHER_UBASE) {
6147 				/*
6148 				 * For now, this has no meaning.
6149 				 */
6150 				regs[rd] = 0;
6151 				break;
6152 			}
6153 
6154 			id -= DIF_VAR_OTHER_UBASE;
6155 
6156 			ASSERT(id < (uint_t)vstate->dtvs_nlocals);
6157 			ASSERT(vstate->dtvs_locals != NULL);
6158 			svar = vstate->dtvs_locals[id];
6159 			ASSERT(svar != NULL);
6160 			v = &svar->dtsv_var;
6161 
6162 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6163 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6164 				size_t sz = v->dtdv_type.dtdt_size;
6165 
6166 				sz += sizeof (uint64_t);
6167 				ASSERT(svar->dtsv_size == (int)NCPU * sz);
6168 				a += CPU->cpu_id * sz;
6169 
6170 				if (*(uint8_t *)a == UINT8_MAX) {
6171 					/*
6172 					 * If the 0th byte is set to UINT8_MAX
6173 					 * then this is to be treated as a
6174 					 * reference to a NULL variable.
6175 					 */
6176 					regs[rd] = 0;
6177 				} else {
6178 					regs[rd] = a + sizeof (uint64_t);
6179 				}
6180 
6181 				break;
6182 			}
6183 
6184 			ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
6185 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6186 			regs[rd] = tmp[CPU->cpu_id];
6187 			break;
6188 
6189 		case DIF_OP_STLS:
6190 			id = DIF_INSTR_VAR(instr);
6191 
6192 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6193 			id -= DIF_VAR_OTHER_UBASE;
6194 			VERIFY(id < (uint_t)vstate->dtvs_nlocals);
6195 			ASSERT(vstate->dtvs_locals != NULL);
6196 			svar = vstate->dtvs_locals[id];
6197 			ASSERT(svar != NULL);
6198 			v = &svar->dtsv_var;
6199 
6200 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6201 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6202 				size_t sz = v->dtdv_type.dtdt_size;
6203 				size_t lim = 0;
6204 
6205 				sz += sizeof (uint64_t);
6206 				ASSERT(svar->dtsv_size == (int)NCPU * sz);
6207 				a += CPU->cpu_id * sz;
6208 
6209 				if (regs[rd] == 0) {
6210 					*(uint8_t *)a = UINT8_MAX;
6211 					break;
6212 				} else {
6213 					*(uint8_t *)a = 0;
6214 					a += sizeof (uint64_t);
6215 				}
6216 
6217 				if (!dtrace_vcanload(
6218 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6219 				    &lim, mstate, vstate))
6220 					break;
6221 
6222 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6223 				    (void *)a, &v->dtdv_type, lim);
6224 				break;
6225 			}
6226 
6227 			ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
6228 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6229 			tmp[CPU->cpu_id] = regs[rd];
6230 			break;
6231 
6232 		case DIF_OP_LDTS: {
6233 			dtrace_dynvar_t *dvar;
6234 			dtrace_key_t *key;
6235 
6236 			id = DIF_INSTR_VAR(instr);
6237 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6238 			id -= DIF_VAR_OTHER_UBASE;
6239 			v = &vstate->dtvs_tlocals[id];
6240 
6241 			key = &tupregs[DIF_DTR_NREGS];
6242 			key[0].dttk_value = (uint64_t)id;
6243 			key[0].dttk_size = 0;
6244 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6245 			key[1].dttk_size = 0;
6246 
6247 			dvar = dtrace_dynvar(dstate, 2, key,
6248 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6249 			    mstate, vstate);
6250 
6251 			if (dvar == NULL) {
6252 				regs[rd] = 0;
6253 				break;
6254 			}
6255 
6256 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6257 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6258 			} else {
6259 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6260 			}
6261 
6262 			break;
6263 		}
6264 
6265 		case DIF_OP_STTS: {
6266 			dtrace_dynvar_t *dvar;
6267 			dtrace_key_t *key;
6268 
6269 			id = DIF_INSTR_VAR(instr);
6270 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6271 			id -= DIF_VAR_OTHER_UBASE;
6272 			VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6273 
6274 			key = &tupregs[DIF_DTR_NREGS];
6275 			key[0].dttk_value = (uint64_t)id;
6276 			key[0].dttk_size = 0;
6277 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6278 			key[1].dttk_size = 0;
6279 			v = &vstate->dtvs_tlocals[id];
6280 
6281 			dvar = dtrace_dynvar(dstate, 2, key,
6282 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6283 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6284 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6285 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6286 
6287 			/*
6288 			 * Given that we're storing to thread-local data,
6289 			 * we need to flush our predicate cache.
6290 			 */
6291 			dtrace_set_thread_predcache(current_thread(), 0);
6292 
6293 			if (dvar == NULL)
6294 				break;
6295 
6296 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6297 				size_t lim = 0;
6298 
6299 				if (!dtrace_vcanload(
6300 				    (void *)(uintptr_t)regs[rd],
6301 				    &v->dtdv_type, &lim, mstate, vstate))
6302 					break;
6303 
6304 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6305 				    dvar->dtdv_data, &v->dtdv_type, lim);
6306 			} else {
6307 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6308 			}
6309 
6310 			break;
6311 		}
6312 
6313 		case DIF_OP_SRA:
6314 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6315 			break;
6316 
6317 		case DIF_OP_CALL:
6318 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6319 			    regs, tupregs, ttop, mstate, state);
6320 			break;
6321 
6322 		case DIF_OP_PUSHTR:
6323 			if (ttop == DIF_DTR_NREGS) {
6324 				*flags |= CPU_DTRACE_TUPOFLOW;
6325 				break;
6326 			}
6327 
6328 			if (r1 == DIF_TYPE_STRING) {
6329 				/*
6330 				 * If this is a string type and the size is 0,
6331 				 * we'll use the system-wide default string
6332 				 * size.  Note that we are _not_ looking at
6333 				 * the value of the DTRACEOPT_STRSIZE option;
6334 				 * had this been set, we would expect to have
6335 				 * a non-zero size value in the "pushtr".
6336 				 */
6337 				tupregs[ttop].dttk_size =
6338 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6339 				    regs[r2] ? regs[r2] :
6340 				    dtrace_strsize_default) + 1;
6341 			} else {
6342 				if (regs[r2] > LONG_MAX) {
6343 					*flags |= CPU_DTRACE_ILLOP;
6344 					break;
6345 				}
6346 				tupregs[ttop].dttk_size = regs[r2];
6347 			}
6348 
6349 			tupregs[ttop++].dttk_value = regs[rd];
6350 			break;
6351 
6352 		case DIF_OP_PUSHTV:
6353 			if (ttop == DIF_DTR_NREGS) {
6354 				*flags |= CPU_DTRACE_TUPOFLOW;
6355 				break;
6356 			}
6357 
6358 			tupregs[ttop].dttk_value = regs[rd];
6359 			tupregs[ttop++].dttk_size = 0;
6360 			break;
6361 
6362 		case DIF_OP_POPTS:
6363 			if (ttop != 0)
6364 				ttop--;
6365 			break;
6366 
6367 		case DIF_OP_FLUSHTS:
6368 			ttop = 0;
6369 			break;
6370 
6371 		case DIF_OP_LDGAA:
6372 		case DIF_OP_LDTAA: {
6373 			dtrace_dynvar_t *dvar;
6374 			dtrace_key_t *key = tupregs;
6375 			uint_t nkeys = ttop;
6376 
6377 			id = DIF_INSTR_VAR(instr);
6378 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6379 			id -= DIF_VAR_OTHER_UBASE;
6380 
6381 			key[nkeys].dttk_value = (uint64_t)id;
6382 			key[nkeys++].dttk_size = 0;
6383 
6384 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6385 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6386 				key[nkeys++].dttk_size = 0;
6387 				VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6388 				v = &vstate->dtvs_tlocals[id];
6389 			} else {
6390 				VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6391 				v = &vstate->dtvs_globals[id]->dtsv_var;
6392 			}
6393 
6394 			dvar = dtrace_dynvar(dstate, nkeys, key,
6395 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6396 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6397 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6398 
6399 			if (dvar == NULL) {
6400 				regs[rd] = 0;
6401 				break;
6402 			}
6403 
6404 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6405 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6406 			} else {
6407 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6408 			}
6409 
6410 			break;
6411 		}
6412 
6413 		case DIF_OP_STGAA:
6414 		case DIF_OP_STTAA: {
6415 			dtrace_dynvar_t *dvar;
6416 			dtrace_key_t *key = tupregs;
6417 			uint_t nkeys = ttop;
6418 
6419 			id = DIF_INSTR_VAR(instr);
6420 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6421 			id -= DIF_VAR_OTHER_UBASE;
6422 
6423 			key[nkeys].dttk_value = (uint64_t)id;
6424 			key[nkeys++].dttk_size = 0;
6425 
6426 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6427 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6428 				key[nkeys++].dttk_size = 0;
6429 				VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6430 				v = &vstate->dtvs_tlocals[id];
6431 			} else {
6432 				VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6433 				v = &vstate->dtvs_globals[id]->dtsv_var;
6434 			}
6435 
6436 			dvar = dtrace_dynvar(dstate, nkeys, key,
6437 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6438 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6439 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6440 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6441 
6442 			if (dvar == NULL)
6443 				break;
6444 
6445 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6446 				size_t lim = 0;
6447 
6448 				if (!dtrace_vcanload(
6449 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6450 				    &lim, mstate, vstate))
6451 					break;
6452 
6453 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6454 				    dvar->dtdv_data, &v->dtdv_type, lim);
6455 			} else {
6456 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6457 			}
6458 
6459 			break;
6460 		}
6461 
6462 		case DIF_OP_ALLOCS: {
6463 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6464 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6465 
6466 			/*
6467 			 * Rounding up the user allocation size could have
6468 			 * overflowed large, bogus allocations (like -1ULL) to
6469 			 * 0.
6470 			 */
6471 			if (size < regs[r1] ||
6472 			    !DTRACE_INSCRATCH(mstate, size)) {
6473 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6474 				regs[rd] = 0;
6475 				break;
6476 			}
6477 
6478 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6479 				mstate->dtms_scratch_ptr += size;
6480 				regs[rd] = ptr;
6481 			break;
6482 		}
6483 
6484 		case DIF_OP_COPYS:
6485 			if (!dtrace_canstore(regs[rd], regs[r2],
6486 			    mstate, vstate)) {
6487 				*flags |= CPU_DTRACE_BADADDR;
6488 				*illval = regs[rd];
6489 				break;
6490 			}
6491 
6492 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6493 				break;
6494 
6495 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6496 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6497 			break;
6498 
6499 		case DIF_OP_STB:
6500 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6501 				*flags |= CPU_DTRACE_BADADDR;
6502 				*illval = regs[rd];
6503 				break;
6504 			}
6505 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6506 			break;
6507 
6508 		case DIF_OP_STH:
6509 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6510 				*flags |= CPU_DTRACE_BADADDR;
6511 				*illval = regs[rd];
6512 				break;
6513 			}
6514 			if (regs[rd] & 1) {
6515 				*flags |= CPU_DTRACE_BADALIGN;
6516 				*illval = regs[rd];
6517 				break;
6518 			}
6519 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6520 			break;
6521 
6522 		case DIF_OP_STW:
6523 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6524 				*flags |= CPU_DTRACE_BADADDR;
6525 				*illval = regs[rd];
6526 				break;
6527 			}
6528 			if (regs[rd] & 3) {
6529 				*flags |= CPU_DTRACE_BADALIGN;
6530 				*illval = regs[rd];
6531 				break;
6532 			}
6533 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6534 			break;
6535 
6536 		case DIF_OP_STX:
6537 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6538 				*flags |= CPU_DTRACE_BADADDR;
6539 				*illval = regs[rd];
6540 				break;
6541 			}
6542 
6543 			/*
6544 			* Darwin kmem_zalloc() called from
6545 			* dtrace_difo_init() is 4-byte aligned.
6546 			*/
6547 			if (regs[rd] & 3) {
6548 				*flags |= CPU_DTRACE_BADALIGN;
6549 				*illval = regs[rd];
6550 				break;
6551 			}
6552 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6553 			break;
6554 		case DIF_OP_STRIP:
6555 			regs[rd] = (uint64_t)dtrace_ptrauth_strip(
6556 			    (void*)regs[r1], r2);
6557 			break;
6558 		}
6559 	}
6560 
6561 	if (!(*flags & CPU_DTRACE_FAULT))
6562 		return (rval);
6563 
6564 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6565 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6566 
6567 	return (0);
6568 }
6569 
6570 __attribute__((noinline))
6571 static void
dtrace_action_breakpoint(dtrace_ecb_t * ecb)6572 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6573 {
6574 	dtrace_probe_t *probe = ecb->dte_probe;
6575 	dtrace_provider_t *prov = probe->dtpr_provider;
6576 	char c[DTRACE_FULLNAMELEN + 80], *str;
6577 	const char *msg = "dtrace: breakpoint action at probe ";
6578 	const char *ecbmsg = " (ecb ";
6579 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6580 	uintptr_t val = (uintptr_t)ecb;
6581 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6582 
6583 	if (dtrace_destructive_disallow)
6584 		return;
6585 
6586 	/*
6587 	 * It's impossible to be taking action on the NULL probe.
6588 	 */
6589 	ASSERT(probe != NULL);
6590 
6591 	/*
6592 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6593 	 * print the provider name, module name, function name and name of
6594 	 * the probe, along with the hex address of the ECB with the breakpoint
6595 	 * action -- all of which we must place in the character buffer by
6596 	 * hand.
6597 	 */
6598 	while (*msg != '\0')
6599 		c[i++] = *msg++;
6600 
6601 	for (str = prov->dtpv_name; *str != '\0'; str++)
6602 		c[i++] = *str;
6603 	c[i++] = ':';
6604 
6605 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6606 		c[i++] = *str;
6607 	c[i++] = ':';
6608 
6609 	for (str = probe->dtpr_func; *str != '\0'; str++)
6610 		c[i++] = *str;
6611 	c[i++] = ':';
6612 
6613 	for (str = probe->dtpr_name; *str != '\0'; str++)
6614 		c[i++] = *str;
6615 
6616 	while (*ecbmsg != '\0')
6617 		c[i++] = *ecbmsg++;
6618 
6619 	while (shift >= 0) {
6620 		mask = (uintptr_t)0xf << shift;
6621 
6622 		if (val >= ((uintptr_t)1 << shift))
6623 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6624 		shift -= 4;
6625 	}
6626 
6627 	c[i++] = ')';
6628 	c[i] = '\0';
6629 
6630 	debug_enter(c);
6631 }
6632 
6633 __attribute__((noinline))
6634 static void
dtrace_action_panic(dtrace_ecb_t * ecb)6635 dtrace_action_panic(dtrace_ecb_t *ecb)
6636 {
6637 	dtrace_probe_t *probe = ecb->dte_probe;
6638 
6639 	/*
6640 	 * It's impossible to be taking action on the NULL probe.
6641 	 */
6642 	ASSERT(probe != NULL);
6643 
6644 	if (dtrace_destructive_disallow)
6645 		return;
6646 
6647 	if (dtrace_panicked != NULL)
6648 		return;
6649 
6650 	if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
6651 		return;
6652 
6653 	/*
6654 	 * We won the right to panic.  (We want to be sure that only one
6655 	 * thread calls panic() from dtrace_probe(), and that panic() is
6656 	 * called exactly once.)
6657 	 */
6658 	panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6659 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6660 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6661 
6662 	/*
6663 	 * APPLE NOTE: this was for an old Mac OS X debug feature
6664 	 * allowing a return from panic().  Revisit someday.
6665 	 */
6666 	dtrace_panicked = NULL;
6667 }
6668 
6669 static void
dtrace_action_raise(uint64_t sig)6670 dtrace_action_raise(uint64_t sig)
6671 {
6672 	if (dtrace_destructive_disallow)
6673 		return;
6674 
6675 	if (sig >= NSIG) {
6676 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6677 		return;
6678 	}
6679 
6680 	/*
6681 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6682 	 * invocations of the raise() action.
6683 	 */
6684 
6685 	uthread_t uthread = current_uthread();
6686 
6687 	if (uthread && uthread->t_dtrace_sig == 0) {
6688 		uthread->t_dtrace_sig = sig;
6689 		act_set_astbsd(current_thread());
6690 	}
6691 }
6692 
6693 static void
dtrace_action_stop(void)6694 dtrace_action_stop(void)
6695 {
6696 	if (dtrace_destructive_disallow)
6697 		return;
6698 
6699         uthread_t uthread = current_uthread();
6700 	if (uthread) {
6701 		/*
6702 		 * The currently running process will be set to task_suspend
6703 		 * when it next leaves the kernel.
6704 		*/
6705 		uthread->t_dtrace_stop = 1;
6706 		act_set_astbsd(current_thread());
6707 	}
6708 }
6709 
6710 
6711 /*
6712  * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
6713  * Both activate only when the currently running process next leaves the
6714  * kernel.
6715  */
6716 static void
dtrace_action_pidresume(uint64_t pid)6717 dtrace_action_pidresume(uint64_t pid)
6718 {
6719 	if (dtrace_destructive_disallow)
6720 		return;
6721 
6722 	if (kauth_cred_issuser(kauth_cred_get()) == 0) {
6723 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6724 		return;
6725 	}
6726         uthread_t uthread = current_uthread();
6727 
6728 	/*
6729 	 * When the currently running process leaves the kernel, it attempts to
6730 	 * task_resume the process (denoted by pid), if that pid appears to have
6731 	 * been stopped by dtrace_action_stop().
6732 	 * The currently running process has a pidresume() queue depth of 1 --
6733 	 * subsequent invocations of the pidresume() action are ignored.
6734 	 */
6735 
6736 	if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
6737 		uthread->t_dtrace_resumepid = pid;
6738 		act_set_astbsd(current_thread());
6739 	}
6740 }
6741 
6742 __attribute__((noinline))
6743 static void
dtrace_action_chill(dtrace_mstate_t * mstate,hrtime_t val)6744 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6745 {
6746 	hrtime_t now;
6747 	volatile uint16_t *flags;
6748 	dtrace_cpu_t *cpu = CPU;
6749 
6750 	if (dtrace_destructive_disallow)
6751 		return;
6752 
6753 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6754 
6755 	now = dtrace_gethrtime();
6756 
6757 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6758 		/*
6759 		 * We need to advance the mark to the current time.
6760 		 */
6761 		cpu->cpu_dtrace_chillmark = now;
6762 		cpu->cpu_dtrace_chilled = 0;
6763 	}
6764 
6765 	/*
6766 	 * Now check to see if the requested chill time would take us over
6767 	 * the maximum amount of time allowed in the chill interval.  (Or
6768 	 * worse, if the calculation itself induces overflow.)
6769 	 */
6770 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6771 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6772 		*flags |= CPU_DTRACE_ILLOP;
6773 		return;
6774 	}
6775 
6776 	while (dtrace_gethrtime() - now < val)
6777 		continue;
6778 
6779 	/*
6780 	 * Normally, we assure that the value of the variable "timestamp" does
6781 	 * not change within an ECB.  The presence of chill() represents an
6782 	 * exception to this rule, however.
6783 	 */
6784 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6785 	cpu->cpu_dtrace_chilled += val;
6786 }
6787 
6788 __attribute__((noinline))
6789 static void
dtrace_action_ustack(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t * buf,uint64_t arg)6790 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6791     uint64_t *buf, uint64_t arg)
6792 {
6793 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6794 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6795 	uint64_t *pcs = &buf[1], *fps;
6796 	char *str = (char *)&pcs[nframes];
6797 	int size, offs = 0, i, j;
6798 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6799 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6800 	char *sym;
6801 
6802 	/*
6803 	 * Should be taking a faster path if string space has not been
6804 	 * allocated.
6805 	 */
6806 	ASSERT(strsize != 0);
6807 
6808 	/*
6809 	 * We will first allocate some temporary space for the frame pointers.
6810 	 */
6811 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6812 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6813 	    (nframes * sizeof (uint64_t));
6814 
6815 	if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
6816 		/*
6817 		 * Not enough room for our frame pointers -- need to indicate
6818 		 * that we ran out of scratch space.
6819 		 */
6820 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6821 		return;
6822 	}
6823 
6824 	mstate->dtms_scratch_ptr += size;
6825 	saved = mstate->dtms_scratch_ptr;
6826 
6827 	/*
6828 	 * Now get a stack with both program counters and frame pointers.
6829 	 */
6830 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6831 	dtrace_getufpstack(buf, fps, nframes + 1);
6832 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6833 
6834 	/*
6835 	 * If that faulted, we're cooked.
6836 	 */
6837 	if (*flags & CPU_DTRACE_FAULT)
6838 		goto out;
6839 
6840 	/*
6841 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6842 	 * each iteration, we restore the scratch pointer.
6843 	 */
6844 	for (i = 0; i < nframes; i++) {
6845 		mstate->dtms_scratch_ptr = saved;
6846 
6847 		if (offs >= strsize)
6848 			break;
6849 
6850 		sym = (char *)(uintptr_t)dtrace_helper(
6851 		    DTRACE_HELPER_ACTION_USTACK,
6852 		    mstate, state, pcs[i], fps[i]);
6853 
6854 		/*
6855 		 * If we faulted while running the helper, we're going to
6856 		 * clear the fault and null out the corresponding string.
6857 		 */
6858 		if (*flags & CPU_DTRACE_FAULT) {
6859 			*flags &= ~CPU_DTRACE_FAULT;
6860 			str[offs++] = '\0';
6861 			continue;
6862 		}
6863 
6864 		if (sym == NULL) {
6865 			str[offs++] = '\0';
6866 			continue;
6867 		}
6868 
6869 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6870 
6871 		/*
6872 		 * Now copy in the string that the helper returned to us.
6873 		 */
6874 		for (j = 0; offs + j < strsize; j++) {
6875 			if ((str[offs + j] = sym[j]) == '\0')
6876 				break;
6877 		}
6878 
6879 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6880 
6881 		offs += j + 1;
6882 	}
6883 
6884 	if (offs >= strsize) {
6885 		/*
6886 		 * If we didn't have room for all of the strings, we don't
6887 		 * abort processing -- this needn't be a fatal error -- but we
6888 		 * still want to increment a counter (dts_stkstroverflows) to
6889 		 * allow this condition to be warned about.  (If this is from
6890 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6891 		 */
6892 		dtrace_error(&state->dts_stkstroverflows);
6893 	}
6894 
6895 	while (offs < strsize)
6896 		str[offs++] = '\0';
6897 
6898 out:
6899 	mstate->dtms_scratch_ptr = old;
6900 }
6901 
6902 __attribute__((noinline))
6903 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)6904 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6905     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6906 {
6907 	volatile uint16_t *flags;
6908 	uint64_t val = *valp;
6909 	size_t valoffs = *valoffsp;
6910 
6911 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6912 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6913 
6914 	/*
6915 	 * If this is a string, we're going to only load until we find the zero
6916 	 * byte -- after which we'll store zero bytes.
6917 	 */
6918 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6919 		char c = '\0' + 1;
6920 		size_t s;
6921 
6922 		for (s = 0; s < size; s++) {
6923 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6924 				c = dtrace_load8(val++);
6925 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6926 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6927 				c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6928 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6929 				if (*flags & CPU_DTRACE_FAULT)
6930 					break;
6931 			}
6932 
6933 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6934 
6935 			if (c == '\0' && intuple)
6936 				break;
6937 		}
6938 	} else {
6939 		uint8_t c;
6940 		while (valoffs < end) {
6941 			if (dtkind == DIF_TF_BYREF) {
6942 				c = dtrace_load8(val++);
6943 			} else if (dtkind == DIF_TF_BYUREF) {
6944 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6945 				c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6946 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6947 				if (*flags & CPU_DTRACE_FAULT)
6948 					break;
6949 			}
6950 
6951 			DTRACE_STORE(uint8_t, tomax,
6952 			    valoffs++, c);
6953 		}
6954 	}
6955 
6956 	*valp = val;
6957 	*valoffsp = valoffs;
6958 }
6959 
6960 /*
6961  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
6962  * defined, we also assert that we are not recursing unless the probe ID is an
6963  * error probe.
6964  */
6965 static dtrace_icookie_t
dtrace_probe_enter(dtrace_id_t id)6966 dtrace_probe_enter(dtrace_id_t id)
6967 {
6968 	thread_t thread = current_thread();
6969 	uint16_t inprobe;
6970 
6971 	dtrace_icookie_t cookie;
6972 
6973 	cookie = dtrace_interrupt_disable();
6974 
6975 	/*
6976 	 * Unless this is an ERROR probe, we are not allowed to recurse in
6977 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
6978 	 * function is instrumented that should not have been instrumented or
6979 	 * that the ordering guarantee of the records will be violated,
6980 	 * resulting in unexpected output. If there is an exception to this
6981 	 * assertion, a new case should be added.
6982 	 */
6983 	inprobe = dtrace_get_thread_inprobe(thread);
6984 	VERIFY(inprobe == 0 ||
6985 	    id == dtrace_probeid_error);
6986 	ASSERT(inprobe < UINT16_MAX);
6987 	dtrace_set_thread_inprobe(thread, inprobe + 1);
6988 
6989 	return (cookie);
6990 }
6991 
6992 /*
6993  * Clears the per-thread inprobe flag and enables interrupts.
6994  */
6995 static void
dtrace_probe_exit(dtrace_icookie_t cookie)6996 dtrace_probe_exit(dtrace_icookie_t cookie)
6997 {
6998 	thread_t thread = current_thread();
6999 	uint16_t inprobe = dtrace_get_thread_inprobe(thread);
7000 
7001 	ASSERT(inprobe > 0);
7002 	dtrace_set_thread_inprobe(thread, inprobe - 1);
7003 
7004 #if INTERRUPT_MASKED_DEBUG
7005 	ml_spin_debug_reset(thread);
7006 #endif /* INTERRUPT_MASKED_DEBUG */
7007 
7008 	dtrace_interrupt_enable(cookie);
7009 }
7010 
7011 /*
7012  * If you're looking for the epicenter of DTrace, you just found it.  This
7013  * is the function called by the provider to fire a probe -- from which all
7014  * subsequent probe-context DTrace activity emanates.
7015  */
7016 void
dtrace_probe(dtrace_id_t id,uint64_t arg0,uint64_t arg1,uint64_t arg2,uint64_t arg3,uint64_t arg4)7017 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
7018     uint64_t arg2, uint64_t arg3, uint64_t arg4)
7019 {
7020 	processorid_t cpuid;
7021 	dtrace_icookie_t cookie;
7022 	dtrace_probe_t *probe;
7023 	dtrace_mstate_t mstate;
7024 	dtrace_ecb_t *ecb;
7025 	dtrace_action_t *act;
7026 	intptr_t offs;
7027 	size_t size;
7028 	int vtime, onintr;
7029 	volatile uint16_t *flags;
7030 	hrtime_t now;
7031 
7032 	cookie = dtrace_probe_enter(id);
7033 
7034 	/* Ensure that probe id is valid. */
7035 	if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
7036 		dtrace_probe_exit(cookie);
7037 		return;
7038 	}
7039 
7040 	probe = dtrace_probes[id - 1];
7041 	if (probe == NULL) {
7042 		dtrace_probe_exit(cookie);
7043 		return;
7044 	}
7045 
7046 	cpuid = CPU->cpu_id;
7047 	onintr = CPU_ON_INTR(CPU);
7048 
7049 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7050 	    probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
7051 		/*
7052 		 * We have hit in the predicate cache; we know that
7053 		 * this predicate would evaluate to be false.
7054 		 */
7055 		dtrace_probe_exit(cookie);
7056 		return;
7057 	}
7058 
7059 	if (panic_quiesce) {
7060 		/*
7061 		 * We don't trace anything if we're panicking.
7062 		 */
7063 		dtrace_probe_exit(cookie);
7064 		return;
7065 	}
7066 
7067 #if !defined(__APPLE__)
7068 	now = dtrace_gethrtime();
7069 	vtime = dtrace_vtime_references != 0;
7070 
7071 	if (vtime && curthread->t_dtrace_start)
7072 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7073 #else
7074 	/*
7075 	 * APPLE NOTE:  The time spent entering DTrace and arriving
7076 	 * to this point, is attributed to the current thread.
7077 	 * Instead it should accrue to DTrace.  FIXME
7078 	 */
7079 	vtime = dtrace_vtime_references != 0;
7080 
7081 	if (vtime)
7082 	{
7083 		int64_t dtrace_accum_time, recent_vtime;
7084 		thread_t thread = current_thread();
7085 
7086 		dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
7087 
7088 		if (dtrace_accum_time >= 0) {
7089 			recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
7090 
7091 			recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
7092 
7093 			dtrace_set_thread_vtime(thread, recent_vtime);
7094 		}
7095 	}
7096 
7097 	now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
7098 #endif /* __APPLE__ */
7099 
7100 	/*
7101 	 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
7102 	 * dtrace_probe() in some circumstances.   See, e.g. fasttrap_isa.c.
7103 	 * However the provider has no access to ECB context, so passes
7104 	 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
7105 	 * Detect that here and cons up a viable state (from the probe_id).
7106 	 */
7107 	if (dtrace_probeid_error == id && 0 == arg0) {
7108 		dtrace_id_t ftp_id = (dtrace_id_t)arg1;
7109 		dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
7110 		dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
7111 
7112 		if (NULL != ftp_ecb) {
7113 			dtrace_state_t *ftp_state = ftp_ecb->dte_state;
7114 
7115 			arg0 = (uint64_t)(uintptr_t)ftp_state;
7116 			arg1 = ftp_ecb->dte_epid;
7117 			/*
7118 			 * args[2-4] established by caller.
7119 			 */
7120 			ftp_state->dts_arg_error_illval = -1; /* arg5 */
7121 		}
7122 	}
7123 
7124 	mstate.dtms_difo = NULL;
7125 	mstate.dtms_probe = probe;
7126 	mstate.dtms_strtok = 0;
7127 	mstate.dtms_arg[0] = arg0;
7128 	mstate.dtms_arg[1] = arg1;
7129 	mstate.dtms_arg[2] = arg2;
7130 	mstate.dtms_arg[3] = arg3;
7131 	mstate.dtms_arg[4] = arg4;
7132 
7133 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7134 
7135 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7136 		dtrace_predicate_t *pred = ecb->dte_predicate;
7137 		dtrace_state_t *state = ecb->dte_state;
7138 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7139 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7140 		dtrace_vstate_t *vstate = &state->dts_vstate;
7141 		dtrace_provider_t *prov = probe->dtpr_provider;
7142 		uint64_t tracememsize = 0;
7143 		int committed = 0;
7144 		caddr_t tomax;
7145 
7146 		/*
7147 		 * A little subtlety with the following (seemingly innocuous)
7148 		 * declaration of the automatic 'val':  by looking at the
7149 		 * code, you might think that it could be declared in the
7150 		 * action processing loop, below.  (That is, it's only used in
7151 		 * the action processing loop.)  However, it must be declared
7152 		 * out of that scope because in the case of DIF expression
7153 		 * arguments to aggregating actions, one iteration of the
7154 		 * action loop will use the last iteration's value.
7155 		 */
7156 #ifdef lint
7157 		uint64_t val = 0;
7158 #else
7159 		uint64_t val = 0;
7160 #endif
7161 
7162 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7163 		*flags &= ~CPU_DTRACE_ERROR;
7164 
7165 		if (prov == dtrace_provider) {
7166 			/*
7167 			 * If dtrace itself is the provider of this probe,
7168 			 * we're only going to continue processing the ECB if
7169 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7170 			 * creating state.  (This prevents disjoint consumers
7171 			 * from seeing one another's metaprobes.)
7172 			 */
7173 			if (arg0 != (uint64_t)(uintptr_t)state)
7174 				continue;
7175 		}
7176 
7177 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7178 			/*
7179 			 * We're not currently active.  If our provider isn't
7180 			 * the dtrace pseudo provider, we're not interested.
7181 			 */
7182 			if (prov != dtrace_provider)
7183 				continue;
7184 
7185 			/*
7186 			 * Now we must further check if we are in the BEGIN
7187 			 * probe.  If we are, we will only continue processing
7188 			 * if we're still in WARMUP -- if one BEGIN enabling
7189 			 * has invoked the exit() action, we don't want to
7190 			 * evaluate subsequent BEGIN enablings.
7191 			 */
7192 			if (probe->dtpr_id == dtrace_probeid_begin &&
7193 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7194 				ASSERT(state->dts_activity ==
7195 				    DTRACE_ACTIVITY_DRAINING);
7196 				continue;
7197 			}
7198 		}
7199 
7200 		if (ecb->dte_cond) {
7201 			/*
7202 			 * If the dte_cond bits indicate that this
7203 			 * consumer is only allowed to see user-mode firings
7204 			 * of this probe, call the provider's dtps_usermode()
7205 			 * entry point to check that the probe was fired
7206 			 * while in a user context. Skip this ECB if that's
7207 			 * not the case.
7208 			 */
7209 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7210 			    prov->dtpv_pops.dtps_usermode &&
7211 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7212 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7213 				continue;
7214 
7215 			/*
7216 			 * This is more subtle than it looks. We have to be
7217 			 * absolutely certain that CRED() isn't going to
7218 			 * change out from under us so it's only legit to
7219 			 * examine that structure if we're in constrained
7220 			 * situations. Currently, the only times we'll this
7221 			 * check is if a non-super-user has enabled the
7222 			 * profile or syscall providers -- providers that
7223 			 * allow visibility of all processes. For the
7224 			 * profile case, the check above will ensure that
7225 			 * we're examining a user context.
7226 			 */
7227 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7228 				cred_t *cr;
7229 				cred_t *s_cr =
7230 				    ecb->dte_state->dts_cred.dcr_cred;
7231 				proc_t *proc;
7232 #pragma unused(proc) /* __APPLE__ */
7233 
7234 				ASSERT(s_cr != NULL);
7235 
7236 			/*
7237 			 * XXX this is hackish, but so is setting a variable
7238 			 * XXX in a McCarthy OR...
7239 			 */
7240 				if ((cr = dtrace_CRED()) == NULL ||
7241 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
7242 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
7243 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
7244 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
7245 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
7246 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
7247 #if !defined(__APPLE__)
7248 				    (proc = ttoproc(curthread)) == NULL ||
7249 				    (proc->p_flag & SNOCD))
7250 #else
7251 					1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
7252 #endif /* __APPLE__ */
7253 					continue;
7254 			}
7255 
7256 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7257 				cred_t *cr;
7258 				cred_t *s_cr =
7259 				    ecb->dte_state->dts_cred.dcr_cred;
7260 #pragma unused(cr, s_cr) /* __APPLE__ */
7261 
7262 				ASSERT(s_cr != NULL);
7263 
7264 #if !defined(__APPLE__)
7265 				if ((cr = CRED()) == NULL ||
7266 				    s_cr->cr_zone->zone_id !=
7267 				    cr->cr_zone->zone_id)
7268 					continue;
7269 #else
7270 				/* APPLE NOTE: Darwin doesn't do zones. */
7271 #endif /* __APPLE__ */
7272 			}
7273 		}
7274 
7275 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7276 			/*
7277 			 * We seem to be dead.  Unless we (a) have kernel
7278 			 * destructive permissions (b) have expicitly enabled
7279 			 * destructive actions and (c) destructive actions have
7280 			 * not been disabled, we're going to transition into
7281 			 * the KILLED state, from which no further processing
7282 			 * on this state will be performed.
7283 			 */
7284 			if (!dtrace_priv_kernel_destructive(state) ||
7285 			    !state->dts_cred.dcr_destructive ||
7286 			    dtrace_destructive_disallow) {
7287 				void *activity = &state->dts_activity;
7288 				dtrace_activity_t current;
7289 
7290 				do {
7291 					current = state->dts_activity;
7292 				} while (dtrace_cas32(activity, current,
7293 				    DTRACE_ACTIVITY_KILLED) != current);
7294 
7295 				continue;
7296 			}
7297 		}
7298 
7299 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7300 		    ecb->dte_alignment, state, &mstate)) < 0)
7301 			continue;
7302 
7303 		tomax = buf->dtb_tomax;
7304 		ASSERT(tomax != NULL);
7305 
7306 		/*
7307 		 * Build and store the record header corresponding to the ECB.
7308 		 */
7309 		if (ecb->dte_size != 0) {
7310 			dtrace_rechdr_t dtrh;
7311 
7312 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7313 				mstate.dtms_timestamp = dtrace_gethrtime();
7314 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7315 			}
7316 
7317 			ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
7318 
7319 			dtrh.dtrh_epid = ecb->dte_epid;
7320 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
7321 			DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
7322 		}
7323 
7324 		mstate.dtms_epid = ecb->dte_epid;
7325 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7326 
7327 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7328 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7329 		else
7330 			mstate.dtms_access = 0;
7331 
7332 		if (pred != NULL) {
7333 			dtrace_difo_t *dp = pred->dtp_difo;
7334 			uint64_t rval;
7335 
7336 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7337 
7338 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7339 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7340 
7341 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7342 					/*
7343 					 * Update the predicate cache...
7344 					 */
7345 					ASSERT(cid == pred->dtp_cacheid);
7346 
7347 					dtrace_set_thread_predcache(current_thread(), cid);
7348 				}
7349 
7350 				continue;
7351 			}
7352 		}
7353 
7354 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7355 		    act != NULL; act = act->dta_next) {
7356 			size_t valoffs;
7357 			dtrace_difo_t *dp;
7358 			dtrace_recdesc_t *rec = &act->dta_rec;
7359 
7360 			size = rec->dtrd_size;
7361 			valoffs = offs + rec->dtrd_offset;
7362 
7363 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7364 				uint64_t v = 0xbad;
7365 				dtrace_aggregation_t *agg;
7366 
7367 				agg = (dtrace_aggregation_t *)act;
7368 
7369 				if ((dp = act->dta_difo) != NULL)
7370 					v = dtrace_dif_emulate(dp,
7371 					    &mstate, vstate, state);
7372 
7373 				if (*flags & CPU_DTRACE_ERROR)
7374 					continue;
7375 
7376 				/*
7377 				 * Note that we always pass the expression
7378 				 * value from the previous iteration of the
7379 				 * action loop.  This value will only be used
7380 				 * if there is an expression argument to the
7381 				 * aggregating action, denoted by the
7382 				 * dtag_hasarg field.
7383 				 */
7384 				dtrace_aggregate(agg, buf,
7385 				    offs, aggbuf, v, val);
7386 				continue;
7387 			}
7388 
7389 			switch (act->dta_kind) {
7390 			case DTRACEACT_STOP:
7391 				if (dtrace_priv_proc_destructive(state))
7392 					dtrace_action_stop();
7393 				continue;
7394 
7395 			case DTRACEACT_BREAKPOINT:
7396 				if (dtrace_priv_kernel_destructive(state))
7397 					dtrace_action_breakpoint(ecb);
7398 				continue;
7399 
7400 			case DTRACEACT_PANIC:
7401 				if (dtrace_priv_kernel_destructive(state))
7402 					dtrace_action_panic(ecb);
7403 				continue;
7404 
7405 			case DTRACEACT_STACK:
7406 				if (!dtrace_priv_kernel(state))
7407 					continue;
7408 
7409 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7410 				    size / sizeof (pc_t), probe->dtpr_aframes,
7411 				    DTRACE_ANCHORED(probe) ? NULL :
7412 				  (uint32_t *)(uintptr_t)arg0);
7413 				continue;
7414 
7415 			case DTRACEACT_JSTACK:
7416 			case DTRACEACT_USTACK:
7417 				if (!dtrace_priv_proc(state))
7418 					continue;
7419 
7420 				/*
7421 				 * See comment in DIF_VAR_PID.
7422 				 */
7423 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7424 				    CPU_ON_INTR(CPU)) {
7425 					int depth = DTRACE_USTACK_NFRAMES(
7426 					    rec->dtrd_arg) + 1;
7427 
7428 					dtrace_bzero((void *)(tomax + valoffs),
7429 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7430 					    + depth * sizeof (uint64_t));
7431 
7432 					continue;
7433 				}
7434 
7435 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7436 				    curproc->p_dtrace_helpers != NULL) {
7437 					/*
7438 					 * This is the slow path -- we have
7439 					 * allocated string space, and we're
7440 					 * getting the stack of a process that
7441 					 * has helpers.  Call into a separate
7442 					 * routine to perform this processing.
7443 					 */
7444 					dtrace_action_ustack(&mstate, state,
7445 					    (uint64_t *)(tomax + valoffs),
7446 					    rec->dtrd_arg);
7447 					continue;
7448 				}
7449 
7450 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7451 				dtrace_getupcstack((uint64_t *)
7452 				    (tomax + valoffs),
7453 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7454 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7455 				continue;
7456 
7457 			default:
7458 				break;
7459 			}
7460 
7461 			dp = act->dta_difo;
7462 			ASSERT(dp != NULL);
7463 
7464 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7465 
7466 			if (*flags & CPU_DTRACE_ERROR)
7467 				continue;
7468 
7469 			switch (act->dta_kind) {
7470 			case DTRACEACT_SPECULATE: {
7471 				dtrace_rechdr_t *dtrh = NULL;
7472 
7473 				ASSERT(buf == &state->dts_buffer[cpuid]);
7474 				buf = dtrace_speculation_buffer(state,
7475 				    cpuid, val);
7476 
7477 				if (buf == NULL) {
7478 					*flags |= CPU_DTRACE_DROP;
7479 					continue;
7480 				}
7481 
7482 				offs = dtrace_buffer_reserve(buf,
7483 				    ecb->dte_needed, ecb->dte_alignment,
7484 				    state, NULL);
7485 
7486 				if (offs < 0) {
7487 					*flags |= CPU_DTRACE_DROP;
7488 					continue;
7489 				}
7490 
7491 				tomax = buf->dtb_tomax;
7492 				ASSERT(tomax != NULL);
7493 
7494 				if (ecb->dte_size == 0)
7495 					continue;
7496 
7497 				ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
7498 				dtrh = ((void *)(tomax + offs));
7499 				dtrh->dtrh_epid = ecb->dte_epid;
7500 
7501 				/*
7502 				 * When the speculation is committed, all of
7503 				 * the records in the speculative buffer will
7504 				 * have their timestamps set to the commit
7505 				 * time.  Until then, it is set to a sentinel
7506 				 * value, for debugability.
7507 				 */
7508 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7509 
7510  				continue;
7511 			}
7512 
7513 			case DTRACEACT_CHILL:
7514 				if (dtrace_priv_kernel_destructive(state))
7515 					dtrace_action_chill(&mstate, val);
7516 				continue;
7517 
7518 			case DTRACEACT_RAISE:
7519 				if (dtrace_priv_proc_destructive(state))
7520 					dtrace_action_raise(val);
7521 				continue;
7522 
7523 			case DTRACEACT_PIDRESUME:   /* __APPLE__ */
7524 				if (dtrace_priv_proc_destructive(state))
7525 					dtrace_action_pidresume(val);
7526 				continue;
7527 
7528 			case DTRACEACT_COMMIT:
7529 				ASSERT(!committed);
7530 
7531 				/*
7532 				 * We need to commit our buffer state.
7533 				 */
7534 				if (ecb->dte_size)
7535 					buf->dtb_offset = offs + ecb->dte_size;
7536 				buf = &state->dts_buffer[cpuid];
7537 				dtrace_speculation_commit(state, cpuid, val);
7538 				committed = 1;
7539 				continue;
7540 
7541 			case DTRACEACT_DISCARD:
7542 				dtrace_speculation_discard(state, cpuid, val);
7543 				continue;
7544 
7545 			case DTRACEACT_DIFEXPR:
7546 			case DTRACEACT_LIBACT:
7547 			case DTRACEACT_PRINTF:
7548 			case DTRACEACT_PRINTA:
7549 			case DTRACEACT_SYSTEM:
7550 			case DTRACEACT_FREOPEN:
7551 			case DTRACEACT_APPLEBINARY:   /* __APPLE__ */
7552 			case DTRACEACT_TRACEMEM:
7553 				break;
7554 
7555 			case DTRACEACT_TRACEMEM_DYNSIZE:
7556 				tracememsize = val;
7557 				break;
7558 
7559 			case DTRACEACT_SYM:
7560 			case DTRACEACT_MOD:
7561 				if (!dtrace_priv_kernel(state))
7562 					continue;
7563 				break;
7564 
7565 			case DTRACEACT_USYM:
7566 			case DTRACEACT_UMOD:
7567 			case DTRACEACT_UADDR: {
7568 				if (!dtrace_priv_proc(state))
7569 					continue;
7570 
7571 				DTRACE_STORE(uint64_t, tomax,
7572 				    valoffs, (uint64_t)dtrace_proc_selfpid());
7573 				DTRACE_STORE(uint64_t, tomax,
7574 				    valoffs + sizeof (uint64_t), val);
7575 
7576 				continue;
7577 			}
7578 
7579 			case DTRACEACT_EXIT: {
7580 				/*
7581 				 * For the exit action, we are going to attempt
7582 				 * to atomically set our activity to be
7583 				 * draining.  If this fails (either because
7584 				 * another CPU has beat us to the exit action,
7585 				 * or because our current activity is something
7586 				 * other than ACTIVE or WARMUP), we will
7587 				 * continue.  This assures that the exit action
7588 				 * can be successfully recorded at most once
7589 				 * when we're in the ACTIVE state.  If we're
7590 				 * encountering the exit() action while in
7591 				 * COOLDOWN, however, we want to honor the new
7592 				 * status code.  (We know that we're the only
7593 				 * thread in COOLDOWN, so there is no race.)
7594 				 */
7595 				void *activity = &state->dts_activity;
7596 				dtrace_activity_t current = state->dts_activity;
7597 
7598 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7599 					break;
7600 
7601 				if (current != DTRACE_ACTIVITY_WARMUP)
7602 					current = DTRACE_ACTIVITY_ACTIVE;
7603 
7604 				if (dtrace_cas32(activity, current,
7605 				    DTRACE_ACTIVITY_DRAINING) != current) {
7606 					*flags |= CPU_DTRACE_DROP;
7607 					continue;
7608 				}
7609 
7610 				break;
7611 			}
7612 
7613 			default:
7614 				ASSERT(0);
7615 			}
7616 
7617 			if (dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF)) {
7618 				uintptr_t end = valoffs + size;
7619 
7620 				if (tracememsize != 0 &&
7621                                     valoffs + tracememsize < end)
7622 				{
7623                                         end = valoffs + tracememsize;
7624                                         tracememsize = 0;
7625                                 }
7626 
7627 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7628 				    !dtrace_vcanload((void *)(uintptr_t)val,
7629 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7630 				{
7631 					continue;
7632 				}
7633 
7634 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7635 				    &val, end, act->dta_intuple,
7636 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7637 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7638 
7639 				continue;
7640 			}
7641 
7642 			switch (size) {
7643 			case 0:
7644 				break;
7645 
7646 			case sizeof (uint8_t):
7647 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7648 				break;
7649 			case sizeof (uint16_t):
7650 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7651 				break;
7652 			case sizeof (uint32_t):
7653 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7654 				break;
7655 			case sizeof (uint64_t):
7656 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7657 				break;
7658 			default:
7659 				/*
7660 				 * Any other size should have been returned by
7661 				 * reference, not by value.
7662 				 */
7663 				ASSERT(0);
7664 				break;
7665 			}
7666 		}
7667 
7668 		if (*flags & CPU_DTRACE_DROP)
7669 			continue;
7670 
7671 		if (*flags & CPU_DTRACE_FAULT) {
7672 			int ndx;
7673 			dtrace_action_t *err;
7674 
7675 			buf->dtb_errors++;
7676 
7677 			if (probe->dtpr_id == dtrace_probeid_error) {
7678 				/*
7679 				 * There's nothing we can do -- we had an
7680 				 * error on the error probe.  We bump an
7681 				 * error counter to at least indicate that
7682 				 * this condition happened.
7683 				 */
7684 				dtrace_error(&state->dts_dblerrors);
7685 				continue;
7686 			}
7687 
7688 			if (vtime) {
7689 				/*
7690 				 * Before recursing on dtrace_probe(), we
7691 				 * need to explicitly clear out our start
7692 				 * time to prevent it from being accumulated
7693 				 * into t_dtrace_vtime.
7694 				 */
7695 
7696 				/*
7697 				 * Darwin sets the sign bit on t_dtrace_tracing
7698 				 * to suspend accumulation to it.
7699 				 */
7700 				dtrace_set_thread_tracing(current_thread(),
7701 				    (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
7702 
7703 			}
7704 
7705 			/*
7706 			 * Iterate over the actions to figure out which action
7707 			 * we were processing when we experienced the error.
7708 			 * Note that act points _past_ the faulting action; if
7709 			 * act is ecb->dte_action, the fault was in the
7710 			 * predicate, if it's ecb->dte_action->dta_next it's
7711 			 * in action #1, and so on.
7712 			 */
7713 			for (err = ecb->dte_action, ndx = 0;
7714 			    err != act; err = err->dta_next, ndx++)
7715 				continue;
7716 
7717 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7718 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7719 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7720 			    cpu_core[cpuid].cpuc_dtrace_illval);
7721 
7722 			continue;
7723 		}
7724 
7725 		if (!committed)
7726 			buf->dtb_offset = offs + ecb->dte_size;
7727 	}
7728 
7729 	/* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
7730 	   to the current thread. Instead it should accrue to DTrace. */
7731 	if (vtime) {
7732 		thread_t thread = current_thread();
7733 		int64_t t = dtrace_get_thread_tracing(thread);
7734 
7735 		if (t >= 0) {
7736 			/* Usual case, accumulate time spent here into t_dtrace_tracing */
7737 			dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
7738 		} else {
7739 			/* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
7740 			dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
7741 		}
7742 	}
7743 
7744 	dtrace_probe_exit(cookie);
7745 }
7746 
7747 /*
7748  * DTrace Probe Hashing Functions
7749  *
7750  * The functions in this section (and indeed, the functions in remaining
7751  * sections) are not _called_ from probe context.  (Any exceptions to this are
7752  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7753  * DTrace framework to look-up probes in, add probes to and remove probes from
7754  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7755  * probe tuple -- allowing for fast lookups, regardless of what was
7756  * specified.)
7757  */
7758 static uint_t
dtrace_hash_str(const char * p)7759 dtrace_hash_str(const char *p)
7760 {
7761 	unsigned int g;
7762 	uint_t hval = 0;
7763 
7764 	while (*p) {
7765 		hval = (hval << 4) + *p++;
7766 		if ((g = (hval & 0xf0000000)) != 0)
7767 			hval ^= g >> 24;
7768 		hval &= ~g;
7769 	}
7770 	return (hval);
7771 }
7772 
7773 static const char*
dtrace_strkey_probe_provider(void * elm,uintptr_t offs)7774 dtrace_strkey_probe_provider(void *elm, uintptr_t offs)
7775 {
7776 #pragma unused(offs)
7777 	dtrace_probe_t *probe = (dtrace_probe_t*)elm;
7778 	return probe->dtpr_provider->dtpv_name;
7779 }
7780 
7781 static const char*
dtrace_strkey_offset(void * elm,uintptr_t offs)7782 dtrace_strkey_offset(void *elm, uintptr_t offs)
7783 {
7784 	return ((char *)((uintptr_t)(elm) + offs));
7785 }
7786 
7787 static const char*
dtrace_strkey_deref_offset(void * elm,uintptr_t offs)7788 dtrace_strkey_deref_offset(void *elm, uintptr_t offs)
7789 {
7790 	return *((char **)((uintptr_t)(elm) + offs));
7791 }
7792 
7793 static dtrace_hash_t *
dtrace_hash_create(dtrace_strkey_f func,uintptr_t arg,uintptr_t nextoffs,uintptr_t prevoffs)7794 dtrace_hash_create(dtrace_strkey_f func, uintptr_t arg, uintptr_t nextoffs, uintptr_t prevoffs)
7795 {
7796 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7797 
7798 	hash->dth_getstr = func;
7799 	hash->dth_stroffs = arg;
7800 	hash->dth_nextoffs = nextoffs;
7801 	hash->dth_prevoffs = prevoffs;
7802 
7803 	hash->dth_size = 1;
7804 	hash->dth_mask = hash->dth_size - 1;
7805 
7806 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7807 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7808 
7809 	return (hash);
7810 }
7811 
7812 /*
7813  * APPLE NOTE: dtrace_hash_destroy is not used.
7814  * It is called by dtrace_detach which is not
7815  * currently implemented.  Revisit someday.
7816  */
7817 #if !defined(__APPLE__)
7818 static void
dtrace_hash_destroy(dtrace_hash_t * hash)7819 dtrace_hash_destroy(dtrace_hash_t *hash)
7820 {
7821 #if DEBUG
7822 	int i;
7823 
7824 	for (i = 0; i < hash->dth_size; i++)
7825 		ASSERT(hash->dth_tab[i] == NULL);
7826 #endif
7827 
7828 	kmem_free(hash->dth_tab,
7829 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7830 	kmem_free(hash, sizeof (dtrace_hash_t));
7831 }
7832 #endif /* __APPLE__ */
7833 
7834 static void
dtrace_hash_resize(dtrace_hash_t * hash)7835 dtrace_hash_resize(dtrace_hash_t *hash)
7836 {
7837 	int size = hash->dth_size, i, ndx;
7838 	int new_size = hash->dth_size << 1;
7839 	int new_mask = new_size - 1;
7840 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7841 
7842 	ASSERT((new_size & new_mask) == 0);
7843 
7844 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7845 
7846 	for (i = 0; i < size; i++) {
7847 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7848 			void *elm = bucket->dthb_chain;
7849 
7850 			ASSERT(elm != NULL);
7851 			ndx = DTRACE_HASHSTR(hash, elm) & new_mask;
7852 
7853 			next = bucket->dthb_next;
7854 			bucket->dthb_next = new_tab[ndx];
7855 			new_tab[ndx] = bucket;
7856 		}
7857 	}
7858 
7859 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7860 	hash->dth_tab = new_tab;
7861 	hash->dth_size = new_size;
7862 	hash->dth_mask = new_mask;
7863 }
7864 
7865 static void
dtrace_hash_add(dtrace_hash_t * hash,void * new)7866 dtrace_hash_add(dtrace_hash_t *hash, void *new)
7867 {
7868 	int hashval = DTRACE_HASHSTR(hash, new);
7869 	int ndx = hashval & hash->dth_mask;
7870 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7871 	void **nextp, **prevp;
7872 
7873 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7874 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7875 			goto add;
7876 	}
7877 
7878 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7879 		dtrace_hash_resize(hash);
7880 		dtrace_hash_add(hash, new);
7881 		return;
7882 	}
7883 
7884 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7885 	bucket->dthb_next = hash->dth_tab[ndx];
7886 	hash->dth_tab[ndx] = bucket;
7887 	hash->dth_nbuckets++;
7888 
7889 add:
7890 	nextp = DTRACE_HASHNEXT(hash, new);
7891 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7892 	*nextp = bucket->dthb_chain;
7893 
7894 	if (bucket->dthb_chain != NULL) {
7895 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7896 		ASSERT(*prevp == NULL);
7897 		*prevp = new;
7898 	}
7899 
7900 	bucket->dthb_chain = new;
7901 	bucket->dthb_len++;
7902 }
7903 
7904 static void *
dtrace_hash_lookup_string(dtrace_hash_t * hash,const char * str)7905 dtrace_hash_lookup_string(dtrace_hash_t *hash, const char *str)
7906 {
7907 	int hashval = dtrace_hash_str(str);
7908 	int ndx = hashval & hash->dth_mask;
7909 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7910 
7911 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7912 		if (strcmp(str, DTRACE_GETSTR(hash, bucket->dthb_chain)) == 0)
7913 			return (bucket->dthb_chain);
7914 	}
7915 
7916 	return (NULL);
7917 }
7918 
7919 static dtrace_probe_t *
dtrace_hash_lookup(dtrace_hash_t * hash,void * template)7920 dtrace_hash_lookup(dtrace_hash_t *hash, void *template)
7921 {
7922 	return dtrace_hash_lookup_string(hash, DTRACE_GETSTR(hash, template));
7923 }
7924 
7925 static int
dtrace_hash_collisions(dtrace_hash_t * hash,void * template)7926 dtrace_hash_collisions(dtrace_hash_t *hash, void *template)
7927 {
7928 	int hashval = DTRACE_HASHSTR(hash, template);
7929 	int ndx = hashval & hash->dth_mask;
7930 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7931 
7932 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7933 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7934 			return (bucket->dthb_len);
7935 	}
7936 
7937 	return (0);
7938 }
7939 
7940 static void
dtrace_hash_remove(dtrace_hash_t * hash,void * elm)7941 dtrace_hash_remove(dtrace_hash_t *hash, void *elm)
7942 {
7943 	int ndx = DTRACE_HASHSTR(hash, elm) & hash->dth_mask;
7944 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7945 
7946 	void **prevp = DTRACE_HASHPREV(hash, elm);
7947 	void **nextp = DTRACE_HASHNEXT(hash, elm);
7948 
7949 	/*
7950 	 * Find the bucket that we're removing this elm from.
7951 	 */
7952 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7953 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, elm))
7954 			break;
7955 	}
7956 
7957 	ASSERT(bucket != NULL);
7958 
7959 	if (*prevp == NULL) {
7960 		if (*nextp == NULL) {
7961 			/*
7962 			 * The removed element was the only element on this
7963 			 * bucket; we need to remove the bucket.
7964 			 */
7965 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7966 
7967 			ASSERT(bucket->dthb_chain == elm);
7968 			ASSERT(b != NULL);
7969 
7970 			if (b == bucket) {
7971 				hash->dth_tab[ndx] = bucket->dthb_next;
7972 			} else {
7973 				while (b->dthb_next != bucket)
7974 					b = b->dthb_next;
7975 				b->dthb_next = bucket->dthb_next;
7976 			}
7977 
7978 			ASSERT(hash->dth_nbuckets > 0);
7979 			hash->dth_nbuckets--;
7980 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7981 			return;
7982 		}
7983 
7984 		bucket->dthb_chain = *nextp;
7985 	} else {
7986 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7987 	}
7988 
7989 	if (*nextp != NULL)
7990 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7991 }
7992 
7993 /*
7994  * DTrace Utility Functions
7995  *
7996  * These are random utility functions that are _not_ called from probe context.
7997  */
7998 static int
dtrace_badattr(const dtrace_attribute_t * a)7999 dtrace_badattr(const dtrace_attribute_t *a)
8000 {
8001 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8002 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8003 	    a->dtat_class > DTRACE_CLASS_MAX);
8004 }
8005 
8006 /*
8007  * Returns a dtrace-managed copy of a string, and will
8008  * deduplicate copies of the same string.
8009  * If the specified string is NULL, returns an empty string
8010  */
8011 static char *
dtrace_strref(const char * str)8012 dtrace_strref(const char *str)
8013 {
8014 	dtrace_string_t *s = NULL;
8015 	size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
8016 
8017 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8018 
8019 	if (str == NULL)
8020 		str = "";
8021 
8022 	for (s = dtrace_hash_lookup_string(dtrace_strings, str); s != NULL;
8023 	     s = *(DTRACE_HASHNEXT(dtrace_strings, s)))  {
8024 		if (strncmp(str, s->dtst_str, bufsize) != 0) {
8025 			continue;
8026 		}
8027 		ASSERT(s->dtst_refcount != UINT32_MAX);
8028 		s->dtst_refcount++;
8029 		return s->dtst_str;
8030 	}
8031 
8032 	s = kmem_zalloc(sizeof(dtrace_string_t) + bufsize, KM_SLEEP);
8033 	s->dtst_refcount = 1;
8034 	(void) strlcpy(s->dtst_str, str, bufsize);
8035 
8036 	dtrace_hash_add(dtrace_strings, s);
8037 
8038 	return s->dtst_str;
8039 }
8040 
8041 static void
dtrace_strunref(const char * str)8042 dtrace_strunref(const char *str)
8043 {
8044 	ASSERT(str != NULL);
8045 	dtrace_string_t *s = NULL;
8046 	size_t bufsize = strlen(str) + 1;
8047 
8048 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8049 
8050 	for (s = dtrace_hash_lookup_string(dtrace_strings, str); s != NULL;
8051 	     s = *(DTRACE_HASHNEXT(dtrace_strings, s)))  {
8052 		if (strncmp(str, s->dtst_str, bufsize) != 0) {
8053 			continue;
8054 		}
8055 		ASSERT(s->dtst_refcount != 0);
8056 		s->dtst_refcount--;
8057 		if (s->dtst_refcount == 0) {
8058 			dtrace_hash_remove(dtrace_strings, s);
8059 			kmem_free(s, sizeof(dtrace_string_t) + bufsize);
8060 		}
8061 		return;
8062 	}
8063 	panic("attempt to unref non-existent string %s", str);
8064 }
8065 
8066 #define	DTRACE_ISALPHA(c)	\
8067 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8068 
8069 static int
dtrace_badname(const char * s)8070 dtrace_badname(const char *s)
8071 {
8072 	char c;
8073 
8074 	if (s == NULL || (c = *s++) == '\0')
8075 		return (0);
8076 
8077 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8078 		return (1);
8079 
8080 	while ((c = *s++) != '\0') {
8081 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8082 		    c != '-' && c != '_' && c != '.' && c != '`')
8083 			return (1);
8084 	}
8085 
8086 	return (0);
8087 }
8088 
8089 static void
dtrace_cred2priv(cred_t * cr,uint32_t * privp,uid_t * uidp,zoneid_t * zoneidp)8090 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8091 {
8092 	uint32_t priv;
8093 
8094 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8095 		if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
8096 			priv = DTRACE_PRIV_USER | DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER;
8097 		}
8098 		else {
8099 			priv = DTRACE_PRIV_ALL;
8100 		}
8101 		*uidp = 0;
8102 		*zoneidp = 0;
8103 	} else {
8104 		*uidp = crgetuid(cr);
8105 		*zoneidp = crgetzoneid(cr);
8106 
8107 		priv = 0;
8108 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8109 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8110 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8111 			priv |= DTRACE_PRIV_USER;
8112 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8113 			priv |= DTRACE_PRIV_PROC;
8114 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8115 			priv |= DTRACE_PRIV_OWNER;
8116 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8117 			priv |= DTRACE_PRIV_ZONEOWNER;
8118 	}
8119 
8120 	*privp = priv;
8121 }
8122 
8123 #ifdef DTRACE_ERRDEBUG
8124 static void
dtrace_errdebug(const char * str)8125 dtrace_errdebug(const char *str)
8126 {
8127 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8128 	int occupied = 0;
8129 
8130 	lck_mtx_lock(&dtrace_errlock);
8131 	dtrace_errlast = str;
8132 	dtrace_errthread = (kthread_t *)current_thread();
8133 
8134 	while (occupied++ < DTRACE_ERRHASHSZ) {
8135 		if (dtrace_errhash[hval].dter_msg == str) {
8136 			dtrace_errhash[hval].dter_count++;
8137 			goto out;
8138 		}
8139 
8140 		if (dtrace_errhash[hval].dter_msg != NULL) {
8141 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8142 			continue;
8143 		}
8144 
8145 		dtrace_errhash[hval].dter_msg = str;
8146 		dtrace_errhash[hval].dter_count = 1;
8147 		goto out;
8148 	}
8149 
8150 	panic("dtrace: undersized error hash");
8151 out:
8152 	lck_mtx_unlock(&dtrace_errlock);
8153 }
8154 #endif
8155 
8156 /*
8157  * DTrace Matching Functions
8158  *
8159  * These functions are used to match groups of probes, given some elements of
8160  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8161  */
8162 static int
dtrace_match_priv(const dtrace_probe_t * prp,uint32_t priv,uid_t uid,zoneid_t zoneid)8163 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8164     zoneid_t zoneid)
8165 {
8166 	if (priv != DTRACE_PRIV_ALL) {
8167 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8168 		uint32_t match = priv & ppriv;
8169 
8170 		/*
8171 		 * No PRIV_DTRACE_* privileges...
8172 		 */
8173 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8174 		    DTRACE_PRIV_KERNEL)) == 0)
8175 			return (0);
8176 
8177 		/*
8178 		 * No matching bits, but there were bits to match...
8179 		 */
8180 		if (match == 0 && ppriv != 0)
8181 			return (0);
8182 
8183 		/*
8184 		 * Need to have permissions to the process, but don't...
8185 		 */
8186 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8187 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8188 			return (0);
8189 		}
8190 
8191 		/*
8192 		 * Need to be in the same zone unless we possess the
8193 		 * privilege to examine all zones.
8194 		 */
8195 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8196 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8197 			return (0);
8198 		}
8199 	}
8200 
8201 	return (1);
8202 }
8203 
8204 /*
8205  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8206  * consists of input pattern strings and an ops-vector to evaluate them.
8207  * This function returns >0 for match, 0 for no match, and <0 for error.
8208  */
8209 static int
dtrace_match_probe(const dtrace_probe_t * prp,const dtrace_probekey_t * pkp,uint32_t priv,uid_t uid,zoneid_t zoneid)8210 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8211     uint32_t priv, uid_t uid, zoneid_t zoneid)
8212 {
8213 	dtrace_provider_t *pvp = prp->dtpr_provider;
8214 	int rv;
8215 
8216 	if (pvp->dtpv_defunct)
8217 		return (0);
8218 
8219 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8220 		return (rv);
8221 
8222 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8223 		return (rv);
8224 
8225 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8226 		return (rv);
8227 
8228 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8229 		return (rv);
8230 
8231 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8232 		return (0);
8233 
8234 	return (rv);
8235 }
8236 
8237 /*
8238  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8239  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8240  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8241  * In addition, all of the recursion cases except for '*' matching have been
8242  * unwound.  For '*', we still implement recursive evaluation, but a depth
8243  * counter is maintained and matching is aborted if we recurse too deep.
8244  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8245  */
8246 static int
dtrace_match_glob(const char * s,const char * p,int depth)8247 dtrace_match_glob(const char *s, const char *p, int depth)
8248 {
8249 	const char *olds;
8250 	char s1, c;
8251 	int gs;
8252 
8253 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8254 		return (-1);
8255 
8256 	if (s == NULL)
8257 		s = ""; /* treat NULL as empty string */
8258 
8259 top:
8260 	olds = s;
8261 	s1 = *s++;
8262 
8263 	if (p == NULL)
8264 		return (0);
8265 
8266 	if ((c = *p++) == '\0')
8267 		return (s1 == '\0');
8268 
8269 	switch (c) {
8270 	case '[': {
8271 		int ok = 0, notflag = 0;
8272 		char lc = '\0';
8273 
8274 		if (s1 == '\0')
8275 			return (0);
8276 
8277 		if (*p == '!') {
8278 			notflag = 1;
8279 			p++;
8280 		}
8281 
8282 		if ((c = *p++) == '\0')
8283 			return (0);
8284 
8285 		do {
8286 			if (c == '-' && lc != '\0' && *p != ']') {
8287 				if ((c = *p++) == '\0')
8288 					return (0);
8289 				if (c == '\\' && (c = *p++) == '\0')
8290 					return (0);
8291 
8292 				if (notflag) {
8293 					if (s1 < lc || s1 > c)
8294 						ok++;
8295 					else
8296 						return (0);
8297 				} else if (lc <= s1 && s1 <= c)
8298 					ok++;
8299 
8300 			} else if (c == '\\' && (c = *p++) == '\0')
8301 				return (0);
8302 
8303 			lc = c; /* save left-hand 'c' for next iteration */
8304 
8305 			if (notflag) {
8306 				if (s1 != c)
8307 					ok++;
8308 				else
8309 					return (0);
8310 			} else if (s1 == c)
8311 				ok++;
8312 
8313 			if ((c = *p++) == '\0')
8314 				return (0);
8315 
8316 		} while (c != ']');
8317 
8318 		if (ok)
8319 			goto top;
8320 
8321 		return (0);
8322 	}
8323 
8324 	case '\\':
8325 		if ((c = *p++) == '\0')
8326 			return (0);
8327 		OS_FALLTHROUGH;
8328 
8329 	default:
8330 		if (c != s1)
8331 			return (0);
8332 		OS_FALLTHROUGH;
8333 
8334 	case '?':
8335 		if (s1 != '\0')
8336 			goto top;
8337 		return (0);
8338 
8339 	case '*':
8340 		while (*p == '*')
8341 			p++; /* consecutive *'s are identical to a single one */
8342 
8343 		if (*p == '\0')
8344 			return (1);
8345 
8346 		for (s = olds; *s != '\0'; s++) {
8347 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8348 				return (gs);
8349 		}
8350 
8351 		return (0);
8352 	}
8353 }
8354 
8355 /*ARGSUSED*/
8356 static int
dtrace_match_string(const char * s,const char * p,int depth)8357 dtrace_match_string(const char *s, const char *p, int depth)
8358 {
8359 #pragma unused(depth) /* __APPLE__ */
8360 	return (s != NULL && s == p);
8361 }
8362 
8363 /*ARGSUSED*/
8364 static int
dtrace_match_module(const char * s,const char * p,int depth)8365 dtrace_match_module(const char *s, const char *p, int depth)
8366 {
8367 #pragma unused(depth) /* __APPLE__ */
8368 	size_t len;
8369 	if (s == NULL || p == NULL)
8370 		return (0);
8371 
8372 	len = strlen(p);
8373 
8374 	if (strncmp(p, s, len) != 0)
8375 		return (0);
8376 
8377 	if (s[len] == '.' || s[len] == '\0')
8378 		return (1);
8379 
8380 	return (0);
8381 }
8382 
8383 /*ARGSUSED*/
8384 static int
dtrace_match_nul(const char * s,const char * p,int depth)8385 dtrace_match_nul(const char *s, const char *p, int depth)
8386 {
8387 #pragma unused(s, p, depth) /* __APPLE__ */
8388 	return (1); /* always match the empty pattern */
8389 }
8390 
8391 /*ARGSUSED*/
8392 static int
dtrace_match_nonzero(const char * s,const char * p,int depth)8393 dtrace_match_nonzero(const char *s, const char *p, int depth)
8394 {
8395 #pragma unused(p, depth) /* __APPLE__ */
8396 	return (s != NULL && s[0] != '\0');
8397 }
8398 
8399 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 *),void * arg1,void * arg2)8400 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8401     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *, void *), void *arg1, void *arg2)
8402 {
8403 	dtrace_probe_t *probe;
8404 	dtrace_provider_t prov_template = {
8405 		.dtpv_name = (char *)(uintptr_t)pkp->dtpk_prov
8406 	};
8407 
8408 	dtrace_probe_t template = {
8409 		.dtpr_provider = &prov_template,
8410 		.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod,
8411 		.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func,
8412 		.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name
8413 	};
8414 
8415 	dtrace_hash_t *hash = NULL;
8416 	int len, rc, best = INT_MAX, nmatched = 0;
8417 	dtrace_id_t i;
8418 
8419 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8420 
8421 	/*
8422 	 * If the probe ID is specified in the key, just lookup by ID and
8423 	 * invoke the match callback once if a matching probe is found.
8424 	 */
8425 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8426 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8427 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8428 		        if ((*matched)(probe, arg1, arg2) == DTRACE_MATCH_FAIL)
8429                                return (DTRACE_MATCH_FAIL);
8430 			nmatched++;
8431 		}
8432 		return (nmatched);
8433 	}
8434 
8435 	/*
8436 	 * We want to find the most distinct of the provider name, module name,
8437 	 * function name, and name.  So for each one that is not a glob
8438 	 * pattern or empty string, we perform a lookup in the corresponding
8439 	 * hash and use the hash table with the fewest collisions to do our
8440 	 * search.
8441 	 */
8442 	if (pkp->dtpk_pmatch == &dtrace_match_string &&
8443 	    (len = dtrace_hash_collisions(dtrace_byprov, &template)) < best) {
8444 		best = len;
8445 		hash = dtrace_byprov;
8446 	}
8447 
8448 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8449 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8450 		best = len;
8451 		hash = dtrace_bymod;
8452 	}
8453 
8454 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8455 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8456 		best = len;
8457 		hash = dtrace_byfunc;
8458 	}
8459 
8460 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8461 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8462 		best = len;
8463 		hash = dtrace_byname;
8464 	}
8465 
8466 	/*
8467 	 * If we did not select a hash table, iterate over every probe and
8468 	 * invoke our callback for each one that matches our input probe key.
8469 	 */
8470 	if (hash == NULL) {
8471 		for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
8472 			if ((probe = dtrace_probes[i]) == NULL ||
8473 			    dtrace_match_probe(probe, pkp, priv, uid,
8474 			    zoneid) <= 0)
8475 				continue;
8476 
8477 			nmatched++;
8478 
8479                        if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
8480 			       if (rc == DTRACE_MATCH_FAIL)
8481                                        return (DTRACE_MATCH_FAIL);
8482 			       break;
8483                        }
8484 		}
8485 
8486 		return (nmatched);
8487 	}
8488 
8489 	/*
8490 	 * If we selected a hash table, iterate over each probe of the same key
8491 	 * name and invoke the callback for every probe that matches the other
8492 	 * attributes of our input probe key.
8493 	 */
8494 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8495 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8496 
8497 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8498 			continue;
8499 
8500 		nmatched++;
8501 
8502 		if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
8503 		    if (rc == DTRACE_MATCH_FAIL)
8504 			return (DTRACE_MATCH_FAIL);
8505 		    break;
8506 		}
8507 	}
8508 
8509 	return (nmatched);
8510 }
8511 
8512 /*
8513  * Return the function pointer dtrace_probecmp() should use to compare the
8514  * specified pattern with a string.  For NULL or empty patterns, we select
8515  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8516  * For non-empty non-glob strings, we use dtrace_match_string().
8517  */
8518 static dtrace_probekey_f *
dtrace_probekey_func(const char * p)8519 dtrace_probekey_func(const char *p)
8520 {
8521 	char c;
8522 
8523 	if (p == NULL || *p == '\0')
8524 		return (&dtrace_match_nul);
8525 
8526 	while ((c = *p++) != '\0') {
8527 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8528 			return (&dtrace_match_glob);
8529 	}
8530 
8531 	return (&dtrace_match_string);
8532 }
8533 
8534 static dtrace_probekey_f *
dtrace_probekey_module_func(const char * p)8535 dtrace_probekey_module_func(const char *p)
8536 {
8537 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8538 
8539 	dtrace_probekey_f *f = dtrace_probekey_func(p);
8540 	if (f == &dtrace_match_string) {
8541 		dtrace_probe_t template = {
8542 			.dtpr_mod = (char *)(uintptr_t)p,
8543 		};
8544 		if (dtrace_hash_lookup(dtrace_bymod, &template) == NULL) {
8545 			return (&dtrace_match_module);
8546 		}
8547 		return (&dtrace_match_string);
8548 	}
8549 	return f;
8550 }
8551 
8552 /*
8553  * Build a probe comparison key for use with dtrace_match_probe() from the
8554  * given probe description.  By convention, a null key only matches anchored
8555  * probes: if each field is the empty string, reset dtpk_fmatch to
8556  * dtrace_match_nonzero().
8557  */
8558 static void
dtrace_probekey(const dtrace_probedesc_t * pdp,dtrace_probekey_t * pkp)8559 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8560 {
8561 
8562 	pkp->dtpk_prov = dtrace_strref(pdp->dtpd_provider);
8563 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8564 
8565 	pkp->dtpk_mod = dtrace_strref(pdp->dtpd_mod);
8566 	pkp->dtpk_mmatch = dtrace_probekey_module_func(pdp->dtpd_mod);
8567 
8568 	pkp->dtpk_func = dtrace_strref(pdp->dtpd_func);
8569 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8570 
8571 	pkp->dtpk_name = dtrace_strref(pdp->dtpd_name);
8572 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8573 
8574 	pkp->dtpk_id = pdp->dtpd_id;
8575 
8576 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8577 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8578 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8579 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8580 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8581 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8582 }
8583 
8584 static void
dtrace_probekey_release(dtrace_probekey_t * pkp)8585 dtrace_probekey_release(dtrace_probekey_t *pkp)
8586 {
8587 	dtrace_strunref(pkp->dtpk_prov);
8588 	dtrace_strunref(pkp->dtpk_mod);
8589 	dtrace_strunref(pkp->dtpk_func);
8590 	dtrace_strunref(pkp->dtpk_name);
8591 }
8592 
8593 static int
dtrace_cond_provider_match(dtrace_probedesc_t * desc,void * data)8594 dtrace_cond_provider_match(dtrace_probedesc_t *desc, void *data)
8595 {
8596 	if (desc == NULL)
8597 		return 1;
8598 
8599 	dtrace_probekey_f *func = dtrace_probekey_func(desc->dtpd_provider);
8600 
8601 	return func((char*)data, desc->dtpd_provider, 0);
8602 }
8603 
8604 /*
8605  * DTrace Provider-to-Framework API Functions
8606  *
8607  * These functions implement much of the Provider-to-Framework API, as
8608  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8609  * the functions in the API for probe management (found below), and
8610  * dtrace_probe() itself (found above).
8611  */
8612 
8613 /*
8614  * Register the calling provider with the DTrace framework.  This should
8615  * generally be called by DTrace providers in their attach(9E) entry point.
8616  */
8617 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)8618 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8619     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8620 {
8621 	dtrace_provider_t *provider;
8622 
8623 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8624 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8625 		    "arguments", name ? name : "<NULL>");
8626 		return (EINVAL);
8627 	}
8628 
8629 	if (name[0] == '\0' || dtrace_badname(name)) {
8630 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8631 		    "provider name", name);
8632 		return (EINVAL);
8633 	}
8634 
8635 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8636 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8637 	    pops->dtps_destroy == NULL ||
8638 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8639 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8640 		    "provider ops", name);
8641 		return (EINVAL);
8642 	}
8643 
8644 	if (dtrace_badattr(&pap->dtpa_provider) ||
8645 	    dtrace_badattr(&pap->dtpa_mod) ||
8646 	    dtrace_badattr(&pap->dtpa_func) ||
8647 	    dtrace_badattr(&pap->dtpa_name) ||
8648 	    dtrace_badattr(&pap->dtpa_args)) {
8649 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8650 		    "provider attributes", name);
8651 		return (EINVAL);
8652 	}
8653 
8654 	if (priv & ~DTRACE_PRIV_ALL) {
8655 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8656 		    "privilege attributes", name);
8657 		return (EINVAL);
8658 	}
8659 
8660 	if ((priv & DTRACE_PRIV_KERNEL) &&
8661 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8662 	    pops->dtps_usermode == NULL) {
8663 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8664 		    "dtps_usermode() op for given privilege attributes", name);
8665 		return (EINVAL);
8666 	}
8667 
8668 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8669 
8670 	provider->dtpv_attr = *pap;
8671 	provider->dtpv_priv.dtpp_flags = priv;
8672 	if (cr != NULL) {
8673 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8674 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8675 	}
8676 	provider->dtpv_pops = *pops;
8677 
8678 	if (pops->dtps_provide == NULL) {
8679 		ASSERT(pops->dtps_provide_module != NULL);
8680 		provider->dtpv_pops.dtps_provide = dtrace_provide_nullop;
8681 	}
8682 
8683 	if (pops->dtps_provide_module == NULL) {
8684 		ASSERT(pops->dtps_provide != NULL);
8685 		provider->dtpv_pops.dtps_provide_module =
8686 		    dtrace_provide_module_nullop;
8687 	}
8688 
8689 	if (pops->dtps_suspend == NULL) {
8690 		ASSERT(pops->dtps_resume == NULL);
8691 		provider->dtpv_pops.dtps_suspend = dtrace_suspend_nullop;
8692 		provider->dtpv_pops.dtps_resume = dtrace_resume_nullop;
8693 	}
8694 
8695 	provider->dtpv_arg = arg;
8696 	*idp = (dtrace_provider_id_t)provider;
8697 
8698 	if (pops == &dtrace_provider_ops) {
8699 		LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8700 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8701 
8702 		provider->dtpv_name = dtrace_strref(name);
8703 
8704 		ASSERT(dtrace_anon.dta_enabling == NULL);
8705 
8706 		/*
8707 		 * We make sure that the DTrace provider is at the head of
8708 		 * the provider chain.
8709 		 */
8710 		provider->dtpv_next = dtrace_provider;
8711 		dtrace_provider = provider;
8712 		return (0);
8713 	}
8714 
8715 	lck_mtx_lock(&dtrace_provider_lock);
8716 	lck_mtx_lock(&dtrace_lock);
8717 
8718 	provider->dtpv_name = dtrace_strref(name);
8719 
8720 	/*
8721 	 * If there is at least one provider registered, we'll add this
8722 	 * provider after the first provider.
8723 	 */
8724 	if (dtrace_provider != NULL) {
8725 		provider->dtpv_next = dtrace_provider->dtpv_next;
8726 		dtrace_provider->dtpv_next = provider;
8727 	} else {
8728 		dtrace_provider = provider;
8729 	}
8730 
8731 	if (dtrace_retained != NULL) {
8732 		dtrace_enabling_provide(provider);
8733 
8734 		/*
8735 		 * Now we need to call dtrace_enabling_matchall_with_cond() --
8736 		 * with a condition matching the provider name we just added,
8737 		 * which will acquire cpu_lock and dtrace_lock.  We therefore need
8738 		 * to drop all of our locks before calling into it...
8739 		 */
8740 		lck_mtx_unlock(&dtrace_lock);
8741 		lck_mtx_unlock(&dtrace_provider_lock);
8742 
8743 		dtrace_match_cond_t cond = {dtrace_cond_provider_match, provider->dtpv_name};
8744 		dtrace_enabling_matchall_with_cond(&cond);
8745 
8746 		return (0);
8747 	}
8748 
8749 	lck_mtx_unlock(&dtrace_lock);
8750 	lck_mtx_unlock(&dtrace_provider_lock);
8751 
8752 	return (0);
8753 }
8754 
8755 /*
8756  * Unregister the specified provider from the DTrace framework.  This should
8757  * generally be called by DTrace providers in their detach(9E) entry point.
8758  */
8759 int
dtrace_unregister(dtrace_provider_id_t id)8760 dtrace_unregister(dtrace_provider_id_t id)
8761 {
8762 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8763 	dtrace_provider_t *prev = NULL;
8764 	int self = 0;
8765 	dtrace_probe_t *probe, *first = NULL, *next = NULL;
8766 	dtrace_probe_t template = {
8767 		.dtpr_provider = old
8768 	};
8769 
8770 	if (old->dtpv_pops.dtps_enable ==
8771 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8772 		/*
8773 		 * If DTrace itself is the provider, we're called with locks
8774 		 * already held.
8775 		 */
8776 		ASSERT(old == dtrace_provider);
8777 		ASSERT(dtrace_devi != NULL);
8778 		LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8779 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8780 		self = 1;
8781 
8782 		if (dtrace_provider->dtpv_next != NULL) {
8783 			/*
8784 			 * There's another provider here; return failure.
8785 			 */
8786 			return (EBUSY);
8787 		}
8788 	} else {
8789 		lck_mtx_lock(&dtrace_provider_lock);
8790 		lck_mtx_lock(&mod_lock);
8791 		lck_mtx_lock(&dtrace_lock);
8792 	}
8793 
8794 	/*
8795 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8796 	 * probes, we refuse to let providers slither away, unless this
8797 	 * provider has already been explicitly invalidated.
8798 	 */
8799 	if (!old->dtpv_defunct &&
8800 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8801 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8802 		if (!self) {
8803 			lck_mtx_unlock(&dtrace_lock);
8804 			lck_mtx_unlock(&mod_lock);
8805 			lck_mtx_unlock(&dtrace_provider_lock);
8806 		}
8807 		return (EBUSY);
8808 	}
8809 
8810 	/*
8811 	 * Attempt to destroy the probes associated with this provider.
8812 	 */
8813 	if (old->dtpv_ecb_count!=0) {
8814 		/*
8815 		 * We have at least one ECB; we can't remove this provider.
8816 		 */
8817 		if (!self) {
8818 			lck_mtx_unlock(&dtrace_lock);
8819 			lck_mtx_unlock(&mod_lock);
8820 			lck_mtx_unlock(&dtrace_provider_lock);
8821 		}
8822 		return (EBUSY);
8823 	}
8824 
8825 	/*
8826 	 * All of the probes for this provider are disabled; we can safely
8827 	 * remove all of them from their hash chains and from the probe array.
8828 	 */
8829 	for (probe = dtrace_hash_lookup(dtrace_byprov, &template); probe != NULL;
8830 	    probe = *(DTRACE_HASHNEXT(dtrace_byprov, probe))) {
8831 		if (probe->dtpr_provider != old)
8832 			continue;
8833 
8834 		dtrace_probes[probe->dtpr_id - 1] = NULL;
8835 		old->dtpv_probe_count--;
8836 
8837 		dtrace_hash_remove(dtrace_bymod, probe);
8838 		dtrace_hash_remove(dtrace_byfunc, probe);
8839 		dtrace_hash_remove(dtrace_byname, probe);
8840 
8841 		if (first == NULL) {
8842 			first = probe;
8843 			probe->dtpr_nextmod = NULL;
8844 		} else {
8845 			/*
8846 			 * Use nextmod as the chain of probes to remove
8847 			 */
8848 			probe->dtpr_nextmod = first;
8849 			first = probe;
8850 		}
8851 	}
8852 
8853 	for (probe = first; probe != NULL; probe = next) {
8854 		next = probe->dtpr_nextmod;
8855 		dtrace_hash_remove(dtrace_byprov, probe);
8856 	}
8857 
8858 	/*
8859 	 * The provider's probes have been removed from the hash chains and
8860 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8861 	 * everyone has cleared out from any probe array processing.
8862 	 */
8863 	dtrace_sync();
8864 
8865 	for (probe = first; probe != NULL; probe = next) {
8866 		next = probe->dtpr_nextmod;
8867 
8868 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8869 		    probe->dtpr_arg);
8870 		dtrace_strunref(probe->dtpr_mod);
8871 		dtrace_strunref(probe->dtpr_func);
8872 		dtrace_strunref(probe->dtpr_name);
8873 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8874 		zfree(dtrace_probe_t_zone, probe);
8875 	}
8876 
8877 	if ((prev = dtrace_provider) == old) {
8878 		ASSERT(self || dtrace_devi == NULL);
8879 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8880 		dtrace_provider = old->dtpv_next;
8881 	} else {
8882 		while (prev != NULL && prev->dtpv_next != old)
8883 			prev = prev->dtpv_next;
8884 
8885 		if (prev == NULL) {
8886 			panic("attempt to unregister non-existent "
8887 			    "dtrace provider %p\n", (void *)id);
8888 		}
8889 
8890 		prev->dtpv_next = old->dtpv_next;
8891 	}
8892 
8893 	dtrace_strunref(old->dtpv_name);
8894 
8895 	if (!self) {
8896 		lck_mtx_unlock(&dtrace_lock);
8897 		lck_mtx_unlock(&mod_lock);
8898 		lck_mtx_unlock(&dtrace_provider_lock);
8899 	}
8900 
8901 	kmem_free(old, sizeof (dtrace_provider_t));
8902 
8903 	return (0);
8904 }
8905 
8906 /*
8907  * Invalidate the specified provider.  All subsequent probe lookups for the
8908  * specified provider will fail, but its probes will not be removed.
8909  */
8910 void
dtrace_invalidate(dtrace_provider_id_t id)8911 dtrace_invalidate(dtrace_provider_id_t id)
8912 {
8913 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8914 
8915 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8916 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8917 
8918 	lck_mtx_lock(&dtrace_provider_lock);
8919 	lck_mtx_lock(&dtrace_lock);
8920 
8921 	pvp->dtpv_defunct = 1;
8922 
8923 	lck_mtx_unlock(&dtrace_lock);
8924 	lck_mtx_unlock(&dtrace_provider_lock);
8925 }
8926 
8927 /*
8928  * Indicate whether or not DTrace has attached.
8929  */
8930 int
dtrace_attached(void)8931 dtrace_attached(void)
8932 {
8933 	/*
8934 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8935 	 * attached.  (It's non-NULL because DTrace is always itself a
8936 	 * provider.)
8937 	 */
8938 	return (dtrace_provider != NULL);
8939 }
8940 
8941 /*
8942  * Remove all the unenabled probes for the given provider.  This function is
8943  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8944  * -- just as many of its associated probes as it can.
8945  */
8946 int
dtrace_condense(dtrace_provider_id_t id)8947 dtrace_condense(dtrace_provider_id_t id)
8948 {
8949 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8950 	dtrace_probe_t *probe, *first = NULL;
8951 	dtrace_probe_t template = {
8952 		.dtpr_provider = prov
8953 	};
8954 
8955 	/*
8956 	 * Make sure this isn't the dtrace provider itself.
8957 	 */
8958 	ASSERT(prov->dtpv_pops.dtps_enable !=
8959 	  (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8960 
8961 	lck_mtx_lock(&dtrace_provider_lock);
8962 	lck_mtx_lock(&dtrace_lock);
8963 
8964 	/*
8965 	 * Attempt to destroy the probes associated with this provider.
8966 	 */
8967 	for (probe = dtrace_hash_lookup(dtrace_byprov, &template); probe != NULL;
8968 	    probe = *(DTRACE_HASHNEXT(dtrace_byprov, probe))) {
8969 
8970 		if (probe->dtpr_provider != prov)
8971 			continue;
8972 
8973 		if (probe->dtpr_ecb != NULL)
8974 			continue;
8975 
8976 		dtrace_probes[probe->dtpr_id - 1] = NULL;
8977 		prov->dtpv_probe_count--;
8978 
8979 		dtrace_hash_remove(dtrace_bymod, probe);
8980 		dtrace_hash_remove(dtrace_byfunc, probe);
8981 		dtrace_hash_remove(dtrace_byname, probe);
8982 
8983 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
8984 		    probe->dtpr_arg);
8985 		dtrace_strunref(probe->dtpr_mod);
8986 		dtrace_strunref(probe->dtpr_func);
8987 		dtrace_strunref(probe->dtpr_name);
8988 		if (first == NULL) {
8989 			first = probe;
8990 			probe->dtpr_nextmod = NULL;
8991 		} else {
8992 			/*
8993 			 * Use nextmod as the chain of probes to remove
8994 			 */
8995 			probe->dtpr_nextmod = first;
8996 			first = probe;
8997 		}
8998 	}
8999 
9000 	for (probe = first; probe != NULL; probe = first) {
9001 		first = probe->dtpr_nextmod;
9002 		dtrace_hash_remove(dtrace_byprov, probe);
9003 		vmem_free(dtrace_arena, (void *)((uintptr_t)probe->dtpr_id), 1);
9004 		zfree(dtrace_probe_t_zone, probe);
9005 	}
9006 
9007 	lck_mtx_unlock(&dtrace_lock);
9008 	lck_mtx_unlock(&dtrace_provider_lock);
9009 
9010 	return (0);
9011 }
9012 
9013 /*
9014  * DTrace Probe Management Functions
9015  *
9016  * The functions in this section perform the DTrace probe management,
9017  * including functions to create probes, look-up probes, and call into the
9018  * providers to request that probes be provided.  Some of these functions are
9019  * in the Provider-to-Framework API; these functions can be identified by the
9020  * fact that they are not declared "static".
9021  */
9022 
9023 /*
9024  * Create a probe with the specified module name, function name, and name.
9025  */
9026 dtrace_id_t
dtrace_probe_create(dtrace_provider_id_t prov,const char * mod,const char * func,const char * name,int aframes,void * arg)9027 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9028     const char *func, const char *name, int aframes, void *arg)
9029 {
9030 	dtrace_probe_t *probe, **probes;
9031 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9032 	dtrace_id_t id;
9033 
9034 	if (provider == dtrace_provider) {
9035 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9036 	} else {
9037 		lck_mtx_lock(&dtrace_lock);
9038 	}
9039 
9040 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9041 	    VM_BESTFIT | VM_SLEEP);
9042 
9043 	probe = zalloc_flags(dtrace_probe_t_zone, Z_WAITOK | Z_ZERO);
9044 
9045 	probe->dtpr_id = id;
9046 	probe->dtpr_gen = dtrace_probegen++;
9047 	probe->dtpr_mod = dtrace_strref(mod);
9048 	probe->dtpr_func = dtrace_strref(func);
9049 	probe->dtpr_name = dtrace_strref(name);
9050 	probe->dtpr_arg = arg;
9051 	probe->dtpr_aframes = aframes;
9052 	probe->dtpr_provider = provider;
9053 
9054 	dtrace_hash_add(dtrace_byprov, probe);
9055 	dtrace_hash_add(dtrace_bymod, probe);
9056 	dtrace_hash_add(dtrace_byfunc, probe);
9057 	dtrace_hash_add(dtrace_byname, probe);
9058 
9059 	if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
9060 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9061 		size_t nsize = osize * 2;
9062 
9063 		probes = kmem_zalloc(nsize, KM_SLEEP);
9064 
9065 		dtrace_probe_t **oprobes = dtrace_probes;
9066 
9067 		bcopy(oprobes, probes, osize);
9068 		dtrace_membar_producer();
9069 		dtrace_probes = probes;
9070 
9071 		dtrace_sync();
9072 
9073 		/*
9074 		 * All CPUs are now seeing the new probes array; we can
9075 		 * safely free the old array.
9076 		 */
9077 		kmem_free(oprobes, osize);
9078 		dtrace_nprobes *= 2;
9079 
9080 		ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
9081 	}
9082 
9083 	ASSERT(dtrace_probes[id - 1] == NULL);
9084 	dtrace_probes[id - 1] = probe;
9085 	provider->dtpv_probe_count++;
9086 
9087 	if (provider != dtrace_provider)
9088 		lck_mtx_unlock(&dtrace_lock);
9089 
9090 	return (id);
9091 }
9092 
9093 static dtrace_probe_t *
dtrace_probe_lookup_id(dtrace_id_t id)9094 dtrace_probe_lookup_id(dtrace_id_t id)
9095 {
9096 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9097 
9098 	if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
9099 		return (NULL);
9100 
9101 	return (dtrace_probes[id - 1]);
9102 }
9103 
9104 static int
dtrace_probe_lookup_match(dtrace_probe_t * probe,void * arg1,void * arg2)9105 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg1, void *arg2)
9106 {
9107 #pragma unused(arg2)
9108 	*((dtrace_id_t *)arg1) = probe->dtpr_id;
9109 
9110 	return (DTRACE_MATCH_DONE);
9111 }
9112 
9113 /*
9114  * Look up a probe based on provider and one or more of module name, function
9115  * name and probe name.
9116  */
9117 dtrace_id_t
dtrace_probe_lookup(dtrace_provider_id_t prid,const char * mod,const char * func,const char * name)9118 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
9119     const char *func, const char *name)
9120 {
9121 	dtrace_probekey_t pkey;
9122 	dtrace_id_t id;
9123 	int match;
9124 
9125 	lck_mtx_lock(&dtrace_lock);
9126 
9127 	pkey.dtpk_prov = dtrace_strref(((dtrace_provider_t *)prid)->dtpv_name);
9128 	pkey.dtpk_pmatch = &dtrace_match_string;
9129 	pkey.dtpk_mod = dtrace_strref(mod);
9130 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9131 	pkey.dtpk_func = dtrace_strref(func);
9132 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9133 	pkey.dtpk_name = dtrace_strref(name);
9134 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9135 	pkey.dtpk_id = DTRACE_IDNONE;
9136 
9137 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9138 	    dtrace_probe_lookup_match, &id, NULL);
9139 
9140 	dtrace_probekey_release(&pkey);
9141 
9142 	lck_mtx_unlock(&dtrace_lock);
9143 
9144 	ASSERT(match == 1 || match == 0);
9145 	return (match ? id : 0);
9146 }
9147 
9148 /*
9149  * Returns the probe argument associated with the specified probe.
9150  */
9151 void *
dtrace_probe_arg(dtrace_provider_id_t id,dtrace_id_t pid)9152 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9153 {
9154 	dtrace_probe_t *probe;
9155 	void *rval = NULL;
9156 
9157 	lck_mtx_lock(&dtrace_lock);
9158 
9159 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9160 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9161 		rval = probe->dtpr_arg;
9162 
9163 	lck_mtx_unlock(&dtrace_lock);
9164 
9165 	return (rval);
9166 }
9167 
9168 /*
9169  * Copy a probe into a probe description.
9170  */
9171 static void
dtrace_probe_description(const dtrace_probe_t * prp,dtrace_probedesc_t * pdp)9172 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9173 {
9174 	bzero(pdp, sizeof (dtrace_probedesc_t));
9175 	pdp->dtpd_id = prp->dtpr_id;
9176 
9177 	/* APPLE NOTE: Darwin employs size bounded string operation. */
9178 	(void) strlcpy(pdp->dtpd_provider,
9179 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
9180 
9181 	(void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
9182 	(void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
9183 	(void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
9184 }
9185 
9186 /*
9187  * Called to indicate that a probe -- or probes -- should be provided by a
9188  * specfied provider.  If the specified description is NULL, the provider will
9189  * be told to provide all of its probes.  (This is done whenever a new
9190  * consumer comes along, or whenever a retained enabling is to be matched.) If
9191  * the specified description is non-NULL, the provider is given the
9192  * opportunity to dynamically provide the specified probe, allowing providers
9193  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9194  * probes.)  If the provider is NULL, the operations will be applied to all
9195  * providers; if the provider is non-NULL the operations will only be applied
9196  * to the specified provider.  The dtrace_provider_lock must be held, and the
9197  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9198  * will need to grab the dtrace_lock when it reenters the framework through
9199  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9200  */
9201 static void
dtrace_probe_provide(dtrace_probedesc_t * desc,dtrace_provider_t * prv)9202 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9203 {
9204 	struct modctl *ctl;
9205 	int all = 0;
9206 
9207 	LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
9208 
9209 	if (prv == NULL) {
9210 		all = 1;
9211 		prv = dtrace_provider;
9212 	}
9213 
9214 	do {
9215 		/*
9216 		 * First, call the blanket provide operation.
9217 		 */
9218 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9219 
9220 		/*
9221 		 * Now call the per-module provide operation.  We will grab
9222 		 * mod_lock to prevent the list from being modified.  Note
9223 		 * that this also prevents the mod_busy bits from changing.
9224 		 * (mod_busy can only be changed with mod_lock held.)
9225 		 */
9226 		lck_mtx_lock(&mod_lock);
9227 
9228 		ctl = dtrace_modctl_list;
9229 		while (ctl) {
9230 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9231 			ctl = ctl->mod_next;
9232 		}
9233 
9234 		lck_mtx_unlock(&mod_lock);
9235 	} while (all && (prv = prv->dtpv_next) != NULL);
9236 }
9237 
9238 /*
9239  * Iterate over each probe, and call the Framework-to-Provider API function
9240  * denoted by offs.
9241  */
9242 static void
dtrace_probe_foreach(uintptr_t offs)9243 dtrace_probe_foreach(uintptr_t offs)
9244 {
9245 	dtrace_provider_t *prov;
9246 	void (*func)(void *, dtrace_id_t, void *);
9247 	dtrace_probe_t *probe;
9248 	dtrace_icookie_t cookie;
9249 	int i;
9250 
9251 	/*
9252 	 * We disable interrupts to walk through the probe array.  This is
9253 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9254 	 * won't see stale data.
9255 	 */
9256 	cookie = dtrace_interrupt_disable();
9257 
9258 	for (i = 0; i < dtrace_nprobes; i++) {
9259 		if ((probe = dtrace_probes[i]) == NULL)
9260 			continue;
9261 
9262 		if (probe->dtpr_ecb == NULL) {
9263 			/*
9264 			 * This probe isn't enabled -- don't call the function.
9265 			 */
9266 			continue;
9267 		}
9268 
9269 		prov = probe->dtpr_provider;
9270 		func = *((void(**)(void *, dtrace_id_t, void *))
9271 		    ((uintptr_t)&prov->dtpv_pops + offs));
9272 
9273 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9274 	}
9275 
9276 	dtrace_interrupt_enable(cookie);
9277 }
9278 
9279 static int
dtrace_probe_enable(const dtrace_probedesc_t * desc,dtrace_enabling_t * enab,dtrace_ecbdesc_t * ep)9280 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab, dtrace_ecbdesc_t *ep)
9281 {
9282 	dtrace_probekey_t pkey;
9283 	uint32_t priv;
9284 	uid_t uid;
9285 	zoneid_t zoneid;
9286 	int err;
9287 
9288 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9289 
9290 	dtrace_ecb_create_cache = NULL;
9291 
9292 	if (desc == NULL) {
9293 		/*
9294 		 * If we're passed a NULL description, we're being asked to
9295 		 * create an ECB with a NULL probe.
9296 		 */
9297 		(void) dtrace_ecb_create_enable(NULL, enab, ep);
9298 		return (0);
9299 	}
9300 
9301 	dtrace_probekey(desc, &pkey);
9302 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9303 	    &priv, &uid, &zoneid);
9304 
9305 	err = dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable, enab, ep);
9306 
9307 	dtrace_probekey_release(&pkey);
9308 
9309 	return err;
9310 }
9311 
9312 /*
9313  * DTrace Helper Provider Functions
9314  */
9315 static void
dtrace_dofattr2attr(dtrace_attribute_t * attr,const dof_attr_t dofattr)9316 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9317 {
9318 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9319 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9320 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9321 }
9322 
9323 static void
dtrace_dofprov2hprov(dtrace_helper_provdesc_t * hprov,const dof_provider_t * dofprov,char * strtab)9324 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9325     const dof_provider_t *dofprov, char *strtab)
9326 {
9327 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9328 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9329 	    dofprov->dofpv_provattr);
9330 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9331 	    dofprov->dofpv_modattr);
9332 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9333 	    dofprov->dofpv_funcattr);
9334 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9335 	    dofprov->dofpv_nameattr);
9336 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9337 	    dofprov->dofpv_argsattr);
9338 }
9339 
9340 static void
dtrace_helper_provide_one(dof_helper_t * dhp,dof_sec_t * sec,proc_t * p)9341 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
9342 {
9343 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9344 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9345 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9346 	dof_provider_t *provider;
9347 	dof_probe_t *probe;
9348 	uint32_t *off, *enoff;
9349 	uint8_t *arg;
9350 	char *strtab;
9351 	uint_t i, nprobes;
9352 	dtrace_helper_provdesc_t dhpv;
9353 	dtrace_helper_probedesc_t dhpb;
9354 	dtrace_meta_t *meta = dtrace_meta_pid;
9355 	dtrace_mops_t *mops = &meta->dtm_mops;
9356 	void *parg;
9357 
9358 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9359 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9360 	    provider->dofpv_strtab * dof->dofh_secsize);
9361 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9362 	    provider->dofpv_probes * dof->dofh_secsize);
9363 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9364 	    provider->dofpv_prargs * dof->dofh_secsize);
9365 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9366 	    provider->dofpv_proffs * dof->dofh_secsize);
9367 
9368 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9369 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9370 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9371 	enoff = NULL;
9372 
9373 	/*
9374 	 * See dtrace_helper_provider_validate().
9375 	 */
9376 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9377 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9378 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9379 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9380 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9381 	}
9382 
9383 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9384 
9385 	/*
9386 	 * Create the provider.
9387 	 */
9388 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9389 
9390 	if ((parg = mops->dtms_provide_proc(meta->dtm_arg, &dhpv, p)) == NULL)
9391 		return;
9392 
9393 	meta->dtm_count++;
9394 
9395 	/*
9396 	 * Create the probes.
9397 	 */
9398 	for (i = 0; i < nprobes; i++) {
9399 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9400 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9401 
9402 		dhpb.dthpb_mod = dhp->dofhp_mod;
9403 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9404 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9405 #if !defined(__APPLE__)
9406 		dhpb.dthpb_base = probe->dofpr_addr;
9407 #else
9408 		dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
9409 #endif
9410 		dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
9411 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9412 		if (enoff != NULL) {
9413 			dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
9414 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9415 		} else {
9416 			dhpb.dthpb_enoffs = NULL;
9417 			dhpb.dthpb_nenoffs = 0;
9418 		}
9419 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9420 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9421 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9422 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9423 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9424 
9425 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9426 	}
9427 
9428 	/*
9429 	 * Since we just created probes, we need to match our enablings
9430 	 * against those, with a precondition knowing that we have only
9431 	 * added probes from this provider
9432 	 */
9433 	char *prov_name = mops->dtms_provider_name(parg);
9434 	ASSERT(prov_name != NULL);
9435 	dtrace_match_cond_t cond = {dtrace_cond_provider_match, (void*)prov_name};
9436 
9437 	dtrace_enabling_matchall_with_cond(&cond);
9438 }
9439 
9440 static void
dtrace_helper_provide(dof_helper_t * dhp,proc_t * p)9441 dtrace_helper_provide(dof_helper_t *dhp, proc_t *p)
9442 {
9443 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9444 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9445 	uint32_t i;
9446 
9447 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
9448 
9449 	for (i = 0; i < dof->dofh_secnum; i++) {
9450 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9451 		    dof->dofh_secoff + i * dof->dofh_secsize);
9452 
9453 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9454 			continue;
9455 
9456 		dtrace_helper_provide_one(dhp, sec, p);
9457 	}
9458 }
9459 
9460 static void
dtrace_helper_provider_remove_one(dof_helper_t * dhp,dof_sec_t * sec,proc_t * p)9461 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
9462 {
9463 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9464 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9465 	dof_sec_t *str_sec;
9466 	dof_provider_t *provider;
9467 	char *strtab;
9468 	dtrace_helper_provdesc_t dhpv;
9469 	dtrace_meta_t *meta = dtrace_meta_pid;
9470 	dtrace_mops_t *mops = &meta->dtm_mops;
9471 
9472 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9473 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9474 	    provider->dofpv_strtab * dof->dofh_secsize);
9475 
9476 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9477 
9478 	/*
9479 	 * Create the provider.
9480 	 */
9481 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9482 
9483 	mops->dtms_remove_proc(meta->dtm_arg, &dhpv, p);
9484 
9485 	meta->dtm_count--;
9486 }
9487 
9488 static void
dtrace_helper_provider_remove(dof_helper_t * dhp,proc_t * p)9489 dtrace_helper_provider_remove(dof_helper_t *dhp, proc_t *p)
9490 {
9491 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9492 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9493 	uint32_t i;
9494 
9495 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
9496 
9497 	for (i = 0; i < dof->dofh_secnum; i++) {
9498 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9499 		    dof->dofh_secoff + i * dof->dofh_secsize);
9500 
9501 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9502 			continue;
9503 
9504 		dtrace_helper_provider_remove_one(dhp, sec, p);
9505 	}
9506 }
9507 
9508 /*
9509  * DTrace Meta Provider-to-Framework API Functions
9510  *
9511  * These functions implement the Meta Provider-to-Framework API, as described
9512  * in <sys/dtrace.h>.
9513  */
9514 int
dtrace_meta_register(const char * name,const dtrace_mops_t * mops,void * arg,dtrace_meta_provider_id_t * idp)9515 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9516     dtrace_meta_provider_id_t *idp)
9517 {
9518 	dtrace_meta_t *meta;
9519 	dtrace_helpers_t *help, *next;
9520 	uint_t i;
9521 
9522 	*idp = DTRACE_METAPROVNONE;
9523 
9524 	/*
9525 	 * We strictly don't need the name, but we hold onto it for
9526 	 * debuggability. All hail error queues!
9527 	 */
9528 	if (name == NULL) {
9529 		cmn_err(CE_WARN, "failed to register meta-provider: "
9530 		    "invalid name");
9531 		return (EINVAL);
9532 	}
9533 
9534 	if (mops == NULL ||
9535 	    mops->dtms_create_probe == NULL ||
9536 	    mops->dtms_provide_proc == NULL ||
9537 	    mops->dtms_remove_proc == NULL) {
9538 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9539 		    "invalid ops", name);
9540 		return (EINVAL);
9541 	}
9542 
9543 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9544 	meta->dtm_mops = *mops;
9545 	meta->dtm_arg = arg;
9546 
9547 	lck_mtx_lock(&dtrace_meta_lock);
9548 	lck_mtx_lock(&dtrace_lock);
9549 
9550 	if (dtrace_meta_pid != NULL) {
9551 		lck_mtx_unlock(&dtrace_lock);
9552 		lck_mtx_unlock(&dtrace_meta_lock);
9553 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9554 		    "user-land meta-provider exists", name);
9555 		kmem_free(meta, sizeof (dtrace_meta_t));
9556 		return (EINVAL);
9557 	}
9558 
9559 	meta->dtm_name = dtrace_strref(name);
9560 
9561 	dtrace_meta_pid = meta;
9562 	*idp = (dtrace_meta_provider_id_t)meta;
9563 
9564 	/*
9565 	 * If there are providers and probes ready to go, pass them
9566 	 * off to the new meta provider now.
9567 	 */
9568 
9569 	help = dtrace_deferred_pid;
9570 	dtrace_deferred_pid = NULL;
9571 
9572 	lck_mtx_unlock(&dtrace_lock);
9573 
9574 	while (help != NULL) {
9575 		for (i = 0; i < help->dthps_nprovs; i++) {
9576 			proc_t *p = proc_find(help->dthps_pid);
9577 			if (p == PROC_NULL)
9578 				continue;
9579 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9580 			    p);
9581 			proc_rele(p);
9582 		}
9583 
9584 		next = help->dthps_next;
9585 		help->dthps_next = NULL;
9586 		help->dthps_prev = NULL;
9587 		help->dthps_deferred = 0;
9588 		help = next;
9589 	}
9590 
9591 	lck_mtx_unlock(&dtrace_meta_lock);
9592 
9593 	return (0);
9594 }
9595 
9596 int
dtrace_meta_unregister(dtrace_meta_provider_id_t id)9597 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9598 {
9599 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9600 
9601 	lck_mtx_lock(&dtrace_meta_lock);
9602 	lck_mtx_lock(&dtrace_lock);
9603 
9604 	if (old == dtrace_meta_pid) {
9605 		pp = &dtrace_meta_pid;
9606 	} else {
9607 		panic("attempt to unregister non-existent "
9608 		    "dtrace meta-provider %p\n", (void *)old);
9609 	}
9610 
9611 	if (old->dtm_count != 0) {
9612 		lck_mtx_unlock(&dtrace_lock);
9613 		lck_mtx_unlock(&dtrace_meta_lock);
9614 		return (EBUSY);
9615 	}
9616 
9617 	*pp = NULL;
9618 
9619 	dtrace_strunref(old->dtm_name);
9620 
9621 	lck_mtx_unlock(&dtrace_lock);
9622 	lck_mtx_unlock(&dtrace_meta_lock);
9623 
9624 	kmem_free(old, sizeof (dtrace_meta_t));
9625 
9626 	return (0);
9627 }
9628 
9629 
9630 /*
9631  * DTrace DIF Object Functions
9632  */
9633 static int
dtrace_difo_err(uint_t pc,const char * format,...)9634 dtrace_difo_err(uint_t pc, const char *format, ...)
9635 {
9636 	if (dtrace_err_verbose) {
9637 		va_list alist;
9638 
9639 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9640 		va_start(alist, format);
9641 		(void) vuprintf(format, alist);
9642 		va_end(alist);
9643 	}
9644 
9645 #ifdef DTRACE_ERRDEBUG
9646 	dtrace_errdebug(format);
9647 #endif
9648 	return (1);
9649 }
9650 
9651 /*
9652  * Validate a DTrace DIF object by checking the IR instructions.  The following
9653  * rules are currently enforced by dtrace_difo_validate():
9654  *
9655  * 1. Each instruction must have a valid opcode
9656  * 2. Each register, string, variable, or subroutine reference must be valid
9657  * 3. No instruction can modify register %r0 (must be zero)
9658  * 4. All instruction reserved bits must be set to zero
9659  * 5. The last instruction must be a "ret" instruction
9660  * 6. All branch targets must reference a valid instruction _after_ the branch
9661  */
9662 static int
dtrace_difo_validate(dtrace_difo_t * dp,dtrace_vstate_t * vstate,uint_t nregs,cred_t * cr)9663 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9664     cred_t *cr)
9665 {
9666 	int err = 0;
9667 	uint_t i;
9668 
9669 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9670 	int kcheckload;
9671 	uint_t pc;
9672 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9673 
9674 	kcheckload = cr == NULL ||
9675 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9676 
9677 	dp->dtdo_destructive = 0;
9678 
9679 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9680 		dif_instr_t instr = dp->dtdo_buf[pc];
9681 
9682 		uint_t r1 = DIF_INSTR_R1(instr);
9683 		uint_t r2 = DIF_INSTR_R2(instr);
9684 		uint_t rd = DIF_INSTR_RD(instr);
9685 		uint_t rs = DIF_INSTR_RS(instr);
9686 		uint_t label = DIF_INSTR_LABEL(instr);
9687 		uint_t v = DIF_INSTR_VAR(instr);
9688 		uint_t subr = DIF_INSTR_SUBR(instr);
9689 		uint_t type = DIF_INSTR_TYPE(instr);
9690 		uint_t op = DIF_INSTR_OP(instr);
9691 
9692 		switch (op) {
9693 		case DIF_OP_OR:
9694 		case DIF_OP_XOR:
9695 		case DIF_OP_AND:
9696 		case DIF_OP_SLL:
9697 		case DIF_OP_SRL:
9698 		case DIF_OP_SRA:
9699 		case DIF_OP_SUB:
9700 		case DIF_OP_ADD:
9701 		case DIF_OP_MUL:
9702 		case DIF_OP_SDIV:
9703 		case DIF_OP_UDIV:
9704 		case DIF_OP_SREM:
9705 		case DIF_OP_UREM:
9706 		case DIF_OP_COPYS:
9707 			if (r1 >= nregs)
9708 				err += efunc(pc, "invalid register %u\n", r1);
9709 			if (r2 >= nregs)
9710 				err += efunc(pc, "invalid register %u\n", r2);
9711 			if (rd >= nregs)
9712 				err += efunc(pc, "invalid register %u\n", rd);
9713 			if (rd == 0)
9714 				err += efunc(pc, "cannot write to %%r0\n");
9715 			break;
9716 		case DIF_OP_NOT:
9717 		case DIF_OP_MOV:
9718 		case DIF_OP_ALLOCS:
9719 			if (r1 >= nregs)
9720 				err += efunc(pc, "invalid register %u\n", r1);
9721 			if (r2 != 0)
9722 				err += efunc(pc, "non-zero reserved bits\n");
9723 			if (rd >= nregs)
9724 				err += efunc(pc, "invalid register %u\n", rd);
9725 			if (rd == 0)
9726 				err += efunc(pc, "cannot write to %%r0\n");
9727 			break;
9728 		case DIF_OP_LDSB:
9729 		case DIF_OP_LDSH:
9730 		case DIF_OP_LDSW:
9731 		case DIF_OP_LDUB:
9732 		case DIF_OP_LDUH:
9733 		case DIF_OP_LDUW:
9734 		case DIF_OP_LDX:
9735 			if (r1 >= nregs)
9736 				err += efunc(pc, "invalid register %u\n", r1);
9737 			if (r2 != 0)
9738 				err += efunc(pc, "non-zero reserved bits\n");
9739 			if (rd >= nregs)
9740 				err += efunc(pc, "invalid register %u\n", rd);
9741 			if (rd == 0)
9742 				err += efunc(pc, "cannot write to %%r0\n");
9743 			if (kcheckload)
9744 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9745 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9746 			break;
9747 		case DIF_OP_RLDSB:
9748 		case DIF_OP_RLDSH:
9749 		case DIF_OP_RLDSW:
9750 		case DIF_OP_RLDUB:
9751 		case DIF_OP_RLDUH:
9752 		case DIF_OP_RLDUW:
9753 		case DIF_OP_RLDX:
9754 			if (r1 >= nregs)
9755 				err += efunc(pc, "invalid register %u\n", r1);
9756 			if (r2 != 0)
9757 				err += efunc(pc, "non-zero reserved bits\n");
9758 			if (rd >= nregs)
9759 				err += efunc(pc, "invalid register %u\n", rd);
9760 			if (rd == 0)
9761 				err += efunc(pc, "cannot write to %%r0\n");
9762 			break;
9763 		case DIF_OP_ULDSB:
9764 		case DIF_OP_ULDSH:
9765 		case DIF_OP_ULDSW:
9766 		case DIF_OP_ULDUB:
9767 		case DIF_OP_ULDUH:
9768 		case DIF_OP_ULDUW:
9769 		case DIF_OP_ULDX:
9770 			if (r1 >= nregs)
9771 				err += efunc(pc, "invalid register %u\n", r1);
9772 			if (r2 != 0)
9773 				err += efunc(pc, "non-zero reserved bits\n");
9774 			if (rd >= nregs)
9775 				err += efunc(pc, "invalid register %u\n", rd);
9776 			if (rd == 0)
9777 				err += efunc(pc, "cannot write to %%r0\n");
9778 			break;
9779 		case DIF_OP_STB:
9780 		case DIF_OP_STH:
9781 		case DIF_OP_STW:
9782 		case DIF_OP_STX:
9783 			if (r1 >= nregs)
9784 				err += efunc(pc, "invalid register %u\n", r1);
9785 			if (r2 != 0)
9786 				err += efunc(pc, "non-zero reserved bits\n");
9787 			if (rd >= nregs)
9788 				err += efunc(pc, "invalid register %u\n", rd);
9789 			if (rd == 0)
9790 				err += efunc(pc, "cannot write to 0 address\n");
9791 			break;
9792 		case DIF_OP_CMP:
9793 		case DIF_OP_SCMP:
9794 			if (r1 >= nregs)
9795 				err += efunc(pc, "invalid register %u\n", r1);
9796 			if (r2 >= nregs)
9797 				err += efunc(pc, "invalid register %u\n", r2);
9798 			if (rd != 0)
9799 				err += efunc(pc, "non-zero reserved bits\n");
9800 			break;
9801 		case DIF_OP_TST:
9802 			if (r1 >= nregs)
9803 				err += efunc(pc, "invalid register %u\n", r1);
9804 			if (r2 != 0 || rd != 0)
9805 				err += efunc(pc, "non-zero reserved bits\n");
9806 			break;
9807 		case DIF_OP_BA:
9808 		case DIF_OP_BE:
9809 		case DIF_OP_BNE:
9810 		case DIF_OP_BG:
9811 		case DIF_OP_BGU:
9812 		case DIF_OP_BGE:
9813 		case DIF_OP_BGEU:
9814 		case DIF_OP_BL:
9815 		case DIF_OP_BLU:
9816 		case DIF_OP_BLE:
9817 		case DIF_OP_BLEU:
9818 			if (label >= dp->dtdo_len) {
9819 				err += efunc(pc, "invalid branch target %u\n",
9820 				    label);
9821 			}
9822 			if (label <= pc) {
9823 				err += efunc(pc, "backward branch to %u\n",
9824 				    label);
9825 			}
9826 			break;
9827 		case DIF_OP_RET:
9828 			if (r1 != 0 || r2 != 0)
9829 				err += efunc(pc, "non-zero reserved bits\n");
9830 			if (rd >= nregs)
9831 				err += efunc(pc, "invalid register %u\n", rd);
9832 			break;
9833 		case DIF_OP_NOP:
9834 		case DIF_OP_POPTS:
9835 		case DIF_OP_FLUSHTS:
9836 			if (r1 != 0 || r2 != 0 || rd != 0)
9837 				err += efunc(pc, "non-zero reserved bits\n");
9838 			break;
9839 		case DIF_OP_SETX:
9840 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9841 				err += efunc(pc, "invalid integer ref %u\n",
9842 				    DIF_INSTR_INTEGER(instr));
9843 			}
9844 			if (rd >= nregs)
9845 				err += efunc(pc, "invalid register %u\n", rd);
9846 			if (rd == 0)
9847 				err += efunc(pc, "cannot write to %%r0\n");
9848 			break;
9849 		case DIF_OP_SETS:
9850 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9851 				err += efunc(pc, "invalid string ref %u\n",
9852 				    DIF_INSTR_STRING(instr));
9853 			}
9854 			if (rd >= nregs)
9855 				err += efunc(pc, "invalid register %u\n", rd);
9856 			if (rd == 0)
9857 				err += efunc(pc, "cannot write to %%r0\n");
9858 			break;
9859 		case DIF_OP_LDGA:
9860 		case DIF_OP_LDTA:
9861 			if (r1 > DIF_VAR_ARRAY_MAX)
9862 				err += efunc(pc, "invalid array %u\n", r1);
9863 			if (r2 >= nregs)
9864 				err += efunc(pc, "invalid register %u\n", r2);
9865 			if (rd >= nregs)
9866 				err += efunc(pc, "invalid register %u\n", rd);
9867 			if (rd == 0)
9868 				err += efunc(pc, "cannot write to %%r0\n");
9869 			break;
9870 		case DIF_OP_LDGS:
9871 		case DIF_OP_LDTS:
9872 		case DIF_OP_LDLS:
9873 		case DIF_OP_LDGAA:
9874 		case DIF_OP_LDTAA:
9875 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9876 				err += efunc(pc, "invalid variable %u\n", v);
9877 			if (rd >= nregs)
9878 				err += efunc(pc, "invalid register %u\n", rd);
9879 			if (rd == 0)
9880 				err += efunc(pc, "cannot write to %%r0\n");
9881 			break;
9882 		case DIF_OP_STGS:
9883 		case DIF_OP_STTS:
9884 		case DIF_OP_STLS:
9885 		case DIF_OP_STGAA:
9886 		case DIF_OP_STTAA:
9887 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9888 				err += efunc(pc, "invalid variable %u\n", v);
9889 			if (rs >= nregs)
9890 				err += efunc(pc, "invalid register %u\n", rd);
9891 			break;
9892 		case DIF_OP_CALL:
9893 			if (subr > DIF_SUBR_MAX &&
9894 			   !(subr >= DIF_SUBR_APPLE_MIN && subr <= DIF_SUBR_APPLE_MAX))
9895 				err += efunc(pc, "invalid subr %u\n", subr);
9896 			if (rd >= nregs)
9897 				err += efunc(pc, "invalid register %u\n", rd);
9898 			if (rd == 0)
9899 				err += efunc(pc, "cannot write to %%r0\n");
9900 
9901 			switch (subr) {
9902 			case DIF_SUBR_COPYOUT:
9903 			case DIF_SUBR_COPYOUTSTR:
9904 			case DIF_SUBR_KDEBUG_TRACE:
9905 			case DIF_SUBR_KDEBUG_TRACE_STRING:
9906 			case DIF_SUBR_PHYSMEM_READ:
9907 			case DIF_SUBR_PHYSMEM_WRITE:
9908 			case DIF_SUBR_LIVEDUMP:
9909 				dp->dtdo_destructive = 1;
9910 				break;
9911 			default:
9912 				break;
9913 			}
9914 			break;
9915 		case DIF_OP_PUSHTR:
9916 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9917 				err += efunc(pc, "invalid ref type %u\n", type);
9918 			if (r2 >= nregs)
9919 				err += efunc(pc, "invalid register %u\n", r2);
9920 			if (rs >= nregs)
9921 				err += efunc(pc, "invalid register %u\n", rs);
9922 			break;
9923 		case DIF_OP_PUSHTV:
9924 			if (type != DIF_TYPE_CTF)
9925 				err += efunc(pc, "invalid val type %u\n", type);
9926 			if (r2 >= nregs)
9927 				err += efunc(pc, "invalid register %u\n", r2);
9928 			if (rs >= nregs)
9929 				err += efunc(pc, "invalid register %u\n", rs);
9930 			break;
9931 		case DIF_OP_STRIP:
9932 			if (r1 >= nregs)
9933 				err += efunc(pc, "invalid register %u\n", r1);
9934 			if (!dtrace_is_valid_ptrauth_key(r2))
9935 				err += efunc(pc, "invalid key\n");
9936 			if (rd >= nregs)
9937 				err += efunc(pc, "invalid register %u\n", rd);
9938 			if (rd == 0)
9939 				err += efunc(pc, "cannot write to %%r0\n");
9940 			break;
9941 		default:
9942 			err += efunc(pc, "invalid opcode %u\n",
9943 			    DIF_INSTR_OP(instr));
9944 		}
9945 	}
9946 
9947 	if (dp->dtdo_len != 0 &&
9948 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9949 		err += efunc(dp->dtdo_len - 1,
9950 		    "expected 'ret' as last DIF instruction\n");
9951 	}
9952 
9953 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9954 		/*
9955 		 * If we're not returning by reference, the size must be either
9956 		 * 0 or the size of one of the base types.
9957 		 */
9958 		switch (dp->dtdo_rtype.dtdt_size) {
9959 		case 0:
9960 		case sizeof (uint8_t):
9961 		case sizeof (uint16_t):
9962 		case sizeof (uint32_t):
9963 		case sizeof (uint64_t):
9964 			break;
9965 
9966 		default:
9967 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9968 		}
9969 	}
9970 
9971 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9972 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9973 		dtrace_diftype_t *vt, *et;
9974 		uint_t id;
9975 		int ndx;
9976 
9977 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9978 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9979 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9980 			err += efunc(i, "unrecognized variable scope %d\n",
9981 			    v->dtdv_scope);
9982 			break;
9983 		}
9984 
9985 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9986 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9987 			err += efunc(i, "unrecognized variable type %d\n",
9988 			    v->dtdv_kind);
9989 			break;
9990 		}
9991 
9992 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9993 			err += efunc(i, "%d exceeds variable id limit\n", id);
9994 			break;
9995 		}
9996 
9997 		if (id < DIF_VAR_OTHER_UBASE)
9998 			continue;
9999 
10000 		/*
10001 		 * For user-defined variables, we need to check that this
10002 		 * definition is identical to any previous definition that we
10003 		 * encountered.
10004 		 */
10005 		ndx = id - DIF_VAR_OTHER_UBASE;
10006 
10007 		switch (v->dtdv_scope) {
10008 		case DIFV_SCOPE_GLOBAL:
10009 			if (maxglobal == -1 || ndx > maxglobal)
10010 				maxglobal = ndx;
10011 
10012 			if (ndx < vstate->dtvs_nglobals) {
10013 				dtrace_statvar_t *svar;
10014 
10015 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10016 					existing = &svar->dtsv_var;
10017 			}
10018 
10019 			break;
10020 
10021 		case DIFV_SCOPE_THREAD:
10022 			if (maxtlocal == -1 || ndx > maxtlocal)
10023 				maxtlocal = ndx;
10024 
10025 			if (ndx < vstate->dtvs_ntlocals)
10026 				existing = &vstate->dtvs_tlocals[ndx];
10027 			break;
10028 
10029 		case DIFV_SCOPE_LOCAL:
10030 			if (maxlocal == -1 || ndx > maxlocal)
10031 				maxlocal = ndx;
10032 			if (ndx < vstate->dtvs_nlocals) {
10033 				dtrace_statvar_t *svar;
10034 
10035 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10036 					existing = &svar->dtsv_var;
10037 			}
10038 
10039 			break;
10040 		}
10041 
10042 		vt = &v->dtdv_type;
10043 
10044 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10045 			if (vt->dtdt_size == 0) {
10046 				err += efunc(i, "zero-sized variable\n");
10047 				break;
10048 			}
10049 
10050 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10051 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10052 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10053 				err += efunc(i, "oversized by-ref static\n");
10054 				break;
10055 			}
10056 		}
10057 
10058 		if (existing == NULL || existing->dtdv_id == 0)
10059 			continue;
10060 
10061 		ASSERT(existing->dtdv_id == v->dtdv_id);
10062 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10063 
10064 		if (existing->dtdv_kind != v->dtdv_kind)
10065 			err += efunc(i, "%d changed variable kind\n", id);
10066 
10067 		et = &existing->dtdv_type;
10068 
10069 		if (vt->dtdt_flags != et->dtdt_flags) {
10070 			err += efunc(i, "%d changed variable type flags\n", id);
10071 			break;
10072 		}
10073 
10074 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10075 			err += efunc(i, "%d changed variable type size\n", id);
10076 			break;
10077 		}
10078 	}
10079 
10080 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10081 		dif_instr_t instr = dp->dtdo_buf[pc];
10082 
10083 		uint_t v = DIF_INSTR_VAR(instr);
10084 		uint_t op = DIF_INSTR_OP(instr);
10085 
10086 		switch (op) {
10087 		case DIF_OP_LDGS:
10088 		case DIF_OP_LDGAA:
10089 		case DIF_OP_STGS:
10090 		case DIF_OP_STGAA:
10091 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxglobal))
10092 				err += efunc(pc, "invalid variable %u\n", v);
10093 			break;
10094 		case DIF_OP_LDTS:
10095 		case DIF_OP_LDTAA:
10096 		case DIF_OP_STTS:
10097 		case DIF_OP_STTAA:
10098 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxtlocal))
10099 				err += efunc(pc, "invalid variable %u\n", v);
10100 			break;
10101 		case DIF_OP_LDLS:
10102 		case DIF_OP_STLS:
10103 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxlocal))
10104 				err += efunc(pc, "invalid variable %u\n", v);
10105 			break;
10106 		default:
10107 			break;
10108 		}
10109 	}
10110 
10111 	return (err);
10112 }
10113 
10114 /*
10115  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10116  * are much more constrained than normal DIFOs.  Specifically, they may
10117  * not:
10118  *
10119  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10120  *    miscellaneous string routines
10121  * 2. Access DTrace variables other than the args[] array, and the
10122  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10123  * 3. Have thread-local variables.
10124  * 4. Have dynamic variables.
10125  */
10126 static int
dtrace_difo_validate_helper(dtrace_difo_t * dp)10127 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10128 {
10129 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10130 	int err = 0;
10131 	uint_t pc;
10132 
10133 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10134 		dif_instr_t instr = dp->dtdo_buf[pc];
10135 
10136 		uint_t v = DIF_INSTR_VAR(instr);
10137 		uint_t subr = DIF_INSTR_SUBR(instr);
10138 		uint_t op = DIF_INSTR_OP(instr);
10139 
10140 		switch (op) {
10141 		case DIF_OP_OR:
10142 		case DIF_OP_XOR:
10143 		case DIF_OP_AND:
10144 		case DIF_OP_SLL:
10145 		case DIF_OP_SRL:
10146 		case DIF_OP_SRA:
10147 		case DIF_OP_SUB:
10148 		case DIF_OP_ADD:
10149 		case DIF_OP_MUL:
10150 		case DIF_OP_SDIV:
10151 		case DIF_OP_UDIV:
10152 		case DIF_OP_SREM:
10153 		case DIF_OP_UREM:
10154 		case DIF_OP_COPYS:
10155 		case DIF_OP_NOT:
10156 		case DIF_OP_MOV:
10157 		case DIF_OP_RLDSB:
10158 		case DIF_OP_RLDSH:
10159 		case DIF_OP_RLDSW:
10160 		case DIF_OP_RLDUB:
10161 		case DIF_OP_RLDUH:
10162 		case DIF_OP_RLDUW:
10163 		case DIF_OP_RLDX:
10164 		case DIF_OP_ULDSB:
10165 		case DIF_OP_ULDSH:
10166 		case DIF_OP_ULDSW:
10167 		case DIF_OP_ULDUB:
10168 		case DIF_OP_ULDUH:
10169 		case DIF_OP_ULDUW:
10170 		case DIF_OP_ULDX:
10171 		case DIF_OP_STB:
10172 		case DIF_OP_STH:
10173 		case DIF_OP_STW:
10174 		case DIF_OP_STX:
10175 		case DIF_OP_ALLOCS:
10176 		case DIF_OP_CMP:
10177 		case DIF_OP_SCMP:
10178 		case DIF_OP_TST:
10179 		case DIF_OP_BA:
10180 		case DIF_OP_BE:
10181 		case DIF_OP_BNE:
10182 		case DIF_OP_BG:
10183 		case DIF_OP_BGU:
10184 		case DIF_OP_BGE:
10185 		case DIF_OP_BGEU:
10186 		case DIF_OP_BL:
10187 		case DIF_OP_BLU:
10188 		case DIF_OP_BLE:
10189 		case DIF_OP_BLEU:
10190 		case DIF_OP_RET:
10191 		case DIF_OP_NOP:
10192 		case DIF_OP_POPTS:
10193 		case DIF_OP_FLUSHTS:
10194 		case DIF_OP_SETX:
10195 		case DIF_OP_SETS:
10196 		case DIF_OP_LDGA:
10197 		case DIF_OP_LDLS:
10198 		case DIF_OP_STGS:
10199 		case DIF_OP_STLS:
10200 		case DIF_OP_PUSHTR:
10201 		case DIF_OP_PUSHTV:
10202 			break;
10203 
10204 		case DIF_OP_LDGS:
10205 			if (v >= DIF_VAR_OTHER_UBASE)
10206 				break;
10207 
10208 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10209 				break;
10210 
10211 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10212 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10213 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10214 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10215 				break;
10216 
10217 			err += efunc(pc, "illegal variable %u\n", v);
10218 			break;
10219 
10220 		case DIF_OP_LDTA:
10221 		case DIF_OP_LDTS:
10222 		case DIF_OP_LDGAA:
10223 		case DIF_OP_LDTAA:
10224 			err += efunc(pc, "illegal dynamic variable load\n");
10225 			break;
10226 
10227 		case DIF_OP_STTS:
10228 		case DIF_OP_STGAA:
10229 		case DIF_OP_STTAA:
10230 			err += efunc(pc, "illegal dynamic variable store\n");
10231 			break;
10232 
10233 		case DIF_OP_CALL:
10234 			switch (subr) {
10235 			case DIF_SUBR_ALLOCA:
10236 			case DIF_SUBR_BCOPY:
10237 			case DIF_SUBR_COPYIN:
10238 			case DIF_SUBR_COPYINTO:
10239 			case DIF_SUBR_COPYINSTR:
10240 			case DIF_SUBR_HTONS:
10241 			case DIF_SUBR_HTONL:
10242 			case DIF_SUBR_HTONLL:
10243 			case DIF_SUBR_INDEX:
10244 			case DIF_SUBR_INET_NTOA:
10245 			case DIF_SUBR_INET_NTOA6:
10246 			case DIF_SUBR_INET_NTOP:
10247 			case DIF_SUBR_JSON:
10248 			case DIF_SUBR_LLTOSTR:
10249 			case DIF_SUBR_NTOHS:
10250 			case DIF_SUBR_NTOHL:
10251 			case DIF_SUBR_NTOHLL:
10252 			case DIF_SUBR_RINDEX:
10253 			case DIF_SUBR_STRCHR:
10254 			case DIF_SUBR_STRTOLL:
10255 			case DIF_SUBR_STRJOIN:
10256 			case DIF_SUBR_STRRCHR:
10257 			case DIF_SUBR_STRSTR:
10258 				break;
10259 			default:
10260 				err += efunc(pc, "invalid subr %u\n", subr);
10261 			}
10262 			break;
10263 
10264 		default:
10265 			err += efunc(pc, "invalid opcode %u\n",
10266 			    DIF_INSTR_OP(instr));
10267 		}
10268 	}
10269 
10270 	return (err);
10271 }
10272 
10273 /*
10274  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10275  * basis; 0 if not.
10276  */
10277 static int
dtrace_difo_cacheable(dtrace_difo_t * dp)10278 dtrace_difo_cacheable(dtrace_difo_t *dp)
10279 {
10280 	uint_t i;
10281 
10282 	if (dp == NULL)
10283 		return (0);
10284 
10285 	for (i = 0; i < dp->dtdo_varlen; i++) {
10286 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10287 
10288 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10289 			continue;
10290 
10291 		switch (v->dtdv_id) {
10292 		case DIF_VAR_CURTHREAD:
10293 		case DIF_VAR_PID:
10294 		case DIF_VAR_TID:
10295 		case DIF_VAR_EXECNAME:
10296 		case DIF_VAR_ZONENAME:
10297 			break;
10298 
10299 		default:
10300 			return (0);
10301 		}
10302 	}
10303 
10304 	/*
10305 	 * This DIF object may be cacheable.  Now we need to look for any
10306 	 * array loading instructions, any memory loading instructions, or
10307 	 * any stores to thread-local variables.
10308 	 */
10309 	for (i = 0; i < dp->dtdo_len; i++) {
10310 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10311 
10312 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10313 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10314 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10315 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10316 			return (0);
10317 	}
10318 
10319 	return (1);
10320 }
10321 
10322 static void
dtrace_difo_hold(dtrace_difo_t * dp)10323 dtrace_difo_hold(dtrace_difo_t *dp)
10324 {
10325 	uint_t i;
10326 
10327 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10328 
10329 	dp->dtdo_refcnt++;
10330 	ASSERT(dp->dtdo_refcnt != 0);
10331 
10332 	/*
10333 	 * We need to check this DIF object for references to the variable
10334 	 * DIF_VAR_VTIMESTAMP.
10335 	 */
10336 	for (i = 0; i < dp->dtdo_varlen; i++) {
10337 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10338 
10339 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10340 			continue;
10341 
10342 		if (dtrace_vtime_references++ == 0)
10343 			dtrace_vtime_enable();
10344 	}
10345 }
10346 
10347 /*
10348  * This routine calculates the dynamic variable chunksize for a given DIF
10349  * object.  The calculation is not fool-proof, and can probably be tricked by
10350  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10351  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10352  * if a dynamic variable size exceeds the chunksize.
10353  */
10354 static void
dtrace_difo_chunksize(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10355 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10356 {
10357 	uint64_t sval = 0;
10358 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10359 	const dif_instr_t *text = dp->dtdo_buf;
10360 	uint_t pc, srd = 0;
10361 	uint_t ttop = 0;
10362 	size_t size, ksize;
10363 	uint_t id, i;
10364 
10365 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10366 		dif_instr_t instr = text[pc];
10367 		uint_t op = DIF_INSTR_OP(instr);
10368 		uint_t rd = DIF_INSTR_RD(instr);
10369 		uint_t r1 = DIF_INSTR_R1(instr);
10370 		uint_t nkeys = 0;
10371 		uchar_t scope;
10372 
10373 		dtrace_key_t *key = tupregs;
10374 
10375 		switch (op) {
10376 		case DIF_OP_SETX:
10377 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10378 			srd = rd;
10379 			continue;
10380 
10381 		case DIF_OP_STTS:
10382 			key = &tupregs[DIF_DTR_NREGS];
10383 			key[0].dttk_size = 0;
10384 			key[1].dttk_size = 0;
10385 			nkeys = 2;
10386 			scope = DIFV_SCOPE_THREAD;
10387 			break;
10388 
10389 		case DIF_OP_STGAA:
10390 		case DIF_OP_STTAA:
10391 			nkeys = ttop;
10392 
10393 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10394 				key[nkeys++].dttk_size = 0;
10395 
10396 			key[nkeys++].dttk_size = 0;
10397 
10398 			if (op == DIF_OP_STTAA) {
10399 				scope = DIFV_SCOPE_THREAD;
10400 			} else {
10401 				scope = DIFV_SCOPE_GLOBAL;
10402 			}
10403 
10404 			break;
10405 
10406 		case DIF_OP_PUSHTR:
10407 			if (ttop == DIF_DTR_NREGS)
10408 				return;
10409 
10410 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10411 				/*
10412 				 * If the register for the size of the "pushtr"
10413 				 * is %r0 (or the value is 0) and the type is
10414 				 * a string, we'll use the system-wide default
10415 				 * string size.
10416 				 */
10417 				tupregs[ttop++].dttk_size =
10418 				    dtrace_strsize_default;
10419 			} else {
10420 				if (srd == 0)
10421 					return;
10422 
10423 				if (sval > LONG_MAX)
10424 					return;
10425 
10426 				tupregs[ttop++].dttk_size = sval;
10427 			}
10428 
10429 			break;
10430 
10431 		case DIF_OP_PUSHTV:
10432 			if (ttop == DIF_DTR_NREGS)
10433 				return;
10434 
10435 			tupregs[ttop++].dttk_size = 0;
10436 			break;
10437 
10438 		case DIF_OP_FLUSHTS:
10439 			ttop = 0;
10440 			break;
10441 
10442 		case DIF_OP_POPTS:
10443 			if (ttop != 0)
10444 				ttop--;
10445 			break;
10446 		}
10447 
10448 		sval = 0;
10449 		srd = 0;
10450 
10451 		if (nkeys == 0)
10452 			continue;
10453 
10454 		/*
10455 		 * We have a dynamic variable allocation; calculate its size.
10456 		 */
10457 		for (ksize = 0, i = 0; i < nkeys; i++)
10458 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10459 
10460 		size = sizeof (dtrace_dynvar_t);
10461 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10462 		size += ksize;
10463 
10464 		/*
10465 		 * Now we need to determine the size of the stored data.
10466 		 */
10467 		id = DIF_INSTR_VAR(instr);
10468 
10469 		for (i = 0; i < dp->dtdo_varlen; i++) {
10470 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10471 
10472 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10473 				size += v->dtdv_type.dtdt_size;
10474 				break;
10475 			}
10476 		}
10477 
10478 		if (i == dp->dtdo_varlen)
10479 			return;
10480 
10481 		/*
10482 		 * We have the size.  If this is larger than the chunk size
10483 		 * for our dynamic variable state, reset the chunk size.
10484 		 */
10485 		size = P2ROUNDUP(size, sizeof (uint64_t));
10486 
10487 		/*
10488 		 * Before setting the chunk size, check that we're not going
10489 		 * to set it to a negative value...
10490 		 */
10491 		if (size > LONG_MAX)
10492 			return;
10493 
10494 		/*
10495 		 * ...and make certain that we didn't badly overflow.
10496 		 */
10497 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10498 			return;
10499 
10500 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10501 			vstate->dtvs_dynvars.dtds_chunksize = size;
10502 	}
10503 }
10504 
10505 static void
dtrace_difo_init(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10506 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10507 {
10508 	int oldsvars, osz, nsz, otlocals, ntlocals;
10509 	uint_t i, id;
10510 
10511 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10512 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10513 
10514 	for (i = 0; i < dp->dtdo_varlen; i++) {
10515 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10516 		dtrace_statvar_t *svar;
10517 		dtrace_statvar_t ***svarp = NULL;
10518 		size_t dsize = 0;
10519 		uint8_t scope = v->dtdv_scope;
10520 		int *np = (int *)NULL;
10521 
10522 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10523 			continue;
10524 
10525 		id -= DIF_VAR_OTHER_UBASE;
10526 
10527 		switch (scope) {
10528 		case DIFV_SCOPE_THREAD:
10529 			while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
10530 				dtrace_difv_t *tlocals;
10531 
10532 				if ((ntlocals = (otlocals << 1)) == 0)
10533 					ntlocals = 1;
10534 
10535 				osz = otlocals * sizeof (dtrace_difv_t);
10536 				nsz = ntlocals * sizeof (dtrace_difv_t);
10537 
10538 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10539 
10540 				if (osz != 0) {
10541 					bcopy(vstate->dtvs_tlocals,
10542 					    tlocals, osz);
10543 					kmem_free(vstate->dtvs_tlocals, osz);
10544 				}
10545 
10546 				vstate->dtvs_tlocals = tlocals;
10547 				vstate->dtvs_ntlocals = ntlocals;
10548 			}
10549 
10550 			vstate->dtvs_tlocals[id] = *v;
10551 			continue;
10552 
10553 		case DIFV_SCOPE_LOCAL:
10554 			np = &vstate->dtvs_nlocals;
10555 			svarp = &vstate->dtvs_locals;
10556 
10557 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10558 				dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
10559 				    sizeof (uint64_t));
10560 			else
10561 				dsize = (int)NCPU * sizeof (uint64_t);
10562 
10563 			break;
10564 
10565 		case DIFV_SCOPE_GLOBAL:
10566 			np = &vstate->dtvs_nglobals;
10567 			svarp = &vstate->dtvs_globals;
10568 
10569 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10570 				dsize = v->dtdv_type.dtdt_size +
10571 				    sizeof (uint64_t);
10572 
10573 			break;
10574 
10575 		default:
10576 			ASSERT(0);
10577 		}
10578 
10579 		while (id >= (uint_t)(oldsvars = *np)) {
10580 			dtrace_statvar_t **statics;
10581 			int newsvars, oldsize, newsize;
10582 
10583 			if ((newsvars = (oldsvars << 1)) == 0)
10584 				newsvars = 1;
10585 
10586 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10587 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10588 
10589 			statics = kmem_zalloc(newsize, KM_SLEEP);
10590 
10591 			if (oldsize != 0) {
10592 				bcopy(*svarp, statics, oldsize);
10593 				kmem_free(*svarp, oldsize);
10594 			}
10595 
10596 			*svarp = statics;
10597 			*np = newsvars;
10598 		}
10599 
10600 		if ((svar = (*svarp)[id]) == NULL) {
10601 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10602 			svar->dtsv_var = *v;
10603 
10604 			if ((svar->dtsv_size = dsize) != 0) {
10605 				svar->dtsv_data = (uint64_t)(uintptr_t)
10606 				    kmem_zalloc(dsize, KM_SLEEP);
10607 			}
10608 
10609 			(*svarp)[id] = svar;
10610 		}
10611 
10612 		svar->dtsv_refcnt++;
10613 	}
10614 
10615 	dtrace_difo_chunksize(dp, vstate);
10616 	dtrace_difo_hold(dp);
10617 }
10618 
10619 static dtrace_difo_t *
dtrace_difo_duplicate(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10620 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10621 {
10622 	dtrace_difo_t *new;
10623 	size_t sz;
10624 
10625 	ASSERT(dp->dtdo_buf != NULL);
10626 	ASSERT(dp->dtdo_refcnt != 0);
10627 
10628 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10629 
10630 	ASSERT(dp->dtdo_buf != NULL);
10631 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10632 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10633 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10634 	new->dtdo_len = dp->dtdo_len;
10635 
10636 	if (dp->dtdo_strtab != NULL) {
10637 		ASSERT(dp->dtdo_strlen != 0);
10638 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10639 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10640 		new->dtdo_strlen = dp->dtdo_strlen;
10641 	}
10642 
10643 	if (dp->dtdo_inttab != NULL) {
10644 		ASSERT(dp->dtdo_intlen != 0);
10645 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10646 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10647 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10648 		new->dtdo_intlen = dp->dtdo_intlen;
10649 	}
10650 
10651 	if (dp->dtdo_vartab != NULL) {
10652 		ASSERT(dp->dtdo_varlen != 0);
10653 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10654 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10655 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10656 		new->dtdo_varlen = dp->dtdo_varlen;
10657 	}
10658 
10659 	dtrace_difo_init(new, vstate);
10660 	return (new);
10661 }
10662 
10663 static void
dtrace_difo_destroy(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10664 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10665 {
10666 	uint_t i;
10667 
10668 	ASSERT(dp->dtdo_refcnt == 0);
10669 
10670 	for (i = 0; i < dp->dtdo_varlen; i++) {
10671 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10672 		dtrace_statvar_t *svar;
10673 		dtrace_statvar_t **svarp = NULL;
10674 		uint_t id;
10675 		uint8_t scope = v->dtdv_scope;
10676 		int *np = NULL;
10677 
10678 		switch (scope) {
10679 		case DIFV_SCOPE_THREAD:
10680 			continue;
10681 
10682 		case DIFV_SCOPE_LOCAL:
10683 			np = &vstate->dtvs_nlocals;
10684 			svarp = vstate->dtvs_locals;
10685 			break;
10686 
10687 		case DIFV_SCOPE_GLOBAL:
10688 			np = &vstate->dtvs_nglobals;
10689 			svarp = vstate->dtvs_globals;
10690 			break;
10691 
10692 		default:
10693 			ASSERT(0);
10694 		}
10695 
10696 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10697 			continue;
10698 
10699 		id -= DIF_VAR_OTHER_UBASE;
10700 
10701 		ASSERT(id < (uint_t)*np);
10702 
10703 		svar = svarp[id];
10704 		ASSERT(svar != NULL);
10705 		ASSERT(svar->dtsv_refcnt > 0);
10706 
10707 		if (--svar->dtsv_refcnt > 0)
10708 			continue;
10709 
10710 		if (svar->dtsv_size != 0) {
10711 			ASSERT(svar->dtsv_data != 0);
10712 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10713 			    svar->dtsv_size);
10714 		}
10715 
10716 		kmem_free(svar, sizeof (dtrace_statvar_t));
10717 		svarp[id] = NULL;
10718 	}
10719 
10720 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10721 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10722 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10723 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10724 
10725 	kmem_free(dp, sizeof (dtrace_difo_t));
10726 }
10727 
10728 static void
dtrace_difo_release(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10729 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10730 {
10731 	uint_t i;
10732 
10733 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10734 	ASSERT(dp->dtdo_refcnt != 0);
10735 
10736 	for (i = 0; i < dp->dtdo_varlen; i++) {
10737 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10738 
10739 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10740 			continue;
10741 
10742 		ASSERT(dtrace_vtime_references > 0);
10743 		if (--dtrace_vtime_references == 0)
10744 			dtrace_vtime_disable();
10745 	}
10746 
10747 	if (--dp->dtdo_refcnt == 0)
10748 		dtrace_difo_destroy(dp, vstate);
10749 }
10750 
10751 /*
10752  * DTrace Format Functions
10753  */
10754 
10755 static dtrace_format_t*
dtrace_format_new(char * str)10756 dtrace_format_new(char *str)
10757 {
10758 	dtrace_format_t *fmt = NULL;
10759 	size_t bufsize = strlen(str) + 1;
10760 
10761 	fmt = kmem_zalloc(sizeof(*fmt) + bufsize, KM_SLEEP);
10762 
10763 	fmt->dtf_refcount = 1;
10764 	(void) strlcpy(fmt->dtf_str, str, bufsize);
10765 
10766 	return fmt;
10767 }
10768 
10769 static uint16_t
dtrace_format_add(dtrace_state_t * state,char * str)10770 dtrace_format_add(dtrace_state_t *state, char *str)
10771 {
10772 	dtrace_format_t **new;
10773 	uint16_t ndx;
10774 
10775 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10776 		if (state->dts_formats[ndx] == NULL) {
10777 			state->dts_formats[ndx] = dtrace_format_new(str);
10778 			return (ndx + 1);
10779 		}
10780 		else if (strcmp(state->dts_formats[ndx]->dtf_str, str) == 0) {
10781 			VERIFY(state->dts_formats[ndx]->dtf_refcount < UINT64_MAX);
10782 			state->dts_formats[ndx]->dtf_refcount++;
10783 			return (ndx + 1);
10784 		}
10785 	}
10786 
10787 	if (state->dts_nformats == USHRT_MAX) {
10788 		/*
10789 		 * This is only likely if a denial-of-service attack is being
10790 		 * attempted.  As such, it's okay to fail silently here.
10791 		 */
10792 		return (0);
10793 	}
10794 
10795 	/*
10796 	 * For simplicity, we always resize the formats array to be exactly the
10797 	 * number of formats.
10798 	 */
10799 	ndx = state->dts_nformats++;
10800 	new = kmem_alloc((ndx + 1) * sizeof (*state->dts_formats), KM_SLEEP);
10801 
10802 	if (state->dts_formats != NULL) {
10803 		ASSERT(ndx != 0);
10804 		bcopy(state->dts_formats, new, ndx * sizeof (*state->dts_formats));
10805 		kmem_free(state->dts_formats, ndx * sizeof (*state->dts_formats));
10806 	}
10807 
10808 	state->dts_formats = new;
10809 	state->dts_formats[ndx] = dtrace_format_new(str);
10810 
10811 	return (ndx + 1);
10812 }
10813 
10814 static void
dtrace_format_remove(dtrace_state_t * state,uint16_t format)10815 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10816 {
10817 	dtrace_format_t *fmt;
10818 
10819 	ASSERT(state->dts_formats != NULL);
10820 	ASSERT(format <= state->dts_nformats);
10821 
10822 	fmt = state->dts_formats[format - 1];
10823 
10824 	ASSERT(fmt != NULL);
10825 	VERIFY(fmt->dtf_refcount > 0);
10826 
10827 	fmt->dtf_refcount--;
10828 
10829 	if (fmt->dtf_refcount == 0) {
10830 		kmem_free(fmt, DTRACE_FORMAT_SIZE(fmt));
10831 		state->dts_formats[format - 1] = NULL;
10832 	}
10833 }
10834 
10835 static void
dtrace_format_destroy(dtrace_state_t * state)10836 dtrace_format_destroy(dtrace_state_t *state)
10837 {
10838 	int i;
10839 
10840 	if (state->dts_nformats == 0) {
10841 		ASSERT(state->dts_formats == NULL);
10842 		return;
10843 	}
10844 
10845 	ASSERT(state->dts_formats != NULL);
10846 
10847 	for (i = 0; i < state->dts_nformats; i++) {
10848 		dtrace_format_t *fmt = state->dts_formats[i];
10849 
10850 		if (fmt == NULL)
10851 			continue;
10852 
10853 		kmem_free(fmt, DTRACE_FORMAT_SIZE(fmt));
10854 	}
10855 
10856 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (*state->dts_formats));
10857 	state->dts_nformats = 0;
10858 	state->dts_formats = NULL;
10859 }
10860 
10861 /*
10862  * DTrace Predicate Functions
10863  */
10864 static dtrace_predicate_t *
dtrace_predicate_create(dtrace_difo_t * dp)10865 dtrace_predicate_create(dtrace_difo_t *dp)
10866 {
10867 	dtrace_predicate_t *pred;
10868 
10869 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10870 	ASSERT(dp->dtdo_refcnt != 0);
10871 
10872 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10873 	pred->dtp_difo = dp;
10874 	pred->dtp_refcnt = 1;
10875 
10876 	if (!dtrace_difo_cacheable(dp))
10877 		return (pred);
10878 
10879 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10880 		/*
10881 		 * This is only theoretically possible -- we have had 2^32
10882 		 * cacheable predicates on this machine.  We cannot allow any
10883 		 * more predicates to become cacheable:  as unlikely as it is,
10884 		 * there may be a thread caching a (now stale) predicate cache
10885 		 * ID. (N.B.: the temptation is being successfully resisted to
10886 		 * have this cmn_err() "Holy shit -- we executed this code!")
10887 		 */
10888 		return (pred);
10889 	}
10890 
10891 	pred->dtp_cacheid = dtrace_predcache_id++;
10892 
10893 	return (pred);
10894 }
10895 
10896 static void
dtrace_predicate_hold(dtrace_predicate_t * pred)10897 dtrace_predicate_hold(dtrace_predicate_t *pred)
10898 {
10899 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10900 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10901 	ASSERT(pred->dtp_refcnt > 0);
10902 
10903 	pred->dtp_refcnt++;
10904 }
10905 
10906 static void
dtrace_predicate_release(dtrace_predicate_t * pred,dtrace_vstate_t * vstate)10907 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10908 {
10909 	dtrace_difo_t *dp = pred->dtp_difo;
10910 #pragma unused(dp) /* __APPLE__ */
10911 
10912 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10913 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10914 	ASSERT(pred->dtp_refcnt > 0);
10915 
10916 	if (--pred->dtp_refcnt == 0) {
10917 		dtrace_difo_release(pred->dtp_difo, vstate);
10918 		kmem_free(pred, sizeof (dtrace_predicate_t));
10919 	}
10920 }
10921 
10922 /*
10923  * DTrace Action Description Functions
10924  */
10925 static dtrace_actdesc_t *
dtrace_actdesc_create(dtrace_actkind_t kind,uint32_t ntuple,uint64_t uarg,uint64_t arg)10926 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10927     uint64_t uarg, uint64_t arg)
10928 {
10929 	dtrace_actdesc_t *act;
10930 
10931 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
10932 	    arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
10933 
10934 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10935 	act->dtad_kind = kind;
10936 	act->dtad_ntuple = ntuple;
10937 	act->dtad_uarg = uarg;
10938 	act->dtad_arg = arg;
10939 	act->dtad_refcnt = 1;
10940 
10941 	return (act);
10942 }
10943 
10944 static void
dtrace_actdesc_hold(dtrace_actdesc_t * act)10945 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10946 {
10947 	ASSERT(act->dtad_refcnt >= 1);
10948 	act->dtad_refcnt++;
10949 }
10950 
10951 static void
dtrace_actdesc_release(dtrace_actdesc_t * act,dtrace_vstate_t * vstate)10952 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10953 {
10954 	dtrace_actkind_t kind = act->dtad_kind;
10955 	dtrace_difo_t *dp;
10956 
10957 	ASSERT(act->dtad_refcnt >= 1);
10958 
10959 	if (--act->dtad_refcnt != 0)
10960 		return;
10961 
10962 	if ((dp = act->dtad_difo) != NULL)
10963 		dtrace_difo_release(dp, vstate);
10964 
10965 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10966 		char *str = (char *)(uintptr_t)act->dtad_arg;
10967 
10968 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10969 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10970 
10971 		if (str != NULL)
10972 			kmem_free(str, strlen(str) + 1);
10973 	}
10974 
10975 	kmem_free(act, sizeof (dtrace_actdesc_t));
10976 }
10977 
10978 /*
10979  * DTrace ECB Functions
10980  */
10981 static dtrace_ecb_t *
dtrace_ecb_add(dtrace_state_t * state,dtrace_probe_t * probe)10982 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10983 {
10984 	dtrace_ecb_t *ecb;
10985 	dtrace_epid_t epid;
10986 
10987 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10988 
10989 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10990 	ecb->dte_predicate = NULL;
10991 	ecb->dte_probe = probe;
10992 
10993 	/*
10994 	 * The default size is the size of the default action: recording
10995 	 * the header.
10996 	 */
10997 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10998 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10999 
11000 	epid = state->dts_epid++;
11001 
11002 	if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
11003 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11004 		int necbs = state->dts_necbs << 1;
11005 
11006 		ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
11007 
11008 		if (necbs == 0) {
11009 			ASSERT(oecbs == NULL);
11010 			necbs = 1;
11011 		}
11012 
11013 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11014 
11015 		if (oecbs != NULL)
11016 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11017 
11018 		dtrace_membar_producer();
11019 		state->dts_ecbs = ecbs;
11020 
11021 		if (oecbs != NULL) {
11022 			/*
11023 			 * If this state is active, we must dtrace_sync()
11024 			 * before we can free the old dts_ecbs array:  we're
11025 			 * coming in hot, and there may be active ring
11026 			 * buffer processing (which indexes into the dts_ecbs
11027 			 * array) on another CPU.
11028 			 */
11029 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11030 				dtrace_sync();
11031 
11032 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11033 		}
11034 
11035 		dtrace_membar_producer();
11036 		state->dts_necbs = necbs;
11037 	}
11038 
11039 	ecb->dte_state = state;
11040 
11041 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11042 	dtrace_membar_producer();
11043 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11044 
11045 	return (ecb);
11046 }
11047 
11048 static int
dtrace_ecb_enable(dtrace_ecb_t * ecb)11049 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11050 {
11051 	dtrace_probe_t *probe = ecb->dte_probe;
11052 
11053 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11054 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11055 	ASSERT(ecb->dte_next == NULL);
11056 
11057 	if (probe == NULL) {
11058 		/*
11059 		 * This is the NULL probe -- there's nothing to do.
11060 		 */
11061 	    return(0);
11062 	}
11063 
11064 	probe->dtpr_provider->dtpv_ecb_count++;
11065 	if (probe->dtpr_ecb == NULL) {
11066 		dtrace_provider_t *prov = probe->dtpr_provider;
11067 
11068 		/*
11069 		 * We're the first ECB on this probe.
11070 		 */
11071 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11072 
11073 		if (ecb->dte_predicate != NULL)
11074 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11075 
11076 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11077                     probe->dtpr_id, probe->dtpr_arg));
11078 	} else {
11079 		/*
11080 		 * This probe is already active.  Swing the last pointer to
11081 		 * point to the new ECB, and issue a dtrace_sync() to assure
11082 		 * that all CPUs have seen the change.
11083 		 */
11084 		ASSERT(probe->dtpr_ecb_last != NULL);
11085 		probe->dtpr_ecb_last->dte_next = ecb;
11086 		probe->dtpr_ecb_last = ecb;
11087 		probe->dtpr_predcache = 0;
11088 
11089 		dtrace_sync();
11090 		return(0);
11091 	}
11092 }
11093 
11094 static int
dtrace_ecb_resize(dtrace_ecb_t * ecb)11095 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11096 {
11097 	dtrace_action_t *act;
11098 	uint32_t curneeded = UINT32_MAX;
11099 	uint32_t aggbase = UINT32_MAX;
11100 
11101 	/*
11102 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11103 	 * we always record it first.)
11104 	 */
11105 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11106 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11107 
11108 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11109 		dtrace_recdesc_t *rec = &act->dta_rec;
11110 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11111 
11112 		ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
11113 
11114 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11115 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11116 
11117 			ASSERT(rec->dtrd_size != 0);
11118 			ASSERT(agg->dtag_first != NULL);
11119 			ASSERT(act->dta_prev->dta_intuple);
11120 			ASSERT(aggbase != UINT32_MAX);
11121 			ASSERT(curneeded != UINT32_MAX);
11122 
11123 			agg->dtag_base = aggbase;
11124 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11125 			rec->dtrd_offset = curneeded;
11126 			if (curneeded + rec->dtrd_size < curneeded)
11127 				return (EINVAL);
11128 			curneeded += rec->dtrd_size;
11129 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11130 
11131 			aggbase = UINT32_MAX;
11132 			curneeded = UINT32_MAX;
11133 		} else if (act->dta_intuple) {
11134 			if (curneeded == UINT32_MAX) {
11135 				/*
11136 				 * This is the first record in a tuple.  Align
11137 				 * curneeded to be at offset 4 in an 8-byte
11138 				 * aligned block.
11139 				 */
11140 				ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
11141 				ASSERT(aggbase == UINT32_MAX);
11142 
11143 				curneeded = P2PHASEUP(ecb->dte_size,
11144 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11145 
11146 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11147 				ASSERT(IS_P2ALIGNED(aggbase,
11148 				    sizeof (uint64_t)));
11149 			}
11150 
11151 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11152 			rec->dtrd_offset = curneeded;
11153 			curneeded += rec->dtrd_size;
11154 			if (curneeded + rec->dtrd_size < curneeded)
11155 				return (EINVAL);
11156 		} else {
11157 			/* tuples must be followed by an aggregation */
11158 			ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
11159 			ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
11160 			rec->dtrd_offset = ecb->dte_size;
11161 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11162 				return (EINVAL);
11163 			ecb->dte_size += rec->dtrd_size;
11164 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11165 		}
11166 	}
11167 
11168 	if ((act = ecb->dte_action) != NULL &&
11169 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11170 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11171 		/*
11172 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11173 		 * actions store no data; set the size to 0.
11174 		 */
11175 		ecb->dte_size = 0;
11176 	}
11177 
11178 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11179 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11180 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
11181 	return (0);
11182 }
11183 
11184 static dtrace_action_t *
dtrace_ecb_aggregation_create(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)11185 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11186 {
11187 	dtrace_aggregation_t *agg;
11188 	size_t size = sizeof (uint64_t);
11189 	int ntuple = desc->dtad_ntuple;
11190 	dtrace_action_t *act;
11191 	dtrace_recdesc_t *frec;
11192 	dtrace_aggid_t aggid;
11193 	dtrace_state_t *state = ecb->dte_state;
11194 
11195 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11196 	agg->dtag_ecb = ecb;
11197 
11198 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11199 
11200 	switch (desc->dtad_kind) {
11201 	case DTRACEAGG_MIN:
11202 		agg->dtag_initial = INT64_MAX;
11203 		agg->dtag_aggregate = dtrace_aggregate_min;
11204 		break;
11205 
11206 	case DTRACEAGG_MAX:
11207 		agg->dtag_initial = INT64_MIN;
11208 		agg->dtag_aggregate = dtrace_aggregate_max;
11209 		break;
11210 
11211 	case DTRACEAGG_COUNT:
11212 		agg->dtag_aggregate = dtrace_aggregate_count;
11213 		break;
11214 
11215 	case DTRACEAGG_QUANTIZE:
11216 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11217 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11218 		    sizeof (uint64_t);
11219 		break;
11220 
11221 	case DTRACEAGG_LQUANTIZE: {
11222 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11223 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11224 
11225 		agg->dtag_initial = desc->dtad_arg;
11226 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11227 
11228 		if (step == 0 || levels == 0)
11229 			goto err;
11230 
11231 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11232 		break;
11233 	}
11234 
11235 	case DTRACEAGG_LLQUANTIZE: {
11236 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11237 		uint16_t low    = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11238 		uint16_t high   = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11239 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11240 		int64_t v;
11241 
11242 		agg->dtag_initial = desc->dtad_arg;
11243 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11244 
11245 		if (factor < 2 || low >= high || nsteps < factor)
11246 			goto err;
11247 
11248 		/*
11249 		 * Now check that the number of steps evenly divides a power
11250 		 * of the factor.  (This assures both integer bucket size and
11251 		 * linearity within each magnitude.)
11252 		 */
11253 		for (v = factor; v < nsteps; v *= factor)
11254 			continue;
11255 
11256 		if ((v % nsteps) || (nsteps % factor))
11257 			goto err;
11258 
11259  		size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11260 		break;
11261   }
11262 
11263 	case DTRACEAGG_AVG:
11264 		agg->dtag_aggregate = dtrace_aggregate_avg;
11265 		size = sizeof (uint64_t) * 2;
11266 		break;
11267 
11268 	case DTRACEAGG_STDDEV:
11269 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11270 		size = sizeof (uint64_t) * 4;
11271 		break;
11272 
11273 	case DTRACEAGG_SUM:
11274 		agg->dtag_aggregate = dtrace_aggregate_sum;
11275 		break;
11276 
11277 	default:
11278 		goto err;
11279 	}
11280 
11281 	agg->dtag_action.dta_rec.dtrd_size = size;
11282 
11283 	if (ntuple == 0)
11284 		goto err;
11285 
11286 	/*
11287 	 * We must make sure that we have enough actions for the n-tuple.
11288 	 */
11289 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11290 		if (DTRACEACT_ISAGG(act->dta_kind))
11291 			break;
11292 
11293 		if (--ntuple == 0) {
11294 			/*
11295 			 * This is the action with which our n-tuple begins.
11296 			 */
11297 			agg->dtag_first = act;
11298 			goto success;
11299 		}
11300 	}
11301 
11302 	/*
11303 	 * This n-tuple is short by ntuple elements.  Return failure.
11304 	 */
11305 	ASSERT(ntuple != 0);
11306 err:
11307 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11308 	return (NULL);
11309 
11310 success:
11311 	/*
11312 	 * If the last action in the tuple has a size of zero, it's actually
11313 	 * an expression argument for the aggregating action.
11314 	 */
11315 	ASSERT(ecb->dte_action_last != NULL);
11316 	act = ecb->dte_action_last;
11317 
11318 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11319 		ASSERT(act->dta_difo != NULL);
11320 
11321 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11322 			agg->dtag_hasarg = 1;
11323 	}
11324 
11325 	/*
11326 	 * We need to allocate an id for this aggregation.
11327 	 */
11328 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11329 	    VM_BESTFIT | VM_SLEEP);
11330 
11331 	if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
11332 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11333 		dtrace_aggregation_t **aggs;
11334 		int naggs = state->dts_naggregations << 1;
11335 		int onaggs = state->dts_naggregations;
11336 
11337 		ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
11338 
11339 		if (naggs == 0) {
11340 			ASSERT(oaggs == NULL);
11341 			naggs = 1;
11342 		}
11343 
11344 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11345 
11346 		if (oaggs != NULL) {
11347 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11348 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11349 		}
11350 
11351 		state->dts_aggregations = aggs;
11352 		state->dts_naggregations = naggs;
11353 	}
11354 
11355 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11356 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11357 
11358 	frec = &agg->dtag_first->dta_rec;
11359 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11360 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11361 
11362 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11363 		ASSERT(!act->dta_intuple);
11364 		act->dta_intuple = 1;
11365 	}
11366 
11367 	return (&agg->dtag_action);
11368 }
11369 
11370 static void
dtrace_ecb_aggregation_destroy(dtrace_ecb_t * ecb,dtrace_action_t * act)11371 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11372 {
11373 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11374 	dtrace_state_t *state = ecb->dte_state;
11375 	dtrace_aggid_t aggid = agg->dtag_id;
11376 
11377 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11378 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11379 
11380 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11381 	state->dts_aggregations[aggid - 1] = NULL;
11382 
11383 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11384 }
11385 
11386 static int
dtrace_ecb_action_add(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)11387 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11388 {
11389 	dtrace_action_t *action, *last;
11390 	dtrace_difo_t *dp = desc->dtad_difo;
11391 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11392 	uint16_t format = 0;
11393 	dtrace_recdesc_t *rec;
11394 	dtrace_state_t *state = ecb->dte_state;
11395 	dtrace_optval_t *opt = state->dts_options;
11396 	dtrace_optval_t nframes=0, strsize;
11397 	uint64_t arg = desc->dtad_arg;
11398 
11399 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11400 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11401 
11402 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11403 		/*
11404 		 * If this is an aggregating action, there must be neither
11405 		 * a speculate nor a commit on the action chain.
11406 		 */
11407 		dtrace_action_t *act;
11408 
11409 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11410 			if (act->dta_kind == DTRACEACT_COMMIT)
11411 				return (EINVAL);
11412 
11413 			if (act->dta_kind == DTRACEACT_SPECULATE)
11414 				return (EINVAL);
11415 		}
11416 
11417 		action = dtrace_ecb_aggregation_create(ecb, desc);
11418 
11419 		if (action == NULL)
11420 			return (EINVAL);
11421 	} else {
11422 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11423 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11424 		    dp != NULL && dp->dtdo_destructive)) {
11425 			state->dts_destructive = 1;
11426 		}
11427 
11428 		switch (desc->dtad_kind) {
11429 		case DTRACEACT_PRINTF:
11430 		case DTRACEACT_PRINTA:
11431 		case DTRACEACT_SYSTEM:
11432 		case DTRACEACT_FREOPEN:
11433 		case DTRACEACT_DIFEXPR:
11434 			/*
11435 			 * We know that our arg is a string -- turn it into a
11436 			 * format.
11437 			 */
11438 			if (arg == 0) {
11439 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11440 				       desc->dtad_kind == DTRACEACT_DIFEXPR);
11441 				format = 0;
11442 			} else {
11443 				ASSERT(arg != 0);
11444 				ASSERT(arg > KERNELBASE);
11445 				format = dtrace_format_add(state,
11446 				    (char *)(uintptr_t)arg);
11447 			}
11448 
11449 			OS_FALLTHROUGH;
11450 		case DTRACEACT_LIBACT:
11451 		case DTRACEACT_TRACEMEM:
11452 		case DTRACEACT_TRACEMEM_DYNSIZE:
11453 		case DTRACEACT_APPLEBINARY:	/* __APPLE__ */
11454 			if (dp == NULL)
11455 				return (EINVAL);
11456 
11457 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11458 				break;
11459 
11460 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11461 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11462 					return (EINVAL);
11463 
11464 				size = opt[DTRACEOPT_STRSIZE];
11465 			}
11466 
11467 			break;
11468 
11469 		case DTRACEACT_STACK:
11470 			if ((nframes = arg) == 0) {
11471 				nframes = opt[DTRACEOPT_STACKFRAMES];
11472 				ASSERT(nframes > 0);
11473 				arg = nframes;
11474 			}
11475 
11476 			size = nframes * sizeof (pc_t);
11477 			break;
11478 
11479 		case DTRACEACT_JSTACK:
11480 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11481 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11482 
11483 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11484 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11485 
11486 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11487 
11488 			OS_FALLTHROUGH;
11489 		case DTRACEACT_USTACK:
11490 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11491 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11492 				strsize = DTRACE_USTACK_STRSIZE(arg);
11493 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11494 				ASSERT(nframes > 0);
11495 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11496 			}
11497 
11498 			/*
11499 			 * Save a slot for the pid.
11500 			 */
11501 			size = (nframes + 1) * sizeof (uint64_t);
11502 			size += DTRACE_USTACK_STRSIZE(arg);
11503 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11504 
11505 			break;
11506 
11507 		case DTRACEACT_SYM:
11508 		case DTRACEACT_MOD:
11509 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11510 			    sizeof (uint64_t)) ||
11511 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11512 				return (EINVAL);
11513 			break;
11514 
11515 		case DTRACEACT_USYM:
11516 		case DTRACEACT_UMOD:
11517 		case DTRACEACT_UADDR:
11518 			if (dp == NULL ||
11519 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11520 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11521 				return (EINVAL);
11522 
11523 			/*
11524 			 * We have a slot for the pid, plus a slot for the
11525 			 * argument.  To keep things simple (aligned with
11526 			 * bitness-neutral sizing), we store each as a 64-bit
11527 			 * quantity.
11528 			 */
11529 			size = 2 * sizeof (uint64_t);
11530 			break;
11531 
11532 		case DTRACEACT_STOP:
11533 		case DTRACEACT_BREAKPOINT:
11534 		case DTRACEACT_PANIC:
11535 			break;
11536 
11537 		case DTRACEACT_CHILL:
11538 		case DTRACEACT_DISCARD:
11539 		case DTRACEACT_RAISE:
11540 		case DTRACEACT_PIDRESUME:	/* __APPLE__ */
11541 			if (dp == NULL)
11542 				return (EINVAL);
11543 			break;
11544 
11545 		case DTRACEACT_EXIT:
11546 			if (dp == NULL ||
11547 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11548 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11549 				return (EINVAL);
11550 			break;
11551 
11552 		case DTRACEACT_SPECULATE:
11553 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11554 				return (EINVAL);
11555 
11556 			if (dp == NULL)
11557 				return (EINVAL);
11558 
11559 			state->dts_speculates = 1;
11560 			break;
11561 
11562 		case DTRACEACT_COMMIT: {
11563 			dtrace_action_t *act = ecb->dte_action;
11564 
11565 			for (; act != NULL; act = act->dta_next) {
11566 				if (act->dta_kind == DTRACEACT_COMMIT)
11567 					return (EINVAL);
11568 			}
11569 
11570 			if (dp == NULL)
11571 				return (EINVAL);
11572 			break;
11573 		}
11574 
11575 		default:
11576 			return (EINVAL);
11577 		}
11578 
11579 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11580 			/*
11581 			 * If this is a data-storing action or a speculate,
11582 			 * we must be sure that there isn't a commit on the
11583 			 * action chain.
11584 			 */
11585 			dtrace_action_t *act = ecb->dte_action;
11586 
11587 			for (; act != NULL; act = act->dta_next) {
11588 				if (act->dta_kind == DTRACEACT_COMMIT)
11589 					return (EINVAL);
11590 			}
11591 		}
11592 
11593 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11594 		action->dta_rec.dtrd_size = size;
11595 	}
11596 
11597 	action->dta_refcnt = 1;
11598 	rec = &action->dta_rec;
11599 	size = rec->dtrd_size;
11600 
11601 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11602 		if (!(size & mask)) {
11603 			align = mask + 1;
11604 			break;
11605 		}
11606 	}
11607 
11608 	action->dta_kind = desc->dtad_kind;
11609 
11610 	if ((action->dta_difo = dp) != NULL)
11611 		dtrace_difo_hold(dp);
11612 
11613 	rec->dtrd_action = action->dta_kind;
11614 	rec->dtrd_arg = arg;
11615 	rec->dtrd_uarg = desc->dtad_uarg;
11616 	rec->dtrd_alignment = (uint16_t)align;
11617 	rec->dtrd_format = format;
11618 
11619 	if ((last = ecb->dte_action_last) != NULL) {
11620 		ASSERT(ecb->dte_action != NULL);
11621 		action->dta_prev = last;
11622 		last->dta_next = action;
11623 	} else {
11624 		ASSERT(ecb->dte_action == NULL);
11625 		ecb->dte_action = action;
11626 	}
11627 
11628 	ecb->dte_action_last = action;
11629 
11630 	return (0);
11631 }
11632 
11633 static void
dtrace_ecb_action_remove(dtrace_ecb_t * ecb)11634 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11635 {
11636 	dtrace_action_t *act = ecb->dte_action, *next;
11637 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11638 	dtrace_difo_t *dp;
11639 	uint16_t format;
11640 
11641 	if (act != NULL && act->dta_refcnt > 1) {
11642 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11643 		act->dta_refcnt--;
11644 	} else {
11645 		for (; act != NULL; act = next) {
11646 			next = act->dta_next;
11647 			ASSERT(next != NULL || act == ecb->dte_action_last);
11648 			ASSERT(act->dta_refcnt == 1);
11649 
11650 			if ((format = act->dta_rec.dtrd_format) != 0)
11651 				dtrace_format_remove(ecb->dte_state, format);
11652 
11653 			if ((dp = act->dta_difo) != NULL)
11654 				dtrace_difo_release(dp, vstate);
11655 
11656 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11657 				dtrace_ecb_aggregation_destroy(ecb, act);
11658 			} else {
11659 				kmem_free(act, sizeof (dtrace_action_t));
11660 			}
11661 		}
11662 	}
11663 
11664 	ecb->dte_action = NULL;
11665 	ecb->dte_action_last = NULL;
11666 	ecb->dte_size = 0;
11667 }
11668 
11669 static void
dtrace_ecb_disable(dtrace_ecb_t * ecb)11670 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11671 {
11672 	/*
11673 	 * We disable the ECB by removing it from its probe.
11674 	 */
11675 	dtrace_ecb_t *pecb, *prev = NULL;
11676 	dtrace_probe_t *probe = ecb->dte_probe;
11677 
11678 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11679 
11680 	if (probe == NULL) {
11681 		/*
11682 		 * This is the NULL probe; there is nothing to disable.
11683 		 */
11684 		return;
11685 	}
11686 
11687 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11688 		if (pecb == ecb)
11689 			break;
11690 		prev = pecb;
11691 	}
11692 
11693 	ASSERT(pecb != NULL);
11694 
11695 	if (prev == NULL) {
11696 		probe->dtpr_ecb = ecb->dte_next;
11697 	} else {
11698 		prev->dte_next = ecb->dte_next;
11699 	}
11700 
11701 	if (ecb == probe->dtpr_ecb_last) {
11702 		ASSERT(ecb->dte_next == NULL);
11703 		probe->dtpr_ecb_last = prev;
11704 	}
11705 
11706 	probe->dtpr_provider->dtpv_ecb_count--;
11707 	/*
11708 	 * The ECB has been disconnected from the probe; now sync to assure
11709 	 * that all CPUs have seen the change before returning.
11710 	 */
11711 	dtrace_sync();
11712 
11713 	if (probe->dtpr_ecb == NULL) {
11714 		/*
11715 		 * That was the last ECB on the probe; clear the predicate
11716 		 * cache ID for the probe, disable it and sync one more time
11717 		 * to assure that we'll never hit it again.
11718 		 */
11719 		dtrace_provider_t *prov = probe->dtpr_provider;
11720 
11721 		ASSERT(ecb->dte_next == NULL);
11722 		ASSERT(probe->dtpr_ecb_last == NULL);
11723 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11724 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11725 		    probe->dtpr_id, probe->dtpr_arg);
11726 		dtrace_sync();
11727 	} else {
11728 		/*
11729 		 * There is at least one ECB remaining on the probe.  If there
11730 		 * is _exactly_ one, set the probe's predicate cache ID to be
11731 		 * the predicate cache ID of the remaining ECB.
11732 		 */
11733 		ASSERT(probe->dtpr_ecb_last != NULL);
11734 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11735 
11736 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11737 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11738 
11739 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11740 
11741 			if (p != NULL)
11742 				probe->dtpr_predcache = p->dtp_cacheid;
11743 		}
11744 
11745 		ecb->dte_next = NULL;
11746 	}
11747 }
11748 
11749 static void
dtrace_ecb_destroy(dtrace_ecb_t * ecb)11750 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11751 {
11752 	dtrace_state_t *state = ecb->dte_state;
11753 	dtrace_vstate_t *vstate = &state->dts_vstate;
11754 	dtrace_predicate_t *pred;
11755 	dtrace_epid_t epid = ecb->dte_epid;
11756 
11757 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11758 	ASSERT(ecb->dte_next == NULL);
11759 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11760 
11761 	if ((pred = ecb->dte_predicate) != NULL)
11762 		dtrace_predicate_release(pred, vstate);
11763 
11764 	dtrace_ecb_action_remove(ecb);
11765 
11766 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11767 	state->dts_ecbs[epid - 1] = NULL;
11768 
11769 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11770 }
11771 
11772 static dtrace_ecb_t *
dtrace_ecb_create(dtrace_state_t * state,dtrace_probe_t * probe,dtrace_enabling_t * enab)11773 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11774     dtrace_enabling_t *enab)
11775 {
11776 	dtrace_ecb_t *ecb;
11777 	dtrace_predicate_t *pred;
11778 	dtrace_actdesc_t *act;
11779 	dtrace_provider_t *prov;
11780 	dtrace_ecbdesc_t *desc = enab->dten_current;
11781 
11782 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11783 	ASSERT(state != NULL);
11784 
11785 	ecb = dtrace_ecb_add(state, probe);
11786 	ecb->dte_uarg = desc->dted_uarg;
11787 
11788 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11789 		dtrace_predicate_hold(pred);
11790 		ecb->dte_predicate = pred;
11791 	}
11792 
11793 	if (probe != NULL) {
11794 		/*
11795 		 * If the provider shows more leg than the consumer is old
11796 		 * enough to see, we need to enable the appropriate implicit
11797 		 * predicate bits to prevent the ecb from activating at
11798 		 * revealing times.
11799 		 *
11800 		 * Providers specifying DTRACE_PRIV_USER at register time
11801 		 * are stating that they need the /proc-style privilege
11802 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11803 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11804 		 */
11805 		prov = probe->dtpr_provider;
11806 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11807 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11808 			ecb->dte_cond |= DTRACE_COND_OWNER;
11809 
11810 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11811 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11812 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11813 
11814 		/*
11815 		 * If the provider shows us kernel innards and the user
11816 		 * is lacking sufficient privilege, enable the
11817 		 * DTRACE_COND_USERMODE implicit predicate.
11818 		 */
11819 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11820 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11821 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11822 	}
11823 
11824 	if (dtrace_ecb_create_cache != NULL) {
11825 		/*
11826 		 * If we have a cached ecb, we'll use its action list instead
11827 		 * of creating our own (saving both time and space).
11828 		 */
11829 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11830 		dtrace_action_t *act_if = cached->dte_action;
11831 
11832 		if (act_if != NULL) {
11833 			ASSERT(act_if->dta_refcnt > 0);
11834 			act_if->dta_refcnt++;
11835 			ecb->dte_action = act_if;
11836 			ecb->dte_action_last = cached->dte_action_last;
11837 			ecb->dte_needed = cached->dte_needed;
11838 			ecb->dte_size = cached->dte_size;
11839 			ecb->dte_alignment = cached->dte_alignment;
11840 		}
11841 
11842 		return (ecb);
11843 	}
11844 
11845 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11846 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11847 			dtrace_ecb_destroy(ecb);
11848 			return (NULL);
11849 		}
11850 	}
11851 
11852 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11853 		dtrace_ecb_destroy(ecb);
11854 		return (NULL);
11855 	}
11856 
11857 	return (dtrace_ecb_create_cache = ecb);
11858 }
11859 
11860 static int
dtrace_ecb_create_enable(dtrace_probe_t * probe,void * arg1,void * arg2)11861 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg1, void *arg2)
11862 {
11863 	dtrace_ecb_t *ecb;
11864 	dtrace_enabling_t *enab = arg1;
11865 	dtrace_ecbdesc_t *ep = arg2;
11866 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11867 
11868 	ASSERT(state != NULL);
11869 
11870 	if (probe != NULL && ep != NULL && probe->dtpr_gen < ep->dted_probegen) {
11871 		/*
11872 		 * This probe was created in a generation for which this
11873 		 * enabling has previously created ECBs; we don't want to
11874 		 * enable it again, so just kick out.
11875 		 */
11876 		return (DTRACE_MATCH_NEXT);
11877 	}
11878 
11879 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11880 		return (DTRACE_MATCH_DONE);
11881 
11882 	if (dtrace_ecb_enable(ecb) < 0)
11883                return (DTRACE_MATCH_FAIL);
11884 
11885 	return (DTRACE_MATCH_NEXT);
11886 }
11887 
11888 static dtrace_ecb_t *
dtrace_epid2ecb(dtrace_state_t * state,dtrace_epid_t id)11889 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11890 {
11891 	dtrace_ecb_t *ecb;
11892 #pragma unused(ecb) /* __APPLE__ */
11893 
11894 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11895 
11896 	if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
11897 		return (NULL);
11898 
11899 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11900 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11901 
11902 	return (state->dts_ecbs[id - 1]);
11903 }
11904 
11905 static dtrace_aggregation_t *
dtrace_aggid2agg(dtrace_state_t * state,dtrace_aggid_t id)11906 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11907 {
11908 	dtrace_aggregation_t *agg;
11909 #pragma unused(agg) /* __APPLE__ */
11910 
11911 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11912 
11913 	if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
11914 		return (NULL);
11915 
11916 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11917 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11918 	    agg->dtag_id == id);
11919 
11920 	return (state->dts_aggregations[id - 1]);
11921 }
11922 
11923 /*
11924  * DTrace Buffer Functions
11925  *
11926  * The following functions manipulate DTrace buffers.  Most of these functions
11927  * are called in the context of establishing or processing consumer state;
11928  * exceptions are explicitly noted.
11929  */
11930 
11931 /*
11932  * Note:  called from cross call context.  This function switches the two
11933  * buffers on a given CPU.  The atomicity of this operation is assured by
11934  * disabling interrupts while the actual switch takes place; the disabling of
11935  * interrupts serializes the execution with any execution of dtrace_probe() on
11936  * the same CPU.
11937  */
11938 static void
dtrace_buffer_switch(dtrace_buffer_t * buf)11939 dtrace_buffer_switch(dtrace_buffer_t *buf)
11940 {
11941 	caddr_t tomax = buf->dtb_tomax;
11942 	caddr_t xamot = buf->dtb_xamot;
11943 	dtrace_icookie_t cookie;
11944 	hrtime_t now;
11945 
11946 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11947 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11948 
11949 	cookie = dtrace_interrupt_disable();
11950 	now = dtrace_gethrtime();
11951 	buf->dtb_tomax = xamot;
11952 	buf->dtb_xamot = tomax;
11953 	buf->dtb_xamot_drops = buf->dtb_drops;
11954 	buf->dtb_xamot_offset = buf->dtb_offset;
11955 	buf->dtb_xamot_errors = buf->dtb_errors;
11956 	buf->dtb_xamot_flags = buf->dtb_flags;
11957 	buf->dtb_offset = 0;
11958 	buf->dtb_drops = 0;
11959 	buf->dtb_errors = 0;
11960 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11961 	buf->dtb_interval = now - buf->dtb_switched;
11962 	buf->dtb_switched = now;
11963 	buf->dtb_cur_limit = buf->dtb_limit;
11964 
11965 	dtrace_interrupt_enable(cookie);
11966 }
11967 
11968 /*
11969  * Note:  called from cross call context.  This function activates a buffer
11970  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11971  * is guaranteed by the disabling of interrupts.
11972  */
11973 static void
dtrace_buffer_activate(dtrace_state_t * state)11974 dtrace_buffer_activate(dtrace_state_t *state)
11975 {
11976 	dtrace_buffer_t *buf;
11977 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11978 
11979 	buf = &state->dts_buffer[CPU->cpu_id];
11980 
11981 	if (buf->dtb_tomax != NULL) {
11982 		/*
11983 		 * We might like to assert that the buffer is marked inactive,
11984 		 * but this isn't necessarily true:  the buffer for the CPU
11985 		 * that processes the BEGIN probe has its buffer activated
11986 		 * manually.  In this case, we take the (harmless) action
11987 		 * re-clearing the bit INACTIVE bit.
11988 		 */
11989 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11990 	}
11991 
11992 	dtrace_interrupt_enable(cookie);
11993 }
11994 
11995 static int
dtrace_buffer_canalloc(size_t size)11996 dtrace_buffer_canalloc(size_t size)
11997 {
11998 	if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
11999 		return (B_FALSE);
12000 	if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
12001 		return (B_FALSE);
12002 
12003 	return (B_TRUE);
12004 }
12005 
12006 static int
dtrace_buffer_alloc(dtrace_buffer_t * bufs,size_t limit,size_t size,int flags,processorid_t cpu)12007 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t limit, size_t size, int flags,
12008     processorid_t cpu)
12009 {
12010 	dtrace_cpu_t *cp;
12011 	dtrace_buffer_t *buf;
12012 	size_t size_before_alloc = dtrace_buffer_memory_inuse;
12013 
12014 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12015 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12016 
12017 	if (size > (size_t)dtrace_nonroot_maxsize &&
12018 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12019 		return (EFBIG);
12020 
12021 	cp = cpu_list;
12022 
12023 	do {
12024 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12025 			continue;
12026 
12027 		buf = &bufs[cp->cpu_id];
12028 
12029 		/*
12030 		 * If there is already a buffer allocated for this CPU, it
12031 		 * is only possible that this is a DR event.  In this case,
12032 		 * the buffer size must match our specified size.
12033 		 */
12034 		if (buf->dtb_tomax != NULL) {
12035 			ASSERT(buf->dtb_size == size);
12036 			continue;
12037 		}
12038 
12039 		ASSERT(buf->dtb_xamot == NULL);
12040 
12041 		/* DTrace, please do not eat all the memory. */
12042 		if (dtrace_buffer_canalloc(size) == B_FALSE)
12043 			goto err;
12044 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12045 			goto err;
12046 		dtrace_buffer_memory_inuse += size;
12047 
12048 		/* Unsure that limit is always lower than size */
12049 		limit = limit == size ? limit - 1 : limit;
12050 		buf->dtb_cur_limit = limit;
12051 		buf->dtb_limit = limit;
12052 		buf->dtb_size = size;
12053 		buf->dtb_flags = flags;
12054 		buf->dtb_offset = 0;
12055 		buf->dtb_drops = 0;
12056 
12057 		if (flags & DTRACEBUF_NOSWITCH)
12058 			continue;
12059 
12060 		/* DTrace, please do not eat all the memory. */
12061 		if (dtrace_buffer_canalloc(size) == B_FALSE)
12062 			goto err;
12063 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12064 			goto err;
12065 		dtrace_buffer_memory_inuse += size;
12066 	} while ((cp = cp->cpu_next) != cpu_list);
12067 
12068 	ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
12069 
12070 	return (0);
12071 
12072 err:
12073 	cp = cpu_list;
12074 
12075 	do {
12076 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12077 			continue;
12078 
12079 		buf = &bufs[cp->cpu_id];
12080 
12081 		if (buf->dtb_xamot != NULL) {
12082 			ASSERT(buf->dtb_tomax != NULL);
12083 			ASSERT(buf->dtb_size == size);
12084 			kmem_free(buf->dtb_xamot, size);
12085 		}
12086 
12087 		if (buf->dtb_tomax != NULL) {
12088 			ASSERT(buf->dtb_size == size);
12089 			kmem_free(buf->dtb_tomax, size);
12090 		}
12091 
12092 		buf->dtb_tomax = NULL;
12093 		buf->dtb_xamot = NULL;
12094 		buf->dtb_size = 0;
12095 	} while ((cp = cp->cpu_next) != cpu_list);
12096 
12097 	/* Restore the size saved before allocating memory */
12098 	dtrace_buffer_memory_inuse = size_before_alloc;
12099 
12100 	return (ENOMEM);
12101 }
12102 
12103 /*
12104  * Note:  called from probe context.  This function just increments the drop
12105  * count on a buffer.  It has been made a function to allow for the
12106  * possibility of understanding the source of mysterious drop counts.  (A
12107  * problem for which one may be particularly disappointed that DTrace cannot
12108  * be used to understand DTrace.)
12109  */
12110 static void
dtrace_buffer_drop(dtrace_buffer_t * buf)12111 dtrace_buffer_drop(dtrace_buffer_t *buf)
12112 {
12113 	buf->dtb_drops++;
12114 }
12115 
12116 /*
12117  * Note:  called from probe context.  This function is called to reserve space
12118  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12119  * mstate.  Returns the new offset in the buffer, or a negative value if an
12120  * error has occurred.
12121  */
12122 static intptr_t
dtrace_buffer_reserve(dtrace_buffer_t * buf,size_t needed,size_t align,dtrace_state_t * state,dtrace_mstate_t * mstate)12123 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12124     dtrace_state_t *state, dtrace_mstate_t *mstate)
12125 {
12126 	intptr_t offs = buf->dtb_offset, soffs;
12127 	intptr_t woffs;
12128 	caddr_t tomax;
12129 	size_t total_off;
12130 
12131 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12132 		return (-1);
12133 
12134 	if ((tomax = buf->dtb_tomax) == NULL) {
12135 		dtrace_buffer_drop(buf);
12136 		return (-1);
12137 	}
12138 
12139 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12140 		while (offs & (align - 1)) {
12141 			/*
12142 			 * Assert that our alignment is off by a number which
12143 			 * is itself sizeof (uint32_t) aligned.
12144 			 */
12145 			ASSERT(!((align - (offs & (align - 1))) &
12146 			    (sizeof (uint32_t) - 1)));
12147 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12148 			offs += sizeof (uint32_t);
12149 		}
12150 
12151 		if ((uint64_t)(soffs = offs + needed) > buf->dtb_cur_limit) {
12152 			if (buf->dtb_cur_limit == buf->dtb_limit) {
12153 				buf->dtb_cur_limit = buf->dtb_size;
12154 
12155 				os_atomic_inc(&state->dts_buf_over_limit, relaxed);
12156 				/**
12157 				 * Set an AST on the current processor
12158 				 * so that we can wake up the process
12159 				 * outside of probe context, when we know
12160 				 * it is safe to do so
12161 				 */
12162 				minor_t minor = getminor(state->dts_dev);
12163 				ASSERT(minor < 32);
12164 
12165 				os_atomic_or(&dtrace_wake_clients, 1 << minor, relaxed);
12166 				ast_dtrace_on();
12167 			}
12168 			if ((uint64_t)soffs > buf->dtb_size) {
12169 				dtrace_buffer_drop(buf);
12170 				return (-1);
12171 			}
12172 		}
12173 
12174 		if (mstate == NULL)
12175 			return (offs);
12176 
12177 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12178 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12179 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12180 
12181 		return (offs);
12182 	}
12183 
12184 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12185 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12186 		    (buf->dtb_flags & DTRACEBUF_FULL))
12187 			return (-1);
12188 		goto out;
12189 	}
12190 
12191 	total_off = needed + (offs & (align - 1));
12192 
12193 	/*
12194 	 * For a ring buffer, life is quite a bit more complicated.  Before
12195 	 * we can store any padding, we need to adjust our wrapping offset.
12196 	 * (If we've never before wrapped or we're not about to, no adjustment
12197 	 * is required.)
12198 	 */
12199 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12200 	    offs + total_off > buf->dtb_size) {
12201 		woffs = buf->dtb_xamot_offset;
12202 
12203 		if (offs + total_off > buf->dtb_size) {
12204 			/*
12205 			 * We can't fit in the end of the buffer.  First, a
12206 			 * sanity check that we can fit in the buffer at all.
12207 			 */
12208 			if (total_off > buf->dtb_size) {
12209 				dtrace_buffer_drop(buf);
12210 				return (-1);
12211 			}
12212 
12213 			/*
12214 			 * We're going to be storing at the top of the buffer,
12215 			 * so now we need to deal with the wrapped offset.  We
12216 			 * only reset our wrapped offset to 0 if it is
12217 			 * currently greater than the current offset.  If it
12218 			 * is less than the current offset, it is because a
12219 			 * previous allocation induced a wrap -- but the
12220 			 * allocation didn't subsequently take the space due
12221 			 * to an error or false predicate evaluation.  In this
12222 			 * case, we'll just leave the wrapped offset alone: if
12223 			 * the wrapped offset hasn't been advanced far enough
12224 			 * for this allocation, it will be adjusted in the
12225 			 * lower loop.
12226 			 */
12227 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12228 				if (woffs >= offs)
12229 					woffs = 0;
12230 			} else {
12231 				woffs = 0;
12232 			}
12233 
12234 			/*
12235 			 * Now we know that we're going to be storing to the
12236 			 * top of the buffer and that there is room for us
12237 			 * there.  We need to clear the buffer from the current
12238 			 * offset to the end (there may be old gunk there).
12239 			 */
12240 			while ((uint64_t)offs < buf->dtb_size)
12241 				tomax[offs++] = 0;
12242 
12243 			/*
12244 			 * We need to set our offset to zero.  And because we
12245 			 * are wrapping, we need to set the bit indicating as
12246 			 * much.  We can also adjust our needed space back
12247 			 * down to the space required by the ECB -- we know
12248 			 * that the top of the buffer is aligned.
12249 			 */
12250 			offs = 0;
12251 			total_off = needed;
12252 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12253 		} else {
12254 			/*
12255 			 * There is room for us in the buffer, so we simply
12256 			 * need to check the wrapped offset.
12257 			 */
12258 			if (woffs < offs) {
12259 				/*
12260 				 * The wrapped offset is less than the offset.
12261 				 * This can happen if we allocated buffer space
12262 				 * that induced a wrap, but then we didn't
12263 				 * subsequently take the space due to an error
12264 				 * or false predicate evaluation.  This is
12265 				 * okay; we know that _this_ allocation isn't
12266 				 * going to induce a wrap.  We still can't
12267 				 * reset the wrapped offset to be zero,
12268 				 * however: the space may have been trashed in
12269 				 * the previous failed probe attempt.  But at
12270 				 * least the wrapped offset doesn't need to
12271 				 * be adjusted at all...
12272 				 */
12273 				goto out;
12274 			}
12275 		}
12276 
12277 		while (offs + total_off > (size_t)woffs) {
12278 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12279 			size_t size;
12280 
12281 			if (epid == DTRACE_EPIDNONE) {
12282 				size = sizeof (uint32_t);
12283 			} else {
12284 				ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
12285 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12286 
12287 				size = state->dts_ecbs[epid - 1]->dte_size;
12288 			}
12289 
12290 			ASSERT(woffs + size <= buf->dtb_size);
12291 			ASSERT(size != 0);
12292 
12293 			if (woffs + size == buf->dtb_size) {
12294 				/*
12295 				 * We've reached the end of the buffer; we want
12296 				 * to set the wrapped offset to 0 and break
12297 				 * out.  However, if the offs is 0, then we're
12298 				 * in a strange edge-condition:  the amount of
12299 				 * space that we want to reserve plus the size
12300 				 * of the record that we're overwriting is
12301 				 * greater than the size of the buffer.  This
12302 				 * is problematic because if we reserve the
12303 				 * space but subsequently don't consume it (due
12304 				 * to a failed predicate or error) the wrapped
12305 				 * offset will be 0 -- yet the EPID at offset 0
12306 				 * will not be committed.  This situation is
12307 				 * relatively easy to deal with:  if we're in
12308 				 * this case, the buffer is indistinguishable
12309 				 * from one that hasn't wrapped; we need only
12310 				 * finish the job by clearing the wrapped bit,
12311 				 * explicitly setting the offset to be 0, and
12312 				 * zero'ing out the old data in the buffer.
12313 				 */
12314 				if (offs == 0) {
12315 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12316 					buf->dtb_offset = 0;
12317 					woffs = total_off;
12318 
12319 					while ((uint64_t)woffs < buf->dtb_size)
12320 						tomax[woffs++] = 0;
12321 				}
12322 
12323 				woffs = 0;
12324 				break;
12325 			}
12326 
12327 			woffs += size;
12328 		}
12329 
12330 		/*
12331 		 * We have a wrapped offset.  It may be that the wrapped offset
12332 		 * has become zero -- that's okay.
12333 		 */
12334 		buf->dtb_xamot_offset = woffs;
12335 	}
12336 
12337 out:
12338 	/*
12339 	 * Now we can plow the buffer with any necessary padding.
12340 	 */
12341 	while (offs & (align - 1)) {
12342 		/*
12343 		 * Assert that our alignment is off by a number which
12344 		 * is itself sizeof (uint32_t) aligned.
12345 		 */
12346 		ASSERT(!((align - (offs & (align - 1))) &
12347 		    (sizeof (uint32_t) - 1)));
12348 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12349 		offs += sizeof (uint32_t);
12350 	}
12351 
12352 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12353 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12354 			buf->dtb_flags |= DTRACEBUF_FULL;
12355 			return (-1);
12356 		}
12357 	}
12358 
12359 	if (mstate == NULL)
12360 		return (offs);
12361 
12362 	/*
12363 	 * For ring buffers and fill buffers, the scratch space is always
12364 	 * the inactive buffer.
12365 	 */
12366 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12367 	mstate->dtms_scratch_size = buf->dtb_size;
12368 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12369 
12370 	return (offs);
12371 }
12372 
12373 static void
dtrace_buffer_polish(dtrace_buffer_t * buf)12374 dtrace_buffer_polish(dtrace_buffer_t *buf)
12375 {
12376 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12377 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12378 
12379 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12380 		return;
12381 
12382 	/*
12383 	 * We need to polish the ring buffer.  There are three cases:
12384 	 *
12385 	 * - The first (and presumably most common) is that there is no gap
12386 	 *   between the buffer offset and the wrapped offset.  In this case,
12387 	 *   there is nothing in the buffer that isn't valid data; we can
12388 	 *   mark the buffer as polished and return.
12389 	 *
12390 	 * - The second (less common than the first but still more common
12391 	 *   than the third) is that there is a gap between the buffer offset
12392 	 *   and the wrapped offset, and the wrapped offset is larger than the
12393 	 *   buffer offset.  This can happen because of an alignment issue, or
12394 	 *   can happen because of a call to dtrace_buffer_reserve() that
12395 	 *   didn't subsequently consume the buffer space.  In this case,
12396 	 *   we need to zero the data from the buffer offset to the wrapped
12397 	 *   offset.
12398 	 *
12399 	 * - The third (and least common) is that there is a gap between the
12400 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12401 	 *   _less_ than the buffer offset.  This can only happen because a
12402 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12403 	 *   was not subsequently consumed.  In this case, we need to zero the
12404 	 *   space from the offset to the end of the buffer _and_ from the
12405 	 *   top of the buffer to the wrapped offset.
12406 	 */
12407 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12408 		bzero(buf->dtb_tomax + buf->dtb_offset,
12409 		    buf->dtb_xamot_offset - buf->dtb_offset);
12410 	}
12411 
12412 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12413 		bzero(buf->dtb_tomax + buf->dtb_offset,
12414 		    buf->dtb_size - buf->dtb_offset);
12415 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12416 	}
12417 }
12418 
12419 static void
dtrace_buffer_free(dtrace_buffer_t * bufs)12420 dtrace_buffer_free(dtrace_buffer_t *bufs)
12421 {
12422 	int i;
12423 
12424 	for (i = 0; i < (int)NCPU; i++) {
12425 		dtrace_buffer_t *buf = &bufs[i];
12426 
12427 		if (buf->dtb_tomax == NULL) {
12428 			ASSERT(buf->dtb_xamot == NULL);
12429 			ASSERT(buf->dtb_size == 0);
12430 			continue;
12431 		}
12432 
12433 		if (buf->dtb_xamot != NULL) {
12434 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12435 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12436 
12437 			ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
12438 			dtrace_buffer_memory_inuse -= buf->dtb_size;
12439 		}
12440 
12441 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12442 		ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
12443 		dtrace_buffer_memory_inuse -= buf->dtb_size;
12444 
12445 		buf->dtb_size = 0;
12446 		buf->dtb_tomax = NULL;
12447 		buf->dtb_xamot = NULL;
12448 	}
12449 }
12450 
12451 /*
12452  * DTrace Enabling Functions
12453  */
12454 static dtrace_enabling_t *
dtrace_enabling_create(dtrace_vstate_t * vstate)12455 dtrace_enabling_create(dtrace_vstate_t *vstate)
12456 {
12457 	dtrace_enabling_t *enab;
12458 
12459 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12460 	enab->dten_vstate = vstate;
12461 
12462 	return (enab);
12463 }
12464 
12465 static void
dtrace_enabling_add(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb)12466 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12467 {
12468 	dtrace_ecbdesc_t **ndesc;
12469 	size_t osize, nsize;
12470 
12471 	/*
12472 	 * We can't add to enablings after we've enabled them, or after we've
12473 	 * retained them.
12474 	 */
12475 	ASSERT(enab->dten_probegen == 0);
12476 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12477 
12478 	/* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
12479 	if (ecb == NULL) return;
12480 
12481 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12482 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12483 		return;
12484 	}
12485 
12486 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12487 
12488 	if (enab->dten_maxdesc == 0) {
12489 		enab->dten_maxdesc = 1;
12490 	} else {
12491 		enab->dten_maxdesc <<= 1;
12492 	}
12493 
12494 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12495 
12496 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12497 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12498 	bcopy(enab->dten_desc, ndesc, osize);
12499 	kmem_free(enab->dten_desc, osize);
12500 
12501 	enab->dten_desc = ndesc;
12502 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12503 }
12504 
12505 static void
dtrace_enabling_addlike(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb,dtrace_probedesc_t * pd)12506 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12507     dtrace_probedesc_t *pd)
12508 {
12509 	dtrace_ecbdesc_t *new;
12510 	dtrace_predicate_t *pred;
12511 	dtrace_actdesc_t *act;
12512 
12513 	/*
12514 	 * We're going to create a new ECB description that matches the
12515 	 * specified ECB in every way, but has the specified probe description.
12516 	 */
12517 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12518 
12519 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12520 		dtrace_predicate_hold(pred);
12521 
12522 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12523 		dtrace_actdesc_hold(act);
12524 
12525 	new->dted_action = ecb->dted_action;
12526 	new->dted_pred = ecb->dted_pred;
12527 	new->dted_probe = *pd;
12528 	new->dted_uarg = ecb->dted_uarg;
12529 
12530 	dtrace_enabling_add(enab, new);
12531 }
12532 
12533 static void
dtrace_enabling_dump(dtrace_enabling_t * enab)12534 dtrace_enabling_dump(dtrace_enabling_t *enab)
12535 {
12536 	int i;
12537 
12538 	for (i = 0; i < enab->dten_ndesc; i++) {
12539 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12540 
12541 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12542 		    desc->dtpd_provider, desc->dtpd_mod,
12543 		    desc->dtpd_func, desc->dtpd_name);
12544 	}
12545 }
12546 
12547 static void
dtrace_enabling_destroy(dtrace_enabling_t * enab)12548 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12549 {
12550 	int i;
12551 	dtrace_ecbdesc_t *ep;
12552 	dtrace_vstate_t *vstate = enab->dten_vstate;
12553 
12554 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12555 
12556 	for (i = 0; i < enab->dten_ndesc; i++) {
12557 		dtrace_actdesc_t *act, *next;
12558 		dtrace_predicate_t *pred;
12559 
12560 		ep = enab->dten_desc[i];
12561 
12562 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12563 			dtrace_predicate_release(pred, vstate);
12564 
12565 		for (act = ep->dted_action; act != NULL; act = next) {
12566 			next = act->dtad_next;
12567 			dtrace_actdesc_release(act, vstate);
12568 		}
12569 
12570 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12571 	}
12572 
12573 	kmem_free(enab->dten_desc,
12574 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12575 
12576 	/*
12577 	 * If this was a retained enabling, decrement the dts_nretained count
12578 	 * and take it off of the dtrace_retained list.
12579 	 */
12580 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12581 	    dtrace_retained == enab) {
12582 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12583 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12584 		enab->dten_vstate->dtvs_state->dts_nretained--;
12585                 dtrace_retained_gen++;
12586 	}
12587 
12588 	if (enab->dten_prev == NULL) {
12589 		if (dtrace_retained == enab) {
12590 			dtrace_retained = enab->dten_next;
12591 
12592 			if (dtrace_retained != NULL)
12593 				dtrace_retained->dten_prev = NULL;
12594 		}
12595 	} else {
12596 		ASSERT(enab != dtrace_retained);
12597 		ASSERT(dtrace_retained != NULL);
12598 		enab->dten_prev->dten_next = enab->dten_next;
12599 	}
12600 
12601 	if (enab->dten_next != NULL) {
12602 		ASSERT(dtrace_retained != NULL);
12603 		enab->dten_next->dten_prev = enab->dten_prev;
12604 	}
12605 
12606 	kmem_free(enab, sizeof (dtrace_enabling_t));
12607 }
12608 
12609 static int
dtrace_enabling_retain(dtrace_enabling_t * enab)12610 dtrace_enabling_retain(dtrace_enabling_t *enab)
12611 {
12612 	dtrace_state_t *state;
12613 
12614 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12615 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12616 	ASSERT(enab->dten_vstate != NULL);
12617 
12618 	state = enab->dten_vstate->dtvs_state;
12619 	ASSERT(state != NULL);
12620 
12621 	/*
12622 	 * We only allow each state to retain dtrace_retain_max enablings.
12623 	 */
12624 	if (state->dts_nretained >= dtrace_retain_max)
12625 		return (ENOSPC);
12626 
12627 	state->dts_nretained++;
12628         dtrace_retained_gen++;
12629 
12630 	if (dtrace_retained == NULL) {
12631 		dtrace_retained = enab;
12632 		return (0);
12633 	}
12634 
12635 	enab->dten_next = dtrace_retained;
12636 	dtrace_retained->dten_prev = enab;
12637 	dtrace_retained = enab;
12638 
12639 	return (0);
12640 }
12641 
12642 static int
dtrace_enabling_replicate(dtrace_state_t * state,dtrace_probedesc_t * match,dtrace_probedesc_t * create)12643 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12644     dtrace_probedesc_t *create)
12645 {
12646 	dtrace_enabling_t *new, *enab;
12647 	int found = 0, err = ENOENT;
12648 
12649 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12650 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12651 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12652 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12653 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12654 
12655 	new = dtrace_enabling_create(&state->dts_vstate);
12656 
12657 	/*
12658 	 * Iterate over all retained enablings, looking for enablings that
12659 	 * match the specified state.
12660 	 */
12661 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12662 		int i;
12663 
12664 		/*
12665 		 * dtvs_state can only be NULL for helper enablings -- and
12666 		 * helper enablings can't be retained.
12667 		 */
12668 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12669 
12670 		if (enab->dten_vstate->dtvs_state != state)
12671 			continue;
12672 
12673 		/*
12674 		 * Now iterate over each probe description; we're looking for
12675 		 * an exact match to the specified probe description.
12676 		 */
12677 		for (i = 0; i < enab->dten_ndesc; i++) {
12678 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12679 			dtrace_probedesc_t *pd = &ep->dted_probe;
12680 
12681 			/* APPLE NOTE: Darwin employs size bounded string operation. */
12682 			if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
12683 				continue;
12684 
12685 			if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
12686 				continue;
12687 
12688 			if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
12689 				continue;
12690 
12691 			if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
12692 				continue;
12693 
12694 			/*
12695 			 * We have a winning probe!  Add it to our growing
12696 			 * enabling.
12697 			 */
12698 			found = 1;
12699 			dtrace_enabling_addlike(new, ep, create);
12700 		}
12701 	}
12702 
12703 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12704 		dtrace_enabling_destroy(new);
12705 		return (err);
12706 	}
12707 
12708 	return (0);
12709 }
12710 
12711 static void
dtrace_enabling_retract(dtrace_state_t * state)12712 dtrace_enabling_retract(dtrace_state_t *state)
12713 {
12714 	dtrace_enabling_t *enab, *next;
12715 
12716 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12717 
12718 	/*
12719 	 * Iterate over all retained enablings, destroy the enablings retained
12720 	 * for the specified state.
12721 	 */
12722 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12723 		next = enab->dten_next;
12724 
12725 		/*
12726 		 * dtvs_state can only be NULL for helper enablings -- and
12727 		 * helper enablings can't be retained.
12728 		 */
12729 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12730 
12731 		if (enab->dten_vstate->dtvs_state == state) {
12732 			ASSERT(state->dts_nretained > 0);
12733 			dtrace_enabling_destroy(enab);
12734 		}
12735 	}
12736 
12737 	ASSERT(state->dts_nretained == 0);
12738 }
12739 
12740 static int
dtrace_enabling_match(dtrace_enabling_t * enab,int * nmatched,dtrace_match_cond_t * cond)12741 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched, dtrace_match_cond_t *cond)
12742 {
12743 	int i = 0;
12744 	int total_matched = 0, matched = 0;
12745 
12746 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12747 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12748 
12749 	for (i = 0; i < enab->dten_ndesc; i++) {
12750 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12751 
12752 		enab->dten_current = ep;
12753 		enab->dten_error = 0;
12754 
12755 		/**
12756 		 * Before doing a dtrace_probe_enable, which is really
12757 		 * expensive, check that this enabling matches the matching precondition
12758 		 * if we have one
12759 		 */
12760 		if (cond && (cond->dmc_func(&ep->dted_probe, cond->dmc_data) == 0)) {
12761 			continue;
12762 		}
12763 		/*
12764 		 * If a provider failed to enable a probe then get out and
12765 		 * let the consumer know we failed.
12766 		 */
12767 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab, ep)) < 0)
12768 			return (EBUSY);
12769 
12770 		total_matched += matched;
12771 
12772 		if (enab->dten_error != 0) {
12773 			/*
12774 			 * If we get an error half-way through enabling the
12775 			 * probes, we kick out -- perhaps with some number of
12776 			 * them enabled.  Leaving enabled probes enabled may
12777 			 * be slightly confusing for user-level, but we expect
12778 			 * that no one will attempt to actually drive on in
12779 			 * the face of such errors.  If this is an anonymous
12780 			 * enabling (indicated with a NULL nmatched pointer),
12781 			 * we cmn_err() a message.  We aren't expecting to
12782 			 * get such an error -- such as it can exist at all,
12783 			 * it would be a result of corrupted DOF in the driver
12784 			 * properties.
12785 			 */
12786 			if (nmatched == NULL) {
12787 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12788 				    "error on %p: %d", (void *)ep,
12789 				    enab->dten_error);
12790 			}
12791 
12792 			return (enab->dten_error);
12793 		}
12794 
12795 		ep->dted_probegen = dtrace_probegen;
12796 	}
12797 
12798 	if (nmatched != NULL)
12799 		*nmatched = total_matched;
12800 
12801 	return (0);
12802 }
12803 
12804 static void
dtrace_enabling_matchall_with_cond(dtrace_match_cond_t * cond)12805 dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond)
12806 {
12807 	dtrace_enabling_t *enab;
12808 
12809 	lck_mtx_lock(&cpu_lock);
12810 	lck_mtx_lock(&dtrace_lock);
12811 
12812 	/*
12813 	 * Iterate over all retained enablings to see if any probes match
12814 	 * against them.  We only perform this operation on enablings for which
12815 	 * we have sufficient permissions by virtue of being in the global zone
12816 	 * or in the same zone as the DTrace client.  Because we can be called
12817 	 * after dtrace_detach() has been called, we cannot assert that there
12818 	 * are retained enablings.  We can safely load from dtrace_retained,
12819 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12820 	 * block pending our completion.
12821 	 */
12822 
12823 	/*
12824 	 * Darwin doesn't do zones.
12825 	 * Behave as if always in "global" zone."
12826 	 */
12827 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12828 		(void) dtrace_enabling_match(enab, NULL, cond);
12829 	}
12830 
12831 	lck_mtx_unlock(&dtrace_lock);
12832 	lck_mtx_unlock(&cpu_lock);
12833 
12834 }
12835 
12836 static void
dtrace_enabling_matchall(void)12837 dtrace_enabling_matchall(void)
12838 {
12839 	dtrace_enabling_matchall_with_cond(NULL);
12840 }
12841 
12842 
12843 
12844 /*
12845  * If an enabling is to be enabled without having matched probes (that is, if
12846  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12847  * enabling must be _primed_ by creating an ECB for every ECB description.
12848  * This must be done to assure that we know the number of speculations, the
12849  * number of aggregations, the minimum buffer size needed, etc. before we
12850  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12851  * enabling any probes, we create ECBs for every ECB decription, but with a
12852  * NULL probe -- which is exactly what this function does.
12853  */
12854 static void
dtrace_enabling_prime(dtrace_state_t * state)12855 dtrace_enabling_prime(dtrace_state_t *state)
12856 {
12857 	dtrace_enabling_t *enab;
12858 	int i;
12859 
12860 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12861 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12862 
12863 		if (enab->dten_vstate->dtvs_state != state)
12864 			continue;
12865 
12866 		/*
12867 		 * We don't want to prime an enabling more than once, lest
12868 		 * we allow a malicious user to induce resource exhaustion.
12869 		 * (The ECBs that result from priming an enabling aren't
12870 		 * leaked -- but they also aren't deallocated until the
12871 		 * consumer state is destroyed.)
12872 		 */
12873 		if (enab->dten_primed)
12874 			continue;
12875 
12876 		for (i = 0; i < enab->dten_ndesc; i++) {
12877 			enab->dten_current = enab->dten_desc[i];
12878 			(void) dtrace_probe_enable(NULL, enab, NULL);
12879 		}
12880 
12881 		enab->dten_primed = 1;
12882 	}
12883 }
12884 
12885 /*
12886  * Called to indicate that probes should be provided due to retained
12887  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12888  * must take an initial lap through the enabling calling the dtps_provide()
12889  * entry point explicitly to allow for autocreated probes.
12890  */
12891 static void
dtrace_enabling_provide(dtrace_provider_t * prv)12892 dtrace_enabling_provide(dtrace_provider_t *prv)
12893 {
12894 	int i, all = 0;
12895 	dtrace_probedesc_t desc;
12896         dtrace_genid_t gen;
12897 
12898 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12899 	LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
12900 
12901 	if (prv == NULL) {
12902 		all = 1;
12903 		prv = dtrace_provider;
12904 	}
12905 
12906 	do {
12907 		dtrace_enabling_t *enab;
12908 		void *parg = prv->dtpv_arg;
12909 
12910 retry:
12911 		gen = dtrace_retained_gen;
12912 		for (enab = dtrace_retained; enab != NULL;
12913 		    enab = enab->dten_next) {
12914 			for (i = 0; i < enab->dten_ndesc; i++) {
12915 				desc = enab->dten_desc[i]->dted_probe;
12916 				lck_mtx_unlock(&dtrace_lock);
12917 				prv->dtpv_pops.dtps_provide(parg, &desc);
12918 				lck_mtx_lock(&dtrace_lock);
12919 				/*
12920 				 * Process the retained enablings again if
12921 				 * they have changed while we weren't holding
12922 				 * dtrace_lock.
12923 				 */
12924 				if (gen != dtrace_retained_gen)
12925 					goto retry;
12926 			}
12927 		}
12928 	} while (all && (prv = prv->dtpv_next) != NULL);
12929 
12930 	lck_mtx_unlock(&dtrace_lock);
12931 	dtrace_probe_provide(NULL, all ? NULL : prv);
12932 	lck_mtx_lock(&dtrace_lock);
12933 }
12934 
12935 /*
12936  * DTrace DOF Functions
12937  */
12938 /*ARGSUSED*/
12939 static void
dtrace_dof_error(dof_hdr_t * dof,const char * str)12940 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12941 {
12942 #pragma unused(dof) /* __APPLE__ */
12943 	if (dtrace_err_verbose)
12944 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12945 
12946 #ifdef DTRACE_ERRDEBUG
12947 	dtrace_errdebug(str);
12948 #endif
12949 }
12950 
12951 /*
12952  * Create DOF out of a currently enabled state.  Right now, we only create
12953  * DOF containing the run-time options -- but this could be expanded to create
12954  * complete DOF representing the enabled state.
12955  */
12956 static dof_hdr_t *
dtrace_dof_create(dtrace_state_t * state)12957 dtrace_dof_create(dtrace_state_t *state)
12958 {
12959 	dof_hdr_t *dof;
12960 	dof_sec_t *sec;
12961 	dof_optdesc_t *opt;
12962 	int i, len = sizeof (dof_hdr_t) +
12963 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12964 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12965 
12966 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12967 
12968 	dof = kmem_zalloc_aligned(len, 8, KM_SLEEP);
12969 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12970 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12971 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12972 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12973 
12974 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12975 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12976 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12977 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12978 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12979 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12980 
12981 	dof->dofh_flags = 0;
12982 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12983 	dof->dofh_secsize = sizeof (dof_sec_t);
12984 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12985 	dof->dofh_secoff = sizeof (dof_hdr_t);
12986 	dof->dofh_loadsz = len;
12987 	dof->dofh_filesz = len;
12988 	dof->dofh_pad = 0;
12989 
12990 	/*
12991 	 * Fill in the option section header...
12992 	 */
12993 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12994 	sec->dofs_type = DOF_SECT_OPTDESC;
12995 	sec->dofs_align = sizeof (uint64_t);
12996 	sec->dofs_flags = DOF_SECF_LOAD;
12997 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12998 
12999 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13000 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13001 
13002 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13003 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13004 
13005 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13006 		opt[i].dofo_option = i;
13007 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13008 		opt[i].dofo_value = state->dts_options[i];
13009 	}
13010 
13011 	return (dof);
13012 }
13013 
13014 static dof_hdr_t *
dtrace_dof_copyin(user_addr_t uarg,int * errp)13015 dtrace_dof_copyin(user_addr_t uarg, int *errp)
13016 {
13017 	dof_hdr_t hdr, *dof;
13018 
13019 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
13020 
13021 	/*
13022 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13023 	 */
13024 	if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
13025 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13026 		*errp = EFAULT;
13027 		return (NULL);
13028 	}
13029 
13030 	/*
13031 	 * Now we'll allocate the entire DOF and copy it in -- provided
13032 	 * that the length isn't outrageous.
13033 	 */
13034 	if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13035 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13036 		*errp = E2BIG;
13037 		return (NULL);
13038 	}
13039 
13040 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13041 		dtrace_dof_error(&hdr, "invalid load size");
13042 		*errp = EINVAL;
13043 		return (NULL);
13044 	}
13045 
13046 	dof = kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
13047 
13048         if (copyin(uarg, dof, hdr.dofh_loadsz) != 0  ||
13049 	  dof->dofh_loadsz != hdr.dofh_loadsz) {
13050 	    kmem_free_aligned(dof, hdr.dofh_loadsz);
13051 	    *errp = EFAULT;
13052 	    return (NULL);
13053 	}
13054 
13055 	return (dof);
13056 }
13057 
13058 static dof_hdr_t *
dtrace_dof_copyin_from_proc(proc_t * p,user_addr_t uarg,int * errp)13059 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
13060 {
13061 	dof_hdr_t hdr, *dof;
13062 
13063 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
13064 
13065 	/*
13066 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13067 	 */
13068 	if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
13069 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13070 		*errp = EFAULT;
13071 		return (NULL);
13072 	}
13073 
13074 	/*
13075 	 * Now we'll allocate the entire DOF and copy it in -- provided
13076 	 * that the length isn't outrageous.
13077 	 */
13078 	if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13079 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13080 		*errp = E2BIG;
13081 		return (NULL);
13082 	}
13083 
13084 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13085 		dtrace_dof_error(&hdr, "invalid load size");
13086 		*errp = EINVAL;
13087 		return (NULL);
13088 	}
13089 
13090 	dof = kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
13091 
13092 	if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
13093 		kmem_free_aligned(dof, hdr.dofh_loadsz);
13094 		*errp = EFAULT;
13095 		return (NULL);
13096 	}
13097 
13098 	return (dof);
13099 }
13100 
13101 static void
dtrace_dof_destroy(dof_hdr_t * dof)13102 dtrace_dof_destroy(dof_hdr_t *dof)
13103 {
13104 	kmem_free_aligned(dof, dof->dofh_loadsz);
13105 }
13106 
13107 static dof_hdr_t *
dtrace_dof_property(const char * name)13108 dtrace_dof_property(const char *name)
13109 {
13110 	unsigned int len = 0;
13111 	dof_hdr_t *dof;
13112 
13113 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
13114 		return NULL;
13115 	}
13116 
13117 	if (!PEReadNVRAMProperty(name, NULL, &len)) {
13118 		return NULL;
13119 	}
13120 
13121 	dof = kmem_alloc_aligned(len, 8, KM_SLEEP);
13122 
13123 	if (!PEReadNVRAMProperty(name, dof, &len)) {
13124 		dtrace_dof_destroy(dof);
13125 		dtrace_dof_error(NULL, "unreadable DOF");
13126 		return NULL;
13127 	}
13128 
13129 	if (len < sizeof (dof_hdr_t)) {
13130 		dtrace_dof_destroy(dof);
13131 		dtrace_dof_error(NULL, "truncated header");
13132 		return (NULL);
13133 	}
13134 
13135 	if (len < dof->dofh_loadsz) {
13136 		dtrace_dof_destroy(dof);
13137 		dtrace_dof_error(NULL, "truncated DOF");
13138 		return (NULL);
13139 	}
13140 
13141 	if (len != dof->dofh_loadsz) {
13142 		dtrace_dof_destroy(dof);
13143 		dtrace_dof_error(NULL, "invalid DOF size");
13144 		return (NULL);
13145 	}
13146 
13147 	if (dof->dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13148 		dtrace_dof_destroy(dof);
13149 		dtrace_dof_error(NULL, "oversized DOF");
13150 		return (NULL);
13151 	}
13152 
13153 	return (dof);
13154 }
13155 
13156 /*
13157  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13158  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13159  * a type other than DOF_SECT_NONE is specified, the header is checked against
13160  * this type and NULL is returned if the types do not match.
13161  */
13162 static dof_sec_t *
dtrace_dof_sect(dof_hdr_t * dof,uint32_t type,dof_secidx_t i)13163 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13164 {
13165 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13166 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13167 
13168 	if (i >= dof->dofh_secnum) {
13169 		dtrace_dof_error(dof, "referenced section index is invalid");
13170 		return (NULL);
13171 	}
13172 
13173 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13174 		dtrace_dof_error(dof, "referenced section is not loadable");
13175 		return (NULL);
13176 	}
13177 
13178 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13179 		dtrace_dof_error(dof, "referenced section is the wrong type");
13180 		return (NULL);
13181 	}
13182 
13183 	return (sec);
13184 }
13185 
13186 static dtrace_probedesc_t *
dtrace_dof_probedesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_probedesc_t * desc)13187 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13188 {
13189 	dof_probedesc_t *probe;
13190 	dof_sec_t *strtab;
13191 	uintptr_t daddr = (uintptr_t)dof;
13192 	uintptr_t str;
13193 	size_t size;
13194 
13195 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13196 		dtrace_dof_error(dof, "invalid probe section");
13197 		return (NULL);
13198 	}
13199 
13200 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13201 		dtrace_dof_error(dof, "bad alignment in probe description");
13202 		return (NULL);
13203 	}
13204 
13205 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13206 		dtrace_dof_error(dof, "truncated probe description");
13207 		return (NULL);
13208 	}
13209 
13210 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13211 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13212 
13213 	if (strtab == NULL)
13214 		return (NULL);
13215 
13216 	str = daddr + strtab->dofs_offset;
13217 	size = strtab->dofs_size;
13218 
13219 	if (probe->dofp_provider >= strtab->dofs_size) {
13220 		dtrace_dof_error(dof, "corrupt probe provider");
13221 		return (NULL);
13222 	}
13223 
13224 	(void) strncpy(desc->dtpd_provider,
13225 	    (char *)(str + probe->dofp_provider),
13226 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13227 
13228 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13229 	desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13230 
13231 	if (probe->dofp_mod >= strtab->dofs_size) {
13232 		dtrace_dof_error(dof, "corrupt probe module");
13233 		return (NULL);
13234 	}
13235 
13236 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13237 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13238 
13239 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13240 	desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13241 
13242 	if (probe->dofp_func >= strtab->dofs_size) {
13243 		dtrace_dof_error(dof, "corrupt probe function");
13244 		return (NULL);
13245 	}
13246 
13247 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13248 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13249 
13250 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13251 	desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13252 
13253 	if (probe->dofp_name >= strtab->dofs_size) {
13254 		dtrace_dof_error(dof, "corrupt probe name");
13255 		return (NULL);
13256 	}
13257 
13258 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13259 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13260 
13261 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13262 	desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13263 
13264 	return (desc);
13265 }
13266 
13267 static dtrace_difo_t *
dtrace_dof_difo(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13268 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13269     cred_t *cr)
13270 {
13271 	dtrace_difo_t *dp;
13272 	size_t ttl = 0;
13273 	dof_difohdr_t *dofd;
13274 	uintptr_t daddr = (uintptr_t)dof;
13275 	size_t max_size = dtrace_difo_maxsize;
13276 	uint_t i;
13277 	int l, n;
13278 
13279 
13280 	static const struct {
13281 		int section;
13282 		int bufoffs;
13283 		int lenoffs;
13284 		int entsize;
13285 		int align;
13286 		const char *msg;
13287 	} difo[] = {
13288 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13289 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13290 		sizeof (dif_instr_t), "multiple DIF sections" },
13291 
13292 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13293 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13294 		sizeof (uint64_t), "multiple integer tables" },
13295 
13296 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13297 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13298 		sizeof (char), "multiple string tables" },
13299 
13300 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13301 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13302 		sizeof (uint_t), "multiple variable tables" },
13303 
13304 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13305 	};
13306 
13307 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13308 		dtrace_dof_error(dof, "invalid DIFO header section");
13309 		return (NULL);
13310 	}
13311 
13312 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13313 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13314 		return (NULL);
13315 	}
13316 
13317 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13318 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13319 		dtrace_dof_error(dof, "bad size in DIFO header");
13320 		return (NULL);
13321 	}
13322 
13323 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13324 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13325 
13326 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13327 	dp->dtdo_rtype = dofd->dofd_rtype;
13328 
13329 	for (l = 0; l < n; l++) {
13330 		dof_sec_t *subsec;
13331 		void **bufp;
13332 		uint32_t *lenp;
13333 
13334 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13335 		    dofd->dofd_links[l])) == NULL)
13336 			goto err; /* invalid section link */
13337 
13338 		if (ttl + subsec->dofs_size > max_size) {
13339 			dtrace_dof_error(dof, "exceeds maximum size");
13340 			goto err;
13341 		}
13342 
13343 		ttl += subsec->dofs_size;
13344 
13345 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13346 
13347 			if (subsec->dofs_type != (uint32_t)difo[i].section)
13348 				continue;
13349 
13350 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13351 				dtrace_dof_error(dof, "section not loaded");
13352 				goto err;
13353 			}
13354 
13355 			if (subsec->dofs_align != (uint32_t)difo[i].align) {
13356 				dtrace_dof_error(dof, "bad alignment");
13357 				goto err;
13358 			}
13359 
13360 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13361 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13362 
13363 			if (*bufp != NULL) {
13364 				dtrace_dof_error(dof, difo[i].msg);
13365 				goto err;
13366 			}
13367 
13368 			if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
13369 				dtrace_dof_error(dof, "entry size mismatch");
13370 				goto err;
13371 			}
13372 
13373 			if (subsec->dofs_entsize != 0 &&
13374 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13375 				dtrace_dof_error(dof, "corrupt entry size");
13376 				goto err;
13377 			}
13378 
13379 			*lenp = subsec->dofs_size;
13380 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13381 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13382 			    *bufp, subsec->dofs_size);
13383 
13384 			if (subsec->dofs_entsize != 0)
13385 				*lenp /= subsec->dofs_entsize;
13386 
13387 			break;
13388 		}
13389 
13390 		/*
13391 		 * If we encounter a loadable DIFO sub-section that is not
13392 		 * known to us, assume this is a broken program and fail.
13393 		 */
13394 		if (difo[i].section == DOF_SECT_NONE &&
13395 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13396 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13397 			goto err;
13398 		}
13399 	}
13400 
13401 	if (dp->dtdo_buf == NULL) {
13402 		/*
13403 		 * We can't have a DIF object without DIF text.
13404 		 */
13405 		dtrace_dof_error(dof, "missing DIF text");
13406 		goto err;
13407 	}
13408 
13409 	/*
13410 	 * Before we validate the DIF object, run through the variable table
13411 	 * looking for the strings -- if any of their size are under, we'll set
13412 	 * their size to be the system-wide default string size.  Note that
13413 	 * this should _not_ happen if the "strsize" option has been set --
13414 	 * in this case, the compiler should have set the size to reflect the
13415 	 * setting of the option.
13416 	 */
13417 	for (i = 0; i < dp->dtdo_varlen; i++) {
13418 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13419 		dtrace_diftype_t *t = &v->dtdv_type;
13420 
13421 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13422 			continue;
13423 
13424 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13425 			t->dtdt_size = dtrace_strsize_default;
13426 	}
13427 
13428 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13429 		goto err;
13430 
13431 	dtrace_difo_init(dp, vstate);
13432 	return (dp);
13433 
13434 err:
13435 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13436 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13437 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13438 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13439 
13440 	kmem_free(dp, sizeof (dtrace_difo_t));
13441 	return (NULL);
13442 }
13443 
13444 static dtrace_predicate_t *
dtrace_dof_predicate(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13445 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13446     cred_t *cr)
13447 {
13448 	dtrace_difo_t *dp;
13449 
13450 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13451 		return (NULL);
13452 
13453 	return (dtrace_predicate_create(dp));
13454 }
13455 
13456 static dtrace_actdesc_t *
dtrace_dof_actdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13457 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13458     cred_t *cr)
13459 {
13460 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13461 	dof_actdesc_t *desc;
13462 	dof_sec_t *difosec;
13463 	size_t offs;
13464 	uintptr_t daddr = (uintptr_t)dof;
13465 	uint64_t arg;
13466 	dtrace_actkind_t kind;
13467 
13468 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13469 		dtrace_dof_error(dof, "invalid action section");
13470 		return (NULL);
13471 	}
13472 
13473 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13474 		dtrace_dof_error(dof, "truncated action description");
13475 		return (NULL);
13476 	}
13477 
13478 	if (sec->dofs_align != sizeof (uint64_t)) {
13479 		dtrace_dof_error(dof, "bad alignment in action description");
13480 		return (NULL);
13481 	}
13482 
13483 	if (sec->dofs_size < sec->dofs_entsize) {
13484 		dtrace_dof_error(dof, "section entry size exceeds total size");
13485 		return (NULL);
13486 	}
13487 
13488 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13489 		dtrace_dof_error(dof, "bad entry size in action description");
13490 		return (NULL);
13491 	}
13492 
13493 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13494 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13495 		return (NULL);
13496 	}
13497 
13498 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13499 		desc = (dof_actdesc_t *)(daddr +
13500 		    (uintptr_t)sec->dofs_offset + offs);
13501 		kind = (dtrace_actkind_t)desc->dofa_kind;
13502 
13503 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13504 		    (kind != DTRACEACT_PRINTA || desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13505 		    (kind == DTRACEACT_DIFEXPR && desc->dofa_strtab != DOF_SECIDX_NONE))
13506 		{
13507 			dof_sec_t *strtab;
13508 			char *str, *fmt;
13509 			uint64_t i;
13510 
13511 			/*
13512 			 * The argument to these actions is an index into the
13513 			 * DOF string table.  For printf()-like actions, this
13514 			 * is the format string.  For print(), this is the
13515 			 * CTF type of the expression result.
13516 			 */
13517 			if ((strtab = dtrace_dof_sect(dof,
13518 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13519 				goto err;
13520 
13521 			str = (char *)((uintptr_t)dof +
13522 			    (uintptr_t)strtab->dofs_offset);
13523 
13524 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13525 				if (str[i] == '\0')
13526 					break;
13527 			}
13528 
13529 			if (i >= strtab->dofs_size) {
13530 				dtrace_dof_error(dof, "bogus format string");
13531 				goto err;
13532 			}
13533 
13534 			if (i == desc->dofa_arg) {
13535 				dtrace_dof_error(dof, "empty format string");
13536 				goto err;
13537 			}
13538 
13539 			i -= desc->dofa_arg;
13540 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13541 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13542 			arg = (uint64_t)(uintptr_t)fmt;
13543 		} else {
13544 			if (kind == DTRACEACT_PRINTA) {
13545 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13546 				arg = 0;
13547 			} else {
13548 				arg = desc->dofa_arg;
13549 			}
13550 		}
13551 
13552 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13553 		    desc->dofa_uarg, arg);
13554 
13555 		if (last != NULL) {
13556 			last->dtad_next = act;
13557 		} else {
13558 			first = act;
13559 		}
13560 
13561 		last = act;
13562 
13563 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13564 			continue;
13565 
13566 		if ((difosec = dtrace_dof_sect(dof,
13567 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13568 			goto err;
13569 
13570 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13571 
13572 		if (act->dtad_difo == NULL)
13573 			goto err;
13574 	}
13575 
13576 	ASSERT(first != NULL);
13577 	return (first);
13578 
13579 err:
13580 	for (act = first; act != NULL; act = next) {
13581 		next = act->dtad_next;
13582 		dtrace_actdesc_release(act, vstate);
13583 	}
13584 
13585 	return (NULL);
13586 }
13587 
13588 static dtrace_ecbdesc_t *
dtrace_dof_ecbdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13589 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13590     cred_t *cr)
13591 {
13592 	dtrace_ecbdesc_t *ep;
13593 	dof_ecbdesc_t *ecb;
13594 	dtrace_probedesc_t *desc;
13595 	dtrace_predicate_t *pred = NULL;
13596 
13597 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13598 		dtrace_dof_error(dof, "truncated ECB description");
13599 		return (NULL);
13600 	}
13601 
13602 	if (sec->dofs_align != sizeof (uint64_t)) {
13603 		dtrace_dof_error(dof, "bad alignment in ECB description");
13604 		return (NULL);
13605 	}
13606 
13607 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13608 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13609 
13610 	if (sec == NULL)
13611 		return (NULL);
13612 
13613 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13614 	ep->dted_uarg = ecb->dofe_uarg;
13615 	desc = &ep->dted_probe;
13616 
13617 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13618 		goto err;
13619 
13620 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13621 		if ((sec = dtrace_dof_sect(dof,
13622 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13623 			goto err;
13624 
13625 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13626 			goto err;
13627 
13628 		ep->dted_pred.dtpdd_predicate = pred;
13629 	}
13630 
13631 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13632 		if ((sec = dtrace_dof_sect(dof,
13633 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13634 			goto err;
13635 
13636 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13637 
13638 		if (ep->dted_action == NULL)
13639 			goto err;
13640 	}
13641 
13642 	return (ep);
13643 
13644 err:
13645 	if (pred != NULL)
13646 		dtrace_predicate_release(pred, vstate);
13647 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13648 	return (NULL);
13649 }
13650 
13651 /*
13652  * APPLE NOTE: dyld handles dof relocation.
13653  * Darwin does not need dtrace_dof_relocate()
13654  */
13655 
13656 /*
13657  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13658  * header:  it should be at the front of a memory region that is at least
13659  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13660  * size.  It need not be validated in any other way.
13661  */
13662 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)13663 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13664     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13665 {
13666 #pragma unused(ubase) /* __APPLE__ */
13667 	uint64_t len = dof->dofh_loadsz, seclen;
13668 	uintptr_t daddr = (uintptr_t)dof;
13669 	dtrace_ecbdesc_t *ep;
13670 	dtrace_enabling_t *enab;
13671 	uint_t i;
13672 
13673 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13674 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13675 
13676 	/*
13677 	 * Check the DOF header identification bytes.  In addition to checking
13678 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13679 	 * we can use them later without fear of regressing existing binaries.
13680 	 */
13681 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13682 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13683 		dtrace_dof_error(dof, "DOF magic string mismatch");
13684 		return (-1);
13685 	}
13686 
13687 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13688 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13689 		dtrace_dof_error(dof, "DOF has invalid data model");
13690 		return (-1);
13691 	}
13692 
13693 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13694 		dtrace_dof_error(dof, "DOF encoding mismatch");
13695 		return (-1);
13696 	}
13697 
13698 	/*
13699 	 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
13700 	 */
13701 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
13702 		dtrace_dof_error(dof, "DOF version mismatch");
13703 		return (-1);
13704 	}
13705 
13706 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13707 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13708 		return (-1);
13709 	}
13710 
13711 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13712 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13713 		return (-1);
13714 	}
13715 
13716 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13717 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13718 		return (-1);
13719 	}
13720 
13721 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13722 		if (dof->dofh_ident[i] != 0) {
13723 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13724 			return (-1);
13725 		}
13726 	}
13727 
13728 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13729 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13730 		return (-1);
13731 	}
13732 
13733 	if (dof->dofh_secsize < sizeof(dof_sec_t)) {
13734 		dtrace_dof_error(dof, "invalid section header size");
13735 		return (-1);
13736 	}
13737 
13738 	/*
13739 	 * Check that the section headers don't exceed the amount of DOF
13740 	 * data.  Note that we cast the section size and number of sections
13741 	 * to uint64_t's to prevent possible overflow in the multiplication.
13742 	 */
13743 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13744 
13745 	if (dof->dofh_secoff > len || seclen > len ||
13746 	    dof->dofh_secoff + seclen > len) {
13747 		dtrace_dof_error(dof, "truncated section headers");
13748 		return (-1);
13749 	}
13750 
13751 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13752 		dtrace_dof_error(dof, "misaligned section headers");
13753 		return (-1);
13754 	}
13755 
13756 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13757 		dtrace_dof_error(dof, "misaligned section size");
13758 		return (-1);
13759 	}
13760 
13761 	/*
13762 	 * Take an initial pass through the section headers to be sure that
13763 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13764 	 * set, do not permit sections relating to providers, probes, or args.
13765 	 */
13766 	for (i = 0; i < dof->dofh_secnum; i++) {
13767 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13768 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13769 
13770 		if (noprobes) {
13771 			switch (sec->dofs_type) {
13772 			case DOF_SECT_PROVIDER:
13773 			case DOF_SECT_PROBES:
13774 			case DOF_SECT_PRARGS:
13775 			case DOF_SECT_PROFFS:
13776 				dtrace_dof_error(dof, "illegal sections "
13777 				    "for enabling");
13778 				return (-1);
13779 			}
13780 		}
13781 
13782 		if (sec->dofs_align & (sec->dofs_align - 1)) {
13783 			dtrace_dof_error(dof, "bad section alignment");
13784 			return (-1);
13785 		}
13786 
13787 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13788 			dtrace_dof_error(dof, "misaligned section");
13789 			return (-1);
13790 		}
13791 
13792 		if (sec->dofs_flags & DOF_SECF_LOAD) {
13793 			len = dof->dofh_loadsz;
13794 		} else {
13795 			len = dof->dofh_filesz;
13796 		}
13797 
13798 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13799 		    sec->dofs_offset + sec->dofs_size > len) {
13800 			dtrace_dof_error(dof, "corrupt section header");
13801 			return (-1);
13802 		}
13803 
13804 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13805 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13806 			dtrace_dof_error(dof, "non-terminating string table");
13807 			return (-1);
13808 		}
13809 	}
13810 
13811 	/*
13812 	 * APPLE NOTE: We have no further relocation to perform.
13813 	 * All dof values are relative offsets.
13814 	 */
13815 
13816 	if ((enab = *enabp) == NULL)
13817 		enab = *enabp = dtrace_enabling_create(vstate);
13818 
13819 	for (i = 0; i < dof->dofh_secnum; i++) {
13820 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13821 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13822 
13823 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13824 			continue;
13825 
13826 		/*
13827 		 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
13828 		 * not all paths out of inlined dtrace_dof_ecbdesc
13829 		 * are checked for the NULL return value.
13830 		 * Check for NULL explicitly here.
13831 		*/
13832 		ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
13833 		if (ep == NULL) {
13834 			dtrace_enabling_destroy(enab);
13835 			*enabp = NULL;
13836 			return (-1);
13837 		}
13838 
13839 		dtrace_enabling_add(enab, ep);
13840 	}
13841 
13842 	return (0);
13843 }
13844 
13845 /*
13846  * Process DOF for any options.  This routine assumes that the DOF has been
13847  * at least processed by dtrace_dof_slurp().
13848  */
13849 static int
dtrace_dof_options(dof_hdr_t * dof,dtrace_state_t * state)13850 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13851 {
13852 	uint_t i;
13853 	int rval;
13854 	uint32_t entsize;
13855 	size_t offs;
13856 	dof_optdesc_t *desc;
13857 
13858 	for (i = 0; i < dof->dofh_secnum; i++) {
13859 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13860 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13861 
13862 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13863 			continue;
13864 
13865 		if (sec->dofs_align != sizeof (uint64_t)) {
13866 			dtrace_dof_error(dof, "bad alignment in "
13867 			    "option description");
13868 			return (EINVAL);
13869 		}
13870 
13871 		if ((entsize = sec->dofs_entsize) == 0) {
13872 			dtrace_dof_error(dof, "zeroed option entry size");
13873 			return (EINVAL);
13874 		}
13875 
13876 		if (entsize < sizeof (dof_optdesc_t)) {
13877 			dtrace_dof_error(dof, "bad option entry size");
13878 			return (EINVAL);
13879 		}
13880 
13881 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13882 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13883 			    (uintptr_t)sec->dofs_offset + offs);
13884 
13885 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13886 				dtrace_dof_error(dof, "non-zero option string");
13887 				return (EINVAL);
13888 			}
13889 
13890 			if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
13891 				dtrace_dof_error(dof, "unset option");
13892 				return (EINVAL);
13893 			}
13894 
13895 			if ((rval = dtrace_state_option(state,
13896 			    desc->dofo_option, desc->dofo_value)) != 0) {
13897 				dtrace_dof_error(dof, "rejected option");
13898 				return (rval);
13899 			}
13900 		}
13901 	}
13902 
13903 	return (0);
13904 }
13905 
13906 /*
13907  * DTrace Consumer State Functions
13908  */
13909 static int
dtrace_dstate_init(dtrace_dstate_t * dstate,size_t size)13910 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13911 {
13912 	size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
13913 	void *base;
13914 	uintptr_t limit;
13915 	dtrace_dynvar_t *dvar, *next, *start;
13916 
13917 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13918 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13919 
13920 	bzero(dstate, sizeof (dtrace_dstate_t));
13921 
13922 	if ((dstate->dtds_chunksize = chunksize) == 0)
13923 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13924 
13925 	VERIFY(dstate->dtds_chunksize < (LONG_MAX - sizeof (dtrace_dynhash_t)));
13926 
13927 	if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13928 		size = min_size;
13929 
13930 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
13931 		return (ENOMEM);
13932 
13933 	dstate->dtds_size = size;
13934 	dstate->dtds_base = base;
13935 	dstate->dtds_percpu = zalloc_percpu(dtrace_state_pcpu_zone, Z_WAITOK | Z_ZERO);
13936 
13937 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13938 
13939 	if (hashsize != 1 && (hashsize & 1))
13940 		hashsize--;
13941 
13942 	dstate->dtds_hashsize = hashsize;
13943 	dstate->dtds_hash = dstate->dtds_base;
13944 
13945 	/*
13946 	 * Set all of our hash buckets to point to the single sink, and (if
13947 	 * it hasn't already been set), set the sink's hash value to be the
13948 	 * sink sentinel value.  The sink is needed for dynamic variable
13949 	 * lookups to know that they have iterated over an entire, valid hash
13950 	 * chain.
13951 	 */
13952 	for (size_t i = 0; i < hashsize; i++)
13953 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13954 
13955 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13956 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13957 
13958 	/*
13959 	 * Determine number of active CPUs.  Divide free list evenly among
13960 	 * active CPUs.
13961 	 */
13962 	start = (dtrace_dynvar_t *)
13963 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13964 	limit = (uintptr_t)base + size;
13965 
13966 	VERIFY((uintptr_t)start < limit);
13967 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13968 
13969 	maxper = (limit - (uintptr_t)start) / (int)NCPU;
13970 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13971 
13972 	zpercpu_foreach_cpu(i) {
13973 		dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, i);
13974 
13975 		dcpu->dtdsc_free = dvar = start;
13976 
13977 		/*
13978 		 * If we don't even have enough chunks to make it once through
13979 		 * NCPUs, we're just going to allocate everything to the first
13980 		 * CPU.  And if we're on the last CPU, we're going to allocate
13981 		 * whatever is left over.  In either case, we set the limit to
13982 		 * be the limit of the dynamic variable space.
13983 		 */
13984 		if (maxper == 0 || i == NCPU - 1) {
13985 			limit = (uintptr_t)base + size;
13986 			start = NULL;
13987 		} else {
13988 			limit = (uintptr_t)start + maxper;
13989 			start = (dtrace_dynvar_t *)limit;
13990 		}
13991 
13992 		VERIFY(limit <= (uintptr_t)base + size);
13993 
13994 		for (;;) {
13995 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13996 			    dstate->dtds_chunksize);
13997 
13998 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13999 				break;
14000 
14001 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14002 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14003 			dvar->dtdv_next = next;
14004 			dvar = next;
14005 		}
14006 
14007 		if (maxper == 0)
14008 			break;
14009 	}
14010 
14011 	return (0);
14012 }
14013 
14014 static void
dtrace_dstate_fini(dtrace_dstate_t * dstate)14015 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14016 {
14017 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14018 
14019 	if (dstate->dtds_base == NULL)
14020 		return;
14021 
14022 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14023 	zfree_percpu(dtrace_state_pcpu_zone, dstate->dtds_percpu);
14024 }
14025 
14026 static void
dtrace_vstate_fini(dtrace_vstate_t * vstate)14027 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14028 {
14029 	/*
14030 	 * Logical XOR, where are you?
14031 	 */
14032 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14033 
14034 	if (vstate->dtvs_nglobals > 0) {
14035 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14036 		    sizeof (dtrace_statvar_t *));
14037 	}
14038 
14039 	if (vstate->dtvs_ntlocals > 0) {
14040 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14041 		    sizeof (dtrace_difv_t));
14042 	}
14043 
14044 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14045 
14046 	if (vstate->dtvs_nlocals > 0) {
14047 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14048 		    sizeof (dtrace_statvar_t *));
14049 	}
14050 }
14051 
14052 static void
dtrace_state_clean(dtrace_state_t * state)14053 dtrace_state_clean(dtrace_state_t *state)
14054 {
14055 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14056 		return;
14057 
14058 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14059 	dtrace_speculation_clean(state);
14060 }
14061 
14062 static void
dtrace_state_deadman(dtrace_state_t * state)14063 dtrace_state_deadman(dtrace_state_t *state)
14064 {
14065 	hrtime_t now;
14066 
14067 	dtrace_sync();
14068 
14069 	now = dtrace_gethrtime();
14070 
14071 	if (state != dtrace_anon.dta_state &&
14072 	    now - state->dts_laststatus >= dtrace_deadman_user)
14073 		return;
14074 
14075 	/*
14076 	 * We must be sure that dts_alive never appears to be less than the
14077 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14078 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14079 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14080 	 * the new value.  This assures that dts_alive never appears to be
14081 	 * less than its true value, regardless of the order in which the
14082 	 * stores to the underlying storage are issued.
14083 	 */
14084 	state->dts_alive = INT64_MAX;
14085 	dtrace_membar_producer();
14086 	state->dts_alive = now;
14087 }
14088 
14089 static int
dtrace_state_create(dev_t * devp,cred_t * cr,dtrace_state_t ** new_state)14090 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
14091 {
14092 	minor_t minor;
14093 	major_t major;
14094 	char c[30];
14095 	dtrace_state_t *state;
14096 	dtrace_optval_t *opt;
14097 	int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
14098 	unsigned int cpu_it;
14099 
14100 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14101 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14102 
14103 	/* Cause restart */
14104 	*new_state = NULL;
14105 
14106 	if (devp != NULL) {
14107 		minor = getminor(*devp);
14108 	}
14109 	else {
14110 		minor = DTRACE_NCLIENTS - 1;
14111 	}
14112 
14113 	state = dtrace_state_allocate(minor);
14114 	if (NULL == state) {
14115 		printf("dtrace_open: couldn't acquire minor number %d. This usually means that too many DTrace clients are in use at the moment", minor);
14116 		return (ERESTART);	/* can't reacquire */
14117 	}
14118 
14119 	state->dts_epid = DTRACE_EPIDNONE + 1;
14120 
14121 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
14122 	state->dts_aggid_arena = vmem_create(c, (void *)1, INT32_MAX, 1,
14123 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14124 
14125 	if (devp != NULL) {
14126 		major = getemajor(*devp);
14127 	} else {
14128 		major = ddi_driver_major(dtrace_devi);
14129 	}
14130 
14131 	state->dts_dev = makedev(major, minor);
14132 
14133 	if (devp != NULL)
14134 		*devp = state->dts_dev;
14135 
14136 	/*
14137 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14138 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14139 	 * other hand, it saves an additional memory reference in the probe
14140 	 * path.
14141 	 */
14142 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14143 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14144 	state->dts_buf_over_limit = 0;
14145 
14146 	/*
14147          * Allocate and initialise the per-process per-CPU random state.
14148 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14149          * assumed to be seeded at this point (if from Fortuna seed file).
14150 	 */
14151 	state->dts_rstate = kmem_zalloc(NCPU * sizeof(uint64_t*), KM_SLEEP);
14152 	state->dts_rstate[0] = kmem_zalloc(2 * sizeof(uint64_t), KM_SLEEP);
14153 	(void) read_random(state->dts_rstate[0], 2 * sizeof(uint64_t));
14154 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14155 		state->dts_rstate[cpu_it] = kmem_zalloc(2 * sizeof(uint64_t), KM_SLEEP);
14156 		/*
14157 		 * Each CPU is assigned a 2^64 period, non-overlapping
14158 		 * subsequence.
14159 		 */
14160 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14161 		    state->dts_rstate[cpu_it]);
14162 	}
14163 
14164 	state->dts_cleaner = CYCLIC_NONE;
14165 	state->dts_deadman = CYCLIC_NONE;
14166 	state->dts_vstate.dtvs_state = state;
14167 
14168 	for (i = 0; i < DTRACEOPT_MAX; i++)
14169 		state->dts_options[i] = DTRACEOPT_UNSET;
14170 
14171 	/*
14172 	 * Set the default options.
14173 	 */
14174 	opt = state->dts_options;
14175 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14176 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14177 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14178 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14179 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14180 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14181 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14182 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14183 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14184 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14185 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14186 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14187 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14188 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14189 	opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_default;
14190 
14191 	/*
14192 	 * Depending on the user credentials, we set flag bits which alter probe
14193 	 * visibility or the amount of destructiveness allowed.  In the case of
14194 	 * actual anonymous tracing, or the possession of all privileges, all of
14195 	 * the normal checks are bypassed.
14196 	 */
14197 #if defined(__APPLE__)
14198 	if (cr != NULL) {
14199 		kauth_cred_ref(cr);
14200 		state->dts_cred.dcr_cred = cr;
14201 	}
14202 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14203 		if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
14204 			/*
14205 			 * Allow only proc credentials when DTrace is
14206 			 * restricted by the current security policy
14207 			 */
14208 			state->dts_cred.dcr_visible = DTRACE_CRV_ALLPROC;
14209 			state->dts_cred.dcr_action = DTRACE_CRA_PROC | DTRACE_CRA_PROC_CONTROL | DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14210 		}
14211 		else {
14212 			state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14213 			state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14214 		}
14215 	}
14216 
14217 #else
14218 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14219 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14220 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14221 	}
14222 	else {
14223 		/*
14224 		 * Set up the credentials for this instantiation.  We take a
14225 		 * hold on the credential to prevent it from disappearing on
14226 		 * us; this in turn prevents the zone_t referenced by this
14227 		 * credential from disappearing.  This means that we can
14228 		 * examine the credential and the zone from probe context.
14229 		 */
14230 		crhold(cr);
14231 		state->dts_cred.dcr_cred = cr;
14232 
14233 		/*
14234 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14235 		 * unlocks the use of variables like pid, zonename, etc.
14236 		 */
14237 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14238 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14239 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14240 		}
14241 
14242 		/*
14243 		 * dtrace_user allows use of syscall and profile providers.
14244 		 * If the user also has proc_owner and/or proc_zone, we
14245 		 * extend the scope to include additional visibility and
14246 		 * destructive power.
14247 		 */
14248 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14249 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14250 				state->dts_cred.dcr_visible |=
14251 				    DTRACE_CRV_ALLPROC;
14252 
14253 				state->dts_cred.dcr_action |=
14254 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14255 			}
14256 
14257 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14258 				state->dts_cred.dcr_visible |=
14259 				    DTRACE_CRV_ALLZONE;
14260 
14261 				state->dts_cred.dcr_action |=
14262 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14263 			}
14264 
14265 			/*
14266 			 * If we have all privs in whatever zone this is,
14267 			 * we can do destructive things to processes which
14268 			 * have altered credentials.
14269 			 *
14270 			 * APPLE NOTE: Darwin doesn't do zones.
14271 			 * Behave as if zone always has destructive privs.
14272 			 */
14273 
14274 			state->dts_cred.dcr_action |=
14275 				DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14276 		}
14277 
14278 		/*
14279 		 * Holding the dtrace_kernel privilege also implies that
14280 		 * the user has the dtrace_user privilege from a visibility
14281 		 * perspective.  But without further privileges, some
14282 		 * destructive actions are not available.
14283 		 */
14284 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14285 			/*
14286 			 * Make all probes in all zones visible.  However,
14287 			 * this doesn't mean that all actions become available
14288 			 * to all zones.
14289 			 */
14290 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14291 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14292 
14293 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14294 			    DTRACE_CRA_PROC;
14295 			/*
14296 			 * Holding proc_owner means that destructive actions
14297 			 * for *this* zone are allowed.
14298 			 */
14299 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14300 				state->dts_cred.dcr_action |=
14301 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14302 
14303 			/*
14304 			 * Holding proc_zone means that destructive actions
14305 			 * for this user/group ID in all zones is allowed.
14306 			 */
14307 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14308 				state->dts_cred.dcr_action |=
14309 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14310 
14311 			/*
14312 			 * If we have all privs in whatever zone this is,
14313 			 * we can do destructive things to processes which
14314 			 * have altered credentials.
14315 			 *
14316 			 * APPLE NOTE: Darwin doesn't do zones.
14317 			 * Behave as if zone always has destructive privs.
14318 			 */
14319 			state->dts_cred.dcr_action |=
14320 				DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14321 		}
14322 
14323 		/*
14324 		 * Holding the dtrace_proc privilege gives control over fasttrap
14325 		 * and pid providers.  We need to grant wider destructive
14326 		 * privileges in the event that the user has proc_owner and/or
14327 		 * proc_zone.
14328 		 */
14329 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14330 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14331 				state->dts_cred.dcr_action |=
14332 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14333 
14334 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14335 				state->dts_cred.dcr_action |=
14336 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14337 		}
14338 	}
14339 #endif
14340 
14341 	*new_state = state;
14342 	return(0);  /* Success */
14343 }
14344 
14345 static int
dtrace_state_buffer(dtrace_state_t * state,dtrace_buffer_t * buf,int which)14346 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14347 {
14348 	dtrace_optval_t *opt = state->dts_options, size;
14349 	processorid_t cpu = 0;
14350 	size_t limit = buf->dtb_size;
14351 	int flags = 0, rval;
14352 
14353 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14354 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14355 	ASSERT(which < DTRACEOPT_MAX);
14356 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14357 	    (state == dtrace_anon.dta_state &&
14358 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14359 
14360 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14361 		return (0);
14362 
14363 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14364 		cpu = opt[DTRACEOPT_CPU];
14365 
14366 	if (which == DTRACEOPT_SPECSIZE)
14367 		flags |= DTRACEBUF_NOSWITCH;
14368 
14369 	if (which == DTRACEOPT_BUFSIZE) {
14370 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14371 			flags |= DTRACEBUF_RING;
14372 
14373 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14374 			flags |= DTRACEBUF_FILL;
14375 
14376 		if (state != dtrace_anon.dta_state ||
14377 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14378 			flags |= DTRACEBUF_INACTIVE;
14379 	}
14380 
14381 	for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
14382 		/*
14383 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14384 		 * aligned, drop it down by the difference.
14385 		 */
14386 		if (size & (sizeof (uint64_t) - 1))
14387 			size -= size & (sizeof (uint64_t) - 1);
14388 
14389 		if (size < state->dts_reserve) {
14390 			/*
14391 			 * Buffers always must be large enough to accommodate
14392 			 * their prereserved space.  We return E2BIG instead
14393 			 * of ENOMEM in this case to allow for user-level
14394 			 * software to differentiate the cases.
14395 			 */
14396 			return (E2BIG);
14397 		}
14398 		limit = opt[DTRACEOPT_BUFLIMIT] * size / 100;
14399 		rval = dtrace_buffer_alloc(buf, limit, size, flags, cpu);
14400 
14401 		if (rval != ENOMEM) {
14402 			opt[which] = size;
14403 			return (rval);
14404 		}
14405 
14406 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14407 			return (rval);
14408 	}
14409 
14410 	return (ENOMEM);
14411 }
14412 
14413 static int
dtrace_state_buffers(dtrace_state_t * state)14414 dtrace_state_buffers(dtrace_state_t *state)
14415 {
14416 	dtrace_speculation_t *spec = state->dts_speculations;
14417 	int rval, i;
14418 
14419 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14420 	    DTRACEOPT_BUFSIZE)) != 0)
14421 		return (rval);
14422 
14423 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14424 	    DTRACEOPT_AGGSIZE)) != 0)
14425 		return (rval);
14426 
14427 	for (i = 0; i < state->dts_nspeculations; i++) {
14428 		if ((rval = dtrace_state_buffer(state,
14429 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14430 			return (rval);
14431 	}
14432 
14433 	return (0);
14434 }
14435 
14436 static void
dtrace_state_prereserve(dtrace_state_t * state)14437 dtrace_state_prereserve(dtrace_state_t *state)
14438 {
14439 	dtrace_ecb_t *ecb;
14440 	dtrace_probe_t *probe;
14441 
14442 	state->dts_reserve = 0;
14443 
14444 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14445 		return;
14446 
14447 	/*
14448 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14449 	 * prereserved space to be the space required by the END probes.
14450 	 */
14451 	probe = dtrace_probes[dtrace_probeid_end - 1];
14452 	ASSERT(probe != NULL);
14453 
14454 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14455 		if (ecb->dte_state != state)
14456 			continue;
14457 
14458 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14459 	}
14460 }
14461 
14462 static int
dtrace_state_go(dtrace_state_t * state,processorid_t * cpu)14463 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14464 {
14465 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14466 	dtrace_speculation_t *spec;
14467 	dtrace_buffer_t *buf;
14468 	cyc_handler_t hdlr;
14469 	cyc_time_t when;
14470 	int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14471 	dtrace_icookie_t cookie;
14472 
14473 	lck_mtx_lock(&cpu_lock);
14474 	lck_mtx_lock(&dtrace_lock);
14475 
14476 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14477 		rval = EBUSY;
14478 		goto out;
14479 	}
14480 
14481 	/*
14482 	 * Before we can perform any checks, we must prime all of the
14483 	 * retained enablings that correspond to this state.
14484 	 */
14485 	dtrace_enabling_prime(state);
14486 
14487 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14488 		rval = EACCES;
14489 		goto out;
14490 	}
14491 
14492 	dtrace_state_prereserve(state);
14493 
14494 	/*
14495 	 * Now we want to do is try to allocate our speculations.
14496 	 * We do not automatically resize the number of speculations; if
14497 	 * this fails, we will fail the operation.
14498 	 */
14499 	nspec = opt[DTRACEOPT_NSPEC];
14500 	ASSERT(nspec != DTRACEOPT_UNSET);
14501 
14502 	if (nspec > INT_MAX) {
14503 		rval = ENOMEM;
14504 		goto out;
14505 	}
14506 
14507 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
14508 
14509 	if (spec == NULL) {
14510 		rval = ENOMEM;
14511 		goto out;
14512 	}
14513 
14514 	state->dts_speculations = spec;
14515 	state->dts_nspeculations = (int)nspec;
14516 
14517 	for (i = 0; i < nspec; i++) {
14518 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
14519 			rval = ENOMEM;
14520 			goto err;
14521 		}
14522 
14523 		spec[i].dtsp_buffer = buf;
14524 	}
14525 
14526 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14527 		if (dtrace_anon.dta_state == NULL) {
14528 			rval = ENOENT;
14529 			goto out;
14530 		}
14531 
14532 		if (state->dts_necbs != 0) {
14533 			rval = EALREADY;
14534 			goto out;
14535 		}
14536 
14537 		state->dts_anon = dtrace_anon_grab();
14538 		ASSERT(state->dts_anon != NULL);
14539 		state = state->dts_anon;
14540 
14541 		/*
14542 		 * We want "grabanon" to be set in the grabbed state, so we'll
14543 		 * copy that option value from the grabbing state into the
14544 		 * grabbed state.
14545 		 */
14546 		state->dts_options[DTRACEOPT_GRABANON] =
14547 		    opt[DTRACEOPT_GRABANON];
14548 
14549 		*cpu = dtrace_anon.dta_beganon;
14550 
14551 		/*
14552 		 * If the anonymous state is active (as it almost certainly
14553 		 * is if the anonymous enabling ultimately matched anything),
14554 		 * we don't allow any further option processing -- but we
14555 		 * don't return failure.
14556 		 */
14557 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14558 			goto out;
14559 	}
14560 
14561 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14562 	    opt[DTRACEOPT_AGGSIZE] != 0) {
14563 		if (state->dts_aggregations == NULL) {
14564 			/*
14565 			 * We're not going to create an aggregation buffer
14566 			 * because we don't have any ECBs that contain
14567 			 * aggregations -- set this option to 0.
14568 			 */
14569 			opt[DTRACEOPT_AGGSIZE] = 0;
14570 		} else {
14571 			/*
14572 			 * If we have an aggregation buffer, we must also have
14573 			 * a buffer to use as scratch.
14574 			 */
14575 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14576 			  (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14577 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14578 			}
14579 		}
14580 	}
14581 
14582 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14583 	    opt[DTRACEOPT_SPECSIZE] != 0) {
14584 		if (!state->dts_speculates) {
14585 			/*
14586 			 * We're not going to create speculation buffers
14587 			 * because we don't have any ECBs that actually
14588 			 * speculate -- set the speculation size to 0.
14589 			 */
14590 			opt[DTRACEOPT_SPECSIZE] = 0;
14591 		}
14592 	}
14593 
14594 	/*
14595 	 * The bare minimum size for any buffer that we're actually going to
14596 	 * do anything to is sizeof (uint64_t).
14597 	 */
14598 	sz = sizeof (uint64_t);
14599 
14600 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14601 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14602 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14603 		/*
14604 		 * A buffer size has been explicitly set to 0 (or to a size
14605 		 * that will be adjusted to 0) and we need the space -- we
14606 		 * need to return failure.  We return ENOSPC to differentiate
14607 		 * it from failing to allocate a buffer due to failure to meet
14608 		 * the reserve (for which we return E2BIG).
14609 		 */
14610 		rval = ENOSPC;
14611 		goto out;
14612 	}
14613 
14614 	if ((rval = dtrace_state_buffers(state)) != 0)
14615 		goto err;
14616 
14617 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14618 		sz = dtrace_dstate_defsize;
14619 
14620 	do {
14621 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14622 
14623 		if (rval == 0)
14624 			break;
14625 
14626 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14627 			goto err;
14628 	} while (sz >>= 1);
14629 
14630 	opt[DTRACEOPT_DYNVARSIZE] = sz;
14631 
14632 	if (rval != 0)
14633 		goto err;
14634 
14635 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14636 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14637 
14638 	if (opt[DTRACEOPT_CLEANRATE] == 0)
14639 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14640 
14641 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14642 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14643 
14644 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14645 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14646 
14647 	if (opt[DTRACEOPT_STRSIZE] > dtrace_strsize_max)
14648 		opt[DTRACEOPT_STRSIZE] = dtrace_strsize_max;
14649 
14650 	if (opt[DTRACEOPT_STRSIZE] < dtrace_strsize_min)
14651 		opt[DTRACEOPT_STRSIZE] = dtrace_strsize_min;
14652 
14653 	if (opt[DTRACEOPT_BUFLIMIT] > dtrace_buflimit_max)
14654 		opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_max;
14655 
14656 	if (opt[DTRACEOPT_BUFLIMIT] < dtrace_buflimit_min)
14657 		opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_min;
14658 
14659 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14660 	hdlr.cyh_arg = state;
14661 	hdlr.cyh_level = CY_LOW_LEVEL;
14662 
14663 	when.cyt_when = 0;
14664 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14665 
14666 	state->dts_cleaner = cyclic_add(&hdlr, &when);
14667 
14668 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14669 	hdlr.cyh_arg = state;
14670 	hdlr.cyh_level = CY_LOW_LEVEL;
14671 
14672 	when.cyt_when = 0;
14673 	when.cyt_interval = dtrace_deadman_interval;
14674 
14675 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14676 	state->dts_deadman = cyclic_add(&hdlr, &when);
14677 
14678 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14679 
14680 	/*
14681 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14682 	 * interrupts here both to record the CPU on which we fired the BEGIN
14683 	 * probe (the data from this CPU will be processed first at user
14684 	 * level) and to manually activate the buffer for this CPU.
14685 	 */
14686 	cookie = dtrace_interrupt_disable();
14687 	*cpu = CPU->cpu_id;
14688 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14689 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14690 
14691 	dtrace_probe(dtrace_probeid_begin,
14692 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14693 	dtrace_interrupt_enable(cookie);
14694 	/*
14695 	 * We may have had an exit action from a BEGIN probe; only change our
14696 	 * state to ACTIVE if we're still in WARMUP.
14697 	 */
14698 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14699 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14700 
14701 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14702 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14703 
14704 	/*
14705 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14706 	 * want each CPU to transition its principal buffer out of the
14707 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14708 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14709 	 * atomically transition from processing none of a state's ECBs to
14710 	 * processing all of them.
14711 	 */
14712 	dtrace_xcall(DTRACE_CPUALL,
14713 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14714 	goto out;
14715 
14716 err:
14717 	dtrace_buffer_free(state->dts_buffer);
14718 	dtrace_buffer_free(state->dts_aggbuffer);
14719 
14720 	if ((nspec = state->dts_nspeculations) == 0) {
14721 		ASSERT(state->dts_speculations == NULL);
14722 		goto out;
14723 	}
14724 
14725 	spec = state->dts_speculations;
14726 	ASSERT(spec != NULL);
14727 
14728 	for (i = 0; i < state->dts_nspeculations; i++) {
14729 		if ((buf = spec[i].dtsp_buffer) == NULL)
14730 			break;
14731 
14732 		dtrace_buffer_free(buf);
14733 		kmem_free(buf, bufsize);
14734 	}
14735 
14736 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14737 	state->dts_nspeculations = 0;
14738 	state->dts_speculations = NULL;
14739 
14740 out:
14741 	lck_mtx_unlock(&dtrace_lock);
14742 	lck_mtx_unlock(&cpu_lock);
14743 
14744 	return (rval);
14745 }
14746 
14747 static int
dtrace_state_stop(dtrace_state_t * state,processorid_t * cpu)14748 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14749 {
14750 	dtrace_icookie_t cookie;
14751 
14752 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14753 
14754 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14755 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14756 		return (EINVAL);
14757 
14758 	/*
14759 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14760 	 * to be sure that every CPU has seen it.  See below for the details
14761 	 * on why this is done.
14762 	 */
14763 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14764 	dtrace_sync();
14765 
14766 	/*
14767 	 * By this point, it is impossible for any CPU to be still processing
14768 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14769 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14770 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14771 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14772 	 * iff we're in the END probe.
14773 	 */
14774 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14775 	dtrace_sync();
14776 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14777 
14778 	/*
14779 	 * Finally, we can release the reserve and call the END probe.  We
14780 	 * disable interrupts across calling the END probe to allow us to
14781 	 * return the CPU on which we actually called the END probe.  This
14782 	 * allows user-land to be sure that this CPU's principal buffer is
14783 	 * processed last.
14784 	 */
14785 	state->dts_reserve = 0;
14786 
14787 	cookie = dtrace_interrupt_disable();
14788 	*cpu = CPU->cpu_id;
14789 	dtrace_probe(dtrace_probeid_end,
14790 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14791 	dtrace_interrupt_enable(cookie);
14792 
14793 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14794 	dtrace_sync();
14795 
14796 	return (0);
14797 }
14798 
14799 static int
dtrace_state_option(dtrace_state_t * state,dtrace_optid_t option,dtrace_optval_t val)14800 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14801     dtrace_optval_t val)
14802 {
14803 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14804 
14805 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14806 		return (EBUSY);
14807 
14808 	if (option >= DTRACEOPT_MAX)
14809 		return (EINVAL);
14810 
14811 	if (option != DTRACEOPT_CPU && val < 0)
14812 		return (EINVAL);
14813 
14814 	switch (option) {
14815 	case DTRACEOPT_DESTRUCTIVE:
14816 		if (dtrace_destructive_disallow)
14817 			return (EACCES);
14818 
14819 		state->dts_cred.dcr_destructive = 1;
14820 		break;
14821 
14822 	case DTRACEOPT_BUFSIZE:
14823 	case DTRACEOPT_DYNVARSIZE:
14824 	case DTRACEOPT_AGGSIZE:
14825 	case DTRACEOPT_SPECSIZE:
14826 	case DTRACEOPT_STRSIZE:
14827 		if (val < 0)
14828 			return (EINVAL);
14829 
14830 		if (val >= LONG_MAX) {
14831 			/*
14832 			 * If this is an otherwise negative value, set it to
14833 			 * the highest multiple of 128m less than LONG_MAX.
14834 			 * Technically, we're adjusting the size without
14835 			 * regard to the buffer resizing policy, but in fact,
14836 			 * this has no effect -- if we set the buffer size to
14837 			 * ~LONG_MAX and the buffer policy is ultimately set to
14838 			 * be "manual", the buffer allocation is guaranteed to
14839 			 * fail, if only because the allocation requires two
14840 			 * buffers.  (We set the the size to the highest
14841 			 * multiple of 128m because it ensures that the size
14842 			 * will remain a multiple of a megabyte when
14843 			 * repeatedly halved -- all the way down to 15m.)
14844 			 */
14845 			val = LONG_MAX - (1 << 27) + 1;
14846 		}
14847 	}
14848 
14849 	state->dts_options[option] = val;
14850 
14851 	return (0);
14852 }
14853 
14854 static void
dtrace_state_destroy(dtrace_state_t * state)14855 dtrace_state_destroy(dtrace_state_t *state)
14856 {
14857 	dtrace_ecb_t *ecb;
14858 	dtrace_vstate_t *vstate = &state->dts_vstate;
14859 	minor_t minor = getminor(state->dts_dev);
14860 	int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14861 	dtrace_speculation_t *spec = state->dts_speculations;
14862 	int nspec = state->dts_nspeculations;
14863 	uint32_t match;
14864 
14865 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14866 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14867 
14868 	/*
14869 	 * First, retract any retained enablings for this state.
14870 	 */
14871 	dtrace_enabling_retract(state);
14872 	ASSERT(state->dts_nretained == 0);
14873 
14874 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14875 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14876 		/*
14877 		 * We have managed to come into dtrace_state_destroy() on a
14878 		 * hot enabling -- almost certainly because of a disorderly
14879 		 * shutdown of a consumer.  (That is, a consumer that is
14880 		 * exiting without having called dtrace_stop().) In this case,
14881 		 * we're going to set our activity to be KILLED, and then
14882 		 * issue a sync to be sure that everyone is out of probe
14883 		 * context before we start blowing away ECBs.
14884 		 */
14885 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14886 		dtrace_sync();
14887 	}
14888 
14889 	/*
14890 	 * Release the credential hold we took in dtrace_state_create().
14891 	 */
14892 	if (state->dts_cred.dcr_cred != NULL)
14893 		kauth_cred_unref(&state->dts_cred.dcr_cred);
14894 
14895 	/*
14896 	 * Now we can safely disable and destroy any enabled probes.  Because
14897 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14898 	 * (especially if they're all enabled), we take two passes through the
14899 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14900 	 * in the second we disable whatever is left over.
14901 	 */
14902 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14903 		for (i = 0; i < state->dts_necbs; i++) {
14904 			if ((ecb = state->dts_ecbs[i]) == NULL)
14905 				continue;
14906 
14907 			if (match && ecb->dte_probe != NULL) {
14908 				dtrace_probe_t *probe = ecb->dte_probe;
14909 				dtrace_provider_t *prov = probe->dtpr_provider;
14910 
14911 				if (!(prov->dtpv_priv.dtpp_flags & match))
14912 					continue;
14913 			}
14914 
14915 			dtrace_ecb_disable(ecb);
14916 			dtrace_ecb_destroy(ecb);
14917 		}
14918 
14919 		if (!match)
14920 			break;
14921 	}
14922 
14923 	/*
14924 	 * Before we free the buffers, perform one more sync to assure that
14925 	 * every CPU is out of probe context.
14926 	 */
14927 	dtrace_sync();
14928 
14929 	dtrace_buffer_free(state->dts_buffer);
14930 	dtrace_buffer_free(state->dts_aggbuffer);
14931 
14932 	for (i = 0; i < (int)NCPU; i++) {
14933 		kmem_free(state->dts_rstate[i], 2 * sizeof(uint64_t));
14934 	}
14935 	kmem_free(state->dts_rstate, NCPU * sizeof(uint64_t*));
14936 
14937 	for (i = 0; i < nspec; i++)
14938 		dtrace_buffer_free(spec[i].dtsp_buffer);
14939 
14940 	if (state->dts_cleaner != CYCLIC_NONE)
14941 		cyclic_remove(state->dts_cleaner);
14942 
14943 	if (state->dts_deadman != CYCLIC_NONE)
14944 		cyclic_remove(state->dts_deadman);
14945 
14946 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14947 	dtrace_vstate_fini(vstate);
14948 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14949 
14950 	if (state->dts_aggregations != NULL) {
14951 #if DEBUG
14952 		for (i = 0; i < state->dts_naggregations; i++)
14953 			ASSERT(state->dts_aggregations[i] == NULL);
14954 #endif
14955 		ASSERT(state->dts_naggregations > 0);
14956 		kmem_free(state->dts_aggregations,
14957 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14958 	}
14959 
14960 	kmem_free(state->dts_buffer, bufsize);
14961 	kmem_free(state->dts_aggbuffer, bufsize);
14962 
14963 	for (i = 0; i < nspec; i++)
14964 		kmem_free(spec[i].dtsp_buffer, bufsize);
14965 
14966 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14967 
14968 	dtrace_format_destroy(state);
14969 
14970 	vmem_destroy(state->dts_aggid_arena);
14971 	dtrace_state_free(minor);
14972 }
14973 
14974 /*
14975  * DTrace Anonymous Enabling Functions
14976  */
14977 
14978 int
dtrace_keep_kernel_symbols(void)14979 dtrace_keep_kernel_symbols(void)
14980 {
14981 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
14982 		return 0;
14983 	}
14984 
14985 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL)
14986 		return 1;
14987 
14988 	return 0;
14989 }
14990 
14991 static dtrace_state_t *
dtrace_anon_grab(void)14992 dtrace_anon_grab(void)
14993 {
14994 	dtrace_state_t *state;
14995 
14996 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14997 
14998 	if ((state = dtrace_anon.dta_state) == NULL) {
14999 		ASSERT(dtrace_anon.dta_enabling == NULL);
15000 		return (NULL);
15001 	}
15002 
15003 	ASSERT(dtrace_anon.dta_enabling != NULL);
15004 	ASSERT(dtrace_retained != NULL);
15005 
15006 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15007 	dtrace_anon.dta_enabling = NULL;
15008 	dtrace_anon.dta_state = NULL;
15009 
15010 	return (state);
15011 }
15012 
15013 static void
dtrace_anon_property(void)15014 dtrace_anon_property(void)
15015 {
15016 	int i, rv;
15017 	dtrace_state_t *state;
15018 	dof_hdr_t *dof;
15019 	char c[32];		/* enough for "dof-data-" + digits */
15020 
15021 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15022 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15023 
15024 	for (i = 0; ; i++) {
15025 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15026 
15027 		dtrace_err_verbose = 1;
15028 
15029 		if ((dof = dtrace_dof_property(c)) == NULL) {
15030 			dtrace_err_verbose = 0;
15031 			break;
15032 		}
15033 
15034 #ifdef illumos
15035 		/*
15036 		 * We want to create anonymous state, so we need to transition
15037 		 * the kernel debugger to indicate that DTrace is active.  If
15038 		 * this fails (e.g. because the debugger has modified text in
15039 		 * some way), we won't continue with the processing.
15040 		 */
15041 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15042 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15043 			    "enabling ignored.");
15044 			dtrace_dof_destroy(dof);
15045 			break;
15046 		}
15047 #endif
15048 
15049 		/*
15050 		 * If we haven't allocated an anonymous state, we'll do so now.
15051 		 */
15052 		if ((state = dtrace_anon.dta_state) == NULL) {
15053 			rv = dtrace_state_create(NULL, NULL, &state);
15054 			dtrace_anon.dta_state = state;
15055 			if (rv != 0 || state == NULL) {
15056 				/*
15057 				 * This basically shouldn't happen:  the only
15058 				 * failure mode from dtrace_state_create() is a
15059 				 * failure of ddi_soft_state_zalloc() that
15060 				 * itself should never happen.  Still, the
15061 				 * interface allows for a failure mode, and
15062 				 * we want to fail as gracefully as possible:
15063 				 * we'll emit an error message and cease
15064 				 * processing anonymous state in this case.
15065 				 */
15066 				cmn_err(CE_WARN, "failed to create "
15067 				    "anonymous state");
15068 				dtrace_dof_destroy(dof);
15069 				break;
15070 			}
15071 		}
15072 
15073 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15074 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
15075 
15076 		if (rv == 0)
15077 			rv = dtrace_dof_options(dof, state);
15078 
15079 		dtrace_err_verbose = 0;
15080 		dtrace_dof_destroy(dof);
15081 
15082 		if (rv != 0) {
15083 			/*
15084 			 * This is malformed DOF; chuck any anonymous state
15085 			 * that we created.
15086 			 */
15087 			ASSERT(dtrace_anon.dta_enabling == NULL);
15088 			dtrace_state_destroy(state);
15089 			dtrace_anon.dta_state = NULL;
15090 			break;
15091 		}
15092 
15093 		ASSERT(dtrace_anon.dta_enabling != NULL);
15094 	}
15095 
15096 	if (dtrace_anon.dta_enabling != NULL) {
15097 		int rval;
15098 
15099 		/*
15100 		 * dtrace_enabling_retain() can only fail because we are
15101 		 * trying to retain more enablings than are allowed -- but
15102 		 * we only have one anonymous enabling, and we are guaranteed
15103 		 * to be allowed at least one retained enabling; we assert
15104 		 * that dtrace_enabling_retain() returns success.
15105 		 */
15106 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15107 		ASSERT(rval == 0);
15108 
15109 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15110 	}
15111 }
15112 
15113 /*
15114  * DTrace Helper Functions
15115  */
15116 static void
dtrace_helper_trace(dtrace_helper_action_t * helper,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,int where)15117 dtrace_helper_trace(dtrace_helper_action_t *helper,
15118     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15119 {
15120 	uint32_t size, next, nnext;
15121 	int i;
15122 	dtrace_helptrace_t *ent;
15123 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
15124 
15125 	if (!dtrace_helptrace_enabled)
15126 		return;
15127 
15128 	ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15129 
15130 	/*
15131 	 * What would a tracing framework be without its own tracing
15132 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15133 	 */
15134 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15135 	    sizeof (uint64_t) - sizeof (uint64_t);
15136 
15137 	/*
15138 	 * Iterate until we can allocate a slot in the trace buffer.
15139 	 */
15140 	do {
15141 		next = dtrace_helptrace_next;
15142 
15143 		if (next + size < dtrace_helptrace_bufsize) {
15144 			nnext = next + size;
15145 		} else {
15146 			nnext = size;
15147 		}
15148 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15149 
15150 	/*
15151 	 * We have our slot; fill it in.
15152 	 */
15153 	if (nnext == size)
15154 		next = 0;
15155 
15156 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
15157 	ent->dtht_helper = helper;
15158 	ent->dtht_where = where;
15159 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15160 
15161 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15162 	    mstate->dtms_fltoffs : -1;
15163 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15164 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
15165 
15166 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15167 		dtrace_statvar_t *svar;
15168 
15169 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15170 			continue;
15171 
15172 		ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
15173 		ent->dtht_locals[i] =
15174 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
15175 	}
15176 }
15177 
15178 __attribute__((noinline))
15179 static uint64_t
dtrace_helper(int which,dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t arg0,uint64_t arg1)15180 dtrace_helper(int which, dtrace_mstate_t *mstate,
15181     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15182 {
15183 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
15184 	uint64_t sarg0 = mstate->dtms_arg[0];
15185 	uint64_t sarg1 = mstate->dtms_arg[1];
15186 	uint64_t rval = 0;
15187 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15188 	dtrace_helper_action_t *helper;
15189 	dtrace_vstate_t *vstate;
15190 	dtrace_difo_t *pred;
15191 	int i, trace = dtrace_helptrace_enabled;
15192 
15193 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15194 
15195 	if (helpers == NULL)
15196 		return (0);
15197 
15198 	if ((helper = helpers->dthps_actions[which]) == NULL)
15199 		return (0);
15200 
15201 	vstate = &helpers->dthps_vstate;
15202 	mstate->dtms_arg[0] = arg0;
15203 	mstate->dtms_arg[1] = arg1;
15204 
15205 	/*
15206 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15207 	 * we'll call the corresponding actions.  Note that the below calls
15208 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15209 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15210 	 * the stored DIF offset with its own (which is the desired behavior).
15211 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15212 	 * from machine state; this is okay, too.
15213 	 */
15214 	for (; helper != NULL; helper = helper->dtha_next) {
15215 		if ((pred = helper->dtha_predicate) != NULL) {
15216 			if (trace)
15217 				dtrace_helper_trace(helper, mstate, vstate, 0);
15218 
15219 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15220 				goto next;
15221 
15222 			if (*flags & CPU_DTRACE_FAULT)
15223 				goto err;
15224 		}
15225 
15226 		for (i = 0; i < helper->dtha_nactions; i++) {
15227 			if (trace)
15228 				dtrace_helper_trace(helper,
15229 				    mstate, vstate, i + 1);
15230 
15231 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15232 			    mstate, vstate, state);
15233 
15234 			if (*flags & CPU_DTRACE_FAULT)
15235 				goto err;
15236 		}
15237 
15238 next:
15239 		if (trace)
15240 			dtrace_helper_trace(helper, mstate, vstate,
15241 			    DTRACE_HELPTRACE_NEXT);
15242 	}
15243 
15244 	if (trace)
15245 		dtrace_helper_trace(helper, mstate, vstate,
15246 		    DTRACE_HELPTRACE_DONE);
15247 
15248 	/*
15249 	 * Restore the arg0 that we saved upon entry.
15250 	 */
15251 	mstate->dtms_arg[0] = sarg0;
15252 	mstate->dtms_arg[1] = sarg1;
15253 
15254 	return (rval);
15255 
15256 err:
15257 	if (trace)
15258 		dtrace_helper_trace(helper, mstate, vstate,
15259 		    DTRACE_HELPTRACE_ERR);
15260 
15261 	/*
15262 	 * Restore the arg0 that we saved upon entry.
15263 	 */
15264 	mstate->dtms_arg[0] = sarg0;
15265 	mstate->dtms_arg[1] = sarg1;
15266 
15267 	return (0);
15268 }
15269 
15270 static void
dtrace_helper_action_destroy(dtrace_helper_action_t * helper,dtrace_vstate_t * vstate)15271 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15272     dtrace_vstate_t *vstate)
15273 {
15274 	int i;
15275 
15276 	if (helper->dtha_predicate != NULL)
15277 		dtrace_difo_release(helper->dtha_predicate, vstate);
15278 
15279 	for (i = 0; i < helper->dtha_nactions; i++) {
15280 		ASSERT(helper->dtha_actions[i] != NULL);
15281 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15282 	}
15283 
15284 	kmem_free(helper->dtha_actions,
15285 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15286 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15287 }
15288 
15289 static int
dtrace_helper_destroygen(proc_t * p,int gen)15290 dtrace_helper_destroygen(proc_t* p, int gen)
15291 {
15292 	dtrace_helpers_t *help = p->p_dtrace_helpers;
15293 	dtrace_vstate_t *vstate;
15294 	uint_t i;
15295 
15296 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15297 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15298 
15299 	if (help == NULL || gen > help->dthps_generation)
15300 		return (EINVAL);
15301 
15302 	vstate = &help->dthps_vstate;
15303 
15304 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15305 		dtrace_helper_action_t *last = NULL, *h, *next;
15306 
15307 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15308 			next = h->dtha_next;
15309 
15310 			if (h->dtha_generation == gen) {
15311 				if (last != NULL) {
15312 					last->dtha_next = next;
15313 				} else {
15314 					help->dthps_actions[i] = next;
15315 				}
15316 
15317 				dtrace_helper_action_destroy(h, vstate);
15318 			} else {
15319 				last = h;
15320 			}
15321 		}
15322 	}
15323 
15324 	/*
15325 	 * Interate until we've cleared out all helper providers with the
15326 	 * given generation number.
15327 	 */
15328 	for (;;) {
15329 		dtrace_helper_provider_t *prov = NULL;
15330 
15331 		/*
15332 		 * Look for a helper provider with the right generation. We
15333 		 * have to start back at the beginning of the list each time
15334 		 * because we drop dtrace_lock. It's unlikely that we'll make
15335 		 * more than two passes.
15336 		 */
15337 		for (i = 0; i < help->dthps_nprovs; i++) {
15338 			prov = help->dthps_provs[i];
15339 
15340 			if (prov->dthp_generation == gen)
15341 				break;
15342 		}
15343 
15344 		/*
15345 		 * If there were no matches, we're done.
15346 		 */
15347 		if (i == help->dthps_nprovs)
15348 			break;
15349 
15350 		/*
15351 		 * Move the last helper provider into this slot.
15352 		 */
15353 		help->dthps_nprovs--;
15354 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15355 		help->dthps_provs[help->dthps_nprovs] = NULL;
15356 
15357 		lck_mtx_unlock(&dtrace_lock);
15358 
15359 		/*
15360 		 * If we have a meta provider, remove this helper provider.
15361 		 */
15362 		if (dtrace_meta_pid != NULL) {
15363 			ASSERT(dtrace_deferred_pid == NULL);
15364 			dtrace_helper_provider_remove(&prov->dthp_prov,
15365 			    p);
15366 		}
15367 
15368 		dtrace_helper_provider_destroy(prov);
15369 
15370 		lck_mtx_lock(&dtrace_lock);
15371 	}
15372 
15373 	return (0);
15374 }
15375 
15376 static int
dtrace_helper_validate(dtrace_helper_action_t * helper)15377 dtrace_helper_validate(dtrace_helper_action_t *helper)
15378 {
15379 	int err = 0, i;
15380 	dtrace_difo_t *dp;
15381 
15382 	if ((dp = helper->dtha_predicate) != NULL)
15383 		err += dtrace_difo_validate_helper(dp);
15384 
15385 	for (i = 0; i < helper->dtha_nactions; i++)
15386 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15387 
15388 	return (err == 0);
15389 }
15390 
15391 static int
dtrace_helper_action_add(proc_t * p,int which,dtrace_ecbdesc_t * ep)15392 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
15393 {
15394 	dtrace_helpers_t *help;
15395 	dtrace_helper_action_t *helper, *last;
15396 	dtrace_actdesc_t *act;
15397 	dtrace_vstate_t *vstate;
15398 	dtrace_predicate_t *pred;
15399 	int count = 0, nactions = 0, i;
15400 
15401 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15402 		return (EINVAL);
15403 
15404 	help = p->p_dtrace_helpers;
15405 	last = help->dthps_actions[which];
15406 	vstate = &help->dthps_vstate;
15407 
15408 	for (count = 0; last != NULL; last = last->dtha_next) {
15409 		count++;
15410 		if (last->dtha_next == NULL)
15411 			break;
15412 	}
15413 
15414 	/*
15415 	 * If we already have dtrace_helper_actions_max helper actions for this
15416 	 * helper action type, we'll refuse to add a new one.
15417 	 */
15418 	if (count >= dtrace_helper_actions_max)
15419 		return (ENOSPC);
15420 
15421 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15422 	helper->dtha_generation = help->dthps_generation;
15423 
15424 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15425 		ASSERT(pred->dtp_difo != NULL);
15426 		dtrace_difo_hold(pred->dtp_difo);
15427 		helper->dtha_predicate = pred->dtp_difo;
15428 	}
15429 
15430 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15431 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15432 			goto err;
15433 
15434 		if (act->dtad_difo == NULL)
15435 			goto err;
15436 
15437 		nactions++;
15438 	}
15439 
15440 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15441 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15442 
15443 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15444 		dtrace_difo_hold(act->dtad_difo);
15445 		helper->dtha_actions[i++] = act->dtad_difo;
15446 	}
15447 
15448 	if (!dtrace_helper_validate(helper))
15449 		goto err;
15450 
15451 	if (last == NULL) {
15452 		help->dthps_actions[which] = helper;
15453 	} else {
15454 		last->dtha_next = helper;
15455 	}
15456 
15457 	if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15458 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15459 		dtrace_helptrace_next = 0;
15460 	}
15461 
15462 	return (0);
15463 err:
15464 	dtrace_helper_action_destroy(helper, vstate);
15465 	return (EINVAL);
15466 }
15467 
15468 static void
dtrace_helper_provider_register(proc_t * p,dtrace_helpers_t * help,dof_helper_t * dofhp)15469 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15470     dof_helper_t *dofhp)
15471 {
15472 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15473 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15474 
15475 	lck_mtx_lock(&dtrace_lock);
15476 
15477 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15478 		/*
15479 		 * If the dtrace module is loaded but not attached, or if
15480 		 * there aren't isn't a meta provider registered to deal with
15481 		 * these provider descriptions, we need to postpone creating
15482 		 * the actual providers until later.
15483 		 */
15484 
15485 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15486 		    dtrace_deferred_pid != help) {
15487 			help->dthps_deferred = 1;
15488 			help->dthps_pid = proc_getpid(p);
15489 			help->dthps_next = dtrace_deferred_pid;
15490 			help->dthps_prev = NULL;
15491 			if (dtrace_deferred_pid != NULL)
15492 				dtrace_deferred_pid->dthps_prev = help;
15493 			dtrace_deferred_pid = help;
15494 		}
15495 
15496 		lck_mtx_unlock(&dtrace_lock);
15497 
15498 	} else if (dofhp != NULL) {
15499 		/*
15500 		 * If the dtrace module is loaded and we have a particular
15501 		 * helper provider description, pass that off to the
15502 		 * meta provider.
15503 		 */
15504 
15505 		lck_mtx_unlock(&dtrace_lock);
15506 
15507 		dtrace_helper_provide(dofhp, p);
15508 
15509 	} else {
15510 		/*
15511 		 * Otherwise, just pass all the helper provider descriptions
15512 		 * off to the meta provider.
15513 		 */
15514 
15515 		uint_t i;
15516 		lck_mtx_unlock(&dtrace_lock);
15517 
15518 		for (i = 0; i < help->dthps_nprovs; i++) {
15519 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15520 				p);
15521 		}
15522 	}
15523 }
15524 
15525 static int
dtrace_helper_provider_add(proc_t * p,dof_helper_t * dofhp,int gen)15526 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
15527 {
15528 	dtrace_helpers_t *help;
15529 	dtrace_helper_provider_t *hprov, **tmp_provs;
15530 	uint_t tmp_maxprovs, i;
15531 
15532 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15533 	help = p->p_dtrace_helpers;
15534 	ASSERT(help != NULL);
15535 
15536 	/*
15537 	 * If we already have dtrace_helper_providers_max helper providers,
15538 	 * we're refuse to add a new one.
15539 	 */
15540 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
15541 		return (ENOSPC);
15542 
15543 	/*
15544 	 * Check to make sure this isn't a duplicate.
15545 	 */
15546 	for (i = 0; i < help->dthps_nprovs; i++) {
15547 		if (dofhp->dofhp_addr ==
15548 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
15549 			return (EALREADY);
15550 	}
15551 
15552 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15553 	hprov->dthp_prov = *dofhp;
15554 	hprov->dthp_ref = 1;
15555 	hprov->dthp_generation = gen;
15556 
15557 	/*
15558 	 * Allocate a bigger table for helper providers if it's already full.
15559 	 */
15560 	if (help->dthps_maxprovs == help->dthps_nprovs) {
15561 		tmp_maxprovs = help->dthps_maxprovs;
15562 		tmp_provs = help->dthps_provs;
15563 
15564 		if (help->dthps_maxprovs == 0)
15565 			help->dthps_maxprovs = 2;
15566 		else
15567 			help->dthps_maxprovs *= 2;
15568 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
15569 			help->dthps_maxprovs = dtrace_helper_providers_max;
15570 
15571 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15572 
15573 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15574 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15575 
15576 		if (tmp_provs != NULL) {
15577 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15578 			    sizeof (dtrace_helper_provider_t *));
15579 			kmem_free(tmp_provs, tmp_maxprovs *
15580 			    sizeof (dtrace_helper_provider_t *));
15581 		}
15582 	}
15583 
15584 	help->dthps_provs[help->dthps_nprovs] = hprov;
15585 	help->dthps_nprovs++;
15586 
15587 	return (0);
15588 }
15589 
15590 static void
dtrace_helper_provider_destroy(dtrace_helper_provider_t * hprov)15591 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15592 {
15593 	lck_mtx_lock(&dtrace_lock);
15594 
15595 	if (--hprov->dthp_ref == 0) {
15596 		dof_hdr_t *dof;
15597 		lck_mtx_unlock(&dtrace_lock);
15598 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15599 		dtrace_dof_destroy(dof);
15600 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15601 	} else {
15602 		lck_mtx_unlock(&dtrace_lock);
15603 	}
15604 }
15605 
15606 static int
dtrace_helper_provider_validate(dof_hdr_t * dof,dof_sec_t * sec)15607 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15608 {
15609 	uintptr_t daddr = (uintptr_t)dof;
15610 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15611 	dof_provider_t *provider;
15612 	dof_probe_t *probe;
15613 	uint8_t *arg;
15614 	char *strtab, *typestr;
15615 	dof_stridx_t typeidx;
15616 	size_t typesz;
15617 	uint_t nprobes, j, k;
15618 
15619 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15620 
15621 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15622 		dtrace_dof_error(dof, "misaligned section offset");
15623 		return (-1);
15624 	}
15625 
15626 	/*
15627 	 * The section needs to be large enough to contain the DOF provider
15628 	 * structure appropriate for the given version.
15629 	 */
15630 	if (sec->dofs_size <
15631 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15632 	    offsetof(dof_provider_t, dofpv_prenoffs) :
15633 	    sizeof (dof_provider_t))) {
15634 		dtrace_dof_error(dof, "provider section too small");
15635 		return (-1);
15636 	}
15637 
15638 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15639 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15640 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15641 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15642 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15643 
15644 	if (str_sec == NULL || prb_sec == NULL ||
15645 	    arg_sec == NULL || off_sec == NULL)
15646 		return (-1);
15647 
15648 	enoff_sec = NULL;
15649 
15650 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15651 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
15652 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15653 	    provider->dofpv_prenoffs)) == NULL)
15654 		return (-1);
15655 
15656 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15657 
15658 	if (provider->dofpv_name >= str_sec->dofs_size ||
15659 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15660 		dtrace_dof_error(dof, "invalid provider name");
15661 		return (-1);
15662 	}
15663 
15664 	if (prb_sec->dofs_entsize == 0 ||
15665 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15666 		dtrace_dof_error(dof, "invalid entry size");
15667 		return (-1);
15668 	}
15669 
15670 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15671 		dtrace_dof_error(dof, "misaligned entry size");
15672 		return (-1);
15673 	}
15674 
15675 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15676 		dtrace_dof_error(dof, "invalid entry size");
15677 		return (-1);
15678 	}
15679 
15680 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15681 		dtrace_dof_error(dof, "misaligned section offset");
15682 		return (-1);
15683 	}
15684 
15685 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15686 		dtrace_dof_error(dof, "invalid entry size");
15687 		return (-1);
15688 	}
15689 
15690 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15691 
15692 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15693 
15694 	/*
15695 	 * Take a pass through the probes to check for errors.
15696 	 */
15697 	for (j = 0; j < nprobes; j++) {
15698 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15699 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15700 
15701 		if (probe->dofpr_func >= str_sec->dofs_size) {
15702 			dtrace_dof_error(dof, "invalid function name");
15703 			return (-1);
15704 		}
15705 
15706 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15707 			dtrace_dof_error(dof, "function name too long");
15708 			return (-1);
15709 		}
15710 
15711 		if (probe->dofpr_name >= str_sec->dofs_size ||
15712 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15713 			dtrace_dof_error(dof, "invalid probe name");
15714 			return (-1);
15715 		}
15716 
15717 		/*
15718 		 * The offset count must not wrap the index, and the offsets
15719 		 * must also not overflow the section's data.
15720 		 */
15721 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15722 		    probe->dofpr_offidx ||
15723 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15724 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15725 			dtrace_dof_error(dof, "invalid probe offset");
15726 			return (-1);
15727 		}
15728 
15729 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15730 			/*
15731 			 * If there's no is-enabled offset section, make sure
15732 			 * there aren't any is-enabled offsets. Otherwise
15733 			 * perform the same checks as for probe offsets
15734 			 * (immediately above).
15735 			 */
15736 			if (enoff_sec == NULL) {
15737 				if (probe->dofpr_enoffidx != 0 ||
15738 				    probe->dofpr_nenoffs != 0) {
15739 					dtrace_dof_error(dof, "is-enabled "
15740 					    "offsets with null section");
15741 					return (-1);
15742 				}
15743 			} else if (probe->dofpr_enoffidx +
15744 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15745 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15746 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15747 				dtrace_dof_error(dof, "invalid is-enabled "
15748 				    "offset");
15749 				return (-1);
15750 			}
15751 
15752 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15753 				dtrace_dof_error(dof, "zero probe and "
15754 				    "is-enabled offsets");
15755 				return (-1);
15756 			}
15757 		} else if (probe->dofpr_noffs == 0) {
15758 			dtrace_dof_error(dof, "zero probe offsets");
15759 			return (-1);
15760 		}
15761 
15762 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15763 		    probe->dofpr_argidx ||
15764 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15765 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15766 			dtrace_dof_error(dof, "invalid args");
15767 			return (-1);
15768 		}
15769 
15770 		typeidx = probe->dofpr_nargv;
15771 		typestr = strtab + probe->dofpr_nargv;
15772 		for (k = 0; k < probe->dofpr_nargc; k++) {
15773 			if (typeidx >= str_sec->dofs_size) {
15774 				dtrace_dof_error(dof, "bad "
15775 				    "native argument type");
15776 				return (-1);
15777 			}
15778 
15779 			typesz = strlen(typestr) + 1;
15780 			if (typesz > DTRACE_ARGTYPELEN) {
15781 				dtrace_dof_error(dof, "native "
15782 				    "argument type too long");
15783 				return (-1);
15784 			}
15785 			typeidx += typesz;
15786 			typestr += typesz;
15787 		}
15788 
15789 		typeidx = probe->dofpr_xargv;
15790 		typestr = strtab + probe->dofpr_xargv;
15791 		for (k = 0; k < probe->dofpr_xargc; k++) {
15792 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15793 				dtrace_dof_error(dof, "bad "
15794 				    "native argument index");
15795 				return (-1);
15796 			}
15797 
15798 			if (typeidx >= str_sec->dofs_size) {
15799 				dtrace_dof_error(dof, "bad "
15800 				    "translated argument type");
15801 				return (-1);
15802 			}
15803 
15804 			typesz = strlen(typestr) + 1;
15805 			if (typesz > DTRACE_ARGTYPELEN) {
15806 				dtrace_dof_error(dof, "translated argument "
15807 				    "type too long");
15808 				return (-1);
15809 			}
15810 
15811 			typeidx += typesz;
15812 			typestr += typesz;
15813 		}
15814 	}
15815 
15816 	return (0);
15817 }
15818 
15819 static int
dtrace_helper_slurp(proc_t * p,dof_hdr_t * dof,dof_helper_t * dhp)15820 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
15821 {
15822 	dtrace_helpers_t *help;
15823 	dtrace_vstate_t *vstate;
15824 	dtrace_enabling_t *enab = NULL;
15825 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15826 	uintptr_t daddr = (uintptr_t)dof;
15827 
15828 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15829 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15830 
15831 	if ((help = p->p_dtrace_helpers) == NULL)
15832 		help = dtrace_helpers_create(p);
15833 
15834 	vstate = &help->dthps_vstate;
15835 
15836 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15837 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15838 		dtrace_dof_destroy(dof);
15839 		return (rv);
15840 	}
15841 
15842 	/*
15843 	 * Look for helper providers and validate their descriptions.
15844 	 */
15845 	if (dhp != NULL) {
15846 		for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
15847 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15848 			    dof->dofh_secoff + i * dof->dofh_secsize);
15849 
15850 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15851 				continue;
15852 
15853 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15854 				dtrace_enabling_destroy(enab);
15855 				dtrace_dof_destroy(dof);
15856 				return (-1);
15857 			}
15858 
15859 			nprovs++;
15860 		}
15861 	}
15862 
15863 	/*
15864 	 * Now we need to walk through the ECB descriptions in the enabling.
15865 	 */
15866 	for (i = 0; i < enab->dten_ndesc; i++) {
15867 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15868 		dtrace_probedesc_t *desc = &ep->dted_probe;
15869 
15870 		/* APPLE NOTE: Darwin employs size bounded string operation. */
15871 		if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
15872 			continue;
15873 
15874 		if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
15875 			continue;
15876 
15877 		if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
15878 			continue;
15879 
15880 		if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
15881 		    ep)) != 0) {
15882 			/*
15883 			 * Adding this helper action failed -- we are now going
15884 			 * to rip out the entire generation and return failure.
15885 			 */
15886 			(void) dtrace_helper_destroygen(p, help->dthps_generation);
15887 			dtrace_enabling_destroy(enab);
15888 			dtrace_dof_destroy(dof);
15889 			return (-1);
15890 		}
15891 
15892 		nhelpers++;
15893 	}
15894 
15895 	if (nhelpers < enab->dten_ndesc)
15896 		dtrace_dof_error(dof, "unmatched helpers");
15897 
15898 	gen = help->dthps_generation++;
15899 	dtrace_enabling_destroy(enab);
15900 
15901 	if (dhp != NULL && nprovs > 0) {
15902 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15903 		if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
15904 			lck_mtx_unlock(&dtrace_lock);
15905 			dtrace_helper_provider_register(p, help, dhp);
15906 			lck_mtx_lock(&dtrace_lock);
15907 
15908 			destroy = 0;
15909 		}
15910 	}
15911 
15912 	if (destroy)
15913 		dtrace_dof_destroy(dof);
15914 
15915 	return (gen);
15916 }
15917 
15918 /*
15919  * APPLE NOTE:  DTrace lazy dof implementation
15920  *
15921  * DTrace user static probes (USDT probes) and helper actions are loaded
15922  * in a process by proccessing dof sections. The dof sections are passed
15923  * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
15924  * expensive to process dof for a process that will never use it. There
15925  * is a memory cost (allocating the providers/probes), and a cpu cost
15926  * (creating the providers/probes).
15927  *
15928  * To reduce this cost, we use "lazy dof". The normal proceedure for
15929  * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
15930  * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
15931  * used, each process retains the dof_ioctl_data_t block, instead of
15932  * copying in the data it points to.
15933  *
15934  * The dof_ioctl_data_t blocks are managed as if they were the actual
15935  * processed dof; on fork the block is copied to the child, on exec and
15936  * exit the block is freed.
15937  *
15938  * If the process loads library(s) containing additional dof, the
15939  * new dof_ioctl_data_t is merged with the existing block.
15940  *
15941  * There are a few catches that make this slightly more difficult.
15942  * When dyld registers dof_ioctl_data_t blocks, it expects a unique
15943  * identifier value for each dof in the block. In non-lazy dof terms,
15944  * this is the generation that dof was loaded in. If we hand back
15945  * a UID for a lazy dof, that same UID must be able to unload the
15946  * dof once it has become non-lazy. To meet this requirement, the
15947  * code that loads lazy dof requires that the UID's for dof(s) in
15948  * the lazy dof be sorted, and in ascending order. It is okay to skip
15949  * UID's, I.E., 1 -> 5 -> 6 is legal.
15950  *
15951  * Once a process has become non-lazy, it will stay non-lazy. All
15952  * future dof operations for that process will be non-lazy, even
15953  * if the dof mode transitions back to lazy.
15954  *
15955  * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
15956  * That way if the lazy check fails due to transitioning to non-lazy, the
15957  * right thing is done with the newly faulted in dof.
15958  */
15959 
15960 /*
15961  * This method is a bit squicky. It must handle:
15962  *
15963  * dof should not be lazy.
15964  * dof should have been handled lazily, but there was an error
15965  * dof was handled lazily, and needs to be freed.
15966  * dof was handled lazily, and must not be freed.
15967  *
15968  *
15969  * Returns EACCESS if dof should be handled non-lazily.
15970  *
15971  * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
15972  *
15973  * If the dofs data is claimed by this method, dofs_claimed will be set.
15974  * Callers should not free claimed dofs.
15975  */
15976 static int
dtrace_lazy_dofs_add(proc_t * p,dof_ioctl_data_t * incoming_dofs,int * dofs_claimed)15977 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
15978 {
15979 	ASSERT(p);
15980 	ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
15981 
15982 	int rval = 0;
15983 	*dofs_claimed = 0;
15984 
15985 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
15986 
15987 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15988 	ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
15989 
15990 	/*
15991 	 * Any existing helpers force non-lazy behavior.
15992 	 */
15993 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15994 		dtrace_sprlock(p);
15995 
15996 		dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15997 		unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
15998 		unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
15999 
16000 		/*
16001 		 * Range check...
16002 		 */
16003 		if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
16004 			dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
16005 			rval = EINVAL;
16006 			goto unlock;
16007 		}
16008 
16009 		/*
16010 		 * Each dof being added must be assigned a unique generation.
16011 		 */
16012 		uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
16013 		for (i=0; i<incoming_dofs->dofiod_count; i++) {
16014 			/*
16015 			 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
16016 			 */
16017 			ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
16018 			incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
16019 		}
16020 
16021 
16022 		if (existing_dofs) {
16023 			/*
16024 			 * Merge the existing and incoming dofs
16025 			 */
16026 			size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
16027 			dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
16028 
16029 			bcopy(&existing_dofs->dofiod_helpers[0],
16030 			      &merged_dofs->dofiod_helpers[0],
16031 			      sizeof(dof_helper_t) * existing_dofs_count);
16032 			bcopy(&incoming_dofs->dofiod_helpers[0],
16033 			      &merged_dofs->dofiod_helpers[existing_dofs_count],
16034 			      sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
16035 
16036 			merged_dofs->dofiod_count = merged_dofs_count;
16037 
16038 			kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
16039 
16040 			p->p_dtrace_lazy_dofs = merged_dofs;
16041 		} else {
16042 			/*
16043 			 * Claim the incoming dofs
16044 			 */
16045 			*dofs_claimed = 1;
16046 			p->p_dtrace_lazy_dofs = incoming_dofs;
16047 		}
16048 
16049 #if DEBUG
16050 		dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
16051 		for (i=0; i<all_dofs->dofiod_count-1; i++) {
16052 			ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
16053 		}
16054 #endif /* DEBUG */
16055 
16056 unlock:
16057 		dtrace_sprunlock(p);
16058 	} else {
16059 		rval = EACCES;
16060 	}
16061 
16062  	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16063 
16064 	return rval;
16065 }
16066 
16067 /*
16068  * Returns:
16069  *
16070  * EINVAL: lazy dof is enabled, but the requested generation was not found.
16071  * EACCES: This removal needs to be handled non-lazily.
16072  */
16073 static int
dtrace_lazy_dofs_remove(proc_t * p,int generation)16074 dtrace_lazy_dofs_remove(proc_t *p, int generation)
16075 {
16076 	int rval = EINVAL;
16077 
16078 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16079 
16080 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16081 	ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
16082 
16083 	/*
16084 	 * Any existing helpers force non-lazy behavior.
16085 	 */
16086 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
16087 		dtrace_sprlock(p);
16088 
16089 		dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
16090 
16091 		if (existing_dofs) {
16092 			int index, existing_dofs_count = existing_dofs->dofiod_count;
16093 			for (index=0; index<existing_dofs_count; index++) {
16094 				if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
16095 					dof_ioctl_data_t* removed_dofs = NULL;
16096 
16097 					/*
16098 					 * If there is only 1 dof, we'll delete it and swap in NULL.
16099 					 */
16100 					if (existing_dofs_count > 1) {
16101 						int removed_dofs_count = existing_dofs_count - 1;
16102 						size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
16103 
16104 						removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
16105 						removed_dofs->dofiod_count = removed_dofs_count;
16106 
16107 						/*
16108 						 * copy the remaining data.
16109 						 */
16110 						if (index > 0) {
16111 							bcopy(&existing_dofs->dofiod_helpers[0],
16112 							      &removed_dofs->dofiod_helpers[0],
16113 							      index * sizeof(dof_helper_t));
16114 						}
16115 
16116 						if (index < existing_dofs_count-1) {
16117 							bcopy(&existing_dofs->dofiod_helpers[index+1],
16118 							      &removed_dofs->dofiod_helpers[index],
16119 							      (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
16120 						}
16121 					}
16122 
16123 					kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
16124 
16125 					p->p_dtrace_lazy_dofs = removed_dofs;
16126 
16127 					rval = KERN_SUCCESS;
16128 
16129 					break;
16130 				}
16131 			}
16132 
16133 #if DEBUG
16134 			dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
16135 			if (all_dofs) {
16136 				unsigned int i;
16137 				for (i=0; i<all_dofs->dofiod_count-1; i++) {
16138 					ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
16139 				}
16140 			}
16141 #endif
16142 
16143 		}
16144 		dtrace_sprunlock(p);
16145 	} else {
16146 		rval = EACCES;
16147 	}
16148 
16149 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16150 
16151 	return rval;
16152 }
16153 
16154 void
dtrace_lazy_dofs_destroy(proc_t * p)16155 dtrace_lazy_dofs_destroy(proc_t *p)
16156 {
16157 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16158 	dtrace_sprlock(p);
16159 
16160 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16161 
16162 	dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
16163 	p->p_dtrace_lazy_dofs = NULL;
16164 
16165 	dtrace_sprunlock(p);
16166 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16167 
16168 	if (lazy_dofs) {
16169 		kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
16170 	}
16171 }
16172 
16173 static int
dtrace_lazy_dofs_proc_iterate_filter(proc_t * p,void * ignored)16174 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
16175 {
16176 #pragma unused(ignored)
16177 	/*
16178 	 * Okay to NULL test without taking the sprlock.
16179 	 */
16180 	return p->p_dtrace_lazy_dofs != NULL;
16181 }
16182 
16183 static void
dtrace_lazy_dofs_process(proc_t * p)16184 dtrace_lazy_dofs_process(proc_t *p) {
16185 	/*
16186 	 * It is possible this process may exit during our attempt to
16187 	 * fault in the dof. We could fix this by holding locks longer,
16188 	 * but the errors are benign.
16189 	 */
16190 	dtrace_sprlock(p);
16191 
16192 
16193 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16194 	ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
16195 
16196 	dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
16197 	p->p_dtrace_lazy_dofs = NULL;
16198 
16199 	dtrace_sprunlock(p);
16200 	lck_mtx_lock(&dtrace_meta_lock);
16201 	/*
16202 	 * Process each dof_helper_t
16203 	 */
16204 	if (lazy_dofs != NULL) {
16205 		unsigned int i;
16206 		int rval;
16207 
16208 		for (i=0; i<lazy_dofs->dofiod_count; i++) {
16209 			/*
16210 			 * When loading lazy dof, we depend on the generations being sorted in ascending order.
16211 			 */
16212 			ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
16213 
16214 			dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
16215 
16216 			/*
16217 			 * We stored the generation in dofhp_dof. Save it, and restore the original value.
16218 			 */
16219 			int generation = dhp->dofhp_dof;
16220 			dhp->dofhp_dof = dhp->dofhp_addr;
16221 
16222 			dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
16223 
16224 			if (dof != NULL) {
16225 				dtrace_helpers_t *help;
16226 
16227 				lck_mtx_lock(&dtrace_lock);
16228 
16229 				/*
16230 				 * This must be done with the dtrace_lock held
16231 				 */
16232 				if ((help = p->p_dtrace_helpers) == NULL)
16233 					help = dtrace_helpers_create(p);
16234 
16235 				/*
16236 				 * If the generation value has been bumped, someone snuck in
16237 				 * when we released the dtrace lock. We have to dump this generation,
16238 				 * there is no safe way to load it.
16239 				 */
16240 				if (help->dthps_generation <= generation) {
16241 					help->dthps_generation = generation;
16242 
16243 					/*
16244 					 * dtrace_helper_slurp() takes responsibility for the dof --
16245 					 * it may free it now or it may save it and free it later.
16246 					 */
16247 					if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
16248 						dtrace_dof_error(NULL, "returned value did not match expected generation");
16249 					}
16250 				}
16251 
16252 				lck_mtx_unlock(&dtrace_lock);
16253 			}
16254 		}
16255 		lck_mtx_unlock(&dtrace_meta_lock);
16256 		kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
16257 	} else {
16258 		lck_mtx_unlock(&dtrace_meta_lock);
16259 	}
16260 }
16261 
16262 static int
dtrace_lazy_dofs_proc_iterate_doit(proc_t * p,void * ignored)16263 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
16264 {
16265 #pragma unused(ignored)
16266 
16267 	dtrace_lazy_dofs_process(p);
16268 
16269 	return PROC_RETURNED;
16270 }
16271 
16272 #define DTRACE_LAZY_DOFS_DUPLICATED 1
16273 
16274 static int
dtrace_lazy_dofs_duplicate(proc_t * parent,proc_t * child)16275 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
16276 {
16277 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
16278 	LCK_MTX_ASSERT(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
16279 	LCK_MTX_ASSERT(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
16280 
16281 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16282 	dtrace_sprlock(parent);
16283 
16284 	/*
16285 	 * We need to make sure that the transition to lazy dofs -> helpers
16286 	 * was atomic for our parent
16287 	 */
16288 	ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
16289 	/*
16290 	 * In theory we should hold the child sprlock, but this is safe...
16291 	 */
16292 	ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
16293 
16294 	dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
16295 	dof_ioctl_data_t* child_dofs = NULL;
16296 	if (parent_dofs) {
16297 		size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
16298 		child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
16299 		bcopy(parent_dofs, child_dofs, parent_dofs_size);
16300 	}
16301 
16302 	dtrace_sprunlock(parent);
16303 
16304 	if (child_dofs) {
16305 		dtrace_sprlock(child);
16306 		child->p_dtrace_lazy_dofs = child_dofs;
16307 		dtrace_sprunlock(child);
16308 		/**
16309 		 * We process the DOF at this point if the mode is set to
16310 		 * LAZY_OFF. This can happen if DTrace is still processing the
16311 		 * DOF of other process (which can happen because the
16312 		 * protected pager can have a huge latency)
16313 		 * but has not processed our parent yet
16314 		 */
16315 		if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
16316 			dtrace_lazy_dofs_process(child);
16317 		}
16318 		lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16319 
16320 		return DTRACE_LAZY_DOFS_DUPLICATED;
16321 	}
16322 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16323 
16324 	return 0;
16325 }
16326 
16327 static dtrace_helpers_t *
dtrace_helpers_create(proc_t * p)16328 dtrace_helpers_create(proc_t *p)
16329 {
16330 	dtrace_helpers_t *help;
16331 
16332 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
16333 	ASSERT(p->p_dtrace_helpers == NULL);
16334 
16335 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16336 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16337 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16338 
16339 	p->p_dtrace_helpers = help;
16340 	dtrace_helpers++;
16341 
16342 	return (help);
16343 }
16344 
16345 static void
dtrace_helpers_destroy(proc_t * p)16346 dtrace_helpers_destroy(proc_t* p)
16347 {
16348 	dtrace_helpers_t *help;
16349 	dtrace_vstate_t *vstate;
16350 	uint_t i;
16351 
16352 	lck_mtx_lock(&dtrace_meta_lock);
16353 	lck_mtx_lock(&dtrace_lock);
16354 
16355 	ASSERT(p->p_dtrace_helpers != NULL);
16356 	ASSERT(dtrace_helpers > 0);
16357 
16358 	help = p->p_dtrace_helpers;
16359 	vstate = &help->dthps_vstate;
16360 
16361 	/*
16362 	 * We're now going to lose the help from this process.
16363 	 */
16364 	p->p_dtrace_helpers = NULL;
16365 	dtrace_sync();
16366 
16367 	/*
16368 	 * Destory the helper actions.
16369 	 */
16370 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16371 		dtrace_helper_action_t *h, *next;
16372 
16373 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16374 			next = h->dtha_next;
16375 			dtrace_helper_action_destroy(h, vstate);
16376 			h = next;
16377 		}
16378 	}
16379 
16380 	lck_mtx_unlock(&dtrace_lock);
16381 
16382 	/*
16383 	 * Destroy the helper providers.
16384 	 */
16385 	if (help->dthps_maxprovs > 0) {
16386 		if (dtrace_meta_pid != NULL) {
16387 			ASSERT(dtrace_deferred_pid == NULL);
16388 
16389 			for (i = 0; i < help->dthps_nprovs; i++) {
16390 				dtrace_helper_provider_remove(
16391 				    &help->dthps_provs[i]->dthp_prov, p);
16392 			}
16393 		} else {
16394 			lck_mtx_lock(&dtrace_lock);
16395 			ASSERT(help->dthps_deferred == 0 ||
16396 			    help->dthps_next != NULL ||
16397 			    help->dthps_prev != NULL ||
16398 			    help == dtrace_deferred_pid);
16399 
16400 			/*
16401 			 * Remove the helper from the deferred list.
16402 			 */
16403 			if (help->dthps_next != NULL)
16404 				help->dthps_next->dthps_prev = help->dthps_prev;
16405 			if (help->dthps_prev != NULL)
16406 				help->dthps_prev->dthps_next = help->dthps_next;
16407 			if (dtrace_deferred_pid == help) {
16408 				dtrace_deferred_pid = help->dthps_next;
16409 				ASSERT(help->dthps_prev == NULL);
16410 			}
16411 
16412 			lck_mtx_unlock(&dtrace_lock);
16413 		}
16414 
16415 
16416 		for (i = 0; i < help->dthps_nprovs; i++) {
16417 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16418 		}
16419 
16420 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16421 		    sizeof (dtrace_helper_provider_t *));
16422 	}
16423 
16424 	lck_mtx_lock(&dtrace_lock);
16425 
16426 	dtrace_vstate_fini(&help->dthps_vstate);
16427 	kmem_free(help->dthps_actions,
16428 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16429 	kmem_free(help, sizeof (dtrace_helpers_t));
16430 
16431 	--dtrace_helpers;
16432 	lck_mtx_unlock(&dtrace_lock);
16433 	lck_mtx_unlock(&dtrace_meta_lock);
16434 }
16435 
16436 static void
dtrace_helpers_duplicate(proc_t * from,proc_t * to)16437 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16438 {
16439 	dtrace_helpers_t *help, *newhelp;
16440 	dtrace_helper_action_t *helper, *new, *last;
16441 	dtrace_difo_t *dp;
16442 	dtrace_vstate_t *vstate;
16443 	uint_t i;
16444 	int j, sz, hasprovs = 0;
16445 
16446 	lck_mtx_lock(&dtrace_meta_lock);
16447 	lck_mtx_lock(&dtrace_lock);
16448 	ASSERT(from->p_dtrace_helpers != NULL);
16449 	ASSERT(dtrace_helpers > 0);
16450 
16451 	help = from->p_dtrace_helpers;
16452 	newhelp = dtrace_helpers_create(to);
16453 	ASSERT(to->p_dtrace_helpers != NULL);
16454 
16455 	newhelp->dthps_generation = help->dthps_generation;
16456 	vstate = &newhelp->dthps_vstate;
16457 
16458 	/*
16459 	 * Duplicate the helper actions.
16460 	 */
16461 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16462 		if ((helper = help->dthps_actions[i]) == NULL)
16463 			continue;
16464 
16465 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16466 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16467 			    KM_SLEEP);
16468 			new->dtha_generation = helper->dtha_generation;
16469 
16470 			if ((dp = helper->dtha_predicate) != NULL) {
16471 				dp = dtrace_difo_duplicate(dp, vstate);
16472 				new->dtha_predicate = dp;
16473 			}
16474 
16475 			new->dtha_nactions = helper->dtha_nactions;
16476 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16477 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16478 
16479 			for (j = 0; j < new->dtha_nactions; j++) {
16480 				dtrace_difo_t *dpj = helper->dtha_actions[j];
16481 
16482 				ASSERT(dpj != NULL);
16483 				dpj = dtrace_difo_duplicate(dpj, vstate);
16484 				new->dtha_actions[j] = dpj;
16485 			}
16486 
16487 			if (last != NULL) {
16488 				last->dtha_next = new;
16489 			} else {
16490 				newhelp->dthps_actions[i] = new;
16491 			}
16492 
16493 			last = new;
16494 		}
16495 	}
16496 
16497 	/*
16498 	 * Duplicate the helper providers and register them with the
16499 	 * DTrace framework.
16500 	 */
16501 	if (help->dthps_nprovs > 0) {
16502 		newhelp->dthps_nprovs = help->dthps_nprovs;
16503 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16504 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16505 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16506 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16507 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16508 			newhelp->dthps_provs[i]->dthp_ref++;
16509 		}
16510 
16511 		hasprovs = 1;
16512 	}
16513 
16514 	lck_mtx_unlock(&dtrace_lock);
16515 
16516 	if (hasprovs)
16517 		dtrace_helper_provider_register(to, newhelp, NULL);
16518 
16519 	lck_mtx_unlock(&dtrace_meta_lock);
16520 }
16521 
16522 /**
16523  * DTrace Process functions
16524  */
16525 
16526 void
dtrace_proc_fork(proc_t * parent_proc,proc_t * child_proc,int spawn)16527 dtrace_proc_fork(proc_t *parent_proc, proc_t *child_proc, int spawn)
16528 {
16529 	/*
16530 	 * This code applies to new processes who are copying the task
16531 	 * and thread state and address spaces of their parent process.
16532 	 */
16533 	if (!spawn) {
16534 		/*
16535 		 * APPLE NOTE: Solaris does a sprlock() and drops the
16536 		 * proc_lock here. We're cheating a bit and only taking
16537 		 * the p_dtrace_sprlock lock. A full sprlock would
16538 		 * task_suspend the parent.
16539 		 */
16540 		dtrace_sprlock(parent_proc);
16541 
16542 		/*
16543 		 * Remove all DTrace tracepoints from the child process. We
16544 		 * need to do this _before_ duplicating USDT providers since
16545 		 * any associated probes may be immediately enabled.
16546 		 */
16547 		if (parent_proc->p_dtrace_count > 0) {
16548 			dtrace_fasttrap_fork(parent_proc, child_proc);
16549 		}
16550 
16551 		dtrace_sprunlock(parent_proc);
16552 
16553 		/*
16554 		 * Duplicate any lazy dof(s). This must be done while NOT
16555 		 * holding the parent sprlock! Lock ordering is
16556 		 * dtrace_dof_mode_lock, then sprlock.  It is imperative we
16557 		 * always call dtrace_lazy_dofs_duplicate, rather than null
16558 		 * check and call if !NULL. If we NULL test, during lazy dof
16559 		 * faulting we can race with the faulting code and proceed
16560 		 * from here to beyond the helpers copy. The lazy dof
16561 		 * faulting will then fail to copy the helpers to the child
16562 		 * process. We return if we duplicated lazy dofs as a process
16563 		 * can only have one at the same time to avoid a race between
16564 		 * a dtrace client and dtrace_proc_fork where a process would
16565 		 * end up with both lazy dofs and helpers.
16566 		 */
16567 		if (dtrace_lazy_dofs_duplicate(parent_proc, child_proc) == DTRACE_LAZY_DOFS_DUPLICATED) {
16568 			return;
16569 		}
16570 
16571 		/*
16572 		 * Duplicate any helper actions and providers if they haven't
16573 		 * already.
16574 		 */
16575 #if !defined(__APPLE__)
16576 		 /*
16577 		 * The SFORKING
16578 		 * we set above informs the code to enable USDT probes that
16579 		 * sprlock() may fail because the child is being forked.
16580 		 */
16581 #endif
16582 		/*
16583 		 * APPLE NOTE: As best I can tell, Apple's sprlock() equivalent
16584 		 * never fails to find the child. We do not set SFORKING.
16585 		 */
16586 		if (parent_proc->p_dtrace_helpers != NULL && dtrace_helpers_fork) {
16587 			(*dtrace_helpers_fork)(parent_proc, child_proc);
16588 		}
16589 	}
16590 }
16591 
16592 void
dtrace_proc_exec(proc_t * p)16593 dtrace_proc_exec(proc_t *p)
16594 {
16595 	/*
16596 	 * Invalidate any predicate evaluation already cached for this thread by DTrace.
16597 	 * That's because we've just stored to p_comm and DTrace refers to that when it
16598 	 * evaluates the "execname" special variable. uid and gid may have changed as well.
16599 	 */
16600 	dtrace_set_thread_predcache(current_thread(), 0);
16601 
16602 	/*
16603 	 * Free any outstanding lazy dof entries. It is imperative we
16604 	 * always call dtrace_lazy_dofs_destroy, rather than null check
16605 	 * and call if !NULL. If we NULL test, during lazy dof faulting
16606 	 * we can race with the faulting code and proceed from here to
16607 	 * beyond the helpers cleanup. The lazy dof faulting will then
16608 	 * install new helpers which no longer belong to this process!
16609 	 */
16610 	dtrace_lazy_dofs_destroy(p);
16611 
16612 
16613 	/*
16614 	 * Clean up any DTrace helpers for the process.
16615 	 */
16616 	if (p->p_dtrace_helpers != NULL && dtrace_helpers_cleanup) {
16617 		(*dtrace_helpers_cleanup)(p);
16618 	}
16619 
16620 	/*
16621 	 * Cleanup the DTrace provider associated with this process.
16622 	 */
16623 	proc_lock(p);
16624 	if (p->p_dtrace_probes && dtrace_fasttrap_exec_ptr) {
16625 		(*dtrace_fasttrap_exec_ptr)(p);
16626 	}
16627 	proc_unlock(p);
16628 }
16629 
16630 void
dtrace_proc_exit(proc_t * p)16631 dtrace_proc_exit(proc_t *p)
16632 {
16633 	/*
16634 	 * Free any outstanding lazy dof entries. It is imperative we
16635 	 * always call dtrace_lazy_dofs_destroy, rather than null check
16636 	 * and call if !NULL. If we NULL test, during lazy dof faulting
16637 	 * we can race with the faulting code and proceed from here to
16638 	 * beyond the helpers cleanup. The lazy dof faulting will then
16639 	 * install new helpers which will never be cleaned up, and leak.
16640 	 */
16641 	dtrace_lazy_dofs_destroy(p);
16642 
16643 	/*
16644 	 * Clean up any DTrace helper actions or probes for the process.
16645 	 */
16646 	if (p->p_dtrace_helpers != NULL) {
16647 		(*dtrace_helpers_cleanup)(p);
16648 	}
16649 
16650 	/*
16651 	 * Clean up any DTrace probes associated with this process.
16652 	 */
16653 	/*
16654 	 * APPLE NOTE: We release ptss pages/entries in dtrace_fasttrap_exit_ptr(),
16655 	 * call this after dtrace_helpers_cleanup()
16656 	 */
16657 	proc_lock(p);
16658 	if (p->p_dtrace_probes && dtrace_fasttrap_exit_ptr) {
16659 		(*dtrace_fasttrap_exit_ptr)(p);
16660 	}
16661 	proc_unlock(p);
16662 }
16663 
16664 /*
16665  * DTrace Hook Functions
16666  */
16667 
16668 /*
16669  * APPLE NOTE:  dtrace_modctl_* routines for kext support.
16670  * Used to manipulate the modctl list within dtrace xnu.
16671  */
16672 
16673 modctl_t *dtrace_modctl_list;
16674 
16675 static void
dtrace_modctl_add(struct modctl * newctl)16676 dtrace_modctl_add(struct modctl * newctl)
16677 {
16678 	struct modctl *nextp, *prevp;
16679 
16680 	ASSERT(newctl != NULL);
16681 	LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16682 
16683 	// Insert new module at the front of the list,
16684 
16685 	newctl->mod_next = dtrace_modctl_list;
16686 	dtrace_modctl_list = newctl;
16687 
16688 	/*
16689 	 * If a module exists with the same name, then that module
16690 	 * must have been unloaded with enabled probes. We will move
16691 	 * the unloaded module to the new module's stale chain and
16692 	 * then stop traversing the list.
16693 	 */
16694 
16695 	prevp = newctl;
16696 	nextp = newctl->mod_next;
16697 
16698 	while (nextp != NULL) {
16699 		if (nextp->mod_loaded) {
16700 			/* This is a loaded module. Keep traversing. */
16701 			prevp = nextp;
16702 			nextp = nextp->mod_next;
16703 			continue;
16704 		}
16705 		else {
16706 			/* Found an unloaded module */
16707 			if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
16708 				/* Names don't match. Keep traversing. */
16709 				prevp = nextp;
16710 				nextp = nextp->mod_next;
16711 				continue;
16712 			}
16713 			else {
16714 				/* We found a stale entry, move it. We're done. */
16715 				prevp->mod_next = nextp->mod_next;
16716 				newctl->mod_stale = nextp;
16717 				nextp->mod_next = NULL;
16718 				break;
16719 			}
16720 		}
16721 	}
16722 }
16723 
16724 static modctl_t *
dtrace_modctl_lookup(struct kmod_info * kmod)16725 dtrace_modctl_lookup(struct kmod_info * kmod)
16726 {
16727     LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16728 
16729     struct modctl * ctl;
16730 
16731     for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
16732 	if (ctl->mod_id == kmod->id)
16733 	    return(ctl);
16734     }
16735     return (NULL);
16736 }
16737 
16738 /*
16739  * This routine is called from dtrace_module_unloaded().
16740  * It removes a modctl structure and its stale chain
16741  * from the kext shadow list.
16742  */
16743 static void
dtrace_modctl_remove(struct modctl * ctl)16744 dtrace_modctl_remove(struct modctl * ctl)
16745 {
16746 	ASSERT(ctl != NULL);
16747 	LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16748 	modctl_t *prevp, *nextp, *curp;
16749 
16750 	// Remove stale chain first
16751 	for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
16752 		nextp = curp->mod_stale;
16753 		/* There should NEVER be user symbols allocated at this point */
16754 		ASSERT(curp->mod_user_symbols == NULL);
16755 		kmem_free(curp, sizeof(modctl_t));
16756 	}
16757 
16758 	prevp = NULL;
16759 	curp = dtrace_modctl_list;
16760 
16761 	while (curp != ctl) {
16762 		prevp = curp;
16763 		curp = curp->mod_next;
16764 	}
16765 
16766 	if (prevp != NULL) {
16767 		prevp->mod_next = ctl->mod_next;
16768 	}
16769 	else {
16770 		dtrace_modctl_list = ctl->mod_next;
16771 	}
16772 
16773 	/* There should NEVER be user symbols allocated at this point */
16774 	ASSERT(ctl->mod_user_symbols == NULL);
16775 
16776 	kmem_free (ctl, sizeof(modctl_t));
16777 }
16778 
16779 /*
16780  * APPLE NOTE: The kext loader will call dtrace_module_loaded
16781  * when the kext is loaded in memory, but before calling the
16782  * kext's start routine.
16783  *
16784  * Return 0 on success
16785  * Return -1 on failure
16786  */
16787 
16788 static int
dtrace_module_loaded(struct kmod_info * kmod,uint32_t flag)16789 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
16790 {
16791 	dtrace_provider_t *prv;
16792 
16793 	/*
16794 	 * If kernel symbols have been disabled, return immediately
16795 	 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
16796 	 */
16797 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
16798 		return 0;
16799 
16800 	struct modctl *ctl = NULL;
16801 	if (!kmod || kmod->address == 0 || kmod->size == 0)
16802 		return(-1);
16803 
16804 	lck_mtx_lock(&dtrace_provider_lock);
16805 	lck_mtx_lock(&mod_lock);
16806 
16807 	/*
16808 	 * Have we seen this kext before?
16809 	 */
16810 
16811 	ctl = dtrace_modctl_lookup(kmod);
16812 
16813 	if (ctl != NULL) {
16814 		/* bail... we already have this kext in the modctl list */
16815 		lck_mtx_unlock(&mod_lock);
16816 		lck_mtx_unlock(&dtrace_provider_lock);
16817 		if (dtrace_err_verbose)
16818 			cmn_err(CE_WARN, "dtrace load module already exists '%s %u' is failing against '%s %u'", kmod->name, (uint_t)kmod->id, ctl->mod_modname, ctl->mod_id);
16819 		return(-1);
16820 	}
16821 	else {
16822 		ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
16823 		if (ctl == NULL) {
16824 			if (dtrace_err_verbose)
16825 				cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
16826 			lck_mtx_unlock(&mod_lock);
16827 			lck_mtx_unlock(&dtrace_provider_lock);
16828 			return (-1);
16829 		}
16830 		ctl->mod_next = NULL;
16831 		ctl->mod_stale = NULL;
16832 		strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
16833 		ctl->mod_loadcnt = kmod->id;
16834 		ctl->mod_nenabled = 0;
16835 		ctl->mod_address  = kmod->address;
16836 		ctl->mod_size = kmod->size;
16837 		ctl->mod_id = kmod->id;
16838 		ctl->mod_loaded = 1;
16839 		ctl->mod_flags = 0;
16840 		ctl->mod_user_symbols = NULL;
16841 		ctl->mod_sdtprobecnt = 0;
16842 		ctl->mod_sdtdesc = NULL;
16843 
16844 		/*
16845 		 * Find the UUID for this module, if it has one
16846 		 */
16847 		kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
16848 		struct load_command* load_cmd = (struct load_command *)&header[1];
16849 		uint32_t i;
16850 		for (i = 0; i < header->ncmds; i++) {
16851 			if (load_cmd->cmd == LC_UUID) {
16852 				struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
16853 				memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
16854 				ctl->mod_flags |= MODCTL_HAS_UUID;
16855 				break;
16856 			}
16857 			load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
16858 		}
16859 
16860 		if (ctl->mod_address == g_kernel_kmod_info.address) {
16861 			ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
16862 			memcpy(dtrace_kerneluuid, ctl->mod_uuid, sizeof(dtrace_kerneluuid));
16863 		}
16864 		/*
16865 		 * Static kexts have a UUID that is not used for symbolication, as all their
16866 		 * symbols are in kernel
16867 		 */
16868 		else if ((flag & KMOD_DTRACE_STATIC_KEXT) == KMOD_DTRACE_STATIC_KEXT) {
16869 			memcpy(ctl->mod_uuid, dtrace_kerneluuid, sizeof(dtrace_kerneluuid));
16870 			ctl->mod_flags |= MODCTL_IS_STATIC_KEXT;
16871 		}
16872 	}
16873 	dtrace_modctl_add(ctl);
16874 
16875 	/*
16876 	 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
16877 	 */
16878 	lck_mtx_lock(&dtrace_lock);
16879 
16880 	/*
16881 	 * DTrace must decide if it will instrument modules lazily via
16882 	 * userspace symbols (default mode), or instrument immediately via
16883 	 * kernel symbols (non-default mode)
16884 	 *
16885 	 * When in default/lazy mode, DTrace will only support modules
16886 	 * built with a valid UUID.
16887 	 *
16888 	 * Overriding the default can be done explicitly in one of
16889 	 * the following two ways.
16890 	 *
16891 	 * A module can force symbols from kernel space using the plist key,
16892 	 * OSBundleForceDTraceInit (see kmod.h).  If this per kext state is set,
16893 	 * we fall through and instrument this module now.
16894 	 *
16895 	 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
16896 	 * from kernel space (see dtrace_impl.h).  If this system state is set
16897 	 * to a non-userspace mode, we fall through and instrument the module now.
16898 	 */
16899 
16900 	if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
16901 	    (!(flag & KMOD_DTRACE_FORCE_INIT)))
16902 	{
16903 		/* Load SDT section for module. Symbol related data will be handled lazily. */
16904 		sdt_load_machsect(ctl);
16905 
16906 		/* We will instrument the module lazily -- this is the default */
16907 		lck_mtx_unlock(&dtrace_lock);
16908 		lck_mtx_unlock(&mod_lock);
16909 		lck_mtx_unlock(&dtrace_provider_lock);
16910 		return 0;
16911 	}
16912 
16913 	/* We will instrument the module immediately using kernel symbols */
16914 	if (!(flag & KMOD_DTRACE_NO_KERNEL_SYMS)) {
16915 		ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
16916 	}
16917 
16918 	/* Load SDT section for module. Symbol related data will be handled lazily. */
16919 	sdt_load_machsect(ctl);
16920 
16921 	lck_mtx_unlock(&dtrace_lock);
16922 
16923 	/*
16924 	 * We're going to call each providers per-module provide operation
16925 	 * specifying only this module.
16926 	 */
16927 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16928 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16929 
16930 	/*
16931 	 * APPLE NOTE: The contract with the kext loader is that once this function
16932 	 * has completed, it may delete kernel symbols at will.
16933 	 * We must set this while still holding the mod_lock.
16934 	 */
16935 	ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
16936 
16937 	lck_mtx_unlock(&mod_lock);
16938 	lck_mtx_unlock(&dtrace_provider_lock);
16939 
16940 	/*
16941 	 * If we have any retained enablings, we need to match against them.
16942 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16943 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16944 	 * module.  (In particular, this happens when loading scheduling
16945 	 * classes.)  So if we have any retained enablings, we need to dispatch
16946 	 * our task queue to do the match for us.
16947 	 */
16948 	lck_mtx_lock(&dtrace_lock);
16949 
16950 	if (dtrace_retained == NULL) {
16951 		lck_mtx_unlock(&dtrace_lock);
16952 		return 0;
16953 	}
16954 
16955 	/* APPLE NOTE!
16956 	 *
16957 	 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
16958 	 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
16959 	 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
16960 	 * the delay call as well.
16961 	 */
16962 	lck_mtx_unlock(&dtrace_lock);
16963 
16964 	dtrace_enabling_matchall();
16965 
16966 	return 0;
16967 }
16968 
16969 /*
16970  * Return 0 on success
16971  * Return -1 on failure
16972  */
16973 static int
dtrace_module_unloaded(struct kmod_info * kmod)16974 dtrace_module_unloaded(struct kmod_info *kmod)
16975 {
16976 	dtrace_probe_t template, *probe, *first, *next;
16977 	dtrace_provider_t *prov;
16978         struct modctl *ctl = NULL;
16979 	struct modctl *syncctl = NULL;
16980 	struct modctl *nextsyncctl = NULL;
16981 	int syncmode = 0;
16982 
16983         lck_mtx_lock(&dtrace_provider_lock);
16984 	lck_mtx_lock(&mod_lock);
16985 	lck_mtx_lock(&dtrace_lock);
16986 
16987 	if (kmod == NULL) {
16988 	    syncmode = 1;
16989 	}
16990 	else {
16991 	    ctl = dtrace_modctl_lookup(kmod);
16992 	    if (ctl == NULL)
16993 	    {
16994 		lck_mtx_unlock(&dtrace_lock);
16995 		lck_mtx_unlock(&mod_lock);
16996 		lck_mtx_unlock(&dtrace_provider_lock);
16997 		return (-1);
16998 	    }
16999 	    ctl->mod_loaded = 0;
17000 	    ctl->mod_address = 0;
17001 	    ctl->mod_size = 0;
17002 	}
17003 
17004 	if (dtrace_bymod == NULL) {
17005 		/*
17006 		 * The DTrace module is loaded (obviously) but not attached;
17007 		 * we don't have any work to do.
17008 		 */
17009 	         if (ctl != NULL)
17010 			 (void)dtrace_modctl_remove(ctl);
17011 		 lck_mtx_unlock(&dtrace_lock);
17012 		 lck_mtx_unlock(&mod_lock);
17013 		 lck_mtx_unlock(&dtrace_provider_lock);
17014 		 return(0);
17015 	}
17016 
17017 	/* Syncmode set means we target and traverse entire modctl list. */
17018         if (syncmode)
17019 	    nextsyncctl = dtrace_modctl_list;
17020 
17021 syncloop:
17022 	if (syncmode)
17023 	{
17024 	    /* find a stale modctl struct */
17025 	    for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
17026 		if (syncctl->mod_address == 0)
17027 		    break;
17028 	    }
17029 	    if (syncctl==NULL)
17030 	    {
17031 		/* We have no more work to do */
17032 		lck_mtx_unlock(&dtrace_lock);
17033 		lck_mtx_unlock(&mod_lock);
17034 		lck_mtx_unlock(&dtrace_provider_lock);
17035 		return(0);
17036 	    }
17037 	    else {
17038 		/* keep track of next syncctl in case this one is removed */
17039 		nextsyncctl = syncctl->mod_next;
17040 		ctl = syncctl;
17041 	    }
17042 	}
17043 
17044 	template.dtpr_mod = ctl->mod_modname;
17045 
17046 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
17047 	    probe != NULL; probe = probe->dtpr_nextmod) {
17048 	        if (probe->dtpr_ecb != NULL) {
17049 			/*
17050 			 * This shouldn't _actually_ be possible -- we're
17051 			 * unloading a module that has an enabled probe in it.
17052 			 * (It's normally up to the provider to make sure that
17053 			 * this can't happen.)  However, because dtps_enable()
17054 			 * doesn't have a failure mode, there can be an
17055 			 * enable/unload race.  Upshot:  we don't want to
17056 			 * assert, but we're not going to disable the
17057 			 * probe, either.
17058 			 */
17059 
17060 
17061 		        if (syncmode) {
17062 			    /* We're syncing, let's look at next in list */
17063 			    goto syncloop;
17064 			}
17065 
17066 			lck_mtx_unlock(&dtrace_lock);
17067 			lck_mtx_unlock(&mod_lock);
17068 			lck_mtx_unlock(&dtrace_provider_lock);
17069 
17070 			if (dtrace_err_verbose) {
17071 				cmn_err(CE_WARN, "unloaded module '%s' had "
17072 				    "enabled probes", ctl->mod_modname);
17073 			}
17074 			return(-1);
17075 		}
17076 	}
17077 
17078 	probe = first;
17079 
17080 	for (first = NULL; probe != NULL; probe = next) {
17081 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
17082 
17083 		dtrace_probes[probe->dtpr_id - 1] = NULL;
17084 		probe->dtpr_provider->dtpv_probe_count--;
17085 
17086 		next = probe->dtpr_nextmod;
17087 		dtrace_hash_remove(dtrace_byprov, probe);
17088 		dtrace_hash_remove(dtrace_bymod, probe);
17089 		dtrace_hash_remove(dtrace_byfunc, probe);
17090 		dtrace_hash_remove(dtrace_byname, probe);
17091 
17092 		if (first == NULL) {
17093 			first = probe;
17094 			probe->dtpr_nextmod = NULL;
17095 		} else {
17096 			probe->dtpr_nextmod = first;
17097 			first = probe;
17098 		}
17099 	}
17100 
17101 	/*
17102 	 * We've removed all of the module's probes from the hash chains and
17103 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
17104 	 * everyone has cleared out from any probe array processing.
17105 	 */
17106 	dtrace_sync();
17107 
17108 	for (probe = first; probe != NULL; probe = first) {
17109 		first = probe->dtpr_nextmod;
17110 		prov = probe->dtpr_provider;
17111 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
17112 		    probe->dtpr_arg);
17113 		dtrace_strunref(probe->dtpr_mod);
17114 		dtrace_strunref(probe->dtpr_func);
17115 		dtrace_strunref(probe->dtpr_name);
17116 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
17117 
17118 		zfree(dtrace_probe_t_zone, probe);
17119 	}
17120 
17121 	dtrace_modctl_remove(ctl);
17122 
17123 	if (syncmode)
17124 	    goto syncloop;
17125 
17126 	lck_mtx_unlock(&dtrace_lock);
17127 	lck_mtx_unlock(&mod_lock);
17128 	lck_mtx_unlock(&dtrace_provider_lock);
17129 
17130 	return(0);
17131 }
17132 
17133 void
dtrace_suspend(void)17134 dtrace_suspend(void)
17135 {
17136 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
17137 }
17138 
17139 void
dtrace_resume(void)17140 dtrace_resume(void)
17141 {
17142 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
17143 }
17144 
17145 static int
dtrace_cpu_setup(cpu_setup_t what,processorid_t cpu)17146 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
17147 {
17148 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17149 	lck_mtx_lock(&dtrace_lock);
17150 
17151 	switch (what) {
17152 	case CPU_CONFIG: {
17153 		dtrace_state_t *state;
17154 		dtrace_optval_t *opt, rs, c;
17155 
17156 		/*
17157 		 * For now, we only allocate a new buffer for anonymous state.
17158 		 */
17159 		if ((state = dtrace_anon.dta_state) == NULL)
17160 			break;
17161 
17162 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
17163 			break;
17164 
17165 		opt = state->dts_options;
17166 		c = opt[DTRACEOPT_CPU];
17167 
17168 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
17169 			break;
17170 
17171 		/*
17172 		 * Regardless of what the actual policy is, we're going to
17173 		 * temporarily set our resize policy to be manual.  We're
17174 		 * also going to temporarily set our CPU option to denote
17175 		 * the newly configured CPU.
17176 		 */
17177 		rs = opt[DTRACEOPT_BUFRESIZE];
17178 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
17179 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
17180 
17181 		(void) dtrace_state_buffers(state);
17182 
17183 		opt[DTRACEOPT_BUFRESIZE] = rs;
17184 		opt[DTRACEOPT_CPU] = c;
17185 
17186 		break;
17187 	}
17188 
17189 	case CPU_UNCONFIG:
17190 		/*
17191 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
17192 		 * buffer will be freed when the consumer exits.)
17193 		 */
17194 		break;
17195 
17196 	default:
17197 		break;
17198 	}
17199 
17200 	lck_mtx_unlock(&dtrace_lock);
17201 	return (0);
17202 }
17203 
17204 static void
dtrace_cpu_setup_initial(processorid_t cpu)17205 dtrace_cpu_setup_initial(processorid_t cpu)
17206 {
17207 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
17208 }
17209 
17210 static void
dtrace_toxrange_add(uintptr_t base,uintptr_t limit)17211 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
17212 {
17213 	if (dtrace_toxranges >= dtrace_toxranges_max) {
17214 		int osize, nsize;
17215 		dtrace_toxrange_t *range;
17216 
17217 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17218 
17219 		if (osize == 0) {
17220 			ASSERT(dtrace_toxrange == NULL);
17221 			ASSERT(dtrace_toxranges_max == 0);
17222 			dtrace_toxranges_max = 1;
17223 		} else {
17224 			dtrace_toxranges_max <<= 1;
17225 		}
17226 
17227 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17228 		range = kmem_zalloc(nsize, KM_SLEEP);
17229 
17230 		if (dtrace_toxrange != NULL) {
17231 			ASSERT(osize != 0);
17232 			bcopy(dtrace_toxrange, range, osize);
17233 			kmem_free(dtrace_toxrange, osize);
17234 		}
17235 
17236 		dtrace_toxrange = range;
17237 	}
17238 
17239 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17240 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17241 
17242 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17243 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17244 	dtrace_toxranges++;
17245 }
17246 
17247 /*
17248  * DTrace Driver Cookbook Functions
17249  */
17250 /*ARGSUSED*/
17251 static int
dtrace_attach(dev_info_t * devi)17252 dtrace_attach(dev_info_t *devi)
17253 {
17254 	dtrace_provider_id_t id;
17255 	dtrace_state_t *state = NULL;
17256 	dtrace_enabling_t *enab;
17257 
17258 	lck_mtx_lock(&cpu_lock);
17259 	lck_mtx_lock(&dtrace_provider_lock);
17260 	lck_mtx_lock(&dtrace_lock);
17261 
17262 	/* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
17263 	dtrace_devi = devi;
17264 
17265 	dtrace_modload = dtrace_module_loaded;
17266 	dtrace_modunload = dtrace_module_unloaded;
17267 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17268 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17269 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17270 	dtrace_cpustart_init = dtrace_suspend;
17271 	dtrace_cpustart_fini = dtrace_resume;
17272 	dtrace_debugger_init = dtrace_suspend;
17273 	dtrace_debugger_fini = dtrace_resume;
17274 
17275 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17276 
17277 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17278 
17279 	dtrace_arena = vmem_create("dtrace", (void *)1, INT32_MAX, 1,
17280 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17281 
17282 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17283 
17284 	dtrace_nprobes = dtrace_nprobes_default;
17285 	dtrace_probes = kmem_zalloc(sizeof(dtrace_probe_t*) * dtrace_nprobes,
17286 	    KM_SLEEP);
17287 
17288 	dtrace_byprov = dtrace_hash_create(dtrace_strkey_probe_provider,
17289 	    0, /* unused */
17290 	    offsetof(dtrace_probe_t, dtpr_nextprov),
17291 	    offsetof(dtrace_probe_t, dtpr_prevprov));
17292 
17293 	dtrace_bymod = dtrace_hash_create(dtrace_strkey_deref_offset,
17294 	    offsetof(dtrace_probe_t, dtpr_mod),
17295 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17296 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17297 
17298 	dtrace_byfunc = dtrace_hash_create(dtrace_strkey_deref_offset,
17299 	    offsetof(dtrace_probe_t, dtpr_func),
17300 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17301 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17302 
17303 	dtrace_byname = dtrace_hash_create(dtrace_strkey_deref_offset,
17304 	    offsetof(dtrace_probe_t, dtpr_name),
17305 	    offsetof(dtrace_probe_t, dtpr_nextname),
17306 	    offsetof(dtrace_probe_t, dtpr_prevname));
17307 
17308 	if (dtrace_retain_max < 1) {
17309 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
17310 		    "setting to 1", dtrace_retain_max);
17311 		dtrace_retain_max = 1;
17312 	}
17313 
17314 	/*
17315 	 * Now discover our toxic ranges.
17316 	 */
17317 	dtrace_toxic_ranges(dtrace_toxrange_add);
17318 
17319 	/*
17320 	 * Before we register ourselves as a provider to our own framework,
17321 	 * we would like to assert that dtrace_provider is NULL -- but that's
17322 	 * not true if we were loaded as a dependency of a DTrace provider.
17323 	 * Once we've registered, we can assert that dtrace_provider is our
17324 	 * pseudo provider.
17325 	 */
17326 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17327 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17328 
17329 	ASSERT(dtrace_provider != NULL);
17330 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17331 
17332 #if defined (__x86_64__)
17333 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17334 	    dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
17335 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17336 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17337 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17338 	    dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
17339 #elif (defined(__arm__) || defined(__arm64__))
17340 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17341 	    dtrace_provider, NULL, NULL, "BEGIN", 2, NULL);
17342 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17343 	    dtrace_provider, NULL, NULL, "END", 1, NULL);
17344 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17345 	    dtrace_provider, NULL, NULL, "ERROR", 4, NULL);
17346 #else
17347 #error Unknown Architecture
17348 #endif
17349 
17350 	dtrace_anon_property();
17351 	lck_mtx_unlock(&cpu_lock);
17352 
17353 	/*
17354 	 * If DTrace helper tracing is enabled, we need to allocate the
17355 	 * trace buffer and initialize the values.
17356 	 */
17357 	if (dtrace_helptrace_enabled) {
17358 		ASSERT(dtrace_helptrace_buffer == NULL);
17359 		dtrace_helptrace_buffer =
17360 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17361 		dtrace_helptrace_next = 0;
17362 	}
17363 
17364 	/*
17365 	 * If there are already providers, we must ask them to provide their
17366 	 * probes, and then match any anonymous enabling against them.  Note
17367 	 * that there should be no other retained enablings at this time:
17368 	 * the only retained enablings at this time should be the anonymous
17369 	 * enabling.
17370 	 */
17371 	if (dtrace_anon.dta_enabling != NULL) {
17372 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17373 
17374 		/*
17375 		 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
17376 		 */
17377 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17378 			dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17379 		}
17380 
17381 		dtrace_enabling_provide(NULL);
17382 		state = dtrace_anon.dta_state;
17383 
17384 		/*
17385 		 * We couldn't hold cpu_lock across the above call to
17386 		 * dtrace_enabling_provide(), but we must hold it to actually
17387 		 * enable the probes.  We have to drop all of our locks, pick
17388 		 * up cpu_lock, and regain our locks before matching the
17389 		 * retained anonymous enabling.
17390 		 */
17391 		lck_mtx_unlock(&dtrace_lock);
17392 		lck_mtx_unlock(&dtrace_provider_lock);
17393 
17394 		lck_mtx_lock(&cpu_lock);
17395 		lck_mtx_lock(&dtrace_provider_lock);
17396 		lck_mtx_lock(&dtrace_lock);
17397 
17398 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17399 			(void) dtrace_enabling_match(enab, NULL, NULL);
17400 
17401 		lck_mtx_unlock(&cpu_lock);
17402 	}
17403 
17404 	lck_mtx_unlock(&dtrace_lock);
17405 	lck_mtx_unlock(&dtrace_provider_lock);
17406 
17407 	if (state != NULL) {
17408 		/*
17409 		 * If we created any anonymous state, set it going now.
17410 		 */
17411 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17412 	}
17413 
17414 	return (DDI_SUCCESS);
17415 }
17416 
17417 /*ARGSUSED*/
17418 static int
dtrace_open(dev_t * devp,int flag,int otyp,cred_t * cred_p)17419 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17420 {
17421 #pragma unused(flag, otyp)
17422 	dtrace_state_t *state;
17423 	uint32_t priv;
17424 	uid_t uid;
17425 	zoneid_t zoneid;
17426 	int rv;
17427 
17428 	/* APPLE: Darwin puts Helper on its own major device. */
17429 
17430 	/*
17431 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17432 	 * caller lacks sufficient permission to do anything with DTrace.
17433 	 */
17434 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17435 	if (priv == DTRACE_PRIV_NONE)
17436 		return (EACCES);
17437 
17438 	/*
17439 	 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
17440 	 * It certainly can't be later than now!
17441 	 */
17442 	fasttrap_init();
17443 
17444 	/*
17445 	 * Ask all providers to provide all their probes.
17446 	 */
17447 	lck_mtx_lock(&dtrace_provider_lock);
17448 	dtrace_probe_provide(NULL, NULL);
17449 	lck_mtx_unlock(&dtrace_provider_lock);
17450 
17451 	lck_mtx_lock(&cpu_lock);
17452 	lck_mtx_lock(&dtrace_lock);
17453 	dtrace_opens++;
17454 	dtrace_membar_producer();
17455 
17456 #ifdef illumos
17457 	/*
17458 	 * If the kernel debugger is active (that is, if the kernel debugger
17459 	 * modified text in some way), we won't allow the open.
17460 	 */
17461 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17462 		dtrace_opens--;
17463 		lck_mtx_unlock(&dtrace_lock);
17464 		lck_mtx_unlock(&cpu_lock);
17465 		return (EBUSY);
17466 	}
17467 #endif
17468 
17469 	rv = dtrace_state_create(devp, cred_p, &state);
17470 	lck_mtx_unlock(&cpu_lock);
17471 
17472 	if (rv != 0 || state == NULL) {
17473 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL) {
17474 #ifdef illumos
17475 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17476 #endif
17477 		}
17478 		lck_mtx_unlock(&dtrace_lock);
17479 		/* propagate EAGAIN or ERESTART */
17480 		return (rv);
17481 	}
17482 
17483 	lck_mtx_unlock(&dtrace_lock);
17484 
17485 	lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17486 
17487 	/*
17488 	 * If we are currently lazy, transition states.
17489 	 *
17490 	 * Unlike dtrace_close, we do not need to check the
17491 	 * value of dtrace_opens, as any positive value (and
17492 	 * we count as 1) means we transition states.
17493 	 */
17494 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
17495 		dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
17496 		/*
17497 		 * We do not need to hold the exclusive lock while processing
17498 		 * DOF on processes. We do need to make sure the mode does not get
17499 		 * changed to DTRACE_DOF_MODE_LAZY_ON during that stage though
17500 		 * (which should not happen anyway since it only happens in
17501 		 * dtrace_close). There is no way imcomplete USDT probes can be
17502 		 * activate by any DTrace clients here since they all have to
17503 		 * call dtrace_open and be blocked on dtrace_dof_mode_lock
17504 		 */
17505 		lck_rw_lock_exclusive_to_shared(&dtrace_dof_mode_lock);
17506 		/*
17507 		 * Iterate all existing processes and load lazy dofs.
17508 		 */
17509 		proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
17510 			     dtrace_lazy_dofs_proc_iterate_doit,
17511 			     NULL,
17512 			     dtrace_lazy_dofs_proc_iterate_filter,
17513 			     NULL);
17514 
17515 		lck_rw_unlock_shared(&dtrace_dof_mode_lock);
17516 	}
17517 	else {
17518 		lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17519 	}
17520 
17521 
17522 	/*
17523 	 * Update kernel symbol state.
17524 	 *
17525 	 * We must own the provider and dtrace locks.
17526 	 *
17527 	 * NOTE! It may appear there is a race by setting this value so late
17528 	 * after dtrace_probe_provide. However, any kext loaded after the
17529 	 * call to probe provide and before we set LAZY_OFF will be marked as
17530 	 * eligible for symbols from userspace. The same dtrace that is currently
17531 	 * calling dtrace_open() (this call!) will get a list of kexts needing
17532 	 * symbols and fill them in, thus closing the race window.
17533 	 *
17534 	 * We want to set this value only after it certain it will succeed, as
17535 	 * this significantly reduces the complexity of error exits.
17536 	 */
17537 	lck_mtx_lock(&dtrace_lock);
17538 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17539 		dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17540 	}
17541 	lck_mtx_unlock(&dtrace_lock);
17542 
17543 	return (0);
17544 }
17545 
17546 /*ARGSUSED*/
17547 static int
dtrace_close(dev_t dev,int flag,int otyp,cred_t * cred_p)17548 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17549 {
17550 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
17551 	minor_t minor = getminor(dev);
17552 	dtrace_state_t *state;
17553 
17554 	/* APPLE NOTE: Darwin puts Helper on its own major device. */
17555 	state = dtrace_state_get(minor);
17556 
17557 	lck_mtx_lock(&cpu_lock);
17558 	lck_mtx_lock(&dtrace_lock);
17559 
17560 	if (state->dts_anon) {
17561 		/*
17562 		 * There is anonymous state. Destroy that first.
17563 		 */
17564 		ASSERT(dtrace_anon.dta_state == NULL);
17565 		dtrace_state_destroy(state->dts_anon);
17566 	}
17567 
17568 	dtrace_state_destroy(state);
17569 	ASSERT(dtrace_opens > 0);
17570 
17571 	/*
17572 	 * Only relinquish control of the kernel debugger interface when there
17573 	 * are no consumers and no anonymous enablings.
17574 	 */
17575 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL) {
17576 #ifdef illumos
17577 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17578 #endif
17579 	}
17580 
17581 	lck_mtx_unlock(&dtrace_lock);
17582 	lck_mtx_unlock(&cpu_lock);
17583 
17584 	/*
17585 	 * Lock ordering requires the dof mode lock be taken before
17586 	 * the dtrace_lock.
17587 	 */
17588 	lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17589 	lck_mtx_lock(&dtrace_lock);
17590 
17591 	if (dtrace_opens == 0) {
17592 		/*
17593 		 * If we are currently lazy-off, and this is the last close, transition to
17594 		 * lazy state.
17595 		 */
17596 		if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
17597 			dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
17598 		}
17599 
17600 		/*
17601 		 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
17602 		 */
17603 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
17604 			dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
17605 		}
17606 	}
17607 
17608 	lck_mtx_unlock(&dtrace_lock);
17609 	lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17610 
17611 	/*
17612 	 * Kext probes may be retained past the end of the kext's lifespan. The
17613 	 * probes are kept until the last reference to them has been removed.
17614 	 * Since closing an active dtrace context is likely to drop that last reference,
17615 	 * lets take a shot at cleaning out the orphaned probes now.
17616 	 */
17617 	dtrace_module_unloaded(NULL);
17618 
17619 	return (0);
17620 }
17621 
17622 /*ARGSUSED*/
17623 static int
dtrace_ioctl_helper(u_long cmd,caddr_t arg,int * rv)17624 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
17625 {
17626 #pragma unused(rv)
17627 	/*
17628 	 * Safe to check this outside the dof mode lock
17629 	 */
17630 	if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
17631 		return KERN_SUCCESS;
17632 
17633 	switch (cmd) {
17634 #if defined (__arm64__)
17635 	case DTRACEHIOC_ADDDOF_U32:
17636 	case DTRACEHIOC_ADDDOF_U64:
17637 #else
17638 	case DTRACEHIOC_ADDDOF:
17639 #endif /* __arm64__*/
17640 	                {
17641 			dof_helper_t *dhp = NULL;
17642 			size_t dof_ioctl_data_size;
17643 			dof_ioctl_data_t* multi_dof;
17644 			unsigned int i;
17645 			int rval = 0;
17646 			user_addr_t user_address = *(user_addr_t*)arg;
17647 			uint64_t dof_count;
17648 			int multi_dof_claimed = 0;
17649 			proc_t* p = current_proc();
17650 
17651 			/*
17652 			 * If this is a restricted process and dtrace is restricted,
17653 			 * do not allow DOFs to be registered
17654 			 */
17655 			if (dtrace_is_restricted() &&
17656 				!dtrace_are_restrictions_relaxed() &&
17657 				!dtrace_can_attach_to_proc(current_proc())) {
17658 				return (EACCES);
17659 			}
17660 
17661 			/*
17662 			 * Read the number of DOF sections being passed in.
17663 			 */
17664 			if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
17665 				   &dof_count,
17666 				   sizeof(dof_count))) {
17667 				dtrace_dof_error(NULL, "failed to copyin dofiod_count");
17668 				return (EFAULT);
17669 			}
17670 
17671 			/*
17672 			 * Range check the count.
17673 			 */
17674 			if (dof_count == 0 || dof_count > 1024) {
17675 				dtrace_dof_error(NULL, "dofiod_count is not valid");
17676 				return (EINVAL);
17677 			}
17678 
17679 			/*
17680 			 * Allocate a correctly sized structure and copyin the data.
17681 			 */
17682 			dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
17683 			if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
17684 				return (ENOMEM);
17685 
17686 			/* NOTE! We can no longer exit this method via return */
17687 			if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
17688 				dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
17689 				rval = EFAULT;
17690 				goto cleanup;
17691 			}
17692 
17693 			/*
17694 			 * Check that the count didn't change between the first copyin and the second.
17695 			 */
17696 			if (multi_dof->dofiod_count != dof_count) {
17697 				rval = EINVAL;
17698 				goto cleanup;
17699 			}
17700 
17701 			/*
17702 			 * Try to process lazily first.
17703 			 */
17704 			rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
17705 
17706 			/*
17707 			 * If rval is EACCES, we must be non-lazy.
17708 			 */
17709 			if (rval == EACCES) {
17710 				rval = 0;
17711 				/*
17712 				 * Process each dof_helper_t
17713 				 */
17714 				i = 0;
17715 				do {
17716 					dhp = &multi_dof->dofiod_helpers[i];
17717 
17718 					dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
17719 
17720 					if (dof != NULL) {
17721 						lck_mtx_lock(&dtrace_meta_lock);
17722 						lck_mtx_lock(&dtrace_lock);
17723 
17724 						/*
17725 						 * dtrace_helper_slurp() takes responsibility for the dof --
17726 						 * it may free it now or it may save it and free it later.
17727 						 */
17728 						if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
17729 							rval = EINVAL;
17730 						}
17731 
17732 						lck_mtx_unlock(&dtrace_lock);
17733 						lck_mtx_unlock(&dtrace_meta_lock);
17734 					}
17735 				} while (++i < multi_dof->dofiod_count && rval == 0);
17736 			}
17737 
17738 			/*
17739 			 * We need to copyout the multi_dof struct, because it contains
17740 			 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
17741 			 *
17742 			 * This could certainly be better optimized.
17743 			 */
17744 			if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
17745 				dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
17746 				/* Don't overwrite pre-existing error code */
17747 				if (rval == 0) rval = EFAULT;
17748 			}
17749 
17750 		cleanup:
17751 			/*
17752 			 * If we had to allocate struct memory, free it.
17753 			 */
17754 			if (multi_dof != NULL && !multi_dof_claimed) {
17755 				kmem_free(multi_dof, dof_ioctl_data_size);
17756 			}
17757 
17758 			return rval;
17759 		}
17760 
17761 		case DTRACEHIOC_REMOVE: {
17762 			int generation = *(int*)arg;
17763 			proc_t* p = current_proc();
17764 
17765 			/*
17766 			 * Try lazy first.
17767 			 */
17768 			int rval = dtrace_lazy_dofs_remove(p, generation);
17769 
17770 			/*
17771 			 * EACCES means non-lazy
17772 			 */
17773 			if (rval == EACCES) {
17774 				lck_mtx_lock(&dtrace_meta_lock);
17775 				lck_mtx_lock(&dtrace_lock);
17776 				rval = dtrace_helper_destroygen(p, generation);
17777 				lck_mtx_unlock(&dtrace_lock);
17778 				lck_mtx_unlock(&dtrace_meta_lock);
17779 			}
17780 
17781 			return (rval);
17782 		}
17783 
17784 		default:
17785 			break;
17786 	}
17787 
17788 	return ENOTTY;
17789 }
17790 
17791 /*ARGSUSED*/
17792 static int
dtrace_ioctl(dev_t dev,u_long cmd,user_addr_t arg,int md,cred_t * cr,int * rv)17793 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
17794 {
17795 #pragma unused(md)
17796 	minor_t minor = getminor(dev);
17797 	dtrace_state_t *state;
17798 	int rval;
17799 
17800 	/* Darwin puts Helper on its own major device. */
17801 
17802 	state = dtrace_state_get(minor);
17803 
17804 	if (state->dts_anon) {
17805 	   ASSERT(dtrace_anon.dta_state == NULL);
17806 	   state = state->dts_anon;
17807 	}
17808 
17809 	switch (cmd) {
17810 	case DTRACEIOC_PROVIDER: {
17811 		dtrace_providerdesc_t pvd;
17812 		dtrace_provider_t *pvp;
17813 
17814 		if (copyin(arg, &pvd, sizeof (pvd)) != 0)
17815 			return (EFAULT);
17816 
17817 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17818 		lck_mtx_lock(&dtrace_provider_lock);
17819 
17820 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17821 			if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
17822 				break;
17823 		}
17824 
17825 		lck_mtx_unlock(&dtrace_provider_lock);
17826 
17827 		if (pvp == NULL)
17828 			return (ESRCH);
17829 
17830 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17831 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17832 		if (copyout(&pvd, arg, sizeof (pvd)) != 0)
17833 			return (EFAULT);
17834 
17835 		return (0);
17836 	}
17837 
17838 	case DTRACEIOC_EPROBE: {
17839 		dtrace_eprobedesc_t epdesc;
17840 		dtrace_ecb_t *ecb;
17841 		dtrace_action_t *act;
17842 		void *buf;
17843 		size_t size;
17844 		uintptr_t dest;
17845 		int nrecs;
17846 
17847 		if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
17848 			return (EFAULT);
17849 
17850 		lck_mtx_lock(&dtrace_lock);
17851 
17852 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17853 			lck_mtx_unlock(&dtrace_lock);
17854 			return (EINVAL);
17855 		}
17856 
17857 		if (ecb->dte_probe == NULL) {
17858 			lck_mtx_unlock(&dtrace_lock);
17859 			return (EINVAL);
17860 		}
17861 
17862 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17863 		epdesc.dtepd_uarg = ecb->dte_uarg;
17864 		epdesc.dtepd_size = ecb->dte_size;
17865 
17866 		nrecs = epdesc.dtepd_nrecs;
17867 		epdesc.dtepd_nrecs = 0;
17868 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17869 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17870 				continue;
17871 
17872 			epdesc.dtepd_nrecs++;
17873 		}
17874 
17875 		/*
17876 		 * Now that we have the size, we need to allocate a temporary
17877 		 * buffer in which to store the complete description.  We need
17878 		 * the temporary buffer to be able to drop dtrace_lock()
17879 		 * across the copyout(), below.
17880 		 */
17881 		size = sizeof (dtrace_eprobedesc_t) +
17882 			(epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17883 
17884 		buf = kmem_alloc(size, KM_SLEEP);
17885 		dest = (uintptr_t)buf;
17886 
17887 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17888 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17889 
17890 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17891 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17892 				continue;
17893 
17894 			if (nrecs-- == 0)
17895 				break;
17896 
17897 			bcopy(&act->dta_rec, (void *)dest,
17898 			sizeof (dtrace_recdesc_t));
17899 			dest += sizeof (dtrace_recdesc_t);
17900 		}
17901 
17902 		lck_mtx_unlock(&dtrace_lock);
17903 
17904 		if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
17905 			kmem_free(buf, size);
17906 			return (EFAULT);
17907 		}
17908 
17909 		kmem_free(buf, size);
17910 		return (0);
17911 	}
17912 
17913 	case DTRACEIOC_AGGDESC: {
17914 		dtrace_aggdesc_t aggdesc;
17915 		dtrace_action_t *act;
17916 		dtrace_aggregation_t *agg;
17917 		int nrecs;
17918 		uint32_t offs;
17919 		dtrace_recdesc_t *lrec;
17920 		void *buf;
17921 		size_t size;
17922 		uintptr_t dest;
17923 
17924 		if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
17925 			return (EFAULT);
17926 
17927 		lck_mtx_lock(&dtrace_lock);
17928 
17929 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17930 			lck_mtx_unlock(&dtrace_lock);
17931 			return (EINVAL);
17932 		}
17933 
17934 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17935 
17936 		nrecs = aggdesc.dtagd_nrecs;
17937 		aggdesc.dtagd_nrecs = 0;
17938 
17939 		offs = agg->dtag_base;
17940 		lrec = &agg->dtag_action.dta_rec;
17941 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17942 
17943 		for (act = agg->dtag_first; ; act = act->dta_next) {
17944 			ASSERT(act->dta_intuple ||
17945 			DTRACEACT_ISAGG(act->dta_kind));
17946 
17947 			/*
17948 			 * If this action has a record size of zero, it
17949 			 * denotes an argument to the aggregating action.
17950 			 * Because the presence of this record doesn't (or
17951 			 * shouldn't) affect the way the data is interpreted,
17952 			 * we don't copy it out to save user-level the
17953 			 * confusion of dealing with a zero-length record.
17954 			 */
17955 			if (act->dta_rec.dtrd_size == 0) {
17956 				ASSERT(agg->dtag_hasarg);
17957 				continue;
17958 			}
17959 
17960 			aggdesc.dtagd_nrecs++;
17961 
17962 			if (act == &agg->dtag_action)
17963 				break;
17964 		}
17965 
17966 		/*
17967 		 * Now that we have the size, we need to allocate a temporary
17968 		 * buffer in which to store the complete description.  We need
17969 		 * the temporary buffer to be able to drop dtrace_lock()
17970 		 * across the copyout(), below.
17971 		 */
17972 		size = sizeof (dtrace_aggdesc_t) +
17973 			(aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17974 
17975 		buf = kmem_alloc(size, KM_SLEEP);
17976 		dest = (uintptr_t)buf;
17977 
17978 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17979 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17980 
17981 		for (act = agg->dtag_first; ; act = act->dta_next) {
17982 			dtrace_recdesc_t rec = act->dta_rec;
17983 
17984 			/*
17985 			 * See the comment in the above loop for why we pass
17986 			 * over zero-length records.
17987 			 */
17988 			if (rec.dtrd_size == 0) {
17989 				ASSERT(agg->dtag_hasarg);
17990 				continue;
17991 			}
17992 
17993 			if (nrecs-- == 0)
17994 				break;
17995 
17996 			rec.dtrd_offset -= offs;
17997 			bcopy(&rec, (void *)dest, sizeof (rec));
17998 			dest += sizeof (dtrace_recdesc_t);
17999 
18000 			if (act == &agg->dtag_action)
18001 				break;
18002 		}
18003 
18004 		lck_mtx_unlock(&dtrace_lock);
18005 
18006 		if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
18007 			kmem_free(buf, size);
18008 			return (EFAULT);
18009 		}
18010 
18011 		kmem_free(buf, size);
18012 		return (0);
18013 	}
18014 
18015 	case DTRACEIOC_ENABLE: {
18016 		dof_hdr_t *dof;
18017 		dtrace_enabling_t *enab = NULL;
18018 		dtrace_vstate_t *vstate;
18019 		int err = 0;
18020 
18021 		*rv = 0;
18022 
18023 		/*
18024 		 * If a NULL argument has been passed, we take this as our
18025 		 * cue to reevaluate our enablings.
18026 		 */
18027 		if (arg == 0) {
18028 			dtrace_enabling_matchall();
18029 
18030 			return (0);
18031 		}
18032 
18033 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
18034 			return (rval);
18035 
18036 		lck_mtx_lock(&cpu_lock);
18037 		lck_mtx_lock(&dtrace_lock);
18038 		vstate = &state->dts_vstate;
18039 
18040 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
18041 			lck_mtx_unlock(&dtrace_lock);
18042 			lck_mtx_unlock(&cpu_lock);
18043 			dtrace_dof_destroy(dof);
18044 			return (EBUSY);
18045 		}
18046 
18047 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
18048 			lck_mtx_unlock(&dtrace_lock);
18049 			lck_mtx_unlock(&cpu_lock);
18050 			dtrace_dof_destroy(dof);
18051 			return (EINVAL);
18052 		}
18053 
18054 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
18055 			dtrace_enabling_destroy(enab);
18056 			lck_mtx_unlock(&dtrace_lock);
18057 			lck_mtx_unlock(&cpu_lock);
18058 			dtrace_dof_destroy(dof);
18059 			return (rval);
18060 		}
18061 
18062 		if ((err = dtrace_enabling_match(enab, rv, NULL)) == 0) {
18063 			err = dtrace_enabling_retain(enab);
18064 		} else {
18065 			dtrace_enabling_destroy(enab);
18066 		}
18067 
18068 		lck_mtx_unlock(&dtrace_lock);
18069 		lck_mtx_unlock(&cpu_lock);
18070 		dtrace_dof_destroy(dof);
18071 
18072 		return (err);
18073 	}
18074 
18075 	case DTRACEIOC_REPLICATE: {
18076 		dtrace_repldesc_t desc;
18077 		dtrace_probedesc_t *match = &desc.dtrpd_match;
18078 		dtrace_probedesc_t *create = &desc.dtrpd_create;
18079 		int err;
18080 
18081 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18082 			return (EFAULT);
18083 
18084 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18085 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18086 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18087 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18088 
18089 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18090 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18091 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18092 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18093 
18094 		lck_mtx_lock(&dtrace_lock);
18095 		err = dtrace_enabling_replicate(state, match, create);
18096 		lck_mtx_unlock(&dtrace_lock);
18097 
18098 		return (err);
18099 	}
18100 
18101 	case DTRACEIOC_PROBEMATCH:
18102 	case DTRACEIOC_PROBES: {
18103 		dtrace_probe_t *probe = NULL;
18104 		dtrace_probedesc_t desc;
18105 		dtrace_probekey_t pkey;
18106 		dtrace_id_t i;
18107 		int m = 0;
18108 		uint32_t priv;
18109 		uid_t uid;
18110 		zoneid_t zoneid;
18111 
18112 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18113 			return (EFAULT);
18114 
18115 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18116 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18117 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18118 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18119 
18120 		/*
18121 		 * Before we attempt to match this probe, we want to give
18122 		 * all providers the opportunity to provide it.
18123 		 */
18124 		if (desc.dtpd_id == DTRACE_IDNONE) {
18125 			lck_mtx_lock(&dtrace_provider_lock);
18126 			dtrace_probe_provide(&desc, NULL);
18127 			lck_mtx_unlock(&dtrace_provider_lock);
18128 			desc.dtpd_id++;
18129 		}
18130 
18131 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
18132 
18133 		lck_mtx_lock(&dtrace_lock);
18134 
18135 		if (cmd == DTRACEIOC_PROBEMATCH)  {
18136 			dtrace_probekey(&desc, &pkey);
18137 			pkey.dtpk_id = DTRACE_IDNONE;
18138 
18139 			/* Quiet compiler warning */
18140 			for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18141 				if ((probe = dtrace_probes[i - 1]) != NULL &&
18142 					(m = dtrace_match_probe(probe, &pkey,
18143 					priv, uid, zoneid)) != 0)
18144 					break;
18145 			}
18146 
18147 			if (m < 0) {
18148 				lck_mtx_unlock(&dtrace_lock);
18149 				return (EINVAL);
18150 			}
18151 			dtrace_probekey_release(&pkey);
18152 
18153 		} else {
18154                         /* Quiet compiler warning */
18155 			for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18156 				if ((probe = dtrace_probes[i - 1]) != NULL &&
18157 					dtrace_match_priv(probe, priv, uid, zoneid))
18158 					break;
18159 			}
18160 		}
18161 
18162 		if (probe == NULL) {
18163 			lck_mtx_unlock(&dtrace_lock);
18164 			return (ESRCH);
18165 		}
18166 
18167 		dtrace_probe_description(probe, &desc);
18168 		lck_mtx_unlock(&dtrace_lock);
18169 
18170 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18171 			return (EFAULT);
18172 
18173 		return (0);
18174 	}
18175 
18176 	case DTRACEIOC_PROBEARG: {
18177 		dtrace_argdesc_t desc;
18178 		dtrace_probe_t *probe;
18179 		dtrace_provider_t *prov;
18180 
18181 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18182 			return (EFAULT);
18183 
18184 		if (desc.dtargd_id == DTRACE_IDNONE)
18185 			return (EINVAL);
18186 
18187 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
18188 			return (EINVAL);
18189 
18190 		lck_mtx_lock(&dtrace_provider_lock);
18191 		lck_mtx_lock(&mod_lock);
18192 		lck_mtx_lock(&dtrace_lock);
18193 
18194                 /* Quiet compiler warning */
18195 		if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
18196 			lck_mtx_unlock(&dtrace_lock);
18197 			lck_mtx_unlock(&mod_lock);
18198 			lck_mtx_unlock(&dtrace_provider_lock);
18199 			return (EINVAL);
18200 		}
18201 
18202 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
18203 			lck_mtx_unlock(&dtrace_lock);
18204 			lck_mtx_unlock(&mod_lock);
18205 			lck_mtx_unlock(&dtrace_provider_lock);
18206 			return (EINVAL);
18207 		}
18208 
18209 		lck_mtx_unlock(&dtrace_lock);
18210 
18211 		prov = probe->dtpr_provider;
18212 
18213 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
18214 		/*
18215 		 * There isn't any typed information for this probe.
18216 		 * Set the argument number to DTRACE_ARGNONE.
18217 		 */
18218 			desc.dtargd_ndx = DTRACE_ARGNONE;
18219 		} else {
18220 			desc.dtargd_native[0] = '\0';
18221 			desc.dtargd_xlate[0] = '\0';
18222 			desc.dtargd_mapping = desc.dtargd_ndx;
18223 
18224 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
18225 			probe->dtpr_id, probe->dtpr_arg, &desc);
18226 		}
18227 
18228 		lck_mtx_unlock(&mod_lock);
18229 		lck_mtx_unlock(&dtrace_provider_lock);
18230 
18231 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18232 			return (EFAULT);
18233 
18234 		return (0);
18235 	}
18236 
18237 	case DTRACEIOC_GO: {
18238 		processorid_t cpuid;
18239 		rval = dtrace_state_go(state, &cpuid);
18240 
18241 		if (rval != 0)
18242 			return (rval);
18243 
18244 		if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18245 			return (EFAULT);
18246 
18247 		return (0);
18248 	}
18249 
18250 	case DTRACEIOC_STOP: {
18251 		processorid_t cpuid;
18252 
18253 		lck_mtx_lock(&dtrace_lock);
18254 		rval = dtrace_state_stop(state, &cpuid);
18255 		lck_mtx_unlock(&dtrace_lock);
18256 
18257 		if (rval != 0)
18258 			return (rval);
18259 
18260 		if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18261 			return (EFAULT);
18262 
18263 		return (0);
18264 	}
18265 
18266 	case DTRACEIOC_DOFGET: {
18267 		dof_hdr_t hdr, *dof;
18268 		uint64_t len;
18269 
18270 		if (copyin(arg, &hdr, sizeof (hdr)) != 0)
18271 			return (EFAULT);
18272 
18273 		lck_mtx_lock(&dtrace_lock);
18274 		dof = dtrace_dof_create(state);
18275 		lck_mtx_unlock(&dtrace_lock);
18276 
18277 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
18278 		rval = copyout(dof, arg, len);
18279 		dtrace_dof_destroy(dof);
18280 
18281 		return (rval == 0 ? 0 : EFAULT);
18282 	}
18283 
18284 	case DTRACEIOC_SLEEP: {
18285 		int64_t time;
18286 		uint64_t abstime;
18287 		uint64_t rvalue = DTRACE_WAKE_TIMEOUT;
18288 
18289 		if (copyin(arg, &time, sizeof(time)) != 0)
18290 			return (EFAULT);
18291 
18292 		nanoseconds_to_absolutetime((uint64_t)time, &abstime);
18293 		clock_absolutetime_interval_to_deadline(abstime, &abstime);
18294 
18295 		if (assert_wait_deadline(state, THREAD_ABORTSAFE, abstime) == THREAD_WAITING) {
18296 			if (state->dts_buf_over_limit > 0) {
18297 				clear_wait(current_thread(), THREAD_INTERRUPTED);
18298 				rvalue = DTRACE_WAKE_BUF_LIMIT;
18299 			} else {
18300 				thread_block(THREAD_CONTINUE_NULL);
18301 				if (state->dts_buf_over_limit > 0) {
18302 					rvalue = DTRACE_WAKE_BUF_LIMIT;
18303 				}
18304 			}
18305 		}
18306 
18307 		if (copyout(&rvalue, arg, sizeof(rvalue)) != 0)
18308 			return (EFAULT);
18309 
18310 		return (0);
18311 	}
18312 
18313 	case DTRACEIOC_SIGNAL: {
18314 		wakeup(state);
18315 		return (0);
18316 	}
18317 
18318 	case DTRACEIOC_AGGSNAP:
18319 	case DTRACEIOC_BUFSNAP: {
18320 		dtrace_bufdesc_t desc;
18321 		caddr_t cached;
18322 		boolean_t over_limit;
18323 		dtrace_buffer_t *buf;
18324 
18325 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18326 			return (EFAULT);
18327 
18328 		if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
18329 			return (EINVAL);
18330 
18331 		lck_mtx_lock(&dtrace_lock);
18332 
18333 		if (cmd == DTRACEIOC_BUFSNAP) {
18334 			buf = &state->dts_buffer[desc.dtbd_cpu];
18335 		} else {
18336 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
18337 		}
18338 
18339 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
18340 			size_t sz = buf->dtb_offset;
18341 
18342 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
18343 				lck_mtx_unlock(&dtrace_lock);
18344 				return (EBUSY);
18345 			}
18346 
18347 			/*
18348 			 * If this buffer has already been consumed, we're
18349 			 * going to indicate that there's nothing left here
18350 			 * to consume.
18351 			 */
18352 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
18353 				lck_mtx_unlock(&dtrace_lock);
18354 
18355 				desc.dtbd_size = 0;
18356 				desc.dtbd_drops = 0;
18357 				desc.dtbd_errors = 0;
18358 				desc.dtbd_oldest = 0;
18359 				sz = sizeof (desc);
18360 
18361 				if (copyout(&desc, arg, sz) != 0)
18362 					return (EFAULT);
18363 
18364 				return (0);
18365 			}
18366 
18367 			/*
18368 			 * If this is a ring buffer that has wrapped, we want
18369 			 * to copy the whole thing out.
18370 			 */
18371 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
18372 				dtrace_buffer_polish(buf);
18373 				sz = buf->dtb_size;
18374 			}
18375 
18376 			if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
18377 				lck_mtx_unlock(&dtrace_lock);
18378 				return (EFAULT);
18379 			}
18380 
18381 			desc.dtbd_size = sz;
18382 			desc.dtbd_drops = buf->dtb_drops;
18383 			desc.dtbd_errors = buf->dtb_errors;
18384 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18385 			desc.dtbd_timestamp = dtrace_gethrtime();
18386 
18387 			lck_mtx_unlock(&dtrace_lock);
18388 
18389 			if (copyout(&desc, arg, sizeof (desc)) != 0)
18390 				return (EFAULT);
18391 
18392 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18393 
18394 			return (0);
18395 		}
18396 
18397 		if (buf->dtb_tomax == NULL) {
18398 			ASSERT(buf->dtb_xamot == NULL);
18399 			lck_mtx_unlock(&dtrace_lock);
18400 			return (ENOENT);
18401 		}
18402 
18403 		cached = buf->dtb_tomax;
18404 		over_limit = buf->dtb_cur_limit == buf->dtb_size;
18405 
18406 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18407 
18408 		dtrace_xcall(desc.dtbd_cpu,
18409 			(dtrace_xcall_t)dtrace_buffer_switch, buf);
18410 
18411 		state->dts_errors += buf->dtb_xamot_errors;
18412 
18413 		/*
18414 		* If the buffers did not actually switch, then the cross call
18415 		* did not take place -- presumably because the given CPU is
18416 		* not in the ready set.  If this is the case, we'll return
18417 		* ENOENT.
18418 		*/
18419 		if (buf->dtb_tomax == cached) {
18420 			ASSERT(buf->dtb_xamot != cached);
18421 			lck_mtx_unlock(&dtrace_lock);
18422 			return (ENOENT);
18423 		}
18424 
18425 		ASSERT(cached == buf->dtb_xamot);
18426 		/*
18427 		 * At this point we know the buffer have switched, so we
18428 		 * can decrement the over limit count if the buffer was over
18429 		 * its limit. The new buffer might already be over its limit
18430 		 * yet, but we don't care since we're guaranteed not to be
18431 		 * checking the buffer over limit count  at this point.
18432 		 */
18433 		if (over_limit) {
18434 			uint32_t old = os_atomic_dec_orig(&state->dts_buf_over_limit, relaxed);
18435 			#pragma unused(old)
18436 
18437 			/*
18438 			 * Verify that we didn't underflow the value
18439 			 */
18440 			ASSERT(old != 0);
18441 		}
18442 
18443 		/*
18444 		* We have our snapshot; now copy it out.
18445 		*/
18446 		if (dtrace_buffer_copyout(buf->dtb_xamot,
18447 					(user_addr_t)desc.dtbd_data,
18448 					buf->dtb_xamot_offset) != 0) {
18449 			lck_mtx_unlock(&dtrace_lock);
18450 			return (EFAULT);
18451 		}
18452 
18453 		desc.dtbd_size = buf->dtb_xamot_offset;
18454 		desc.dtbd_drops = buf->dtb_xamot_drops;
18455 		desc.dtbd_errors = buf->dtb_xamot_errors;
18456 		desc.dtbd_oldest = 0;
18457 		desc.dtbd_timestamp = buf->dtb_switched;
18458 
18459 		lck_mtx_unlock(&dtrace_lock);
18460 
18461 		/*
18462 		 * Finally, copy out the buffer description.
18463 		 */
18464 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18465 			return (EFAULT);
18466 
18467 		return (0);
18468 	}
18469 
18470 	case DTRACEIOC_CONF: {
18471 		dtrace_conf_t conf;
18472 
18473 		bzero(&conf, sizeof (conf));
18474 		conf.dtc_difversion = DIF_VERSION;
18475 		conf.dtc_difintregs = DIF_DIR_NREGS;
18476 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18477 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18478 
18479 		if (copyout(&conf, arg, sizeof (conf)) != 0)
18480 			return (EFAULT);
18481 
18482 		return (0);
18483 	}
18484 
18485 	case DTRACEIOC_STATUS: {
18486 		dtrace_status_t stat;
18487 		dtrace_dstate_t *dstate;
18488 		int j;
18489 		uint64_t nerrs;
18490 
18491 		/*
18492 		* See the comment in dtrace_state_deadman() for the reason
18493 		* for setting dts_laststatus to INT64_MAX before setting
18494 		* it to the correct value.
18495 		*/
18496 		state->dts_laststatus = INT64_MAX;
18497 		dtrace_membar_producer();
18498 		state->dts_laststatus = dtrace_gethrtime();
18499 
18500 		bzero(&stat, sizeof (stat));
18501 
18502 		lck_mtx_lock(&dtrace_lock);
18503 
18504 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18505 			lck_mtx_unlock(&dtrace_lock);
18506 			return (ENOENT);
18507 		}
18508 
18509 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18510 			stat.dtst_exiting = 1;
18511 
18512 		nerrs = state->dts_errors;
18513 		dstate = &state->dts_vstate.dtvs_dynvars;
18514 
18515 		zpercpu_foreach_cpu(i) {
18516 			dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, i);
18517 
18518 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18519 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18520 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18521 
18522 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18523 				stat.dtst_filled++;
18524 
18525 			nerrs += state->dts_buffer[i].dtb_errors;
18526 
18527 			for (j = 0; j < state->dts_nspeculations; j++) {
18528 				dtrace_speculation_t *spec;
18529 				dtrace_buffer_t *buf;
18530 
18531 				spec = &state->dts_speculations[j];
18532 				buf = &spec->dtsp_buffer[i];
18533 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18534 			}
18535 		}
18536 
18537 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18538 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18539 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18540 		stat.dtst_dblerrors = state->dts_dblerrors;
18541 		stat.dtst_killed =
18542 			(state->dts_activity == DTRACE_ACTIVITY_KILLED);
18543 		stat.dtst_errors = nerrs;
18544 
18545 		lck_mtx_unlock(&dtrace_lock);
18546 
18547 		if (copyout(&stat, arg, sizeof (stat)) != 0)
18548 			return (EFAULT);
18549 
18550 		return (0);
18551 	}
18552 
18553 	case DTRACEIOC_FORMAT: {
18554 		dtrace_fmtdesc_t fmt;
18555 		char *str;
18556 		int len;
18557 
18558 		if (copyin(arg, &fmt, sizeof (fmt)) != 0)
18559 			return (EFAULT);
18560 
18561 		lck_mtx_lock(&dtrace_lock);
18562 
18563 		if (fmt.dtfd_format == 0 ||
18564 			fmt.dtfd_format > state->dts_nformats) {
18565 			lck_mtx_unlock(&dtrace_lock);
18566 			return (EINVAL);
18567 		}
18568 
18569 		/*
18570 		 * Format strings are allocated contiguously and they are
18571 		 * never freed; if a format index is less than the number
18572 		 * of formats, we can assert that the format map is non-NULL
18573 		 * and that the format for the specified index is non-NULL.
18574 		 */
18575 		ASSERT(state->dts_formats != NULL);
18576 		str = state->dts_formats[fmt.dtfd_format - 1]->dtf_str;
18577 		ASSERT(str != NULL);
18578 
18579 		len = strlen(str) + 1;
18580 
18581 		if (len > fmt.dtfd_length) {
18582 			fmt.dtfd_length = len;
18583 
18584 			if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
18585 				lck_mtx_unlock(&dtrace_lock);
18586 				return (EINVAL);
18587 			}
18588 		} else {
18589 			if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
18590 				lck_mtx_unlock(&dtrace_lock);
18591 				return (EINVAL);
18592 			}
18593 		}
18594 
18595 		lck_mtx_unlock(&dtrace_lock);
18596 		return (0);
18597 	}
18598 
18599 	case DTRACEIOC_MODUUIDSLIST: {
18600 		size_t module_uuids_list_size;
18601 		dtrace_module_uuids_list_t* uuids_list;
18602 		uint64_t dtmul_count;
18603 
18604 		/*
18605 		 * Security restrictions make this operation illegal, if this is enabled DTrace
18606 		 * must refuse to provide any fbt probes.
18607 		 */
18608 		if (dtrace_fbt_probes_restricted()) {
18609 			cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
18610 			return (EPERM);
18611 		}
18612 
18613 		/*
18614 		 * Fail if the kernel symbol mode makes this operation illegal.
18615 		 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
18616 		 * for them without holding the dtrace_lock.
18617 		 */
18618 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
18619 		    dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
18620 			cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
18621 			return (EPERM);
18622 		}
18623 
18624 		/*
18625 		 * Read the number of symbolsdesc structs being passed in.
18626 		 */
18627 		if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
18628 			   &dtmul_count,
18629 			   sizeof(dtmul_count))) {
18630 			cmn_err(CE_WARN, "failed to copyin dtmul_count");
18631 			return (EFAULT);
18632 		}
18633 
18634 		/*
18635 		 * Range check the count. More than 2k kexts is probably an error.
18636 		 */
18637 		if (dtmul_count > 2048) {
18638 			cmn_err(CE_WARN, "dtmul_count is not valid");
18639 			return (EINVAL);
18640 		}
18641 
18642 		/*
18643 		 * For all queries, we return EINVAL when the user specified
18644 		 * count does not match the actual number of modules we find
18645 		 * available.
18646 		 *
18647 		 * If the user specified count is zero, then this serves as a
18648 		 * simple query to count the available modules in need of symbols.
18649 		 */
18650 
18651 		rval = 0;
18652 
18653 		if (dtmul_count == 0)
18654 		{
18655 			lck_mtx_lock(&mod_lock);
18656 			struct modctl* ctl = dtrace_modctl_list;
18657 			while (ctl) {
18658 				ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18659 				if (!MOD_SYMBOLS_DONE(ctl) && !MOD_IS_STATIC_KEXT(ctl)) {
18660 					dtmul_count++;
18661 					rval = EINVAL;
18662 				}
18663 				ctl = ctl->mod_next;
18664 			}
18665 			lck_mtx_unlock(&mod_lock);
18666 
18667 			if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
18668 				return (EFAULT);
18669 			else
18670 				return (rval);
18671 		}
18672 
18673 		/*
18674 		 * If we reach this point, then we have a request for full list data.
18675 		 * Allocate a correctly sized structure and copyin the data.
18676 		 */
18677 		module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
18678 		if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
18679 			return (ENOMEM);
18680 
18681 		/* NOTE! We can no longer exit this method via return */
18682 		if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
18683 			cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
18684 			rval = EFAULT;
18685 			goto moduuidslist_cleanup;
18686 		}
18687 
18688 		/*
18689 		 * Check that the count didn't change between the first copyin and the second.
18690 		 */
18691 		if (uuids_list->dtmul_count != dtmul_count) {
18692 			rval = EINVAL;
18693 			goto moduuidslist_cleanup;
18694 		}
18695 
18696 		/*
18697 		 * Build the list of UUID's that need symbols
18698 		 */
18699 		lck_mtx_lock(&mod_lock);
18700 
18701 		dtmul_count = 0;
18702 
18703 		struct modctl* ctl = dtrace_modctl_list;
18704 		while (ctl) {
18705 			/*
18706 			 * We assume that userspace symbols will be "better" than kernel level symbols,
18707 			 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
18708 			 * are available, add user syms if the module might use them.
18709 			 */
18710 			ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18711 			if (!MOD_SYMBOLS_DONE(ctl) && !MOD_IS_STATIC_KEXT(ctl)) {
18712 				UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
18713 				if (dtmul_count++ < uuids_list->dtmul_count) {
18714 					memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
18715 				}
18716 			}
18717 			ctl = ctl->mod_next;
18718 		}
18719 
18720 		lck_mtx_unlock(&mod_lock);
18721 
18722 		if (uuids_list->dtmul_count < dtmul_count)
18723 			rval = EINVAL;
18724 
18725 		uuids_list->dtmul_count = dtmul_count;
18726 
18727 		/*
18728 		 * Copyout the symbols list (or at least the count!)
18729 		 */
18730 		if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
18731 			cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
18732 			rval = EFAULT;
18733 		}
18734 
18735 	moduuidslist_cleanup:
18736 		/*
18737 		 * If we had to allocate struct memory, free it.
18738 		 */
18739 		if (uuids_list != NULL) {
18740 			kmem_free(uuids_list, module_uuids_list_size);
18741 		}
18742 
18743 		return rval;
18744 	}
18745 
18746 	case DTRACEIOC_PROVMODSYMS: {
18747 		size_t module_symbols_size;
18748 		dtrace_module_symbols_t* module_symbols;
18749 		uint64_t dtmodsyms_count;
18750 
18751 		/*
18752 		 * Security restrictions make this operation illegal, if this is enabled DTrace
18753 		 * must refuse to provide any fbt probes.
18754 		 */
18755 		if (dtrace_fbt_probes_restricted()) {
18756 			cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
18757 			return (EPERM);
18758 		}
18759 
18760 		/*
18761 		 * Fail if the kernel symbol mode makes this operation illegal.
18762 		 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
18763 		 * for them without holding the dtrace_lock.
18764 		 */
18765 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
18766 		    dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
18767 			cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
18768 			return (EPERM);
18769 		}
18770 
18771 		/*
18772 		 * Read the number of module symbols structs being passed in.
18773 		 */
18774 		if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
18775 			   &dtmodsyms_count,
18776 			   sizeof(dtmodsyms_count))) {
18777 			cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
18778 			return (EFAULT);
18779 		}
18780 
18781 		/* Ensure that we have at least one symbol. */
18782 		if (dtmodsyms_count == 0) {
18783 			cmn_err(CE_WARN, "Invalid dtmodsyms_count value");
18784 			return (EINVAL);
18785 		}
18786 
18787 		/* Safely calculate size we need for copyin buffer. */
18788 		module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
18789 		if (module_symbols_size == 0 || module_symbols_size > (size_t)dtrace_copy_maxsize()) {
18790 			cmn_err(CE_WARN, "Invalid module_symbols_size %ld", module_symbols_size);
18791 			return (EINVAL);
18792 		}
18793 
18794 		if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
18795 			return (ENOMEM);
18796 
18797 		rval = 0;
18798 
18799 		/* NOTE! We can no longer exit this method via return */
18800 		if (copyin(arg, module_symbols, module_symbols_size) != 0) {
18801 			cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t");
18802 			rval = EFAULT;
18803 			goto module_symbols_cleanup;
18804 		}
18805 
18806 		/*
18807 		 * Check that the count didn't change between the first copyin and the second.
18808 		 */
18809 		if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
18810 			rval = EINVAL;
18811 			goto module_symbols_cleanup;
18812 		}
18813 
18814 		/*
18815 		 * Find the modctl to add symbols to.
18816 		 */
18817 		lck_mtx_lock(&dtrace_provider_lock);
18818 		lck_mtx_lock(&mod_lock);
18819 
18820 		struct modctl* ctl = dtrace_modctl_list;
18821 		while (ctl) {
18822 			ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18823 			if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl) && memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
18824 				dtrace_provider_t *prv;
18825 				ctl->mod_user_symbols = module_symbols;
18826 
18827 				/*
18828 				 * We're going to call each providers per-module provide operation
18829 				 * specifying only this module.
18830 				 */
18831 				for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
18832 					prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
18833 				/*
18834 				 * We gave every provider a chance to provide with the user syms, go ahead and clear them
18835 				 */
18836 				ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
18837 			}
18838 			ctl = ctl->mod_next;
18839 		}
18840 
18841 		lck_mtx_unlock(&mod_lock);
18842 		lck_mtx_unlock(&dtrace_provider_lock);
18843 
18844 	module_symbols_cleanup:
18845 		/*
18846 		 * If we had to allocate struct memory, free it.
18847 		 */
18848 		if (module_symbols != NULL) {
18849 			kmem_free(module_symbols, module_symbols_size);
18850 		}
18851 
18852 		return rval;
18853 	}
18854 
18855 	case DTRACEIOC_PROCWAITFOR: {
18856 		dtrace_procdesc_t pdesc = {
18857 			.p_name = {0},
18858 			.p_pid  = -1
18859 		};
18860 
18861 		if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
18862 			goto proc_waitfor_error;
18863 
18864 		if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
18865 			goto proc_waitfor_error;
18866 
18867 		if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
18868 			goto proc_waitfor_error;
18869 
18870 		return 0;
18871 
18872 	proc_waitfor_error:
18873 		/* The process was suspended, revert this since the client will not do it. */
18874 		if (pdesc.p_pid != -1) {
18875 			proc_t *proc = proc_find(pdesc.p_pid);
18876 			if (proc != PROC_NULL) {
18877 				task_pidresume(proc->task);
18878 				proc_rele(proc);
18879 			}
18880 		}
18881 
18882 		return rval;
18883 	}
18884 
18885 	default:
18886 		break;
18887 	}
18888 
18889 	return (ENOTTY);
18890 }
18891 
18892 /*
18893  * APPLE NOTE:  dtrace_detach not implemented
18894  */
18895 #if !defined(__APPLE__)
18896 /*ARGSUSED*/
18897 static int
dtrace_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)18898 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18899 {
18900 	dtrace_state_t *state;
18901 
18902 	switch (cmd) {
18903 	case DDI_DETACH:
18904 		break;
18905 
18906 	case DDI_SUSPEND:
18907 		return (DDI_SUCCESS);
18908 
18909 	default:
18910 		return (DDI_FAILURE);
18911 	}
18912 
18913 	lck_mtx_lock(&cpu_lock);
18914 	lck_mtx_lock(&dtrace_provider_lock);
18915 	lck_mtx_lock(&dtrace_lock);
18916 
18917 	ASSERT(dtrace_opens == 0);
18918 
18919 	if (dtrace_helpers > 0) {
18920 		lck_mtx_unlock(&dtrace_lock);
18921 		lck_mtx_unlock(&dtrace_provider_lock);
18922 		lck_mtx_unlock(&cpu_lock);
18923 		return (DDI_FAILURE);
18924 	}
18925 
18926 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18927 		lck_mtx_unlock(&dtrace_lock);
18928 		lck_mtx_unlock(&dtrace_provider_lock);
18929 		lck_mtx_unlock(&cpu_lock);
18930 		return (DDI_FAILURE);
18931 	}
18932 
18933 	dtrace_provider = NULL;
18934 
18935 	if ((state = dtrace_anon_grab()) != NULL) {
18936 		/*
18937 		 * If there were ECBs on this state, the provider should
18938 		 * have not been allowed to detach; assert that there is
18939 		 * none.
18940 		 */
18941 		ASSERT(state->dts_necbs == 0);
18942 		dtrace_state_destroy(state);
18943 
18944 		/*
18945 		 * If we're being detached with anonymous state, we need to
18946 		 * indicate to the kernel debugger that DTrace is now inactive.
18947 		 */
18948 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18949 	}
18950 
18951 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18952 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18953 	dtrace_cpu_init = NULL;
18954 	dtrace_helpers_cleanup = NULL;
18955 	dtrace_helpers_fork = NULL;
18956 	dtrace_cpustart_init = NULL;
18957 	dtrace_cpustart_fini = NULL;
18958 	dtrace_debugger_init = NULL;
18959 	dtrace_debugger_fini = NULL;
18960 	dtrace_kreloc_init = NULL;
18961 	dtrace_kreloc_fini = NULL;
18962 	dtrace_modload = NULL;
18963 	dtrace_modunload = NULL;
18964 
18965 	lck_mtx_unlock(&cpu_lock);
18966 
18967 	if (dtrace_helptrace_enabled) {
18968 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
18969 		dtrace_helptrace_buffer = NULL;
18970 	}
18971 
18972 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18973 	dtrace_probes = NULL;
18974 	dtrace_nprobes = 0;
18975 
18976 	dtrace_hash_destroy(dtrace_strings);
18977 	dtrace_hash_destroy(dtrace_byprov);
18978 	dtrace_hash_destroy(dtrace_bymod);
18979 	dtrace_hash_destroy(dtrace_byfunc);
18980 	dtrace_hash_destroy(dtrace_byname);
18981 	dtrace_strings = NULL;
18982 	dtrace_byprov = NULL;
18983 	dtrace_bymod = NULL;
18984 	dtrace_byfunc = NULL;
18985 	dtrace_byname = NULL;
18986 
18987 	kmem_cache_destroy(dtrace_state_cache);
18988 	vmem_destroy(dtrace_arena);
18989 
18990 	if (dtrace_toxrange != NULL) {
18991 		kmem_free(dtrace_toxrange,
18992 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18993 		dtrace_toxrange = NULL;
18994 		dtrace_toxranges = 0;
18995 		dtrace_toxranges_max = 0;
18996 	}
18997 
18998 	ddi_remove_minor_node(dtrace_devi, NULL);
18999 	dtrace_devi = NULL;
19000 
19001 	ddi_soft_state_fini(&dtrace_softstate);
19002 
19003 	ASSERT(dtrace_vtime_references == 0);
19004 	ASSERT(dtrace_opens == 0);
19005 	ASSERT(dtrace_retained == NULL);
19006 
19007 	lck_mtx_unlock(&dtrace_lock);
19008 	lck_mtx_unlock(&dtrace_provider_lock);
19009 
19010 #ifdef illumos
19011 	/*
19012 	 * We don't destroy the task queue until after we have dropped our
19013 	 * locks (taskq_destroy() may block on running tasks).  To prevent
19014 	 * attempting to do work after we have effectively detached but before
19015 	 * the task queue has been destroyed, all tasks dispatched via the
19016 	 * task queue must check that DTrace is still attached before
19017 	 * performing any operation.
19018 	 */
19019 	taskq_destroy(dtrace_taskq);
19020 	dtrace_taskq = NULL;
19021 #endif
19022 
19023 	return (DDI_SUCCESS);
19024 }
19025 #endif  /* __APPLE__ */
19026 
19027 d_open_t _dtrace_open, helper_open;
19028 d_close_t _dtrace_close, helper_close;
19029 d_ioctl_t _dtrace_ioctl, helper_ioctl;
19030 
19031 int
_dtrace_open(dev_t dev,int flags,int devtype,struct proc * p)19032 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
19033 {
19034 #pragma unused(p)
19035 	dev_t locdev = dev;
19036 
19037 	return  dtrace_open( &locdev, flags, devtype, CRED());
19038 }
19039 
19040 int
helper_open(dev_t dev,int flags,int devtype,struct proc * p)19041 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
19042 {
19043 #pragma unused(dev,flags,devtype,p)
19044 	return 0;
19045 }
19046 
19047 int
_dtrace_close(dev_t dev,int flags,int devtype,struct proc * p)19048 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
19049 {
19050 #pragma unused(p)
19051 	return dtrace_close( dev, flags, devtype, CRED());
19052 }
19053 
19054 int
helper_close(dev_t dev,int flags,int devtype,struct proc * p)19055 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
19056 {
19057 #pragma unused(dev,flags,devtype,p)
19058 	return 0;
19059 }
19060 
19061 int
_dtrace_ioctl(dev_t dev,u_long cmd,caddr_t data,int fflag,struct proc * p)19062 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19063 {
19064 #pragma unused(p)
19065 	int err, rv = 0;
19066     user_addr_t uaddrp;
19067 
19068     if (proc_is64bit(p))
19069 		uaddrp = *(user_addr_t *)data;
19070 	else
19071 		uaddrp = (user_addr_t) *(uint32_t *)data;
19072 
19073 	err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
19074 
19075 	/* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19076 	if (err != 0) {
19077 		ASSERT( (err & 0xfffff000) == 0 );
19078 		return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19079 	} else if (rv != 0) {
19080 		ASSERT( (rv & 0xfff00000) == 0 );
19081 		return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19082 	} else
19083 		return 0;
19084 }
19085 
19086 int
helper_ioctl(dev_t dev,u_long cmd,caddr_t data,int fflag,struct proc * p)19087 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19088 {
19089 #pragma unused(dev,fflag,p)
19090 	int err, rv = 0;
19091 
19092 	err = dtrace_ioctl_helper(cmd, data, &rv);
19093 	/* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19094 	if (err != 0) {
19095 		ASSERT( (err & 0xfffff000) == 0 );
19096 		return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19097 	} else if (rv != 0) {
19098 		ASSERT( (rv & 0xfff00000) == 0 );
19099 		return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19100 	} else
19101 		return 0;
19102 }
19103 
19104 #define HELPER_MAJOR  -24 /* let the kernel pick the device number */
19105 
19106 const static struct cdevsw helper_cdevsw =
19107 {
19108 	.d_open = helper_open,
19109 	.d_close = helper_close,
19110 	.d_read = eno_rdwrt,
19111 	.d_write = eno_rdwrt,
19112 	.d_ioctl = helper_ioctl,
19113 	.d_stop = (stop_fcn_t *)nulldev,
19114 	.d_reset = (reset_fcn_t *)nulldev,
19115 	.d_select = eno_select,
19116 	.d_mmap = eno_mmap,
19117 	.d_strategy = eno_strat,
19118 	.d_reserved_1 = eno_getc,
19119 	.d_reserved_2 = eno_putc,
19120 };
19121 
19122 static int helper_majdevno = 0;
19123 
19124 static int gDTraceInited = 0;
19125 
19126 void
helper_init(void)19127 helper_init( void )
19128 {
19129 	/*
19130 	 * Once the "helper" is initialized, it can take ioctl calls that use locks
19131 	 * and zones initialized in dtrace_init. Make certain dtrace_init was called
19132 	 * before us.
19133 	 */
19134 
19135 	if (!gDTraceInited) {
19136 		panic("helper_init before dtrace_init");
19137 	}
19138 
19139 	if (0 >= helper_majdevno)
19140 	{
19141 		helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
19142 
19143 		if (helper_majdevno < 0) {
19144 			printf("helper_init: failed to allocate a major number!\n");
19145 			return;
19146 		}
19147 
19148 		if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19149 					DTRACEMNR_HELPER )) {
19150 			printf("dtrace_init: failed to devfs_make_node for helper!\n");
19151 			return;
19152 		}
19153 	} else
19154 		panic("helper_init: called twice!");
19155 }
19156 
19157 #undef HELPER_MAJOR
19158 
19159 static int
dtrace_clone_func(dev_t dev,int action)19160 dtrace_clone_func(dev_t dev, int action)
19161 {
19162 #pragma unused(dev)
19163 
19164 	if (action == DEVFS_CLONE_ALLOC) {
19165 		return dtrace_state_reserve();
19166 	}
19167 	else if (action == DEVFS_CLONE_FREE) {
19168 		return 0;
19169 	}
19170 	else return -1;
19171 }
19172 
19173 void dtrace_ast(void);
19174 
19175 void
dtrace_ast(void)19176 dtrace_ast(void)
19177 {
19178 	int i;
19179 	uint32_t clients = os_atomic_xchg(&dtrace_wake_clients, 0, relaxed);
19180 	if (clients == 0)
19181 		return;
19182 	/**
19183 	 * We disable preemption here to be sure that we won't get
19184 	 * interrupted by a wakeup to a thread that is higher
19185 	 * priority than us, so that we do issue all wakeups
19186 	 */
19187 	disable_preemption();
19188 	for (i = 0; i < DTRACE_NCLIENTS; i++) {
19189 		if (clients & (1 << i)) {
19190 			dtrace_state_t *state = dtrace_state_get(i);
19191 			if (state) {
19192 				wakeup(state);
19193 			}
19194 
19195 		}
19196 	}
19197 	enable_preemption();
19198 }
19199 
19200 
19201 #define DTRACE_MAJOR  -24 /* let the kernel pick the device number */
19202 
19203 static const struct cdevsw dtrace_cdevsw =
19204 {
19205 	.d_open = _dtrace_open,
19206 	.d_close = _dtrace_close,
19207 	.d_read = eno_rdwrt,
19208 	.d_write = eno_rdwrt,
19209 	.d_ioctl = _dtrace_ioctl,
19210 	.d_stop = (stop_fcn_t *)nulldev,
19211 	.d_reset = (reset_fcn_t *)nulldev,
19212 	.d_select = eno_select,
19213 	.d_mmap = eno_mmap,
19214 	.d_strategy = eno_strat,
19215 	.d_reserved_1 = eno_getc,
19216 	.d_reserved_2 = eno_putc,
19217 };
19218 
19219 LCK_ATTR_DECLARE(dtrace_lck_attr, 0, 0);
19220 LCK_GRP_DECLARE(dtrace_lck_grp, "dtrace");
19221 
19222 static int gMajDevNo;
19223 
dtrace_early_init(void)19224 void dtrace_early_init (void)
19225 {
19226 	dtrace_restriction_policy_load();
19227 
19228 	/*
19229 	 * See dtrace_impl.h for a description of kernel symbol modes.
19230 	 * The default is to wait for symbols from userspace (lazy symbols).
19231 	 */
19232 	if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
19233 		dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
19234 	}
19235 }
19236 
19237 void
dtrace_init(void)19238 dtrace_init( void )
19239 {
19240 	if (0 == gDTraceInited) {
19241 		unsigned int i, ncpu;
19242 		size_t size = sizeof(dtrace_buffer_memory_maxsize);
19243 
19244 		/*
19245 		 * Disable destructive actions when dtrace is running
19246 		 * in a restricted environment
19247 		 */
19248 		dtrace_destructive_disallow = dtrace_is_restricted() &&
19249 		    !dtrace_are_restrictions_relaxed();
19250 
19251 		/*
19252 		 * DTrace allocates buffers based on the maximum number
19253 		 * of enabled cpus. This call avoids any race when finding
19254 		 * that count.
19255 		 */
19256 		ASSERT(dtrace_max_cpus == 0);
19257 		ncpu = dtrace_max_cpus = ml_wait_max_cpus();
19258 
19259 		/*
19260 		 * Retrieve the size of the physical memory in order to define
19261 		 * the state buffer memory maximal size.  If we cannot retrieve
19262 		 * this value, we'll consider that we have 1Gb of memory per CPU, that's
19263 		 * still better than raising a kernel panic.
19264 		 */
19265 		if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
19266 		                             &size, NULL, 0))
19267 		{
19268 			dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
19269 			printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
19270 			       dtrace_buffer_memory_maxsize);
19271 		}
19272 
19273 		/*
19274 		 * Finally, divide by three to prevent DTrace from eating too
19275 		 * much memory.
19276 		 */
19277 		dtrace_buffer_memory_maxsize /= 3;
19278 		ASSERT(dtrace_buffer_memory_maxsize > 0);
19279 
19280 		gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
19281 
19282 		if (gMajDevNo < 0) {
19283 			printf("dtrace_init: failed to allocate a major number!\n");
19284 			gDTraceInited = 0;
19285 			return;
19286 		}
19287 
19288 		if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19289 					dtrace_clone_func, DTRACEMNR_DTRACE )) {
19290 			printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
19291 			gDTraceInited = 0;
19292 			return;
19293 		}
19294 
19295 		/*
19296 		 * The cpu_core structure consists of per-CPU state available in any context.
19297 		 * On some architectures, this may mean that the page(s) containing the
19298 		 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
19299 		 * is up to the platform to assure that this is performed properly.  Note that
19300 		 * the structure is sized to avoid false sharing.
19301 		 */
19302 
19303 		/*
19304 		 * Initialize the CPU offline/online hooks.
19305 		 */
19306 		dtrace_install_cpu_hooks();
19307 
19308 		dtrace_modctl_list = NULL;
19309 
19310 		cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
19311 		for (i = 0; i < ncpu; ++i) {
19312 			lck_mtx_init(&cpu_core[i].cpuc_pid_lock, &dtrace_lck_grp, &dtrace_lck_attr);
19313 		}
19314 
19315 		cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
19316 		for (i = 0; i < ncpu; ++i) {
19317 			cpu_list[i].cpu_id = (processorid_t)i;
19318 			cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
19319 			LIST_INIT(&cpu_list[i].cpu_cyc_list);
19320 			lck_rw_init(&cpu_list[i].cpu_ft_lock, &dtrace_lck_grp, &dtrace_lck_attr);
19321 		}
19322 
19323 		lck_mtx_lock(&cpu_lock);
19324 		for (i = 0; i < ncpu; ++i)
19325 			/* FIXME: track CPU configuration */
19326 			dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
19327 		lck_mtx_unlock(&cpu_lock);
19328 
19329 		(void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
19330 
19331 		dtrace_strings = dtrace_hash_create(dtrace_strkey_offset,
19332 		    offsetof(dtrace_string_t, dtst_str),
19333 		    offsetof(dtrace_string_t, dtst_next),
19334 		    offsetof(dtrace_string_t, dtst_prev));
19335 
19336 		/*
19337 		 * See dtrace_impl.h for a description of dof modes.
19338 		 * The default is lazy dof.
19339 		 *
19340 		 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
19341 		 * makes no sense...
19342 		 */
19343 		if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
19344 #if defined(XNU_TARGET_OS_OSX)
19345 			dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
19346 #else
19347 			dtrace_dof_mode = DTRACE_DOF_MODE_NEVER;
19348 #endif
19349 		}
19350 
19351 		/*
19352 		 * Sanity check of dof mode value.
19353 		 */
19354 		switch (dtrace_dof_mode) {
19355 			case DTRACE_DOF_MODE_NEVER:
19356 			case DTRACE_DOF_MODE_LAZY_ON:
19357 				/* valid modes, but nothing else we need to do */
19358 				break;
19359 
19360 			case DTRACE_DOF_MODE_LAZY_OFF:
19361 			case DTRACE_DOF_MODE_NON_LAZY:
19362 				/* Cannot wait for a dtrace_open to init fasttrap */
19363 				fasttrap_init();
19364 				break;
19365 
19366 			default:
19367 				/* Invalid, clamp to non lazy */
19368 				dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
19369 				fasttrap_init();
19370 				break;
19371 		}
19372 
19373 #if CONFIG_DTRACE
19374         if (dtrace_dof_mode != DTRACE_DOF_MODE_NEVER)
19375             commpage_update_dof(true);
19376 #endif
19377 
19378 		gDTraceInited = 1;
19379 
19380 	} else
19381 		panic("dtrace_init: called twice!");
19382 }
19383 
19384 void
dtrace_postinit(void)19385 dtrace_postinit(void)
19386 {
19387 	/*
19388 	 * Called from bsd_init after all provider's *_init() routines have been
19389 	 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
19390 	 * to go.
19391 	 */
19392 	dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0)); /* Punning a dev_t to a dev_info_t* */
19393 
19394 	/*
19395 	 * Add the mach_kernel to the module list for lazy processing
19396 	 */
19397 	struct kmod_info fake_kernel_kmod;
19398 	memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
19399 
19400 	strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
19401 	fake_kernel_kmod.id = 1;
19402 	fake_kernel_kmod.address = g_kernel_kmod_info.address;
19403 	fake_kernel_kmod.size = g_kernel_kmod_info.size;
19404 
19405 	/* Ensure we don't try to touch symbols if they are gone. */
19406 	boolean_t keepsyms = false;
19407 	PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
19408 
19409 	if (dtrace_module_loaded(&fake_kernel_kmod, (keepsyms) ? 0 : KMOD_DTRACE_NO_KERNEL_SYMS) != 0) {
19410 		printf("dtrace_postinit: Could not register mach_kernel modctl\n");
19411 	}
19412 
19413 	(void)OSKextRegisterKextsWithDTrace();
19414 }
19415 #undef DTRACE_MAJOR
19416 
19417 /*
19418  * Routines used to register interest in cpu's being added to or removed
19419  * from the system.
19420  */
19421 void
register_cpu_setup_func(cpu_setup_func_t * ignore1,void * ignore2)19422 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19423 {
19424 #pragma unused(ignore1,ignore2)
19425 }
19426 
19427 void
unregister_cpu_setup_func(cpu_setup_func_t * ignore1,void * ignore2)19428 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19429 {
19430 #pragma unused(ignore1,ignore2)
19431 }
19432