xref: /xnu-10002.61.3/bsd/dev/dtrace/dtrace.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
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/processor.h>
98 #include <kern/task.h>
99 #include <kern/zalloc.h>
100 #include <netinet/in.h>
101 #include <libkern/sysctl.h>
102 #include <sys/kdebug.h>
103 #include <sys/sdt_impl.h>
104 
105 #if CONFIG_PERVASIVE_CPI
106 #include <kern/monotonic.h>
107 #include <machine/monotonic.h>
108 #endif /* CONFIG_PERVASIVE_CPI */
109 
110 #include "dtrace_xoroshiro128_plus.h"
111 
112 #include <IOKit/IOPlatformExpert.h>
113 
114 #include <kern/cpu_data.h>
115 
116 extern addr64_t kvtophys(vm_offset_t va);
117 
118 extern uint32_t pmap_find_phys(void *, uint64_t);
119 extern boolean_t pmap_valid_page(uint32_t);
120 extern void OSKextRegisterKextsWithDTrace(void);
121 extern kmod_info_t g_kernel_kmod_info;
122 extern void commpage_update_dof(boolean_t enabled);
123 
124 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
125 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
126 
127 #define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
128 
129 extern void dtrace_suspend(void);
130 extern void dtrace_resume(void);
131 extern void dtrace_early_init(void);
132 extern int dtrace_keep_kernel_symbols(void);
133 extern void dtrace_init(void);
134 extern void helper_init(void);
135 extern void fasttrap_init(void);
136 
137 static int  dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
138 extern void dtrace_lazy_dofs_destroy(proc_t *);
139 extern void dtrace_postinit(void);
140 
141 extern void dtrace_proc_fork(proc_t*, proc_t*, int);
142 extern void dtrace_proc_exec(proc_t*);
143 extern void dtrace_proc_exit(proc_t*);
144 
145 /*
146  * DTrace Tunable Variables
147  *
148  * The following variables may be dynamically tuned by using sysctl(8), the
149  * variables being stored in the kern.dtrace namespace.  For example:
150  * 	sysctl kern.dtrace.dof_maxsize = 1048575 	# 1M
151  *
152  * In general, the only variables that one should be tuning this way are those
153  * that affect system-wide DTrace behavior, and for which the default behavior
154  * is undesirable.  Most of these variables are tunable on a per-consumer
155  * basis using DTrace options, and need not be tuned on a system-wide basis.
156  * When tuning these variables, avoid pathological values; while some attempt
157  * is made to verify the integrity of these variables, they are not considered
158  * part of the supported interface to DTrace, and they are therefore not
159  * checked comprehensively.
160  */
161 uint64_t	dtrace_buffer_memory_maxsize = 0;		/* initialized in dtrace_init */
162 uint64_t	dtrace_buffer_memory_inuse = 0;
163 int		dtrace_destructive_disallow = 1;
164 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
165 size_t		dtrace_difo_maxsize = (256 * 1024);
166 dtrace_optval_t	dtrace_dof_maxsize = (512 * 1024);
167 dtrace_optval_t	dtrace_statvar_maxsize = (16 * 1024);
168 dtrace_optval_t	dtrace_statvar_maxsize_max = (16 * 10 * 1024);
169 size_t		dtrace_actions_max = (16 * 1024);
170 size_t		dtrace_retain_max = 1024;
171 dtrace_optval_t	dtrace_helper_actions_max = 32;
172 dtrace_optval_t	dtrace_helper_providers_max = 64;
173 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
174 size_t		dtrace_strsize_default = 256;
175 dtrace_optval_t	dtrace_strsize_min = 8;
176 dtrace_optval_t	dtrace_strsize_max = 65536;
177 dtrace_optval_t	dtrace_cleanrate_default = 990099000;		/* 1.1 hz */
178 dtrace_optval_t	dtrace_cleanrate_min = 20000000;			/* 50 hz */
179 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
180 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
181 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
182 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
183 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
184 dtrace_optval_t	dtrace_nspec_default = 1;
185 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
186 dtrace_optval_t dtrace_stackframes_default = 20;
187 dtrace_optval_t dtrace_ustackframes_default = 20;
188 dtrace_optval_t dtrace_jstackframes_default = 50;
189 dtrace_optval_t dtrace_jstackstrsize_default = 512;
190 dtrace_optval_t dtrace_buflimit_default = 75;
191 dtrace_optval_t dtrace_buflimit_min = 1;
192 dtrace_optval_t dtrace_buflimit_max = 99;
193 size_t		dtrace_nprobes_default = 4;
194 int		dtrace_msgdsize_max = 128;
195 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
196 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
197 int		dtrace_devdepth_max = 32;
198 int		dtrace_err_verbose;
199 hrtime_t	dtrace_deadman_interval = NANOSEC;
200 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
201 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
202 
203 /*
204  * DTrace External Variables
205  *
206  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
207  * available to DTrace consumers via the backtick (`) syntax.  One of these,
208  * dtrace_zero, is made deliberately so:  it is provided as a source of
209  * well-known, zero-filled memory.  While this variable is not documented,
210  * it is used by some translators as an implementation detail.
211  */
212 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
213 unsigned int	dtrace_max_cpus = 0;		/* number of enabled cpus */
214 /*
215  * DTrace Internal Variables
216  */
217 static dev_info_t	*dtrace_devi;		/* device info */
218 static vmem_t		*dtrace_arena;		/* probe ID arena */
219 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
220 static int		dtrace_nprobes;		/* number of probes */
221 static dtrace_provider_t *dtrace_provider;	/* provider list */
222 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
223 static int		dtrace_opens;		/* number of opens */
224 static int		dtrace_helpers;		/* number of helpers */
225 static dtrace_hash_t	*dtrace_strings;
226 static dtrace_hash_t	*dtrace_byprov;		/* probes hashed by provider */
227 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
228 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
229 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
230 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
231 static int		dtrace_toxranges;	/* number of toxic ranges */
232 static int		dtrace_toxranges_max;	/* size of toxic range array */
233 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
234 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
235 static kthread_t	*dtrace_panicked;	/* panicking thread */
236 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
237 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
238 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
239 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
240 static dtrace_genid_t   dtrace_retained_gen;    /* current retained enab gen */
241 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
242 
243 static int		dtrace_dof_mode;	/* See dtrace_impl.h for a description of Darwin's dof modes. */
244 
245 			/*
246 			 * This does't quite fit as an internal variable, as it must be accessed in
247 			 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
248 			 */
249 int			dtrace_kernel_symbol_mode;	/* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
250 static uint32_t		dtrace_wake_clients;
251 static uint8_t      dtrace_kerneluuid[16];	/* the 128-bit uuid */
252 
253 /*
254  * To save memory, some common memory allocations are given a
255  * unique zone. For example, dtrace_probe_t is 72 bytes in size,
256  * which means it would fall into the kalloc.128 bucket. With
257  * 20k elements allocated, the space saved is substantial.
258  */
259 
260 static ZONE_DEFINE_TYPE(dtrace_probe_t_zone, "dtrace.dtrace_probe_t",
261     dtrace_probe_t, ZC_PGZ_USE_GUARDS);
262 
263 static ZONE_DEFINE(dtrace_state_pcpu_zone, "dtrace.dtrace_dstate_percpu_t",
264     sizeof(dtrace_dstate_percpu_t), ZC_PERCPU);
265 
266 static int dtrace_module_unloaded(struct kmod_info *kmod);
267 
268 /*
269  * DTrace Locking
270  * DTrace is protected by three (relatively coarse-grained) locks:
271  *
272  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
273  *     including enabling state, probes, ECBs, consumer state, helper state,
274  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
275  *     probe context is lock-free -- synchronization is handled via the
276  *     dtrace_sync() cross call mechanism.
277  *
278  * (2) dtrace_provider_lock is required when manipulating provider state, or
279  *     when provider state must be held constant.
280  *
281  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
282  *     when meta provider state must be held constant.
283  *
284  * The lock ordering between these three locks is dtrace_meta_lock before
285  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
286  * several places where dtrace_provider_lock is held by the framework as it
287  * calls into the providers -- which then call back into the framework,
288  * grabbing dtrace_lock.)
289  *
290  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
291  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
292  * role as a coarse-grained lock; it is acquired before both of these locks.
293  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
294  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
295  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
296  * acquired _between_ dtrace_provider_lock and dtrace_lock.
297  */
298 
299 
300 /*
301  * APPLE NOTE:
302  *
303  * For porting purposes, all kmutex_t vars have been changed
304  * to lck_mtx_t, which require explicit initialization.
305  *
306  * kmutex_t becomes lck_mtx_t
307  * mutex_enter() becomes lck_mtx_lock()
308  * mutex_exit() becomes lck_mtx_unlock()
309  *
310  * Lock asserts are changed like this:
311  *
312  * ASSERT(MUTEX_HELD(&cpu_lock));
313  *	becomes:
314  * LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
315  *
316  */
317 static LCK_MTX_DECLARE_ATTR(dtrace_lock,
318     &dtrace_lck_grp, &dtrace_lck_attr);		/* probe state lock */
319 static LCK_MTX_DECLARE_ATTR(dtrace_provider_lock,
320     &dtrace_lck_grp, &dtrace_lck_attr);	/* provider state lock */
321 static LCK_MTX_DECLARE_ATTR(dtrace_meta_lock,
322     &dtrace_lck_grp, &dtrace_lck_attr);	/* meta-provider state lock */
323 static LCK_RW_DECLARE_ATTR(dtrace_dof_mode_lock,
324     &dtrace_lck_grp, &dtrace_lck_attr);	/* dof mode lock */
325 
326 /*
327  * DTrace Provider Variables
328  *
329  * These are the variables relating to DTrace as a provider (that is, the
330  * provider of the BEGIN, END, and ERROR probes).
331  */
332 static dtrace_pattr_t	dtrace_provider_attr = {
333 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
334 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
335 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
336 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
337 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
338 };
339 
340 static void
dtrace_provide_nullop(void * arg,const dtrace_probedesc_t * desc)341 dtrace_provide_nullop(void *arg, const dtrace_probedesc_t *desc)
342 {
343 #pragma unused(arg, desc)
344 }
345 
346 static void
dtrace_provide_module_nullop(void * arg,struct modctl * ctl)347 dtrace_provide_module_nullop(void *arg, struct modctl *ctl)
348 {
349 #pragma unused(arg, ctl)
350 }
351 
352 static int
dtrace_enable_nullop(void * arg,dtrace_id_t id,void * parg)353 dtrace_enable_nullop(void *arg, dtrace_id_t id, void *parg)
354 {
355 #pragma unused(arg, id, parg)
356     return (0);
357 }
358 
359 static void
dtrace_disable_nullop(void * arg,dtrace_id_t id,void * parg)360 dtrace_disable_nullop(void *arg, dtrace_id_t id, void *parg)
361 {
362 #pragma unused(arg, id, parg)
363 }
364 
365 static void
dtrace_suspend_nullop(void * arg,dtrace_id_t id,void * parg)366 dtrace_suspend_nullop(void *arg, dtrace_id_t id, void *parg)
367 {
368 #pragma unused(arg, id, parg)
369 }
370 
371 static void
dtrace_resume_nullop(void * arg,dtrace_id_t id,void * parg)372 dtrace_resume_nullop(void *arg, dtrace_id_t id, void *parg)
373 {
374 #pragma unused(arg, id, parg)
375 }
376 
377 static void
dtrace_destroy_nullop(void * arg,dtrace_id_t id,void * parg)378 dtrace_destroy_nullop(void *arg, dtrace_id_t id, void *parg)
379 {
380 #pragma unused(arg, id, parg)
381 }
382 
383 
384 static dtrace_pops_t dtrace_provider_ops = {
385 	.dtps_provide = dtrace_provide_nullop,
386 	.dtps_provide_module =	dtrace_provide_module_nullop,
387 	.dtps_enable =	dtrace_enable_nullop,
388 	.dtps_disable =	dtrace_disable_nullop,
389 	.dtps_suspend =	dtrace_suspend_nullop,
390 	.dtps_resume =	dtrace_resume_nullop,
391 	.dtps_getargdesc =	NULL,
392 	.dtps_getargval =	NULL,
393 	.dtps_usermode =	NULL,
394 	.dtps_destroy =	dtrace_destroy_nullop,
395 };
396 
397 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
398 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
399 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
400 
401 /*
402  * DTrace Helper Tracing Variables
403  */
404 uint32_t dtrace_helptrace_next = 0;
405 uint32_t dtrace_helptrace_nlocals;
406 char	*dtrace_helptrace_buffer;
407 size_t	dtrace_helptrace_bufsize = 512 * 1024;
408 
409 #if DEBUG
410 int	dtrace_helptrace_enabled = 1;
411 #else
412 int	dtrace_helptrace_enabled = 0;
413 #endif
414 
415 #if defined (__arm64__)
416 /*
417  * The ioctl for adding helper DOF is based on the
418  * size of a user_addr_t.  We need to recognize both
419  * U32 and U64 as the same action.
420  */
421 #define DTRACEHIOC_ADDDOF_U32       _IOW('h', 4, user32_addr_t)
422 #define DTRACEHIOC_ADDDOF_U64       _IOW('h', 4, user64_addr_t)
423 #endif  /* __arm64__ */
424 
425 /*
426  * DTrace Error Hashing
427  *
428  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
429  * table.  This is very useful for checking coverage of tests that are
430  * expected to induce DIF or DOF processing errors, and may be useful for
431  * debugging problems in the DIF code generator or in DOF generation .  The
432  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
433  */
434 #if DEBUG
435 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
436 static const char *dtrace_errlast;
437 static kthread_t *dtrace_errthread;
438 static LCK_MTX_DECLARE_ATTR(dtrace_errlock, &dtrace_lck_grp, &dtrace_lck_attr);
439 #endif
440 
441 /*
442  * DTrace Macros and Constants
443  *
444  * These are various macros that are useful in various spots in the
445  * implementation, along with a few random constants that have no meaning
446  * outside of the implementation.  There is no real structure to this cpp
447  * mishmash -- but is there ever?
448  */
449 
450 #define	DTRACE_GETSTR(hash, elm)	\
451 	(hash->dth_getstr(elm, hash->dth_stroffs))
452 
453 #define	DTRACE_HASHSTR(hash, elm)	\
454 	dtrace_hash_str(DTRACE_GETSTR(hash, elm))
455 
456 #define	DTRACE_HASHNEXT(hash, elm)	\
457 	(void**)((uintptr_t)(elm) + (hash)->dth_nextoffs)
458 
459 #define	DTRACE_HASHPREV(hash, elm)	\
460 	(void**)((uintptr_t)(elm) + (hash)->dth_prevoffs)
461 
462 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
463 	(strcmp(DTRACE_GETSTR(hash, lhs), \
464 	    DTRACE_GETSTR(hash, rhs)) == 0)
465 
466 #define	DTRACE_AGGHASHSIZE_SLEW		17
467 
468 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
469 
470 /*
471  * The key for a thread-local variable needs to be unique to a single
472  * thread over the lifetime of the system, and not overlap with any variable
473  * IDs. So we take thread's thread_id, a unique 64-bit number that is never
474  * reused after the thread exits, and add DIF_VARIABLE_MAX to it, which
475  * guarantees that it won’t overlap any variable IDs. We also want to treat
476  * running in interrupt context as independent of thread-context. So if
477  * interrupts are active, we set the 63rd bit, otherwise it’s cleared.
478  *
479  * This is necessary (but not sufficient) to assure that global associative
480  * arrays never collide with thread-local variables. To guarantee that they
481  * cannot collide, we must also define the order for keying dynamic variables.
482  *
483  * That order is:
484  *
485  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
486  *
487  * Because the variable-key and the tls-key are in orthogonal spaces, there is
488  * no way for a global variable key signature to match a thread-local key
489  * signature.
490  */
491 #if defined (__x86_64__) || defined(__arm64__)
492 #define	DTRACE_TLS_THRKEY(where) {                                           \
493 	uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
494 	uint64_t thr = thread_tid(current_thread());                             \
495 	ASSERT(intr < 2);                                                        \
496 	(where) = ((thr + DIF_VARIABLE_MAX) & (~((uint64_t)1 << 63))) |          \
497 		((uint64_t)intr << 63);                                              \
498 }
499 #else
500 #error Unknown architecture
501 #endif
502 
503 #define	DT_BSWAP_8(x)	((x) & 0xff)
504 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
505 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
506 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
507 
508 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
509 
510 #define	DTRACE_STORE(type, tomax, offset, what) \
511 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
512 
513 
514 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
515 	if (addr & (MIN(size,4) - 1)) {					\
516 		*flags |= CPU_DTRACE_BADALIGN;				\
517 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
518 		return (0);						\
519 	}
520 
521 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
522 do {									\
523 	if ((remp) != NULL) {						\
524 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
525 	}								\
526 } while (0)
527 
528 
529 /*
530  * Test whether a range of memory starting at testaddr of size testsz falls
531  * within the range of memory described by addr, sz.  We take care to avoid
532  * problems with overflow and underflow of the unsigned quantities, and
533  * disallow all negative sizes.  Ranges of size 0 are allowed.
534  */
535 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
536 	((testaddr) - (baseaddr) < (basesz) && \
537 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
538 	(testaddr) + (testsz) >= (testaddr))
539 
540 /*
541  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
542  * alloc_sz on the righthand side of the comparison in order to avoid overflow
543  * or underflow in the comparison with it.  This is simpler than the INRANGE
544  * check above, because we know that the dtms_scratch_ptr is valid in the
545  * range.  Allocations of size zero are allowed.
546  */
547 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
548 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
549 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
550 
551 #if defined (__x86_64__) || defined (__arm64__)
552 #define	DTRACE_LOADFUNC(bits)						\
553 /*CSTYLED*/								\
554 uint##bits##_t dtrace_load##bits(uintptr_t addr);			\
555 									\
556 extern int dtrace_nofault_copy##bits(uintptr_t, uint##bits##_t *);	\
557 									\
558 uint##bits##_t								\
559 dtrace_load##bits(uintptr_t addr)					\
560 {									\
561 	size_t size = bits / NBBY;					\
562 	/*CSTYLED*/							\
563 	uint##bits##_t rval = 0;					\
564 	int i;								\
565 	volatile uint16_t *flags = (volatile uint16_t *)		\
566 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
567 									\
568 	DTRACE_ALIGNCHECK(addr, size, flags);				\
569 									\
570 	for (i = 0; i < dtrace_toxranges; i++) {			\
571 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
572 			continue;					\
573 									\
574 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
575 			continue;					\
576 									\
577 		/*							\
578 		 * This address falls within a toxic region; return 0.	\
579 		 */							\
580 		*flags |= CPU_DTRACE_BADADDR;				\
581 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
582 		return (0);						\
583 	}								\
584 									\
585 	{								\
586 	*flags |= CPU_DTRACE_NOFAULT;					\
587 	/*CSTYLED*/							\
588 	/*                                                              \
589 	* PR6394061 - avoid device memory that is unpredictably		\
590 	* mapped and unmapped                                   	\
591 	*/								\
592 	if (!pmap_valid_page(pmap_find_phys(kernel_pmap, addr)) ||	\
593 	    dtrace_nofault_copy##bits(addr, &rval)) {			\
594 		*flags |= CPU_DTRACE_BADADDR;				\
595 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
596 		return (0);						\
597 	}								\
598 									\
599 	*flags &= ~CPU_DTRACE_NOFAULT;					\
600 	}								\
601 									\
602 	return (rval);							\
603 }
604 #else /* all other architectures */
605 #error Unknown Architecture
606 #endif
607 
608 #ifdef __LP64__
609 #define	dtrace_loadptr	dtrace_load64
610 #else
611 #define	dtrace_loadptr	dtrace_load32
612 #endif
613 
614 #define	DTRACE_DYNHASH_FREE	0
615 #define	DTRACE_DYNHASH_SINK	1
616 #define	DTRACE_DYNHASH_VALID	2
617 
618 #define DTRACE_MATCH_FAIL       -1
619 #define	DTRACE_MATCH_NEXT	0
620 #define	DTRACE_MATCH_DONE	1
621 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
622 #define	DTRACE_STATE_ALIGN	64
623 
624 #define	DTRACE_FLAGS2FLT(flags)						\
625 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
626 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
627 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
628 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
629 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
630 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
631 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
632 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
633 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
634 	DTRACEFLT_UNKNOWN)
635 
636 #define	DTRACEACT_ISSTRING(act)						\
637 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
638 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
639 
640 
641 static size_t dtrace_strlen(const char *, size_t);
642 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
643 static void dtrace_enabling_provide(dtrace_provider_t *);
644 static int dtrace_enabling_match(dtrace_enabling_t *, int *, dtrace_match_cond_t *cond);
645 static void dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond);
646 static void dtrace_enabling_matchall(void);
647 static dtrace_state_t *dtrace_anon_grab(void);
648 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
649     dtrace_state_t *, uint64_t, uint64_t);
650 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
651 static void dtrace_buffer_drop(dtrace_buffer_t *);
652 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
653     dtrace_state_t *, dtrace_mstate_t *);
654 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
655     dtrace_optval_t);
656 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *, void *);
657 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
658 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
659 	dtrace_mstate_t *, dtrace_vstate_t *);
660 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
661 	dtrace_mstate_t *, dtrace_vstate_t *);
662 
663 
664 /*
665  * DTrace sysctl handlers
666  *
667  * These declarations and functions are used for a deeper DTrace configuration.
668  * Most of them are not per-consumer basis and may impact the other DTrace
669  * consumers.  Correctness may not be supported for all the variables, so you
670  * should be careful about what values you are using.
671  */
672 
673 SYSCTL_DECL(_kern_dtrace);
674 SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
675 
676 static int
677 sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
678 {
679 #pragma unused(oidp, arg2)
680 	int changed, error;
681 	int value = *(int *) arg1;
682 
683 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
684 	if (error || !changed)
685 		return (error);
686 
687 	if (value != 0 && value != 1)
688 		return (ERANGE);
689 
690 	lck_mtx_lock(&dtrace_lock);
691 		dtrace_err_verbose = value;
692 	lck_mtx_unlock(&dtrace_lock);
693 
694 	return (0);
695 }
696 
697 /*
698  * kern.dtrace.err_verbose
699  *
700  * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
701  * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
702  */
703 SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
704 	CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
705 	&dtrace_err_verbose, 0,
706 	sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
707 
708 static int
709 sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
710 {
711 #pragma unused(oidp, arg2, req)
712 	int changed, error;
713 	uint64_t value = *(uint64_t *) arg1;
714 
715 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
716 	if (error || !changed)
717 		return (error);
718 
719 	if (value <= dtrace_buffer_memory_inuse)
720 		return (ERANGE);
721 
722 	lck_mtx_lock(&dtrace_lock);
723 		dtrace_buffer_memory_maxsize = value;
724 	lck_mtx_unlock(&dtrace_lock);
725 
726 	return (0);
727 }
728 
729 /*
730  * kern.dtrace.buffer_memory_maxsize
731  *
732  * Set DTrace maximal size in bytes used by all the consumers' state buffers.  By default
733  * the limit is PHYS_MEM / 3 for *all* consumers.  Attempting to set a null, a negative value
734  * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
735  */
736 SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
737 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
738 	&dtrace_buffer_memory_maxsize, 0,
739 	sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
740 
741 /*
742  * kern.dtrace.buffer_memory_inuse
743  *
744  * Current state buffer memory used, in bytes, by all the DTrace consumers.
745  * This value is read-only.
746  */
747 SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
748 	&dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
749 
750 static int
751 sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
752 {
753 #pragma unused(oidp, arg2, req)
754 	int changed, error;
755 	size_t value = *(size_t*) arg1;
756 
757 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
758 	if (error || !changed)
759 		return (error);
760 
761 	if (value <= 0)
762 		return (ERANGE);
763 
764 	lck_mtx_lock(&dtrace_lock);
765 		dtrace_difo_maxsize = value;
766 	lck_mtx_unlock(&dtrace_lock);
767 
768 	return (0);
769 }
770 
771 /*
772  * kern.dtrace.difo_maxsize
773  *
774  * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
775  * to get the default value.  Attempting to set a null or negative size will
776  * result in a failure.
777  */
778 SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
779 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
780 	&dtrace_difo_maxsize, 0,
781 	sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
782 
783 static int
784 sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
785 {
786 #pragma unused(oidp, arg2, req)
787 	int changed, error;
788 	dtrace_optval_t value = *(dtrace_optval_t *) arg1;
789 
790 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
791 	if (error || !changed)
792 		return (error);
793 
794 	if (value <= 0)
795 		return (ERANGE);
796 
797 	if (value >= dtrace_copy_maxsize())
798 		return (ERANGE);
799 
800 	lck_mtx_lock(&dtrace_lock);
801 		dtrace_dof_maxsize = value;
802 	lck_mtx_unlock(&dtrace_lock);
803 
804 	return (0);
805 }
806 
807 /*
808  * kern.dtrace.dof_maxsize
809  *
810  * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
811  * get the default value.  Attempting to set a null or negative size will result
812  * in a failure.
813  */
814 SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
815 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
816 	&dtrace_dof_maxsize, 0,
817 	sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
818 
819 static int
820 sysctl_dtrace_statvar_maxsize SYSCTL_HANDLER_ARGS
821 {
822 #pragma unused(oidp, arg2, req)
823 	int changed, error;
824 	dtrace_optval_t value = *(dtrace_optval_t*) arg1;
825 
826 	error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
827 	if (error || !changed)
828 		return (error);
829 
830 	if (value <= 0)
831 		return (ERANGE);
832 	if (value > dtrace_statvar_maxsize_max)
833 		return (ERANGE);
834 
835 	lck_mtx_lock(&dtrace_lock);
836 		dtrace_statvar_maxsize = value;
837 	lck_mtx_unlock(&dtrace_lock);
838 
839 	return (0);
840 }
841 
842 /*
843  * kern.dtrace.global_maxsize
844  *
845  * Set the variable max size in bytes, check the definition of
846  * dtrace_statvar_maxsize to get the default value.  Attempting to set a null,
847  * too high or negative size will result in a failure.
848  */
849 SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
850 	CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
851 	&dtrace_statvar_maxsize, 0,
852 	sysctl_dtrace_statvar_maxsize, "Q", "dtrace statvar maxsize");
853 
854 
855 /*
856  * kern.dtrace.provide_private_probes
857  *
858  * Set whether the providers must provide the private probes.  This is
859  * kept as compatibility as they are always provided.
860  */
861 SYSCTL_INT(_kern_dtrace, OID_AUTO, provide_private_probes,
862 	CTLFLAG_RD | CTLFLAG_LOCKED,
863 	(int *)NULL, 1, "provider must provide the private probes");
864 
865 /*
866  * kern.dtrace.dof_mode
867  *
868  * Returns the current DOF mode.
869  * This value is read-only.
870  */
871 SYSCTL_INT(_kern_dtrace, OID_AUTO, dof_mode, CTLFLAG_RD | CTLFLAG_LOCKED,
872 	&dtrace_dof_mode, 0, "dtrace dof mode");
873 
874 /*
875  * DTrace Probe Context Functions
876  *
877  * These functions are called from probe context.  Because probe context is
878  * any context in which C may be called, arbitrarily locks may be held,
879  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
880  * As a result, functions called from probe context may only call other DTrace
881  * support functions -- they may not interact at all with the system at large.
882  * (Note that the ASSERT macro is made probe-context safe by redefining it in
883  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
884  * loads are to be performed from probe context, they _must_ be in terms of
885  * the safe dtrace_load*() variants.
886  *
887  * Some functions in this block are not actually called from probe context;
888  * for these functions, there will be a comment above the function reading
889  * "Note:  not called from probe context."
890  */
891 
892 int
dtrace_assfail(const char * a,const char * f,int l)893 dtrace_assfail(const char *a, const char *f, int l)
894 {
895 	panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
896 
897 	/*
898 	 * We just need something here that even the most clever compiler
899 	 * cannot optimize away.
900 	 */
901 	return (a[(uintptr_t)f]);
902 }
903 
904 /*
905  * Atomically increment a specified error counter from probe context.
906  */
907 static void
dtrace_error(uint32_t * counter)908 dtrace_error(uint32_t *counter)
909 {
910 	/*
911 	 * Most counters stored to in probe context are per-CPU counters.
912 	 * However, there are some error conditions that are sufficiently
913 	 * arcane that they don't merit per-CPU storage.  If these counters
914 	 * are incremented concurrently on different CPUs, scalability will be
915 	 * adversely affected -- but we don't expect them to be white-hot in a
916 	 * correctly constructed enabling...
917 	 */
918 	uint32_t oval, nval;
919 
920 	do {
921 		oval = *counter;
922 
923 		if ((nval = oval + 1) == 0) {
924 			/*
925 			 * If the counter would wrap, set it to 1 -- assuring
926 			 * that the counter is never zero when we have seen
927 			 * errors.  (The counter must be 32-bits because we
928 			 * aren't guaranteed a 64-bit compare&swap operation.)
929 			 * To save this code both the infamy of being fingered
930 			 * by a priggish news story and the indignity of being
931 			 * the target of a neo-puritan witch trial, we're
932 			 * carefully avoiding any colorful description of the
933 			 * likelihood of this condition -- but suffice it to
934 			 * say that it is only slightly more likely than the
935 			 * overflow of predicate cache IDs, as discussed in
936 			 * dtrace_predicate_create().
937 			 */
938 			nval = 1;
939 		}
940 	} while (dtrace_cas32(counter, oval, nval) != oval);
941 }
942 
943 /*
944  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
945  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
946  */
947 DTRACE_LOADFUNC(8)
948 DTRACE_LOADFUNC(16)
949 DTRACE_LOADFUNC(32)
950 DTRACE_LOADFUNC(64)
951 
952 static int
dtrace_inscratch(uintptr_t dest,size_t size,dtrace_mstate_t * mstate)953 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
954 {
955 	if (dest < mstate->dtms_scratch_base)
956 		return (0);
957 
958 	if (dest + size < dest)
959 		return (0);
960 
961 	if (dest + size > mstate->dtms_scratch_ptr)
962 		return (0);
963 
964 	return (1);
965 }
966 
967 static int
dtrace_canstore_statvar(uint64_t addr,size_t sz,size_t * remain,dtrace_statvar_t ** svars,int nsvars)968 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
969     dtrace_statvar_t **svars, int nsvars)
970 {
971 	int i;
972 
973 	size_t maxglobalsize, maxlocalsize;
974 
975 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
976 	maxlocalsize = (maxglobalsize) * NCPU;
977 
978 	if (nsvars == 0)
979 		return (0);
980 
981 	for (i = 0; i < nsvars; i++) {
982 		dtrace_statvar_t *svar = svars[i];
983 		uint8_t scope;
984 		size_t size;
985 
986 		if (svar == NULL || (size = svar->dtsv_size) == 0)
987 			continue;
988 
989 		scope = svar->dtsv_var.dtdv_scope;
990 
991 		/**
992 		 * We verify that our size is valid in the spirit of providing
993 		 * defense in depth:  we want to prevent attackers from using
994 		 * DTrace to escalate an orthogonal kernel heap corruption bug
995 		 * into the ability to store to arbitrary locations in memory.
996 		 */
997 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
998 			(scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
999 
1000 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size)) {
1001 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
1002 				svar->dtsv_size);
1003 			return (1);
1004 		}
1005 	}
1006 
1007 	return (0);
1008 }
1009 
1010 /*
1011  * Check to see if the address is within a memory region to which a store may
1012  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
1013  * region.  The caller of dtrace_canstore() is responsible for performing any
1014  * alignment checks that are needed before stores are actually executed.
1015  */
1016 static int
dtrace_canstore(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1017 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1018     dtrace_vstate_t *vstate)
1019 {
1020 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
1021 }
1022 /*
1023  * Implementation of dtrace_canstore which communicates the upper bound of the
1024  * allowed memory region.
1025  */
1026 static int
dtrace_canstore_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1027 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
1028 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1029 {
1030 	/*
1031 	 * First, check to see if the address is in allocated scratch space...
1032 	 */
1033 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
1034 	    mstate->dtms_scratch_ptr - mstate->dtms_scratch_base)) {
1035 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
1036 		    mstate->dtms_scratch_ptr - mstate->dtms_scratch_base);
1037 		return (1);
1038 	}
1039 	/*
1040 	 * Now check to see if it's a dynamic variable.  This check will pick
1041 	 * up both thread-local variables and any global dynamically-allocated
1042 	 * variables.
1043 	 */
1044 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
1045 	    vstate->dtvs_dynvars.dtds_size)) {
1046 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
1047 		uintptr_t base = (uintptr_t)dstate->dtds_base +
1048 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
1049 		uintptr_t chunkoffs;
1050 		dtrace_dynvar_t *dvar;
1051 
1052 		/*
1053 		 * Before we assume that we can store here, we need to make
1054 		 * sure that it isn't in our metadata -- storing to our
1055 		 * dynamic variable metadata would corrupt our state.  For
1056 		 * the range to not include any dynamic variable metadata,
1057 		 * it must:
1058 		 *
1059 		 *	(1) Start above the hash table that is at the base of
1060 		 *	the dynamic variable space
1061 		 *
1062 		 *	(2) Have a starting chunk offset that is beyond the
1063 		 *	dtrace_dynvar_t that is at the base of every chunk
1064 		 *
1065 		 *	(3) Not span a chunk boundary
1066 		 *
1067 		 *	(4) Not be in the tuple space of a dynamic variable
1068 		 *
1069 		 */
1070 		if (addr < base)
1071 			return (0);
1072 
1073 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
1074 
1075 		if (chunkoffs < sizeof (dtrace_dynvar_t))
1076 			return (0);
1077 
1078 		if (chunkoffs + sz > dstate->dtds_chunksize)
1079 			return (0);
1080 
1081 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
1082 
1083 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
1084 			return (0);
1085 
1086 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
1087 			((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
1088 			return (0);
1089 
1090 		return (1);
1091 	}
1092 
1093 	/*
1094 	 * Finally, check the static local and global variables.  These checks
1095 	 * take the longest, so we perform them last.
1096 	 */
1097 	if (dtrace_canstore_statvar(addr, sz, remain,
1098 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
1099 		return (1);
1100 
1101 	if (dtrace_canstore_statvar(addr, sz, remain,
1102 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
1103 		return (1);
1104 
1105 	return (0);
1106 }
1107 
1108 
1109 /*
1110  * Convenience routine to check to see if the address is within a memory
1111  * region in which a load may be issued given the user's privilege level;
1112  * if not, it sets the appropriate error flags and loads 'addr' into the
1113  * illegal value slot.
1114  *
1115  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
1116  * appropriate memory access protection.
1117  */
1118 int
dtrace_canload(uint64_t addr,size_t sz,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1119 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1120     dtrace_vstate_t *vstate)
1121 {
1122 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
1123 }
1124 
1125 /*
1126  * Implementation of dtrace_canload which communicates the upper bound of the
1127  * allowed memory region.
1128  */
1129 static int
dtrace_canload_remains(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1130 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
1131 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1132 {
1133 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
1134 
1135 	/*
1136 	 * If we hold the privilege to read from kernel memory, then
1137 	 * everything is readable.
1138 	 */
1139 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1140 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1141 		return (1);
1142 	}
1143 
1144 	/*
1145 	 * You can obviously read that which you can store.
1146 	 */
1147 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
1148 		return (1);
1149 
1150 	/*
1151 	 * We're allowed to read from our own string table.
1152 	 */
1153 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
1154 	    mstate->dtms_difo->dtdo_strlen)) {
1155 		DTRACE_RANGE_REMAIN(remain, addr,
1156 			mstate->dtms_difo->dtdo_strtab,
1157 			mstate->dtms_difo->dtdo_strlen);
1158 		return (1);
1159 	}
1160 
1161 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1162 	*illval = addr;
1163 	return (0);
1164 }
1165 
1166 /*
1167  * Convenience routine to check to see if a given string is within a memory
1168  * region in which a load may be issued given the user's privilege level;
1169  * this exists so that we don't need to issue unnecessary dtrace_strlen()
1170  * calls in the event that the user has all privileges.
1171  */
1172 static int
dtrace_strcanload(uint64_t addr,size_t sz,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1173 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1174 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1175 {
1176 	size_t rsize = 0;
1177 
1178 	/*
1179 	 * If we hold the privilege to read from kernel memory, then
1180 	 * everything is readable.
1181 	 */
1182 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1183 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1184 		return (1);
1185 	}
1186 
1187 	/*
1188 	 * Even if the caller is uninterested in querying the remaining valid
1189 	 * range, it is required to ensure that the access is allowed.
1190 	 */
1191 	if (remain == NULL) {
1192 		remain = &rsize;
1193 	}
1194 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1195 		size_t strsz;
1196 		/*
1197 		 * Perform the strlen after determining the length of the
1198 		 * memory region which is accessible.  This prevents timing
1199 		 * information from being used to find NULs in memory which is
1200 		 * not accessible to the caller.
1201 		 */
1202 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1203 			MIN(sz, *remain));
1204 		if (strsz <= *remain) {
1205 			return (1);
1206 		}
1207 	}
1208 
1209 	return (0);
1210 }
1211 
1212 /*
1213  * Convenience routine to check to see if a given variable is within a memory
1214  * region in which a load may be issued given the user's privilege level.
1215  */
1216 static int
dtrace_vcanload(void * src,dtrace_diftype_t * type,size_t * remain,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate)1217 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1218 	dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1219 {
1220 	size_t sz;
1221 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1222 
1223 	/*
1224 	 * Calculate the max size before performing any checks since even
1225 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1226 	 * return the max length via 'remain'.
1227 	 */
1228 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1229 		dtrace_state_t *state = vstate->dtvs_state;
1230 
1231 		if (state != NULL) {
1232 			sz = state->dts_options[DTRACEOPT_STRSIZE];
1233 		} else {
1234 			/*
1235 			 * In helper context, we have a NULL state; fall back
1236 			 * to using the system-wide default for the string size
1237 			 * in this case.
1238 			 */
1239 			sz = dtrace_strsize_default;
1240 		}
1241 	} else {
1242 		sz = type->dtdt_size;
1243 	}
1244 
1245 	/*
1246 	 * If we hold the privilege to read from kernel memory, then
1247 	 * everything is readable.
1248 	 */
1249 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1250 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1251 		return (1);
1252 	}
1253 
1254 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1255 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1256 			vstate));
1257 	}
1258 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1259 		vstate));
1260 }
1261 
1262 #define	isdigit(ch)	((ch) >= '0' && (ch) <= '9')
1263 #define	islower(ch)	((ch) >= 'a' && (ch) <= 'z')
1264 #define	isspace(ch)	(((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \
1265 			((ch) == '\t') || ((ch) == '\f'))
1266 #define	isxdigit(ch)	(isdigit(ch) || ((ch) >= 'a' && (ch) <= 'f') || \
1267 			((ch) >= 'A' && (ch) <= 'F'))
1268 #define	lisalnum(x)	\
1269 	(isdigit(x) || ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))
1270 
1271 #define	DIGIT(x)	\
1272 	(isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
1273 
1274 /*
1275  * Convert a string to a signed integer using safe loads.
1276  */
1277 static int64_t
dtrace_strtoll(char * input,int base,size_t limit)1278 dtrace_strtoll(char *input, int base, size_t limit)
1279 {
1280 	uintptr_t pos = (uintptr_t)input;
1281 	int64_t val = 0;
1282 	int x;
1283 	boolean_t neg = B_FALSE;
1284 	char c, cc, ccc;
1285 	uintptr_t end = pos + limit;
1286 
1287 	/*
1288 	 * Consume any whitespace preceding digits.
1289 	 */
1290 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1291 		pos++;
1292 
1293 	/*
1294 	 * Handle an explicit sign if one is present.
1295 	 */
1296 	if (c == '-' || c == '+') {
1297 		if (c == '-')
1298 			neg = B_TRUE;
1299 		c = dtrace_load8(++pos);
1300 	}
1301 
1302 	/*
1303 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1304 	 * if present.
1305 	 */
1306 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1307 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1308 		pos += 2;
1309 		c = ccc;
1310 	}
1311 
1312 	/*
1313 	 * Read in contiguous digits until the first non-digit character.
1314 	 */
1315 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1316 	    c = dtrace_load8(++pos))
1317 		val = val * base + x;
1318 
1319 	return (neg ? -val : val);
1320 }
1321 
1322 
1323 /*
1324  * Compare two strings using safe loads.
1325  */
1326 static int
dtrace_strncmp(const char * s1,const char * s2,size_t limit)1327 dtrace_strncmp(const char *s1, const char *s2, size_t limit)
1328 {
1329 	uint8_t c1, c2;
1330 	volatile uint16_t *flags;
1331 
1332 	if (s1 == s2 || limit == 0)
1333 		return (0);
1334 
1335 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1336 
1337 	do {
1338 		if (s1 == NULL) {
1339 			c1 = '\0';
1340 		} else {
1341 			c1 = dtrace_load8((uintptr_t)s1++);
1342 		}
1343 
1344 		if (s2 == NULL) {
1345 			c2 = '\0';
1346 		} else {
1347 			c2 = dtrace_load8((uintptr_t)s2++);
1348 		}
1349 
1350 		if (c1 != c2)
1351 			return (c1 - c2);
1352 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1353 
1354 	return (0);
1355 }
1356 
1357 /*
1358  * Compute strlen(s) for a string using safe memory accesses.  The additional
1359  * len parameter is used to specify a maximum length to ensure completion.
1360  */
1361 static size_t
dtrace_strlen(const char * s,size_t lim)1362 dtrace_strlen(const char *s, size_t lim)
1363 {
1364 	uint_t len;
1365 
1366 	for (len = 0; len != lim; len++) {
1367 		if (dtrace_load8((uintptr_t)s++) == '\0')
1368 			break;
1369 	}
1370 
1371 	return (len);
1372 }
1373 
1374 /*
1375  * Check if an address falls within a toxic region.
1376  */
1377 static int
dtrace_istoxic(uintptr_t kaddr,size_t size)1378 dtrace_istoxic(uintptr_t kaddr, size_t size)
1379 {
1380 	uintptr_t taddr, tsize;
1381 	int i;
1382 
1383 	for (i = 0; i < dtrace_toxranges; i++) {
1384 		taddr = dtrace_toxrange[i].dtt_base;
1385 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1386 
1387 		if (kaddr - taddr < tsize) {
1388 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1389 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1390 			return (1);
1391 		}
1392 
1393 		if (taddr - kaddr < size) {
1394 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1395 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1396 			return (1);
1397 		}
1398 	}
1399 
1400 	return (0);
1401 }
1402 
1403 /*
1404  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1405  * memory specified by the DIF program.  The dst is assumed to be safe memory
1406  * that we can store to directly because it is managed by DTrace.  As with
1407  * standard bcopy, overlapping copies are handled properly.
1408  */
1409 static void
dtrace_bcopy(const void * src,void * dst,size_t len)1410 dtrace_bcopy(const void *src, void *dst, size_t len)
1411 {
1412 	if (len != 0) {
1413 		uint8_t *s1 = dst;
1414 		const uint8_t *s2 = src;
1415 
1416 		if (s1 <= s2) {
1417 			do {
1418 				*s1++ = dtrace_load8((uintptr_t)s2++);
1419 			} while (--len != 0);
1420 		} else {
1421 			s2 += len;
1422 			s1 += len;
1423 
1424 			do {
1425 				*--s1 = dtrace_load8((uintptr_t)--s2);
1426 			} while (--len != 0);
1427 		}
1428 	}
1429 }
1430 
1431 /*
1432  * Copy src to dst using safe memory accesses, up to either the specified
1433  * length, or the point that a nul byte is encountered.  The src is assumed to
1434  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1435  * safe memory that we can store to directly because it is managed by DTrace.
1436  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1437  */
1438 static void
dtrace_strcpy(const void * src,void * dst,size_t len)1439 dtrace_strcpy(const void *src, void *dst, size_t len)
1440 {
1441 	if (len != 0) {
1442 		uint8_t *s1 = dst, c;
1443 		const uint8_t *s2 = src;
1444 
1445 		do {
1446 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1447 		} while (--len != 0 && c != '\0');
1448 	}
1449 }
1450 
1451 /*
1452  * Copy src to dst, deriving the size and type from the specified (BYREF)
1453  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1454  * program.  The dst is assumed to be DTrace variable memory that is of the
1455  * specified type; we assume that we can store to directly.
1456  */
1457 static void
dtrace_vcopy(void * src,void * dst,dtrace_diftype_t * type,size_t limit)1458 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1459 {
1460 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1461 
1462 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1463 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1464 	} else {
1465 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1466 	}
1467 }
1468 
1469 /*
1470  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1471  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1472  * safe memory that we can access directly because it is managed by DTrace.
1473  */
1474 static int
dtrace_bcmp(const void * s1,const void * s2,size_t len)1475 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1476 {
1477 	volatile uint16_t *flags;
1478 
1479 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1480 
1481 	if (s1 == s2)
1482 		return (0);
1483 
1484 	if (s1 == NULL || s2 == NULL)
1485 		return (1);
1486 
1487 	if (s1 != s2 && len != 0) {
1488 		const uint8_t *ps1 = s1;
1489 		const uint8_t *ps2 = s2;
1490 
1491 		do {
1492 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1493 				return (1);
1494 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1495 	}
1496 	return (0);
1497 }
1498 
1499 /*
1500  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1501  * is for safe DTrace-managed memory only.
1502  */
1503 static void
dtrace_bzero(void * dst,size_t len)1504 dtrace_bzero(void *dst, size_t len)
1505 {
1506 	uchar_t *cp;
1507 
1508 	for (cp = dst; len != 0; len--)
1509 		*cp++ = 0;
1510 }
1511 
1512 static void
dtrace_add_128(uint64_t * addend1,uint64_t * addend2,uint64_t * sum)1513 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1514 {
1515 	uint64_t result[2];
1516 
1517 	result[0] = addend1[0] + addend2[0];
1518 	result[1] = addend1[1] + addend2[1] +
1519 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1520 
1521 	sum[0] = result[0];
1522 	sum[1] = result[1];
1523 }
1524 
1525 /*
1526  * Shift the 128-bit value in a by b. If b is positive, shift left.
1527  * If b is negative, shift right.
1528  */
1529 static void
dtrace_shift_128(uint64_t * a,int b)1530 dtrace_shift_128(uint64_t *a, int b)
1531 {
1532 	uint64_t mask;
1533 
1534 	if (b == 0)
1535 		return;
1536 
1537 	if (b < 0) {
1538 		b = -b;
1539 		if (b >= 64) {
1540 			a[0] = a[1] >> (b - 64);
1541 			a[1] = 0;
1542 		} else {
1543 			a[0] >>= b;
1544 			mask = 1LL << (64 - b);
1545 			mask -= 1;
1546 			a[0] |= ((a[1] & mask) << (64 - b));
1547 			a[1] >>= b;
1548 		}
1549 	} else {
1550 		if (b >= 64) {
1551 			a[1] = a[0] << (b - 64);
1552 			a[0] = 0;
1553 		} else {
1554 			a[1] <<= b;
1555 			mask = a[0] >> (64 - b);
1556 			a[1] |= mask;
1557 			a[0] <<= b;
1558 		}
1559 	}
1560 }
1561 
1562 /*
1563  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1564  * use native multiplication on those, and then re-combine into the
1565  * resulting 128-bit value.
1566  *
1567  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1568  *     hi1 * hi2 << 64 +
1569  *     hi1 * lo2 << 32 +
1570  *     hi2 * lo1 << 32 +
1571  *     lo1 * lo2
1572  */
1573 static void
dtrace_multiply_128(uint64_t factor1,uint64_t factor2,uint64_t * product)1574 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1575 {
1576 	uint64_t hi1, hi2, lo1, lo2;
1577 	uint64_t tmp[2];
1578 
1579 	hi1 = factor1 >> 32;
1580 	hi2 = factor2 >> 32;
1581 
1582 	lo1 = factor1 & DT_MASK_LO;
1583 	lo2 = factor2 & DT_MASK_LO;
1584 
1585 	product[0] = lo1 * lo2;
1586 	product[1] = hi1 * hi2;
1587 
1588 	tmp[0] = hi1 * lo2;
1589 	tmp[1] = 0;
1590 	dtrace_shift_128(tmp, 32);
1591 	dtrace_add_128(product, tmp, product);
1592 
1593 	tmp[0] = hi2 * lo1;
1594 	tmp[1] = 0;
1595 	dtrace_shift_128(tmp, 32);
1596 	dtrace_add_128(product, tmp, product);
1597 }
1598 
1599 /*
1600  * This privilege check should be used by actions and subroutines to
1601  * verify that the user credentials of the process that enabled the
1602  * invoking ECB match the target credentials
1603  */
1604 static int
dtrace_priv_proc_common_user(dtrace_state_t * state)1605 dtrace_priv_proc_common_user(dtrace_state_t *state)
1606 {
1607 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1608 
1609 	/*
1610 	 * We should always have a non-NULL state cred here, since if cred
1611 	 * is null (anonymous tracing), we fast-path bypass this routine.
1612 	 */
1613 	ASSERT(s_cr != NULL);
1614 
1615 	if ((cr = dtrace_CRED()) != NULL &&
1616 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1617 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1618 	    posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1619 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1620 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1621 	    posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1622 		return (1);
1623 
1624 	return (0);
1625 }
1626 
1627 /*
1628  * This privilege check should be used by actions and subroutines to
1629  * verify that the zone of the process that enabled the invoking ECB
1630  * matches the target credentials
1631  */
1632 static int
dtrace_priv_proc_common_zone(dtrace_state_t * state)1633 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1634 {
1635 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1636 #pragma unused(cr, s_cr, state) /* __APPLE__ */
1637 
1638 	/*
1639 	 * We should always have a non-NULL state cred here, since if cred
1640 	 * is null (anonymous tracing), we fast-path bypass this routine.
1641 	 */
1642 	ASSERT(s_cr != NULL);
1643 
1644 	return 1; /* APPLE NOTE: Darwin doesn't do zones. */
1645 }
1646 
1647 /*
1648  * This privilege check should be used by actions and subroutines to
1649  * verify that the process has not setuid or changed credentials.
1650  */
1651 static int
dtrace_priv_proc_common_nocd(void)1652 dtrace_priv_proc_common_nocd(void)
1653 {
1654 	return 1; /* Darwin omits "No Core Dump" flag. */
1655 }
1656 
1657 static int
dtrace_priv_proc_destructive(dtrace_state_t * state)1658 dtrace_priv_proc_destructive(dtrace_state_t *state)
1659 {
1660 	int action = state->dts_cred.dcr_action;
1661 
1662 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1663 		goto bad;
1664 
1665 	if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1666 		goto bad;
1667 
1668 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1669 	    dtrace_priv_proc_common_zone(state) == 0)
1670 		goto bad;
1671 
1672 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1673 	    dtrace_priv_proc_common_user(state) == 0)
1674 		goto bad;
1675 
1676 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1677 	    dtrace_priv_proc_common_nocd() == 0)
1678 		goto bad;
1679 
1680 	return (1);
1681 
1682 bad:
1683 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1684 
1685 	return (0);
1686 }
1687 
1688 static int
dtrace_priv_proc_control(dtrace_state_t * state)1689 dtrace_priv_proc_control(dtrace_state_t *state)
1690 {
1691 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1692 		goto bad;
1693 
1694 	if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1695 		goto bad;
1696 
1697 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1698 		return (1);
1699 
1700 	if (dtrace_priv_proc_common_zone(state) &&
1701 	    dtrace_priv_proc_common_user(state) &&
1702 	    dtrace_priv_proc_common_nocd())
1703 		return (1);
1704 
1705 bad:
1706 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1707 
1708 	return (0);
1709 }
1710 
1711 static int
dtrace_priv_proc(dtrace_state_t * state)1712 dtrace_priv_proc(dtrace_state_t *state)
1713 {
1714 	if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1715 		goto bad;
1716 
1717 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed() && !dtrace_can_attach_to_proc(current_proc()))
1718 		goto bad;
1719 
1720 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1721 		return (1);
1722 
1723 bad:
1724 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1725 
1726 	return (0);
1727 }
1728 
1729 /*
1730  * The P_LNOATTACH check is an Apple specific check.
1731  * We need a version of dtrace_priv_proc() that omits
1732  * that check for PID and EXECNAME accesses
1733  */
1734 static int
dtrace_priv_proc_relaxed(dtrace_state_t * state)1735 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1736 {
1737 
1738 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1739 		return (1);
1740 
1741 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1742 
1743 	return (0);
1744 }
1745 
1746 static int
dtrace_priv_kernel(dtrace_state_t * state)1747 dtrace_priv_kernel(dtrace_state_t *state)
1748 {
1749 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed())
1750 		goto bad;
1751 
1752 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1753 		return (1);
1754 
1755 bad:
1756 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1757 
1758 	return (0);
1759 }
1760 
1761 static int
dtrace_priv_kernel_destructive(dtrace_state_t * state)1762 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1763 {
1764 	if (dtrace_is_restricted())
1765 		goto bad;
1766 
1767 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1768 		return (1);
1769 
1770 bad:
1771 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1772 
1773 	return (0);
1774 }
1775 
1776 /*
1777  * Note:  not called from probe context.  This function is called
1778  * asynchronously (and at a regular interval) from outside of probe context to
1779  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1780  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1781  */
1782 static void
dtrace_dynvar_clean(dtrace_dstate_t * dstate)1783 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1784 {
1785 	dtrace_dynvar_t *dirty;
1786 	int work = 0;
1787 
1788 	zpercpu_foreach(dcpu, dstate->dtds_percpu) {
1789 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1790 
1791 		/*
1792 		 * If the dirty list is NULL, there is no dirty work to do.
1793 		 */
1794 		if (dcpu->dtdsc_dirty == NULL)
1795 			continue;
1796 
1797 		/*
1798 		 * If the clean list is non-NULL, then we're not going to do
1799 		 * any work for this CPU -- it means that there has not been
1800 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1801 		 * since the last time we cleaned house.
1802 		 */
1803 		if (dcpu->dtdsc_clean != NULL)
1804 			continue;
1805 
1806 		work = 1;
1807 
1808 		/*
1809 		 * Atomically move the dirty list aside.
1810 		 */
1811 		do {
1812 			dirty = dcpu->dtdsc_dirty;
1813 
1814 			/*
1815 			 * Before we zap the dirty list, set the rinsing list.
1816 			 * (This allows for a potential assertion in
1817 			 * dtrace_dynvar():  if a free dynamic variable appears
1818 			 * on a hash chain, either the dirty list or the
1819 			 * rinsing list for some CPU must be non-NULL.)
1820 			 */
1821 			dcpu->dtdsc_rinsing = dirty;
1822 			dtrace_membar_producer();
1823 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1824 		    dirty, NULL) != dirty);
1825 	}
1826 
1827 	if (!work) {
1828 		/*
1829 		 * We have no work to do; we can simply return.
1830 		 */
1831 		return;
1832 	}
1833 
1834 	dtrace_sync();
1835 
1836 	zpercpu_foreach(dcpu, dstate->dtds_percpu) {
1837 		if (dcpu->dtdsc_rinsing == NULL)
1838 			continue;
1839 
1840 		/*
1841 		 * We are now guaranteed that no hash chain contains a pointer
1842 		 * into this dirty list; we can make it clean.
1843 		 */
1844 		ASSERT(dcpu->dtdsc_clean == NULL);
1845 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1846 		dcpu->dtdsc_rinsing = NULL;
1847 	}
1848 
1849 	/*
1850 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1851 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1852 	 * This prevents a race whereby a CPU incorrectly decides that
1853 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1854 	 * after dtrace_dynvar_clean() has completed.
1855 	 */
1856 	dtrace_sync();
1857 
1858 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1859 }
1860 
1861 /*
1862  * Depending on the value of the op parameter, this function looks-up,
1863  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1864  * allocation is requested, this function will return a pointer to a
1865  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1866  * variable can be allocated.  If NULL is returned, the appropriate counter
1867  * will be incremented.
1868  */
1869 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)1870 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1871     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1872     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1873 {
1874 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1875 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1876 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1877 	processorid_t me = CPU->cpu_id, cpu = me;
1878 	dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, me);
1879 	size_t bucket, ksize;
1880 	size_t chunksize = dstate->dtds_chunksize;
1881 	uintptr_t kdata, lock, nstate;
1882 	uint_t i;
1883 
1884 	ASSERT(nkeys != 0);
1885 
1886 	/*
1887 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1888 	 * algorithm.  For the by-value portions, we perform the algorithm in
1889 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1890 	 * bit, and seems to have only a minute effect on distribution.  For
1891 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1892 	 * over each referenced byte.  It's painful to do this, but it's much
1893 	 * better than pathological hash distribution.  The efficacy of the
1894 	 * hashing algorithm (and a comparison with other algorithms) may be
1895 	 * found by running the ::dtrace_dynstat MDB dcmd.
1896 	 */
1897 	for (i = 0; i < nkeys; i++) {
1898 		if (key[i].dttk_size == 0) {
1899 			uint64_t val = key[i].dttk_value;
1900 
1901 			hashval += (val >> 48) & 0xffff;
1902 			hashval += (hashval << 10);
1903 			hashval ^= (hashval >> 6);
1904 
1905 			hashval += (val >> 32) & 0xffff;
1906 			hashval += (hashval << 10);
1907 			hashval ^= (hashval >> 6);
1908 
1909 			hashval += (val >> 16) & 0xffff;
1910 			hashval += (hashval << 10);
1911 			hashval ^= (hashval >> 6);
1912 
1913 			hashval += val & 0xffff;
1914 			hashval += (hashval << 10);
1915 			hashval ^= (hashval >> 6);
1916 		} else {
1917 			/*
1918 			 * This is incredibly painful, but it beats the hell
1919 			 * out of the alternative.
1920 			 */
1921 			uint64_t j, size = key[i].dttk_size;
1922 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1923 
1924 			if (!dtrace_canload(base, size, mstate, vstate))
1925 				break;
1926 
1927 			for (j = 0; j < size; j++) {
1928 				hashval += dtrace_load8(base + j);
1929 				hashval += (hashval << 10);
1930 				hashval ^= (hashval >> 6);
1931 			}
1932 		}
1933 	}
1934 
1935 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1936 		return (NULL);
1937 
1938 	hashval += (hashval << 3);
1939 	hashval ^= (hashval >> 11);
1940 	hashval += (hashval << 15);
1941 
1942 	/*
1943 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1944 	 * comes out to be one of our two sentinel hash values.  If this
1945 	 * actually happens, we set the hashval to be a value known to be a
1946 	 * non-sentinel value.
1947 	 */
1948 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1949 		hashval = DTRACE_DYNHASH_VALID;
1950 
1951 	/*
1952 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1953 	 * important here, tricks can be pulled to reduce it.  (However, it's
1954 	 * critical that hash collisions be kept to an absolute minimum;
1955 	 * they're much more painful than a divide.)  It's better to have a
1956 	 * solution that generates few collisions and still keeps things
1957 	 * relatively simple.
1958 	 */
1959 	bucket = hashval % dstate->dtds_hashsize;
1960 
1961 	if (op == DTRACE_DYNVAR_DEALLOC) {
1962 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1963 
1964 		for (;;) {
1965 			while ((lock = *lockp) & 1)
1966 				continue;
1967 
1968 			if (dtrace_casptr((void *)(uintptr_t)lockp,
1969 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1970 				break;
1971 		}
1972 
1973 		dtrace_membar_producer();
1974 	}
1975 
1976 top:
1977 	prev = NULL;
1978 	lock = hash[bucket].dtdh_lock;
1979 
1980 	dtrace_membar_consumer();
1981 
1982 	start = hash[bucket].dtdh_chain;
1983 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1984 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1985 	    op != DTRACE_DYNVAR_DEALLOC));
1986 
1987 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1988 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1989 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1990 
1991 		if (dvar->dtdv_hashval != hashval) {
1992 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1993 				/*
1994 				 * We've reached the sink, and therefore the
1995 				 * end of the hash chain; we can kick out of
1996 				 * the loop knowing that we have seen a valid
1997 				 * snapshot of state.
1998 				 */
1999 				ASSERT(dvar->dtdv_next == NULL);
2000 				ASSERT(dvar == &dtrace_dynhash_sink);
2001 				break;
2002 			}
2003 
2004 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2005 				/*
2006 				 * We've gone off the rails:  somewhere along
2007 				 * the line, one of the members of this hash
2008 				 * chain was deleted.  Note that we could also
2009 				 * detect this by simply letting this loop run
2010 				 * to completion, as we would eventually hit
2011 				 * the end of the dirty list.  However, we
2012 				 * want to avoid running the length of the
2013 				 * dirty list unnecessarily (it might be quite
2014 				 * long), so we catch this as early as
2015 				 * possible by detecting the hash marker.  In
2016 				 * this case, we simply set dvar to NULL and
2017 				 * break; the conditional after the loop will
2018 				 * send us back to top.
2019 				 */
2020 				dvar = NULL;
2021 				break;
2022 			}
2023 
2024 			goto next;
2025 		}
2026 
2027 		if (dtuple->dtt_nkeys != nkeys)
2028 			goto next;
2029 
2030 		for (i = 0; i < nkeys; i++, dkey++) {
2031 			if (dkey->dttk_size != key[i].dttk_size)
2032 				goto next; /* size or type mismatch */
2033 
2034 			if (dkey->dttk_size != 0) {
2035 				if (dtrace_bcmp(
2036 				    (void *)(uintptr_t)key[i].dttk_value,
2037 				    (void *)(uintptr_t)dkey->dttk_value,
2038 				    dkey->dttk_size))
2039 					goto next;
2040 			} else {
2041 				if (dkey->dttk_value != key[i].dttk_value)
2042 					goto next;
2043 			}
2044 		}
2045 
2046 		if (op != DTRACE_DYNVAR_DEALLOC)
2047 			return (dvar);
2048 
2049 		ASSERT(dvar->dtdv_next == NULL ||
2050 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2051 
2052 		if (prev != NULL) {
2053 			ASSERT(hash[bucket].dtdh_chain != dvar);
2054 			ASSERT(start != dvar);
2055 			ASSERT(prev->dtdv_next == dvar);
2056 			prev->dtdv_next = dvar->dtdv_next;
2057 		} else {
2058 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
2059 			    start, dvar->dtdv_next) != start) {
2060 				/*
2061 				 * We have failed to atomically swing the
2062 				 * hash table head pointer, presumably because
2063 				 * of a conflicting allocation on another CPU.
2064 				 * We need to reread the hash chain and try
2065 				 * again.
2066 				 */
2067 				goto top;
2068 			}
2069 		}
2070 
2071 		dtrace_membar_producer();
2072 
2073 		/*
2074 		 * Now set the hash value to indicate that it's free.
2075 		 */
2076 		ASSERT(hash[bucket].dtdh_chain != dvar);
2077 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2078 
2079 		dtrace_membar_producer();
2080 
2081 		/*
2082 		 * Set the next pointer to point at the dirty list, and
2083 		 * atomically swing the dirty pointer to the newly freed dvar.
2084 		 */
2085 		do {
2086 			next = dcpu->dtdsc_dirty;
2087 			dvar->dtdv_next = next;
2088 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2089 
2090 		/*
2091 		 * Finally, unlock this hash bucket.
2092 		 */
2093 		ASSERT(hash[bucket].dtdh_lock == lock);
2094 		ASSERT(lock & 1);
2095 		hash[bucket].dtdh_lock++;
2096 
2097 		return (NULL);
2098 next:
2099 		prev = dvar;
2100 		continue;
2101 	}
2102 
2103 	if (dvar == NULL) {
2104 		/*
2105 		 * If dvar is NULL, it is because we went off the rails:
2106 		 * one of the elements that we traversed in the hash chain
2107 		 * was deleted while we were traversing it.  In this case,
2108 		 * we assert that we aren't doing a dealloc (deallocs lock
2109 		 * the hash bucket to prevent themselves from racing with
2110 		 * one another), and retry the hash chain traversal.
2111 		 */
2112 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2113 		goto top;
2114 	}
2115 
2116 	if (op != DTRACE_DYNVAR_ALLOC) {
2117 		/*
2118 		 * If we are not to allocate a new variable, we want to
2119 		 * return NULL now.  Before we return, check that the value
2120 		 * of the lock word hasn't changed.  If it has, we may have
2121 		 * seen an inconsistent snapshot.
2122 		 */
2123 		if (op == DTRACE_DYNVAR_NOALLOC) {
2124 			if (hash[bucket].dtdh_lock != lock)
2125 				goto top;
2126 		} else {
2127 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2128 			ASSERT(hash[bucket].dtdh_lock == lock);
2129 			ASSERT(lock & 1);
2130 			hash[bucket].dtdh_lock++;
2131 		}
2132 
2133 		return (NULL);
2134 	}
2135 
2136 	/*
2137 	 * We need to allocate a new dynamic variable.  The size we need is the
2138 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2139 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2140 	 * the size of any referred-to data (dsize).  We then round the final
2141 	 * size up to the chunksize for allocation.
2142 	 */
2143 	for (ksize = 0, i = 0; i < nkeys; i++)
2144 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2145 
2146 	/*
2147 	 * This should be pretty much impossible, but could happen if, say,
2148 	 * strange DIF specified the tuple.  Ideally, this should be an
2149 	 * assertion and not an error condition -- but that requires that the
2150 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2151 	 * bullet-proof.  (That is, it must not be able to be fooled by
2152 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2153 	 * solving this would presumably not amount to solving the Halting
2154 	 * Problem -- but it still seems awfully hard.
2155 	 */
2156 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2157 	    ksize + dsize > chunksize) {
2158 		dcpu->dtdsc_drops++;
2159 		return (NULL);
2160 	}
2161 
2162 	nstate = DTRACE_DSTATE_EMPTY;
2163 
2164 	do {
2165 retry:
2166 		free = dcpu->dtdsc_free;
2167 
2168 		if (free == NULL) {
2169 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2170 			void *rval;
2171 
2172 			if (clean == NULL) {
2173 				/*
2174 				 * We're out of dynamic variable space on
2175 				 * this CPU.  Unless we have tried all CPUs,
2176 				 * we'll try to allocate from a different
2177 				 * CPU.
2178 				 */
2179 				switch (dstate->dtds_state) {
2180 				case DTRACE_DSTATE_CLEAN: {
2181 					void *sp = &dstate->dtds_state;
2182 
2183 					if (++cpu >= (int)NCPU)
2184 						cpu = 0;
2185 
2186 					if (dcpu->dtdsc_dirty != NULL &&
2187 					    nstate == DTRACE_DSTATE_EMPTY)
2188 						nstate = DTRACE_DSTATE_DIRTY;
2189 
2190 					if (dcpu->dtdsc_rinsing != NULL)
2191 						nstate = DTRACE_DSTATE_RINSING;
2192 
2193 					dcpu = zpercpu_get_cpu(dstate->dtds_percpu, cpu);
2194 
2195 					if (cpu != me)
2196 						goto retry;
2197 
2198 					(void) dtrace_cas32(sp,
2199 					    DTRACE_DSTATE_CLEAN, nstate);
2200 
2201 					/*
2202 					 * To increment the correct bean
2203 					 * counter, take another lap.
2204 					 */
2205 					goto retry;
2206 				}
2207 
2208 				case DTRACE_DSTATE_DIRTY:
2209 					dcpu->dtdsc_dirty_drops++;
2210 					break;
2211 
2212 				case DTRACE_DSTATE_RINSING:
2213 					dcpu->dtdsc_rinsing_drops++;
2214 					break;
2215 
2216 				case DTRACE_DSTATE_EMPTY:
2217 					dcpu->dtdsc_drops++;
2218 					break;
2219 				}
2220 
2221 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2222 				return (NULL);
2223 			}
2224 
2225 			/*
2226 			 * The clean list appears to be non-empty.  We want to
2227 			 * move the clean list to the free list; we start by
2228 			 * moving the clean pointer aside.
2229 			 */
2230 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2231 			    clean, NULL) != clean) {
2232 				/*
2233 				 * We are in one of two situations:
2234 				 *
2235 				 *  (a)	The clean list was switched to the
2236 				 *	free list by another CPU.
2237 				 *
2238 				 *  (b)	The clean list was added to by the
2239 				 *	cleansing cyclic.
2240 				 *
2241 				 * In either of these situations, we can
2242 				 * just reattempt the free list allocation.
2243 				 */
2244 				goto retry;
2245 			}
2246 
2247 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2248 
2249 			/*
2250 			 * Now we'll move the clean list to the free list.
2251 			 * It's impossible for this to fail:  the only way
2252 			 * the free list can be updated is through this
2253 			 * code path, and only one CPU can own the clean list.
2254 			 * Thus, it would only be possible for this to fail if
2255 			 * this code were racing with dtrace_dynvar_clean().
2256 			 * (That is, if dtrace_dynvar_clean() updated the clean
2257 			 * list, and we ended up racing to update the free
2258 			 * list.)  This race is prevented by the dtrace_sync()
2259 			 * in dtrace_dynvar_clean() -- which flushes the
2260 			 * owners of the clean lists out before resetting
2261 			 * the clean lists.
2262 			 */
2263 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2264 			ASSERT(rval == NULL);
2265 			goto retry;
2266 		}
2267 
2268 		dvar = free;
2269 		new_free = dvar->dtdv_next;
2270 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2271 
2272 	/*
2273 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2274 	 * tuple array and copy any referenced key data into the data space
2275 	 * following the tuple array.  As we do this, we relocate dttk_value
2276 	 * in the final tuple to point to the key data address in the chunk.
2277 	 */
2278 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2279 	dvar->dtdv_data = (void *)(kdata + ksize);
2280 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2281 
2282 	for (i = 0; i < nkeys; i++) {
2283 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2284 		size_t kesize = key[i].dttk_size;
2285 
2286 		if (kesize != 0) {
2287 			dtrace_bcopy(
2288 			    (const void *)(uintptr_t)key[i].dttk_value,
2289 			    (void *)kdata, kesize);
2290 			dkey->dttk_value = kdata;
2291 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2292 		} else {
2293 			dkey->dttk_value = key[i].dttk_value;
2294 		}
2295 
2296 		dkey->dttk_size = kesize;
2297 	}
2298 
2299 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2300 	dvar->dtdv_hashval = hashval;
2301 	dvar->dtdv_next = start;
2302 
2303 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2304 		return (dvar);
2305 
2306 	/*
2307 	 * The cas has failed.  Either another CPU is adding an element to
2308 	 * this hash chain, or another CPU is deleting an element from this
2309 	 * hash chain.  The simplest way to deal with both of these cases
2310 	 * (though not necessarily the most efficient) is to free our
2311 	 * allocated block and tail-call ourselves.  Note that the free is
2312 	 * to the dirty list and _not_ to the free list.  This is to prevent
2313 	 * races with allocators, above.
2314 	 */
2315 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2316 
2317 	dtrace_membar_producer();
2318 
2319 	do {
2320 		free = dcpu->dtdsc_dirty;
2321 		dvar->dtdv_next = free;
2322 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2323 
2324 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2325 }
2326 
2327 /*ARGSUSED*/
2328 static void
dtrace_aggregate_min(uint64_t * oval,uint64_t nval,uint64_t arg)2329 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2330 {
2331 #pragma unused(arg) /* __APPLE__ */
2332 	if ((int64_t)nval < (int64_t)*oval)
2333 		*oval = nval;
2334 }
2335 
2336 /*ARGSUSED*/
2337 static void
dtrace_aggregate_max(uint64_t * oval,uint64_t nval,uint64_t arg)2338 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2339 {
2340 #pragma unused(arg) /* __APPLE__ */
2341 	if ((int64_t)nval > (int64_t)*oval)
2342 		*oval = nval;
2343 }
2344 
2345 static void
dtrace_aggregate_quantize(uint64_t * quanta,uint64_t nval,uint64_t incr)2346 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2347 {
2348 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2349 	int64_t val = (int64_t)nval;
2350 
2351 	if (val < 0) {
2352 		for (i = 0; i < zero; i++) {
2353 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2354 				quanta[i] += incr;
2355 				return;
2356 			}
2357 		}
2358 	} else {
2359 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2360 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2361 				quanta[i - 1] += incr;
2362 				return;
2363 			}
2364 		}
2365 
2366 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2367 		return;
2368 	}
2369 
2370 	ASSERT(0);
2371 }
2372 
2373 static void
dtrace_aggregate_lquantize(uint64_t * lquanta,uint64_t nval,uint64_t incr)2374 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2375 {
2376 	uint64_t arg = *lquanta++;
2377 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2378 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2379 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2380 	int32_t val = (int32_t)nval, level;
2381 
2382 	ASSERT(step != 0);
2383 	ASSERT(levels != 0);
2384 
2385 	if (val < base) {
2386 		/*
2387 		 * This is an underflow.
2388 		 */
2389 		lquanta[0] += incr;
2390 		return;
2391 	}
2392 
2393 	level = (val - base) / step;
2394 
2395 	if (level < levels) {
2396 		lquanta[level + 1] += incr;
2397 		return;
2398 	}
2399 
2400 	/*
2401 	 * This is an overflow.
2402 	 */
2403 	lquanta[levels + 1] += incr;
2404 }
2405 
2406 static int
dtrace_aggregate_llquantize_bucket(int16_t factor,int16_t low,int16_t high,int16_t nsteps,int64_t value)2407 dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2408                                    int16_t nsteps, int64_t value)
2409 {
2410 	int64_t this = 1, last, next;
2411 	int base = 1, order;
2412 
2413 	for (order = 0; order < low; ++order)
2414 		this *= factor;
2415 
2416 	/*
2417 	 * If our value is less than our factor taken to the power of the
2418 	 * low order of magnitude, it goes into the zeroth bucket.
2419 	 */
2420 	if (value < this)
2421 		return 0;
2422 	else
2423 		last = this;
2424 
2425 	for (this *= factor; order <= high; ++order) {
2426 		int nbuckets = this > nsteps ? nsteps : this;
2427 
2428 		/*
2429 		 * We should not generally get log/linear quantizations
2430 		 * with a high magnitude that allows 64-bits to
2431 		 * overflow, but we nonetheless protect against this
2432 		 * by explicitly checking for overflow, and clamping
2433 		 * our value accordingly.
2434 		 */
2435 		next = this * factor;
2436 		if (next < this) {
2437 			value = this - 1;
2438 		}
2439 
2440 		/*
2441 		 * If our value lies within this order of magnitude,
2442 		 * determine its position by taking the offset within
2443 		 * the order of magnitude, dividing by the bucket
2444 		 * width, and adding to our (accumulated) base.
2445 		 */
2446 		if (value < this) {
2447 			return (base + (value - last) / (this / nbuckets));
2448 		}
2449 
2450 		base += nbuckets - (nbuckets / factor);
2451 		last = this;
2452 		this = next;
2453 	}
2454 
2455 	/*
2456 	 * Our value is greater than or equal to our factor taken to the
2457 	 * power of one plus the high magnitude -- return the top bucket.
2458 	 */
2459 	return base;
2460 }
2461 
2462 static void
dtrace_aggregate_llquantize(uint64_t * llquanta,uint64_t nval,uint64_t incr)2463 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2464 {
2465 	uint64_t arg    = *llquanta++;
2466 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2467 	uint16_t low    = DTRACE_LLQUANTIZE_LOW(arg);
2468 	uint16_t high   = DTRACE_LLQUANTIZE_HIGH(arg);
2469 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2470 
2471 	llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2472 }
2473 
2474 /*ARGSUSED*/
2475 static void
dtrace_aggregate_avg(uint64_t * data,uint64_t nval,uint64_t arg)2476 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2477 {
2478 #pragma unused(arg) /* __APPLE__ */
2479 	data[0]++;
2480 	data[1] += nval;
2481 }
2482 
2483 /*ARGSUSED*/
2484 static void
dtrace_aggregate_stddev(uint64_t * data,uint64_t nval,uint64_t arg)2485 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2486 {
2487 #pragma unused(arg) /* __APPLE__ */
2488 	int64_t snval = (int64_t)nval;
2489 	uint64_t tmp[2];
2490 
2491 	data[0]++;
2492 	data[1] += nval;
2493 
2494 	/*
2495 	 * What we want to say here is:
2496 	 *
2497 	 * data[2] += nval * nval;
2498 	 *
2499 	 * But given that nval is 64-bit, we could easily overflow, so
2500 	 * we do this as 128-bit arithmetic.
2501 	 */
2502 	if (snval < 0)
2503 		snval = -snval;
2504 
2505 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2506 	dtrace_add_128(data + 2, tmp, data + 2);
2507 }
2508 
2509 /*ARGSUSED*/
2510 static void
dtrace_aggregate_count(uint64_t * oval,uint64_t nval,uint64_t arg)2511 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2512 {
2513 #pragma unused(nval, arg) /* __APPLE__ */
2514 	*oval = *oval + 1;
2515 }
2516 
2517 /*ARGSUSED*/
2518 static void
dtrace_aggregate_sum(uint64_t * oval,uint64_t nval,uint64_t arg)2519 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2520 {
2521 #pragma unused(arg) /* __APPLE__ */
2522 	*oval += nval;
2523 }
2524 
2525 /*
2526  * Aggregate given the tuple in the principal data buffer, and the aggregating
2527  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2528  * buffer is specified as the buf parameter.  This routine does not return
2529  * failure; if there is no space in the aggregation buffer, the data will be
2530  * dropped, and a corresponding counter incremented.
2531  */
2532 __attribute__((noinline))
2533 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)2534 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2535     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2536 {
2537 #pragma unused(arg)
2538 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2539 	uint32_t i, ndx, size, fsize;
2540 	uint32_t align = sizeof (uint64_t) - 1;
2541 	dtrace_aggbuffer_t *agb;
2542 	dtrace_aggkey_t *key;
2543 	uint32_t hashval = 0, limit, isstr;
2544 	caddr_t tomax, data, kdata;
2545 	dtrace_actkind_t action;
2546 	dtrace_action_t *act;
2547 	uintptr_t offs;
2548 
2549 	if (buf == NULL)
2550 		return;
2551 
2552 	if (!agg->dtag_hasarg) {
2553 		/*
2554 		 * Currently, only quantize() and lquantize() take additional
2555 		 * arguments, and they have the same semantics:  an increment
2556 		 * value that defaults to 1 when not present.  If additional
2557 		 * aggregating actions take arguments, the setting of the
2558 		 * default argument value will presumably have to become more
2559 		 * sophisticated...
2560 		 */
2561 		arg = 1;
2562 	}
2563 
2564 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2565 	size = rec->dtrd_offset - agg->dtag_base;
2566 	fsize = size + rec->dtrd_size;
2567 
2568 	ASSERT(dbuf->dtb_tomax != NULL);
2569 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2570 
2571 	if ((tomax = buf->dtb_tomax) == NULL) {
2572 		dtrace_buffer_drop(buf);
2573 		return;
2574 	}
2575 
2576 	/*
2577 	 * The metastructure is always at the bottom of the buffer.
2578 	 */
2579 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2580 	    sizeof (dtrace_aggbuffer_t));
2581 
2582 	if (buf->dtb_offset == 0) {
2583 		/*
2584 		 * We just kludge up approximately 1/8th of the size to be
2585 		 * buckets.  If this guess ends up being routinely
2586 		 * off-the-mark, we may need to dynamically readjust this
2587 		 * based on past performance.
2588 		 */
2589 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2590 
2591 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2592 		    (uintptr_t)tomax || hashsize == 0) {
2593 			/*
2594 			 * We've been given a ludicrously small buffer;
2595 			 * increment our drop count and leave.
2596 			 */
2597 			dtrace_buffer_drop(buf);
2598 			return;
2599 		}
2600 
2601 		/*
2602 		 * And now, a pathetic attempt to try to get a an odd (or
2603 		 * perchance, a prime) hash size for better hash distribution.
2604 		 */
2605 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2606 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2607 
2608 		agb->dtagb_hashsize = hashsize;
2609 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2610 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2611 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2612 
2613 		for (i = 0; i < agb->dtagb_hashsize; i++)
2614 			agb->dtagb_hash[i] = NULL;
2615 	}
2616 
2617 	ASSERT(agg->dtag_first != NULL);
2618 	ASSERT(agg->dtag_first->dta_intuple);
2619 
2620 	/*
2621 	 * Calculate the hash value based on the key.  Note that we _don't_
2622 	 * include the aggid in the hashing (but we will store it as part of
2623 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2624 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2625 	 * gets good distribution in practice.  The efficacy of the hashing
2626 	 * algorithm (and a comparison with other algorithms) may be found by
2627 	 * running the ::dtrace_aggstat MDB dcmd.
2628 	 */
2629 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2630 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2631 		limit = i + act->dta_rec.dtrd_size;
2632 		ASSERT(limit <= size);
2633 		isstr = DTRACEACT_ISSTRING(act);
2634 
2635 		for (; i < limit; i++) {
2636 			hashval += data[i];
2637 			hashval += (hashval << 10);
2638 			hashval ^= (hashval >> 6);
2639 
2640 			if (isstr && data[i] == '\0')
2641 				break;
2642 		}
2643 	}
2644 
2645 	hashval += (hashval << 3);
2646 	hashval ^= (hashval >> 11);
2647 	hashval += (hashval << 15);
2648 
2649 	/*
2650 	 * Yes, the divide here is expensive -- but it's generally the least
2651 	 * of the performance issues given the amount of data that we iterate
2652 	 * over to compute hash values, compare data, etc.
2653 	 */
2654 	ndx = hashval % agb->dtagb_hashsize;
2655 
2656 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2657 		ASSERT((caddr_t)key >= tomax);
2658 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2659 
2660 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2661 			continue;
2662 
2663 		kdata = key->dtak_data;
2664 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2665 
2666 		for (act = agg->dtag_first; act->dta_intuple;
2667 		    act = act->dta_next) {
2668 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2669 			limit = i + act->dta_rec.dtrd_size;
2670 			ASSERT(limit <= size);
2671 			isstr = DTRACEACT_ISSTRING(act);
2672 
2673 			for (; i < limit; i++) {
2674 				if (kdata[i] != data[i])
2675 					goto next;
2676 
2677 				if (isstr && data[i] == '\0')
2678 					break;
2679 			}
2680 		}
2681 
2682 		if (action != key->dtak_action) {
2683 			/*
2684 			 * We are aggregating on the same value in the same
2685 			 * aggregation with two different aggregating actions.
2686 			 * (This should have been picked up in the compiler,
2687 			 * so we may be dealing with errant or devious DIF.)
2688 			 * This is an error condition; we indicate as much,
2689 			 * and return.
2690 			 */
2691 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2692 			return;
2693 		}
2694 
2695 		/*
2696 		 * This is a hit:  we need to apply the aggregator to
2697 		 * the value at this key.
2698 		 */
2699 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2700 		return;
2701 next:
2702 		continue;
2703 	}
2704 
2705 	/*
2706 	 * We didn't find it.  We need to allocate some zero-filled space,
2707 	 * link it into the hash table appropriately, and apply the aggregator
2708 	 * to the (zero-filled) value.
2709 	 */
2710 	offs = buf->dtb_offset;
2711 	while (offs & (align - 1))
2712 		offs += sizeof (uint32_t);
2713 
2714 	/*
2715 	 * If we don't have enough room to both allocate a new key _and_
2716 	 * its associated data, increment the drop count and return.
2717 	 */
2718 	if ((uintptr_t)tomax + offs + fsize >
2719 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2720 		dtrace_buffer_drop(buf);
2721 		return;
2722 	}
2723 
2724 	/*CONSTCOND*/
2725 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2726 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2727 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2728 
2729 	key->dtak_data = kdata = tomax + offs;
2730 	buf->dtb_offset = offs + fsize;
2731 
2732 	/*
2733 	 * Now copy the data across.
2734 	 */
2735 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2736 
2737 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2738 		kdata[i] = data[i];
2739 
2740 	/*
2741 	 * Because strings are not zeroed out by default, we need to iterate
2742 	 * looking for actions that store strings, and we need to explicitly
2743 	 * pad these strings out with zeroes.
2744 	 */
2745 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2746 		int nul;
2747 
2748 		if (!DTRACEACT_ISSTRING(act))
2749 			continue;
2750 
2751 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2752 		limit = i + act->dta_rec.dtrd_size;
2753 		ASSERT(limit <= size);
2754 
2755 		for (nul = 0; i < limit; i++) {
2756 			if (nul) {
2757 				kdata[i] = '\0';
2758 				continue;
2759 			}
2760 
2761 			if (data[i] != '\0')
2762 				continue;
2763 
2764 			nul = 1;
2765 		}
2766 	}
2767 
2768 	for (i = size; i < fsize; i++)
2769 		kdata[i] = 0;
2770 
2771 	key->dtak_hashval = hashval;
2772 	key->dtak_size = size;
2773 	key->dtak_action = action;
2774 	key->dtak_next = agb->dtagb_hash[ndx];
2775 	agb->dtagb_hash[ndx] = key;
2776 
2777 	/*
2778 	 * Finally, apply the aggregator.
2779 	 */
2780 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2781 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2782 }
2783 
2784 /*
2785  * Given consumer state, this routine finds a speculation in the INACTIVE
2786  * state and transitions it into the ACTIVE state.  If there is no speculation
2787  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2788  * incremented -- it is up to the caller to take appropriate action.
2789  */
2790 static int
dtrace_speculation(dtrace_state_t * state)2791 dtrace_speculation(dtrace_state_t *state)
2792 {
2793 	int i = 0;
2794 	dtrace_speculation_state_t current;
2795 	uint32_t *stat = &state->dts_speculations_unavail, count;
2796 
2797 	while (i < state->dts_nspeculations) {
2798 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2799 
2800 		current = spec->dtsp_state;
2801 
2802 		if (current != DTRACESPEC_INACTIVE) {
2803 			if (current == DTRACESPEC_COMMITTINGMANY ||
2804 			    current == DTRACESPEC_COMMITTING ||
2805 			    current == DTRACESPEC_DISCARDING)
2806 				stat = &state->dts_speculations_busy;
2807 			i++;
2808 			continue;
2809 		}
2810 
2811 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2812 		    current, DTRACESPEC_ACTIVE) == current)
2813 			return (i + 1);
2814 	}
2815 
2816 	/*
2817 	 * We couldn't find a speculation.  If we found as much as a single
2818 	 * busy speculation buffer, we'll attribute this failure as "busy"
2819 	 * instead of "unavail".
2820 	 */
2821 	do {
2822 		count = *stat;
2823 	} while (dtrace_cas32(stat, count, count + 1) != count);
2824 
2825 	return (0);
2826 }
2827 
2828 /*
2829  * This routine commits an active speculation.  If the specified speculation
2830  * is not in a valid state to perform a commit(), this routine will silently do
2831  * nothing.  The state of the specified speculation is transitioned according
2832  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2833  */
2834 static void
dtrace_speculation_commit(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)2835 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2836     dtrace_specid_t which)
2837 {
2838 	dtrace_speculation_t *spec;
2839 	dtrace_buffer_t *src, *dest;
2840 	uintptr_t daddr, saddr, dlimit, slimit;
2841 	dtrace_speculation_state_t current,  new = DTRACESPEC_INACTIVE;
2842 	intptr_t offs;
2843 	uint64_t timestamp;
2844 
2845 	if (which == 0)
2846 		return;
2847 
2848 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
2849 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2850 		return;
2851 	}
2852 
2853 	spec = &state->dts_speculations[which - 1];
2854 	src = &spec->dtsp_buffer[cpu];
2855 	dest = &state->dts_buffer[cpu];
2856 
2857 	do {
2858 		current = spec->dtsp_state;
2859 
2860 		if (current == DTRACESPEC_COMMITTINGMANY)
2861 			break;
2862 
2863 		switch (current) {
2864 		case DTRACESPEC_INACTIVE:
2865 		case DTRACESPEC_DISCARDING:
2866 			return;
2867 
2868 		case DTRACESPEC_COMMITTING:
2869 			/*
2870 			 * This is only possible if we are (a) commit()'ing
2871 			 * without having done a prior speculate() on this CPU
2872 			 * and (b) racing with another commit() on a different
2873 			 * CPU.  There's nothing to do -- we just assert that
2874 			 * our offset is 0.
2875 			 */
2876 			ASSERT(src->dtb_offset == 0);
2877 			return;
2878 
2879 		case DTRACESPEC_ACTIVE:
2880 			new = DTRACESPEC_COMMITTING;
2881 			break;
2882 
2883 		case DTRACESPEC_ACTIVEONE:
2884 			/*
2885 			 * This speculation is active on one CPU.  If our
2886 			 * buffer offset is non-zero, we know that the one CPU
2887 			 * must be us.  Otherwise, we are committing on a
2888 			 * different CPU from the speculate(), and we must
2889 			 * rely on being asynchronously cleaned.
2890 			 */
2891 			if (src->dtb_offset != 0) {
2892 				new = DTRACESPEC_COMMITTING;
2893 				break;
2894 			}
2895 			OS_FALLTHROUGH;
2896 
2897 		case DTRACESPEC_ACTIVEMANY:
2898 			new = DTRACESPEC_COMMITTINGMANY;
2899 			break;
2900 
2901 		default:
2902 			ASSERT(0);
2903 		}
2904 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2905 	    current, new) != current);
2906 
2907 	/*
2908 	 * We have set the state to indicate that we are committing this
2909 	 * speculation.  Now reserve the necessary space in the destination
2910 	 * buffer.
2911 	 */
2912 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2913 	    sizeof (uint64_t), state, NULL)) < 0) {
2914 		dtrace_buffer_drop(dest);
2915 		goto out;
2916 	}
2917 
2918 	/*
2919 	 * We have sufficient space to copy the speculative buffer into the
2920 	 * primary buffer.  First, modify the speculative buffer, filling
2921 	 * in the timestamp of all entries with the current time.  The data
2922 	 * must have the commit() time rather than the time it was traced,
2923 	 * so that all entries in the primary buffer are in timestamp order.
2924 	 */
2925 	timestamp = dtrace_gethrtime();
2926 	saddr = (uintptr_t)src->dtb_tomax;
2927 	slimit = saddr + src->dtb_offset;
2928 	while (saddr < slimit) {
2929 		size_t size;
2930 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2931 
2932 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2933 			saddr += sizeof (dtrace_epid_t);
2934 			continue;
2935 		}
2936 
2937 		ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2938 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2939 
2940 		ASSERT(saddr + size <= slimit);
2941 		ASSERT(size >= sizeof(dtrace_rechdr_t));
2942 		ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2943 
2944 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2945 
2946 		saddr += size;
2947 	}
2948 
2949 	/*
2950 	 * Copy the buffer across.  (Note that this is a
2951 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2952 	 * a serious performance issue, a high-performance DTrace-specific
2953 	 * bcopy() should obviously be invented.)
2954 	 */
2955 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2956 	dlimit = daddr + src->dtb_offset;
2957 	saddr = (uintptr_t)src->dtb_tomax;
2958 
2959 	/*
2960 	 * First, the aligned portion.
2961 	 */
2962 	while (dlimit - daddr >= sizeof (uint64_t)) {
2963 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2964 
2965 		daddr += sizeof (uint64_t);
2966 		saddr += sizeof (uint64_t);
2967 	}
2968 
2969 	/*
2970 	 * Now any left-over bit...
2971 	 */
2972 	while (dlimit - daddr)
2973 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2974 
2975 	/*
2976 	 * Finally, commit the reserved space in the destination buffer.
2977 	 */
2978 	dest->dtb_offset = offs + src->dtb_offset;
2979 
2980 out:
2981 	/*
2982 	 * If we're lucky enough to be the only active CPU on this speculation
2983 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2984 	 */
2985 	if (current == DTRACESPEC_ACTIVE ||
2986 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2987 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2988 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2989 #pragma unused(rval) /* __APPLE__ */
2990 
2991 		ASSERT(rval == DTRACESPEC_COMMITTING);
2992 	}
2993 
2994 	src->dtb_offset = 0;
2995 	src->dtb_xamot_drops += src->dtb_drops;
2996 	src->dtb_drops = 0;
2997 }
2998 
2999 /*
3000  * This routine discards an active speculation.  If the specified speculation
3001  * is not in a valid state to perform a discard(), this routine will silently
3002  * do nothing.  The state of the specified speculation is transitioned
3003  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3004  */
3005 __attribute__((noinline))
3006 static void
dtrace_speculation_discard(dtrace_state_t * state,processorid_t cpu,dtrace_specid_t which)3007 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3008     dtrace_specid_t which)
3009 {
3010 	dtrace_speculation_t *spec;
3011 	dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
3012 	dtrace_buffer_t *buf;
3013 
3014 	if (which == 0)
3015 		return;
3016 
3017 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
3018 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3019 		return;
3020 	}
3021 
3022 	spec = &state->dts_speculations[which - 1];
3023 	buf = &spec->dtsp_buffer[cpu];
3024 
3025 	do {
3026 		current = spec->dtsp_state;
3027 
3028 		switch (current) {
3029 		case DTRACESPEC_INACTIVE:
3030 		case DTRACESPEC_COMMITTINGMANY:
3031 		case DTRACESPEC_COMMITTING:
3032 		case DTRACESPEC_DISCARDING:
3033 			return;
3034 
3035 		case DTRACESPEC_ACTIVE:
3036 		case DTRACESPEC_ACTIVEMANY:
3037 			new = DTRACESPEC_DISCARDING;
3038 			break;
3039 
3040 		case DTRACESPEC_ACTIVEONE:
3041 			if (buf->dtb_offset != 0) {
3042 				new = DTRACESPEC_INACTIVE;
3043 			} else {
3044 				new = DTRACESPEC_DISCARDING;
3045 			}
3046 			break;
3047 
3048 		default:
3049 			ASSERT(0);
3050 		}
3051 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3052 	    current, new) != current);
3053 
3054 	buf->dtb_offset = 0;
3055 	buf->dtb_drops = 0;
3056 }
3057 
3058 /*
3059  * Note:  not called from probe context.  This function is called
3060  * asynchronously from cross call context to clean any speculations that are
3061  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
3062  * transitioned back to the INACTIVE state until all CPUs have cleaned the
3063  * speculation.
3064  */
3065 static void
dtrace_speculation_clean_here(dtrace_state_t * state)3066 dtrace_speculation_clean_here(dtrace_state_t *state)
3067 {
3068 	dtrace_icookie_t cookie;
3069 	processorid_t cpu = CPU->cpu_id;
3070 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3071 	dtrace_specid_t i;
3072 
3073 	cookie = dtrace_interrupt_disable();
3074 
3075 	if (dest->dtb_tomax == NULL) {
3076 		dtrace_interrupt_enable(cookie);
3077 		return;
3078 	}
3079 
3080 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3081 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3082 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3083 
3084 		if (src->dtb_tomax == NULL)
3085 			continue;
3086 
3087 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3088 			src->dtb_offset = 0;
3089 			continue;
3090 		}
3091 
3092 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3093 			continue;
3094 
3095 		if (src->dtb_offset == 0)
3096 			continue;
3097 
3098 		dtrace_speculation_commit(state, cpu, i + 1);
3099 	}
3100 
3101 	dtrace_interrupt_enable(cookie);
3102 }
3103 
3104 /*
3105  * Note:  not called from probe context.  This function is called
3106  * asynchronously (and at a regular interval) to clean any speculations that
3107  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
3108  * is work to be done, it cross calls all CPUs to perform that work;
3109  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3110  * INACTIVE state until they have been cleaned by all CPUs.
3111  */
3112 static void
dtrace_speculation_clean(dtrace_state_t * state)3113 dtrace_speculation_clean(dtrace_state_t *state)
3114 {
3115 	int work = 0;
3116 	uint32_t rv;
3117 	dtrace_specid_t i;
3118 
3119 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3120 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3121 
3122 		ASSERT(!spec->dtsp_cleaning);
3123 
3124 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3125 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3126 			continue;
3127 
3128 		work++;
3129 		spec->dtsp_cleaning = 1;
3130 	}
3131 
3132 	if (!work)
3133 		return;
3134 
3135 	dtrace_xcall(DTRACE_CPUALL,
3136 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3137 
3138 	/*
3139 	 * We now know that all CPUs have committed or discarded their
3140 	 * speculation buffers, as appropriate.  We can now set the state
3141 	 * to inactive.
3142 	 */
3143 	for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3144 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3145 		dtrace_speculation_state_t current, new;
3146 
3147 		if (!spec->dtsp_cleaning)
3148 			continue;
3149 
3150 		current = spec->dtsp_state;
3151 		ASSERT(current == DTRACESPEC_DISCARDING ||
3152 		    current == DTRACESPEC_COMMITTINGMANY);
3153 
3154 		new = DTRACESPEC_INACTIVE;
3155 
3156 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3157 		ASSERT(rv == current);
3158 		spec->dtsp_cleaning = 0;
3159 	}
3160 }
3161 
3162 /*
3163  * Called as part of a speculate() to get the speculative buffer associated
3164  * with a given speculation.  Returns NULL if the specified speculation is not
3165  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3166  * the active CPU is not the specified CPU -- the speculation will be
3167  * atomically transitioned into the ACTIVEMANY state.
3168  */
3169 __attribute__((noinline))
3170 static dtrace_buffer_t *
dtrace_speculation_buffer(dtrace_state_t * state,processorid_t cpuid,dtrace_specid_t which)3171 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3172     dtrace_specid_t which)
3173 {
3174 	dtrace_speculation_t *spec;
3175 	dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
3176 	dtrace_buffer_t *buf;
3177 
3178 	if (which == 0)
3179 		return (NULL);
3180 
3181 	if (which > (dtrace_specid_t)state->dts_nspeculations) {
3182 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3183 		return (NULL);
3184 	}
3185 
3186 	spec = &state->dts_speculations[which - 1];
3187 	buf = &spec->dtsp_buffer[cpuid];
3188 
3189 	do {
3190 		current = spec->dtsp_state;
3191 
3192 		switch (current) {
3193 		case DTRACESPEC_INACTIVE:
3194 		case DTRACESPEC_COMMITTINGMANY:
3195 		case DTRACESPEC_DISCARDING:
3196 			return (NULL);
3197 
3198 		case DTRACESPEC_COMMITTING:
3199 			ASSERT(buf->dtb_offset == 0);
3200 			return (NULL);
3201 
3202 		case DTRACESPEC_ACTIVEONE:
3203 			/*
3204 			 * This speculation is currently active on one CPU.
3205 			 * Check the offset in the buffer; if it's non-zero,
3206 			 * that CPU must be us (and we leave the state alone).
3207 			 * If it's zero, assume that we're starting on a new
3208 			 * CPU -- and change the state to indicate that the
3209 			 * speculation is active on more than one CPU.
3210 			 */
3211 			if (buf->dtb_offset != 0)
3212 				return (buf);
3213 
3214 			new = DTRACESPEC_ACTIVEMANY;
3215 			break;
3216 
3217 		case DTRACESPEC_ACTIVEMANY:
3218 			return (buf);
3219 
3220 		case DTRACESPEC_ACTIVE:
3221 			new = DTRACESPEC_ACTIVEONE;
3222 			break;
3223 
3224 		default:
3225 			ASSERT(0);
3226 		}
3227 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3228 	    current, new) != current);
3229 
3230 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3231 	return (buf);
3232 }
3233 
3234 /*
3235  * Return a string.  In the event that the user lacks the privilege to access
3236  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3237  * don't fail access checking.
3238  *
3239  * dtrace_dif_variable() uses this routine as a helper for various
3240  * builtin values such as 'execname' and 'probefunc.'
3241  */
3242 static
3243 uintptr_t
dtrace_dif_varstr(uintptr_t addr,dtrace_state_t * state,dtrace_mstate_t * mstate)3244 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3245     dtrace_mstate_t *mstate)
3246 {
3247 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3248 	uintptr_t ret;
3249 	size_t strsz;
3250 
3251 	/*
3252 	 * The easy case: this probe is allowed to read all of memory, so
3253 	 * we can just return this as a vanilla pointer.
3254 	 */
3255 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3256 		return (addr);
3257 
3258 	/*
3259 	 * This is the tougher case: we copy the string in question from
3260 	 * kernel memory into scratch memory and return it that way: this
3261 	 * ensures that we won't trip up when access checking tests the
3262 	 * BYREF return value.
3263 	 */
3264 	strsz = dtrace_strlen((char *)addr, size) + 1;
3265 
3266 	if (mstate->dtms_scratch_ptr + strsz >
3267 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3268 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3269 		return (0);
3270 	}
3271 
3272 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3273 	    strsz);
3274 	ret = mstate->dtms_scratch_ptr;
3275 	mstate->dtms_scratch_ptr += strsz;
3276 	return (ret);
3277 }
3278 
3279 /*
3280  * This function implements the DIF emulator's variable lookups.  The emulator
3281  * passes a reserved variable identifier and optional built-in array index.
3282  */
3283 static uint64_t
dtrace_dif_variable(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t v,uint64_t ndx)3284 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3285     uint64_t ndx)
3286 {
3287 	/*
3288 	 * If we're accessing one of the uncached arguments, we'll turn this
3289 	 * into a reference in the args array.
3290 	 */
3291 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3292 		ndx = v - DIF_VAR_ARG0;
3293 		v = DIF_VAR_ARGS;
3294 	}
3295 
3296 	switch (v) {
3297 	case DIF_VAR_ARGS:
3298 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3299 		if (ndx >= sizeof (mstate->dtms_arg) /
3300 		    sizeof (mstate->dtms_arg[0])) {
3301 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3302 			dtrace_vstate_t *vstate = &state->dts_vstate;
3303 			dtrace_provider_t *pv;
3304 			uint64_t val;
3305 			int argndx = ndx;
3306 
3307 			if (argndx < 0) {
3308 				DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3309 				return (0);
3310 			}
3311 
3312 			pv = mstate->dtms_probe->dtpr_provider;
3313 			if (pv->dtpv_pops.dtps_getargval != NULL)
3314 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3315 				    mstate->dtms_probe->dtpr_id,
3316 				    mstate->dtms_probe->dtpr_arg, argndx, aframes);
3317 			/* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
3318 			else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && argndx == 5) {
3319 			        return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
3320 			}
3321 
3322 			else
3323 				val = dtrace_getarg(argndx, aframes, mstate, vstate);
3324 
3325 			/*
3326 			 * This is regrettably required to keep the compiler
3327 			 * from tail-optimizing the call to dtrace_getarg().
3328 			 * The condition always evaluates to true, but the
3329 			 * compiler has no way of figuring that out a priori.
3330 			 * (None of this would be necessary if the compiler
3331 			 * could be relied upon to _always_ tail-optimize
3332 			 * the call to dtrace_getarg() -- but it can't.)
3333 			 */
3334 			if (mstate->dtms_probe != NULL)
3335 				return (val);
3336 
3337 			ASSERT(0);
3338 		}
3339 
3340 		return (mstate->dtms_arg[ndx]);
3341 
3342 	case DIF_VAR_UREGS: {
3343 		thread_t thread;
3344 
3345 		if (!dtrace_priv_proc(state))
3346 			return (0);
3347 
3348 		if ((thread = current_thread()) == NULL) {
3349 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3350 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3351 			return (0);
3352 		}
3353 
3354 		return (dtrace_getreg(find_user_regs(thread), ndx));
3355 	}
3356 
3357 	case DIF_VAR_VMREGS: {
3358 		uint64_t rval;
3359 
3360 		if (!dtrace_priv_kernel(state))
3361 			return (0);
3362 
3363 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3364 
3365 		rval = dtrace_getvmreg(ndx);
3366 
3367 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3368 
3369 		return (rval);
3370 	}
3371 
3372 	case DIF_VAR_CURTHREAD:
3373 		if (!dtrace_priv_kernel(state))
3374 			return (0);
3375 
3376 		return ((uint64_t)(uintptr_t)current_thread());
3377 
3378 	case DIF_VAR_TIMESTAMP:
3379 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3380 			mstate->dtms_timestamp = dtrace_gethrtime();
3381 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3382 		}
3383 		return (mstate->dtms_timestamp);
3384 
3385 	case DIF_VAR_VTIMESTAMP:
3386 		ASSERT(dtrace_vtime_references != 0);
3387 		return (dtrace_get_thread_vtime(current_thread()));
3388 
3389 	case DIF_VAR_WALLTIMESTAMP:
3390 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3391 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3392 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3393 		}
3394 		return (mstate->dtms_walltimestamp);
3395 
3396 	case DIF_VAR_MACHTIMESTAMP:
3397 		if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3398 			mstate->dtms_machtimestamp = mach_absolute_time();
3399 			mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3400 		}
3401 		return (mstate->dtms_machtimestamp);
3402 
3403 	case DIF_VAR_MACHCTIMESTAMP:
3404 		if (!(mstate->dtms_present & DTRACE_MSTATE_MACHCTIMESTAMP)) {
3405 			mstate->dtms_machctimestamp = mach_continuous_time();
3406 			mstate->dtms_present |= DTRACE_MSTATE_MACHCTIMESTAMP;
3407 		}
3408 		return (mstate->dtms_machctimestamp);
3409 
3410 
3411 	case DIF_VAR_CPU:
3412 		return ((uint64_t) dtrace_get_thread_last_cpu_id(current_thread()));
3413 
3414 	case DIF_VAR_IPL:
3415 		if (!dtrace_priv_kernel(state))
3416 			return (0);
3417 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3418 			mstate->dtms_ipl = dtrace_getipl();
3419 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3420 		}
3421 		return (mstate->dtms_ipl);
3422 
3423 	case DIF_VAR_EPID:
3424 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3425 		return (mstate->dtms_epid);
3426 
3427 	case DIF_VAR_ID:
3428 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3429 		return (mstate->dtms_probe->dtpr_id);
3430 
3431 	case DIF_VAR_STACKDEPTH:
3432 		if (!dtrace_priv_kernel(state))
3433 			return (0);
3434 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3435 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3436 
3437 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3438 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3439 		}
3440 		return (mstate->dtms_stackdepth);
3441 
3442 	case DIF_VAR_USTACKDEPTH:
3443 		if (!dtrace_priv_proc(state))
3444 			return (0);
3445 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3446 			/*
3447 			 * See comment in DIF_VAR_PID.
3448 			 */
3449 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3450 			    CPU_ON_INTR(CPU)) {
3451 				mstate->dtms_ustackdepth = 0;
3452 			} else {
3453 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3454 				mstate->dtms_ustackdepth =
3455 				    dtrace_getustackdepth();
3456 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3457 			}
3458 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3459 		}
3460 		return (mstate->dtms_ustackdepth);
3461 
3462 	case DIF_VAR_CALLER:
3463 		if (!dtrace_priv_kernel(state))
3464 			return (0);
3465 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3466 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3467 
3468 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3469 				/*
3470 				 * If this is an unanchored probe, we are
3471 				 * required to go through the slow path:
3472 				 * dtrace_caller() only guarantees correct
3473 				 * results for anchored probes.
3474 				 */
3475 				pc_t caller[2];
3476 
3477 				dtrace_getpcstack(caller, 2, aframes,
3478 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3479 				mstate->dtms_caller = caller[1];
3480 			} else if ((mstate->dtms_caller =
3481 				dtrace_caller(aframes)) == (uintptr_t)-1) {
3482 				/*
3483 				 * We have failed to do this the quick way;
3484 				 * we must resort to the slower approach of
3485 				 * calling dtrace_getpcstack().
3486 				 */
3487 				pc_t caller;
3488 
3489 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3490 				mstate->dtms_caller = caller;
3491 			}
3492 
3493 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3494 		}
3495 		return (mstate->dtms_caller);
3496 
3497 	case DIF_VAR_UCALLER:
3498 		if (!dtrace_priv_proc(state))
3499 			return (0);
3500 
3501 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3502 			uint64_t ustack[3];
3503 
3504 			/*
3505 			 * dtrace_getupcstack() fills in the first uint64_t
3506 			 * with the current PID.  The second uint64_t will
3507 			 * be the program counter at user-level.  The third
3508 			 * uint64_t will contain the caller, which is what
3509 			 * we're after.
3510 			 */
3511 			ustack[2] = 0;
3512 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3513 			dtrace_getupcstack(ustack, 3);
3514 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3515 			mstate->dtms_ucaller = ustack[2];
3516 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3517 		}
3518 
3519 		return (mstate->dtms_ucaller);
3520 
3521 	case DIF_VAR_PROBEPROV:
3522 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3523 		return (dtrace_dif_varstr(
3524 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3525 		    state, mstate));
3526 
3527 	case DIF_VAR_PROBEMOD:
3528 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3529 		return (dtrace_dif_varstr(
3530 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3531 		    state, mstate));
3532 
3533 	case DIF_VAR_PROBEFUNC:
3534 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3535 		return (dtrace_dif_varstr(
3536 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3537 		    state, mstate));
3538 
3539 	case DIF_VAR_PROBENAME:
3540 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3541 		return (dtrace_dif_varstr(
3542 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3543 		    state, mstate));
3544 
3545 	case DIF_VAR_PID:
3546 		if (!dtrace_priv_proc_relaxed(state))
3547 			return (0);
3548 
3549 		/*
3550 		 * Note that we are assuming that an unanchored probe is
3551 		 * always due to a high-level interrupt.  (And we're assuming
3552 		 * that there is only a single high level interrupt.)
3553 		 */
3554 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3555 			/* Anchored probe that fires while on an interrupt accrues to process 0 */
3556 			return 0;
3557 
3558 		return ((uint64_t)dtrace_proc_selfpid());
3559 
3560 	case DIF_VAR_PPID:
3561 		if (!dtrace_priv_proc_relaxed(state))
3562 			return (0);
3563 
3564 		/*
3565 		 * See comment in DIF_VAR_PID.
3566 		 */
3567 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3568 			return (0);
3569 
3570 		return ((uint64_t)dtrace_proc_selfppid());
3571 
3572 	case DIF_VAR_TID:
3573 		/* We do not need to check for null current_thread() */
3574 		return thread_tid(current_thread()); /* globally unique */
3575 
3576 	case DIF_VAR_PTHREAD_SELF:
3577 		if (!dtrace_priv_proc(state))
3578 			return (0);
3579 
3580 		/* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3581 		return 0;
3582 
3583 	case DIF_VAR_DISPATCHQADDR:
3584 		if (!dtrace_priv_proc(state))
3585 			return (0);
3586 
3587 		/* We do not need to check for null current_thread() */
3588 		return thread_dispatchqaddr(current_thread());
3589 
3590 	case DIF_VAR_EXECNAME:
3591 	{
3592 		char *xname = (char *)mstate->dtms_scratch_ptr;
3593 		char *pname = proc_best_name(curproc);
3594 		size_t scratch_size = sizeof(proc_name_t);
3595 
3596 		/* The scratch allocation's lifetime is that of the clause. */
3597 		if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3598 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3599 			return 0;
3600 		}
3601 
3602 		if (!dtrace_priv_proc_relaxed(state))
3603 			return (0);
3604 
3605 		mstate->dtms_scratch_ptr += scratch_size;
3606 		strlcpy(xname, pname, scratch_size);
3607 
3608 		return ((uint64_t)(uintptr_t)xname);
3609 	}
3610 
3611 
3612 	case DIF_VAR_ZONENAME:
3613 	{
3614 		/* scratch_size is equal to length('global') + 1 for the null-terminator. */
3615 		char *zname = (char *)mstate->dtms_scratch_ptr;
3616 		size_t scratch_size = 6 + 1;
3617 
3618 		if (!dtrace_priv_proc(state))
3619 			return (0);
3620 
3621 		/* The scratch allocation's lifetime is that of the clause. */
3622 		if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3623 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3624 			return 0;
3625 		}
3626 
3627 		mstate->dtms_scratch_ptr += scratch_size;
3628 
3629 		/* The kernel does not provide zonename, it will always return 'global'. */
3630 		strlcpy(zname, "global", scratch_size);
3631 
3632 		return ((uint64_t)(uintptr_t)zname);
3633 	}
3634 
3635 #if CONFIG_PERVASIVE_CPI && MONOTONIC
3636 	case DIF_VAR_CPUINSTRS:
3637 		return mt_cur_cpu_instrs();
3638 
3639 	case DIF_VAR_CPUCYCLES:
3640 		return mt_cur_cpu_cycles();
3641 
3642 	case DIF_VAR_VINSTRS: {
3643         struct recount_usage usage = { 0 };
3644         recount_current_thread_usage(&usage);
3645         return usage.ru_instructions;
3646     }
3647 
3648 	case DIF_VAR_VCYCLES: {
3649         struct recount_usage usage = { 0 };
3650         recount_current_thread_usage(&usage);
3651         return usage.ru_cycles;
3652     }
3653 #else /* CONFIG_PERVASIVE_CPI && MONOTONIC */
3654 	case DIF_VAR_CPUINSTRS: /* FALLTHROUGH */
3655 	case DIF_VAR_CPUCYCLES: /* FALLTHROUGH */
3656 	case DIF_VAR_VINSTRS: /* FALLTHROUGH */
3657 	case DIF_VAR_VCYCLES: /* FALLTHROUGH */
3658 		return 0;
3659 #endif /* !CONFIG_PERVASIVE_CPI || !MONOTONIC */
3660 
3661 	case DIF_VAR_UID:
3662 		if (!dtrace_priv_proc_relaxed(state))
3663 			return (0);
3664 
3665 		/*
3666 		 * See comment in DIF_VAR_PID.
3667 		 */
3668 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3669 			return (0);
3670 
3671 		return ((uint64_t) dtrace_proc_selfruid());
3672 
3673 	case DIF_VAR_GID:
3674 		if (!dtrace_priv_proc(state))
3675 			return (0);
3676 
3677 		/*
3678 		 * See comment in DIF_VAR_PID.
3679 		 */
3680 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3681 			return (0);
3682 
3683 		if (dtrace_CRED() != NULL)
3684 			/* Credential does not require lazy initialization. */
3685 			return ((uint64_t)kauth_getgid());
3686 		else {
3687 			/* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3688 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3689 			return -1ULL;
3690 		}
3691 
3692 	case DIF_VAR_ERRNO: {
3693 		uthread_t uthread = current_uthread();
3694 		if (!dtrace_priv_proc(state))
3695 			return (0);
3696 
3697 		/*
3698 		 * See comment in DIF_VAR_PID.
3699 		 */
3700 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3701 			return (0);
3702 
3703 		if (uthread)
3704 			return (uint64_t)uthread->t_dtrace_errno;
3705 		else {
3706 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3707 			return -1ULL;
3708 		}
3709 	}
3710 
3711 	default:
3712 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3713 		return (0);
3714 	}
3715 }
3716 
3717 typedef enum dtrace_json_state {
3718 	DTRACE_JSON_REST = 1,
3719 	DTRACE_JSON_OBJECT,
3720 	DTRACE_JSON_STRING,
3721 	DTRACE_JSON_STRING_ESCAPE,
3722 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3723 	DTRACE_JSON_COLON,
3724 	DTRACE_JSON_COMMA,
3725 	DTRACE_JSON_VALUE,
3726 	DTRACE_JSON_IDENTIFIER,
3727 	DTRACE_JSON_NUMBER,
3728 	DTRACE_JSON_NUMBER_FRAC,
3729 	DTRACE_JSON_NUMBER_EXP,
3730 	DTRACE_JSON_COLLECT_OBJECT
3731 } dtrace_json_state_t;
3732 
3733 /*
3734  * This function possesses just enough knowledge about JSON to extract a single
3735  * value from a JSON string and store it in the scratch buffer.  It is able
3736  * to extract nested object values, and members of arrays by index.
3737  *
3738  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3739  * be looked up as we descend into the object tree.  e.g.
3740  *
3741  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3742  *       with nelems = 5.
3743  *
3744  * The run time of this function must be bounded above by strsize to limit the
3745  * amount of work done in probe context.  As such, it is implemented as a
3746  * simple state machine, reading one character at a time using safe loads
3747  * until we find the requested element, hit a parsing error or run off the
3748  * end of the object or string.
3749  *
3750  * As there is no way for a subroutine to return an error without interrupting
3751  * clause execution, we simply return NULL in the event of a missing key or any
3752  * other error condition.  Each NULL return in this function is commented with
3753  * the error condition it represents -- parsing or otherwise.
3754  *
3755  * The set of states for the state machine closely matches the JSON
3756  * specification (http://json.org/).  Briefly:
3757  *
3758  *   DTRACE_JSON_REST:
3759  *     Skip whitespace until we find either a top-level Object, moving
3760  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3761  *
3762  *   DTRACE_JSON_OBJECT:
3763  *     Locate the next key String in an Object.  Sets a flag to denote
3764  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3765  *
3766  *   DTRACE_JSON_COLON:
3767  *     Skip whitespace until we find the colon that separates key Strings
3768  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3769  *
3770  *   DTRACE_JSON_VALUE:
3771  *     Detects the type of the next value (String, Number, Identifier, Object
3772  *     or Array) and routes to the states that process that type.  Here we also
3773  *     deal with the element selector list if we are requested to traverse down
3774  *     into the object tree.
3775  *
3776  *   DTRACE_JSON_COMMA:
3777  *     Skip whitespace until we find the comma that separates key-value pairs
3778  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3779  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3780  *     states return to this state at the end of their value, unless otherwise
3781  *     noted.
3782  *
3783  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3784  *     Processes a Number literal from the JSON, including any exponent
3785  *     component that may be present.  Numbers are returned as strings, which
3786  *     may be passed to strtoll() if an integer is required.
3787  *
3788  *   DTRACE_JSON_IDENTIFIER:
3789  *     Processes a "true", "false" or "null" literal in the JSON.
3790  *
3791  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3792  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3793  *     Processes a String literal from the JSON, whether the String denotes
3794  *     a key, a value or part of a larger Object.  Handles all escape sequences
3795  *     present in the specification, including four-digit unicode characters,
3796  *     but merely includes the escape sequence without converting it to the
3797  *     actual escaped character.  If the String is flagged as a key, we
3798  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3799  *
3800  *   DTRACE_JSON_COLLECT_OBJECT:
3801  *     This state collects an entire Object (or Array), correctly handling
3802  *     embedded strings.  If the full element selector list matches this nested
3803  *     object, we return the Object in full as a string.  If not, we use this
3804  *     state to skip to the next value at this level and continue processing.
3805  */
3806 static char *
dtrace_json(uint64_t size,uintptr_t json,char * elemlist,int nelems,char * dest)3807 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3808     char *dest)
3809 {
3810 	dtrace_json_state_t state = DTRACE_JSON_REST;
3811 	int64_t array_elem = INT64_MIN;
3812 	int64_t array_pos = 0;
3813 	uint8_t escape_unicount = 0;
3814 	boolean_t string_is_key = B_FALSE;
3815 	boolean_t collect_object = B_FALSE;
3816 	boolean_t found_key = B_FALSE;
3817 	boolean_t in_array = B_FALSE;
3818 	uint32_t braces = 0, brackets = 0;
3819 	char *elem = elemlist;
3820 	char *dd = dest;
3821 	uintptr_t cur;
3822 
3823 	for (cur = json; cur < json + size; cur++) {
3824 		char cc = dtrace_load8(cur);
3825 		if (cc == '\0')
3826 			return (NULL);
3827 
3828 		switch (state) {
3829 		case DTRACE_JSON_REST:
3830 			if (isspace(cc))
3831 				break;
3832 
3833 			if (cc == '{') {
3834 				state = DTRACE_JSON_OBJECT;
3835 				break;
3836 			}
3837 
3838 			if (cc == '[') {
3839 				in_array = B_TRUE;
3840 				array_pos = 0;
3841 				array_elem = dtrace_strtoll(elem, 10, size);
3842 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3843 				state = DTRACE_JSON_VALUE;
3844 				break;
3845 			}
3846 
3847 			/*
3848 			 * ERROR: expected to find a top-level object or array.
3849 			 */
3850 			return (NULL);
3851 		case DTRACE_JSON_OBJECT:
3852 			if (isspace(cc))
3853 				break;
3854 
3855 			if (cc == '"') {
3856 				state = DTRACE_JSON_STRING;
3857 				string_is_key = B_TRUE;
3858 				break;
3859 			}
3860 
3861 			/*
3862 			 * ERROR: either the object did not start with a key
3863 			 * string, or we've run off the end of the object
3864 			 * without finding the requested key.
3865 			 */
3866 			return (NULL);
3867 		case DTRACE_JSON_STRING:
3868 			if (cc == '\\') {
3869 				*dd++ = '\\';
3870 				state = DTRACE_JSON_STRING_ESCAPE;
3871 				break;
3872 			}
3873 
3874 			if (cc == '"') {
3875 				if (collect_object) {
3876 					/*
3877 					 * We don't reset the dest here, as
3878 					 * the string is part of a larger
3879 					 * object being collected.
3880 					 */
3881 					*dd++ = cc;
3882 					collect_object = B_FALSE;
3883 					state = DTRACE_JSON_COLLECT_OBJECT;
3884 					break;
3885 				}
3886 				*dd = '\0';
3887 				dd = dest; /* reset string buffer */
3888 				if (string_is_key) {
3889 					if (dtrace_strncmp(dest, elem,
3890 					    size) == 0)
3891 						found_key = B_TRUE;
3892 				} else if (found_key) {
3893 					if (nelems > 1) {
3894 						/*
3895 						 * We expected an object, not
3896 						 * this string.
3897 						 */
3898 						return (NULL);
3899 					}
3900 					return (dest);
3901 				}
3902 				state = string_is_key ? DTRACE_JSON_COLON :
3903 				    DTRACE_JSON_COMMA;
3904 				string_is_key = B_FALSE;
3905 				break;
3906 			}
3907 
3908 			*dd++ = cc;
3909 			break;
3910 		case DTRACE_JSON_STRING_ESCAPE:
3911 			*dd++ = cc;
3912 			if (cc == 'u') {
3913 				escape_unicount = 0;
3914 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3915 			} else {
3916 				state = DTRACE_JSON_STRING;
3917 			}
3918 			break;
3919 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3920 			if (!isxdigit(cc)) {
3921 				/*
3922 				 * ERROR: invalid unicode escape, expected
3923 				 * four valid hexidecimal digits.
3924 				 */
3925 				return (NULL);
3926 			}
3927 
3928 			*dd++ = cc;
3929 			if (++escape_unicount == 4)
3930 				state = DTRACE_JSON_STRING;
3931 			break;
3932 		case DTRACE_JSON_COLON:
3933 			if (isspace(cc))
3934 				break;
3935 
3936 			if (cc == ':') {
3937 				state = DTRACE_JSON_VALUE;
3938 				break;
3939 			}
3940 
3941 			/*
3942 			 * ERROR: expected a colon.
3943 			 */
3944 			return (NULL);
3945 		case DTRACE_JSON_COMMA:
3946 			if (isspace(cc))
3947 				break;
3948 
3949 			if (cc == ',') {
3950 				if (in_array) {
3951 					state = DTRACE_JSON_VALUE;
3952 					if (++array_pos == array_elem)
3953 						found_key = B_TRUE;
3954 				} else {
3955 					state = DTRACE_JSON_OBJECT;
3956 				}
3957 				break;
3958 			}
3959 
3960 			/*
3961 			 * ERROR: either we hit an unexpected character, or
3962 			 * we reached the end of the object or array without
3963 			 * finding the requested key.
3964 			 */
3965 			return (NULL);
3966 		case DTRACE_JSON_IDENTIFIER:
3967 			if (islower(cc)) {
3968 				*dd++ = cc;
3969 				break;
3970 			}
3971 
3972 			*dd = '\0';
3973 			dd = dest; /* reset string buffer */
3974 
3975 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3976 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3977 			    dtrace_strncmp(dest, "null", 5) == 0) {
3978 				if (found_key) {
3979 					if (nelems > 1) {
3980 						/*
3981 						 * ERROR: We expected an object,
3982 						 * not this identifier.
3983 						 */
3984 						return (NULL);
3985 					}
3986 					return (dest);
3987 				} else {
3988 					cur--;
3989 					state = DTRACE_JSON_COMMA;
3990 					break;
3991 				}
3992 			}
3993 
3994 			/*
3995 			 * ERROR: we did not recognise the identifier as one
3996 			 * of those in the JSON specification.
3997 			 */
3998 			return (NULL);
3999 		case DTRACE_JSON_NUMBER:
4000 			if (cc == '.') {
4001 				*dd++ = cc;
4002 				state = DTRACE_JSON_NUMBER_FRAC;
4003 				break;
4004 			}
4005 
4006 			if (cc == 'x' || cc == 'X') {
4007 				/*
4008 				 * ERROR: specification explicitly excludes
4009 				 * hexidecimal or octal numbers.
4010 				 */
4011 				return (NULL);
4012 			}
4013 
4014 			OS_FALLTHROUGH;
4015 		case DTRACE_JSON_NUMBER_FRAC:
4016 			if (cc == 'e' || cc == 'E') {
4017 				*dd++ = cc;
4018 				state = DTRACE_JSON_NUMBER_EXP;
4019 				break;
4020 			}
4021 
4022 			if (cc == '+' || cc == '-') {
4023 				/*
4024 				 * ERROR: expect sign as part of exponent only.
4025 				 */
4026 				return (NULL);
4027 			}
4028 			OS_FALLTHROUGH;
4029 		case DTRACE_JSON_NUMBER_EXP:
4030 			if (isdigit(cc) || cc == '+' || cc == '-') {
4031 				*dd++ = cc;
4032 				break;
4033 			}
4034 
4035 			*dd = '\0';
4036 			dd = dest; /* reset string buffer */
4037 			if (found_key) {
4038 				if (nelems > 1) {
4039 					/*
4040 					 * ERROR: We expected an object, not
4041 					 * this number.
4042 					 */
4043 					return (NULL);
4044 				}
4045 				return (dest);
4046 			}
4047 
4048 			cur--;
4049 			state = DTRACE_JSON_COMMA;
4050 			break;
4051 		case DTRACE_JSON_VALUE:
4052 			if (isspace(cc))
4053 				break;
4054 
4055 			if (cc == '{' || cc == '[') {
4056 				if (nelems > 1 && found_key) {
4057 					in_array = cc == '[' ? B_TRUE : B_FALSE;
4058 					/*
4059 					 * If our element selector directs us
4060 					 * to descend into this nested object,
4061 					 * then move to the next selector
4062 					 * element in the list and restart the
4063 					 * state machine.
4064 					 */
4065 					while (*elem != '\0')
4066 						elem++;
4067 					elem++; /* skip the inter-element NUL */
4068 					nelems--;
4069 					dd = dest;
4070 					if (in_array) {
4071 						state = DTRACE_JSON_VALUE;
4072 						array_pos = 0;
4073 						array_elem = dtrace_strtoll(
4074 						    elem, 10, size);
4075 						found_key = array_elem == 0 ?
4076 						    B_TRUE : B_FALSE;
4077 					} else {
4078 						found_key = B_FALSE;
4079 						state = DTRACE_JSON_OBJECT;
4080 					}
4081 					break;
4082 				}
4083 
4084 				/*
4085 				 * Otherwise, we wish to either skip this
4086 				 * nested object or return it in full.
4087 				 */
4088 				if (cc == '[')
4089 					brackets = 1;
4090 				else
4091 					braces = 1;
4092 				*dd++ = cc;
4093 				state = DTRACE_JSON_COLLECT_OBJECT;
4094 				break;
4095 			}
4096 
4097 			if (cc == '"') {
4098 				state = DTRACE_JSON_STRING;
4099 				break;
4100 			}
4101 
4102 			if (islower(cc)) {
4103 				/*
4104 				 * Here we deal with true, false and null.
4105 				 */
4106 				*dd++ = cc;
4107 				state = DTRACE_JSON_IDENTIFIER;
4108 				break;
4109 			}
4110 
4111 			if (cc == '-' || isdigit(cc)) {
4112 				*dd++ = cc;
4113 				state = DTRACE_JSON_NUMBER;
4114 				break;
4115 			}
4116 
4117 			/*
4118 			 * ERROR: unexpected character at start of value.
4119 			 */
4120 			return (NULL);
4121 		case DTRACE_JSON_COLLECT_OBJECT:
4122 			if (cc == '\0')
4123 				/*
4124 				 * ERROR: unexpected end of input.
4125 				 */
4126 				return (NULL);
4127 
4128 			*dd++ = cc;
4129 			if (cc == '"') {
4130 				collect_object = B_TRUE;
4131 				state = DTRACE_JSON_STRING;
4132 				break;
4133 			}
4134 
4135 			if (cc == ']') {
4136 				if (brackets-- == 0) {
4137 					/*
4138 					 * ERROR: unbalanced brackets.
4139 					 */
4140 					return (NULL);
4141 				}
4142 			} else if (cc == '}') {
4143 				if (braces-- == 0) {
4144 					/*
4145 					 * ERROR: unbalanced braces.
4146 					 */
4147 					return (NULL);
4148 				}
4149 			} else if (cc == '{') {
4150 				braces++;
4151 			} else if (cc == '[') {
4152 				brackets++;
4153 			}
4154 
4155 			if (brackets == 0 && braces == 0) {
4156 				if (found_key) {
4157 					*dd = '\0';
4158 					return (dest);
4159 				}
4160 				dd = dest; /* reset string buffer */
4161 				state = DTRACE_JSON_COMMA;
4162 			}
4163 			break;
4164 		}
4165 	}
4166 	return (NULL);
4167 }
4168 
4169 /*
4170  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4171  * Notice that we don't bother validating the proper number of arguments or
4172  * their types in the tuple stack.  This isn't needed because all argument
4173  * interpretation is safe because of our load safety -- the worst that can
4174  * happen is that a bogus program can obtain bogus results.
4175  */
4176 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)4177 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4178     dtrace_key_t *tupregs, int nargs,
4179     dtrace_mstate_t *mstate, dtrace_state_t *state)
4180 {
4181 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4182 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4183 	dtrace_vstate_t *vstate = &state->dts_vstate;
4184 
4185 #if !defined(__APPLE__)
4186 	union {
4187 		mutex_impl_t mi;
4188 		uint64_t mx;
4189 	} m;
4190 
4191 	union {
4192 		krwlock_t ri;
4193 		uintptr_t rw;
4194 	} r;
4195 #else
4196 /* FIXME: awaits lock/mutex work */
4197 #endif /* __APPLE__ */
4198 
4199 	switch (subr) {
4200 	case DIF_SUBR_RAND:
4201 		regs[rd] = dtrace_xoroshiro128_plus_next(
4202 		    state->dts_rstate[CPU->cpu_id]);
4203 		break;
4204 
4205 #if !defined(__APPLE__)
4206 	case DIF_SUBR_MUTEX_OWNED:
4207 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4208 		    mstate, vstate)) {
4209 			regs[rd] = 0;
4210 			break;
4211 		}
4212 
4213 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4214 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4215 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4216 		else
4217 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4218 		break;
4219 
4220 	case DIF_SUBR_MUTEX_OWNER:
4221 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4222 		    mstate, vstate)) {
4223 			regs[rd] = 0;
4224 			break;
4225 		}
4226 
4227 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4228 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4229 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4230 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4231 		else
4232 			regs[rd] = 0;
4233 		break;
4234 
4235 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4236 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4237 		    mstate, vstate)) {
4238 			regs[rd] = 0;
4239 			break;
4240 		}
4241 
4242 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4243 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4244 		break;
4245 
4246 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4247 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4248 		    mstate, vstate)) {
4249 			regs[rd] = 0;
4250 			break;
4251 		}
4252 
4253 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4254 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4255 		break;
4256 
4257 	case DIF_SUBR_RW_READ_HELD: {
4258 		uintptr_t tmp;
4259 
4260 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4261 		    mstate, vstate)) {
4262 			regs[rd] = 0;
4263 			break;
4264 		}
4265 
4266 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4267 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4268 		break;
4269 	}
4270 
4271 	case DIF_SUBR_RW_WRITE_HELD:
4272 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4273 		    mstate, vstate)) {
4274 			regs[rd] = 0;
4275 			break;
4276 		}
4277 
4278 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4279 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4280 		break;
4281 
4282 	case DIF_SUBR_RW_ISWRITER:
4283 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4284 		    mstate, vstate)) {
4285 			regs[rd] = 0;
4286 			break;
4287 		}
4288 
4289 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4290 		regs[rd] = _RW_ISWRITER(&r.ri);
4291 		break;
4292 #else
4293 /* FIXME: awaits lock/mutex work */
4294 #endif /* __APPLE__ */
4295 
4296 	case DIF_SUBR_BCOPY: {
4297 		/*
4298 		 * We need to be sure that the destination is in the scratch
4299 		 * region -- no other region is allowed.
4300 		 */
4301 		uintptr_t src = tupregs[0].dttk_value;
4302 		uintptr_t dest = tupregs[1].dttk_value;
4303 		size_t size = tupregs[2].dttk_value;
4304 
4305 		if (!dtrace_inscratch(dest, size, mstate)) {
4306 			*flags |= CPU_DTRACE_BADADDR;
4307 			*illval = regs[rd];
4308 			break;
4309 		}
4310 
4311 		if (!dtrace_canload(src, size, mstate, vstate)) {
4312 			regs[rd] = 0;
4313 			break;
4314 		}
4315 
4316 		dtrace_bcopy((void *)src, (void *)dest, size);
4317 		break;
4318 	}
4319 
4320 	case DIF_SUBR_ALLOCA:
4321 	case DIF_SUBR_COPYIN: {
4322 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4323 		uint64_t size =
4324 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4325 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4326 
4327 		/*
4328 		 * Check whether the user can access kernel memory
4329 		 */
4330 		if (dtrace_priv_kernel(state) == 0) {
4331 			DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
4332 			regs[rd] = 0;
4333 			break;
4334 		}
4335 		/*
4336 		 * This action doesn't require any credential checks since
4337 		 * probes will not activate in user contexts to which the
4338 		 * enabling user does not have permissions.
4339 		 */
4340 
4341 		/*
4342 		 * Rounding up the user allocation size could have overflowed
4343 		 * a large, bogus allocation (like -1ULL) to 0.
4344 		 */
4345 		if (scratch_size < size ||
4346 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4347 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4348 			regs[rd] = 0;
4349 			break;
4350 		}
4351 
4352 		if (subr == DIF_SUBR_COPYIN) {
4353 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4354 			if (dtrace_priv_proc(state))
4355 				dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4356 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4357 		}
4358 
4359 		mstate->dtms_scratch_ptr += scratch_size;
4360 		regs[rd] = dest;
4361 		break;
4362 	}
4363 
4364 	case DIF_SUBR_COPYINTO: {
4365 		uint64_t size = tupregs[1].dttk_value;
4366 		uintptr_t dest = tupregs[2].dttk_value;
4367 
4368 		/*
4369 		 * This action doesn't require any credential checks since
4370 		 * probes will not activate in user contexts to which the
4371 		 * enabling user does not have permissions.
4372 		 */
4373 		if (!dtrace_inscratch(dest, size, mstate)) {
4374 			*flags |= CPU_DTRACE_BADADDR;
4375 			*illval = regs[rd];
4376 			break;
4377 		}
4378 
4379 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4380 		if (dtrace_priv_proc(state))
4381 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4382 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4383 		break;
4384 	}
4385 
4386 	case DIF_SUBR_COPYINSTR: {
4387 		uintptr_t dest = mstate->dtms_scratch_ptr;
4388 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4389 
4390 		if (nargs > 1 && tupregs[1].dttk_value < size)
4391 			size = tupregs[1].dttk_value + 1;
4392 
4393 		/*
4394 		 * This action doesn't require any credential checks since
4395 		 * probes will not activate in user contexts to which the
4396 		 * enabling user does not have permissions.
4397 		 */
4398 		if (!DTRACE_INSCRATCH(mstate, size)) {
4399 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4400 			regs[rd] = 0;
4401 			break;
4402 		}
4403 
4404 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4405 		if (dtrace_priv_proc(state))
4406 			dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4407 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4408 
4409 		((char *)dest)[size - 1] = '\0';
4410 		mstate->dtms_scratch_ptr += size;
4411 		regs[rd] = dest;
4412 		break;
4413 	}
4414 
4415 	case DIF_SUBR_MSGSIZE:
4416 	case DIF_SUBR_MSGDSIZE: {
4417 		/* Darwin does not implement SysV streams messages */
4418 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4419 		regs[rd] = 0;
4420 		break;
4421 	}
4422 
4423 	case DIF_SUBR_PROGENYOF: {
4424 		pid_t pid = tupregs[0].dttk_value;
4425 		struct proc *p = current_proc();
4426 		int rval = 0, lim = nprocs;
4427 
4428 		while(p && (lim-- > 0)) {
4429 			pid_t ppid;
4430 
4431 			ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
4432 			if (*flags & CPU_DTRACE_FAULT)
4433 				break;
4434 
4435 			if (ppid == pid) {
4436 				rval = 1;
4437 				break;
4438 			}
4439 
4440 			if (ppid == 0)
4441 				break; /* Can't climb process tree any further. */
4442 
4443 			p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
4444 #if __has_feature(ptrauth_calls)
4445 			p = ptrauth_strip(p, ptrauth_key_process_independent_data);
4446 #endif
4447 			if (*flags & CPU_DTRACE_FAULT)
4448 				break;
4449 		}
4450 
4451 		regs[rd] = rval;
4452 		break;
4453 	}
4454 
4455 	case DIF_SUBR_SPECULATION:
4456 		regs[rd] = dtrace_speculation(state);
4457 		break;
4458 
4459 
4460 	case DIF_SUBR_COPYOUT: {
4461 		uintptr_t kaddr = tupregs[0].dttk_value;
4462 		user_addr_t uaddr = tupregs[1].dttk_value;
4463 		uint64_t size = tupregs[2].dttk_value;
4464 
4465 		if (!dtrace_destructive_disallow &&
4466 		    dtrace_priv_proc_control(state) &&
4467 		    !dtrace_istoxic(kaddr, size) &&
4468 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4469 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4470 			dtrace_copyout(kaddr, uaddr, size, flags);
4471 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4472 		}
4473 		break;
4474 	}
4475 
4476 	case DIF_SUBR_COPYOUTSTR: {
4477 		uintptr_t kaddr = tupregs[0].dttk_value;
4478 		user_addr_t uaddr = tupregs[1].dttk_value;
4479 		uint64_t size = tupregs[2].dttk_value;
4480 		size_t lim;
4481 
4482 		if (!dtrace_destructive_disallow &&
4483 		    dtrace_priv_proc_control(state) &&
4484 		    !dtrace_istoxic(kaddr, size) &&
4485 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4486 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4487 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4488 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4489 		}
4490 		break;
4491 	}
4492 
4493 	case DIF_SUBR_STRLEN: {
4494 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4495 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4496 		size_t lim;
4497 
4498 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4499 			regs[rd] = 0;
4500 			break;
4501 		}
4502 
4503 		regs[rd] = dtrace_strlen((char *)addr, lim);
4504 
4505 		break;
4506 	}
4507 
4508 	case DIF_SUBR_STRCHR:
4509 	case DIF_SUBR_STRRCHR: {
4510 		/*
4511 		 * We're going to iterate over the string looking for the
4512 		 * specified character.  We will iterate until we have reached
4513 		 * the string length or we have found the character.  If this
4514 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4515 		 * of the specified character instead of the first.
4516 		 */
4517 		uintptr_t addr = tupregs[0].dttk_value;
4518 		uintptr_t addr_limit;
4519 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4520 		size_t lim;
4521 		char c, target = (char)tupregs[1].dttk_value;
4522 
4523 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4524 			regs[rd] = 0;
4525 			break;
4526 		}
4527 		addr_limit = addr + lim;
4528 
4529 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4530 			if ((c = dtrace_load8(addr)) == target) {
4531 				regs[rd] = addr;
4532 
4533 				if (subr == DIF_SUBR_STRCHR)
4534 					break;
4535 			}
4536 
4537 			if (c == '\0')
4538 				break;
4539 		}
4540 
4541 		break;
4542 	}
4543 
4544 	case DIF_SUBR_STRSTR:
4545 	case DIF_SUBR_INDEX:
4546 	case DIF_SUBR_RINDEX: {
4547 		/*
4548 		 * We're going to iterate over the string looking for the
4549 		 * specified string.  We will iterate until we have reached
4550 		 * the string length or we have found the string.  (Yes, this
4551 		 * is done in the most naive way possible -- but considering
4552 		 * that the string we're searching for is likely to be
4553 		 * relatively short, the complexity of Rabin-Karp or similar
4554 		 * hardly seems merited.)
4555 		 */
4556 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4557 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4558 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4559 		size_t len = dtrace_strlen(addr, size);
4560 		size_t sublen = dtrace_strlen(substr, size);
4561 		char *limit = addr + len, *orig = addr;
4562 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4563 		int inc = 1;
4564 
4565 		regs[rd] = notfound;
4566 
4567 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4568 			regs[rd] = 0;
4569 			break;
4570 		}
4571 
4572 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4573 		    vstate)) {
4574 			regs[rd] = 0;
4575 			break;
4576 		}
4577 
4578 		/*
4579 		 * strstr() and index()/rindex() have similar semantics if
4580 		 * both strings are the empty string: strstr() returns a
4581 		 * pointer to the (empty) string, and index() and rindex()
4582 		 * both return index 0 (regardless of any position argument).
4583 		 */
4584 		if (sublen == 0 && len == 0) {
4585 			if (subr == DIF_SUBR_STRSTR)
4586 				regs[rd] = (uintptr_t)addr;
4587 			else
4588 				regs[rd] = 0;
4589 			break;
4590 		}
4591 
4592 		if (subr != DIF_SUBR_STRSTR) {
4593 			if (subr == DIF_SUBR_RINDEX) {
4594 				limit = orig - 1;
4595 				addr += len;
4596 				inc = -1;
4597 			}
4598 
4599 			/*
4600 			 * Both index() and rindex() take an optional position
4601 			 * argument that denotes the starting position.
4602 			 */
4603 			if (nargs == 3) {
4604 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4605 
4606 				/*
4607 				 * If the position argument to index() is
4608 				 * negative, Perl implicitly clamps it at
4609 				 * zero.  This semantic is a little surprising
4610 				 * given the special meaning of negative
4611 				 * positions to similar Perl functions like
4612 				 * substr(), but it appears to reflect a
4613 				 * notion that index() can start from a
4614 				 * negative index and increment its way up to
4615 				 * the string.  Given this notion, Perl's
4616 				 * rindex() is at least self-consistent in
4617 				 * that it implicitly clamps positions greater
4618 				 * than the string length to be the string
4619 				 * length.  Where Perl completely loses
4620 				 * coherence, however, is when the specified
4621 				 * substring is the empty string ("").  In
4622 				 * this case, even if the position is
4623 				 * negative, rindex() returns 0 -- and even if
4624 				 * the position is greater than the length,
4625 				 * index() returns the string length.  These
4626 				 * semantics violate the notion that index()
4627 				 * should never return a value less than the
4628 				 * specified position and that rindex() should
4629 				 * never return a value greater than the
4630 				 * specified position.  (One assumes that
4631 				 * these semantics are artifacts of Perl's
4632 				 * implementation and not the results of
4633 				 * deliberate design -- it beggars belief that
4634 				 * even Larry Wall could desire such oddness.)
4635 				 * While in the abstract one would wish for
4636 				 * consistent position semantics across
4637 				 * substr(), index() and rindex() -- or at the
4638 				 * very least self-consistent position
4639 				 * semantics for index() and rindex() -- we
4640 				 * instead opt to keep with the extant Perl
4641 				 * semantics, in all their broken glory.  (Do
4642 				 * we have more desire to maintain Perl's
4643 				 * semantics than Perl does?  Probably.)
4644 				 */
4645 				if (subr == DIF_SUBR_RINDEX) {
4646 					if (pos < 0) {
4647 						if (sublen == 0)
4648 							regs[rd] = 0;
4649 						break;
4650 					}
4651 
4652 					if ((size_t)pos > len)
4653 						pos = len;
4654 				} else {
4655 					if (pos < 0)
4656 						pos = 0;
4657 
4658 					if ((size_t)pos >= len) {
4659 						if (sublen == 0)
4660 							regs[rd] = len;
4661 						break;
4662 					}
4663 				}
4664 
4665 				addr = orig + pos;
4666 			}
4667 		}
4668 
4669 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4670 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4671 				if (subr != DIF_SUBR_STRSTR) {
4672 					/*
4673 					 * As D index() and rindex() are
4674 					 * modeled on Perl (and not on awk),
4675 					 * we return a zero-based (and not a
4676 					 * one-based) index.  (For you Perl
4677 					 * weenies: no, we're not going to add
4678 					 * $[ -- and shouldn't you be at a con
4679 					 * or something?)
4680 					 */
4681 					regs[rd] = (uintptr_t)(addr - orig);
4682 					break;
4683 				}
4684 
4685 				ASSERT(subr == DIF_SUBR_STRSTR);
4686 				regs[rd] = (uintptr_t)addr;
4687 				break;
4688 			}
4689 		}
4690 
4691 		break;
4692 	}
4693 
4694 	case DIF_SUBR_STRTOK: {
4695 		uintptr_t addr = tupregs[0].dttk_value;
4696 		uintptr_t tokaddr = tupregs[1].dttk_value;
4697 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4698 		uintptr_t limit, toklimit;
4699 		size_t clim;
4700 		char *dest = (char *)mstate->dtms_scratch_ptr;
4701 		uint8_t c='\0', tokmap[32];	 /* 256 / 8 */
4702 		uint64_t i = 0;
4703 
4704 		/*
4705 		 * Check both the token buffer and (later) the input buffer,
4706 		 * since both could be non-scratch addresses.
4707 		 */
4708 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4709 			regs[rd] = 0;
4710 			break;
4711 		}
4712 		toklimit = tokaddr + clim;
4713 
4714 		if (!DTRACE_INSCRATCH(mstate, size)) {
4715 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4716 			regs[rd] = 0;
4717 			break;
4718 		}
4719 
4720 		if (addr == 0) {
4721 			/*
4722 			 * If the address specified is NULL, we use our saved
4723 			 * strtok pointer from the mstate.  Note that this
4724 			 * means that the saved strtok pointer is _only_
4725 			 * valid within multiple enablings of the same probe --
4726 			 * it behaves like an implicit clause-local variable.
4727 			 */
4728 			addr = mstate->dtms_strtok;
4729 			limit = mstate->dtms_strtok_limit;
4730 		} else {
4731 			/*
4732 			 * If the user-specified address is non-NULL we must
4733 			 * access check it.  This is the only time we have
4734 			 * a chance to do so, since this address may reside
4735 			 * in the string table of this clause-- future calls
4736 			 * (when we fetch addr from mstate->dtms_strtok)
4737 			 * would fail this access check.
4738 			 */
4739 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4740 				vstate)) {
4741 				regs[rd] = 0;
4742 				break;
4743 			}
4744 			limit = addr + clim;
4745 		}
4746 
4747 		/*
4748 		 * First, zero the token map, and then process the token
4749 		 * string -- setting a bit in the map for every character
4750 		 * found in the token string.
4751 		 */
4752 		for (i = 0; i < (int)sizeof (tokmap); i++)
4753 			tokmap[i] = 0;
4754 
4755 		for (; tokaddr < toklimit; tokaddr++) {
4756 			if ((c = dtrace_load8(tokaddr)) == '\0')
4757 				break;
4758 
4759 			ASSERT((c >> 3) < sizeof (tokmap));
4760 			tokmap[c >> 3] |= (1 << (c & 0x7));
4761 		}
4762 
4763 		for (; addr < limit; addr++) {
4764 			/*
4765 			 * We're looking for a character that is _not_
4766 			 * contained in the token string.
4767 			 */
4768 			if ((c = dtrace_load8(addr)) == '\0')
4769 				break;
4770 
4771 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4772 				break;
4773 		}
4774 
4775 		if (c == '\0') {
4776 			/*
4777 			 * We reached the end of the string without finding
4778 			 * any character that was not in the token string.
4779 			 * We return NULL in this case, and we set the saved
4780 			 * address to NULL as well.
4781 			 */
4782 			regs[rd] = 0;
4783 			mstate->dtms_strtok = 0;
4784 			mstate->dtms_strtok_limit = 0;
4785 			break;
4786 		}
4787 
4788 		/*
4789 		 * From here on, we're copying into the destination string.
4790 		 */
4791 		for (i = 0; addr < limit && i < size - 1; addr++) {
4792 			if ((c = dtrace_load8(addr)) == '\0')
4793 				break;
4794 
4795 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4796 				break;
4797 
4798 			ASSERT(i < size);
4799 			dest[i++] = c;
4800 		}
4801 
4802 		ASSERT(i < size);
4803 		dest[i] = '\0';
4804 		regs[rd] = (uintptr_t)dest;
4805 		mstate->dtms_scratch_ptr += size;
4806 		mstate->dtms_strtok = addr;
4807 		mstate->dtms_strtok_limit = limit;
4808 		break;
4809 	}
4810 
4811 	case DIF_SUBR_SUBSTR: {
4812 		uintptr_t s = tupregs[0].dttk_value;
4813 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4814 		char *d = (char *)mstate->dtms_scratch_ptr;
4815 		int64_t index = (int64_t)tupregs[1].dttk_value;
4816 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4817 		size_t len = dtrace_strlen((char *)s, size);
4818 		int64_t i = 0;
4819 
4820 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4821 			regs[rd] = 0;
4822 			break;
4823 		}
4824 
4825 		if (!DTRACE_INSCRATCH(mstate, size)) {
4826 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4827 			regs[rd] = 0;
4828 			break;
4829 		}
4830 
4831 		if (nargs <= 2)
4832 			remaining = (int64_t)size;
4833 
4834 		if (index < 0) {
4835 			index += len;
4836 
4837 			if (index < 0 && index + remaining > 0) {
4838 				remaining += index;
4839 				index = 0;
4840 			}
4841 		}
4842 
4843 		if ((size_t)index >= len || index < 0) {
4844 			remaining = 0;
4845 		} else if (remaining < 0) {
4846 			remaining += len - index;
4847 		} else if ((uint64_t)index + (uint64_t)remaining > size) {
4848 			remaining = size - index;
4849 		}
4850 
4851 		for (i = 0; i < remaining; i++) {
4852 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4853 				break;
4854 			}
4855 
4856 		d[i] = '\0';
4857 
4858 		mstate->dtms_scratch_ptr += size;
4859 		regs[rd] = (uintptr_t)d;
4860 		break;
4861 	}
4862 
4863 	case DIF_SUBR_GETMAJOR:
4864 		regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4865 		break;
4866 
4867 	case DIF_SUBR_GETMINOR:
4868 		regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4869 		break;
4870 
4871 	case DIF_SUBR_DDI_PATHNAME: {
4872 		/* APPLE NOTE: currently unsupported on Darwin */
4873 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4874 		regs[rd] = 0;
4875 		break;
4876 	}
4877 
4878 	case DIF_SUBR_STRJOIN: {
4879 		char *d = (char *)mstate->dtms_scratch_ptr;
4880 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4881 		uintptr_t s1 = tupregs[0].dttk_value;
4882 		uintptr_t s2 = tupregs[1].dttk_value;
4883 		uint64_t i = 0, j = 0;
4884 		size_t lim1, lim2;
4885 		char c;
4886 
4887 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
4888 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
4889 			regs[rd] = 0;
4890 			break;
4891 		}
4892 
4893 		if (!DTRACE_INSCRATCH(mstate, size)) {
4894 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4895 			regs[rd] = 0;
4896 			break;
4897 		}
4898 
4899 		for (;;) {
4900 			if (i >= size) {
4901 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4902 				regs[rd] = 0;
4903 				break;
4904 			}
4905 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
4906 			if ((d[i++] = c) == '\0') {
4907 				i--;
4908 				break;
4909 			}
4910 		}
4911 
4912 		for (;;) {
4913 			if (i >= size) {
4914 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4915 				regs[rd] = 0;
4916 				break;
4917 			}
4918 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
4919 			if ((d[i++] = c) == '\0')
4920 				break;
4921 		}
4922 
4923 		if (i < size) {
4924 			mstate->dtms_scratch_ptr += i;
4925 			regs[rd] = (uintptr_t)d;
4926 		}
4927 
4928 		break;
4929 	}
4930 
4931 	case DIF_SUBR_STRTOLL: {
4932 		uintptr_t s = tupregs[0].dttk_value;
4933 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4934 		size_t lim;
4935 		int base = 10;
4936 
4937 		if (nargs > 1) {
4938 			if ((base = tupregs[1].dttk_value) <= 1 ||
4939 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4940 				*flags |= CPU_DTRACE_ILLOP;
4941 				break;
4942 			}
4943 		}
4944 
4945 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
4946 			regs[rd] = INT64_MIN;
4947 			break;
4948 		}
4949 
4950 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
4951 		break;
4952 	}
4953 
4954 	case DIF_SUBR_LLTOSTR: {
4955 		int64_t i = (int64_t)tupregs[0].dttk_value;
4956 		uint64_t val, digit;
4957 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4958 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4959 		int base = 10;
4960 
4961 		if (nargs > 1) {
4962 			if ((base = tupregs[1].dttk_value) <= 1 ||
4963 			     base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4964 				*flags |= CPU_DTRACE_ILLOP;
4965 				break;
4966 			}
4967 		}
4968 
4969 		val = (base == 10 && i < 0) ? i * -1 : i;
4970 
4971 		if (!DTRACE_INSCRATCH(mstate, size)) {
4972 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4973 			regs[rd] = 0;
4974 			break;
4975 		}
4976 
4977 		for (*end-- = '\0'; val; val /= base) {
4978 			if ((digit = val % base) <= '9' - '0') {
4979 				*end-- = '0' + digit;
4980 			} else {
4981 				*end-- = 'a' + (digit - ('9' - '0') - 1);
4982 			}
4983 		}
4984 
4985 		if (i == 0 && base == 16)
4986 			*end-- = '0';
4987 
4988 		if (base == 16)
4989 			*end-- = 'x';
4990 
4991 		if (i == 0 || base == 8 || base == 16)
4992 			*end-- = '0';
4993 
4994 		if (i < 0 && base == 10)
4995 			*end-- = '-';
4996 
4997 		regs[rd] = (uintptr_t)end + 1;
4998 		mstate->dtms_scratch_ptr += size;
4999 		break;
5000 	}
5001 
5002 	case DIF_SUBR_HTONS:
5003 	case DIF_SUBR_NTOHS:
5004 #ifdef _BIG_ENDIAN
5005 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5006 #else
5007 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5008 #endif
5009 		break;
5010 
5011 
5012 	case DIF_SUBR_HTONL:
5013 	case DIF_SUBR_NTOHL:
5014 #ifdef _BIG_ENDIAN
5015 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5016 #else
5017 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5018 #endif
5019 		break;
5020 
5021 
5022 	case DIF_SUBR_HTONLL:
5023 	case DIF_SUBR_NTOHLL:
5024 #ifdef _BIG_ENDIAN
5025 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5026 #else
5027 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5028 #endif
5029 		break;
5030 
5031 
5032 	case DIF_SUBR_DIRNAME:
5033 	case DIF_SUBR_BASENAME: {
5034 		char *dest = (char *)mstate->dtms_scratch_ptr;
5035 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5036 		uintptr_t src = tupregs[0].dttk_value;
5037 		int i, j, len = dtrace_strlen((char *)src, size);
5038 		int lastbase = -1, firstbase = -1, lastdir = -1;
5039 		int start, end;
5040 
5041 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5042 			regs[rd] = 0;
5043 			break;
5044 		}
5045 
5046 		if (!DTRACE_INSCRATCH(mstate, size)) {
5047 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5048 			regs[rd] = 0;
5049 			break;
5050 		}
5051 
5052 		/*
5053 		 * The basename and dirname for a zero-length string is
5054 		 * defined to be "."
5055 		 */
5056 		if (len == 0) {
5057 			len = 1;
5058 			src = (uintptr_t)".";
5059 		}
5060 
5061 		/*
5062 		 * Start from the back of the string, moving back toward the
5063 		 * front until we see a character that isn't a slash.  That
5064 		 * character is the last character in the basename.
5065 		 */
5066 		for (i = len - 1; i >= 0; i--) {
5067 			if (dtrace_load8(src + i) != '/')
5068 				break;
5069 		}
5070 
5071 		if (i >= 0)
5072 			lastbase = i;
5073 
5074 		/*
5075 		 * Starting from the last character in the basename, move
5076 		 * towards the front until we find a slash.  The character
5077 		 * that we processed immediately before that is the first
5078 		 * character in the basename.
5079 		 */
5080 		for (; i >= 0; i--) {
5081 			if (dtrace_load8(src + i) == '/')
5082 				break;
5083 		}
5084 
5085 		if (i >= 0)
5086 			firstbase = i + 1;
5087 
5088 		/*
5089 		 * Now keep going until we find a non-slash character.  That
5090 		 * character is the last character in the dirname.
5091 		 */
5092 		for (; i >= 0; i--) {
5093 			if (dtrace_load8(src + i) != '/')
5094 				break;
5095 		}
5096 
5097 		if (i >= 0)
5098 			lastdir = i;
5099 
5100 		ASSERT(!(lastbase == -1 && firstbase != -1));
5101 		ASSERT(!(firstbase == -1 && lastdir != -1));
5102 
5103 		if (lastbase == -1) {
5104 			/*
5105 			 * We didn't find a non-slash character.  We know that
5106 			 * the length is non-zero, so the whole string must be
5107 			 * slashes.  In either the dirname or the basename
5108 			 * case, we return '/'.
5109 			 */
5110 			ASSERT(firstbase == -1);
5111 			firstbase = lastbase = lastdir = 0;
5112 		}
5113 
5114 		if (firstbase == -1) {
5115 			/*
5116 			 * The entire string consists only of a basename
5117 			 * component.  If we're looking for dirname, we need
5118 			 * to change our string to be just "."; if we're
5119 			 * looking for a basename, we'll just set the first
5120 			 * character of the basename to be 0.
5121 			 */
5122 			if (subr == DIF_SUBR_DIRNAME) {
5123 				ASSERT(lastdir == -1);
5124 				src = (uintptr_t)".";
5125 				lastdir = 0;
5126 			} else {
5127 				firstbase = 0;
5128 			}
5129 		}
5130 
5131 		if (subr == DIF_SUBR_DIRNAME) {
5132 			if (lastdir == -1) {
5133 				/*
5134 				 * We know that we have a slash in the name --
5135 				 * or lastdir would be set to 0, above.  And
5136 				 * because lastdir is -1, we know that this
5137 				 * slash must be the first character.  (That
5138 				 * is, the full string must be of the form
5139 				 * "/basename".)  In this case, the last
5140 				 * character of the directory name is 0.
5141 				 */
5142 				lastdir = 0;
5143 			}
5144 
5145 			start = 0;
5146 			end = lastdir;
5147 		} else {
5148 			ASSERT(subr == DIF_SUBR_BASENAME);
5149 			ASSERT(firstbase != -1 && lastbase != -1);
5150 			start = firstbase;
5151 			end = lastbase;
5152 		}
5153 
5154 		for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
5155 			dest[j] = dtrace_load8(src + i);
5156 
5157 		dest[j] = '\0';
5158 		regs[rd] = (uintptr_t)dest;
5159 		mstate->dtms_scratch_ptr += size;
5160 		break;
5161 	}
5162 
5163 	case DIF_SUBR_CLEANPATH: {
5164 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5165 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5166 		uintptr_t src = tupregs[0].dttk_value;
5167 		size_t lim;
5168 		size_t i = 0, j = 0;
5169 
5170 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5171 			regs[rd] = 0;
5172 			break;
5173 		}
5174 
5175 		if (!DTRACE_INSCRATCH(mstate, size)) {
5176 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5177 			regs[rd] = 0;
5178 			break;
5179 		}
5180 
5181 		/*
5182 		 * Move forward, loading each character.
5183 		 */
5184 		do {
5185 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5186 next:
5187 			if ((uint64_t)(j + 5) >= size)	/* 5 = strlen("/..c\0") */
5188 				break;
5189 
5190 			if (c != '/') {
5191 				dest[j++] = c;
5192 				continue;
5193 			}
5194 
5195 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5196 
5197 			if (c == '/') {
5198 				/*
5199 				 * We have two slashes -- we can just advance
5200 				 * to the next character.
5201 				 */
5202 				goto next;
5203 			}
5204 
5205 			if (c != '.') {
5206 				/*
5207 				 * This is not "." and it's not ".." -- we can
5208 				 * just store the "/" and this character and
5209 				 * drive on.
5210 				 */
5211 				dest[j++] = '/';
5212 				dest[j++] = c;
5213 				continue;
5214 			}
5215 
5216 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5217 
5218 			if (c == '/') {
5219 				/*
5220 				 * This is a "/./" component.  We're not going
5221 				 * to store anything in the destination buffer;
5222 				 * we're just going to go to the next component.
5223 				 */
5224 				goto next;
5225 			}
5226 
5227 			if (c != '.') {
5228 				/*
5229 				 * This is not ".." -- we can just store the
5230 				 * "/." and this character and continue
5231 				 * processing.
5232 				 */
5233 				dest[j++] = '/';
5234 				dest[j++] = '.';
5235 				dest[j++] = c;
5236 				continue;
5237 			}
5238 
5239 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5240 
5241 			if (c != '/' && c != '\0') {
5242 				/*
5243 				 * This is not ".." -- it's "..[mumble]".
5244 				 * We'll store the "/.." and this character
5245 				 * and continue processing.
5246 				 */
5247 				dest[j++] = '/';
5248 				dest[j++] = '.';
5249 				dest[j++] = '.';
5250 				dest[j++] = c;
5251 				continue;
5252 			}
5253 
5254 			/*
5255 			 * This is "/../" or "/..\0".  We need to back up
5256 			 * our destination pointer until we find a "/".
5257 			 */
5258 			i--;
5259 			while (j != 0 && dest[--j] != '/')
5260 				continue;
5261 
5262 			if (c == '\0')
5263 				dest[++j] = '/';
5264 		} while (c != '\0');
5265 
5266 		dest[j] = '\0';
5267 		regs[rd] = (uintptr_t)dest;
5268 		mstate->dtms_scratch_ptr += size;
5269 		break;
5270 	}
5271 
5272 	case DIF_SUBR_INET_NTOA:
5273 	case DIF_SUBR_INET_NTOA6:
5274 	case DIF_SUBR_INET_NTOP: {
5275 		size_t size;
5276 		int af, argi, i;
5277 		char *base, *end;
5278 
5279 		if (subr == DIF_SUBR_INET_NTOP) {
5280 			af = (int)tupregs[0].dttk_value;
5281 			argi = 1;
5282 		} else {
5283 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5284 			argi = 0;
5285 		}
5286 
5287 		if (af == AF_INET) {
5288 #if !defined(__APPLE__)
5289 			ipaddr_t ip4;
5290 #else
5291 			uint32_t ip4;
5292 #endif /* __APPLE__ */
5293 			uint8_t *ptr8, val;
5294 
5295 			/*
5296 			 * Safely load the IPv4 address.
5297 			 */
5298 #if !defined(__APPLE__)
5299 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5300 #else
5301 			if (!dtrace_canload(tupregs[argi].dttk_value, sizeof(ip4),
5302 				mstate, vstate)) {
5303 				regs[rd] = 0;
5304 				break;
5305 			}
5306 
5307 			dtrace_bcopy(
5308 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5309 			    (void *)(uintptr_t)&ip4, sizeof (ip4));
5310 #endif /* __APPLE__ */
5311 			/*
5312 			 * Check an IPv4 string will fit in scratch.
5313 			 */
5314 #if !defined(__APPLE__)
5315 			size = INET_ADDRSTRLEN;
5316 #else
5317 			size = MAX_IPv4_STR_LEN;
5318 #endif /* __APPLE__ */
5319 			if (!DTRACE_INSCRATCH(mstate, size)) {
5320 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5321 				regs[rd] = 0;
5322 				break;
5323 			}
5324 			base = (char *)mstate->dtms_scratch_ptr;
5325 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5326 
5327 			/*
5328 			 * Stringify as a dotted decimal quad.
5329 			 */
5330 			*end-- = '\0';
5331 			ptr8 = (uint8_t *)&ip4;
5332 			for (i = 3; i >= 0; i--) {
5333 				val = ptr8[i];
5334 
5335 				if (val == 0) {
5336 					*end-- = '0';
5337 				} else {
5338 					for (; val; val /= 10) {
5339 						*end-- = '0' + (val % 10);
5340 					}
5341 				}
5342 
5343 				if (i > 0)
5344 					*end-- = '.';
5345 			}
5346 			ASSERT(end + 1 >= base);
5347 
5348 		} else if (af == AF_INET6) {
5349 #if defined(__APPLE__)
5350 #define _S6_un __u6_addr
5351 #define _S6_u8 __u6_addr8
5352 #endif /* __APPLE__ */
5353 			struct in6_addr ip6;
5354 			int firstzero, tryzero, numzero, v6end;
5355 			uint16_t val;
5356 			const char digits[] = "0123456789abcdef";
5357 
5358 			/*
5359 			 * Stringify using RFC 1884 convention 2 - 16 bit
5360 			 * hexadecimal values with a zero-run compression.
5361 			 * Lower case hexadecimal digits are used.
5362 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5363 			 * The IPv4 embedded form is returned for inet_ntop,
5364 			 * just the IPv4 string is returned for inet_ntoa6.
5365 			 */
5366 
5367 			if (!dtrace_canload(tupregs[argi].dttk_value,
5368 				sizeof(struct in6_addr), mstate, vstate)) {
5369 				regs[rd] = 0;
5370 				break;
5371 			}
5372 
5373 			/*
5374 			 * Safely load the IPv6 address.
5375 			 */
5376 			dtrace_bcopy(
5377 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5378 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5379 
5380 			/*
5381 			 * Check an IPv6 string will fit in scratch.
5382 			 */
5383 			size = INET6_ADDRSTRLEN;
5384 			if (!DTRACE_INSCRATCH(mstate, size)) {
5385 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5386 				regs[rd] = 0;
5387 				break;
5388 			}
5389 			base = (char *)mstate->dtms_scratch_ptr;
5390 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5391 			*end-- = '\0';
5392 
5393 			/*
5394 			 * Find the longest run of 16 bit zero values
5395 			 * for the single allowed zero compression - "::".
5396 			 */
5397 			firstzero = -1;
5398 			tryzero = -1;
5399 			numzero = 1;
5400 			for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
5401 				if (ip6._S6_un._S6_u8[i] == 0 &&
5402 				    tryzero == -1 && i % 2 == 0) {
5403 					tryzero = i;
5404 					continue;
5405 				}
5406 
5407 				if (tryzero != -1 &&
5408 				    (ip6._S6_un._S6_u8[i] != 0 ||
5409 				    i == sizeof (struct in6_addr) - 1)) {
5410 
5411 					if (i - tryzero <= numzero) {
5412 						tryzero = -1;
5413 						continue;
5414 					}
5415 
5416 					firstzero = tryzero;
5417 					numzero = i - i % 2 - tryzero;
5418 					tryzero = -1;
5419 
5420 					if (ip6._S6_un._S6_u8[i] == 0 &&
5421 					    i == sizeof (struct in6_addr) - 1)
5422 						numzero += 2;
5423 				}
5424 			}
5425 			ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
5426 
5427 			/*
5428 			 * Check for an IPv4 embedded address.
5429 			 */
5430 			v6end = sizeof (struct in6_addr) - 2;
5431 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5432 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5433 				for (i = sizeof (struct in6_addr) - 1;
5434 				     i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
5435 					ASSERT(end >= base);
5436 
5437 					val = ip6._S6_un._S6_u8[i];
5438 
5439 					if (val == 0) {
5440 						*end-- = '0';
5441 					} else {
5442 						for (; val; val /= 10) {
5443 							*end-- = '0' + val % 10;
5444 						}
5445 					}
5446 
5447 					if (i > (int)DTRACE_V4MAPPED_OFFSET)
5448 						*end-- = '.';
5449 				}
5450 
5451 				if (subr == DIF_SUBR_INET_NTOA6)
5452 					goto inetout;
5453 
5454 				/*
5455 				 * Set v6end to skip the IPv4 address that
5456 				 * we have already stringified.
5457 				 */
5458 				v6end = 10;
5459 			}
5460 
5461 			/*
5462 			 * Build the IPv6 string by working through the
5463 			 * address in reverse.
5464 			 */
5465 			for (i = v6end; i >= 0; i -= 2) {
5466 				ASSERT(end >= base);
5467 
5468 				if (i == firstzero + numzero - 2) {
5469 					*end-- = ':';
5470 					*end-- = ':';
5471 					i -= numzero - 2;
5472 					continue;
5473 				}
5474 
5475 				if (i < 14 && i != firstzero - 2)
5476 					*end-- = ':';
5477 
5478 				val = (ip6._S6_un._S6_u8[i] << 8) +
5479 				    ip6._S6_un._S6_u8[i + 1];
5480 
5481 				if (val == 0) {
5482 					*end-- = '0';
5483 				} else {
5484 					for (; val; val /= 16) {
5485 						*end-- = digits[val % 16];
5486 					}
5487 				}
5488 			}
5489 			ASSERT(end + 1 >= base);
5490 
5491 #if defined(__APPLE__)
5492 #undef _S6_un
5493 #undef _S6_u8
5494 #endif /* __APPLE__ */
5495 		} else {
5496 			/*
5497 			 * The user didn't use AH_INET or AH_INET6.
5498 			 */
5499 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5500 			regs[rd] = 0;
5501 			break;
5502 		}
5503 
5504 inetout:	regs[rd] = (uintptr_t)end + 1;
5505 		mstate->dtms_scratch_ptr += size;
5506 		break;
5507 	}
5508 
5509 	case DIF_SUBR_JSON: {
5510 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5511 		uintptr_t json = tupregs[0].dttk_value;
5512 		size_t jsonlen = dtrace_strlen((char *)json, size);
5513 		uintptr_t elem = tupregs[1].dttk_value;
5514 		size_t elemlen = dtrace_strlen((char *)elem, size);
5515 
5516 		char *dest = (char *)mstate->dtms_scratch_ptr;
5517 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5518 		char *ee = elemlist;
5519 		int nelems = 1;
5520 		uintptr_t cur;
5521 
5522 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5523 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5524 			regs[rd] = 0;
5525 			break;
5526 		}
5527 
5528 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5529 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5530 			regs[rd] = 0;
5531 			break;
5532 		}
5533 
5534 		/*
5535 		 * Read the element selector and split it up into a packed list
5536 		 * of strings.
5537 		 */
5538 		for (cur = elem; cur < elem + elemlen; cur++) {
5539 			char cc = dtrace_load8(cur);
5540 
5541 			if (cur == elem && cc == '[') {
5542 				/*
5543 				 * If the first element selector key is
5544 				 * actually an array index then ignore the
5545 				 * bracket.
5546 				 */
5547 				continue;
5548 			}
5549 
5550 			if (cc == ']')
5551 				continue;
5552 
5553 			if (cc == '.' || cc == '[') {
5554 				nelems++;
5555 				cc = '\0';
5556 			}
5557 
5558 			*ee++ = cc;
5559 		}
5560 		*ee++ = '\0';
5561 
5562 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5563 		    nelems, dest)) != 0)
5564 			mstate->dtms_scratch_ptr += jsonlen + 1;
5565 		break;
5566 	}
5567 
5568 	case DIF_SUBR_TOUPPER:
5569 	case DIF_SUBR_TOLOWER: {
5570 		uintptr_t src = tupregs[0].dttk_value;
5571 		char *dest = (char *)mstate->dtms_scratch_ptr;
5572 		char lower, upper, base, c;
5573 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5574 		size_t len = dtrace_strlen((char*) src, size);
5575 		size_t i = 0;
5576 
5577 		lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
5578 		upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
5579 		base  = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
5580 
5581 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5582 			regs[rd] = 0;
5583 			break;
5584 		}
5585 
5586 		if (!DTRACE_INSCRATCH(mstate, size)) {
5587 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5588 			regs[rd] = 0;
5589 			break;
5590 		}
5591 
5592 		for (i = 0; i < size - 1; ++i) {
5593 			if ((c = dtrace_load8(src + i)) == '\0')
5594 				break;
5595 			if (c >= lower && c <= upper)
5596 				c = base + (c - lower);
5597 			dest[i] = c;
5598 		}
5599 
5600 		ASSERT(i < size);
5601 
5602 		dest[i] = '\0';
5603 		regs[rd] = (uintptr_t) dest;
5604 		mstate->dtms_scratch_ptr += size;
5605 
5606 		break;
5607 	}
5608 
5609 	case DIF_SUBR_STRIP:
5610 		if (!dtrace_is_valid_ptrauth_key(tupregs[1].dttk_value)) {
5611 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5612 			break;
5613 		}
5614 		regs[rd] = (uint64_t)dtrace_ptrauth_strip(
5615 		    (void*)tupregs[0].dttk_value, tupregs[1].dttk_value);
5616 		break;
5617 
5618 #if defined(__APPLE__)
5619 	case DIF_SUBR_VM_KERNEL_ADDRPERM: {
5620 		if (!dtrace_priv_kernel(state)) {
5621 			regs[rd] = 0;
5622 		} else {
5623 			regs[rd] = VM_KERNEL_ADDRPERM((vm_offset_t) tupregs[0].dttk_value);
5624 		}
5625 
5626 		break;
5627 	}
5628 
5629 	case DIF_SUBR_KDEBUG_TRACE: {
5630 		uint32_t debugid;
5631 		uintptr_t args[4] = {0};
5632 		int i;
5633 
5634 		if (nargs < 2 || nargs > 5) {
5635 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5636 			break;
5637 		}
5638 
5639 		if (dtrace_destructive_disallow ||
5640 		    !dtrace_priv_kernel_destructive(state)) {
5641 			return;
5642 		}
5643 
5644 		debugid = tupregs[0].dttk_value;
5645 		for (i = 0; i < nargs - 1; i++)
5646 			args[i] = tupregs[i + 1].dttk_value;
5647 
5648 		kernel_debug(debugid, args[0], args[1], args[2], args[3], 0);
5649 
5650 		break;
5651 	}
5652 
5653 	case DIF_SUBR_KDEBUG_TRACE_STRING: {
5654 		if (nargs != 3) {
5655 			break;
5656 		}
5657 
5658 		if (dtrace_destructive_disallow ||
5659 		    !dtrace_priv_kernel_destructive(state)) {
5660 			return;
5661 		}
5662 
5663 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5664 		uint32_t debugid = tupregs[0].dttk_value;
5665 		uint64_t str_id = tupregs[1].dttk_value;
5666 		uintptr_t src = tupregs[2].dttk_value;
5667 		size_t lim;
5668 		char buf[size];
5669 		char* str = NULL;
5670 
5671 		if (src != (uintptr_t)0) {
5672 			str = buf;
5673 			if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5674 				break;
5675 			}
5676 			dtrace_strcpy((void*)src, buf, size);
5677 		}
5678 
5679 		(void)kernel_debug_string(debugid, &str_id, str);
5680 		regs[rd] = str_id;
5681 
5682 		break;
5683 	}
5684 
5685 	case DIF_SUBR_MTONS:
5686 		absolutetime_to_nanoseconds(tupregs[0].dttk_value, &regs[rd]);
5687 
5688 		break;
5689 	case DIF_SUBR_PHYSMEM_READ: {
5690 #if DEBUG || DEVELOPMENT
5691 		if (dtrace_destructive_disallow ||
5692 		    !dtrace_priv_kernel_destructive(state)) {
5693 			return;
5694 		}
5695 		regs[rd] = dtrace_physmem_read(tupregs[0].dttk_value,
5696 		    tupregs[1].dttk_value);
5697 #else
5698 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5699 #endif /* DEBUG || DEVELOPMENT */
5700 		break;
5701 	}
5702 	case DIF_SUBR_PHYSMEM_WRITE: {
5703 #if DEBUG || DEVELOPMENT
5704 		if (dtrace_destructive_disallow ||
5705 		    !dtrace_priv_kernel_destructive(state)) {
5706 			return;
5707 		}
5708 
5709 		dtrace_physmem_write(tupregs[0].dttk_value,
5710 		    tupregs[1].dttk_value, (size_t)tupregs[2].dttk_value);
5711 #else
5712 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5713 #endif /* DEBUG || DEVELOPMENT */
5714 		break;
5715 	}
5716 
5717 	case DIF_SUBR_KVTOPHYS: {
5718 #if DEBUG || DEVELOPMENT
5719 		regs[rd] = kvtophys(tupregs[0].dttk_value);
5720 #else
5721 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5722 #endif /* DEBUG || DEVELOPMENT */
5723 		break;
5724 	}
5725 
5726 	case DIF_SUBR_LIVEDUMP: {
5727 #if DEBUG || DEVELOPMENT
5728 		if (dtrace_destructive_disallow ||
5729 		    !dtrace_priv_kernel_destructive(state)) {
5730 			break;
5731 		}
5732 
5733 		/* For the moment, there is only one type of livedump. */
5734 		if (nargs != 1 || tupregs[0].dttk_value != 0) {
5735 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5736 			break;
5737 		}
5738 
5739 		char *dest = (char *)mstate->dtms_scratch_ptr;
5740 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5741 
5742 		if (!DTRACE_INSCRATCH(mstate, size)) {
5743 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5744 			regs[rd] = 0;
5745 			break;
5746 		}
5747 
5748 		dtrace_livedump(dest, size);
5749 		regs[rd] = (uintptr_t) dest;
5750 		mstate->dtms_scratch_ptr += strlen(dest) + 1;
5751 #else
5752 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5753 #endif /* DEBUG || DEVELOPMENT */
5754 		break;
5755 	}
5756 #endif /* defined(__APPLE__) */
5757 
5758 	}
5759 }
5760 
5761 /*
5762  * Emulate the execution of DTrace IR instructions specified by the given
5763  * DIF object.  This function is deliberately void of assertions as all of
5764  * the necessary checks are handled by a call to dtrace_difo_validate().
5765  */
5766 static uint64_t
dtrace_dif_emulate(dtrace_difo_t * difo,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,dtrace_state_t * state)5767 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5768     dtrace_vstate_t *vstate, dtrace_state_t *state)
5769 {
5770 	const dif_instr_t *text = difo->dtdo_buf;
5771 	const uint_t textlen = difo->dtdo_len;
5772 	const char *strtab = difo->dtdo_strtab;
5773 	const uint64_t *inttab = difo->dtdo_inttab;
5774 
5775 	uint64_t rval = 0;
5776 	dtrace_statvar_t *svar;
5777 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5778 	dtrace_difv_t *v;
5779 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5780 	volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5781 
5782 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5783 	uint64_t regs[DIF_DIR_NREGS];
5784 	uint64_t *tmp;
5785 
5786 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5787 	int64_t cc_r;
5788 	uint_t pc = 0, id, opc = 0;
5789 	uint8_t ttop = 0;
5790 	dif_instr_t instr;
5791 	uint_t r1, r2, rd;
5792 
5793 	/*
5794 	 * We stash the current DIF object into the machine state: we need it
5795 	 * for subsequent access checking.
5796 	 */
5797 	mstate->dtms_difo = difo;
5798 
5799 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5800 
5801 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5802 		opc = pc;
5803 
5804 		instr = text[pc++];
5805 		r1 = DIF_INSTR_R1(instr);
5806 		r2 = DIF_INSTR_R2(instr);
5807 		rd = DIF_INSTR_RD(instr);
5808 
5809 		switch (DIF_INSTR_OP(instr)) {
5810 		case DIF_OP_OR:
5811 			regs[rd] = regs[r1] | regs[r2];
5812 			break;
5813 		case DIF_OP_XOR:
5814 			regs[rd] = regs[r1] ^ regs[r2];
5815 			break;
5816 		case DIF_OP_AND:
5817 			regs[rd] = regs[r1] & regs[r2];
5818 			break;
5819 		case DIF_OP_SLL:
5820 			regs[rd] = regs[r1] << regs[r2];
5821 			break;
5822 		case DIF_OP_SRL:
5823 			regs[rd] = regs[r1] >> regs[r2];
5824 			break;
5825 		case DIF_OP_SUB:
5826 			regs[rd] = regs[r1] - regs[r2];
5827 			break;
5828 		case DIF_OP_ADD:
5829 			regs[rd] = regs[r1] + regs[r2];
5830 			break;
5831 		case DIF_OP_MUL:
5832 			regs[rd] = regs[r1] * regs[r2];
5833 			break;
5834 		case DIF_OP_SDIV:
5835 			if (regs[r2] == 0) {
5836 				regs[rd] = 0;
5837 				*flags |= CPU_DTRACE_DIVZERO;
5838 			} else {
5839 				regs[rd] = (int64_t)regs[r1] /
5840 				    (int64_t)regs[r2];
5841 			}
5842 			break;
5843 
5844 		case DIF_OP_UDIV:
5845 			if (regs[r2] == 0) {
5846 				regs[rd] = 0;
5847 				*flags |= CPU_DTRACE_DIVZERO;
5848 			} else {
5849 				regs[rd] = regs[r1] / regs[r2];
5850 			}
5851 			break;
5852 
5853 		case DIF_OP_SREM:
5854 			if (regs[r2] == 0) {
5855 				regs[rd] = 0;
5856 				*flags |= CPU_DTRACE_DIVZERO;
5857 			} else {
5858 				regs[rd] = (int64_t)regs[r1] %
5859 				    (int64_t)regs[r2];
5860 			}
5861 			break;
5862 
5863 		case DIF_OP_UREM:
5864 			if (regs[r2] == 0) {
5865 				regs[rd] = 0;
5866 				*flags |= CPU_DTRACE_DIVZERO;
5867 			} else {
5868 				regs[rd] = regs[r1] % regs[r2];
5869 			}
5870 			break;
5871 
5872 		case DIF_OP_NOT:
5873 			regs[rd] = ~regs[r1];
5874 			break;
5875 		case DIF_OP_MOV:
5876 			regs[rd] = regs[r1];
5877 			break;
5878 		case DIF_OP_CMP:
5879 			cc_r = regs[r1] - regs[r2];
5880 			cc_n = cc_r < 0;
5881 			cc_z = cc_r == 0;
5882 			cc_v = 0;
5883 			cc_c = regs[r1] < regs[r2];
5884 			break;
5885 		case DIF_OP_TST:
5886 			cc_n = cc_v = cc_c = 0;
5887 			cc_z = regs[r1] == 0;
5888 			break;
5889 		case DIF_OP_BA:
5890 			pc = DIF_INSTR_LABEL(instr);
5891 			break;
5892 		case DIF_OP_BE:
5893 			if (cc_z)
5894 				pc = DIF_INSTR_LABEL(instr);
5895 			break;
5896 		case DIF_OP_BNE:
5897 			if (cc_z == 0)
5898 				pc = DIF_INSTR_LABEL(instr);
5899 			break;
5900 		case DIF_OP_BG:
5901 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5902 				pc = DIF_INSTR_LABEL(instr);
5903 			break;
5904 		case DIF_OP_BGU:
5905 			if ((cc_c | cc_z) == 0)
5906 				pc = DIF_INSTR_LABEL(instr);
5907 			break;
5908 		case DIF_OP_BGE:
5909 			if ((cc_n ^ cc_v) == 0)
5910 				pc = DIF_INSTR_LABEL(instr);
5911 			break;
5912 		case DIF_OP_BGEU:
5913 			if (cc_c == 0)
5914 				pc = DIF_INSTR_LABEL(instr);
5915 			break;
5916 		case DIF_OP_BL:
5917 			if (cc_n ^ cc_v)
5918 				pc = DIF_INSTR_LABEL(instr);
5919 			break;
5920 		case DIF_OP_BLU:
5921 			if (cc_c)
5922 				pc = DIF_INSTR_LABEL(instr);
5923 			break;
5924 		case DIF_OP_BLE:
5925 			if (cc_z | (cc_n ^ cc_v))
5926 				pc = DIF_INSTR_LABEL(instr);
5927 			break;
5928 		case DIF_OP_BLEU:
5929 			if (cc_c | cc_z)
5930 				pc = DIF_INSTR_LABEL(instr);
5931 			break;
5932 		case DIF_OP_RLDSB:
5933 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5934 				*flags |= CPU_DTRACE_KPRIV;
5935 				*illval = regs[r1];
5936 				break;
5937 			}
5938 			OS_FALLTHROUGH;
5939 		case DIF_OP_LDSB:
5940 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5941 			break;
5942 		case DIF_OP_RLDSH:
5943 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5944 				*flags |= CPU_DTRACE_KPRIV;
5945 				*illval = regs[r1];
5946 				break;
5947 			}
5948 			OS_FALLTHROUGH;
5949 		case DIF_OP_LDSH:
5950 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5951 			break;
5952 		case DIF_OP_RLDSW:
5953 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5954 				*flags |= CPU_DTRACE_KPRIV;
5955 				*illval = regs[r1];
5956 				break;
5957 			}
5958 			OS_FALLTHROUGH;
5959 		case DIF_OP_LDSW:
5960 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5961 			break;
5962 		case DIF_OP_RLDUB:
5963 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5964 				*flags |= CPU_DTRACE_KPRIV;
5965 				*illval = regs[r1];
5966 				break;
5967 			}
5968 			OS_FALLTHROUGH;
5969 		case DIF_OP_LDUB:
5970 			regs[rd] = dtrace_load8(regs[r1]);
5971 			break;
5972 		case DIF_OP_RLDUH:
5973 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5974 				*flags |= CPU_DTRACE_KPRIV;
5975 				*illval = regs[r1];
5976 				break;
5977 			}
5978 			OS_FALLTHROUGH;
5979 		case DIF_OP_LDUH:
5980 			regs[rd] = dtrace_load16(regs[r1]);
5981 			break;
5982 		case DIF_OP_RLDUW:
5983 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5984 				*flags |= CPU_DTRACE_KPRIV;
5985 				*illval = regs[r1];
5986 				break;
5987 			}
5988 			OS_FALLTHROUGH;
5989 		case DIF_OP_LDUW:
5990 			regs[rd] = dtrace_load32(regs[r1]);
5991 			break;
5992 		case DIF_OP_RLDX:
5993 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5994 				*flags |= CPU_DTRACE_KPRIV;
5995 				*illval = regs[r1];
5996 				break;
5997 			}
5998 			OS_FALLTHROUGH;
5999 		case DIF_OP_LDX:
6000 			regs[rd] = dtrace_load64(regs[r1]);
6001 			break;
6002 /*
6003  * Darwin 32-bit kernel may fetch from 64-bit user.
6004  * Do not cast regs to uintptr_t
6005  * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
6006  * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
6007  */
6008 		case DIF_OP_ULDSB:
6009 			regs[rd] = (int8_t)
6010 			    dtrace_fuword8(regs[r1]);
6011 			break;
6012 		case DIF_OP_ULDSH:
6013 			regs[rd] = (int16_t)
6014 			    dtrace_fuword16(regs[r1]);
6015 			break;
6016 		case DIF_OP_ULDSW:
6017 			regs[rd] = (int32_t)
6018 			    dtrace_fuword32(regs[r1]);
6019 			break;
6020 		case DIF_OP_ULDUB:
6021 			regs[rd] =
6022 			    dtrace_fuword8(regs[r1]);
6023 			break;
6024 		case DIF_OP_ULDUH:
6025 			regs[rd] =
6026 			    dtrace_fuword16(regs[r1]);
6027 			break;
6028 		case DIF_OP_ULDUW:
6029 			regs[rd] =
6030 			    dtrace_fuword32(regs[r1]);
6031 			break;
6032 		case DIF_OP_ULDX:
6033 			regs[rd] =
6034 			    dtrace_fuword64(regs[r1]);
6035 			break;
6036 		case DIF_OP_RET:
6037 			rval = regs[rd];
6038 			pc = textlen;
6039 			break;
6040 		case DIF_OP_NOP:
6041 			break;
6042 		case DIF_OP_SETX:
6043 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6044 			break;
6045 		case DIF_OP_SETS:
6046 			regs[rd] = (uint64_t)(uintptr_t)
6047 			    (strtab + DIF_INSTR_STRING(instr));
6048 			break;
6049 		case DIF_OP_SCMP: {
6050 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6051 			uintptr_t s1 = regs[r1];
6052 			uintptr_t s2 = regs[r2];
6053 			size_t lim1 = sz, lim2 = sz;
6054 
6055 			if (s1 != 0 &&
6056 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6057 				break;
6058 			if (s2 != 0 &&
6059 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6060 				break;
6061 
6062 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6063 				MIN(lim1, lim2));
6064 
6065 			cc_n = cc_r < 0;
6066 			cc_z = cc_r == 0;
6067 			cc_v = cc_c = 0;
6068 			break;
6069 		}
6070 		case DIF_OP_LDGA:
6071 			regs[rd] = dtrace_dif_variable(mstate, state,
6072 			    r1, regs[r2]);
6073 			break;
6074 		case DIF_OP_LDGS:
6075 			id = DIF_INSTR_VAR(instr);
6076 
6077 			if (id >= DIF_VAR_OTHER_UBASE) {
6078 				uintptr_t a;
6079 
6080 				id -= DIF_VAR_OTHER_UBASE;
6081 				svar = vstate->dtvs_globals[id];
6082 				ASSERT(svar != NULL);
6083 				v = &svar->dtsv_var;
6084 
6085 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6086 					regs[rd] = svar->dtsv_data;
6087 					break;
6088 				}
6089 
6090 				a = (uintptr_t)svar->dtsv_data;
6091 
6092 				if (*(uint8_t *)a == UINT8_MAX) {
6093 					/*
6094 					 * If the 0th byte is set to UINT8_MAX
6095 					 * then this is to be treated as a
6096 					 * reference to a NULL variable.
6097 					 */
6098 					regs[rd] = 0;
6099 				} else {
6100 					regs[rd] = a + sizeof (uint64_t);
6101 				}
6102 
6103 				break;
6104 			}
6105 
6106 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6107 			break;
6108 
6109 		case DIF_OP_STGS:
6110 			id = DIF_INSTR_VAR(instr);
6111 
6112 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6113 			id -= DIF_VAR_OTHER_UBASE;
6114 
6115 			VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6116 			svar = vstate->dtvs_globals[id];
6117 			ASSERT(svar != NULL);
6118 			v = &svar->dtsv_var;
6119 
6120 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6121 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6122 				size_t lim = 0;
6123 
6124 				ASSERT(a != 0);
6125 				ASSERT(svar->dtsv_size != 0);
6126 
6127 				if (regs[rd] == 0) {
6128 					*(uint8_t *)a = UINT8_MAX;
6129 					break;
6130 				} else {
6131 					*(uint8_t *)a = 0;
6132 					a += sizeof (uint64_t);
6133 				}
6134 				if (!dtrace_vcanload(
6135 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6136 					&lim, mstate, vstate))
6137 					break;
6138 
6139 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6140 				    (void *)a, &v->dtdv_type, lim);
6141 				break;
6142 			}
6143 
6144 			svar->dtsv_data = regs[rd];
6145 			break;
6146 
6147 		case DIF_OP_LDTA:
6148 			/*
6149 			 * There are no DTrace built-in thread-local arrays at
6150 			 * present.  This opcode is saved for future work.
6151 			 */
6152 			*flags |= CPU_DTRACE_ILLOP;
6153 			regs[rd] = 0;
6154 			break;
6155 
6156 		case DIF_OP_LDLS:
6157 			id = DIF_INSTR_VAR(instr);
6158 
6159 			if (id < DIF_VAR_OTHER_UBASE) {
6160 				/*
6161 				 * For now, this has no meaning.
6162 				 */
6163 				regs[rd] = 0;
6164 				break;
6165 			}
6166 
6167 			id -= DIF_VAR_OTHER_UBASE;
6168 
6169 			ASSERT(id < (uint_t)vstate->dtvs_nlocals);
6170 			ASSERT(vstate->dtvs_locals != NULL);
6171 			svar = vstate->dtvs_locals[id];
6172 			ASSERT(svar != NULL);
6173 			v = &svar->dtsv_var;
6174 
6175 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6176 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6177 				size_t sz = v->dtdv_type.dtdt_size;
6178 
6179 				sz += sizeof (uint64_t);
6180 				ASSERT(svar->dtsv_size == (int)NCPU * sz);
6181 				a += CPU->cpu_id * sz;
6182 
6183 				if (*(uint8_t *)a == UINT8_MAX) {
6184 					/*
6185 					 * If the 0th byte is set to UINT8_MAX
6186 					 * then this is to be treated as a
6187 					 * reference to a NULL variable.
6188 					 */
6189 					regs[rd] = 0;
6190 				} else {
6191 					regs[rd] = a + sizeof (uint64_t);
6192 				}
6193 
6194 				break;
6195 			}
6196 
6197 			ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
6198 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6199 			regs[rd] = tmp[CPU->cpu_id];
6200 			break;
6201 
6202 		case DIF_OP_STLS:
6203 			id = DIF_INSTR_VAR(instr);
6204 
6205 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6206 			id -= DIF_VAR_OTHER_UBASE;
6207 			VERIFY(id < (uint_t)vstate->dtvs_nlocals);
6208 			ASSERT(vstate->dtvs_locals != NULL);
6209 			svar = vstate->dtvs_locals[id];
6210 			ASSERT(svar != NULL);
6211 			v = &svar->dtsv_var;
6212 
6213 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6214 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6215 				size_t sz = v->dtdv_type.dtdt_size;
6216 				size_t lim = 0;
6217 
6218 				sz += sizeof (uint64_t);
6219 				ASSERT(svar->dtsv_size == (int)NCPU * sz);
6220 				a += CPU->cpu_id * sz;
6221 
6222 				if (regs[rd] == 0) {
6223 					*(uint8_t *)a = UINT8_MAX;
6224 					break;
6225 				} else {
6226 					*(uint8_t *)a = 0;
6227 					a += sizeof (uint64_t);
6228 				}
6229 
6230 				if (!dtrace_vcanload(
6231 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6232 				    &lim, mstate, vstate))
6233 					break;
6234 
6235 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6236 				    (void *)a, &v->dtdv_type, lim);
6237 				break;
6238 			}
6239 
6240 			ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
6241 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6242 			tmp[CPU->cpu_id] = regs[rd];
6243 			break;
6244 
6245 		case DIF_OP_LDTS: {
6246 			dtrace_dynvar_t *dvar;
6247 			dtrace_key_t *key;
6248 
6249 			id = DIF_INSTR_VAR(instr);
6250 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6251 			id -= DIF_VAR_OTHER_UBASE;
6252 			v = &vstate->dtvs_tlocals[id];
6253 
6254 			key = &tupregs[DIF_DTR_NREGS];
6255 			key[0].dttk_value = (uint64_t)id;
6256 			key[0].dttk_size = 0;
6257 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6258 			key[1].dttk_size = 0;
6259 
6260 			dvar = dtrace_dynvar(dstate, 2, key,
6261 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6262 			    mstate, vstate);
6263 
6264 			if (dvar == NULL) {
6265 				regs[rd] = 0;
6266 				break;
6267 			}
6268 
6269 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6270 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6271 			} else {
6272 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6273 			}
6274 
6275 			break;
6276 		}
6277 
6278 		case DIF_OP_STTS: {
6279 			dtrace_dynvar_t *dvar;
6280 			dtrace_key_t *key;
6281 
6282 			id = DIF_INSTR_VAR(instr);
6283 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6284 			id -= DIF_VAR_OTHER_UBASE;
6285 			VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6286 
6287 			key = &tupregs[DIF_DTR_NREGS];
6288 			key[0].dttk_value = (uint64_t)id;
6289 			key[0].dttk_size = 0;
6290 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6291 			key[1].dttk_size = 0;
6292 			v = &vstate->dtvs_tlocals[id];
6293 
6294 			dvar = dtrace_dynvar(dstate, 2, key,
6295 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6296 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6297 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6298 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6299 
6300 			/*
6301 			 * Given that we're storing to thread-local data,
6302 			 * we need to flush our predicate cache.
6303 			 */
6304 			dtrace_set_thread_predcache(current_thread(), 0);
6305 
6306 			if (dvar == NULL)
6307 				break;
6308 
6309 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6310 				size_t lim = 0;
6311 
6312 				if (!dtrace_vcanload(
6313 				    (void *)(uintptr_t)regs[rd],
6314 				    &v->dtdv_type, &lim, mstate, vstate))
6315 					break;
6316 
6317 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6318 				    dvar->dtdv_data, &v->dtdv_type, lim);
6319 			} else {
6320 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6321 			}
6322 
6323 			break;
6324 		}
6325 
6326 		case DIF_OP_SRA:
6327 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6328 			break;
6329 
6330 		case DIF_OP_CALL:
6331 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6332 			    regs, tupregs, ttop, mstate, state);
6333 			break;
6334 
6335 		case DIF_OP_PUSHTR:
6336 			if (ttop == DIF_DTR_NREGS) {
6337 				*flags |= CPU_DTRACE_TUPOFLOW;
6338 				break;
6339 			}
6340 
6341 			if (r1 == DIF_TYPE_STRING) {
6342 				/*
6343 				 * If this is a string type and the size is 0,
6344 				 * we'll use the system-wide default string
6345 				 * size.  Note that we are _not_ looking at
6346 				 * the value of the DTRACEOPT_STRSIZE option;
6347 				 * had this been set, we would expect to have
6348 				 * a non-zero size value in the "pushtr".
6349 				 */
6350 				tupregs[ttop].dttk_size =
6351 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6352 				    regs[r2] ? regs[r2] :
6353 				    dtrace_strsize_default) + 1;
6354 			} else {
6355 				if (regs[r2] > LONG_MAX) {
6356 					*flags |= CPU_DTRACE_ILLOP;
6357 					break;
6358 				}
6359 				tupregs[ttop].dttk_size = regs[r2];
6360 			}
6361 
6362 			tupregs[ttop++].dttk_value = regs[rd];
6363 			break;
6364 
6365 		case DIF_OP_PUSHTV:
6366 			if (ttop == DIF_DTR_NREGS) {
6367 				*flags |= CPU_DTRACE_TUPOFLOW;
6368 				break;
6369 			}
6370 
6371 			tupregs[ttop].dttk_value = regs[rd];
6372 			tupregs[ttop++].dttk_size = 0;
6373 			break;
6374 
6375 		case DIF_OP_POPTS:
6376 			if (ttop != 0)
6377 				ttop--;
6378 			break;
6379 
6380 		case DIF_OP_FLUSHTS:
6381 			ttop = 0;
6382 			break;
6383 
6384 		case DIF_OP_LDGAA:
6385 		case DIF_OP_LDTAA: {
6386 			dtrace_dynvar_t *dvar;
6387 			dtrace_key_t *key = tupregs;
6388 			uint_t nkeys = ttop;
6389 
6390 			id = DIF_INSTR_VAR(instr);
6391 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6392 			id -= DIF_VAR_OTHER_UBASE;
6393 
6394 			key[nkeys].dttk_value = (uint64_t)id;
6395 			key[nkeys++].dttk_size = 0;
6396 
6397 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6398 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6399 				key[nkeys++].dttk_size = 0;
6400 				VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6401 				v = &vstate->dtvs_tlocals[id];
6402 			} else {
6403 				VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6404 				v = &vstate->dtvs_globals[id]->dtsv_var;
6405 			}
6406 
6407 			dvar = dtrace_dynvar(dstate, nkeys, key,
6408 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6409 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6410 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6411 
6412 			if (dvar == NULL) {
6413 				regs[rd] = 0;
6414 				break;
6415 			}
6416 
6417 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6418 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6419 			} else {
6420 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6421 			}
6422 
6423 			break;
6424 		}
6425 
6426 		case DIF_OP_STGAA:
6427 		case DIF_OP_STTAA: {
6428 			dtrace_dynvar_t *dvar;
6429 			dtrace_key_t *key = tupregs;
6430 			uint_t nkeys = ttop;
6431 
6432 			id = DIF_INSTR_VAR(instr);
6433 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6434 			id -= DIF_VAR_OTHER_UBASE;
6435 
6436 			key[nkeys].dttk_value = (uint64_t)id;
6437 			key[nkeys++].dttk_size = 0;
6438 
6439 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6440 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6441 				key[nkeys++].dttk_size = 0;
6442 				VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
6443 				v = &vstate->dtvs_tlocals[id];
6444 			} else {
6445 				VERIFY(id < (uint_t)vstate->dtvs_nglobals);
6446 				v = &vstate->dtvs_globals[id]->dtsv_var;
6447 			}
6448 
6449 			dvar = dtrace_dynvar(dstate, nkeys, key,
6450 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6451 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6452 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6453 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6454 
6455 			if (dvar == NULL)
6456 				break;
6457 
6458 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6459 				size_t lim = 0;
6460 
6461 				if (!dtrace_vcanload(
6462 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6463 				    &lim, mstate, vstate))
6464 					break;
6465 
6466 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6467 				    dvar->dtdv_data, &v->dtdv_type, lim);
6468 			} else {
6469 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6470 			}
6471 
6472 			break;
6473 		}
6474 
6475 		case DIF_OP_ALLOCS: {
6476 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6477 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6478 
6479 			/*
6480 			 * Rounding up the user allocation size could have
6481 			 * overflowed large, bogus allocations (like -1ULL) to
6482 			 * 0.
6483 			 */
6484 			if (size < regs[r1] ||
6485 			    !DTRACE_INSCRATCH(mstate, size)) {
6486 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6487 				regs[rd] = 0;
6488 				break;
6489 			}
6490 
6491 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6492 				mstate->dtms_scratch_ptr += size;
6493 				regs[rd] = ptr;
6494 			break;
6495 		}
6496 
6497 		case DIF_OP_COPYS:
6498 			if (!dtrace_canstore(regs[rd], regs[r2],
6499 			    mstate, vstate)) {
6500 				*flags |= CPU_DTRACE_BADADDR;
6501 				*illval = regs[rd];
6502 				break;
6503 			}
6504 
6505 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6506 				break;
6507 
6508 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6509 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6510 			break;
6511 
6512 		case DIF_OP_STB:
6513 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6514 				*flags |= CPU_DTRACE_BADADDR;
6515 				*illval = regs[rd];
6516 				break;
6517 			}
6518 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6519 			break;
6520 
6521 		case DIF_OP_STH:
6522 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6523 				*flags |= CPU_DTRACE_BADADDR;
6524 				*illval = regs[rd];
6525 				break;
6526 			}
6527 			if (regs[rd] & 1) {
6528 				*flags |= CPU_DTRACE_BADALIGN;
6529 				*illval = regs[rd];
6530 				break;
6531 			}
6532 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6533 			break;
6534 
6535 		case DIF_OP_STW:
6536 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6537 				*flags |= CPU_DTRACE_BADADDR;
6538 				*illval = regs[rd];
6539 				break;
6540 			}
6541 			if (regs[rd] & 3) {
6542 				*flags |= CPU_DTRACE_BADALIGN;
6543 				*illval = regs[rd];
6544 				break;
6545 			}
6546 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6547 			break;
6548 
6549 		case DIF_OP_STX:
6550 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6551 				*flags |= CPU_DTRACE_BADADDR;
6552 				*illval = regs[rd];
6553 				break;
6554 			}
6555 
6556 			/*
6557 			* Darwin kmem_zalloc() called from
6558 			* dtrace_difo_init() is 4-byte aligned.
6559 			*/
6560 			if (regs[rd] & 3) {
6561 				*flags |= CPU_DTRACE_BADALIGN;
6562 				*illval = regs[rd];
6563 				break;
6564 			}
6565 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6566 			break;
6567 		case DIF_OP_STRIP:
6568 			regs[rd] = (uint64_t)dtrace_ptrauth_strip(
6569 			    (void*)regs[r1], r2);
6570 			break;
6571 		}
6572 	}
6573 
6574 	if (!(*flags & CPU_DTRACE_FAULT))
6575 		return (rval);
6576 
6577 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6578 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6579 
6580 	return (0);
6581 }
6582 
6583 __attribute__((noinline))
6584 static void
dtrace_action_breakpoint(dtrace_ecb_t * ecb)6585 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6586 {
6587 	dtrace_probe_t *probe = ecb->dte_probe;
6588 	dtrace_provider_t *prov = probe->dtpr_provider;
6589 	char c[DTRACE_FULLNAMELEN + 80], *str;
6590 	const char *msg = "dtrace: breakpoint action at probe ";
6591 	const char *ecbmsg = " (ecb ";
6592 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6593 	uintptr_t val = (uintptr_t)ecb;
6594 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6595 
6596 	if (dtrace_destructive_disallow)
6597 		return;
6598 
6599 	/*
6600 	 * It's impossible to be taking action on the NULL probe.
6601 	 */
6602 	ASSERT(probe != NULL);
6603 
6604 	/*
6605 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6606 	 * print the provider name, module name, function name and name of
6607 	 * the probe, along with the hex address of the ECB with the breakpoint
6608 	 * action -- all of which we must place in the character buffer by
6609 	 * hand.
6610 	 */
6611 	while (*msg != '\0')
6612 		c[i++] = *msg++;
6613 
6614 	for (str = prov->dtpv_name; *str != '\0'; str++)
6615 		c[i++] = *str;
6616 	c[i++] = ':';
6617 
6618 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6619 		c[i++] = *str;
6620 	c[i++] = ':';
6621 
6622 	for (str = probe->dtpr_func; *str != '\0'; str++)
6623 		c[i++] = *str;
6624 	c[i++] = ':';
6625 
6626 	for (str = probe->dtpr_name; *str != '\0'; str++)
6627 		c[i++] = *str;
6628 
6629 	while (*ecbmsg != '\0')
6630 		c[i++] = *ecbmsg++;
6631 
6632 	while (shift >= 0) {
6633 		mask = (uintptr_t)0xf << shift;
6634 
6635 		if (val >= ((uintptr_t)1 << shift))
6636 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6637 		shift -= 4;
6638 	}
6639 
6640 	c[i++] = ')';
6641 	c[i] = '\0';
6642 
6643 	debug_enter(c);
6644 }
6645 
6646 __attribute__((noinline))
6647 static void
dtrace_action_panic(dtrace_ecb_t * ecb)6648 dtrace_action_panic(dtrace_ecb_t *ecb)
6649 {
6650 	dtrace_probe_t *probe = ecb->dte_probe;
6651 
6652 	/*
6653 	 * It's impossible to be taking action on the NULL probe.
6654 	 */
6655 	ASSERT(probe != NULL);
6656 
6657 	if (dtrace_destructive_disallow)
6658 		return;
6659 
6660 	if (dtrace_panicked != NULL)
6661 		return;
6662 
6663 	if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
6664 		return;
6665 
6666 	/*
6667 	 * We won the right to panic.  (We want to be sure that only one
6668 	 * thread calls panic() from dtrace_probe(), and that panic() is
6669 	 * called exactly once.)
6670 	 */
6671 	panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6672 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6673 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6674 
6675 	/*
6676 	 * APPLE NOTE: this was for an old Mac OS X debug feature
6677 	 * allowing a return from panic().  Revisit someday.
6678 	 */
6679 	dtrace_panicked = NULL;
6680 }
6681 
6682 static void
dtrace_action_raise(uint64_t sig)6683 dtrace_action_raise(uint64_t sig)
6684 {
6685 	if (dtrace_destructive_disallow)
6686 		return;
6687 
6688 	if (sig >= NSIG) {
6689 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6690 		return;
6691 	}
6692 
6693 	/*
6694 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6695 	 * invocations of the raise() action.
6696 	 */
6697 
6698 	uthread_t uthread = current_uthread();
6699 
6700 	if (uthread && uthread->t_dtrace_sig == 0) {
6701 		uthread->t_dtrace_sig = sig;
6702 		act_set_astbsd(current_thread());
6703 	}
6704 }
6705 
6706 static void
dtrace_action_stop(void)6707 dtrace_action_stop(void)
6708 {
6709 	if (dtrace_destructive_disallow)
6710 		return;
6711 
6712         uthread_t uthread = current_uthread();
6713 	if (uthread) {
6714 		/*
6715 		 * The currently running process will be set to task_suspend
6716 		 * when it next leaves the kernel.
6717 		*/
6718 		uthread->t_dtrace_stop = 1;
6719 		act_set_astbsd(current_thread());
6720 	}
6721 }
6722 
6723 
6724 /*
6725  * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
6726  * Both activate only when the currently running process next leaves the
6727  * kernel.
6728  */
6729 static void
dtrace_action_pidresume(uint64_t pid)6730 dtrace_action_pidresume(uint64_t pid)
6731 {
6732 	if (dtrace_destructive_disallow)
6733 		return;
6734 
6735 	if (kauth_cred_issuser(kauth_cred_get()) == 0) {
6736 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6737 		return;
6738 	}
6739         uthread_t uthread = current_uthread();
6740 
6741 	/*
6742 	 * When the currently running process leaves the kernel, it attempts to
6743 	 * task_resume the process (denoted by pid), if that pid appears to have
6744 	 * been stopped by dtrace_action_stop().
6745 	 * The currently running process has a pidresume() queue depth of 1 --
6746 	 * subsequent invocations of the pidresume() action are ignored.
6747 	 */
6748 
6749 	if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
6750 		uthread->t_dtrace_resumepid = pid;
6751 		act_set_astbsd(current_thread());
6752 	}
6753 }
6754 
6755 __attribute__((noinline))
6756 static void
dtrace_action_chill(dtrace_mstate_t * mstate,hrtime_t val)6757 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6758 {
6759 	hrtime_t now;
6760 	volatile uint16_t *flags;
6761 	dtrace_cpu_t *cpu = CPU;
6762 
6763 	if (dtrace_destructive_disallow)
6764 		return;
6765 
6766 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6767 
6768 	now = dtrace_gethrtime();
6769 
6770 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6771 		/*
6772 		 * We need to advance the mark to the current time.
6773 		 */
6774 		cpu->cpu_dtrace_chillmark = now;
6775 		cpu->cpu_dtrace_chilled = 0;
6776 	}
6777 
6778 	/*
6779 	 * Now check to see if the requested chill time would take us over
6780 	 * the maximum amount of time allowed in the chill interval.  (Or
6781 	 * worse, if the calculation itself induces overflow.)
6782 	 */
6783 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6784 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6785 		*flags |= CPU_DTRACE_ILLOP;
6786 		return;
6787 	}
6788 
6789 	while (dtrace_gethrtime() - now < val)
6790 		continue;
6791 
6792 	/*
6793 	 * Normally, we assure that the value of the variable "timestamp" does
6794 	 * not change within an ECB.  The presence of chill() represents an
6795 	 * exception to this rule, however.
6796 	 */
6797 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6798 	cpu->cpu_dtrace_chilled += val;
6799 }
6800 
6801 __attribute__((noinline))
6802 static void
dtrace_action_ustack(dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t * buf,uint64_t arg)6803 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6804     uint64_t *buf, uint64_t arg)
6805 {
6806 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6807 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6808 	uint64_t *pcs = &buf[1], *fps;
6809 	char *str = (char *)&pcs[nframes];
6810 	int size, offs = 0, i, j;
6811 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6812 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6813 	char *sym;
6814 
6815 	/*
6816 	 * Should be taking a faster path if string space has not been
6817 	 * allocated.
6818 	 */
6819 	ASSERT(strsize != 0);
6820 
6821 	/*
6822 	 * We will first allocate some temporary space for the frame pointers.
6823 	 */
6824 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6825 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6826 	    (nframes * sizeof (uint64_t));
6827 
6828 	if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
6829 		/*
6830 		 * Not enough room for our frame pointers -- need to indicate
6831 		 * that we ran out of scratch space.
6832 		 */
6833 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6834 		return;
6835 	}
6836 
6837 	mstate->dtms_scratch_ptr += size;
6838 	saved = mstate->dtms_scratch_ptr;
6839 
6840 	/*
6841 	 * Now get a stack with both program counters and frame pointers.
6842 	 */
6843 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6844 	dtrace_getufpstack(buf, fps, nframes + 1);
6845 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6846 
6847 	/*
6848 	 * If that faulted, we're cooked.
6849 	 */
6850 	if (*flags & CPU_DTRACE_FAULT)
6851 		goto out;
6852 
6853 	/*
6854 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6855 	 * each iteration, we restore the scratch pointer.
6856 	 */
6857 	for (i = 0; i < nframes; i++) {
6858 		mstate->dtms_scratch_ptr = saved;
6859 
6860 		if (offs >= strsize)
6861 			break;
6862 
6863 		sym = (char *)(uintptr_t)dtrace_helper(
6864 		    DTRACE_HELPER_ACTION_USTACK,
6865 		    mstate, state, pcs[i], fps[i]);
6866 
6867 		/*
6868 		 * If we faulted while running the helper, we're going to
6869 		 * clear the fault and null out the corresponding string.
6870 		 */
6871 		if (*flags & CPU_DTRACE_FAULT) {
6872 			*flags &= ~CPU_DTRACE_FAULT;
6873 			str[offs++] = '\0';
6874 			continue;
6875 		}
6876 
6877 		if (sym == NULL) {
6878 			str[offs++] = '\0';
6879 			continue;
6880 		}
6881 
6882 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6883 
6884 		/*
6885 		 * Now copy in the string that the helper returned to us.
6886 		 */
6887 		for (j = 0; offs + j < strsize; j++) {
6888 			if ((str[offs + j] = sym[j]) == '\0')
6889 				break;
6890 		}
6891 
6892 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6893 
6894 		offs += j + 1;
6895 	}
6896 
6897 	if (offs >= strsize) {
6898 		/*
6899 		 * If we didn't have room for all of the strings, we don't
6900 		 * abort processing -- this needn't be a fatal error -- but we
6901 		 * still want to increment a counter (dts_stkstroverflows) to
6902 		 * allow this condition to be warned about.  (If this is from
6903 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6904 		 */
6905 		dtrace_error(&state->dts_stkstroverflows);
6906 	}
6907 
6908 	while (offs < strsize)
6909 		str[offs++] = '\0';
6910 
6911 out:
6912 	mstate->dtms_scratch_ptr = old;
6913 }
6914 
6915 __attribute__((noinline))
6916 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)6917 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6918     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6919 {
6920 	volatile uint16_t *flags;
6921 	uint64_t val = *valp;
6922 	size_t valoffs = *valoffsp;
6923 
6924 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6925 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6926 
6927 	/*
6928 	 * If this is a string, we're going to only load until we find the zero
6929 	 * byte -- after which we'll store zero bytes.
6930 	 */
6931 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6932 		char c = '\0' + 1;
6933 		size_t s;
6934 
6935 		for (s = 0; s < size; s++) {
6936 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6937 				c = dtrace_load8(val++);
6938 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6939 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6940 				c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6941 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6942 				if (*flags & CPU_DTRACE_FAULT)
6943 					break;
6944 			}
6945 
6946 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6947 
6948 			if (c == '\0' && intuple)
6949 				break;
6950 		}
6951 	} else {
6952 		uint8_t c;
6953 		while (valoffs < end) {
6954 			if (dtkind == DIF_TF_BYREF) {
6955 				c = dtrace_load8(val++);
6956 			} else if (dtkind == DIF_TF_BYUREF) {
6957 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6958 				c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6959 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6960 				if (*flags & CPU_DTRACE_FAULT)
6961 					break;
6962 			}
6963 
6964 			DTRACE_STORE(uint8_t, tomax,
6965 			    valoffs++, c);
6966 		}
6967 	}
6968 
6969 	*valp = val;
6970 	*valoffsp = valoffs;
6971 }
6972 
6973 /*
6974  * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
6975  * defined, we also assert that we are not recursing unless the probe ID is an
6976  * error probe.
6977  */
6978 static dtrace_icookie_t
dtrace_probe_enter(dtrace_id_t id)6979 dtrace_probe_enter(dtrace_id_t id)
6980 {
6981 	thread_t thread = current_thread();
6982 	uint16_t inprobe;
6983 
6984 	dtrace_icookie_t cookie;
6985 
6986 	cookie = dtrace_interrupt_disable();
6987 
6988 	/*
6989 	 * Unless this is an ERROR probe, we are not allowed to recurse in
6990 	 * dtrace_probe(). Recursing into DTrace probe usually means that a
6991 	 * function is instrumented that should not have been instrumented or
6992 	 * that the ordering guarantee of the records will be violated,
6993 	 * resulting in unexpected output. If there is an exception to this
6994 	 * assertion, a new case should be added.
6995 	 */
6996 	inprobe = dtrace_get_thread_inprobe(thread);
6997 	VERIFY(inprobe == 0 ||
6998 	    id == dtrace_probeid_error);
6999 	ASSERT(inprobe < UINT16_MAX);
7000 	dtrace_set_thread_inprobe(thread, inprobe + 1);
7001 
7002 	return (cookie);
7003 }
7004 
7005 /*
7006  * Clears the per-thread inprobe flag and enables interrupts.
7007  */
7008 static void
dtrace_probe_exit(dtrace_icookie_t cookie)7009 dtrace_probe_exit(dtrace_icookie_t cookie)
7010 {
7011 	thread_t thread = current_thread();
7012 	uint16_t inprobe = dtrace_get_thread_inprobe(thread);
7013 
7014 	ASSERT(inprobe > 0);
7015 	dtrace_set_thread_inprobe(thread, inprobe - 1);
7016 
7017 #if SCHED_HYGIENE_DEBUG
7018 	/*
7019 	 * Probes can take a relatively long time depending on what the user has
7020 	 * requested be done in probe context.
7021 	 * Probes can fire from places where interrupts are already disabled
7022 	 * (like an interrupt handler) or where preemption has been disabled.
7023 	 * In order to not trip the interrupt or preemption thresholds, it is
7024 	 * important to reset timestamps when leaving probe context.
7025 	 */
7026 
7027 	/* Interrupts were disabled for the duration of this probe. */
7028 	ml_spin_debug_reset(thread);
7029 
7030 	/* May have been called from an interrupt handler. */
7031 	ml_irq_debug_abandon();
7032 
7033 	/* May have been called with preemption disabled. */
7034 	abandon_preemption_disable_measurement();
7035 
7036 #endif /* SCHED_HYGIENE_DEBUG */
7037 
7038 	dtrace_interrupt_enable(cookie);
7039 }
7040 
7041 /*
7042  * If you're looking for the epicenter of DTrace, you just found it.  This
7043  * is the function called by the provider to fire a probe -- from which all
7044  * subsequent probe-context DTrace activity emanates.
7045  */
7046 void
dtrace_probe(dtrace_id_t id,uint64_t arg0,uint64_t arg1,uint64_t arg2,uint64_t arg3,uint64_t arg4)7047 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
7048     uint64_t arg2, uint64_t arg3, uint64_t arg4)
7049 {
7050 	processorid_t cpuid;
7051 	dtrace_icookie_t cookie;
7052 	dtrace_probe_t *probe;
7053 	dtrace_mstate_t mstate;
7054 	dtrace_ecb_t *ecb;
7055 	dtrace_action_t *act;
7056 	intptr_t offs;
7057 	size_t size;
7058 	int vtime, onintr;
7059 	volatile uint16_t *flags;
7060 	hrtime_t now;
7061 
7062 	cookie = dtrace_probe_enter(id);
7063 
7064 	/* Ensure that probe id is valid. */
7065 	if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
7066 		dtrace_probe_exit(cookie);
7067 		return;
7068 	}
7069 
7070 	probe = dtrace_probes[id - 1];
7071 	if (probe == NULL) {
7072 		dtrace_probe_exit(cookie);
7073 		return;
7074 	}
7075 
7076 	cpuid = CPU->cpu_id;
7077 	onintr = CPU_ON_INTR(CPU);
7078 
7079 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7080 	    probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
7081 		/*
7082 		 * We have hit in the predicate cache; we know that
7083 		 * this predicate would evaluate to be false.
7084 		 */
7085 		dtrace_probe_exit(cookie);
7086 		return;
7087 	}
7088 
7089 	if (panic_quiesce) {
7090 		/*
7091 		 * We don't trace anything if we're panicking.
7092 		 */
7093 		dtrace_probe_exit(cookie);
7094 		return;
7095 	}
7096 
7097 #if !defined(__APPLE__)
7098 	now = dtrace_gethrtime();
7099 	vtime = dtrace_vtime_references != 0;
7100 
7101 	if (vtime && curthread->t_dtrace_start)
7102 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7103 #else
7104 	/*
7105 	 * APPLE NOTE:  The time spent entering DTrace and arriving
7106 	 * to this point, is attributed to the current thread.
7107 	 * Instead it should accrue to DTrace.  FIXME
7108 	 */
7109 	vtime = dtrace_vtime_references != 0;
7110 
7111 	if (vtime)
7112 	{
7113 		int64_t dtrace_accum_time, recent_vtime;
7114 		thread_t thread = current_thread();
7115 
7116 		dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
7117 
7118 		if (dtrace_accum_time >= 0) {
7119 			recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
7120 
7121 			recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
7122 
7123 			dtrace_set_thread_vtime(thread, recent_vtime);
7124 		}
7125 	}
7126 
7127 	now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
7128 #endif /* __APPLE__ */
7129 
7130 	/*
7131 	 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
7132 	 * dtrace_probe() in some circumstances.   See, e.g. fasttrap_isa.c.
7133 	 * However the provider has no access to ECB context, so passes
7134 	 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
7135 	 * Detect that here and cons up a viable state (from the probe_id).
7136 	 */
7137 	if (dtrace_probeid_error == id && 0 == arg0) {
7138 		dtrace_id_t ftp_id = (dtrace_id_t)arg1;
7139 		dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
7140 		dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
7141 
7142 		if (NULL != ftp_ecb) {
7143 			dtrace_state_t *ftp_state = ftp_ecb->dte_state;
7144 
7145 			arg0 = (uint64_t)(uintptr_t)ftp_state;
7146 			arg1 = ftp_ecb->dte_epid;
7147 			/*
7148 			 * args[2-4] established by caller.
7149 			 */
7150 			ftp_state->dts_arg_error_illval = -1; /* arg5 */
7151 		}
7152 	}
7153 
7154 	mstate.dtms_difo = NULL;
7155 	mstate.dtms_probe = probe;
7156 	mstate.dtms_strtok = 0;
7157 	mstate.dtms_arg[0] = arg0;
7158 	mstate.dtms_arg[1] = arg1;
7159 	mstate.dtms_arg[2] = arg2;
7160 	mstate.dtms_arg[3] = arg3;
7161 	mstate.dtms_arg[4] = arg4;
7162 
7163 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7164 
7165 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7166 		dtrace_predicate_t *pred = ecb->dte_predicate;
7167 		dtrace_state_t *state = ecb->dte_state;
7168 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7169 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7170 		dtrace_vstate_t *vstate = &state->dts_vstate;
7171 		dtrace_provider_t *prov = probe->dtpr_provider;
7172 		uint64_t tracememsize = 0;
7173 		int committed = 0;
7174 		caddr_t tomax;
7175 
7176 		/*
7177 		 * A little subtlety with the following (seemingly innocuous)
7178 		 * declaration of the automatic 'val':  by looking at the
7179 		 * code, you might think that it could be declared in the
7180 		 * action processing loop, below.  (That is, it's only used in
7181 		 * the action processing loop.)  However, it must be declared
7182 		 * out of that scope because in the case of DIF expression
7183 		 * arguments to aggregating actions, one iteration of the
7184 		 * action loop will use the last iteration's value.
7185 		 */
7186 #ifdef lint
7187 		uint64_t val = 0;
7188 #else
7189 		uint64_t val = 0;
7190 #endif
7191 
7192 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7193 		*flags &= ~CPU_DTRACE_ERROR;
7194 
7195 		if (prov == dtrace_provider) {
7196 			/*
7197 			 * If dtrace itself is the provider of this probe,
7198 			 * we're only going to continue processing the ECB if
7199 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7200 			 * creating state.  (This prevents disjoint consumers
7201 			 * from seeing one another's metaprobes.)
7202 			 */
7203 			if (arg0 != (uint64_t)(uintptr_t)state)
7204 				continue;
7205 		}
7206 
7207 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7208 			/*
7209 			 * We're not currently active.  If our provider isn't
7210 			 * the dtrace pseudo provider, we're not interested.
7211 			 */
7212 			if (prov != dtrace_provider)
7213 				continue;
7214 
7215 			/*
7216 			 * Now we must further check if we are in the BEGIN
7217 			 * probe.  If we are, we will only continue processing
7218 			 * if we're still in WARMUP -- if one BEGIN enabling
7219 			 * has invoked the exit() action, we don't want to
7220 			 * evaluate subsequent BEGIN enablings.
7221 			 */
7222 			if (probe->dtpr_id == dtrace_probeid_begin &&
7223 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7224 				ASSERT(state->dts_activity ==
7225 				    DTRACE_ACTIVITY_DRAINING);
7226 				continue;
7227 			}
7228 		}
7229 
7230 		if (ecb->dte_cond) {
7231 			/*
7232 			 * If the dte_cond bits indicate that this
7233 			 * consumer is only allowed to see user-mode firings
7234 			 * of this probe, call the provider's dtps_usermode()
7235 			 * entry point to check that the probe was fired
7236 			 * while in a user context. Skip this ECB if that's
7237 			 * not the case.
7238 			 */
7239 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7240 			    prov->dtpv_pops.dtps_usermode &&
7241 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7242 			    probe->dtpr_id, probe->dtpr_arg) == 0)
7243 				continue;
7244 
7245 			/*
7246 			 * This is more subtle than it looks. We have to be
7247 			 * absolutely certain that CRED() isn't going to
7248 			 * change out from under us so it's only legit to
7249 			 * examine that structure if we're in constrained
7250 			 * situations. Currently, the only times we'll this
7251 			 * check is if a non-super-user has enabled the
7252 			 * profile or syscall providers -- providers that
7253 			 * allow visibility of all processes. For the
7254 			 * profile case, the check above will ensure that
7255 			 * we're examining a user context.
7256 			 */
7257 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
7258 				cred_t *cr;
7259 				cred_t *s_cr =
7260 				    ecb->dte_state->dts_cred.dcr_cred;
7261 				proc_t *proc;
7262 #pragma unused(proc) /* __APPLE__ */
7263 
7264 				ASSERT(s_cr != NULL);
7265 
7266 			/*
7267 			 * XXX this is hackish, but so is setting a variable
7268 			 * XXX in a McCarthy OR...
7269 			 */
7270 				if ((cr = dtrace_CRED()) == NULL ||
7271 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
7272 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
7273 				    posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
7274 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
7275 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
7276 				    posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
7277 #if !defined(__APPLE__)
7278 				    (proc = ttoproc(curthread)) == NULL ||
7279 				    (proc->p_flag & SNOCD))
7280 #else
7281 					1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
7282 #endif /* __APPLE__ */
7283 					continue;
7284 			}
7285 
7286 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7287 				cred_t *cr;
7288 				cred_t *s_cr =
7289 				    ecb->dte_state->dts_cred.dcr_cred;
7290 #pragma unused(cr, s_cr) /* __APPLE__ */
7291 
7292 				ASSERT(s_cr != NULL);
7293 
7294 #if !defined(__APPLE__)
7295 				if ((cr = CRED()) == NULL ||
7296 				    s_cr->cr_zone->zone_id !=
7297 				    cr->cr_zone->zone_id)
7298 					continue;
7299 #else
7300 				/* APPLE NOTE: Darwin doesn't do zones. */
7301 #endif /* __APPLE__ */
7302 			}
7303 		}
7304 
7305 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7306 			/*
7307 			 * We seem to be dead.  Unless we (a) have kernel
7308 			 * destructive permissions (b) have expicitly enabled
7309 			 * destructive actions and (c) destructive actions have
7310 			 * not been disabled, we're going to transition into
7311 			 * the KILLED state, from which no further processing
7312 			 * on this state will be performed.
7313 			 */
7314 			if (!dtrace_priv_kernel_destructive(state) ||
7315 			    !state->dts_cred.dcr_destructive ||
7316 			    dtrace_destructive_disallow) {
7317 				void *activity = &state->dts_activity;
7318 				dtrace_activity_t current;
7319 
7320 				do {
7321 					current = state->dts_activity;
7322 				} while (dtrace_cas32(activity, current,
7323 				    DTRACE_ACTIVITY_KILLED) != current);
7324 
7325 				continue;
7326 			}
7327 		}
7328 
7329 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7330 		    ecb->dte_alignment, state, &mstate)) < 0)
7331 			continue;
7332 
7333 		tomax = buf->dtb_tomax;
7334 		ASSERT(tomax != NULL);
7335 
7336 		/*
7337 		 * Build and store the record header corresponding to the ECB.
7338 		 */
7339 		if (ecb->dte_size != 0) {
7340 			dtrace_rechdr_t dtrh;
7341 
7342 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7343 				mstate.dtms_timestamp = dtrace_gethrtime();
7344 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7345 			}
7346 
7347 			ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
7348 
7349 			dtrh.dtrh_epid = ecb->dte_epid;
7350 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
7351 			DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
7352 		}
7353 
7354 		mstate.dtms_epid = ecb->dte_epid;
7355 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7356 
7357 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7358 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7359 		else
7360 			mstate.dtms_access = 0;
7361 
7362 		if (pred != NULL) {
7363 			dtrace_difo_t *dp = pred->dtp_difo;
7364 			uint64_t rval;
7365 
7366 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7367 
7368 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7369 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7370 
7371 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7372 					/*
7373 					 * Update the predicate cache...
7374 					 */
7375 					ASSERT(cid == pred->dtp_cacheid);
7376 
7377 					dtrace_set_thread_predcache(current_thread(), cid);
7378 				}
7379 
7380 				continue;
7381 			}
7382 		}
7383 
7384 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7385 		    act != NULL; act = act->dta_next) {
7386 			size_t valoffs;
7387 			dtrace_difo_t *dp;
7388 			dtrace_recdesc_t *rec = &act->dta_rec;
7389 
7390 			size = rec->dtrd_size;
7391 			valoffs = offs + rec->dtrd_offset;
7392 
7393 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7394 				uint64_t v = 0xbad;
7395 				dtrace_aggregation_t *agg;
7396 
7397 				agg = (dtrace_aggregation_t *)act;
7398 
7399 				if ((dp = act->dta_difo) != NULL)
7400 					v = dtrace_dif_emulate(dp,
7401 					    &mstate, vstate, state);
7402 
7403 				if (*flags & CPU_DTRACE_ERROR)
7404 					continue;
7405 
7406 				/*
7407 				 * Note that we always pass the expression
7408 				 * value from the previous iteration of the
7409 				 * action loop.  This value will only be used
7410 				 * if there is an expression argument to the
7411 				 * aggregating action, denoted by the
7412 				 * dtag_hasarg field.
7413 				 */
7414 				dtrace_aggregate(agg, buf,
7415 				    offs, aggbuf, v, val);
7416 				continue;
7417 			}
7418 
7419 			switch (act->dta_kind) {
7420 			case DTRACEACT_STOP:
7421 				if (dtrace_priv_proc_destructive(state))
7422 					dtrace_action_stop();
7423 				continue;
7424 
7425 			case DTRACEACT_BREAKPOINT:
7426 				if (dtrace_priv_kernel_destructive(state))
7427 					dtrace_action_breakpoint(ecb);
7428 				continue;
7429 
7430 			case DTRACEACT_PANIC:
7431 				if (dtrace_priv_kernel_destructive(state))
7432 					dtrace_action_panic(ecb);
7433 				continue;
7434 
7435 			case DTRACEACT_STACK:
7436 				if (!dtrace_priv_kernel(state))
7437 					continue;
7438 
7439 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7440 				    size / sizeof (pc_t), probe->dtpr_aframes,
7441 				    DTRACE_ANCHORED(probe) ? NULL :
7442 				  (uint32_t *)(uintptr_t)arg0);
7443 				continue;
7444 
7445 			case DTRACEACT_JSTACK:
7446 			case DTRACEACT_USTACK:
7447 				if (!dtrace_priv_proc(state))
7448 					continue;
7449 
7450 				/*
7451 				 * See comment in DIF_VAR_PID.
7452 				 */
7453 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7454 				    CPU_ON_INTR(CPU)) {
7455 					int depth = DTRACE_USTACK_NFRAMES(
7456 					    rec->dtrd_arg) + 1;
7457 
7458 					dtrace_bzero((void *)(tomax + valoffs),
7459 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7460 					    + depth * sizeof (uint64_t));
7461 
7462 					continue;
7463 				}
7464 
7465 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7466 				    curproc->p_dtrace_helpers != NULL) {
7467 					/*
7468 					 * This is the slow path -- we have
7469 					 * allocated string space, and we're
7470 					 * getting the stack of a process that
7471 					 * has helpers.  Call into a separate
7472 					 * routine to perform this processing.
7473 					 */
7474 					dtrace_action_ustack(&mstate, state,
7475 					    (uint64_t *)(tomax + valoffs),
7476 					    rec->dtrd_arg);
7477 					continue;
7478 				}
7479 
7480 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7481 				dtrace_getupcstack((uint64_t *)
7482 				    (tomax + valoffs),
7483 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7484 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7485 				continue;
7486 
7487 			default:
7488 				break;
7489 			}
7490 
7491 			dp = act->dta_difo;
7492 			ASSERT(dp != NULL);
7493 
7494 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7495 
7496 			if (*flags & CPU_DTRACE_ERROR)
7497 				continue;
7498 
7499 			switch (act->dta_kind) {
7500 			case DTRACEACT_SPECULATE: {
7501 				dtrace_rechdr_t *dtrh = NULL;
7502 
7503 				ASSERT(buf == &state->dts_buffer[cpuid]);
7504 				buf = dtrace_speculation_buffer(state,
7505 				    cpuid, val);
7506 
7507 				if (buf == NULL) {
7508 					*flags |= CPU_DTRACE_DROP;
7509 					continue;
7510 				}
7511 
7512 				offs = dtrace_buffer_reserve(buf,
7513 				    ecb->dte_needed, ecb->dte_alignment,
7514 				    state, NULL);
7515 
7516 				if (offs < 0) {
7517 					*flags |= CPU_DTRACE_DROP;
7518 					continue;
7519 				}
7520 
7521 				tomax = buf->dtb_tomax;
7522 				ASSERT(tomax != NULL);
7523 
7524 				if (ecb->dte_size == 0)
7525 					continue;
7526 
7527 				ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
7528 				dtrh = ((void *)(tomax + offs));
7529 				dtrh->dtrh_epid = ecb->dte_epid;
7530 
7531 				/*
7532 				 * When the speculation is committed, all of
7533 				 * the records in the speculative buffer will
7534 				 * have their timestamps set to the commit
7535 				 * time.  Until then, it is set to a sentinel
7536 				 * value, for debugability.
7537 				 */
7538 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7539 
7540  				continue;
7541 			}
7542 
7543 			case DTRACEACT_CHILL:
7544 				if (dtrace_priv_kernel_destructive(state))
7545 					dtrace_action_chill(&mstate, val);
7546 				continue;
7547 
7548 			case DTRACEACT_RAISE:
7549 				if (dtrace_priv_proc_destructive(state))
7550 					dtrace_action_raise(val);
7551 				continue;
7552 
7553 			case DTRACEACT_PIDRESUME:   /* __APPLE__ */
7554 				if (dtrace_priv_proc_destructive(state))
7555 					dtrace_action_pidresume(val);
7556 				continue;
7557 
7558 			case DTRACEACT_COMMIT:
7559 				ASSERT(!committed);
7560 
7561 				/*
7562 				 * We need to commit our buffer state.
7563 				 */
7564 				if (ecb->dte_size)
7565 					buf->dtb_offset = offs + ecb->dte_size;
7566 				buf = &state->dts_buffer[cpuid];
7567 				dtrace_speculation_commit(state, cpuid, val);
7568 				committed = 1;
7569 				continue;
7570 
7571 			case DTRACEACT_DISCARD:
7572 				dtrace_speculation_discard(state, cpuid, val);
7573 				continue;
7574 
7575 			case DTRACEACT_DIFEXPR:
7576 			case DTRACEACT_LIBACT:
7577 			case DTRACEACT_PRINTF:
7578 			case DTRACEACT_PRINTA:
7579 			case DTRACEACT_SYSTEM:
7580 			case DTRACEACT_FREOPEN:
7581 			case DTRACEACT_APPLEBINARY:   /* __APPLE__ */
7582 			case DTRACEACT_TRACEMEM:
7583 				break;
7584 
7585 			case DTRACEACT_TRACEMEM_DYNSIZE:
7586 				tracememsize = val;
7587 				break;
7588 
7589 			case DTRACEACT_SYM:
7590 			case DTRACEACT_MOD:
7591 				if (!dtrace_priv_kernel(state))
7592 					continue;
7593 				break;
7594 
7595 			case DTRACEACT_USYM:
7596 			case DTRACEACT_UMOD:
7597 			case DTRACEACT_UADDR: {
7598 				if (!dtrace_priv_proc(state))
7599 					continue;
7600 
7601 				DTRACE_STORE(uint64_t, tomax,
7602 				    valoffs, (uint64_t)dtrace_proc_selfpid());
7603 				DTRACE_STORE(uint64_t, tomax,
7604 				    valoffs + sizeof (uint64_t), val);
7605 
7606 				continue;
7607 			}
7608 
7609 			case DTRACEACT_EXIT: {
7610 				/*
7611 				 * For the exit action, we are going to attempt
7612 				 * to atomically set our activity to be
7613 				 * draining.  If this fails (either because
7614 				 * another CPU has beat us to the exit action,
7615 				 * or because our current activity is something
7616 				 * other than ACTIVE or WARMUP), we will
7617 				 * continue.  This assures that the exit action
7618 				 * can be successfully recorded at most once
7619 				 * when we're in the ACTIVE state.  If we're
7620 				 * encountering the exit() action while in
7621 				 * COOLDOWN, however, we want to honor the new
7622 				 * status code.  (We know that we're the only
7623 				 * thread in COOLDOWN, so there is no race.)
7624 				 */
7625 				void *activity = &state->dts_activity;
7626 				dtrace_activity_t current = state->dts_activity;
7627 
7628 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7629 					break;
7630 
7631 				if (current != DTRACE_ACTIVITY_WARMUP)
7632 					current = DTRACE_ACTIVITY_ACTIVE;
7633 
7634 				if (dtrace_cas32(activity, current,
7635 				    DTRACE_ACTIVITY_DRAINING) != current) {
7636 					*flags |= CPU_DTRACE_DROP;
7637 					continue;
7638 				}
7639 
7640 				break;
7641 			}
7642 
7643 			default:
7644 				ASSERT(0);
7645 			}
7646 
7647 			if (dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF)) {
7648 				uintptr_t end = valoffs + size;
7649 
7650 				if (tracememsize != 0 &&
7651                                     valoffs + tracememsize < end)
7652 				{
7653                                         end = valoffs + tracememsize;
7654                                         tracememsize = 0;
7655                                 }
7656 
7657 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7658 				    !dtrace_vcanload((void *)(uintptr_t)val,
7659 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7660 				{
7661 					continue;
7662 				}
7663 
7664 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7665 				    &val, end, act->dta_intuple,
7666 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7667 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7668 
7669 				continue;
7670 			}
7671 
7672 			switch (size) {
7673 			case 0:
7674 				break;
7675 
7676 			case sizeof (uint8_t):
7677 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7678 				break;
7679 			case sizeof (uint16_t):
7680 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7681 				break;
7682 			case sizeof (uint32_t):
7683 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7684 				break;
7685 			case sizeof (uint64_t):
7686 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7687 				break;
7688 			default:
7689 				/*
7690 				 * Any other size should have been returned by
7691 				 * reference, not by value.
7692 				 */
7693 				ASSERT(0);
7694 				break;
7695 			}
7696 		}
7697 
7698 		if (*flags & CPU_DTRACE_DROP)
7699 			continue;
7700 
7701 		if (*flags & CPU_DTRACE_FAULT) {
7702 			int ndx;
7703 			dtrace_action_t *err;
7704 
7705 			buf->dtb_errors++;
7706 
7707 			if (probe->dtpr_id == dtrace_probeid_error) {
7708 				/*
7709 				 * There's nothing we can do -- we had an
7710 				 * error on the error probe.  We bump an
7711 				 * error counter to at least indicate that
7712 				 * this condition happened.
7713 				 */
7714 				dtrace_error(&state->dts_dblerrors);
7715 				continue;
7716 			}
7717 
7718 			if (vtime) {
7719 				/*
7720 				 * Before recursing on dtrace_probe(), we
7721 				 * need to explicitly clear out our start
7722 				 * time to prevent it from being accumulated
7723 				 * into t_dtrace_vtime.
7724 				 */
7725 
7726 				/*
7727 				 * Darwin sets the sign bit on t_dtrace_tracing
7728 				 * to suspend accumulation to it.
7729 				 */
7730 				dtrace_set_thread_tracing(current_thread(),
7731 				    (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
7732 			}
7733 
7734 			/*
7735 			 * Iterate over the actions to figure out which action
7736 			 * we were processing when we experienced the error.
7737 			 * Note that act points _past_ the faulting action; if
7738 			 * act is ecb->dte_action, the fault was in the
7739 			 * predicate, if it's ecb->dte_action->dta_next it's
7740 			 * in action #1, and so on.
7741 			 */
7742 			for (err = ecb->dte_action, ndx = 0;
7743 			    err != act; err = err->dta_next, ndx++)
7744 				continue;
7745 
7746 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7747 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7748 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7749 			    cpu_core[cpuid].cpuc_dtrace_illval);
7750 
7751 			continue;
7752 		}
7753 
7754 		if (!committed)
7755 			buf->dtb_offset = offs + ecb->dte_size;
7756 	}
7757 
7758 	/* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
7759 	   to the current thread. Instead it should accrue to DTrace. */
7760 	if (vtime) {
7761 		thread_t thread = current_thread();
7762 		int64_t t = dtrace_get_thread_tracing(thread);
7763 
7764 		if (t >= 0) {
7765 			/* Usual case, accumulate time spent here into t_dtrace_tracing */
7766 			dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
7767 		} else {
7768 			/* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
7769 			dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
7770 		}
7771 	}
7772 
7773 	dtrace_probe_exit(cookie);
7774 }
7775 
7776 /*
7777  * DTrace Probe Hashing Functions
7778  *
7779  * The functions in this section (and indeed, the functions in remaining
7780  * sections) are not _called_ from probe context.  (Any exceptions to this are
7781  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7782  * DTrace framework to look-up probes in, add probes to and remove probes from
7783  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7784  * probe tuple -- allowing for fast lookups, regardless of what was
7785  * specified.)
7786  */
7787 static uint_t
dtrace_hash_str(const char * p)7788 dtrace_hash_str(const char *p)
7789 {
7790 	unsigned int g;
7791 	uint_t hval = 0;
7792 
7793 	while (*p) {
7794 		hval = (hval << 4) + *p++;
7795 		if ((g = (hval & 0xf0000000)) != 0)
7796 			hval ^= g >> 24;
7797 		hval &= ~g;
7798 	}
7799 	return (hval);
7800 }
7801 
7802 static const char*
dtrace_strkey_probe_provider(void * elm,uintptr_t offs)7803 dtrace_strkey_probe_provider(void *elm, uintptr_t offs)
7804 {
7805 #pragma unused(offs)
7806 	dtrace_probe_t *probe = (dtrace_probe_t*)elm;
7807 	return probe->dtpr_provider->dtpv_name;
7808 }
7809 
7810 static const char*
dtrace_strkey_offset(void * elm,uintptr_t offs)7811 dtrace_strkey_offset(void *elm, uintptr_t offs)
7812 {
7813 	return ((char *)((uintptr_t)(elm) + offs));
7814 }
7815 
7816 static const char*
dtrace_strkey_deref_offset(void * elm,uintptr_t offs)7817 dtrace_strkey_deref_offset(void *elm, uintptr_t offs)
7818 {
7819 	return *((char **)((uintptr_t)(elm) + offs));
7820 }
7821 
7822 static dtrace_hash_t *
dtrace_hash_create(dtrace_strkey_f func,uintptr_t arg,uintptr_t nextoffs,uintptr_t prevoffs)7823 dtrace_hash_create(dtrace_strkey_f func, uintptr_t arg, uintptr_t nextoffs, uintptr_t prevoffs)
7824 {
7825 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7826 
7827 	hash->dth_getstr = func;
7828 	hash->dth_stroffs = arg;
7829 	hash->dth_nextoffs = nextoffs;
7830 	hash->dth_prevoffs = prevoffs;
7831 
7832 	hash->dth_size = 1;
7833 	hash->dth_mask = hash->dth_size - 1;
7834 
7835 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7836 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7837 
7838 	return (hash);
7839 }
7840 
7841 /*
7842  * APPLE NOTE: dtrace_hash_destroy is not used.
7843  * It is called by dtrace_detach which is not
7844  * currently implemented.  Revisit someday.
7845  */
7846 #if !defined(__APPLE__)
7847 static void
dtrace_hash_destroy(dtrace_hash_t * hash)7848 dtrace_hash_destroy(dtrace_hash_t *hash)
7849 {
7850 #if DEBUG
7851 	int i;
7852 
7853 	for (i = 0; i < hash->dth_size; i++)
7854 		ASSERT(hash->dth_tab[i] == NULL);
7855 #endif
7856 
7857 	kmem_free(hash->dth_tab,
7858 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7859 	kmem_free(hash, sizeof (dtrace_hash_t));
7860 }
7861 #endif /* __APPLE__ */
7862 
7863 static void
dtrace_hash_resize(dtrace_hash_t * hash)7864 dtrace_hash_resize(dtrace_hash_t *hash)
7865 {
7866 	int size = hash->dth_size, i, ndx;
7867 	int new_size = hash->dth_size << 1;
7868 	int new_mask = new_size - 1;
7869 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7870 
7871 	ASSERT((new_size & new_mask) == 0);
7872 
7873 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7874 
7875 	for (i = 0; i < size; i++) {
7876 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7877 			void *elm = bucket->dthb_chain;
7878 
7879 			ASSERT(elm != NULL);
7880 			ndx = DTRACE_HASHSTR(hash, elm) & new_mask;
7881 
7882 			next = bucket->dthb_next;
7883 			bucket->dthb_next = new_tab[ndx];
7884 			new_tab[ndx] = bucket;
7885 		}
7886 	}
7887 
7888 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7889 	hash->dth_tab = new_tab;
7890 	hash->dth_size = new_size;
7891 	hash->dth_mask = new_mask;
7892 }
7893 
7894 static void
dtrace_hash_add(dtrace_hash_t * hash,void * new)7895 dtrace_hash_add(dtrace_hash_t *hash, void *new)
7896 {
7897 	int hashval = DTRACE_HASHSTR(hash, new);
7898 	int ndx = hashval & hash->dth_mask;
7899 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7900 	void **nextp, **prevp;
7901 
7902 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7903 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7904 			goto add;
7905 	}
7906 
7907 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7908 		dtrace_hash_resize(hash);
7909 		dtrace_hash_add(hash, new);
7910 		return;
7911 	}
7912 
7913 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7914 	bucket->dthb_next = hash->dth_tab[ndx];
7915 	hash->dth_tab[ndx] = bucket;
7916 	hash->dth_nbuckets++;
7917 
7918 add:
7919 	nextp = DTRACE_HASHNEXT(hash, new);
7920 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7921 	*nextp = bucket->dthb_chain;
7922 
7923 	if (bucket->dthb_chain != NULL) {
7924 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7925 		ASSERT(*prevp == NULL);
7926 		*prevp = new;
7927 	}
7928 
7929 	bucket->dthb_chain = new;
7930 	bucket->dthb_len++;
7931 }
7932 
7933 static void *
dtrace_hash_lookup_string(dtrace_hash_t * hash,const char * str)7934 dtrace_hash_lookup_string(dtrace_hash_t *hash, const char *str)
7935 {
7936 	int hashval = dtrace_hash_str(str);
7937 	int ndx = hashval & hash->dth_mask;
7938 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7939 
7940 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7941 		if (strcmp(str, DTRACE_GETSTR(hash, bucket->dthb_chain)) == 0)
7942 			return (bucket->dthb_chain);
7943 	}
7944 
7945 	return (NULL);
7946 }
7947 
7948 static dtrace_probe_t *
dtrace_hash_lookup(dtrace_hash_t * hash,void * template)7949 dtrace_hash_lookup(dtrace_hash_t *hash, void *template)
7950 {
7951 	return dtrace_hash_lookup_string(hash, DTRACE_GETSTR(hash, template));
7952 }
7953 
7954 static int
dtrace_hash_collisions(dtrace_hash_t * hash,void * template)7955 dtrace_hash_collisions(dtrace_hash_t *hash, void *template)
7956 {
7957 	int hashval = DTRACE_HASHSTR(hash, template);
7958 	int ndx = hashval & hash->dth_mask;
7959 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7960 
7961 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7962 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7963 			return (bucket->dthb_len);
7964 	}
7965 
7966 	return (0);
7967 }
7968 
7969 static void
dtrace_hash_remove(dtrace_hash_t * hash,void * elm)7970 dtrace_hash_remove(dtrace_hash_t *hash, void *elm)
7971 {
7972 	int ndx = DTRACE_HASHSTR(hash, elm) & hash->dth_mask;
7973 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7974 
7975 	void **prevp = DTRACE_HASHPREV(hash, elm);
7976 	void **nextp = DTRACE_HASHNEXT(hash, elm);
7977 
7978 	/*
7979 	 * Find the bucket that we're removing this elm from.
7980 	 */
7981 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7982 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, elm))
7983 			break;
7984 	}
7985 
7986 	ASSERT(bucket != NULL);
7987 
7988 	if (*prevp == NULL) {
7989 		if (*nextp == NULL) {
7990 			/*
7991 			 * The removed element was the only element on this
7992 			 * bucket; we need to remove the bucket.
7993 			 */
7994 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7995 
7996 			ASSERT(bucket->dthb_chain == elm);
7997 			ASSERT(b != NULL);
7998 
7999 			if (b == bucket) {
8000 				hash->dth_tab[ndx] = bucket->dthb_next;
8001 			} else {
8002 				while (b->dthb_next != bucket)
8003 					b = b->dthb_next;
8004 				b->dthb_next = bucket->dthb_next;
8005 			}
8006 
8007 			ASSERT(hash->dth_nbuckets > 0);
8008 			hash->dth_nbuckets--;
8009 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8010 			return;
8011 		}
8012 
8013 		bucket->dthb_chain = *nextp;
8014 	} else {
8015 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8016 	}
8017 
8018 	if (*nextp != NULL)
8019 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8020 }
8021 
8022 /*
8023  * DTrace Utility Functions
8024  *
8025  * These are random utility functions that are _not_ called from probe context.
8026  */
8027 static int
dtrace_badattr(const dtrace_attribute_t * a)8028 dtrace_badattr(const dtrace_attribute_t *a)
8029 {
8030 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
8031 	    a->dtat_data > DTRACE_STABILITY_MAX ||
8032 	    a->dtat_class > DTRACE_CLASS_MAX);
8033 }
8034 
8035 /*
8036  * Returns a dtrace-managed copy of a string, and will
8037  * deduplicate copies of the same string.
8038  * If the specified string is NULL, returns an empty string
8039  */
8040 static char *
dtrace_strref(const char * str)8041 dtrace_strref(const char *str)
8042 {
8043 	dtrace_string_t *s = NULL;
8044 	size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
8045 
8046 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8047 
8048 	if (str == NULL)
8049 		str = "";
8050 
8051 	for (s = dtrace_hash_lookup_string(dtrace_strings, str); s != NULL;
8052 	     s = *(DTRACE_HASHNEXT(dtrace_strings, s)))  {
8053 		if (strncmp(str, s->dtst_str, bufsize) != 0) {
8054 			continue;
8055 		}
8056 		ASSERT(s->dtst_refcount != UINT32_MAX);
8057 		s->dtst_refcount++;
8058 		return s->dtst_str;
8059 	}
8060 
8061 	s = kmem_zalloc(sizeof(dtrace_string_t) + bufsize, KM_SLEEP);
8062 	s->dtst_refcount = 1;
8063 	(void) strlcpy(s->dtst_str, str, bufsize);
8064 
8065 	dtrace_hash_add(dtrace_strings, s);
8066 
8067 	return s->dtst_str;
8068 }
8069 
8070 static void
dtrace_strunref(const char * str)8071 dtrace_strunref(const char *str)
8072 {
8073 	ASSERT(str != NULL);
8074 	dtrace_string_t *s = NULL;
8075 	size_t bufsize = strlen(str) + 1;
8076 
8077 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8078 
8079 	for (s = dtrace_hash_lookup_string(dtrace_strings, str); s != NULL;
8080 	     s = *(DTRACE_HASHNEXT(dtrace_strings, s)))  {
8081 		if (strncmp(str, s->dtst_str, bufsize) != 0) {
8082 			continue;
8083 		}
8084 		ASSERT(s->dtst_refcount != 0);
8085 		s->dtst_refcount--;
8086 		if (s->dtst_refcount == 0) {
8087 			dtrace_hash_remove(dtrace_strings, s);
8088 			kmem_free(s, sizeof(dtrace_string_t) + bufsize);
8089 		}
8090 		return;
8091 	}
8092 	panic("attempt to unref non-existent string %s", str);
8093 }
8094 
8095 #define	DTRACE_ISALPHA(c)	\
8096 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8097 
8098 static int
dtrace_badname(const char * s)8099 dtrace_badname(const char *s)
8100 {
8101 	char c;
8102 
8103 	if (s == NULL || (c = *s++) == '\0')
8104 		return (0);
8105 
8106 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8107 		return (1);
8108 
8109 	while ((c = *s++) != '\0') {
8110 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8111 		    c != '-' && c != '_' && c != '.' && c != '`')
8112 			return (1);
8113 	}
8114 
8115 	return (0);
8116 }
8117 
8118 static void
dtrace_cred2priv(cred_t * cr,uint32_t * privp,uid_t * uidp,zoneid_t * zoneidp)8119 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8120 {
8121 	uint32_t priv;
8122 
8123 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8124 		if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
8125 			priv = DTRACE_PRIV_USER | DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER;
8126 		}
8127 		else {
8128 			priv = DTRACE_PRIV_ALL;
8129 		}
8130 		*uidp = 0;
8131 		*zoneidp = 0;
8132 	} else {
8133 		*uidp = crgetuid(cr);
8134 		*zoneidp = crgetzoneid(cr);
8135 
8136 		priv = 0;
8137 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8138 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8139 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8140 			priv |= DTRACE_PRIV_USER;
8141 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8142 			priv |= DTRACE_PRIV_PROC;
8143 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8144 			priv |= DTRACE_PRIV_OWNER;
8145 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8146 			priv |= DTRACE_PRIV_ZONEOWNER;
8147 	}
8148 
8149 	*privp = priv;
8150 }
8151 
8152 #ifdef DTRACE_ERRDEBUG
8153 static void
dtrace_errdebug(const char * str)8154 dtrace_errdebug(const char *str)
8155 {
8156 	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8157 	int occupied = 0;
8158 
8159 	lck_mtx_lock(&dtrace_errlock);
8160 	dtrace_errlast = str;
8161 	dtrace_errthread = (kthread_t *)current_thread();
8162 
8163 	while (occupied++ < DTRACE_ERRHASHSZ) {
8164 		if (dtrace_errhash[hval].dter_msg == str) {
8165 			dtrace_errhash[hval].dter_count++;
8166 			goto out;
8167 		}
8168 
8169 		if (dtrace_errhash[hval].dter_msg != NULL) {
8170 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
8171 			continue;
8172 		}
8173 
8174 		dtrace_errhash[hval].dter_msg = str;
8175 		dtrace_errhash[hval].dter_count = 1;
8176 		goto out;
8177 	}
8178 
8179 	panic("dtrace: undersized error hash");
8180 out:
8181 	lck_mtx_unlock(&dtrace_errlock);
8182 }
8183 #endif
8184 
8185 /*
8186  * DTrace Matching Functions
8187  *
8188  * These functions are used to match groups of probes, given some elements of
8189  * a probe tuple, or some globbed expressions for elements of a probe tuple.
8190  */
8191 static int
dtrace_match_priv(const dtrace_probe_t * prp,uint32_t priv,uid_t uid,zoneid_t zoneid)8192 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8193     zoneid_t zoneid)
8194 {
8195 	if (priv != DTRACE_PRIV_ALL) {
8196 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8197 		uint32_t match = priv & ppriv;
8198 
8199 		/*
8200 		 * No PRIV_DTRACE_* privileges...
8201 		 */
8202 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8203 		    DTRACE_PRIV_KERNEL)) == 0)
8204 			return (0);
8205 
8206 		/*
8207 		 * No matching bits, but there were bits to match...
8208 		 */
8209 		if (match == 0 && ppriv != 0)
8210 			return (0);
8211 
8212 		/*
8213 		 * Need to have permissions to the process, but don't...
8214 		 */
8215 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8216 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8217 			return (0);
8218 		}
8219 
8220 		/*
8221 		 * Need to be in the same zone unless we possess the
8222 		 * privilege to examine all zones.
8223 		 */
8224 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8225 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8226 			return (0);
8227 		}
8228 	}
8229 
8230 	return (1);
8231 }
8232 
8233 /*
8234  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8235  * consists of input pattern strings and an ops-vector to evaluate them.
8236  * This function returns >0 for match, 0 for no match, and <0 for error.
8237  */
8238 static int
dtrace_match_probe(const dtrace_probe_t * prp,const dtrace_probekey_t * pkp,uint32_t priv,uid_t uid,zoneid_t zoneid)8239 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8240     uint32_t priv, uid_t uid, zoneid_t zoneid)
8241 {
8242 	dtrace_provider_t *pvp = prp->dtpr_provider;
8243 	int rv;
8244 
8245 	if (pvp->dtpv_defunct)
8246 		return (0);
8247 
8248 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8249 		return (rv);
8250 
8251 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8252 		return (rv);
8253 
8254 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8255 		return (rv);
8256 
8257 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8258 		return (rv);
8259 
8260 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8261 		return (0);
8262 
8263 	return (rv);
8264 }
8265 
8266 /*
8267  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8268  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
8269  * libc's version, the kernel version only applies to 8-bit ASCII strings.
8270  * In addition, all of the recursion cases except for '*' matching have been
8271  * unwound.  For '*', we still implement recursive evaluation, but a depth
8272  * counter is maintained and matching is aborted if we recurse too deep.
8273  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8274  */
8275 static int
dtrace_match_glob(const char * s,const char * p,int depth)8276 dtrace_match_glob(const char *s, const char *p, int depth)
8277 {
8278 	const char *olds;
8279 	char s1, c;
8280 	int gs;
8281 
8282 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8283 		return (-1);
8284 
8285 	if (s == NULL)
8286 		s = ""; /* treat NULL as empty string */
8287 
8288 top:
8289 	olds = s;
8290 	s1 = *s++;
8291 
8292 	if (p == NULL)
8293 		return (0);
8294 
8295 	if ((c = *p++) == '\0')
8296 		return (s1 == '\0');
8297 
8298 	switch (c) {
8299 	case '[': {
8300 		int ok = 0, notflag = 0;
8301 		char lc = '\0';
8302 
8303 		if (s1 == '\0')
8304 			return (0);
8305 
8306 		if (*p == '!') {
8307 			notflag = 1;
8308 			p++;
8309 		}
8310 
8311 		if ((c = *p++) == '\0')
8312 			return (0);
8313 
8314 		do {
8315 			if (c == '-' && lc != '\0' && *p != ']') {
8316 				if ((c = *p++) == '\0')
8317 					return (0);
8318 				if (c == '\\' && (c = *p++) == '\0')
8319 					return (0);
8320 
8321 				if (notflag) {
8322 					if (s1 < lc || s1 > c)
8323 						ok++;
8324 					else
8325 						return (0);
8326 				} else if (lc <= s1 && s1 <= c)
8327 					ok++;
8328 
8329 			} else if (c == '\\' && (c = *p++) == '\0')
8330 				return (0);
8331 
8332 			lc = c; /* save left-hand 'c' for next iteration */
8333 
8334 			if (notflag) {
8335 				if (s1 != c)
8336 					ok++;
8337 				else
8338 					return (0);
8339 			} else if (s1 == c)
8340 				ok++;
8341 
8342 			if ((c = *p++) == '\0')
8343 				return (0);
8344 
8345 		} while (c != ']');
8346 
8347 		if (ok)
8348 			goto top;
8349 
8350 		return (0);
8351 	}
8352 
8353 	case '\\':
8354 		if ((c = *p++) == '\0')
8355 			return (0);
8356 		OS_FALLTHROUGH;
8357 
8358 	default:
8359 		if (c != s1)
8360 			return (0);
8361 		OS_FALLTHROUGH;
8362 
8363 	case '?':
8364 		if (s1 != '\0')
8365 			goto top;
8366 		return (0);
8367 
8368 	case '*':
8369 		while (*p == '*')
8370 			p++; /* consecutive *'s are identical to a single one */
8371 
8372 		if (*p == '\0')
8373 			return (1);
8374 
8375 		for (s = olds; *s != '\0'; s++) {
8376 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8377 				return (gs);
8378 		}
8379 
8380 		return (0);
8381 	}
8382 }
8383 
8384 /*ARGSUSED*/
8385 static int
dtrace_match_string(const char * s,const char * p,int depth)8386 dtrace_match_string(const char *s, const char *p, int depth)
8387 {
8388 #pragma unused(depth) /* __APPLE__ */
8389 	return (s != NULL && s == p);
8390 }
8391 
8392 /*ARGSUSED*/
8393 static int
dtrace_match_module(const char * s,const char * p,int depth)8394 dtrace_match_module(const char *s, const char *p, int depth)
8395 {
8396 #pragma unused(depth) /* __APPLE__ */
8397 	size_t len;
8398 	if (s == NULL || p == NULL)
8399 		return (0);
8400 
8401 	len = strlen(p);
8402 
8403 	if (strncmp(p, s, len) != 0)
8404 		return (0);
8405 
8406 	if (s[len] == '.' || s[len] == '\0')
8407 		return (1);
8408 
8409 	return (0);
8410 }
8411 
8412 /*ARGSUSED*/
8413 static int
dtrace_match_nul(const char * s,const char * p,int depth)8414 dtrace_match_nul(const char *s, const char *p, int depth)
8415 {
8416 #pragma unused(s, p, depth) /* __APPLE__ */
8417 	return (1); /* always match the empty pattern */
8418 }
8419 
8420 /*ARGSUSED*/
8421 static int
dtrace_match_nonzero(const char * s,const char * p,int depth)8422 dtrace_match_nonzero(const char *s, const char *p, int depth)
8423 {
8424 #pragma unused(p, depth) /* __APPLE__ */
8425 	return (s != NULL && s[0] != '\0');
8426 }
8427 
8428 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)8429 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8430     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *, void *), void *arg1, void *arg2)
8431 {
8432 	dtrace_probe_t *probe;
8433 	dtrace_provider_t prov_template = {
8434 		.dtpv_name = (char *)(uintptr_t)pkp->dtpk_prov
8435 	};
8436 
8437 	dtrace_probe_t template = {
8438 		.dtpr_provider = &prov_template,
8439 		.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod,
8440 		.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func,
8441 		.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name
8442 	};
8443 
8444 	dtrace_hash_t *hash = NULL;
8445 	int len, rc, best = INT_MAX, nmatched = 0;
8446 	dtrace_id_t i;
8447 
8448 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8449 
8450 	/*
8451 	 * If the probe ID is specified in the key, just lookup by ID and
8452 	 * invoke the match callback once if a matching probe is found.
8453 	 */
8454 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8455 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8456 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8457 		        if ((*matched)(probe, arg1, arg2) == DTRACE_MATCH_FAIL)
8458                                return (DTRACE_MATCH_FAIL);
8459 			nmatched++;
8460 		}
8461 		return (nmatched);
8462 	}
8463 
8464 	/*
8465 	 * We want to find the most distinct of the provider name, module name,
8466 	 * function name, and name.  So for each one that is not a glob
8467 	 * pattern or empty string, we perform a lookup in the corresponding
8468 	 * hash and use the hash table with the fewest collisions to do our
8469 	 * search.
8470 	 */
8471 	if (pkp->dtpk_pmatch == &dtrace_match_string &&
8472 	    (len = dtrace_hash_collisions(dtrace_byprov, &template)) < best) {
8473 		best = len;
8474 		hash = dtrace_byprov;
8475 	}
8476 
8477 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8478 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8479 		best = len;
8480 		hash = dtrace_bymod;
8481 	}
8482 
8483 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8484 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8485 		best = len;
8486 		hash = dtrace_byfunc;
8487 	}
8488 
8489 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8490 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8491 		best = len;
8492 		hash = dtrace_byname;
8493 	}
8494 
8495 	/*
8496 	 * If we did not select a hash table, iterate over every probe and
8497 	 * invoke our callback for each one that matches our input probe key.
8498 	 */
8499 	if (hash == NULL) {
8500 		for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
8501 			if ((probe = dtrace_probes[i]) == NULL ||
8502 			    dtrace_match_probe(probe, pkp, priv, uid,
8503 			    zoneid) <= 0)
8504 				continue;
8505 
8506 			nmatched++;
8507 
8508                        if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
8509 			       if (rc == DTRACE_MATCH_FAIL)
8510                                        return (DTRACE_MATCH_FAIL);
8511 			       break;
8512                        }
8513 		}
8514 
8515 		return (nmatched);
8516 	}
8517 
8518 	/*
8519 	 * If we selected a hash table, iterate over each probe of the same key
8520 	 * name and invoke the callback for every probe that matches the other
8521 	 * attributes of our input probe key.
8522 	 */
8523 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8524 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8525 
8526 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8527 			continue;
8528 
8529 		nmatched++;
8530 
8531 		if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
8532 		    if (rc == DTRACE_MATCH_FAIL)
8533 			return (DTRACE_MATCH_FAIL);
8534 		    break;
8535 		}
8536 	}
8537 
8538 	return (nmatched);
8539 }
8540 
8541 /*
8542  * Return the function pointer dtrace_probecmp() should use to compare the
8543  * specified pattern with a string.  For NULL or empty patterns, we select
8544  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8545  * For non-empty non-glob strings, we use dtrace_match_string().
8546  */
8547 static dtrace_probekey_f *
dtrace_probekey_func(const char * p)8548 dtrace_probekey_func(const char *p)
8549 {
8550 	char c;
8551 
8552 	if (p == NULL || *p == '\0')
8553 		return (&dtrace_match_nul);
8554 
8555 	while ((c = *p++) != '\0') {
8556 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8557 			return (&dtrace_match_glob);
8558 	}
8559 
8560 	return (&dtrace_match_string);
8561 }
8562 
8563 static dtrace_probekey_f *
dtrace_probekey_module_func(const char * p)8564 dtrace_probekey_module_func(const char *p)
8565 {
8566 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8567 
8568 	dtrace_probekey_f *f = dtrace_probekey_func(p);
8569 	if (f == &dtrace_match_string) {
8570 		dtrace_probe_t template = {
8571 			.dtpr_mod = (char *)(uintptr_t)p,
8572 		};
8573 		if (dtrace_hash_lookup(dtrace_bymod, &template) == NULL) {
8574 			return (&dtrace_match_module);
8575 		}
8576 		return (&dtrace_match_string);
8577 	}
8578 	return f;
8579 }
8580 
8581 /*
8582  * Build a probe comparison key for use with dtrace_match_probe() from the
8583  * given probe description.  By convention, a null key only matches anchored
8584  * probes: if each field is the empty string, reset dtpk_fmatch to
8585  * dtrace_match_nonzero().
8586  */
8587 static void
dtrace_probekey(const dtrace_probedesc_t * pdp,dtrace_probekey_t * pkp)8588 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8589 {
8590 
8591 	pkp->dtpk_prov = dtrace_strref(pdp->dtpd_provider);
8592 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8593 
8594 	pkp->dtpk_mod = dtrace_strref(pdp->dtpd_mod);
8595 	pkp->dtpk_mmatch = dtrace_probekey_module_func(pdp->dtpd_mod);
8596 
8597 	pkp->dtpk_func = dtrace_strref(pdp->dtpd_func);
8598 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8599 
8600 	pkp->dtpk_name = dtrace_strref(pdp->dtpd_name);
8601 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8602 
8603 	pkp->dtpk_id = pdp->dtpd_id;
8604 
8605 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8606 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8607 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8608 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8609 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8610 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8611 }
8612 
8613 static void
dtrace_probekey_release(dtrace_probekey_t * pkp)8614 dtrace_probekey_release(dtrace_probekey_t *pkp)
8615 {
8616 	dtrace_strunref(pkp->dtpk_prov);
8617 	dtrace_strunref(pkp->dtpk_mod);
8618 	dtrace_strunref(pkp->dtpk_func);
8619 	dtrace_strunref(pkp->dtpk_name);
8620 }
8621 
8622 static int
dtrace_cond_provider_match(dtrace_probedesc_t * desc,void * data)8623 dtrace_cond_provider_match(dtrace_probedesc_t *desc, void *data)
8624 {
8625 	if (desc == NULL)
8626 		return 1;
8627 
8628 	dtrace_probekey_f *func = dtrace_probekey_func(desc->dtpd_provider);
8629 
8630 	return func((char*)data, desc->dtpd_provider, 0);
8631 }
8632 
8633 /*
8634  * DTrace Provider-to-Framework API Functions
8635  *
8636  * These functions implement much of the Provider-to-Framework API, as
8637  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8638  * the functions in the API for probe management (found below), and
8639  * dtrace_probe() itself (found above).
8640  */
8641 
8642 /*
8643  * Register the calling provider with the DTrace framework.  This should
8644  * generally be called by DTrace providers in their attach(9E) entry point.
8645  */
8646 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)8647 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8648     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8649 {
8650 	dtrace_provider_t *provider;
8651 
8652 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8653 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8654 		    "arguments", name ? name : "<NULL>");
8655 		return (EINVAL);
8656 	}
8657 
8658 	if (name[0] == '\0' || dtrace_badname(name)) {
8659 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8660 		    "provider name", name);
8661 		return (EINVAL);
8662 	}
8663 
8664 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8665 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8666 	    pops->dtps_destroy == NULL ||
8667 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8668 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8669 		    "provider ops", name);
8670 		return (EINVAL);
8671 	}
8672 
8673 	if (dtrace_badattr(&pap->dtpa_provider) ||
8674 	    dtrace_badattr(&pap->dtpa_mod) ||
8675 	    dtrace_badattr(&pap->dtpa_func) ||
8676 	    dtrace_badattr(&pap->dtpa_name) ||
8677 	    dtrace_badattr(&pap->dtpa_args)) {
8678 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8679 		    "provider attributes", name);
8680 		return (EINVAL);
8681 	}
8682 
8683 	if (priv & ~DTRACE_PRIV_ALL) {
8684 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8685 		    "privilege attributes", name);
8686 		return (EINVAL);
8687 	}
8688 
8689 	if ((priv & DTRACE_PRIV_KERNEL) &&
8690 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8691 	    pops->dtps_usermode == NULL) {
8692 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8693 		    "dtps_usermode() op for given privilege attributes", name);
8694 		return (EINVAL);
8695 	}
8696 
8697 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8698 
8699 	provider->dtpv_attr = *pap;
8700 	provider->dtpv_priv.dtpp_flags = priv;
8701 	if (cr != NULL) {
8702 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8703 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8704 	}
8705 	provider->dtpv_pops = *pops;
8706 
8707 	if (pops->dtps_provide == NULL) {
8708 		ASSERT(pops->dtps_provide_module != NULL);
8709 		provider->dtpv_pops.dtps_provide = dtrace_provide_nullop;
8710 	}
8711 
8712 	if (pops->dtps_provide_module == NULL) {
8713 		ASSERT(pops->dtps_provide != NULL);
8714 		provider->dtpv_pops.dtps_provide_module =
8715 		    dtrace_provide_module_nullop;
8716 	}
8717 
8718 	if (pops->dtps_suspend == NULL) {
8719 		ASSERT(pops->dtps_resume == NULL);
8720 		provider->dtpv_pops.dtps_suspend = dtrace_suspend_nullop;
8721 		provider->dtpv_pops.dtps_resume = dtrace_resume_nullop;
8722 	}
8723 
8724 	provider->dtpv_arg = arg;
8725 	*idp = (dtrace_provider_id_t)provider;
8726 
8727 	if (pops == &dtrace_provider_ops) {
8728 		LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8729 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8730 
8731 		provider->dtpv_name = dtrace_strref(name);
8732 
8733 		ASSERT(dtrace_anon.dta_enabling == NULL);
8734 
8735 		/*
8736 		 * We make sure that the DTrace provider is at the head of
8737 		 * the provider chain.
8738 		 */
8739 		provider->dtpv_next = dtrace_provider;
8740 		dtrace_provider = provider;
8741 		return (0);
8742 	}
8743 
8744 	lck_mtx_lock(&dtrace_provider_lock);
8745 	lck_mtx_lock(&dtrace_lock);
8746 
8747 	provider->dtpv_name = dtrace_strref(name);
8748 
8749 	/*
8750 	 * If there is at least one provider registered, we'll add this
8751 	 * provider after the first provider.
8752 	 */
8753 	if (dtrace_provider != NULL) {
8754 		provider->dtpv_next = dtrace_provider->dtpv_next;
8755 		dtrace_provider->dtpv_next = provider;
8756 	} else {
8757 		dtrace_provider = provider;
8758 	}
8759 
8760 	if (dtrace_retained != NULL) {
8761 		dtrace_enabling_provide(provider);
8762 
8763 		/*
8764 		 * Now we need to call dtrace_enabling_matchall_with_cond() --
8765 		 * with a condition matching the provider name we just added,
8766 		 * which will acquire cpu_lock and dtrace_lock.  We therefore need
8767 		 * to drop all of our locks before calling into it...
8768 		 */
8769 		lck_mtx_unlock(&dtrace_lock);
8770 		lck_mtx_unlock(&dtrace_provider_lock);
8771 
8772 		dtrace_match_cond_t cond = {dtrace_cond_provider_match, provider->dtpv_name};
8773 		dtrace_enabling_matchall_with_cond(&cond);
8774 
8775 		return (0);
8776 	}
8777 
8778 	lck_mtx_unlock(&dtrace_lock);
8779 	lck_mtx_unlock(&dtrace_provider_lock);
8780 
8781 	return (0);
8782 }
8783 
8784 /*
8785  * Unregister the specified provider from the DTrace framework.  This should
8786  * generally be called by DTrace providers in their detach(9E) entry point.
8787  */
8788 int
dtrace_unregister(dtrace_provider_id_t id)8789 dtrace_unregister(dtrace_provider_id_t id)
8790 {
8791 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8792 	dtrace_provider_t *prev = NULL;
8793 	int self = 0;
8794 	dtrace_probe_t *probe, *first = NULL, *next = NULL;
8795 	dtrace_probe_t template = {
8796 		.dtpr_provider = old
8797 	};
8798 
8799 	if (old->dtpv_pops.dtps_enable ==
8800 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8801 		/*
8802 		 * If DTrace itself is the provider, we're called with locks
8803 		 * already held.
8804 		 */
8805 		ASSERT(old == dtrace_provider);
8806 		ASSERT(dtrace_devi != NULL);
8807 		LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8808 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8809 		self = 1;
8810 
8811 		if (dtrace_provider->dtpv_next != NULL) {
8812 			/*
8813 			 * There's another provider here; return failure.
8814 			 */
8815 			return (EBUSY);
8816 		}
8817 	} else {
8818 		lck_mtx_lock(&dtrace_provider_lock);
8819 		lck_mtx_lock(&mod_lock);
8820 		lck_mtx_lock(&dtrace_lock);
8821 	}
8822 
8823 	/*
8824 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8825 	 * probes, we refuse to let providers slither away, unless this
8826 	 * provider has already been explicitly invalidated.
8827 	 */
8828 	if (!old->dtpv_defunct &&
8829 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8830 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8831 		if (!self) {
8832 			lck_mtx_unlock(&dtrace_lock);
8833 			lck_mtx_unlock(&mod_lock);
8834 			lck_mtx_unlock(&dtrace_provider_lock);
8835 		}
8836 		return (EBUSY);
8837 	}
8838 
8839 	/*
8840 	 * Attempt to destroy the probes associated with this provider.
8841 	 */
8842 	if (old->dtpv_ecb_count!=0) {
8843 		/*
8844 		 * We have at least one ECB; we can't remove this provider.
8845 		 */
8846 		if (!self) {
8847 			lck_mtx_unlock(&dtrace_lock);
8848 			lck_mtx_unlock(&mod_lock);
8849 			lck_mtx_unlock(&dtrace_provider_lock);
8850 		}
8851 		return (EBUSY);
8852 	}
8853 
8854 	/*
8855 	 * All of the probes for this provider are disabled; we can safely
8856 	 * remove all of them from their hash chains and from the probe array.
8857 	 */
8858 	for (probe = dtrace_hash_lookup(dtrace_byprov, &template); probe != NULL;
8859 	    probe = *(DTRACE_HASHNEXT(dtrace_byprov, probe))) {
8860 		if (probe->dtpr_provider != old)
8861 			continue;
8862 
8863 		dtrace_probes[probe->dtpr_id - 1] = NULL;
8864 		old->dtpv_probe_count--;
8865 
8866 		dtrace_hash_remove(dtrace_bymod, probe);
8867 		dtrace_hash_remove(dtrace_byfunc, probe);
8868 		dtrace_hash_remove(dtrace_byname, probe);
8869 
8870 		if (first == NULL) {
8871 			first = probe;
8872 			probe->dtpr_nextmod = NULL;
8873 		} else {
8874 			/*
8875 			 * Use nextmod as the chain of probes to remove
8876 			 */
8877 			probe->dtpr_nextmod = first;
8878 			first = probe;
8879 		}
8880 	}
8881 
8882 	for (probe = first; probe != NULL; probe = next) {
8883 		next = probe->dtpr_nextmod;
8884 		dtrace_hash_remove(dtrace_byprov, probe);
8885 	}
8886 
8887 	/*
8888 	 * The provider's probes have been removed from the hash chains and
8889 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8890 	 * everyone has cleared out from any probe array processing.
8891 	 */
8892 	dtrace_sync();
8893 
8894 	for (probe = first; probe != NULL; probe = next) {
8895 		next = probe->dtpr_nextmod;
8896 
8897 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8898 		    probe->dtpr_arg);
8899 		dtrace_strunref(probe->dtpr_mod);
8900 		dtrace_strunref(probe->dtpr_func);
8901 		dtrace_strunref(probe->dtpr_name);
8902 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8903 		zfree(dtrace_probe_t_zone, probe);
8904 	}
8905 
8906 	if ((prev = dtrace_provider) == old) {
8907 		ASSERT(self || dtrace_devi == NULL);
8908 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8909 		dtrace_provider = old->dtpv_next;
8910 	} else {
8911 		while (prev != NULL && prev->dtpv_next != old)
8912 			prev = prev->dtpv_next;
8913 
8914 		if (prev == NULL) {
8915 			panic("attempt to unregister non-existent "
8916 			    "dtrace provider %p\n", (void *)id);
8917 		}
8918 
8919 		prev->dtpv_next = old->dtpv_next;
8920 	}
8921 
8922 	dtrace_strunref(old->dtpv_name);
8923 
8924 	if (!self) {
8925 		lck_mtx_unlock(&dtrace_lock);
8926 		lck_mtx_unlock(&mod_lock);
8927 		lck_mtx_unlock(&dtrace_provider_lock);
8928 	}
8929 
8930 	kmem_free(old, sizeof (dtrace_provider_t));
8931 
8932 	return (0);
8933 }
8934 
8935 /*
8936  * Invalidate the specified provider.  All subsequent probe lookups for the
8937  * specified provider will fail, but its probes will not be removed.
8938  */
8939 void
dtrace_invalidate(dtrace_provider_id_t id)8940 dtrace_invalidate(dtrace_provider_id_t id)
8941 {
8942 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8943 
8944 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8945 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8946 
8947 	lck_mtx_lock(&dtrace_provider_lock);
8948 	lck_mtx_lock(&dtrace_lock);
8949 
8950 	pvp->dtpv_defunct = 1;
8951 
8952 	lck_mtx_unlock(&dtrace_lock);
8953 	lck_mtx_unlock(&dtrace_provider_lock);
8954 }
8955 
8956 /*
8957  * Indicate whether or not DTrace has attached.
8958  */
8959 int
dtrace_attached(void)8960 dtrace_attached(void)
8961 {
8962 	/*
8963 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8964 	 * attached.  (It's non-NULL because DTrace is always itself a
8965 	 * provider.)
8966 	 */
8967 	return (dtrace_provider != NULL);
8968 }
8969 
8970 /*
8971  * Remove all the unenabled probes for the given provider.  This function is
8972  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8973  * -- just as many of its associated probes as it can.
8974  */
8975 int
dtrace_condense(dtrace_provider_id_t id)8976 dtrace_condense(dtrace_provider_id_t id)
8977 {
8978 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8979 	dtrace_probe_t *probe, *first = NULL;
8980 	dtrace_probe_t template = {
8981 		.dtpr_provider = prov
8982 	};
8983 
8984 	/*
8985 	 * Make sure this isn't the dtrace provider itself.
8986 	 */
8987 	ASSERT(prov->dtpv_pops.dtps_enable !=
8988 	  (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8989 
8990 	lck_mtx_lock(&dtrace_provider_lock);
8991 	lck_mtx_lock(&dtrace_lock);
8992 
8993 	/*
8994 	 * Attempt to destroy the probes associated with this provider.
8995 	 */
8996 	for (probe = dtrace_hash_lookup(dtrace_byprov, &template); probe != NULL;
8997 	    probe = *(DTRACE_HASHNEXT(dtrace_byprov, probe))) {
8998 
8999 		if (probe->dtpr_provider != prov)
9000 			continue;
9001 
9002 		if (probe->dtpr_ecb != NULL)
9003 			continue;
9004 
9005 		dtrace_probes[probe->dtpr_id - 1] = NULL;
9006 		prov->dtpv_probe_count--;
9007 
9008 		dtrace_hash_remove(dtrace_bymod, probe);
9009 		dtrace_hash_remove(dtrace_byfunc, probe);
9010 		dtrace_hash_remove(dtrace_byname, probe);
9011 
9012 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
9013 		    probe->dtpr_arg);
9014 		dtrace_strunref(probe->dtpr_mod);
9015 		dtrace_strunref(probe->dtpr_func);
9016 		dtrace_strunref(probe->dtpr_name);
9017 		if (first == NULL) {
9018 			first = probe;
9019 			probe->dtpr_nextmod = NULL;
9020 		} else {
9021 			/*
9022 			 * Use nextmod as the chain of probes to remove
9023 			 */
9024 			probe->dtpr_nextmod = first;
9025 			first = probe;
9026 		}
9027 	}
9028 
9029 	for (probe = first; probe != NULL; probe = first) {
9030 		first = probe->dtpr_nextmod;
9031 		dtrace_hash_remove(dtrace_byprov, probe);
9032 		vmem_free(dtrace_arena, (void *)((uintptr_t)probe->dtpr_id), 1);
9033 		zfree(dtrace_probe_t_zone, probe);
9034 	}
9035 
9036 	lck_mtx_unlock(&dtrace_lock);
9037 	lck_mtx_unlock(&dtrace_provider_lock);
9038 
9039 	return (0);
9040 }
9041 
9042 /*
9043  * DTrace Probe Management Functions
9044  *
9045  * The functions in this section perform the DTrace probe management,
9046  * including functions to create probes, look-up probes, and call into the
9047  * providers to request that probes be provided.  Some of these functions are
9048  * in the Provider-to-Framework API; these functions can be identified by the
9049  * fact that they are not declared "static".
9050  */
9051 
9052 /*
9053  * Create a probe with the specified module name, function name, and name.
9054  */
9055 dtrace_id_t
dtrace_probe_create(dtrace_provider_id_t prov,const char * mod,const char * func,const char * name,int aframes,void * arg)9056 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9057     const char *func, const char *name, int aframes, void *arg)
9058 {
9059 	dtrace_probe_t *probe, **probes;
9060 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9061 	dtrace_id_t id;
9062 
9063 	if (provider == dtrace_provider) {
9064 		LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9065 	} else {
9066 		lck_mtx_lock(&dtrace_lock);
9067 	}
9068 
9069 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9070 	    VM_BESTFIT | VM_SLEEP);
9071 
9072 	probe = zalloc_flags(dtrace_probe_t_zone, Z_WAITOK | Z_ZERO);
9073 
9074 	probe->dtpr_id = id;
9075 	probe->dtpr_gen = dtrace_probegen++;
9076 	probe->dtpr_mod = dtrace_strref(mod);
9077 	probe->dtpr_func = dtrace_strref(func);
9078 	probe->dtpr_name = dtrace_strref(name);
9079 	probe->dtpr_arg = arg;
9080 	probe->dtpr_aframes = aframes;
9081 	probe->dtpr_provider = provider;
9082 
9083 	dtrace_hash_add(dtrace_byprov, probe);
9084 	dtrace_hash_add(dtrace_bymod, probe);
9085 	dtrace_hash_add(dtrace_byfunc, probe);
9086 	dtrace_hash_add(dtrace_byname, probe);
9087 
9088 	if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
9089 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9090 		size_t nsize = osize * 2;
9091 
9092 		probes = kmem_zalloc(nsize, KM_SLEEP);
9093 
9094 		dtrace_probe_t **oprobes = dtrace_probes;
9095 
9096 		bcopy(oprobes, probes, osize);
9097 		dtrace_membar_producer();
9098 		dtrace_probes = probes;
9099 
9100 		dtrace_sync();
9101 
9102 		/*
9103 		 * All CPUs are now seeing the new probes array; we can
9104 		 * safely free the old array.
9105 		 */
9106 		kmem_free(oprobes, osize);
9107 		dtrace_nprobes *= 2;
9108 
9109 		ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
9110 	}
9111 
9112 	ASSERT(dtrace_probes[id - 1] == NULL);
9113 	dtrace_probes[id - 1] = probe;
9114 	provider->dtpv_probe_count++;
9115 
9116 	if (provider != dtrace_provider)
9117 		lck_mtx_unlock(&dtrace_lock);
9118 
9119 	return (id);
9120 }
9121 
9122 static dtrace_probe_t *
dtrace_probe_lookup_id(dtrace_id_t id)9123 dtrace_probe_lookup_id(dtrace_id_t id)
9124 {
9125 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9126 
9127 	if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
9128 		return (NULL);
9129 
9130 	return (dtrace_probes[id - 1]);
9131 }
9132 
9133 static int
dtrace_probe_lookup_match(dtrace_probe_t * probe,void * arg1,void * arg2)9134 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg1, void *arg2)
9135 {
9136 #pragma unused(arg2)
9137 	*((dtrace_id_t *)arg1) = probe->dtpr_id;
9138 
9139 	return (DTRACE_MATCH_DONE);
9140 }
9141 
9142 /*
9143  * Look up a probe based on provider and one or more of module name, function
9144  * name and probe name.
9145  */
9146 dtrace_id_t
dtrace_probe_lookup(dtrace_provider_id_t prid,const char * mod,const char * func,const char * name)9147 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
9148     const char *func, const char *name)
9149 {
9150 	dtrace_probekey_t pkey;
9151 	dtrace_id_t id;
9152 	int match;
9153 
9154 	lck_mtx_lock(&dtrace_lock);
9155 
9156 	pkey.dtpk_prov = dtrace_strref(((dtrace_provider_t *)prid)->dtpv_name);
9157 	pkey.dtpk_pmatch = &dtrace_match_string;
9158 	pkey.dtpk_mod = dtrace_strref(mod);
9159 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9160 	pkey.dtpk_func = dtrace_strref(func);
9161 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9162 	pkey.dtpk_name = dtrace_strref(name);
9163 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9164 	pkey.dtpk_id = DTRACE_IDNONE;
9165 
9166 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9167 	    dtrace_probe_lookup_match, &id, NULL);
9168 
9169 	dtrace_probekey_release(&pkey);
9170 
9171 	lck_mtx_unlock(&dtrace_lock);
9172 
9173 	ASSERT(match == 1 || match == 0);
9174 	return (match ? id : 0);
9175 }
9176 
9177 /*
9178  * Returns the probe argument associated with the specified probe.
9179  */
9180 void *
dtrace_probe_arg(dtrace_provider_id_t id,dtrace_id_t pid)9181 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9182 {
9183 	dtrace_probe_t *probe;
9184 	void *rval = NULL;
9185 
9186 	lck_mtx_lock(&dtrace_lock);
9187 
9188 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9189 	    probe->dtpr_provider == (dtrace_provider_t *)id)
9190 		rval = probe->dtpr_arg;
9191 
9192 	lck_mtx_unlock(&dtrace_lock);
9193 
9194 	return (rval);
9195 }
9196 
9197 /*
9198  * Copy a probe into a probe description.
9199  */
9200 static void
dtrace_probe_description(const dtrace_probe_t * prp,dtrace_probedesc_t * pdp)9201 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9202 {
9203 	bzero(pdp, sizeof (dtrace_probedesc_t));
9204 	pdp->dtpd_id = prp->dtpr_id;
9205 
9206 	/* APPLE NOTE: Darwin employs size bounded string operation. */
9207 	(void) strlcpy(pdp->dtpd_provider,
9208 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
9209 
9210 	(void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
9211 	(void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
9212 	(void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
9213 }
9214 
9215 /*
9216  * Called to indicate that a probe -- or probes -- should be provided by a
9217  * specfied provider.  If the specified description is NULL, the provider will
9218  * be told to provide all of its probes.  (This is done whenever a new
9219  * consumer comes along, or whenever a retained enabling is to be matched.) If
9220  * the specified description is non-NULL, the provider is given the
9221  * opportunity to dynamically provide the specified probe, allowing providers
9222  * to support the creation of probes on-the-fly.  (So-called _autocreated_
9223  * probes.)  If the provider is NULL, the operations will be applied to all
9224  * providers; if the provider is non-NULL the operations will only be applied
9225  * to the specified provider.  The dtrace_provider_lock must be held, and the
9226  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9227  * will need to grab the dtrace_lock when it reenters the framework through
9228  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9229  */
9230 static void
dtrace_probe_provide(dtrace_probedesc_t * desc,dtrace_provider_t * prv)9231 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9232 {
9233 	struct modctl *ctl;
9234 	int all = 0;
9235 
9236 	LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
9237 
9238 	if (prv == NULL) {
9239 		all = 1;
9240 		prv = dtrace_provider;
9241 	}
9242 
9243 	do {
9244 		/*
9245 		 * First, call the blanket provide operation.
9246 		 */
9247 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9248 
9249 		/*
9250 		 * Now call the per-module provide operation.  We will grab
9251 		 * mod_lock to prevent the list from being modified.  Note
9252 		 * that this also prevents the mod_busy bits from changing.
9253 		 * (mod_busy can only be changed with mod_lock held.)
9254 		 */
9255 		lck_mtx_lock(&mod_lock);
9256 
9257 		ctl = dtrace_modctl_list;
9258 		while (ctl) {
9259 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9260 			ctl = ctl->mod_next;
9261 		}
9262 
9263 		lck_mtx_unlock(&mod_lock);
9264 	} while (all && (prv = prv->dtpv_next) != NULL);
9265 }
9266 
9267 /*
9268  * Iterate over each probe, and call the Framework-to-Provider API function
9269  * denoted by offs.
9270  */
9271 static void
dtrace_probe_foreach(uintptr_t offs)9272 dtrace_probe_foreach(uintptr_t offs)
9273 {
9274 	dtrace_provider_t *prov;
9275 	void (*func)(void *, dtrace_id_t, void *);
9276 	dtrace_probe_t *probe;
9277 	dtrace_icookie_t cookie;
9278 	int i;
9279 
9280 	/*
9281 	 * We disable interrupts to walk through the probe array.  This is
9282 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9283 	 * won't see stale data.
9284 	 */
9285 	cookie = dtrace_interrupt_disable();
9286 
9287 	for (i = 0; i < dtrace_nprobes; i++) {
9288 		if ((probe = dtrace_probes[i]) == NULL)
9289 			continue;
9290 
9291 		if (probe->dtpr_ecb == NULL) {
9292 			/*
9293 			 * This probe isn't enabled -- don't call the function.
9294 			 */
9295 			continue;
9296 		}
9297 
9298 		prov = probe->dtpr_provider;
9299 		func = *((void(**)(void *, dtrace_id_t, void *))
9300 		    ((uintptr_t)&prov->dtpv_pops + offs));
9301 
9302 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9303 	}
9304 
9305 	dtrace_interrupt_enable(cookie);
9306 }
9307 
9308 static int
dtrace_probe_enable(const dtrace_probedesc_t * desc,dtrace_enabling_t * enab,dtrace_ecbdesc_t * ep)9309 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab, dtrace_ecbdesc_t *ep)
9310 {
9311 	dtrace_probekey_t pkey;
9312 	uint32_t priv;
9313 	uid_t uid;
9314 	zoneid_t zoneid;
9315 	int err;
9316 
9317 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9318 
9319 	dtrace_ecb_create_cache = NULL;
9320 
9321 	if (desc == NULL) {
9322 		/*
9323 		 * If we're passed a NULL description, we're being asked to
9324 		 * create an ECB with a NULL probe.
9325 		 */
9326 		(void) dtrace_ecb_create_enable(NULL, enab, ep);
9327 		return (0);
9328 	}
9329 
9330 	dtrace_probekey(desc, &pkey);
9331 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9332 	    &priv, &uid, &zoneid);
9333 
9334 	err = dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable, enab, ep);
9335 
9336 	dtrace_probekey_release(&pkey);
9337 
9338 	return err;
9339 }
9340 
9341 /*
9342  * DTrace Helper Provider Functions
9343  */
9344 static void
dtrace_dofattr2attr(dtrace_attribute_t * attr,const dof_attr_t dofattr)9345 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9346 {
9347 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
9348 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
9349 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9350 }
9351 
9352 static void
dtrace_dofprov2hprov(dtrace_helper_provdesc_t * hprov,const dof_provider_t * dofprov,char * strtab)9353 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9354     const dof_provider_t *dofprov, char *strtab)
9355 {
9356 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9357 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9358 	    dofprov->dofpv_provattr);
9359 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9360 	    dofprov->dofpv_modattr);
9361 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9362 	    dofprov->dofpv_funcattr);
9363 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9364 	    dofprov->dofpv_nameattr);
9365 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9366 	    dofprov->dofpv_argsattr);
9367 }
9368 
9369 static void
dtrace_helper_provide_one(dof_helper_t * dhp,dof_sec_t * sec,proc_t * p)9370 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
9371 {
9372 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9373 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9374 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9375 	dof_provider_t *provider;
9376 	dof_probe_t *probe;
9377 	uint32_t *off, *enoff;
9378 	uint8_t *arg;
9379 	char *strtab;
9380 	uint_t i, nprobes;
9381 	dtrace_helper_provdesc_t dhpv;
9382 	dtrace_helper_probedesc_t dhpb;
9383 	dtrace_meta_t *meta = dtrace_meta_pid;
9384 	dtrace_mops_t *mops = &meta->dtm_mops;
9385 	void *parg;
9386 
9387 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9388 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9389 	    provider->dofpv_strtab * dof->dofh_secsize);
9390 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9391 	    provider->dofpv_probes * dof->dofh_secsize);
9392 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9393 	    provider->dofpv_prargs * dof->dofh_secsize);
9394 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9395 	    provider->dofpv_proffs * dof->dofh_secsize);
9396 
9397 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9398 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9399 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9400 	enoff = NULL;
9401 
9402 	/*
9403 	 * See dtrace_helper_provider_validate().
9404 	 */
9405 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9406 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
9407 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9408 		    provider->dofpv_prenoffs * dof->dofh_secsize);
9409 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9410 	}
9411 
9412 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9413 
9414 	/*
9415 	 * Create the provider.
9416 	 */
9417 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9418 
9419 	if ((parg = mops->dtms_provide_proc(meta->dtm_arg, &dhpv, p)) == NULL)
9420 		return;
9421 
9422 	meta->dtm_count++;
9423 
9424 	/*
9425 	 * Create the probes.
9426 	 */
9427 	for (i = 0; i < nprobes; i++) {
9428 		probe = (dof_probe_t *)(uintptr_t)(daddr +
9429 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9430 
9431 		dhpb.dthpb_mod = dhp->dofhp_mod;
9432 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9433 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9434 #if !defined(__APPLE__)
9435 		dhpb.dthpb_base = probe->dofpr_addr;
9436 #else
9437 		dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
9438 #endif
9439 		dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
9440 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9441 		if (enoff != NULL) {
9442 			dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
9443 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9444 		} else {
9445 			dhpb.dthpb_enoffs = NULL;
9446 			dhpb.dthpb_nenoffs = 0;
9447 		}
9448 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9449 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9450 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9451 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9452 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9453 
9454 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9455 	}
9456 
9457 	/*
9458 	 * Since we just created probes, we need to match our enablings
9459 	 * against those, with a precondition knowing that we have only
9460 	 * added probes from this provider
9461 	 */
9462 	char *prov_name = mops->dtms_provider_name(parg);
9463 	ASSERT(prov_name != NULL);
9464 	dtrace_match_cond_t cond = {dtrace_cond_provider_match, (void*)prov_name};
9465 
9466 	dtrace_enabling_matchall_with_cond(&cond);
9467 }
9468 
9469 static void
dtrace_helper_provide(dof_helper_t * dhp,proc_t * p)9470 dtrace_helper_provide(dof_helper_t *dhp, proc_t *p)
9471 {
9472 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9473 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9474 	uint32_t i;
9475 
9476 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
9477 
9478 	for (i = 0; i < dof->dofh_secnum; i++) {
9479 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9480 		    dof->dofh_secoff + i * dof->dofh_secsize);
9481 
9482 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9483 			continue;
9484 
9485 		dtrace_helper_provide_one(dhp, sec, p);
9486 	}
9487 }
9488 
9489 static void
dtrace_helper_provider_remove_one(dof_helper_t * dhp,dof_sec_t * sec,proc_t * p)9490 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
9491 {
9492 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9493 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9494 	dof_sec_t *str_sec;
9495 	dof_provider_t *provider;
9496 	char *strtab;
9497 	dtrace_helper_provdesc_t dhpv;
9498 	dtrace_meta_t *meta = dtrace_meta_pid;
9499 	dtrace_mops_t *mops = &meta->dtm_mops;
9500 
9501 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9502 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9503 	    provider->dofpv_strtab * dof->dofh_secsize);
9504 
9505 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9506 
9507 	/*
9508 	 * Create the provider.
9509 	 */
9510 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9511 
9512 	mops->dtms_remove_proc(meta->dtm_arg, &dhpv, p);
9513 
9514 	meta->dtm_count--;
9515 }
9516 
9517 static void
dtrace_helper_provider_remove(dof_helper_t * dhp,proc_t * p)9518 dtrace_helper_provider_remove(dof_helper_t *dhp, proc_t *p)
9519 {
9520 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9521 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9522 	uint32_t i;
9523 
9524 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
9525 
9526 	for (i = 0; i < dof->dofh_secnum; i++) {
9527 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9528 		    dof->dofh_secoff + i * dof->dofh_secsize);
9529 
9530 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9531 			continue;
9532 
9533 		dtrace_helper_provider_remove_one(dhp, sec, p);
9534 	}
9535 }
9536 
9537 /*
9538  * DTrace Meta Provider-to-Framework API Functions
9539  *
9540  * These functions implement the Meta Provider-to-Framework API, as described
9541  * in <sys/dtrace.h>.
9542  */
9543 int
dtrace_meta_register(const char * name,const dtrace_mops_t * mops,void * arg,dtrace_meta_provider_id_t * idp)9544 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9545     dtrace_meta_provider_id_t *idp)
9546 {
9547 	dtrace_meta_t *meta;
9548 	dtrace_helpers_t *help, *next;
9549 	uint_t i;
9550 
9551 	*idp = DTRACE_METAPROVNONE;
9552 
9553 	/*
9554 	 * We strictly don't need the name, but we hold onto it for
9555 	 * debuggability. All hail error queues!
9556 	 */
9557 	if (name == NULL) {
9558 		cmn_err(CE_WARN, "failed to register meta-provider: "
9559 		    "invalid name");
9560 		return (EINVAL);
9561 	}
9562 
9563 	if (mops == NULL ||
9564 	    mops->dtms_create_probe == NULL ||
9565 	    mops->dtms_provide_proc == NULL ||
9566 	    mops->dtms_remove_proc == NULL) {
9567 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9568 		    "invalid ops", name);
9569 		return (EINVAL);
9570 	}
9571 
9572 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9573 	meta->dtm_mops = *mops;
9574 	meta->dtm_arg = arg;
9575 
9576 	lck_mtx_lock(&dtrace_meta_lock);
9577 	lck_mtx_lock(&dtrace_lock);
9578 
9579 	if (dtrace_meta_pid != NULL) {
9580 		lck_mtx_unlock(&dtrace_lock);
9581 		lck_mtx_unlock(&dtrace_meta_lock);
9582 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9583 		    "user-land meta-provider exists", name);
9584 		kmem_free(meta, sizeof (dtrace_meta_t));
9585 		return (EINVAL);
9586 	}
9587 
9588 	meta->dtm_name = dtrace_strref(name);
9589 
9590 	dtrace_meta_pid = meta;
9591 	*idp = (dtrace_meta_provider_id_t)meta;
9592 
9593 	/*
9594 	 * If there are providers and probes ready to go, pass them
9595 	 * off to the new meta provider now.
9596 	 */
9597 
9598 	help = dtrace_deferred_pid;
9599 	dtrace_deferred_pid = NULL;
9600 
9601 	lck_mtx_unlock(&dtrace_lock);
9602 
9603 	while (help != NULL) {
9604 		for (i = 0; i < help->dthps_nprovs; i++) {
9605 			proc_t *p = proc_find(help->dthps_pid);
9606 			if (p == PROC_NULL)
9607 				continue;
9608 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9609 			    p);
9610 			proc_rele(p);
9611 		}
9612 
9613 		next = help->dthps_next;
9614 		help->dthps_next = NULL;
9615 		help->dthps_prev = NULL;
9616 		help->dthps_deferred = 0;
9617 		help = next;
9618 	}
9619 
9620 	lck_mtx_unlock(&dtrace_meta_lock);
9621 
9622 	return (0);
9623 }
9624 
9625 int
dtrace_meta_unregister(dtrace_meta_provider_id_t id)9626 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9627 {
9628 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9629 
9630 	lck_mtx_lock(&dtrace_meta_lock);
9631 	lck_mtx_lock(&dtrace_lock);
9632 
9633 	if (old == dtrace_meta_pid) {
9634 		pp = &dtrace_meta_pid;
9635 	} else {
9636 		panic("attempt to unregister non-existent "
9637 		    "dtrace meta-provider %p\n", (void *)old);
9638 	}
9639 
9640 	if (old->dtm_count != 0) {
9641 		lck_mtx_unlock(&dtrace_lock);
9642 		lck_mtx_unlock(&dtrace_meta_lock);
9643 		return (EBUSY);
9644 	}
9645 
9646 	*pp = NULL;
9647 
9648 	dtrace_strunref(old->dtm_name);
9649 
9650 	lck_mtx_unlock(&dtrace_lock);
9651 	lck_mtx_unlock(&dtrace_meta_lock);
9652 
9653 	kmem_free(old, sizeof (dtrace_meta_t));
9654 
9655 	return (0);
9656 }
9657 
9658 
9659 /*
9660  * DTrace DIF Object Functions
9661  */
9662 static int
dtrace_difo_err(uint_t pc,const char * format,...)9663 dtrace_difo_err(uint_t pc, const char *format, ...)
9664 {
9665 	if (dtrace_err_verbose) {
9666 		va_list alist;
9667 
9668 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9669 		va_start(alist, format);
9670 		(void) vuprintf(format, alist);
9671 		va_end(alist);
9672 	}
9673 
9674 #ifdef DTRACE_ERRDEBUG
9675 	dtrace_errdebug(format);
9676 #endif
9677 	return (1);
9678 }
9679 
9680 /*
9681  * Validate a DTrace DIF object by checking the IR instructions.  The following
9682  * rules are currently enforced by dtrace_difo_validate():
9683  *
9684  * 1. Each instruction must have a valid opcode
9685  * 2. Each register, string, variable, or subroutine reference must be valid
9686  * 3. No instruction can modify register %r0 (must be zero)
9687  * 4. All instruction reserved bits must be set to zero
9688  * 5. The last instruction must be a "ret" instruction
9689  * 6. All branch targets must reference a valid instruction _after_ the branch
9690  */
9691 static int
dtrace_difo_validate(dtrace_difo_t * dp,dtrace_vstate_t * vstate,uint_t nregs,cred_t * cr)9692 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9693     cred_t *cr)
9694 {
9695 	int err = 0;
9696 	uint_t i;
9697 
9698 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9699 	int kcheckload;
9700 	uint_t pc;
9701 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9702 
9703 	kcheckload = cr == NULL ||
9704 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9705 
9706 	dp->dtdo_destructive = 0;
9707 
9708 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9709 		dif_instr_t instr = dp->dtdo_buf[pc];
9710 
9711 		uint_t r1 = DIF_INSTR_R1(instr);
9712 		uint_t r2 = DIF_INSTR_R2(instr);
9713 		uint_t rd = DIF_INSTR_RD(instr);
9714 		uint_t rs = DIF_INSTR_RS(instr);
9715 		uint_t label = DIF_INSTR_LABEL(instr);
9716 		uint_t v = DIF_INSTR_VAR(instr);
9717 		uint_t subr = DIF_INSTR_SUBR(instr);
9718 		uint_t type = DIF_INSTR_TYPE(instr);
9719 		uint_t op = DIF_INSTR_OP(instr);
9720 
9721 		switch (op) {
9722 		case DIF_OP_OR:
9723 		case DIF_OP_XOR:
9724 		case DIF_OP_AND:
9725 		case DIF_OP_SLL:
9726 		case DIF_OP_SRL:
9727 		case DIF_OP_SRA:
9728 		case DIF_OP_SUB:
9729 		case DIF_OP_ADD:
9730 		case DIF_OP_MUL:
9731 		case DIF_OP_SDIV:
9732 		case DIF_OP_UDIV:
9733 		case DIF_OP_SREM:
9734 		case DIF_OP_UREM:
9735 		case DIF_OP_COPYS:
9736 			if (r1 >= nregs)
9737 				err += efunc(pc, "invalid register %u\n", r1);
9738 			if (r2 >= nregs)
9739 				err += efunc(pc, "invalid register %u\n", r2);
9740 			if (rd >= nregs)
9741 				err += efunc(pc, "invalid register %u\n", rd);
9742 			if (rd == 0)
9743 				err += efunc(pc, "cannot write to %%r0\n");
9744 			break;
9745 		case DIF_OP_NOT:
9746 		case DIF_OP_MOV:
9747 		case DIF_OP_ALLOCS:
9748 			if (r1 >= nregs)
9749 				err += efunc(pc, "invalid register %u\n", r1);
9750 			if (r2 != 0)
9751 				err += efunc(pc, "non-zero reserved bits\n");
9752 			if (rd >= nregs)
9753 				err += efunc(pc, "invalid register %u\n", rd);
9754 			if (rd == 0)
9755 				err += efunc(pc, "cannot write to %%r0\n");
9756 			break;
9757 		case DIF_OP_LDSB:
9758 		case DIF_OP_LDSH:
9759 		case DIF_OP_LDSW:
9760 		case DIF_OP_LDUB:
9761 		case DIF_OP_LDUH:
9762 		case DIF_OP_LDUW:
9763 		case DIF_OP_LDX:
9764 			if (r1 >= nregs)
9765 				err += efunc(pc, "invalid register %u\n", r1);
9766 			if (r2 != 0)
9767 				err += efunc(pc, "non-zero reserved bits\n");
9768 			if (rd >= nregs)
9769 				err += efunc(pc, "invalid register %u\n", rd);
9770 			if (rd == 0)
9771 				err += efunc(pc, "cannot write to %%r0\n");
9772 			if (kcheckload)
9773 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9774 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9775 			break;
9776 		case DIF_OP_RLDSB:
9777 		case DIF_OP_RLDSH:
9778 		case DIF_OP_RLDSW:
9779 		case DIF_OP_RLDUB:
9780 		case DIF_OP_RLDUH:
9781 		case DIF_OP_RLDUW:
9782 		case DIF_OP_RLDX:
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 %%r0\n");
9791 			break;
9792 		case DIF_OP_ULDSB:
9793 		case DIF_OP_ULDSH:
9794 		case DIF_OP_ULDSW:
9795 		case DIF_OP_ULDUB:
9796 		case DIF_OP_ULDUH:
9797 		case DIF_OP_ULDUW:
9798 		case DIF_OP_ULDX:
9799 			if (r1 >= nregs)
9800 				err += efunc(pc, "invalid register %u\n", r1);
9801 			if (r2 != 0)
9802 				err += efunc(pc, "non-zero reserved bits\n");
9803 			if (rd >= nregs)
9804 				err += efunc(pc, "invalid register %u\n", rd);
9805 			if (rd == 0)
9806 				err += efunc(pc, "cannot write to %%r0\n");
9807 			break;
9808 		case DIF_OP_STB:
9809 		case DIF_OP_STH:
9810 		case DIF_OP_STW:
9811 		case DIF_OP_STX:
9812 			if (r1 >= nregs)
9813 				err += efunc(pc, "invalid register %u\n", r1);
9814 			if (r2 != 0)
9815 				err += efunc(pc, "non-zero reserved bits\n");
9816 			if (rd >= nregs)
9817 				err += efunc(pc, "invalid register %u\n", rd);
9818 			if (rd == 0)
9819 				err += efunc(pc, "cannot write to 0 address\n");
9820 			break;
9821 		case DIF_OP_CMP:
9822 		case DIF_OP_SCMP:
9823 			if (r1 >= nregs)
9824 				err += efunc(pc, "invalid register %u\n", r1);
9825 			if (r2 >= nregs)
9826 				err += efunc(pc, "invalid register %u\n", r2);
9827 			if (rd != 0)
9828 				err += efunc(pc, "non-zero reserved bits\n");
9829 			break;
9830 		case DIF_OP_TST:
9831 			if (r1 >= nregs)
9832 				err += efunc(pc, "invalid register %u\n", r1);
9833 			if (r2 != 0 || rd != 0)
9834 				err += efunc(pc, "non-zero reserved bits\n");
9835 			break;
9836 		case DIF_OP_BA:
9837 		case DIF_OP_BE:
9838 		case DIF_OP_BNE:
9839 		case DIF_OP_BG:
9840 		case DIF_OP_BGU:
9841 		case DIF_OP_BGE:
9842 		case DIF_OP_BGEU:
9843 		case DIF_OP_BL:
9844 		case DIF_OP_BLU:
9845 		case DIF_OP_BLE:
9846 		case DIF_OP_BLEU:
9847 			if (label >= dp->dtdo_len) {
9848 				err += efunc(pc, "invalid branch target %u\n",
9849 				    label);
9850 			}
9851 			if (label <= pc) {
9852 				err += efunc(pc, "backward branch to %u\n",
9853 				    label);
9854 			}
9855 			break;
9856 		case DIF_OP_RET:
9857 			if (r1 != 0 || r2 != 0)
9858 				err += efunc(pc, "non-zero reserved bits\n");
9859 			if (rd >= nregs)
9860 				err += efunc(pc, "invalid register %u\n", rd);
9861 			break;
9862 		case DIF_OP_NOP:
9863 		case DIF_OP_POPTS:
9864 		case DIF_OP_FLUSHTS:
9865 			if (r1 != 0 || r2 != 0 || rd != 0)
9866 				err += efunc(pc, "non-zero reserved bits\n");
9867 			break;
9868 		case DIF_OP_SETX:
9869 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9870 				err += efunc(pc, "invalid integer ref %u\n",
9871 				    DIF_INSTR_INTEGER(instr));
9872 			}
9873 			if (rd >= nregs)
9874 				err += efunc(pc, "invalid register %u\n", rd);
9875 			if (rd == 0)
9876 				err += efunc(pc, "cannot write to %%r0\n");
9877 			break;
9878 		case DIF_OP_SETS:
9879 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9880 				err += efunc(pc, "invalid string ref %u\n",
9881 				    DIF_INSTR_STRING(instr));
9882 			}
9883 			if (rd >= nregs)
9884 				err += efunc(pc, "invalid register %u\n", rd);
9885 			if (rd == 0)
9886 				err += efunc(pc, "cannot write to %%r0\n");
9887 			break;
9888 		case DIF_OP_LDGA:
9889 		case DIF_OP_LDTA:
9890 			if (r1 > DIF_VAR_ARRAY_MAX)
9891 				err += efunc(pc, "invalid array %u\n", r1);
9892 			if (r2 >= nregs)
9893 				err += efunc(pc, "invalid register %u\n", r2);
9894 			if (rd >= nregs)
9895 				err += efunc(pc, "invalid register %u\n", rd);
9896 			if (rd == 0)
9897 				err += efunc(pc, "cannot write to %%r0\n");
9898 			break;
9899 		case DIF_OP_LDGS:
9900 		case DIF_OP_LDTS:
9901 		case DIF_OP_LDLS:
9902 		case DIF_OP_LDGAA:
9903 		case DIF_OP_LDTAA:
9904 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9905 				err += efunc(pc, "invalid variable %u\n", v);
9906 			if (rd >= nregs)
9907 				err += efunc(pc, "invalid register %u\n", rd);
9908 			if (rd == 0)
9909 				err += efunc(pc, "cannot write to %%r0\n");
9910 			break;
9911 		case DIF_OP_STGS:
9912 		case DIF_OP_STTS:
9913 		case DIF_OP_STLS:
9914 		case DIF_OP_STGAA:
9915 		case DIF_OP_STTAA:
9916 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9917 				err += efunc(pc, "invalid variable %u\n", v);
9918 			if (rs >= nregs)
9919 				err += efunc(pc, "invalid register %u\n", rd);
9920 			break;
9921 		case DIF_OP_CALL:
9922 			if (subr > DIF_SUBR_MAX &&
9923 			   !(subr >= DIF_SUBR_APPLE_MIN && subr <= DIF_SUBR_APPLE_MAX))
9924 				err += efunc(pc, "invalid subr %u\n", subr);
9925 			if (rd >= nregs)
9926 				err += efunc(pc, "invalid register %u\n", rd);
9927 			if (rd == 0)
9928 				err += efunc(pc, "cannot write to %%r0\n");
9929 
9930 			switch (subr) {
9931 			case DIF_SUBR_COPYOUT:
9932 			case DIF_SUBR_COPYOUTSTR:
9933 			case DIF_SUBR_KDEBUG_TRACE:
9934 			case DIF_SUBR_KDEBUG_TRACE_STRING:
9935 			case DIF_SUBR_PHYSMEM_READ:
9936 			case DIF_SUBR_PHYSMEM_WRITE:
9937 			case DIF_SUBR_LIVEDUMP:
9938 				dp->dtdo_destructive = 1;
9939 				break;
9940 			default:
9941 				break;
9942 			}
9943 			break;
9944 		case DIF_OP_PUSHTR:
9945 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9946 				err += efunc(pc, "invalid ref type %u\n", type);
9947 			if (r2 >= nregs)
9948 				err += efunc(pc, "invalid register %u\n", r2);
9949 			if (rs >= nregs)
9950 				err += efunc(pc, "invalid register %u\n", rs);
9951 			break;
9952 		case DIF_OP_PUSHTV:
9953 			if (type != DIF_TYPE_CTF)
9954 				err += efunc(pc, "invalid val type %u\n", type);
9955 			if (r2 >= nregs)
9956 				err += efunc(pc, "invalid register %u\n", r2);
9957 			if (rs >= nregs)
9958 				err += efunc(pc, "invalid register %u\n", rs);
9959 			break;
9960 		case DIF_OP_STRIP:
9961 			if (r1 >= nregs)
9962 				err += efunc(pc, "invalid register %u\n", r1);
9963 			if (!dtrace_is_valid_ptrauth_key(r2))
9964 				err += efunc(pc, "invalid key\n");
9965 			if (rd >= nregs)
9966 				err += efunc(pc, "invalid register %u\n", rd);
9967 			if (rd == 0)
9968 				err += efunc(pc, "cannot write to %%r0\n");
9969 			break;
9970 		default:
9971 			err += efunc(pc, "invalid opcode %u\n",
9972 			    DIF_INSTR_OP(instr));
9973 		}
9974 	}
9975 
9976 	if (dp->dtdo_len != 0 &&
9977 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9978 		err += efunc(dp->dtdo_len - 1,
9979 		    "expected 'ret' as last DIF instruction\n");
9980 	}
9981 
9982 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9983 		/*
9984 		 * If we're not returning by reference, the size must be either
9985 		 * 0 or the size of one of the base types.
9986 		 */
9987 		switch (dp->dtdo_rtype.dtdt_size) {
9988 		case 0:
9989 		case sizeof (uint8_t):
9990 		case sizeof (uint16_t):
9991 		case sizeof (uint32_t):
9992 		case sizeof (uint64_t):
9993 			break;
9994 
9995 		default:
9996 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9997 		}
9998 	}
9999 
10000 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10001 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10002 		dtrace_diftype_t *vt, *et;
10003 		uint_t id;
10004 		int ndx;
10005 
10006 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10007 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
10008 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10009 			err += efunc(i, "unrecognized variable scope %d\n",
10010 			    v->dtdv_scope);
10011 			break;
10012 		}
10013 
10014 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10015 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
10016 			err += efunc(i, "unrecognized variable type %d\n",
10017 			    v->dtdv_kind);
10018 			break;
10019 		}
10020 
10021 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10022 			err += efunc(i, "%d exceeds variable id limit\n", id);
10023 			break;
10024 		}
10025 
10026 		if (id < DIF_VAR_OTHER_UBASE)
10027 			continue;
10028 
10029 		/*
10030 		 * For user-defined variables, we need to check that this
10031 		 * definition is identical to any previous definition that we
10032 		 * encountered.
10033 		 */
10034 		ndx = id - DIF_VAR_OTHER_UBASE;
10035 
10036 		switch (v->dtdv_scope) {
10037 		case DIFV_SCOPE_GLOBAL:
10038 			if (maxglobal == -1 || ndx > maxglobal)
10039 				maxglobal = ndx;
10040 
10041 			if (ndx < vstate->dtvs_nglobals) {
10042 				dtrace_statvar_t *svar;
10043 
10044 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10045 					existing = &svar->dtsv_var;
10046 			}
10047 
10048 			break;
10049 
10050 		case DIFV_SCOPE_THREAD:
10051 			if (maxtlocal == -1 || ndx > maxtlocal)
10052 				maxtlocal = ndx;
10053 
10054 			if (ndx < vstate->dtvs_ntlocals)
10055 				existing = &vstate->dtvs_tlocals[ndx];
10056 			break;
10057 
10058 		case DIFV_SCOPE_LOCAL:
10059 			if (maxlocal == -1 || ndx > maxlocal)
10060 				maxlocal = ndx;
10061 			if (ndx < vstate->dtvs_nlocals) {
10062 				dtrace_statvar_t *svar;
10063 
10064 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10065 					existing = &svar->dtsv_var;
10066 			}
10067 
10068 			break;
10069 		}
10070 
10071 		vt = &v->dtdv_type;
10072 
10073 		if (vt->dtdt_flags & DIF_TF_BYREF) {
10074 			if (vt->dtdt_size == 0) {
10075 				err += efunc(i, "zero-sized variable\n");
10076 				break;
10077 			}
10078 
10079 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10080 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10081 			    vt->dtdt_size > dtrace_statvar_maxsize) {
10082 				err += efunc(i, "oversized by-ref static\n");
10083 				break;
10084 			}
10085 		}
10086 
10087 		if (existing == NULL || existing->dtdv_id == 0)
10088 			continue;
10089 
10090 		ASSERT(existing->dtdv_id == v->dtdv_id);
10091 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
10092 
10093 		if (existing->dtdv_kind != v->dtdv_kind)
10094 			err += efunc(i, "%d changed variable kind\n", id);
10095 
10096 		et = &existing->dtdv_type;
10097 
10098 		if (vt->dtdt_flags != et->dtdt_flags) {
10099 			err += efunc(i, "%d changed variable type flags\n", id);
10100 			break;
10101 		}
10102 
10103 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10104 			err += efunc(i, "%d changed variable type size\n", id);
10105 			break;
10106 		}
10107 	}
10108 
10109 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10110 		dif_instr_t instr = dp->dtdo_buf[pc];
10111 
10112 		uint_t v = DIF_INSTR_VAR(instr);
10113 		uint_t op = DIF_INSTR_OP(instr);
10114 
10115 		switch (op) {
10116 		case DIF_OP_LDGS:
10117 		case DIF_OP_LDGAA:
10118 		case DIF_OP_STGS:
10119 		case DIF_OP_STGAA:
10120 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxglobal))
10121 				err += efunc(pc, "invalid variable %u\n", v);
10122 			break;
10123 		case DIF_OP_LDTS:
10124 		case DIF_OP_LDTAA:
10125 		case DIF_OP_STTS:
10126 		case DIF_OP_STTAA:
10127 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxtlocal))
10128 				err += efunc(pc, "invalid variable %u\n", v);
10129 			break;
10130 		case DIF_OP_LDLS:
10131 		case DIF_OP_STLS:
10132 			if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxlocal))
10133 				err += efunc(pc, "invalid variable %u\n", v);
10134 			break;
10135 		default:
10136 			break;
10137 		}
10138 	}
10139 
10140 	return (err);
10141 }
10142 
10143 /*
10144  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
10145  * are much more constrained than normal DIFOs.  Specifically, they may
10146  * not:
10147  *
10148  * 1. Make calls to subroutines other than copyin(), copyinstr() or
10149  *    miscellaneous string routines
10150  * 2. Access DTrace variables other than the args[] array, and the
10151  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10152  * 3. Have thread-local variables.
10153  * 4. Have dynamic variables.
10154  */
10155 static int
dtrace_difo_validate_helper(dtrace_difo_t * dp)10156 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10157 {
10158 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10159 	int err = 0;
10160 	uint_t pc;
10161 
10162 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10163 		dif_instr_t instr = dp->dtdo_buf[pc];
10164 
10165 		uint_t v = DIF_INSTR_VAR(instr);
10166 		uint_t subr = DIF_INSTR_SUBR(instr);
10167 		uint_t op = DIF_INSTR_OP(instr);
10168 
10169 		switch (op) {
10170 		case DIF_OP_OR:
10171 		case DIF_OP_XOR:
10172 		case DIF_OP_AND:
10173 		case DIF_OP_SLL:
10174 		case DIF_OP_SRL:
10175 		case DIF_OP_SRA:
10176 		case DIF_OP_SUB:
10177 		case DIF_OP_ADD:
10178 		case DIF_OP_MUL:
10179 		case DIF_OP_SDIV:
10180 		case DIF_OP_UDIV:
10181 		case DIF_OP_SREM:
10182 		case DIF_OP_UREM:
10183 		case DIF_OP_COPYS:
10184 		case DIF_OP_NOT:
10185 		case DIF_OP_MOV:
10186 		case DIF_OP_RLDSB:
10187 		case DIF_OP_RLDSH:
10188 		case DIF_OP_RLDSW:
10189 		case DIF_OP_RLDUB:
10190 		case DIF_OP_RLDUH:
10191 		case DIF_OP_RLDUW:
10192 		case DIF_OP_RLDX:
10193 		case DIF_OP_ULDSB:
10194 		case DIF_OP_ULDSH:
10195 		case DIF_OP_ULDSW:
10196 		case DIF_OP_ULDUB:
10197 		case DIF_OP_ULDUH:
10198 		case DIF_OP_ULDUW:
10199 		case DIF_OP_ULDX:
10200 		case DIF_OP_STB:
10201 		case DIF_OP_STH:
10202 		case DIF_OP_STW:
10203 		case DIF_OP_STX:
10204 		case DIF_OP_ALLOCS:
10205 		case DIF_OP_CMP:
10206 		case DIF_OP_SCMP:
10207 		case DIF_OP_TST:
10208 		case DIF_OP_BA:
10209 		case DIF_OP_BE:
10210 		case DIF_OP_BNE:
10211 		case DIF_OP_BG:
10212 		case DIF_OP_BGU:
10213 		case DIF_OP_BGE:
10214 		case DIF_OP_BGEU:
10215 		case DIF_OP_BL:
10216 		case DIF_OP_BLU:
10217 		case DIF_OP_BLE:
10218 		case DIF_OP_BLEU:
10219 		case DIF_OP_RET:
10220 		case DIF_OP_NOP:
10221 		case DIF_OP_POPTS:
10222 		case DIF_OP_FLUSHTS:
10223 		case DIF_OP_SETX:
10224 		case DIF_OP_SETS:
10225 		case DIF_OP_LDGA:
10226 		case DIF_OP_LDLS:
10227 		case DIF_OP_STGS:
10228 		case DIF_OP_STLS:
10229 		case DIF_OP_PUSHTR:
10230 		case DIF_OP_PUSHTV:
10231 			break;
10232 
10233 		case DIF_OP_LDGS:
10234 			if (v >= DIF_VAR_OTHER_UBASE)
10235 				break;
10236 
10237 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10238 				break;
10239 
10240 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10241 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10242 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10243 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
10244 				break;
10245 
10246 			err += efunc(pc, "illegal variable %u\n", v);
10247 			break;
10248 
10249 		case DIF_OP_LDTA:
10250 		case DIF_OP_LDTS:
10251 		case DIF_OP_LDGAA:
10252 		case DIF_OP_LDTAA:
10253 			err += efunc(pc, "illegal dynamic variable load\n");
10254 			break;
10255 
10256 		case DIF_OP_STTS:
10257 		case DIF_OP_STGAA:
10258 		case DIF_OP_STTAA:
10259 			err += efunc(pc, "illegal dynamic variable store\n");
10260 			break;
10261 
10262 		case DIF_OP_CALL:
10263 			switch (subr) {
10264 			case DIF_SUBR_ALLOCA:
10265 			case DIF_SUBR_BCOPY:
10266 			case DIF_SUBR_COPYIN:
10267 			case DIF_SUBR_COPYINTO:
10268 			case DIF_SUBR_COPYINSTR:
10269 			case DIF_SUBR_HTONS:
10270 			case DIF_SUBR_HTONL:
10271 			case DIF_SUBR_HTONLL:
10272 			case DIF_SUBR_INDEX:
10273 			case DIF_SUBR_INET_NTOA:
10274 			case DIF_SUBR_INET_NTOA6:
10275 			case DIF_SUBR_INET_NTOP:
10276 			case DIF_SUBR_JSON:
10277 			case DIF_SUBR_LLTOSTR:
10278 			case DIF_SUBR_NTOHS:
10279 			case DIF_SUBR_NTOHL:
10280 			case DIF_SUBR_NTOHLL:
10281 			case DIF_SUBR_RINDEX:
10282 			case DIF_SUBR_STRCHR:
10283 			case DIF_SUBR_STRTOLL:
10284 			case DIF_SUBR_STRJOIN:
10285 			case DIF_SUBR_STRRCHR:
10286 			case DIF_SUBR_STRSTR:
10287 				break;
10288 			default:
10289 				err += efunc(pc, "invalid subr %u\n", subr);
10290 			}
10291 			break;
10292 
10293 		default:
10294 			err += efunc(pc, "invalid opcode %u\n",
10295 			    DIF_INSTR_OP(instr));
10296 		}
10297 	}
10298 
10299 	return (err);
10300 }
10301 
10302 /*
10303  * Returns 1 if the expression in the DIF object can be cached on a per-thread
10304  * basis; 0 if not.
10305  */
10306 static int
dtrace_difo_cacheable(dtrace_difo_t * dp)10307 dtrace_difo_cacheable(dtrace_difo_t *dp)
10308 {
10309 	uint_t i;
10310 
10311 	if (dp == NULL)
10312 		return (0);
10313 
10314 	for (i = 0; i < dp->dtdo_varlen; i++) {
10315 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10316 
10317 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10318 			continue;
10319 
10320 		switch (v->dtdv_id) {
10321 		case DIF_VAR_CURTHREAD:
10322 		case DIF_VAR_PID:
10323 		case DIF_VAR_TID:
10324 		case DIF_VAR_EXECNAME:
10325 		case DIF_VAR_ZONENAME:
10326 			break;
10327 
10328 		default:
10329 			return (0);
10330 		}
10331 	}
10332 
10333 	/*
10334 	 * This DIF object may be cacheable.  Now we need to look for any
10335 	 * array loading instructions, any memory loading instructions, or
10336 	 * any stores to thread-local variables.
10337 	 */
10338 	for (i = 0; i < dp->dtdo_len; i++) {
10339 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10340 
10341 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10342 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10343 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10344 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
10345 			return (0);
10346 	}
10347 
10348 	return (1);
10349 }
10350 
10351 static void
dtrace_difo_hold(dtrace_difo_t * dp)10352 dtrace_difo_hold(dtrace_difo_t *dp)
10353 {
10354 	uint_t i;
10355 
10356 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10357 
10358 	dp->dtdo_refcnt++;
10359 	ASSERT(dp->dtdo_refcnt != 0);
10360 
10361 	/*
10362 	 * We need to check this DIF object for references to the variable
10363 	 * DIF_VAR_VTIMESTAMP.
10364 	 */
10365 	for (i = 0; i < dp->dtdo_varlen; i++) {
10366 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10367 
10368 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10369 			continue;
10370 
10371 		if (dtrace_vtime_references++ == 0)
10372 			dtrace_vtime_enable();
10373 	}
10374 }
10375 
10376 /*
10377  * This routine calculates the dynamic variable chunksize for a given DIF
10378  * object.  The calculation is not fool-proof, and can probably be tricked by
10379  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
10380  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10381  * if a dynamic variable size exceeds the chunksize.
10382  */
10383 static void
dtrace_difo_chunksize(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10384 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10385 {
10386 	uint64_t sval = 0;
10387 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10388 	const dif_instr_t *text = dp->dtdo_buf;
10389 	uint_t pc, srd = 0;
10390 	uint_t ttop = 0;
10391 	size_t size, ksize;
10392 	uint_t id, i;
10393 
10394 	for (pc = 0; pc < dp->dtdo_len; pc++) {
10395 		dif_instr_t instr = text[pc];
10396 		uint_t op = DIF_INSTR_OP(instr);
10397 		uint_t rd = DIF_INSTR_RD(instr);
10398 		uint_t r1 = DIF_INSTR_R1(instr);
10399 		uint_t nkeys = 0;
10400 		uchar_t scope;
10401 
10402 		dtrace_key_t *key = tupregs;
10403 
10404 		switch (op) {
10405 		case DIF_OP_SETX:
10406 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10407 			srd = rd;
10408 			continue;
10409 
10410 		case DIF_OP_STTS:
10411 			key = &tupregs[DIF_DTR_NREGS];
10412 			key[0].dttk_size = 0;
10413 			key[1].dttk_size = 0;
10414 			nkeys = 2;
10415 			scope = DIFV_SCOPE_THREAD;
10416 			break;
10417 
10418 		case DIF_OP_STGAA:
10419 		case DIF_OP_STTAA:
10420 			nkeys = ttop;
10421 
10422 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10423 				key[nkeys++].dttk_size = 0;
10424 
10425 			key[nkeys++].dttk_size = 0;
10426 
10427 			if (op == DIF_OP_STTAA) {
10428 				scope = DIFV_SCOPE_THREAD;
10429 			} else {
10430 				scope = DIFV_SCOPE_GLOBAL;
10431 			}
10432 
10433 			break;
10434 
10435 		case DIF_OP_PUSHTR:
10436 			if (ttop == DIF_DTR_NREGS)
10437 				return;
10438 
10439 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10440 				/*
10441 				 * If the register for the size of the "pushtr"
10442 				 * is %r0 (or the value is 0) and the type is
10443 				 * a string, we'll use the system-wide default
10444 				 * string size.
10445 				 */
10446 				tupregs[ttop++].dttk_size =
10447 				    dtrace_strsize_default;
10448 			} else {
10449 				if (srd == 0)
10450 					return;
10451 
10452 				if (sval > LONG_MAX)
10453 					return;
10454 
10455 				tupregs[ttop++].dttk_size = sval;
10456 			}
10457 
10458 			break;
10459 
10460 		case DIF_OP_PUSHTV:
10461 			if (ttop == DIF_DTR_NREGS)
10462 				return;
10463 
10464 			tupregs[ttop++].dttk_size = 0;
10465 			break;
10466 
10467 		case DIF_OP_FLUSHTS:
10468 			ttop = 0;
10469 			break;
10470 
10471 		case DIF_OP_POPTS:
10472 			if (ttop != 0)
10473 				ttop--;
10474 			break;
10475 		}
10476 
10477 		sval = 0;
10478 		srd = 0;
10479 
10480 		if (nkeys == 0)
10481 			continue;
10482 
10483 		/*
10484 		 * We have a dynamic variable allocation; calculate its size.
10485 		 */
10486 		for (ksize = 0, i = 0; i < nkeys; i++)
10487 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10488 
10489 		size = sizeof (dtrace_dynvar_t);
10490 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10491 		size += ksize;
10492 
10493 		/*
10494 		 * Now we need to determine the size of the stored data.
10495 		 */
10496 		id = DIF_INSTR_VAR(instr);
10497 
10498 		for (i = 0; i < dp->dtdo_varlen; i++) {
10499 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10500 
10501 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10502 				size += v->dtdv_type.dtdt_size;
10503 				break;
10504 			}
10505 		}
10506 
10507 		if (i == dp->dtdo_varlen)
10508 			return;
10509 
10510 		/*
10511 		 * We have the size.  If this is larger than the chunk size
10512 		 * for our dynamic variable state, reset the chunk size.
10513 		 */
10514 		size = P2ROUNDUP(size, sizeof (uint64_t));
10515 
10516 		/*
10517 		 * Before setting the chunk size, check that we're not going
10518 		 * to set it to a negative value...
10519 		 */
10520 		if (size > LONG_MAX)
10521 			return;
10522 
10523 		/*
10524 		 * ...and make certain that we didn't badly overflow.
10525 		 */
10526 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10527 			return;
10528 
10529 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10530 			vstate->dtvs_dynvars.dtds_chunksize = size;
10531 	}
10532 }
10533 
10534 static void
dtrace_difo_init(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10535 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10536 {
10537 	int oldsvars, osz, nsz, otlocals, ntlocals;
10538 	uint_t i, id;
10539 
10540 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10541 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10542 
10543 	for (i = 0; i < dp->dtdo_varlen; i++) {
10544 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10545 		dtrace_statvar_t *svar;
10546 		dtrace_statvar_t ***svarp = NULL;
10547 		size_t dsize = 0;
10548 		uint8_t scope = v->dtdv_scope;
10549 		int *np = (int *)NULL;
10550 
10551 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10552 			continue;
10553 
10554 		id -= DIF_VAR_OTHER_UBASE;
10555 
10556 		switch (scope) {
10557 		case DIFV_SCOPE_THREAD:
10558 			while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
10559 				dtrace_difv_t *tlocals;
10560 
10561 				if ((ntlocals = (otlocals << 1)) == 0)
10562 					ntlocals = 1;
10563 
10564 				osz = otlocals * sizeof (dtrace_difv_t);
10565 				nsz = ntlocals * sizeof (dtrace_difv_t);
10566 
10567 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10568 
10569 				if (osz != 0) {
10570 					bcopy(vstate->dtvs_tlocals,
10571 					    tlocals, osz);
10572 					kmem_free(vstate->dtvs_tlocals, osz);
10573 				}
10574 
10575 				vstate->dtvs_tlocals = tlocals;
10576 				vstate->dtvs_ntlocals = ntlocals;
10577 			}
10578 
10579 			vstate->dtvs_tlocals[id] = *v;
10580 			continue;
10581 
10582 		case DIFV_SCOPE_LOCAL:
10583 			np = &vstate->dtvs_nlocals;
10584 			svarp = &vstate->dtvs_locals;
10585 
10586 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10587 				dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
10588 				    sizeof (uint64_t));
10589 			else
10590 				dsize = (int)NCPU * sizeof (uint64_t);
10591 
10592 			break;
10593 
10594 		case DIFV_SCOPE_GLOBAL:
10595 			np = &vstate->dtvs_nglobals;
10596 			svarp = &vstate->dtvs_globals;
10597 
10598 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10599 				dsize = v->dtdv_type.dtdt_size +
10600 				    sizeof (uint64_t);
10601 
10602 			break;
10603 
10604 		default:
10605 			ASSERT(0);
10606 		}
10607 
10608 		while (id >= (uint_t)(oldsvars = *np)) {
10609 			dtrace_statvar_t **statics;
10610 			int newsvars, oldsize, newsize;
10611 
10612 			if ((newsvars = (oldsvars << 1)) == 0)
10613 				newsvars = 1;
10614 
10615 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10616 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10617 
10618 			statics = kmem_zalloc(newsize, KM_SLEEP);
10619 
10620 			if (oldsize != 0) {
10621 				bcopy(*svarp, statics, oldsize);
10622 				kmem_free(*svarp, oldsize);
10623 			}
10624 
10625 			*svarp = statics;
10626 			*np = newsvars;
10627 		}
10628 
10629 		if ((svar = (*svarp)[id]) == NULL) {
10630 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10631 			svar->dtsv_var = *v;
10632 
10633 			if ((svar->dtsv_size = dsize) != 0) {
10634 				svar->dtsv_data = (uint64_t)(uintptr_t)
10635 				    kmem_zalloc(dsize, KM_SLEEP);
10636 			}
10637 
10638 			(*svarp)[id] = svar;
10639 		}
10640 
10641 		svar->dtsv_refcnt++;
10642 	}
10643 
10644 	dtrace_difo_chunksize(dp, vstate);
10645 	dtrace_difo_hold(dp);
10646 }
10647 
10648 static dtrace_difo_t *
dtrace_difo_duplicate(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10649 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10650 {
10651 	dtrace_difo_t *new;
10652 	size_t sz;
10653 
10654 	ASSERT(dp->dtdo_buf != NULL);
10655 	ASSERT(dp->dtdo_refcnt != 0);
10656 
10657 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10658 
10659 	ASSERT(dp->dtdo_buf != NULL);
10660 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10661 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10662 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10663 	new->dtdo_len = dp->dtdo_len;
10664 
10665 	if (dp->dtdo_strtab != NULL) {
10666 		ASSERT(dp->dtdo_strlen != 0);
10667 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10668 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10669 		new->dtdo_strlen = dp->dtdo_strlen;
10670 	}
10671 
10672 	if (dp->dtdo_inttab != NULL) {
10673 		ASSERT(dp->dtdo_intlen != 0);
10674 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10675 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10676 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10677 		new->dtdo_intlen = dp->dtdo_intlen;
10678 	}
10679 
10680 	if (dp->dtdo_vartab != NULL) {
10681 		ASSERT(dp->dtdo_varlen != 0);
10682 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10683 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10684 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10685 		new->dtdo_varlen = dp->dtdo_varlen;
10686 	}
10687 
10688 	dtrace_difo_init(new, vstate);
10689 	return (new);
10690 }
10691 
10692 static void
dtrace_difo_destroy(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10693 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10694 {
10695 	uint_t i;
10696 
10697 	ASSERT(dp->dtdo_refcnt == 0);
10698 
10699 	for (i = 0; i < dp->dtdo_varlen; i++) {
10700 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10701 		dtrace_statvar_t *svar;
10702 		dtrace_statvar_t **svarp = NULL;
10703 		uint_t id;
10704 		uint8_t scope = v->dtdv_scope;
10705 		int *np = NULL;
10706 
10707 		switch (scope) {
10708 		case DIFV_SCOPE_THREAD:
10709 			continue;
10710 
10711 		case DIFV_SCOPE_LOCAL:
10712 			np = &vstate->dtvs_nlocals;
10713 			svarp = vstate->dtvs_locals;
10714 			break;
10715 
10716 		case DIFV_SCOPE_GLOBAL:
10717 			np = &vstate->dtvs_nglobals;
10718 			svarp = vstate->dtvs_globals;
10719 			break;
10720 
10721 		default:
10722 			ASSERT(0);
10723 		}
10724 
10725 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10726 			continue;
10727 
10728 		id -= DIF_VAR_OTHER_UBASE;
10729 
10730 		ASSERT(id < (uint_t)*np);
10731 
10732 		svar = svarp[id];
10733 		ASSERT(svar != NULL);
10734 		ASSERT(svar->dtsv_refcnt > 0);
10735 
10736 		if (--svar->dtsv_refcnt > 0)
10737 			continue;
10738 
10739 		if (svar->dtsv_size != 0) {
10740 			ASSERT(svar->dtsv_data != 0);
10741 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10742 			    svar->dtsv_size);
10743 		}
10744 
10745 		kmem_free(svar, sizeof (dtrace_statvar_t));
10746 		svarp[id] = NULL;
10747 	}
10748 
10749 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10750 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10751 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10752 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10753 
10754 	kmem_free(dp, sizeof (dtrace_difo_t));
10755 }
10756 
10757 static void
dtrace_difo_release(dtrace_difo_t * dp,dtrace_vstate_t * vstate)10758 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10759 {
10760 	uint_t i;
10761 
10762 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10763 	ASSERT(dp->dtdo_refcnt != 0);
10764 
10765 	for (i = 0; i < dp->dtdo_varlen; i++) {
10766 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10767 
10768 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10769 			continue;
10770 
10771 		ASSERT(dtrace_vtime_references > 0);
10772 		if (--dtrace_vtime_references == 0)
10773 			dtrace_vtime_disable();
10774 	}
10775 
10776 	if (--dp->dtdo_refcnt == 0)
10777 		dtrace_difo_destroy(dp, vstate);
10778 }
10779 
10780 /*
10781  * DTrace Format Functions
10782  */
10783 
10784 static dtrace_format_t*
dtrace_format_new(char * str)10785 dtrace_format_new(char *str)
10786 {
10787 	dtrace_format_t *fmt = NULL;
10788 	size_t bufsize = strlen(str) + 1;
10789 
10790 	fmt = kmem_zalloc(sizeof(*fmt) + bufsize, KM_SLEEP);
10791 
10792 	fmt->dtf_refcount = 1;
10793 	(void) strlcpy(fmt->dtf_str, str, bufsize);
10794 
10795 	return fmt;
10796 }
10797 
10798 static uint16_t
dtrace_format_add(dtrace_state_t * state,char * str)10799 dtrace_format_add(dtrace_state_t *state, char *str)
10800 {
10801 	dtrace_format_t **new;
10802 	uint16_t ndx;
10803 
10804 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10805 		if (state->dts_formats[ndx] == NULL) {
10806 			state->dts_formats[ndx] = dtrace_format_new(str);
10807 			return (ndx + 1);
10808 		}
10809 		else if (strcmp(state->dts_formats[ndx]->dtf_str, str) == 0) {
10810 			VERIFY(state->dts_formats[ndx]->dtf_refcount < UINT64_MAX);
10811 			state->dts_formats[ndx]->dtf_refcount++;
10812 			return (ndx + 1);
10813 		}
10814 	}
10815 
10816 	if (state->dts_nformats == USHRT_MAX) {
10817 		/*
10818 		 * This is only likely if a denial-of-service attack is being
10819 		 * attempted.  As such, it's okay to fail silently here.
10820 		 */
10821 		return (0);
10822 	}
10823 
10824 	/*
10825 	 * For simplicity, we always resize the formats array to be exactly the
10826 	 * number of formats.
10827 	 */
10828 	ndx = state->dts_nformats++;
10829 	new = kmem_alloc((ndx + 1) * sizeof (*state->dts_formats), KM_SLEEP);
10830 
10831 	if (state->dts_formats != NULL) {
10832 		ASSERT(ndx != 0);
10833 		bcopy(state->dts_formats, new, ndx * sizeof (*state->dts_formats));
10834 		kmem_free(state->dts_formats, ndx * sizeof (*state->dts_formats));
10835 	}
10836 
10837 	state->dts_formats = new;
10838 	state->dts_formats[ndx] = dtrace_format_new(str);
10839 
10840 	return (ndx + 1);
10841 }
10842 
10843 static void
dtrace_format_remove(dtrace_state_t * state,uint16_t format)10844 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10845 {
10846 	dtrace_format_t *fmt;
10847 
10848 	ASSERT(state->dts_formats != NULL);
10849 	ASSERT(format <= state->dts_nformats);
10850 
10851 	fmt = state->dts_formats[format - 1];
10852 
10853 	ASSERT(fmt != NULL);
10854 	VERIFY(fmt->dtf_refcount > 0);
10855 
10856 	fmt->dtf_refcount--;
10857 
10858 	if (fmt->dtf_refcount == 0) {
10859 		kmem_free(fmt, DTRACE_FORMAT_SIZE(fmt));
10860 		state->dts_formats[format - 1] = NULL;
10861 	}
10862 }
10863 
10864 static void
dtrace_format_destroy(dtrace_state_t * state)10865 dtrace_format_destroy(dtrace_state_t *state)
10866 {
10867 	int i;
10868 
10869 	if (state->dts_nformats == 0) {
10870 		ASSERT(state->dts_formats == NULL);
10871 		return;
10872 	}
10873 
10874 	ASSERT(state->dts_formats != NULL);
10875 
10876 	for (i = 0; i < state->dts_nformats; i++) {
10877 		dtrace_format_t *fmt = state->dts_formats[i];
10878 
10879 		if (fmt == NULL)
10880 			continue;
10881 
10882 		kmem_free(fmt, DTRACE_FORMAT_SIZE(fmt));
10883 	}
10884 
10885 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (*state->dts_formats));
10886 	state->dts_nformats = 0;
10887 	state->dts_formats = NULL;
10888 }
10889 
10890 /*
10891  * DTrace Predicate Functions
10892  */
10893 static dtrace_predicate_t *
dtrace_predicate_create(dtrace_difo_t * dp)10894 dtrace_predicate_create(dtrace_difo_t *dp)
10895 {
10896 	dtrace_predicate_t *pred;
10897 
10898 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10899 	ASSERT(dp->dtdo_refcnt != 0);
10900 
10901 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10902 	pred->dtp_difo = dp;
10903 	pred->dtp_refcnt = 1;
10904 
10905 	if (!dtrace_difo_cacheable(dp))
10906 		return (pred);
10907 
10908 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10909 		/*
10910 		 * This is only theoretically possible -- we have had 2^32
10911 		 * cacheable predicates on this machine.  We cannot allow any
10912 		 * more predicates to become cacheable:  as unlikely as it is,
10913 		 * there may be a thread caching a (now stale) predicate cache
10914 		 * ID. (N.B.: the temptation is being successfully resisted to
10915 		 * have this cmn_err() "Holy shit -- we executed this code!")
10916 		 */
10917 		return (pred);
10918 	}
10919 
10920 	pred->dtp_cacheid = dtrace_predcache_id++;
10921 
10922 	return (pred);
10923 }
10924 
10925 static void
dtrace_predicate_hold(dtrace_predicate_t * pred)10926 dtrace_predicate_hold(dtrace_predicate_t *pred)
10927 {
10928 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10929 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10930 	ASSERT(pred->dtp_refcnt > 0);
10931 
10932 	pred->dtp_refcnt++;
10933 }
10934 
10935 static void
dtrace_predicate_release(dtrace_predicate_t * pred,dtrace_vstate_t * vstate)10936 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10937 {
10938 	dtrace_difo_t *dp = pred->dtp_difo;
10939 #pragma unused(dp) /* __APPLE__ */
10940 
10941 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10942 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10943 	ASSERT(pred->dtp_refcnt > 0);
10944 
10945 	if (--pred->dtp_refcnt == 0) {
10946 		dtrace_difo_release(pred->dtp_difo, vstate);
10947 		kmem_free(pred, sizeof (dtrace_predicate_t));
10948 	}
10949 }
10950 
10951 /*
10952  * DTrace Action Description Functions
10953  */
10954 static dtrace_actdesc_t *
dtrace_actdesc_create(dtrace_actkind_t kind,uint32_t ntuple,uint64_t uarg,uint64_t arg)10955 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10956     uint64_t uarg, uint64_t arg)
10957 {
10958 	dtrace_actdesc_t *act;
10959 
10960 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
10961 	    arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
10962 
10963 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10964 	act->dtad_kind = kind;
10965 	act->dtad_ntuple = ntuple;
10966 	act->dtad_uarg = uarg;
10967 	act->dtad_arg = arg;
10968 	act->dtad_refcnt = 1;
10969 
10970 	return (act);
10971 }
10972 
10973 static void
dtrace_actdesc_hold(dtrace_actdesc_t * act)10974 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10975 {
10976 	ASSERT(act->dtad_refcnt >= 1);
10977 	act->dtad_refcnt++;
10978 }
10979 
10980 static void
dtrace_actdesc_release(dtrace_actdesc_t * act,dtrace_vstate_t * vstate)10981 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10982 {
10983 	dtrace_actkind_t kind = act->dtad_kind;
10984 	dtrace_difo_t *dp;
10985 
10986 	ASSERT(act->dtad_refcnt >= 1);
10987 
10988 	if (--act->dtad_refcnt != 0)
10989 		return;
10990 
10991 	if ((dp = act->dtad_difo) != NULL)
10992 		dtrace_difo_release(dp, vstate);
10993 
10994 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10995 		char *str = (char *)(uintptr_t)act->dtad_arg;
10996 
10997 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10998 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10999 
11000 		if (str != NULL)
11001 			kmem_free(str, strlen(str) + 1);
11002 	}
11003 
11004 	kmem_free(act, sizeof (dtrace_actdesc_t));
11005 }
11006 
11007 /*
11008  * DTrace ECB Functions
11009  */
11010 static dtrace_ecb_t *
dtrace_ecb_add(dtrace_state_t * state,dtrace_probe_t * probe)11011 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11012 {
11013 	dtrace_ecb_t *ecb;
11014 	dtrace_epid_t epid;
11015 
11016 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11017 
11018 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11019 	ecb->dte_predicate = NULL;
11020 	ecb->dte_probe = probe;
11021 
11022 	/*
11023 	 * The default size is the size of the default action: recording
11024 	 * the header.
11025 	 */
11026 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11027 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11028 
11029 	epid = state->dts_epid++;
11030 
11031 	if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
11032 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11033 		int necbs = state->dts_necbs << 1;
11034 
11035 		ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
11036 
11037 		if (necbs == 0) {
11038 			ASSERT(oecbs == NULL);
11039 			necbs = 1;
11040 		}
11041 
11042 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11043 
11044 		if (oecbs != NULL)
11045 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11046 
11047 		dtrace_membar_producer();
11048 		state->dts_ecbs = ecbs;
11049 
11050 		if (oecbs != NULL) {
11051 			/*
11052 			 * If this state is active, we must dtrace_sync()
11053 			 * before we can free the old dts_ecbs array:  we're
11054 			 * coming in hot, and there may be active ring
11055 			 * buffer processing (which indexes into the dts_ecbs
11056 			 * array) on another CPU.
11057 			 */
11058 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11059 				dtrace_sync();
11060 
11061 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11062 		}
11063 
11064 		dtrace_membar_producer();
11065 		state->dts_necbs = necbs;
11066 	}
11067 
11068 	ecb->dte_state = state;
11069 
11070 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
11071 	dtrace_membar_producer();
11072 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11073 
11074 	return (ecb);
11075 }
11076 
11077 static int
dtrace_ecb_enable(dtrace_ecb_t * ecb)11078 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11079 {
11080 	dtrace_probe_t *probe = ecb->dte_probe;
11081 
11082 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11083 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11084 	ASSERT(ecb->dte_next == NULL);
11085 
11086 	if (probe == NULL) {
11087 		/*
11088 		 * This is the NULL probe -- there's nothing to do.
11089 		 */
11090 	    return(0);
11091 	}
11092 
11093 	probe->dtpr_provider->dtpv_ecb_count++;
11094 	if (probe->dtpr_ecb == NULL) {
11095 		dtrace_provider_t *prov = probe->dtpr_provider;
11096 
11097 		/*
11098 		 * We're the first ECB on this probe.
11099 		 */
11100 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11101 
11102 		if (ecb->dte_predicate != NULL)
11103 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11104 
11105 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11106                     probe->dtpr_id, probe->dtpr_arg));
11107 	} else {
11108 		/*
11109 		 * This probe is already active.  Swing the last pointer to
11110 		 * point to the new ECB, and issue a dtrace_sync() to assure
11111 		 * that all CPUs have seen the change.
11112 		 */
11113 		ASSERT(probe->dtpr_ecb_last != NULL);
11114 		probe->dtpr_ecb_last->dte_next = ecb;
11115 		probe->dtpr_ecb_last = ecb;
11116 		probe->dtpr_predcache = 0;
11117 
11118 		dtrace_sync();
11119 		return(0);
11120 	}
11121 }
11122 
11123 static int
dtrace_ecb_resize(dtrace_ecb_t * ecb)11124 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11125 {
11126 	dtrace_action_t *act;
11127 	uint32_t curneeded = UINT32_MAX;
11128 	uint32_t aggbase = UINT32_MAX;
11129 
11130 	/*
11131 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
11132 	 * we always record it first.)
11133 	 */
11134 	ecb->dte_size = sizeof (dtrace_rechdr_t);
11135 	ecb->dte_alignment = sizeof (dtrace_epid_t);
11136 
11137 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11138 		dtrace_recdesc_t *rec = &act->dta_rec;
11139 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11140 
11141 		ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
11142 
11143 		if (DTRACEACT_ISAGG(act->dta_kind)) {
11144 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11145 
11146 			ASSERT(rec->dtrd_size != 0);
11147 			ASSERT(agg->dtag_first != NULL);
11148 			ASSERT(act->dta_prev->dta_intuple);
11149 			ASSERT(aggbase != UINT32_MAX);
11150 			ASSERT(curneeded != UINT32_MAX);
11151 
11152 			agg->dtag_base = aggbase;
11153 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11154 			rec->dtrd_offset = curneeded;
11155 			if (curneeded + rec->dtrd_size < curneeded)
11156 				return (EINVAL);
11157 			curneeded += rec->dtrd_size;
11158 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11159 
11160 			aggbase = UINT32_MAX;
11161 			curneeded = UINT32_MAX;
11162 		} else if (act->dta_intuple) {
11163 			if (curneeded == UINT32_MAX) {
11164 				/*
11165 				 * This is the first record in a tuple.  Align
11166 				 * curneeded to be at offset 4 in an 8-byte
11167 				 * aligned block.
11168 				 */
11169 				ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
11170 				ASSERT(aggbase == UINT32_MAX);
11171 
11172 				curneeded = P2PHASEUP(ecb->dte_size,
11173 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
11174 
11175 				aggbase = curneeded - sizeof (dtrace_aggid_t);
11176 				ASSERT(IS_P2ALIGNED(aggbase,
11177 				    sizeof (uint64_t)));
11178 			}
11179 
11180 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11181 			rec->dtrd_offset = curneeded;
11182 			curneeded += rec->dtrd_size;
11183 			if (curneeded + rec->dtrd_size < curneeded)
11184 				return (EINVAL);
11185 		} else {
11186 			/* tuples must be followed by an aggregation */
11187 			ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
11188 			ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
11189 			rec->dtrd_offset = ecb->dte_size;
11190 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11191 				return (EINVAL);
11192 			ecb->dte_size += rec->dtrd_size;
11193 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11194 		}
11195 	}
11196 
11197 	if ((act = ecb->dte_action) != NULL &&
11198 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11199 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11200 		/*
11201 		 * If the size is still sizeof (dtrace_rechdr_t), then all
11202 		 * actions store no data; set the size to 0.
11203 		 */
11204 		ecb->dte_size = 0;
11205 	}
11206 
11207 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11208 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11209 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
11210 	return (0);
11211 }
11212 
11213 static dtrace_action_t *
dtrace_ecb_aggregation_create(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)11214 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11215 {
11216 	dtrace_aggregation_t *agg;
11217 	size_t size = sizeof (uint64_t);
11218 	int ntuple = desc->dtad_ntuple;
11219 	dtrace_action_t *act;
11220 	dtrace_recdesc_t *frec;
11221 	dtrace_aggid_t aggid;
11222 	dtrace_state_t *state = ecb->dte_state;
11223 
11224 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11225 	agg->dtag_ecb = ecb;
11226 
11227 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11228 
11229 	switch (desc->dtad_kind) {
11230 	case DTRACEAGG_MIN:
11231 		agg->dtag_initial = INT64_MAX;
11232 		agg->dtag_aggregate = dtrace_aggregate_min;
11233 		break;
11234 
11235 	case DTRACEAGG_MAX:
11236 		agg->dtag_initial = INT64_MIN;
11237 		agg->dtag_aggregate = dtrace_aggregate_max;
11238 		break;
11239 
11240 	case DTRACEAGG_COUNT:
11241 		agg->dtag_aggregate = dtrace_aggregate_count;
11242 		break;
11243 
11244 	case DTRACEAGG_QUANTIZE:
11245 		agg->dtag_aggregate = dtrace_aggregate_quantize;
11246 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11247 		    sizeof (uint64_t);
11248 		break;
11249 
11250 	case DTRACEAGG_LQUANTIZE: {
11251 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11252 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11253 
11254 		agg->dtag_initial = desc->dtad_arg;
11255 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
11256 
11257 		if (step == 0 || levels == 0)
11258 			goto err;
11259 
11260 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11261 		break;
11262 	}
11263 
11264 	case DTRACEAGG_LLQUANTIZE: {
11265 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11266 		uint16_t low    = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11267 		uint16_t high   = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11268 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11269 		int64_t v;
11270 
11271 		agg->dtag_initial = desc->dtad_arg;
11272 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
11273 
11274 		if (factor < 2 || low >= high || nsteps < factor)
11275 			goto err;
11276 
11277 		/*
11278 		 * Now check that the number of steps evenly divides a power
11279 		 * of the factor.  (This assures both integer bucket size and
11280 		 * linearity within each magnitude.)
11281 		 */
11282 		for (v = factor; v < nsteps; v *= factor)
11283 			continue;
11284 
11285 		if ((v % nsteps) || (nsteps % factor))
11286 			goto err;
11287 
11288  		size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11289 		break;
11290   }
11291 
11292 	case DTRACEAGG_AVG:
11293 		agg->dtag_aggregate = dtrace_aggregate_avg;
11294 		size = sizeof (uint64_t) * 2;
11295 		break;
11296 
11297 	case DTRACEAGG_STDDEV:
11298 		agg->dtag_aggregate = dtrace_aggregate_stddev;
11299 		size = sizeof (uint64_t) * 4;
11300 		break;
11301 
11302 	case DTRACEAGG_SUM:
11303 		agg->dtag_aggregate = dtrace_aggregate_sum;
11304 		break;
11305 
11306 	default:
11307 		goto err;
11308 	}
11309 
11310 	agg->dtag_action.dta_rec.dtrd_size = size;
11311 
11312 	if (ntuple == 0)
11313 		goto err;
11314 
11315 	/*
11316 	 * We must make sure that we have enough actions for the n-tuple.
11317 	 */
11318 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11319 		if (DTRACEACT_ISAGG(act->dta_kind))
11320 			break;
11321 
11322 		if (--ntuple == 0) {
11323 			/*
11324 			 * This is the action with which our n-tuple begins.
11325 			 */
11326 			agg->dtag_first = act;
11327 			goto success;
11328 		}
11329 	}
11330 
11331 	/*
11332 	 * This n-tuple is short by ntuple elements.  Return failure.
11333 	 */
11334 	ASSERT(ntuple != 0);
11335 err:
11336 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11337 	return (NULL);
11338 
11339 success:
11340 	/*
11341 	 * If the last action in the tuple has a size of zero, it's actually
11342 	 * an expression argument for the aggregating action.
11343 	 */
11344 	ASSERT(ecb->dte_action_last != NULL);
11345 	act = ecb->dte_action_last;
11346 
11347 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
11348 		ASSERT(act->dta_difo != NULL);
11349 
11350 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11351 			agg->dtag_hasarg = 1;
11352 	}
11353 
11354 	/*
11355 	 * We need to allocate an id for this aggregation.
11356 	 */
11357 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11358 	    VM_BESTFIT | VM_SLEEP);
11359 
11360 	if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
11361 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
11362 		dtrace_aggregation_t **aggs;
11363 		int naggs = state->dts_naggregations << 1;
11364 		int onaggs = state->dts_naggregations;
11365 
11366 		ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
11367 
11368 		if (naggs == 0) {
11369 			ASSERT(oaggs == NULL);
11370 			naggs = 1;
11371 		}
11372 
11373 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11374 
11375 		if (oaggs != NULL) {
11376 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11377 			kmem_free(oaggs, onaggs * sizeof (*aggs));
11378 		}
11379 
11380 		state->dts_aggregations = aggs;
11381 		state->dts_naggregations = naggs;
11382 	}
11383 
11384 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11385 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11386 
11387 	frec = &agg->dtag_first->dta_rec;
11388 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11389 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11390 
11391 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11392 		ASSERT(!act->dta_intuple);
11393 		act->dta_intuple = 1;
11394 	}
11395 
11396 	return (&agg->dtag_action);
11397 }
11398 
11399 static void
dtrace_ecb_aggregation_destroy(dtrace_ecb_t * ecb,dtrace_action_t * act)11400 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11401 {
11402 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11403 	dtrace_state_t *state = ecb->dte_state;
11404 	dtrace_aggid_t aggid = agg->dtag_id;
11405 
11406 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11407 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11408 
11409 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
11410 	state->dts_aggregations[aggid - 1] = NULL;
11411 
11412 	kmem_free(agg, sizeof (dtrace_aggregation_t));
11413 }
11414 
11415 static int
dtrace_ecb_action_add(dtrace_ecb_t * ecb,dtrace_actdesc_t * desc)11416 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11417 {
11418 	dtrace_action_t *action, *last;
11419 	dtrace_difo_t *dp = desc->dtad_difo;
11420 	uint32_t size = 0, align = sizeof (uint8_t), mask;
11421 	uint16_t format = 0;
11422 	dtrace_recdesc_t *rec;
11423 	dtrace_state_t *state = ecb->dte_state;
11424 	dtrace_optval_t *opt = state->dts_options;
11425 	dtrace_optval_t nframes=0, strsize;
11426 	uint64_t arg = desc->dtad_arg;
11427 
11428 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11429 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11430 
11431 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11432 		/*
11433 		 * If this is an aggregating action, there must be neither
11434 		 * a speculate nor a commit on the action chain.
11435 		 */
11436 		dtrace_action_t *act;
11437 
11438 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11439 			if (act->dta_kind == DTRACEACT_COMMIT)
11440 				return (EINVAL);
11441 
11442 			if (act->dta_kind == DTRACEACT_SPECULATE)
11443 				return (EINVAL);
11444 		}
11445 
11446 		action = dtrace_ecb_aggregation_create(ecb, desc);
11447 
11448 		if (action == NULL)
11449 			return (EINVAL);
11450 	} else {
11451 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11452 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11453 		    dp != NULL && dp->dtdo_destructive)) {
11454 			state->dts_destructive = 1;
11455 		}
11456 
11457 		switch (desc->dtad_kind) {
11458 		case DTRACEACT_PRINTF:
11459 		case DTRACEACT_PRINTA:
11460 		case DTRACEACT_SYSTEM:
11461 		case DTRACEACT_FREOPEN:
11462 		case DTRACEACT_DIFEXPR:
11463 			/*
11464 			 * We know that our arg is a string -- turn it into a
11465 			 * format.
11466 			 */
11467 			if (arg == 0) {
11468 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11469 				       desc->dtad_kind == DTRACEACT_DIFEXPR);
11470 				format = 0;
11471 			} else {
11472 				ASSERT(arg != 0);
11473 				ASSERT(arg > KERNELBASE);
11474 				format = dtrace_format_add(state,
11475 				    (char *)(uintptr_t)arg);
11476 			}
11477 
11478 			OS_FALLTHROUGH;
11479 		case DTRACEACT_LIBACT:
11480 		case DTRACEACT_TRACEMEM:
11481 		case DTRACEACT_TRACEMEM_DYNSIZE:
11482 		case DTRACEACT_APPLEBINARY:	/* __APPLE__ */
11483 			if (dp == NULL)
11484 				return (EINVAL);
11485 
11486 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11487 				break;
11488 
11489 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11490 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11491 					return (EINVAL);
11492 
11493 				size = opt[DTRACEOPT_STRSIZE];
11494 			}
11495 
11496 			break;
11497 
11498 		case DTRACEACT_STACK:
11499 			if ((nframes = arg) == 0) {
11500 				nframes = opt[DTRACEOPT_STACKFRAMES];
11501 				ASSERT(nframes > 0);
11502 				arg = nframes;
11503 			}
11504 
11505 			size = nframes * sizeof (pc_t);
11506 			break;
11507 
11508 		case DTRACEACT_JSTACK:
11509 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11510 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11511 
11512 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11513 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11514 
11515 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11516 
11517 			OS_FALLTHROUGH;
11518 		case DTRACEACT_USTACK:
11519 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11520 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11521 				strsize = DTRACE_USTACK_STRSIZE(arg);
11522 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11523 				ASSERT(nframes > 0);
11524 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11525 			}
11526 
11527 			/*
11528 			 * Save a slot for the pid.
11529 			 */
11530 			size = (nframes + 1) * sizeof (uint64_t);
11531 			size += DTRACE_USTACK_STRSIZE(arg);
11532 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11533 
11534 			break;
11535 
11536 		case DTRACEACT_SYM:
11537 		case DTRACEACT_MOD:
11538 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11539 			    sizeof (uint64_t)) ||
11540 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11541 				return (EINVAL);
11542 			break;
11543 
11544 		case DTRACEACT_USYM:
11545 		case DTRACEACT_UMOD:
11546 		case DTRACEACT_UADDR:
11547 			if (dp == NULL ||
11548 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11549 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11550 				return (EINVAL);
11551 
11552 			/*
11553 			 * We have a slot for the pid, plus a slot for the
11554 			 * argument.  To keep things simple (aligned with
11555 			 * bitness-neutral sizing), we store each as a 64-bit
11556 			 * quantity.
11557 			 */
11558 			size = 2 * sizeof (uint64_t);
11559 			break;
11560 
11561 		case DTRACEACT_STOP:
11562 		case DTRACEACT_BREAKPOINT:
11563 		case DTRACEACT_PANIC:
11564 			break;
11565 
11566 		case DTRACEACT_CHILL:
11567 		case DTRACEACT_DISCARD:
11568 		case DTRACEACT_RAISE:
11569 		case DTRACEACT_PIDRESUME:	/* __APPLE__ */
11570 			if (dp == NULL)
11571 				return (EINVAL);
11572 			break;
11573 
11574 		case DTRACEACT_EXIT:
11575 			if (dp == NULL ||
11576 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11577 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11578 				return (EINVAL);
11579 			break;
11580 
11581 		case DTRACEACT_SPECULATE:
11582 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11583 				return (EINVAL);
11584 
11585 			if (dp == NULL)
11586 				return (EINVAL);
11587 
11588 			state->dts_speculates = 1;
11589 			break;
11590 
11591 		case DTRACEACT_COMMIT: {
11592 			dtrace_action_t *act = ecb->dte_action;
11593 
11594 			for (; act != NULL; act = act->dta_next) {
11595 				if (act->dta_kind == DTRACEACT_COMMIT)
11596 					return (EINVAL);
11597 			}
11598 
11599 			if (dp == NULL)
11600 				return (EINVAL);
11601 			break;
11602 		}
11603 
11604 		default:
11605 			return (EINVAL);
11606 		}
11607 
11608 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11609 			/*
11610 			 * If this is a data-storing action or a speculate,
11611 			 * we must be sure that there isn't a commit on the
11612 			 * action chain.
11613 			 */
11614 			dtrace_action_t *act = ecb->dte_action;
11615 
11616 			for (; act != NULL; act = act->dta_next) {
11617 				if (act->dta_kind == DTRACEACT_COMMIT)
11618 					return (EINVAL);
11619 			}
11620 		}
11621 
11622 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11623 		action->dta_rec.dtrd_size = size;
11624 	}
11625 
11626 	action->dta_refcnt = 1;
11627 	rec = &action->dta_rec;
11628 	size = rec->dtrd_size;
11629 
11630 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11631 		if (!(size & mask)) {
11632 			align = mask + 1;
11633 			break;
11634 		}
11635 	}
11636 
11637 	action->dta_kind = desc->dtad_kind;
11638 
11639 	if ((action->dta_difo = dp) != NULL)
11640 		dtrace_difo_hold(dp);
11641 
11642 	rec->dtrd_action = action->dta_kind;
11643 	rec->dtrd_arg = arg;
11644 	rec->dtrd_uarg = desc->dtad_uarg;
11645 	rec->dtrd_alignment = (uint16_t)align;
11646 	rec->dtrd_format = format;
11647 
11648 	if ((last = ecb->dte_action_last) != NULL) {
11649 		ASSERT(ecb->dte_action != NULL);
11650 		action->dta_prev = last;
11651 		last->dta_next = action;
11652 	} else {
11653 		ASSERT(ecb->dte_action == NULL);
11654 		ecb->dte_action = action;
11655 	}
11656 
11657 	ecb->dte_action_last = action;
11658 
11659 	return (0);
11660 }
11661 
11662 static void
dtrace_ecb_action_remove(dtrace_ecb_t * ecb)11663 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11664 {
11665 	dtrace_action_t *act = ecb->dte_action, *next;
11666 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11667 	dtrace_difo_t *dp;
11668 	uint16_t format;
11669 
11670 	if (act != NULL && act->dta_refcnt > 1) {
11671 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11672 		act->dta_refcnt--;
11673 	} else {
11674 		for (; act != NULL; act = next) {
11675 			next = act->dta_next;
11676 			ASSERT(next != NULL || act == ecb->dte_action_last);
11677 			ASSERT(act->dta_refcnt == 1);
11678 
11679 			if ((format = act->dta_rec.dtrd_format) != 0)
11680 				dtrace_format_remove(ecb->dte_state, format);
11681 
11682 			if ((dp = act->dta_difo) != NULL)
11683 				dtrace_difo_release(dp, vstate);
11684 
11685 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11686 				dtrace_ecb_aggregation_destroy(ecb, act);
11687 			} else {
11688 				kmem_free(act, sizeof (dtrace_action_t));
11689 			}
11690 		}
11691 	}
11692 
11693 	ecb->dte_action = NULL;
11694 	ecb->dte_action_last = NULL;
11695 	ecb->dte_size = 0;
11696 }
11697 
11698 static void
dtrace_ecb_disable(dtrace_ecb_t * ecb)11699 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11700 {
11701 	/*
11702 	 * We disable the ECB by removing it from its probe.
11703 	 */
11704 	dtrace_ecb_t *pecb, *prev = NULL;
11705 	dtrace_probe_t *probe = ecb->dte_probe;
11706 
11707 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11708 
11709 	if (probe == NULL) {
11710 		/*
11711 		 * This is the NULL probe; there is nothing to disable.
11712 		 */
11713 		return;
11714 	}
11715 
11716 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11717 		if (pecb == ecb)
11718 			break;
11719 		prev = pecb;
11720 	}
11721 
11722 	ASSERT(pecb != NULL);
11723 
11724 	if (prev == NULL) {
11725 		probe->dtpr_ecb = ecb->dte_next;
11726 	} else {
11727 		prev->dte_next = ecb->dte_next;
11728 	}
11729 
11730 	if (ecb == probe->dtpr_ecb_last) {
11731 		ASSERT(ecb->dte_next == NULL);
11732 		probe->dtpr_ecb_last = prev;
11733 	}
11734 
11735 	probe->dtpr_provider->dtpv_ecb_count--;
11736 	/*
11737 	 * The ECB has been disconnected from the probe; now sync to assure
11738 	 * that all CPUs have seen the change before returning.
11739 	 */
11740 	dtrace_sync();
11741 
11742 	if (probe->dtpr_ecb == NULL) {
11743 		/*
11744 		 * That was the last ECB on the probe; clear the predicate
11745 		 * cache ID for the probe, disable it and sync one more time
11746 		 * to assure that we'll never hit it again.
11747 		 */
11748 		dtrace_provider_t *prov = probe->dtpr_provider;
11749 
11750 		ASSERT(ecb->dte_next == NULL);
11751 		ASSERT(probe->dtpr_ecb_last == NULL);
11752 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11753 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11754 		    probe->dtpr_id, probe->dtpr_arg);
11755 		dtrace_sync();
11756 	} else {
11757 		/*
11758 		 * There is at least one ECB remaining on the probe.  If there
11759 		 * is _exactly_ one, set the probe's predicate cache ID to be
11760 		 * the predicate cache ID of the remaining ECB.
11761 		 */
11762 		ASSERT(probe->dtpr_ecb_last != NULL);
11763 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11764 
11765 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11766 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11767 
11768 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11769 
11770 			if (p != NULL)
11771 				probe->dtpr_predcache = p->dtp_cacheid;
11772 		}
11773 
11774 		ecb->dte_next = NULL;
11775 	}
11776 }
11777 
11778 static void
dtrace_ecb_destroy(dtrace_ecb_t * ecb)11779 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11780 {
11781 	dtrace_state_t *state = ecb->dte_state;
11782 	dtrace_vstate_t *vstate = &state->dts_vstate;
11783 	dtrace_predicate_t *pred;
11784 	dtrace_epid_t epid = ecb->dte_epid;
11785 
11786 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11787 	ASSERT(ecb->dte_next == NULL);
11788 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11789 
11790 	if ((pred = ecb->dte_predicate) != NULL)
11791 		dtrace_predicate_release(pred, vstate);
11792 
11793 	dtrace_ecb_action_remove(ecb);
11794 
11795 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11796 	state->dts_ecbs[epid - 1] = NULL;
11797 
11798 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11799 }
11800 
11801 static dtrace_ecb_t *
dtrace_ecb_create(dtrace_state_t * state,dtrace_probe_t * probe,dtrace_enabling_t * enab)11802 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11803     dtrace_enabling_t *enab)
11804 {
11805 	dtrace_ecb_t *ecb;
11806 	dtrace_predicate_t *pred;
11807 	dtrace_actdesc_t *act;
11808 	dtrace_provider_t *prov;
11809 	dtrace_ecbdesc_t *desc = enab->dten_current;
11810 
11811 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11812 	ASSERT(state != NULL);
11813 
11814 	ecb = dtrace_ecb_add(state, probe);
11815 	ecb->dte_uarg = desc->dted_uarg;
11816 
11817 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11818 		dtrace_predicate_hold(pred);
11819 		ecb->dte_predicate = pred;
11820 	}
11821 
11822 	if (probe != NULL) {
11823 		/*
11824 		 * If the provider shows more leg than the consumer is old
11825 		 * enough to see, we need to enable the appropriate implicit
11826 		 * predicate bits to prevent the ecb from activating at
11827 		 * revealing times.
11828 		 *
11829 		 * Providers specifying DTRACE_PRIV_USER at register time
11830 		 * are stating that they need the /proc-style privilege
11831 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11832 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11833 		 */
11834 		prov = probe->dtpr_provider;
11835 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11836 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11837 			ecb->dte_cond |= DTRACE_COND_OWNER;
11838 
11839 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11840 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11841 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11842 
11843 		/*
11844 		 * If the provider shows us kernel innards and the user
11845 		 * is lacking sufficient privilege, enable the
11846 		 * DTRACE_COND_USERMODE implicit predicate.
11847 		 */
11848 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11849 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11850 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11851 	}
11852 
11853 	if (dtrace_ecb_create_cache != NULL) {
11854 		/*
11855 		 * If we have a cached ecb, we'll use its action list instead
11856 		 * of creating our own (saving both time and space).
11857 		 */
11858 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11859 		dtrace_action_t *act_if = cached->dte_action;
11860 
11861 		if (act_if != NULL) {
11862 			ASSERT(act_if->dta_refcnt > 0);
11863 			act_if->dta_refcnt++;
11864 			ecb->dte_action = act_if;
11865 			ecb->dte_action_last = cached->dte_action_last;
11866 			ecb->dte_needed = cached->dte_needed;
11867 			ecb->dte_size = cached->dte_size;
11868 			ecb->dte_alignment = cached->dte_alignment;
11869 		}
11870 
11871 		return (ecb);
11872 	}
11873 
11874 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11875 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11876 			dtrace_ecb_destroy(ecb);
11877 			return (NULL);
11878 		}
11879 	}
11880 
11881 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11882 		dtrace_ecb_destroy(ecb);
11883 		return (NULL);
11884 	}
11885 
11886 	return (dtrace_ecb_create_cache = ecb);
11887 }
11888 
11889 static int
dtrace_ecb_create_enable(dtrace_probe_t * probe,void * arg1,void * arg2)11890 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg1, void *arg2)
11891 {
11892 	dtrace_ecb_t *ecb;
11893 	dtrace_enabling_t *enab = arg1;
11894 	dtrace_ecbdesc_t *ep = arg2;
11895 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11896 
11897 	ASSERT(state != NULL);
11898 
11899 	if (probe != NULL && ep != NULL && probe->dtpr_gen < ep->dted_probegen) {
11900 		/*
11901 		 * This probe was created in a generation for which this
11902 		 * enabling has previously created ECBs; we don't want to
11903 		 * enable it again, so just kick out.
11904 		 */
11905 		return (DTRACE_MATCH_NEXT);
11906 	}
11907 
11908 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11909 		return (DTRACE_MATCH_DONE);
11910 
11911 	if (dtrace_ecb_enable(ecb) < 0)
11912                return (DTRACE_MATCH_FAIL);
11913 
11914 	return (DTRACE_MATCH_NEXT);
11915 }
11916 
11917 static dtrace_ecb_t *
dtrace_epid2ecb(dtrace_state_t * state,dtrace_epid_t id)11918 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11919 {
11920 	dtrace_ecb_t *ecb;
11921 #pragma unused(ecb) /* __APPLE__ */
11922 
11923 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11924 
11925 	if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
11926 		return (NULL);
11927 
11928 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11929 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11930 
11931 	return (state->dts_ecbs[id - 1]);
11932 }
11933 
11934 static dtrace_aggregation_t *
dtrace_aggid2agg(dtrace_state_t * state,dtrace_aggid_t id)11935 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11936 {
11937 	dtrace_aggregation_t *agg;
11938 #pragma unused(agg) /* __APPLE__ */
11939 
11940 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11941 
11942 	if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
11943 		return (NULL);
11944 
11945 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11946 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11947 	    agg->dtag_id == id);
11948 
11949 	return (state->dts_aggregations[id - 1]);
11950 }
11951 
11952 /*
11953  * DTrace Buffer Functions
11954  *
11955  * The following functions manipulate DTrace buffers.  Most of these functions
11956  * are called in the context of establishing or processing consumer state;
11957  * exceptions are explicitly noted.
11958  */
11959 
11960 /*
11961  * Note:  called from cross call context.  This function switches the two
11962  * buffers on a given CPU.  The atomicity of this operation is assured by
11963  * disabling interrupts while the actual switch takes place; the disabling of
11964  * interrupts serializes the execution with any execution of dtrace_probe() on
11965  * the same CPU.
11966  */
11967 static void
dtrace_buffer_switch(dtrace_buffer_t * buf)11968 dtrace_buffer_switch(dtrace_buffer_t *buf)
11969 {
11970 	caddr_t tomax = buf->dtb_tomax;
11971 	caddr_t xamot = buf->dtb_xamot;
11972 	dtrace_icookie_t cookie;
11973 	hrtime_t now;
11974 
11975 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11976 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11977 
11978 	cookie = dtrace_interrupt_disable();
11979 	now = dtrace_gethrtime();
11980 	buf->dtb_tomax = xamot;
11981 	buf->dtb_xamot = tomax;
11982 	buf->dtb_xamot_drops = buf->dtb_drops;
11983 	buf->dtb_xamot_offset = buf->dtb_offset;
11984 	buf->dtb_xamot_errors = buf->dtb_errors;
11985 	buf->dtb_xamot_flags = buf->dtb_flags;
11986 	buf->dtb_offset = 0;
11987 	buf->dtb_drops = 0;
11988 	buf->dtb_errors = 0;
11989 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11990 	buf->dtb_interval = now - buf->dtb_switched;
11991 	buf->dtb_switched = now;
11992 	buf->dtb_cur_limit = buf->dtb_limit;
11993 
11994 	dtrace_interrupt_enable(cookie);
11995 }
11996 
11997 /*
11998  * Note:  called from cross call context.  This function activates a buffer
11999  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
12000  * is guaranteed by the disabling of interrupts.
12001  */
12002 static void
dtrace_buffer_activate(dtrace_state_t * state)12003 dtrace_buffer_activate(dtrace_state_t *state)
12004 {
12005 	dtrace_buffer_t *buf;
12006 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
12007 
12008 	buf = &state->dts_buffer[CPU->cpu_id];
12009 
12010 	if (buf->dtb_tomax != NULL) {
12011 		/*
12012 		 * We might like to assert that the buffer is marked inactive,
12013 		 * but this isn't necessarily true:  the buffer for the CPU
12014 		 * that processes the BEGIN probe has its buffer activated
12015 		 * manually.  In this case, we take the (harmless) action
12016 		 * re-clearing the bit INACTIVE bit.
12017 		 */
12018 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12019 	}
12020 
12021 	dtrace_interrupt_enable(cookie);
12022 }
12023 
12024 static int
dtrace_buffer_canalloc(size_t size)12025 dtrace_buffer_canalloc(size_t size)
12026 {
12027 	if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
12028 		return (B_FALSE);
12029 	if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
12030 		return (B_FALSE);
12031 
12032 	return (B_TRUE);
12033 }
12034 
12035 static int
dtrace_buffer_alloc(dtrace_buffer_t * bufs,size_t limit,size_t size,int flags,processorid_t cpu)12036 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t limit, size_t size, int flags,
12037     processorid_t cpu)
12038 {
12039 	dtrace_cpu_t *cp;
12040 	dtrace_buffer_t *buf;
12041 	size_t size_before_alloc = dtrace_buffer_memory_inuse;
12042 
12043 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12044 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12045 
12046 	if (size > (size_t)dtrace_nonroot_maxsize &&
12047 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12048 		return (EFBIG);
12049 
12050 	cp = cpu_list;
12051 
12052 	do {
12053 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12054 			continue;
12055 
12056 		buf = &bufs[cp->cpu_id];
12057 
12058 		/*
12059 		 * If there is already a buffer allocated for this CPU, it
12060 		 * is only possible that this is a DR event.  In this case,
12061 		 * the buffer size must match our specified size.
12062 		 */
12063 		if (buf->dtb_tomax != NULL) {
12064 			ASSERT(buf->dtb_size == size);
12065 			continue;
12066 		}
12067 
12068 		ASSERT(buf->dtb_xamot == NULL);
12069 
12070 		/* DTrace, please do not eat all the memory. */
12071 		if (dtrace_buffer_canalloc(size) == B_FALSE)
12072 			goto err;
12073 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12074 			goto err;
12075 		dtrace_buffer_memory_inuse += size;
12076 
12077 		/* Unsure that limit is always lower than size */
12078 		limit = limit == size ? limit - 1 : limit;
12079 		buf->dtb_cur_limit = limit;
12080 		buf->dtb_limit = limit;
12081 		buf->dtb_size = size;
12082 		buf->dtb_flags = flags;
12083 		buf->dtb_offset = 0;
12084 		buf->dtb_drops = 0;
12085 
12086 		if (flags & DTRACEBUF_NOSWITCH)
12087 			continue;
12088 
12089 		/* DTrace, please do not eat all the memory. */
12090 		if (dtrace_buffer_canalloc(size) == B_FALSE)
12091 			goto err;
12092 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12093 			goto err;
12094 		dtrace_buffer_memory_inuse += size;
12095 	} while ((cp = cp->cpu_next) != cpu_list);
12096 
12097 	ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
12098 
12099 	return (0);
12100 
12101 err:
12102 	cp = cpu_list;
12103 
12104 	do {
12105 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12106 			continue;
12107 
12108 		buf = &bufs[cp->cpu_id];
12109 
12110 		if (buf->dtb_xamot != NULL) {
12111 			ASSERT(buf->dtb_tomax != NULL);
12112 			ASSERT(buf->dtb_size == size);
12113 			kmem_free(buf->dtb_xamot, size);
12114 		}
12115 
12116 		if (buf->dtb_tomax != NULL) {
12117 			ASSERT(buf->dtb_size == size);
12118 			kmem_free(buf->dtb_tomax, size);
12119 		}
12120 
12121 		buf->dtb_tomax = NULL;
12122 		buf->dtb_xamot = NULL;
12123 		buf->dtb_size = 0;
12124 	} while ((cp = cp->cpu_next) != cpu_list);
12125 
12126 	/* Restore the size saved before allocating memory */
12127 	dtrace_buffer_memory_inuse = size_before_alloc;
12128 
12129 	return (ENOMEM);
12130 }
12131 
12132 /*
12133  * Note:  called from probe context.  This function just increments the drop
12134  * count on a buffer.  It has been made a function to allow for the
12135  * possibility of understanding the source of mysterious drop counts.  (A
12136  * problem for which one may be particularly disappointed that DTrace cannot
12137  * be used to understand DTrace.)
12138  */
12139 static void
dtrace_buffer_drop(dtrace_buffer_t * buf)12140 dtrace_buffer_drop(dtrace_buffer_t *buf)
12141 {
12142 	buf->dtb_drops++;
12143 }
12144 
12145 /*
12146  * Note:  called from probe context.  This function is called to reserve space
12147  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
12148  * mstate.  Returns the new offset in the buffer, or a negative value if an
12149  * error has occurred.
12150  */
12151 static intptr_t
dtrace_buffer_reserve(dtrace_buffer_t * buf,size_t needed,size_t align,dtrace_state_t * state,dtrace_mstate_t * mstate)12152 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12153     dtrace_state_t *state, dtrace_mstate_t *mstate)
12154 {
12155 	intptr_t offs = buf->dtb_offset, soffs;
12156 	intptr_t woffs;
12157 	caddr_t tomax;
12158 	size_t total_off;
12159 
12160 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12161 		return (-1);
12162 
12163 	if ((tomax = buf->dtb_tomax) == NULL) {
12164 		dtrace_buffer_drop(buf);
12165 		return (-1);
12166 	}
12167 
12168 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12169 		while (offs & (align - 1)) {
12170 			/*
12171 			 * Assert that our alignment is off by a number which
12172 			 * is itself sizeof (uint32_t) aligned.
12173 			 */
12174 			ASSERT(!((align - (offs & (align - 1))) &
12175 			    (sizeof (uint32_t) - 1)));
12176 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12177 			offs += sizeof (uint32_t);
12178 		}
12179 
12180 		if ((uint64_t)(soffs = offs + needed) > buf->dtb_cur_limit) {
12181 			if (buf->dtb_cur_limit == buf->dtb_limit) {
12182 				buf->dtb_cur_limit = buf->dtb_size;
12183 
12184 				os_atomic_inc(&state->dts_buf_over_limit, relaxed);
12185 				/**
12186 				 * Set an AST on the current processor
12187 				 * so that we can wake up the process
12188 				 * outside of probe context, when we know
12189 				 * it is safe to do so
12190 				 */
12191 				minor_t minor = getminor(state->dts_dev);
12192 				ASSERT(minor < 32);
12193 
12194 				os_atomic_or(&dtrace_wake_clients, 1 << minor, relaxed);
12195 				ast_dtrace_on();
12196 			}
12197 			if ((uint64_t)soffs > buf->dtb_size) {
12198 				dtrace_buffer_drop(buf);
12199 				return (-1);
12200 			}
12201 		}
12202 
12203 		if (mstate == NULL)
12204 			return (offs);
12205 
12206 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12207 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
12208 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12209 
12210 		return (offs);
12211 	}
12212 
12213 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12214 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12215 		    (buf->dtb_flags & DTRACEBUF_FULL))
12216 			return (-1);
12217 		goto out;
12218 	}
12219 
12220 	total_off = needed + (offs & (align - 1));
12221 
12222 	/*
12223 	 * For a ring buffer, life is quite a bit more complicated.  Before
12224 	 * we can store any padding, we need to adjust our wrapping offset.
12225 	 * (If we've never before wrapped or we're not about to, no adjustment
12226 	 * is required.)
12227 	 */
12228 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12229 	    offs + total_off > buf->dtb_size) {
12230 		woffs = buf->dtb_xamot_offset;
12231 
12232 		if (offs + total_off > buf->dtb_size) {
12233 			/*
12234 			 * We can't fit in the end of the buffer.  First, a
12235 			 * sanity check that we can fit in the buffer at all.
12236 			 */
12237 			if (total_off > buf->dtb_size) {
12238 				dtrace_buffer_drop(buf);
12239 				return (-1);
12240 			}
12241 
12242 			/*
12243 			 * We're going to be storing at the top of the buffer,
12244 			 * so now we need to deal with the wrapped offset.  We
12245 			 * only reset our wrapped offset to 0 if it is
12246 			 * currently greater than the current offset.  If it
12247 			 * is less than the current offset, it is because a
12248 			 * previous allocation induced a wrap -- but the
12249 			 * allocation didn't subsequently take the space due
12250 			 * to an error or false predicate evaluation.  In this
12251 			 * case, we'll just leave the wrapped offset alone: if
12252 			 * the wrapped offset hasn't been advanced far enough
12253 			 * for this allocation, it will be adjusted in the
12254 			 * lower loop.
12255 			 */
12256 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12257 				if (woffs >= offs)
12258 					woffs = 0;
12259 			} else {
12260 				woffs = 0;
12261 			}
12262 
12263 			/*
12264 			 * Now we know that we're going to be storing to the
12265 			 * top of the buffer and that there is room for us
12266 			 * there.  We need to clear the buffer from the current
12267 			 * offset to the end (there may be old gunk there).
12268 			 */
12269 			while ((uint64_t)offs < buf->dtb_size)
12270 				tomax[offs++] = 0;
12271 
12272 			/*
12273 			 * We need to set our offset to zero.  And because we
12274 			 * are wrapping, we need to set the bit indicating as
12275 			 * much.  We can also adjust our needed space back
12276 			 * down to the space required by the ECB -- we know
12277 			 * that the top of the buffer is aligned.
12278 			 */
12279 			offs = 0;
12280 			total_off = needed;
12281 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
12282 		} else {
12283 			/*
12284 			 * There is room for us in the buffer, so we simply
12285 			 * need to check the wrapped offset.
12286 			 */
12287 			if (woffs < offs) {
12288 				/*
12289 				 * The wrapped offset is less than the offset.
12290 				 * This can happen if we allocated buffer space
12291 				 * that induced a wrap, but then we didn't
12292 				 * subsequently take the space due to an error
12293 				 * or false predicate evaluation.  This is
12294 				 * okay; we know that _this_ allocation isn't
12295 				 * going to induce a wrap.  We still can't
12296 				 * reset the wrapped offset to be zero,
12297 				 * however: the space may have been trashed in
12298 				 * the previous failed probe attempt.  But at
12299 				 * least the wrapped offset doesn't need to
12300 				 * be adjusted at all...
12301 				 */
12302 				goto out;
12303 			}
12304 		}
12305 
12306 		while (offs + total_off > (size_t)woffs) {
12307 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12308 			size_t size;
12309 
12310 			if (epid == DTRACE_EPIDNONE) {
12311 				size = sizeof (uint32_t);
12312 			} else {
12313 				ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
12314 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
12315 
12316 				size = state->dts_ecbs[epid - 1]->dte_size;
12317 			}
12318 
12319 			ASSERT(woffs + size <= buf->dtb_size);
12320 			ASSERT(size != 0);
12321 
12322 			if (woffs + size == buf->dtb_size) {
12323 				/*
12324 				 * We've reached the end of the buffer; we want
12325 				 * to set the wrapped offset to 0 and break
12326 				 * out.  However, if the offs is 0, then we're
12327 				 * in a strange edge-condition:  the amount of
12328 				 * space that we want to reserve plus the size
12329 				 * of the record that we're overwriting is
12330 				 * greater than the size of the buffer.  This
12331 				 * is problematic because if we reserve the
12332 				 * space but subsequently don't consume it (due
12333 				 * to a failed predicate or error) the wrapped
12334 				 * offset will be 0 -- yet the EPID at offset 0
12335 				 * will not be committed.  This situation is
12336 				 * relatively easy to deal with:  if we're in
12337 				 * this case, the buffer is indistinguishable
12338 				 * from one that hasn't wrapped; we need only
12339 				 * finish the job by clearing the wrapped bit,
12340 				 * explicitly setting the offset to be 0, and
12341 				 * zero'ing out the old data in the buffer.
12342 				 */
12343 				if (offs == 0) {
12344 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12345 					buf->dtb_offset = 0;
12346 					woffs = total_off;
12347 
12348 					while ((uint64_t)woffs < buf->dtb_size)
12349 						tomax[woffs++] = 0;
12350 				}
12351 
12352 				woffs = 0;
12353 				break;
12354 			}
12355 
12356 			woffs += size;
12357 		}
12358 
12359 		/*
12360 		 * We have a wrapped offset.  It may be that the wrapped offset
12361 		 * has become zero -- that's okay.
12362 		 */
12363 		buf->dtb_xamot_offset = woffs;
12364 	}
12365 
12366 out:
12367 	/*
12368 	 * Now we can plow the buffer with any necessary padding.
12369 	 */
12370 	while (offs & (align - 1)) {
12371 		/*
12372 		 * Assert that our alignment is off by a number which
12373 		 * is itself sizeof (uint32_t) aligned.
12374 		 */
12375 		ASSERT(!((align - (offs & (align - 1))) &
12376 		    (sizeof (uint32_t) - 1)));
12377 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12378 		offs += sizeof (uint32_t);
12379 	}
12380 
12381 	if (buf->dtb_flags & DTRACEBUF_FILL) {
12382 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
12383 			buf->dtb_flags |= DTRACEBUF_FULL;
12384 			return (-1);
12385 		}
12386 	}
12387 
12388 	if (mstate == NULL)
12389 		return (offs);
12390 
12391 	/*
12392 	 * For ring buffers and fill buffers, the scratch space is always
12393 	 * the inactive buffer.
12394 	 */
12395 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12396 	mstate->dtms_scratch_size = buf->dtb_size;
12397 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12398 
12399 	return (offs);
12400 }
12401 
12402 static void
dtrace_buffer_polish(dtrace_buffer_t * buf)12403 dtrace_buffer_polish(dtrace_buffer_t *buf)
12404 {
12405 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12406 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12407 
12408 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12409 		return;
12410 
12411 	/*
12412 	 * We need to polish the ring buffer.  There are three cases:
12413 	 *
12414 	 * - The first (and presumably most common) is that there is no gap
12415 	 *   between the buffer offset and the wrapped offset.  In this case,
12416 	 *   there is nothing in the buffer that isn't valid data; we can
12417 	 *   mark the buffer as polished and return.
12418 	 *
12419 	 * - The second (less common than the first but still more common
12420 	 *   than the third) is that there is a gap between the buffer offset
12421 	 *   and the wrapped offset, and the wrapped offset is larger than the
12422 	 *   buffer offset.  This can happen because of an alignment issue, or
12423 	 *   can happen because of a call to dtrace_buffer_reserve() that
12424 	 *   didn't subsequently consume the buffer space.  In this case,
12425 	 *   we need to zero the data from the buffer offset to the wrapped
12426 	 *   offset.
12427 	 *
12428 	 * - The third (and least common) is that there is a gap between the
12429 	 *   buffer offset and the wrapped offset, but the wrapped offset is
12430 	 *   _less_ than the buffer offset.  This can only happen because a
12431 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
12432 	 *   was not subsequently consumed.  In this case, we need to zero the
12433 	 *   space from the offset to the end of the buffer _and_ from the
12434 	 *   top of the buffer to the wrapped offset.
12435 	 */
12436 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
12437 		bzero(buf->dtb_tomax + buf->dtb_offset,
12438 		    buf->dtb_xamot_offset - buf->dtb_offset);
12439 	}
12440 
12441 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
12442 		bzero(buf->dtb_tomax + buf->dtb_offset,
12443 		    buf->dtb_size - buf->dtb_offset);
12444 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12445 	}
12446 }
12447 
12448 static void
dtrace_buffer_free(dtrace_buffer_t * bufs)12449 dtrace_buffer_free(dtrace_buffer_t *bufs)
12450 {
12451 	int i;
12452 
12453 	for (i = 0; i < (int)NCPU; i++) {
12454 		dtrace_buffer_t *buf = &bufs[i];
12455 
12456 		if (buf->dtb_tomax == NULL) {
12457 			ASSERT(buf->dtb_xamot == NULL);
12458 			ASSERT(buf->dtb_size == 0);
12459 			continue;
12460 		}
12461 
12462 		if (buf->dtb_xamot != NULL) {
12463 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12464 			kmem_free(buf->dtb_xamot, buf->dtb_size);
12465 
12466 			ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
12467 			dtrace_buffer_memory_inuse -= buf->dtb_size;
12468 		}
12469 
12470 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12471 		ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
12472 		dtrace_buffer_memory_inuse -= buf->dtb_size;
12473 
12474 		buf->dtb_size = 0;
12475 		buf->dtb_tomax = NULL;
12476 		buf->dtb_xamot = NULL;
12477 	}
12478 }
12479 
12480 /*
12481  * DTrace Enabling Functions
12482  */
12483 static dtrace_enabling_t *
dtrace_enabling_create(dtrace_vstate_t * vstate)12484 dtrace_enabling_create(dtrace_vstate_t *vstate)
12485 {
12486 	dtrace_enabling_t *enab;
12487 
12488 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12489 	enab->dten_vstate = vstate;
12490 
12491 	return (enab);
12492 }
12493 
12494 static void
dtrace_enabling_add(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb)12495 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12496 {
12497 	dtrace_ecbdesc_t **ndesc;
12498 	size_t osize, nsize;
12499 
12500 	/*
12501 	 * We can't add to enablings after we've enabled them, or after we've
12502 	 * retained them.
12503 	 */
12504 	ASSERT(enab->dten_probegen == 0);
12505 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12506 
12507 	/* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
12508 	if (ecb == NULL) return;
12509 
12510 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12511 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12512 		return;
12513 	}
12514 
12515 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12516 
12517 	if (enab->dten_maxdesc == 0) {
12518 		enab->dten_maxdesc = 1;
12519 	} else {
12520 		enab->dten_maxdesc <<= 1;
12521 	}
12522 
12523 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12524 
12525 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12526 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12527 	bcopy(enab->dten_desc, ndesc, osize);
12528 	kmem_free(enab->dten_desc, osize);
12529 
12530 	enab->dten_desc = ndesc;
12531 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12532 }
12533 
12534 static void
dtrace_enabling_addlike(dtrace_enabling_t * enab,dtrace_ecbdesc_t * ecb,dtrace_probedesc_t * pd)12535 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12536     dtrace_probedesc_t *pd)
12537 {
12538 	dtrace_ecbdesc_t *new;
12539 	dtrace_predicate_t *pred;
12540 	dtrace_actdesc_t *act;
12541 
12542 	/*
12543 	 * We're going to create a new ECB description that matches the
12544 	 * specified ECB in every way, but has the specified probe description.
12545 	 */
12546 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12547 
12548 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12549 		dtrace_predicate_hold(pred);
12550 
12551 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12552 		dtrace_actdesc_hold(act);
12553 
12554 	new->dted_action = ecb->dted_action;
12555 	new->dted_pred = ecb->dted_pred;
12556 	new->dted_probe = *pd;
12557 	new->dted_uarg = ecb->dted_uarg;
12558 
12559 	dtrace_enabling_add(enab, new);
12560 }
12561 
12562 static void
dtrace_enabling_dump(dtrace_enabling_t * enab)12563 dtrace_enabling_dump(dtrace_enabling_t *enab)
12564 {
12565 	int i;
12566 
12567 	for (i = 0; i < enab->dten_ndesc; i++) {
12568 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12569 
12570 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12571 		    desc->dtpd_provider, desc->dtpd_mod,
12572 		    desc->dtpd_func, desc->dtpd_name);
12573 	}
12574 }
12575 
12576 static void
dtrace_enabling_destroy(dtrace_enabling_t * enab)12577 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12578 {
12579 	int i;
12580 	dtrace_ecbdesc_t *ep;
12581 	dtrace_vstate_t *vstate = enab->dten_vstate;
12582 
12583 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12584 
12585 	for (i = 0; i < enab->dten_ndesc; i++) {
12586 		dtrace_actdesc_t *act, *next;
12587 		dtrace_predicate_t *pred;
12588 
12589 		ep = enab->dten_desc[i];
12590 
12591 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12592 			dtrace_predicate_release(pred, vstate);
12593 
12594 		for (act = ep->dted_action; act != NULL; act = next) {
12595 			next = act->dtad_next;
12596 			dtrace_actdesc_release(act, vstate);
12597 		}
12598 
12599 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12600 	}
12601 
12602 	kmem_free(enab->dten_desc,
12603 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12604 
12605 	/*
12606 	 * If this was a retained enabling, decrement the dts_nretained count
12607 	 * and take it off of the dtrace_retained list.
12608 	 */
12609 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12610 	    dtrace_retained == enab) {
12611 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12612 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12613 		enab->dten_vstate->dtvs_state->dts_nretained--;
12614                 dtrace_retained_gen++;
12615 	}
12616 
12617 	if (enab->dten_prev == NULL) {
12618 		if (dtrace_retained == enab) {
12619 			dtrace_retained = enab->dten_next;
12620 
12621 			if (dtrace_retained != NULL)
12622 				dtrace_retained->dten_prev = NULL;
12623 		}
12624 	} else {
12625 		ASSERT(enab != dtrace_retained);
12626 		ASSERT(dtrace_retained != NULL);
12627 		enab->dten_prev->dten_next = enab->dten_next;
12628 	}
12629 
12630 	if (enab->dten_next != NULL) {
12631 		ASSERT(dtrace_retained != NULL);
12632 		enab->dten_next->dten_prev = enab->dten_prev;
12633 	}
12634 
12635 	kmem_free(enab, sizeof (dtrace_enabling_t));
12636 }
12637 
12638 static int
dtrace_enabling_retain(dtrace_enabling_t * enab)12639 dtrace_enabling_retain(dtrace_enabling_t *enab)
12640 {
12641 	dtrace_state_t *state;
12642 
12643 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12644 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12645 	ASSERT(enab->dten_vstate != NULL);
12646 
12647 	state = enab->dten_vstate->dtvs_state;
12648 	ASSERT(state != NULL);
12649 
12650 	/*
12651 	 * We only allow each state to retain dtrace_retain_max enablings.
12652 	 */
12653 	if (state->dts_nretained >= dtrace_retain_max)
12654 		return (ENOSPC);
12655 
12656 	state->dts_nretained++;
12657         dtrace_retained_gen++;
12658 
12659 	if (dtrace_retained == NULL) {
12660 		dtrace_retained = enab;
12661 		return (0);
12662 	}
12663 
12664 	enab->dten_next = dtrace_retained;
12665 	dtrace_retained->dten_prev = enab;
12666 	dtrace_retained = enab;
12667 
12668 	return (0);
12669 }
12670 
12671 static int
dtrace_enabling_replicate(dtrace_state_t * state,dtrace_probedesc_t * match,dtrace_probedesc_t * create)12672 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12673     dtrace_probedesc_t *create)
12674 {
12675 	dtrace_enabling_t *new, *enab;
12676 	int found = 0, err = ENOENT;
12677 
12678 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12679 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12680 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12681 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12682 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12683 
12684 	new = dtrace_enabling_create(&state->dts_vstate);
12685 
12686 	/*
12687 	 * Iterate over all retained enablings, looking for enablings that
12688 	 * match the specified state.
12689 	 */
12690 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12691 		int i;
12692 
12693 		/*
12694 		 * dtvs_state can only be NULL for helper enablings -- and
12695 		 * helper enablings can't be retained.
12696 		 */
12697 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12698 
12699 		if (enab->dten_vstate->dtvs_state != state)
12700 			continue;
12701 
12702 		/*
12703 		 * Now iterate over each probe description; we're looking for
12704 		 * an exact match to the specified probe description.
12705 		 */
12706 		for (i = 0; i < enab->dten_ndesc; i++) {
12707 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12708 			dtrace_probedesc_t *pd = &ep->dted_probe;
12709 
12710 			/* APPLE NOTE: Darwin employs size bounded string operation. */
12711 			if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
12712 				continue;
12713 
12714 			if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
12715 				continue;
12716 
12717 			if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
12718 				continue;
12719 
12720 			if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
12721 				continue;
12722 
12723 			/*
12724 			 * We have a winning probe!  Add it to our growing
12725 			 * enabling.
12726 			 */
12727 			found = 1;
12728 			dtrace_enabling_addlike(new, ep, create);
12729 		}
12730 	}
12731 
12732 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12733 		dtrace_enabling_destroy(new);
12734 		return (err);
12735 	}
12736 
12737 	return (0);
12738 }
12739 
12740 static void
dtrace_enabling_retract(dtrace_state_t * state)12741 dtrace_enabling_retract(dtrace_state_t *state)
12742 {
12743 	dtrace_enabling_t *enab, *next;
12744 
12745 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12746 
12747 	/*
12748 	 * Iterate over all retained enablings, destroy the enablings retained
12749 	 * for the specified state.
12750 	 */
12751 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12752 		next = enab->dten_next;
12753 
12754 		/*
12755 		 * dtvs_state can only be NULL for helper enablings -- and
12756 		 * helper enablings can't be retained.
12757 		 */
12758 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12759 
12760 		if (enab->dten_vstate->dtvs_state == state) {
12761 			ASSERT(state->dts_nretained > 0);
12762 			dtrace_enabling_destroy(enab);
12763 		}
12764 	}
12765 
12766 	ASSERT(state->dts_nretained == 0);
12767 }
12768 
12769 static int
dtrace_enabling_match(dtrace_enabling_t * enab,int * nmatched,dtrace_match_cond_t * cond)12770 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched, dtrace_match_cond_t *cond)
12771 {
12772 	int i = 0;
12773 	int total_matched = 0, matched = 0;
12774 
12775 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12776 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12777 
12778 	for (i = 0; i < enab->dten_ndesc; i++) {
12779 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12780 
12781 		enab->dten_current = ep;
12782 		enab->dten_error = 0;
12783 
12784 		/**
12785 		 * Before doing a dtrace_probe_enable, which is really
12786 		 * expensive, check that this enabling matches the matching precondition
12787 		 * if we have one
12788 		 */
12789 		if (cond && (cond->dmc_func(&ep->dted_probe, cond->dmc_data) == 0)) {
12790 			continue;
12791 		}
12792 		/*
12793 		 * If a provider failed to enable a probe then get out and
12794 		 * let the consumer know we failed.
12795 		 */
12796 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab, ep)) < 0)
12797 			return (EBUSY);
12798 
12799 		total_matched += matched;
12800 
12801 		if (enab->dten_error != 0) {
12802 			/*
12803 			 * If we get an error half-way through enabling the
12804 			 * probes, we kick out -- perhaps with some number of
12805 			 * them enabled.  Leaving enabled probes enabled may
12806 			 * be slightly confusing for user-level, but we expect
12807 			 * that no one will attempt to actually drive on in
12808 			 * the face of such errors.  If this is an anonymous
12809 			 * enabling (indicated with a NULL nmatched pointer),
12810 			 * we cmn_err() a message.  We aren't expecting to
12811 			 * get such an error -- such as it can exist at all,
12812 			 * it would be a result of corrupted DOF in the driver
12813 			 * properties.
12814 			 */
12815 			if (nmatched == NULL) {
12816 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12817 				    "error on %p: %d", (void *)ep,
12818 				    enab->dten_error);
12819 			}
12820 
12821 			return (enab->dten_error);
12822 		}
12823 
12824 		ep->dted_probegen = dtrace_probegen;
12825 	}
12826 
12827 	if (nmatched != NULL)
12828 		*nmatched = total_matched;
12829 
12830 	return (0);
12831 }
12832 
12833 static void
dtrace_enabling_matchall_with_cond(dtrace_match_cond_t * cond)12834 dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond)
12835 {
12836 	dtrace_enabling_t *enab;
12837 
12838 	lck_mtx_lock(&cpu_lock);
12839 	lck_mtx_lock(&dtrace_lock);
12840 
12841 	/*
12842 	 * Iterate over all retained enablings to see if any probes match
12843 	 * against them.  We only perform this operation on enablings for which
12844 	 * we have sufficient permissions by virtue of being in the global zone
12845 	 * or in the same zone as the DTrace client.  Because we can be called
12846 	 * after dtrace_detach() has been called, we cannot assert that there
12847 	 * are retained enablings.  We can safely load from dtrace_retained,
12848 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12849 	 * block pending our completion.
12850 	 */
12851 
12852 	/*
12853 	 * Darwin doesn't do zones.
12854 	 * Behave as if always in "global" zone."
12855 	 */
12856 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12857 		(void) dtrace_enabling_match(enab, NULL, cond);
12858 	}
12859 
12860 	lck_mtx_unlock(&dtrace_lock);
12861 	lck_mtx_unlock(&cpu_lock);
12862 
12863 }
12864 
12865 static void
dtrace_enabling_matchall(void)12866 dtrace_enabling_matchall(void)
12867 {
12868 	dtrace_enabling_matchall_with_cond(NULL);
12869 }
12870 
12871 
12872 
12873 /*
12874  * If an enabling is to be enabled without having matched probes (that is, if
12875  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12876  * enabling must be _primed_ by creating an ECB for every ECB description.
12877  * This must be done to assure that we know the number of speculations, the
12878  * number of aggregations, the minimum buffer size needed, etc. before we
12879  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12880  * enabling any probes, we create ECBs for every ECB decription, but with a
12881  * NULL probe -- which is exactly what this function does.
12882  */
12883 static void
dtrace_enabling_prime(dtrace_state_t * state)12884 dtrace_enabling_prime(dtrace_state_t *state)
12885 {
12886 	dtrace_enabling_t *enab;
12887 	int i;
12888 
12889 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12890 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12891 
12892 		if (enab->dten_vstate->dtvs_state != state)
12893 			continue;
12894 
12895 		/*
12896 		 * We don't want to prime an enabling more than once, lest
12897 		 * we allow a malicious user to induce resource exhaustion.
12898 		 * (The ECBs that result from priming an enabling aren't
12899 		 * leaked -- but they also aren't deallocated until the
12900 		 * consumer state is destroyed.)
12901 		 */
12902 		if (enab->dten_primed)
12903 			continue;
12904 
12905 		for (i = 0; i < enab->dten_ndesc; i++) {
12906 			enab->dten_current = enab->dten_desc[i];
12907 			(void) dtrace_probe_enable(NULL, enab, NULL);
12908 		}
12909 
12910 		enab->dten_primed = 1;
12911 	}
12912 }
12913 
12914 /*
12915  * Called to indicate that probes should be provided due to retained
12916  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12917  * must take an initial lap through the enabling calling the dtps_provide()
12918  * entry point explicitly to allow for autocreated probes.
12919  */
12920 static void
dtrace_enabling_provide(dtrace_provider_t * prv)12921 dtrace_enabling_provide(dtrace_provider_t *prv)
12922 {
12923 	int i, all = 0;
12924 	dtrace_probedesc_t desc;
12925         dtrace_genid_t gen;
12926 
12927 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12928 	LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
12929 
12930 	if (prv == NULL) {
12931 		all = 1;
12932 		prv = dtrace_provider;
12933 	}
12934 
12935 	do {
12936 		dtrace_enabling_t *enab;
12937 		void *parg = prv->dtpv_arg;
12938 
12939 retry:
12940 		gen = dtrace_retained_gen;
12941 		for (enab = dtrace_retained; enab != NULL;
12942 		    enab = enab->dten_next) {
12943 			for (i = 0; i < enab->dten_ndesc; i++) {
12944 				desc = enab->dten_desc[i]->dted_probe;
12945 				lck_mtx_unlock(&dtrace_lock);
12946 				prv->dtpv_pops.dtps_provide(parg, &desc);
12947 				lck_mtx_lock(&dtrace_lock);
12948 				/*
12949 				 * Process the retained enablings again if
12950 				 * they have changed while we weren't holding
12951 				 * dtrace_lock.
12952 				 */
12953 				if (gen != dtrace_retained_gen)
12954 					goto retry;
12955 			}
12956 		}
12957 	} while (all && (prv = prv->dtpv_next) != NULL);
12958 
12959 	lck_mtx_unlock(&dtrace_lock);
12960 	dtrace_probe_provide(NULL, all ? NULL : prv);
12961 	lck_mtx_lock(&dtrace_lock);
12962 }
12963 
12964 /*
12965  * DTrace DOF Functions
12966  */
12967 /*ARGSUSED*/
12968 static void
dtrace_dof_error(dof_hdr_t * dof,const char * str)12969 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12970 {
12971 #pragma unused(dof) /* __APPLE__ */
12972 	if (dtrace_err_verbose)
12973 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12974 
12975 #ifdef DTRACE_ERRDEBUG
12976 	dtrace_errdebug(str);
12977 #endif
12978 }
12979 
12980 /*
12981  * Create DOF out of a currently enabled state.  Right now, we only create
12982  * DOF containing the run-time options -- but this could be expanded to create
12983  * complete DOF representing the enabled state.
12984  */
12985 static dof_hdr_t *
dtrace_dof_create(dtrace_state_t * state)12986 dtrace_dof_create(dtrace_state_t *state)
12987 {
12988 	dof_hdr_t *dof;
12989 	dof_sec_t *sec;
12990 	dof_optdesc_t *opt;
12991 	int i, len = sizeof (dof_hdr_t) +
12992 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12993 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12994 
12995 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12996 
12997 	dof = kmem_zalloc_aligned(len, 8, KM_SLEEP);
12998 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12999 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13000 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13001 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13002 
13003 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13004 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13005 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13006 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13007 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13008 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13009 
13010 	dof->dofh_flags = 0;
13011 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
13012 	dof->dofh_secsize = sizeof (dof_sec_t);
13013 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
13014 	dof->dofh_secoff = sizeof (dof_hdr_t);
13015 	dof->dofh_loadsz = len;
13016 	dof->dofh_filesz = len;
13017 	dof->dofh_pad = 0;
13018 
13019 	/*
13020 	 * Fill in the option section header...
13021 	 */
13022 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13023 	sec->dofs_type = DOF_SECT_OPTDESC;
13024 	sec->dofs_align = sizeof (uint64_t);
13025 	sec->dofs_flags = DOF_SECF_LOAD;
13026 	sec->dofs_entsize = sizeof (dof_optdesc_t);
13027 
13028 	opt = (dof_optdesc_t *)((uintptr_t)sec +
13029 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13030 
13031 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13032 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13033 
13034 	for (i = 0; i < DTRACEOPT_MAX; i++) {
13035 		opt[i].dofo_option = i;
13036 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
13037 		opt[i].dofo_value = state->dts_options[i];
13038 	}
13039 
13040 	return (dof);
13041 }
13042 
13043 static dof_hdr_t *
dtrace_dof_copyin(user_addr_t uarg,int * errp)13044 dtrace_dof_copyin(user_addr_t uarg, int *errp)
13045 {
13046 	dof_hdr_t hdr, *dof;
13047 
13048 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
13049 
13050 	/*
13051 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13052 	 */
13053 	if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
13054 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13055 		*errp = EFAULT;
13056 		return (NULL);
13057 	}
13058 
13059 	/*
13060 	 * Now we'll allocate the entire DOF and copy it in -- provided
13061 	 * that the length isn't outrageous.
13062 	 */
13063 	if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13064 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13065 		*errp = E2BIG;
13066 		return (NULL);
13067 	}
13068 
13069 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13070 		dtrace_dof_error(&hdr, "invalid load size");
13071 		*errp = EINVAL;
13072 		return (NULL);
13073 	}
13074 
13075 	dof = kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
13076 
13077 	if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
13078 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13079 		kmem_free_aligned(dof, hdr.dofh_loadsz);
13080 		*errp = EFAULT;
13081 		return (NULL);
13082 	}
13083 
13084 	return (dof);
13085 }
13086 
13087 static dof_hdr_t *
dtrace_dof_copyin_from_proc(proc_t * p,user_addr_t uarg,int * errp)13088 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
13089 {
13090 	dof_hdr_t hdr, *dof;
13091 
13092 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
13093 
13094 	/*
13095 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
13096 	 */
13097 	if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
13098 		dtrace_dof_error(NULL, "failed to copyin DOF header");
13099 		*errp = EFAULT;
13100 		return (NULL);
13101 	}
13102 
13103 	/*
13104 	 * Now we'll allocate the entire DOF and copy it in -- provided
13105 	 * that the length isn't outrageous.
13106 	 */
13107 	if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13108 		dtrace_dof_error(&hdr, "load size exceeds maximum");
13109 		*errp = E2BIG;
13110 		return (NULL);
13111 	}
13112 
13113 	if (hdr.dofh_loadsz < sizeof (hdr)) {
13114 		dtrace_dof_error(&hdr, "invalid load size");
13115 		*errp = EINVAL;
13116 		return (NULL);
13117 	}
13118 
13119 	dof = kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
13120 
13121 	if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS ||
13122 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
13123 		kmem_free_aligned(dof, hdr.dofh_loadsz);
13124 		*errp = EFAULT;
13125 		return (NULL);
13126 	}
13127 
13128 	return (dof);
13129 }
13130 
13131 static void
dtrace_dof_destroy(dof_hdr_t * dof)13132 dtrace_dof_destroy(dof_hdr_t *dof)
13133 {
13134 	kmem_free_aligned(dof, dof->dofh_loadsz);
13135 }
13136 
13137 static dof_hdr_t *
dtrace_dof_property(const char * name)13138 dtrace_dof_property(const char *name)
13139 {
13140 	unsigned int len = 0;
13141 	dof_hdr_t *dof;
13142 
13143 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
13144 		return NULL;
13145 	}
13146 
13147 	if (!PEReadNVRAMProperty(name, NULL, &len)) {
13148 		return NULL;
13149 	}
13150 
13151 	dof = kmem_alloc_aligned(len, 8, KM_SLEEP);
13152 
13153 	if (!PEReadNVRAMProperty(name, dof, &len)) {
13154 		dtrace_dof_destroy(dof);
13155 		dtrace_dof_error(NULL, "unreadable DOF");
13156 		return NULL;
13157 	}
13158 
13159 	if (len < sizeof (dof_hdr_t)) {
13160 		dtrace_dof_destroy(dof);
13161 		dtrace_dof_error(NULL, "truncated header");
13162 		return (NULL);
13163 	}
13164 
13165 	if (len < dof->dofh_loadsz) {
13166 		dtrace_dof_destroy(dof);
13167 		dtrace_dof_error(NULL, "truncated DOF");
13168 		return (NULL);
13169 	}
13170 
13171 	if (len != dof->dofh_loadsz) {
13172 		dtrace_dof_destroy(dof);
13173 		dtrace_dof_error(NULL, "invalid DOF size");
13174 		return (NULL);
13175 	}
13176 
13177 	if (dof->dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
13178 		dtrace_dof_destroy(dof);
13179 		dtrace_dof_error(NULL, "oversized DOF");
13180 		return (NULL);
13181 	}
13182 
13183 	return (dof);
13184 }
13185 
13186 /*
13187  * Return the dof_sec_t pointer corresponding to a given section index.  If the
13188  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
13189  * a type other than DOF_SECT_NONE is specified, the header is checked against
13190  * this type and NULL is returned if the types do not match.
13191  */
13192 static dof_sec_t *
dtrace_dof_sect(dof_hdr_t * dof,uint32_t type,dof_secidx_t i)13193 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13194 {
13195 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13196 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13197 
13198 	if (i >= dof->dofh_secnum) {
13199 		dtrace_dof_error(dof, "referenced section index is invalid");
13200 		return (NULL);
13201 	}
13202 
13203 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13204 		dtrace_dof_error(dof, "referenced section is not loadable");
13205 		return (NULL);
13206 	}
13207 
13208 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13209 		dtrace_dof_error(dof, "referenced section is the wrong type");
13210 		return (NULL);
13211 	}
13212 
13213 	return (sec);
13214 }
13215 
13216 static dtrace_probedesc_t *
dtrace_dof_probedesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_probedesc_t * desc)13217 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13218 {
13219 	dof_probedesc_t *probe;
13220 	dof_sec_t *strtab;
13221 	uintptr_t daddr = (uintptr_t)dof;
13222 	uintptr_t str;
13223 	size_t size;
13224 
13225 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13226 		dtrace_dof_error(dof, "invalid probe section");
13227 		return (NULL);
13228 	}
13229 
13230 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13231 		dtrace_dof_error(dof, "bad alignment in probe description");
13232 		return (NULL);
13233 	}
13234 
13235 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13236 		dtrace_dof_error(dof, "truncated probe description");
13237 		return (NULL);
13238 	}
13239 
13240 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13241 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13242 
13243 	if (strtab == NULL)
13244 		return (NULL);
13245 
13246 	str = daddr + strtab->dofs_offset;
13247 	size = strtab->dofs_size;
13248 
13249 	if (probe->dofp_provider >= strtab->dofs_size) {
13250 		dtrace_dof_error(dof, "corrupt probe provider");
13251 		return (NULL);
13252 	}
13253 
13254 	(void) strncpy(desc->dtpd_provider,
13255 	    (char *)(str + probe->dofp_provider),
13256 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13257 
13258 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13259 	desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13260 
13261 	if (probe->dofp_mod >= strtab->dofs_size) {
13262 		dtrace_dof_error(dof, "corrupt probe module");
13263 		return (NULL);
13264 	}
13265 
13266 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13267 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13268 
13269 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13270 	desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13271 
13272 	if (probe->dofp_func >= strtab->dofs_size) {
13273 		dtrace_dof_error(dof, "corrupt probe function");
13274 		return (NULL);
13275 	}
13276 
13277 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13278 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13279 
13280 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13281 	desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13282 
13283 	if (probe->dofp_name >= strtab->dofs_size) {
13284 		dtrace_dof_error(dof, "corrupt probe name");
13285 		return (NULL);
13286 	}
13287 
13288 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13289 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13290 
13291 	/* APPLE NOTE: Darwin employs size bounded string operation. */
13292 	desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13293 
13294 	return (desc);
13295 }
13296 
13297 static dtrace_difo_t *
dtrace_dof_difo(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13298 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13299     cred_t *cr)
13300 {
13301 	dtrace_difo_t *dp;
13302 	size_t ttl = 0;
13303 	dof_difohdr_t *dofd;
13304 	uintptr_t daddr = (uintptr_t)dof;
13305 	size_t max_size = dtrace_difo_maxsize;
13306 	uint_t i;
13307 	int l, n;
13308 
13309 
13310 	static const struct {
13311 		int section;
13312 		int bufoffs;
13313 		int lenoffs;
13314 		int entsize;
13315 		int align;
13316 		const char *msg;
13317 	} difo[] = {
13318 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13319 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13320 		sizeof (dif_instr_t), "multiple DIF sections" },
13321 
13322 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13323 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13324 		sizeof (uint64_t), "multiple integer tables" },
13325 
13326 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13327 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
13328 		sizeof (char), "multiple string tables" },
13329 
13330 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13331 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13332 		sizeof (uint_t), "multiple variable tables" },
13333 
13334 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13335 	};
13336 
13337 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13338 		dtrace_dof_error(dof, "invalid DIFO header section");
13339 		return (NULL);
13340 	}
13341 
13342 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
13343 		dtrace_dof_error(dof, "bad alignment in DIFO header");
13344 		return (NULL);
13345 	}
13346 
13347 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13348 	    sec->dofs_size % sizeof (dof_secidx_t)) {
13349 		dtrace_dof_error(dof, "bad size in DIFO header");
13350 		return (NULL);
13351 	}
13352 
13353 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13354 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13355 
13356 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13357 	dp->dtdo_rtype = dofd->dofd_rtype;
13358 
13359 	for (l = 0; l < n; l++) {
13360 		dof_sec_t *subsec;
13361 		void **bufp;
13362 		uint32_t *lenp;
13363 
13364 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13365 		    dofd->dofd_links[l])) == NULL)
13366 			goto err; /* invalid section link */
13367 
13368 		if (ttl + subsec->dofs_size > max_size) {
13369 			dtrace_dof_error(dof, "exceeds maximum size");
13370 			goto err;
13371 		}
13372 
13373 		ttl += subsec->dofs_size;
13374 
13375 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13376 
13377 			if (subsec->dofs_type != (uint32_t)difo[i].section)
13378 				continue;
13379 
13380 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13381 				dtrace_dof_error(dof, "section not loaded");
13382 				goto err;
13383 			}
13384 
13385 			if (subsec->dofs_align != (uint32_t)difo[i].align) {
13386 				dtrace_dof_error(dof, "bad alignment");
13387 				goto err;
13388 			}
13389 
13390 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13391 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13392 
13393 			if (*bufp != NULL) {
13394 				dtrace_dof_error(dof, difo[i].msg);
13395 				goto err;
13396 			}
13397 
13398 			if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
13399 				dtrace_dof_error(dof, "entry size mismatch");
13400 				goto err;
13401 			}
13402 
13403 			if (subsec->dofs_entsize != 0 &&
13404 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13405 				dtrace_dof_error(dof, "corrupt entry size");
13406 				goto err;
13407 			}
13408 
13409 			*lenp = subsec->dofs_size;
13410 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13411 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13412 			    *bufp, subsec->dofs_size);
13413 
13414 			if (subsec->dofs_entsize != 0)
13415 				*lenp /= subsec->dofs_entsize;
13416 
13417 			break;
13418 		}
13419 
13420 		/*
13421 		 * If we encounter a loadable DIFO sub-section that is not
13422 		 * known to us, assume this is a broken program and fail.
13423 		 */
13424 		if (difo[i].section == DOF_SECT_NONE &&
13425 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
13426 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
13427 			goto err;
13428 		}
13429 	}
13430 
13431 	if (dp->dtdo_buf == NULL) {
13432 		/*
13433 		 * We can't have a DIF object without DIF text.
13434 		 */
13435 		dtrace_dof_error(dof, "missing DIF text");
13436 		goto err;
13437 	}
13438 
13439 	/*
13440 	 * Before we validate the DIF object, run through the variable table
13441 	 * looking for the strings -- if any of their size are under, we'll set
13442 	 * their size to be the system-wide default string size.  Note that
13443 	 * this should _not_ happen if the "strsize" option has been set --
13444 	 * in this case, the compiler should have set the size to reflect the
13445 	 * setting of the option.
13446 	 */
13447 	for (i = 0; i < dp->dtdo_varlen; i++) {
13448 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
13449 		dtrace_diftype_t *t = &v->dtdv_type;
13450 
13451 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13452 			continue;
13453 
13454 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13455 			t->dtdt_size = dtrace_strsize_default;
13456 	}
13457 
13458 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13459 		goto err;
13460 
13461 	dtrace_difo_init(dp, vstate);
13462 	return (dp);
13463 
13464 err:
13465 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13466 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13467 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13468 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13469 
13470 	kmem_free(dp, sizeof (dtrace_difo_t));
13471 	return (NULL);
13472 }
13473 
13474 static dtrace_predicate_t *
dtrace_dof_predicate(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13475 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13476     cred_t *cr)
13477 {
13478 	dtrace_difo_t *dp;
13479 
13480 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13481 		return (NULL);
13482 
13483 	return (dtrace_predicate_create(dp));
13484 }
13485 
13486 static dtrace_actdesc_t *
dtrace_dof_actdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13487 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13488     cred_t *cr)
13489 {
13490 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13491 	dof_actdesc_t *desc;
13492 	dof_sec_t *difosec;
13493 	size_t offs;
13494 	uintptr_t daddr = (uintptr_t)dof;
13495 	uint64_t arg;
13496 	dtrace_actkind_t kind;
13497 
13498 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13499 		dtrace_dof_error(dof, "invalid action section");
13500 		return (NULL);
13501 	}
13502 
13503 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13504 		dtrace_dof_error(dof, "truncated action description");
13505 		return (NULL);
13506 	}
13507 
13508 	if (sec->dofs_align != sizeof (uint64_t)) {
13509 		dtrace_dof_error(dof, "bad alignment in action description");
13510 		return (NULL);
13511 	}
13512 
13513 	if (sec->dofs_size < sec->dofs_entsize) {
13514 		dtrace_dof_error(dof, "section entry size exceeds total size");
13515 		return (NULL);
13516 	}
13517 
13518 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13519 		dtrace_dof_error(dof, "bad entry size in action description");
13520 		return (NULL);
13521 	}
13522 
13523 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13524 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13525 		return (NULL);
13526 	}
13527 
13528 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13529 		desc = (dof_actdesc_t *)(daddr +
13530 		    (uintptr_t)sec->dofs_offset + offs);
13531 		kind = (dtrace_actkind_t)desc->dofa_kind;
13532 
13533 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13534 		    (kind != DTRACEACT_PRINTA || desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13535 		    (kind == DTRACEACT_DIFEXPR && desc->dofa_strtab != DOF_SECIDX_NONE))
13536 		{
13537 			dof_sec_t *strtab;
13538 			char *str, *fmt;
13539 			uint64_t i;
13540 
13541 			/*
13542 			 * The argument to these actions is an index into the
13543 			 * DOF string table.  For printf()-like actions, this
13544 			 * is the format string.  For print(), this is the
13545 			 * CTF type of the expression result.
13546 			 */
13547 			if ((strtab = dtrace_dof_sect(dof,
13548 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13549 				goto err;
13550 
13551 			str = (char *)((uintptr_t)dof +
13552 			    (uintptr_t)strtab->dofs_offset);
13553 
13554 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13555 				if (str[i] == '\0')
13556 					break;
13557 			}
13558 
13559 			if (i >= strtab->dofs_size) {
13560 				dtrace_dof_error(dof, "bogus format string");
13561 				goto err;
13562 			}
13563 
13564 			if (i == desc->dofa_arg) {
13565 				dtrace_dof_error(dof, "empty format string");
13566 				goto err;
13567 			}
13568 
13569 			i -= desc->dofa_arg;
13570 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13571 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13572 			arg = (uint64_t)(uintptr_t)fmt;
13573 		} else {
13574 			if (kind == DTRACEACT_PRINTA) {
13575 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13576 				arg = 0;
13577 			} else {
13578 				arg = desc->dofa_arg;
13579 			}
13580 		}
13581 
13582 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13583 		    desc->dofa_uarg, arg);
13584 
13585 		if (last != NULL) {
13586 			last->dtad_next = act;
13587 		} else {
13588 			first = act;
13589 		}
13590 
13591 		last = act;
13592 
13593 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13594 			continue;
13595 
13596 		if ((difosec = dtrace_dof_sect(dof,
13597 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13598 			goto err;
13599 
13600 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13601 
13602 		if (act->dtad_difo == NULL)
13603 			goto err;
13604 	}
13605 
13606 	ASSERT(first != NULL);
13607 	return (first);
13608 
13609 err:
13610 	for (act = first; act != NULL; act = next) {
13611 		next = act->dtad_next;
13612 		dtrace_actdesc_release(act, vstate);
13613 	}
13614 
13615 	return (NULL);
13616 }
13617 
13618 static dtrace_ecbdesc_t *
dtrace_dof_ecbdesc(dof_hdr_t * dof,dof_sec_t * sec,dtrace_vstate_t * vstate,cred_t * cr)13619 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13620     cred_t *cr)
13621 {
13622 	dtrace_ecbdesc_t *ep;
13623 	dof_ecbdesc_t *ecb;
13624 	dtrace_probedesc_t *desc;
13625 	dtrace_predicate_t *pred = NULL;
13626 
13627 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13628 		dtrace_dof_error(dof, "truncated ECB description");
13629 		return (NULL);
13630 	}
13631 
13632 	if (sec->dofs_align != sizeof (uint64_t)) {
13633 		dtrace_dof_error(dof, "bad alignment in ECB description");
13634 		return (NULL);
13635 	}
13636 
13637 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13638 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13639 
13640 	if (sec == NULL)
13641 		return (NULL);
13642 
13643 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13644 	ep->dted_uarg = ecb->dofe_uarg;
13645 	desc = &ep->dted_probe;
13646 
13647 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13648 		goto err;
13649 
13650 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13651 		if ((sec = dtrace_dof_sect(dof,
13652 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13653 			goto err;
13654 
13655 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13656 			goto err;
13657 
13658 		ep->dted_pred.dtpdd_predicate = pred;
13659 	}
13660 
13661 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13662 		if ((sec = dtrace_dof_sect(dof,
13663 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13664 			goto err;
13665 
13666 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13667 
13668 		if (ep->dted_action == NULL)
13669 			goto err;
13670 	}
13671 
13672 	return (ep);
13673 
13674 err:
13675 	if (pred != NULL)
13676 		dtrace_predicate_release(pred, vstate);
13677 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13678 	return (NULL);
13679 }
13680 
13681 /*
13682  * APPLE NOTE: dyld handles dof relocation.
13683  * Darwin does not need dtrace_dof_relocate()
13684  */
13685 
13686 /*
13687  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13688  * header:  it should be at the front of a memory region that is at least
13689  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13690  * size.  It need not be validated in any other way.
13691  */
13692 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)13693 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13694     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13695 {
13696 #pragma unused(ubase) /* __APPLE__ */
13697 	uint64_t len = dof->dofh_loadsz, seclen;
13698 	uintptr_t daddr = (uintptr_t)dof;
13699 	dtrace_ecbdesc_t *ep;
13700 	dtrace_enabling_t *enab;
13701 	uint_t i;
13702 
13703 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13704 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13705 
13706 	/*
13707 	 * Check the DOF header identification bytes.  In addition to checking
13708 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13709 	 * we can use them later without fear of regressing existing binaries.
13710 	 */
13711 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13712 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13713 		dtrace_dof_error(dof, "DOF magic string mismatch");
13714 		return (-1);
13715 	}
13716 
13717 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13718 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13719 		dtrace_dof_error(dof, "DOF has invalid data model");
13720 		return (-1);
13721 	}
13722 
13723 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13724 		dtrace_dof_error(dof, "DOF encoding mismatch");
13725 		return (-1);
13726 	}
13727 
13728 	/*
13729 	 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
13730 	 */
13731 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
13732 		dtrace_dof_error(dof, "DOF version mismatch");
13733 		return (-1);
13734 	}
13735 
13736 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13737 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13738 		return (-1);
13739 	}
13740 
13741 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13742 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13743 		return (-1);
13744 	}
13745 
13746 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13747 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13748 		return (-1);
13749 	}
13750 
13751 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13752 		if (dof->dofh_ident[i] != 0) {
13753 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13754 			return (-1);
13755 		}
13756 	}
13757 
13758 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13759 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13760 		return (-1);
13761 	}
13762 
13763 	if (dof->dofh_secsize < sizeof(dof_sec_t)) {
13764 		dtrace_dof_error(dof, "invalid section header size");
13765 		return (-1);
13766 	}
13767 
13768 	/*
13769 	 * Check that the section headers don't exceed the amount of DOF
13770 	 * data.  Note that we cast the section size and number of sections
13771 	 * to uint64_t's to prevent possible overflow in the multiplication.
13772 	 */
13773 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13774 
13775 	if (dof->dofh_secoff > len || seclen > len ||
13776 	    dof->dofh_secoff + seclen > len) {
13777 		dtrace_dof_error(dof, "truncated section headers");
13778 		return (-1);
13779 	}
13780 
13781 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13782 		dtrace_dof_error(dof, "misaligned section headers");
13783 		return (-1);
13784 	}
13785 
13786 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13787 		dtrace_dof_error(dof, "misaligned section size");
13788 		return (-1);
13789 	}
13790 
13791 	/*
13792 	 * Take an initial pass through the section headers to be sure that
13793 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13794 	 * set, do not permit sections relating to providers, probes, or args.
13795 	 */
13796 	for (i = 0; i < dof->dofh_secnum; i++) {
13797 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13798 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13799 
13800 		if (noprobes) {
13801 			switch (sec->dofs_type) {
13802 			case DOF_SECT_PROVIDER:
13803 			case DOF_SECT_PROBES:
13804 			case DOF_SECT_PRARGS:
13805 			case DOF_SECT_PROFFS:
13806 				dtrace_dof_error(dof, "illegal sections "
13807 				    "for enabling");
13808 				return (-1);
13809 			}
13810 		}
13811 
13812 		if (sec->dofs_align & (sec->dofs_align - 1)) {
13813 			dtrace_dof_error(dof, "bad section alignment");
13814 			return (-1);
13815 		}
13816 
13817 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13818 			dtrace_dof_error(dof, "misaligned section");
13819 			return (-1);
13820 		}
13821 
13822 		if (sec->dofs_flags & DOF_SECF_LOAD) {
13823 			len = dof->dofh_loadsz;
13824 		} else {
13825 			len = dof->dofh_filesz;
13826 		}
13827 
13828 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13829 		    sec->dofs_offset + sec->dofs_size > len) {
13830 			dtrace_dof_error(dof, "corrupt section header");
13831 			return (-1);
13832 		}
13833 
13834 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13835 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13836 			dtrace_dof_error(dof, "non-terminating string table");
13837 			return (-1);
13838 		}
13839 	}
13840 
13841 	/*
13842 	 * APPLE NOTE: We have no further relocation to perform.
13843 	 * All dof values are relative offsets.
13844 	 */
13845 
13846 	if ((enab = *enabp) == NULL)
13847 		enab = *enabp = dtrace_enabling_create(vstate);
13848 
13849 	for (i = 0; i < dof->dofh_secnum; i++) {
13850 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13851 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13852 
13853 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13854 			continue;
13855 
13856 		/*
13857 		 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
13858 		 * not all paths out of inlined dtrace_dof_ecbdesc
13859 		 * are checked for the NULL return value.
13860 		 * Check for NULL explicitly here.
13861 		*/
13862 		ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
13863 		if (ep == NULL) {
13864 			dtrace_enabling_destroy(enab);
13865 			*enabp = NULL;
13866 			return (-1);
13867 		}
13868 
13869 		dtrace_enabling_add(enab, ep);
13870 	}
13871 
13872 	return (0);
13873 }
13874 
13875 /*
13876  * Process DOF for any options.  This routine assumes that the DOF has been
13877  * at least processed by dtrace_dof_slurp().
13878  */
13879 static int
dtrace_dof_options(dof_hdr_t * dof,dtrace_state_t * state)13880 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13881 {
13882 	uint_t i;
13883 	int rval;
13884 	uint32_t entsize;
13885 	size_t offs;
13886 	dof_optdesc_t *desc;
13887 
13888 	for (i = 0; i < dof->dofh_secnum; i++) {
13889 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13890 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13891 
13892 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13893 			continue;
13894 
13895 		if (sec->dofs_align != sizeof (uint64_t)) {
13896 			dtrace_dof_error(dof, "bad alignment in "
13897 			    "option description");
13898 			return (EINVAL);
13899 		}
13900 
13901 		if ((entsize = sec->dofs_entsize) == 0) {
13902 			dtrace_dof_error(dof, "zeroed option entry size");
13903 			return (EINVAL);
13904 		}
13905 
13906 		if (entsize < sizeof (dof_optdesc_t)) {
13907 			dtrace_dof_error(dof, "bad option entry size");
13908 			return (EINVAL);
13909 		}
13910 
13911 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13912 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13913 			    (uintptr_t)sec->dofs_offset + offs);
13914 
13915 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13916 				dtrace_dof_error(dof, "non-zero option string");
13917 				return (EINVAL);
13918 			}
13919 
13920 			if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
13921 				dtrace_dof_error(dof, "unset option");
13922 				return (EINVAL);
13923 			}
13924 
13925 			if ((rval = dtrace_state_option(state,
13926 			    desc->dofo_option, desc->dofo_value)) != 0) {
13927 				dtrace_dof_error(dof, "rejected option");
13928 				return (rval);
13929 			}
13930 		}
13931 	}
13932 
13933 	return (0);
13934 }
13935 
13936 /*
13937  * DTrace Consumer State Functions
13938  */
13939 static int
dtrace_dstate_init(dtrace_dstate_t * dstate,size_t size)13940 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13941 {
13942 	size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
13943 	void *base;
13944 	uintptr_t limit;
13945 	dtrace_dynvar_t *dvar, *next, *start;
13946 
13947 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13948 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13949 
13950 	bzero(dstate, sizeof (dtrace_dstate_t));
13951 
13952 	if ((dstate->dtds_chunksize = chunksize) == 0)
13953 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13954 
13955 	VERIFY(dstate->dtds_chunksize < (LONG_MAX - sizeof (dtrace_dynhash_t)));
13956 
13957 	if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13958 		size = min_size;
13959 
13960 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
13961 		return (ENOMEM);
13962 
13963 	dstate->dtds_size = size;
13964 	dstate->dtds_base = base;
13965 	dstate->dtds_percpu = zalloc_percpu(dtrace_state_pcpu_zone, Z_WAITOK | Z_ZERO);
13966 
13967 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13968 
13969 	if (hashsize != 1 && (hashsize & 1))
13970 		hashsize--;
13971 
13972 	dstate->dtds_hashsize = hashsize;
13973 	dstate->dtds_hash = dstate->dtds_base;
13974 
13975 	/*
13976 	 * Set all of our hash buckets to point to the single sink, and (if
13977 	 * it hasn't already been set), set the sink's hash value to be the
13978 	 * sink sentinel value.  The sink is needed for dynamic variable
13979 	 * lookups to know that they have iterated over an entire, valid hash
13980 	 * chain.
13981 	 */
13982 	for (size_t i = 0; i < hashsize; i++)
13983 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13984 
13985 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13986 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13987 
13988 	/*
13989 	 * Determine number of active CPUs.  Divide free list evenly among
13990 	 * active CPUs.
13991 	 */
13992 	start = (dtrace_dynvar_t *)
13993 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13994 	limit = (uintptr_t)base + size;
13995 
13996 	VERIFY((uintptr_t)start < limit);
13997 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13998 
13999 	maxper = (limit - (uintptr_t)start) / (int)NCPU;
14000 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14001 
14002 	zpercpu_foreach_cpu(i) {
14003 		dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, i);
14004 
14005 		dcpu->dtdsc_free = dvar = start;
14006 
14007 		/*
14008 		 * If we don't even have enough chunks to make it once through
14009 		 * NCPUs, we're just going to allocate everything to the first
14010 		 * CPU.  And if we're on the last CPU, we're going to allocate
14011 		 * whatever is left over.  In either case, we set the limit to
14012 		 * be the limit of the dynamic variable space.
14013 		 */
14014 		if (maxper == 0 || i == NCPU - 1) {
14015 			limit = (uintptr_t)base + size;
14016 			start = NULL;
14017 		} else {
14018 			limit = (uintptr_t)start + maxper;
14019 			start = (dtrace_dynvar_t *)limit;
14020 		}
14021 
14022 		VERIFY(limit <= (uintptr_t)base + size);
14023 
14024 		for (;;) {
14025 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14026 			    dstate->dtds_chunksize);
14027 
14028 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14029 				break;
14030 
14031 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14032 			    (uintptr_t)dvar <= (uintptr_t)base + size);
14033 			dvar->dtdv_next = next;
14034 			dvar = next;
14035 		}
14036 
14037 		if (maxper == 0)
14038 			break;
14039 	}
14040 
14041 	return (0);
14042 }
14043 
14044 static void
dtrace_dstate_fini(dtrace_dstate_t * dstate)14045 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14046 {
14047 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14048 
14049 	if (dstate->dtds_base == NULL)
14050 		return;
14051 
14052 	kmem_free(dstate->dtds_base, dstate->dtds_size);
14053 	zfree_percpu(dtrace_state_pcpu_zone, dstate->dtds_percpu);
14054 }
14055 
14056 static void
dtrace_vstate_fini(dtrace_vstate_t * vstate)14057 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14058 {
14059 	/*
14060 	 * Logical XOR, where are you?
14061 	 */
14062 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14063 
14064 	if (vstate->dtvs_nglobals > 0) {
14065 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14066 		    sizeof (dtrace_statvar_t *));
14067 	}
14068 
14069 	if (vstate->dtvs_ntlocals > 0) {
14070 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14071 		    sizeof (dtrace_difv_t));
14072 	}
14073 
14074 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14075 
14076 	if (vstate->dtvs_nlocals > 0) {
14077 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14078 		    sizeof (dtrace_statvar_t *));
14079 	}
14080 }
14081 
14082 static void
dtrace_state_clean(dtrace_state_t * state)14083 dtrace_state_clean(dtrace_state_t *state)
14084 {
14085 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14086 		return;
14087 
14088 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14089 	dtrace_speculation_clean(state);
14090 }
14091 
14092 static void
dtrace_state_deadman(dtrace_state_t * state)14093 dtrace_state_deadman(dtrace_state_t *state)
14094 {
14095 	hrtime_t now;
14096 
14097 	dtrace_sync();
14098 
14099 	now = dtrace_gethrtime();
14100 
14101 	if (state != dtrace_anon.dta_state &&
14102 	    now - state->dts_laststatus >= dtrace_deadman_user)
14103 		return;
14104 
14105 	/*
14106 	 * We must be sure that dts_alive never appears to be less than the
14107 	 * value upon entry to dtrace_state_deadman(), and because we lack a
14108 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
14109 	 * store INT64_MAX to it, followed by a memory barrier, followed by
14110 	 * the new value.  This assures that dts_alive never appears to be
14111 	 * less than its true value, regardless of the order in which the
14112 	 * stores to the underlying storage are issued.
14113 	 */
14114 	state->dts_alive = INT64_MAX;
14115 	dtrace_membar_producer();
14116 	state->dts_alive = now;
14117 }
14118 
14119 static int
dtrace_state_create(dev_t * devp,cred_t * cr,dtrace_state_t ** new_state)14120 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
14121 {
14122 	minor_t minor;
14123 	major_t major;
14124 	char c[30];
14125 	dtrace_state_t *state;
14126 	dtrace_optval_t *opt;
14127 	int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
14128 	unsigned int cpu_it;
14129 
14130 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14131 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14132 
14133 	/* Cause restart */
14134 	*new_state = NULL;
14135 
14136 	if (devp != NULL) {
14137 		minor = getminor(*devp);
14138 	}
14139 	else {
14140 		minor = DTRACE_NCLIENTS - 1;
14141 	}
14142 
14143 	state = dtrace_state_allocate(minor);
14144 	if (NULL == state) {
14145 		printf("dtrace_open: couldn't acquire minor number %d. This usually means that too many DTrace clients are in use at the moment", minor);
14146 		return (ERESTART);	/* can't reacquire */
14147 	}
14148 
14149 	state->dts_epid = DTRACE_EPIDNONE + 1;
14150 
14151 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
14152 	state->dts_aggid_arena = vmem_create(c, (void *)1, INT32_MAX, 1,
14153 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14154 
14155 	if (devp != NULL) {
14156 		major = getemajor(*devp);
14157 	} else {
14158 		major = ddi_driver_major(dtrace_devi);
14159 	}
14160 
14161 	state->dts_dev = makedev(major, minor);
14162 
14163 	if (devp != NULL)
14164 		*devp = state->dts_dev;
14165 
14166 	/*
14167 	 * We allocate NCPU buffers.  On the one hand, this can be quite
14168 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
14169 	 * other hand, it saves an additional memory reference in the probe
14170 	 * path.
14171 	 */
14172 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14173 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14174 	state->dts_buf_over_limit = 0;
14175 
14176 	/*
14177          * Allocate and initialise the per-process per-CPU random state.
14178 	 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14179          * assumed to be seeded at this point (if from Fortuna seed file).
14180 	 */
14181 	state->dts_rstate = kmem_zalloc(NCPU * sizeof(uint64_t*), KM_SLEEP);
14182 	state->dts_rstate[0] = kmem_zalloc(2 * sizeof(uint64_t), KM_SLEEP);
14183 	(void) read_random(state->dts_rstate[0], 2 * sizeof(uint64_t));
14184 	for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14185 		state->dts_rstate[cpu_it] = kmem_zalloc(2 * sizeof(uint64_t), KM_SLEEP);
14186 		/*
14187 		 * Each CPU is assigned a 2^64 period, non-overlapping
14188 		 * subsequence.
14189 		 */
14190 		dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14191 		    state->dts_rstate[cpu_it]);
14192 	}
14193 
14194 	state->dts_cleaner = CYCLIC_NONE;
14195 	state->dts_deadman = CYCLIC_NONE;
14196 	state->dts_vstate.dtvs_state = state;
14197 
14198 	for (i = 0; i < DTRACEOPT_MAX; i++)
14199 		state->dts_options[i] = DTRACEOPT_UNSET;
14200 
14201 	/*
14202 	 * Set the default options.
14203 	 */
14204 	opt = state->dts_options;
14205 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14206 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14207 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14208 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14209 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14210 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14211 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14212 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14213 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14214 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14215 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14216 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14217 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14218 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14219 	opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_default;
14220 
14221 	/*
14222 	 * Depending on the user credentials, we set flag bits which alter probe
14223 	 * visibility or the amount of destructiveness allowed.  In the case of
14224 	 * actual anonymous tracing, or the possession of all privileges, all of
14225 	 * the normal checks are bypassed.
14226 	 */
14227 #if defined(__APPLE__)
14228 	if (cr != NULL) {
14229 		kauth_cred_ref(cr);
14230 		state->dts_cred.dcr_cred = cr;
14231 	}
14232 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14233 		if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
14234 			/*
14235 			 * Allow only proc credentials when DTrace is
14236 			 * restricted by the current security policy
14237 			 */
14238 			state->dts_cred.dcr_visible = DTRACE_CRV_ALLPROC;
14239 			state->dts_cred.dcr_action = DTRACE_CRA_PROC | DTRACE_CRA_PROC_CONTROL | DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14240 		}
14241 		else {
14242 			state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14243 			state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14244 		}
14245 	}
14246 
14247 #else
14248 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14249 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14250 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14251 	}
14252 	else {
14253 		/*
14254 		 * Set up the credentials for this instantiation.  We take a
14255 		 * hold on the credential to prevent it from disappearing on
14256 		 * us; this in turn prevents the zone_t referenced by this
14257 		 * credential from disappearing.  This means that we can
14258 		 * examine the credential and the zone from probe context.
14259 		 */
14260 		crhold(cr);
14261 		state->dts_cred.dcr_cred = cr;
14262 
14263 		/*
14264 		 * CRA_PROC means "we have *some* privilege for dtrace" and
14265 		 * unlocks the use of variables like pid, zonename, etc.
14266 		 */
14267 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14268 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14269 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14270 		}
14271 
14272 		/*
14273 		 * dtrace_user allows use of syscall and profile providers.
14274 		 * If the user also has proc_owner and/or proc_zone, we
14275 		 * extend the scope to include additional visibility and
14276 		 * destructive power.
14277 		 */
14278 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14279 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14280 				state->dts_cred.dcr_visible |=
14281 				    DTRACE_CRV_ALLPROC;
14282 
14283 				state->dts_cred.dcr_action |=
14284 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14285 			}
14286 
14287 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14288 				state->dts_cred.dcr_visible |=
14289 				    DTRACE_CRV_ALLZONE;
14290 
14291 				state->dts_cred.dcr_action |=
14292 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14293 			}
14294 
14295 			/*
14296 			 * If we have all privs in whatever zone this is,
14297 			 * we can do destructive things to processes which
14298 			 * have altered credentials.
14299 			 *
14300 			 * APPLE NOTE: Darwin doesn't do zones.
14301 			 * Behave as if zone always has destructive privs.
14302 			 */
14303 
14304 			state->dts_cred.dcr_action |=
14305 				DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14306 		}
14307 
14308 		/*
14309 		 * Holding the dtrace_kernel privilege also implies that
14310 		 * the user has the dtrace_user privilege from a visibility
14311 		 * perspective.  But without further privileges, some
14312 		 * destructive actions are not available.
14313 		 */
14314 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14315 			/*
14316 			 * Make all probes in all zones visible.  However,
14317 			 * this doesn't mean that all actions become available
14318 			 * to all zones.
14319 			 */
14320 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14321 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14322 
14323 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14324 			    DTRACE_CRA_PROC;
14325 			/*
14326 			 * Holding proc_owner means that destructive actions
14327 			 * for *this* zone are allowed.
14328 			 */
14329 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14330 				state->dts_cred.dcr_action |=
14331 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14332 
14333 			/*
14334 			 * Holding proc_zone means that destructive actions
14335 			 * for this user/group ID in all zones is allowed.
14336 			 */
14337 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14338 				state->dts_cred.dcr_action |=
14339 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14340 
14341 			/*
14342 			 * If we have all privs in whatever zone this is,
14343 			 * we can do destructive things to processes which
14344 			 * have altered credentials.
14345 			 *
14346 			 * APPLE NOTE: Darwin doesn't do zones.
14347 			 * Behave as if zone always has destructive privs.
14348 			 */
14349 			state->dts_cred.dcr_action |=
14350 				DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14351 		}
14352 
14353 		/*
14354 		 * Holding the dtrace_proc privilege gives control over fasttrap
14355 		 * and pid providers.  We need to grant wider destructive
14356 		 * privileges in the event that the user has proc_owner and/or
14357 		 * proc_zone.
14358 		 */
14359 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14360 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14361 				state->dts_cred.dcr_action |=
14362 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14363 
14364 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14365 				state->dts_cred.dcr_action |=
14366 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14367 		}
14368 	}
14369 #endif
14370 
14371 	*new_state = state;
14372 	return(0);  /* Success */
14373 }
14374 
14375 static int
dtrace_state_buffer(dtrace_state_t * state,dtrace_buffer_t * buf,int which)14376 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14377 {
14378 	dtrace_optval_t *opt = state->dts_options, size;
14379 	processorid_t cpu = 0;
14380 	size_t limit = buf->dtb_size;
14381 	int flags = 0, rval;
14382 
14383 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14384 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14385 	ASSERT(which < DTRACEOPT_MAX);
14386 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14387 	    (state == dtrace_anon.dta_state &&
14388 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14389 
14390 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14391 		return (0);
14392 
14393 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14394 		cpu = opt[DTRACEOPT_CPU];
14395 
14396 	if (which == DTRACEOPT_SPECSIZE)
14397 		flags |= DTRACEBUF_NOSWITCH;
14398 
14399 	if (which == DTRACEOPT_BUFSIZE) {
14400 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14401 			flags |= DTRACEBUF_RING;
14402 
14403 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14404 			flags |= DTRACEBUF_FILL;
14405 
14406 		if (state != dtrace_anon.dta_state ||
14407 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14408 			flags |= DTRACEBUF_INACTIVE;
14409 	}
14410 
14411 	for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
14412 		/*
14413 		 * The size must be 8-byte aligned.  If the size is not 8-byte
14414 		 * aligned, drop it down by the difference.
14415 		 */
14416 		if (size & (sizeof (uint64_t) - 1))
14417 			size -= size & (sizeof (uint64_t) - 1);
14418 
14419 		if (size < state->dts_reserve) {
14420 			/*
14421 			 * Buffers always must be large enough to accommodate
14422 			 * their prereserved space.  We return E2BIG instead
14423 			 * of ENOMEM in this case to allow for user-level
14424 			 * software to differentiate the cases.
14425 			 */
14426 			return (E2BIG);
14427 		}
14428 		limit = opt[DTRACEOPT_BUFLIMIT] * size / 100;
14429 		rval = dtrace_buffer_alloc(buf, limit, size, flags, cpu);
14430 
14431 		if (rval != ENOMEM) {
14432 			opt[which] = size;
14433 			return (rval);
14434 		}
14435 
14436 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14437 			return (rval);
14438 	}
14439 
14440 	return (ENOMEM);
14441 }
14442 
14443 static int
dtrace_state_buffers(dtrace_state_t * state)14444 dtrace_state_buffers(dtrace_state_t *state)
14445 {
14446 	dtrace_speculation_t *spec = state->dts_speculations;
14447 	int rval, i;
14448 
14449 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14450 	    DTRACEOPT_BUFSIZE)) != 0)
14451 		return (rval);
14452 
14453 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14454 	    DTRACEOPT_AGGSIZE)) != 0)
14455 		return (rval);
14456 
14457 	for (i = 0; i < state->dts_nspeculations; i++) {
14458 		if ((rval = dtrace_state_buffer(state,
14459 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14460 			return (rval);
14461 	}
14462 
14463 	return (0);
14464 }
14465 
14466 static void
dtrace_state_prereserve(dtrace_state_t * state)14467 dtrace_state_prereserve(dtrace_state_t *state)
14468 {
14469 	dtrace_ecb_t *ecb;
14470 	dtrace_probe_t *probe;
14471 
14472 	state->dts_reserve = 0;
14473 
14474 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14475 		return;
14476 
14477 	/*
14478 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14479 	 * prereserved space to be the space required by the END probes.
14480 	 */
14481 	probe = dtrace_probes[dtrace_probeid_end - 1];
14482 	ASSERT(probe != NULL);
14483 
14484 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14485 		if (ecb->dte_state != state)
14486 			continue;
14487 
14488 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14489 	}
14490 }
14491 
14492 static int
dtrace_state_go(dtrace_state_t * state,processorid_t * cpu)14493 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14494 {
14495 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14496 	dtrace_speculation_t *spec;
14497 	dtrace_buffer_t *buf;
14498 	cyc_handler_t hdlr;
14499 	cyc_time_t when;
14500 	int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14501 	dtrace_icookie_t cookie;
14502 
14503 	lck_mtx_lock(&cpu_lock);
14504 	lck_mtx_lock(&dtrace_lock);
14505 
14506 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14507 		rval = EBUSY;
14508 		goto out;
14509 	}
14510 
14511 	/*
14512 	 * Before we can perform any checks, we must prime all of the
14513 	 * retained enablings that correspond to this state.
14514 	 */
14515 	dtrace_enabling_prime(state);
14516 
14517 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14518 		rval = EACCES;
14519 		goto out;
14520 	}
14521 
14522 	dtrace_state_prereserve(state);
14523 
14524 	/*
14525 	 * Now we want to do is try to allocate our speculations.
14526 	 * We do not automatically resize the number of speculations; if
14527 	 * this fails, we will fail the operation.
14528 	 */
14529 	nspec = opt[DTRACEOPT_NSPEC];
14530 	ASSERT(nspec != DTRACEOPT_UNSET);
14531 
14532 	if (nspec > INT_MAX) {
14533 		rval = ENOMEM;
14534 		goto out;
14535 	}
14536 
14537 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
14538 
14539 	if (spec == NULL) {
14540 		rval = ENOMEM;
14541 		goto out;
14542 	}
14543 
14544 	state->dts_speculations = spec;
14545 	state->dts_nspeculations = (int)nspec;
14546 
14547 	for (i = 0; i < nspec; i++) {
14548 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
14549 			rval = ENOMEM;
14550 			goto err;
14551 		}
14552 
14553 		spec[i].dtsp_buffer = buf;
14554 	}
14555 
14556 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14557 		if (dtrace_anon.dta_state == NULL) {
14558 			rval = ENOENT;
14559 			goto out;
14560 		}
14561 
14562 		if (state->dts_necbs != 0) {
14563 			rval = EALREADY;
14564 			goto out;
14565 		}
14566 
14567 		state->dts_anon = dtrace_anon_grab();
14568 		ASSERT(state->dts_anon != NULL);
14569 		state = state->dts_anon;
14570 
14571 		/*
14572 		 * We want "grabanon" to be set in the grabbed state, so we'll
14573 		 * copy that option value from the grabbing state into the
14574 		 * grabbed state.
14575 		 */
14576 		state->dts_options[DTRACEOPT_GRABANON] =
14577 		    opt[DTRACEOPT_GRABANON];
14578 
14579 		*cpu = dtrace_anon.dta_beganon;
14580 
14581 		/*
14582 		 * If the anonymous state is active (as it almost certainly
14583 		 * is if the anonymous enabling ultimately matched anything),
14584 		 * we don't allow any further option processing -- but we
14585 		 * don't return failure.
14586 		 */
14587 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14588 			goto out;
14589 	}
14590 
14591 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14592 	    opt[DTRACEOPT_AGGSIZE] != 0) {
14593 		if (state->dts_aggregations == NULL) {
14594 			/*
14595 			 * We're not going to create an aggregation buffer
14596 			 * because we don't have any ECBs that contain
14597 			 * aggregations -- set this option to 0.
14598 			 */
14599 			opt[DTRACEOPT_AGGSIZE] = 0;
14600 		} else {
14601 			/*
14602 			 * If we have an aggregation buffer, we must also have
14603 			 * a buffer to use as scratch.
14604 			 */
14605 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14606 			  (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14607 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14608 			}
14609 		}
14610 	}
14611 
14612 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14613 	    opt[DTRACEOPT_SPECSIZE] != 0) {
14614 		if (!state->dts_speculates) {
14615 			/*
14616 			 * We're not going to create speculation buffers
14617 			 * because we don't have any ECBs that actually
14618 			 * speculate -- set the speculation size to 0.
14619 			 */
14620 			opt[DTRACEOPT_SPECSIZE] = 0;
14621 		}
14622 	}
14623 
14624 	/*
14625 	 * The bare minimum size for any buffer that we're actually going to
14626 	 * do anything to is sizeof (uint64_t).
14627 	 */
14628 	sz = sizeof (uint64_t);
14629 
14630 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14631 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14632 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14633 		/*
14634 		 * A buffer size has been explicitly set to 0 (or to a size
14635 		 * that will be adjusted to 0) and we need the space -- we
14636 		 * need to return failure.  We return ENOSPC to differentiate
14637 		 * it from failing to allocate a buffer due to failure to meet
14638 		 * the reserve (for which we return E2BIG).
14639 		 */
14640 		rval = ENOSPC;
14641 		goto out;
14642 	}
14643 
14644 	if ((rval = dtrace_state_buffers(state)) != 0)
14645 		goto err;
14646 
14647 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14648 		sz = dtrace_dstate_defsize;
14649 
14650 	do {
14651 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14652 
14653 		if (rval == 0)
14654 			break;
14655 
14656 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14657 			goto err;
14658 	} while (sz >>= 1);
14659 
14660 	opt[DTRACEOPT_DYNVARSIZE] = sz;
14661 
14662 	if (rval != 0)
14663 		goto err;
14664 
14665 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14666 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14667 
14668 	if (opt[DTRACEOPT_CLEANRATE] == 0)
14669 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14670 
14671 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14672 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14673 
14674 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14675 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14676 
14677 	if (opt[DTRACEOPT_STRSIZE] > dtrace_strsize_max)
14678 		opt[DTRACEOPT_STRSIZE] = dtrace_strsize_max;
14679 
14680 	if (opt[DTRACEOPT_STRSIZE] < dtrace_strsize_min)
14681 		opt[DTRACEOPT_STRSIZE] = dtrace_strsize_min;
14682 
14683 	if (opt[DTRACEOPT_BUFLIMIT] > dtrace_buflimit_max)
14684 		opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_max;
14685 
14686 	if (opt[DTRACEOPT_BUFLIMIT] < dtrace_buflimit_min)
14687 		opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_min;
14688 
14689 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14690 	hdlr.cyh_arg = state;
14691 	hdlr.cyh_level = CY_LOW_LEVEL;
14692 
14693 	when.cyt_when = 0;
14694 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14695 
14696 	state->dts_cleaner = cyclic_add(&hdlr, &when);
14697 
14698 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14699 	hdlr.cyh_arg = state;
14700 	hdlr.cyh_level = CY_LOW_LEVEL;
14701 
14702 	when.cyt_when = 0;
14703 	when.cyt_interval = dtrace_deadman_interval;
14704 
14705 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14706 	state->dts_deadman = cyclic_add(&hdlr, &when);
14707 
14708 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14709 
14710 	/*
14711 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14712 	 * interrupts here both to record the CPU on which we fired the BEGIN
14713 	 * probe (the data from this CPU will be processed first at user
14714 	 * level) and to manually activate the buffer for this CPU.
14715 	 */
14716 	cookie = dtrace_interrupt_disable();
14717 	*cpu = CPU->cpu_id;
14718 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14719 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14720 
14721 	dtrace_probe(dtrace_probeid_begin,
14722 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14723 	dtrace_interrupt_enable(cookie);
14724 	/*
14725 	 * We may have had an exit action from a BEGIN probe; only change our
14726 	 * state to ACTIVE if we're still in WARMUP.
14727 	 */
14728 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14729 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14730 
14731 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14732 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14733 
14734 	/*
14735 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14736 	 * want each CPU to transition its principal buffer out of the
14737 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14738 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14739 	 * atomically transition from processing none of a state's ECBs to
14740 	 * processing all of them.
14741 	 */
14742 	dtrace_xcall(DTRACE_CPUALL,
14743 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14744 	goto out;
14745 
14746 err:
14747 	dtrace_buffer_free(state->dts_buffer);
14748 	dtrace_buffer_free(state->dts_aggbuffer);
14749 
14750 	if ((nspec = state->dts_nspeculations) == 0) {
14751 		ASSERT(state->dts_speculations == NULL);
14752 		goto out;
14753 	}
14754 
14755 	spec = state->dts_speculations;
14756 	ASSERT(spec != NULL);
14757 
14758 	for (i = 0; i < state->dts_nspeculations; i++) {
14759 		if ((buf = spec[i].dtsp_buffer) == NULL)
14760 			break;
14761 
14762 		dtrace_buffer_free(buf);
14763 		kmem_free(buf, bufsize);
14764 	}
14765 
14766 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14767 	state->dts_nspeculations = 0;
14768 	state->dts_speculations = NULL;
14769 
14770 out:
14771 	lck_mtx_unlock(&dtrace_lock);
14772 	lck_mtx_unlock(&cpu_lock);
14773 
14774 	return (rval);
14775 }
14776 
14777 static int
dtrace_state_stop(dtrace_state_t * state,processorid_t * cpu)14778 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14779 {
14780 	dtrace_icookie_t cookie;
14781 
14782 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14783 
14784 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14785 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14786 		return (EINVAL);
14787 
14788 	/*
14789 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14790 	 * to be sure that every CPU has seen it.  See below for the details
14791 	 * on why this is done.
14792 	 */
14793 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14794 	dtrace_sync();
14795 
14796 	/*
14797 	 * By this point, it is impossible for any CPU to be still processing
14798 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14799 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14800 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14801 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14802 	 * iff we're in the END probe.
14803 	 */
14804 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14805 	dtrace_sync();
14806 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14807 
14808 	/*
14809 	 * Finally, we can release the reserve and call the END probe.  We
14810 	 * disable interrupts across calling the END probe to allow us to
14811 	 * return the CPU on which we actually called the END probe.  This
14812 	 * allows user-land to be sure that this CPU's principal buffer is
14813 	 * processed last.
14814 	 */
14815 	state->dts_reserve = 0;
14816 
14817 	cookie = dtrace_interrupt_disable();
14818 	*cpu = CPU->cpu_id;
14819 	dtrace_probe(dtrace_probeid_end,
14820 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14821 	dtrace_interrupt_enable(cookie);
14822 
14823 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14824 	dtrace_sync();
14825 
14826 	return (0);
14827 }
14828 
14829 static int
dtrace_state_option(dtrace_state_t * state,dtrace_optid_t option,dtrace_optval_t val)14830 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14831     dtrace_optval_t val)
14832 {
14833 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14834 
14835 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14836 		return (EBUSY);
14837 
14838 	if (option >= DTRACEOPT_MAX)
14839 		return (EINVAL);
14840 
14841 	if (option != DTRACEOPT_CPU && val < 0)
14842 		return (EINVAL);
14843 
14844 	switch (option) {
14845 	case DTRACEOPT_DESTRUCTIVE:
14846 		if (dtrace_destructive_disallow)
14847 			return (EACCES);
14848 
14849 		state->dts_cred.dcr_destructive = 1;
14850 		break;
14851 
14852 	case DTRACEOPT_BUFSIZE:
14853 	case DTRACEOPT_DYNVARSIZE:
14854 	case DTRACEOPT_AGGSIZE:
14855 	case DTRACEOPT_SPECSIZE:
14856 	case DTRACEOPT_STRSIZE:
14857 		if (val < 0)
14858 			return (EINVAL);
14859 
14860 		if (val >= LONG_MAX) {
14861 			/*
14862 			 * If this is an otherwise negative value, set it to
14863 			 * the highest multiple of 128m less than LONG_MAX.
14864 			 * Technically, we're adjusting the size without
14865 			 * regard to the buffer resizing policy, but in fact,
14866 			 * this has no effect -- if we set the buffer size to
14867 			 * ~LONG_MAX and the buffer policy is ultimately set to
14868 			 * be "manual", the buffer allocation is guaranteed to
14869 			 * fail, if only because the allocation requires two
14870 			 * buffers.  (We set the the size to the highest
14871 			 * multiple of 128m because it ensures that the size
14872 			 * will remain a multiple of a megabyte when
14873 			 * repeatedly halved -- all the way down to 15m.)
14874 			 */
14875 			val = LONG_MAX - (1 << 27) + 1;
14876 		}
14877 	}
14878 
14879 	state->dts_options[option] = val;
14880 
14881 	return (0);
14882 }
14883 
14884 static void
dtrace_state_destroy(dtrace_state_t * state)14885 dtrace_state_destroy(dtrace_state_t *state)
14886 {
14887 	dtrace_ecb_t *ecb;
14888 	dtrace_vstate_t *vstate = &state->dts_vstate;
14889 	minor_t minor = getminor(state->dts_dev);
14890 	int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14891 	dtrace_speculation_t *spec = state->dts_speculations;
14892 	int nspec = state->dts_nspeculations;
14893 	uint32_t match;
14894 
14895 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14896 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14897 
14898 	/*
14899 	 * First, retract any retained enablings for this state.
14900 	 */
14901 	dtrace_enabling_retract(state);
14902 	ASSERT(state->dts_nretained == 0);
14903 
14904 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14905 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14906 		/*
14907 		 * We have managed to come into dtrace_state_destroy() on a
14908 		 * hot enabling -- almost certainly because of a disorderly
14909 		 * shutdown of a consumer.  (That is, a consumer that is
14910 		 * exiting without having called dtrace_stop().) In this case,
14911 		 * we're going to set our activity to be KILLED, and then
14912 		 * issue a sync to be sure that everyone is out of probe
14913 		 * context before we start blowing away ECBs.
14914 		 */
14915 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14916 		dtrace_sync();
14917 	}
14918 
14919 	/*
14920 	 * Release the credential hold we took in dtrace_state_create().
14921 	 */
14922 	if (state->dts_cred.dcr_cred != NULL)
14923 		kauth_cred_unref(&state->dts_cred.dcr_cred);
14924 
14925 	/*
14926 	 * Now we can safely disable and destroy any enabled probes.  Because
14927 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14928 	 * (especially if they're all enabled), we take two passes through the
14929 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14930 	 * in the second we disable whatever is left over.
14931 	 */
14932 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14933 		for (i = 0; i < state->dts_necbs; i++) {
14934 			if ((ecb = state->dts_ecbs[i]) == NULL)
14935 				continue;
14936 
14937 			if (match && ecb->dte_probe != NULL) {
14938 				dtrace_probe_t *probe = ecb->dte_probe;
14939 				dtrace_provider_t *prov = probe->dtpr_provider;
14940 
14941 				if (!(prov->dtpv_priv.dtpp_flags & match))
14942 					continue;
14943 			}
14944 
14945 			dtrace_ecb_disable(ecb);
14946 			dtrace_ecb_destroy(ecb);
14947 		}
14948 
14949 		if (!match)
14950 			break;
14951 	}
14952 
14953 	/*
14954 	 * Before we free the buffers, perform one more sync to assure that
14955 	 * every CPU is out of probe context.
14956 	 */
14957 	dtrace_sync();
14958 
14959 	dtrace_buffer_free(state->dts_buffer);
14960 	dtrace_buffer_free(state->dts_aggbuffer);
14961 
14962 	for (i = 0; i < (int)NCPU; i++) {
14963 		kmem_free(state->dts_rstate[i], 2 * sizeof(uint64_t));
14964 	}
14965 	kmem_free(state->dts_rstate, NCPU * sizeof(uint64_t*));
14966 
14967 	for (i = 0; i < nspec; i++)
14968 		dtrace_buffer_free(spec[i].dtsp_buffer);
14969 
14970 	if (state->dts_cleaner != CYCLIC_NONE)
14971 		cyclic_remove(state->dts_cleaner);
14972 
14973 	if (state->dts_deadman != CYCLIC_NONE)
14974 		cyclic_remove(state->dts_deadman);
14975 
14976 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14977 	dtrace_vstate_fini(vstate);
14978 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14979 
14980 	if (state->dts_aggregations != NULL) {
14981 #if DEBUG
14982 		for (i = 0; i < state->dts_naggregations; i++)
14983 			ASSERT(state->dts_aggregations[i] == NULL);
14984 #endif
14985 		ASSERT(state->dts_naggregations > 0);
14986 		kmem_free(state->dts_aggregations,
14987 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14988 	}
14989 
14990 	kmem_free(state->dts_buffer, bufsize);
14991 	kmem_free(state->dts_aggbuffer, bufsize);
14992 
14993 	for (i = 0; i < nspec; i++)
14994 		kmem_free(spec[i].dtsp_buffer, bufsize);
14995 
14996 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14997 
14998 	dtrace_format_destroy(state);
14999 
15000 	vmem_destroy(state->dts_aggid_arena);
15001 	dtrace_state_free(minor);
15002 }
15003 
15004 /*
15005  * DTrace Anonymous Enabling Functions
15006  */
15007 
15008 int
dtrace_keep_kernel_symbols(void)15009 dtrace_keep_kernel_symbols(void)
15010 {
15011 	if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
15012 		return 0;
15013 	}
15014 
15015 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL)
15016 		return 1;
15017 
15018 	return 0;
15019 }
15020 
15021 static dtrace_state_t *
dtrace_anon_grab(void)15022 dtrace_anon_grab(void)
15023 {
15024 	dtrace_state_t *state;
15025 
15026 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15027 
15028 	if ((state = dtrace_anon.dta_state) == NULL) {
15029 		ASSERT(dtrace_anon.dta_enabling == NULL);
15030 		return (NULL);
15031 	}
15032 
15033 	ASSERT(dtrace_anon.dta_enabling != NULL);
15034 	ASSERT(dtrace_retained != NULL);
15035 
15036 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15037 	dtrace_anon.dta_enabling = NULL;
15038 	dtrace_anon.dta_state = NULL;
15039 
15040 	return (state);
15041 }
15042 
15043 static void
dtrace_anon_property(void)15044 dtrace_anon_property(void)
15045 {
15046 	int i, rv;
15047 	dtrace_state_t *state;
15048 	dof_hdr_t *dof;
15049 	char c[32];		/* enough for "dof-data-" + digits */
15050 
15051 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15052 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15053 
15054 	for (i = 0; ; i++) {
15055 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
15056 
15057 		dtrace_err_verbose = 1;
15058 
15059 		if ((dof = dtrace_dof_property(c)) == NULL) {
15060 			dtrace_err_verbose = 0;
15061 			break;
15062 		}
15063 
15064 #ifdef illumos
15065 		/*
15066 		 * We want to create anonymous state, so we need to transition
15067 		 * the kernel debugger to indicate that DTrace is active.  If
15068 		 * this fails (e.g. because the debugger has modified text in
15069 		 * some way), we won't continue with the processing.
15070 		 */
15071 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15072 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15073 			    "enabling ignored.");
15074 			dtrace_dof_destroy(dof);
15075 			break;
15076 		}
15077 #endif
15078 
15079 		/*
15080 		 * If we haven't allocated an anonymous state, we'll do so now.
15081 		 */
15082 		if ((state = dtrace_anon.dta_state) == NULL) {
15083 			rv = dtrace_state_create(NULL, NULL, &state);
15084 			dtrace_anon.dta_state = state;
15085 			if (rv != 0 || state == NULL) {
15086 				/*
15087 				 * This basically shouldn't happen:  the only
15088 				 * failure mode from dtrace_state_create() is a
15089 				 * failure of ddi_soft_state_zalloc() that
15090 				 * itself should never happen.  Still, the
15091 				 * interface allows for a failure mode, and
15092 				 * we want to fail as gracefully as possible:
15093 				 * we'll emit an error message and cease
15094 				 * processing anonymous state in this case.
15095 				 */
15096 				cmn_err(CE_WARN, "failed to create "
15097 				    "anonymous state");
15098 				dtrace_dof_destroy(dof);
15099 				break;
15100 			}
15101 		}
15102 
15103 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15104 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
15105 
15106 		if (rv == 0)
15107 			rv = dtrace_dof_options(dof, state);
15108 
15109 		dtrace_err_verbose = 0;
15110 		dtrace_dof_destroy(dof);
15111 
15112 		if (rv != 0) {
15113 			/*
15114 			 * This is malformed DOF; chuck any anonymous state
15115 			 * that we created.
15116 			 */
15117 			ASSERT(dtrace_anon.dta_enabling == NULL);
15118 			dtrace_state_destroy(state);
15119 			dtrace_anon.dta_state = NULL;
15120 			break;
15121 		}
15122 
15123 		ASSERT(dtrace_anon.dta_enabling != NULL);
15124 	}
15125 
15126 	if (dtrace_anon.dta_enabling != NULL) {
15127 		int rval;
15128 
15129 		/*
15130 		 * dtrace_enabling_retain() can only fail because we are
15131 		 * trying to retain more enablings than are allowed -- but
15132 		 * we only have one anonymous enabling, and we are guaranteed
15133 		 * to be allowed at least one retained enabling; we assert
15134 		 * that dtrace_enabling_retain() returns success.
15135 		 */
15136 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15137 		ASSERT(rval == 0);
15138 
15139 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
15140 	}
15141 }
15142 
15143 /*
15144  * DTrace Helper Functions
15145  */
15146 static void
dtrace_helper_trace(dtrace_helper_action_t * helper,dtrace_mstate_t * mstate,dtrace_vstate_t * vstate,int where)15147 dtrace_helper_trace(dtrace_helper_action_t *helper,
15148     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15149 {
15150 	uint32_t size, next, nnext;
15151 	int i;
15152 	dtrace_helptrace_t *ent;
15153 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
15154 
15155 	if (!dtrace_helptrace_enabled)
15156 		return;
15157 
15158 	ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15159 
15160 	/*
15161 	 * What would a tracing framework be without its own tracing
15162 	 * framework?  (Well, a hell of a lot simpler, for starters...)
15163 	 */
15164 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15165 	    sizeof (uint64_t) - sizeof (uint64_t);
15166 
15167 	/*
15168 	 * Iterate until we can allocate a slot in the trace buffer.
15169 	 */
15170 	do {
15171 		next = dtrace_helptrace_next;
15172 
15173 		if (next + size < dtrace_helptrace_bufsize) {
15174 			nnext = next + size;
15175 		} else {
15176 			nnext = size;
15177 		}
15178 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15179 
15180 	/*
15181 	 * We have our slot; fill it in.
15182 	 */
15183 	if (nnext == size)
15184 		next = 0;
15185 
15186 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
15187 	ent->dtht_helper = helper;
15188 	ent->dtht_where = where;
15189 	ent->dtht_nlocals = vstate->dtvs_nlocals;
15190 
15191 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15192 	    mstate->dtms_fltoffs : -1;
15193 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15194 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
15195 
15196 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
15197 		dtrace_statvar_t *svar;
15198 
15199 		if ((svar = vstate->dtvs_locals[i]) == NULL)
15200 			continue;
15201 
15202 		ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
15203 		ent->dtht_locals[i] =
15204 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
15205 	}
15206 }
15207 
15208 __attribute__((noinline))
15209 static uint64_t
dtrace_helper(int which,dtrace_mstate_t * mstate,dtrace_state_t * state,uint64_t arg0,uint64_t arg1)15210 dtrace_helper(int which, dtrace_mstate_t *mstate,
15211     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15212 {
15213 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
15214 	uint64_t sarg0 = mstate->dtms_arg[0];
15215 	uint64_t sarg1 = mstate->dtms_arg[1];
15216 	uint64_t rval = 0;
15217 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15218 	dtrace_helper_action_t *helper;
15219 	dtrace_vstate_t *vstate;
15220 	dtrace_difo_t *pred;
15221 	int i, trace = dtrace_helptrace_enabled;
15222 
15223 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15224 
15225 	if (helpers == NULL)
15226 		return (0);
15227 
15228 	if ((helper = helpers->dthps_actions[which]) == NULL)
15229 		return (0);
15230 
15231 	vstate = &helpers->dthps_vstate;
15232 	mstate->dtms_arg[0] = arg0;
15233 	mstate->dtms_arg[1] = arg1;
15234 
15235 	/*
15236 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
15237 	 * we'll call the corresponding actions.  Note that the below calls
15238 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
15239 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
15240 	 * the stored DIF offset with its own (which is the desired behavior).
15241 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15242 	 * from machine state; this is okay, too.
15243 	 */
15244 	for (; helper != NULL; helper = helper->dtha_next) {
15245 		if ((pred = helper->dtha_predicate) != NULL) {
15246 			if (trace)
15247 				dtrace_helper_trace(helper, mstate, vstate, 0);
15248 
15249 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15250 				goto next;
15251 
15252 			if (*flags & CPU_DTRACE_FAULT)
15253 				goto err;
15254 		}
15255 
15256 		for (i = 0; i < helper->dtha_nactions; i++) {
15257 			if (trace)
15258 				dtrace_helper_trace(helper,
15259 				    mstate, vstate, i + 1);
15260 
15261 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
15262 			    mstate, vstate, state);
15263 
15264 			if (*flags & CPU_DTRACE_FAULT)
15265 				goto err;
15266 		}
15267 
15268 next:
15269 		if (trace)
15270 			dtrace_helper_trace(helper, mstate, vstate,
15271 			    DTRACE_HELPTRACE_NEXT);
15272 	}
15273 
15274 	if (trace)
15275 		dtrace_helper_trace(helper, mstate, vstate,
15276 		    DTRACE_HELPTRACE_DONE);
15277 
15278 	/*
15279 	 * Restore the arg0 that we saved upon entry.
15280 	 */
15281 	mstate->dtms_arg[0] = sarg0;
15282 	mstate->dtms_arg[1] = sarg1;
15283 
15284 	return (rval);
15285 
15286 err:
15287 	if (trace)
15288 		dtrace_helper_trace(helper, mstate, vstate,
15289 		    DTRACE_HELPTRACE_ERR);
15290 
15291 	/*
15292 	 * Restore the arg0 that we saved upon entry.
15293 	 */
15294 	mstate->dtms_arg[0] = sarg0;
15295 	mstate->dtms_arg[1] = sarg1;
15296 
15297 	return (0);
15298 }
15299 
15300 static void
dtrace_helper_action_destroy(dtrace_helper_action_t * helper,dtrace_vstate_t * vstate)15301 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15302     dtrace_vstate_t *vstate)
15303 {
15304 	int i;
15305 
15306 	if (helper->dtha_predicate != NULL)
15307 		dtrace_difo_release(helper->dtha_predicate, vstate);
15308 
15309 	for (i = 0; i < helper->dtha_nactions; i++) {
15310 		ASSERT(helper->dtha_actions[i] != NULL);
15311 		dtrace_difo_release(helper->dtha_actions[i], vstate);
15312 	}
15313 
15314 	kmem_free(helper->dtha_actions,
15315 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
15316 	kmem_free(helper, sizeof (dtrace_helper_action_t));
15317 }
15318 
15319 static int
dtrace_helper_destroygen(proc_t * p,int gen)15320 dtrace_helper_destroygen(proc_t* p, int gen)
15321 {
15322 	dtrace_helpers_t *help = p->p_dtrace_helpers;
15323 	dtrace_vstate_t *vstate;
15324 	uint_t i;
15325 
15326 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15327 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15328 
15329 	if (help == NULL || gen > help->dthps_generation)
15330 		return (EINVAL);
15331 
15332 	vstate = &help->dthps_vstate;
15333 
15334 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15335 		dtrace_helper_action_t *last = NULL, *h, *next;
15336 
15337 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15338 			next = h->dtha_next;
15339 
15340 			if (h->dtha_generation == gen) {
15341 				if (last != NULL) {
15342 					last->dtha_next = next;
15343 				} else {
15344 					help->dthps_actions[i] = next;
15345 				}
15346 
15347 				dtrace_helper_action_destroy(h, vstate);
15348 			} else {
15349 				last = h;
15350 			}
15351 		}
15352 	}
15353 
15354 	/*
15355 	 * Interate until we've cleared out all helper providers with the
15356 	 * given generation number.
15357 	 */
15358 	for (;;) {
15359 		dtrace_helper_provider_t *prov = NULL;
15360 
15361 		/*
15362 		 * Look for a helper provider with the right generation. We
15363 		 * have to start back at the beginning of the list each time
15364 		 * because we drop dtrace_lock. It's unlikely that we'll make
15365 		 * more than two passes.
15366 		 */
15367 		for (i = 0; i < help->dthps_nprovs; i++) {
15368 			prov = help->dthps_provs[i];
15369 
15370 			if (prov->dthp_generation == gen)
15371 				break;
15372 		}
15373 
15374 		/*
15375 		 * If there were no matches, we're done.
15376 		 */
15377 		if (i == help->dthps_nprovs)
15378 			break;
15379 
15380 		/*
15381 		 * Move the last helper provider into this slot.
15382 		 */
15383 		help->dthps_nprovs--;
15384 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15385 		help->dthps_provs[help->dthps_nprovs] = NULL;
15386 
15387 		lck_mtx_unlock(&dtrace_lock);
15388 
15389 		/*
15390 		 * If we have a meta provider, remove this helper provider.
15391 		 */
15392 		if (dtrace_meta_pid != NULL) {
15393 			ASSERT(dtrace_deferred_pid == NULL);
15394 			dtrace_helper_provider_remove(&prov->dthp_prov,
15395 			    p);
15396 		}
15397 
15398 		dtrace_helper_provider_destroy(prov);
15399 
15400 		lck_mtx_lock(&dtrace_lock);
15401 	}
15402 
15403 	return (0);
15404 }
15405 
15406 static int
dtrace_helper_validate(dtrace_helper_action_t * helper)15407 dtrace_helper_validate(dtrace_helper_action_t *helper)
15408 {
15409 	int err = 0, i;
15410 	dtrace_difo_t *dp;
15411 
15412 	if ((dp = helper->dtha_predicate) != NULL)
15413 		err += dtrace_difo_validate_helper(dp);
15414 
15415 	for (i = 0; i < helper->dtha_nactions; i++)
15416 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15417 
15418 	return (err == 0);
15419 }
15420 
15421 static int
dtrace_helper_action_add(proc_t * p,int which,dtrace_ecbdesc_t * ep)15422 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
15423 {
15424 	dtrace_helpers_t *help;
15425 	dtrace_helper_action_t *helper, *last;
15426 	dtrace_actdesc_t *act;
15427 	dtrace_vstate_t *vstate;
15428 	dtrace_predicate_t *pred;
15429 	int count = 0, nactions = 0, i;
15430 
15431 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15432 		return (EINVAL);
15433 
15434 	help = p->p_dtrace_helpers;
15435 	last = help->dthps_actions[which];
15436 	vstate = &help->dthps_vstate;
15437 
15438 	for (count = 0; last != NULL; last = last->dtha_next) {
15439 		count++;
15440 		if (last->dtha_next == NULL)
15441 			break;
15442 	}
15443 
15444 	/*
15445 	 * If we already have dtrace_helper_actions_max helper actions for this
15446 	 * helper action type, we'll refuse to add a new one.
15447 	 */
15448 	if (count >= dtrace_helper_actions_max)
15449 		return (ENOSPC);
15450 
15451 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15452 	helper->dtha_generation = help->dthps_generation;
15453 
15454 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15455 		ASSERT(pred->dtp_difo != NULL);
15456 		dtrace_difo_hold(pred->dtp_difo);
15457 		helper->dtha_predicate = pred->dtp_difo;
15458 	}
15459 
15460 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15461 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15462 			goto err;
15463 
15464 		if (act->dtad_difo == NULL)
15465 			goto err;
15466 
15467 		nactions++;
15468 	}
15469 
15470 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15471 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15472 
15473 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15474 		dtrace_difo_hold(act->dtad_difo);
15475 		helper->dtha_actions[i++] = act->dtad_difo;
15476 	}
15477 
15478 	if (!dtrace_helper_validate(helper))
15479 		goto err;
15480 
15481 	if (last == NULL) {
15482 		help->dthps_actions[which] = helper;
15483 	} else {
15484 		last->dtha_next = helper;
15485 	}
15486 
15487 	if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15488 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15489 		dtrace_helptrace_next = 0;
15490 	}
15491 
15492 	return (0);
15493 err:
15494 	dtrace_helper_action_destroy(helper, vstate);
15495 	return (EINVAL);
15496 }
15497 
15498 static void
dtrace_helper_provider_register(proc_t * p,dtrace_helpers_t * help,dof_helper_t * dofhp)15499 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15500     dof_helper_t *dofhp)
15501 {
15502 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15503 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15504 
15505 	lck_mtx_lock(&dtrace_lock);
15506 
15507 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15508 		/*
15509 		 * If the dtrace module is loaded but not attached, or if
15510 		 * there aren't isn't a meta provider registered to deal with
15511 		 * these provider descriptions, we need to postpone creating
15512 		 * the actual providers until later.
15513 		 */
15514 
15515 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15516 		    dtrace_deferred_pid != help) {
15517 			help->dthps_deferred = 1;
15518 			help->dthps_pid = proc_getpid(p);
15519 			help->dthps_next = dtrace_deferred_pid;
15520 			help->dthps_prev = NULL;
15521 			if (dtrace_deferred_pid != NULL)
15522 				dtrace_deferred_pid->dthps_prev = help;
15523 			dtrace_deferred_pid = help;
15524 		}
15525 
15526 		lck_mtx_unlock(&dtrace_lock);
15527 
15528 	} else if (dofhp != NULL) {
15529 		/*
15530 		 * If the dtrace module is loaded and we have a particular
15531 		 * helper provider description, pass that off to the
15532 		 * meta provider.
15533 		 */
15534 
15535 		lck_mtx_unlock(&dtrace_lock);
15536 
15537 		dtrace_helper_provide(dofhp, p);
15538 
15539 	} else {
15540 		/*
15541 		 * Otherwise, just pass all the helper provider descriptions
15542 		 * off to the meta provider.
15543 		 */
15544 
15545 		uint_t i;
15546 		lck_mtx_unlock(&dtrace_lock);
15547 
15548 		for (i = 0; i < help->dthps_nprovs; i++) {
15549 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15550 				p);
15551 		}
15552 	}
15553 }
15554 
15555 static int
dtrace_helper_provider_add(proc_t * p,dof_helper_t * dofhp,int gen)15556 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
15557 {
15558 	dtrace_helpers_t *help;
15559 	dtrace_helper_provider_t *hprov, **tmp_provs;
15560 	uint_t tmp_maxprovs, i;
15561 
15562 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15563 	help = p->p_dtrace_helpers;
15564 	ASSERT(help != NULL);
15565 
15566 	/*
15567 	 * If we already have dtrace_helper_providers_max helper providers,
15568 	 * we're refuse to add a new one.
15569 	 */
15570 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
15571 		return (ENOSPC);
15572 
15573 	/*
15574 	 * Check to make sure this isn't a duplicate.
15575 	 */
15576 	for (i = 0; i < help->dthps_nprovs; i++) {
15577 		if (dofhp->dofhp_addr ==
15578 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
15579 			return (EALREADY);
15580 	}
15581 
15582 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15583 	hprov->dthp_prov = *dofhp;
15584 	hprov->dthp_ref = 1;
15585 	hprov->dthp_generation = gen;
15586 
15587 	/*
15588 	 * Allocate a bigger table for helper providers if it's already full.
15589 	 */
15590 	if (help->dthps_maxprovs == help->dthps_nprovs) {
15591 		tmp_maxprovs = help->dthps_maxprovs;
15592 		tmp_provs = help->dthps_provs;
15593 
15594 		if (help->dthps_maxprovs == 0)
15595 			help->dthps_maxprovs = 2;
15596 		else
15597 			help->dthps_maxprovs *= 2;
15598 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
15599 			help->dthps_maxprovs = dtrace_helper_providers_max;
15600 
15601 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15602 
15603 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15604 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15605 
15606 		if (tmp_provs != NULL) {
15607 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15608 			    sizeof (dtrace_helper_provider_t *));
15609 			kmem_free(tmp_provs, tmp_maxprovs *
15610 			    sizeof (dtrace_helper_provider_t *));
15611 		}
15612 	}
15613 
15614 	help->dthps_provs[help->dthps_nprovs] = hprov;
15615 	help->dthps_nprovs++;
15616 
15617 	return (0);
15618 }
15619 
15620 static void
dtrace_helper_provider_destroy(dtrace_helper_provider_t * hprov)15621 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15622 {
15623 	lck_mtx_lock(&dtrace_lock);
15624 
15625 	if (--hprov->dthp_ref == 0) {
15626 		dof_hdr_t *dof;
15627 		lck_mtx_unlock(&dtrace_lock);
15628 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15629 		dtrace_dof_destroy(dof);
15630 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15631 	} else {
15632 		lck_mtx_unlock(&dtrace_lock);
15633 	}
15634 }
15635 
15636 static int
dtrace_helper_provider_validate(dof_hdr_t * dof,dof_sec_t * sec)15637 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15638 {
15639 	uintptr_t daddr = (uintptr_t)dof;
15640 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15641 	dof_provider_t *provider;
15642 	dof_probe_t *probe;
15643 	uint8_t *arg;
15644 	char *strtab, *typestr;
15645 	dof_stridx_t typeidx;
15646 	size_t typesz;
15647 	uint_t nprobes, j, k;
15648 
15649 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15650 
15651 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15652 		dtrace_dof_error(dof, "misaligned section offset");
15653 		return (-1);
15654 	}
15655 
15656 	/*
15657 	 * The section needs to be large enough to contain the DOF provider
15658 	 * structure appropriate for the given version.
15659 	 */
15660 	if (sec->dofs_size <
15661 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15662 	    offsetof(dof_provider_t, dofpv_prenoffs) :
15663 	    sizeof (dof_provider_t))) {
15664 		dtrace_dof_error(dof, "provider section too small");
15665 		return (-1);
15666 	}
15667 
15668 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15669 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15670 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15671 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15672 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15673 
15674 	if (str_sec == NULL || prb_sec == NULL ||
15675 	    arg_sec == NULL || off_sec == NULL)
15676 		return (-1);
15677 
15678 	enoff_sec = NULL;
15679 
15680 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15681 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
15682 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15683 	    provider->dofpv_prenoffs)) == NULL)
15684 		return (-1);
15685 
15686 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15687 
15688 	if (provider->dofpv_name >= str_sec->dofs_size ||
15689 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15690 		dtrace_dof_error(dof, "invalid provider name");
15691 		return (-1);
15692 	}
15693 
15694 	if (prb_sec->dofs_entsize == 0 ||
15695 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15696 		dtrace_dof_error(dof, "invalid entry size");
15697 		return (-1);
15698 	}
15699 
15700 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15701 		dtrace_dof_error(dof, "misaligned entry size");
15702 		return (-1);
15703 	}
15704 
15705 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15706 		dtrace_dof_error(dof, "invalid entry size");
15707 		return (-1);
15708 	}
15709 
15710 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15711 		dtrace_dof_error(dof, "misaligned section offset");
15712 		return (-1);
15713 	}
15714 
15715 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15716 		dtrace_dof_error(dof, "invalid entry size");
15717 		return (-1);
15718 	}
15719 
15720 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15721 
15722 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15723 
15724 	/*
15725 	 * Take a pass through the probes to check for errors.
15726 	 */
15727 	for (j = 0; j < nprobes; j++) {
15728 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15729 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15730 
15731 		if (probe->dofpr_func >= str_sec->dofs_size) {
15732 			dtrace_dof_error(dof, "invalid function name");
15733 			return (-1);
15734 		}
15735 
15736 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15737 			dtrace_dof_error(dof, "function name too long");
15738 			return (-1);
15739 		}
15740 
15741 		if (probe->dofpr_name >= str_sec->dofs_size ||
15742 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15743 			dtrace_dof_error(dof, "invalid probe name");
15744 			return (-1);
15745 		}
15746 
15747 		/*
15748 		 * The offset count must not wrap the index, and the offsets
15749 		 * must also not overflow the section's data.
15750 		 */
15751 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15752 		    probe->dofpr_offidx ||
15753 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15754 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15755 			dtrace_dof_error(dof, "invalid probe offset");
15756 			return (-1);
15757 		}
15758 
15759 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15760 			/*
15761 			 * If there's no is-enabled offset section, make sure
15762 			 * there aren't any is-enabled offsets. Otherwise
15763 			 * perform the same checks as for probe offsets
15764 			 * (immediately above).
15765 			 */
15766 			if (enoff_sec == NULL) {
15767 				if (probe->dofpr_enoffidx != 0 ||
15768 				    probe->dofpr_nenoffs != 0) {
15769 					dtrace_dof_error(dof, "is-enabled "
15770 					    "offsets with null section");
15771 					return (-1);
15772 				}
15773 			} else if (probe->dofpr_enoffidx +
15774 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15775 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15776 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15777 				dtrace_dof_error(dof, "invalid is-enabled "
15778 				    "offset");
15779 				return (-1);
15780 			}
15781 
15782 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15783 				dtrace_dof_error(dof, "zero probe and "
15784 				    "is-enabled offsets");
15785 				return (-1);
15786 			}
15787 		} else if (probe->dofpr_noffs == 0) {
15788 			dtrace_dof_error(dof, "zero probe offsets");
15789 			return (-1);
15790 		}
15791 
15792 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15793 		    probe->dofpr_argidx ||
15794 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15795 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15796 			dtrace_dof_error(dof, "invalid args");
15797 			return (-1);
15798 		}
15799 
15800 		typeidx = probe->dofpr_nargv;
15801 		typestr = strtab + probe->dofpr_nargv;
15802 		for (k = 0; k < probe->dofpr_nargc; k++) {
15803 			if (typeidx >= str_sec->dofs_size) {
15804 				dtrace_dof_error(dof, "bad "
15805 				    "native argument type");
15806 				return (-1);
15807 			}
15808 
15809 			typesz = strlen(typestr) + 1;
15810 			if (typesz > DTRACE_ARGTYPELEN) {
15811 				dtrace_dof_error(dof, "native "
15812 				    "argument type too long");
15813 				return (-1);
15814 			}
15815 			typeidx += typesz;
15816 			typestr += typesz;
15817 		}
15818 
15819 		typeidx = probe->dofpr_xargv;
15820 		typestr = strtab + probe->dofpr_xargv;
15821 		for (k = 0; k < probe->dofpr_xargc; k++) {
15822 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15823 				dtrace_dof_error(dof, "bad "
15824 				    "native argument index");
15825 				return (-1);
15826 			}
15827 
15828 			if (typeidx >= str_sec->dofs_size) {
15829 				dtrace_dof_error(dof, "bad "
15830 				    "translated argument type");
15831 				return (-1);
15832 			}
15833 
15834 			typesz = strlen(typestr) + 1;
15835 			if (typesz > DTRACE_ARGTYPELEN) {
15836 				dtrace_dof_error(dof, "translated argument "
15837 				    "type too long");
15838 				return (-1);
15839 			}
15840 
15841 			typeidx += typesz;
15842 			typestr += typesz;
15843 		}
15844 	}
15845 
15846 	return (0);
15847 }
15848 
15849 static int
dtrace_helper_slurp(proc_t * p,dof_hdr_t * dof,dof_helper_t * dhp)15850 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
15851 {
15852 	dtrace_helpers_t *help;
15853 	dtrace_vstate_t *vstate;
15854 	dtrace_enabling_t *enab = NULL;
15855 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15856 	uintptr_t daddr = (uintptr_t)dof;
15857 
15858 	LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
15859 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15860 
15861 	if ((help = p->p_dtrace_helpers) == NULL)
15862 		help = dtrace_helpers_create(p);
15863 
15864 	vstate = &help->dthps_vstate;
15865 
15866 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15867 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15868 		dtrace_dof_destroy(dof);
15869 		return (rv);
15870 	}
15871 
15872 	/*
15873 	 * Look for helper providers and validate their descriptions.
15874 	 */
15875 	if (dhp != NULL) {
15876 		for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
15877 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15878 			    dof->dofh_secoff + i * dof->dofh_secsize);
15879 
15880 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15881 				continue;
15882 
15883 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15884 				dtrace_enabling_destroy(enab);
15885 				dtrace_dof_destroy(dof);
15886 				return (-1);
15887 			}
15888 
15889 			nprovs++;
15890 		}
15891 	}
15892 
15893 	/*
15894 	 * Now we need to walk through the ECB descriptions in the enabling.
15895 	 */
15896 	for (i = 0; i < enab->dten_ndesc; i++) {
15897 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15898 		dtrace_probedesc_t *desc = &ep->dted_probe;
15899 
15900 		/* APPLE NOTE: Darwin employs size bounded string operation. */
15901 		if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
15902 			continue;
15903 
15904 		if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
15905 			continue;
15906 
15907 		if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
15908 			continue;
15909 
15910 		if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
15911 		    ep)) != 0) {
15912 			/*
15913 			 * Adding this helper action failed -- we are now going
15914 			 * to rip out the entire generation and return failure.
15915 			 */
15916 			(void) dtrace_helper_destroygen(p, help->dthps_generation);
15917 			dtrace_enabling_destroy(enab);
15918 			dtrace_dof_destroy(dof);
15919 			return (-1);
15920 		}
15921 
15922 		nhelpers++;
15923 	}
15924 
15925 	if (nhelpers < enab->dten_ndesc)
15926 		dtrace_dof_error(dof, "unmatched helpers");
15927 
15928 	gen = help->dthps_generation++;
15929 	dtrace_enabling_destroy(enab);
15930 
15931 	if (dhp != NULL && nprovs > 0) {
15932 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15933 		if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
15934 			lck_mtx_unlock(&dtrace_lock);
15935 			dtrace_helper_provider_register(p, help, dhp);
15936 			lck_mtx_lock(&dtrace_lock);
15937 
15938 			destroy = 0;
15939 		}
15940 	}
15941 
15942 	if (destroy)
15943 		dtrace_dof_destroy(dof);
15944 
15945 	return (gen);
15946 }
15947 
15948 /*
15949  * APPLE NOTE:  DTrace lazy dof implementation
15950  *
15951  * DTrace user static probes (USDT probes) and helper actions are loaded
15952  * in a process by proccessing dof sections. The dof sections are passed
15953  * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
15954  * expensive to process dof for a process that will never use it. There
15955  * is a memory cost (allocating the providers/probes), and a cpu cost
15956  * (creating the providers/probes).
15957  *
15958  * To reduce this cost, we use "lazy dof". The normal proceedure for
15959  * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
15960  * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
15961  * used, each process retains the dof_ioctl_data_t block, instead of
15962  * copying in the data it points to.
15963  *
15964  * The dof_ioctl_data_t blocks are managed as if they were the actual
15965  * processed dof; on fork the block is copied to the child, on exec and
15966  * exit the block is freed.
15967  *
15968  * If the process loads library(s) containing additional dof, the
15969  * new dof_ioctl_data_t is merged with the existing block.
15970  *
15971  * There are a few catches that make this slightly more difficult.
15972  * When dyld registers dof_ioctl_data_t blocks, it expects a unique
15973  * identifier value for each dof in the block. In non-lazy dof terms,
15974  * this is the generation that dof was loaded in. If we hand back
15975  * a UID for a lazy dof, that same UID must be able to unload the
15976  * dof once it has become non-lazy. To meet this requirement, the
15977  * code that loads lazy dof requires that the UID's for dof(s) in
15978  * the lazy dof be sorted, and in ascending order. It is okay to skip
15979  * UID's, I.E., 1 -> 5 -> 6 is legal.
15980  *
15981  * Once a process has become non-lazy, it will stay non-lazy. All
15982  * future dof operations for that process will be non-lazy, even
15983  * if the dof mode transitions back to lazy.
15984  *
15985  * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
15986  * That way if the lazy check fails due to transitioning to non-lazy, the
15987  * right thing is done with the newly faulted in dof.
15988  */
15989 
15990 /*
15991  * This method is a bit squicky. It must handle:
15992  *
15993  * dof should not be lazy.
15994  * dof should have been handled lazily, but there was an error
15995  * dof was handled lazily, and needs to be freed.
15996  * dof was handled lazily, and must not be freed.
15997  *
15998  *
15999  * Returns EACCESS if dof should be handled non-lazily.
16000  *
16001  * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
16002  *
16003  * If the dofs data is claimed by this method, dofs_claimed will be set.
16004  * Callers should not free claimed dofs.
16005  */
16006 static int
dtrace_lazy_dofs_add(proc_t * p,dof_ioctl_data_t * incoming_dofs,int * dofs_claimed)16007 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
16008 {
16009 	ASSERT(p);
16010 	ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
16011 
16012 	int rval = 0;
16013 	*dofs_claimed = 0;
16014 
16015 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16016 
16017 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16018 	ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
16019 
16020 	/*
16021 	 * Any existing helpers force non-lazy behavior.
16022 	 */
16023 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
16024 		dtrace_sprlock(p);
16025 
16026 		dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
16027 		unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
16028 		unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
16029 
16030 		/*
16031 		 * Range check...
16032 		 */
16033 		if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
16034 			dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
16035 			rval = EINVAL;
16036 			goto unlock;
16037 		}
16038 
16039 		/*
16040 		 * Each dof being added must be assigned a unique generation.
16041 		 */
16042 		uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
16043 		for (i=0; i<incoming_dofs->dofiod_count; i++) {
16044 			/*
16045 			 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
16046 			 */
16047 			ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
16048 			incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
16049 		}
16050 
16051 
16052 		if (existing_dofs) {
16053 			/*
16054 			 * Merge the existing and incoming dofs
16055 			 */
16056 			size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
16057 			dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
16058 
16059 			bcopy(&existing_dofs->dofiod_helpers[0],
16060 			      &merged_dofs->dofiod_helpers[0],
16061 			      sizeof(dof_helper_t) * existing_dofs_count);
16062 			bcopy(&incoming_dofs->dofiod_helpers[0],
16063 			      &merged_dofs->dofiod_helpers[existing_dofs_count],
16064 			      sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
16065 
16066 			merged_dofs->dofiod_count = merged_dofs_count;
16067 
16068 			kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
16069 
16070 			p->p_dtrace_lazy_dofs = merged_dofs;
16071 		} else {
16072 			/*
16073 			 * Claim the incoming dofs
16074 			 */
16075 			*dofs_claimed = 1;
16076 			p->p_dtrace_lazy_dofs = incoming_dofs;
16077 		}
16078 
16079 #if DEBUG
16080 		dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
16081 		for (i=0; i<all_dofs->dofiod_count-1; i++) {
16082 			ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
16083 		}
16084 #endif /* DEBUG */
16085 
16086 unlock:
16087 		dtrace_sprunlock(p);
16088 	} else {
16089 		rval = EACCES;
16090 	}
16091 
16092  	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16093 
16094 	return rval;
16095 }
16096 
16097 /*
16098  * Returns:
16099  *
16100  * EINVAL: lazy dof is enabled, but the requested generation was not found.
16101  * EACCES: This removal needs to be handled non-lazily.
16102  */
16103 static int
dtrace_lazy_dofs_remove(proc_t * p,int generation)16104 dtrace_lazy_dofs_remove(proc_t *p, int generation)
16105 {
16106 	int rval = EINVAL;
16107 
16108 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16109 
16110 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16111 	ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
16112 
16113 	/*
16114 	 * Any existing helpers force non-lazy behavior.
16115 	 */
16116 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
16117 		dtrace_sprlock(p);
16118 
16119 		dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
16120 
16121 		if (existing_dofs) {
16122 			int index, existing_dofs_count = existing_dofs->dofiod_count;
16123 			for (index=0; index<existing_dofs_count; index++) {
16124 				if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
16125 					dof_ioctl_data_t* removed_dofs = NULL;
16126 
16127 					/*
16128 					 * If there is only 1 dof, we'll delete it and swap in NULL.
16129 					 */
16130 					if (existing_dofs_count > 1) {
16131 						int removed_dofs_count = existing_dofs_count - 1;
16132 						size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
16133 
16134 						removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
16135 						removed_dofs->dofiod_count = removed_dofs_count;
16136 
16137 						/*
16138 						 * copy the remaining data.
16139 						 */
16140 						if (index > 0) {
16141 							bcopy(&existing_dofs->dofiod_helpers[0],
16142 							      &removed_dofs->dofiod_helpers[0],
16143 							      index * sizeof(dof_helper_t));
16144 						}
16145 
16146 						if (index < existing_dofs_count-1) {
16147 							bcopy(&existing_dofs->dofiod_helpers[index+1],
16148 							      &removed_dofs->dofiod_helpers[index],
16149 							      (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
16150 						}
16151 					}
16152 
16153 					kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
16154 
16155 					p->p_dtrace_lazy_dofs = removed_dofs;
16156 
16157 					rval = KERN_SUCCESS;
16158 
16159 					break;
16160 				}
16161 			}
16162 
16163 #if DEBUG
16164 			dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
16165 			if (all_dofs) {
16166 				unsigned int i;
16167 				for (i=0; i<all_dofs->dofiod_count-1; i++) {
16168 					ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
16169 				}
16170 			}
16171 #endif
16172 
16173 		}
16174 		dtrace_sprunlock(p);
16175 	} else {
16176 		rval = EACCES;
16177 	}
16178 
16179 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16180 
16181 	return rval;
16182 }
16183 
16184 void
dtrace_lazy_dofs_destroy(proc_t * p)16185 dtrace_lazy_dofs_destroy(proc_t *p)
16186 {
16187 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16188 	dtrace_sprlock(p);
16189 
16190 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16191 
16192 	dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
16193 	p->p_dtrace_lazy_dofs = NULL;
16194 
16195 	dtrace_sprunlock(p);
16196 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16197 
16198 	if (lazy_dofs) {
16199 		kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
16200 	}
16201 }
16202 
16203 static int
dtrace_lazy_dofs_proc_iterate_filter(proc_t * p,void * ignored)16204 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
16205 {
16206 #pragma unused(ignored)
16207 	/*
16208 	 * Okay to NULL test without taking the sprlock.
16209 	 */
16210 	return p->p_dtrace_lazy_dofs != NULL;
16211 }
16212 
16213 static void
dtrace_lazy_dofs_process(proc_t * p)16214 dtrace_lazy_dofs_process(proc_t *p) {
16215 	/*
16216 	 * It is possible this process may exit during our attempt to
16217 	 * fault in the dof. We could fix this by holding locks longer,
16218 	 * but the errors are benign.
16219 	 */
16220 	dtrace_sprlock(p);
16221 
16222 
16223 	ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
16224 	ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
16225 
16226 	dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
16227 	p->p_dtrace_lazy_dofs = NULL;
16228 
16229 	dtrace_sprunlock(p);
16230 	lck_mtx_lock(&dtrace_meta_lock);
16231 	/*
16232 	 * Process each dof_helper_t
16233 	 */
16234 	if (lazy_dofs != NULL) {
16235 		unsigned int i;
16236 		int rval;
16237 
16238 		for (i=0; i<lazy_dofs->dofiod_count; i++) {
16239 			/*
16240 			 * When loading lazy dof, we depend on the generations being sorted in ascending order.
16241 			 */
16242 			ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
16243 
16244 			dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
16245 
16246 			/*
16247 			 * We stored the generation in dofhp_dof. Save it, and restore the original value.
16248 			 */
16249 			int generation = dhp->dofhp_dof;
16250 			dhp->dofhp_dof = dhp->dofhp_addr;
16251 
16252 			dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
16253 
16254 			if (dof != NULL) {
16255 				dtrace_helpers_t *help;
16256 
16257 				lck_mtx_lock(&dtrace_lock);
16258 
16259 				/*
16260 				 * This must be done with the dtrace_lock held
16261 				 */
16262 				if ((help = p->p_dtrace_helpers) == NULL)
16263 					help = dtrace_helpers_create(p);
16264 
16265 				/*
16266 				 * If the generation value has been bumped, someone snuck in
16267 				 * when we released the dtrace lock. We have to dump this generation,
16268 				 * there is no safe way to load it.
16269 				 */
16270 				if (help->dthps_generation <= generation) {
16271 					help->dthps_generation = generation;
16272 
16273 					/*
16274 					 * dtrace_helper_slurp() takes responsibility for the dof --
16275 					 * it may free it now or it may save it and free it later.
16276 					 */
16277 					if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
16278 						dtrace_dof_error(NULL, "returned value did not match expected generation");
16279 					}
16280 				}
16281 
16282 				lck_mtx_unlock(&dtrace_lock);
16283 			}
16284 		}
16285 		lck_mtx_unlock(&dtrace_meta_lock);
16286 		kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
16287 	} else {
16288 		lck_mtx_unlock(&dtrace_meta_lock);
16289 	}
16290 }
16291 
16292 static int
dtrace_lazy_dofs_proc_iterate_doit(proc_t * p,void * ignored)16293 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
16294 {
16295 #pragma unused(ignored)
16296 
16297 	dtrace_lazy_dofs_process(p);
16298 
16299 	return PROC_RETURNED;
16300 }
16301 
16302 #define DTRACE_LAZY_DOFS_DUPLICATED 1
16303 
16304 static int
dtrace_lazy_dofs_duplicate(proc_t * parent,proc_t * child)16305 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
16306 {
16307 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
16308 	LCK_MTX_ASSERT(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
16309 	LCK_MTX_ASSERT(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
16310 
16311 	lck_rw_lock_shared(&dtrace_dof_mode_lock);
16312 	dtrace_sprlock(parent);
16313 
16314 	/*
16315 	 * We need to make sure that the transition to lazy dofs -> helpers
16316 	 * was atomic for our parent
16317 	 */
16318 	ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
16319 	/*
16320 	 * In theory we should hold the child sprlock, but this is safe...
16321 	 */
16322 	ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
16323 
16324 	dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
16325 	dof_ioctl_data_t* child_dofs = NULL;
16326 	if (parent_dofs) {
16327 		size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
16328 		child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
16329 		bcopy(parent_dofs, child_dofs, parent_dofs_size);
16330 	}
16331 
16332 	dtrace_sprunlock(parent);
16333 
16334 	if (child_dofs) {
16335 		dtrace_sprlock(child);
16336 		child->p_dtrace_lazy_dofs = child_dofs;
16337 		dtrace_sprunlock(child);
16338 		/**
16339 		 * We process the DOF at this point if the mode is set to
16340 		 * LAZY_OFF. This can happen if DTrace is still processing the
16341 		 * DOF of other process (which can happen because the
16342 		 * protected pager can have a huge latency)
16343 		 * but has not processed our parent yet
16344 		 */
16345 		if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
16346 			dtrace_lazy_dofs_process(child);
16347 		}
16348 		lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16349 
16350 		return DTRACE_LAZY_DOFS_DUPLICATED;
16351 	}
16352 	lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16353 
16354 	return 0;
16355 }
16356 
16357 static dtrace_helpers_t *
dtrace_helpers_create(proc_t * p)16358 dtrace_helpers_create(proc_t *p)
16359 {
16360 	dtrace_helpers_t *help;
16361 
16362 	LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
16363 	ASSERT(p->p_dtrace_helpers == NULL);
16364 
16365 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16366 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16367 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16368 
16369 	p->p_dtrace_helpers = help;
16370 	dtrace_helpers++;
16371 
16372 	return (help);
16373 }
16374 
16375 static void
dtrace_helpers_destroy(proc_t * p)16376 dtrace_helpers_destroy(proc_t* p)
16377 {
16378 	dtrace_helpers_t *help;
16379 	dtrace_vstate_t *vstate;
16380 	uint_t i;
16381 
16382 	lck_mtx_lock(&dtrace_meta_lock);
16383 	lck_mtx_lock(&dtrace_lock);
16384 
16385 	ASSERT(p->p_dtrace_helpers != NULL);
16386 	ASSERT(dtrace_helpers > 0);
16387 
16388 	help = p->p_dtrace_helpers;
16389 	vstate = &help->dthps_vstate;
16390 
16391 	/*
16392 	 * We're now going to lose the help from this process.
16393 	 */
16394 	p->p_dtrace_helpers = NULL;
16395 	dtrace_sync();
16396 
16397 	/*
16398 	 * Destory the helper actions.
16399 	 */
16400 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16401 		dtrace_helper_action_t *h, *next;
16402 
16403 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
16404 			next = h->dtha_next;
16405 			dtrace_helper_action_destroy(h, vstate);
16406 			h = next;
16407 		}
16408 	}
16409 
16410 	lck_mtx_unlock(&dtrace_lock);
16411 
16412 	/*
16413 	 * Destroy the helper providers.
16414 	 */
16415 	if (help->dthps_maxprovs > 0) {
16416 		if (dtrace_meta_pid != NULL) {
16417 			ASSERT(dtrace_deferred_pid == NULL);
16418 
16419 			for (i = 0; i < help->dthps_nprovs; i++) {
16420 				dtrace_helper_provider_remove(
16421 				    &help->dthps_provs[i]->dthp_prov, p);
16422 			}
16423 		} else {
16424 			lck_mtx_lock(&dtrace_lock);
16425 			ASSERT(help->dthps_deferred == 0 ||
16426 			    help->dthps_next != NULL ||
16427 			    help->dthps_prev != NULL ||
16428 			    help == dtrace_deferred_pid);
16429 
16430 			/*
16431 			 * Remove the helper from the deferred list.
16432 			 */
16433 			if (help->dthps_next != NULL)
16434 				help->dthps_next->dthps_prev = help->dthps_prev;
16435 			if (help->dthps_prev != NULL)
16436 				help->dthps_prev->dthps_next = help->dthps_next;
16437 			if (dtrace_deferred_pid == help) {
16438 				dtrace_deferred_pid = help->dthps_next;
16439 				ASSERT(help->dthps_prev == NULL);
16440 			}
16441 
16442 			lck_mtx_unlock(&dtrace_lock);
16443 		}
16444 
16445 
16446 		for (i = 0; i < help->dthps_nprovs; i++) {
16447 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
16448 		}
16449 
16450 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
16451 		    sizeof (dtrace_helper_provider_t *));
16452 	}
16453 
16454 	lck_mtx_lock(&dtrace_lock);
16455 
16456 	dtrace_vstate_fini(&help->dthps_vstate);
16457 	kmem_free(help->dthps_actions,
16458 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16459 	kmem_free(help, sizeof (dtrace_helpers_t));
16460 
16461 	--dtrace_helpers;
16462 	lck_mtx_unlock(&dtrace_lock);
16463 	lck_mtx_unlock(&dtrace_meta_lock);
16464 }
16465 
16466 static void
dtrace_helpers_duplicate(proc_t * from,proc_t * to)16467 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16468 {
16469 	dtrace_helpers_t *help, *newhelp;
16470 	dtrace_helper_action_t *helper, *new, *last;
16471 	dtrace_difo_t *dp;
16472 	dtrace_vstate_t *vstate;
16473 	uint_t i;
16474 	int j, sz, hasprovs = 0;
16475 
16476 	lck_mtx_lock(&dtrace_meta_lock);
16477 	lck_mtx_lock(&dtrace_lock);
16478 	ASSERT(from->p_dtrace_helpers != NULL);
16479 	ASSERT(dtrace_helpers > 0);
16480 
16481 	help = from->p_dtrace_helpers;
16482 	newhelp = dtrace_helpers_create(to);
16483 	ASSERT(to->p_dtrace_helpers != NULL);
16484 
16485 	newhelp->dthps_generation = help->dthps_generation;
16486 	vstate = &newhelp->dthps_vstate;
16487 
16488 	/*
16489 	 * Duplicate the helper actions.
16490 	 */
16491 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16492 		if ((helper = help->dthps_actions[i]) == NULL)
16493 			continue;
16494 
16495 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16496 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16497 			    KM_SLEEP);
16498 			new->dtha_generation = helper->dtha_generation;
16499 
16500 			if ((dp = helper->dtha_predicate) != NULL) {
16501 				dp = dtrace_difo_duplicate(dp, vstate);
16502 				new->dtha_predicate = dp;
16503 			}
16504 
16505 			new->dtha_nactions = helper->dtha_nactions;
16506 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16507 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16508 
16509 			for (j = 0; j < new->dtha_nactions; j++) {
16510 				dtrace_difo_t *dpj = helper->dtha_actions[j];
16511 
16512 				ASSERT(dpj != NULL);
16513 				dpj = dtrace_difo_duplicate(dpj, vstate);
16514 				new->dtha_actions[j] = dpj;
16515 			}
16516 
16517 			if (last != NULL) {
16518 				last->dtha_next = new;
16519 			} else {
16520 				newhelp->dthps_actions[i] = new;
16521 			}
16522 
16523 			last = new;
16524 		}
16525 	}
16526 
16527 	/*
16528 	 * Duplicate the helper providers and register them with the
16529 	 * DTrace framework.
16530 	 */
16531 	if (help->dthps_nprovs > 0) {
16532 		newhelp->dthps_nprovs = help->dthps_nprovs;
16533 		newhelp->dthps_maxprovs = help->dthps_nprovs;
16534 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16535 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16536 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
16537 			newhelp->dthps_provs[i] = help->dthps_provs[i];
16538 			newhelp->dthps_provs[i]->dthp_ref++;
16539 		}
16540 
16541 		hasprovs = 1;
16542 	}
16543 
16544 	lck_mtx_unlock(&dtrace_lock);
16545 
16546 	if (hasprovs)
16547 		dtrace_helper_provider_register(to, newhelp, NULL);
16548 
16549 	lck_mtx_unlock(&dtrace_meta_lock);
16550 }
16551 
16552 /**
16553  * DTrace Process functions
16554  */
16555 
16556 void
dtrace_proc_fork(proc_t * parent_proc,proc_t * child_proc,int spawn)16557 dtrace_proc_fork(proc_t *parent_proc, proc_t *child_proc, int spawn)
16558 {
16559 	/*
16560 	 * This code applies to new processes who are copying the task
16561 	 * and thread state and address spaces of their parent process.
16562 	 */
16563 	if (!spawn) {
16564 		/*
16565 		 * APPLE NOTE: Solaris does a sprlock() and drops the
16566 		 * proc_lock here. We're cheating a bit and only taking
16567 		 * the p_dtrace_sprlock lock. A full sprlock would
16568 		 * task_suspend the parent.
16569 		 */
16570 		dtrace_sprlock(parent_proc);
16571 
16572 		/*
16573 		 * Remove all DTrace tracepoints from the child process. We
16574 		 * need to do this _before_ duplicating USDT providers since
16575 		 * any associated probes may be immediately enabled.
16576 		 */
16577 		if (parent_proc->p_dtrace_count > 0) {
16578 			dtrace_fasttrap_fork(parent_proc, child_proc);
16579 		}
16580 
16581 		dtrace_sprunlock(parent_proc);
16582 
16583 		/*
16584 		 * Duplicate any lazy dof(s). This must be done while NOT
16585 		 * holding the parent sprlock! Lock ordering is
16586 		 * dtrace_dof_mode_lock, then sprlock.  It is imperative we
16587 		 * always call dtrace_lazy_dofs_duplicate, rather than null
16588 		 * check and call if !NULL. If we NULL test, during lazy dof
16589 		 * faulting we can race with the faulting code and proceed
16590 		 * from here to beyond the helpers copy. The lazy dof
16591 		 * faulting will then fail to copy the helpers to the child
16592 		 * process. We return if we duplicated lazy dofs as a process
16593 		 * can only have one at the same time to avoid a race between
16594 		 * a dtrace client and dtrace_proc_fork where a process would
16595 		 * end up with both lazy dofs and helpers.
16596 		 */
16597 		if (dtrace_lazy_dofs_duplicate(parent_proc, child_proc) == DTRACE_LAZY_DOFS_DUPLICATED) {
16598 			return;
16599 		}
16600 
16601 		/*
16602 		 * Duplicate any helper actions and providers if they haven't
16603 		 * already.
16604 		 */
16605 #if !defined(__APPLE__)
16606 		 /*
16607 		 * The SFORKING
16608 		 * we set above informs the code to enable USDT probes that
16609 		 * sprlock() may fail because the child is being forked.
16610 		 */
16611 #endif
16612 		/*
16613 		 * APPLE NOTE: As best I can tell, Apple's sprlock() equivalent
16614 		 * never fails to find the child. We do not set SFORKING.
16615 		 */
16616 		if (parent_proc->p_dtrace_helpers != NULL && dtrace_helpers_fork) {
16617 			(*dtrace_helpers_fork)(parent_proc, child_proc);
16618 		}
16619 	}
16620 }
16621 
16622 void
dtrace_proc_exec(proc_t * p)16623 dtrace_proc_exec(proc_t *p)
16624 {
16625 	/*
16626 	 * Invalidate any predicate evaluation already cached for this thread by DTrace.
16627 	 * That's because we've just stored to p_comm and DTrace refers to that when it
16628 	 * evaluates the "execname" special variable. uid and gid may have changed as well.
16629 	 */
16630 	dtrace_set_thread_predcache(current_thread(), 0);
16631 
16632 	/*
16633 	 * Free any outstanding lazy dof entries. It is imperative we
16634 	 * always call dtrace_lazy_dofs_destroy, rather than null check
16635 	 * and call if !NULL. If we NULL test, during lazy dof faulting
16636 	 * we can race with the faulting code and proceed from here to
16637 	 * beyond the helpers cleanup. The lazy dof faulting will then
16638 	 * install new helpers which no longer belong to this process!
16639 	 */
16640 	dtrace_lazy_dofs_destroy(p);
16641 
16642 
16643 	/*
16644 	 * Clean up any DTrace helpers for the process.
16645 	 */
16646 	if (p->p_dtrace_helpers != NULL && dtrace_helpers_cleanup) {
16647 		(*dtrace_helpers_cleanup)(p);
16648 	}
16649 
16650 	/*
16651 	 * Cleanup the DTrace provider associated with this process.
16652 	 */
16653 	proc_lock(p);
16654 	if (p->p_dtrace_probes && dtrace_fasttrap_exec_ptr) {
16655 		(*dtrace_fasttrap_exec_ptr)(p);
16656 	}
16657 	proc_unlock(p);
16658 }
16659 
16660 void
dtrace_proc_exit(proc_t * p)16661 dtrace_proc_exit(proc_t *p)
16662 {
16663 	/*
16664 	 * Free any outstanding lazy dof entries. It is imperative we
16665 	 * always call dtrace_lazy_dofs_destroy, rather than null check
16666 	 * and call if !NULL. If we NULL test, during lazy dof faulting
16667 	 * we can race with the faulting code and proceed from here to
16668 	 * beyond the helpers cleanup. The lazy dof faulting will then
16669 	 * install new helpers which will never be cleaned up, and leak.
16670 	 */
16671 	dtrace_lazy_dofs_destroy(p);
16672 
16673 	/*
16674 	 * Clean up any DTrace helper actions or probes for the process.
16675 	 */
16676 	if (p->p_dtrace_helpers != NULL) {
16677 		(*dtrace_helpers_cleanup)(p);
16678 	}
16679 
16680 	/*
16681 	 * Clean up any DTrace probes associated with this process.
16682 	 */
16683 	/*
16684 	 * APPLE NOTE: We release ptss pages/entries in dtrace_fasttrap_exit_ptr(),
16685 	 * call this after dtrace_helpers_cleanup()
16686 	 */
16687 	proc_lock(p);
16688 	if (p->p_dtrace_probes && dtrace_fasttrap_exit_ptr) {
16689 		(*dtrace_fasttrap_exit_ptr)(p);
16690 	}
16691 	proc_unlock(p);
16692 }
16693 
16694 /*
16695  * DTrace Hook Functions
16696  */
16697 
16698 /*
16699  * APPLE NOTE:  dtrace_modctl_* routines for kext support.
16700  * Used to manipulate the modctl list within dtrace xnu.
16701  */
16702 
16703 modctl_t *dtrace_modctl_list;
16704 
16705 static void
dtrace_modctl_add(struct modctl * newctl)16706 dtrace_modctl_add(struct modctl * newctl)
16707 {
16708 	struct modctl *nextp, *prevp;
16709 
16710 	ASSERT(newctl != NULL);
16711 	LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16712 
16713 	// Insert new module at the front of the list,
16714 
16715 	newctl->mod_next = dtrace_modctl_list;
16716 	dtrace_modctl_list = newctl;
16717 
16718 	/*
16719 	 * If a module exists with the same name, then that module
16720 	 * must have been unloaded with enabled probes. We will move
16721 	 * the unloaded module to the new module's stale chain and
16722 	 * then stop traversing the list.
16723 	 */
16724 
16725 	prevp = newctl;
16726 	nextp = newctl->mod_next;
16727 
16728 	while (nextp != NULL) {
16729 		if (nextp->mod_loaded) {
16730 			/* This is a loaded module. Keep traversing. */
16731 			prevp = nextp;
16732 			nextp = nextp->mod_next;
16733 			continue;
16734 		}
16735 		else {
16736 			/* Found an unloaded module */
16737 			if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
16738 				/* Names don't match. Keep traversing. */
16739 				prevp = nextp;
16740 				nextp = nextp->mod_next;
16741 				continue;
16742 			}
16743 			else {
16744 				/* We found a stale entry, move it. We're done. */
16745 				prevp->mod_next = nextp->mod_next;
16746 				newctl->mod_stale = nextp;
16747 				nextp->mod_next = NULL;
16748 				break;
16749 			}
16750 		}
16751 	}
16752 }
16753 
16754 static modctl_t *
dtrace_modctl_lookup(struct kmod_info * kmod)16755 dtrace_modctl_lookup(struct kmod_info * kmod)
16756 {
16757     LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16758 
16759     struct modctl * ctl;
16760 
16761     for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
16762 	if (ctl->mod_id == kmod->id)
16763 	    return(ctl);
16764     }
16765     return (NULL);
16766 }
16767 
16768 /*
16769  * This routine is called from dtrace_module_unloaded().
16770  * It removes a modctl structure and its stale chain
16771  * from the kext shadow list.
16772  */
16773 static void
dtrace_modctl_remove(struct modctl * ctl)16774 dtrace_modctl_remove(struct modctl * ctl)
16775 {
16776 	ASSERT(ctl != NULL);
16777 	LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
16778 	modctl_t *prevp, *nextp, *curp;
16779 
16780 	// Remove stale chain first
16781 	for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
16782 		nextp = curp->mod_stale;
16783 		/* There should NEVER be user symbols allocated at this point */
16784 		ASSERT(curp->mod_user_symbols == NULL);
16785 		kmem_free(curp, sizeof(modctl_t));
16786 	}
16787 
16788 	prevp = NULL;
16789 	curp = dtrace_modctl_list;
16790 
16791 	while (curp != ctl) {
16792 		prevp = curp;
16793 		curp = curp->mod_next;
16794 	}
16795 
16796 	if (prevp != NULL) {
16797 		prevp->mod_next = ctl->mod_next;
16798 	}
16799 	else {
16800 		dtrace_modctl_list = ctl->mod_next;
16801 	}
16802 
16803 	/* There should NEVER be user symbols allocated at this point */
16804 	ASSERT(ctl->mod_user_symbols == NULL);
16805 
16806 	kmem_free (ctl, sizeof(modctl_t));
16807 }
16808 
16809 /*
16810  * APPLE NOTE: The kext loader will call dtrace_module_loaded
16811  * when the kext is loaded in memory, but before calling the
16812  * kext's start routine.
16813  *
16814  * Return 0 on success
16815  * Return -1 on failure
16816  */
16817 
16818 static int
dtrace_module_loaded(struct kmod_info * kmod,uint32_t flag)16819 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
16820 {
16821 	dtrace_provider_t *prv;
16822 
16823 	/*
16824 	 * If kernel symbols have been disabled, return immediately
16825 	 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
16826 	 */
16827 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
16828 		return 0;
16829 
16830 
16831 	struct modctl *ctl = NULL;
16832 	if (!kmod || kmod->address == 0 || kmod->size == 0)
16833 		return(-1);
16834 
16835 	lck_mtx_lock(&dtrace_provider_lock);
16836 	lck_mtx_lock(&mod_lock);
16837 
16838 	/*
16839 	 * Have we seen this kext before?
16840 	 */
16841 
16842 	ctl = dtrace_modctl_lookup(kmod);
16843 
16844 	if (ctl != NULL) {
16845 		/* bail... we already have this kext in the modctl list */
16846 		lck_mtx_unlock(&mod_lock);
16847 		lck_mtx_unlock(&dtrace_provider_lock);
16848 		if (dtrace_err_verbose)
16849 			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);
16850 		return(-1);
16851 	}
16852 	else {
16853 		ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
16854 		if (ctl == NULL) {
16855 			if (dtrace_err_verbose)
16856 				cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
16857 			lck_mtx_unlock(&mod_lock);
16858 			lck_mtx_unlock(&dtrace_provider_lock);
16859 			return (-1);
16860 		}
16861 		ctl->mod_next = NULL;
16862 		ctl->mod_stale = NULL;
16863 		strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
16864 		ctl->mod_loadcnt = kmod->id;
16865 		ctl->mod_nenabled = 0;
16866 		ctl->mod_address  = kmod->address;
16867 		ctl->mod_size = kmod->size;
16868 		ctl->mod_id = kmod->id;
16869 		ctl->mod_loaded = 1;
16870 		ctl->mod_flags = 0;
16871 		ctl->mod_user_symbols = NULL;
16872 		ctl->mod_sdtprobecnt = 0;
16873 		ctl->mod_sdtdesc = NULL;
16874 
16875 		/*
16876 		 * Find the UUID for this module, if it has one
16877 		 */
16878 		kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
16879 		struct load_command* load_cmd = (struct load_command *)&header[1];
16880 		uint32_t i;
16881 		for (i = 0; i < header->ncmds; i++) {
16882 			if (load_cmd->cmd == LC_UUID) {
16883 				struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
16884 				memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
16885 				ctl->mod_flags |= MODCTL_HAS_UUID;
16886 				break;
16887 			}
16888 			load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
16889 		}
16890 
16891 		if (ctl->mod_address == g_kernel_kmod_info.address) {
16892 			ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
16893 			memcpy(dtrace_kerneluuid, ctl->mod_uuid, sizeof(dtrace_kerneluuid));
16894 		}
16895 		/*
16896 		 * Static kexts have a UUID that is not used for symbolication, as all their
16897 		 * symbols are in kernel
16898 		 */
16899 		else if ((flag & KMOD_DTRACE_STATIC_KEXT) == KMOD_DTRACE_STATIC_KEXT) {
16900 			memcpy(ctl->mod_uuid, dtrace_kerneluuid, sizeof(dtrace_kerneluuid));
16901 			ctl->mod_flags |= MODCTL_IS_STATIC_KEXT;
16902 		}
16903 	}
16904 	dtrace_modctl_add(ctl);
16905 
16906 	/*
16907 	 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
16908 	 */
16909 	lck_mtx_lock(&dtrace_lock);
16910 
16911 	/*
16912 	 * DTrace must decide if it will instrument modules lazily via
16913 	 * userspace symbols (default mode), or instrument immediately via
16914 	 * kernel symbols (non-default mode)
16915 	 *
16916 	 * When in default/lazy mode, DTrace will only support modules
16917 	 * built with a valid UUID.
16918 	 *
16919 	 * Overriding the default can be done explicitly in one of
16920 	 * the following two ways.
16921 	 *
16922 	 * A module can force symbols from kernel space using the plist key,
16923 	 * OSBundleForceDTraceInit (see kmod.h).  If this per kext state is set,
16924 	 * we fall through and instrument this module now.
16925 	 *
16926 	 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
16927 	 * from kernel space (see dtrace_impl.h).  If this system state is set
16928 	 * to a non-userspace mode, we fall through and instrument the module now.
16929 	 */
16930 
16931 	if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
16932 	    (!(flag & KMOD_DTRACE_FORCE_INIT)))
16933 	{
16934 		/* Load SDT section for module. Symbol related data will be handled lazily. */
16935 		sdt_load_machsect(ctl);
16936 
16937 		/* We will instrument the module lazily -- this is the default */
16938 		lck_mtx_unlock(&dtrace_lock);
16939 		lck_mtx_unlock(&mod_lock);
16940 		lck_mtx_unlock(&dtrace_provider_lock);
16941 		return 0;
16942 	}
16943 
16944 	/* We will instrument the module immediately using kernel symbols */
16945 	if (!(flag & KMOD_DTRACE_NO_KERNEL_SYMS)) {
16946 		ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
16947 	}
16948 
16949 	/* Load SDT section for module. Symbol related data will be handled lazily. */
16950 	sdt_load_machsect(ctl);
16951 
16952 	lck_mtx_unlock(&dtrace_lock);
16953 
16954 	/*
16955 	 * We're going to call each providers per-module provide operation
16956 	 * specifying only this module.
16957 	 */
16958 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16959 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16960 
16961 	/*
16962 	 * APPLE NOTE: The contract with the kext loader is that once this function
16963 	 * has completed, it may delete kernel symbols at will.
16964 	 * We must set this while still holding the mod_lock.
16965 	 */
16966 	ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
16967 
16968 	lck_mtx_unlock(&mod_lock);
16969 	lck_mtx_unlock(&dtrace_provider_lock);
16970 
16971 	/*
16972 	 * If we have any retained enablings, we need to match against them.
16973 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
16974 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16975 	 * module.  (In particular, this happens when loading scheduling
16976 	 * classes.)  So if we have any retained enablings, we need to dispatch
16977 	 * our task queue to do the match for us.
16978 	 */
16979 	lck_mtx_lock(&dtrace_lock);
16980 
16981 	if (dtrace_retained == NULL) {
16982 		lck_mtx_unlock(&dtrace_lock);
16983 		return 0;
16984 	}
16985 
16986 	/* APPLE NOTE!
16987 	 *
16988 	 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
16989 	 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
16990 	 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
16991 	 * the delay call as well.
16992 	 */
16993 	lck_mtx_unlock(&dtrace_lock);
16994 
16995 	dtrace_enabling_matchall();
16996 
16997 	return 0;
16998 }
16999 
17000 /*
17001  * Return 0 on success
17002  * Return -1 on failure
17003  */
17004 static int
dtrace_module_unloaded(struct kmod_info * kmod)17005 dtrace_module_unloaded(struct kmod_info *kmod)
17006 {
17007 	dtrace_probe_t template, *probe, *first, *next;
17008 	dtrace_provider_t *prov;
17009         struct modctl *ctl = NULL;
17010 	struct modctl *syncctl = NULL;
17011 	struct modctl *nextsyncctl = NULL;
17012 	int syncmode = 0;
17013 
17014         lck_mtx_lock(&dtrace_provider_lock);
17015 	lck_mtx_lock(&mod_lock);
17016 	lck_mtx_lock(&dtrace_lock);
17017 
17018 	if (kmod == NULL) {
17019 	    syncmode = 1;
17020 	}
17021 	else {
17022 	    ctl = dtrace_modctl_lookup(kmod);
17023 	    if (ctl == NULL)
17024 	    {
17025 		lck_mtx_unlock(&dtrace_lock);
17026 		lck_mtx_unlock(&mod_lock);
17027 		lck_mtx_unlock(&dtrace_provider_lock);
17028 		return (-1);
17029 	    }
17030 	    ctl->mod_loaded = 0;
17031 	    ctl->mod_address = 0;
17032 	    ctl->mod_size = 0;
17033 	}
17034 
17035 	if (dtrace_bymod == NULL) {
17036 		/*
17037 		 * The DTrace module is loaded (obviously) but not attached;
17038 		 * we don't have any work to do.
17039 		 */
17040 	         if (ctl != NULL)
17041 			 (void)dtrace_modctl_remove(ctl);
17042 		 lck_mtx_unlock(&dtrace_lock);
17043 		 lck_mtx_unlock(&mod_lock);
17044 		 lck_mtx_unlock(&dtrace_provider_lock);
17045 		 return(0);
17046 	}
17047 
17048 	/* Syncmode set means we target and traverse entire modctl list. */
17049         if (syncmode)
17050 	    nextsyncctl = dtrace_modctl_list;
17051 
17052 syncloop:
17053 	if (syncmode)
17054 	{
17055 	    /* find a stale modctl struct */
17056 	    for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
17057 		if (syncctl->mod_address == 0)
17058 		    break;
17059 	    }
17060 	    if (syncctl==NULL)
17061 	    {
17062 		/* We have no more work to do */
17063 		lck_mtx_unlock(&dtrace_lock);
17064 		lck_mtx_unlock(&mod_lock);
17065 		lck_mtx_unlock(&dtrace_provider_lock);
17066 		return(0);
17067 	    }
17068 	    else {
17069 		/* keep track of next syncctl in case this one is removed */
17070 		nextsyncctl = syncctl->mod_next;
17071 		ctl = syncctl;
17072 	    }
17073 	}
17074 
17075 	template.dtpr_mod = ctl->mod_modname;
17076 
17077 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
17078 	    probe != NULL; probe = probe->dtpr_nextmod) {
17079 	        if (probe->dtpr_ecb != NULL) {
17080 			/*
17081 			 * This shouldn't _actually_ be possible -- we're
17082 			 * unloading a module that has an enabled probe in it.
17083 			 * (It's normally up to the provider to make sure that
17084 			 * this can't happen.)  However, because dtps_enable()
17085 			 * doesn't have a failure mode, there can be an
17086 			 * enable/unload race.  Upshot:  we don't want to
17087 			 * assert, but we're not going to disable the
17088 			 * probe, either.
17089 			 */
17090 
17091 
17092 		        if (syncmode) {
17093 			    /* We're syncing, let's look at next in list */
17094 			    goto syncloop;
17095 			}
17096 
17097 			lck_mtx_unlock(&dtrace_lock);
17098 			lck_mtx_unlock(&mod_lock);
17099 			lck_mtx_unlock(&dtrace_provider_lock);
17100 
17101 			if (dtrace_err_verbose) {
17102 				cmn_err(CE_WARN, "unloaded module '%s' had "
17103 				    "enabled probes", ctl->mod_modname);
17104 			}
17105 			return(-1);
17106 		}
17107 	}
17108 
17109 	probe = first;
17110 
17111 	for (first = NULL; probe != NULL; probe = next) {
17112 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
17113 
17114 		dtrace_probes[probe->dtpr_id - 1] = NULL;
17115 		probe->dtpr_provider->dtpv_probe_count--;
17116 
17117 		next = probe->dtpr_nextmod;
17118 		dtrace_hash_remove(dtrace_byprov, probe);
17119 		dtrace_hash_remove(dtrace_bymod, probe);
17120 		dtrace_hash_remove(dtrace_byfunc, probe);
17121 		dtrace_hash_remove(dtrace_byname, probe);
17122 
17123 		if (first == NULL) {
17124 			first = probe;
17125 			probe->dtpr_nextmod = NULL;
17126 		} else {
17127 			probe->dtpr_nextmod = first;
17128 			first = probe;
17129 		}
17130 	}
17131 
17132 	/*
17133 	 * We've removed all of the module's probes from the hash chains and
17134 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
17135 	 * everyone has cleared out from any probe array processing.
17136 	 */
17137 	dtrace_sync();
17138 
17139 	for (probe = first; probe != NULL; probe = first) {
17140 		first = probe->dtpr_nextmod;
17141 		prov = probe->dtpr_provider;
17142 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
17143 		    probe->dtpr_arg);
17144 		dtrace_strunref(probe->dtpr_mod);
17145 		dtrace_strunref(probe->dtpr_func);
17146 		dtrace_strunref(probe->dtpr_name);
17147 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
17148 
17149 		zfree(dtrace_probe_t_zone, probe);
17150 	}
17151 
17152 	dtrace_modctl_remove(ctl);
17153 
17154 	if (syncmode)
17155 	    goto syncloop;
17156 
17157 	lck_mtx_unlock(&dtrace_lock);
17158 	lck_mtx_unlock(&mod_lock);
17159 	lck_mtx_unlock(&dtrace_provider_lock);
17160 
17161 	return(0);
17162 }
17163 
17164 void
dtrace_suspend(void)17165 dtrace_suspend(void)
17166 {
17167 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
17168 }
17169 
17170 void
dtrace_resume(void)17171 dtrace_resume(void)
17172 {
17173 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
17174 }
17175 
17176 static int
dtrace_cpu_setup(cpu_setup_t what,processorid_t cpu)17177 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
17178 {
17179 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17180 	lck_mtx_lock(&dtrace_lock);
17181 
17182 	switch (what) {
17183 	case CPU_CONFIG: {
17184 		dtrace_state_t *state;
17185 		dtrace_optval_t *opt, rs, c;
17186 
17187 		/*
17188 		 * For now, we only allocate a new buffer for anonymous state.
17189 		 */
17190 		if ((state = dtrace_anon.dta_state) == NULL)
17191 			break;
17192 
17193 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
17194 			break;
17195 
17196 		opt = state->dts_options;
17197 		c = opt[DTRACEOPT_CPU];
17198 
17199 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
17200 			break;
17201 
17202 		/*
17203 		 * Regardless of what the actual policy is, we're going to
17204 		 * temporarily set our resize policy to be manual.  We're
17205 		 * also going to temporarily set our CPU option to denote
17206 		 * the newly configured CPU.
17207 		 */
17208 		rs = opt[DTRACEOPT_BUFRESIZE];
17209 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
17210 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
17211 
17212 		(void) dtrace_state_buffers(state);
17213 
17214 		opt[DTRACEOPT_BUFRESIZE] = rs;
17215 		opt[DTRACEOPT_CPU] = c;
17216 
17217 		break;
17218 	}
17219 
17220 	case CPU_UNCONFIG:
17221 		/*
17222 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
17223 		 * buffer will be freed when the consumer exits.)
17224 		 */
17225 		break;
17226 
17227 	default:
17228 		break;
17229 	}
17230 
17231 	lck_mtx_unlock(&dtrace_lock);
17232 	return (0);
17233 }
17234 
17235 static void
dtrace_cpu_setup_initial(processorid_t cpu)17236 dtrace_cpu_setup_initial(processorid_t cpu)
17237 {
17238 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
17239 }
17240 
17241 static void
dtrace_toxrange_add(uintptr_t base,uintptr_t limit)17242 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
17243 {
17244 	if (dtrace_toxranges >= dtrace_toxranges_max) {
17245 		int osize, nsize;
17246 		dtrace_toxrange_t *range;
17247 
17248 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17249 
17250 		if (osize == 0) {
17251 			ASSERT(dtrace_toxrange == NULL);
17252 			ASSERT(dtrace_toxranges_max == 0);
17253 			dtrace_toxranges_max = 1;
17254 		} else {
17255 			dtrace_toxranges_max <<= 1;
17256 		}
17257 
17258 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
17259 		range = kmem_zalloc(nsize, KM_SLEEP);
17260 
17261 		if (dtrace_toxrange != NULL) {
17262 			ASSERT(osize != 0);
17263 			bcopy(dtrace_toxrange, range, osize);
17264 			kmem_free(dtrace_toxrange, osize);
17265 		}
17266 
17267 		dtrace_toxrange = range;
17268 	}
17269 
17270 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17271 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17272 
17273 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17274 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17275 	dtrace_toxranges++;
17276 }
17277 
17278 /*
17279  * DTrace Driver Cookbook Functions
17280  */
17281 /*ARGSUSED*/
17282 static int
dtrace_attach(dev_info_t * devi)17283 dtrace_attach(dev_info_t *devi)
17284 {
17285 	dtrace_provider_id_t id;
17286 	dtrace_state_t *state = NULL;
17287 	dtrace_enabling_t *enab;
17288 
17289 	lck_mtx_lock(&cpu_lock);
17290 	lck_mtx_lock(&dtrace_provider_lock);
17291 	lck_mtx_lock(&dtrace_lock);
17292 
17293 	/* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
17294 	dtrace_devi = devi;
17295 
17296 	dtrace_modload = dtrace_module_loaded;
17297 	dtrace_modunload = dtrace_module_unloaded;
17298 	dtrace_cpu_init = dtrace_cpu_setup_initial;
17299 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
17300 	dtrace_helpers_fork = dtrace_helpers_duplicate;
17301 	dtrace_cpustart_init = dtrace_suspend;
17302 	dtrace_cpustart_fini = dtrace_resume;
17303 	dtrace_debugger_init = dtrace_suspend;
17304 	dtrace_debugger_fini = dtrace_resume;
17305 
17306 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17307 
17308 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17309 
17310 	dtrace_arena = vmem_create("dtrace", (void *)1, INT32_MAX, 1,
17311 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17312 
17313 	LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
17314 
17315 	dtrace_nprobes = dtrace_nprobes_default;
17316 	dtrace_probes = kmem_zalloc(sizeof(dtrace_probe_t*) * dtrace_nprobes,
17317 	    KM_SLEEP);
17318 
17319 	dtrace_byprov = dtrace_hash_create(dtrace_strkey_probe_provider,
17320 	    0, /* unused */
17321 	    offsetof(dtrace_probe_t, dtpr_nextprov),
17322 	    offsetof(dtrace_probe_t, dtpr_prevprov));
17323 
17324 	dtrace_bymod = dtrace_hash_create(dtrace_strkey_deref_offset,
17325 	    offsetof(dtrace_probe_t, dtpr_mod),
17326 	    offsetof(dtrace_probe_t, dtpr_nextmod),
17327 	    offsetof(dtrace_probe_t, dtpr_prevmod));
17328 
17329 	dtrace_byfunc = dtrace_hash_create(dtrace_strkey_deref_offset,
17330 	    offsetof(dtrace_probe_t, dtpr_func),
17331 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
17332 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
17333 
17334 	dtrace_byname = dtrace_hash_create(dtrace_strkey_deref_offset,
17335 	    offsetof(dtrace_probe_t, dtpr_name),
17336 	    offsetof(dtrace_probe_t, dtpr_nextname),
17337 	    offsetof(dtrace_probe_t, dtpr_prevname));
17338 
17339 	if (dtrace_retain_max < 1) {
17340 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
17341 		    "setting to 1", dtrace_retain_max);
17342 		dtrace_retain_max = 1;
17343 	}
17344 
17345 	/*
17346 	 * Now discover our toxic ranges.
17347 	 */
17348 	dtrace_toxic_ranges(dtrace_toxrange_add);
17349 
17350 	/*
17351 	 * Before we register ourselves as a provider to our own framework,
17352 	 * we would like to assert that dtrace_provider is NULL -- but that's
17353 	 * not true if we were loaded as a dependency of a DTrace provider.
17354 	 * Once we've registered, we can assert that dtrace_provider is our
17355 	 * pseudo provider.
17356 	 */
17357 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
17358 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17359 
17360 	ASSERT(dtrace_provider != NULL);
17361 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17362 
17363 #if defined (__x86_64__)
17364 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17365 	    dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
17366 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17367 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
17368 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17369 	    dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
17370 #elif defined(__arm64__)
17371 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17372 	    dtrace_provider, NULL, NULL, "BEGIN", 2, NULL);
17373 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17374 	    dtrace_provider, NULL, NULL, "END", 1, NULL);
17375 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17376 	    dtrace_provider, NULL, NULL, "ERROR", 4, NULL);
17377 #else
17378 #error Unknown Architecture
17379 #endif
17380 
17381 	dtrace_anon_property();
17382 	lck_mtx_unlock(&cpu_lock);
17383 
17384 	/*
17385 	 * If DTrace helper tracing is enabled, we need to allocate the
17386 	 * trace buffer and initialize the values.
17387 	 */
17388 	if (dtrace_helptrace_enabled) {
17389 		ASSERT(dtrace_helptrace_buffer == NULL);
17390 		dtrace_helptrace_buffer =
17391 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17392 		dtrace_helptrace_next = 0;
17393 	}
17394 
17395 	/*
17396 	 * If there are already providers, we must ask them to provide their
17397 	 * probes, and then match any anonymous enabling against them.  Note
17398 	 * that there should be no other retained enablings at this time:
17399 	 * the only retained enablings at this time should be the anonymous
17400 	 * enabling.
17401 	 */
17402 	if (dtrace_anon.dta_enabling != NULL) {
17403 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17404 
17405 		/*
17406 		 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
17407 		 */
17408 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17409 			dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17410 		}
17411 
17412 		dtrace_enabling_provide(NULL);
17413 		state = dtrace_anon.dta_state;
17414 
17415 		/*
17416 		 * We couldn't hold cpu_lock across the above call to
17417 		 * dtrace_enabling_provide(), but we must hold it to actually
17418 		 * enable the probes.  We have to drop all of our locks, pick
17419 		 * up cpu_lock, and regain our locks before matching the
17420 		 * retained anonymous enabling.
17421 		 */
17422 		lck_mtx_unlock(&dtrace_lock);
17423 		lck_mtx_unlock(&dtrace_provider_lock);
17424 
17425 		lck_mtx_lock(&cpu_lock);
17426 		lck_mtx_lock(&dtrace_provider_lock);
17427 		lck_mtx_lock(&dtrace_lock);
17428 
17429 		if ((enab = dtrace_anon.dta_enabling) != NULL)
17430 			(void) dtrace_enabling_match(enab, NULL, NULL);
17431 
17432 		lck_mtx_unlock(&cpu_lock);
17433 	}
17434 
17435 	lck_mtx_unlock(&dtrace_lock);
17436 	lck_mtx_unlock(&dtrace_provider_lock);
17437 
17438 	if (state != NULL) {
17439 		/*
17440 		 * If we created any anonymous state, set it going now.
17441 		 */
17442 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17443 	}
17444 
17445 	return (DDI_SUCCESS);
17446 }
17447 
17448 /*ARGSUSED*/
17449 static int
dtrace_open(dev_t * devp,int flag,int otyp,cred_t * cred_p)17450 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17451 {
17452 #pragma unused(flag, otyp)
17453 	dtrace_state_t *state;
17454 	uint32_t priv;
17455 	uid_t uid;
17456 	zoneid_t zoneid;
17457 	int rv;
17458 
17459 	if (minor(*devp) < 0 || minor(*devp) >= DTRACE_NCLIENTS)
17460 		return (ENXIO);
17461 
17462 	/* APPLE: Darwin puts Helper on its own major device. */
17463 
17464 	/*
17465 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
17466 	 * caller lacks sufficient permission to do anything with DTrace.
17467 	 */
17468 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17469 	if (priv == DTRACE_PRIV_NONE)
17470 		return (EACCES);
17471 
17472 	/*
17473 	 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
17474 	 * It certainly can't be later than now!
17475 	 */
17476 	fasttrap_init();
17477 
17478 	/*
17479 	 * Ask all providers to provide all their probes.
17480 	 */
17481 	lck_mtx_lock(&dtrace_provider_lock);
17482 	dtrace_probe_provide(NULL, NULL);
17483 	lck_mtx_unlock(&dtrace_provider_lock);
17484 
17485 	lck_mtx_lock(&cpu_lock);
17486 	lck_mtx_lock(&dtrace_lock);
17487 	dtrace_opens++;
17488 	dtrace_membar_producer();
17489 
17490 #ifdef illumos
17491 	/*
17492 	 * If the kernel debugger is active (that is, if the kernel debugger
17493 	 * modified text in some way), we won't allow the open.
17494 	 */
17495 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17496 		dtrace_opens--;
17497 		lck_mtx_unlock(&dtrace_lock);
17498 		lck_mtx_unlock(&cpu_lock);
17499 		return (EBUSY);
17500 	}
17501 #endif
17502 
17503 	rv = dtrace_state_create(devp, cred_p, &state);
17504 	lck_mtx_unlock(&cpu_lock);
17505 
17506 	if (rv != 0 || state == NULL) {
17507 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL) {
17508 #ifdef illumos
17509 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17510 #endif
17511 		}
17512 		lck_mtx_unlock(&dtrace_lock);
17513 		/* propagate EAGAIN or ERESTART */
17514 		return (rv);
17515 	}
17516 
17517 	lck_mtx_unlock(&dtrace_lock);
17518 
17519 	lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17520 
17521 	/*
17522 	 * If we are currently lazy, transition states.
17523 	 *
17524 	 * Unlike dtrace_close, we do not need to check the
17525 	 * value of dtrace_opens, as any positive value (and
17526 	 * we count as 1) means we transition states.
17527 	 */
17528 	if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
17529 		dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
17530 		/*
17531 		 * We do not need to hold the exclusive lock while processing
17532 		 * DOF on processes. We do need to make sure the mode does not get
17533 		 * changed to DTRACE_DOF_MODE_LAZY_ON during that stage though
17534 		 * (which should not happen anyway since it only happens in
17535 		 * dtrace_close). There is no way imcomplete USDT probes can be
17536 		 * activate by any DTrace clients here since they all have to
17537 		 * call dtrace_open and be blocked on dtrace_dof_mode_lock
17538 		 */
17539 		lck_rw_lock_exclusive_to_shared(&dtrace_dof_mode_lock);
17540 		/*
17541 		 * Iterate all existing processes and load lazy dofs.
17542 		 */
17543 		proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
17544 			     dtrace_lazy_dofs_proc_iterate_doit,
17545 			     NULL,
17546 			     dtrace_lazy_dofs_proc_iterate_filter,
17547 			     NULL);
17548 
17549 		lck_rw_unlock_shared(&dtrace_dof_mode_lock);
17550 	}
17551 	else {
17552 		lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17553 	}
17554 
17555 
17556 	/*
17557 	 * Update kernel symbol state.
17558 	 *
17559 	 * We must own the provider and dtrace locks.
17560 	 *
17561 	 * NOTE! It may appear there is a race by setting this value so late
17562 	 * after dtrace_probe_provide. However, any kext loaded after the
17563 	 * call to probe provide and before we set LAZY_OFF will be marked as
17564 	 * eligible for symbols from userspace. The same dtrace that is currently
17565 	 * calling dtrace_open() (this call!) will get a list of kexts needing
17566 	 * symbols and fill them in, thus closing the race window.
17567 	 *
17568 	 * We want to set this value only after it certain it will succeed, as
17569 	 * this significantly reduces the complexity of error exits.
17570 	 */
17571 	lck_mtx_lock(&dtrace_lock);
17572 	if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17573 		dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17574 	}
17575 	lck_mtx_unlock(&dtrace_lock);
17576 
17577 	/* Suspend cluster powerdown while DTrace device is opened. */
17578 	suspend_cluster_powerdown();
17579 	return (0);
17580 }
17581 
17582 /*ARGSUSED*/
17583 static int
dtrace_close(dev_t dev,int flag,int otyp,cred_t * cred_p)17584 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17585 {
17586 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
17587 	minor_t minor = getminor(dev);
17588 	dtrace_state_t *state;
17589 
17590 	/* APPLE NOTE: Darwin puts Helper on its own major device. */
17591 	state = dtrace_state_get(minor);
17592 
17593 	lck_mtx_lock(&cpu_lock);
17594 	lck_mtx_lock(&dtrace_lock);
17595 
17596 	if (state->dts_anon) {
17597 		/*
17598 		 * There is anonymous state. Destroy that first.
17599 		 */
17600 		ASSERT(dtrace_anon.dta_state == NULL);
17601 		dtrace_state_destroy(state->dts_anon);
17602 	}
17603 
17604 	dtrace_state_destroy(state);
17605 	ASSERT(dtrace_opens > 0);
17606 
17607 	/*
17608 	 * Only relinquish control of the kernel debugger interface when there
17609 	 * are no consumers and no anonymous enablings.
17610 	 */
17611 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL) {
17612 #ifdef illumos
17613 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17614 #endif
17615 	}
17616 
17617 	lck_mtx_unlock(&dtrace_lock);
17618 	lck_mtx_unlock(&cpu_lock);
17619 
17620 	/*
17621 	 * Lock ordering requires the dof mode lock be taken before
17622 	 * the dtrace_lock.
17623 	 */
17624 	lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17625 	lck_mtx_lock(&dtrace_lock);
17626 
17627 	if (dtrace_opens == 0) {
17628 		/*
17629 		 * If we are currently lazy-off, and this is the last close, transition to
17630 		 * lazy state.
17631 		 */
17632 		if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
17633 			dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
17634 		}
17635 
17636 		/*
17637 		 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
17638 		 */
17639 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
17640 			dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
17641 		}
17642 	}
17643 
17644 	lck_mtx_unlock(&dtrace_lock);
17645 	lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17646 
17647 	/*
17648 	 * Kext probes may be retained past the end of the kext's lifespan. The
17649 	 * probes are kept until the last reference to them has been removed.
17650 	 * Since closing an active dtrace context is likely to drop that last reference,
17651 	 * lets take a shot at cleaning out the orphaned probes now.
17652 	 */
17653 	dtrace_module_unloaded(NULL);
17654 
17655 	/* State is gone so resume cluster powerdown. */
17656 	resume_cluster_powerdown();
17657 	return (0);
17658 }
17659 
17660 /*ARGSUSED*/
17661 static int
dtrace_ioctl_helper(u_long cmd,caddr_t arg,int * rv)17662 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
17663 {
17664 #pragma unused(rv)
17665 	/*
17666 	 * Safe to check this outside the dof mode lock
17667 	 */
17668 	if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
17669 		return KERN_SUCCESS;
17670 
17671 	switch (cmd) {
17672 #if defined (__arm64__)
17673 	case DTRACEHIOC_ADDDOF_U32:
17674 	case DTRACEHIOC_ADDDOF_U64:
17675 #else
17676 	case DTRACEHIOC_ADDDOF:
17677 #endif /* __arm64__*/
17678 	                {
17679 			dof_helper_t *dhp = NULL;
17680 			size_t dof_ioctl_data_size;
17681 			dof_ioctl_data_t* multi_dof;
17682 			unsigned int i;
17683 			int rval = 0;
17684 			user_addr_t user_address = *(user_addr_t*)arg;
17685 			uint64_t dof_count;
17686 			int multi_dof_claimed = 0;
17687 			proc_t* p = current_proc();
17688 
17689 			/*
17690 			 * If this is a restricted process and dtrace is restricted,
17691 			 * do not allow DOFs to be registered
17692 			 */
17693 			if (dtrace_is_restricted() &&
17694 				!dtrace_are_restrictions_relaxed() &&
17695 				!dtrace_can_attach_to_proc(current_proc())) {
17696 				return (EACCES);
17697 			}
17698 
17699 			/*
17700 			 * Read the number of DOF sections being passed in.
17701 			 */
17702 			if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
17703 				   &dof_count,
17704 				   sizeof(dof_count))) {
17705 				dtrace_dof_error(NULL, "failed to copyin dofiod_count");
17706 				return (EFAULT);
17707 			}
17708 
17709 			/*
17710 			 * Range check the count.
17711 			 */
17712 			if (dof_count == 0 || dof_count > 1024) {
17713 				dtrace_dof_error(NULL, "dofiod_count is not valid");
17714 				return (EINVAL);
17715 			}
17716 
17717 			/*
17718 			 * Allocate a correctly sized structure and copyin the data.
17719 			 */
17720 			dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
17721 			if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
17722 				return (ENOMEM);
17723 
17724 			/* NOTE! We can no longer exit this method via return */
17725 			if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
17726 				dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
17727 				rval = EFAULT;
17728 				goto cleanup;
17729 			}
17730 
17731 			/*
17732 			 * Check that the count didn't change between the first copyin and the second.
17733 			 */
17734 			if (multi_dof->dofiod_count != dof_count) {
17735 				rval = EINVAL;
17736 				goto cleanup;
17737 			}
17738 
17739 			/*
17740 			 * Try to process lazily first.
17741 			 */
17742 			rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
17743 
17744 			/*
17745 			 * If rval is EACCES, we must be non-lazy.
17746 			 */
17747 			if (rval == EACCES) {
17748 				rval = 0;
17749 				/*
17750 				 * Process each dof_helper_t
17751 				 */
17752 				i = 0;
17753 				do {
17754 					dhp = &multi_dof->dofiod_helpers[i];
17755 
17756 					dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
17757 
17758 					if (dof != NULL) {
17759 						lck_mtx_lock(&dtrace_meta_lock);
17760 						lck_mtx_lock(&dtrace_lock);
17761 
17762 						/*
17763 						 * dtrace_helper_slurp() takes responsibility for the dof --
17764 						 * it may free it now or it may save it and free it later.
17765 						 */
17766 						if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
17767 							rval = EINVAL;
17768 						}
17769 
17770 						lck_mtx_unlock(&dtrace_lock);
17771 						lck_mtx_unlock(&dtrace_meta_lock);
17772 					}
17773 				} while (++i < multi_dof->dofiod_count && rval == 0);
17774 			}
17775 
17776 			/*
17777 			 * We need to copyout the multi_dof struct, because it contains
17778 			 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
17779 			 *
17780 			 * This could certainly be better optimized.
17781 			 */
17782 			if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
17783 				dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
17784 				/* Don't overwrite pre-existing error code */
17785 				if (rval == 0) rval = EFAULT;
17786 			}
17787 
17788 		cleanup:
17789 			/*
17790 			 * If we had to allocate struct memory, free it.
17791 			 */
17792 			if (multi_dof != NULL && !multi_dof_claimed) {
17793 				kmem_free(multi_dof, dof_ioctl_data_size);
17794 			}
17795 
17796 			return rval;
17797 		}
17798 
17799 		case DTRACEHIOC_REMOVE: {
17800 			int generation = *(int*)arg;
17801 			proc_t* p = current_proc();
17802 
17803 			/*
17804 			 * Try lazy first.
17805 			 */
17806 			int rval = dtrace_lazy_dofs_remove(p, generation);
17807 
17808 			/*
17809 			 * EACCES means non-lazy
17810 			 */
17811 			if (rval == EACCES) {
17812 				lck_mtx_lock(&dtrace_meta_lock);
17813 				lck_mtx_lock(&dtrace_lock);
17814 				rval = dtrace_helper_destroygen(p, generation);
17815 				lck_mtx_unlock(&dtrace_lock);
17816 				lck_mtx_unlock(&dtrace_meta_lock);
17817 			}
17818 
17819 			return (rval);
17820 		}
17821 
17822 		default:
17823 			break;
17824 	}
17825 
17826 	return ENOTTY;
17827 }
17828 
17829 /*ARGSUSED*/
17830 static int
dtrace_ioctl(dev_t dev,u_long cmd,user_addr_t arg,int md,cred_t * cr,int * rv)17831 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
17832 {
17833 #pragma unused(md)
17834 	minor_t minor = getminor(dev);
17835 	dtrace_state_t *state;
17836 	int rval;
17837 
17838 	/* Darwin puts Helper on its own major device. */
17839 
17840 	state = dtrace_state_get(minor);
17841 
17842 	if (state->dts_anon) {
17843 	   ASSERT(dtrace_anon.dta_state == NULL);
17844 	   state = state->dts_anon;
17845 	}
17846 
17847 	switch (cmd) {
17848 	case DTRACEIOC_PROVIDER: {
17849 		dtrace_providerdesc_t pvd;
17850 		dtrace_provider_t *pvp;
17851 
17852 		if (copyin(arg, &pvd, sizeof (pvd)) != 0)
17853 			return (EFAULT);
17854 
17855 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17856 		lck_mtx_lock(&dtrace_provider_lock);
17857 
17858 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17859 			if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
17860 				break;
17861 		}
17862 
17863 		lck_mtx_unlock(&dtrace_provider_lock);
17864 
17865 		if (pvp == NULL)
17866 			return (ESRCH);
17867 
17868 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17869 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17870 		if (copyout(&pvd, arg, sizeof (pvd)) != 0)
17871 			return (EFAULT);
17872 
17873 		return (0);
17874 	}
17875 
17876 	case DTRACEIOC_EPROBE: {
17877 		dtrace_eprobedesc_t epdesc;
17878 		dtrace_ecb_t *ecb;
17879 		dtrace_action_t *act;
17880 		void *buf;
17881 		size_t size;
17882 		uintptr_t dest;
17883 		int nrecs;
17884 
17885 		if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
17886 			return (EFAULT);
17887 
17888 		lck_mtx_lock(&dtrace_lock);
17889 
17890 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17891 			lck_mtx_unlock(&dtrace_lock);
17892 			return (EINVAL);
17893 		}
17894 
17895 		if (ecb->dte_probe == NULL) {
17896 			lck_mtx_unlock(&dtrace_lock);
17897 			return (EINVAL);
17898 		}
17899 
17900 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17901 		epdesc.dtepd_uarg = ecb->dte_uarg;
17902 		epdesc.dtepd_size = ecb->dte_size;
17903 
17904 		nrecs = epdesc.dtepd_nrecs;
17905 		epdesc.dtepd_nrecs = 0;
17906 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17907 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17908 				continue;
17909 
17910 			epdesc.dtepd_nrecs++;
17911 		}
17912 
17913 		/*
17914 		 * Now that we have the size, we need to allocate a temporary
17915 		 * buffer in which to store the complete description.  We need
17916 		 * the temporary buffer to be able to drop dtrace_lock()
17917 		 * across the copyout(), below.
17918 		 */
17919 		size = sizeof (dtrace_eprobedesc_t) +
17920 			(epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17921 
17922 		buf = kmem_alloc(size, KM_SLEEP);
17923 		dest = (uintptr_t)buf;
17924 
17925 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17926 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17927 
17928 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17929 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17930 				continue;
17931 
17932 			if (nrecs-- == 0)
17933 				break;
17934 
17935 			bcopy(&act->dta_rec, (void *)dest,
17936 			sizeof (dtrace_recdesc_t));
17937 			dest += sizeof (dtrace_recdesc_t);
17938 		}
17939 
17940 		lck_mtx_unlock(&dtrace_lock);
17941 
17942 		if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
17943 			kmem_free(buf, size);
17944 			return (EFAULT);
17945 		}
17946 
17947 		kmem_free(buf, size);
17948 		return (0);
17949 	}
17950 
17951 	case DTRACEIOC_AGGDESC: {
17952 		dtrace_aggdesc_t aggdesc;
17953 		dtrace_action_t *act;
17954 		dtrace_aggregation_t *agg;
17955 		int nrecs;
17956 		uint32_t offs;
17957 		dtrace_recdesc_t *lrec;
17958 		void *buf;
17959 		size_t size;
17960 		uintptr_t dest;
17961 
17962 		if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
17963 			return (EFAULT);
17964 
17965 		lck_mtx_lock(&dtrace_lock);
17966 
17967 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17968 			lck_mtx_unlock(&dtrace_lock);
17969 			return (EINVAL);
17970 		}
17971 
17972 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17973 
17974 		nrecs = aggdesc.dtagd_nrecs;
17975 		aggdesc.dtagd_nrecs = 0;
17976 
17977 		offs = agg->dtag_base;
17978 		lrec = &agg->dtag_action.dta_rec;
17979 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17980 
17981 		for (act = agg->dtag_first; ; act = act->dta_next) {
17982 			ASSERT(act->dta_intuple ||
17983 			DTRACEACT_ISAGG(act->dta_kind));
17984 
17985 			/*
17986 			 * If this action has a record size of zero, it
17987 			 * denotes an argument to the aggregating action.
17988 			 * Because the presence of this record doesn't (or
17989 			 * shouldn't) affect the way the data is interpreted,
17990 			 * we don't copy it out to save user-level the
17991 			 * confusion of dealing with a zero-length record.
17992 			 */
17993 			if (act->dta_rec.dtrd_size == 0) {
17994 				ASSERT(agg->dtag_hasarg);
17995 				continue;
17996 			}
17997 
17998 			aggdesc.dtagd_nrecs++;
17999 
18000 			if (act == &agg->dtag_action)
18001 				break;
18002 		}
18003 
18004 		/*
18005 		 * Now that we have the size, we need to allocate a temporary
18006 		 * buffer in which to store the complete description.  We need
18007 		 * the temporary buffer to be able to drop dtrace_lock()
18008 		 * across the copyout(), below.
18009 		 */
18010 		size = sizeof (dtrace_aggdesc_t) +
18011 			(aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
18012 
18013 		buf = kmem_alloc(size, KM_SLEEP);
18014 		dest = (uintptr_t)buf;
18015 
18016 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
18017 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
18018 
18019 		for (act = agg->dtag_first; ; act = act->dta_next) {
18020 			dtrace_recdesc_t rec = act->dta_rec;
18021 
18022 			/*
18023 			 * See the comment in the above loop for why we pass
18024 			 * over zero-length records.
18025 			 */
18026 			if (rec.dtrd_size == 0) {
18027 				ASSERT(agg->dtag_hasarg);
18028 				continue;
18029 			}
18030 
18031 			if (nrecs-- == 0)
18032 				break;
18033 
18034 			rec.dtrd_offset -= offs;
18035 			bcopy(&rec, (void *)dest, sizeof (rec));
18036 			dest += sizeof (dtrace_recdesc_t);
18037 
18038 			if (act == &agg->dtag_action)
18039 				break;
18040 		}
18041 
18042 		lck_mtx_unlock(&dtrace_lock);
18043 
18044 		if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
18045 			kmem_free(buf, size);
18046 			return (EFAULT);
18047 		}
18048 
18049 		kmem_free(buf, size);
18050 		return (0);
18051 	}
18052 
18053 	case DTRACEIOC_ENABLE: {
18054 		dof_hdr_t *dof;
18055 		dtrace_enabling_t *enab = NULL;
18056 		dtrace_vstate_t *vstate;
18057 		int err = 0;
18058 
18059 		*rv = 0;
18060 
18061 		/*
18062 		 * If a NULL argument has been passed, we take this as our
18063 		 * cue to reevaluate our enablings.
18064 		 */
18065 		if (arg == 0) {
18066 			dtrace_enabling_matchall();
18067 
18068 			return (0);
18069 		}
18070 
18071 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
18072 			return (rval);
18073 
18074 		lck_mtx_lock(&cpu_lock);
18075 		lck_mtx_lock(&dtrace_lock);
18076 		vstate = &state->dts_vstate;
18077 
18078 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
18079 			lck_mtx_unlock(&dtrace_lock);
18080 			lck_mtx_unlock(&cpu_lock);
18081 			dtrace_dof_destroy(dof);
18082 			return (EBUSY);
18083 		}
18084 
18085 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
18086 			lck_mtx_unlock(&dtrace_lock);
18087 			lck_mtx_unlock(&cpu_lock);
18088 			dtrace_dof_destroy(dof);
18089 			return (EINVAL);
18090 		}
18091 
18092 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
18093 			dtrace_enabling_destroy(enab);
18094 			lck_mtx_unlock(&dtrace_lock);
18095 			lck_mtx_unlock(&cpu_lock);
18096 			dtrace_dof_destroy(dof);
18097 			return (rval);
18098 		}
18099 
18100 		if ((err = dtrace_enabling_match(enab, rv, NULL)) == 0) {
18101 			err = dtrace_enabling_retain(enab);
18102 		} else {
18103 			dtrace_enabling_destroy(enab);
18104 		}
18105 
18106 		lck_mtx_unlock(&dtrace_lock);
18107 		lck_mtx_unlock(&cpu_lock);
18108 		dtrace_dof_destroy(dof);
18109 
18110 		return (err);
18111 	}
18112 
18113 	case DTRACEIOC_REPLICATE: {
18114 		dtrace_repldesc_t desc;
18115 		dtrace_probedesc_t *match = &desc.dtrpd_match;
18116 		dtrace_probedesc_t *create = &desc.dtrpd_create;
18117 		int err;
18118 
18119 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18120 			return (EFAULT);
18121 
18122 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18123 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18124 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18125 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18126 
18127 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18128 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18129 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18130 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18131 
18132 		lck_mtx_lock(&dtrace_lock);
18133 		err = dtrace_enabling_replicate(state, match, create);
18134 		lck_mtx_unlock(&dtrace_lock);
18135 
18136 		return (err);
18137 	}
18138 
18139 	case DTRACEIOC_PROBEMATCH:
18140 	case DTRACEIOC_PROBES: {
18141 		dtrace_probe_t *probe = NULL;
18142 		dtrace_probedesc_t desc;
18143 		dtrace_probekey_t pkey;
18144 		dtrace_id_t i;
18145 		int m = 0;
18146 		uint32_t priv;
18147 		uid_t uid;
18148 		zoneid_t zoneid;
18149 
18150 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18151 			return (EFAULT);
18152 
18153 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18154 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18155 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18156 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18157 
18158 		/*
18159 		 * Before we attempt to match this probe, we want to give
18160 		 * all providers the opportunity to provide it.
18161 		 */
18162 		if (desc.dtpd_id == DTRACE_IDNONE) {
18163 			lck_mtx_lock(&dtrace_provider_lock);
18164 			dtrace_probe_provide(&desc, NULL);
18165 			lck_mtx_unlock(&dtrace_provider_lock);
18166 			desc.dtpd_id++;
18167 		}
18168 
18169 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
18170 
18171 		lck_mtx_lock(&dtrace_lock);
18172 
18173 		if (cmd == DTRACEIOC_PROBEMATCH)  {
18174 			dtrace_probekey(&desc, &pkey);
18175 			pkey.dtpk_id = DTRACE_IDNONE;
18176 
18177 			/* Quiet compiler warning */
18178 			for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18179 				if ((probe = dtrace_probes[i - 1]) != NULL &&
18180 					(m = dtrace_match_probe(probe, &pkey,
18181 					priv, uid, zoneid)) != 0)
18182 					break;
18183 			}
18184 
18185 			if (m < 0) {
18186 				lck_mtx_unlock(&dtrace_lock);
18187 				return (EINVAL);
18188 			}
18189 			dtrace_probekey_release(&pkey);
18190 
18191 		} else {
18192                         /* Quiet compiler warning */
18193 			for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18194 				if ((probe = dtrace_probes[i - 1]) != NULL &&
18195 					dtrace_match_priv(probe, priv, uid, zoneid))
18196 					break;
18197 			}
18198 		}
18199 
18200 		if (probe == NULL) {
18201 			lck_mtx_unlock(&dtrace_lock);
18202 			return (ESRCH);
18203 		}
18204 
18205 		dtrace_probe_description(probe, &desc);
18206 		lck_mtx_unlock(&dtrace_lock);
18207 
18208 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18209 			return (EFAULT);
18210 
18211 		return (0);
18212 	}
18213 
18214 	case DTRACEIOC_PROBEARG: {
18215 		dtrace_argdesc_t desc;
18216 		dtrace_probe_t *probe;
18217 		dtrace_provider_t *prov;
18218 
18219 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18220 			return (EFAULT);
18221 
18222 		if (desc.dtargd_id == DTRACE_IDNONE)
18223 			return (EINVAL);
18224 
18225 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
18226 			return (EINVAL);
18227 
18228 		lck_mtx_lock(&dtrace_provider_lock);
18229 		lck_mtx_lock(&mod_lock);
18230 		lck_mtx_lock(&dtrace_lock);
18231 
18232                 /* Quiet compiler warning */
18233 		if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
18234 			lck_mtx_unlock(&dtrace_lock);
18235 			lck_mtx_unlock(&mod_lock);
18236 			lck_mtx_unlock(&dtrace_provider_lock);
18237 			return (EINVAL);
18238 		}
18239 
18240 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
18241 			lck_mtx_unlock(&dtrace_lock);
18242 			lck_mtx_unlock(&mod_lock);
18243 			lck_mtx_unlock(&dtrace_provider_lock);
18244 			return (EINVAL);
18245 		}
18246 
18247 		lck_mtx_unlock(&dtrace_lock);
18248 
18249 		prov = probe->dtpr_provider;
18250 
18251 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
18252 		/*
18253 		 * There isn't any typed information for this probe.
18254 		 * Set the argument number to DTRACE_ARGNONE.
18255 		 */
18256 			desc.dtargd_ndx = DTRACE_ARGNONE;
18257 		} else {
18258 			desc.dtargd_native[0] = '\0';
18259 			desc.dtargd_xlate[0] = '\0';
18260 			desc.dtargd_mapping = desc.dtargd_ndx;
18261 
18262 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
18263 			probe->dtpr_id, probe->dtpr_arg, &desc);
18264 		}
18265 
18266 		lck_mtx_unlock(&mod_lock);
18267 		lck_mtx_unlock(&dtrace_provider_lock);
18268 
18269 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18270 			return (EFAULT);
18271 
18272 		return (0);
18273 	}
18274 
18275 	case DTRACEIOC_GO: {
18276 		processorid_t cpuid;
18277 		rval = dtrace_state_go(state, &cpuid);
18278 
18279 		if (rval != 0)
18280 			return (rval);
18281 
18282 		if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18283 			return (EFAULT);
18284 
18285 		return (0);
18286 	}
18287 
18288 	case DTRACEIOC_STOP: {
18289 		processorid_t cpuid;
18290 
18291 		lck_mtx_lock(&dtrace_lock);
18292 		rval = dtrace_state_stop(state, &cpuid);
18293 		lck_mtx_unlock(&dtrace_lock);
18294 
18295 		if (rval != 0)
18296 			return (rval);
18297 
18298 		if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18299 			return (EFAULT);
18300 
18301 		return (0);
18302 	}
18303 
18304 	case DTRACEIOC_DOFGET: {
18305 		dof_hdr_t hdr, *dof;
18306 		uint64_t len;
18307 
18308 		if (copyin(arg, &hdr, sizeof (hdr)) != 0)
18309 			return (EFAULT);
18310 
18311 		lck_mtx_lock(&dtrace_lock);
18312 		dof = dtrace_dof_create(state);
18313 		lck_mtx_unlock(&dtrace_lock);
18314 
18315 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
18316 		rval = copyout(dof, arg, len);
18317 		dtrace_dof_destroy(dof);
18318 
18319 		return (rval == 0 ? 0 : EFAULT);
18320 	}
18321 
18322 	case DTRACEIOC_SLEEP: {
18323 		int64_t time;
18324 		uint64_t abstime;
18325 		uint64_t rvalue = DTRACE_WAKE_TIMEOUT;
18326 
18327 		if (copyin(arg, &time, sizeof(time)) != 0)
18328 			return (EFAULT);
18329 
18330 		nanoseconds_to_absolutetime((uint64_t)time, &abstime);
18331 		clock_absolutetime_interval_to_deadline(abstime, &abstime);
18332 
18333 		if (assert_wait_deadline(state, THREAD_ABORTSAFE, abstime) == THREAD_WAITING) {
18334 			if (state->dts_buf_over_limit > 0) {
18335 				clear_wait(current_thread(), THREAD_INTERRUPTED);
18336 				rvalue = DTRACE_WAKE_BUF_LIMIT;
18337 			} else {
18338 				thread_block(THREAD_CONTINUE_NULL);
18339 				if (state->dts_buf_over_limit > 0) {
18340 					rvalue = DTRACE_WAKE_BUF_LIMIT;
18341 				}
18342 			}
18343 		}
18344 
18345 		if (copyout(&rvalue, arg, sizeof(rvalue)) != 0)
18346 			return (EFAULT);
18347 
18348 		return (0);
18349 	}
18350 
18351 	case DTRACEIOC_SIGNAL: {
18352 		wakeup(state);
18353 		return (0);
18354 	}
18355 
18356 	case DTRACEIOC_AGGSNAP:
18357 	case DTRACEIOC_BUFSNAP: {
18358 		dtrace_bufdesc_t desc;
18359 		caddr_t cached;
18360 		boolean_t over_limit;
18361 		dtrace_buffer_t *buf;
18362 
18363 		if (copyin(arg, &desc, sizeof (desc)) != 0)
18364 			return (EFAULT);
18365 
18366 		if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
18367 			return (EINVAL);
18368 
18369 		lck_mtx_lock(&dtrace_lock);
18370 
18371 		if (cmd == DTRACEIOC_BUFSNAP) {
18372 			buf = &state->dts_buffer[desc.dtbd_cpu];
18373 		} else {
18374 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
18375 		}
18376 
18377 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
18378 			size_t sz = buf->dtb_offset;
18379 
18380 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
18381 				lck_mtx_unlock(&dtrace_lock);
18382 				return (EBUSY);
18383 			}
18384 
18385 			/*
18386 			 * If this buffer has already been consumed, we're
18387 			 * going to indicate that there's nothing left here
18388 			 * to consume.
18389 			 */
18390 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
18391 				lck_mtx_unlock(&dtrace_lock);
18392 
18393 				desc.dtbd_size = 0;
18394 				desc.dtbd_drops = 0;
18395 				desc.dtbd_errors = 0;
18396 				desc.dtbd_oldest = 0;
18397 				sz = sizeof (desc);
18398 
18399 				if (copyout(&desc, arg, sz) != 0)
18400 					return (EFAULT);
18401 
18402 				return (0);
18403 			}
18404 
18405 			/*
18406 			 * If this is a ring buffer that has wrapped, we want
18407 			 * to copy the whole thing out.
18408 			 */
18409 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
18410 				dtrace_buffer_polish(buf);
18411 				sz = buf->dtb_size;
18412 			}
18413 
18414 			if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
18415 				lck_mtx_unlock(&dtrace_lock);
18416 				return (EFAULT);
18417 			}
18418 
18419 			desc.dtbd_size = sz;
18420 			desc.dtbd_drops = buf->dtb_drops;
18421 			desc.dtbd_errors = buf->dtb_errors;
18422 			desc.dtbd_oldest = buf->dtb_xamot_offset;
18423 			desc.dtbd_timestamp = dtrace_gethrtime();
18424 
18425 			lck_mtx_unlock(&dtrace_lock);
18426 
18427 			if (copyout(&desc, arg, sizeof (desc)) != 0)
18428 				return (EFAULT);
18429 
18430 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
18431 
18432 			return (0);
18433 		}
18434 
18435 		if (buf->dtb_tomax == NULL) {
18436 			ASSERT(buf->dtb_xamot == NULL);
18437 			lck_mtx_unlock(&dtrace_lock);
18438 			return (ENOENT);
18439 		}
18440 
18441 		cached = buf->dtb_tomax;
18442 		over_limit = buf->dtb_cur_limit == buf->dtb_size;
18443 
18444 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18445 
18446 		dtrace_xcall(desc.dtbd_cpu,
18447 			(dtrace_xcall_t)dtrace_buffer_switch, buf);
18448 
18449 		state->dts_errors += buf->dtb_xamot_errors;
18450 
18451 		/*
18452 		* If the buffers did not actually switch, then the cross call
18453 		* did not take place -- presumably because the given CPU is
18454 		* not in the ready set.  If this is the case, we'll return
18455 		* ENOENT.
18456 		*/
18457 		if (buf->dtb_tomax == cached) {
18458 			ASSERT(buf->dtb_xamot != cached);
18459 			lck_mtx_unlock(&dtrace_lock);
18460 			return (ENOENT);
18461 		}
18462 
18463 		ASSERT(cached == buf->dtb_xamot);
18464 		/*
18465 		 * At this point we know the buffer have switched, so we
18466 		 * can decrement the over limit count if the buffer was over
18467 		 * its limit. The new buffer might already be over its limit
18468 		 * yet, but we don't care since we're guaranteed not to be
18469 		 * checking the buffer over limit count  at this point.
18470 		 */
18471 		if (over_limit) {
18472 			uint32_t old = os_atomic_dec_orig(&state->dts_buf_over_limit, relaxed);
18473 			#pragma unused(old)
18474 
18475 			/*
18476 			 * Verify that we didn't underflow the value
18477 			 */
18478 			ASSERT(old != 0);
18479 		}
18480 
18481 		/*
18482 		* We have our snapshot; now copy it out.
18483 		*/
18484 		if (dtrace_buffer_copyout(buf->dtb_xamot,
18485 					(user_addr_t)desc.dtbd_data,
18486 					buf->dtb_xamot_offset) != 0) {
18487 			lck_mtx_unlock(&dtrace_lock);
18488 			return (EFAULT);
18489 		}
18490 
18491 		desc.dtbd_size = buf->dtb_xamot_offset;
18492 		desc.dtbd_drops = buf->dtb_xamot_drops;
18493 		desc.dtbd_errors = buf->dtb_xamot_errors;
18494 		desc.dtbd_oldest = 0;
18495 		desc.dtbd_timestamp = buf->dtb_switched;
18496 
18497 		lck_mtx_unlock(&dtrace_lock);
18498 
18499 		/*
18500 		 * Finally, copy out the buffer description.
18501 		 */
18502 		if (copyout(&desc, arg, sizeof (desc)) != 0)
18503 			return (EFAULT);
18504 
18505 		return (0);
18506 	}
18507 
18508 	case DTRACEIOC_CONF: {
18509 		dtrace_conf_t conf;
18510 
18511 		bzero(&conf, sizeof (conf));
18512 		conf.dtc_difversion = DIF_VERSION;
18513 		conf.dtc_difintregs = DIF_DIR_NREGS;
18514 		conf.dtc_diftupregs = DIF_DTR_NREGS;
18515 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18516 
18517 		if (copyout(&conf, arg, sizeof (conf)) != 0)
18518 			return (EFAULT);
18519 
18520 		return (0);
18521 	}
18522 
18523 	case DTRACEIOC_STATUS: {
18524 		dtrace_status_t stat;
18525 		dtrace_dstate_t *dstate;
18526 		int j;
18527 		uint64_t nerrs;
18528 
18529 		/*
18530 		* See the comment in dtrace_state_deadman() for the reason
18531 		* for setting dts_laststatus to INT64_MAX before setting
18532 		* it to the correct value.
18533 		*/
18534 		state->dts_laststatus = INT64_MAX;
18535 		dtrace_membar_producer();
18536 		state->dts_laststatus = dtrace_gethrtime();
18537 
18538 		bzero(&stat, sizeof (stat));
18539 
18540 		lck_mtx_lock(&dtrace_lock);
18541 
18542 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18543 			lck_mtx_unlock(&dtrace_lock);
18544 			return (ENOENT);
18545 		}
18546 
18547 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18548 			stat.dtst_exiting = 1;
18549 
18550 		nerrs = state->dts_errors;
18551 		dstate = &state->dts_vstate.dtvs_dynvars;
18552 
18553 		zpercpu_foreach_cpu(i) {
18554 			dtrace_dstate_percpu_t *dcpu = zpercpu_get_cpu(dstate->dtds_percpu, i);
18555 
18556 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
18557 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18558 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18559 
18560 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18561 				stat.dtst_filled++;
18562 
18563 			nerrs += state->dts_buffer[i].dtb_errors;
18564 
18565 			for (j = 0; j < state->dts_nspeculations; j++) {
18566 				dtrace_speculation_t *spec;
18567 				dtrace_buffer_t *buf;
18568 
18569 				spec = &state->dts_speculations[j];
18570 				buf = &spec->dtsp_buffer[i];
18571 				stat.dtst_specdrops += buf->dtb_xamot_drops;
18572 			}
18573 		}
18574 
18575 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
18576 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18577 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18578 		stat.dtst_dblerrors = state->dts_dblerrors;
18579 		stat.dtst_killed =
18580 			(state->dts_activity == DTRACE_ACTIVITY_KILLED);
18581 		stat.dtst_errors = nerrs;
18582 
18583 		lck_mtx_unlock(&dtrace_lock);
18584 
18585 		if (copyout(&stat, arg, sizeof (stat)) != 0)
18586 			return (EFAULT);
18587 
18588 		return (0);
18589 	}
18590 
18591 	case DTRACEIOC_FORMAT: {
18592 		dtrace_fmtdesc_t fmt;
18593 		char *str;
18594 		int len;
18595 
18596 		if (copyin(arg, &fmt, sizeof (fmt)) != 0)
18597 			return (EFAULT);
18598 
18599 		lck_mtx_lock(&dtrace_lock);
18600 
18601 		if (fmt.dtfd_format == 0 ||
18602 			fmt.dtfd_format > state->dts_nformats) {
18603 			lck_mtx_unlock(&dtrace_lock);
18604 			return (EINVAL);
18605 		}
18606 
18607 		/*
18608 		 * Format strings are allocated contiguously and they are
18609 		 * never freed; if a format index is less than the number
18610 		 * of formats, we can assert that the format map is non-NULL
18611 		 * and that the format for the specified index is non-NULL.
18612 		 */
18613 		ASSERT(state->dts_formats != NULL);
18614 		str = state->dts_formats[fmt.dtfd_format - 1]->dtf_str;
18615 		ASSERT(str != NULL);
18616 
18617 		len = strlen(str) + 1;
18618 
18619 		if (len > fmt.dtfd_length) {
18620 			fmt.dtfd_length = len;
18621 
18622 			if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
18623 				lck_mtx_unlock(&dtrace_lock);
18624 				return (EINVAL);
18625 			}
18626 		} else {
18627 			if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
18628 				lck_mtx_unlock(&dtrace_lock);
18629 				return (EINVAL);
18630 			}
18631 		}
18632 
18633 		lck_mtx_unlock(&dtrace_lock);
18634 		return (0);
18635 	}
18636 
18637 	case DTRACEIOC_MODUUIDSLIST: {
18638 		size_t module_uuids_list_size;
18639 		dtrace_module_uuids_list_t* uuids_list;
18640 		uint64_t dtmul_count;
18641 
18642 		/*
18643 		 * Security restrictions make this operation illegal, if this is enabled DTrace
18644 		 * must refuse to provide any fbt probes.
18645 		 */
18646 		if (dtrace_fbt_probes_restricted()) {
18647 			cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
18648 			return (EPERM);
18649 		}
18650 
18651 		/*
18652 		 * Fail if the kernel symbol mode makes this operation illegal.
18653 		 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
18654 		 * for them without holding the dtrace_lock.
18655 		 */
18656 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
18657 		    dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
18658 			cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
18659 			return (EPERM);
18660 		}
18661 
18662 		/*
18663 		 * Read the number of symbolsdesc structs being passed in.
18664 		 */
18665 		if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
18666 		    &dtmul_count, sizeof(dtmul_count)) != 0) {
18667 			cmn_err(CE_WARN, "failed to copyin dtmul_count");
18668 			return (EFAULT);
18669 		}
18670 
18671 		/*
18672 		 * Range check the count. More than 2k kexts is probably an error.
18673 		 */
18674 		if (dtmul_count > 2048) {
18675 			cmn_err(CE_WARN, "dtmul_count is not valid");
18676 			return (EINVAL);
18677 		}
18678 
18679 		/*
18680 		 * For all queries, we return EINVAL when the user specified
18681 		 * count does not match the actual number of modules we find
18682 		 * available.
18683 		 *
18684 		 * If the user specified count is zero, then this serves as a
18685 		 * simple query to count the available modules in need of symbols.
18686 		 */
18687 
18688 		rval = 0;
18689 
18690 		if (dtmul_count == 0)
18691 		{
18692 			lck_mtx_lock(&mod_lock);
18693 			struct modctl* ctl = dtrace_modctl_list;
18694 			while (ctl) {
18695 				ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18696 				if (!MOD_SYMBOLS_DONE(ctl) && !MOD_IS_STATIC_KEXT(ctl)) {
18697 					dtmul_count++;
18698 					rval = EINVAL;
18699 				}
18700 				ctl = ctl->mod_next;
18701 			}
18702 			lck_mtx_unlock(&mod_lock);
18703 
18704 			if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
18705 				return (EFAULT);
18706 			else
18707 				return (rval);
18708 		}
18709 
18710 		/*
18711 		 * If we reach this point, then we have a request for full list data.
18712 		 * Allocate a correctly sized structure and copyin the data.
18713 		 */
18714 		module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
18715 		if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
18716 			return (ENOMEM);
18717 
18718 		/* NOTE! We can no longer exit this method via return */
18719 		if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
18720 			cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
18721 			rval = EFAULT;
18722 			goto moduuidslist_cleanup;
18723 		}
18724 
18725 		/*
18726 		 * Check that the count didn't change between the first copyin and the second.
18727 		 */
18728 		if (uuids_list->dtmul_count != dtmul_count) {
18729 			rval = EINVAL;
18730 			goto moduuidslist_cleanup;
18731 		}
18732 
18733 		/*
18734 		 * Build the list of UUID's that need symbols
18735 		 */
18736 		lck_mtx_lock(&mod_lock);
18737 
18738 		dtmul_count = 0;
18739 
18740 		struct modctl* ctl = dtrace_modctl_list;
18741 		while (ctl) {
18742 			/*
18743 			 * We assume that userspace symbols will be "better" than kernel level symbols,
18744 			 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
18745 			 * are available, add user syms if the module might use them.
18746 			 */
18747 			ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18748 			if (!MOD_SYMBOLS_DONE(ctl) && !MOD_IS_STATIC_KEXT(ctl)) {
18749 				UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
18750 				if (dtmul_count++ < uuids_list->dtmul_count) {
18751 					memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
18752 				}
18753 			}
18754 			ctl = ctl->mod_next;
18755 		}
18756 
18757 		lck_mtx_unlock(&mod_lock);
18758 
18759 		if (uuids_list->dtmul_count < dtmul_count)
18760 			rval = EINVAL;
18761 
18762 		uuids_list->dtmul_count = dtmul_count;
18763 
18764 		/*
18765 		 * Copyout the symbols list (or at least the count!)
18766 		 */
18767 		if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
18768 			cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
18769 			rval = EFAULT;
18770 		}
18771 
18772 	moduuidslist_cleanup:
18773 		/*
18774 		 * If we had to allocate struct memory, free it.
18775 		 */
18776 		if (uuids_list != NULL) {
18777 			kmem_free(uuids_list, module_uuids_list_size);
18778 		}
18779 
18780 		return rval;
18781 	}
18782 
18783 	case DTRACEIOC_PROVMODSYMS: {
18784 		size_t module_symbols_size;
18785 		dtrace_module_symbols_t* module_symbols;
18786 		uint64_t dtmodsyms_count;
18787 
18788 		/*
18789 		 * Security restrictions make this operation illegal, if this is enabled DTrace
18790 		 * must refuse to provide any fbt probes.
18791 		 */
18792 		if (dtrace_fbt_probes_restricted()) {
18793 			cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
18794 			return (EPERM);
18795 		}
18796 
18797 		/*
18798 		 * Fail if the kernel symbol mode makes this operation illegal.
18799 		 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
18800 		 * for them without holding the dtrace_lock.
18801 		 */
18802 		if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
18803 		    dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
18804 			cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
18805 			return (EPERM);
18806 		}
18807 
18808 		/*
18809 		 * Read the number of module symbols structs being passed in.
18810 		 */
18811 		if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
18812 		    &dtmodsyms_count, sizeof(dtmodsyms_count)) != 0) {
18813 			cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
18814 			return (EFAULT);
18815 		}
18816 
18817 		/* Ensure that we have at least one symbol. */
18818 		if (dtmodsyms_count == 0) {
18819 			cmn_err(CE_WARN, "Invalid dtmodsyms_count value");
18820 			return (EINVAL);
18821 		}
18822 
18823 		/* Safely calculate size we need for copyin buffer. */
18824 		module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
18825 		if (module_symbols_size == 0 || module_symbols_size > (size_t)dtrace_copy_maxsize()) {
18826 			cmn_err(CE_WARN, "Invalid module_symbols_size %ld", module_symbols_size);
18827 			return (EINVAL);
18828 		}
18829 
18830 		if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
18831 			return (ENOMEM);
18832 
18833 		rval = 0;
18834 
18835 		/* NOTE! We can no longer exit this method via return */
18836 		if (copyin(arg, module_symbols, module_symbols_size) != 0) {
18837 			cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t");
18838 			rval = EFAULT;
18839 			goto module_symbols_cleanup;
18840 		}
18841 
18842 		/*
18843 		 * Check that the count didn't change between the first copyin and the second.
18844 		 */
18845 		if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
18846 			rval = EINVAL;
18847 			goto module_symbols_cleanup;
18848 		}
18849 
18850 		/*
18851 		 * Find the modctl to add symbols to.
18852 		 */
18853 		lck_mtx_lock(&dtrace_provider_lock);
18854 		lck_mtx_lock(&mod_lock);
18855 
18856 		struct modctl* ctl = dtrace_modctl_list;
18857 		while (ctl) {
18858 			ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
18859 			if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl) && memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
18860 				dtrace_provider_t *prv;
18861 				ctl->mod_user_symbols = module_symbols;
18862 
18863 				/*
18864 				 * We're going to call each providers per-module provide operation
18865 				 * specifying only this module.
18866 				 */
18867 				for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
18868 					prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
18869 				/*
18870 				 * We gave every provider a chance to provide with the user syms, go ahead and clear them
18871 				 */
18872 				ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
18873 			}
18874 			ctl = ctl->mod_next;
18875 		}
18876 
18877 		lck_mtx_unlock(&mod_lock);
18878 		lck_mtx_unlock(&dtrace_provider_lock);
18879 
18880 	module_symbols_cleanup:
18881 		/*
18882 		 * If we had to allocate struct memory, free it.
18883 		 */
18884 		if (module_symbols != NULL) {
18885 			kmem_free(module_symbols, module_symbols_size);
18886 		}
18887 
18888 		return rval;
18889 	}
18890 
18891 	case DTRACEIOC_PROCWAITFOR: {
18892 		dtrace_procdesc_t pdesc = {
18893 			.p_name = {0},
18894 			.p_pid  = -1
18895 		};
18896 
18897 		if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
18898 			goto proc_waitfor_error;
18899 
18900 		if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
18901 			goto proc_waitfor_error;
18902 
18903 		if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
18904 			goto proc_waitfor_error;
18905 
18906 		return 0;
18907 
18908 	proc_waitfor_error:
18909 		/* The process was suspended, revert this since the client will not do it. */
18910 		if (pdesc.p_pid != -1) {
18911 			proc_t *proc = proc_find(pdesc.p_pid);
18912 			if (proc != PROC_NULL) {
18913 				task_pidresume(proc_task(proc));
18914 				proc_rele(proc);
18915 			}
18916 		}
18917 
18918 		return rval;
18919 	}
18920 
18921 	default:
18922 		break;
18923 	}
18924 
18925 	return (ENOTTY);
18926 }
18927 
18928 /*
18929  * APPLE NOTE:  dtrace_detach not implemented
18930  */
18931 #if !defined(__APPLE__)
18932 /*ARGSUSED*/
18933 static int
dtrace_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)18934 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18935 {
18936 	dtrace_state_t *state;
18937 
18938 	switch (cmd) {
18939 	case DDI_DETACH:
18940 		break;
18941 
18942 	case DDI_SUSPEND:
18943 		return (DDI_SUCCESS);
18944 
18945 	default:
18946 		return (DDI_FAILURE);
18947 	}
18948 
18949 	lck_mtx_lock(&cpu_lock);
18950 	lck_mtx_lock(&dtrace_provider_lock);
18951 	lck_mtx_lock(&dtrace_lock);
18952 
18953 	ASSERT(dtrace_opens == 0);
18954 
18955 	if (dtrace_helpers > 0) {
18956 		lck_mtx_unlock(&dtrace_lock);
18957 		lck_mtx_unlock(&dtrace_provider_lock);
18958 		lck_mtx_unlock(&cpu_lock);
18959 		return (DDI_FAILURE);
18960 	}
18961 
18962 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18963 		lck_mtx_unlock(&dtrace_lock);
18964 		lck_mtx_unlock(&dtrace_provider_lock);
18965 		lck_mtx_unlock(&cpu_lock);
18966 		return (DDI_FAILURE);
18967 	}
18968 
18969 	dtrace_provider = NULL;
18970 
18971 	if ((state = dtrace_anon_grab()) != NULL) {
18972 		/*
18973 		 * If there were ECBs on this state, the provider should
18974 		 * have not been allowed to detach; assert that there is
18975 		 * none.
18976 		 */
18977 		ASSERT(state->dts_necbs == 0);
18978 		dtrace_state_destroy(state);
18979 
18980 		/*
18981 		 * If we're being detached with anonymous state, we need to
18982 		 * indicate to the kernel debugger that DTrace is now inactive.
18983 		 */
18984 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18985 	}
18986 
18987 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18988 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18989 	dtrace_cpu_init = NULL;
18990 	dtrace_helpers_cleanup = NULL;
18991 	dtrace_helpers_fork = NULL;
18992 	dtrace_cpustart_init = NULL;
18993 	dtrace_cpustart_fini = NULL;
18994 	dtrace_debugger_init = NULL;
18995 	dtrace_debugger_fini = NULL;
18996 	dtrace_kreloc_init = NULL;
18997 	dtrace_kreloc_fini = NULL;
18998 	dtrace_modload = NULL;
18999 	dtrace_modunload = NULL;
19000 
19001 	lck_mtx_unlock(&cpu_lock);
19002 
19003 	if (dtrace_helptrace_enabled) {
19004 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
19005 		dtrace_helptrace_buffer = NULL;
19006 	}
19007 
19008 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
19009 	dtrace_probes = NULL;
19010 	dtrace_nprobes = 0;
19011 
19012 	dtrace_hash_destroy(dtrace_strings);
19013 	dtrace_hash_destroy(dtrace_byprov);
19014 	dtrace_hash_destroy(dtrace_bymod);
19015 	dtrace_hash_destroy(dtrace_byfunc);
19016 	dtrace_hash_destroy(dtrace_byname);
19017 	dtrace_strings = NULL;
19018 	dtrace_byprov = NULL;
19019 	dtrace_bymod = NULL;
19020 	dtrace_byfunc = NULL;
19021 	dtrace_byname = NULL;
19022 
19023 	kmem_cache_destroy(dtrace_state_cache);
19024 	vmem_destroy(dtrace_arena);
19025 
19026 	if (dtrace_toxrange != NULL) {
19027 		kmem_free(dtrace_toxrange,
19028 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
19029 		dtrace_toxrange = NULL;
19030 		dtrace_toxranges = 0;
19031 		dtrace_toxranges_max = 0;
19032 	}
19033 
19034 	ddi_remove_minor_node(dtrace_devi, NULL);
19035 	dtrace_devi = NULL;
19036 
19037 	ddi_soft_state_fini(&dtrace_softstate);
19038 
19039 	ASSERT(dtrace_vtime_references == 0);
19040 	ASSERT(dtrace_opens == 0);
19041 	ASSERT(dtrace_retained == NULL);
19042 
19043 	lck_mtx_unlock(&dtrace_lock);
19044 	lck_mtx_unlock(&dtrace_provider_lock);
19045 
19046 #ifdef illumos
19047 	/*
19048 	 * We don't destroy the task queue until after we have dropped our
19049 	 * locks (taskq_destroy() may block on running tasks).  To prevent
19050 	 * attempting to do work after we have effectively detached but before
19051 	 * the task queue has been destroyed, all tasks dispatched via the
19052 	 * task queue must check that DTrace is still attached before
19053 	 * performing any operation.
19054 	 */
19055 	taskq_destroy(dtrace_taskq);
19056 	dtrace_taskq = NULL;
19057 #endif
19058 
19059 	return (DDI_SUCCESS);
19060 }
19061 #endif  /* __APPLE__ */
19062 
19063 d_open_t _dtrace_open, helper_open;
19064 d_close_t _dtrace_close, helper_close;
19065 d_ioctl_t _dtrace_ioctl, helper_ioctl;
19066 
19067 int
_dtrace_open(dev_t dev,int flags,int devtype,struct proc * p)19068 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
19069 {
19070 #pragma unused(p)
19071 	dev_t locdev = dev;
19072 
19073 	return  dtrace_open( &locdev, flags, devtype, CRED());
19074 }
19075 
19076 int
helper_open(dev_t dev,int flags,int devtype,struct proc * p)19077 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
19078 {
19079 #pragma unused(dev,flags,devtype,p)
19080 	return 0;
19081 }
19082 
19083 int
_dtrace_close(dev_t dev,int flags,int devtype,struct proc * p)19084 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
19085 {
19086 #pragma unused(p)
19087 	return dtrace_close( dev, flags, devtype, CRED());
19088 }
19089 
19090 int
helper_close(dev_t dev,int flags,int devtype,struct proc * p)19091 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
19092 {
19093 #pragma unused(dev,flags,devtype,p)
19094 	return 0;
19095 }
19096 
19097 int
_dtrace_ioctl(dev_t dev,u_long cmd,caddr_t data,int fflag,struct proc * p)19098 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19099 {
19100 #pragma unused(p)
19101 	int err, rv = 0;
19102     user_addr_t uaddrp;
19103 
19104     if (proc_is64bit(p))
19105 		uaddrp = *(user_addr_t *)data;
19106 	else
19107 		uaddrp = (user_addr_t) *(uint32_t *)data;
19108 
19109 	err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
19110 
19111 	/* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19112 	if (err != 0) {
19113 		ASSERT( (err & 0xfffff000) == 0 );
19114 		return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19115 	} else if (rv != 0) {
19116 		ASSERT( (rv & 0xfff00000) == 0 );
19117 		return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19118 	} else
19119 		return 0;
19120 }
19121 
19122 int
helper_ioctl(dev_t dev,u_long cmd,caddr_t data,int fflag,struct proc * p)19123 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19124 {
19125 #pragma unused(dev,fflag,p)
19126 	int err, rv = 0;
19127 
19128 	err = dtrace_ioctl_helper(cmd, data, &rv);
19129 	/* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19130 	if (err != 0) {
19131 		ASSERT( (err & 0xfffff000) == 0 );
19132 		return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19133 	} else if (rv != 0) {
19134 		ASSERT( (rv & 0xfff00000) == 0 );
19135 		return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19136 	} else
19137 		return 0;
19138 }
19139 
19140 #define HELPER_MAJOR  -24 /* let the kernel pick the device number */
19141 
19142 #define nulldevfp        (void (*)(void))&nulldev
19143 
19144 const static struct cdevsw helper_cdevsw =
19145 {
19146 	.d_open = helper_open,
19147 	.d_close = helper_close,
19148 	.d_read = eno_rdwrt,
19149 	.d_write = eno_rdwrt,
19150 	.d_ioctl = helper_ioctl,
19151 	.d_stop = eno_stop,
19152 	.d_reset = eno_reset,
19153 	.d_select = eno_select,
19154 	.d_mmap = eno_mmap,
19155 	.d_strategy = eno_strat,
19156 	.d_reserved_1 = eno_getc,
19157 	.d_reserved_2 = eno_putc,
19158 };
19159 
19160 static int helper_majdevno = 0;
19161 
19162 static int gDTraceInited = 0;
19163 
19164 void
helper_init(void)19165 helper_init( void )
19166 {
19167 	/*
19168 	 * Once the "helper" is initialized, it can take ioctl calls that use locks
19169 	 * and zones initialized in dtrace_init. Make certain dtrace_init was called
19170 	 * before us.
19171 	 */
19172 
19173 	if (!gDTraceInited) {
19174 		panic("helper_init before dtrace_init");
19175 	}
19176 
19177 	if (0 >= helper_majdevno)
19178 	{
19179 		helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
19180 
19181 		if (helper_majdevno < 0) {
19182 			printf("helper_init: failed to allocate a major number!\n");
19183 			return;
19184 		}
19185 
19186 		if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19187 					DTRACEMNR_HELPER )) {
19188 			printf("dtrace_init: failed to devfs_make_node for helper!\n");
19189 			return;
19190 		}
19191 	} else
19192 		panic("helper_init: called twice!");
19193 }
19194 
19195 #undef HELPER_MAJOR
19196 
19197 static int
dtrace_clone_func(dev_t dev,int action)19198 dtrace_clone_func(dev_t dev, int action)
19199 {
19200 #pragma unused(dev)
19201 
19202 	if (action == DEVFS_CLONE_ALLOC) {
19203 		return dtrace_state_reserve();
19204 	}
19205 	else if (action == DEVFS_CLONE_FREE) {
19206 		return 0;
19207 	}
19208 	else return -1;
19209 }
19210 
19211 void dtrace_ast(void);
19212 
19213 void
dtrace_ast(void)19214 dtrace_ast(void)
19215 {
19216 	int i;
19217 	uint32_t clients = os_atomic_xchg(&dtrace_wake_clients, 0, relaxed);
19218 	if (clients == 0)
19219 		return;
19220 	/**
19221 	 * We disable preemption here to be sure that we won't get
19222 	 * interrupted by a wakeup to a thread that is higher
19223 	 * priority than us, so that we do issue all wakeups
19224 	 */
19225 	disable_preemption();
19226 	for (i = 0; i < DTRACE_NCLIENTS; i++) {
19227 		if (clients & (1 << i)) {
19228 			dtrace_state_t *state = dtrace_state_get(i);
19229 			if (state) {
19230 				wakeup(state);
19231 			}
19232 
19233 		}
19234 	}
19235 	enable_preemption();
19236 }
19237 
19238 
19239 #define DTRACE_MAJOR  -24 /* let the kernel pick the device number */
19240 
19241 static const struct cdevsw dtrace_cdevsw =
19242 {
19243 	.d_open = _dtrace_open,
19244 	.d_close = _dtrace_close,
19245 	.d_read = eno_rdwrt,
19246 	.d_write = eno_rdwrt,
19247 	.d_ioctl = _dtrace_ioctl,
19248 	.d_stop = eno_stop,
19249 	.d_reset = eno_reset,
19250 	.d_select = eno_select,
19251 	.d_mmap = eno_mmap,
19252 	.d_strategy = eno_strat,
19253 	.d_reserved_1 = eno_getc,
19254 	.d_reserved_2 = eno_putc,
19255 };
19256 
19257 LCK_ATTR_DECLARE(dtrace_lck_attr, 0, 0);
19258 LCK_GRP_DECLARE(dtrace_lck_grp, "dtrace");
19259 
19260 static int gMajDevNo;
19261 
dtrace_early_init(void)19262 void dtrace_early_init (void)
19263 {
19264 	dtrace_restriction_policy_load();
19265 
19266 	/*
19267 	 * See dtrace_impl.h for a description of kernel symbol modes.
19268 	 * The default is to wait for symbols from userspace (lazy symbols).
19269 	 */
19270 	if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
19271 		dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
19272 	}
19273 }
19274 
19275 void
dtrace_init(void)19276 dtrace_init( void )
19277 {
19278 	if (0 == gDTraceInited) {
19279 		unsigned int i, ncpu;
19280 		size_t size = sizeof(dtrace_buffer_memory_maxsize);
19281 
19282 		/*
19283 		 * Disable destructive actions when dtrace is running
19284 		 * in a restricted environment
19285 		 */
19286 		dtrace_destructive_disallow = dtrace_is_restricted() &&
19287 		    !dtrace_are_restrictions_relaxed();
19288 
19289 		/*
19290 		 * DTrace allocates buffers based on the maximum number
19291 		 * of enabled cpus. This call avoids any race when finding
19292 		 * that count.
19293 		 */
19294 		ASSERT(dtrace_max_cpus == 0);
19295 		ncpu = dtrace_max_cpus = ml_wait_max_cpus();
19296 
19297 		/*
19298 		 * Retrieve the size of the physical memory in order to define
19299 		 * the state buffer memory maximal size.  If we cannot retrieve
19300 		 * this value, we'll consider that we have 1Gb of memory per CPU, that's
19301 		 * still better than raising a kernel panic.
19302 		 */
19303 		if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
19304 		                             &size, NULL, 0))
19305 		{
19306 			dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
19307 			printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
19308 			       dtrace_buffer_memory_maxsize);
19309 		}
19310 
19311 		/*
19312 		 * Finally, divide by three to prevent DTrace from eating too
19313 		 * much memory.
19314 		 */
19315 		dtrace_buffer_memory_maxsize /= 3;
19316 		ASSERT(dtrace_buffer_memory_maxsize > 0);
19317 
19318 		gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
19319 
19320 		if (gMajDevNo < 0) {
19321 			printf("dtrace_init: failed to allocate a major number!\n");
19322 			gDTraceInited = 0;
19323 			return;
19324 		}
19325 
19326 		if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19327 					dtrace_clone_func, DTRACEMNR_DTRACE )) {
19328 			printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
19329 			gDTraceInited = 0;
19330 			return;
19331 		}
19332 
19333 		/*
19334 		 * The cpu_core structure consists of per-CPU state available in any context.
19335 		 * On some architectures, this may mean that the page(s) containing the
19336 		 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
19337 		 * is up to the platform to assure that this is performed properly.  Note that
19338 		 * the structure is sized to avoid false sharing.
19339 		 */
19340 
19341 		dtrace_modctl_list = NULL;
19342 
19343 		cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
19344 		for (i = 0; i < ncpu; ++i) {
19345 			lck_mtx_init(&cpu_core[i].cpuc_pid_lock, &dtrace_lck_grp, &dtrace_lck_attr);
19346 		}
19347 
19348 		cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
19349 		for (i = 0; i < ncpu; ++i) {
19350 			cpu_list[i].cpu_id = (processorid_t)i;
19351 			cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
19352 			LIST_INIT(&cpu_list[i].cpu_cyc_list);
19353 			lck_rw_init(&cpu_list[i].cpu_ft_lock, &dtrace_lck_grp, &dtrace_lck_attr);
19354 		}
19355 
19356 		/*
19357 		 * Initialize the CPU offline/online hooks.
19358 		 */
19359 		dtrace_install_cpu_hooks();
19360 
19361 		lck_mtx_lock(&cpu_lock);
19362 		for (i = 0; i < ncpu; ++i)
19363 			/* FIXME: track CPU configuration */
19364 			dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
19365 		lck_mtx_unlock(&cpu_lock);
19366 
19367 		(void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
19368 
19369 		dtrace_strings = dtrace_hash_create(dtrace_strkey_offset,
19370 		    offsetof(dtrace_string_t, dtst_str),
19371 		    offsetof(dtrace_string_t, dtst_next),
19372 		    offsetof(dtrace_string_t, dtst_prev));
19373 
19374 		/*
19375 		 * See dtrace_impl.h for a description of dof modes.
19376 		 * The default is lazy dof.
19377 		 *
19378 		 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
19379 		 * makes no sense...
19380 		 */
19381 		if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
19382 #if defined(XNU_TARGET_OS_OSX)
19383 			dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
19384 #else
19385 			dtrace_dof_mode = DTRACE_DOF_MODE_NEVER;
19386 #endif
19387 		}
19388 
19389 		/*
19390 		 * Sanity check of dof mode value.
19391 		 */
19392 		switch (dtrace_dof_mode) {
19393 			case DTRACE_DOF_MODE_NEVER:
19394 			case DTRACE_DOF_MODE_LAZY_ON:
19395 				/* valid modes, but nothing else we need to do */
19396 				break;
19397 
19398 			case DTRACE_DOF_MODE_LAZY_OFF:
19399 			case DTRACE_DOF_MODE_NON_LAZY:
19400 				/* Cannot wait for a dtrace_open to init fasttrap */
19401 				fasttrap_init();
19402 				break;
19403 
19404 			default:
19405 				/* Invalid, clamp to non lazy */
19406 				dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
19407 				fasttrap_init();
19408 				break;
19409 		}
19410 
19411 #if CONFIG_DTRACE
19412         if (dtrace_dof_mode != DTRACE_DOF_MODE_NEVER)
19413             commpage_update_dof(true);
19414 #endif
19415 
19416 		gDTraceInited = 1;
19417 
19418 	} else
19419 		panic("dtrace_init: called twice!");
19420 }
19421 
19422 void
dtrace_postinit(void)19423 dtrace_postinit(void)
19424 {
19425 	/*
19426 	 * Called from bsd_init after all provider's *_init() routines have been
19427 	 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
19428 	 * to go.
19429 	 */
19430 	dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0)); /* Punning a dev_t to a dev_info_t* */
19431 
19432 	/*
19433 	 * Add the mach_kernel to the module list for lazy processing
19434 	 */
19435 	struct kmod_info fake_kernel_kmod;
19436 	memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
19437 
19438 	strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
19439 	fake_kernel_kmod.id = 1;
19440 	fake_kernel_kmod.address = g_kernel_kmod_info.address;
19441 	fake_kernel_kmod.size = g_kernel_kmod_info.size;
19442 
19443 	/* Ensure we don't try to touch symbols if they are gone. */
19444 	boolean_t keepsyms = false;
19445 	PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
19446 
19447 	if (dtrace_module_loaded(&fake_kernel_kmod, (keepsyms) ? 0 : KMOD_DTRACE_NO_KERNEL_SYMS) != 0) {
19448 		printf("dtrace_postinit: Could not register mach_kernel modctl\n");
19449 	}
19450 
19451 	(void)OSKextRegisterKextsWithDTrace();
19452 }
19453 #undef DTRACE_MAJOR
19454 
19455 /*
19456  * Routines used to register interest in cpu's being added to or removed
19457  * from the system.
19458  */
19459 void
register_cpu_setup_func(cpu_setup_func_t * ignore1,void * ignore2)19460 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19461 {
19462 #pragma unused(ignore1,ignore2)
19463 }
19464 
19465 void
unregister_cpu_setup_func(cpu_setup_func_t * ignore1,void * ignore2)19466 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19467 {
19468 #pragma unused(ignore1,ignore2)
19469 }
19470