]> git.saurik.com Git - apple/xnu.git/blame - bsd/dev/dtrace/dtrace.c
xnu-4570.51.1.tar.gz
[apple/xnu.git] / bsd / dev / dtrace / dtrace.c
CommitLineData
2d21ac55
A
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
39236c6e 22/*
39037602 23 * Portions Copyright (c) 2013, 2016, Joyent, Inc. All rights reserved.
3e170ce0 24 * Portions Copyright (c) 2013 by Delphix. All rights reserved.
39236c6e
A
25 */
26
2d21ac55 27/*
6d2010ae 28 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
2d21ac55
A
29 * Use is subject to license terms.
30 */
31
b0d623f7 32/* #pragma ident "@(#)dtrace.c 1.65 08/07/02 SMI" */
2d21ac55
A
33
34/*
35 * DTrace - Dynamic Tracing for Solaris
36 *
37 * This is the implementation of the Solaris Dynamic Tracing framework
38 * (DTrace). The user-visible interface to DTrace is described at length in
39 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
40 * library, the in-kernel DTrace framework, and the DTrace providers are
41 * described in the block comments in the <sys/dtrace.h> header file. The
42 * internal architecture of DTrace is described in the block comments in the
43 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
44 * implementation very much assume mastery of all of these sources; if one has
45 * an unanswered question about the implementation, one should consult them
46 * first.
47 *
48 * The functions here are ordered roughly as follows:
49 *
50 * - Probe context functions
51 * - Probe hashing functions
52 * - Non-probe context utility functions
53 * - Matching functions
54 * - Provider-to-Framework API functions
55 * - Probe management functions
56 * - DIF object functions
57 * - Format functions
58 * - Predicate functions
59 * - ECB functions
60 * - Buffer functions
61 * - Enabling functions
62 * - DOF functions
63 * - Anonymous enabling functions
39037602 64 * - Process functions
2d21ac55
A
65 * - Consumer state functions
66 * - Helper functions
67 * - Hook functions
68 * - Driver cookbook functions
69 *
70 * Each group of functions begins with a block comment labelled the "DTrace
71 * [Group] Functions", allowing one to find each block by searching forward
72 * on capital-f functions.
73 */
2d21ac55
A
74#include <sys/errno.h>
75#include <sys/types.h>
76#include <sys/stat.h>
77#include <sys/conf.h>
78#include <sys/systm.h>
79#include <sys/dtrace_impl.h>
80#include <sys/param.h>
6d2010ae 81#include <sys/proc_internal.h>
2d21ac55
A
82#include <sys/ioctl.h>
83#include <sys/fcntl.h>
84#include <miscfs/devfs/devfs.h>
85#include <sys/malloc.h>
86#include <sys/kernel_types.h>
87#include <sys/proc_internal.h>
88#include <sys/uio_internal.h>
89#include <sys/kauth.h>
90#include <vm/pmap.h>
91#include <sys/user.h>
92#include <mach/exception_types.h>
93#include <sys/signalvar.h>
6d2010ae 94#include <mach/task.h>
2d21ac55 95#include <kern/zalloc.h>
b0d623f7 96#include <kern/ast.h>
39037602 97#include <kern/sched_prim.h>
fe8ab488 98#include <kern/task.h>
b0d623f7 99#include <netinet/in.h>
39037602
A
100#include <libkern/sysctl.h>
101#include <sys/kdebug.h>
b0d623f7 102
5ba3f43e
A
103#if MONOTONIC
104#include <kern/monotonic.h>
105#include <machine/monotonic.h>
106#endif /* MONOTONIC */
107
a39ff7e2
A
108#include <IOKit/IOPlatformExpert.h>
109
6d2010ae 110#include <kern/cpu_data.h>
b0d623f7
A
111extern uint32_t pmap_find_phys(void *, uint64_t);
112extern boolean_t pmap_valid_page(uint32_t);
6d2010ae
A
113extern void OSKextRegisterKextsWithDTrace(void);
114extern kmod_info_t g_kernel_kmod_info;
b0d623f7
A
115
116/* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
117#define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
2d21ac55
A
118
119#define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
120
121extern void dtrace_suspend(void);
122extern void dtrace_resume(void);
123extern void dtrace_init(void);
124extern void helper_init(void);
b0d623f7 125extern void fasttrap_init(void);
39037602
A
126
127static int dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
b0d623f7
A
128extern void dtrace_lazy_dofs_destroy(proc_t *);
129extern void dtrace_postinit(void);
2d21ac55 130
39037602
A
131extern void dtrace_proc_fork(proc_t*, proc_t*, int);
132extern void dtrace_proc_exec(proc_t*);
133extern void dtrace_proc_exit(proc_t*);
2d21ac55
A
134/*
135 * DTrace Tunable Variables
136 *
fe8ab488
A
137 * The following variables may be dynamically tuned by using sysctl(8), the
138 * variables being stored in the kern.dtrace namespace. For example:
139 * sysctl kern.dtrace.dof_maxsize = 1048575 # 1M
2d21ac55
A
140 *
141 * In general, the only variables that one should be tuning this way are those
142 * that affect system-wide DTrace behavior, and for which the default behavior
143 * is undesirable. Most of these variables are tunable on a per-consumer
144 * basis using DTrace options, and need not be tuned on a system-wide basis.
145 * When tuning these variables, avoid pathological values; while some attempt
146 * is made to verify the integrity of these variables, they are not considered
147 * part of the supported interface to DTrace, and they are therefore not
fe8ab488 148 * checked comprehensively.
2d21ac55 149 */
fe8ab488
A
150uint64_t dtrace_buffer_memory_maxsize = 0; /* initialized in dtrace_init */
151uint64_t dtrace_buffer_memory_inuse = 0;
2d21ac55 152int dtrace_destructive_disallow = 0;
2d21ac55
A
153dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
154size_t dtrace_difo_maxsize = (256 * 1024);
5ba3f43e 155dtrace_optval_t dtrace_dof_maxsize = (512 * 1024);
ecc0ceb4
A
156dtrace_optval_t dtrace_statvar_maxsize = (16 * 1024);
157dtrace_optval_t dtrace_statvar_maxsize_max = (16 * 10 * 1024);
2d21ac55
A
158size_t dtrace_actions_max = (16 * 1024);
159size_t dtrace_retain_max = 1024;
160dtrace_optval_t dtrace_helper_actions_max = 32;
6d2010ae 161dtrace_optval_t dtrace_helper_providers_max = 64;
2d21ac55
A
162dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
163size_t dtrace_strsize_default = 256;
39037602
A
164dtrace_optval_t dtrace_strsize_min = 8;
165dtrace_optval_t dtrace_strsize_max = 65536;
39236c6e
A
166dtrace_optval_t dtrace_cleanrate_default = 990099000; /* 1.1 hz */
167dtrace_optval_t dtrace_cleanrate_min = 20000000; /* 50 hz */
2d21ac55
A
168dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
169dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
170dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
171dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
172dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
173dtrace_optval_t dtrace_nspec_default = 1;
174dtrace_optval_t dtrace_specsize_default = 32 * 1024;
175dtrace_optval_t dtrace_stackframes_default = 20;
176dtrace_optval_t dtrace_ustackframes_default = 20;
177dtrace_optval_t dtrace_jstackframes_default = 50;
178dtrace_optval_t dtrace_jstackstrsize_default = 512;
39037602
A
179dtrace_optval_t dtrace_buflimit_default = 75;
180dtrace_optval_t dtrace_buflimit_min = 1;
181dtrace_optval_t dtrace_buflimit_max = 99;
2d21ac55
A
182int dtrace_msgdsize_max = 128;
183hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
184hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
185int dtrace_devdepth_max = 32;
186int dtrace_err_verbose;
fe8ab488 187int dtrace_provide_private_probes = 0;
2d21ac55
A
188hrtime_t dtrace_deadman_interval = NANOSEC;
189hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
190hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
191
192/*
193 * DTrace External Variables
194 *
195 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
196 * available to DTrace consumers via the backtick (`) syntax. One of these,
197 * dtrace_zero, is made deliberately so: it is provided as a source of
198 * well-known, zero-filled memory. While this variable is not documented,
199 * it is used by some translators as an implementation detail.
200 */
201const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
39236c6e 202unsigned int dtrace_max_cpus = 0; /* number of enabled cpus */
2d21ac55
A
203/*
204 * DTrace Internal Variables
205 */
206static dev_info_t *dtrace_devi; /* device info */
207static vmem_t *dtrace_arena; /* probe ID arena */
2d21ac55
A
208static taskq_t *dtrace_taskq; /* task queue */
209static dtrace_probe_t **dtrace_probes; /* array of all probes */
210static int dtrace_nprobes; /* number of probes */
211static dtrace_provider_t *dtrace_provider; /* provider list */
212static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
213static int dtrace_opens; /* number of opens */
214static int dtrace_helpers; /* number of helpers */
2d21ac55
A
215static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
216static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
217static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
218static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
219static int dtrace_toxranges; /* number of toxic ranges */
220static int dtrace_toxranges_max; /* size of toxic range array */
221static dtrace_anon_t dtrace_anon; /* anonymous enabling */
222static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
223static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
224static kthread_t *dtrace_panicked; /* panicking thread */
225static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
226static dtrace_genid_t dtrace_probegen; /* current probe generation */
227static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
228static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
b0d623f7 229static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
2d21ac55 230static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
fe8ab488 231
b0d623f7 232static int dtrace_dof_mode; /* See dtrace_impl.h for a description of Darwin's dof modes. */
6d2010ae
A
233
234 /*
235 * This does't quite fit as an internal variable, as it must be accessed in
236 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
237 */
238int dtrace_kernel_symbol_mode; /* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
39037602 239static uint32_t dtrace_wake_clients;
2d21ac55 240
fe8ab488 241
2d21ac55
A
242/*
243 * To save memory, some common memory allocations are given a
b0d623f7 244 * unique zone. For example, dtrace_probe_t is 72 bytes in size,
2d21ac55
A
245 * which means it would fall into the kalloc.128 bucket. With
246 * 20k elements allocated, the space saved is substantial.
247 */
248
249struct zone *dtrace_probe_t_zone;
6d2010ae
A
250
251static int dtrace_module_unloaded(struct kmod_info *kmod);
2d21ac55
A
252
253/*
254 * DTrace Locking
255 * DTrace is protected by three (relatively coarse-grained) locks:
256 *
257 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
258 * including enabling state, probes, ECBs, consumer state, helper state,
259 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
260 * probe context is lock-free -- synchronization is handled via the
261 * dtrace_sync() cross call mechanism.
262 *
263 * (2) dtrace_provider_lock is required when manipulating provider state, or
264 * when provider state must be held constant.
265 *
266 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
267 * when meta provider state must be held constant.
268 *
269 * The lock ordering between these three locks is dtrace_meta_lock before
270 * dtrace_provider_lock before dtrace_lock. (In particular, there are
271 * several places where dtrace_provider_lock is held by the framework as it
272 * calls into the providers -- which then call back into the framework,
273 * grabbing dtrace_lock.)
274 *
275 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
276 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
277 * role as a coarse-grained lock; it is acquired before both of these locks.
278 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
279 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
280 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
281 * acquired _between_ dtrace_provider_lock and dtrace_lock.
282 */
283
fe8ab488 284
2d21ac55
A
285/*
286 * APPLE NOTE:
287 *
fe8ab488
A
288 * For porting purposes, all kmutex_t vars have been changed
289 * to lck_mtx_t, which require explicit initialization.
2d21ac55 290 *
fe8ab488 291 * kmutex_t becomes lck_mtx_t
2d21ac55
A
292 * mutex_enter() becomes lck_mtx_lock()
293 * mutex_exit() becomes lck_mtx_unlock()
294 *
295 * Lock asserts are changed like this:
296 *
297 * ASSERT(MUTEX_HELD(&cpu_lock));
298 * becomes:
5ba3f43e 299 * LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 300 *
2d21ac55
A
301 */
302static lck_mtx_t dtrace_lock; /* probe state lock */
303static lck_mtx_t dtrace_provider_lock; /* provider state lock */
304static lck_mtx_t dtrace_meta_lock; /* meta-provider state lock */
2d21ac55 305static lck_rw_t dtrace_dof_mode_lock; /* dof mode lock */
2d21ac55
A
306
307/*
308 * DTrace Provider Variables
309 *
310 * These are the variables relating to DTrace as a provider (that is, the
311 * provider of the BEGIN, END, and ERROR probes).
312 */
313static dtrace_pattr_t dtrace_provider_attr = {
314{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
315{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
316{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
317{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
318{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
319};
320
321static void
322dtrace_nullop(void)
323{}
324
6d2010ae
A
325static int
326dtrace_enable_nullop(void)
327{
328 return (0);
329}
330
2d21ac55
A
331static dtrace_pops_t dtrace_provider_ops = {
332 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
333 (void (*)(void *, struct modctl *))dtrace_nullop,
6d2010ae 334 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
2d21ac55
A
335 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
336 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
337 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
338 NULL,
339 NULL,
340 NULL,
341 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
342};
343
344static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
345static dtrace_id_t dtrace_probeid_end; /* special END probe */
346dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
347
348/*
349 * DTrace Helper Tracing Variables
350 */
351uint32_t dtrace_helptrace_next = 0;
352uint32_t dtrace_helptrace_nlocals;
353char *dtrace_helptrace_buffer;
b0d623f7 354size_t dtrace_helptrace_bufsize = 512 * 1024;
2d21ac55 355
b0d623f7 356#if DEBUG
2d21ac55
A
357int dtrace_helptrace_enabled = 1;
358#else
359int dtrace_helptrace_enabled = 0;
360#endif
361
5ba3f43e
A
362#if defined (__arm64__)
363/*
364 * The ioctl for adding helper DOF is based on the
365 * size of a user_addr_t. We need to recognize both
366 * U32 and U64 as the same action.
367 */
368#define DTRACEHIOC_ADDDOF_U32 _IOW('h', 4, user32_addr_t)
369#define DTRACEHIOC_ADDDOF_U64 _IOW('h', 4, user64_addr_t)
370#endif /* __arm64__ */
fe8ab488 371
2d21ac55
A
372/*
373 * DTrace Error Hashing
374 *
375 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
376 * table. This is very useful for checking coverage of tests that are
377 * expected to induce DIF or DOF processing errors, and may be useful for
378 * debugging problems in the DIF code generator or in DOF generation . The
379 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
380 */
b0d623f7 381#if DEBUG
2d21ac55
A
382static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
383static const char *dtrace_errlast;
384static kthread_t *dtrace_errthread;
385static lck_mtx_t dtrace_errlock;
386#endif
387
388/*
389 * DTrace Macros and Constants
390 *
391 * These are various macros that are useful in various spots in the
392 * implementation, along with a few random constants that have no meaning
393 * outside of the implementation. There is no real structure to this cpp
394 * mishmash -- but is there ever?
395 */
396#define DTRACE_HASHSTR(hash, probe) \
397 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
398
399#define DTRACE_HASHNEXT(hash, probe) \
400 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
401
402#define DTRACE_HASHPREV(hash, probe) \
403 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
404
405#define DTRACE_HASHEQ(hash, lhs, rhs) \
406 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
407 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
408
409#define DTRACE_AGGHASHSIZE_SLEW 17
410
b0d623f7
A
411#define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
412
2d21ac55
A
413/*
414 * The key for a thread-local variable consists of the lower 61 bits of the
fe8ab488 415 * current_thread(), plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
2d21ac55
A
416 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
417 * equal to a variable identifier. This is necessary (but not sufficient) to
418 * assure that global associative arrays never collide with thread-local
419 * variables. To guarantee that they cannot collide, we must also define the
420 * order for keying dynamic variables. That order is:
421 *
422 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
423 *
424 * Because the variable-key and the tls-key are in orthogonal spaces, there is
425 * no way for a global variable key signature to match a thread-local key
426 * signature.
427 */
39236c6e 428#if defined (__x86_64__)
b0d623f7
A
429/* FIXME: two function calls!! */
430#define DTRACE_TLS_THRKEY(where) { \
431 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
432 uint64_t thr = (uintptr_t)current_thread(); \
433 ASSERT(intr < (1 << 3)); \
434 (where) = ((thr + DIF_VARIABLE_MAX) & \
435 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
436}
5ba3f43e
A
437#elif defined(__arm__)
438/* FIXME: three function calls!!! */
439#define DTRACE_TLS_THRKEY(where) { \
440 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
441 uint64_t thr = (uintptr_t)current_thread(); \
442 uint_t pid = (uint_t)dtrace_proc_selfpid(); \
443 ASSERT(intr < (1 << 3)); \
444 (where) = (((thr << 32 | pid) + DIF_VARIABLE_MAX) & \
445 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
446}
447#elif defined (__arm64__)
448/* FIXME: two function calls!! */
449#define DTRACE_TLS_THRKEY(where) { \
450 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
451 uint64_t thr = (uintptr_t)current_thread(); \
452 ASSERT(intr < (1 << 3)); \
453 (where) = ((thr + DIF_VARIABLE_MAX) & \
454 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
455}
2d21ac55 456#else
39236c6e 457#error Unknown architecture
b0d623f7 458#endif
2d21ac55 459
b0d623f7
A
460#define DT_BSWAP_8(x) ((x) & 0xff)
461#define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
462#define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
463#define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
464
465#define DT_MASK_LO 0x00000000FFFFFFFFULL
466
2d21ac55
A
467#define DTRACE_STORE(type, tomax, offset, what) \
468 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
469
39236c6e 470
b0d623f7
A
471#define DTRACE_ALIGNCHECK(addr, size, flags) \
472 if (addr & (MIN(size,4) - 1)) { \
473 *flags |= CPU_DTRACE_BADALIGN; \
474 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
475 return (0); \
476 }
b0d623f7 477
39037602
A
478#define DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz) \
479do { \
480 if ((remp) != NULL) { \
481 *(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr); \
482 } \
483} while (0)
484
485
b0d623f7
A
486/*
487 * Test whether a range of memory starting at testaddr of size testsz falls
488 * within the range of memory described by addr, sz. We take care to avoid
489 * problems with overflow and underflow of the unsigned quantities, and
490 * disallow all negative sizes. Ranges of size 0 are allowed.
491 */
492#define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
493 ((testaddr) - (baseaddr) < (basesz) && \
494 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
495 (testaddr) + (testsz) >= (testaddr))
496
497/*
498 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
499 * alloc_sz on the righthand side of the comparison in order to avoid overflow
500 * or underflow in the comparison with it. This is simpler than the INRANGE
501 * check above, because we know that the dtms_scratch_ptr is valid in the
502 * range. Allocations of size zero are allowed.
503 */
504#define DTRACE_INSCRATCH(mstate, alloc_sz) \
505 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
506 (mstate)->dtms_scratch_ptr >= (alloc_sz))
2d21ac55 507
6d2010ae 508#define RECOVER_LABEL(bits) dtraceLoadRecover##bits:
2d21ac55 509
39037602 510#if defined (__x86_64__) || (defined (__arm__) || defined (__arm64__))
2d21ac55
A
511#define DTRACE_LOADFUNC(bits) \
512/*CSTYLED*/ \
2d21ac55
A
513uint##bits##_t dtrace_load##bits(uintptr_t addr); \
514 \
515uint##bits##_t \
516dtrace_load##bits(uintptr_t addr) \
517{ \
518 size_t size = bits / NBBY; \
519 /*CSTYLED*/ \
520 uint##bits##_t rval = 0; \
521 int i; \
2d21ac55
A
522 volatile uint16_t *flags = (volatile uint16_t *) \
523 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
524 \
525 DTRACE_ALIGNCHECK(addr, size, flags); \
526 \
527 for (i = 0; i < dtrace_toxranges; i++) { \
528 if (addr >= dtrace_toxrange[i].dtt_limit) \
529 continue; \
530 \
531 if (addr + size <= dtrace_toxrange[i].dtt_base) \
532 continue; \
533 \
534 /* \
535 * This address falls within a toxic region; return 0. \
536 */ \
537 *flags |= CPU_DTRACE_BADADDR; \
538 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
539 return (0); \
540 } \
541 \
b0d623f7 542 { \
6d2010ae 543 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
b0d623f7
A
544 *flags |= CPU_DTRACE_NOFAULT; \
545 recover = dtrace_set_thread_recover(current_thread(), recover); \
546 /*CSTYLED*/ \
547 /* \
548 * PR6394061 - avoid device memory that is unpredictably \
549 * mapped and unmapped \
550 */ \
551 if (pmap_valid_page(pmap_find_phys(kernel_pmap, addr))) \
552 rval = *((volatile uint##bits##_t *)addr); \
39037602
A
553 else { \
554 *flags |= CPU_DTRACE_BADADDR; \
555 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
556 return (0); \
557 } \
558 \
b0d623f7
A
559 RECOVER_LABEL(bits); \
560 (void)dtrace_set_thread_recover(current_thread(), recover); \
561 *flags &= ~CPU_DTRACE_NOFAULT; \
562 } \
563 \
564 return (rval); \
565}
566#else /* all other architectures */
39236c6e 567#error Unknown Architecture
b0d623f7 568#endif
2d21ac55 569
2d21ac55
A
570#ifdef __LP64__
571#define dtrace_loadptr dtrace_load64
572#else
573#define dtrace_loadptr dtrace_load32
574#endif
575
576#define DTRACE_DYNHASH_FREE 0
577#define DTRACE_DYNHASH_SINK 1
578#define DTRACE_DYNHASH_VALID 2
579
6d2010ae 580#define DTRACE_MATCH_FAIL -1
2d21ac55
A
581#define DTRACE_MATCH_NEXT 0
582#define DTRACE_MATCH_DONE 1
583#define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
584#define DTRACE_STATE_ALIGN 64
585
586#define DTRACE_FLAGS2FLT(flags) \
587 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
588 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
589 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
590 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
591 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
592 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
593 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
594 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
b0d623f7 595 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
2d21ac55
A
596 DTRACEFLT_UNKNOWN)
597
598#define DTRACEACT_ISSTRING(act) \
599 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
600 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
601
b0d623f7 602
b0d623f7 603static size_t dtrace_strlen(const char *, size_t);
2d21ac55
A
604static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
605static void dtrace_enabling_provide(dtrace_provider_t *);
39037602
A
606static int dtrace_enabling_match(dtrace_enabling_t *, int *, dtrace_match_cond_t *cond);
607static void dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond);
2d21ac55
A
608static void dtrace_enabling_matchall(void);
609static dtrace_state_t *dtrace_anon_grab(void);
610static uint64_t dtrace_helper(int, dtrace_mstate_t *,
611 dtrace_state_t *, uint64_t, uint64_t);
612static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
613static void dtrace_buffer_drop(dtrace_buffer_t *);
614static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
615 dtrace_state_t *, dtrace_mstate_t *);
616static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
617 dtrace_optval_t);
d190cdc3 618static int dtrace_ecb_create_enable(dtrace_probe_t *, void *, void *);
2d21ac55 619static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
39037602
A
620static int dtrace_canload_remains(uint64_t, size_t, size_t *,
621 dtrace_mstate_t *, dtrace_vstate_t *);
622static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
623 dtrace_mstate_t *, dtrace_vstate_t *);
2d21ac55 624
fe8ab488
A
625
626/*
627 * DTrace sysctl handlers
628 *
629 * These declarations and functions are used for a deeper DTrace configuration.
630 * Most of them are not per-consumer basis and may impact the other DTrace
631 * consumers. Correctness may not be supported for all the variables, so you
632 * should be careful about what values you are using.
633 */
634
635SYSCTL_DECL(_kern_dtrace);
636SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
637
638static int
639sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
640{
641#pragma unused(oidp, arg2)
642 int changed, error;
643 int value = *(int *) arg1;
644
645 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
646 if (error || !changed)
647 return (error);
648
649 if (value != 0 && value != 1)
650 return (ERANGE);
651
652 lck_mtx_lock(&dtrace_lock);
653 dtrace_err_verbose = value;
654 lck_mtx_unlock(&dtrace_lock);
655
656 return (0);
657}
658
659/*
660 * kern.dtrace.err_verbose
661 *
662 * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
663 * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
664 */
665SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
666 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
667 &dtrace_err_verbose, 0,
668 sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
669
670static int
671sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
672{
673#pragma unused(oidp, arg2, req)
674 int changed, error;
675 uint64_t value = *(uint64_t *) arg1;
676
677 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
678 if (error || !changed)
679 return (error);
680
681 if (value <= dtrace_buffer_memory_inuse)
682 return (ERANGE);
683
684 lck_mtx_lock(&dtrace_lock);
685 dtrace_buffer_memory_maxsize = value;
686 lck_mtx_unlock(&dtrace_lock);
687
688 return (0);
689}
690
691/*
692 * kern.dtrace.buffer_memory_maxsize
693 *
694 * Set DTrace maximal size in bytes used by all the consumers' state buffers. By default
695 * the limit is PHYS_MEM / 3 for *all* consumers. Attempting to set a null, a negative value
696 * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
697 */
698SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
699 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
700 &dtrace_buffer_memory_maxsize, 0,
701 sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
702
703/*
704 * kern.dtrace.buffer_memory_inuse
705 *
706 * Current state buffer memory used, in bytes, by all the DTrace consumers.
707 * This value is read-only.
708 */
709SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
710 &dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
711
712static int
713sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
714{
715#pragma unused(oidp, arg2, req)
716 int changed, error;
717 size_t value = *(size_t*) arg1;
718
719 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
720 if (error || !changed)
721 return (error);
722
723 if (value <= 0)
724 return (ERANGE);
725
726 lck_mtx_lock(&dtrace_lock);
727 dtrace_difo_maxsize = value;
728 lck_mtx_unlock(&dtrace_lock);
729
730 return (0);
731}
732
733/*
734 * kern.dtrace.difo_maxsize
735 *
736 * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
737 * to get the default value. Attempting to set a null or negative size will
738 * result in a failure.
739 */
740SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
741 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
742 &dtrace_difo_maxsize, 0,
743 sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
744
745static int
746sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
747{
748#pragma unused(oidp, arg2, req)
749 int changed, error;
750 dtrace_optval_t value = *(dtrace_optval_t *) arg1;
751
752 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
753 if (error || !changed)
754 return (error);
755
756 if (value <= 0)
757 return (ERANGE);
758
759 lck_mtx_lock(&dtrace_lock);
760 dtrace_dof_maxsize = value;
761 lck_mtx_unlock(&dtrace_lock);
762
763 return (0);
764}
765
766/*
767 * kern.dtrace.dof_maxsize
768 *
769 * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
770 * get the default value. Attempting to set a null or negative size will result
771 * in a failure.
772 */
773SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
774 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
775 &dtrace_dof_maxsize, 0,
776 sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
777
778static int
ecc0ceb4 779sysctl_dtrace_statvar_maxsize SYSCTL_HANDLER_ARGS
fe8ab488
A
780{
781#pragma unused(oidp, arg2, req)
782 int changed, error;
783 dtrace_optval_t value = *(dtrace_optval_t*) arg1;
784
785 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
786 if (error || !changed)
787 return (error);
788
789 if (value <= 0)
790 return (ERANGE);
ecc0ceb4
A
791 if (value > dtrace_statvar_maxsize_max)
792 return (ERANGE);
fe8ab488
A
793
794 lck_mtx_lock(&dtrace_lock);
ecc0ceb4 795 dtrace_statvar_maxsize = value;
fe8ab488
A
796 lck_mtx_unlock(&dtrace_lock);
797
798 return (0);
799}
800
801/*
802 * kern.dtrace.global_maxsize
803 *
ecc0ceb4
A
804 * Set the variable max size in bytes, check the definition of
805 * dtrace_statvar_maxsize to get the default value. Attempting to set a null,
806 * too high or negative size will result in a failure.
fe8ab488
A
807 */
808SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
809 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
ecc0ceb4
A
810 &dtrace_statvar_maxsize, 0,
811 sysctl_dtrace_statvar_maxsize, "Q", "dtrace statvar maxsize");
fe8ab488
A
812
813static int
814sysctl_dtrace_provide_private_probes SYSCTL_HANDLER_ARGS
815{
816#pragma unused(oidp, arg2)
817 int error;
818 int value = *(int *) arg1;
819
820 error = sysctl_io_number(req, value, sizeof(value), &value, NULL);
821 if (error)
822 return (error);
823
5ba3f43e
A
824 if (req->newptr) {
825 if (value != 0 && value != 1)
826 return (ERANGE);
fe8ab488 827
5ba3f43e
A
828 /*
829 * We do not allow changing this back to zero, as private probes
830 * would still be left registered
831 */
832 if (value != 1)
833 return (EPERM);
fe8ab488 834
5ba3f43e
A
835 lck_mtx_lock(&dtrace_lock);
836 dtrace_provide_private_probes = value;
837 lck_mtx_unlock(&dtrace_lock);
838 }
fe8ab488
A
839 return (0);
840}
841
842/*
843 * kern.dtrace.provide_private_probes
844 *
845 * Set whether the providers must provide the private probes. This is
846 * mainly used by the FBT provider to request probes for the private/static
847 * symbols.
848 */
849SYSCTL_PROC(_kern_dtrace, OID_AUTO, provide_private_probes,
850 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
851 &dtrace_provide_private_probes, 0,
852 sysctl_dtrace_provide_private_probes, "I", "provider must provide the private probes");
853
2d21ac55
A
854/*
855 * DTrace Probe Context Functions
856 *
857 * These functions are called from probe context. Because probe context is
858 * any context in which C may be called, arbitrarily locks may be held,
859 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
860 * As a result, functions called from probe context may only call other DTrace
861 * support functions -- they may not interact at all with the system at large.
862 * (Note that the ASSERT macro is made probe-context safe by redefining it in
863 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
864 * loads are to be performed from probe context, they _must_ be in terms of
865 * the safe dtrace_load*() variants.
866 *
867 * Some functions in this block are not actually called from probe context;
868 * for these functions, there will be a comment above the function reading
869 * "Note: not called from probe context."
870 */
2d21ac55
A
871
872int
873dtrace_assfail(const char *a, const char *f, int l)
874{
316670eb 875 panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
2d21ac55
A
876
877 /*
878 * We just need something here that even the most clever compiler
879 * cannot optimize away.
880 */
881 return (a[(uintptr_t)f]);
882}
883
884/*
885 * Atomically increment a specified error counter from probe context.
886 */
887static void
888dtrace_error(uint32_t *counter)
889{
890 /*
891 * Most counters stored to in probe context are per-CPU counters.
892 * However, there are some error conditions that are sufficiently
893 * arcane that they don't merit per-CPU storage. If these counters
894 * are incremented concurrently on different CPUs, scalability will be
895 * adversely affected -- but we don't expect them to be white-hot in a
896 * correctly constructed enabling...
897 */
898 uint32_t oval, nval;
899
900 do {
901 oval = *counter;
902
903 if ((nval = oval + 1) == 0) {
904 /*
905 * If the counter would wrap, set it to 1 -- assuring
906 * that the counter is never zero when we have seen
907 * errors. (The counter must be 32-bits because we
908 * aren't guaranteed a 64-bit compare&swap operation.)
909 * To save this code both the infamy of being fingered
910 * by a priggish news story and the indignity of being
911 * the target of a neo-puritan witch trial, we're
912 * carefully avoiding any colorful description of the
913 * likelihood of this condition -- but suffice it to
914 * say that it is only slightly more likely than the
915 * overflow of predicate cache IDs, as discussed in
916 * dtrace_predicate_create().
917 */
918 nval = 1;
919 }
920 } while (dtrace_cas32(counter, oval, nval) != oval);
921}
922
923/*
924 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
925 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
926 */
927DTRACE_LOADFUNC(8)
928DTRACE_LOADFUNC(16)
929DTRACE_LOADFUNC(32)
930DTRACE_LOADFUNC(64)
931
932static int
933dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
934{
935 if (dest < mstate->dtms_scratch_base)
936 return (0);
937
938 if (dest + size < dest)
939 return (0);
940
941 if (dest + size > mstate->dtms_scratch_ptr)
942 return (0);
943
944 return (1);
945}
946
947static int
39037602 948dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
2d21ac55
A
949 dtrace_statvar_t **svars, int nsvars)
950{
951 int i;
952
ecc0ceb4
A
953 size_t maxglobalsize, maxlocalsize;
954
39037602
A
955 maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
956 maxlocalsize = (maxglobalsize) * NCPU;
ecc0ceb4
A
957
958 if (nsvars == 0)
959 return (0);
960
2d21ac55
A
961 for (i = 0; i < nsvars; i++) {
962 dtrace_statvar_t *svar = svars[i];
ecc0ceb4
A
963 uint8_t scope;
964 size_t size;
2d21ac55 965
ecc0ceb4 966 if (svar == NULL || (size = svar->dtsv_size) == 0)
2d21ac55
A
967 continue;
968
ecc0ceb4
A
969 scope = svar->dtsv_var.dtdv_scope;
970
971 /**
972 * We verify that our size is valid in the spirit of providing
973 * defense in depth: we want to prevent attackers from using
974 * DTrace to escalate an orthogonal kernel heap corruption bug
975 * into the ability to store to arbitrary locations in memory.
976 */
39037602
A
977 VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
978 (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
ecc0ceb4 979
39037602
A
980 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size)) {
981 DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
982 svar->dtsv_size);
2d21ac55 983 return (1);
39037602 984 }
2d21ac55
A
985 }
986
987 return (0);
988}
989
990/*
991 * Check to see if the address is within a memory region to which a store may
992 * be issued. This includes the DTrace scratch areas, and any DTrace variable
993 * region. The caller of dtrace_canstore() is responsible for performing any
994 * alignment checks that are needed before stores are actually executed.
995 */
996static int
997dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
998 dtrace_vstate_t *vstate)
39037602
A
999{
1000 return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
1001}
1002/*
1003 * Implementation of dtrace_canstore which communicates the upper bound of the
1004 * allowed memory region.
1005 */
1006static int
1007dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
1008 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
2d21ac55 1009{
2d21ac55
A
1010 /*
1011 * First, check to see if the address is in scratch space...
1012 */
b0d623f7 1013 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
39037602
A
1014 mstate->dtms_scratch_size)) {
1015 DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
1016 mstate->dtms_scratch_size);
2d21ac55 1017 return (1);
39037602 1018 }
2d21ac55
A
1019 /*
1020 * Now check to see if it's a dynamic variable. This check will pick
1021 * up both thread-local variables and any global dynamically-allocated
1022 * variables.
1023 */
b0d623f7
A
1024 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
1025 vstate->dtvs_dynvars.dtds_size)) {
1026 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
1027 uintptr_t base = (uintptr_t)dstate->dtds_base +
1028 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
1029 uintptr_t chunkoffs;
39037602 1030 dtrace_dynvar_t *dvar;
b0d623f7
A
1031
1032 /*
1033 * Before we assume that we can store here, we need to make
1034 * sure that it isn't in our metadata -- storing to our
1035 * dynamic variable metadata would corrupt our state. For
1036 * the range to not include any dynamic variable metadata,
1037 * it must:
1038 *
1039 * (1) Start above the hash table that is at the base of
1040 * the dynamic variable space
1041 *
1042 * (2) Have a starting chunk offset that is beyond the
1043 * dtrace_dynvar_t that is at the base of every chunk
1044 *
1045 * (3) Not span a chunk boundary
1046 *
39037602
A
1047 * (4) Not be in the tuple space of a dynamic variable
1048 *
b0d623f7
A
1049 */
1050 if (addr < base)
1051 return (0);
1052
1053 chunkoffs = (addr - base) % dstate->dtds_chunksize;
1054
1055 if (chunkoffs < sizeof (dtrace_dynvar_t))
1056 return (0);
1057
1058 if (chunkoffs + sz > dstate->dtds_chunksize)
1059 return (0);
1060
39037602
A
1061 dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
1062
1063 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
1064 return (0);
1065
1066 if (chunkoffs < sizeof (dtrace_dynvar_t) +
1067 ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
1068 return (0);
1069
2d21ac55 1070 return (1);
b0d623f7 1071 }
2d21ac55
A
1072
1073 /*
1074 * Finally, check the static local and global variables. These checks
1075 * take the longest, so we perform them last.
1076 */
39037602 1077 if (dtrace_canstore_statvar(addr, sz, remain,
2d21ac55
A
1078 vstate->dtvs_locals, vstate->dtvs_nlocals))
1079 return (1);
1080
39037602 1081 if (dtrace_canstore_statvar(addr, sz, remain,
2d21ac55
A
1082 vstate->dtvs_globals, vstate->dtvs_nglobals))
1083 return (1);
1084
1085 return (0);
1086}
1087
b0d623f7
A
1088
1089/*
1090 * Convenience routine to check to see if the address is within a memory
1091 * region in which a load may be issued given the user's privilege level;
1092 * if not, it sets the appropriate error flags and loads 'addr' into the
1093 * illegal value slot.
1094 *
1095 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
1096 * appropriate memory access protection.
1097 */
5ba3f43e 1098int
b0d623f7
A
1099dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1100 dtrace_vstate_t *vstate)
39037602
A
1101{
1102 return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
1103}
1104
1105/*
1106 * Implementation of dtrace_canload which communicates the upper bound of the
1107 * allowed memory region.
1108 */
1109static int
1110dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
1111 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
b0d623f7 1112{
b0d623f7 1113 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
b0d623f7
A
1114
1115 /*
1116 * If we hold the privilege to read from kernel memory, then
1117 * everything is readable.
1118 */
39037602
A
1119 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1120 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
b0d623f7 1121 return (1);
39037602 1122 }
b0d623f7
A
1123
1124 /*
1125 * You can obviously read that which you can store.
1126 */
39037602 1127 if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
b0d623f7
A
1128 return (1);
1129
1130 /*
1131 * We're allowed to read from our own string table.
1132 */
1133 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
39037602
A
1134 mstate->dtms_difo->dtdo_strlen)) {
1135 DTRACE_RANGE_REMAIN(remain, addr,
1136 mstate->dtms_difo->dtdo_strtab,
1137 mstate->dtms_difo->dtdo_strlen);
b0d623f7 1138 return (1);
39037602 1139 }
b0d623f7
A
1140
1141 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1142 *illval = addr;
1143 return (0);
1144}
1145
1146/*
1147 * Convenience routine to check to see if a given string is within a memory
1148 * region in which a load may be issued given the user's privilege level;
1149 * this exists so that we don't need to issue unnecessary dtrace_strlen()
1150 * calls in the event that the user has all privileges.
1151 */
1152static int
39037602
A
1153dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1154 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
b0d623f7 1155{
39037602 1156 size_t rsize;
b0d623f7
A
1157
1158 /*
1159 * If we hold the privilege to read from kernel memory, then
1160 * everything is readable.
1161 */
39037602
A
1162 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1163 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
b0d623f7 1164 return (1);
39037602 1165 }
b0d623f7 1166
39037602
A
1167 /*
1168 * Even if the caller is uninterested in querying the remaining valid
1169 * range, it is required to ensure that the access is allowed.
1170 */
1171 if (remain == NULL) {
1172 remain = &rsize;
1173 }
1174 if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1175 size_t strsz;
1176 /*
1177 * Perform the strlen after determining the length of the
1178 * memory region which is accessible. This prevents timing
1179 * information from being used to find NULs in memory which is
1180 * not accessible to the caller.
1181 */
1182 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1183 MIN(sz, *remain));
1184 if (strsz <= *remain) {
1185 return (1);
1186 }
1187 }
b0d623f7
A
1188
1189 return (0);
1190}
1191
1192/*
1193 * Convenience routine to check to see if a given variable is within a memory
1194 * region in which a load may be issued given the user's privilege level.
1195 */
1196static int
39037602
A
1197dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1198 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
b0d623f7
A
1199{
1200 size_t sz;
1201 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1202
39037602
A
1203 /*
1204 * Calculate the max size before performing any checks since even
1205 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1206 * return the max length via 'remain'.
1207 */
1208 if (type->dtdt_kind == DIF_TYPE_STRING) {
1209 dtrace_state_t *state = vstate->dtvs_state;
1210
1211 if (state != NULL) {
1212 sz = state->dts_options[DTRACEOPT_STRSIZE];
1213 } else {
1214 /*
1215 * In helper context, we have a NULL state; fall back
1216 * to using the system-wide default for the string size
1217 * in this case.
1218 */
1219 sz = dtrace_strsize_default;
1220 }
1221 } else {
1222 sz = type->dtdt_size;
1223 }
1224
b0d623f7
A
1225 /*
1226 * If we hold the privilege to read from kernel memory, then
1227 * everything is readable.
1228 */
39037602
A
1229 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1230 DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
b0d623f7 1231 return (1);
39037602 1232 }
b0d623f7 1233
39037602
A
1234 if (type->dtdt_kind == DIF_TYPE_STRING) {
1235 return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1236 vstate));
1237 }
1238 return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1239 vstate));
b0d623f7
A
1240}
1241
2d21ac55
A
1242/*
1243 * Compare two strings using safe loads.
1244 */
1245static int
1246dtrace_strncmp(char *s1, char *s2, size_t limit)
1247{
1248 uint8_t c1, c2;
1249 volatile uint16_t *flags;
1250
1251 if (s1 == s2 || limit == 0)
1252 return (0);
1253
1254 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1255
1256 do {
b0d623f7 1257 if (s1 == NULL) {
2d21ac55 1258 c1 = '\0';
b0d623f7 1259 } else {
2d21ac55 1260 c1 = dtrace_load8((uintptr_t)s1++);
b0d623f7 1261 }
2d21ac55 1262
b0d623f7 1263 if (s2 == NULL) {
2d21ac55 1264 c2 = '\0';
b0d623f7 1265 } else {
2d21ac55 1266 c2 = dtrace_load8((uintptr_t)s2++);
b0d623f7 1267 }
2d21ac55
A
1268
1269 if (c1 != c2)
1270 return (c1 - c2);
1271 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1272
1273 return (0);
1274}
1275
1276/*
1277 * Compute strlen(s) for a string using safe memory accesses. The additional
1278 * len parameter is used to specify a maximum length to ensure completion.
1279 */
1280static size_t
1281dtrace_strlen(const char *s, size_t lim)
1282{
1283 uint_t len;
1284
b0d623f7 1285 for (len = 0; len != lim; len++) {
2d21ac55
A
1286 if (dtrace_load8((uintptr_t)s++) == '\0')
1287 break;
b0d623f7 1288 }
2d21ac55
A
1289
1290 return (len);
1291}
1292
1293/*
1294 * Check if an address falls within a toxic region.
1295 */
1296static int
1297dtrace_istoxic(uintptr_t kaddr, size_t size)
1298{
1299 uintptr_t taddr, tsize;
1300 int i;
1301
1302 for (i = 0; i < dtrace_toxranges; i++) {
1303 taddr = dtrace_toxrange[i].dtt_base;
1304 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1305
1306 if (kaddr - taddr < tsize) {
1307 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1308 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1309 return (1);
1310 }
1311
1312 if (taddr - kaddr < size) {
1313 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1314 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1315 return (1);
1316 }
1317 }
1318
1319 return (0);
1320}
1321
1322/*
1323 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1324 * memory specified by the DIF program. The dst is assumed to be safe memory
1325 * that we can store to directly because it is managed by DTrace. As with
1326 * standard bcopy, overlapping copies are handled properly.
1327 */
1328static void
1329dtrace_bcopy(const void *src, void *dst, size_t len)
1330{
1331 if (len != 0) {
1332 uint8_t *s1 = dst;
1333 const uint8_t *s2 = src;
1334
1335 if (s1 <= s2) {
1336 do {
1337 *s1++ = dtrace_load8((uintptr_t)s2++);
1338 } while (--len != 0);
1339 } else {
1340 s2 += len;
1341 s1 += len;
1342
1343 do {
1344 *--s1 = dtrace_load8((uintptr_t)--s2);
1345 } while (--len != 0);
1346 }
1347 }
1348}
1349
1350/*
1351 * Copy src to dst using safe memory accesses, up to either the specified
1352 * length, or the point that a nul byte is encountered. The src is assumed to
1353 * be unsafe memory specified by the DIF program. The dst is assumed to be
1354 * safe memory that we can store to directly because it is managed by DTrace.
1355 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1356 */
1357static void
1358dtrace_strcpy(const void *src, void *dst, size_t len)
1359{
1360 if (len != 0) {
1361 uint8_t *s1 = dst, c;
1362 const uint8_t *s2 = src;
1363
1364 do {
1365 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1366 } while (--len != 0 && c != '\0');
1367 }
1368}
1369
1370/*
1371 * Copy src to dst, deriving the size and type from the specified (BYREF)
1372 * variable type. The src is assumed to be unsafe memory specified by the DIF
1373 * program. The dst is assumed to be DTrace variable memory that is of the
1374 * specified type; we assume that we can store to directly.
1375 */
1376static void
39037602 1377dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
2d21ac55
A
1378{
1379 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1380
b0d623f7 1381 if (type->dtdt_kind == DIF_TYPE_STRING) {
39037602 1382 dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
b0d623f7 1383 } else {
39037602
A
1384 dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1385 }
b0d623f7 1386}
2d21ac55
A
1387
1388/*
1389 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1390 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1391 * safe memory that we can access directly because it is managed by DTrace.
1392 */
1393static int
1394dtrace_bcmp(const void *s1, const void *s2, size_t len)
1395{
1396 volatile uint16_t *flags;
1397
1398 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1399
1400 if (s1 == s2)
1401 return (0);
1402
1403 if (s1 == NULL || s2 == NULL)
1404 return (1);
1405
1406 if (s1 != s2 && len != 0) {
1407 const uint8_t *ps1 = s1;
1408 const uint8_t *ps2 = s2;
1409
1410 do {
1411 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1412 return (1);
1413 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1414 }
1415 return (0);
1416}
1417
1418/*
1419 * Zero the specified region using a simple byte-by-byte loop. Note that this
1420 * is for safe DTrace-managed memory only.
1421 */
1422static void
1423dtrace_bzero(void *dst, size_t len)
1424{
1425 uchar_t *cp;
1426
1427 for (cp = dst; len != 0; len--)
1428 *cp++ = 0;
1429}
1430
b0d623f7
A
1431static void
1432dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1433{
1434 uint64_t result[2];
1435
1436 result[0] = addend1[0] + addend2[0];
1437 result[1] = addend1[1] + addend2[1] +
1438 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1439
1440 sum[0] = result[0];
1441 sum[1] = result[1];
1442}
1443
1444/*
1445 * Shift the 128-bit value in a by b. If b is positive, shift left.
1446 * If b is negative, shift right.
1447 */
1448static void
1449dtrace_shift_128(uint64_t *a, int b)
1450{
1451 uint64_t mask;
1452
1453 if (b == 0)
1454 return;
1455
1456 if (b < 0) {
1457 b = -b;
1458 if (b >= 64) {
1459 a[0] = a[1] >> (b - 64);
1460 a[1] = 0;
1461 } else {
1462 a[0] >>= b;
1463 mask = 1LL << (64 - b);
1464 mask -= 1;
1465 a[0] |= ((a[1] & mask) << (64 - b));
1466 a[1] >>= b;
1467 }
1468 } else {
1469 if (b >= 64) {
1470 a[1] = a[0] << (b - 64);
1471 a[0] = 0;
1472 } else {
1473 a[1] <<= b;
1474 mask = a[0] >> (64 - b);
1475 a[1] |= mask;
1476 a[0] <<= b;
1477 }
1478 }
1479}
1480
1481/*
1482 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1483 * use native multiplication on those, and then re-combine into the
1484 * resulting 128-bit value.
1485 *
1486 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1487 * hi1 * hi2 << 64 +
1488 * hi1 * lo2 << 32 +
1489 * hi2 * lo1 << 32 +
1490 * lo1 * lo2
1491 */
1492static void
1493dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1494{
1495 uint64_t hi1, hi2, lo1, lo2;
1496 uint64_t tmp[2];
1497
1498 hi1 = factor1 >> 32;
1499 hi2 = factor2 >> 32;
1500
1501 lo1 = factor1 & DT_MASK_LO;
1502 lo2 = factor2 & DT_MASK_LO;
1503
1504 product[0] = lo1 * lo2;
1505 product[1] = hi1 * hi2;
1506
1507 tmp[0] = hi1 * lo2;
1508 tmp[1] = 0;
1509 dtrace_shift_128(tmp, 32);
1510 dtrace_add_128(product, tmp, product);
1511
1512 tmp[0] = hi2 * lo1;
1513 tmp[1] = 0;
1514 dtrace_shift_128(tmp, 32);
1515 dtrace_add_128(product, tmp, product);
1516}
1517
2d21ac55
A
1518/*
1519 * This privilege check should be used by actions and subroutines to
1520 * verify that the user credentials of the process that enabled the
1521 * invoking ECB match the target credentials
1522 */
1523static int
1524dtrace_priv_proc_common_user(dtrace_state_t *state)
1525{
1526 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1527
1528 /*
1529 * We should always have a non-NULL state cred here, since if cred
1530 * is null (anonymous tracing), we fast-path bypass this routine.
1531 */
1532 ASSERT(s_cr != NULL);
1533
2d21ac55 1534 if ((cr = dtrace_CRED()) != NULL &&
6d2010ae
A
1535 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1536 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1537 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1538 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1539 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1540 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
2d21ac55
A
1541 return (1);
1542
1543 return (0);
1544}
1545
1546/*
1547 * This privilege check should be used by actions and subroutines to
1548 * verify that the zone of the process that enabled the invoking ECB
1549 * matches the target credentials
1550 */
1551static int
1552dtrace_priv_proc_common_zone(dtrace_state_t *state)
1553{
1554 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
fe8ab488 1555#pragma unused(cr, s_cr, state) /* __APPLE__ */
2d21ac55
A
1556
1557 /*
1558 * We should always have a non-NULL state cred here, since if cred
1559 * is null (anonymous tracing), we fast-path bypass this routine.
1560 */
1561 ASSERT(s_cr != NULL);
1562
fe8ab488 1563 return 1; /* APPLE NOTE: Darwin doesn't do zones. */
2d21ac55
A
1564}
1565
1566/*
1567 * This privilege check should be used by actions and subroutines to
1568 * verify that the process has not setuid or changed credentials.
1569 */
2d21ac55
A
1570static int
1571dtrace_priv_proc_common_nocd(void)
1572{
1573 return 1; /* Darwin omits "No Core Dump" flag. */
1574}
2d21ac55
A
1575
1576static int
1577dtrace_priv_proc_destructive(dtrace_state_t *state)
1578{
1579 int action = state->dts_cred.dcr_action;
1580
cf7d32b8
A
1581 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1582 goto bad;
fe8ab488
A
1583
1584 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1585 goto bad;
cf7d32b8 1586
2d21ac55
A
1587 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1588 dtrace_priv_proc_common_zone(state) == 0)
1589 goto bad;
1590
1591 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1592 dtrace_priv_proc_common_user(state) == 0)
1593 goto bad;
1594
1595 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1596 dtrace_priv_proc_common_nocd() == 0)
1597 goto bad;
1598
1599 return (1);
1600
1601bad:
1602 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1603
1604 return (0);
1605}
1606
1607static int
1608dtrace_priv_proc_control(dtrace_state_t *state)
1609{
cf7d32b8
A
1610 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1611 goto bad;
fe8ab488
A
1612
1613 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1614 goto bad;
cf7d32b8 1615
2d21ac55
A
1616 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1617 return (1);
1618
1619 if (dtrace_priv_proc_common_zone(state) &&
1620 dtrace_priv_proc_common_user(state) &&
1621 dtrace_priv_proc_common_nocd())
1622 return (1);
1623
cf7d32b8 1624bad:
2d21ac55
A
1625 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1626
1627 return (0);
1628}
1629
1630static int
1631dtrace_priv_proc(dtrace_state_t *state)
1632{
cf7d32b8
A
1633 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1634 goto bad;
fe8ab488 1635
39037602 1636 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed() && !dtrace_can_attach_to_proc(current_proc()))
fe8ab488 1637 goto bad;
cf7d32b8 1638
2d21ac55
A
1639 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1640 return (1);
1641
cf7d32b8 1642bad:
2d21ac55
A
1643 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1644
1645 return (0);
1646}
1647
fe8ab488
A
1648/*
1649 * The P_LNOATTACH check is an Apple specific check.
1650 * We need a version of dtrace_priv_proc() that omits
1651 * that check for PID and EXECNAME accesses
1652 */
935ed37a
A
1653static int
1654dtrace_priv_proc_relaxed(dtrace_state_t *state)
1655{
1656
1657 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1658 return (1);
1659
1660 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1661
1662 return (0);
1663}
935ed37a 1664
2d21ac55
A
1665static int
1666dtrace_priv_kernel(dtrace_state_t *state)
1667{
39037602 1668 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed())
fe8ab488
A
1669 goto bad;
1670
2d21ac55
A
1671 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1672 return (1);
1673
fe8ab488 1674bad:
2d21ac55
A
1675 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1676
1677 return (0);
1678}
1679
1680static int
1681dtrace_priv_kernel_destructive(dtrace_state_t *state)
1682{
fe8ab488
A
1683 if (dtrace_is_restricted())
1684 goto bad;
1685
2d21ac55
A
1686 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1687 return (1);
1688
fe8ab488 1689bad:
2d21ac55
A
1690 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1691
1692 return (0);
1693}
1694
1695/*
1696 * Note: not called from probe context. This function is called
1697 * asynchronously (and at a regular interval) from outside of probe context to
1698 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1699 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1700 */
fe8ab488 1701static void
2d21ac55
A
1702dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1703{
1704 dtrace_dynvar_t *dirty;
1705 dtrace_dstate_percpu_t *dcpu;
1706 int i, work = 0;
1707
c910b4d9 1708 for (i = 0; i < (int)NCPU; i++) {
2d21ac55
A
1709 dcpu = &dstate->dtds_percpu[i];
1710
1711 ASSERT(dcpu->dtdsc_rinsing == NULL);
1712
1713 /*
1714 * If the dirty list is NULL, there is no dirty work to do.
1715 */
1716 if (dcpu->dtdsc_dirty == NULL)
1717 continue;
1718
1719 /*
1720 * If the clean list is non-NULL, then we're not going to do
1721 * any work for this CPU -- it means that there has not been
1722 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1723 * since the last time we cleaned house.
1724 */
1725 if (dcpu->dtdsc_clean != NULL)
1726 continue;
1727
1728 work = 1;
1729
1730 /*
1731 * Atomically move the dirty list aside.
1732 */
1733 do {
1734 dirty = dcpu->dtdsc_dirty;
1735
1736 /*
1737 * Before we zap the dirty list, set the rinsing list.
1738 * (This allows for a potential assertion in
1739 * dtrace_dynvar(): if a free dynamic variable appears
1740 * on a hash chain, either the dirty list or the
1741 * rinsing list for some CPU must be non-NULL.)
1742 */
1743 dcpu->dtdsc_rinsing = dirty;
1744 dtrace_membar_producer();
1745 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1746 dirty, NULL) != dirty);
1747 }
1748
1749 if (!work) {
1750 /*
1751 * We have no work to do; we can simply return.
1752 */
1753 return;
1754 }
1755
1756 dtrace_sync();
1757
c910b4d9 1758 for (i = 0; i < (int)NCPU; i++) {
2d21ac55
A
1759 dcpu = &dstate->dtds_percpu[i];
1760
1761 if (dcpu->dtdsc_rinsing == NULL)
1762 continue;
1763
1764 /*
1765 * We are now guaranteed that no hash chain contains a pointer
1766 * into this dirty list; we can make it clean.
1767 */
1768 ASSERT(dcpu->dtdsc_clean == NULL);
1769 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1770 dcpu->dtdsc_rinsing = NULL;
1771 }
1772
1773 /*
1774 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1775 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1776 * This prevents a race whereby a CPU incorrectly decides that
1777 * the state should be something other than DTRACE_DSTATE_CLEAN
1778 * after dtrace_dynvar_clean() has completed.
1779 */
1780 dtrace_sync();
1781
1782 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1783}
1784
1785/*
1786 * Depending on the value of the op parameter, this function looks-up,
1787 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1788 * allocation is requested, this function will return a pointer to a
1789 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1790 * variable can be allocated. If NULL is returned, the appropriate counter
1791 * will be incremented.
1792 */
fe8ab488 1793static dtrace_dynvar_t *
2d21ac55 1794dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
b0d623f7
A
1795 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1796 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
2d21ac55
A
1797{
1798 uint64_t hashval = DTRACE_DYNHASH_VALID;
1799 dtrace_dynhash_t *hash = dstate->dtds_hash;
1800 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1801 processorid_t me = CPU->cpu_id, cpu = me;
1802 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1803 size_t bucket, ksize;
1804 size_t chunksize = dstate->dtds_chunksize;
1805 uintptr_t kdata, lock, nstate;
1806 uint_t i;
1807
1808 ASSERT(nkeys != 0);
1809
1810 /*
1811 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1812 * algorithm. For the by-value portions, we perform the algorithm in
1813 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1814 * bit, and seems to have only a minute effect on distribution. For
1815 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1816 * over each referenced byte. It's painful to do this, but it's much
1817 * better than pathological hash distribution. The efficacy of the
1818 * hashing algorithm (and a comparison with other algorithms) may be
1819 * found by running the ::dtrace_dynstat MDB dcmd.
1820 */
1821 for (i = 0; i < nkeys; i++) {
1822 if (key[i].dttk_size == 0) {
1823 uint64_t val = key[i].dttk_value;
1824
1825 hashval += (val >> 48) & 0xffff;
1826 hashval += (hashval << 10);
1827 hashval ^= (hashval >> 6);
1828
1829 hashval += (val >> 32) & 0xffff;
1830 hashval += (hashval << 10);
1831 hashval ^= (hashval >> 6);
1832
1833 hashval += (val >> 16) & 0xffff;
1834 hashval += (hashval << 10);
1835 hashval ^= (hashval >> 6);
1836
1837 hashval += val & 0xffff;
1838 hashval += (hashval << 10);
1839 hashval ^= (hashval >> 6);
1840 } else {
1841 /*
1842 * This is incredibly painful, but it beats the hell
1843 * out of the alternative.
1844 */
1845 uint64_t j, size = key[i].dttk_size;
1846 uintptr_t base = (uintptr_t)key[i].dttk_value;
1847
b0d623f7
A
1848 if (!dtrace_canload(base, size, mstate, vstate))
1849 break;
1850
2d21ac55
A
1851 for (j = 0; j < size; j++) {
1852 hashval += dtrace_load8(base + j);
1853 hashval += (hashval << 10);
1854 hashval ^= (hashval >> 6);
1855 }
1856 }
1857 }
1858
b0d623f7
A
1859 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1860 return (NULL);
1861
2d21ac55
A
1862 hashval += (hashval << 3);
1863 hashval ^= (hashval >> 11);
1864 hashval += (hashval << 15);
1865
1866 /*
1867 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1868 * comes out to be one of our two sentinel hash values. If this
1869 * actually happens, we set the hashval to be a value known to be a
1870 * non-sentinel value.
1871 */
1872 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1873 hashval = DTRACE_DYNHASH_VALID;
1874
1875 /*
1876 * Yes, it's painful to do a divide here. If the cycle count becomes
1877 * important here, tricks can be pulled to reduce it. (However, it's
1878 * critical that hash collisions be kept to an absolute minimum;
1879 * they're much more painful than a divide.) It's better to have a
1880 * solution that generates few collisions and still keeps things
1881 * relatively simple.
1882 */
1883 bucket = hashval % dstate->dtds_hashsize;
1884
1885 if (op == DTRACE_DYNVAR_DEALLOC) {
1886 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1887
1888 for (;;) {
1889 while ((lock = *lockp) & 1)
1890 continue;
1891
b0d623f7
A
1892 if (dtrace_casptr((void *)(uintptr_t)lockp,
1893 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1894 break;
2d21ac55
A
1895 }
1896
1897 dtrace_membar_producer();
1898 }
1899
1900top:
1901 prev = NULL;
1902 lock = hash[bucket].dtdh_lock;
1903
1904 dtrace_membar_consumer();
1905
1906 start = hash[bucket].dtdh_chain;
1907 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1908 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1909 op != DTRACE_DYNVAR_DEALLOC));
1910
1911 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1912 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1913 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1914
1915 if (dvar->dtdv_hashval != hashval) {
1916 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1917 /*
1918 * We've reached the sink, and therefore the
1919 * end of the hash chain; we can kick out of
1920 * the loop knowing that we have seen a valid
1921 * snapshot of state.
1922 */
1923 ASSERT(dvar->dtdv_next == NULL);
1924 ASSERT(dvar == &dtrace_dynhash_sink);
1925 break;
1926 }
1927
1928 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1929 /*
1930 * We've gone off the rails: somewhere along
1931 * the line, one of the members of this hash
1932 * chain was deleted. Note that we could also
1933 * detect this by simply letting this loop run
1934 * to completion, as we would eventually hit
1935 * the end of the dirty list. However, we
1936 * want to avoid running the length of the
1937 * dirty list unnecessarily (it might be quite
1938 * long), so we catch this as early as
1939 * possible by detecting the hash marker. In
1940 * this case, we simply set dvar to NULL and
1941 * break; the conditional after the loop will
1942 * send us back to top.
1943 */
1944 dvar = NULL;
1945 break;
1946 }
1947
1948 goto next;
1949 }
1950
1951 if (dtuple->dtt_nkeys != nkeys)
1952 goto next;
1953
1954 for (i = 0; i < nkeys; i++, dkey++) {
1955 if (dkey->dttk_size != key[i].dttk_size)
1956 goto next; /* size or type mismatch */
1957
1958 if (dkey->dttk_size != 0) {
1959 if (dtrace_bcmp(
1960 (void *)(uintptr_t)key[i].dttk_value,
1961 (void *)(uintptr_t)dkey->dttk_value,
1962 dkey->dttk_size))
1963 goto next;
1964 } else {
1965 if (dkey->dttk_value != key[i].dttk_value)
1966 goto next;
1967 }
1968 }
1969
1970 if (op != DTRACE_DYNVAR_DEALLOC)
1971 return (dvar);
1972
1973 ASSERT(dvar->dtdv_next == NULL ||
1974 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1975
1976 if (prev != NULL) {
1977 ASSERT(hash[bucket].dtdh_chain != dvar);
1978 ASSERT(start != dvar);
1979 ASSERT(prev->dtdv_next == dvar);
1980 prev->dtdv_next = dvar->dtdv_next;
1981 } else {
1982 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1983 start, dvar->dtdv_next) != start) {
1984 /*
1985 * We have failed to atomically swing the
1986 * hash table head pointer, presumably because
1987 * of a conflicting allocation on another CPU.
1988 * We need to reread the hash chain and try
1989 * again.
1990 */
1991 goto top;
1992 }
1993 }
1994
1995 dtrace_membar_producer();
1996
1997 /*
1998 * Now set the hash value to indicate that it's free.
1999 */
2000 ASSERT(hash[bucket].dtdh_chain != dvar);
2001 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2002
2003 dtrace_membar_producer();
2004
2005 /*
2006 * Set the next pointer to point at the dirty list, and
2007 * atomically swing the dirty pointer to the newly freed dvar.
2008 */
2009 do {
2010 next = dcpu->dtdsc_dirty;
2011 dvar->dtdv_next = next;
2012 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2013
2014 /*
2015 * Finally, unlock this hash bucket.
2016 */
2017 ASSERT(hash[bucket].dtdh_lock == lock);
2018 ASSERT(lock & 1);
2019 hash[bucket].dtdh_lock++;
2020
2021 return (NULL);
2022next:
2023 prev = dvar;
2024 continue;
2025 }
2026
2027 if (dvar == NULL) {
2028 /*
2029 * If dvar is NULL, it is because we went off the rails:
2030 * one of the elements that we traversed in the hash chain
2031 * was deleted while we were traversing it. In this case,
2032 * we assert that we aren't doing a dealloc (deallocs lock
2033 * the hash bucket to prevent themselves from racing with
2034 * one another), and retry the hash chain traversal.
2035 */
2036 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2037 goto top;
2038 }
2039
2040 if (op != DTRACE_DYNVAR_ALLOC) {
2041 /*
2042 * If we are not to allocate a new variable, we want to
2043 * return NULL now. Before we return, check that the value
2044 * of the lock word hasn't changed. If it has, we may have
2045 * seen an inconsistent snapshot.
2046 */
2047 if (op == DTRACE_DYNVAR_NOALLOC) {
2048 if (hash[bucket].dtdh_lock != lock)
2049 goto top;
2050 } else {
2051 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2052 ASSERT(hash[bucket].dtdh_lock == lock);
2053 ASSERT(lock & 1);
2054 hash[bucket].dtdh_lock++;
2055 }
2056
2057 return (NULL);
2058 }
2059
2060 /*
2061 * We need to allocate a new dynamic variable. The size we need is the
2062 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2063 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2064 * the size of any referred-to data (dsize). We then round the final
2065 * size up to the chunksize for allocation.
2066 */
2067 for (ksize = 0, i = 0; i < nkeys; i++)
2068 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2069
2070 /*
2071 * This should be pretty much impossible, but could happen if, say,
2072 * strange DIF specified the tuple. Ideally, this should be an
2073 * assertion and not an error condition -- but that requires that the
2074 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2075 * bullet-proof. (That is, it must not be able to be fooled by
2076 * malicious DIF.) Given the lack of backwards branches in DIF,
2077 * solving this would presumably not amount to solving the Halting
2078 * Problem -- but it still seems awfully hard.
2079 */
2080 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2081 ksize + dsize > chunksize) {
2082 dcpu->dtdsc_drops++;
2083 return (NULL);
2084 }
2085
2086 nstate = DTRACE_DSTATE_EMPTY;
2087
2088 do {
2089retry:
2090 free = dcpu->dtdsc_free;
2091
2092 if (free == NULL) {
2093 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2094 void *rval;
2095
2096 if (clean == NULL) {
2097 /*
2098 * We're out of dynamic variable space on
2099 * this CPU. Unless we have tried all CPUs,
2100 * we'll try to allocate from a different
2101 * CPU.
2102 */
2103 switch (dstate->dtds_state) {
2104 case DTRACE_DSTATE_CLEAN: {
2105 void *sp = &dstate->dtds_state;
2106
c910b4d9 2107 if (++cpu >= (int)NCPU)
2d21ac55
A
2108 cpu = 0;
2109
2110 if (dcpu->dtdsc_dirty != NULL &&
2111 nstate == DTRACE_DSTATE_EMPTY)
2112 nstate = DTRACE_DSTATE_DIRTY;
2113
2114 if (dcpu->dtdsc_rinsing != NULL)
2115 nstate = DTRACE_DSTATE_RINSING;
2116
2117 dcpu = &dstate->dtds_percpu[cpu];
2118
2119 if (cpu != me)
2120 goto retry;
2121
2122 (void) dtrace_cas32(sp,
2123 DTRACE_DSTATE_CLEAN, nstate);
2124
2125 /*
2126 * To increment the correct bean
2127 * counter, take another lap.
2128 */
2129 goto retry;
2130 }
2131
2132 case DTRACE_DSTATE_DIRTY:
2133 dcpu->dtdsc_dirty_drops++;
2134 break;
2135
2136 case DTRACE_DSTATE_RINSING:
2137 dcpu->dtdsc_rinsing_drops++;
2138 break;
2139
2140 case DTRACE_DSTATE_EMPTY:
2141 dcpu->dtdsc_drops++;
2142 break;
2143 }
2144
2145 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2146 return (NULL);
2147 }
2148
2149 /*
2150 * The clean list appears to be non-empty. We want to
2151 * move the clean list to the free list; we start by
2152 * moving the clean pointer aside.
2153 */
2154 if (dtrace_casptr(&dcpu->dtdsc_clean,
2155 clean, NULL) != clean) {
2156 /*
2157 * We are in one of two situations:
2158 *
2159 * (a) The clean list was switched to the
2160 * free list by another CPU.
2161 *
2162 * (b) The clean list was added to by the
2163 * cleansing cyclic.
2164 *
2165 * In either of these situations, we can
2166 * just reattempt the free list allocation.
2167 */
2168 goto retry;
2169 }
2170
2171 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2172
2173 /*
2174 * Now we'll move the clean list to the free list.
2175 * It's impossible for this to fail: the only way
2176 * the free list can be updated is through this
2177 * code path, and only one CPU can own the clean list.
2178 * Thus, it would only be possible for this to fail if
2179 * this code were racing with dtrace_dynvar_clean().
2180 * (That is, if dtrace_dynvar_clean() updated the clean
2181 * list, and we ended up racing to update the free
2182 * list.) This race is prevented by the dtrace_sync()
2183 * in dtrace_dynvar_clean() -- which flushes the
2184 * owners of the clean lists out before resetting
2185 * the clean lists.
2186 */
2187 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2188 ASSERT(rval == NULL);
2189 goto retry;
2190 }
2191
2192 dvar = free;
2193 new_free = dvar->dtdv_next;
2194 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2195
2196 /*
2197 * We have now allocated a new chunk. We copy the tuple keys into the
2198 * tuple array and copy any referenced key data into the data space
2199 * following the tuple array. As we do this, we relocate dttk_value
2200 * in the final tuple to point to the key data address in the chunk.
2201 */
2202 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2203 dvar->dtdv_data = (void *)(kdata + ksize);
2204 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2205
2206 for (i = 0; i < nkeys; i++) {
2207 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2208 size_t kesize = key[i].dttk_size;
2209
2210 if (kesize != 0) {
2211 dtrace_bcopy(
2212 (const void *)(uintptr_t)key[i].dttk_value,
2213 (void *)kdata, kesize);
2214 dkey->dttk_value = kdata;
2215 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2216 } else {
2217 dkey->dttk_value = key[i].dttk_value;
2218 }
2219
2220 dkey->dttk_size = kesize;
2221 }
2222
2223 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2224 dvar->dtdv_hashval = hashval;
2225 dvar->dtdv_next = start;
2226
2227 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2228 return (dvar);
2229
2230 /*
2231 * The cas has failed. Either another CPU is adding an element to
2232 * this hash chain, or another CPU is deleting an element from this
2233 * hash chain. The simplest way to deal with both of these cases
2234 * (though not necessarily the most efficient) is to free our
2235 * allocated block and tail-call ourselves. Note that the free is
2236 * to the dirty list and _not_ to the free list. This is to prevent
2237 * races with allocators, above.
2238 */
2239 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2240
2241 dtrace_membar_producer();
2242
2243 do {
2244 free = dcpu->dtdsc_dirty;
2245 dvar->dtdv_next = free;
2246 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2247
b0d623f7 2248 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2d21ac55
A
2249}
2250
2251/*ARGSUSED*/
2252static void
2253dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2254{
b0d623f7
A
2255#pragma unused(arg) /* __APPLE__ */
2256 if ((int64_t)nval < (int64_t)*oval)
2d21ac55
A
2257 *oval = nval;
2258}
2259
2260/*ARGSUSED*/
2261static void
2262dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2263{
b0d623f7
A
2264#pragma unused(arg) /* __APPLE__ */
2265 if ((int64_t)nval > (int64_t)*oval)
2d21ac55
A
2266 *oval = nval;
2267}
2268
2269static void
2270dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2271{
2272 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2273 int64_t val = (int64_t)nval;
2274
2275 if (val < 0) {
2276 for (i = 0; i < zero; i++) {
2277 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2278 quanta[i] += incr;
2279 return;
2280 }
2281 }
2282 } else {
2283 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2284 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2285 quanta[i - 1] += incr;
2286 return;
2287 }
2288 }
2289
2290 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2291 return;
2292 }
2293
2294 ASSERT(0);
2295}
2296
2297static void
2298dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2299{
2300 uint64_t arg = *lquanta++;
2301 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2302 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2303 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2304 int32_t val = (int32_t)nval, level;
2305
2306 ASSERT(step != 0);
2307 ASSERT(levels != 0);
2308
2309 if (val < base) {
2310 /*
2311 * This is an underflow.
2312 */
2313 lquanta[0] += incr;
2314 return;
2315 }
2316
2317 level = (val - base) / step;
2318
2319 if (level < levels) {
2320 lquanta[level + 1] += incr;
2321 return;
2322 }
2323
2324 /*
2325 * This is an overflow.
2326 */
2327 lquanta[levels + 1] += incr;
2328}
2329
39236c6e
A
2330static int
2331dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2332 int16_t nsteps, int64_t value)
2333{
2334 int64_t this = 1, last, next;
2335 int base = 1, order;
2336
2337 for (order = 0; order < low; ++order)
2338 this *= factor;
2339
2340 /*
2341 * If our value is less than our factor taken to the power of the
2342 * low order of magnitude, it goes into the zeroth bucket.
2343 */
2344 if (value < this)
2345 return 0;
2346 else
2347 last = this;
2348
2349 for (this *= factor; order <= high; ++order) {
2350 int nbuckets = this > nsteps ? nsteps : this;
2351
2352 /*
2353 * We should not generally get log/linear quantizations
2354 * with a high magnitude that allows 64-bits to
2355 * overflow, but we nonetheless protect against this
2356 * by explicitly checking for overflow, and clamping
2357 * our value accordingly.
2358 */
2359 next = this * factor;
2360 if (next < this) {
2361 value = this - 1;
2362 }
2363
2364 /*
2365 * If our value lies within this order of magnitude,
2366 * determine its position by taking the offset within
2367 * the order of magnitude, dividing by the bucket
2368 * width, and adding to our (accumulated) base.
2369 */
2370 if (value < this) {
2371 return (base + (value - last) / (this / nbuckets));
2372 }
2373
2374 base += nbuckets - (nbuckets / factor);
2375 last = this;
2376 this = next;
2377 }
2378
2379 /*
2380 * Our value is greater than or equal to our factor taken to the
2381 * power of one plus the high magnitude -- return the top bucket.
2382 */
2383 return base;
2384}
2385
2386static void
2387dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2388{
2389 uint64_t arg = *llquanta++;
2390 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2391 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2392 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
15129b1c 2393 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
39236c6e
A
2394
2395 llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2396}
2397
2d21ac55
A
2398/*ARGSUSED*/
2399static void
2400dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2401{
b0d623f7 2402#pragma unused(arg) /* __APPLE__ */
2d21ac55
A
2403 data[0]++;
2404 data[1] += nval;
2405}
2406
2407/*ARGSUSED*/
2408static void
b0d623f7 2409dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2d21ac55 2410{
b0d623f7
A
2411#pragma unused(arg) /* __APPLE__ */
2412 int64_t snval = (int64_t)nval;
2413 uint64_t tmp[2];
2414
2415 data[0]++;
2416 data[1] += nval;
2417
2418 /*
2419 * What we want to say here is:
2420 *
2421 * data[2] += nval * nval;
2422 *
2423 * But given that nval is 64-bit, we could easily overflow, so
2424 * we do this as 128-bit arithmetic.
2425 */
2426 if (snval < 0)
2427 snval = -snval;
2428
2429 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2430 dtrace_add_128(data + 2, tmp, data + 2);
2d21ac55
A
2431}
2432
2433/*ARGSUSED*/
2434static void
b0d623f7 2435dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2d21ac55 2436{
b0d623f7
A
2437#pragma unused(nval, arg) /* __APPLE__ */
2438 *oval = *oval + 1;
2439}
2440
2441/*ARGSUSED*/
2442static void
2443dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2444{
2445#pragma unused(arg) /* __APPLE__ */
2d21ac55
A
2446 *oval += nval;
2447}
2448
2449/*
2450 * Aggregate given the tuple in the principal data buffer, and the aggregating
2451 * action denoted by the specified dtrace_aggregation_t. The aggregation
2452 * buffer is specified as the buf parameter. This routine does not return
2453 * failure; if there is no space in the aggregation buffer, the data will be
2454 * dropped, and a corresponding counter incremented.
2455 */
2456static void
2457dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2458 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2459{
c910b4d9 2460#pragma unused(arg)
2d21ac55
A
2461 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2462 uint32_t i, ndx, size, fsize;
2463 uint32_t align = sizeof (uint64_t) - 1;
2464 dtrace_aggbuffer_t *agb;
2465 dtrace_aggkey_t *key;
2466 uint32_t hashval = 0, limit, isstr;
2467 caddr_t tomax, data, kdata;
2468 dtrace_actkind_t action;
2469 dtrace_action_t *act;
2470 uintptr_t offs;
2471
2472 if (buf == NULL)
2473 return;
2474
2475 if (!agg->dtag_hasarg) {
2476 /*
2477 * Currently, only quantize() and lquantize() take additional
2478 * arguments, and they have the same semantics: an increment
2479 * value that defaults to 1 when not present. If additional
2480 * aggregating actions take arguments, the setting of the
2481 * default argument value will presumably have to become more
2482 * sophisticated...
2483 */
2484 arg = 1;
2485 }
2486
2487 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2488 size = rec->dtrd_offset - agg->dtag_base;
2489 fsize = size + rec->dtrd_size;
2490
2491 ASSERT(dbuf->dtb_tomax != NULL);
2492 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2493
2494 if ((tomax = buf->dtb_tomax) == NULL) {
2495 dtrace_buffer_drop(buf);
2496 return;
2497 }
2498
2499 /*
2500 * The metastructure is always at the bottom of the buffer.
2501 */
2502 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2503 sizeof (dtrace_aggbuffer_t));
2504
2505 if (buf->dtb_offset == 0) {
2506 /*
2507 * We just kludge up approximately 1/8th of the size to be
2508 * buckets. If this guess ends up being routinely
2509 * off-the-mark, we may need to dynamically readjust this
2510 * based on past performance.
2511 */
2512 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2513
2514 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2515 (uintptr_t)tomax || hashsize == 0) {
2516 /*
2517 * We've been given a ludicrously small buffer;
2518 * increment our drop count and leave.
2519 */
2520 dtrace_buffer_drop(buf);
2521 return;
2522 }
2523
2524 /*
2525 * And now, a pathetic attempt to try to get a an odd (or
2526 * perchance, a prime) hash size for better hash distribution.
2527 */
2528 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2529 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2530
2531 agb->dtagb_hashsize = hashsize;
2532 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2533 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2534 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2535
2536 for (i = 0; i < agb->dtagb_hashsize; i++)
2537 agb->dtagb_hash[i] = NULL;
2538 }
2539
2540 ASSERT(agg->dtag_first != NULL);
2541 ASSERT(agg->dtag_first->dta_intuple);
2542
2543 /*
2544 * Calculate the hash value based on the key. Note that we _don't_
2545 * include the aggid in the hashing (but we will store it as part of
2546 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2547 * algorithm: a simple, quick algorithm that has no known funnels, and
2548 * gets good distribution in practice. The efficacy of the hashing
2549 * algorithm (and a comparison with other algorithms) may be found by
2550 * running the ::dtrace_aggstat MDB dcmd.
2551 */
2552 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2553 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2554 limit = i + act->dta_rec.dtrd_size;
2555 ASSERT(limit <= size);
2556 isstr = DTRACEACT_ISSTRING(act);
2557
2558 for (; i < limit; i++) {
2559 hashval += data[i];
2560 hashval += (hashval << 10);
2561 hashval ^= (hashval >> 6);
2562
2563 if (isstr && data[i] == '\0')
2564 break;
2565 }
2566 }
2567
2568 hashval += (hashval << 3);
2569 hashval ^= (hashval >> 11);
2570 hashval += (hashval << 15);
2571
2572 /*
2573 * Yes, the divide here is expensive -- but it's generally the least
2574 * of the performance issues given the amount of data that we iterate
2575 * over to compute hash values, compare data, etc.
2576 */
2577 ndx = hashval % agb->dtagb_hashsize;
2578
2579 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2580 ASSERT((caddr_t)key >= tomax);
2581 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2582
2583 if (hashval != key->dtak_hashval || key->dtak_size != size)
2584 continue;
2585
2586 kdata = key->dtak_data;
2587 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2588
2589 for (act = agg->dtag_first; act->dta_intuple;
2590 act = act->dta_next) {
2591 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2592 limit = i + act->dta_rec.dtrd_size;
2593 ASSERT(limit <= size);
2594 isstr = DTRACEACT_ISSTRING(act);
2595
2596 for (; i < limit; i++) {
2597 if (kdata[i] != data[i])
2598 goto next;
2599
2600 if (isstr && data[i] == '\0')
2601 break;
2602 }
2603 }
2604
2605 if (action != key->dtak_action) {
2606 /*
2607 * We are aggregating on the same value in the same
2608 * aggregation with two different aggregating actions.
2609 * (This should have been picked up in the compiler,
2610 * so we may be dealing with errant or devious DIF.)
2611 * This is an error condition; we indicate as much,
2612 * and return.
2613 */
2614 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2615 return;
2616 }
2617
2618 /*
2619 * This is a hit: we need to apply the aggregator to
2620 * the value at this key.
2621 */
2622 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2623 return;
2624next:
2625 continue;
2626 }
2627
2628 /*
2629 * We didn't find it. We need to allocate some zero-filled space,
2630 * link it into the hash table appropriately, and apply the aggregator
2631 * to the (zero-filled) value.
2632 */
2633 offs = buf->dtb_offset;
2634 while (offs & (align - 1))
2635 offs += sizeof (uint32_t);
2636
2637 /*
2638 * If we don't have enough room to both allocate a new key _and_
2639 * its associated data, increment the drop count and return.
2640 */
2641 if ((uintptr_t)tomax + offs + fsize >
2642 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2643 dtrace_buffer_drop(buf);
2644 return;
2645 }
2646
2647 /*CONSTCOND*/
2648 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2649 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2650 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2651
2652 key->dtak_data = kdata = tomax + offs;
2653 buf->dtb_offset = offs + fsize;
2654
2655 /*
2656 * Now copy the data across.
2657 */
2658 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2659
2660 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2661 kdata[i] = data[i];
2662
2663 /*
2664 * Because strings are not zeroed out by default, we need to iterate
2665 * looking for actions that store strings, and we need to explicitly
2666 * pad these strings out with zeroes.
2667 */
2668 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2669 int nul;
2670
2671 if (!DTRACEACT_ISSTRING(act))
2672 continue;
2673
2674 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2675 limit = i + act->dta_rec.dtrd_size;
2676 ASSERT(limit <= size);
2677
2678 for (nul = 0; i < limit; i++) {
2679 if (nul) {
2680 kdata[i] = '\0';
2681 continue;
2682 }
2683
2684 if (data[i] != '\0')
2685 continue;
2686
2687 nul = 1;
2688 }
2689 }
2690
2691 for (i = size; i < fsize; i++)
2692 kdata[i] = 0;
2693
2694 key->dtak_hashval = hashval;
2695 key->dtak_size = size;
2696 key->dtak_action = action;
2697 key->dtak_next = agb->dtagb_hash[ndx];
2698 agb->dtagb_hash[ndx] = key;
2699
2700 /*
2701 * Finally, apply the aggregator.
2702 */
2703 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2704 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2705}
2706
2707/*
2708 * Given consumer state, this routine finds a speculation in the INACTIVE
2709 * state and transitions it into the ACTIVE state. If there is no speculation
2710 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2711 * incremented -- it is up to the caller to take appropriate action.
2712 */
2713static int
2714dtrace_speculation(dtrace_state_t *state)
2715{
2716 int i = 0;
2717 dtrace_speculation_state_t current;
2718 uint32_t *stat = &state->dts_speculations_unavail, count;
2719
2720 while (i < state->dts_nspeculations) {
2721 dtrace_speculation_t *spec = &state->dts_speculations[i];
2722
2723 current = spec->dtsp_state;
2724
2725 if (current != DTRACESPEC_INACTIVE) {
2726 if (current == DTRACESPEC_COMMITTINGMANY ||
2727 current == DTRACESPEC_COMMITTING ||
2728 current == DTRACESPEC_DISCARDING)
2729 stat = &state->dts_speculations_busy;
2730 i++;
2731 continue;
2732 }
2733
2734 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2735 current, DTRACESPEC_ACTIVE) == current)
2736 return (i + 1);
2737 }
2738
2739 /*
2740 * We couldn't find a speculation. If we found as much as a single
2741 * busy speculation buffer, we'll attribute this failure as "busy"
2742 * instead of "unavail".
2743 */
2744 do {
2745 count = *stat;
2746 } while (dtrace_cas32(stat, count, count + 1) != count);
2747
2748 return (0);
2749}
2750
2751/*
2752 * This routine commits an active speculation. If the specified speculation
2753 * is not in a valid state to perform a commit(), this routine will silently do
2754 * nothing. The state of the specified speculation is transitioned according
2755 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2756 */
2757static void
2758dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2759 dtrace_specid_t which)
2760{
2761 dtrace_speculation_t *spec;
2762 dtrace_buffer_t *src, *dest;
04b8595b 2763 uintptr_t daddr, saddr, dlimit, slimit;
b0d623f7 2764 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2d21ac55 2765 intptr_t offs;
04b8595b 2766 uint64_t timestamp;
2d21ac55
A
2767
2768 if (which == 0)
2769 return;
2770
b0d623f7
A
2771 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2772 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2773 return;
2774 }
b0d623f7 2775
2d21ac55
A
2776 spec = &state->dts_speculations[which - 1];
2777 src = &spec->dtsp_buffer[cpu];
2778 dest = &state->dts_buffer[cpu];
2779
2780 do {
2781 current = spec->dtsp_state;
2782
2783 if (current == DTRACESPEC_COMMITTINGMANY)
2784 break;
2785
2786 switch (current) {
2787 case DTRACESPEC_INACTIVE:
2788 case DTRACESPEC_DISCARDING:
2789 return;
2790
2791 case DTRACESPEC_COMMITTING:
2792 /*
2793 * This is only possible if we are (a) commit()'ing
2794 * without having done a prior speculate() on this CPU
2795 * and (b) racing with another commit() on a different
2796 * CPU. There's nothing to do -- we just assert that
2797 * our offset is 0.
2798 */
2799 ASSERT(src->dtb_offset == 0);
2800 return;
2801
2802 case DTRACESPEC_ACTIVE:
2803 new = DTRACESPEC_COMMITTING;
2804 break;
2805
2806 case DTRACESPEC_ACTIVEONE:
2807 /*
2808 * This speculation is active on one CPU. If our
2809 * buffer offset is non-zero, we know that the one CPU
2810 * must be us. Otherwise, we are committing on a
2811 * different CPU from the speculate(), and we must
2812 * rely on being asynchronously cleaned.
2813 */
2814 if (src->dtb_offset != 0) {
2815 new = DTRACESPEC_COMMITTING;
2816 break;
2817 }
2818 /*FALLTHROUGH*/
2819
2820 case DTRACESPEC_ACTIVEMANY:
2821 new = DTRACESPEC_COMMITTINGMANY;
2822 break;
2823
2824 default:
2825 ASSERT(0);
2826 }
2827 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2828 current, new) != current);
2829
2830 /*
2831 * We have set the state to indicate that we are committing this
2832 * speculation. Now reserve the necessary space in the destination
2833 * buffer.
2834 */
2835 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2836 sizeof (uint64_t), state, NULL)) < 0) {
2837 dtrace_buffer_drop(dest);
2838 goto out;
2839 }
2840
2841 /*
04b8595b
A
2842 * We have sufficient space to copy the speculative buffer into the
2843 * primary buffer. First, modify the speculative buffer, filling
2844 * in the timestamp of all entries with the current time. The data
2845 * must have the commit() time rather than the time it was traced,
2846 * so that all entries in the primary buffer are in timestamp order.
2847 */
2848 timestamp = dtrace_gethrtime();
2849 saddr = (uintptr_t)src->dtb_tomax;
2850 slimit = saddr + src->dtb_offset;
2851 while (saddr < slimit) {
2852 size_t size;
2853 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2854
2855 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2856 saddr += sizeof (dtrace_epid_t);
2857 continue;
2858 }
2859
2860 ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2861 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2862
2863 ASSERT(saddr + size <= slimit);
2864 ASSERT(size >= sizeof(dtrace_rechdr_t));
2865 ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2866
2867 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2868
2869 saddr += size;
2870 }
2871
2872 /*
2873 * Copy the buffer across. (Note that this is a
2d21ac55
A
2874 * highly subobtimal bcopy(); in the unlikely event that this becomes
2875 * a serious performance issue, a high-performance DTrace-specific
2876 * bcopy() should obviously be invented.)
2877 */
2878 daddr = (uintptr_t)dest->dtb_tomax + offs;
2879 dlimit = daddr + src->dtb_offset;
2880 saddr = (uintptr_t)src->dtb_tomax;
2881
2882 /*
2883 * First, the aligned portion.
2884 */
2885 while (dlimit - daddr >= sizeof (uint64_t)) {
2886 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2887
2888 daddr += sizeof (uint64_t);
2889 saddr += sizeof (uint64_t);
2890 }
2891
2892 /*
2893 * Now any left-over bit...
2894 */
2895 while (dlimit - daddr)
2896 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2897
2898 /*
2899 * Finally, commit the reserved space in the destination buffer.
2900 */
2901 dest->dtb_offset = offs + src->dtb_offset;
2902
2903out:
2904 /*
2905 * If we're lucky enough to be the only active CPU on this speculation
2906 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2907 */
2908 if (current == DTRACESPEC_ACTIVE ||
2909 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2910 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2911 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
b0d623f7 2912#pragma unused(rval) /* __APPLE__ */
2d21ac55
A
2913
2914 ASSERT(rval == DTRACESPEC_COMMITTING);
2915 }
2916
2917 src->dtb_offset = 0;
2918 src->dtb_xamot_drops += src->dtb_drops;
2919 src->dtb_drops = 0;
2920}
2921
2922/*
2923 * This routine discards an active speculation. If the specified speculation
2924 * is not in a valid state to perform a discard(), this routine will silently
2925 * do nothing. The state of the specified speculation is transitioned
2926 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2927 */
2928static void
2929dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2930 dtrace_specid_t which)
2931{
2932 dtrace_speculation_t *spec;
b0d623f7 2933 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2d21ac55
A
2934 dtrace_buffer_t *buf;
2935
2936 if (which == 0)
2937 return;
2938
b0d623f7
A
2939 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2940 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2941 return;
2942 }
2d21ac55
A
2943
2944 spec = &state->dts_speculations[which - 1];
2945 buf = &spec->dtsp_buffer[cpu];
2946
2947 do {
2948 current = spec->dtsp_state;
2949
2950 switch (current) {
2951 case DTRACESPEC_INACTIVE:
2952 case DTRACESPEC_COMMITTINGMANY:
2953 case DTRACESPEC_COMMITTING:
2954 case DTRACESPEC_DISCARDING:
2955 return;
2956
2957 case DTRACESPEC_ACTIVE:
2958 case DTRACESPEC_ACTIVEMANY:
2959 new = DTRACESPEC_DISCARDING;
2960 break;
2961
2962 case DTRACESPEC_ACTIVEONE:
2963 if (buf->dtb_offset != 0) {
2964 new = DTRACESPEC_INACTIVE;
2965 } else {
2966 new = DTRACESPEC_DISCARDING;
2967 }
2968 break;
2969
2970 default:
2971 ASSERT(0);
2972 }
2973 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2974 current, new) != current);
2975
2976 buf->dtb_offset = 0;
2977 buf->dtb_drops = 0;
2978}
2979
2980/*
2981 * Note: not called from probe context. This function is called
2982 * asynchronously from cross call context to clean any speculations that are
2983 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2984 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2985 * speculation.
2986 */
2987static void
2988dtrace_speculation_clean_here(dtrace_state_t *state)
2989{
2990 dtrace_icookie_t cookie;
2991 processorid_t cpu = CPU->cpu_id;
2992 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2993 dtrace_specid_t i;
2994
2995 cookie = dtrace_interrupt_disable();
2996
2997 if (dest->dtb_tomax == NULL) {
2998 dtrace_interrupt_enable(cookie);
2999 return;
3000 }
3001
b0d623f7 3002 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2d21ac55
A
3003 dtrace_speculation_t *spec = &state->dts_speculations[i];
3004 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3005
3006 if (src->dtb_tomax == NULL)
3007 continue;
3008
3009 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3010 src->dtb_offset = 0;
3011 continue;
3012 }
3013
3014 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3015 continue;
3016
3017 if (src->dtb_offset == 0)
3018 continue;
3019
3020 dtrace_speculation_commit(state, cpu, i + 1);
3021 }
3022
3023 dtrace_interrupt_enable(cookie);
3024}
3025
3026/*
3027 * Note: not called from probe context. This function is called
3028 * asynchronously (and at a regular interval) to clean any speculations that
3029 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
3030 * is work to be done, it cross calls all CPUs to perform that work;
3031 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3032 * INACTIVE state until they have been cleaned by all CPUs.
3033 */
3034static void
3035dtrace_speculation_clean(dtrace_state_t *state)
3036{
b0d623f7
A
3037 int work = 0;
3038 uint32_t rv;
2d21ac55
A
3039 dtrace_specid_t i;
3040
b0d623f7 3041 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2d21ac55
A
3042 dtrace_speculation_t *spec = &state->dts_speculations[i];
3043
3044 ASSERT(!spec->dtsp_cleaning);
3045
3046 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3047 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3048 continue;
3049
3050 work++;
3051 spec->dtsp_cleaning = 1;
3052 }
3053
3054 if (!work)
3055 return;
3056
3057 dtrace_xcall(DTRACE_CPUALL,
3058 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3059
3060 /*
3061 * We now know that all CPUs have committed or discarded their
3062 * speculation buffers, as appropriate. We can now set the state
3063 * to inactive.
3064 */
b0d623f7 3065 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2d21ac55
A
3066 dtrace_speculation_t *spec = &state->dts_speculations[i];
3067 dtrace_speculation_state_t current, new;
3068
3069 if (!spec->dtsp_cleaning)
3070 continue;
3071
3072 current = spec->dtsp_state;
3073 ASSERT(current == DTRACESPEC_DISCARDING ||
3074 current == DTRACESPEC_COMMITTINGMANY);
3075
3076 new = DTRACESPEC_INACTIVE;
3077
3078 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3079 ASSERT(rv == current);
3080 spec->dtsp_cleaning = 0;
3081 }
3082}
3083
3084/*
3085 * Called as part of a speculate() to get the speculative buffer associated
3086 * with a given speculation. Returns NULL if the specified speculation is not
3087 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
3088 * the active CPU is not the specified CPU -- the speculation will be
3089 * atomically transitioned into the ACTIVEMANY state.
3090 */
3091static dtrace_buffer_t *
3092dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3093 dtrace_specid_t which)
3094{
3095 dtrace_speculation_t *spec;
b0d623f7 3096 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2d21ac55
A
3097 dtrace_buffer_t *buf;
3098
3099 if (which == 0)
3100 return (NULL);
3101
b0d623f7 3102 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2d21ac55
A
3103 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3104 return (NULL);
3105 }
3106
3107 spec = &state->dts_speculations[which - 1];
3108 buf = &spec->dtsp_buffer[cpuid];
3109
3110 do {
3111 current = spec->dtsp_state;
3112
3113 switch (current) {
3114 case DTRACESPEC_INACTIVE:
3115 case DTRACESPEC_COMMITTINGMANY:
3116 case DTRACESPEC_DISCARDING:
3117 return (NULL);
3118
3119 case DTRACESPEC_COMMITTING:
3120 ASSERT(buf->dtb_offset == 0);
3121 return (NULL);
3122
3123 case DTRACESPEC_ACTIVEONE:
3124 /*
3125 * This speculation is currently active on one CPU.
3126 * Check the offset in the buffer; if it's non-zero,
3127 * that CPU must be us (and we leave the state alone).
3128 * If it's zero, assume that we're starting on a new
3129 * CPU -- and change the state to indicate that the
3130 * speculation is active on more than one CPU.
3131 */
3132 if (buf->dtb_offset != 0)
3133 return (buf);
3134
3135 new = DTRACESPEC_ACTIVEMANY;
3136 break;
3137
3138 case DTRACESPEC_ACTIVEMANY:
3139 return (buf);
3140
3141 case DTRACESPEC_ACTIVE:
3142 new = DTRACESPEC_ACTIVEONE;
3143 break;
3144
3145 default:
3146 ASSERT(0);
3147 }
3148 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3149 current, new) != current);
3150
3151 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3152 return (buf);
3153}
3154
b0d623f7
A
3155/*
3156 * Return a string. In the event that the user lacks the privilege to access
3157 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3158 * don't fail access checking.
3159 *
3160 * dtrace_dif_variable() uses this routine as a helper for various
3161 * builtin values such as 'execname' and 'probefunc.'
3162 */
b0d623f7 3163static
b0d623f7
A
3164uintptr_t
3165dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3166 dtrace_mstate_t *mstate)
3167{
3168 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3169 uintptr_t ret;
3170 size_t strsz;
3171
3172 /*
3173 * The easy case: this probe is allowed to read all of memory, so
3174 * we can just return this as a vanilla pointer.
3175 */
3176 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3177 return (addr);
3178
3179 /*
3180 * This is the tougher case: we copy the string in question from
3181 * kernel memory into scratch memory and return it that way: this
3182 * ensures that we won't trip up when access checking tests the
3183 * BYREF return value.
3184 */
3185 strsz = dtrace_strlen((char *)addr, size) + 1;
3186
3187 if (mstate->dtms_scratch_ptr + strsz >
3188 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3189 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 3190 return (0);
b0d623f7
A
3191 }
3192
3193 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3194 strsz);
3195 ret = mstate->dtms_scratch_ptr;
3196 mstate->dtms_scratch_ptr += strsz;
3197 return (ret);
3198}
3199
2d21ac55
A
3200/*
3201 * This function implements the DIF emulator's variable lookups. The emulator
3202 * passes a reserved variable identifier and optional built-in array index.
3203 */
3204static uint64_t
3205dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3206 uint64_t ndx)
3207{
3208 /*
3209 * If we're accessing one of the uncached arguments, we'll turn this
3210 * into a reference in the args array.
3211 */
3212 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3213 ndx = v - DIF_VAR_ARG0;
3214 v = DIF_VAR_ARGS;
3215 }
3216
3217 switch (v) {
3218 case DIF_VAR_ARGS:
3219 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3220 if (ndx >= sizeof (mstate->dtms_arg) /
3221 sizeof (mstate->dtms_arg[0])) {
fe8ab488
A
3222 /*
3223 * APPLE NOTE: Account for introduction of __dtrace_probe()
3224 */
2d21ac55 3225 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
5ba3f43e 3226 dtrace_vstate_t *vstate = &state->dts_vstate;
2d21ac55
A
3227 dtrace_provider_t *pv;
3228 uint64_t val;
3229
3230 pv = mstate->dtms_probe->dtpr_provider;
3231 if (pv->dtpv_pops.dtps_getargval != NULL)
3232 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3233 mstate->dtms_probe->dtpr_id,
3234 mstate->dtms_probe->dtpr_arg, ndx, aframes);
b0d623f7 3235 /* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
2d21ac55 3236 else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
b0d623f7 3237 return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
2d21ac55 3238 }
fe8ab488 3239
2d21ac55 3240 else
5ba3f43e 3241 val = dtrace_getarg(ndx, aframes, mstate, vstate);
2d21ac55
A
3242
3243 /*
3244 * This is regrettably required to keep the compiler
3245 * from tail-optimizing the call to dtrace_getarg().
3246 * The condition always evaluates to true, but the
3247 * compiler has no way of figuring that out a priori.
3248 * (None of this would be necessary if the compiler
3249 * could be relied upon to _always_ tail-optimize
3250 * the call to dtrace_getarg() -- but it can't.)
3251 */
3252 if (mstate->dtms_probe != NULL)
3253 return (val);
3254
3255 ASSERT(0);
3256 }
3257
3258 return (mstate->dtms_arg[ndx]);
3259
2d21ac55
A
3260 case DIF_VAR_UREGS: {
3261 thread_t thread;
3262
3263 if (!dtrace_priv_proc(state))
3264 return (0);
3265
3266 if ((thread = current_thread()) == NULL) {
3267 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3268 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3269 return (0);
3270 }
3271
3272 return (dtrace_getreg(find_user_regs(thread), ndx));
3273 }
2d21ac55 3274
fe8ab488 3275
2d21ac55
A
3276 case DIF_VAR_CURTHREAD:
3277 if (!dtrace_priv_kernel(state))
3278 return (0);
3279
3280 return ((uint64_t)(uintptr_t)current_thread());
2d21ac55
A
3281
3282 case DIF_VAR_TIMESTAMP:
3283 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3284 mstate->dtms_timestamp = dtrace_gethrtime();
3285 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3286 }
3287 return (mstate->dtms_timestamp);
3288
2d21ac55
A
3289 case DIF_VAR_VTIMESTAMP:
3290 ASSERT(dtrace_vtime_references != 0);
3291 return (dtrace_get_thread_vtime(current_thread()));
2d21ac55
A
3292
3293 case DIF_VAR_WALLTIMESTAMP:
3294 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3295 mstate->dtms_walltimestamp = dtrace_gethrestime();
3296 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3297 }
3298 return (mstate->dtms_walltimestamp);
3299
fe8ab488
A
3300 case DIF_VAR_MACHTIMESTAMP:
3301 if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3302 mstate->dtms_machtimestamp = mach_absolute_time();
3303 mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3304 }
3305 return (mstate->dtms_machtimestamp);
3306
3e170ce0
A
3307 case DIF_VAR_CPU:
3308 return ((uint64_t) dtrace_get_thread_last_cpu_id(current_thread()));
3309
2d21ac55
A
3310 case DIF_VAR_IPL:
3311 if (!dtrace_priv_kernel(state))
3312 return (0);
3313 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3314 mstate->dtms_ipl = dtrace_getipl();
3315 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3316 }
3317 return (mstate->dtms_ipl);
3318
3319 case DIF_VAR_EPID:
3320 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3321 return (mstate->dtms_epid);
3322
3323 case DIF_VAR_ID:
3324 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3325 return (mstate->dtms_probe->dtpr_id);
3326
3327 case DIF_VAR_STACKDEPTH:
3328 if (!dtrace_priv_kernel(state))
3329 return (0);
3330 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
fe8ab488
A
3331 /*
3332 * APPLE NOTE: Account for introduction of __dtrace_probe()
3333 */
2d21ac55 3334 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
2d21ac55
A
3335
3336 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3337 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3338 }
3339 return (mstate->dtms_stackdepth);
3340
3341 case DIF_VAR_USTACKDEPTH:
3342 if (!dtrace_priv_proc(state))
3343 return (0);
3344 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3345 /*
3346 * See comment in DIF_VAR_PID.
3347 */
3348 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3349 CPU_ON_INTR(CPU)) {
3350 mstate->dtms_ustackdepth = 0;
3351 } else {
3352 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3353 mstate->dtms_ustackdepth =
3354 dtrace_getustackdepth();
3355 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3356 }
3357 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3358 }
3359 return (mstate->dtms_ustackdepth);
3360
3361 case DIF_VAR_CALLER:
3362 if (!dtrace_priv_kernel(state))
3363 return (0);
3364 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
fe8ab488
A
3365 /*
3366 * APPLE NOTE: Account for introduction of __dtrace_probe()
3367 */
2d21ac55 3368 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
2d21ac55
A
3369
3370 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3371 /*
3372 * If this is an unanchored probe, we are
3373 * required to go through the slow path:
3374 * dtrace_caller() only guarantees correct
3375 * results for anchored probes.
3376 */
3377 pc_t caller[2];
3378
3379 dtrace_getpcstack(caller, 2, aframes,
3380 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3381 mstate->dtms_caller = caller[1];
3382 } else if ((mstate->dtms_caller =
fe8ab488 3383 dtrace_caller(aframes)) == (uintptr_t)-1) {
2d21ac55
A
3384 /*
3385 * We have failed to do this the quick way;
3386 * we must resort to the slower approach of
3387 * calling dtrace_getpcstack().
3388 */
3389 pc_t caller;
3390
3391 dtrace_getpcstack(&caller, 1, aframes, NULL);
3392 mstate->dtms_caller = caller;
3393 }
3394
3395 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3396 }
3397 return (mstate->dtms_caller);
3398
3399 case DIF_VAR_UCALLER:
3400 if (!dtrace_priv_proc(state))
3401 return (0);
3402
3403 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3404 uint64_t ustack[3];
3405
3406 /*
3407 * dtrace_getupcstack() fills in the first uint64_t
3408 * with the current PID. The second uint64_t will
3409 * be the program counter at user-level. The third
3410 * uint64_t will contain the caller, which is what
3411 * we're after.
3412 */
fe8ab488 3413 ustack[2] = 0;
b0d623f7 3414 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2d21ac55 3415 dtrace_getupcstack(ustack, 3);
b0d623f7 3416 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2d21ac55
A
3417 mstate->dtms_ucaller = ustack[2];
3418 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3419 }
3420
3421 return (mstate->dtms_ucaller);
3422
3423 case DIF_VAR_PROBEPROV:
3424 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
b0d623f7
A
3425 return (dtrace_dif_varstr(
3426 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3427 state, mstate));
2d21ac55
A
3428
3429 case DIF_VAR_PROBEMOD:
3430 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
b0d623f7
A
3431 return (dtrace_dif_varstr(
3432 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3433 state, mstate));
2d21ac55
A
3434
3435 case DIF_VAR_PROBEFUNC:
3436 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
b0d623f7
A
3437 return (dtrace_dif_varstr(
3438 (uintptr_t)mstate->dtms_probe->dtpr_func,
3439 state, mstate));
2d21ac55
A
3440
3441 case DIF_VAR_PROBENAME:
3442 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
b0d623f7
A
3443 return (dtrace_dif_varstr(
3444 (uintptr_t)mstate->dtms_probe->dtpr_name,
3445 state, mstate));
2d21ac55 3446
2d21ac55 3447 case DIF_VAR_PID:
935ed37a 3448 if (!dtrace_priv_proc_relaxed(state))
2d21ac55
A
3449 return (0);
3450
3451 /*
3452 * Note that we are assuming that an unanchored probe is
3453 * always due to a high-level interrupt. (And we're assuming
3454 * that there is only a single high level interrupt.)
3455 */
3456 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3457 /* Anchored probe that fires while on an interrupt accrues to process 0 */
3458 return 0;
3459
39236c6e 3460 return ((uint64_t)dtrace_proc_selfpid());
2d21ac55 3461
2d21ac55 3462 case DIF_VAR_PPID:
935ed37a 3463 if (!dtrace_priv_proc_relaxed(state))
2d21ac55
A
3464 return (0);
3465
3466 /*
3467 * See comment in DIF_VAR_PID.
3468 */
3469 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3470 return (0);
3471
39236c6e 3472 return ((uint64_t)dtrace_proc_selfppid());
2d21ac55 3473
2d21ac55 3474 case DIF_VAR_TID:
b0d623f7
A
3475 /* We do not need to check for null current_thread() */
3476 return thread_tid(current_thread()); /* globally unique */
3477
3478 case DIF_VAR_PTHREAD_SELF:
3479 if (!dtrace_priv_proc(state))
3480 return (0);
3481
3482 /* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3483 return 0;
3484
3485 case DIF_VAR_DISPATCHQADDR:
3486 if (!dtrace_priv_proc(state))
2d21ac55
A
3487 return (0);
3488
b0d623f7
A
3489 /* We do not need to check for null current_thread() */
3490 return thread_dispatchqaddr(current_thread());
2d21ac55 3491
2d21ac55
A
3492 case DIF_VAR_EXECNAME:
3493 {
3494 char *xname = (char *)mstate->dtms_scratch_ptr;
3495 size_t scratch_size = MAXCOMLEN+1;
3496
3497 /* The scratch allocation's lifetime is that of the clause. */
b0d623f7
A
3498 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3499 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2d21ac55 3500 return 0;
b0d623f7 3501 }
2d21ac55 3502
935ed37a 3503 if (!dtrace_priv_proc_relaxed(state))
2d21ac55
A
3504 return (0);
3505
3506 mstate->dtms_scratch_ptr += scratch_size;
3e170ce0 3507 proc_selfname( xname, scratch_size );
2d21ac55
A
3508
3509 return ((uint64_t)(uintptr_t)xname);
3510 }
2d21ac55 3511
2d21ac55 3512
2d21ac55 3513 case DIF_VAR_ZONENAME:
5ba3f43e
A
3514 {
3515 /* scratch_size is equal to length('global') + 1 for the null-terminator. */
3516 char *zname = (char *)mstate->dtms_scratch_ptr;
3517 size_t scratch_size = 6 + 1;
39236c6e 3518
2d21ac55
A
3519 if (!dtrace_priv_proc(state))
3520 return (0);
39236c6e 3521
5ba3f43e
A
3522 /* The scratch allocation's lifetime is that of the clause. */
3523 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3524 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3525 return 0;
3526 }
3527
3528 mstate->dtms_scratch_ptr += scratch_size;
39236c6e 3529
5ba3f43e
A
3530 /* The kernel does not provide zonename, it will always return 'global'. */
3531 strlcpy(zname, "global", scratch_size);
39236c6e 3532
5ba3f43e
A
3533 return ((uint64_t)(uintptr_t)zname);
3534 }
39236c6e 3535
5ba3f43e
A
3536#if MONOTONIC
3537 case DIF_VAR_CPUINSTRS:
3538 return mt_cur_cpu_instrs();
3539
3540 case DIF_VAR_CPUCYCLES:
3541 return mt_cur_cpu_cycles();
3542
3543 case DIF_VAR_VINSTRS:
3544 return mt_cur_thread_instrs();
3545
3546 case DIF_VAR_VCYCLES:
3547 return mt_cur_thread_cycles();
3548#else /* MONOTONIC */
3549 case DIF_VAR_CPUINSTRS: /* FALLTHROUGH */
3550 case DIF_VAR_CPUCYCLES: /* FALLTHROUGH */
3551 case DIF_VAR_VINSTRS: /* FALLTHROUGH */
3552 case DIF_VAR_VCYCLES: /* FALLTHROUGH */
3553 return 0;
3554#endif /* !MONOTONIC */
2d21ac55 3555
2d21ac55 3556 case DIF_VAR_UID:
39236c6e 3557 if (!dtrace_priv_proc_relaxed(state))
2d21ac55
A
3558 return (0);
3559
3560 /*
3561 * See comment in DIF_VAR_PID.
3562 */
3563 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3564 return (0);
3565
39236c6e 3566 return ((uint64_t) dtrace_proc_selfruid());
2d21ac55 3567
2d21ac55
A
3568 case DIF_VAR_GID:
3569 if (!dtrace_priv_proc(state))
3570 return (0);
3571
3572 /*
3573 * See comment in DIF_VAR_PID.
3574 */
3575 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3576 return (0);
3577
3578 if (dtrace_CRED() != NULL)
b0d623f7 3579 /* Credential does not require lazy initialization. */
2d21ac55 3580 return ((uint64_t)kauth_getgid());
b0d623f7
A
3581 else {
3582 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3583 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3584 return -1ULL;
3585 }
2d21ac55 3586
2d21ac55
A
3587 case DIF_VAR_ERRNO: {
3588 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
3589 if (!dtrace_priv_proc(state))
3590 return (0);
3591
3592 /*
3593 * See comment in DIF_VAR_PID.
3594 */
3595 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3596 return (0);
3597
b0d623f7
A
3598 if (uthread)
3599 return (uint64_t)uthread->t_dtrace_errno;
3600 else {
3601 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3602 return -1ULL;
3603 }
2d21ac55 3604 }
2d21ac55
A
3605
3606 default:
3607 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3608 return (0);
3609 }
3610}
3611
3612/*
3613 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3614 * Notice that we don't bother validating the proper number of arguments or
3615 * their types in the tuple stack. This isn't needed because all argument
3616 * interpretation is safe because of our load safety -- the worst that can
3617 * happen is that a bogus program can obtain bogus results.
3618 */
3619static void
3620dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3621 dtrace_key_t *tupregs, int nargs,
3622 dtrace_mstate_t *mstate, dtrace_state_t *state)
3623{
3624 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2d21ac55 3625 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
b0d623f7 3626 dtrace_vstate_t *vstate = &state->dts_vstate;
2d21ac55
A
3627
3628#if !defined(__APPLE__)
3629 union {
3630 mutex_impl_t mi;
3631 uint64_t mx;
3632 } m;
3633
3634 union {
3635 krwlock_t ri;
3636 uintptr_t rw;
3637 } r;
3638#else
b0d623f7 3639/* FIXME: awaits lock/mutex work */
2d21ac55
A
3640#endif /* __APPLE__ */
3641
3642 switch (subr) {
3643 case DIF_SUBR_RAND:
3644 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3645 break;
3646
3647#if !defined(__APPLE__)
3648 case DIF_SUBR_MUTEX_OWNED:
b0d623f7
A
3649 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3650 mstate, vstate)) {
fe8ab488 3651 regs[rd] = 0;
b0d623f7
A
3652 break;
3653 }
3654
2d21ac55
A
3655 m.mx = dtrace_load64(tupregs[0].dttk_value);
3656 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3657 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3658 else
3659 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3660 break;
3661
3662 case DIF_SUBR_MUTEX_OWNER:
b0d623f7
A
3663 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3664 mstate, vstate)) {
fe8ab488 3665 regs[rd] = 0;
b0d623f7
A
3666 break;
3667 }
3668
2d21ac55
A
3669 m.mx = dtrace_load64(tupregs[0].dttk_value);
3670 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3671 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3672 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3673 else
3674 regs[rd] = 0;
3675 break;
3676
3677 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
b0d623f7
A
3678 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3679 mstate, vstate)) {
fe8ab488 3680 regs[rd] = 0;
b0d623f7
A
3681 break;
3682 }
3683
2d21ac55
A
3684 m.mx = dtrace_load64(tupregs[0].dttk_value);
3685 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3686 break;
3687
3688 case DIF_SUBR_MUTEX_TYPE_SPIN:
b0d623f7
A
3689 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3690 mstate, vstate)) {
fe8ab488 3691 regs[rd] = 0;
b0d623f7
A
3692 break;
3693 }
3694
2d21ac55
A
3695 m.mx = dtrace_load64(tupregs[0].dttk_value);
3696 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3697 break;
3698
3699 case DIF_SUBR_RW_READ_HELD: {
3700 uintptr_t tmp;
3701
b0d623f7
A
3702 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3703 mstate, vstate)) {
fe8ab488 3704 regs[rd] = 0;
b0d623f7
A
3705 break;
3706 }
3707
2d21ac55
A
3708 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3709 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3710 break;
3711 }
3712
3713 case DIF_SUBR_RW_WRITE_HELD:
b0d623f7
A
3714 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3715 mstate, vstate)) {
fe8ab488 3716 regs[rd] = 0;
b0d623f7
A
3717 break;
3718 }
3719
2d21ac55
A
3720 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3721 regs[rd] = _RW_WRITE_HELD(&r.ri);
3722 break;
3723
3724 case DIF_SUBR_RW_ISWRITER:
b0d623f7
A
3725 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3726 mstate, vstate)) {
fe8ab488 3727 regs[rd] = 0;
b0d623f7
A
3728 break;
3729 }
3730
2d21ac55
A
3731 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3732 regs[rd] = _RW_ISWRITER(&r.ri);
3733 break;
3734#else
b0d623f7 3735/* FIXME: awaits lock/mutex work */
2d21ac55
A
3736#endif /* __APPLE__ */
3737
3738 case DIF_SUBR_BCOPY: {
3739 /*
3740 * We need to be sure that the destination is in the scratch
3741 * region -- no other region is allowed.
3742 */
3743 uintptr_t src = tupregs[0].dttk_value;
3744 uintptr_t dest = tupregs[1].dttk_value;
3745 size_t size = tupregs[2].dttk_value;
3746
3747 if (!dtrace_inscratch(dest, size, mstate)) {
3748 *flags |= CPU_DTRACE_BADADDR;
3749 *illval = regs[rd];
3750 break;
3751 }
3752
b0d623f7 3753 if (!dtrace_canload(src, size, mstate, vstate)) {
fe8ab488 3754 regs[rd] = 0;
b0d623f7
A
3755 break;
3756 }
3757
2d21ac55
A
3758 dtrace_bcopy((void *)src, (void *)dest, size);
3759 break;
3760 }
3761
3762 case DIF_SUBR_ALLOCA:
3763 case DIF_SUBR_COPYIN: {
3764 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3765 uint64_t size =
3766 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3767 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3768
39037602
A
3769 /*
3770 * Check whether the user can access kernel memory
3771 */
3772 if (dtrace_priv_kernel(state) == 0) {
3773 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
3774 regs[rd] = 0;
3775 break;
3776 }
2d21ac55
A
3777 /*
3778 * This action doesn't require any credential checks since
3779 * probes will not activate in user contexts to which the
3780 * enabling user does not have permissions.
3781 */
b0d623f7
A
3782
3783 /*
3784 * Rounding up the user allocation size could have overflowed
3785 * a large, bogus allocation (like -1ULL) to 0.
3786 */
3787 if (scratch_size < size ||
3788 !DTRACE_INSCRATCH(mstate, scratch_size)) {
2d21ac55 3789 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 3790 regs[rd] = 0;
2d21ac55
A
3791 break;
3792 }
3793
3794 if (subr == DIF_SUBR_COPYIN) {
3795 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
cf7d32b8 3796 if (dtrace_priv_proc(state))
b0d623f7 3797 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
2d21ac55
A
3798 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3799 }
3800
3801 mstate->dtms_scratch_ptr += scratch_size;
3802 regs[rd] = dest;
3803 break;
3804 }
3805
3806 case DIF_SUBR_COPYINTO: {
3807 uint64_t size = tupregs[1].dttk_value;
3808 uintptr_t dest = tupregs[2].dttk_value;
3809
3810 /*
3811 * This action doesn't require any credential checks since
3812 * probes will not activate in user contexts to which the
3813 * enabling user does not have permissions.
3814 */
3815 if (!dtrace_inscratch(dest, size, mstate)) {
3816 *flags |= CPU_DTRACE_BADADDR;
3817 *illval = regs[rd];
3818 break;
3819 }
3820
3821 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
cf7d32b8 3822 if (dtrace_priv_proc(state))
b0d623f7 3823 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
2d21ac55
A
3824 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3825 break;
3826 }
3827
3828 case DIF_SUBR_COPYINSTR: {
3829 uintptr_t dest = mstate->dtms_scratch_ptr;
3830 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3831
3832 if (nargs > 1 && tupregs[1].dttk_value < size)
3833 size = tupregs[1].dttk_value + 1;
3834
3835 /*
3836 * This action doesn't require any credential checks since
3837 * probes will not activate in user contexts to which the
3838 * enabling user does not have permissions.
3839 */
b0d623f7 3840 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 3841 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 3842 regs[rd] = 0;
2d21ac55
A
3843 break;
3844 }
3845
3846 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
cf7d32b8 3847 if (dtrace_priv_proc(state))
b0d623f7 3848 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
2d21ac55
A
3849 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3850
3851 ((char *)dest)[size - 1] = '\0';
3852 mstate->dtms_scratch_ptr += size;
3853 regs[rd] = dest;
3854 break;
3855 }
3856
2d21ac55
A
3857 case DIF_SUBR_MSGSIZE:
3858 case DIF_SUBR_MSGDSIZE: {
3859 /* Darwin does not implement SysV streams messages */
b0d623f7 3860 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2d21ac55
A
3861 regs[rd] = 0;
3862 break;
3863 }
2d21ac55 3864
2d21ac55
A
3865 case DIF_SUBR_PROGENYOF: {
3866 pid_t pid = tupregs[0].dttk_value;
3867 struct proc *p = current_proc();
3868 int rval = 0, lim = nprocs;
3869
3870 while(p && (lim-- > 0)) {
3871 pid_t ppid;
3872
3873 ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
3874 if (*flags & CPU_DTRACE_FAULT)
3875 break;
3876
3877 if (ppid == pid) {
3878 rval = 1;
3879 break;
3880 }
3881
3882 if (ppid == 0)
3883 break; /* Can't climb process tree any further. */
3884
3885 p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
3886 if (*flags & CPU_DTRACE_FAULT)
3887 break;
3888 }
3889
3890 regs[rd] = rval;
3891 break;
3892 }
2d21ac55
A
3893
3894 case DIF_SUBR_SPECULATION:
3895 regs[rd] = dtrace_speculation(state);
3896 break;
3897
fe8ab488 3898
2d21ac55
A
3899 case DIF_SUBR_COPYOUT: {
3900 uintptr_t kaddr = tupregs[0].dttk_value;
fe8ab488 3901 user_addr_t uaddr = tupregs[1].dttk_value;
2d21ac55
A
3902 uint64_t size = tupregs[2].dttk_value;
3903
3904 if (!dtrace_destructive_disallow &&
3905 dtrace_priv_proc_control(state) &&
ecc0ceb4
A
3906 !dtrace_istoxic(kaddr, size) &&
3907 dtrace_canload(kaddr, size, mstate, vstate)) {
2d21ac55 3908 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
b0d623f7 3909 dtrace_copyout(kaddr, uaddr, size, flags);
2d21ac55
A
3910 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3911 }
3912 break;
3913 }
3914
3915 case DIF_SUBR_COPYOUTSTR: {
3916 uintptr_t kaddr = tupregs[0].dttk_value;
fe8ab488 3917 user_addr_t uaddr = tupregs[1].dttk_value;
2d21ac55 3918 uint64_t size = tupregs[2].dttk_value;
39037602 3919 size_t lim;
2d21ac55
A
3920
3921 if (!dtrace_destructive_disallow &&
3922 dtrace_priv_proc_control(state) &&
ecc0ceb4 3923 !dtrace_istoxic(kaddr, size) &&
39037602 3924 dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
2d21ac55 3925 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
39037602 3926 dtrace_copyoutstr(kaddr, uaddr, lim, flags);
2d21ac55
A
3927 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3928 }
3929 break;
3930 }
2d21ac55 3931
b0d623f7 3932 case DIF_SUBR_STRLEN: {
39037602 3933 size_t size = state->dts_options[DTRACEOPT_STRSIZE];
b0d623f7 3934 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
39037602 3935 size_t lim;
b0d623f7 3936
39037602 3937 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
fe8ab488 3938 regs[rd] = 0;
b0d623f7
A
3939 break;
3940 }
3941
39037602 3942 regs[rd] = dtrace_strlen((char *)addr, lim);
b0d623f7 3943
2d21ac55 3944 break;
b0d623f7 3945 }
2d21ac55
A
3946
3947 case DIF_SUBR_STRCHR:
3948 case DIF_SUBR_STRRCHR: {
3949 /*
3950 * We're going to iterate over the string looking for the
3951 * specified character. We will iterate until we have reached
3952 * the string length or we have found the character. If this
3953 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3954 * of the specified character instead of the first.
3955 */
3956 uintptr_t addr = tupregs[0].dttk_value;
39037602
A
3957 uintptr_t addr_limit;
3958 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3959 size_t lim;
2d21ac55
A
3960 char c, target = (char)tupregs[1].dttk_value;
3961
39037602 3962 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
5ba3f43e 3963 regs[rd] = 0;
39037602
A
3964 break;
3965 }
3966 addr_limit = addr + lim;
3967
3968 for (regs[rd] = 0; addr < addr_limit; addr++) {
2d21ac55
A
3969 if ((c = dtrace_load8(addr)) == target) {
3970 regs[rd] = addr;
3971
3972 if (subr == DIF_SUBR_STRCHR)
3973 break;
3974 }
3975
3976 if (c == '\0')
3977 break;
3978 }
3979
3980 break;
3981 }
3982
3983 case DIF_SUBR_STRSTR:
3984 case DIF_SUBR_INDEX:
3985 case DIF_SUBR_RINDEX: {
3986 /*
3987 * We're going to iterate over the string looking for the
3988 * specified string. We will iterate until we have reached
3989 * the string length or we have found the string. (Yes, this
3990 * is done in the most naive way possible -- but considering
3991 * that the string we're searching for is likely to be
3992 * relatively short, the complexity of Rabin-Karp or similar
3993 * hardly seems merited.)
3994 */
3995 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3996 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3997 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3998 size_t len = dtrace_strlen(addr, size);
3999 size_t sublen = dtrace_strlen(substr, size);
4000 char *limit = addr + len, *orig = addr;
4001 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4002 int inc = 1;
4003
4004 regs[rd] = notfound;
4005
b0d623f7 4006 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
fe8ab488 4007 regs[rd] = 0;
b0d623f7
A
4008 break;
4009 }
4010
4011 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4012 vstate)) {
fe8ab488 4013 regs[rd] = 0;
b0d623f7
A
4014 break;
4015 }
4016
2d21ac55
A
4017 /*
4018 * strstr() and index()/rindex() have similar semantics if
4019 * both strings are the empty string: strstr() returns a
4020 * pointer to the (empty) string, and index() and rindex()
4021 * both return index 0 (regardless of any position argument).
4022 */
4023 if (sublen == 0 && len == 0) {
4024 if (subr == DIF_SUBR_STRSTR)
4025 regs[rd] = (uintptr_t)addr;
4026 else
4027 regs[rd] = 0;
4028 break;
4029 }
4030
4031 if (subr != DIF_SUBR_STRSTR) {
4032 if (subr == DIF_SUBR_RINDEX) {
4033 limit = orig - 1;
4034 addr += len;
4035 inc = -1;
4036 }
4037
4038 /*
4039 * Both index() and rindex() take an optional position
4040 * argument that denotes the starting position.
4041 */
4042 if (nargs == 3) {
4043 int64_t pos = (int64_t)tupregs[2].dttk_value;
4044
4045 /*
4046 * If the position argument to index() is
4047 * negative, Perl implicitly clamps it at
4048 * zero. This semantic is a little surprising
4049 * given the special meaning of negative
4050 * positions to similar Perl functions like
4051 * substr(), but it appears to reflect a
4052 * notion that index() can start from a
4053 * negative index and increment its way up to
4054 * the string. Given this notion, Perl's
4055 * rindex() is at least self-consistent in
4056 * that it implicitly clamps positions greater
4057 * than the string length to be the string
4058 * length. Where Perl completely loses
4059 * coherence, however, is when the specified
4060 * substring is the empty string (""). In
4061 * this case, even if the position is
4062 * negative, rindex() returns 0 -- and even if
4063 * the position is greater than the length,
4064 * index() returns the string length. These
4065 * semantics violate the notion that index()
4066 * should never return a value less than the
4067 * specified position and that rindex() should
4068 * never return a value greater than the
4069 * specified position. (One assumes that
4070 * these semantics are artifacts of Perl's
4071 * implementation and not the results of
4072 * deliberate design -- it beggars belief that
4073 * even Larry Wall could desire such oddness.)
4074 * While in the abstract one would wish for
4075 * consistent position semantics across
4076 * substr(), index() and rindex() -- or at the
4077 * very least self-consistent position
4078 * semantics for index() and rindex() -- we
4079 * instead opt to keep with the extant Perl
4080 * semantics, in all their broken glory. (Do
4081 * we have more desire to maintain Perl's
4082 * semantics than Perl does? Probably.)
4083 */
4084 if (subr == DIF_SUBR_RINDEX) {
4085 if (pos < 0) {
4086 if (sublen == 0)
4087 regs[rd] = 0;
4088 break;
4089 }
4090
b0d623f7 4091 if ((size_t)pos > len)
2d21ac55
A
4092 pos = len;
4093 } else {
4094 if (pos < 0)
4095 pos = 0;
4096
b0d623f7 4097 if ((size_t)pos >= len) {
2d21ac55
A
4098 if (sublen == 0)
4099 regs[rd] = len;
4100 break;
4101 }
4102 }
4103
4104 addr = orig + pos;
4105 }
4106 }
4107
4108 for (regs[rd] = notfound; addr != limit; addr += inc) {
4109 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4110 if (subr != DIF_SUBR_STRSTR) {
4111 /*
4112 * As D index() and rindex() are
4113 * modeled on Perl (and not on awk),
4114 * we return a zero-based (and not a
4115 * one-based) index. (For you Perl
4116 * weenies: no, we're not going to add
4117 * $[ -- and shouldn't you be at a con
4118 * or something?)
4119 */
4120 regs[rd] = (uintptr_t)(addr - orig);
4121 break;
4122 }
4123
4124 ASSERT(subr == DIF_SUBR_STRSTR);
4125 regs[rd] = (uintptr_t)addr;
4126 break;
4127 }
4128 }
4129
4130 break;
4131 }
4132
4133 case DIF_SUBR_STRTOK: {
4134 uintptr_t addr = tupregs[0].dttk_value;
4135 uintptr_t tokaddr = tupregs[1].dttk_value;
4136 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
39037602
A
4137 uintptr_t limit, toklimit;
4138 size_t clim;
2d21ac55 4139 char *dest = (char *)mstate->dtms_scratch_ptr;
b0d623f7
A
4140 uint8_t c='\0', tokmap[32]; /* 256 / 8 */
4141 uint64_t i = 0;
b0d623f7
A
4142
4143 /*
4144 * Check both the token buffer and (later) the input buffer,
4145 * since both could be non-scratch addresses.
4146 */
39037602 4147 if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
fe8ab488 4148 regs[rd] = 0;
b0d623f7
A
4149 break;
4150 }
39037602 4151 toklimit = tokaddr + clim;
2d21ac55 4152
b0d623f7 4153 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4154 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4155 regs[rd] = 0;
2d21ac55
A
4156 break;
4157 }
4158
fe8ab488 4159 if (addr == 0) {
2d21ac55
A
4160 /*
4161 * If the address specified is NULL, we use our saved
4162 * strtok pointer from the mstate. Note that this
4163 * means that the saved strtok pointer is _only_
4164 * valid within multiple enablings of the same probe --
4165 * it behaves like an implicit clause-local variable.
4166 */
4167 addr = mstate->dtms_strtok;
39037602 4168 limit = mstate->dtms_strtok_limit;
b0d623f7
A
4169 } else {
4170 /*
4171 * If the user-specified address is non-NULL we must
4172 * access check it. This is the only time we have
4173 * a chance to do so, since this address may reside
4174 * in the string table of this clause-- future calls
4175 * (when we fetch addr from mstate->dtms_strtok)
4176 * would fail this access check.
4177 */
39037602
A
4178 if (!dtrace_strcanload(addr, size, &clim, mstate,
4179 vstate)) {
fe8ab488 4180 regs[rd] = 0;
b0d623f7 4181 break;
fe8ab488 4182 }
39037602 4183 limit = addr + clim;
2d21ac55
A
4184 }
4185
4186 /*
4187 * First, zero the token map, and then process the token
4188 * string -- setting a bit in the map for every character
4189 * found in the token string.
4190 */
c910b4d9 4191 for (i = 0; i < (int)sizeof (tokmap); i++)
2d21ac55
A
4192 tokmap[i] = 0;
4193
4194 for (; tokaddr < toklimit; tokaddr++) {
4195 if ((c = dtrace_load8(tokaddr)) == '\0')
4196 break;
4197
4198 ASSERT((c >> 3) < sizeof (tokmap));
4199 tokmap[c >> 3] |= (1 << (c & 0x7));
4200 }
4201
39037602 4202 for (; addr < limit; addr++) {
2d21ac55 4203 /*
39037602
A
4204 * We're looking for a character that is _not_
4205 * contained in the token string.
2d21ac55
A
4206 */
4207 if ((c = dtrace_load8(addr)) == '\0')
4208 break;
4209
4210 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4211 break;
4212 }
4213
4214 if (c == '\0') {
4215 /*
4216 * We reached the end of the string without finding
4217 * any character that was not in the token string.
4218 * We return NULL in this case, and we set the saved
4219 * address to NULL as well.
4220 */
fe8ab488
A
4221 regs[rd] = 0;
4222 mstate->dtms_strtok = 0;
5ba3f43e 4223 mstate->dtms_strtok_limit = 0;
2d21ac55
A
4224 break;
4225 }
4226
4227 /*
4228 * From here on, we're copying into the destination string.
4229 */
4230 for (i = 0; addr < limit && i < size - 1; addr++) {
4231 if ((c = dtrace_load8(addr)) == '\0')
4232 break;
4233
4234 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4235 break;
4236
4237 ASSERT(i < size);
4238 dest[i++] = c;
4239 }
4240
4241 ASSERT(i < size);
4242 dest[i] = '\0';
4243 regs[rd] = (uintptr_t)dest;
4244 mstate->dtms_scratch_ptr += size;
4245 mstate->dtms_strtok = addr;
39037602 4246 mstate->dtms_strtok_limit = limit;
2d21ac55
A
4247 break;
4248 }
4249
4250 case DIF_SUBR_SUBSTR: {
4251 uintptr_t s = tupregs[0].dttk_value;
4252 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4253 char *d = (char *)mstate->dtms_scratch_ptr;
4254 int64_t index = (int64_t)tupregs[1].dttk_value;
4255 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4256 size_t len = dtrace_strlen((char *)s, size);
4257 int64_t i = 0;
4258
b0d623f7 4259 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
fe8ab488 4260 regs[rd] = 0;
b0d623f7
A
4261 break;
4262 }
2d21ac55 4263
b0d623f7 4264 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4265 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4266 regs[rd] = 0;
2d21ac55
A
4267 break;
4268 }
4269
b0d623f7
A
4270 if (nargs <= 2)
4271 remaining = (int64_t)size;
4272
2d21ac55
A
4273 if (index < 0) {
4274 index += len;
4275
4276 if (index < 0 && index + remaining > 0) {
4277 remaining += index;
4278 index = 0;
4279 }
4280 }
4281
b0d623f7
A
4282 if ((size_t)index >= len || index < 0) {
4283 remaining = 0;
4284 } else if (remaining < 0) {
4285 remaining += len - index;
4286 } else if ((uint64_t)index + (uint64_t)remaining > size) {
4287 remaining = size - index;
4288 }
fe8ab488 4289
b0d623f7
A
4290 for (i = 0; i < remaining; i++) {
4291 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
2d21ac55
A
4292 break;
4293 }
b0d623f7
A
4294
4295 d[i] = '\0';
2d21ac55
A
4296
4297 mstate->dtms_scratch_ptr += size;
4298 regs[rd] = (uintptr_t)d;
4299 break;
4300 }
4301
2d21ac55
A
4302 case DIF_SUBR_GETMAJOR:
4303 regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4304 break;
2d21ac55 4305
2d21ac55
A
4306 case DIF_SUBR_GETMINOR:
4307 regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4308 break;
2d21ac55 4309
2d21ac55 4310 case DIF_SUBR_DDI_PATHNAME: {
fe8ab488 4311 /* APPLE NOTE: currently unsupported on Darwin */
b0d623f7 4312 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
fe8ab488 4313 regs[rd] = 0;
2d21ac55
A
4314 break;
4315 }
2d21ac55
A
4316
4317 case DIF_SUBR_STRJOIN: {
4318 char *d = (char *)mstate->dtms_scratch_ptr;
4319 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4320 uintptr_t s1 = tupregs[0].dttk_value;
4321 uintptr_t s2 = tupregs[1].dttk_value;
39037602
A
4322 uint64_t i = 0, j = 0;
4323 size_t lim1, lim2;
4324 char c;
b0d623f7 4325
39037602
A
4326 if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
4327 !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
fe8ab488 4328 regs[rd] = 0;
b0d623f7
A
4329 break;
4330 }
2d21ac55 4331
b0d623f7 4332 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4333 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4334 regs[rd] = 0;
2d21ac55
A
4335 break;
4336 }
4337
4338 for (;;) {
4339 if (i >= size) {
4340 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4341 regs[rd] = 0;
2d21ac55
A
4342 break;
4343 }
39037602
A
4344 c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
4345 if ((d[i++] = c) == '\0') {
2d21ac55
A
4346 i--;
4347 break;
4348 }
4349 }
4350
4351 for (;;) {
4352 if (i >= size) {
4353 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4354 regs[rd] = 0;
2d21ac55
A
4355 break;
4356 }
39037602
A
4357 c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
4358 if ((d[i++] = c) == '\0')
2d21ac55
A
4359 break;
4360 }
4361
4362 if (i < size) {
4363 mstate->dtms_scratch_ptr += i;
4364 regs[rd] = (uintptr_t)d;
4365 }
4366
4367 break;
4368 }
4369
4370 case DIF_SUBR_LLTOSTR: {
4371 int64_t i = (int64_t)tupregs[0].dttk_value;
5ba3f43e
A
4372 uint64_t val, digit;
4373 uint64_t size = 65; /* enough room for 2^64 in binary */
2d21ac55 4374 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5ba3f43e
A
4375 int base = 10;
4376
4377 if (nargs > 1) {
4378 if ((base = tupregs[1].dttk_value) <= 1 ||
4379 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4380 *flags |= CPU_DTRACE_ILLOP;
4381 break;
4382 }
4383 }
4384
4385 val = (base == 10 && i < 0) ? i * -1 : i;
2d21ac55 4386
b0d623f7 4387 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4388 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4389 regs[rd] = 0;
2d21ac55
A
4390 break;
4391 }
4392
5ba3f43e
A
4393 for (*end-- = '\0'; val; val /= base) {
4394 if ((digit = val % base) <= '9' - '0') {
4395 *end-- = '0' + digit;
4396 } else {
4397 *end-- = 'a' + (digit - ('9' - '0') - 1);
4398 }
4399 }
2d21ac55 4400
5ba3f43e 4401 if (i == 0 && base == 16)
2d21ac55
A
4402 *end-- = '0';
4403
5ba3f43e
A
4404 if (base == 16)
4405 *end-- = 'x';
4406
4407 if (i == 0 || base == 8 || base == 16)
4408 *end-- = '0';
4409
4410 if (i < 0 && base == 10)
2d21ac55
A
4411 *end-- = '-';
4412
4413 regs[rd] = (uintptr_t)end + 1;
4414 mstate->dtms_scratch_ptr += size;
4415 break;
4416 }
4417
b0d623f7
A
4418 case DIF_SUBR_HTONS:
4419 case DIF_SUBR_NTOHS:
4420#ifdef _BIG_ENDIAN
4421 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4422#else
4423 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4424#endif
4425 break;
4426
4427
4428 case DIF_SUBR_HTONL:
4429 case DIF_SUBR_NTOHL:
4430#ifdef _BIG_ENDIAN
4431 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4432#else
4433 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4434#endif
4435 break;
4436
4437
4438 case DIF_SUBR_HTONLL:
4439 case DIF_SUBR_NTOHLL:
4440#ifdef _BIG_ENDIAN
4441 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4442#else
4443 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4444#endif
4445 break;
4446
4447
2d21ac55
A
4448 case DIF_SUBR_DIRNAME:
4449 case DIF_SUBR_BASENAME: {
4450 char *dest = (char *)mstate->dtms_scratch_ptr;
4451 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4452 uintptr_t src = tupregs[0].dttk_value;
4453 int i, j, len = dtrace_strlen((char *)src, size);
4454 int lastbase = -1, firstbase = -1, lastdir = -1;
4455 int start, end;
4456
b0d623f7 4457 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
fe8ab488 4458 regs[rd] = 0;
b0d623f7
A
4459 break;
4460 }
4461
4462 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4463 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4464 regs[rd] = 0;
2d21ac55
A
4465 break;
4466 }
4467
4468 /*
4469 * The basename and dirname for a zero-length string is
4470 * defined to be "."
4471 */
4472 if (len == 0) {
4473 len = 1;
4474 src = (uintptr_t)".";
4475 }
4476
4477 /*
4478 * Start from the back of the string, moving back toward the
4479 * front until we see a character that isn't a slash. That
4480 * character is the last character in the basename.
4481 */
4482 for (i = len - 1; i >= 0; i--) {
4483 if (dtrace_load8(src + i) != '/')
4484 break;
4485 }
4486
4487 if (i >= 0)
4488 lastbase = i;
4489
4490 /*
4491 * Starting from the last character in the basename, move
4492 * towards the front until we find a slash. The character
4493 * that we processed immediately before that is the first
4494 * character in the basename.
4495 */
4496 for (; i >= 0; i--) {
4497 if (dtrace_load8(src + i) == '/')
4498 break;
4499 }
4500
4501 if (i >= 0)
4502 firstbase = i + 1;
4503
4504 /*
4505 * Now keep going until we find a non-slash character. That
4506 * character is the last character in the dirname.
4507 */
4508 for (; i >= 0; i--) {
4509 if (dtrace_load8(src + i) != '/')
4510 break;
4511 }
4512
4513 if (i >= 0)
4514 lastdir = i;
4515
4516 ASSERT(!(lastbase == -1 && firstbase != -1));
4517 ASSERT(!(firstbase == -1 && lastdir != -1));
4518
4519 if (lastbase == -1) {
4520 /*
4521 * We didn't find a non-slash character. We know that
4522 * the length is non-zero, so the whole string must be
4523 * slashes. In either the dirname or the basename
4524 * case, we return '/'.
4525 */
4526 ASSERT(firstbase == -1);
4527 firstbase = lastbase = lastdir = 0;
4528 }
4529
4530 if (firstbase == -1) {
4531 /*
4532 * The entire string consists only of a basename
4533 * component. If we're looking for dirname, we need
4534 * to change our string to be just "."; if we're
4535 * looking for a basename, we'll just set the first
4536 * character of the basename to be 0.
4537 */
4538 if (subr == DIF_SUBR_DIRNAME) {
4539 ASSERT(lastdir == -1);
4540 src = (uintptr_t)".";
4541 lastdir = 0;
4542 } else {
4543 firstbase = 0;
4544 }
4545 }
4546
4547 if (subr == DIF_SUBR_DIRNAME) {
4548 if (lastdir == -1) {
4549 /*
4550 * We know that we have a slash in the name --
4551 * or lastdir would be set to 0, above. And
4552 * because lastdir is -1, we know that this
4553 * slash must be the first character. (That
4554 * is, the full string must be of the form
4555 * "/basename".) In this case, the last
4556 * character of the directory name is 0.
4557 */
4558 lastdir = 0;
4559 }
4560
4561 start = 0;
4562 end = lastdir;
4563 } else {
4564 ASSERT(subr == DIF_SUBR_BASENAME);
4565 ASSERT(firstbase != -1 && lastbase != -1);
4566 start = firstbase;
4567 end = lastbase;
4568 }
4569
b0d623f7
A
4570 for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
4571 dest[j] = dtrace_load8(src + i);
2d21ac55
A
4572
4573 dest[j] = '\0';
4574 regs[rd] = (uintptr_t)dest;
4575 mstate->dtms_scratch_ptr += size;
4576 break;
4577 }
4578
4579 case DIF_SUBR_CLEANPATH: {
4580 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4581 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4582 uintptr_t src = tupregs[0].dttk_value;
39037602
A
4583 size_t lim;
4584 size_t i = 0, j = 0;
2d21ac55 4585
39037602 4586 if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
fe8ab488 4587 regs[rd] = 0;
b0d623f7
A
4588 break;
4589 }
4590
4591 if (!DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 4592 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4593 regs[rd] = 0;
2d21ac55
A
4594 break;
4595 }
4596
4597 /*
4598 * Move forward, loading each character.
4599 */
4600 do {
39037602 4601 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
2d21ac55 4602next:
b0d623f7
A
4603 if ((uint64_t)(j + 5) >= size) /* 5 = strlen("/..c\0") */
4604 break;
2d21ac55
A
4605
4606 if (c != '/') {
4607 dest[j++] = c;
4608 continue;
4609 }
4610
39037602 4611 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
2d21ac55
A
4612
4613 if (c == '/') {
4614 /*
4615 * We have two slashes -- we can just advance
4616 * to the next character.
4617 */
4618 goto next;
4619 }
4620
4621 if (c != '.') {
4622 /*
4623 * This is not "." and it's not ".." -- we can
4624 * just store the "/" and this character and
4625 * drive on.
4626 */
4627 dest[j++] = '/';
4628 dest[j++] = c;
4629 continue;
4630 }
4631
39037602 4632 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
2d21ac55
A
4633
4634 if (c == '/') {
4635 /*
4636 * This is a "/./" component. We're not going
4637 * to store anything in the destination buffer;
4638 * we're just going to go to the next component.
4639 */
4640 goto next;
4641 }
4642
4643 if (c != '.') {
4644 /*
4645 * This is not ".." -- we can just store the
4646 * "/." and this character and continue
4647 * processing.
4648 */
4649 dest[j++] = '/';
4650 dest[j++] = '.';
4651 dest[j++] = c;
4652 continue;
4653 }
4654
39037602 4655 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
2d21ac55
A
4656
4657 if (c != '/' && c != '\0') {
4658 /*
4659 * This is not ".." -- it's "..[mumble]".
4660 * We'll store the "/.." and this character
4661 * and continue processing.
4662 */
4663 dest[j++] = '/';
4664 dest[j++] = '.';
4665 dest[j++] = '.';
4666 dest[j++] = c;
4667 continue;
4668 }
4669
4670 /*
4671 * This is "/../" or "/..\0". We need to back up
4672 * our destination pointer until we find a "/".
4673 */
4674 i--;
4675 while (j != 0 && dest[--j] != '/')
4676 continue;
4677
4678 if (c == '\0')
4679 dest[++j] = '/';
4680 } while (c != '\0');
4681
4682 dest[j] = '\0';
4683 regs[rd] = (uintptr_t)dest;
4684 mstate->dtms_scratch_ptr += size;
4685 break;
4686 }
2d21ac55 4687
b0d623f7
A
4688 case DIF_SUBR_INET_NTOA:
4689 case DIF_SUBR_INET_NTOA6:
4690 case DIF_SUBR_INET_NTOP: {
4691 size_t size;
4692 int af, argi, i;
4693 char *base, *end;
2d21ac55 4694
b0d623f7
A
4695 if (subr == DIF_SUBR_INET_NTOP) {
4696 af = (int)tupregs[0].dttk_value;
4697 argi = 1;
4698 } else {
4699 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4700 argi = 0;
2d21ac55
A
4701 }
4702
b0d623f7
A
4703 if (af == AF_INET) {
4704#if !defined(__APPLE__)
4705 ipaddr_t ip4;
4706#else
6d2010ae 4707 uint32_t ip4;
b0d623f7
A
4708#endif /* __APPLE__ */
4709 uint8_t *ptr8, val;
4710
4711 /*
4712 * Safely load the IPv4 address.
4713 */
6d2010ae 4714#if !defined(__APPLE__)
b0d623f7 4715 ip4 = dtrace_load32(tupregs[argi].dttk_value);
6d2010ae 4716#else
39037602
A
4717 if (!dtrace_canload(tupregs[argi].dttk_value, sizeof(ip4),
4718 mstate, vstate)) {
4719 regs[rd] = 0;
4720 break;
4721 }
4722
6d2010ae
A
4723 dtrace_bcopy(
4724 (void *)(uintptr_t)tupregs[argi].dttk_value,
4725 (void *)(uintptr_t)&ip4, sizeof (ip4));
4726#endif /* __APPLE__ */
b0d623f7
A
4727 /*
4728 * Check an IPv4 string will fit in scratch.
4729 */
4730#if !defined(__APPLE__)
4731 size = INET_ADDRSTRLEN;
4732#else
4733 size = MAX_IPv4_STR_LEN;
4734#endif /* __APPLE__ */
4735 if (!DTRACE_INSCRATCH(mstate, size)) {
4736 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4737 regs[rd] = 0;
b0d623f7
A
4738 break;
4739 }
4740 base = (char *)mstate->dtms_scratch_ptr;
4741 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4742
4743 /*
4744 * Stringify as a dotted decimal quad.
4745 */
4746 *end-- = '\0';
4747 ptr8 = (uint8_t *)&ip4;
4748 for (i = 3; i >= 0; i--) {
4749 val = ptr8[i];
4750
4751 if (val == 0) {
4752 *end-- = '0';
4753 } else {
4754 for (; val; val /= 10) {
4755 *end-- = '0' + (val % 10);
4756 }
4757 }
4758
4759 if (i > 0)
4760 *end-- = '.';
4761 }
4762 ASSERT(end + 1 >= base);
4763
4764 } else if (af == AF_INET6) {
4765#if defined(__APPLE__)
4766#define _S6_un __u6_addr
4767#define _S6_u8 __u6_addr8
4768#endif /* __APPLE__ */
4769 struct in6_addr ip6;
4770 int firstzero, tryzero, numzero, v6end;
4771 uint16_t val;
4772 const char digits[] = "0123456789abcdef";
4773
4774 /*
4775 * Stringify using RFC 1884 convention 2 - 16 bit
4776 * hexadecimal values with a zero-run compression.
4777 * Lower case hexadecimal digits are used.
4778 * eg, fe80::214:4fff:fe0b:76c8.
4779 * The IPv4 embedded form is returned for inet_ntop,
4780 * just the IPv4 string is returned for inet_ntoa6.
4781 */
4782
39037602
A
4783 if (!dtrace_canload(tupregs[argi].dttk_value,
4784 sizeof(struct in6_addr), mstate, vstate)) {
4785 regs[rd] = 0;
4786 break;
4787 }
4788
b0d623f7
A
4789 /*
4790 * Safely load the IPv6 address.
4791 */
4792 dtrace_bcopy(
4793 (void *)(uintptr_t)tupregs[argi].dttk_value,
4794 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4795
4796 /*
4797 * Check an IPv6 string will fit in scratch.
4798 */
4799 size = INET6_ADDRSTRLEN;
4800 if (!DTRACE_INSCRATCH(mstate, size)) {
4801 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 4802 regs[rd] = 0;
b0d623f7
A
4803 break;
4804 }
4805 base = (char *)mstate->dtms_scratch_ptr;
4806 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4807 *end-- = '\0';
4808
4809 /*
4810 * Find the longest run of 16 bit zero values
4811 * for the single allowed zero compression - "::".
4812 */
4813 firstzero = -1;
4814 tryzero = -1;
4815 numzero = 1;
b0d623f7 4816 for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
b0d623f7
A
4817 if (ip6._S6_un._S6_u8[i] == 0 &&
4818 tryzero == -1 && i % 2 == 0) {
4819 tryzero = i;
4820 continue;
4821 }
4822
4823 if (tryzero != -1 &&
4824 (ip6._S6_un._S6_u8[i] != 0 ||
4825 i == sizeof (struct in6_addr) - 1)) {
4826
4827 if (i - tryzero <= numzero) {
4828 tryzero = -1;
4829 continue;
4830 }
4831
4832 firstzero = tryzero;
4833 numzero = i - i % 2 - tryzero;
4834 tryzero = -1;
4835
4836 if (ip6._S6_un._S6_u8[i] == 0 &&
4837 i == sizeof (struct in6_addr) - 1)
4838 numzero += 2;
4839 }
4840 }
b0d623f7 4841 ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
b0d623f7
A
4842
4843 /*
4844 * Check for an IPv4 embedded address.
4845 */
4846 v6end = sizeof (struct in6_addr) - 2;
4847 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4848 IN6_IS_ADDR_V4COMPAT(&ip6)) {
b0d623f7
A
4849 for (i = sizeof (struct in6_addr) - 1;
4850 i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
b0d623f7
A
4851 ASSERT(end >= base);
4852
4853 val = ip6._S6_un._S6_u8[i];
4854
4855 if (val == 0) {
4856 *end-- = '0';
4857 } else {
4858 for (; val; val /= 10) {
4859 *end-- = '0' + val % 10;
4860 }
4861 }
4862
b0d623f7
A
4863 if (i > (int)DTRACE_V4MAPPED_OFFSET)
4864 *end-- = '.';
b0d623f7
A
4865 }
4866
4867 if (subr == DIF_SUBR_INET_NTOA6)
4868 goto inetout;
4869
4870 /*
4871 * Set v6end to skip the IPv4 address that
4872 * we have already stringified.
4873 */
4874 v6end = 10;
4875 }
4876
4877 /*
4878 * Build the IPv6 string by working through the
4879 * address in reverse.
4880 */
4881 for (i = v6end; i >= 0; i -= 2) {
4882 ASSERT(end >= base);
4883
4884 if (i == firstzero + numzero - 2) {
4885 *end-- = ':';
4886 *end-- = ':';
4887 i -= numzero - 2;
4888 continue;
4889 }
4890
4891 if (i < 14 && i != firstzero - 2)
4892 *end-- = ':';
4893
4894 val = (ip6._S6_un._S6_u8[i] << 8) +
4895 ip6._S6_un._S6_u8[i + 1];
4896
4897 if (val == 0) {
4898 *end-- = '0';
4899 } else {
4900 for (; val; val /= 16) {
4901 *end-- = digits[val % 16];
4902 }
4903 }
4904 }
4905 ASSERT(end + 1 >= base);
4906
4907#if defined(__APPLE__)
4908#undef _S6_un
4909#undef _S6_u8
4910#endif /* __APPLE__ */
4911 } else {
4912 /*
4913 * The user didn't use AH_INET or AH_INET6.
4914 */
4915 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
fe8ab488 4916 regs[rd] = 0;
b0d623f7
A
4917 break;
4918 }
4919
4920inetout: regs[rd] = (uintptr_t)end + 1;
4921 mstate->dtms_scratch_ptr += size;
4922 break;
4923 }
b0d623f7 4924
fe8ab488
A
4925 case DIF_SUBR_TOUPPER:
4926 case DIF_SUBR_TOLOWER: {
4927 uintptr_t src = tupregs[0].dttk_value;
4928 char *dest = (char *)mstate->dtms_scratch_ptr;
4929 char lower, upper, base, c;
4930 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4931 size_t len = dtrace_strlen((char*) src, size);
4932 size_t i = 0;
4933
4934 lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
4935 upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
4936 base = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
4937
4938 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4939 regs[rd] = 0;
4940 break;
4941 }
4942
4943 if (!DTRACE_INSCRATCH(mstate, size)) {
4944 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4945 regs[rd] = 0;
4946 break;
4947 }
4948
4949 for (i = 0; i < size - 1; ++i) {
4950 if ((c = dtrace_load8(src + i)) == '\0')
4951 break;
4952 if (c >= lower && c <= upper)
4953 c = base + (c - lower);
4954 dest[i] = c;
4955 }
4956
4957 ASSERT(i < size);
4958
4959 dest[i] = '\0';
4960 regs[rd] = (uintptr_t) dest;
4961 mstate->dtms_scratch_ptr += size;
4962
4963 break;
4964 }
4965
39037602 4966#if defined(__APPLE__)
3e170ce0
A
4967 case DIF_SUBR_VM_KERNEL_ADDRPERM: {
4968 if (!dtrace_priv_kernel(state)) {
4969 regs[rd] = 0;
4970 } else {
4971 regs[rd] = VM_KERNEL_ADDRPERM((vm_offset_t) tupregs[0].dttk_value);
4972 }
4973
4974 break;
4975 }
39037602
A
4976
4977 case DIF_SUBR_KDEBUG_TRACE: {
4978 uint32_t debugid;
4979 uintptr_t args[4] = {0};
4980 int i;
4981
4982 if (nargs < 2 || nargs > 5) {
4983 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4984 break;
b0d623f7 4985 }
b0d623f7 4986
39037602
A
4987 if (dtrace_destructive_disallow)
4988 return;
4989
4990 debugid = tupregs[0].dttk_value;
4991 for (i = 0; i < nargs - 1; i++)
4992 args[i] = tupregs[i + 1].dttk_value;
4993
4994 kernel_debug(debugid, args[0], args[1], args[2], args[3], 0);
4995
4996 break;
4997 }
4998
4999 case DIF_SUBR_KDEBUG_TRACE_STRING: {
5000 if (nargs != 3) {
5001 break;
b0d623f7
A
5002 }
5003
39037602
A
5004 if (dtrace_destructive_disallow)
5005 return;
5006
5007 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5008 uint32_t debugid = tupregs[0].dttk_value;
5009 uint64_t str_id = tupregs[1].dttk_value;
5010 uintptr_t src = tupregs[2].dttk_value;
5011 size_t lim;
5012 char buf[size];
5013 char* str = NULL;
5014
5015 if (src != (uintptr_t)0) {
5016 str = buf;
5017 if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5018 break;
5019 }
5020 dtrace_strcpy((void*)src, buf, size);
2d21ac55 5021 }
b0d623f7 5022
39037602
A
5023 (void)kernel_debug_string(debugid, &str_id, str);
5024 regs[rd] = str_id;
5025
2d21ac55
A
5026 break;
5027 }
39037602
A
5028#endif
5029
2d21ac55
A
5030 }
5031}
5032
5033/*
5034 * Emulate the execution of DTrace IR instructions specified by the given
5035 * DIF object. This function is deliberately void of assertions as all of
5036 * the necessary checks are handled by a call to dtrace_difo_validate().
5037 */
5038static uint64_t
5039dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5040 dtrace_vstate_t *vstate, dtrace_state_t *state)
5041{
5042 const dif_instr_t *text = difo->dtdo_buf;
5043 const uint_t textlen = difo->dtdo_len;
5044 const char *strtab = difo->dtdo_strtab;
5045 const uint64_t *inttab = difo->dtdo_inttab;
5046
5047 uint64_t rval = 0;
5048 dtrace_statvar_t *svar;
5049 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5050 dtrace_difv_t *v;
5051 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2d21ac55 5052 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2d21ac55
A
5053
5054 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5055 uint64_t regs[DIF_DIR_NREGS];
5056 uint64_t *tmp;
5057
5058 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5059 int64_t cc_r;
b0d623f7 5060 uint_t pc = 0, id, opc = 0;
2d21ac55
A
5061 uint8_t ttop = 0;
5062 dif_instr_t instr;
5063 uint_t r1, r2, rd;
5064
b0d623f7
A
5065 /*
5066 * We stash the current DIF object into the machine state: we need it
5067 * for subsequent access checking.
5068 */
5069 mstate->dtms_difo = difo;
5070
2d21ac55
A
5071 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5072
5073 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5074 opc = pc;
5075
5076 instr = text[pc++];
5077 r1 = DIF_INSTR_R1(instr);
5078 r2 = DIF_INSTR_R2(instr);
5079 rd = DIF_INSTR_RD(instr);
5080
5081 switch (DIF_INSTR_OP(instr)) {
5082 case DIF_OP_OR:
5083 regs[rd] = regs[r1] | regs[r2];
5084 break;
5085 case DIF_OP_XOR:
5086 regs[rd] = regs[r1] ^ regs[r2];
5087 break;
5088 case DIF_OP_AND:
5089 regs[rd] = regs[r1] & regs[r2];
5090 break;
5091 case DIF_OP_SLL:
5092 regs[rd] = regs[r1] << regs[r2];
5093 break;
5094 case DIF_OP_SRL:
5095 regs[rd] = regs[r1] >> regs[r2];
5096 break;
5097 case DIF_OP_SUB:
5098 regs[rd] = regs[r1] - regs[r2];
5099 break;
5100 case DIF_OP_ADD:
5101 regs[rd] = regs[r1] + regs[r2];
5102 break;
5103 case DIF_OP_MUL:
5104 regs[rd] = regs[r1] * regs[r2];
5105 break;
5106 case DIF_OP_SDIV:
5107 if (regs[r2] == 0) {
5108 regs[rd] = 0;
5109 *flags |= CPU_DTRACE_DIVZERO;
5110 } else {
5111 regs[rd] = (int64_t)regs[r1] /
5112 (int64_t)regs[r2];
5113 }
5114 break;
5115
5116 case DIF_OP_UDIV:
5117 if (regs[r2] == 0) {
5118 regs[rd] = 0;
5119 *flags |= CPU_DTRACE_DIVZERO;
5120 } else {
5121 regs[rd] = regs[r1] / regs[r2];
5122 }
5123 break;
5124
5125 case DIF_OP_SREM:
5126 if (regs[r2] == 0) {
5127 regs[rd] = 0;
5128 *flags |= CPU_DTRACE_DIVZERO;
5129 } else {
5130 regs[rd] = (int64_t)regs[r1] %
5131 (int64_t)regs[r2];
5132 }
5133 break;
5134
5135 case DIF_OP_UREM:
5136 if (regs[r2] == 0) {
5137 regs[rd] = 0;
5138 *flags |= CPU_DTRACE_DIVZERO;
5139 } else {
5140 regs[rd] = regs[r1] % regs[r2];
5141 }
5142 break;
5143
5144 case DIF_OP_NOT:
5145 regs[rd] = ~regs[r1];
5146 break;
5147 case DIF_OP_MOV:
5148 regs[rd] = regs[r1];
5149 break;
5150 case DIF_OP_CMP:
5151 cc_r = regs[r1] - regs[r2];
5152 cc_n = cc_r < 0;
5153 cc_z = cc_r == 0;
5154 cc_v = 0;
5155 cc_c = regs[r1] < regs[r2];
5156 break;
5157 case DIF_OP_TST:
5158 cc_n = cc_v = cc_c = 0;
5159 cc_z = regs[r1] == 0;
5160 break;
5161 case DIF_OP_BA:
5162 pc = DIF_INSTR_LABEL(instr);
5163 break;
5164 case DIF_OP_BE:
5165 if (cc_z)
5166 pc = DIF_INSTR_LABEL(instr);
5167 break;
5168 case DIF_OP_BNE:
5169 if (cc_z == 0)
5170 pc = DIF_INSTR_LABEL(instr);
5171 break;
5172 case DIF_OP_BG:
5173 if ((cc_z | (cc_n ^ cc_v)) == 0)
5174 pc = DIF_INSTR_LABEL(instr);
5175 break;
5176 case DIF_OP_BGU:
5177 if ((cc_c | cc_z) == 0)
5178 pc = DIF_INSTR_LABEL(instr);
5179 break;
5180 case DIF_OP_BGE:
5181 if ((cc_n ^ cc_v) == 0)
5182 pc = DIF_INSTR_LABEL(instr);
5183 break;
5184 case DIF_OP_BGEU:
5185 if (cc_c == 0)
5186 pc = DIF_INSTR_LABEL(instr);
5187 break;
5188 case DIF_OP_BL:
5189 if (cc_n ^ cc_v)
5190 pc = DIF_INSTR_LABEL(instr);
5191 break;
5192 case DIF_OP_BLU:
5193 if (cc_c)
5194 pc = DIF_INSTR_LABEL(instr);
5195 break;
5196 case DIF_OP_BLE:
5197 if (cc_z | (cc_n ^ cc_v))
5198 pc = DIF_INSTR_LABEL(instr);
5199 break;
5200 case DIF_OP_BLEU:
5201 if (cc_c | cc_z)
5202 pc = DIF_INSTR_LABEL(instr);
5203 break;
5204 case DIF_OP_RLDSB:
5205 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5206 *flags |= CPU_DTRACE_KPRIV;
5207 *illval = regs[r1];
5208 break;
5209 }
5210 /*FALLTHROUGH*/
5211 case DIF_OP_LDSB:
5212 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5213 break;
5214 case DIF_OP_RLDSH:
5215 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5216 *flags |= CPU_DTRACE_KPRIV;
5217 *illval = regs[r1];
5218 break;
5219 }
5220 /*FALLTHROUGH*/
5221 case DIF_OP_LDSH:
5222 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5223 break;
5224 case DIF_OP_RLDSW:
5225 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5226 *flags |= CPU_DTRACE_KPRIV;
5227 *illval = regs[r1];
5228 break;
5229 }
5230 /*FALLTHROUGH*/
5231 case DIF_OP_LDSW:
5232 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5233 break;
5234 case DIF_OP_RLDUB:
5235 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5236 *flags |= CPU_DTRACE_KPRIV;
5237 *illval = regs[r1];
5238 break;
5239 }
5240 /*FALLTHROUGH*/
5241 case DIF_OP_LDUB:
5242 regs[rd] = dtrace_load8(regs[r1]);
5243 break;
5244 case DIF_OP_RLDUH:
5245 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5246 *flags |= CPU_DTRACE_KPRIV;
5247 *illval = regs[r1];
5248 break;
5249 }
5250 /*FALLTHROUGH*/
5251 case DIF_OP_LDUH:
5252 regs[rd] = dtrace_load16(regs[r1]);
5253 break;
5254 case DIF_OP_RLDUW:
5255 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5256 *flags |= CPU_DTRACE_KPRIV;
5257 *illval = regs[r1];
5258 break;
5259 }
5260 /*FALLTHROUGH*/
5261 case DIF_OP_LDUW:
5262 regs[rd] = dtrace_load32(regs[r1]);
5263 break;
5264 case DIF_OP_RLDX:
5265 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5266 *flags |= CPU_DTRACE_KPRIV;
5267 *illval = regs[r1];
5268 break;
5269 }
5270 /*FALLTHROUGH*/
5271 case DIF_OP_LDX:
5272 regs[rd] = dtrace_load64(regs[r1]);
5273 break;
fe8ab488
A
5274/*
5275 * Darwin 32-bit kernel may fetch from 64-bit user.
5276 * Do not cast regs to uintptr_t
5277 * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
5278 * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
5279 */
2d21ac55
A
5280 case DIF_OP_ULDSB:
5281 regs[rd] = (int8_t)
5282 dtrace_fuword8(regs[r1]);
5283 break;
5284 case DIF_OP_ULDSH:
5285 regs[rd] = (int16_t)
5286 dtrace_fuword16(regs[r1]);
5287 break;
5288 case DIF_OP_ULDSW:
5289 regs[rd] = (int32_t)
5290 dtrace_fuword32(regs[r1]);
5291 break;
5292 case DIF_OP_ULDUB:
5293 regs[rd] =
5294 dtrace_fuword8(regs[r1]);
5295 break;
5296 case DIF_OP_ULDUH:
5297 regs[rd] =
5298 dtrace_fuword16(regs[r1]);
5299 break;
5300 case DIF_OP_ULDUW:
5301 regs[rd] =
5302 dtrace_fuword32(regs[r1]);
5303 break;
5304 case DIF_OP_ULDX:
5305 regs[rd] =
5306 dtrace_fuword64(regs[r1]);
5307 break;
5308 case DIF_OP_RET:
5309 rval = regs[rd];
b0d623f7 5310 pc = textlen;
2d21ac55
A
5311 break;
5312 case DIF_OP_NOP:
5313 break;
5314 case DIF_OP_SETX:
5315 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5316 break;
5317 case DIF_OP_SETS:
5318 regs[rd] = (uint64_t)(uintptr_t)
5319 (strtab + DIF_INSTR_STRING(instr));
5320 break;
b0d623f7
A
5321 case DIF_OP_SCMP: {
5322 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5323 uintptr_t s1 = regs[r1];
5324 uintptr_t s2 = regs[r2];
39037602 5325 size_t lim1 = sz, lim2 = sz;
b0d623f7 5326
fe8ab488 5327 if (s1 != 0 &&
39037602 5328 !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
b0d623f7 5329 break;
fe8ab488 5330 if (s2 != 0 &&
39037602 5331 !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
b0d623f7
A
5332 break;
5333
39037602
A
5334 cc_r = dtrace_strncmp((char *)s1, (char *)s2,
5335 MIN(lim1, lim2));
2d21ac55
A
5336
5337 cc_n = cc_r < 0;
5338 cc_z = cc_r == 0;
5339 cc_v = cc_c = 0;
5340 break;
b0d623f7 5341 }
2d21ac55
A
5342 case DIF_OP_LDGA:
5343 regs[rd] = dtrace_dif_variable(mstate, state,
5344 r1, regs[r2]);
5345 break;
5346 case DIF_OP_LDGS:
5347 id = DIF_INSTR_VAR(instr);
5348
5349 if (id >= DIF_VAR_OTHER_UBASE) {
5350 uintptr_t a;
5351
5352 id -= DIF_VAR_OTHER_UBASE;
5353 svar = vstate->dtvs_globals[id];
5354 ASSERT(svar != NULL);
5355 v = &svar->dtsv_var;
5356
5357 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5358 regs[rd] = svar->dtsv_data;
5359 break;
5360 }
5361
5362 a = (uintptr_t)svar->dtsv_data;
5363
5364 if (*(uint8_t *)a == UINT8_MAX) {
5365 /*
5366 * If the 0th byte is set to UINT8_MAX
5367 * then this is to be treated as a
5368 * reference to a NULL variable.
5369 */
fe8ab488 5370 regs[rd] = 0;
2d21ac55
A
5371 } else {
5372 regs[rd] = a + sizeof (uint64_t);
5373 }
5374
5375 break;
5376 }
5377
5378 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5379 break;
5380
5381 case DIF_OP_STGS:
5382 id = DIF_INSTR_VAR(instr);
5383
5384 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5385 id -= DIF_VAR_OTHER_UBASE;
5386
39037602 5387 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
2d21ac55
A
5388 svar = vstate->dtvs_globals[id];
5389 ASSERT(svar != NULL);
5390 v = &svar->dtsv_var;
5391
5392 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5393 uintptr_t a = (uintptr_t)svar->dtsv_data;
39037602 5394 size_t lim;
2d21ac55 5395
fe8ab488 5396 ASSERT(a != 0);
2d21ac55
A
5397 ASSERT(svar->dtsv_size != 0);
5398
fe8ab488 5399 if (regs[rd] == 0) {
2d21ac55
A
5400 *(uint8_t *)a = UINT8_MAX;
5401 break;
5402 } else {
5403 *(uint8_t *)a = 0;
5404 a += sizeof (uint64_t);
5405 }
b0d623f7
A
5406 if (!dtrace_vcanload(
5407 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
39037602 5408 &lim, mstate, vstate))
b0d623f7 5409 break;
2d21ac55
A
5410
5411 dtrace_vcopy((void *)(uintptr_t)regs[rd],
39037602 5412 (void *)a, &v->dtdv_type, lim);
2d21ac55
A
5413 break;
5414 }
5415
5416 svar->dtsv_data = regs[rd];
5417 break;
5418
5419 case DIF_OP_LDTA:
5420 /*
5421 * There are no DTrace built-in thread-local arrays at
5422 * present. This opcode is saved for future work.
5423 */
5424 *flags |= CPU_DTRACE_ILLOP;
5425 regs[rd] = 0;
5426 break;
5427
5428 case DIF_OP_LDLS:
5429 id = DIF_INSTR_VAR(instr);
5430
5431 if (id < DIF_VAR_OTHER_UBASE) {
5432 /*
5433 * For now, this has no meaning.
5434 */
5435 regs[rd] = 0;
5436 break;
5437 }
5438
5439 id -= DIF_VAR_OTHER_UBASE;
5440
b0d623f7 5441 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
2d21ac55 5442 ASSERT(vstate->dtvs_locals != NULL);
2d21ac55
A
5443 svar = vstate->dtvs_locals[id];
5444 ASSERT(svar != NULL);
5445 v = &svar->dtsv_var;
5446
5447 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5448 uintptr_t a = (uintptr_t)svar->dtsv_data;
5449 size_t sz = v->dtdv_type.dtdt_size;
5450
5451 sz += sizeof (uint64_t);
c910b4d9 5452 ASSERT(svar->dtsv_size == (int)NCPU * sz);
2d21ac55
A
5453 a += CPU->cpu_id * sz;
5454
5455 if (*(uint8_t *)a == UINT8_MAX) {
5456 /*
5457 * If the 0th byte is set to UINT8_MAX
5458 * then this is to be treated as a
5459 * reference to a NULL variable.
5460 */
fe8ab488 5461 regs[rd] = 0;
2d21ac55
A
5462 } else {
5463 regs[rd] = a + sizeof (uint64_t);
5464 }
5465
5466 break;
5467 }
5468
c910b4d9 5469 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
2d21ac55
A
5470 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5471 regs[rd] = tmp[CPU->cpu_id];
5472 break;
5473
5474 case DIF_OP_STLS:
5475 id = DIF_INSTR_VAR(instr);
5476
5477 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5478 id -= DIF_VAR_OTHER_UBASE;
39037602 5479 VERIFY(id < (uint_t)vstate->dtvs_nlocals);
2d21ac55
A
5480 ASSERT(vstate->dtvs_locals != NULL);
5481 svar = vstate->dtvs_locals[id];
5482 ASSERT(svar != NULL);
5483 v = &svar->dtsv_var;
5484
5485 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5486 uintptr_t a = (uintptr_t)svar->dtsv_data;
5487 size_t sz = v->dtdv_type.dtdt_size;
39037602 5488 size_t lim;
2d21ac55
A
5489
5490 sz += sizeof (uint64_t);
c910b4d9 5491 ASSERT(svar->dtsv_size == (int)NCPU * sz);
2d21ac55
A
5492 a += CPU->cpu_id * sz;
5493
fe8ab488 5494 if (regs[rd] == 0) {
2d21ac55
A
5495 *(uint8_t *)a = UINT8_MAX;
5496 break;
5497 } else {
5498 *(uint8_t *)a = 0;
5499 a += sizeof (uint64_t);
5500 }
5501
b0d623f7
A
5502 if (!dtrace_vcanload(
5503 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
39037602 5504 &lim, mstate, vstate))
b0d623f7
A
5505 break;
5506
2d21ac55 5507 dtrace_vcopy((void *)(uintptr_t)regs[rd],
39037602 5508 (void *)a, &v->dtdv_type, lim);
2d21ac55
A
5509 break;
5510 }
5511
c910b4d9 5512 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
2d21ac55
A
5513 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5514 tmp[CPU->cpu_id] = regs[rd];
5515 break;
5516
5517 case DIF_OP_LDTS: {
5518 dtrace_dynvar_t *dvar;
5519 dtrace_key_t *key;
5520
5521 id = DIF_INSTR_VAR(instr);
5522 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5523 id -= DIF_VAR_OTHER_UBASE;
5524 v = &vstate->dtvs_tlocals[id];
5525
5526 key = &tupregs[DIF_DTR_NREGS];
5527 key[0].dttk_value = (uint64_t)id;
5528 key[0].dttk_size = 0;
5529 DTRACE_TLS_THRKEY(key[1].dttk_value);
5530 key[1].dttk_size = 0;
5531
5532 dvar = dtrace_dynvar(dstate, 2, key,
b0d623f7
A
5533 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5534 mstate, vstate);
2d21ac55
A
5535
5536 if (dvar == NULL) {
5537 regs[rd] = 0;
5538 break;
5539 }
5540
5541 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5542 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5543 } else {
5544 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5545 }
5546
5547 break;
5548 }
5549
5550 case DIF_OP_STTS: {
5551 dtrace_dynvar_t *dvar;
5552 dtrace_key_t *key;
5553
5554 id = DIF_INSTR_VAR(instr);
5555 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5556 id -= DIF_VAR_OTHER_UBASE;
39037602 5557 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
2d21ac55
A
5558
5559 key = &tupregs[DIF_DTR_NREGS];
5560 key[0].dttk_value = (uint64_t)id;
5561 key[0].dttk_size = 0;
5562 DTRACE_TLS_THRKEY(key[1].dttk_value);
5563 key[1].dttk_size = 0;
5564 v = &vstate->dtvs_tlocals[id];
5565
5566 dvar = dtrace_dynvar(dstate, 2, key,
5567 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5568 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5569 regs[rd] ? DTRACE_DYNVAR_ALLOC :
b0d623f7 5570 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
2d21ac55
A
5571
5572 /*
5573 * Given that we're storing to thread-local data,
5574 * we need to flush our predicate cache.
5575 */
2d21ac55 5576 dtrace_set_thread_predcache(current_thread(), 0);
2d21ac55 5577
2d21ac55
A
5578 if (dvar == NULL)
5579 break;
5580
5581 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
39037602
A
5582 size_t lim;
5583
b0d623f7
A
5584 if (!dtrace_vcanload(
5585 (void *)(uintptr_t)regs[rd],
39037602 5586 &v->dtdv_type, &lim, mstate, vstate))
b0d623f7
A
5587 break;
5588
2d21ac55 5589 dtrace_vcopy((void *)(uintptr_t)regs[rd],
39037602 5590 dvar->dtdv_data, &v->dtdv_type, lim);
2d21ac55
A
5591 } else {
5592 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5593 }
5594
5595 break;
5596 }
5597
5598 case DIF_OP_SRA:
5599 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5600 break;
5601
5602 case DIF_OP_CALL:
5603 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5604 regs, tupregs, ttop, mstate, state);
5605 break;
5606
5607 case DIF_OP_PUSHTR:
5608 if (ttop == DIF_DTR_NREGS) {
5609 *flags |= CPU_DTRACE_TUPOFLOW;
5610 break;
5611 }
5612
5613 if (r1 == DIF_TYPE_STRING) {
5614 /*
5615 * If this is a string type and the size is 0,
5616 * we'll use the system-wide default string
5617 * size. Note that we are _not_ looking at
5618 * the value of the DTRACEOPT_STRSIZE option;
5619 * had this been set, we would expect to have
5620 * a non-zero size value in the "pushtr".
5621 */
5622 tupregs[ttop].dttk_size =
5623 dtrace_strlen((char *)(uintptr_t)regs[rd],
5624 regs[r2] ? regs[r2] :
5625 dtrace_strsize_default) + 1;
5626 } else {
ecc0ceb4
A
5627 if (regs[r2] > LONG_MAX) {
5628 *flags |= CPU_DTRACE_ILLOP;
5629 break;
5630 }
2d21ac55
A
5631 tupregs[ttop].dttk_size = regs[r2];
5632 }
5633
5634 tupregs[ttop++].dttk_value = regs[rd];
5635 break;
5636
5637 case DIF_OP_PUSHTV:
5638 if (ttop == DIF_DTR_NREGS) {
5639 *flags |= CPU_DTRACE_TUPOFLOW;
5640 break;
5641 }
5642
5643 tupregs[ttop].dttk_value = regs[rd];
5644 tupregs[ttop++].dttk_size = 0;
5645 break;
5646
5647 case DIF_OP_POPTS:
5648 if (ttop != 0)
5649 ttop--;
5650 break;
5651
5652 case DIF_OP_FLUSHTS:
5653 ttop = 0;
5654 break;
5655
5656 case DIF_OP_LDGAA:
5657 case DIF_OP_LDTAA: {
5658 dtrace_dynvar_t *dvar;
5659 dtrace_key_t *key = tupregs;
5660 uint_t nkeys = ttop;
5661
5662 id = DIF_INSTR_VAR(instr);
5663 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5664 id -= DIF_VAR_OTHER_UBASE;
5665
5666 key[nkeys].dttk_value = (uint64_t)id;
5667 key[nkeys++].dttk_size = 0;
5668
5669 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5670 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5671 key[nkeys++].dttk_size = 0;
39037602 5672 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
2d21ac55
A
5673 v = &vstate->dtvs_tlocals[id];
5674 } else {
39037602 5675 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
2d21ac55
A
5676 v = &vstate->dtvs_globals[id]->dtsv_var;
5677 }
5678
5679 dvar = dtrace_dynvar(dstate, nkeys, key,
5680 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5681 v->dtdv_type.dtdt_size : sizeof (uint64_t),
b0d623f7 5682 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
2d21ac55
A
5683
5684 if (dvar == NULL) {
5685 regs[rd] = 0;
5686 break;
5687 }
5688
5689 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5690 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5691 } else {
5692 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5693 }
5694
5695 break;
5696 }
5697
5698 case DIF_OP_STGAA:
5699 case DIF_OP_STTAA: {
5700 dtrace_dynvar_t *dvar;
5701 dtrace_key_t *key = tupregs;
5702 uint_t nkeys = ttop;
5703
5704 id = DIF_INSTR_VAR(instr);
5705 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5706 id -= DIF_VAR_OTHER_UBASE;
5707
5708 key[nkeys].dttk_value = (uint64_t)id;
5709 key[nkeys++].dttk_size = 0;
5710
5711 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5712 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5713 key[nkeys++].dttk_size = 0;
39037602 5714 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
2d21ac55
A
5715 v = &vstate->dtvs_tlocals[id];
5716 } else {
39037602 5717 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
2d21ac55
A
5718 v = &vstate->dtvs_globals[id]->dtsv_var;
5719 }
5720
5721 dvar = dtrace_dynvar(dstate, nkeys, key,
5722 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5723 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5724 regs[rd] ? DTRACE_DYNVAR_ALLOC :
b0d623f7 5725 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
2d21ac55
A
5726
5727 if (dvar == NULL)
5728 break;
5729
5730 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
39037602
A
5731 size_t lim;
5732
b0d623f7
A
5733 if (!dtrace_vcanload(
5734 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
39037602 5735 &lim, mstate, vstate))
b0d623f7
A
5736 break;
5737
2d21ac55 5738 dtrace_vcopy((void *)(uintptr_t)regs[rd],
39037602 5739 dvar->dtdv_data, &v->dtdv_type, lim);
2d21ac55
A
5740 } else {
5741 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5742 }
5743
5744 break;
5745 }
5746
5747 case DIF_OP_ALLOCS: {
5748 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5749 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5750
b0d623f7
A
5751 /*
5752 * Rounding up the user allocation size could have
5753 * overflowed large, bogus allocations (like -1ULL) to
5754 * 0.
5755 */
5756 if (size < regs[r1] ||
5757 !DTRACE_INSCRATCH(mstate, size)) {
2d21ac55 5758 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
fe8ab488 5759 regs[rd] = 0;
b0d623f7
A
5760 break;
5761 }
5762
5763 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
2d21ac55
A
5764 mstate->dtms_scratch_ptr += size;
5765 regs[rd] = ptr;
2d21ac55
A
5766 break;
5767 }
5768
5769 case DIF_OP_COPYS:
5770 if (!dtrace_canstore(regs[rd], regs[r2],
5771 mstate, vstate)) {
5772 *flags |= CPU_DTRACE_BADADDR;
5773 *illval = regs[rd];
5774 break;
5775 }
5776
b0d623f7
A
5777 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5778 break;
5779
2d21ac55
A
5780 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5781 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5782 break;
5783
5784 case DIF_OP_STB:
5785 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5786 *flags |= CPU_DTRACE_BADADDR;
5787 *illval = regs[rd];
5788 break;
5789 }
5790 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5791 break;
5792
5793 case DIF_OP_STH:
5794 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5795 *flags |= CPU_DTRACE_BADADDR;
5796 *illval = regs[rd];
5797 break;
5798 }
5799 if (regs[rd] & 1) {
5800 *flags |= CPU_DTRACE_BADALIGN;
5801 *illval = regs[rd];
5802 break;
5803 }
5804 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5805 break;
5806
5807 case DIF_OP_STW:
5808 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5809 *flags |= CPU_DTRACE_BADADDR;
5810 *illval = regs[rd];
5811 break;
5812 }
5813 if (regs[rd] & 3) {
5814 *flags |= CPU_DTRACE_BADALIGN;
5815 *illval = regs[rd];
5816 break;
5817 }
5818 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5819 break;
5820
5821 case DIF_OP_STX:
5822 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5823 *flags |= CPU_DTRACE_BADADDR;
5824 *illval = regs[rd];
5825 break;
5826 }
fe8ab488
A
5827
5828 /*
5829 * Darwin kmem_zalloc() called from
5830 * dtrace_difo_init() is 4-byte aligned.
5831 */
5832 if (regs[rd] & 3) {
2d21ac55
A
5833 *flags |= CPU_DTRACE_BADALIGN;
5834 *illval = regs[rd];
5835 break;
5836 }
5837 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5838 break;
5839 }
5840 }
5841
5842 if (!(*flags & CPU_DTRACE_FAULT))
5843 return (rval);
5844
5845 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5846 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5847
5848 return (0);
5849}
5850
5851static void
5852dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5853{
5854 dtrace_probe_t *probe = ecb->dte_probe;
5855 dtrace_provider_t *prov = probe->dtpr_provider;
5856 char c[DTRACE_FULLNAMELEN + 80], *str;
b0d623f7
A
5857 const char *msg = "dtrace: breakpoint action at probe ";
5858 const char *ecbmsg = " (ecb ";
2d21ac55
A
5859 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5860 uintptr_t val = (uintptr_t)ecb;
5861 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5862
5863 if (dtrace_destructive_disallow)
5864 return;
5865
5866 /*
5867 * It's impossible to be taking action on the NULL probe.
5868 */
5869 ASSERT(probe != NULL);
5870
5871 /*
5872 * This is a poor man's (destitute man's?) sprintf(): we want to
5873 * print the provider name, module name, function name and name of
5874 * the probe, along with the hex address of the ECB with the breakpoint
5875 * action -- all of which we must place in the character buffer by
5876 * hand.
5877 */
5878 while (*msg != '\0')
5879 c[i++] = *msg++;
5880
5881 for (str = prov->dtpv_name; *str != '\0'; str++)
5882 c[i++] = *str;
5883 c[i++] = ':';
5884
5885 for (str = probe->dtpr_mod; *str != '\0'; str++)
5886 c[i++] = *str;
5887 c[i++] = ':';
5888
5889 for (str = probe->dtpr_func; *str != '\0'; str++)
5890 c[i++] = *str;
5891 c[i++] = ':';
5892
5893 for (str = probe->dtpr_name; *str != '\0'; str++)
5894 c[i++] = *str;
5895
5896 while (*ecbmsg != '\0')
5897 c[i++] = *ecbmsg++;
5898
5899 while (shift >= 0) {
5900 mask = (uintptr_t)0xf << shift;
5901
5902 if (val >= ((uintptr_t)1 << shift))
5903 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5904 shift -= 4;
5905 }
5906
5907 c[i++] = ')';
5908 c[i] = '\0';
5909
5910 debug_enter(c);
5911}
5912
5913static void
5914dtrace_action_panic(dtrace_ecb_t *ecb)
5915{
5916 dtrace_probe_t *probe = ecb->dte_probe;
5917
5918 /*
5919 * It's impossible to be taking action on the NULL probe.
5920 */
5921 ASSERT(probe != NULL);
5922
5923 if (dtrace_destructive_disallow)
5924 return;
5925
5926 if (dtrace_panicked != NULL)
5927 return;
5928
2d21ac55
A
5929 if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
5930 return;
2d21ac55
A
5931
5932 /*
5933 * We won the right to panic. (We want to be sure that only one
5934 * thread calls panic() from dtrace_probe(), and that panic() is
5935 * called exactly once.)
5936 */
316670eb 5937 panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
2d21ac55
A
5938 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5939 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5940
fe8ab488
A
5941 /*
5942 * APPLE NOTE: this was for an old Mac OS X debug feature
5943 * allowing a return from panic(). Revisit someday.
5944 */
2d21ac55 5945 dtrace_panicked = NULL;
2d21ac55
A
5946}
5947
5948static void
5949dtrace_action_raise(uint64_t sig)
5950{
5951 if (dtrace_destructive_disallow)
5952 return;
5953
5954 if (sig >= NSIG) {
5955 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5956 return;
5957 }
5958
2d21ac55
A
5959 /*
5960 * raise() has a queue depth of 1 -- we ignore all subsequent
5961 * invocations of the raise() action.
5962 */
2d21ac55 5963
2d21ac55
A
5964 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5965
5966 if (uthread && uthread->t_dtrace_sig == 0) {
5967 uthread->t_dtrace_sig = sig;
6d2010ae 5968 act_set_astbsd(current_thread());
2d21ac55 5969 }
2d21ac55
A
5970}
5971
5972static void
5973dtrace_action_stop(void)
5974{
5975 if (dtrace_destructive_disallow)
5976 return;
5977
6d2010ae
A
5978 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5979 if (uthread) {
5980 /*
5981 * The currently running process will be set to task_suspend
5982 * when it next leaves the kernel.
5983 */
b0d623f7 5984 uthread->t_dtrace_stop = 1;
6d2010ae 5985 act_set_astbsd(current_thread());
b0d623f7 5986 }
2d21ac55
A
5987}
5988
fe8ab488
A
5989
5990/*
5991 * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
5992 * Both activate only when the currently running process next leaves the
5993 * kernel.
5994 */
6d2010ae
A
5995static void
5996dtrace_action_pidresume(uint64_t pid)
5997{
5998 if (dtrace_destructive_disallow)
5999 return;
6000
6001 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
6002 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6003 return;
6004 }
6d2010ae
A
6005 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
6006
6007 /*
6008 * When the currently running process leaves the kernel, it attempts to
6009 * task_resume the process (denoted by pid), if that pid appears to have
6010 * been stopped by dtrace_action_stop().
6011 * The currently running process has a pidresume() queue depth of 1 --
6012 * subsequent invocations of the pidresume() action are ignored.
6013 */
6014
6015 if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
6016 uthread->t_dtrace_resumepid = pid;
6017 act_set_astbsd(current_thread());
6018 }
6019}
6d2010ae 6020
2d21ac55
A
6021static void
6022dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6023{
6024 hrtime_t now;
6025 volatile uint16_t *flags;
6d2010ae 6026 dtrace_cpu_t *cpu = CPU;
2d21ac55
A
6027
6028 if (dtrace_destructive_disallow)
6029 return;
6030
6031 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6032
6033 now = dtrace_gethrtime();
6034
6035 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6036 /*
6037 * We need to advance the mark to the current time.
6038 */
6039 cpu->cpu_dtrace_chillmark = now;
6040 cpu->cpu_dtrace_chilled = 0;
6041 }
6042
6043 /*
6044 * Now check to see if the requested chill time would take us over
6045 * the maximum amount of time allowed in the chill interval. (Or
6046 * worse, if the calculation itself induces overflow.)
6047 */
6048 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6049 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6050 *flags |= CPU_DTRACE_ILLOP;
6051 return;
6052 }
6053
6054 while (dtrace_gethrtime() - now < val)
6055 continue;
6056
6057 /*
6058 * Normally, we assure that the value of the variable "timestamp" does
6059 * not change within an ECB. The presence of chill() represents an
6060 * exception to this rule, however.
6061 */
6062 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6063 cpu->cpu_dtrace_chilled += val;
6064}
6065
6066static void
6067dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6068 uint64_t *buf, uint64_t arg)
6069{
6070 int nframes = DTRACE_USTACK_NFRAMES(arg);
6071 int strsize = DTRACE_USTACK_STRSIZE(arg);
6072 uint64_t *pcs = &buf[1], *fps;
6073 char *str = (char *)&pcs[nframes];
6074 int size, offs = 0, i, j;
6075 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6076 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6077 char *sym;
6078
6079 /*
6080 * Should be taking a faster path if string space has not been
6081 * allocated.
6082 */
6083 ASSERT(strsize != 0);
6084
6085 /*
6086 * We will first allocate some temporary space for the frame pointers.
6087 */
6088 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6089 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6090 (nframes * sizeof (uint64_t));
6091
b0d623f7 6092 if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
2d21ac55
A
6093 /*
6094 * Not enough room for our frame pointers -- need to indicate
6095 * that we ran out of scratch space.
6096 */
6097 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6098 return;
6099 }
6100
6101 mstate->dtms_scratch_ptr += size;
6102 saved = mstate->dtms_scratch_ptr;
6103
6104 /*
6105 * Now get a stack with both program counters and frame pointers.
6106 */
6107 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6108 dtrace_getufpstack(buf, fps, nframes + 1);
6109 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6110
6111 /*
6112 * If that faulted, we're cooked.
6113 */
6114 if (*flags & CPU_DTRACE_FAULT)
6115 goto out;
6116
6117 /*
6118 * Now we want to walk up the stack, calling the USTACK helper. For
6119 * each iteration, we restore the scratch pointer.
6120 */
6121 for (i = 0; i < nframes; i++) {
6122 mstate->dtms_scratch_ptr = saved;
6123
6124 if (offs >= strsize)
6125 break;
6126
6127 sym = (char *)(uintptr_t)dtrace_helper(
6128 DTRACE_HELPER_ACTION_USTACK,
6129 mstate, state, pcs[i], fps[i]);
6130
6131 /*
6132 * If we faulted while running the helper, we're going to
6133 * clear the fault and null out the corresponding string.
6134 */
6135 if (*flags & CPU_DTRACE_FAULT) {
6136 *flags &= ~CPU_DTRACE_FAULT;
6137 str[offs++] = '\0';
6138 continue;
6139 }
6140
6141 if (sym == NULL) {
6142 str[offs++] = '\0';
6143 continue;
6144 }
6145
6146 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6147
6148 /*
6149 * Now copy in the string that the helper returned to us.
6150 */
6151 for (j = 0; offs + j < strsize; j++) {
6152 if ((str[offs + j] = sym[j]) == '\0')
6153 break;
6154 }
6155
6156 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6157
6158 offs += j + 1;
6159 }
6160
6161 if (offs >= strsize) {
6162 /*
6163 * If we didn't have room for all of the strings, we don't
6164 * abort processing -- this needn't be a fatal error -- but we
6165 * still want to increment a counter (dts_stkstroverflows) to
6166 * allow this condition to be warned about. (If this is from
6167 * a jstack() action, it is easily tuned via jstackstrsize.)
6168 */
6169 dtrace_error(&state->dts_stkstroverflows);
6170 }
6171
6172 while (offs < strsize)
6173 str[offs++] = '\0';
6174
6175out:
6176 mstate->dtms_scratch_ptr = old;
6177}
6178
3e170ce0
A
6179static void
6180dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6181 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6182{
6183 volatile uint16_t *flags;
6184 uint64_t val = *valp;
6185 size_t valoffs = *valoffsp;
6186
6187 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6188 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6189
6190 /*
6191 * If this is a string, we're going to only load until we find the zero
6192 * byte -- after which we'll store zero bytes.
6193 */
6194 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6195 char c = '\0' + 1;
6196 size_t s;
6197
6198 for (s = 0; s < size; s++) {
6199 if (c != '\0' && dtkind == DIF_TF_BYREF) {
6200 c = dtrace_load8(val++);
6201 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6202 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6203 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6204 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6205 if (*flags & CPU_DTRACE_FAULT)
6206 break;
6207 }
6208
6209 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6210
6211 if (c == '\0' && intuple)
6212 break;
6213 }
6214 } else {
6215 uint8_t c;
6216 while (valoffs < end) {
6217 if (dtkind == DIF_TF_BYREF) {
6218 c = dtrace_load8(val++);
6219 } else if (dtkind == DIF_TF_BYUREF) {
6220 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6221 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6222 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6223 if (*flags & CPU_DTRACE_FAULT)
6224 break;
6225 }
6226
6227 DTRACE_STORE(uint8_t, tomax,
6228 valoffs++, c);
6229 }
6230 }
6231
6232 *valp = val;
6233 *valoffsp = valoffs;
6234}
6235
2d21ac55
A
6236/*
6237 * If you're looking for the epicenter of DTrace, you just found it. This
6238 * is the function called by the provider to fire a probe -- from which all
6239 * subsequent probe-context DTrace activity emanates.
6240 */
2d21ac55
A
6241static void
6242__dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6243 uint64_t arg2, uint64_t arg3, uint64_t arg4)
2d21ac55
A
6244{
6245 processorid_t cpuid;
6246 dtrace_icookie_t cookie;
6247 dtrace_probe_t *probe;
6248 dtrace_mstate_t mstate;
6249 dtrace_ecb_t *ecb;
6250 dtrace_action_t *act;
6251 intptr_t offs;
6252 size_t size;
6253 int vtime, onintr;
6254 volatile uint16_t *flags;
6255 hrtime_t now;
6256
2d21ac55
A
6257 cookie = dtrace_interrupt_disable();
6258 probe = dtrace_probes[id - 1];
6259 cpuid = CPU->cpu_id;
6260 onintr = CPU_ON_INTR(CPU);
6261
2d21ac55
A
6262 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6263 probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
2d21ac55
A
6264 /*
6265 * We have hit in the predicate cache; we know that
6266 * this predicate would evaluate to be false.
6267 */
6268 dtrace_interrupt_enable(cookie);
6269 return;
6270 }
6271
6272 if (panic_quiesce) {
6273 /*
6274 * We don't trace anything if we're panicking.
6275 */
6276 dtrace_interrupt_enable(cookie);
6277 return;
6278 }
6279
6280#if !defined(__APPLE__)
6281 now = dtrace_gethrtime();
6282 vtime = dtrace_vtime_references != 0;
6283
6284 if (vtime && curthread->t_dtrace_start)
6285 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6286#else
fe8ab488
A
6287 /*
6288 * APPLE NOTE: The time spent entering DTrace and arriving
6289 * to this point, is attributed to the current thread.
6290 * Instead it should accrue to DTrace. FIXME
6291 */
2d21ac55
A
6292 vtime = dtrace_vtime_references != 0;
6293
6294 if (vtime)
6295 {
6296 int64_t dtrace_accum_time, recent_vtime;
6297 thread_t thread = current_thread();
6298
6299 dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
6300
6301 if (dtrace_accum_time >= 0) {
6302 recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
6303
6304 recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
6305
6306 dtrace_set_thread_vtime(thread, recent_vtime);
6307 }
6308 }
6309
6310 now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
6311#endif /* __APPLE__ */
6312
cf7d32b8 6313 /*
fe8ab488
A
6314 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
6315 * dtrace_probe() in some circumstances. See, e.g. fasttrap_isa.c.
6316 * However the provider has no access to ECB context, so passes
6317 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
6318 * Detect that here and cons up a viable state (from the probe_id).
cf7d32b8 6319 */
b0d623f7 6320 if (dtrace_probeid_error == id && 0 == arg0) {
cf7d32b8
A
6321 dtrace_id_t ftp_id = (dtrace_id_t)arg1;
6322 dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
6323 dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
6324
6325 if (NULL != ftp_ecb) {
6326 dtrace_state_t *ftp_state = ftp_ecb->dte_state;
6327
6328 arg0 = (uint64_t)(uintptr_t)ftp_state;
6329 arg1 = ftp_ecb->dte_epid;
6330 /*
6331 * args[2-4] established by caller.
6332 */
6333 ftp_state->dts_arg_error_illval = -1; /* arg5 */
6334 }
6335 }
cf7d32b8 6336
b0d623f7 6337 mstate.dtms_difo = NULL;
2d21ac55 6338 mstate.dtms_probe = probe;
fe8ab488 6339 mstate.dtms_strtok = 0;
2d21ac55
A
6340 mstate.dtms_arg[0] = arg0;
6341 mstate.dtms_arg[1] = arg1;
6342 mstate.dtms_arg[2] = arg2;
6343 mstate.dtms_arg[3] = arg3;
6344 mstate.dtms_arg[4] = arg4;
6345
6346 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6347
6348 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6349 dtrace_predicate_t *pred = ecb->dte_predicate;
6350 dtrace_state_t *state = ecb->dte_state;
6351 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6352 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6353 dtrace_vstate_t *vstate = &state->dts_vstate;
6354 dtrace_provider_t *prov = probe->dtpr_provider;
fe8ab488 6355 uint64_t tracememsize = 0;
2d21ac55
A
6356 int committed = 0;
6357 caddr_t tomax;
6358
6359 /*
6360 * A little subtlety with the following (seemingly innocuous)
6361 * declaration of the automatic 'val': by looking at the
6362 * code, you might think that it could be declared in the
6363 * action processing loop, below. (That is, it's only used in
6364 * the action processing loop.) However, it must be declared
6365 * out of that scope because in the case of DIF expression
6366 * arguments to aggregating actions, one iteration of the
6367 * action loop will use the last iteration's value.
6368 */
6369#ifdef lint
6370 uint64_t val = 0;
6371#else
c910b4d9 6372 uint64_t val = 0;
2d21ac55
A
6373#endif
6374
6375 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6376 *flags &= ~CPU_DTRACE_ERROR;
6377
6378 if (prov == dtrace_provider) {
6379 /*
6380 * If dtrace itself is the provider of this probe,
6381 * we're only going to continue processing the ECB if
6382 * arg0 (the dtrace_state_t) is equal to the ECB's
6383 * creating state. (This prevents disjoint consumers
6384 * from seeing one another's metaprobes.)
6385 */
6386 if (arg0 != (uint64_t)(uintptr_t)state)
6387 continue;
6388 }
6389
6390 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6391 /*
6392 * We're not currently active. If our provider isn't
6393 * the dtrace pseudo provider, we're not interested.
6394 */
6395 if (prov != dtrace_provider)
6396 continue;
6397
6398 /*
6399 * Now we must further check if we are in the BEGIN
6400 * probe. If we are, we will only continue processing
6401 * if we're still in WARMUP -- if one BEGIN enabling
6402 * has invoked the exit() action, we don't want to
6403 * evaluate subsequent BEGIN enablings.
6404 */
6405 if (probe->dtpr_id == dtrace_probeid_begin &&
6406 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6407 ASSERT(state->dts_activity ==
6408 DTRACE_ACTIVITY_DRAINING);
6409 continue;
6410 }
6411 }
6412
2d21ac55
A
6413 if (ecb->dte_cond) {
6414 /*
6415 * If the dte_cond bits indicate that this
6416 * consumer is only allowed to see user-mode firings
6417 * of this probe, call the provider's dtps_usermode()
6418 * entry point to check that the probe was fired
6419 * while in a user context. Skip this ECB if that's
6420 * not the case.
6421 */
6422 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
39037602 6423 prov->dtpv_pops.dtps_usermode &&
2d21ac55
A
6424 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6425 probe->dtpr_id, probe->dtpr_arg) == 0)
6426 continue;
6427
6428 /*
6429 * This is more subtle than it looks. We have to be
6430 * absolutely certain that CRED() isn't going to
6431 * change out from under us so it's only legit to
6432 * examine that structure if we're in constrained
6433 * situations. Currently, the only times we'll this
6434 * check is if a non-super-user has enabled the
6435 * profile or syscall providers -- providers that
6436 * allow visibility of all processes. For the
6437 * profile case, the check above will ensure that
6438 * we're examining a user context.
6439 */
6440 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6441 cred_t *cr;
6442 cred_t *s_cr =
6443 ecb->dte_state->dts_cred.dcr_cred;
6444 proc_t *proc;
b0d623f7 6445#pragma unused(proc) /* __APPLE__ */
2d21ac55
A
6446
6447 ASSERT(s_cr != NULL);
6448
6d2010ae
A
6449 /*
6450 * XXX this is hackish, but so is setting a variable
6451 * XXX in a McCarthy OR...
6452 */
2d21ac55 6453 if ((cr = dtrace_CRED()) == NULL ||
6d2010ae
A
6454 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
6455 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
6456 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
6457 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
6458 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
6459 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
2d21ac55
A
6460#if !defined(__APPLE__)
6461 (proc = ttoproc(curthread)) == NULL ||
6462 (proc->p_flag & SNOCD))
6463#else
fe8ab488 6464 1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
2d21ac55
A
6465#endif /* __APPLE__ */
6466 continue;
6467 }
6468
6469 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6470 cred_t *cr;
6471 cred_t *s_cr =
6472 ecb->dte_state->dts_cred.dcr_cred;
b0d623f7 6473#pragma unused(cr, s_cr) /* __APPLE__ */
2d21ac55
A
6474
6475 ASSERT(s_cr != NULL);
6476
b0d623f7 6477#if !defined(__APPLE__)
2d21ac55
A
6478 if ((cr = CRED()) == NULL ||
6479 s_cr->cr_zone->zone_id !=
6480 cr->cr_zone->zone_id)
6481 continue;
b0d623f7 6482#else
fe8ab488 6483 /* APPLE NOTE: Darwin doesn't do zones. */
2d21ac55
A
6484#endif /* __APPLE__ */
6485 }
6486 }
6487
6488 if (now - state->dts_alive > dtrace_deadman_timeout) {
6489 /*
6490 * We seem to be dead. Unless we (a) have kernel
6491 * destructive permissions (b) have expicitly enabled
6492 * destructive actions and (c) destructive actions have
6493 * not been disabled, we're going to transition into
6494 * the KILLED state, from which no further processing
6495 * on this state will be performed.
6496 */
6497 if (!dtrace_priv_kernel_destructive(state) ||
6498 !state->dts_cred.dcr_destructive ||
6499 dtrace_destructive_disallow) {
6500 void *activity = &state->dts_activity;
6501 dtrace_activity_t current;
6502
6503 do {
6504 current = state->dts_activity;
6505 } while (dtrace_cas32(activity, current,
6506 DTRACE_ACTIVITY_KILLED) != current);
6507
6508 continue;
6509 }
6510 }
6511
6512 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6513 ecb->dte_alignment, state, &mstate)) < 0)
6514 continue;
6515
6516 tomax = buf->dtb_tomax;
6517 ASSERT(tomax != NULL);
6518
04b8595b
A
6519 /*
6520 * Build and store the record header corresponding to the ECB.
6521 */
6522 if (ecb->dte_size != 0) {
6523 dtrace_rechdr_t dtrh;
6524
6525 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6526 mstate.dtms_timestamp = dtrace_gethrtime();
6527 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6528 }
6529
6530 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6531
6532 dtrh.dtrh_epid = ecb->dte_epid;
6533 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
6534 DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
6535 }
2d21ac55
A
6536
6537 mstate.dtms_epid = ecb->dte_epid;
6538 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6539
b0d623f7
A
6540 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6541 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6542 else
6543 mstate.dtms_access = 0;
6544
2d21ac55
A
6545 if (pred != NULL) {
6546 dtrace_difo_t *dp = pred->dtp_difo;
5ba3f43e 6547 uint64_t rval;
2d21ac55
A
6548
6549 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6550
6551 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6552 dtrace_cacheid_t cid = probe->dtpr_predcache;
6553
6554 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6555 /*
6556 * Update the predicate cache...
6557 */
6558 ASSERT(cid == pred->dtp_cacheid);
fe8ab488 6559
2d21ac55 6560 dtrace_set_thread_predcache(current_thread(), cid);
2d21ac55
A
6561 }
6562
6563 continue;
6564 }
6565 }
6566
6567 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6568 act != NULL; act = act->dta_next) {
6569 size_t valoffs;
6570 dtrace_difo_t *dp;
6571 dtrace_recdesc_t *rec = &act->dta_rec;
6572
6573 size = rec->dtrd_size;
6574 valoffs = offs + rec->dtrd_offset;
6575
6576 if (DTRACEACT_ISAGG(act->dta_kind)) {
6577 uint64_t v = 0xbad;
6578 dtrace_aggregation_t *agg;
6579
6580 agg = (dtrace_aggregation_t *)act;
6581
6582 if ((dp = act->dta_difo) != NULL)
6583 v = dtrace_dif_emulate(dp,
6584 &mstate, vstate, state);
6585
6586 if (*flags & CPU_DTRACE_ERROR)
6587 continue;
6588
6589 /*
6590 * Note that we always pass the expression
6591 * value from the previous iteration of the
6592 * action loop. This value will only be used
6593 * if there is an expression argument to the
6594 * aggregating action, denoted by the
6595 * dtag_hasarg field.
6596 */
6597 dtrace_aggregate(agg, buf,
6598 offs, aggbuf, v, val);
6599 continue;
6600 }
6601
6602 switch (act->dta_kind) {
6603 case DTRACEACT_STOP:
6604 if (dtrace_priv_proc_destructive(state))
6605 dtrace_action_stop();
6606 continue;
6607
6608 case DTRACEACT_BREAKPOINT:
6609 if (dtrace_priv_kernel_destructive(state))
6610 dtrace_action_breakpoint(ecb);
6611 continue;
6612
6613 case DTRACEACT_PANIC:
6614 if (dtrace_priv_kernel_destructive(state))
6615 dtrace_action_panic(ecb);
6616 continue;
6617
6618 case DTRACEACT_STACK:
6619 if (!dtrace_priv_kernel(state))
6620 continue;
6621
b0d623f7
A
6622 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6623 size / sizeof (pc_t), probe->dtpr_aframes,
6624 DTRACE_ANCHORED(probe) ? NULL :
6625 (uint32_t *)(uintptr_t)arg0);
2d21ac55
A
6626 continue;
6627
6628 case DTRACEACT_JSTACK:
6629 case DTRACEACT_USTACK:
6630 if (!dtrace_priv_proc(state))
6631 continue;
6632
6633 /*
6634 * See comment in DIF_VAR_PID.
6635 */
6636 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6637 CPU_ON_INTR(CPU)) {
6638 int depth = DTRACE_USTACK_NFRAMES(
6639 rec->dtrd_arg) + 1;
6640
6641 dtrace_bzero((void *)(tomax + valoffs),
6642 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6643 + depth * sizeof (uint64_t));
6644
6645 continue;
6646 }
6647
6648 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6649 curproc->p_dtrace_helpers != NULL) {
6650 /*
6651 * This is the slow path -- we have
6652 * allocated string space, and we're
6653 * getting the stack of a process that
6654 * has helpers. Call into a separate
6655 * routine to perform this processing.
6656 */
6657 dtrace_action_ustack(&mstate, state,
6658 (uint64_t *)(tomax + valoffs),
6659 rec->dtrd_arg);
6660 continue;
6661 }
6662
6663 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6664 dtrace_getupcstack((uint64_t *)
6665 (tomax + valoffs),
6666 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6667 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6668 continue;
6669
6670 default:
6671 break;
6672 }
6673
6674 dp = act->dta_difo;
6675 ASSERT(dp != NULL);
6676
6677 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6678
6679 if (*flags & CPU_DTRACE_ERROR)
6680 continue;
6681
6682 switch (act->dta_kind) {
04b8595b
A
6683 case DTRACEACT_SPECULATE: {
6684 dtrace_rechdr_t *dtrh = NULL;
6685
2d21ac55
A
6686 ASSERT(buf == &state->dts_buffer[cpuid]);
6687 buf = dtrace_speculation_buffer(state,
6688 cpuid, val);
6689
6690 if (buf == NULL) {
6691 *flags |= CPU_DTRACE_DROP;
6692 continue;
6693 }
6694
6695 offs = dtrace_buffer_reserve(buf,
6696 ecb->dte_needed, ecb->dte_alignment,
6697 state, NULL);
6698
6699 if (offs < 0) {
6700 *flags |= CPU_DTRACE_DROP;
6701 continue;
6702 }
6703
6704 tomax = buf->dtb_tomax;
6705 ASSERT(tomax != NULL);
6706
39037602 6707 if (ecb->dte_size == 0)
04b8595b
A
6708 continue;
6709
6710 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6711 dtrh = ((void *)(tomax + offs));
6712 dtrh->dtrh_epid = ecb->dte_epid;
6713
6714 /*
6715 * When the speculation is committed, all of
6716 * the records in the speculative buffer will
6717 * have their timestamps set to the commit
6718 * time. Until then, it is set to a sentinel
6719 * value, for debugability.
6720 */
6721 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6722
6723 continue;
6724 }
2d21ac55
A
6725
6726 case DTRACEACT_CHILL:
6727 if (dtrace_priv_kernel_destructive(state))
6728 dtrace_action_chill(&mstate, val);
6729 continue;
6730
6731 case DTRACEACT_RAISE:
6732 if (dtrace_priv_proc_destructive(state))
6733 dtrace_action_raise(val);
6734 continue;
6735
fe8ab488 6736 case DTRACEACT_PIDRESUME: /* __APPLE__ */
6d2010ae
A
6737 if (dtrace_priv_proc_destructive(state))
6738 dtrace_action_pidresume(val);
6739 continue;
6d2010ae 6740
2d21ac55
A
6741 case DTRACEACT_COMMIT:
6742 ASSERT(!committed);
6743
6744 /*
6745 * We need to commit our buffer state.
6746 */
6747 if (ecb->dte_size)
6748 buf->dtb_offset = offs + ecb->dte_size;
6749 buf = &state->dts_buffer[cpuid];
6750 dtrace_speculation_commit(state, cpuid, val);
6751 committed = 1;
6752 continue;
6753
6754 case DTRACEACT_DISCARD:
6755 dtrace_speculation_discard(state, cpuid, val);
6756 continue;
6757
6758 case DTRACEACT_DIFEXPR:
6759 case DTRACEACT_LIBACT:
6760 case DTRACEACT_PRINTF:
6761 case DTRACEACT_PRINTA:
6762 case DTRACEACT_SYSTEM:
6763 case DTRACEACT_FREOPEN:
fe8ab488
A
6764 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
6765 case DTRACEACT_TRACEMEM:
6766 break;
6767
6768 case DTRACEACT_TRACEMEM_DYNSIZE:
6769 tracememsize = val;
2d21ac55
A
6770 break;
6771
6772 case DTRACEACT_SYM:
6773 case DTRACEACT_MOD:
6774 if (!dtrace_priv_kernel(state))
6775 continue;
6776 break;
6777
2d21ac55
A
6778 case DTRACEACT_USYM:
6779 case DTRACEACT_UMOD:
6780 case DTRACEACT_UADDR: {
6781 if (!dtrace_priv_proc(state))
6782 continue;
6783
6784 DTRACE_STORE(uint64_t, tomax,
39236c6e 6785 valoffs, (uint64_t)dtrace_proc_selfpid());
2d21ac55
A
6786 DTRACE_STORE(uint64_t, tomax,
6787 valoffs + sizeof (uint64_t), val);
6788
6789 continue;
6790 }
2d21ac55
A
6791
6792 case DTRACEACT_EXIT: {
6793 /*
6794 * For the exit action, we are going to attempt
6795 * to atomically set our activity to be
6796 * draining. If this fails (either because
6797 * another CPU has beat us to the exit action,
6798 * or because our current activity is something
6799 * other than ACTIVE or WARMUP), we will
6800 * continue. This assures that the exit action
6801 * can be successfully recorded at most once
6802 * when we're in the ACTIVE state. If we're
6803 * encountering the exit() action while in
6804 * COOLDOWN, however, we want to honor the new
6805 * status code. (We know that we're the only
6806 * thread in COOLDOWN, so there is no race.)
6807 */
6808 void *activity = &state->dts_activity;
6809 dtrace_activity_t current = state->dts_activity;
6810
6811 if (current == DTRACE_ACTIVITY_COOLDOWN)
6812 break;
6813
6814 if (current != DTRACE_ACTIVITY_WARMUP)
6815 current = DTRACE_ACTIVITY_ACTIVE;
6816
6817 if (dtrace_cas32(activity, current,
6818 DTRACE_ACTIVITY_DRAINING) != current) {
6819 *flags |= CPU_DTRACE_DROP;
6820 continue;
6821 }
6822
6823 break;
6824 }
6825
6826 default:
6827 ASSERT(0);
6828 }
6829
3e170ce0 6830 if (dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF)) {
2d21ac55
A
6831 uintptr_t end = valoffs + size;
6832
fe8ab488
A
6833 if (tracememsize != 0 &&
6834 valoffs + tracememsize < end)
6835 {
6836 end = valoffs + tracememsize;
6837 tracememsize = 0;
6838 }
6839
3e170ce0
A
6840 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
6841 !dtrace_vcanload((void *)(uintptr_t)val,
39037602 6842 &dp->dtdo_rtype, NULL, &mstate, vstate))
3e170ce0 6843 {
2d21ac55
A
6844 continue;
6845 }
6846
3e170ce0
A
6847 dtrace_store_by_ref(dp, tomax, size, &valoffs,
6848 &val, end, act->dta_intuple,
6849 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
6850 DIF_TF_BYREF: DIF_TF_BYUREF);
2d21ac55
A
6851
6852 continue;
6853 }
6854
6855 switch (size) {
6856 case 0:
6857 break;
6858
6859 case sizeof (uint8_t):
6860 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6861 break;
6862 case sizeof (uint16_t):
6863 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6864 break;
6865 case sizeof (uint32_t):
6866 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6867 break;
6868 case sizeof (uint64_t):
6869 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6870 break;
6871 default:
6872 /*
6873 * Any other size should have been returned by
6874 * reference, not by value.
6875 */
6876 ASSERT(0);
6877 break;
6878 }
6879 }
6880
6881 if (*flags & CPU_DTRACE_DROP)
6882 continue;
6883
6884 if (*flags & CPU_DTRACE_FAULT) {
6885 int ndx;
6886 dtrace_action_t *err;
6887
6888 buf->dtb_errors++;
6889
6890 if (probe->dtpr_id == dtrace_probeid_error) {
6891 /*
6892 * There's nothing we can do -- we had an
6893 * error on the error probe. We bump an
6894 * error counter to at least indicate that
6895 * this condition happened.
6896 */
6897 dtrace_error(&state->dts_dblerrors);
6898 continue;
6899 }
6900
6901 if (vtime) {
6902 /*
6903 * Before recursing on dtrace_probe(), we
6904 * need to explicitly clear out our start
6905 * time to prevent it from being accumulated
6906 * into t_dtrace_vtime.
6907 */
fe8ab488
A
6908
6909 /*
6910 * Darwin sets the sign bit on t_dtrace_tracing
6911 * to suspend accumulation to it.
6912 */
2d21ac55 6913 dtrace_set_thread_tracing(current_thread(),
fe8ab488
A
6914 (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
6915
2d21ac55
A
6916 }
6917
6918 /*
6919 * Iterate over the actions to figure out which action
6920 * we were processing when we experienced the error.
6921 * Note that act points _past_ the faulting action; if
6922 * act is ecb->dte_action, the fault was in the
6923 * predicate, if it's ecb->dte_action->dta_next it's
6924 * in action #1, and so on.
6925 */
6926 for (err = ecb->dte_action, ndx = 0;
6927 err != act; err = err->dta_next, ndx++)
6928 continue;
6929
6930 dtrace_probe_error(state, ecb->dte_epid, ndx,
6931 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6932 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6933 cpu_core[cpuid].cpuc_dtrace_illval);
6934
6935 continue;
6936 }
6937
6938 if (!committed)
6939 buf->dtb_offset = offs + ecb->dte_size;
6940 }
6941
fe8ab488 6942 /* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
b0d623f7 6943 to the current thread. Instead it should accrue to DTrace. */
2d21ac55
A
6944 if (vtime) {
6945 thread_t thread = current_thread();
6946 int64_t t = dtrace_get_thread_tracing(thread);
6947
6948 if (t >= 0) {
6949 /* Usual case, accumulate time spent here into t_dtrace_tracing */
6950 dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
6951 } else {
6952 /* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
6953 dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
6954 }
6955 }
2d21ac55
A
6956
6957 dtrace_interrupt_enable(cookie);
6958}
6959
fe8ab488
A
6960/*
6961 * APPLE NOTE: Don't allow a thread to re-enter dtrace_probe().
6962 * This could occur if a probe is encountered on some function in the
6963 * transitive closure of the call to dtrace_probe().
6964 * Solaris has some strong guarantees that this won't happen.
6965 * The Darwin implementation is not so mature as to make those guarantees.
6966 * Hence, the introduction of __dtrace_probe() on xnu.
6967 */
6d2010ae 6968
2d21ac55
A
6969void
6970dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6971 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6972{
6973 thread_t thread = current_thread();
6d2010ae 6974 disable_preemption();
2d21ac55
A
6975 if (id == dtrace_probeid_error) {
6976 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
b0d623f7 6977 dtrace_getipl(); /* Defeat tail-call optimization of __dtrace_probe() */
2d21ac55
A
6978 } else if (!dtrace_get_thread_reentering(thread)) {
6979 dtrace_set_thread_reentering(thread, TRUE);
6980 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6981 dtrace_set_thread_reentering(thread, FALSE);
6982 }
b0d623f7
A
6983#if DEBUG
6984 else __dtrace_probe(dtrace_probeid_error, 0, id, 1, -1, DTRACEFLT_UNKNOWN);
6985#endif
6d2010ae 6986 enable_preemption();
2d21ac55 6987}
2d21ac55
A
6988
6989/*
6990 * DTrace Probe Hashing Functions
6991 *
6992 * The functions in this section (and indeed, the functions in remaining
6993 * sections) are not _called_ from probe context. (Any exceptions to this are
6994 * marked with a "Note:".) Rather, they are called from elsewhere in the
6995 * DTrace framework to look-up probes in, add probes to and remove probes from
6996 * the DTrace probe hashes. (Each probe is hashed by each element of the
6997 * probe tuple -- allowing for fast lookups, regardless of what was
6998 * specified.)
6999 */
7000static uint_t
b0d623f7 7001dtrace_hash_str(const char *p)
2d21ac55
A
7002{
7003 unsigned int g;
7004 uint_t hval = 0;
7005
7006 while (*p) {
7007 hval = (hval << 4) + *p++;
7008 if ((g = (hval & 0xf0000000)) != 0)
7009 hval ^= g >> 24;
7010 hval &= ~g;
7011 }
7012 return (hval);
7013}
7014
7015static dtrace_hash_t *
7016dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7017{
7018 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7019
7020 hash->dth_stroffs = stroffs;
7021 hash->dth_nextoffs = nextoffs;
7022 hash->dth_prevoffs = prevoffs;
7023
7024 hash->dth_size = 1;
7025 hash->dth_mask = hash->dth_size - 1;
7026
7027 hash->dth_tab = kmem_zalloc(hash->dth_size *
7028 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7029
7030 return (hash);
7031}
7032
fe8ab488
A
7033/*
7034 * APPLE NOTE: dtrace_hash_destroy is not used.
7035 * It is called by dtrace_detach which is not
7036 * currently implemented. Revisit someday.
7037 */
7038#if !defined(__APPLE__)
2d21ac55
A
7039static void
7040dtrace_hash_destroy(dtrace_hash_t *hash)
7041{
b0d623f7 7042#if DEBUG
2d21ac55
A
7043 int i;
7044
7045 for (i = 0; i < hash->dth_size; i++)
7046 ASSERT(hash->dth_tab[i] == NULL);
7047#endif
7048
7049 kmem_free(hash->dth_tab,
7050 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7051 kmem_free(hash, sizeof (dtrace_hash_t));
7052}
7053#endif /* __APPLE__ */
7054
7055static void
7056dtrace_hash_resize(dtrace_hash_t *hash)
7057{
7058 int size = hash->dth_size, i, ndx;
7059 int new_size = hash->dth_size << 1;
7060 int new_mask = new_size - 1;
7061 dtrace_hashbucket_t **new_tab, *bucket, *next;
7062
7063 ASSERT((new_size & new_mask) == 0);
7064
7065 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7066
7067 for (i = 0; i < size; i++) {
7068 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7069 dtrace_probe_t *probe = bucket->dthb_chain;
7070
7071 ASSERT(probe != NULL);
7072 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7073
7074 next = bucket->dthb_next;
7075 bucket->dthb_next = new_tab[ndx];
7076 new_tab[ndx] = bucket;
7077 }
7078 }
7079
7080 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7081 hash->dth_tab = new_tab;
7082 hash->dth_size = new_size;
7083 hash->dth_mask = new_mask;
7084}
7085
7086static void
7087dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7088{
7089 int hashval = DTRACE_HASHSTR(hash, new);
7090 int ndx = hashval & hash->dth_mask;
7091 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7092 dtrace_probe_t **nextp, **prevp;
7093
7094 for (; bucket != NULL; bucket = bucket->dthb_next) {
7095 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7096 goto add;
7097 }
7098
7099 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7100 dtrace_hash_resize(hash);
7101 dtrace_hash_add(hash, new);
7102 return;
7103 }
7104
7105 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7106 bucket->dthb_next = hash->dth_tab[ndx];
7107 hash->dth_tab[ndx] = bucket;
7108 hash->dth_nbuckets++;
7109
7110add:
7111 nextp = DTRACE_HASHNEXT(hash, new);
7112 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7113 *nextp = bucket->dthb_chain;
7114
7115 if (bucket->dthb_chain != NULL) {
7116 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7117 ASSERT(*prevp == NULL);
7118 *prevp = new;
7119 }
7120
7121 bucket->dthb_chain = new;
7122 bucket->dthb_len++;
7123}
7124
7125static dtrace_probe_t *
7126dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7127{
7128 int hashval = DTRACE_HASHSTR(hash, template);
7129 int ndx = hashval & hash->dth_mask;
7130 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7131
7132 for (; bucket != NULL; bucket = bucket->dthb_next) {
7133 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7134 return (bucket->dthb_chain);
7135 }
7136
7137 return (NULL);
7138}
7139
7140static int
7141dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7142{
7143 int hashval = DTRACE_HASHSTR(hash, template);
7144 int ndx = hashval & hash->dth_mask;
7145 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7146
7147 for (; bucket != NULL; bucket = bucket->dthb_next) {
7148 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7149 return (bucket->dthb_len);
7150 }
7151
fe8ab488 7152 return (0);
2d21ac55
A
7153}
7154
7155static void
7156dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7157{
7158 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7159 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7160
7161 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7162 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7163
7164 /*
7165 * Find the bucket that we're removing this probe from.
7166 */
7167 for (; bucket != NULL; bucket = bucket->dthb_next) {
7168 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7169 break;
7170 }
7171
7172 ASSERT(bucket != NULL);
7173
7174 if (*prevp == NULL) {
7175 if (*nextp == NULL) {
7176 /*
7177 * The removed probe was the only probe on this
7178 * bucket; we need to remove the bucket.
7179 */
7180 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7181
7182 ASSERT(bucket->dthb_chain == probe);
7183 ASSERT(b != NULL);
7184
7185 if (b == bucket) {
7186 hash->dth_tab[ndx] = bucket->dthb_next;
7187 } else {
7188 while (b->dthb_next != bucket)
7189 b = b->dthb_next;
7190 b->dthb_next = bucket->dthb_next;
7191 }
7192
7193 ASSERT(hash->dth_nbuckets > 0);
7194 hash->dth_nbuckets--;
7195 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7196 return;
7197 }
7198
7199 bucket->dthb_chain = *nextp;
7200 } else {
7201 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7202 }
7203
7204 if (*nextp != NULL)
7205 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7206}
7207
7208/*
7209 * DTrace Utility Functions
7210 *
7211 * These are random utility functions that are _not_ called from probe context.
7212 */
7213static int
7214dtrace_badattr(const dtrace_attribute_t *a)
7215{
7216 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7217 a->dtat_data > DTRACE_STABILITY_MAX ||
7218 a->dtat_class > DTRACE_CLASS_MAX);
7219}
7220
7221/*
7222 * Return a duplicate copy of a string. If the specified string is NULL,
7223 * this function returns a zero-length string.
fe8ab488 7224 * APPLE NOTE: Darwin employs size bounded string operation.
2d21ac55 7225 */
b0d623f7
A
7226static char *
7227dtrace_strdup(const char *str)
7228{
7229 size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
7230 char *new = kmem_zalloc(bufsize, KM_SLEEP);
7231
7232 if (str != NULL)
7233 (void) strlcpy(new, str, bufsize);
7234
7235 return (new);
7236}
2d21ac55
A
7237
7238#define DTRACE_ISALPHA(c) \
7239 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7240
7241static int
7242dtrace_badname(const char *s)
7243{
7244 char c;
7245
7246 if (s == NULL || (c = *s++) == '\0')
7247 return (0);
7248
7249 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7250 return (1);
7251
7252 while ((c = *s++) != '\0') {
7253 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7254 c != '-' && c != '_' && c != '.' && c != '`')
7255 return (1);
7256 }
7257
7258 return (0);
7259}
7260
7261static void
7262dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7263{
7264 uint32_t priv;
7265
7266 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
39037602 7267 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
5ba3f43e 7268 priv = DTRACE_PRIV_USER | DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER;
39037602
A
7269 }
7270 else {
7271 priv = DTRACE_PRIV_ALL;
7272 }
5ba3f43e
A
7273 *uidp = 0;
7274 *zoneidp = 0;
2d21ac55
A
7275 } else {
7276 *uidp = crgetuid(cr);
7277 *zoneidp = crgetzoneid(cr);
7278
7279 priv = 0;
7280 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7281 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7282 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7283 priv |= DTRACE_PRIV_USER;
7284 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7285 priv |= DTRACE_PRIV_PROC;
7286 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7287 priv |= DTRACE_PRIV_OWNER;
7288 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7289 priv |= DTRACE_PRIV_ZONEOWNER;
7290 }
7291
7292 *privp = priv;
7293}
7294
7295#ifdef DTRACE_ERRDEBUG
7296static void
7297dtrace_errdebug(const char *str)
7298{
b0d623f7 7299 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
2d21ac55
A
7300 int occupied = 0;
7301
7302 lck_mtx_lock(&dtrace_errlock);
7303 dtrace_errlast = str;
b0d623f7 7304 dtrace_errthread = (kthread_t *)current_thread();
2d21ac55
A
7305
7306 while (occupied++ < DTRACE_ERRHASHSZ) {
7307 if (dtrace_errhash[hval].dter_msg == str) {
7308 dtrace_errhash[hval].dter_count++;
7309 goto out;
7310 }
7311
7312 if (dtrace_errhash[hval].dter_msg != NULL) {
7313 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7314 continue;
7315 }
7316
7317 dtrace_errhash[hval].dter_msg = str;
7318 dtrace_errhash[hval].dter_count = 1;
7319 goto out;
7320 }
7321
7322 panic("dtrace: undersized error hash");
7323out:
7324 lck_mtx_unlock(&dtrace_errlock);
7325}
7326#endif
7327
7328/*
7329 * DTrace Matching Functions
7330 *
7331 * These functions are used to match groups of probes, given some elements of
7332 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7333 */
7334static int
7335dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7336 zoneid_t zoneid)
7337{
7338 if (priv != DTRACE_PRIV_ALL) {
7339 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7340 uint32_t match = priv & ppriv;
7341
7342 /*
7343 * No PRIV_DTRACE_* privileges...
7344 */
7345 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7346 DTRACE_PRIV_KERNEL)) == 0)
7347 return (0);
7348
7349 /*
7350 * No matching bits, but there were bits to match...
7351 */
7352 if (match == 0 && ppriv != 0)
7353 return (0);
7354
7355 /*
7356 * Need to have permissions to the process, but don't...
7357 */
7358 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7359 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7360 return (0);
7361 }
7362
7363 /*
7364 * Need to be in the same zone unless we possess the
7365 * privilege to examine all zones.
7366 */
7367 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7368 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7369 return (0);
7370 }
7371 }
7372
7373 return (1);
7374}
7375
7376/*
7377 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7378 * consists of input pattern strings and an ops-vector to evaluate them.
7379 * This function returns >0 for match, 0 for no match, and <0 for error.
7380 */
7381static int
7382dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7383 uint32_t priv, uid_t uid, zoneid_t zoneid)
7384{
7385 dtrace_provider_t *pvp = prp->dtpr_provider;
7386 int rv;
7387
7388 if (pvp->dtpv_defunct)
7389 return (0);
7390
7391 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7392 return (rv);
7393
7394 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7395 return (rv);
7396
7397 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7398 return (rv);
7399
7400 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7401 return (rv);
7402
7403 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7404 return (0);
7405
7406 return (rv);
7407}
7408
7409/*
7410 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7411 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7412 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7413 * In addition, all of the recursion cases except for '*' matching have been
7414 * unwound. For '*', we still implement recursive evaluation, but a depth
7415 * counter is maintained and matching is aborted if we recurse too deep.
7416 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7417 */
7418static int
7419dtrace_match_glob(const char *s, const char *p, int depth)
7420{
7421 const char *olds;
7422 char s1, c;
7423 int gs;
7424
7425 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7426 return (-1);
7427
7428 if (s == NULL)
7429 s = ""; /* treat NULL as empty string */
7430
7431top:
7432 olds = s;
7433 s1 = *s++;
7434
7435 if (p == NULL)
7436 return (0);
7437
7438 if ((c = *p++) == '\0')
7439 return (s1 == '\0');
7440
7441 switch (c) {
7442 case '[': {
7443 int ok = 0, notflag = 0;
7444 char lc = '\0';
7445
7446 if (s1 == '\0')
7447 return (0);
7448
7449 if (*p == '!') {
7450 notflag = 1;
7451 p++;
7452 }
7453
7454 if ((c = *p++) == '\0')
7455 return (0);
7456
7457 do {
7458 if (c == '-' && lc != '\0' && *p != ']') {
7459 if ((c = *p++) == '\0')
7460 return (0);
7461 if (c == '\\' && (c = *p++) == '\0')
7462 return (0);
7463
7464 if (notflag) {
7465 if (s1 < lc || s1 > c)
7466 ok++;
7467 else
7468 return (0);
7469 } else if (lc <= s1 && s1 <= c)
7470 ok++;
7471
7472 } else if (c == '\\' && (c = *p++) == '\0')
7473 return (0);
7474
7475 lc = c; /* save left-hand 'c' for next iteration */
7476
7477 if (notflag) {
7478 if (s1 != c)
7479 ok++;
7480 else
7481 return (0);
7482 } else if (s1 == c)
7483 ok++;
7484
7485 if ((c = *p++) == '\0')
7486 return (0);
7487
7488 } while (c != ']');
7489
7490 if (ok)
7491 goto top;
7492
7493 return (0);
7494 }
7495
7496 case '\\':
7497 if ((c = *p++) == '\0')
7498 return (0);
7499 /*FALLTHRU*/
7500
7501 default:
7502 if (c != s1)
7503 return (0);
7504 /*FALLTHRU*/
7505
7506 case '?':
7507 if (s1 != '\0')
7508 goto top;
7509 return (0);
7510
7511 case '*':
7512 while (*p == '*')
7513 p++; /* consecutive *'s are identical to a single one */
7514
7515 if (*p == '\0')
7516 return (1);
7517
7518 for (s = olds; *s != '\0'; s++) {
7519 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7520 return (gs);
7521 }
7522
7523 return (0);
7524 }
7525}
7526
7527/*ARGSUSED*/
7528static int
7529dtrace_match_string(const char *s, const char *p, int depth)
7530{
b0d623f7 7531#pragma unused(depth) /* __APPLE__ */
fe8ab488
A
7532
7533 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7 7534 return (s != NULL && strncmp(s, p, strlen(s) + 1) == 0);
2d21ac55
A
7535}
7536
7537/*ARGSUSED*/
7538static int
7539dtrace_match_nul(const char *s, const char *p, int depth)
7540{
b0d623f7 7541#pragma unused(s, p, depth) /* __APPLE__ */
2d21ac55
A
7542 return (1); /* always match the empty pattern */
7543}
7544
7545/*ARGSUSED*/
7546static int
7547dtrace_match_nonzero(const char *s, const char *p, int depth)
7548{
b0d623f7 7549#pragma unused(p, depth) /* __APPLE__ */
2d21ac55
A
7550 return (s != NULL && s[0] != '\0');
7551}
7552
7553static int
7554dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
d190cdc3 7555 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *, void *), void *arg1, void *arg2)
2d21ac55
A
7556{
7557 dtrace_probe_t template, *probe;
7558 dtrace_hash_t *hash = NULL;
6d2010ae 7559 int len, rc, best = INT_MAX, nmatched = 0;
2d21ac55
A
7560 dtrace_id_t i;
7561
5ba3f43e 7562 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
7563
7564 /*
7565 * If the probe ID is specified in the key, just lookup by ID and
7566 * invoke the match callback once if a matching probe is found.
7567 */
7568 if (pkp->dtpk_id != DTRACE_IDNONE) {
7569 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7570 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
d190cdc3 7571 if ((*matched)(probe, arg1, arg2) == DTRACE_MATCH_FAIL)
6d2010ae 7572 return (DTRACE_MATCH_FAIL);
2d21ac55
A
7573 nmatched++;
7574 }
7575 return (nmatched);
7576 }
7577
b0d623f7
A
7578 template.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod;
7579 template.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func;
7580 template.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name;
2d21ac55
A
7581
7582 /*
7583 * We want to find the most distinct of the module name, function
7584 * name, and name. So for each one that is not a glob pattern or
7585 * empty string, we perform a lookup in the corresponding hash and
7586 * use the hash table with the fewest collisions to do our search.
7587 */
7588 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7589 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7590 best = len;
7591 hash = dtrace_bymod;
7592 }
7593
7594 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7595 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7596 best = len;
7597 hash = dtrace_byfunc;
7598 }
7599
7600 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7601 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7602 best = len;
7603 hash = dtrace_byname;
7604 }
7605
7606 /*
7607 * If we did not select a hash table, iterate over every probe and
7608 * invoke our callback for each one that matches our input probe key.
7609 */
7610 if (hash == NULL) {
b0d623f7 7611 for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
2d21ac55
A
7612 if ((probe = dtrace_probes[i]) == NULL ||
7613 dtrace_match_probe(probe, pkp, priv, uid,
7614 zoneid) <= 0)
7615 continue;
7616
7617 nmatched++;
7618
d190cdc3 7619 if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
6d2010ae
A
7620 if (rc == DTRACE_MATCH_FAIL)
7621 return (DTRACE_MATCH_FAIL);
7622 break;
7623 }
2d21ac55
A
7624 }
7625
7626 return (nmatched);
7627 }
7628
7629 /*
7630 * If we selected a hash table, iterate over each probe of the same key
7631 * name and invoke the callback for every probe that matches the other
7632 * attributes of our input probe key.
7633 */
7634 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7635 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7636
7637 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7638 continue;
7639
7640 nmatched++;
7641
d190cdc3 7642 if ((rc = (*matched)(probe, arg1, arg2)) != DTRACE_MATCH_NEXT) {
6d2010ae
A
7643 if (rc == DTRACE_MATCH_FAIL)
7644 return (DTRACE_MATCH_FAIL);
7645 break;
7646 }
2d21ac55
A
7647 }
7648
7649 return (nmatched);
7650}
7651
7652/*
7653 * Return the function pointer dtrace_probecmp() should use to compare the
7654 * specified pattern with a string. For NULL or empty patterns, we select
7655 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7656 * For non-empty non-glob strings, we use dtrace_match_string().
7657 */
7658static dtrace_probekey_f *
7659dtrace_probekey_func(const char *p)
7660{
7661 char c;
7662
7663 if (p == NULL || *p == '\0')
7664 return (&dtrace_match_nul);
7665
7666 while ((c = *p++) != '\0') {
7667 if (c == '[' || c == '?' || c == '*' || c == '\\')
7668 return (&dtrace_match_glob);
7669 }
7670
7671 return (&dtrace_match_string);
7672}
7673
7674/*
7675 * Build a probe comparison key for use with dtrace_match_probe() from the
7676 * given probe description. By convention, a null key only matches anchored
7677 * probes: if each field is the empty string, reset dtpk_fmatch to
7678 * dtrace_match_nonzero().
7679 */
7680static void
7681dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7682{
7683 pkp->dtpk_prov = pdp->dtpd_provider;
7684 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7685
7686 pkp->dtpk_mod = pdp->dtpd_mod;
7687 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7688
7689 pkp->dtpk_func = pdp->dtpd_func;
7690 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7691
7692 pkp->dtpk_name = pdp->dtpd_name;
7693 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7694
7695 pkp->dtpk_id = pdp->dtpd_id;
7696
7697 if (pkp->dtpk_id == DTRACE_IDNONE &&
7698 pkp->dtpk_pmatch == &dtrace_match_nul &&
7699 pkp->dtpk_mmatch == &dtrace_match_nul &&
7700 pkp->dtpk_fmatch == &dtrace_match_nul &&
7701 pkp->dtpk_nmatch == &dtrace_match_nul)
7702 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7703}
7704
39037602
A
7705static int
7706dtrace_cond_provider_match(dtrace_probedesc_t *desc, void *data)
7707{
7708 if (desc == NULL)
7709 return 1;
7710
7711 dtrace_probekey_f *func = dtrace_probekey_func(desc->dtpd_provider);
7712
813fb2f6 7713 return func((char*)data, desc->dtpd_provider, 0);
39037602
A
7714}
7715
2d21ac55
A
7716/*
7717 * DTrace Provider-to-Framework API Functions
7718 *
7719 * These functions implement much of the Provider-to-Framework API, as
7720 * described in <sys/dtrace.h>. The parts of the API not in this section are
7721 * the functions in the API for probe management (found below), and
7722 * dtrace_probe() itself (found above).
7723 */
7724
7725/*
7726 * Register the calling provider with the DTrace framework. This should
7727 * generally be called by DTrace providers in their attach(9E) entry point.
7728 */
7729int
7730dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7731 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7732{
7733 dtrace_provider_t *provider;
7734
7735 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7736 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7737 "arguments", name ? name : "<NULL>");
7738 return (EINVAL);
7739 }
7740
7741 if (name[0] == '\0' || dtrace_badname(name)) {
7742 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7743 "provider name", name);
7744 return (EINVAL);
7745 }
7746
7747 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7748 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7749 pops->dtps_destroy == NULL ||
7750 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7751 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7752 "provider ops", name);
7753 return (EINVAL);
7754 }
7755
7756 if (dtrace_badattr(&pap->dtpa_provider) ||
7757 dtrace_badattr(&pap->dtpa_mod) ||
7758 dtrace_badattr(&pap->dtpa_func) ||
7759 dtrace_badattr(&pap->dtpa_name) ||
7760 dtrace_badattr(&pap->dtpa_args)) {
7761 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7762 "provider attributes", name);
7763 return (EINVAL);
7764 }
7765
7766 if (priv & ~DTRACE_PRIV_ALL) {
7767 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7768 "privilege attributes", name);
7769 return (EINVAL);
7770 }
7771
7772 if ((priv & DTRACE_PRIV_KERNEL) &&
7773 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7774 pops->dtps_usermode == NULL) {
7775 cmn_err(CE_WARN, "failed to register provider '%s': need "
7776 "dtps_usermode() op for given privilege attributes", name);
7777 return (EINVAL);
7778 }
7779
7780 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
fe8ab488
A
7781
7782 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7
A
7783 {
7784 size_t bufsize = strlen(name) + 1;
7785 provider->dtpv_name = kmem_alloc(bufsize, KM_SLEEP);
7786 (void) strlcpy(provider->dtpv_name, name, bufsize);
7787 }
2d21ac55
A
7788
7789 provider->dtpv_attr = *pap;
7790 provider->dtpv_priv.dtpp_flags = priv;
7791 if (cr != NULL) {
7792 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7793 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7794 }
7795 provider->dtpv_pops = *pops;
7796
7797 if (pops->dtps_provide == NULL) {
7798 ASSERT(pops->dtps_provide_module != NULL);
7799 provider->dtpv_pops.dtps_provide =
7800 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7801 }
7802
7803 if (pops->dtps_provide_module == NULL) {
7804 ASSERT(pops->dtps_provide != NULL);
7805 provider->dtpv_pops.dtps_provide_module =
7806 (void (*)(void *, struct modctl *))dtrace_nullop;
7807 }
7808
7809 if (pops->dtps_suspend == NULL) {
7810 ASSERT(pops->dtps_resume == NULL);
7811 provider->dtpv_pops.dtps_suspend =
7812 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7813 provider->dtpv_pops.dtps_resume =
7814 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7815 }
7816
7817 provider->dtpv_arg = arg;
7818 *idp = (dtrace_provider_id_t)provider;
7819
7820 if (pops == &dtrace_provider_ops) {
5ba3f43e
A
7821 LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7822 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
7823 ASSERT(dtrace_anon.dta_enabling == NULL);
7824
7825 /*
7826 * We make sure that the DTrace provider is at the head of
7827 * the provider chain.
7828 */
7829 provider->dtpv_next = dtrace_provider;
7830 dtrace_provider = provider;
7831 return (0);
7832 }
7833
7834 lck_mtx_lock(&dtrace_provider_lock);
7835 lck_mtx_lock(&dtrace_lock);
7836
7837 /*
7838 * If there is at least one provider registered, we'll add this
7839 * provider after the first provider.
7840 */
7841 if (dtrace_provider != NULL) {
7842 provider->dtpv_next = dtrace_provider->dtpv_next;
7843 dtrace_provider->dtpv_next = provider;
7844 } else {
7845 dtrace_provider = provider;
7846 }
7847
7848 if (dtrace_retained != NULL) {
7849 dtrace_enabling_provide(provider);
7850
7851 /*
39037602
A
7852 * Now we need to call dtrace_enabling_matchall_with_cond() --
7853 * with a condition matching the provider name we just added,
7854 * which will acquire cpu_lock and dtrace_lock. We therefore need
2d21ac55
A
7855 * to drop all of our locks before calling into it...
7856 */
7857 lck_mtx_unlock(&dtrace_lock);
7858 lck_mtx_unlock(&dtrace_provider_lock);
39037602
A
7859
7860 dtrace_match_cond_t cond = {dtrace_cond_provider_match, provider->dtpv_name};
7861 dtrace_enabling_matchall_with_cond(&cond);
2d21ac55
A
7862
7863 return (0);
7864 }
7865
7866 lck_mtx_unlock(&dtrace_lock);
7867 lck_mtx_unlock(&dtrace_provider_lock);
7868
7869 return (0);
7870}
7871
7872/*
7873 * Unregister the specified provider from the DTrace framework. This should
7874 * generally be called by DTrace providers in their detach(9E) entry point.
7875 */
7876int
7877dtrace_unregister(dtrace_provider_id_t id)
7878{
7879 dtrace_provider_t *old = (dtrace_provider_t *)id;
7880 dtrace_provider_t *prev = NULL;
7881 int i, self = 0;
7882 dtrace_probe_t *probe, *first = NULL;
7883
7884 if (old->dtpv_pops.dtps_enable ==
6d2010ae 7885 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
2d21ac55
A
7886 /*
7887 * If DTrace itself is the provider, we're called with locks
7888 * already held.
7889 */
7890 ASSERT(old == dtrace_provider);
7891 ASSERT(dtrace_devi != NULL);
5ba3f43e
A
7892 LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7893 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
7894 self = 1;
7895
7896 if (dtrace_provider->dtpv_next != NULL) {
7897 /*
7898 * There's another provider here; return failure.
7899 */
7900 return (EBUSY);
7901 }
7902 } else {
7903 lck_mtx_lock(&dtrace_provider_lock);
7904 lck_mtx_lock(&mod_lock);
7905 lck_mtx_lock(&dtrace_lock);
7906 }
7907
7908 /*
7909 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7910 * probes, we refuse to let providers slither away, unless this
7911 * provider has already been explicitly invalidated.
7912 */
7913 if (!old->dtpv_defunct &&
7914 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7915 dtrace_anon.dta_state->dts_necbs > 0))) {
7916 if (!self) {
7917 lck_mtx_unlock(&dtrace_lock);
7918 lck_mtx_unlock(&mod_lock);
7919 lck_mtx_unlock(&dtrace_provider_lock);
7920 }
7921 return (EBUSY);
7922 }
7923
7924 /*
7925 * Attempt to destroy the probes associated with this provider.
7926 */
fe8ab488 7927 if (old->dtpv_ecb_count!=0) {
2d21ac55
A
7928 /*
7929 * We have at least one ECB; we can't remove this provider.
7930 */
7931 if (!self) {
7932 lck_mtx_unlock(&dtrace_lock);
7933 lck_mtx_unlock(&mod_lock);
7934 lck_mtx_unlock(&dtrace_provider_lock);
7935 }
7936 return (EBUSY);
7937 }
7938
7939 /*
7940 * All of the probes for this provider are disabled; we can safely
7941 * remove all of them from their hash chains and from the probe array.
7942 */
fe8ab488 7943 for (i = 0; i < dtrace_nprobes && old->dtpv_probe_count!=0; i++) {
2d21ac55
A
7944 if ((probe = dtrace_probes[i]) == NULL)
7945 continue;
7946
7947 if (probe->dtpr_provider != old)
7948 continue;
7949
7950 dtrace_probes[i] = NULL;
fe8ab488 7951 old->dtpv_probe_count--;
2d21ac55
A
7952
7953 dtrace_hash_remove(dtrace_bymod, probe);
7954 dtrace_hash_remove(dtrace_byfunc, probe);
7955 dtrace_hash_remove(dtrace_byname, probe);
7956
7957 if (first == NULL) {
7958 first = probe;
7959 probe->dtpr_nextmod = NULL;
7960 } else {
7961 probe->dtpr_nextmod = first;
7962 first = probe;
7963 }
7964 }
7965
7966 /*
7967 * The provider's probes have been removed from the hash chains and
7968 * from the probe array. Now issue a dtrace_sync() to be sure that
7969 * everyone has cleared out from any probe array processing.
7970 */
7971 dtrace_sync();
7972
7973 for (probe = first; probe != NULL; probe = first) {
7974 first = probe->dtpr_nextmod;
7975
7976 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7977 probe->dtpr_arg);
7978 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7979 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7980 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7981 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
2d21ac55 7982 zfree(dtrace_probe_t_zone, probe);
2d21ac55
A
7983 }
7984
7985 if ((prev = dtrace_provider) == old) {
7986 ASSERT(self || dtrace_devi == NULL);
7987 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7988 dtrace_provider = old->dtpv_next;
7989 } else {
7990 while (prev != NULL && prev->dtpv_next != old)
7991 prev = prev->dtpv_next;
7992
7993 if (prev == NULL) {
7994 panic("attempt to unregister non-existent "
7995 "dtrace provider %p\n", (void *)id);
7996 }
7997
7998 prev->dtpv_next = old->dtpv_next;
7999 }
8000
8001 if (!self) {
8002 lck_mtx_unlock(&dtrace_lock);
8003 lck_mtx_unlock(&mod_lock);
8004 lck_mtx_unlock(&dtrace_provider_lock);
8005 }
8006
8007 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8008 kmem_free(old, sizeof (dtrace_provider_t));
8009
8010 return (0);
8011}
8012
8013/*
8014 * Invalidate the specified provider. All subsequent probe lookups for the
8015 * specified provider will fail, but its probes will not be removed.
8016 */
8017void
8018dtrace_invalidate(dtrace_provider_id_t id)
8019{
8020 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8021
8022 ASSERT(pvp->dtpv_pops.dtps_enable !=
6d2010ae 8023 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
2d21ac55
A
8024
8025 lck_mtx_lock(&dtrace_provider_lock);
8026 lck_mtx_lock(&dtrace_lock);
8027
8028 pvp->dtpv_defunct = 1;
8029
8030 lck_mtx_unlock(&dtrace_lock);
8031 lck_mtx_unlock(&dtrace_provider_lock);
8032}
8033
8034/*
8035 * Indicate whether or not DTrace has attached.
8036 */
8037int
8038dtrace_attached(void)
8039{
8040 /*
8041 * dtrace_provider will be non-NULL iff the DTrace driver has
8042 * attached. (It's non-NULL because DTrace is always itself a
8043 * provider.)
8044 */
8045 return (dtrace_provider != NULL);
8046}
8047
8048/*
8049 * Remove all the unenabled probes for the given provider. This function is
8050 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8051 * -- just as many of its associated probes as it can.
8052 */
8053int
8054dtrace_condense(dtrace_provider_id_t id)
8055{
8056 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8057 int i;
8058 dtrace_probe_t *probe;
8059
8060 /*
8061 * Make sure this isn't the dtrace provider itself.
8062 */
8063 ASSERT(prov->dtpv_pops.dtps_enable !=
6d2010ae 8064 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
2d21ac55
A
8065
8066 lck_mtx_lock(&dtrace_provider_lock);
8067 lck_mtx_lock(&dtrace_lock);
8068
8069 /*
8070 * Attempt to destroy the probes associated with this provider.
8071 */
8072 for (i = 0; i < dtrace_nprobes; i++) {
8073 if ((probe = dtrace_probes[i]) == NULL)
8074 continue;
8075
8076 if (probe->dtpr_provider != prov)
8077 continue;
8078
8079 if (probe->dtpr_ecb != NULL)
8080 continue;
8081
8082 dtrace_probes[i] = NULL;
fe8ab488 8083 prov->dtpv_probe_count--;
2d21ac55
A
8084
8085 dtrace_hash_remove(dtrace_bymod, probe);
8086 dtrace_hash_remove(dtrace_byfunc, probe);
8087 dtrace_hash_remove(dtrace_byname, probe);
8088
8089 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8090 probe->dtpr_arg);
8091 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8092 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8093 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
2d21ac55 8094 zfree(dtrace_probe_t_zone, probe);
2d21ac55
A
8095 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8096 }
8097
8098 lck_mtx_unlock(&dtrace_lock);
8099 lck_mtx_unlock(&dtrace_provider_lock);
8100
8101 return (0);
8102}
8103
8104/*
8105 * DTrace Probe Management Functions
8106 *
8107 * The functions in this section perform the DTrace probe management,
8108 * including functions to create probes, look-up probes, and call into the
8109 * providers to request that probes be provided. Some of these functions are
8110 * in the Provider-to-Framework API; these functions can be identified by the
8111 * fact that they are not declared "static".
8112 */
8113
8114/*
8115 * Create a probe with the specified module name, function name, and name.
8116 */
8117dtrace_id_t
8118dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8119 const char *func, const char *name, int aframes, void *arg)
8120{
8121 dtrace_probe_t *probe, **probes;
8122 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8123 dtrace_id_t id;
8124
8125 if (provider == dtrace_provider) {
5ba3f43e 8126 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
8127 } else {
8128 lck_mtx_lock(&dtrace_lock);
8129 }
8130
8131 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8132 VM_BESTFIT | VM_SLEEP);
fe8ab488 8133
2d21ac55
A
8134 probe = zalloc(dtrace_probe_t_zone);
8135 bzero(probe, sizeof (dtrace_probe_t));
2d21ac55
A
8136
8137 probe->dtpr_id = id;
8138 probe->dtpr_gen = dtrace_probegen++;
8139 probe->dtpr_mod = dtrace_strdup(mod);
8140 probe->dtpr_func = dtrace_strdup(func);
8141 probe->dtpr_name = dtrace_strdup(name);
8142 probe->dtpr_arg = arg;
8143 probe->dtpr_aframes = aframes;
8144 probe->dtpr_provider = provider;
8145
8146 dtrace_hash_add(dtrace_bymod, probe);
8147 dtrace_hash_add(dtrace_byfunc, probe);
8148 dtrace_hash_add(dtrace_byname, probe);
8149
b0d623f7 8150 if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
2d21ac55
A
8151 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8152 size_t nsize = osize << 1;
8153
8154 if (nsize == 0) {
8155 ASSERT(osize == 0);
8156 ASSERT(dtrace_probes == NULL);
8157 nsize = sizeof (dtrace_probe_t *);
8158 }
8159
8160 probes = kmem_zalloc(nsize, KM_SLEEP);
8161
8162 if (dtrace_probes == NULL) {
8163 ASSERT(osize == 0);
8164 dtrace_probes = probes;
8165 dtrace_nprobes = 1;
8166 } else {
8167 dtrace_probe_t **oprobes = dtrace_probes;
8168
8169 bcopy(oprobes, probes, osize);
8170 dtrace_membar_producer();
8171 dtrace_probes = probes;
8172
8173 dtrace_sync();
8174
8175 /*
8176 * All CPUs are now seeing the new probes array; we can
8177 * safely free the old array.
8178 */
8179 kmem_free(oprobes, osize);
8180 dtrace_nprobes <<= 1;
8181 }
8182
b0d623f7 8183 ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
2d21ac55
A
8184 }
8185
8186 ASSERT(dtrace_probes[id - 1] == NULL);
8187 dtrace_probes[id - 1] = probe;
fe8ab488 8188 provider->dtpv_probe_count++;
2d21ac55
A
8189
8190 if (provider != dtrace_provider)
8191 lck_mtx_unlock(&dtrace_lock);
8192
8193 return (id);
8194}
8195
8196static dtrace_probe_t *
8197dtrace_probe_lookup_id(dtrace_id_t id)
8198{
5ba3f43e 8199 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 8200
b0d623f7
A
8201 if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
8202 return (NULL);
2d21ac55
A
8203
8204 return (dtrace_probes[id - 1]);
8205}
8206
8207static int
d190cdc3 8208dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg1, void *arg2)
2d21ac55 8209{
d190cdc3
A
8210#pragma unused(arg2)
8211 *((dtrace_id_t *)arg1) = probe->dtpr_id;
2d21ac55
A
8212
8213 return (DTRACE_MATCH_DONE);
8214}
8215
8216/*
8217 * Look up a probe based on provider and one or more of module name, function
8218 * name and probe name.
8219 */
8220dtrace_id_t
8221dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8222 const char *func, const char *name)
8223{
8224 dtrace_probekey_t pkey;
8225 dtrace_id_t id;
8226 int match;
8227
8228 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8229 pkey.dtpk_pmatch = &dtrace_match_string;
8230 pkey.dtpk_mod = mod;
8231 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8232 pkey.dtpk_func = func;
8233 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8234 pkey.dtpk_name = name;
8235 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8236 pkey.dtpk_id = DTRACE_IDNONE;
8237
8238 lck_mtx_lock(&dtrace_lock);
8239 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
d190cdc3 8240 dtrace_probe_lookup_match, &id, NULL);
2d21ac55
A
8241 lck_mtx_unlock(&dtrace_lock);
8242
8243 ASSERT(match == 1 || match == 0);
8244 return (match ? id : 0);
8245}
8246
8247/*
8248 * Returns the probe argument associated with the specified probe.
8249 */
8250void *
8251dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8252{
8253 dtrace_probe_t *probe;
8254 void *rval = NULL;
8255
8256 lck_mtx_lock(&dtrace_lock);
8257
8258 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8259 probe->dtpr_provider == (dtrace_provider_t *)id)
8260 rval = probe->dtpr_arg;
8261
8262 lck_mtx_unlock(&dtrace_lock);
8263
8264 return (rval);
8265}
8266
8267/*
8268 * Copy a probe into a probe description.
8269 */
8270static void
8271dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8272{
8273 bzero(pdp, sizeof (dtrace_probedesc_t));
8274 pdp->dtpd_id = prp->dtpr_id;
8275
fe8ab488 8276 /* APPLE NOTE: Darwin employs size bounded string operation. */
2d21ac55
A
8277 (void) strlcpy(pdp->dtpd_provider,
8278 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
8279
8280 (void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
8281 (void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
8282 (void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
8283}
8284
8285/*
8286 * Called to indicate that a probe -- or probes -- should be provided by a
8287 * specfied provider. If the specified description is NULL, the provider will
8288 * be told to provide all of its probes. (This is done whenever a new
8289 * consumer comes along, or whenever a retained enabling is to be matched.) If
8290 * the specified description is non-NULL, the provider is given the
8291 * opportunity to dynamically provide the specified probe, allowing providers
8292 * to support the creation of probes on-the-fly. (So-called _autocreated_
8293 * probes.) If the provider is NULL, the operations will be applied to all
8294 * providers; if the provider is non-NULL the operations will only be applied
8295 * to the specified provider. The dtrace_provider_lock must be held, and the
8296 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8297 * will need to grab the dtrace_lock when it reenters the framework through
8298 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8299 */
8300static void
8301dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8302{
8303 struct modctl *ctl;
8304 int all = 0;
8305
5ba3f43e 8306 LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
8307
8308 if (prv == NULL) {
8309 all = 1;
8310 prv = dtrace_provider;
8311 }
6d2010ae 8312
2d21ac55 8313 do {
2d21ac55
A
8314 /*
8315 * First, call the blanket provide operation.
8316 */
8317 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
6d2010ae 8318
2d21ac55
A
8319 /*
8320 * Now call the per-module provide operation. We will grab
8321 * mod_lock to prevent the list from being modified. Note
8322 * that this also prevents the mod_busy bits from changing.
8323 * (mod_busy can only be changed with mod_lock held.)
8324 */
6d2010ae
A
8325 lck_mtx_lock(&mod_lock);
8326
6d2010ae
A
8327 ctl = dtrace_modctl_list;
8328 while (ctl) {
8329 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8330 ctl = ctl->mod_next;
2d21ac55 8331 }
6d2010ae
A
8332
8333 lck_mtx_unlock(&mod_lock);
2d21ac55
A
8334 } while (all && (prv = prv->dtpv_next) != NULL);
8335}
8336
8337/*
8338 * Iterate over each probe, and call the Framework-to-Provider API function
8339 * denoted by offs.
8340 */
8341static void
8342dtrace_probe_foreach(uintptr_t offs)
8343{
8344 dtrace_provider_t *prov;
8345 void (*func)(void *, dtrace_id_t, void *);
8346 dtrace_probe_t *probe;
8347 dtrace_icookie_t cookie;
8348 int i;
8349
8350 /*
8351 * We disable interrupts to walk through the probe array. This is
8352 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8353 * won't see stale data.
8354 */
8355 cookie = dtrace_interrupt_disable();
8356
8357 for (i = 0; i < dtrace_nprobes; i++) {
8358 if ((probe = dtrace_probes[i]) == NULL)
8359 continue;
8360
8361 if (probe->dtpr_ecb == NULL) {
8362 /*
8363 * This probe isn't enabled -- don't call the function.
8364 */
8365 continue;
8366 }
8367
8368 prov = probe->dtpr_provider;
8369 func = *((void(**)(void *, dtrace_id_t, void *))
8370 ((uintptr_t)&prov->dtpv_pops + offs));
8371
8372 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8373 }
8374
8375 dtrace_interrupt_enable(cookie);
8376}
8377
8378static int
d190cdc3 8379dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab, dtrace_ecbdesc_t *ep)
2d21ac55
A
8380{
8381 dtrace_probekey_t pkey;
8382 uint32_t priv;
8383 uid_t uid;
8384 zoneid_t zoneid;
8385
5ba3f43e 8386 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
8387
8388 dtrace_ecb_create_cache = NULL;
8389
8390 if (desc == NULL) {
8391 /*
8392 * If we're passed a NULL description, we're being asked to
8393 * create an ECB with a NULL probe.
8394 */
d190cdc3 8395 (void) dtrace_ecb_create_enable(NULL, enab, ep);
2d21ac55
A
8396 return (0);
8397 }
8398
8399 dtrace_probekey(desc, &pkey);
8400 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8401 &priv, &uid, &zoneid);
8402
8403 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
d190cdc3 8404 enab, ep));
2d21ac55
A
8405}
8406
8407/*
8408 * DTrace Helper Provider Functions
8409 */
8410static void
8411dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8412{
8413 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8414 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8415 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8416}
8417
8418static void
8419dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8420 const dof_provider_t *dofprov, char *strtab)
8421{
8422 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8423 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8424 dofprov->dofpv_provattr);
8425 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8426 dofprov->dofpv_modattr);
8427 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8428 dofprov->dofpv_funcattr);
8429 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8430 dofprov->dofpv_nameattr);
8431 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8432 dofprov->dofpv_argsattr);
8433}
8434
8435static void
d190cdc3 8436dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
2d21ac55
A
8437{
8438 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8439 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8440 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8441 dof_provider_t *provider;
8442 dof_probe_t *probe;
8443 uint32_t *off, *enoff;
8444 uint8_t *arg;
8445 char *strtab;
8446 uint_t i, nprobes;
8447 dtrace_helper_provdesc_t dhpv;
8448 dtrace_helper_probedesc_t dhpb;
8449 dtrace_meta_t *meta = dtrace_meta_pid;
8450 dtrace_mops_t *mops = &meta->dtm_mops;
8451 void *parg;
8452
8453 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8454 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8455 provider->dofpv_strtab * dof->dofh_secsize);
8456 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8457 provider->dofpv_probes * dof->dofh_secsize);
8458 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8459 provider->dofpv_prargs * dof->dofh_secsize);
8460 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8461 provider->dofpv_proffs * dof->dofh_secsize);
8462
8463 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8464 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8465 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8466 enoff = NULL;
8467
8468 /*
8469 * See dtrace_helper_provider_validate().
8470 */
8471 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8472 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8473 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8474 provider->dofpv_prenoffs * dof->dofh_secsize);
8475 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8476 }
8477
8478 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8479
8480 /*
8481 * Create the provider.
8482 */
8483 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8484
d190cdc3 8485 if ((parg = mops->dtms_provide_proc(meta->dtm_arg, &dhpv, p)) == NULL)
2d21ac55
A
8486 return;
8487
8488 meta->dtm_count++;
8489
8490 /*
8491 * Create the probes.
8492 */
8493 for (i = 0; i < nprobes; i++) {
8494 probe = (dof_probe_t *)(uintptr_t)(daddr +
8495 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8496
8497 dhpb.dthpb_mod = dhp->dofhp_mod;
8498 dhpb.dthpb_func = strtab + probe->dofpr_func;
8499 dhpb.dthpb_name = strtab + probe->dofpr_name;
b0d623f7 8500#if !defined(__APPLE__)
2d21ac55 8501 dhpb.dthpb_base = probe->dofpr_addr;
b0d623f7
A
8502#else
8503 dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
2d21ac55 8504#endif
b0d623f7 8505 dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
2d21ac55
A
8506 dhpb.dthpb_noffs = probe->dofpr_noffs;
8507 if (enoff != NULL) {
b0d623f7 8508 dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
2d21ac55
A
8509 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8510 } else {
8511 dhpb.dthpb_enoffs = NULL;
8512 dhpb.dthpb_nenoffs = 0;
8513 }
8514 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8515 dhpb.dthpb_nargc = probe->dofpr_nargc;
8516 dhpb.dthpb_xargc = probe->dofpr_xargc;
8517 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8518 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8519
8520 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8521 }
39037602
A
8522
8523 /*
8524 * Since we just created probes, we need to match our enablings
8525 * against those, with a precondition knowing that we have only
8526 * added probes from this provider
8527 */
8528 char *prov_name = mops->dtms_provider_name(parg);
8529 ASSERT(prov_name != NULL);
8530 dtrace_match_cond_t cond = {dtrace_cond_provider_match, (void*)prov_name};
8531
8532 dtrace_enabling_matchall_with_cond(&cond);
2d21ac55
A
8533}
8534
8535static void
d190cdc3 8536dtrace_helper_provide(dof_helper_t *dhp, proc_t *p)
2d21ac55
A
8537{
8538 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8539 dof_hdr_t *dof = (dof_hdr_t *)daddr;
b0d623f7 8540 uint32_t i;
2d21ac55 8541
5ba3f43e 8542 LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
8543
8544 for (i = 0; i < dof->dofh_secnum; i++) {
8545 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8546 dof->dofh_secoff + i * dof->dofh_secsize);
8547
8548 if (sec->dofs_type != DOF_SECT_PROVIDER)
8549 continue;
8550
d190cdc3 8551 dtrace_helper_provide_one(dhp, sec, p);
2d21ac55 8552 }
2d21ac55
A
8553}
8554
8555static void
d190cdc3 8556dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, proc_t *p)
2d21ac55
A
8557{
8558 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8559 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8560 dof_sec_t *str_sec;
8561 dof_provider_t *provider;
8562 char *strtab;
8563 dtrace_helper_provdesc_t dhpv;
8564 dtrace_meta_t *meta = dtrace_meta_pid;
8565 dtrace_mops_t *mops = &meta->dtm_mops;
8566
8567 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8568 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8569 provider->dofpv_strtab * dof->dofh_secsize);
8570
8571 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8572
8573 /*
8574 * Create the provider.
8575 */
8576 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8577
d190cdc3 8578 mops->dtms_remove_proc(meta->dtm_arg, &dhpv, p);
2d21ac55
A
8579
8580 meta->dtm_count--;
8581}
8582
8583static void
d190cdc3 8584dtrace_helper_provider_remove(dof_helper_t *dhp, proc_t *p)
2d21ac55
A
8585{
8586 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8587 dof_hdr_t *dof = (dof_hdr_t *)daddr;
b0d623f7 8588 uint32_t i;
2d21ac55 8589
5ba3f43e 8590 LCK_MTX_ASSERT(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
8591
8592 for (i = 0; i < dof->dofh_secnum; i++) {
8593 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8594 dof->dofh_secoff + i * dof->dofh_secsize);
8595
8596 if (sec->dofs_type != DOF_SECT_PROVIDER)
8597 continue;
8598
d190cdc3 8599 dtrace_helper_provider_remove_one(dhp, sec, p);
2d21ac55
A
8600 }
8601}
8602
8603/*
8604 * DTrace Meta Provider-to-Framework API Functions
8605 *
8606 * These functions implement the Meta Provider-to-Framework API, as described
8607 * in <sys/dtrace.h>.
8608 */
8609int
8610dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8611 dtrace_meta_provider_id_t *idp)
8612{
8613 dtrace_meta_t *meta;
8614 dtrace_helpers_t *help, *next;
b0d623f7 8615 uint_t i;
2d21ac55
A
8616
8617 *idp = DTRACE_METAPROVNONE;
8618
8619 /*
8620 * We strictly don't need the name, but we hold onto it for
8621 * debuggability. All hail error queues!
8622 */
8623 if (name == NULL) {
8624 cmn_err(CE_WARN, "failed to register meta-provider: "
8625 "invalid name");
8626 return (EINVAL);
8627 }
8628
8629 if (mops == NULL ||
8630 mops->dtms_create_probe == NULL ||
d190cdc3
A
8631 mops->dtms_provide_proc == NULL ||
8632 mops->dtms_remove_proc == NULL) {
2d21ac55
A
8633 cmn_err(CE_WARN, "failed to register meta-register %s: "
8634 "invalid ops", name);
8635 return (EINVAL);
8636 }
8637
8638 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8639 meta->dtm_mops = *mops;
fe8ab488
A
8640
8641 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7
A
8642 {
8643 size_t bufsize = strlen(name) + 1;
8644 meta->dtm_name = kmem_alloc(bufsize, KM_SLEEP);
8645 (void) strlcpy(meta->dtm_name, name, bufsize);
8646 }
fe8ab488 8647
2d21ac55
A
8648 meta->dtm_arg = arg;
8649
8650 lck_mtx_lock(&dtrace_meta_lock);
8651 lck_mtx_lock(&dtrace_lock);
8652
8653 if (dtrace_meta_pid != NULL) {
8654 lck_mtx_unlock(&dtrace_lock);
8655 lck_mtx_unlock(&dtrace_meta_lock);
8656 cmn_err(CE_WARN, "failed to register meta-register %s: "
8657 "user-land meta-provider exists", name);
8658 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8659 kmem_free(meta, sizeof (dtrace_meta_t));
8660 return (EINVAL);
8661 }
8662
8663 dtrace_meta_pid = meta;
8664 *idp = (dtrace_meta_provider_id_t)meta;
8665
8666 /*
8667 * If there are providers and probes ready to go, pass them
8668 * off to the new meta provider now.
8669 */
8670
8671 help = dtrace_deferred_pid;
8672 dtrace_deferred_pid = NULL;
8673
8674 lck_mtx_unlock(&dtrace_lock);
8675
8676 while (help != NULL) {
8677 for (i = 0; i < help->dthps_nprovs; i++) {
d190cdc3
A
8678 proc_t *p = proc_find(help->dthps_pid);
8679 if (p == PROC_NULL)
8680 continue;
2d21ac55 8681 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
d190cdc3
A
8682 p);
8683 proc_rele(p);
2d21ac55
A
8684 }
8685
8686 next = help->dthps_next;
8687 help->dthps_next = NULL;
8688 help->dthps_prev = NULL;
8689 help->dthps_deferred = 0;
8690 help = next;
8691 }
8692
8693 lck_mtx_unlock(&dtrace_meta_lock);
8694
8695 return (0);
8696}
8697
8698int
8699dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8700{
8701 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8702
8703 lck_mtx_lock(&dtrace_meta_lock);
8704 lck_mtx_lock(&dtrace_lock);
8705
8706 if (old == dtrace_meta_pid) {
8707 pp = &dtrace_meta_pid;
8708 } else {
8709 panic("attempt to unregister non-existent "
8710 "dtrace meta-provider %p\n", (void *)old);
8711 }
8712
8713 if (old->dtm_count != 0) {
8714 lck_mtx_unlock(&dtrace_lock);
8715 lck_mtx_unlock(&dtrace_meta_lock);
8716 return (EBUSY);
8717 }
8718
8719 *pp = NULL;
8720
8721 lck_mtx_unlock(&dtrace_lock);
8722 lck_mtx_unlock(&dtrace_meta_lock);
8723
8724 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8725 kmem_free(old, sizeof (dtrace_meta_t));
8726
8727 return (0);
8728}
8729
8730
8731/*
8732 * DTrace DIF Object Functions
8733 */
8734static int
8735dtrace_difo_err(uint_t pc, const char *format, ...)
8736{
8737 if (dtrace_err_verbose) {
8738 va_list alist;
8739
8740 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8741 va_start(alist, format);
8742 (void) vuprintf(format, alist);
8743 va_end(alist);
8744 }
8745
8746#ifdef DTRACE_ERRDEBUG
8747 dtrace_errdebug(format);
8748#endif
8749 return (1);
8750}
8751
8752/*
8753 * Validate a DTrace DIF object by checking the IR instructions. The following
8754 * rules are currently enforced by dtrace_difo_validate():
8755 *
8756 * 1. Each instruction must have a valid opcode
8757 * 2. Each register, string, variable, or subroutine reference must be valid
8758 * 3. No instruction can modify register %r0 (must be zero)
8759 * 4. All instruction reserved bits must be set to zero
8760 * 5. The last instruction must be a "ret" instruction
8761 * 6. All branch targets must reference a valid instruction _after_ the branch
8762 */
8763static int
8764dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8765 cred_t *cr)
8766{
b0d623f7
A
8767 int err = 0;
8768 uint_t i;
fe8ab488 8769
b0d623f7
A
8770 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8771 int kcheckload;
8772 uint_t pc;
39037602 8773 int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
b0d623f7
A
8774
8775 kcheckload = cr == NULL ||
8776 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
2d21ac55
A
8777
8778 dp->dtdo_destructive = 0;
8779
8780 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8781 dif_instr_t instr = dp->dtdo_buf[pc];
8782
8783 uint_t r1 = DIF_INSTR_R1(instr);
8784 uint_t r2 = DIF_INSTR_R2(instr);
8785 uint_t rd = DIF_INSTR_RD(instr);
8786 uint_t rs = DIF_INSTR_RS(instr);
8787 uint_t label = DIF_INSTR_LABEL(instr);
8788 uint_t v = DIF_INSTR_VAR(instr);
8789 uint_t subr = DIF_INSTR_SUBR(instr);
8790 uint_t type = DIF_INSTR_TYPE(instr);
8791 uint_t op = DIF_INSTR_OP(instr);
8792
8793 switch (op) {
8794 case DIF_OP_OR:
8795 case DIF_OP_XOR:
8796 case DIF_OP_AND:
8797 case DIF_OP_SLL:
8798 case DIF_OP_SRL:
8799 case DIF_OP_SRA:
8800 case DIF_OP_SUB:
8801 case DIF_OP_ADD:
8802 case DIF_OP_MUL:
8803 case DIF_OP_SDIV:
8804 case DIF_OP_UDIV:
8805 case DIF_OP_SREM:
8806 case DIF_OP_UREM:
8807 case DIF_OP_COPYS:
8808 if (r1 >= nregs)
8809 err += efunc(pc, "invalid register %u\n", r1);
8810 if (r2 >= nregs)
8811 err += efunc(pc, "invalid register %u\n", r2);
8812 if (rd >= nregs)
8813 err += efunc(pc, "invalid register %u\n", rd);
8814 if (rd == 0)
8815 err += efunc(pc, "cannot write to %r0\n");
8816 break;
8817 case DIF_OP_NOT:
8818 case DIF_OP_MOV:
8819 case DIF_OP_ALLOCS:
8820 if (r1 >= nregs)
8821 err += efunc(pc, "invalid register %u\n", r1);
8822 if (r2 != 0)
8823 err += efunc(pc, "non-zero reserved bits\n");
8824 if (rd >= nregs)
8825 err += efunc(pc, "invalid register %u\n", rd);
8826 if (rd == 0)
8827 err += efunc(pc, "cannot write to %r0\n");
8828 break;
8829 case DIF_OP_LDSB:
8830 case DIF_OP_LDSH:
8831 case DIF_OP_LDSW:
8832 case DIF_OP_LDUB:
8833 case DIF_OP_LDUH:
8834 case DIF_OP_LDUW:
8835 case DIF_OP_LDX:
8836 if (r1 >= nregs)
8837 err += efunc(pc, "invalid register %u\n", r1);
8838 if (r2 != 0)
8839 err += efunc(pc, "non-zero reserved bits\n");
8840 if (rd >= nregs)
8841 err += efunc(pc, "invalid register %u\n", rd);
8842 if (rd == 0)
8843 err += efunc(pc, "cannot write to %r0\n");
b0d623f7 8844 if (kcheckload)
2d21ac55
A
8845 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8846 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8847 break;
8848 case DIF_OP_RLDSB:
8849 case DIF_OP_RLDSH:
8850 case DIF_OP_RLDSW:
8851 case DIF_OP_RLDUB:
8852 case DIF_OP_RLDUH:
8853 case DIF_OP_RLDUW:
8854 case DIF_OP_RLDX:
8855 if (r1 >= nregs)
8856 err += efunc(pc, "invalid register %u\n", r1);
8857 if (r2 != 0)
8858 err += efunc(pc, "non-zero reserved bits\n");
8859 if (rd >= nregs)
8860 err += efunc(pc, "invalid register %u\n", rd);
8861 if (rd == 0)
8862 err += efunc(pc, "cannot write to %r0\n");
8863 break;
8864 case DIF_OP_ULDSB:
8865 case DIF_OP_ULDSH:
8866 case DIF_OP_ULDSW:
8867 case DIF_OP_ULDUB:
8868 case DIF_OP_ULDUH:
8869 case DIF_OP_ULDUW:
8870 case DIF_OP_ULDX:
8871 if (r1 >= nregs)
8872 err += efunc(pc, "invalid register %u\n", r1);
8873 if (r2 != 0)
8874 err += efunc(pc, "non-zero reserved bits\n");
8875 if (rd >= nregs)
8876 err += efunc(pc, "invalid register %u\n", rd);
8877 if (rd == 0)
8878 err += efunc(pc, "cannot write to %r0\n");
8879 break;
8880 case DIF_OP_STB:
8881 case DIF_OP_STH:
8882 case DIF_OP_STW:
8883 case DIF_OP_STX:
8884 if (r1 >= nregs)
8885 err += efunc(pc, "invalid register %u\n", r1);
8886 if (r2 != 0)
8887 err += efunc(pc, "non-zero reserved bits\n");
8888 if (rd >= nregs)
8889 err += efunc(pc, "invalid register %u\n", rd);
8890 if (rd == 0)
8891 err += efunc(pc, "cannot write to 0 address\n");
8892 break;
8893 case DIF_OP_CMP:
8894 case DIF_OP_SCMP:
8895 if (r1 >= nregs)
8896 err += efunc(pc, "invalid register %u\n", r1);
8897 if (r2 >= nregs)
8898 err += efunc(pc, "invalid register %u\n", r2);
8899 if (rd != 0)
8900 err += efunc(pc, "non-zero reserved bits\n");
8901 break;
8902 case DIF_OP_TST:
8903 if (r1 >= nregs)
8904 err += efunc(pc, "invalid register %u\n", r1);
8905 if (r2 != 0 || rd != 0)
8906 err += efunc(pc, "non-zero reserved bits\n");
8907 break;
8908 case DIF_OP_BA:
8909 case DIF_OP_BE:
8910 case DIF_OP_BNE:
8911 case DIF_OP_BG:
8912 case DIF_OP_BGU:
8913 case DIF_OP_BGE:
8914 case DIF_OP_BGEU:
8915 case DIF_OP_BL:
8916 case DIF_OP_BLU:
8917 case DIF_OP_BLE:
8918 case DIF_OP_BLEU:
8919 if (label >= dp->dtdo_len) {
8920 err += efunc(pc, "invalid branch target %u\n",
8921 label);
8922 }
8923 if (label <= pc) {
8924 err += efunc(pc, "backward branch to %u\n",
8925 label);
8926 }
8927 break;
8928 case DIF_OP_RET:
8929 if (r1 != 0 || r2 != 0)
8930 err += efunc(pc, "non-zero reserved bits\n");
8931 if (rd >= nregs)
8932 err += efunc(pc, "invalid register %u\n", rd);
8933 break;
8934 case DIF_OP_NOP:
8935 case DIF_OP_POPTS:
8936 case DIF_OP_FLUSHTS:
8937 if (r1 != 0 || r2 != 0 || rd != 0)
8938 err += efunc(pc, "non-zero reserved bits\n");
8939 break;
8940 case DIF_OP_SETX:
8941 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8942 err += efunc(pc, "invalid integer ref %u\n",
8943 DIF_INSTR_INTEGER(instr));
8944 }
8945 if (rd >= nregs)
8946 err += efunc(pc, "invalid register %u\n", rd);
8947 if (rd == 0)
8948 err += efunc(pc, "cannot write to %r0\n");
8949 break;
8950 case DIF_OP_SETS:
8951 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8952 err += efunc(pc, "invalid string ref %u\n",
8953 DIF_INSTR_STRING(instr));
8954 }
8955 if (rd >= nregs)
8956 err += efunc(pc, "invalid register %u\n", rd);
8957 if (rd == 0)
8958 err += efunc(pc, "cannot write to %r0\n");
8959 break;
8960 case DIF_OP_LDGA:
8961 case DIF_OP_LDTA:
8962 if (r1 > DIF_VAR_ARRAY_MAX)
8963 err += efunc(pc, "invalid array %u\n", r1);
8964 if (r2 >= nregs)
8965 err += efunc(pc, "invalid register %u\n", r2);
8966 if (rd >= nregs)
8967 err += efunc(pc, "invalid register %u\n", rd);
8968 if (rd == 0)
8969 err += efunc(pc, "cannot write to %r0\n");
8970 break;
8971 case DIF_OP_LDGS:
8972 case DIF_OP_LDTS:
8973 case DIF_OP_LDLS:
8974 case DIF_OP_LDGAA:
8975 case DIF_OP_LDTAA:
8976 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8977 err += efunc(pc, "invalid variable %u\n", v);
8978 if (rd >= nregs)
8979 err += efunc(pc, "invalid register %u\n", rd);
8980 if (rd == 0)
8981 err += efunc(pc, "cannot write to %r0\n");
8982 break;
8983 case DIF_OP_STGS:
8984 case DIF_OP_STTS:
8985 case DIF_OP_STLS:
8986 case DIF_OP_STGAA:
8987 case DIF_OP_STTAA:
8988 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8989 err += efunc(pc, "invalid variable %u\n", v);
8990 if (rs >= nregs)
8991 err += efunc(pc, "invalid register %u\n", rd);
8992 break;
8993 case DIF_OP_CALL:
39037602
A
8994 if (subr > DIF_SUBR_MAX &&
8995 !(subr >= DIF_SUBR_APPLE_MIN && subr <= DIF_SUBR_APPLE_MAX))
2d21ac55
A
8996 err += efunc(pc, "invalid subr %u\n", subr);
8997 if (rd >= nregs)
8998 err += efunc(pc, "invalid register %u\n", rd);
8999 if (rd == 0)
9000 err += efunc(pc, "cannot write to %r0\n");
9001
9002 if (subr == DIF_SUBR_COPYOUT ||
39037602
A
9003 subr == DIF_SUBR_COPYOUTSTR ||
9004 subr == DIF_SUBR_KDEBUG_TRACE ||
9005 subr == DIF_SUBR_KDEBUG_TRACE_STRING) {
2d21ac55
A
9006 dp->dtdo_destructive = 1;
9007 }
9008 break;
9009 case DIF_OP_PUSHTR:
9010 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9011 err += efunc(pc, "invalid ref type %u\n", type);
9012 if (r2 >= nregs)
9013 err += efunc(pc, "invalid register %u\n", r2);
9014 if (rs >= nregs)
9015 err += efunc(pc, "invalid register %u\n", rs);
9016 break;
9017 case DIF_OP_PUSHTV:
9018 if (type != DIF_TYPE_CTF)
9019 err += efunc(pc, "invalid val type %u\n", type);
9020 if (r2 >= nregs)
9021 err += efunc(pc, "invalid register %u\n", r2);
9022 if (rs >= nregs)
9023 err += efunc(pc, "invalid register %u\n", rs);
9024 break;
9025 default:
9026 err += efunc(pc, "invalid opcode %u\n",
9027 DIF_INSTR_OP(instr));
9028 }
9029 }
9030
9031 if (dp->dtdo_len != 0 &&
9032 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9033 err += efunc(dp->dtdo_len - 1,
9034 "expected 'ret' as last DIF instruction\n");
9035 }
9036
3e170ce0 9037 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
2d21ac55
A
9038 /*
9039 * If we're not returning by reference, the size must be either
9040 * 0 or the size of one of the base types.
9041 */
9042 switch (dp->dtdo_rtype.dtdt_size) {
9043 case 0:
9044 case sizeof (uint8_t):
9045 case sizeof (uint16_t):
9046 case sizeof (uint32_t):
9047 case sizeof (uint64_t):
9048 break;
9049
9050 default:
6d2010ae 9051 err += efunc(dp->dtdo_len - 1, "bad return size\n");
2d21ac55
A
9052 }
9053 }
9054
9055 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9056 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9057 dtrace_diftype_t *vt, *et;
b0d623f7
A
9058 uint_t id;
9059 int ndx;
2d21ac55
A
9060
9061 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9062 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9063 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9064 err += efunc(i, "unrecognized variable scope %d\n",
9065 v->dtdv_scope);
9066 break;
9067 }
9068
9069 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9070 v->dtdv_kind != DIFV_KIND_SCALAR) {
9071 err += efunc(i, "unrecognized variable type %d\n",
9072 v->dtdv_kind);
9073 break;
9074 }
9075
9076 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9077 err += efunc(i, "%d exceeds variable id limit\n", id);
9078 break;
9079 }
9080
9081 if (id < DIF_VAR_OTHER_UBASE)
9082 continue;
9083
9084 /*
9085 * For user-defined variables, we need to check that this
9086 * definition is identical to any previous definition that we
9087 * encountered.
9088 */
9089 ndx = id - DIF_VAR_OTHER_UBASE;
9090
9091 switch (v->dtdv_scope) {
9092 case DIFV_SCOPE_GLOBAL:
39037602
A
9093 if (maxglobal == -1 || ndx > maxglobal)
9094 maxglobal = ndx;
9095
2d21ac55
A
9096 if (ndx < vstate->dtvs_nglobals) {
9097 dtrace_statvar_t *svar;
9098
9099 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9100 existing = &svar->dtsv_var;
9101 }
9102
9103 break;
9104
9105 case DIFV_SCOPE_THREAD:
39037602
A
9106 if (maxtlocal == -1 || ndx > maxtlocal)
9107 maxtlocal = ndx;
9108
2d21ac55
A
9109 if (ndx < vstate->dtvs_ntlocals)
9110 existing = &vstate->dtvs_tlocals[ndx];
9111 break;
9112
9113 case DIFV_SCOPE_LOCAL:
39037602
A
9114 if (maxlocal == -1 || ndx > maxlocal)
9115 maxlocal = ndx;
2d21ac55
A
9116 if (ndx < vstate->dtvs_nlocals) {
9117 dtrace_statvar_t *svar;
9118
9119 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9120 existing = &svar->dtsv_var;
9121 }
9122
9123 break;
9124 }
9125
9126 vt = &v->dtdv_type;
9127
9128 if (vt->dtdt_flags & DIF_TF_BYREF) {
9129 if (vt->dtdt_size == 0) {
9130 err += efunc(i, "zero-sized variable\n");
9131 break;
9132 }
9133
ecc0ceb4
A
9134 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9135 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9136 vt->dtdt_size > dtrace_statvar_maxsize) {
9137 err += efunc(i, "oversized by-ref static\n");
2d21ac55
A
9138 break;
9139 }
9140 }
9141
9142 if (existing == NULL || existing->dtdv_id == 0)
9143 continue;
9144
9145 ASSERT(existing->dtdv_id == v->dtdv_id);
9146 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9147
9148 if (existing->dtdv_kind != v->dtdv_kind)
9149 err += efunc(i, "%d changed variable kind\n", id);
9150
9151 et = &existing->dtdv_type;
9152
9153 if (vt->dtdt_flags != et->dtdt_flags) {
9154 err += efunc(i, "%d changed variable type flags\n", id);
9155 break;
9156 }
9157
9158 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9159 err += efunc(i, "%d changed variable type size\n", id);
9160 break;
9161 }
9162 }
9163
39037602
A
9164 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9165 dif_instr_t instr = dp->dtdo_buf[pc];
9166
9167 uint_t v = DIF_INSTR_VAR(instr);
9168 uint_t op = DIF_INSTR_OP(instr);
9169
9170 switch (op) {
9171 case DIF_OP_LDGS:
9172 case DIF_OP_LDGAA:
9173 case DIF_OP_STGS:
9174 case DIF_OP_STGAA:
9175 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxglobal))
9176 err += efunc(pc, "invalid variable %u\n", v);
9177 break;
9178 case DIF_OP_LDTS:
9179 case DIF_OP_LDTAA:
9180 case DIF_OP_STTS:
9181 case DIF_OP_STTAA:
9182 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxtlocal))
9183 err += efunc(pc, "invalid variable %u\n", v);
9184 break;
9185 case DIF_OP_LDLS:
9186 case DIF_OP_STLS:
9187 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxlocal))
9188 err += efunc(pc, "invalid variable %u\n", v);
9189 break;
9190 default:
9191 break;
9192 }
9193 }
9194
2d21ac55
A
9195 return (err);
9196}
9197
9198/*
9199 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9200 * are much more constrained than normal DIFOs. Specifically, they may
9201 * not:
9202 *
9203 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9204 * miscellaneous string routines
9205 * 2. Access DTrace variables other than the args[] array, and the
9206 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9207 * 3. Have thread-local variables.
9208 * 4. Have dynamic variables.
9209 */
9210static int
9211dtrace_difo_validate_helper(dtrace_difo_t *dp)
9212{
9213 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9214 int err = 0;
9215 uint_t pc;
9216
9217 for (pc = 0; pc < dp->dtdo_len; pc++) {
9218 dif_instr_t instr = dp->dtdo_buf[pc];
9219
9220 uint_t v = DIF_INSTR_VAR(instr);
9221 uint_t subr = DIF_INSTR_SUBR(instr);
9222 uint_t op = DIF_INSTR_OP(instr);
9223
9224 switch (op) {
9225 case DIF_OP_OR:
9226 case DIF_OP_XOR:
9227 case DIF_OP_AND:
9228 case DIF_OP_SLL:
9229 case DIF_OP_SRL:
9230 case DIF_OP_SRA:
9231 case DIF_OP_SUB:
9232 case DIF_OP_ADD:
9233 case DIF_OP_MUL:
9234 case DIF_OP_SDIV:
9235 case DIF_OP_UDIV:
9236 case DIF_OP_SREM:
9237 case DIF_OP_UREM:
9238 case DIF_OP_COPYS:
9239 case DIF_OP_NOT:
9240 case DIF_OP_MOV:
9241 case DIF_OP_RLDSB:
9242 case DIF_OP_RLDSH:
9243 case DIF_OP_RLDSW:
9244 case DIF_OP_RLDUB:
9245 case DIF_OP_RLDUH:
9246 case DIF_OP_RLDUW:
9247 case DIF_OP_RLDX:
9248 case DIF_OP_ULDSB:
9249 case DIF_OP_ULDSH:
9250 case DIF_OP_ULDSW:
9251 case DIF_OP_ULDUB:
9252 case DIF_OP_ULDUH:
9253 case DIF_OP_ULDUW:
9254 case DIF_OP_ULDX:
9255 case DIF_OP_STB:
9256 case DIF_OP_STH:
9257 case DIF_OP_STW:
9258 case DIF_OP_STX:
9259 case DIF_OP_ALLOCS:
9260 case DIF_OP_CMP:
9261 case DIF_OP_SCMP:
9262 case DIF_OP_TST:
9263 case DIF_OP_BA:
9264 case DIF_OP_BE:
9265 case DIF_OP_BNE:
9266 case DIF_OP_BG:
9267 case DIF_OP_BGU:
9268 case DIF_OP_BGE:
9269 case DIF_OP_BGEU:
9270 case DIF_OP_BL:
9271 case DIF_OP_BLU:
9272 case DIF_OP_BLE:
9273 case DIF_OP_BLEU:
9274 case DIF_OP_RET:
9275 case DIF_OP_NOP:
9276 case DIF_OP_POPTS:
9277 case DIF_OP_FLUSHTS:
9278 case DIF_OP_SETX:
9279 case DIF_OP_SETS:
9280 case DIF_OP_LDGA:
9281 case DIF_OP_LDLS:
9282 case DIF_OP_STGS:
9283 case DIF_OP_STLS:
9284 case DIF_OP_PUSHTR:
9285 case DIF_OP_PUSHTV:
9286 break;
9287
9288 case DIF_OP_LDGS:
9289 if (v >= DIF_VAR_OTHER_UBASE)
9290 break;
9291
9292 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9293 break;
9294
9295 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9296 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9297 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9298 v == DIF_VAR_UID || v == DIF_VAR_GID)
9299 break;
9300
9301 err += efunc(pc, "illegal variable %u\n", v);
9302 break;
9303
9304 case DIF_OP_LDTA:
9305 case DIF_OP_LDTS:
9306 case DIF_OP_LDGAA:
9307 case DIF_OP_LDTAA:
9308 err += efunc(pc, "illegal dynamic variable load\n");
9309 break;
9310
9311 case DIF_OP_STTS:
9312 case DIF_OP_STGAA:
9313 case DIF_OP_STTAA:
9314 err += efunc(pc, "illegal dynamic variable store\n");
9315 break;
9316
9317 case DIF_OP_CALL:
9318 if (subr == DIF_SUBR_ALLOCA ||
9319 subr == DIF_SUBR_BCOPY ||
9320 subr == DIF_SUBR_COPYIN ||
9321 subr == DIF_SUBR_COPYINTO ||
9322 subr == DIF_SUBR_COPYINSTR ||
9323 subr == DIF_SUBR_INDEX ||
b0d623f7
A
9324 subr == DIF_SUBR_INET_NTOA ||
9325 subr == DIF_SUBR_INET_NTOA6 ||
9326 subr == DIF_SUBR_INET_NTOP ||
2d21ac55
A
9327 subr == DIF_SUBR_LLTOSTR ||
9328 subr == DIF_SUBR_RINDEX ||
9329 subr == DIF_SUBR_STRCHR ||
9330 subr == DIF_SUBR_STRJOIN ||
9331 subr == DIF_SUBR_STRRCHR ||
9332 subr == DIF_SUBR_STRSTR ||
39037602
A
9333 subr == DIF_SUBR_KDEBUG_TRACE ||
9334 subr == DIF_SUBR_KDEBUG_TRACE_STRING ||
b0d623f7
A
9335 subr == DIF_SUBR_HTONS ||
9336 subr == DIF_SUBR_HTONL ||
9337 subr == DIF_SUBR_HTONLL ||
9338 subr == DIF_SUBR_NTOHS ||
9339 subr == DIF_SUBR_NTOHL ||
9340 subr == DIF_SUBR_NTOHLL)
2d21ac55
A
9341 break;
9342
9343 err += efunc(pc, "invalid subr %u\n", subr);
9344 break;
9345
9346 default:
9347 err += efunc(pc, "invalid opcode %u\n",
9348 DIF_INSTR_OP(instr));
9349 }
9350 }
9351
9352 return (err);
9353}
9354
9355/*
9356 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9357 * basis; 0 if not.
9358 */
9359static int
9360dtrace_difo_cacheable(dtrace_difo_t *dp)
9361{
b0d623f7 9362 uint_t i;
2d21ac55
A
9363
9364 if (dp == NULL)
9365 return (0);
9366
9367 for (i = 0; i < dp->dtdo_varlen; i++) {
9368 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9369
9370 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9371 continue;
9372
9373 switch (v->dtdv_id) {
9374 case DIF_VAR_CURTHREAD:
9375 case DIF_VAR_PID:
9376 case DIF_VAR_TID:
9377 case DIF_VAR_EXECNAME:
9378 case DIF_VAR_ZONENAME:
9379 break;
9380
9381 default:
9382 return (0);
9383 }
9384 }
9385
9386 /*
9387 * This DIF object may be cacheable. Now we need to look for any
9388 * array loading instructions, any memory loading instructions, or
9389 * any stores to thread-local variables.
9390 */
9391 for (i = 0; i < dp->dtdo_len; i++) {
9392 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9393
9394 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9395 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9396 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9397 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9398 return (0);
9399 }
9400
9401 return (1);
9402}
9403
9404static void
9405dtrace_difo_hold(dtrace_difo_t *dp)
9406{
b0d623f7 9407 uint_t i;
2d21ac55 9408
5ba3f43e 9409 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9410
9411 dp->dtdo_refcnt++;
9412 ASSERT(dp->dtdo_refcnt != 0);
9413
9414 /*
9415 * We need to check this DIF object for references to the variable
9416 * DIF_VAR_VTIMESTAMP.
9417 */
9418 for (i = 0; i < dp->dtdo_varlen; i++) {
9419 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9420
9421 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9422 continue;
9423
9424 if (dtrace_vtime_references++ == 0)
9425 dtrace_vtime_enable();
9426 }
9427}
9428
9429/*
9430 * This routine calculates the dynamic variable chunksize for a given DIF
9431 * object. The calculation is not fool-proof, and can probably be tricked by
9432 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9433 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9434 * if a dynamic variable size exceeds the chunksize.
9435 */
9436static void
9437dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9438{
b0d623f7 9439 uint64_t sval = 0;
2d21ac55
A
9440 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9441 const dif_instr_t *text = dp->dtdo_buf;
9442 uint_t pc, srd = 0;
9443 uint_t ttop = 0;
9444 size_t size, ksize;
9445 uint_t id, i;
9446
9447 for (pc = 0; pc < dp->dtdo_len; pc++) {
9448 dif_instr_t instr = text[pc];
9449 uint_t op = DIF_INSTR_OP(instr);
9450 uint_t rd = DIF_INSTR_RD(instr);
9451 uint_t r1 = DIF_INSTR_R1(instr);
9452 uint_t nkeys = 0;
9453 uchar_t scope;
9454
9455 dtrace_key_t *key = tupregs;
9456
9457 switch (op) {
9458 case DIF_OP_SETX:
9459 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9460 srd = rd;
9461 continue;
9462
9463 case DIF_OP_STTS:
9464 key = &tupregs[DIF_DTR_NREGS];
9465 key[0].dttk_size = 0;
9466 key[1].dttk_size = 0;
9467 nkeys = 2;
9468 scope = DIFV_SCOPE_THREAD;
9469 break;
9470
9471 case DIF_OP_STGAA:
9472 case DIF_OP_STTAA:
9473 nkeys = ttop;
9474
9475 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9476 key[nkeys++].dttk_size = 0;
9477
9478 key[nkeys++].dttk_size = 0;
9479
9480 if (op == DIF_OP_STTAA) {
9481 scope = DIFV_SCOPE_THREAD;
9482 } else {
9483 scope = DIFV_SCOPE_GLOBAL;
9484 }
9485
9486 break;
9487
9488 case DIF_OP_PUSHTR:
9489 if (ttop == DIF_DTR_NREGS)
9490 return;
9491
9492 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9493 /*
9494 * If the register for the size of the "pushtr"
9495 * is %r0 (or the value is 0) and the type is
9496 * a string, we'll use the system-wide default
9497 * string size.
9498 */
9499 tupregs[ttop++].dttk_size =
9500 dtrace_strsize_default;
9501 } else {
9502 if (srd == 0)
9503 return;
9504
ecc0ceb4
A
9505 if (sval > LONG_MAX)
9506 return;
9507
2d21ac55
A
9508 tupregs[ttop++].dttk_size = sval;
9509 }
9510
9511 break;
9512
9513 case DIF_OP_PUSHTV:
9514 if (ttop == DIF_DTR_NREGS)
9515 return;
9516
9517 tupregs[ttop++].dttk_size = 0;
9518 break;
9519
9520 case DIF_OP_FLUSHTS:
9521 ttop = 0;
9522 break;
9523
9524 case DIF_OP_POPTS:
9525 if (ttop != 0)
9526 ttop--;
9527 break;
9528 }
9529
9530 sval = 0;
9531 srd = 0;
9532
9533 if (nkeys == 0)
9534 continue;
9535
9536 /*
9537 * We have a dynamic variable allocation; calculate its size.
9538 */
9539 for (ksize = 0, i = 0; i < nkeys; i++)
9540 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9541
9542 size = sizeof (dtrace_dynvar_t);
9543 size += sizeof (dtrace_key_t) * (nkeys - 1);
9544 size += ksize;
9545
9546 /*
9547 * Now we need to determine the size of the stored data.
9548 */
9549 id = DIF_INSTR_VAR(instr);
9550
9551 for (i = 0; i < dp->dtdo_varlen; i++) {
9552 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9553
9554 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9555 size += v->dtdv_type.dtdt_size;
9556 break;
9557 }
9558 }
9559
9560 if (i == dp->dtdo_varlen)
9561 return;
9562
9563 /*
9564 * We have the size. If this is larger than the chunk size
9565 * for our dynamic variable state, reset the chunk size.
9566 */
9567 size = P2ROUNDUP(size, sizeof (uint64_t));
9568
ecc0ceb4
A
9569 /*
9570 * Before setting the chunk size, check that we're not going
9571 * to set it to a negative value...
9572 */
9573 if (size > LONG_MAX)
9574 return;
9575
9576 /*
9577 * ...and make certain that we didn't badly overflow.
9578 */
9579 if (size < ksize || size < sizeof (dtrace_dynvar_t))
9580 return;
9581
2d21ac55
A
9582 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9583 vstate->dtvs_dynvars.dtds_chunksize = size;
9584 }
9585}
9586
9587static void
9588dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9589{
b0d623f7
A
9590 int oldsvars, osz, nsz, otlocals, ntlocals;
9591 uint_t i, id;
2d21ac55 9592
5ba3f43e 9593 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9594 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9595
9596 for (i = 0; i < dp->dtdo_varlen; i++) {
9597 dtrace_difv_t *v = &dp->dtdo_vartab[i];
b0d623f7
A
9598 dtrace_statvar_t *svar;
9599 dtrace_statvar_t ***svarp = NULL;
2d21ac55
A
9600 size_t dsize = 0;
9601 uint8_t scope = v->dtdv_scope;
b0d623f7 9602 int *np = (int *)NULL;
2d21ac55
A
9603
9604 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9605 continue;
9606
9607 id -= DIF_VAR_OTHER_UBASE;
9608
9609 switch (scope) {
9610 case DIFV_SCOPE_THREAD:
b0d623f7 9611 while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
2d21ac55
A
9612 dtrace_difv_t *tlocals;
9613
9614 if ((ntlocals = (otlocals << 1)) == 0)
9615 ntlocals = 1;
9616
9617 osz = otlocals * sizeof (dtrace_difv_t);
9618 nsz = ntlocals * sizeof (dtrace_difv_t);
9619
9620 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9621
9622 if (osz != 0) {
9623 bcopy(vstate->dtvs_tlocals,
9624 tlocals, osz);
9625 kmem_free(vstate->dtvs_tlocals, osz);
9626 }
9627
9628 vstate->dtvs_tlocals = tlocals;
9629 vstate->dtvs_ntlocals = ntlocals;
9630 }
9631
9632 vstate->dtvs_tlocals[id] = *v;
9633 continue;
9634
9635 case DIFV_SCOPE_LOCAL:
9636 np = &vstate->dtvs_nlocals;
9637 svarp = &vstate->dtvs_locals;
9638
9639 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
c910b4d9 9640 dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
2d21ac55
A
9641 sizeof (uint64_t));
9642 else
c910b4d9 9643 dsize = (int)NCPU * sizeof (uint64_t);
2d21ac55
A
9644
9645 break;
9646
9647 case DIFV_SCOPE_GLOBAL:
9648 np = &vstate->dtvs_nglobals;
9649 svarp = &vstate->dtvs_globals;
9650
9651 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9652 dsize = v->dtdv_type.dtdt_size +
9653 sizeof (uint64_t);
9654
9655 break;
9656
9657 default:
9658 ASSERT(0);
9659 }
9660
b0d623f7 9661 while (id >= (uint_t)(oldsvars = *np)) {
2d21ac55
A
9662 dtrace_statvar_t **statics;
9663 int newsvars, oldsize, newsize;
9664
9665 if ((newsvars = (oldsvars << 1)) == 0)
9666 newsvars = 1;
9667
9668 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9669 newsize = newsvars * sizeof (dtrace_statvar_t *);
9670
9671 statics = kmem_zalloc(newsize, KM_SLEEP);
9672
9673 if (oldsize != 0) {
9674 bcopy(*svarp, statics, oldsize);
9675 kmem_free(*svarp, oldsize);
9676 }
9677
9678 *svarp = statics;
9679 *np = newsvars;
9680 }
9681
9682 if ((svar = (*svarp)[id]) == NULL) {
9683 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9684 svar->dtsv_var = *v;
9685
9686 if ((svar->dtsv_size = dsize) != 0) {
9687 svar->dtsv_data = (uint64_t)(uintptr_t)
9688 kmem_zalloc(dsize, KM_SLEEP);
9689 }
9690
9691 (*svarp)[id] = svar;
9692 }
9693
9694 svar->dtsv_refcnt++;
9695 }
9696
9697 dtrace_difo_chunksize(dp, vstate);
9698 dtrace_difo_hold(dp);
9699}
9700
9701static dtrace_difo_t *
9702dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9703{
9704 dtrace_difo_t *new;
9705 size_t sz;
9706
9707 ASSERT(dp->dtdo_buf != NULL);
9708 ASSERT(dp->dtdo_refcnt != 0);
9709
9710 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9711
9712 ASSERT(dp->dtdo_buf != NULL);
9713 sz = dp->dtdo_len * sizeof (dif_instr_t);
9714 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9715 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9716 new->dtdo_len = dp->dtdo_len;
9717
9718 if (dp->dtdo_strtab != NULL) {
9719 ASSERT(dp->dtdo_strlen != 0);
9720 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9721 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9722 new->dtdo_strlen = dp->dtdo_strlen;
9723 }
9724
9725 if (dp->dtdo_inttab != NULL) {
9726 ASSERT(dp->dtdo_intlen != 0);
9727 sz = dp->dtdo_intlen * sizeof (uint64_t);
9728 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9729 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9730 new->dtdo_intlen = dp->dtdo_intlen;
9731 }
9732
9733 if (dp->dtdo_vartab != NULL) {
9734 ASSERT(dp->dtdo_varlen != 0);
9735 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9736 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9737 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9738 new->dtdo_varlen = dp->dtdo_varlen;
9739 }
9740
9741 dtrace_difo_init(new, vstate);
9742 return (new);
9743}
9744
9745static void
9746dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9747{
b0d623f7 9748 uint_t i;
2d21ac55
A
9749
9750 ASSERT(dp->dtdo_refcnt == 0);
9751
9752 for (i = 0; i < dp->dtdo_varlen; i++) {
9753 dtrace_difv_t *v = &dp->dtdo_vartab[i];
b0d623f7
A
9754 dtrace_statvar_t *svar;
9755 dtrace_statvar_t **svarp = NULL;
9756 uint_t id;
9757 uint8_t scope = v->dtdv_scope;
9758 int *np = NULL;
2d21ac55
A
9759
9760 switch (scope) {
9761 case DIFV_SCOPE_THREAD:
9762 continue;
9763
9764 case DIFV_SCOPE_LOCAL:
9765 np = &vstate->dtvs_nlocals;
9766 svarp = vstate->dtvs_locals;
9767 break;
9768
9769 case DIFV_SCOPE_GLOBAL:
9770 np = &vstate->dtvs_nglobals;
9771 svarp = vstate->dtvs_globals;
9772 break;
9773
9774 default:
9775 ASSERT(0);
9776 }
9777
9778 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9779 continue;
9780
9781 id -= DIF_VAR_OTHER_UBASE;
b0d623f7 9782
b0d623f7 9783 ASSERT(id < (uint_t)*np);
2d21ac55
A
9784
9785 svar = svarp[id];
9786 ASSERT(svar != NULL);
9787 ASSERT(svar->dtsv_refcnt > 0);
9788
9789 if (--svar->dtsv_refcnt > 0)
9790 continue;
9791
9792 if (svar->dtsv_size != 0) {
fe8ab488 9793 ASSERT(svar->dtsv_data != 0);
2d21ac55
A
9794 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9795 svar->dtsv_size);
9796 }
9797
9798 kmem_free(svar, sizeof (dtrace_statvar_t));
9799 svarp[id] = NULL;
9800 }
9801
9802 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9803 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9804 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9805 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9806
9807 kmem_free(dp, sizeof (dtrace_difo_t));
9808}
9809
9810static void
9811dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9812{
b0d623f7 9813 uint_t i;
2d21ac55 9814
5ba3f43e 9815 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9816 ASSERT(dp->dtdo_refcnt != 0);
9817
9818 for (i = 0; i < dp->dtdo_varlen; i++) {
9819 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9820
9821 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9822 continue;
9823
9824 ASSERT(dtrace_vtime_references > 0);
9825 if (--dtrace_vtime_references == 0)
9826 dtrace_vtime_disable();
9827 }
9828
9829 if (--dp->dtdo_refcnt == 0)
9830 dtrace_difo_destroy(dp, vstate);
9831}
9832
9833/*
9834 * DTrace Format Functions
9835 */
9836static uint16_t
9837dtrace_format_add(dtrace_state_t *state, char *str)
9838{
9839 char *fmt, **new;
9840 uint16_t ndx, len = strlen(str) + 1;
9841
9842 fmt = kmem_zalloc(len, KM_SLEEP);
9843 bcopy(str, fmt, len);
9844
9845 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9846 if (state->dts_formats[ndx] == NULL) {
9847 state->dts_formats[ndx] = fmt;
9848 return (ndx + 1);
9849 }
9850 }
9851
9852 if (state->dts_nformats == USHRT_MAX) {
9853 /*
9854 * This is only likely if a denial-of-service attack is being
9855 * attempted. As such, it's okay to fail silently here.
9856 */
9857 kmem_free(fmt, len);
9858 return (0);
9859 }
9860
9861 /*
9862 * For simplicity, we always resize the formats array to be exactly the
9863 * number of formats.
9864 */
9865 ndx = state->dts_nformats++;
9866 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9867
9868 if (state->dts_formats != NULL) {
9869 ASSERT(ndx != 0);
9870 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9871 kmem_free(state->dts_formats, ndx * sizeof (char *));
9872 }
9873
9874 state->dts_formats = new;
9875 state->dts_formats[ndx] = fmt;
9876
9877 return (ndx + 1);
9878}
9879
9880static void
9881dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9882{
9883 char *fmt;
9884
9885 ASSERT(state->dts_formats != NULL);
9886 ASSERT(format <= state->dts_nformats);
9887 ASSERT(state->dts_formats[format - 1] != NULL);
9888
9889 fmt = state->dts_formats[format - 1];
9890 kmem_free(fmt, strlen(fmt) + 1);
9891 state->dts_formats[format - 1] = NULL;
9892}
9893
9894static void
9895dtrace_format_destroy(dtrace_state_t *state)
9896{
9897 int i;
9898
9899 if (state->dts_nformats == 0) {
9900 ASSERT(state->dts_formats == NULL);
9901 return;
9902 }
9903
9904 ASSERT(state->dts_formats != NULL);
9905
9906 for (i = 0; i < state->dts_nformats; i++) {
9907 char *fmt = state->dts_formats[i];
9908
9909 if (fmt == NULL)
9910 continue;
9911
9912 kmem_free(fmt, strlen(fmt) + 1);
9913 }
9914
9915 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9916 state->dts_nformats = 0;
9917 state->dts_formats = NULL;
9918}
9919
9920/*
9921 * DTrace Predicate Functions
9922 */
9923static dtrace_predicate_t *
9924dtrace_predicate_create(dtrace_difo_t *dp)
9925{
9926 dtrace_predicate_t *pred;
9927
5ba3f43e 9928 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9929 ASSERT(dp->dtdo_refcnt != 0);
9930
9931 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9932 pred->dtp_difo = dp;
9933 pred->dtp_refcnt = 1;
9934
9935 if (!dtrace_difo_cacheable(dp))
9936 return (pred);
9937
9938 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9939 /*
9940 * This is only theoretically possible -- we have had 2^32
9941 * cacheable predicates on this machine. We cannot allow any
9942 * more predicates to become cacheable: as unlikely as it is,
9943 * there may be a thread caching a (now stale) predicate cache
9944 * ID. (N.B.: the temptation is being successfully resisted to
9945 * have this cmn_err() "Holy shit -- we executed this code!")
9946 */
9947 return (pred);
9948 }
9949
9950 pred->dtp_cacheid = dtrace_predcache_id++;
9951
9952 return (pred);
9953}
9954
9955static void
9956dtrace_predicate_hold(dtrace_predicate_t *pred)
9957{
5ba3f43e 9958 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9959 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9960 ASSERT(pred->dtp_refcnt > 0);
9961
9962 pred->dtp_refcnt++;
9963}
9964
9965static void
9966dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9967{
9968 dtrace_difo_t *dp = pred->dtp_difo;
b0d623f7 9969#pragma unused(dp) /* __APPLE__ */
2d21ac55 9970
5ba3f43e 9971 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
9972 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9973 ASSERT(pred->dtp_refcnt > 0);
9974
9975 if (--pred->dtp_refcnt == 0) {
9976 dtrace_difo_release(pred->dtp_difo, vstate);
9977 kmem_free(pred, sizeof (dtrace_predicate_t));
9978 }
9979}
9980
9981/*
9982 * DTrace Action Description Functions
9983 */
9984static dtrace_actdesc_t *
9985dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9986 uint64_t uarg, uint64_t arg)
9987{
9988 dtrace_actdesc_t *act;
9989
fe8ab488
A
9990 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
9991 arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
2d21ac55
A
9992
9993 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9994 act->dtad_kind = kind;
9995 act->dtad_ntuple = ntuple;
9996 act->dtad_uarg = uarg;
9997 act->dtad_arg = arg;
9998 act->dtad_refcnt = 1;
9999
10000 return (act);
10001}
10002
10003static void
10004dtrace_actdesc_hold(dtrace_actdesc_t *act)
10005{
10006 ASSERT(act->dtad_refcnt >= 1);
10007 act->dtad_refcnt++;
10008}
10009
10010static void
10011dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10012{
10013 dtrace_actkind_t kind = act->dtad_kind;
10014 dtrace_difo_t *dp;
10015
10016 ASSERT(act->dtad_refcnt >= 1);
10017
10018 if (--act->dtad_refcnt != 0)
10019 return;
10020
10021 if ((dp = act->dtad_difo) != NULL)
10022 dtrace_difo_release(dp, vstate);
10023
10024 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10025 char *str = (char *)(uintptr_t)act->dtad_arg;
10026
b0d623f7
A
10027 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10028 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
2d21ac55
A
10029
10030 if (str != NULL)
10031 kmem_free(str, strlen(str) + 1);
10032 }
10033
10034 kmem_free(act, sizeof (dtrace_actdesc_t));
10035}
10036
10037/*
10038 * DTrace ECB Functions
10039 */
10040static dtrace_ecb_t *
10041dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10042{
10043 dtrace_ecb_t *ecb;
10044 dtrace_epid_t epid;
10045
5ba3f43e 10046 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10047
10048 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10049 ecb->dte_predicate = NULL;
10050 ecb->dte_probe = probe;
10051
10052 /*
10053 * The default size is the size of the default action: recording
04b8595b 10054 * the header.
2d21ac55 10055 */
04b8595b 10056 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
2d21ac55
A
10057 ecb->dte_alignment = sizeof (dtrace_epid_t);
10058
10059 epid = state->dts_epid++;
10060
b0d623f7 10061 if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
2d21ac55
A
10062 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10063 int necbs = state->dts_necbs << 1;
10064
b0d623f7 10065 ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
2d21ac55
A
10066
10067 if (necbs == 0) {
10068 ASSERT(oecbs == NULL);
10069 necbs = 1;
10070 }
10071
10072 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10073
10074 if (oecbs != NULL)
10075 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10076
10077 dtrace_membar_producer();
10078 state->dts_ecbs = ecbs;
10079
10080 if (oecbs != NULL) {
10081 /*
10082 * If this state is active, we must dtrace_sync()
10083 * before we can free the old dts_ecbs array: we're
10084 * coming in hot, and there may be active ring
10085 * buffer processing (which indexes into the dts_ecbs
10086 * array) on another CPU.
10087 */
10088 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10089 dtrace_sync();
10090
10091 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10092 }
10093
10094 dtrace_membar_producer();
10095 state->dts_necbs = necbs;
10096 }
10097
10098 ecb->dte_state = state;
10099
10100 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10101 dtrace_membar_producer();
10102 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10103
10104 return (ecb);
10105}
10106
6d2010ae 10107static int
2d21ac55
A
10108dtrace_ecb_enable(dtrace_ecb_t *ecb)
10109{
10110 dtrace_probe_t *probe = ecb->dte_probe;
10111
5ba3f43e
A
10112 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10113 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10114 ASSERT(ecb->dte_next == NULL);
10115
10116 if (probe == NULL) {
10117 /*
10118 * This is the NULL probe -- there's nothing to do.
10119 */
6d2010ae 10120 return(0);
2d21ac55
A
10121 }
10122
fe8ab488 10123 probe->dtpr_provider->dtpv_ecb_count++;
2d21ac55
A
10124 if (probe->dtpr_ecb == NULL) {
10125 dtrace_provider_t *prov = probe->dtpr_provider;
10126
10127 /*
10128 * We're the first ECB on this probe.
10129 */
10130 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10131
10132 if (ecb->dte_predicate != NULL)
10133 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10134
6d2010ae
A
10135 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10136 probe->dtpr_id, probe->dtpr_arg));
2d21ac55
A
10137 } else {
10138 /*
10139 * This probe is already active. Swing the last pointer to
10140 * point to the new ECB, and issue a dtrace_sync() to assure
10141 * that all CPUs have seen the change.
10142 */
10143 ASSERT(probe->dtpr_ecb_last != NULL);
10144 probe->dtpr_ecb_last->dte_next = ecb;
10145 probe->dtpr_ecb_last = ecb;
10146 probe->dtpr_predcache = 0;
10147
10148 dtrace_sync();
6d2010ae 10149 return(0);
2d21ac55
A
10150 }
10151}
10152
39037602 10153static int
2d21ac55
A
10154dtrace_ecb_resize(dtrace_ecb_t *ecb)
10155{
2d21ac55 10156 dtrace_action_t *act;
04b8595b 10157 uint32_t curneeded = UINT32_MAX;
2d21ac55 10158 uint32_t aggbase = UINT32_MAX;
2d21ac55
A
10159
10160 /*
04b8595b
A
10161 * If we record anything, we always record the dtrace_rechdr_t. (And
10162 * we always record it first.)
2d21ac55 10163 */
04b8595b
A
10164 ecb->dte_size = sizeof (dtrace_rechdr_t);
10165 ecb->dte_alignment = sizeof (dtrace_epid_t);
2d21ac55
A
10166
10167 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10168 dtrace_recdesc_t *rec = &act->dta_rec;
04b8595b 10169 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
2d21ac55 10170
04b8595b 10171 ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
2d21ac55
A
10172
10173 if (DTRACEACT_ISAGG(act->dta_kind)) {
10174 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
2d21ac55 10175
04b8595b
A
10176 ASSERT(rec->dtrd_size != 0);
10177 ASSERT(agg->dtag_first != NULL);
10178 ASSERT(act->dta_prev->dta_intuple);
2d21ac55 10179 ASSERT(aggbase != UINT32_MAX);
04b8595b 10180 ASSERT(curneeded != UINT32_MAX);
2d21ac55
A
10181
10182 agg->dtag_base = aggbase;
04b8595b
A
10183 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10184 rec->dtrd_offset = curneeded;
39037602
A
10185 if (curneeded + rec->dtrd_size < curneeded)
10186 return (EINVAL);
04b8595b
A
10187 curneeded += rec->dtrd_size;
10188 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
2d21ac55 10189
04b8595b
A
10190 aggbase = UINT32_MAX;
10191 curneeded = UINT32_MAX;
10192 } else if (act->dta_intuple) {
10193 if (curneeded == UINT32_MAX) {
10194 /*
10195 * This is the first record in a tuple. Align
10196 * curneeded to be at offset 4 in an 8-byte
10197 * aligned block.
10198 */
10199 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
10200 ASSERT(aggbase == UINT32_MAX);
10201
10202 curneeded = P2PHASEUP(ecb->dte_size,
10203 sizeof (uint64_t), sizeof (dtrace_aggid_t));
10204
10205 aggbase = curneeded - sizeof (dtrace_aggid_t);
10206 ASSERT(IS_P2ALIGNED(aggbase,
10207 sizeof (uint64_t)));
2d21ac55 10208 }
2d21ac55 10209
04b8595b
A
10210 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10211 rec->dtrd_offset = curneeded;
10212 curneeded += rec->dtrd_size;
39037602
A
10213 if (curneeded + rec->dtrd_size < curneeded)
10214 return (EINVAL);
04b8595b
A
10215 } else {
10216 /* tuples must be followed by an aggregation */
10217 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
10218 ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
10219 rec->dtrd_offset = ecb->dte_size;
39037602
A
10220 if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
10221 return (EINVAL);
04b8595b
A
10222 ecb->dte_size += rec->dtrd_size;
10223 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
2d21ac55 10224 }
2d21ac55
A
10225 }
10226
10227 if ((act = ecb->dte_action) != NULL &&
10228 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
04b8595b 10229 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
2d21ac55 10230 /*
04b8595b 10231 * If the size is still sizeof (dtrace_rechdr_t), then all
2d21ac55
A
10232 * actions store no data; set the size to 0.
10233 */
2d21ac55 10234 ecb->dte_size = 0;
2d21ac55
A
10235 }
10236
04b8595b
A
10237 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10238 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10239 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
39037602 10240 return (0);
2d21ac55
A
10241}
10242
10243static dtrace_action_t *
10244dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10245{
10246 dtrace_aggregation_t *agg;
10247 size_t size = sizeof (uint64_t);
10248 int ntuple = desc->dtad_ntuple;
10249 dtrace_action_t *act;
10250 dtrace_recdesc_t *frec;
10251 dtrace_aggid_t aggid;
10252 dtrace_state_t *state = ecb->dte_state;
10253
10254 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10255 agg->dtag_ecb = ecb;
10256
10257 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10258
10259 switch (desc->dtad_kind) {
10260 case DTRACEAGG_MIN:
b0d623f7 10261 agg->dtag_initial = INT64_MAX;
2d21ac55
A
10262 agg->dtag_aggregate = dtrace_aggregate_min;
10263 break;
10264
10265 case DTRACEAGG_MAX:
b0d623f7 10266 agg->dtag_initial = INT64_MIN;
2d21ac55
A
10267 agg->dtag_aggregate = dtrace_aggregate_max;
10268 break;
10269
10270 case DTRACEAGG_COUNT:
10271 agg->dtag_aggregate = dtrace_aggregate_count;
10272 break;
10273
10274 case DTRACEAGG_QUANTIZE:
10275 agg->dtag_aggregate = dtrace_aggregate_quantize;
10276 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10277 sizeof (uint64_t);
10278 break;
10279
10280 case DTRACEAGG_LQUANTIZE: {
10281 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10282 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10283
10284 agg->dtag_initial = desc->dtad_arg;
10285 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10286
10287 if (step == 0 || levels == 0)
10288 goto err;
10289
10290 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10291 break;
10292 }
10293
39236c6e
A
10294 case DTRACEAGG_LLQUANTIZE: {
10295 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10296 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10297 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
15129b1c 10298 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
39236c6e
A
10299 int64_t v;
10300
10301 agg->dtag_initial = desc->dtad_arg;
10302 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10303
10304 if (factor < 2 || low >= high || nsteps < factor)
10305 goto err;
10306
10307 /*
10308 * Now check that the number of steps evenly divides a power
10309 * of the factor. (This assures both integer bucket size and
10310 * linearity within each magnitude.)
10311 */
10312 for (v = factor; v < nsteps; v *= factor)
10313 continue;
10314
10315 if ((v % nsteps) || (nsteps % factor))
10316 goto err;
10317
10318 size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10319 break;
10320 }
10321
2d21ac55
A
10322 case DTRACEAGG_AVG:
10323 agg->dtag_aggregate = dtrace_aggregate_avg;
10324 size = sizeof (uint64_t) * 2;
10325 break;
10326
b0d623f7
A
10327 case DTRACEAGG_STDDEV:
10328 agg->dtag_aggregate = dtrace_aggregate_stddev;
10329 size = sizeof (uint64_t) * 4;
10330 break;
10331
2d21ac55
A
10332 case DTRACEAGG_SUM:
10333 agg->dtag_aggregate = dtrace_aggregate_sum;
10334 break;
10335
10336 default:
10337 goto err;
10338 }
10339
10340 agg->dtag_action.dta_rec.dtrd_size = size;
10341
10342 if (ntuple == 0)
10343 goto err;
10344
10345 /*
10346 * We must make sure that we have enough actions for the n-tuple.
10347 */
10348 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10349 if (DTRACEACT_ISAGG(act->dta_kind))
10350 break;
10351
10352 if (--ntuple == 0) {
10353 /*
10354 * This is the action with which our n-tuple begins.
10355 */
10356 agg->dtag_first = act;
10357 goto success;
10358 }
10359 }
10360
10361 /*
10362 * This n-tuple is short by ntuple elements. Return failure.
10363 */
10364 ASSERT(ntuple != 0);
10365err:
10366 kmem_free(agg, sizeof (dtrace_aggregation_t));
10367 return (NULL);
10368
10369success:
10370 /*
10371 * If the last action in the tuple has a size of zero, it's actually
10372 * an expression argument for the aggregating action.
10373 */
10374 ASSERT(ecb->dte_action_last != NULL);
10375 act = ecb->dte_action_last;
10376
10377 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10378 ASSERT(act->dta_difo != NULL);
10379
10380 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10381 agg->dtag_hasarg = 1;
10382 }
10383
10384 /*
10385 * We need to allocate an id for this aggregation.
10386 */
10387 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10388 VM_BESTFIT | VM_SLEEP);
10389
b0d623f7 10390 if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
2d21ac55
A
10391 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10392 dtrace_aggregation_t **aggs;
10393 int naggs = state->dts_naggregations << 1;
10394 int onaggs = state->dts_naggregations;
10395
b0d623f7 10396 ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
2d21ac55
A
10397
10398 if (naggs == 0) {
10399 ASSERT(oaggs == NULL);
10400 naggs = 1;
10401 }
10402
10403 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10404
10405 if (oaggs != NULL) {
10406 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10407 kmem_free(oaggs, onaggs * sizeof (*aggs));
10408 }
10409
10410 state->dts_aggregations = aggs;
10411 state->dts_naggregations = naggs;
10412 }
10413
10414 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10415 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10416
10417 frec = &agg->dtag_first->dta_rec;
10418 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10419 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10420
10421 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10422 ASSERT(!act->dta_intuple);
10423 act->dta_intuple = 1;
10424 }
10425
10426 return (&agg->dtag_action);
10427}
10428
10429static void
10430dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10431{
10432 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10433 dtrace_state_t *state = ecb->dte_state;
10434 dtrace_aggid_t aggid = agg->dtag_id;
10435
10436 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10437 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10438
10439 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10440 state->dts_aggregations[aggid - 1] = NULL;
10441
10442 kmem_free(agg, sizeof (dtrace_aggregation_t));
10443}
10444
10445static int
10446dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10447{
10448 dtrace_action_t *action, *last;
10449 dtrace_difo_t *dp = desc->dtad_difo;
10450 uint32_t size = 0, align = sizeof (uint8_t), mask;
10451 uint16_t format = 0;
10452 dtrace_recdesc_t *rec;
10453 dtrace_state_t *state = ecb->dte_state;
b0d623f7
A
10454 dtrace_optval_t *opt = state->dts_options;
10455 dtrace_optval_t nframes=0, strsize;
2d21ac55
A
10456 uint64_t arg = desc->dtad_arg;
10457
5ba3f43e 10458 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10459 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10460
10461 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10462 /*
10463 * If this is an aggregating action, there must be neither
10464 * a speculate nor a commit on the action chain.
10465 */
10466 dtrace_action_t *act;
10467
10468 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10469 if (act->dta_kind == DTRACEACT_COMMIT)
10470 return (EINVAL);
10471
10472 if (act->dta_kind == DTRACEACT_SPECULATE)
10473 return (EINVAL);
10474 }
10475
10476 action = dtrace_ecb_aggregation_create(ecb, desc);
10477
10478 if (action == NULL)
10479 return (EINVAL);
10480 } else {
10481 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10482 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10483 dp != NULL && dp->dtdo_destructive)) {
10484 state->dts_destructive = 1;
10485 }
10486
10487 switch (desc->dtad_kind) {
10488 case DTRACEACT_PRINTF:
10489 case DTRACEACT_PRINTA:
10490 case DTRACEACT_SYSTEM:
10491 case DTRACEACT_FREOPEN:
3e170ce0 10492 case DTRACEACT_DIFEXPR:
2d21ac55
A
10493 /*
10494 * We know that our arg is a string -- turn it into a
10495 * format.
10496 */
fe8ab488 10497 if (arg == 0) {
3e170ce0
A
10498 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10499 desc->dtad_kind == DTRACEACT_DIFEXPR);
2d21ac55
A
10500 format = 0;
10501 } else {
fe8ab488 10502 ASSERT(arg != 0);
b0d623f7 10503 ASSERT(arg > KERNELBASE);
2d21ac55
A
10504 format = dtrace_format_add(state,
10505 (char *)(uintptr_t)arg);
10506 }
10507
10508 /*FALLTHROUGH*/
10509 case DTRACEACT_LIBACT:
fe8ab488
A
10510 case DTRACEACT_TRACEMEM:
10511 case DTRACEACT_TRACEMEM_DYNSIZE:
10512 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
2d21ac55
A
10513 if (dp == NULL)
10514 return (EINVAL);
10515
10516 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10517 break;
10518
10519 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10520 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10521 return (EINVAL);
10522
10523 size = opt[DTRACEOPT_STRSIZE];
10524 }
10525
10526 break;
10527
10528 case DTRACEACT_STACK:
10529 if ((nframes = arg) == 0) {
10530 nframes = opt[DTRACEOPT_STACKFRAMES];
10531 ASSERT(nframes > 0);
10532 arg = nframes;
10533 }
10534
10535 size = nframes * sizeof (pc_t);
10536 break;
10537
10538 case DTRACEACT_JSTACK:
10539 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10540 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10541
10542 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10543 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10544
10545 arg = DTRACE_USTACK_ARG(nframes, strsize);
10546
10547 /*FALLTHROUGH*/
10548 case DTRACEACT_USTACK:
10549 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10550 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10551 strsize = DTRACE_USTACK_STRSIZE(arg);
10552 nframes = opt[DTRACEOPT_USTACKFRAMES];
10553 ASSERT(nframes > 0);
10554 arg = DTRACE_USTACK_ARG(nframes, strsize);
10555 }
10556
10557 /*
10558 * Save a slot for the pid.
10559 */
10560 size = (nframes + 1) * sizeof (uint64_t);
10561 size += DTRACE_USTACK_STRSIZE(arg);
10562 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10563
10564 break;
10565
10566 case DTRACEACT_SYM:
10567 case DTRACEACT_MOD:
10568 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10569 sizeof (uint64_t)) ||
10570 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10571 return (EINVAL);
10572 break;
10573
10574 case DTRACEACT_USYM:
10575 case DTRACEACT_UMOD:
10576 case DTRACEACT_UADDR:
10577 if (dp == NULL ||
10578 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10579 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10580 return (EINVAL);
10581
10582 /*
10583 * We have a slot for the pid, plus a slot for the
10584 * argument. To keep things simple (aligned with
10585 * bitness-neutral sizing), we store each as a 64-bit
10586 * quantity.
10587 */
10588 size = 2 * sizeof (uint64_t);
10589 break;
10590
10591 case DTRACEACT_STOP:
10592 case DTRACEACT_BREAKPOINT:
10593 case DTRACEACT_PANIC:
10594 break;
10595
10596 case DTRACEACT_CHILL:
10597 case DTRACEACT_DISCARD:
10598 case DTRACEACT_RAISE:
fe8ab488 10599 case DTRACEACT_PIDRESUME: /* __APPLE__ */
2d21ac55
A
10600 if (dp == NULL)
10601 return (EINVAL);
10602 break;
10603
10604 case DTRACEACT_EXIT:
10605 if (dp == NULL ||
10606 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10607 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10608 return (EINVAL);
10609 break;
10610
10611 case DTRACEACT_SPECULATE:
04b8595b 10612 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
2d21ac55
A
10613 return (EINVAL);
10614
10615 if (dp == NULL)
10616 return (EINVAL);
10617
10618 state->dts_speculates = 1;
10619 break;
10620
10621 case DTRACEACT_COMMIT: {
10622 dtrace_action_t *act = ecb->dte_action;
10623
10624 for (; act != NULL; act = act->dta_next) {
10625 if (act->dta_kind == DTRACEACT_COMMIT)
10626 return (EINVAL);
10627 }
10628
10629 if (dp == NULL)
10630 return (EINVAL);
10631 break;
10632 }
10633
10634 default:
10635 return (EINVAL);
10636 }
10637
10638 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10639 /*
10640 * If this is a data-storing action or a speculate,
10641 * we must be sure that there isn't a commit on the
10642 * action chain.
10643 */
10644 dtrace_action_t *act = ecb->dte_action;
10645
10646 for (; act != NULL; act = act->dta_next) {
10647 if (act->dta_kind == DTRACEACT_COMMIT)
10648 return (EINVAL);
10649 }
10650 }
10651
10652 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10653 action->dta_rec.dtrd_size = size;
10654 }
10655
10656 action->dta_refcnt = 1;
10657 rec = &action->dta_rec;
10658 size = rec->dtrd_size;
10659
10660 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10661 if (!(size & mask)) {
10662 align = mask + 1;
10663 break;
10664 }
10665 }
10666
10667 action->dta_kind = desc->dtad_kind;
10668
10669 if ((action->dta_difo = dp) != NULL)
10670 dtrace_difo_hold(dp);
10671
10672 rec->dtrd_action = action->dta_kind;
10673 rec->dtrd_arg = arg;
10674 rec->dtrd_uarg = desc->dtad_uarg;
10675 rec->dtrd_alignment = (uint16_t)align;
10676 rec->dtrd_format = format;
10677
10678 if ((last = ecb->dte_action_last) != NULL) {
10679 ASSERT(ecb->dte_action != NULL);
10680 action->dta_prev = last;
10681 last->dta_next = action;
10682 } else {
10683 ASSERT(ecb->dte_action == NULL);
10684 ecb->dte_action = action;
10685 }
10686
10687 ecb->dte_action_last = action;
10688
10689 return (0);
10690}
10691
10692static void
10693dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10694{
10695 dtrace_action_t *act = ecb->dte_action, *next;
10696 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10697 dtrace_difo_t *dp;
10698 uint16_t format;
10699
10700 if (act != NULL && act->dta_refcnt > 1) {
10701 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10702 act->dta_refcnt--;
10703 } else {
10704 for (; act != NULL; act = next) {
10705 next = act->dta_next;
10706 ASSERT(next != NULL || act == ecb->dte_action_last);
10707 ASSERT(act->dta_refcnt == 1);
10708
10709 if ((format = act->dta_rec.dtrd_format) != 0)
10710 dtrace_format_remove(ecb->dte_state, format);
10711
10712 if ((dp = act->dta_difo) != NULL)
10713 dtrace_difo_release(dp, vstate);
10714
10715 if (DTRACEACT_ISAGG(act->dta_kind)) {
10716 dtrace_ecb_aggregation_destroy(ecb, act);
10717 } else {
10718 kmem_free(act, sizeof (dtrace_action_t));
10719 }
10720 }
10721 }
10722
10723 ecb->dte_action = NULL;
10724 ecb->dte_action_last = NULL;
04b8595b 10725 ecb->dte_size = 0;
2d21ac55
A
10726}
10727
10728static void
10729dtrace_ecb_disable(dtrace_ecb_t *ecb)
10730{
10731 /*
10732 * We disable the ECB by removing it from its probe.
10733 */
10734 dtrace_ecb_t *pecb, *prev = NULL;
10735 dtrace_probe_t *probe = ecb->dte_probe;
10736
5ba3f43e 10737 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10738
10739 if (probe == NULL) {
10740 /*
10741 * This is the NULL probe; there is nothing to disable.
10742 */
10743 return;
10744 }
10745
10746 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10747 if (pecb == ecb)
10748 break;
10749 prev = pecb;
10750 }
10751
10752 ASSERT(pecb != NULL);
10753
10754 if (prev == NULL) {
10755 probe->dtpr_ecb = ecb->dte_next;
10756 } else {
10757 prev->dte_next = ecb->dte_next;
10758 }
10759
10760 if (ecb == probe->dtpr_ecb_last) {
10761 ASSERT(ecb->dte_next == NULL);
10762 probe->dtpr_ecb_last = prev;
10763 }
10764
fe8ab488 10765 probe->dtpr_provider->dtpv_ecb_count--;
2d21ac55
A
10766 /*
10767 * The ECB has been disconnected from the probe; now sync to assure
10768 * that all CPUs have seen the change before returning.
10769 */
10770 dtrace_sync();
10771
10772 if (probe->dtpr_ecb == NULL) {
10773 /*
10774 * That was the last ECB on the probe; clear the predicate
10775 * cache ID for the probe, disable it and sync one more time
10776 * to assure that we'll never hit it again.
10777 */
10778 dtrace_provider_t *prov = probe->dtpr_provider;
10779
10780 ASSERT(ecb->dte_next == NULL);
10781 ASSERT(probe->dtpr_ecb_last == NULL);
10782 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10783 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10784 probe->dtpr_id, probe->dtpr_arg);
10785 dtrace_sync();
10786 } else {
10787 /*
10788 * There is at least one ECB remaining on the probe. If there
10789 * is _exactly_ one, set the probe's predicate cache ID to be
10790 * the predicate cache ID of the remaining ECB.
10791 */
10792 ASSERT(probe->dtpr_ecb_last != NULL);
10793 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10794
10795 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10796 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10797
10798 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10799
10800 if (p != NULL)
10801 probe->dtpr_predcache = p->dtp_cacheid;
10802 }
10803
10804 ecb->dte_next = NULL;
10805 }
10806}
10807
10808static void
10809dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10810{
10811 dtrace_state_t *state = ecb->dte_state;
10812 dtrace_vstate_t *vstate = &state->dts_vstate;
10813 dtrace_predicate_t *pred;
10814 dtrace_epid_t epid = ecb->dte_epid;
10815
5ba3f43e 10816 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10817 ASSERT(ecb->dte_next == NULL);
10818 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10819
10820 if ((pred = ecb->dte_predicate) != NULL)
10821 dtrace_predicate_release(pred, vstate);
10822
10823 dtrace_ecb_action_remove(ecb);
10824
10825 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10826 state->dts_ecbs[epid - 1] = NULL;
10827
10828 kmem_free(ecb, sizeof (dtrace_ecb_t));
10829}
10830
10831static dtrace_ecb_t *
10832dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10833 dtrace_enabling_t *enab)
10834{
10835 dtrace_ecb_t *ecb;
10836 dtrace_predicate_t *pred;
10837 dtrace_actdesc_t *act;
10838 dtrace_provider_t *prov;
10839 dtrace_ecbdesc_t *desc = enab->dten_current;
10840
5ba3f43e 10841 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
10842 ASSERT(state != NULL);
10843
10844 ecb = dtrace_ecb_add(state, probe);
10845 ecb->dte_uarg = desc->dted_uarg;
10846
10847 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10848 dtrace_predicate_hold(pred);
10849 ecb->dte_predicate = pred;
10850 }
10851
10852 if (probe != NULL) {
10853 /*
10854 * If the provider shows more leg than the consumer is old
10855 * enough to see, we need to enable the appropriate implicit
10856 * predicate bits to prevent the ecb from activating at
10857 * revealing times.
10858 *
10859 * Providers specifying DTRACE_PRIV_USER at register time
10860 * are stating that they need the /proc-style privilege
10861 * model to be enforced, and this is what DTRACE_COND_OWNER
10862 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10863 */
10864 prov = probe->dtpr_provider;
10865 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10866 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10867 ecb->dte_cond |= DTRACE_COND_OWNER;
10868
10869 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10870 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10871 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10872
10873 /*
10874 * If the provider shows us kernel innards and the user
10875 * is lacking sufficient privilege, enable the
10876 * DTRACE_COND_USERMODE implicit predicate.
10877 */
10878 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10879 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10880 ecb->dte_cond |= DTRACE_COND_USERMODE;
10881 }
10882
10883 if (dtrace_ecb_create_cache != NULL) {
10884 /*
10885 * If we have a cached ecb, we'll use its action list instead
10886 * of creating our own (saving both time and space).
10887 */
10888 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
c910b4d9 10889 dtrace_action_t *act_if = cached->dte_action;
2d21ac55 10890
c910b4d9
A
10891 if (act_if != NULL) {
10892 ASSERT(act_if->dta_refcnt > 0);
10893 act_if->dta_refcnt++;
10894 ecb->dte_action = act_if;
2d21ac55
A
10895 ecb->dte_action_last = cached->dte_action_last;
10896 ecb->dte_needed = cached->dte_needed;
10897 ecb->dte_size = cached->dte_size;
10898 ecb->dte_alignment = cached->dte_alignment;
10899 }
10900
10901 return (ecb);
10902 }
10903
10904 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10905 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10906 dtrace_ecb_destroy(ecb);
10907 return (NULL);
10908 }
10909 }
10910
39037602
A
10911 if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
10912 dtrace_ecb_destroy(ecb);
10913 return (NULL);
10914 }
2d21ac55
A
10915
10916 return (dtrace_ecb_create_cache = ecb);
10917}
10918
10919static int
d190cdc3 10920dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg1, void *arg2)
2d21ac55
A
10921{
10922 dtrace_ecb_t *ecb;
d190cdc3
A
10923 dtrace_enabling_t *enab = arg1;
10924 dtrace_ecbdesc_t *ep = arg2;
2d21ac55
A
10925 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10926
10927 ASSERT(state != NULL);
10928
d190cdc3 10929 if (probe != NULL && ep != NULL && probe->dtpr_gen < ep->dted_probegen) {
2d21ac55
A
10930 /*
10931 * This probe was created in a generation for which this
10932 * enabling has previously created ECBs; we don't want to
10933 * enable it again, so just kick out.
10934 */
10935 return (DTRACE_MATCH_NEXT);
10936 }
10937
10938 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10939 return (DTRACE_MATCH_DONE);
10940
6d2010ae
A
10941 if (dtrace_ecb_enable(ecb) < 0)
10942 return (DTRACE_MATCH_FAIL);
10943
2d21ac55
A
10944 return (DTRACE_MATCH_NEXT);
10945}
10946
10947static dtrace_ecb_t *
10948dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10949{
10950 dtrace_ecb_t *ecb;
b0d623f7 10951#pragma unused(ecb) /* __APPLE__ */
2d21ac55 10952
5ba3f43e 10953 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 10954
fe8ab488 10955 if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
2d21ac55
A
10956 return (NULL);
10957
10958 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10959 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10960
10961 return (state->dts_ecbs[id - 1]);
10962}
10963
10964static dtrace_aggregation_t *
10965dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10966{
10967 dtrace_aggregation_t *agg;
b0d623f7 10968#pragma unused(agg) /* __APPLE__ */
2d21ac55 10969
5ba3f43e 10970 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 10971
b0d623f7 10972 if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
2d21ac55
A
10973 return (NULL);
10974
10975 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10976 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10977 agg->dtag_id == id);
10978
10979 return (state->dts_aggregations[id - 1]);
10980}
10981
10982/*
10983 * DTrace Buffer Functions
10984 *
10985 * The following functions manipulate DTrace buffers. Most of these functions
10986 * are called in the context of establishing or processing consumer state;
10987 * exceptions are explicitly noted.
10988 */
10989
10990/*
10991 * Note: called from cross call context. This function switches the two
10992 * buffers on a given CPU. The atomicity of this operation is assured by
10993 * disabling interrupts while the actual switch takes place; the disabling of
10994 * interrupts serializes the execution with any execution of dtrace_probe() on
10995 * the same CPU.
10996 */
10997static void
10998dtrace_buffer_switch(dtrace_buffer_t *buf)
10999{
11000 caddr_t tomax = buf->dtb_tomax;
11001 caddr_t xamot = buf->dtb_xamot;
11002 dtrace_icookie_t cookie;
04b8595b 11003 hrtime_t now;
2d21ac55
A
11004
11005 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11006 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11007
11008 cookie = dtrace_interrupt_disable();
04b8595b 11009 now = dtrace_gethrtime();
2d21ac55
A
11010 buf->dtb_tomax = xamot;
11011 buf->dtb_xamot = tomax;
11012 buf->dtb_xamot_drops = buf->dtb_drops;
11013 buf->dtb_xamot_offset = buf->dtb_offset;
11014 buf->dtb_xamot_errors = buf->dtb_errors;
11015 buf->dtb_xamot_flags = buf->dtb_flags;
11016 buf->dtb_offset = 0;
11017 buf->dtb_drops = 0;
11018 buf->dtb_errors = 0;
11019 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
04b8595b
A
11020 buf->dtb_interval = now - buf->dtb_switched;
11021 buf->dtb_switched = now;
39037602
A
11022 buf->dtb_cur_limit = buf->dtb_limit;
11023
2d21ac55
A
11024 dtrace_interrupt_enable(cookie);
11025}
11026
11027/*
11028 * Note: called from cross call context. This function activates a buffer
11029 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11030 * is guaranteed by the disabling of interrupts.
11031 */
11032static void
11033dtrace_buffer_activate(dtrace_state_t *state)
11034{
11035 dtrace_buffer_t *buf;
11036 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11037
11038 buf = &state->dts_buffer[CPU->cpu_id];
11039
11040 if (buf->dtb_tomax != NULL) {
11041 /*
11042 * We might like to assert that the buffer is marked inactive,
11043 * but this isn't necessarily true: the buffer for the CPU
11044 * that processes the BEGIN probe has its buffer activated
11045 * manually. In this case, we take the (harmless) action
11046 * re-clearing the bit INACTIVE bit.
11047 */
11048 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11049 }
11050
11051 dtrace_interrupt_enable(cookie);
11052}
11053
fe8ab488
A
11054static int
11055dtrace_buffer_canalloc(size_t size)
11056{
11057 if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
11058 return (B_FALSE);
11059 if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
11060 return (B_FALSE);
11061
11062 return (B_TRUE);
11063}
11064
2d21ac55 11065static int
39037602 11066dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t limit, size_t size, int flags,
2d21ac55
A
11067 processorid_t cpu)
11068{
6d2010ae 11069 dtrace_cpu_t *cp;
2d21ac55 11070 dtrace_buffer_t *buf;
fe8ab488 11071 size_t size_before_alloc = dtrace_buffer_memory_inuse;
2d21ac55 11072
5ba3f43e
A
11073 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11074 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 11075
b0d623f7
A
11076 if (size > (size_t)dtrace_nonroot_maxsize &&
11077 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11078 return (EFBIG);
2d21ac55
A
11079
11080 cp = cpu_list;
11081
11082 do {
11083 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11084 continue;
11085
11086 buf = &bufs[cp->cpu_id];
11087
11088 /*
11089 * If there is already a buffer allocated for this CPU, it
11090 * is only possible that this is a DR event. In this case,
11091 * the buffer size must match our specified size.
11092 */
11093 if (buf->dtb_tomax != NULL) {
11094 ASSERT(buf->dtb_size == size);
11095 continue;
11096 }
11097
11098 ASSERT(buf->dtb_xamot == NULL);
11099
fe8ab488
A
11100 /* DTrace, please do not eat all the memory. */
11101 if (dtrace_buffer_canalloc(size) == B_FALSE)
11102 goto err;
2d21ac55
A
11103 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11104 goto err;
fe8ab488 11105 dtrace_buffer_memory_inuse += size;
2d21ac55 11106
39037602
A
11107 /* Unsure that limit is always lower than size */
11108 limit = limit == size ? limit - 1 : limit;
11109 buf->dtb_cur_limit = limit;
11110 buf->dtb_limit = limit;
2d21ac55
A
11111 buf->dtb_size = size;
11112 buf->dtb_flags = flags;
11113 buf->dtb_offset = 0;
11114 buf->dtb_drops = 0;
11115
11116 if (flags & DTRACEBUF_NOSWITCH)
11117 continue;
11118
fe8ab488
A
11119 /* DTrace, please do not eat all the memory. */
11120 if (dtrace_buffer_canalloc(size) == B_FALSE)
11121 goto err;
2d21ac55
A
11122 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11123 goto err;
fe8ab488 11124 dtrace_buffer_memory_inuse += size;
2d21ac55
A
11125 } while ((cp = cp->cpu_next) != cpu_list);
11126
fe8ab488
A
11127 ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
11128
2d21ac55
A
11129 return (0);
11130
11131err:
11132 cp = cpu_list;
11133
11134 do {
11135 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11136 continue;
11137
11138 buf = &bufs[cp->cpu_id];
11139
11140 if (buf->dtb_xamot != NULL) {
11141 ASSERT(buf->dtb_tomax != NULL);
11142 ASSERT(buf->dtb_size == size);
11143 kmem_free(buf->dtb_xamot, size);
11144 }
11145
11146 if (buf->dtb_tomax != NULL) {
11147 ASSERT(buf->dtb_size == size);
11148 kmem_free(buf->dtb_tomax, size);
11149 }
11150
11151 buf->dtb_tomax = NULL;
11152 buf->dtb_xamot = NULL;
11153 buf->dtb_size = 0;
11154 } while ((cp = cp->cpu_next) != cpu_list);
11155
fe8ab488
A
11156 /* Restore the size saved before allocating memory */
11157 dtrace_buffer_memory_inuse = size_before_alloc;
11158
2d21ac55
A
11159 return (ENOMEM);
11160}
11161
11162/*
11163 * Note: called from probe context. This function just increments the drop
11164 * count on a buffer. It has been made a function to allow for the
11165 * possibility of understanding the source of mysterious drop counts. (A
11166 * problem for which one may be particularly disappointed that DTrace cannot
11167 * be used to understand DTrace.)
11168 */
11169static void
11170dtrace_buffer_drop(dtrace_buffer_t *buf)
11171{
11172 buf->dtb_drops++;
11173}
11174
11175/*
11176 * Note: called from probe context. This function is called to reserve space
11177 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
11178 * mstate. Returns the new offset in the buffer, or a negative value if an
11179 * error has occurred.
11180 */
11181static intptr_t
11182dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11183 dtrace_state_t *state, dtrace_mstate_t *mstate)
11184{
11185 intptr_t offs = buf->dtb_offset, soffs;
11186 intptr_t woffs;
11187 caddr_t tomax;
c910b4d9 11188 size_t total_off;
2d21ac55
A
11189
11190 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11191 return (-1);
11192
11193 if ((tomax = buf->dtb_tomax) == NULL) {
11194 dtrace_buffer_drop(buf);
11195 return (-1);
11196 }
11197
11198 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11199 while (offs & (align - 1)) {
11200 /*
11201 * Assert that our alignment is off by a number which
11202 * is itself sizeof (uint32_t) aligned.
11203 */
11204 ASSERT(!((align - (offs & (align - 1))) &
11205 (sizeof (uint32_t) - 1)));
11206 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11207 offs += sizeof (uint32_t);
11208 }
11209
39037602
A
11210 if ((uint64_t)(soffs = offs + needed) > buf->dtb_cur_limit) {
11211 if (buf->dtb_cur_limit == buf->dtb_limit) {
11212 buf->dtb_cur_limit = buf->dtb_size;
11213
11214 atomic_add_32(&state->dts_buf_over_limit, 1);
11215 /**
11216 * Set an AST on the current processor
11217 * so that we can wake up the process
11218 * outside of probe context, when we know
11219 * it is safe to do so
11220 */
11221 minor_t minor = getminor(state->dts_dev);
11222 ASSERT(minor < 32);
11223
11224 atomic_or_32(&dtrace_wake_clients, 1 << minor);
11225 ast_dtrace_on();
11226 }
11227 if ((uint64_t)soffs > buf->dtb_size) {
11228 dtrace_buffer_drop(buf);
11229 return (-1);
11230 }
2d21ac55
A
11231 }
11232
11233 if (mstate == NULL)
11234 return (offs);
11235
11236 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11237 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11238 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11239
11240 return (offs);
11241 }
11242
11243 if (buf->dtb_flags & DTRACEBUF_FILL) {
11244 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11245 (buf->dtb_flags & DTRACEBUF_FULL))
11246 return (-1);
11247 goto out;
11248 }
11249
c910b4d9 11250 total_off = needed + (offs & (align - 1));
2d21ac55
A
11251
11252 /*
11253 * For a ring buffer, life is quite a bit more complicated. Before
11254 * we can store any padding, we need to adjust our wrapping offset.
11255 * (If we've never before wrapped or we're not about to, no adjustment
11256 * is required.)
11257 */
11258 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
c910b4d9 11259 offs + total_off > buf->dtb_size) {
2d21ac55
A
11260 woffs = buf->dtb_xamot_offset;
11261
c910b4d9 11262 if (offs + total_off > buf->dtb_size) {
2d21ac55
A
11263 /*
11264 * We can't fit in the end of the buffer. First, a
11265 * sanity check that we can fit in the buffer at all.
11266 */
c910b4d9 11267 if (total_off > buf->dtb_size) {
2d21ac55
A
11268 dtrace_buffer_drop(buf);
11269 return (-1);
11270 }
11271
11272 /*
11273 * We're going to be storing at the top of the buffer,
11274 * so now we need to deal with the wrapped offset. We
11275 * only reset our wrapped offset to 0 if it is
11276 * currently greater than the current offset. If it
11277 * is less than the current offset, it is because a
11278 * previous allocation induced a wrap -- but the
11279 * allocation didn't subsequently take the space due
11280 * to an error or false predicate evaluation. In this
11281 * case, we'll just leave the wrapped offset alone: if
11282 * the wrapped offset hasn't been advanced far enough
11283 * for this allocation, it will be adjusted in the
11284 * lower loop.
11285 */
11286 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11287 if (woffs >= offs)
11288 woffs = 0;
11289 } else {
11290 woffs = 0;
11291 }
11292
11293 /*
11294 * Now we know that we're going to be storing to the
11295 * top of the buffer and that there is room for us
11296 * there. We need to clear the buffer from the current
11297 * offset to the end (there may be old gunk there).
11298 */
b0d623f7 11299 while ((uint64_t)offs < buf->dtb_size)
2d21ac55
A
11300 tomax[offs++] = 0;
11301
11302 /*
11303 * We need to set our offset to zero. And because we
11304 * are wrapping, we need to set the bit indicating as
11305 * much. We can also adjust our needed space back
11306 * down to the space required by the ECB -- we know
11307 * that the top of the buffer is aligned.
11308 */
11309 offs = 0;
c910b4d9 11310 total_off = needed;
2d21ac55
A
11311 buf->dtb_flags |= DTRACEBUF_WRAPPED;
11312 } else {
11313 /*
11314 * There is room for us in the buffer, so we simply
11315 * need to check the wrapped offset.
11316 */
11317 if (woffs < offs) {
11318 /*
11319 * The wrapped offset is less than the offset.
11320 * This can happen if we allocated buffer space
11321 * that induced a wrap, but then we didn't
11322 * subsequently take the space due to an error
11323 * or false predicate evaluation. This is
11324 * okay; we know that _this_ allocation isn't
11325 * going to induce a wrap. We still can't
11326 * reset the wrapped offset to be zero,
11327 * however: the space may have been trashed in
11328 * the previous failed probe attempt. But at
11329 * least the wrapped offset doesn't need to
11330 * be adjusted at all...
11331 */
11332 goto out;
11333 }
11334 }
11335
b0d623f7 11336 while (offs + total_off > (size_t)woffs) {
2d21ac55
A
11337 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11338 size_t size;
11339
11340 if (epid == DTRACE_EPIDNONE) {
11341 size = sizeof (uint32_t);
11342 } else {
b0d623f7 11343 ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
2d21ac55
A
11344 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11345
11346 size = state->dts_ecbs[epid - 1]->dte_size;
11347 }
11348
11349 ASSERT(woffs + size <= buf->dtb_size);
11350 ASSERT(size != 0);
11351
11352 if (woffs + size == buf->dtb_size) {
11353 /*
11354 * We've reached the end of the buffer; we want
11355 * to set the wrapped offset to 0 and break
11356 * out. However, if the offs is 0, then we're
11357 * in a strange edge-condition: the amount of
11358 * space that we want to reserve plus the size
11359 * of the record that we're overwriting is
11360 * greater than the size of the buffer. This
11361 * is problematic because if we reserve the
11362 * space but subsequently don't consume it (due
11363 * to a failed predicate or error) the wrapped
11364 * offset will be 0 -- yet the EPID at offset 0
11365 * will not be committed. This situation is
11366 * relatively easy to deal with: if we're in
11367 * this case, the buffer is indistinguishable
11368 * from one that hasn't wrapped; we need only
11369 * finish the job by clearing the wrapped bit,
11370 * explicitly setting the offset to be 0, and
11371 * zero'ing out the old data in the buffer.
11372 */
11373 if (offs == 0) {
11374 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11375 buf->dtb_offset = 0;
c910b4d9 11376 woffs = total_off;
2d21ac55 11377
b0d623f7 11378 while ((uint64_t)woffs < buf->dtb_size)
2d21ac55
A
11379 tomax[woffs++] = 0;
11380 }
11381
11382 woffs = 0;
11383 break;
11384 }
11385
11386 woffs += size;
11387 }
11388
11389 /*
11390 * We have a wrapped offset. It may be that the wrapped offset
11391 * has become zero -- that's okay.
11392 */
11393 buf->dtb_xamot_offset = woffs;
11394 }
11395
11396out:
11397 /*
11398 * Now we can plow the buffer with any necessary padding.
11399 */
11400 while (offs & (align - 1)) {
11401 /*
11402 * Assert that our alignment is off by a number which
11403 * is itself sizeof (uint32_t) aligned.
11404 */
11405 ASSERT(!((align - (offs & (align - 1))) &
11406 (sizeof (uint32_t) - 1)));
11407 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11408 offs += sizeof (uint32_t);
11409 }
11410
11411 if (buf->dtb_flags & DTRACEBUF_FILL) {
11412 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11413 buf->dtb_flags |= DTRACEBUF_FULL;
11414 return (-1);
11415 }
11416 }
11417
11418 if (mstate == NULL)
11419 return (offs);
11420
11421 /*
11422 * For ring buffers and fill buffers, the scratch space is always
11423 * the inactive buffer.
11424 */
11425 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11426 mstate->dtms_scratch_size = buf->dtb_size;
11427 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11428
11429 return (offs);
11430}
11431
11432static void
11433dtrace_buffer_polish(dtrace_buffer_t *buf)
11434{
11435 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
5ba3f43e 11436 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11437
11438 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11439 return;
11440
11441 /*
11442 * We need to polish the ring buffer. There are three cases:
11443 *
11444 * - The first (and presumably most common) is that there is no gap
11445 * between the buffer offset and the wrapped offset. In this case,
11446 * there is nothing in the buffer that isn't valid data; we can
11447 * mark the buffer as polished and return.
11448 *
11449 * - The second (less common than the first but still more common
11450 * than the third) is that there is a gap between the buffer offset
11451 * and the wrapped offset, and the wrapped offset is larger than the
11452 * buffer offset. This can happen because of an alignment issue, or
11453 * can happen because of a call to dtrace_buffer_reserve() that
11454 * didn't subsequently consume the buffer space. In this case,
11455 * we need to zero the data from the buffer offset to the wrapped
11456 * offset.
11457 *
11458 * - The third (and least common) is that there is a gap between the
11459 * buffer offset and the wrapped offset, but the wrapped offset is
11460 * _less_ than the buffer offset. This can only happen because a
11461 * call to dtrace_buffer_reserve() induced a wrap, but the space
11462 * was not subsequently consumed. In this case, we need to zero the
11463 * space from the offset to the end of the buffer _and_ from the
11464 * top of the buffer to the wrapped offset.
11465 */
11466 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11467 bzero(buf->dtb_tomax + buf->dtb_offset,
11468 buf->dtb_xamot_offset - buf->dtb_offset);
11469 }
11470
11471 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11472 bzero(buf->dtb_tomax + buf->dtb_offset,
11473 buf->dtb_size - buf->dtb_offset);
11474 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11475 }
11476}
11477
11478static void
11479dtrace_buffer_free(dtrace_buffer_t *bufs)
11480{
11481 int i;
11482
c910b4d9 11483 for (i = 0; i < (int)NCPU; i++) {
2d21ac55
A
11484 dtrace_buffer_t *buf = &bufs[i];
11485
11486 if (buf->dtb_tomax == NULL) {
11487 ASSERT(buf->dtb_xamot == NULL);
11488 ASSERT(buf->dtb_size == 0);
11489 continue;
11490 }
11491
11492 if (buf->dtb_xamot != NULL) {
11493 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11494 kmem_free(buf->dtb_xamot, buf->dtb_size);
fe8ab488
A
11495
11496 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11497 dtrace_buffer_memory_inuse -= buf->dtb_size;
2d21ac55
A
11498 }
11499
11500 kmem_free(buf->dtb_tomax, buf->dtb_size);
fe8ab488
A
11501 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11502 dtrace_buffer_memory_inuse -= buf->dtb_size;
11503
2d21ac55
A
11504 buf->dtb_size = 0;
11505 buf->dtb_tomax = NULL;
11506 buf->dtb_xamot = NULL;
11507 }
11508}
11509
11510/*
11511 * DTrace Enabling Functions
11512 */
11513static dtrace_enabling_t *
11514dtrace_enabling_create(dtrace_vstate_t *vstate)
11515{
11516 dtrace_enabling_t *enab;
11517
11518 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11519 enab->dten_vstate = vstate;
11520
11521 return (enab);
11522}
11523
11524static void
11525dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11526{
11527 dtrace_ecbdesc_t **ndesc;
11528 size_t osize, nsize;
11529
11530 /*
11531 * We can't add to enablings after we've enabled them, or after we've
11532 * retained them.
11533 */
11534 ASSERT(enab->dten_probegen == 0);
11535 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11536
fe8ab488
A
11537 /* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
11538 if (ecb == NULL) return;
2d21ac55
A
11539
11540 if (enab->dten_ndesc < enab->dten_maxdesc) {
11541 enab->dten_desc[enab->dten_ndesc++] = ecb;
11542 return;
11543 }
11544
11545 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11546
11547 if (enab->dten_maxdesc == 0) {
11548 enab->dten_maxdesc = 1;
11549 } else {
11550 enab->dten_maxdesc <<= 1;
11551 }
11552
11553 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11554
11555 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11556 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11557 bcopy(enab->dten_desc, ndesc, osize);
11558 kmem_free(enab->dten_desc, osize);
11559
11560 enab->dten_desc = ndesc;
11561 enab->dten_desc[enab->dten_ndesc++] = ecb;
11562}
11563
11564static void
11565dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11566 dtrace_probedesc_t *pd)
11567{
11568 dtrace_ecbdesc_t *new;
11569 dtrace_predicate_t *pred;
11570 dtrace_actdesc_t *act;
11571
11572 /*
11573 * We're going to create a new ECB description that matches the
11574 * specified ECB in every way, but has the specified probe description.
11575 */
11576 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11577
11578 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11579 dtrace_predicate_hold(pred);
11580
11581 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11582 dtrace_actdesc_hold(act);
11583
11584 new->dted_action = ecb->dted_action;
11585 new->dted_pred = ecb->dted_pred;
11586 new->dted_probe = *pd;
11587 new->dted_uarg = ecb->dted_uarg;
11588
11589 dtrace_enabling_add(enab, new);
11590}
11591
11592static void
11593dtrace_enabling_dump(dtrace_enabling_t *enab)
11594{
11595 int i;
11596
11597 for (i = 0; i < enab->dten_ndesc; i++) {
11598 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11599
11600 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11601 desc->dtpd_provider, desc->dtpd_mod,
11602 desc->dtpd_func, desc->dtpd_name);
11603 }
11604}
11605
11606static void
11607dtrace_enabling_destroy(dtrace_enabling_t *enab)
11608{
11609 int i;
11610 dtrace_ecbdesc_t *ep;
11611 dtrace_vstate_t *vstate = enab->dten_vstate;
11612
5ba3f43e 11613 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11614
11615 for (i = 0; i < enab->dten_ndesc; i++) {
11616 dtrace_actdesc_t *act, *next;
11617 dtrace_predicate_t *pred;
11618
11619 ep = enab->dten_desc[i];
11620
11621 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11622 dtrace_predicate_release(pred, vstate);
11623
11624 for (act = ep->dted_action; act != NULL; act = next) {
11625 next = act->dtad_next;
11626 dtrace_actdesc_release(act, vstate);
11627 }
11628
11629 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11630 }
11631
11632 kmem_free(enab->dten_desc,
11633 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11634
11635 /*
11636 * If this was a retained enabling, decrement the dts_nretained count
11637 * and take it off of the dtrace_retained list.
11638 */
11639 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11640 dtrace_retained == enab) {
11641 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11642 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11643 enab->dten_vstate->dtvs_state->dts_nretained--;
b0d623f7 11644 dtrace_retained_gen++;
2d21ac55
A
11645 }
11646
11647 if (enab->dten_prev == NULL) {
11648 if (dtrace_retained == enab) {
11649 dtrace_retained = enab->dten_next;
11650
11651 if (dtrace_retained != NULL)
11652 dtrace_retained->dten_prev = NULL;
11653 }
11654 } else {
11655 ASSERT(enab != dtrace_retained);
11656 ASSERT(dtrace_retained != NULL);
11657 enab->dten_prev->dten_next = enab->dten_next;
11658 }
11659
11660 if (enab->dten_next != NULL) {
11661 ASSERT(dtrace_retained != NULL);
11662 enab->dten_next->dten_prev = enab->dten_prev;
11663 }
11664
11665 kmem_free(enab, sizeof (dtrace_enabling_t));
11666}
11667
11668static int
11669dtrace_enabling_retain(dtrace_enabling_t *enab)
11670{
11671 dtrace_state_t *state;
11672
5ba3f43e 11673 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11674 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11675 ASSERT(enab->dten_vstate != NULL);
11676
11677 state = enab->dten_vstate->dtvs_state;
11678 ASSERT(state != NULL);
11679
11680 /*
11681 * We only allow each state to retain dtrace_retain_max enablings.
11682 */
11683 if (state->dts_nretained >= dtrace_retain_max)
11684 return (ENOSPC);
11685
11686 state->dts_nretained++;
b0d623f7 11687 dtrace_retained_gen++;
2d21ac55
A
11688
11689 if (dtrace_retained == NULL) {
11690 dtrace_retained = enab;
11691 return (0);
11692 }
11693
11694 enab->dten_next = dtrace_retained;
11695 dtrace_retained->dten_prev = enab;
11696 dtrace_retained = enab;
11697
11698 return (0);
11699}
11700
11701static int
11702dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11703 dtrace_probedesc_t *create)
11704{
11705 dtrace_enabling_t *new, *enab;
11706 int found = 0, err = ENOENT;
11707
5ba3f43e 11708 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11709 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11710 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11711 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11712 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11713
11714 new = dtrace_enabling_create(&state->dts_vstate);
11715
11716 /*
11717 * Iterate over all retained enablings, looking for enablings that
11718 * match the specified state.
11719 */
11720 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11721 int i;
11722
11723 /*
11724 * dtvs_state can only be NULL for helper enablings -- and
11725 * helper enablings can't be retained.
11726 */
11727 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11728
11729 if (enab->dten_vstate->dtvs_state != state)
11730 continue;
11731
11732 /*
11733 * Now iterate over each probe description; we're looking for
11734 * an exact match to the specified probe description.
11735 */
11736 for (i = 0; i < enab->dten_ndesc; i++) {
11737 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11738 dtrace_probedesc_t *pd = &ep->dted_probe;
11739
fe8ab488 11740 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7
A
11741 if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
11742 continue;
11743
11744 if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
11745 continue;
11746
11747 if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
11748 continue;
11749
11750 if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
11751 continue;
2d21ac55
A
11752
11753 /*
11754 * We have a winning probe! Add it to our growing
11755 * enabling.
11756 */
11757 found = 1;
11758 dtrace_enabling_addlike(new, ep, create);
11759 }
11760 }
11761
11762 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11763 dtrace_enabling_destroy(new);
11764 return (err);
11765 }
11766
11767 return (0);
11768}
11769
11770static void
11771dtrace_enabling_retract(dtrace_state_t *state)
11772{
11773 dtrace_enabling_t *enab, *next;
11774
5ba3f43e 11775 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11776
11777 /*
11778 * Iterate over all retained enablings, destroy the enablings retained
11779 * for the specified state.
11780 */
11781 for (enab = dtrace_retained; enab != NULL; enab = next) {
11782 next = enab->dten_next;
11783
11784 /*
11785 * dtvs_state can only be NULL for helper enablings -- and
11786 * helper enablings can't be retained.
11787 */
11788 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11789
11790 if (enab->dten_vstate->dtvs_state == state) {
11791 ASSERT(state->dts_nretained > 0);
11792 dtrace_enabling_destroy(enab);
11793 }
11794 }
11795
11796 ASSERT(state->dts_nretained == 0);
11797}
11798
11799static int
39037602 11800dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched, dtrace_match_cond_t *cond)
2d21ac55
A
11801{
11802 int i = 0;
6d2010ae 11803 int total_matched = 0, matched = 0;
2d21ac55 11804
5ba3f43e
A
11805 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11806 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11807
11808 for (i = 0; i < enab->dten_ndesc; i++) {
11809 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11810
11811 enab->dten_current = ep;
11812 enab->dten_error = 0;
11813
39037602
A
11814 /**
11815 * Before doing a dtrace_probe_enable, which is really
11816 * expensive, check that this enabling matches the matching precondition
11817 * if we have one
11818 */
11819 if (cond && (cond->dmc_func(&ep->dted_probe, cond->dmc_data) == 0)) {
11820 continue;
11821 }
6d2010ae
A
11822 /*
11823 * If a provider failed to enable a probe then get out and
11824 * let the consumer know we failed.
11825 */
d190cdc3 11826 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab, ep)) < 0)
6d2010ae
A
11827 return (EBUSY);
11828
11829 total_matched += matched;
2d21ac55
A
11830
11831 if (enab->dten_error != 0) {
11832 /*
11833 * If we get an error half-way through enabling the
11834 * probes, we kick out -- perhaps with some number of
11835 * them enabled. Leaving enabled probes enabled may
11836 * be slightly confusing for user-level, but we expect
11837 * that no one will attempt to actually drive on in
11838 * the face of such errors. If this is an anonymous
11839 * enabling (indicated with a NULL nmatched pointer),
11840 * we cmn_err() a message. We aren't expecting to
11841 * get such an error -- such as it can exist at all,
11842 * it would be a result of corrupted DOF in the driver
11843 * properties.
11844 */
11845 if (nmatched == NULL) {
11846 cmn_err(CE_WARN, "dtrace_enabling_match() "
11847 "error on %p: %d", (void *)ep,
11848 enab->dten_error);
11849 }
11850
11851 return (enab->dten_error);
11852 }
d190cdc3
A
11853
11854 ep->dted_probegen = dtrace_probegen;
2d21ac55
A
11855 }
11856
2d21ac55 11857 if (nmatched != NULL)
6d2010ae 11858 *nmatched = total_matched;
2d21ac55
A
11859
11860 return (0);
11861}
11862
11863static void
39037602 11864dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond)
2d21ac55
A
11865{
11866 dtrace_enabling_t *enab;
11867
11868 lck_mtx_lock(&cpu_lock);
11869 lck_mtx_lock(&dtrace_lock);
11870
11871 /*
b0d623f7
A
11872 * Iterate over all retained enablings to see if any probes match
11873 * against them. We only perform this operation on enablings for which
11874 * we have sufficient permissions by virtue of being in the global zone
11875 * or in the same zone as the DTrace client. Because we can be called
11876 * after dtrace_detach() has been called, we cannot assert that there
11877 * are retained enablings. We can safely load from dtrace_retained,
11878 * however: the taskq_destroy() at the end of dtrace_detach() will
11879 * block pending our completion.
2d21ac55 11880 */
2d21ac55 11881
fe8ab488
A
11882 /*
11883 * Darwin doesn't do zones.
11884 * Behave as if always in "global" zone."
11885 */
11886 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
39037602 11887 (void) dtrace_enabling_match(enab, NULL, cond);
2d21ac55
A
11888 }
11889
b0d623f7
A
11890 lck_mtx_unlock(&dtrace_lock);
11891 lck_mtx_unlock(&cpu_lock);
39037602
A
11892
11893}
11894
11895static void
11896dtrace_enabling_matchall(void)
11897{
11898 dtrace_enabling_matchall_with_cond(NULL);
2d21ac55
A
11899}
11900
39037602
A
11901
11902
2d21ac55
A
11903/*
11904 * If an enabling is to be enabled without having matched probes (that is, if
11905 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11906 * enabling must be _primed_ by creating an ECB for every ECB description.
11907 * This must be done to assure that we know the number of speculations, the
11908 * number of aggregations, the minimum buffer size needed, etc. before we
11909 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11910 * enabling any probes, we create ECBs for every ECB decription, but with a
11911 * NULL probe -- which is exactly what this function does.
11912 */
11913static void
11914dtrace_enabling_prime(dtrace_state_t *state)
11915{
11916 dtrace_enabling_t *enab;
11917 int i;
11918
11919 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11920 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11921
11922 if (enab->dten_vstate->dtvs_state != state)
11923 continue;
11924
11925 /*
11926 * We don't want to prime an enabling more than once, lest
11927 * we allow a malicious user to induce resource exhaustion.
11928 * (The ECBs that result from priming an enabling aren't
11929 * leaked -- but they also aren't deallocated until the
11930 * consumer state is destroyed.)
11931 */
11932 if (enab->dten_primed)
11933 continue;
11934
11935 for (i = 0; i < enab->dten_ndesc; i++) {
11936 enab->dten_current = enab->dten_desc[i];
d190cdc3 11937 (void) dtrace_probe_enable(NULL, enab, NULL);
2d21ac55
A
11938 }
11939
11940 enab->dten_primed = 1;
11941 }
11942}
11943
11944/*
11945 * Called to indicate that probes should be provided due to retained
11946 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11947 * must take an initial lap through the enabling calling the dtps_provide()
11948 * entry point explicitly to allow for autocreated probes.
11949 */
11950static void
11951dtrace_enabling_provide(dtrace_provider_t *prv)
11952{
11953 int i, all = 0;
11954 dtrace_probedesc_t desc;
b0d623f7 11955 dtrace_genid_t gen;
2d21ac55 11956
5ba3f43e
A
11957 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11958 LCK_MTX_ASSERT(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
11959
11960 if (prv == NULL) {
11961 all = 1;
11962 prv = dtrace_provider;
11963 }
11964
11965 do {
b0d623f7 11966 dtrace_enabling_t *enab;
2d21ac55
A
11967 void *parg = prv->dtpv_arg;
11968
b0d623f7
A
11969retry:
11970 gen = dtrace_retained_gen;
11971 for (enab = dtrace_retained; enab != NULL;
11972 enab = enab->dten_next) {
2d21ac55
A
11973 for (i = 0; i < enab->dten_ndesc; i++) {
11974 desc = enab->dten_desc[i]->dted_probe;
11975 lck_mtx_unlock(&dtrace_lock);
11976 prv->dtpv_pops.dtps_provide(parg, &desc);
11977 lck_mtx_lock(&dtrace_lock);
b0d623f7
A
11978 /*
11979 * Process the retained enablings again if
11980 * they have changed while we weren't holding
11981 * dtrace_lock.
11982 */
11983 if (gen != dtrace_retained_gen)
11984 goto retry;
2d21ac55
A
11985 }
11986 }
11987 } while (all && (prv = prv->dtpv_next) != NULL);
11988
11989 lck_mtx_unlock(&dtrace_lock);
11990 dtrace_probe_provide(NULL, all ? NULL : prv);
11991 lck_mtx_lock(&dtrace_lock);
11992}
11993
11994/*
11995 * DTrace DOF Functions
11996 */
11997/*ARGSUSED*/
11998static void
11999dtrace_dof_error(dof_hdr_t *dof, const char *str)
12000{
b0d623f7 12001#pragma unused(dof) /* __APPLE__ */
2d21ac55
A
12002 if (dtrace_err_verbose)
12003 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12004
12005#ifdef DTRACE_ERRDEBUG
12006 dtrace_errdebug(str);
12007#endif
12008}
12009
12010/*
12011 * Create DOF out of a currently enabled state. Right now, we only create
12012 * DOF containing the run-time options -- but this could be expanded to create
12013 * complete DOF representing the enabled state.
12014 */
12015static dof_hdr_t *
12016dtrace_dof_create(dtrace_state_t *state)
12017{
12018 dof_hdr_t *dof;
12019 dof_sec_t *sec;
12020 dof_optdesc_t *opt;
12021 int i, len = sizeof (dof_hdr_t) +
12022 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12023 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12024
5ba3f43e 12025 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
12026
12027 dof = dt_kmem_zalloc_aligned(len, 8, KM_SLEEP);
12028 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12029 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12030 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12031 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12032
12033 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12034 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12035 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12036 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12037 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12038 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12039
12040 dof->dofh_flags = 0;
12041 dof->dofh_hdrsize = sizeof (dof_hdr_t);
12042 dof->dofh_secsize = sizeof (dof_sec_t);
12043 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
12044 dof->dofh_secoff = sizeof (dof_hdr_t);
12045 dof->dofh_loadsz = len;
12046 dof->dofh_filesz = len;
12047 dof->dofh_pad = 0;
12048
12049 /*
12050 * Fill in the option section header...
12051 */
12052 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12053 sec->dofs_type = DOF_SECT_OPTDESC;
12054 sec->dofs_align = sizeof (uint64_t);
12055 sec->dofs_flags = DOF_SECF_LOAD;
12056 sec->dofs_entsize = sizeof (dof_optdesc_t);
12057
12058 opt = (dof_optdesc_t *)((uintptr_t)sec +
12059 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12060
12061 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12062 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12063
12064 for (i = 0; i < DTRACEOPT_MAX; i++) {
12065 opt[i].dofo_option = i;
12066 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12067 opt[i].dofo_value = state->dts_options[i];
12068 }
12069
12070 return (dof);
12071}
12072
12073static dof_hdr_t *
b0d623f7 12074dtrace_dof_copyin(user_addr_t uarg, int *errp)
2d21ac55
A
12075{
12076 dof_hdr_t hdr, *dof;
12077
5ba3f43e 12078 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
2d21ac55
A
12079
12080 /*
12081 * First, we're going to copyin() the sizeof (dof_hdr_t).
12082 */
b0d623f7 12083 if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
2d21ac55
A
12084 dtrace_dof_error(NULL, "failed to copyin DOF header");
12085 *errp = EFAULT;
12086 return (NULL);
12087 }
12088
12089 /*
12090 * Now we'll allocate the entire DOF and copy it in -- provided
12091 * that the length isn't outrageous.
12092 */
b0d623f7 12093 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
2d21ac55
A
12094 dtrace_dof_error(&hdr, "load size exceeds maximum");
12095 *errp = E2BIG;
12096 return (NULL);
12097 }
12098
12099 if (hdr.dofh_loadsz < sizeof (hdr)) {
12100 dtrace_dof_error(&hdr, "invalid load size");
12101 *errp = EINVAL;
12102 return (NULL);
12103 }
12104
12105 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12106
6d2010ae
A
12107 if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
12108 dof->dofh_loadsz != hdr.dofh_loadsz) {
12109 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12110 *errp = EFAULT;
12111 return (NULL);
12112 }
2d21ac55
A
12113
12114 return (dof);
12115}
12116
2d21ac55
A
12117static dof_hdr_t *
12118dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
12119{
12120 dof_hdr_t hdr, *dof;
12121
5ba3f43e 12122 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
2d21ac55
A
12123
12124 /*
12125 * First, we're going to copyin() the sizeof (dof_hdr_t).
12126 */
12127 if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
12128 dtrace_dof_error(NULL, "failed to copyin DOF header");
12129 *errp = EFAULT;
12130 return (NULL);
12131 }
12132
12133 /*
12134 * Now we'll allocate the entire DOF and copy it in -- provided
12135 * that the length isn't outrageous.
12136 */
b0d623f7 12137 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
2d21ac55
A
12138 dtrace_dof_error(&hdr, "load size exceeds maximum");
12139 *errp = E2BIG;
12140 return (NULL);
12141 }
12142
12143 if (hdr.dofh_loadsz < sizeof (hdr)) {
12144 dtrace_dof_error(&hdr, "invalid load size");
12145 *errp = EINVAL;
12146 return (NULL);
12147 }
12148
12149 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12150
12151 if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
12152 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12153 *errp = EFAULT;
12154 return (NULL);
12155 }
12156
12157 return (dof);
12158}
12159
a39ff7e2
A
12160static void
12161dtrace_dof_destroy(dof_hdr_t *dof)
12162{
12163 dt_kmem_free_aligned(dof, dof->dofh_loadsz);
12164}
12165
2d21ac55
A
12166static dof_hdr_t *
12167dtrace_dof_property(const char *name)
12168{
a39ff7e2 12169 unsigned int len;
2d21ac55
A
12170 dof_hdr_t *dof;
12171
a39ff7e2
A
12172 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
12173 return NULL;
12174 }
12175
12176 if (!PEReadNVRAMProperty(name, NULL, &len)) {
12177 return NULL;
12178 }
2d21ac55 12179
a39ff7e2
A
12180 dof = dt_kmem_alloc_aligned(len, 8, KM_SLEEP);
12181
12182 if (!PEReadNVRAMProperty(name, dof, &len)) {
12183 dtrace_dof_destroy(dof);
12184 dtrace_dof_error(NULL, "unreadable DOF");
12185 return NULL;
12186 }
2d21ac55
A
12187
12188 if (len < sizeof (dof_hdr_t)) {
a39ff7e2 12189 dtrace_dof_destroy(dof);
2d21ac55
A
12190 dtrace_dof_error(NULL, "truncated header");
12191 return (NULL);
12192 }
12193
a39ff7e2
A
12194 if (len < dof->dofh_loadsz) {
12195 dtrace_dof_destroy(dof);
2d21ac55
A
12196 dtrace_dof_error(NULL, "truncated DOF");
12197 return (NULL);
12198 }
12199
a39ff7e2
A
12200 if (len != dof->dofh_loadsz) {
12201 dtrace_dof_destroy(dof);
12202 dtrace_dof_error(NULL, "invalid DOF size");
2d21ac55
A
12203 return (NULL);
12204 }
12205
a39ff7e2
A
12206 if (dof->dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
12207 dtrace_dof_destroy(dof);
12208 dtrace_dof_error(NULL, "oversized DOF");
12209 return (NULL);
12210 }
2d21ac55
A
12211
12212 return (dof);
12213}
12214
2d21ac55
A
12215/*
12216 * Return the dof_sec_t pointer corresponding to a given section index. If the
12217 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
12218 * a type other than DOF_SECT_NONE is specified, the header is checked against
12219 * this type and NULL is returned if the types do not match.
12220 */
12221static dof_sec_t *
12222dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12223{
12224 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12225 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12226
12227 if (i >= dof->dofh_secnum) {
12228 dtrace_dof_error(dof, "referenced section index is invalid");
12229 return (NULL);
12230 }
12231
12232 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12233 dtrace_dof_error(dof, "referenced section is not loadable");
12234 return (NULL);
12235 }
12236
12237 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12238 dtrace_dof_error(dof, "referenced section is the wrong type");
12239 return (NULL);
12240 }
12241
12242 return (sec);
12243}
12244
12245static dtrace_probedesc_t *
12246dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12247{
12248 dof_probedesc_t *probe;
12249 dof_sec_t *strtab;
12250 uintptr_t daddr = (uintptr_t)dof;
12251 uintptr_t str;
12252 size_t size;
12253
12254 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12255 dtrace_dof_error(dof, "invalid probe section");
12256 return (NULL);
12257 }
12258
12259 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12260 dtrace_dof_error(dof, "bad alignment in probe description");
12261 return (NULL);
12262 }
12263
12264 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12265 dtrace_dof_error(dof, "truncated probe description");
12266 return (NULL);
12267 }
12268
12269 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12270 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12271
12272 if (strtab == NULL)
12273 return (NULL);
12274
12275 str = daddr + strtab->dofs_offset;
12276 size = strtab->dofs_size;
12277
12278 if (probe->dofp_provider >= strtab->dofs_size) {
12279 dtrace_dof_error(dof, "corrupt probe provider");
12280 return (NULL);
12281 }
12282
12283 (void) strncpy(desc->dtpd_provider,
12284 (char *)(str + probe->dofp_provider),
12285 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
fe8ab488
A
12286
12287 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7 12288 desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
2d21ac55
A
12289
12290 if (probe->dofp_mod >= strtab->dofs_size) {
12291 dtrace_dof_error(dof, "corrupt probe module");
12292 return (NULL);
12293 }
12294
12295 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12296 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
fe8ab488
A
12297
12298 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7 12299 desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
2d21ac55
A
12300
12301 if (probe->dofp_func >= strtab->dofs_size) {
12302 dtrace_dof_error(dof, "corrupt probe function");
12303 return (NULL);
12304 }
12305
12306 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12307 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
fe8ab488
A
12308
12309 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7 12310 desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
2d21ac55
A
12311
12312 if (probe->dofp_name >= strtab->dofs_size) {
12313 dtrace_dof_error(dof, "corrupt probe name");
12314 return (NULL);
12315 }
12316
12317 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12318 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
fe8ab488
A
12319
12320 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7 12321 desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
2d21ac55
A
12322
12323 return (desc);
12324}
12325
12326static dtrace_difo_t *
12327dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12328 cred_t *cr)
12329{
12330 dtrace_difo_t *dp;
12331 size_t ttl = 0;
12332 dof_difohdr_t *dofd;
12333 uintptr_t daddr = (uintptr_t)dof;
c910b4d9 12334 size_t max_size = dtrace_difo_maxsize;
b0d623f7
A
12335 uint_t i;
12336 int l, n;
b0d623f7 12337
2d21ac55
A
12338
12339 static const struct {
12340 int section;
12341 int bufoffs;
12342 int lenoffs;
12343 int entsize;
12344 int align;
12345 const char *msg;
12346 } difo[] = {
12347 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12348 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12349 sizeof (dif_instr_t), "multiple DIF sections" },
12350
12351 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12352 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12353 sizeof (uint64_t), "multiple integer tables" },
12354
12355 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12356 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12357 sizeof (char), "multiple string tables" },
12358
12359 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12360 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12361 sizeof (uint_t), "multiple variable tables" },
12362
2d21ac55 12363 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
2d21ac55
A
12364 };
12365
12366 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12367 dtrace_dof_error(dof, "invalid DIFO header section");
12368 return (NULL);
12369 }
12370
12371 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12372 dtrace_dof_error(dof, "bad alignment in DIFO header");
12373 return (NULL);
12374 }
12375
12376 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12377 sec->dofs_size % sizeof (dof_secidx_t)) {
12378 dtrace_dof_error(dof, "bad size in DIFO header");
12379 return (NULL);
12380 }
12381
12382 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12383 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12384
12385 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12386 dp->dtdo_rtype = dofd->dofd_rtype;
12387
12388 for (l = 0; l < n; l++) {
12389 dof_sec_t *subsec;
12390 void **bufp;
12391 uint32_t *lenp;
12392
12393 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12394 dofd->dofd_links[l])) == NULL)
12395 goto err; /* invalid section link */
12396
c910b4d9 12397 if (ttl + subsec->dofs_size > max_size) {
2d21ac55
A
12398 dtrace_dof_error(dof, "exceeds maximum size");
12399 goto err;
12400 }
12401
12402 ttl += subsec->dofs_size;
12403
12404 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
b0d623f7 12405
b0d623f7
A
12406 if (subsec->dofs_type != (uint32_t)difo[i].section)
12407 continue;
2d21ac55
A
12408
12409 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12410 dtrace_dof_error(dof, "section not loaded");
12411 goto err;
12412 }
12413
b0d623f7
A
12414 if (subsec->dofs_align != (uint32_t)difo[i].align) {
12415 dtrace_dof_error(dof, "bad alignment");
12416 goto err;
12417 }
2d21ac55
A
12418
12419 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12420 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12421
12422 if (*bufp != NULL) {
12423 dtrace_dof_error(dof, difo[i].msg);
12424 goto err;
12425 }
12426
b0d623f7
A
12427 if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
12428 dtrace_dof_error(dof, "entry size mismatch");
12429 goto err;
12430 }
2d21ac55
A
12431
12432 if (subsec->dofs_entsize != 0 &&
12433 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12434 dtrace_dof_error(dof, "corrupt entry size");
12435 goto err;
12436 }
12437
12438 *lenp = subsec->dofs_size;
12439 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12440 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12441 *bufp, subsec->dofs_size);
12442
12443 if (subsec->dofs_entsize != 0)
12444 *lenp /= subsec->dofs_entsize;
12445
12446 break;
12447 }
12448
12449 /*
12450 * If we encounter a loadable DIFO sub-section that is not
12451 * known to us, assume this is a broken program and fail.
12452 */
12453 if (difo[i].section == DOF_SECT_NONE &&
12454 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12455 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12456 goto err;
12457 }
12458 }
b0d623f7 12459
2d21ac55
A
12460 if (dp->dtdo_buf == NULL) {
12461 /*
12462 * We can't have a DIF object without DIF text.
12463 */
12464 dtrace_dof_error(dof, "missing DIF text");
12465 goto err;
12466 }
12467
12468 /*
12469 * Before we validate the DIF object, run through the variable table
12470 * looking for the strings -- if any of their size are under, we'll set
12471 * their size to be the system-wide default string size. Note that
12472 * this should _not_ happen if the "strsize" option has been set --
12473 * in this case, the compiler should have set the size to reflect the
12474 * setting of the option.
12475 */
12476 for (i = 0; i < dp->dtdo_varlen; i++) {
12477 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12478 dtrace_diftype_t *t = &v->dtdv_type;
12479
12480 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12481 continue;
12482
12483 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12484 t->dtdt_size = dtrace_strsize_default;
12485 }
12486
12487 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12488 goto err;
12489
12490 dtrace_difo_init(dp, vstate);
12491 return (dp);
12492
12493err:
12494 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12495 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12496 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12497 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12498
12499 kmem_free(dp, sizeof (dtrace_difo_t));
12500 return (NULL);
12501}
12502
12503static dtrace_predicate_t *
12504dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12505 cred_t *cr)
12506{
12507 dtrace_difo_t *dp;
12508
12509 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12510 return (NULL);
12511
12512 return (dtrace_predicate_create(dp));
12513}
12514
12515static dtrace_actdesc_t *
12516dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12517 cred_t *cr)
12518{
12519 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12520 dof_actdesc_t *desc;
12521 dof_sec_t *difosec;
12522 size_t offs;
12523 uintptr_t daddr = (uintptr_t)dof;
12524 uint64_t arg;
12525 dtrace_actkind_t kind;
12526
12527 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12528 dtrace_dof_error(dof, "invalid action section");
12529 return (NULL);
12530 }
12531
12532 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12533 dtrace_dof_error(dof, "truncated action description");
12534 return (NULL);
12535 }
12536
12537 if (sec->dofs_align != sizeof (uint64_t)) {
12538 dtrace_dof_error(dof, "bad alignment in action description");
12539 return (NULL);
12540 }
12541
12542 if (sec->dofs_size < sec->dofs_entsize) {
12543 dtrace_dof_error(dof, "section entry size exceeds total size");
12544 return (NULL);
12545 }
12546
12547 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12548 dtrace_dof_error(dof, "bad entry size in action description");
12549 return (NULL);
12550 }
12551
12552 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12553 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12554 return (NULL);
12555 }
12556
12557 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12558 desc = (dof_actdesc_t *)(daddr +
12559 (uintptr_t)sec->dofs_offset + offs);
12560 kind = (dtrace_actkind_t)desc->dofa_kind;
12561
3e170ce0
A
12562 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12563 (kind != DTRACEACT_PRINTA || desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12564 (kind == DTRACEACT_DIFEXPR && desc->dofa_strtab != DOF_SECIDX_NONE))
12565 {
2d21ac55
A
12566 dof_sec_t *strtab;
12567 char *str, *fmt;
12568 uint64_t i;
12569
12570 /*
3e170ce0
A
12571 * The argument to these actions is an index into the
12572 * DOF string table. For printf()-like actions, this
12573 * is the format string. For print(), this is the
12574 * CTF type of the expression result.
2d21ac55
A
12575 */
12576 if ((strtab = dtrace_dof_sect(dof,
12577 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12578 goto err;
12579
12580 str = (char *)((uintptr_t)dof +
12581 (uintptr_t)strtab->dofs_offset);
12582
12583 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12584 if (str[i] == '\0')
12585 break;
12586 }
12587
12588 if (i >= strtab->dofs_size) {
12589 dtrace_dof_error(dof, "bogus format string");
12590 goto err;
12591 }
12592
12593 if (i == desc->dofa_arg) {
12594 dtrace_dof_error(dof, "empty format string");
12595 goto err;
12596 }
12597
12598 i -= desc->dofa_arg;
12599 fmt = kmem_alloc(i + 1, KM_SLEEP);
12600 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12601 arg = (uint64_t)(uintptr_t)fmt;
12602 } else {
12603 if (kind == DTRACEACT_PRINTA) {
12604 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12605 arg = 0;
12606 } else {
12607 arg = desc->dofa_arg;
12608 }
12609 }
12610
12611 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12612 desc->dofa_uarg, arg);
12613
12614 if (last != NULL) {
12615 last->dtad_next = act;
12616 } else {
12617 first = act;
12618 }
12619
12620 last = act;
12621
12622 if (desc->dofa_difo == DOF_SECIDX_NONE)
12623 continue;
12624
12625 if ((difosec = dtrace_dof_sect(dof,
12626 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12627 goto err;
12628
12629 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12630
12631 if (act->dtad_difo == NULL)
12632 goto err;
12633 }
12634
12635 ASSERT(first != NULL);
12636 return (first);
12637
12638err:
12639 for (act = first; act != NULL; act = next) {
12640 next = act->dtad_next;
12641 dtrace_actdesc_release(act, vstate);
12642 }
12643
12644 return (NULL);
12645}
12646
12647static dtrace_ecbdesc_t *
12648dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12649 cred_t *cr)
12650{
12651 dtrace_ecbdesc_t *ep;
12652 dof_ecbdesc_t *ecb;
12653 dtrace_probedesc_t *desc;
12654 dtrace_predicate_t *pred = NULL;
12655
12656 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12657 dtrace_dof_error(dof, "truncated ECB description");
12658 return (NULL);
12659 }
12660
12661 if (sec->dofs_align != sizeof (uint64_t)) {
12662 dtrace_dof_error(dof, "bad alignment in ECB description");
12663 return (NULL);
12664 }
12665
12666 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12667 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12668
12669 if (sec == NULL)
12670 return (NULL);
12671
12672 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12673 ep->dted_uarg = ecb->dofe_uarg;
12674 desc = &ep->dted_probe;
12675
12676 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12677 goto err;
12678
12679 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12680 if ((sec = dtrace_dof_sect(dof,
12681 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12682 goto err;
12683
12684 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12685 goto err;
12686
12687 ep->dted_pred.dtpdd_predicate = pred;
12688 }
12689
12690 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12691 if ((sec = dtrace_dof_sect(dof,
12692 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12693 goto err;
12694
12695 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12696
12697 if (ep->dted_action == NULL)
12698 goto err;
12699 }
12700
12701 return (ep);
12702
12703err:
12704 if (pred != NULL)
12705 dtrace_predicate_release(pred, vstate);
12706 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12707 return (NULL);
12708}
12709
2d21ac55 12710/*
fe8ab488
A
12711 * APPLE NOTE: dyld handles dof relocation.
12712 * Darwin does not need dtrace_dof_relocate()
2d21ac55 12713 */
2d21ac55
A
12714
12715/*
12716 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12717 * header: it should be at the front of a memory region that is at least
12718 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12719 * size. It need not be validated in any other way.
12720 */
12721static int
12722dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12723 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12724{
b0d623f7 12725#pragma unused(ubase) /* __APPLE__ */
2d21ac55
A
12726 uint64_t len = dof->dofh_loadsz, seclen;
12727 uintptr_t daddr = (uintptr_t)dof;
12728 dtrace_ecbdesc_t *ep;
12729 dtrace_enabling_t *enab;
12730 uint_t i;
12731
5ba3f43e 12732 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
12733 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12734
12735 /*
12736 * Check the DOF header identification bytes. In addition to checking
12737 * valid settings, we also verify that unused bits/bytes are zeroed so
12738 * we can use them later without fear of regressing existing binaries.
12739 */
12740 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12741 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12742 dtrace_dof_error(dof, "DOF magic string mismatch");
12743 return (-1);
12744 }
12745
12746 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12747 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12748 dtrace_dof_error(dof, "DOF has invalid data model");
12749 return (-1);
12750 }
12751
12752 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12753 dtrace_dof_error(dof, "DOF encoding mismatch");
12754 return (-1);
12755 }
12756
2d21ac55 12757 /*
fe8ab488 12758 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
2d21ac55
A
12759 */
12760 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
12761 dtrace_dof_error(dof, "DOF version mismatch");
12762 return (-1);
12763 }
2d21ac55
A
12764
12765 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12766 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12767 return (-1);
12768 }
12769
12770 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12771 dtrace_dof_error(dof, "DOF uses too many integer registers");
12772 return (-1);
12773 }
12774
12775 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12776 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12777 return (-1);
12778 }
12779
12780 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12781 if (dof->dofh_ident[i] != 0) {
12782 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12783 return (-1);
12784 }
12785 }
12786
12787 if (dof->dofh_flags & ~DOF_FL_VALID) {
12788 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12789 return (-1);
12790 }
12791
12792 if (dof->dofh_secsize == 0) {
12793 dtrace_dof_error(dof, "zero section header size");
12794 return (-1);
12795 }
12796
12797 /*
12798 * Check that the section headers don't exceed the amount of DOF
12799 * data. Note that we cast the section size and number of sections
12800 * to uint64_t's to prevent possible overflow in the multiplication.
12801 */
12802 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12803
12804 if (dof->dofh_secoff > len || seclen > len ||
12805 dof->dofh_secoff + seclen > len) {
12806 dtrace_dof_error(dof, "truncated section headers");
12807 return (-1);
12808 }
12809
12810 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12811 dtrace_dof_error(dof, "misaligned section headers");
12812 return (-1);
12813 }
12814
12815 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12816 dtrace_dof_error(dof, "misaligned section size");
12817 return (-1);
12818 }
12819
12820 /*
12821 * Take an initial pass through the section headers to be sure that
12822 * the headers don't have stray offsets. If the 'noprobes' flag is
12823 * set, do not permit sections relating to providers, probes, or args.
12824 */
12825 for (i = 0; i < dof->dofh_secnum; i++) {
12826 dof_sec_t *sec = (dof_sec_t *)(daddr +
12827 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12828
12829 if (noprobes) {
12830 switch (sec->dofs_type) {
12831 case DOF_SECT_PROVIDER:
12832 case DOF_SECT_PROBES:
12833 case DOF_SECT_PRARGS:
12834 case DOF_SECT_PROFFS:
12835 dtrace_dof_error(dof, "illegal sections "
12836 "for enabling");
12837 return (-1);
12838 }
12839 }
12840
12841 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12842 continue; /* just ignore non-loadable sections */
12843
12844 if (sec->dofs_align & (sec->dofs_align - 1)) {
12845 dtrace_dof_error(dof, "bad section alignment");
12846 return (-1);
12847 }
12848
12849 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12850 dtrace_dof_error(dof, "misaligned section");
12851 return (-1);
12852 }
12853
12854 if (sec->dofs_offset > len || sec->dofs_size > len ||
12855 sec->dofs_offset + sec->dofs_size > len) {
12856 dtrace_dof_error(dof, "corrupt section header");
12857 return (-1);
12858 }
12859
12860 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12861 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12862 dtrace_dof_error(dof, "non-terminating string table");
12863 return (-1);
12864 }
12865 }
12866
b0d623f7 12867 /*
fe8ab488
A
12868 * APPLE NOTE: We have no further relocation to perform.
12869 * All dof values are relative offsets.
b0d623f7 12870 */
2d21ac55
A
12871
12872 if ((enab = *enabp) == NULL)
12873 enab = *enabp = dtrace_enabling_create(vstate);
12874
12875 for (i = 0; i < dof->dofh_secnum; i++) {
12876 dof_sec_t *sec = (dof_sec_t *)(daddr +
12877 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12878
12879 if (sec->dofs_type != DOF_SECT_ECBDESC)
12880 continue;
12881
fe8ab488
A
12882 /*
12883 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
12884 * not all paths out of inlined dtrace_dof_ecbdesc
12885 * are checked for the NULL return value.
12886 * Check for NULL explicitly here.
12887 */
2d21ac55
A
12888 ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
12889 if (ep == NULL) {
12890 dtrace_enabling_destroy(enab);
12891 *enabp = NULL;
12892 return (-1);
12893 }
2d21ac55
A
12894
12895 dtrace_enabling_add(enab, ep);
12896 }
12897
12898 return (0);
12899}
12900
12901/*
12902 * Process DOF for any options. This routine assumes that the DOF has been
12903 * at least processed by dtrace_dof_slurp().
12904 */
12905static int
12906dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12907{
b0d623f7
A
12908 uint_t i;
12909 int rval;
2d21ac55
A
12910 uint32_t entsize;
12911 size_t offs;
12912 dof_optdesc_t *desc;
12913
12914 for (i = 0; i < dof->dofh_secnum; i++) {
12915 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12916 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12917
12918 if (sec->dofs_type != DOF_SECT_OPTDESC)
12919 continue;
12920
12921 if (sec->dofs_align != sizeof (uint64_t)) {
12922 dtrace_dof_error(dof, "bad alignment in "
12923 "option description");
12924 return (EINVAL);
12925 }
12926
12927 if ((entsize = sec->dofs_entsize) == 0) {
12928 dtrace_dof_error(dof, "zeroed option entry size");
12929 return (EINVAL);
12930 }
12931
12932 if (entsize < sizeof (dof_optdesc_t)) {
12933 dtrace_dof_error(dof, "bad option entry size");
12934 return (EINVAL);
12935 }
12936
12937 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12938 desc = (dof_optdesc_t *)((uintptr_t)dof +
12939 (uintptr_t)sec->dofs_offset + offs);
12940
12941 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12942 dtrace_dof_error(dof, "non-zero option string");
12943 return (EINVAL);
12944 }
12945
b0d623f7 12946 if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
2d21ac55
A
12947 dtrace_dof_error(dof, "unset option");
12948 return (EINVAL);
12949 }
12950
12951 if ((rval = dtrace_state_option(state,
12952 desc->dofo_option, desc->dofo_value)) != 0) {
12953 dtrace_dof_error(dof, "rejected option");
12954 return (rval);
12955 }
12956 }
12957 }
12958
12959 return (0);
12960}
12961
12962/*
12963 * DTrace Consumer State Functions
12964 */
fe8ab488 12965static int
2d21ac55
A
12966dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12967{
c910b4d9 12968 size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
2d21ac55
A
12969 void *base;
12970 uintptr_t limit;
12971 dtrace_dynvar_t *dvar, *next, *start;
b0d623f7 12972 size_t i;
2d21ac55 12973
5ba3f43e 12974 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
12975 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12976
12977 bzero(dstate, sizeof (dtrace_dstate_t));
12978
12979 if ((dstate->dtds_chunksize = chunksize) == 0)
12980 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12981
ecc0ceb4
A
12982 VERIFY(dstate->dtds_chunksize < (LONG_MAX - sizeof (dtrace_dynhash_t)));
12983
c910b4d9
A
12984 if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12985 size = min_size;
2d21ac55
A
12986
12987 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12988 return (ENOMEM);
12989
12990 dstate->dtds_size = size;
12991 dstate->dtds_base = base;
12992 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
c910b4d9 12993 bzero(dstate->dtds_percpu, (int)NCPU * sizeof (dtrace_dstate_percpu_t));
2d21ac55
A
12994
12995 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12996
12997 if (hashsize != 1 && (hashsize & 1))
12998 hashsize--;
12999
13000 dstate->dtds_hashsize = hashsize;
13001 dstate->dtds_hash = dstate->dtds_base;
13002
13003 /*
13004 * Set all of our hash buckets to point to the single sink, and (if
13005 * it hasn't already been set), set the sink's hash value to be the
13006 * sink sentinel value. The sink is needed for dynamic variable
13007 * lookups to know that they have iterated over an entire, valid hash
13008 * chain.
13009 */
13010 for (i = 0; i < hashsize; i++)
13011 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13012
13013 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13014 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13015
13016 /*
13017 * Determine number of active CPUs. Divide free list evenly among
13018 * active CPUs.
13019 */
13020 start = (dtrace_dynvar_t *)
13021 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13022 limit = (uintptr_t)base + size;
13023
ecc0ceb4
A
13024 VERIFY((uintptr_t)start < limit);
13025 VERIFY((uintptr_t)start >= (uintptr_t)base);
13026
c910b4d9 13027 maxper = (limit - (uintptr_t)start) / (int)NCPU;
2d21ac55
A
13028 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13029
b0d623f7 13030 for (i = 0; i < NCPU; i++) {
2d21ac55
A
13031 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13032
13033 /*
13034 * If we don't even have enough chunks to make it once through
13035 * NCPUs, we're just going to allocate everything to the first
13036 * CPU. And if we're on the last CPU, we're going to allocate
13037 * whatever is left over. In either case, we set the limit to
13038 * be the limit of the dynamic variable space.
13039 */
b0d623f7 13040 if (maxper == 0 || i == NCPU - 1) {
2d21ac55
A
13041 limit = (uintptr_t)base + size;
13042 start = NULL;
13043 } else {
13044 limit = (uintptr_t)start + maxper;
13045 start = (dtrace_dynvar_t *)limit;
13046 }
13047
ecc0ceb4 13048 VERIFY(limit <= (uintptr_t)base + size);
2d21ac55
A
13049
13050 for (;;) {
13051 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13052 dstate->dtds_chunksize);
13053
13054 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13055 break;
13056
ecc0ceb4
A
13057 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
13058 (uintptr_t)dvar <= (uintptr_t)base + size);
2d21ac55
A
13059 dvar->dtdv_next = next;
13060 dvar = next;
13061 }
13062
13063 if (maxper == 0)
13064 break;
13065 }
13066
13067 return (0);
13068}
13069
fe8ab488 13070static void
2d21ac55
A
13071dtrace_dstate_fini(dtrace_dstate_t *dstate)
13072{
5ba3f43e 13073 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
13074
13075 if (dstate->dtds_base == NULL)
13076 return;
13077
13078 kmem_free(dstate->dtds_base, dstate->dtds_size);
13079 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13080}
13081
13082static void
13083dtrace_vstate_fini(dtrace_vstate_t *vstate)
13084{
13085 /*
13086 * Logical XOR, where are you?
13087 */
13088 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13089
13090 if (vstate->dtvs_nglobals > 0) {
13091 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13092 sizeof (dtrace_statvar_t *));
13093 }
13094
13095 if (vstate->dtvs_ntlocals > 0) {
13096 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13097 sizeof (dtrace_difv_t));
13098 }
13099
13100 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13101
13102 if (vstate->dtvs_nlocals > 0) {
13103 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13104 sizeof (dtrace_statvar_t *));
13105 }
13106}
13107
13108static void
13109dtrace_state_clean(dtrace_state_t *state)
13110{
13111 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13112 return;
13113
13114 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13115 dtrace_speculation_clean(state);
13116}
13117
13118static void
13119dtrace_state_deadman(dtrace_state_t *state)
13120{
13121 hrtime_t now;
13122
13123 dtrace_sync();
13124
13125 now = dtrace_gethrtime();
13126
13127 if (state != dtrace_anon.dta_state &&
13128 now - state->dts_laststatus >= dtrace_deadman_user)
13129 return;
13130
13131 /*
13132 * We must be sure that dts_alive never appears to be less than the
13133 * value upon entry to dtrace_state_deadman(), and because we lack a
13134 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13135 * store INT64_MAX to it, followed by a memory barrier, followed by
13136 * the new value. This assures that dts_alive never appears to be
13137 * less than its true value, regardless of the order in which the
13138 * stores to the underlying storage are issued.
13139 */
13140 state->dts_alive = INT64_MAX;
13141 dtrace_membar_producer();
13142 state->dts_alive = now;
13143}
13144
b0d623f7
A
13145static int
13146dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
2d21ac55
A
13147{
13148 minor_t minor;
13149 major_t major;
13150 char c[30];
13151 dtrace_state_t *state;
13152 dtrace_optval_t *opt;
c910b4d9 13153 int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
2d21ac55 13154
5ba3f43e
A
13155 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13156 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 13157
b0d623f7
A
13158 /* Cause restart */
13159 *new_state = NULL;
13160
813fb2f6
A
13161 if (devp != NULL) {
13162 minor = getminor(*devp);
13163 }
13164 else {
13165 minor = DTRACE_NCLIENTS - 1;
13166 }
2d21ac55 13167
39037602
A
13168 state = dtrace_state_allocate(minor);
13169 if (NULL == state) {
13170 printf("dtrace_open: couldn't acquire minor number %d. This usually means that too many DTrace clients are in use at the moment", minor);
13171 return (ERESTART); /* can't reacquire */
2d21ac55
A
13172 }
13173
2d21ac55
A
13174 state->dts_epid = DTRACE_EPIDNONE + 1;
13175
13176 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13177 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13178 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13179
13180 if (devp != NULL) {
13181 major = getemajor(*devp);
13182 } else {
13183 major = ddi_driver_major(dtrace_devi);
13184 }
13185
13186 state->dts_dev = makedevice(major, minor);
13187
13188 if (devp != NULL)
13189 *devp = state->dts_dev;
13190
13191 /*
13192 * We allocate NCPU buffers. On the one hand, this can be quite
13193 * a bit of memory per instance (nearly 36K on a Starcat). On the
13194 * other hand, it saves an additional memory reference in the probe
13195 * path.
13196 */
13197 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13198 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
39037602 13199 state->dts_buf_over_limit = 0;
2d21ac55
A
13200 state->dts_cleaner = CYCLIC_NONE;
13201 state->dts_deadman = CYCLIC_NONE;
13202 state->dts_vstate.dtvs_state = state;
13203
13204 for (i = 0; i < DTRACEOPT_MAX; i++)
13205 state->dts_options[i] = DTRACEOPT_UNSET;
13206
13207 /*
13208 * Set the default options.
13209 */
13210 opt = state->dts_options;
13211 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13212 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13213 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13214 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13215 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13216 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13217 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13218 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13219 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13220 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13221 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13222 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13223 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13224 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
39037602 13225 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_default;
2d21ac55
A
13226
13227 /*
13228 * Depending on the user credentials, we set flag bits which alter probe
13229 * visibility or the amount of destructiveness allowed. In the case of
13230 * actual anonymous tracing, or the possession of all privileges, all of
13231 * the normal checks are bypassed.
13232 */
39037602
A
13233#if defined(__APPLE__)
13234 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13235 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
13236 /*
13237 * Allow only proc credentials when DTrace is
13238 * restricted by the current security policy
13239 */
13240 state->dts_cred.dcr_visible = DTRACE_CRV_ALLPROC;
13241 state->dts_cred.dcr_action = DTRACE_CRA_PROC | DTRACE_CRA_PROC_CONTROL | DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13242 }
13243 else {
13244 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13245 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13246 }
13247 }
13248
13249#else
2d21ac55
A
13250 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13251 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13252 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
39037602
A
13253 }
13254 else {
2d21ac55
A
13255 /*
13256 * Set up the credentials for this instantiation. We take a
13257 * hold on the credential to prevent it from disappearing on
13258 * us; this in turn prevents the zone_t referenced by this
13259 * credential from disappearing. This means that we can
13260 * examine the credential and the zone from probe context.
13261 */
13262 crhold(cr);
13263 state->dts_cred.dcr_cred = cr;
13264
13265 /*
13266 * CRA_PROC means "we have *some* privilege for dtrace" and
13267 * unlocks the use of variables like pid, zonename, etc.
13268 */
13269 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13270 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13271 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13272 }
13273
13274 /*
13275 * dtrace_user allows use of syscall and profile providers.
13276 * If the user also has proc_owner and/or proc_zone, we
13277 * extend the scope to include additional visibility and
13278 * destructive power.
13279 */
13280 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13281 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13282 state->dts_cred.dcr_visible |=
13283 DTRACE_CRV_ALLPROC;
13284
13285 state->dts_cred.dcr_action |=
13286 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13287 }
13288
13289 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13290 state->dts_cred.dcr_visible |=
13291 DTRACE_CRV_ALLZONE;
13292
13293 state->dts_cred.dcr_action |=
13294 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13295 }
13296
13297 /*
13298 * If we have all privs in whatever zone this is,
13299 * we can do destructive things to processes which
13300 * have altered credentials.
fe8ab488
A
13301 *
13302 * APPLE NOTE: Darwin doesn't do zones.
13303 * Behave as if zone always has destructive privs.
2d21ac55 13304 */
fe8ab488 13305
2d21ac55
A
13306 state->dts_cred.dcr_action |=
13307 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
2d21ac55
A
13308 }
13309
13310 /*
13311 * Holding the dtrace_kernel privilege also implies that
13312 * the user has the dtrace_user privilege from a visibility
13313 * perspective. But without further privileges, some
13314 * destructive actions are not available.
13315 */
13316 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13317 /*
13318 * Make all probes in all zones visible. However,
13319 * this doesn't mean that all actions become available
13320 * to all zones.
13321 */
13322 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13323 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13324
13325 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13326 DTRACE_CRA_PROC;
13327 /*
13328 * Holding proc_owner means that destructive actions
13329 * for *this* zone are allowed.
13330 */
13331 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13332 state->dts_cred.dcr_action |=
13333 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13334
13335 /*
13336 * Holding proc_zone means that destructive actions
13337 * for this user/group ID in all zones is allowed.
13338 */
13339 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13340 state->dts_cred.dcr_action |=
13341 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13342
13343 /*
13344 * If we have all privs in whatever zone this is,
13345 * we can do destructive things to processes which
13346 * have altered credentials.
fe8ab488
A
13347 *
13348 * APPLE NOTE: Darwin doesn't do zones.
13349 * Behave as if zone always has destructive privs.
13350 */
2d21ac55
A
13351 state->dts_cred.dcr_action |=
13352 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
2d21ac55
A
13353 }
13354
13355 /*
13356 * Holding the dtrace_proc privilege gives control over fasttrap
13357 * and pid providers. We need to grant wider destructive
13358 * privileges in the event that the user has proc_owner and/or
13359 * proc_zone.
13360 */
13361 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13362 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13363 state->dts_cred.dcr_action |=
13364 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13365
13366 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13367 state->dts_cred.dcr_action |=
13368 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13369 }
13370 }
39037602 13371#endif
2d21ac55 13372
b0d623f7
A
13373 *new_state = state;
13374 return(0); /* Success */
2d21ac55
A
13375}
13376
13377static int
13378dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13379{
13380 dtrace_optval_t *opt = state->dts_options, size;
c910b4d9 13381 processorid_t cpu = 0;
39037602 13382 size_t limit = buf->dtb_size;
2d21ac55
A
13383 int flags = 0, rval;
13384
5ba3f43e
A
13385 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13386 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
13387 ASSERT(which < DTRACEOPT_MAX);
13388 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13389 (state == dtrace_anon.dta_state &&
13390 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13391
13392 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13393 return (0);
13394
13395 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13396 cpu = opt[DTRACEOPT_CPU];
13397
13398 if (which == DTRACEOPT_SPECSIZE)
13399 flags |= DTRACEBUF_NOSWITCH;
13400
13401 if (which == DTRACEOPT_BUFSIZE) {
13402 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13403 flags |= DTRACEBUF_RING;
13404
13405 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13406 flags |= DTRACEBUF_FILL;
13407
13408 if (state != dtrace_anon.dta_state ||
13409 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13410 flags |= DTRACEBUF_INACTIVE;
13411 }
13412
b0d623f7 13413 for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
2d21ac55
A
13414 /*
13415 * The size must be 8-byte aligned. If the size is not 8-byte
13416 * aligned, drop it down by the difference.
13417 */
13418 if (size & (sizeof (uint64_t) - 1))
13419 size -= size & (sizeof (uint64_t) - 1);
13420
13421 if (size < state->dts_reserve) {
13422 /*
13423 * Buffers always must be large enough to accommodate
13424 * their prereserved space. We return E2BIG instead
13425 * of ENOMEM in this case to allow for user-level
13426 * software to differentiate the cases.
13427 */
13428 return (E2BIG);
13429 }
39037602
A
13430 limit = opt[DTRACEOPT_BUFLIMIT] * size / 100;
13431 rval = dtrace_buffer_alloc(buf, limit, size, flags, cpu);
2d21ac55
A
13432
13433 if (rval != ENOMEM) {
13434 opt[which] = size;
13435 return (rval);
13436 }
13437
13438 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13439 return (rval);
13440 }
13441
13442 return (ENOMEM);
13443}
13444
13445static int
13446dtrace_state_buffers(dtrace_state_t *state)
13447{
13448 dtrace_speculation_t *spec = state->dts_speculations;
13449 int rval, i;
13450
13451 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13452 DTRACEOPT_BUFSIZE)) != 0)
13453 return (rval);
13454
13455 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13456 DTRACEOPT_AGGSIZE)) != 0)
13457 return (rval);
13458
13459 for (i = 0; i < state->dts_nspeculations; i++) {
13460 if ((rval = dtrace_state_buffer(state,
13461 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13462 return (rval);
13463 }
13464
13465 return (0);
13466}
13467
13468static void
13469dtrace_state_prereserve(dtrace_state_t *state)
13470{
13471 dtrace_ecb_t *ecb;
13472 dtrace_probe_t *probe;
13473
13474 state->dts_reserve = 0;
13475
13476 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13477 return;
13478
13479 /*
13480 * If our buffer policy is a "fill" buffer policy, we need to set the
13481 * prereserved space to be the space required by the END probes.
13482 */
13483 probe = dtrace_probes[dtrace_probeid_end - 1];
13484 ASSERT(probe != NULL);
13485
13486 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13487 if (ecb->dte_state != state)
13488 continue;
13489
13490 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13491 }
13492}
13493
13494static int
13495dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13496{
13497 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13498 dtrace_speculation_t *spec;
13499 dtrace_buffer_t *buf;
13500 cyc_handler_t hdlr;
13501 cyc_time_t when;
c910b4d9 13502 int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
2d21ac55
A
13503 dtrace_icookie_t cookie;
13504
13505 lck_mtx_lock(&cpu_lock);
13506 lck_mtx_lock(&dtrace_lock);
13507
13508 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13509 rval = EBUSY;
13510 goto out;
13511 }
13512
13513 /*
13514 * Before we can perform any checks, we must prime all of the
13515 * retained enablings that correspond to this state.
13516 */
13517 dtrace_enabling_prime(state);
13518
13519 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13520 rval = EACCES;
13521 goto out;
13522 }
13523
13524 dtrace_state_prereserve(state);
13525
13526 /*
13527 * Now we want to do is try to allocate our speculations.
13528 * We do not automatically resize the number of speculations; if
13529 * this fails, we will fail the operation.
13530 */
13531 nspec = opt[DTRACEOPT_NSPEC];
13532 ASSERT(nspec != DTRACEOPT_UNSET);
13533
13534 if (nspec > INT_MAX) {
13535 rval = ENOMEM;
13536 goto out;
13537 }
13538
13539 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13540
13541 if (spec == NULL) {
13542 rval = ENOMEM;
13543 goto out;
13544 }
13545
13546 state->dts_speculations = spec;
13547 state->dts_nspeculations = (int)nspec;
13548
13549 for (i = 0; i < nspec; i++) {
13550 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13551 rval = ENOMEM;
13552 goto err;
13553 }
13554
13555 spec[i].dtsp_buffer = buf;
13556 }
13557
13558 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13559 if (dtrace_anon.dta_state == NULL) {
13560 rval = ENOENT;
13561 goto out;
13562 }
13563
13564 if (state->dts_necbs != 0) {
13565 rval = EALREADY;
13566 goto out;
13567 }
13568
13569 state->dts_anon = dtrace_anon_grab();
13570 ASSERT(state->dts_anon != NULL);
13571 state = state->dts_anon;
13572
13573 /*
13574 * We want "grabanon" to be set in the grabbed state, so we'll
13575 * copy that option value from the grabbing state into the
13576 * grabbed state.
13577 */
13578 state->dts_options[DTRACEOPT_GRABANON] =
13579 opt[DTRACEOPT_GRABANON];
13580
13581 *cpu = dtrace_anon.dta_beganon;
13582
13583 /*
13584 * If the anonymous state is active (as it almost certainly
13585 * is if the anonymous enabling ultimately matched anything),
13586 * we don't allow any further option processing -- but we
13587 * don't return failure.
13588 */
13589 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13590 goto out;
13591 }
13592
13593 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13594 opt[DTRACEOPT_AGGSIZE] != 0) {
13595 if (state->dts_aggregations == NULL) {
13596 /*
13597 * We're not going to create an aggregation buffer
13598 * because we don't have any ECBs that contain
13599 * aggregations -- set this option to 0.
13600 */
13601 opt[DTRACEOPT_AGGSIZE] = 0;
13602 } else {
13603 /*
13604 * If we have an aggregation buffer, we must also have
13605 * a buffer to use as scratch.
13606 */
b0d623f7
A
13607 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13608 (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13609 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13610 }
2d21ac55
A
13611 }
13612 }
13613
13614 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13615 opt[DTRACEOPT_SPECSIZE] != 0) {
13616 if (!state->dts_speculates) {
13617 /*
13618 * We're not going to create speculation buffers
13619 * because we don't have any ECBs that actually
13620 * speculate -- set the speculation size to 0.
13621 */
13622 opt[DTRACEOPT_SPECSIZE] = 0;
13623 }
13624 }
13625
13626 /*
13627 * The bare minimum size for any buffer that we're actually going to
13628 * do anything to is sizeof (uint64_t).
13629 */
13630 sz = sizeof (uint64_t);
13631
13632 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13633 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13634 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13635 /*
13636 * A buffer size has been explicitly set to 0 (or to a size
13637 * that will be adjusted to 0) and we need the space -- we
13638 * need to return failure. We return ENOSPC to differentiate
13639 * it from failing to allocate a buffer due to failure to meet
13640 * the reserve (for which we return E2BIG).
13641 */
13642 rval = ENOSPC;
13643 goto out;
13644 }
13645
13646 if ((rval = dtrace_state_buffers(state)) != 0)
13647 goto err;
13648
13649 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13650 sz = dtrace_dstate_defsize;
13651
13652 do {
13653 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13654
13655 if (rval == 0)
13656 break;
13657
13658 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13659 goto err;
13660 } while (sz >>= 1);
13661
13662 opt[DTRACEOPT_DYNVARSIZE] = sz;
13663
13664 if (rval != 0)
13665 goto err;
13666
13667 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13668 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13669
13670 if (opt[DTRACEOPT_CLEANRATE] == 0)
13671 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13672
13673 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13674 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13675
13676 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13677 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13678
39037602
A
13679 if (opt[DTRACEOPT_STRSIZE] > dtrace_strsize_max)
13680 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_max;
13681
13682 if (opt[DTRACEOPT_STRSIZE] < dtrace_strsize_min)
13683 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_min;
13684
13685 if (opt[DTRACEOPT_BUFLIMIT] > dtrace_buflimit_max)
13686 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_max;
13687
13688 if (opt[DTRACEOPT_BUFLIMIT] < dtrace_buflimit_min)
13689 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_min;
13690
2d21ac55
A
13691 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13692 hdlr.cyh_arg = state;
13693 hdlr.cyh_level = CY_LOW_LEVEL;
13694
13695 when.cyt_when = 0;
13696 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13697
13698 state->dts_cleaner = cyclic_add(&hdlr, &when);
13699
13700 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13701 hdlr.cyh_arg = state;
13702 hdlr.cyh_level = CY_LOW_LEVEL;
13703
13704 when.cyt_when = 0;
13705 when.cyt_interval = dtrace_deadman_interval;
13706
13707 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13708 state->dts_deadman = cyclic_add(&hdlr, &when);
13709
13710 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13711
13712 /*
13713 * Now it's time to actually fire the BEGIN probe. We need to disable
13714 * interrupts here both to record the CPU on which we fired the BEGIN
13715 * probe (the data from this CPU will be processed first at user
13716 * level) and to manually activate the buffer for this CPU.
13717 */
13718 cookie = dtrace_interrupt_disable();
13719 *cpu = CPU->cpu_id;
13720 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13721 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13722
13723 dtrace_probe(dtrace_probeid_begin,
13724 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13725 dtrace_interrupt_enable(cookie);
13726 /*
13727 * We may have had an exit action from a BEGIN probe; only change our
13728 * state to ACTIVE if we're still in WARMUP.
13729 */
13730 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13731 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13732
13733 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13734 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13735
13736 /*
13737 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13738 * want each CPU to transition its principal buffer out of the
13739 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13740 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13741 * atomically transition from processing none of a state's ECBs to
13742 * processing all of them.
13743 */
13744 dtrace_xcall(DTRACE_CPUALL,
13745 (dtrace_xcall_t)dtrace_buffer_activate, state);
13746 goto out;
13747
13748err:
13749 dtrace_buffer_free(state->dts_buffer);
13750 dtrace_buffer_free(state->dts_aggbuffer);
13751
13752 if ((nspec = state->dts_nspeculations) == 0) {
13753 ASSERT(state->dts_speculations == NULL);
13754 goto out;
13755 }
13756
13757 spec = state->dts_speculations;
13758 ASSERT(spec != NULL);
13759
13760 for (i = 0; i < state->dts_nspeculations; i++) {
13761 if ((buf = spec[i].dtsp_buffer) == NULL)
13762 break;
13763
13764 dtrace_buffer_free(buf);
13765 kmem_free(buf, bufsize);
13766 }
13767
13768 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13769 state->dts_nspeculations = 0;
13770 state->dts_speculations = NULL;
13771
13772out:
13773 lck_mtx_unlock(&dtrace_lock);
13774 lck_mtx_unlock(&cpu_lock);
13775
13776 return (rval);
13777}
13778
13779static int
13780dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13781{
13782 dtrace_icookie_t cookie;
13783
5ba3f43e 13784 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
13785
13786 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13787 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13788 return (EINVAL);
13789
13790 /*
13791 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13792 * to be sure that every CPU has seen it. See below for the details
13793 * on why this is done.
13794 */
13795 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13796 dtrace_sync();
13797
13798 /*
13799 * By this point, it is impossible for any CPU to be still processing
13800 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13801 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13802 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13803 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13804 * iff we're in the END probe.
13805 */
13806 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13807 dtrace_sync();
13808 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13809
13810 /*
13811 * Finally, we can release the reserve and call the END probe. We
13812 * disable interrupts across calling the END probe to allow us to
13813 * return the CPU on which we actually called the END probe. This
13814 * allows user-land to be sure that this CPU's principal buffer is
13815 * processed last.
13816 */
13817 state->dts_reserve = 0;
13818
13819 cookie = dtrace_interrupt_disable();
13820 *cpu = CPU->cpu_id;
13821 dtrace_probe(dtrace_probeid_end,
13822 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13823 dtrace_interrupt_enable(cookie);
13824
13825 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13826 dtrace_sync();
13827
13828 return (0);
13829}
13830
13831static int
13832dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13833 dtrace_optval_t val)
13834{
5ba3f43e 13835 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
13836
13837 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13838 return (EBUSY);
13839
13840 if (option >= DTRACEOPT_MAX)
13841 return (EINVAL);
13842
13843 if (option != DTRACEOPT_CPU && val < 0)
13844 return (EINVAL);
13845
13846 switch (option) {
13847 case DTRACEOPT_DESTRUCTIVE:
fe8ab488
A
13848 /*
13849 * Prevent consumers from enabling destructive actions if DTrace
13850 * is running in a restricted environment, or if actions are
13851 * disallowed.
13852 */
13853 if (dtrace_is_restricted() || dtrace_destructive_disallow)
2d21ac55
A
13854 return (EACCES);
13855
13856 state->dts_cred.dcr_destructive = 1;
13857 break;
13858
13859 case DTRACEOPT_BUFSIZE:
13860 case DTRACEOPT_DYNVARSIZE:
13861 case DTRACEOPT_AGGSIZE:
13862 case DTRACEOPT_SPECSIZE:
13863 case DTRACEOPT_STRSIZE:
13864 if (val < 0)
13865 return (EINVAL);
13866
13867 if (val >= LONG_MAX) {
13868 /*
13869 * If this is an otherwise negative value, set it to
13870 * the highest multiple of 128m less than LONG_MAX.
13871 * Technically, we're adjusting the size without
13872 * regard to the buffer resizing policy, but in fact,
13873 * this has no effect -- if we set the buffer size to
13874 * ~LONG_MAX and the buffer policy is ultimately set to
13875 * be "manual", the buffer allocation is guaranteed to
13876 * fail, if only because the allocation requires two
13877 * buffers. (We set the the size to the highest
13878 * multiple of 128m because it ensures that the size
13879 * will remain a multiple of a megabyte when
13880 * repeatedly halved -- all the way down to 15m.)
13881 */
13882 val = LONG_MAX - (1 << 27) + 1;
13883 }
13884 }
13885
13886 state->dts_options[option] = val;
13887
13888 return (0);
13889}
13890
13891static void
13892dtrace_state_destroy(dtrace_state_t *state)
13893{
13894 dtrace_ecb_t *ecb;
13895 dtrace_vstate_t *vstate = &state->dts_vstate;
13896 minor_t minor = getminor(state->dts_dev);
c910b4d9 13897 int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
2d21ac55
A
13898 dtrace_speculation_t *spec = state->dts_speculations;
13899 int nspec = state->dts_nspeculations;
13900 uint32_t match;
13901
5ba3f43e
A
13902 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13903 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
13904
13905 /*
13906 * First, retract any retained enablings for this state.
13907 */
13908 dtrace_enabling_retract(state);
13909 ASSERT(state->dts_nretained == 0);
13910
13911 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13912 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13913 /*
13914 * We have managed to come into dtrace_state_destroy() on a
13915 * hot enabling -- almost certainly because of a disorderly
13916 * shutdown of a consumer. (That is, a consumer that is
13917 * exiting without having called dtrace_stop().) In this case,
13918 * we're going to set our activity to be KILLED, and then
13919 * issue a sync to be sure that everyone is out of probe
13920 * context before we start blowing away ECBs.
13921 */
13922 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13923 dtrace_sync();
13924 }
13925
13926 /*
13927 * Release the credential hold we took in dtrace_state_create().
13928 */
13929 if (state->dts_cred.dcr_cred != NULL)
13930 crfree(state->dts_cred.dcr_cred);
13931
13932 /*
13933 * Now we can safely disable and destroy any enabled probes. Because
13934 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13935 * (especially if they're all enabled), we take two passes through the
13936 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13937 * in the second we disable whatever is left over.
13938 */
13939 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13940 for (i = 0; i < state->dts_necbs; i++) {
13941 if ((ecb = state->dts_ecbs[i]) == NULL)
13942 continue;
13943
13944 if (match && ecb->dte_probe != NULL) {
13945 dtrace_probe_t *probe = ecb->dte_probe;
13946 dtrace_provider_t *prov = probe->dtpr_provider;
13947
13948 if (!(prov->dtpv_priv.dtpp_flags & match))
13949 continue;
13950 }
13951
13952 dtrace_ecb_disable(ecb);
13953 dtrace_ecb_destroy(ecb);
13954 }
13955
13956 if (!match)
13957 break;
13958 }
13959
13960 /*
13961 * Before we free the buffers, perform one more sync to assure that
13962 * every CPU is out of probe context.
13963 */
13964 dtrace_sync();
13965
13966 dtrace_buffer_free(state->dts_buffer);
13967 dtrace_buffer_free(state->dts_aggbuffer);
13968
13969 for (i = 0; i < nspec; i++)
13970 dtrace_buffer_free(spec[i].dtsp_buffer);
13971
13972 if (state->dts_cleaner != CYCLIC_NONE)
13973 cyclic_remove(state->dts_cleaner);
13974
13975 if (state->dts_deadman != CYCLIC_NONE)
13976 cyclic_remove(state->dts_deadman);
13977
13978 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13979 dtrace_vstate_fini(vstate);
13980 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13981
13982 if (state->dts_aggregations != NULL) {
b0d623f7 13983#if DEBUG
2d21ac55
A
13984 for (i = 0; i < state->dts_naggregations; i++)
13985 ASSERT(state->dts_aggregations[i] == NULL);
13986#endif
13987 ASSERT(state->dts_naggregations > 0);
13988 kmem_free(state->dts_aggregations,
13989 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13990 }
13991
13992 kmem_free(state->dts_buffer, bufsize);
13993 kmem_free(state->dts_aggbuffer, bufsize);
13994
13995 for (i = 0; i < nspec; i++)
13996 kmem_free(spec[i].dtsp_buffer, bufsize);
13997
13998 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13999
14000 dtrace_format_destroy(state);
14001
14002 vmem_destroy(state->dts_aggid_arena);
39037602 14003 dtrace_state_free(minor);
2d21ac55
A
14004}
14005
14006/*
14007 * DTrace Anonymous Enabling Functions
14008 */
14009static dtrace_state_t *
14010dtrace_anon_grab(void)
14011{
14012 dtrace_state_t *state;
14013
5ba3f43e 14014 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
14015
14016 if ((state = dtrace_anon.dta_state) == NULL) {
14017 ASSERT(dtrace_anon.dta_enabling == NULL);
14018 return (NULL);
14019 }
14020
14021 ASSERT(dtrace_anon.dta_enabling != NULL);
14022 ASSERT(dtrace_retained != NULL);
14023
14024 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14025 dtrace_anon.dta_enabling = NULL;
14026 dtrace_anon.dta_state = NULL;
14027
14028 return (state);
14029}
14030
14031static void
14032dtrace_anon_property(void)
14033{
14034 int i, rv;
14035 dtrace_state_t *state;
14036 dof_hdr_t *dof;
14037 char c[32]; /* enough for "dof-data-" + digits */
14038
5ba3f43e
A
14039 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14040 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
14041
14042 for (i = 0; ; i++) {
14043 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14044
14045 dtrace_err_verbose = 1;
14046
14047 if ((dof = dtrace_dof_property(c)) == NULL) {
14048 dtrace_err_verbose = 0;
14049 break;
14050 }
14051
14052 /*
14053 * We want to create anonymous state, so we need to transition
14054 * the kernel debugger to indicate that DTrace is active. If
14055 * this fails (e.g. because the debugger has modified text in
14056 * some way), we won't continue with the processing.
14057 */
14058 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14059 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14060 "enabling ignored.");
14061 dtrace_dof_destroy(dof);
14062 break;
14063 }
14064
14065 /*
14066 * If we haven't allocated an anonymous state, we'll do so now.
14067 */
14068 if ((state = dtrace_anon.dta_state) == NULL) {
b0d623f7
A
14069 rv = dtrace_state_create(NULL, NULL, &state);
14070 dtrace_anon.dta_state = state;
14071 if (rv != 0 || state == NULL) {
2d21ac55
A
14072 /*
14073 * This basically shouldn't happen: the only
14074 * failure mode from dtrace_state_create() is a
14075 * failure of ddi_soft_state_zalloc() that
14076 * itself should never happen. Still, the
14077 * interface allows for a failure mode, and
14078 * we want to fail as gracefully as possible:
14079 * we'll emit an error message and cease
14080 * processing anonymous state in this case.
14081 */
14082 cmn_err(CE_WARN, "failed to create "
14083 "anonymous state");
14084 dtrace_dof_destroy(dof);
14085 break;
14086 }
14087 }
14088
14089 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14090 &dtrace_anon.dta_enabling, 0, B_TRUE);
14091
14092 if (rv == 0)
14093 rv = dtrace_dof_options(dof, state);
14094
14095 dtrace_err_verbose = 0;
14096 dtrace_dof_destroy(dof);
14097
14098 if (rv != 0) {
14099 /*
14100 * This is malformed DOF; chuck any anonymous state
14101 * that we created.
14102 */
14103 ASSERT(dtrace_anon.dta_enabling == NULL);
14104 dtrace_state_destroy(state);
14105 dtrace_anon.dta_state = NULL;
14106 break;
14107 }
14108
14109 ASSERT(dtrace_anon.dta_enabling != NULL);
14110 }
14111
14112 if (dtrace_anon.dta_enabling != NULL) {
14113 int rval;
14114
14115 /*
14116 * dtrace_enabling_retain() can only fail because we are
14117 * trying to retain more enablings than are allowed -- but
14118 * we only have one anonymous enabling, and we are guaranteed
14119 * to be allowed at least one retained enabling; we assert
14120 * that dtrace_enabling_retain() returns success.
14121 */
14122 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14123 ASSERT(rval == 0);
14124
14125 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14126 }
14127}
14128
14129/*
14130 * DTrace Helper Functions
14131 */
14132static void
14133dtrace_helper_trace(dtrace_helper_action_t *helper,
14134 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14135{
b0d623f7
A
14136 uint32_t size, next, nnext;
14137 int i;
2d21ac55
A
14138 dtrace_helptrace_t *ent;
14139 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14140
14141 if (!dtrace_helptrace_enabled)
14142 return;
14143
b0d623f7 14144 ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
2d21ac55
A
14145
14146 /*
14147 * What would a tracing framework be without its own tracing
14148 * framework? (Well, a hell of a lot simpler, for starters...)
14149 */
14150 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14151 sizeof (uint64_t) - sizeof (uint64_t);
14152
14153 /*
14154 * Iterate until we can allocate a slot in the trace buffer.
14155 */
14156 do {
14157 next = dtrace_helptrace_next;
14158
14159 if (next + size < dtrace_helptrace_bufsize) {
14160 nnext = next + size;
14161 } else {
14162 nnext = size;
14163 }
14164 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14165
14166 /*
14167 * We have our slot; fill it in.
14168 */
14169 if (nnext == size)
14170 next = 0;
14171
14172 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14173 ent->dtht_helper = helper;
14174 ent->dtht_where = where;
14175 ent->dtht_nlocals = vstate->dtvs_nlocals;
14176
14177 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14178 mstate->dtms_fltoffs : -1;
14179 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14180 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14181
14182 for (i = 0; i < vstate->dtvs_nlocals; i++) {
14183 dtrace_statvar_t *svar;
14184
14185 if ((svar = vstate->dtvs_locals[i]) == NULL)
14186 continue;
14187
c910b4d9 14188 ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
2d21ac55
A
14189 ent->dtht_locals[i] =
14190 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14191 }
14192}
14193
14194static uint64_t
14195dtrace_helper(int which, dtrace_mstate_t *mstate,
14196 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14197{
14198 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14199 uint64_t sarg0 = mstate->dtms_arg[0];
14200 uint64_t sarg1 = mstate->dtms_arg[1];
c910b4d9 14201 uint64_t rval = 0;
2d21ac55
A
14202 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14203 dtrace_helper_action_t *helper;
14204 dtrace_vstate_t *vstate;
14205 dtrace_difo_t *pred;
14206 int i, trace = dtrace_helptrace_enabled;
14207
14208 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14209
14210 if (helpers == NULL)
14211 return (0);
14212
14213 if ((helper = helpers->dthps_actions[which]) == NULL)
14214 return (0);
14215
14216 vstate = &helpers->dthps_vstate;
14217 mstate->dtms_arg[0] = arg0;
14218 mstate->dtms_arg[1] = arg1;
14219
14220 /*
14221 * Now iterate over each helper. If its predicate evaluates to 'true',
14222 * we'll call the corresponding actions. Note that the below calls
14223 * to dtrace_dif_emulate() may set faults in machine state. This is
14224 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
14225 * the stored DIF offset with its own (which is the desired behavior).
14226 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14227 * from machine state; this is okay, too.
14228 */
14229 for (; helper != NULL; helper = helper->dtha_next) {
14230 if ((pred = helper->dtha_predicate) != NULL) {
14231 if (trace)
14232 dtrace_helper_trace(helper, mstate, vstate, 0);
14233
14234 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14235 goto next;
14236
14237 if (*flags & CPU_DTRACE_FAULT)
14238 goto err;
14239 }
14240
14241 for (i = 0; i < helper->dtha_nactions; i++) {
14242 if (trace)
14243 dtrace_helper_trace(helper,
14244 mstate, vstate, i + 1);
14245
14246 rval = dtrace_dif_emulate(helper->dtha_actions[i],
14247 mstate, vstate, state);
14248
14249 if (*flags & CPU_DTRACE_FAULT)
14250 goto err;
14251 }
14252
14253next:
14254 if (trace)
14255 dtrace_helper_trace(helper, mstate, vstate,
14256 DTRACE_HELPTRACE_NEXT);
14257 }
14258
14259 if (trace)
14260 dtrace_helper_trace(helper, mstate, vstate,
14261 DTRACE_HELPTRACE_DONE);
14262
14263 /*
14264 * Restore the arg0 that we saved upon entry.
14265 */
14266 mstate->dtms_arg[0] = sarg0;
14267 mstate->dtms_arg[1] = sarg1;
14268
14269 return (rval);
14270
14271err:
14272 if (trace)
14273 dtrace_helper_trace(helper, mstate, vstate,
14274 DTRACE_HELPTRACE_ERR);
14275
14276 /*
14277 * Restore the arg0 that we saved upon entry.
14278 */
14279 mstate->dtms_arg[0] = sarg0;
14280 mstate->dtms_arg[1] = sarg1;
14281
fe8ab488 14282 return (0);
2d21ac55
A
14283}
14284
14285static void
14286dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14287 dtrace_vstate_t *vstate)
14288{
14289 int i;
14290
14291 if (helper->dtha_predicate != NULL)
14292 dtrace_difo_release(helper->dtha_predicate, vstate);
14293
14294 for (i = 0; i < helper->dtha_nactions; i++) {
14295 ASSERT(helper->dtha_actions[i] != NULL);
14296 dtrace_difo_release(helper->dtha_actions[i], vstate);
14297 }
14298
14299 kmem_free(helper->dtha_actions,
14300 helper->dtha_nactions * sizeof (dtrace_difo_t *));
14301 kmem_free(helper, sizeof (dtrace_helper_action_t));
14302}
14303
2d21ac55
A
14304static int
14305dtrace_helper_destroygen(proc_t* p, int gen)
14306{
2d21ac55
A
14307 dtrace_helpers_t *help = p->p_dtrace_helpers;
14308 dtrace_vstate_t *vstate;
b0d623f7 14309 uint_t i;
2d21ac55 14310
5ba3f43e 14311 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
14312
14313 if (help == NULL || gen > help->dthps_generation)
14314 return (EINVAL);
14315
14316 vstate = &help->dthps_vstate;
14317
14318 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14319 dtrace_helper_action_t *last = NULL, *h, *next;
14320
14321 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14322 next = h->dtha_next;
14323
14324 if (h->dtha_generation == gen) {
14325 if (last != NULL) {
14326 last->dtha_next = next;
14327 } else {
14328 help->dthps_actions[i] = next;
14329 }
14330
14331 dtrace_helper_action_destroy(h, vstate);
14332 } else {
14333 last = h;
14334 }
14335 }
14336 }
14337
14338 /*
14339 * Interate until we've cleared out all helper providers with the
14340 * given generation number.
14341 */
14342 for (;;) {
c910b4d9 14343 dtrace_helper_provider_t *prov = NULL;
2d21ac55
A
14344
14345 /*
14346 * Look for a helper provider with the right generation. We
14347 * have to start back at the beginning of the list each time
14348 * because we drop dtrace_lock. It's unlikely that we'll make
14349 * more than two passes.
14350 */
14351 for (i = 0; i < help->dthps_nprovs; i++) {
14352 prov = help->dthps_provs[i];
14353
14354 if (prov->dthp_generation == gen)
14355 break;
14356 }
14357
14358 /*
14359 * If there were no matches, we're done.
14360 */
14361 if (i == help->dthps_nprovs)
14362 break;
14363
14364 /*
14365 * Move the last helper provider into this slot.
14366 */
14367 help->dthps_nprovs--;
14368 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14369 help->dthps_provs[help->dthps_nprovs] = NULL;
14370
14371 lck_mtx_unlock(&dtrace_lock);
14372
14373 /*
14374 * If we have a meta provider, remove this helper provider.
14375 */
14376 lck_mtx_lock(&dtrace_meta_lock);
14377 if (dtrace_meta_pid != NULL) {
14378 ASSERT(dtrace_deferred_pid == NULL);
14379 dtrace_helper_provider_remove(&prov->dthp_prov,
d190cdc3 14380 p);
2d21ac55
A
14381 }
14382 lck_mtx_unlock(&dtrace_meta_lock);
14383
14384 dtrace_helper_provider_destroy(prov);
14385
14386 lck_mtx_lock(&dtrace_lock);
14387 }
14388
14389 return (0);
14390}
14391
14392static int
14393dtrace_helper_validate(dtrace_helper_action_t *helper)
14394{
14395 int err = 0, i;
14396 dtrace_difo_t *dp;
14397
14398 if ((dp = helper->dtha_predicate) != NULL)
14399 err += dtrace_difo_validate_helper(dp);
14400
14401 for (i = 0; i < helper->dtha_nactions; i++)
14402 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14403
14404 return (err == 0);
14405}
14406
2d21ac55
A
14407static int
14408dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
2d21ac55
A
14409{
14410 dtrace_helpers_t *help;
14411 dtrace_helper_action_t *helper, *last;
14412 dtrace_actdesc_t *act;
14413 dtrace_vstate_t *vstate;
14414 dtrace_predicate_t *pred;
14415 int count = 0, nactions = 0, i;
14416
14417 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14418 return (EINVAL);
14419
2d21ac55 14420 help = p->p_dtrace_helpers;
2d21ac55
A
14421 last = help->dthps_actions[which];
14422 vstate = &help->dthps_vstate;
14423
14424 for (count = 0; last != NULL; last = last->dtha_next) {
14425 count++;
14426 if (last->dtha_next == NULL)
14427 break;
14428 }
14429
14430 /*
14431 * If we already have dtrace_helper_actions_max helper actions for this
14432 * helper action type, we'll refuse to add a new one.
14433 */
14434 if (count >= dtrace_helper_actions_max)
14435 return (ENOSPC);
14436
14437 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14438 helper->dtha_generation = help->dthps_generation;
14439
14440 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14441 ASSERT(pred->dtp_difo != NULL);
14442 dtrace_difo_hold(pred->dtp_difo);
14443 helper->dtha_predicate = pred->dtp_difo;
14444 }
14445
14446 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14447 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14448 goto err;
14449
14450 if (act->dtad_difo == NULL)
14451 goto err;
14452
14453 nactions++;
14454 }
14455
14456 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14457 (helper->dtha_nactions = nactions), KM_SLEEP);
14458
14459 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14460 dtrace_difo_hold(act->dtad_difo);
14461 helper->dtha_actions[i++] = act->dtad_difo;
14462 }
14463
14464 if (!dtrace_helper_validate(helper))
14465 goto err;
14466
14467 if (last == NULL) {
14468 help->dthps_actions[which] = helper;
14469 } else {
14470 last->dtha_next = helper;
14471 }
14472
b0d623f7 14473 if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
2d21ac55
A
14474 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14475 dtrace_helptrace_next = 0;
14476 }
14477
14478 return (0);
14479err:
14480 dtrace_helper_action_destroy(helper, vstate);
14481 return (EINVAL);
14482}
14483
14484static void
14485dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14486 dof_helper_t *dofhp)
14487{
5ba3f43e 14488 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
2d21ac55
A
14489
14490 lck_mtx_lock(&dtrace_meta_lock);
14491 lck_mtx_lock(&dtrace_lock);
14492
14493 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14494 /*
14495 * If the dtrace module is loaded but not attached, or if
14496 * there aren't isn't a meta provider registered to deal with
14497 * these provider descriptions, we need to postpone creating
14498 * the actual providers until later.
14499 */
14500
14501 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14502 dtrace_deferred_pid != help) {
14503 help->dthps_deferred = 1;
14504 help->dthps_pid = p->p_pid;
14505 help->dthps_next = dtrace_deferred_pid;
14506 help->dthps_prev = NULL;
14507 if (dtrace_deferred_pid != NULL)
14508 dtrace_deferred_pid->dthps_prev = help;
14509 dtrace_deferred_pid = help;
14510 }
14511
14512 lck_mtx_unlock(&dtrace_lock);
14513
14514 } else if (dofhp != NULL) {
14515 /*
14516 * If the dtrace module is loaded and we have a particular
14517 * helper provider description, pass that off to the
14518 * meta provider.
14519 */
14520
14521 lck_mtx_unlock(&dtrace_lock);
14522
d190cdc3 14523 dtrace_helper_provide(dofhp, p);
2d21ac55
A
14524
14525 } else {
14526 /*
14527 * Otherwise, just pass all the helper provider descriptions
14528 * off to the meta provider.
14529 */
14530
b0d623f7 14531 uint_t i;
2d21ac55
A
14532 lck_mtx_unlock(&dtrace_lock);
14533
14534 for (i = 0; i < help->dthps_nprovs; i++) {
14535 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
d190cdc3 14536 p);
2d21ac55
A
14537 }
14538 }
14539
14540 lck_mtx_unlock(&dtrace_meta_lock);
14541}
14542
2d21ac55
A
14543static int
14544dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
2d21ac55
A
14545{
14546 dtrace_helpers_t *help;
14547 dtrace_helper_provider_t *hprov, **tmp_provs;
14548 uint_t tmp_maxprovs, i;
14549
5ba3f43e 14550 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 14551 help = p->p_dtrace_helpers;
2d21ac55
A
14552 ASSERT(help != NULL);
14553
14554 /*
14555 * If we already have dtrace_helper_providers_max helper providers,
14556 * we're refuse to add a new one.
14557 */
14558 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14559 return (ENOSPC);
14560
14561 /*
14562 * Check to make sure this isn't a duplicate.
14563 */
14564 for (i = 0; i < help->dthps_nprovs; i++) {
14565 if (dofhp->dofhp_addr ==
14566 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14567 return (EALREADY);
14568 }
14569
14570 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14571 hprov->dthp_prov = *dofhp;
14572 hprov->dthp_ref = 1;
14573 hprov->dthp_generation = gen;
14574
14575 /*
14576 * Allocate a bigger table for helper providers if it's already full.
14577 */
14578 if (help->dthps_maxprovs == help->dthps_nprovs) {
14579 tmp_maxprovs = help->dthps_maxprovs;
14580 tmp_provs = help->dthps_provs;
14581
14582 if (help->dthps_maxprovs == 0)
14583 help->dthps_maxprovs = 2;
14584 else
14585 help->dthps_maxprovs *= 2;
14586 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14587 help->dthps_maxprovs = dtrace_helper_providers_max;
14588
14589 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14590
14591 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14592 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14593
14594 if (tmp_provs != NULL) {
14595 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14596 sizeof (dtrace_helper_provider_t *));
14597 kmem_free(tmp_provs, tmp_maxprovs *
14598 sizeof (dtrace_helper_provider_t *));
14599 }
14600 }
14601
14602 help->dthps_provs[help->dthps_nprovs] = hprov;
14603 help->dthps_nprovs++;
14604
14605 return (0);
14606}
14607
14608static void
14609dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14610{
14611 lck_mtx_lock(&dtrace_lock);
14612
14613 if (--hprov->dthp_ref == 0) {
14614 dof_hdr_t *dof;
14615 lck_mtx_unlock(&dtrace_lock);
14616 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14617 dtrace_dof_destroy(dof);
14618 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14619 } else {
14620 lck_mtx_unlock(&dtrace_lock);
14621 }
14622}
14623
14624static int
14625dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14626{
14627 uintptr_t daddr = (uintptr_t)dof;
14628 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14629 dof_provider_t *provider;
14630 dof_probe_t *probe;
14631 uint8_t *arg;
14632 char *strtab, *typestr;
14633 dof_stridx_t typeidx;
14634 size_t typesz;
14635 uint_t nprobes, j, k;
14636
14637 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14638
14639 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14640 dtrace_dof_error(dof, "misaligned section offset");
14641 return (-1);
14642 }
14643
14644 /*
14645 * The section needs to be large enough to contain the DOF provider
14646 * structure appropriate for the given version.
14647 */
14648 if (sec->dofs_size <
14649 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14650 offsetof(dof_provider_t, dofpv_prenoffs) :
14651 sizeof (dof_provider_t))) {
14652 dtrace_dof_error(dof, "provider section too small");
14653 return (-1);
14654 }
14655
14656 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14657 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14658 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14659 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14660 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14661
14662 if (str_sec == NULL || prb_sec == NULL ||
14663 arg_sec == NULL || off_sec == NULL)
14664 return (-1);
14665
14666 enoff_sec = NULL;
14667
14668 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14669 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14670 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14671 provider->dofpv_prenoffs)) == NULL)
14672 return (-1);
14673
14674 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14675
14676 if (provider->dofpv_name >= str_sec->dofs_size ||
14677 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14678 dtrace_dof_error(dof, "invalid provider name");
14679 return (-1);
14680 }
14681
14682 if (prb_sec->dofs_entsize == 0 ||
14683 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14684 dtrace_dof_error(dof, "invalid entry size");
14685 return (-1);
14686 }
14687
14688 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14689 dtrace_dof_error(dof, "misaligned entry size");
14690 return (-1);
14691 }
14692
14693 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14694 dtrace_dof_error(dof, "invalid entry size");
14695 return (-1);
14696 }
14697
14698 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14699 dtrace_dof_error(dof, "misaligned section offset");
14700 return (-1);
14701 }
14702
14703 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14704 dtrace_dof_error(dof, "invalid entry size");
14705 return (-1);
14706 }
14707
14708 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14709
14710 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14711
14712 /*
14713 * Take a pass through the probes to check for errors.
14714 */
14715 for (j = 0; j < nprobes; j++) {
14716 probe = (dof_probe_t *)(uintptr_t)(daddr +
14717 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14718
14719 if (probe->dofpr_func >= str_sec->dofs_size) {
14720 dtrace_dof_error(dof, "invalid function name");
14721 return (-1);
14722 }
14723
14724 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14725 dtrace_dof_error(dof, "function name too long");
14726 return (-1);
14727 }
14728
14729 if (probe->dofpr_name >= str_sec->dofs_size ||
14730 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14731 dtrace_dof_error(dof, "invalid probe name");
14732 return (-1);
14733 }
14734
14735 /*
14736 * The offset count must not wrap the index, and the offsets
14737 * must also not overflow the section's data.
14738 */
14739 if (probe->dofpr_offidx + probe->dofpr_noffs <
14740 probe->dofpr_offidx ||
14741 (probe->dofpr_offidx + probe->dofpr_noffs) *
14742 off_sec->dofs_entsize > off_sec->dofs_size) {
14743 dtrace_dof_error(dof, "invalid probe offset");
14744 return (-1);
14745 }
14746
14747 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14748 /*
14749 * If there's no is-enabled offset section, make sure
14750 * there aren't any is-enabled offsets. Otherwise
14751 * perform the same checks as for probe offsets
14752 * (immediately above).
14753 */
14754 if (enoff_sec == NULL) {
14755 if (probe->dofpr_enoffidx != 0 ||
14756 probe->dofpr_nenoffs != 0) {
14757 dtrace_dof_error(dof, "is-enabled "
14758 "offsets with null section");
14759 return (-1);
14760 }
14761 } else if (probe->dofpr_enoffidx +
14762 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14763 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14764 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14765 dtrace_dof_error(dof, "invalid is-enabled "
14766 "offset");
14767 return (-1);
14768 }
14769
14770 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14771 dtrace_dof_error(dof, "zero probe and "
14772 "is-enabled offsets");
14773 return (-1);
14774 }
14775 } else if (probe->dofpr_noffs == 0) {
14776 dtrace_dof_error(dof, "zero probe offsets");
14777 return (-1);
14778 }
14779
14780 if (probe->dofpr_argidx + probe->dofpr_xargc <
14781 probe->dofpr_argidx ||
14782 (probe->dofpr_argidx + probe->dofpr_xargc) *
14783 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14784 dtrace_dof_error(dof, "invalid args");
14785 return (-1);
14786 }
14787
14788 typeidx = probe->dofpr_nargv;
14789 typestr = strtab + probe->dofpr_nargv;
14790 for (k = 0; k < probe->dofpr_nargc; k++) {
14791 if (typeidx >= str_sec->dofs_size) {
14792 dtrace_dof_error(dof, "bad "
14793 "native argument type");
14794 return (-1);
14795 }
14796
14797 typesz = strlen(typestr) + 1;
14798 if (typesz > DTRACE_ARGTYPELEN) {
14799 dtrace_dof_error(dof, "native "
14800 "argument type too long");
14801 return (-1);
14802 }
14803 typeidx += typesz;
14804 typestr += typesz;
14805 }
14806
14807 typeidx = probe->dofpr_xargv;
14808 typestr = strtab + probe->dofpr_xargv;
14809 for (k = 0; k < probe->dofpr_xargc; k++) {
14810 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14811 dtrace_dof_error(dof, "bad "
14812 "native argument index");
14813 return (-1);
14814 }
14815
14816 if (typeidx >= str_sec->dofs_size) {
14817 dtrace_dof_error(dof, "bad "
14818 "translated argument type");
14819 return (-1);
14820 }
14821
14822 typesz = strlen(typestr) + 1;
14823 if (typesz > DTRACE_ARGTYPELEN) {
14824 dtrace_dof_error(dof, "translated argument "
14825 "type too long");
14826 return (-1);
14827 }
14828
14829 typeidx += typesz;
14830 typestr += typesz;
14831 }
14832 }
14833
14834 return (0);
14835}
14836
2d21ac55
A
14837static int
14838dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
2d21ac55
A
14839{
14840 dtrace_helpers_t *help;
14841 dtrace_vstate_t *vstate;
14842 dtrace_enabling_t *enab = NULL;
14843 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14844 uintptr_t daddr = (uintptr_t)dof;
14845
5ba3f43e 14846 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55 14847
2d21ac55
A
14848 if ((help = p->p_dtrace_helpers) == NULL)
14849 help = dtrace_helpers_create(p);
2d21ac55
A
14850
14851 vstate = &help->dthps_vstate;
14852
14853 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14854 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14855 dtrace_dof_destroy(dof);
14856 return (rv);
14857 }
14858
14859 /*
14860 * Look for helper providers and validate their descriptions.
14861 */
14862 if (dhp != NULL) {
b0d623f7 14863 for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
2d21ac55
A
14864 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14865 dof->dofh_secoff + i * dof->dofh_secsize);
14866
14867 if (sec->dofs_type != DOF_SECT_PROVIDER)
14868 continue;
14869
14870 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14871 dtrace_enabling_destroy(enab);
14872 dtrace_dof_destroy(dof);
14873 return (-1);
14874 }
14875
14876 nprovs++;
14877 }
14878 }
14879
14880 /*
14881 * Now we need to walk through the ECB descriptions in the enabling.
14882 */
14883 for (i = 0; i < enab->dten_ndesc; i++) {
14884 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14885 dtrace_probedesc_t *desc = &ep->dted_probe;
14886
fe8ab488 14887 /* APPLE NOTE: Darwin employs size bounded string operation. */
b0d623f7
A
14888 if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
14889 continue;
2d21ac55 14890
b0d623f7
A
14891 if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
14892 continue;
14893
14894 if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
14895 continue;
b0d623f7 14896
b0d623f7
A
14897 if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
14898 ep)) != 0) {
b0d623f7 14899 /*
2d21ac55
A
14900 * Adding this helper action failed -- we are now going
14901 * to rip out the entire generation and return failure.
14902 */
2d21ac55 14903 (void) dtrace_helper_destroygen(p, help->dthps_generation);
2d21ac55
A
14904 dtrace_enabling_destroy(enab);
14905 dtrace_dof_destroy(dof);
14906 return (-1);
14907 }
14908
14909 nhelpers++;
14910 }
14911
14912 if (nhelpers < enab->dten_ndesc)
14913 dtrace_dof_error(dof, "unmatched helpers");
14914
14915 gen = help->dthps_generation++;
14916 dtrace_enabling_destroy(enab);
14917
14918 if (dhp != NULL && nprovs > 0) {
14919 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
2d21ac55 14920 if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
2d21ac55 14921 lck_mtx_unlock(&dtrace_lock);
2d21ac55 14922 dtrace_helper_provider_register(p, help, dhp);
2d21ac55
A
14923 lck_mtx_lock(&dtrace_lock);
14924
14925 destroy = 0;
14926 }
14927 }
14928
14929 if (destroy)
14930 dtrace_dof_destroy(dof);
14931
14932 return (gen);
14933}
14934
2d21ac55 14935/*
fe8ab488 14936 * APPLE NOTE: DTrace lazy dof implementation
2d21ac55
A
14937 *
14938 * DTrace user static probes (USDT probes) and helper actions are loaded
14939 * in a process by proccessing dof sections. The dof sections are passed
14940 * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
14941 * expensive to process dof for a process that will never use it. There
14942 * is a memory cost (allocating the providers/probes), and a cpu cost
14943 * (creating the providers/probes).
14944 *
14945 * To reduce this cost, we use "lazy dof". The normal proceedure for
14946 * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
14947 * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
14948 * used, each process retains the dof_ioctl_data_t block, instead of
14949 * copying in the data it points to.
14950 *
14951 * The dof_ioctl_data_t blocks are managed as if they were the actual
14952 * processed dof; on fork the block is copied to the child, on exec and
14953 * exit the block is freed.
14954 *
14955 * If the process loads library(s) containing additional dof, the
14956 * new dof_ioctl_data_t is merged with the existing block.
14957 *
14958 * There are a few catches that make this slightly more difficult.
14959 * When dyld registers dof_ioctl_data_t blocks, it expects a unique
14960 * identifier value for each dof in the block. In non-lazy dof terms,
14961 * this is the generation that dof was loaded in. If we hand back
14962 * a UID for a lazy dof, that same UID must be able to unload the
14963 * dof once it has become non-lazy. To meet this requirement, the
14964 * code that loads lazy dof requires that the UID's for dof(s) in
14965 * the lazy dof be sorted, and in ascending order. It is okay to skip
14966 * UID's, I.E., 1 -> 5 -> 6 is legal.
14967 *
14968 * Once a process has become non-lazy, it will stay non-lazy. All
14969 * future dof operations for that process will be non-lazy, even
14970 * if the dof mode transitions back to lazy.
14971 *
14972 * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
14973 * That way if the lazy check fails due to transitioning to non-lazy, the
14974 * right thing is done with the newly faulted in dof.
14975 */
14976
14977/*
14978 * This method is a bit squicky. It must handle:
14979 *
14980 * dof should not be lazy.
14981 * dof should have been handled lazily, but there was an error
14982 * dof was handled lazily, and needs to be freed.
14983 * dof was handled lazily, and must not be freed.
14984 *
14985 *
14986 * Returns EACCESS if dof should be handled non-lazily.
14987 *
14988 * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
14989 *
14990 * If the dofs data is claimed by this method, dofs_claimed will be set.
14991 * Callers should not free claimed dofs.
14992 */
b0d623f7 14993static int
2d21ac55
A
14994dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
14995{
14996 ASSERT(p);
14997 ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
14998
14999 int rval = 0;
15000 *dofs_claimed = 0;
15001
15002 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15003
2d21ac55
A
15004 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15005 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
15006
15007 /*
15008 * Any existing helpers force non-lazy behavior.
15009 */
15010 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15011 lck_mtx_lock(&p->p_dtrace_sprlock);
15012
15013 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15014 unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
15015 unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
15016
15017 /*
15018 * Range check...
15019 */
15020 if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
15021 dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
15022 rval = EINVAL;
15023 goto unlock;
15024 }
15025
15026 /*
15027 * Each dof being added must be assigned a unique generation.
15028 */
15029 uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
15030 for (i=0; i<incoming_dofs->dofiod_count; i++) {
15031 /*
15032 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
15033 */
15034 ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
15035 incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
15036 }
15037
15038
15039 if (existing_dofs) {
15040 /*
15041 * Merge the existing and incoming dofs
15042 */
15043 size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
15044 dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
15045
15046 bcopy(&existing_dofs->dofiod_helpers[0],
15047 &merged_dofs->dofiod_helpers[0],
15048 sizeof(dof_helper_t) * existing_dofs_count);
15049 bcopy(&incoming_dofs->dofiod_helpers[0],
15050 &merged_dofs->dofiod_helpers[existing_dofs_count],
15051 sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
15052
15053 merged_dofs->dofiod_count = merged_dofs_count;
15054
15055 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
15056
15057 p->p_dtrace_lazy_dofs = merged_dofs;
15058 } else {
15059 /*
15060 * Claim the incoming dofs
15061 */
15062 *dofs_claimed = 1;
15063 p->p_dtrace_lazy_dofs = incoming_dofs;
15064 }
15065
15066#if DEBUG
15067 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
15068 for (i=0; i<all_dofs->dofiod_count-1; i++) {
15069 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
15070 }
b0d623f7 15071#endif /* DEBUG */
2d21ac55
A
15072
15073unlock:
15074 lck_mtx_unlock(&p->p_dtrace_sprlock);
15075 } else {
15076 rval = EACCES;
15077 }
15078
15079 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15080
15081 return rval;
15082}
15083
15084/*
15085 * Returns:
15086 *
15087 * EINVAL: lazy dof is enabled, but the requested generation was not found.
15088 * EACCES: This removal needs to be handled non-lazily.
15089 */
b0d623f7 15090static int
2d21ac55
A
15091dtrace_lazy_dofs_remove(proc_t *p, int generation)
15092{
15093 int rval = EINVAL;
15094
15095 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15096
2d21ac55
A
15097 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15098 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
15099
15100 /*
15101 * Any existing helpers force non-lazy behavior.
15102 */
15103 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15104 lck_mtx_lock(&p->p_dtrace_sprlock);
15105
15106 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15107
15108 if (existing_dofs) {
15109 int index, existing_dofs_count = existing_dofs->dofiod_count;
15110 for (index=0; index<existing_dofs_count; index++) {
15111 if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
15112 dof_ioctl_data_t* removed_dofs = NULL;
15113
15114 /*
15115 * If there is only 1 dof, we'll delete it and swap in NULL.
15116 */
15117 if (existing_dofs_count > 1) {
15118 int removed_dofs_count = existing_dofs_count - 1;
15119 size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
15120
15121 removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
15122 removed_dofs->dofiod_count = removed_dofs_count;
15123
15124 /*
15125 * copy the remaining data.
15126 */
15127 if (index > 0) {
15128 bcopy(&existing_dofs->dofiod_helpers[0],
15129 &removed_dofs->dofiod_helpers[0],
15130 index * sizeof(dof_helper_t));
15131 }
15132
15133 if (index < existing_dofs_count-1) {
15134 bcopy(&existing_dofs->dofiod_helpers[index+1],
15135 &removed_dofs->dofiod_helpers[index],
15136 (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
15137 }
15138 }
15139
15140 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
15141
15142 p->p_dtrace_lazy_dofs = removed_dofs;
15143
15144 rval = KERN_SUCCESS;
15145
15146 break;
15147 }
15148 }
15149
15150#if DEBUG
15151 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
15152 if (all_dofs) {
15153 unsigned int i;
15154 for (i=0; i<all_dofs->dofiod_count-1; i++) {
15155 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
15156 }
15157 }
15158#endif
15159
15160 }
15161
15162 lck_mtx_unlock(&p->p_dtrace_sprlock);
15163 } else {
15164 rval = EACCES;
15165 }
15166
15167 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
39037602 15168
2d21ac55
A
15169 return rval;
15170}
15171
15172void
15173dtrace_lazy_dofs_destroy(proc_t *p)
15174{
15175 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15176 lck_mtx_lock(&p->p_dtrace_sprlock);
15177
2d21ac55
A
15178 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15179
15180 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15181 p->p_dtrace_lazy_dofs = NULL;
15182
15183 lck_mtx_unlock(&p->p_dtrace_sprlock);
15184 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15185
15186 if (lazy_dofs) {
15187 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15188 }
15189}
15190
2d21ac55
A
15191static int
15192dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
15193{
15194#pragma unused(ignored)
15195 /*
15196 * Okay to NULL test without taking the sprlock.
15197 */
15198 return p->p_dtrace_lazy_dofs != NULL;
15199}
15200
39037602
A
15201static void
15202dtrace_lazy_dofs_process(proc_t *p) {
2d21ac55
A
15203 /*
15204 * It is possible this process may exit during our attempt to
15205 * fault in the dof. We could fix this by holding locks longer,
15206 * but the errors are benign.
15207 */
15208 lck_mtx_lock(&p->p_dtrace_sprlock);
15209
39037602 15210
2d21ac55
A
15211 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15212 ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
15213
2d21ac55
A
15214 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15215 p->p_dtrace_lazy_dofs = NULL;
15216
15217 lck_mtx_unlock(&p->p_dtrace_sprlock);
15218
15219 /*
15220 * Process each dof_helper_t
15221 */
15222 if (lazy_dofs != NULL) {
15223 unsigned int i;
15224 int rval;
15225
15226 for (i=0; i<lazy_dofs->dofiod_count; i++) {
15227 /*
15228 * When loading lazy dof, we depend on the generations being sorted in ascending order.
15229 */
15230 ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
15231
15232 dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
15233
15234 /*
15235 * We stored the generation in dofhp_dof. Save it, and restore the original value.
15236 */
15237 int generation = dhp->dofhp_dof;
15238 dhp->dofhp_dof = dhp->dofhp_addr;
15239
15240 dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
39037602 15241
2d21ac55
A
15242 if (dof != NULL) {
15243 dtrace_helpers_t *help;
15244
15245 lck_mtx_lock(&dtrace_lock);
15246
15247 /*
15248 * This must be done with the dtrace_lock held
15249 */
15250 if ((help = p->p_dtrace_helpers) == NULL)
15251 help = dtrace_helpers_create(p);
15252
15253 /*
15254 * If the generation value has been bumped, someone snuck in
15255 * when we released the dtrace lock. We have to dump this generation,
15256 * there is no safe way to load it.
15257 */
15258 if (help->dthps_generation <= generation) {
15259 help->dthps_generation = generation;
15260
15261 /*
15262 * dtrace_helper_slurp() takes responsibility for the dof --
15263 * it may free it now or it may save it and free it later.
15264 */
15265 if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
15266 dtrace_dof_error(NULL, "returned value did not match expected generation");
15267 }
15268 }
15269
15270 lck_mtx_unlock(&dtrace_lock);
15271 }
15272 }
15273
15274 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15275 }
39037602
A
15276}
15277
15278static int
15279dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
15280{
15281#pragma unused(ignored)
15282
15283 dtrace_lazy_dofs_process(p);
2d21ac55
A
15284
15285 return PROC_RETURNED;
15286}
15287
39037602
A
15288#define DTRACE_LAZY_DOFS_DUPLICATED 1
15289
15290static int
15291dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
15292{
5ba3f43e
A
15293 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15294 LCK_MTX_ASSERT(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
15295 LCK_MTX_ASSERT(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
39037602
A
15296
15297 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15298 lck_mtx_lock(&parent->p_dtrace_sprlock);
15299
15300 /*
15301 * We need to make sure that the transition to lazy dofs -> helpers
15302 * was atomic for our parent
15303 */
15304 ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
15305 /*
15306 * In theory we should hold the child sprlock, but this is safe...
15307 */
15308 ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
15309
15310 dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
15311 dof_ioctl_data_t* child_dofs = NULL;
15312 if (parent_dofs) {
15313 size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
15314 child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
15315 bcopy(parent_dofs, child_dofs, parent_dofs_size);
15316 }
15317
15318 lck_mtx_unlock(&parent->p_dtrace_sprlock);
15319
15320 if (child_dofs) {
15321 lck_mtx_lock(&child->p_dtrace_sprlock);
15322 child->p_dtrace_lazy_dofs = child_dofs;
15323 lck_mtx_unlock(&child->p_dtrace_sprlock);
15324 /**
15325 * We process the DOF at this point if the mode is set to
15326 * LAZY_OFF. This can happen if DTrace is still processing the
15327 * DOF of other process (which can happen because the
15328 * protected pager can have a huge latency)
15329 * but has not processed our parent yet
15330 */
15331 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
15332 dtrace_lazy_dofs_process(child);
15333 }
15334 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15335
15336 return DTRACE_LAZY_DOFS_DUPLICATED;
15337 }
15338 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15339
15340 return 0;
15341}
15342
2d21ac55
A
15343static dtrace_helpers_t *
15344dtrace_helpers_create(proc_t *p)
15345{
15346 dtrace_helpers_t *help;
15347
5ba3f43e 15348 LCK_MTX_ASSERT(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
15349 ASSERT(p->p_dtrace_helpers == NULL);
15350
15351 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15352 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15353 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15354
15355 p->p_dtrace_helpers = help;
15356 dtrace_helpers++;
15357
15358 return (help);
15359}
15360
2d21ac55
A
15361static void
15362dtrace_helpers_destroy(proc_t* p)
15363{
2d21ac55
A
15364 dtrace_helpers_t *help;
15365 dtrace_vstate_t *vstate;
b0d623f7 15366 uint_t i;
2d21ac55
A
15367
15368 lck_mtx_lock(&dtrace_lock);
15369
15370 ASSERT(p->p_dtrace_helpers != NULL);
15371 ASSERT(dtrace_helpers > 0);
15372
15373 help = p->p_dtrace_helpers;
15374 vstate = &help->dthps_vstate;
15375
15376 /*
15377 * We're now going to lose the help from this process.
15378 */
15379 p->p_dtrace_helpers = NULL;
15380 dtrace_sync();
15381
15382 /*
15383 * Destory the helper actions.
15384 */
15385 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15386 dtrace_helper_action_t *h, *next;
15387
15388 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15389 next = h->dtha_next;
15390 dtrace_helper_action_destroy(h, vstate);
15391 h = next;
15392 }
15393 }
15394
15395 lck_mtx_unlock(&dtrace_lock);
15396
15397 /*
15398 * Destroy the helper providers.
15399 */
15400 if (help->dthps_maxprovs > 0) {
15401 lck_mtx_lock(&dtrace_meta_lock);
15402 if (dtrace_meta_pid != NULL) {
15403 ASSERT(dtrace_deferred_pid == NULL);
15404
15405 for (i = 0; i < help->dthps_nprovs; i++) {
15406 dtrace_helper_provider_remove(
d190cdc3 15407 &help->dthps_provs[i]->dthp_prov, p);
2d21ac55
A
15408 }
15409 } else {
15410 lck_mtx_lock(&dtrace_lock);
15411 ASSERT(help->dthps_deferred == 0 ||
15412 help->dthps_next != NULL ||
15413 help->dthps_prev != NULL ||
15414 help == dtrace_deferred_pid);
15415
15416 /*
15417 * Remove the helper from the deferred list.
15418 */
15419 if (help->dthps_next != NULL)
15420 help->dthps_next->dthps_prev = help->dthps_prev;
15421 if (help->dthps_prev != NULL)
15422 help->dthps_prev->dthps_next = help->dthps_next;
15423 if (dtrace_deferred_pid == help) {
15424 dtrace_deferred_pid = help->dthps_next;
15425 ASSERT(help->dthps_prev == NULL);
15426 }
15427
15428 lck_mtx_unlock(&dtrace_lock);
15429 }
15430
15431 lck_mtx_unlock(&dtrace_meta_lock);
15432
15433 for (i = 0; i < help->dthps_nprovs; i++) {
15434 dtrace_helper_provider_destroy(help->dthps_provs[i]);
15435 }
15436
15437 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15438 sizeof (dtrace_helper_provider_t *));
15439 }
15440
15441 lck_mtx_lock(&dtrace_lock);
15442
15443 dtrace_vstate_fini(&help->dthps_vstate);
15444 kmem_free(help->dthps_actions,
15445 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15446 kmem_free(help, sizeof (dtrace_helpers_t));
15447
15448 --dtrace_helpers;
15449 lck_mtx_unlock(&dtrace_lock);
15450}
15451
15452static void
15453dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15454{
15455 dtrace_helpers_t *help, *newhelp;
15456 dtrace_helper_action_t *helper, *new, *last;
15457 dtrace_difo_t *dp;
15458 dtrace_vstate_t *vstate;
b0d623f7
A
15459 uint_t i;
15460 int j, sz, hasprovs = 0;
2d21ac55
A
15461
15462 lck_mtx_lock(&dtrace_lock);
15463 ASSERT(from->p_dtrace_helpers != NULL);
15464 ASSERT(dtrace_helpers > 0);
15465
15466 help = from->p_dtrace_helpers;
15467 newhelp = dtrace_helpers_create(to);
15468 ASSERT(to->p_dtrace_helpers != NULL);
15469
15470 newhelp->dthps_generation = help->dthps_generation;
15471 vstate = &newhelp->dthps_vstate;
15472
15473 /*
15474 * Duplicate the helper actions.
15475 */
15476 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15477 if ((helper = help->dthps_actions[i]) == NULL)
15478 continue;
15479
15480 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15481 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15482 KM_SLEEP);
15483 new->dtha_generation = helper->dtha_generation;
15484
15485 if ((dp = helper->dtha_predicate) != NULL) {
15486 dp = dtrace_difo_duplicate(dp, vstate);
15487 new->dtha_predicate = dp;
15488 }
15489
15490 new->dtha_nactions = helper->dtha_nactions;
15491 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15492 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15493
b0d623f7
A
15494 for (j = 0; j < new->dtha_nactions; j++) {
15495 dtrace_difo_t *dpj = helper->dtha_actions[j];
15496
15497 ASSERT(dpj != NULL);
15498 dpj = dtrace_difo_duplicate(dpj, vstate);
15499 new->dtha_actions[j] = dpj;
15500 }
2d21ac55
A
15501
15502 if (last != NULL) {
15503 last->dtha_next = new;
15504 } else {
15505 newhelp->dthps_actions[i] = new;
15506 }
15507
15508 last = new;
15509 }
15510 }
15511
15512 /*
15513 * Duplicate the helper providers and register them with the
15514 * DTrace framework.
15515 */
15516 if (help->dthps_nprovs > 0) {
15517 newhelp->dthps_nprovs = help->dthps_nprovs;
15518 newhelp->dthps_maxprovs = help->dthps_nprovs;
15519 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15520 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15521 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15522 newhelp->dthps_provs[i] = help->dthps_provs[i];
15523 newhelp->dthps_provs[i]->dthp_ref++;
15524 }
15525
15526 hasprovs = 1;
15527 }
15528
15529 lck_mtx_unlock(&dtrace_lock);
15530
15531 if (hasprovs)
15532 dtrace_helper_provider_register(to, newhelp, NULL);
15533}
15534
39037602
A
15535/**
15536 * DTrace Process functions
15537 */
15538
15539void
15540dtrace_proc_fork(proc_t *parent_proc, proc_t *child_proc, int spawn)
15541{
15542 /*
15543 * This code applies to new processes who are copying the task
15544 * and thread state and address spaces of their parent process.
15545 */
15546 if (!spawn) {
15547 /*
15548 * APPLE NOTE: Solaris does a sprlock() and drops the
15549 * proc_lock here. We're cheating a bit and only taking
15550 * the p_dtrace_sprlock lock. A full sprlock would
15551 * task_suspend the parent.
15552 */
15553 lck_mtx_lock(&parent_proc->p_dtrace_sprlock);
15554
15555 /*
15556 * Remove all DTrace tracepoints from the child process. We
15557 * need to do this _before_ duplicating USDT providers since
15558 * any associated probes may be immediately enabled.
15559 */
15560 if (parent_proc->p_dtrace_count > 0) {
15561 dtrace_fasttrap_fork(parent_proc, child_proc);
15562 }
15563
15564 lck_mtx_unlock(&parent_proc->p_dtrace_sprlock);
15565
15566 /*
15567 * Duplicate any lazy dof(s). This must be done while NOT
15568 * holding the parent sprlock! Lock ordering is
15569 * dtrace_dof_mode_lock, then sprlock. It is imperative we
15570 * always call dtrace_lazy_dofs_duplicate, rather than null
15571 * check and call if !NULL. If we NULL test, during lazy dof
15572 * faulting we can race with the faulting code and proceed
15573 * from here to beyond the helpers copy. The lazy dof
15574 * faulting will then fail to copy the helpers to the child
15575 * process. We return if we duplicated lazy dofs as a process
15576 * can only have one at the same time to avoid a race between
15577 * a dtrace client and dtrace_proc_fork where a process would
15578 * end up with both lazy dofs and helpers.
15579 */
15580 if (dtrace_lazy_dofs_duplicate(parent_proc, child_proc) == DTRACE_LAZY_DOFS_DUPLICATED) {
15581 return;
15582 }
15583
15584 /*
15585 * Duplicate any helper actions and providers if they haven't
15586 * already.
15587 */
15588#if !defined(__APPLE__)
15589 /*
15590 * The SFORKING
15591 * we set above informs the code to enable USDT probes that
15592 * sprlock() may fail because the child is being forked.
15593 */
15594#endif
15595 /*
15596 * APPLE NOTE: As best I can tell, Apple's sprlock() equivalent
15597 * never fails to find the child. We do not set SFORKING.
15598 */
15599 if (parent_proc->p_dtrace_helpers != NULL && dtrace_helpers_fork) {
15600 (*dtrace_helpers_fork)(parent_proc, child_proc);
15601 }
15602 }
15603}
15604
15605void
15606dtrace_proc_exec(proc_t *p)
15607{
15608 /*
15609 * Invalidate any predicate evaluation already cached for this thread by DTrace.
15610 * That's because we've just stored to p_comm and DTrace refers to that when it
15611 * evaluates the "execname" special variable. uid and gid may have changed as well.
15612 */
15613 dtrace_set_thread_predcache(current_thread(), 0);
15614
15615 /*
15616 * Free any outstanding lazy dof entries. It is imperative we
15617 * always call dtrace_lazy_dofs_destroy, rather than null check
15618 * and call if !NULL. If we NULL test, during lazy dof faulting
15619 * we can race with the faulting code and proceed from here to
15620 * beyond the helpers cleanup. The lazy dof faulting will then
15621 * install new helpers which no longer belong to this process!
15622 */
15623 dtrace_lazy_dofs_destroy(p);
15624
15625
15626 /*
15627 * Clean up any DTrace helpers for the process.
15628 */
15629 if (p->p_dtrace_helpers != NULL && dtrace_helpers_cleanup) {
15630 (*dtrace_helpers_cleanup)(p);
15631 }
15632
15633 /*
15634 * Cleanup the DTrace provider associated with this process.
15635 */
15636 proc_lock(p);
15637 if (p->p_dtrace_probes && dtrace_fasttrap_exec_ptr) {
15638 (*dtrace_fasttrap_exec_ptr)(p);
15639 }
15640 proc_unlock(p);
15641}
15642
15643void
15644dtrace_proc_exit(proc_t *p)
15645{
15646 /*
15647 * Free any outstanding lazy dof entries. It is imperative we
15648 * always call dtrace_lazy_dofs_destroy, rather than null check
15649 * and call if !NULL. If we NULL test, during lazy dof faulting
15650 * we can race with the faulting code and proceed from here to
15651 * beyond the helpers cleanup. The lazy dof faulting will then
15652 * install new helpers which will never be cleaned up, and leak.
15653 */
15654 dtrace_lazy_dofs_destroy(p);
15655
15656 /*
15657 * Clean up any DTrace helper actions or probes for the process.
15658 */
15659 if (p->p_dtrace_helpers != NULL) {
15660 (*dtrace_helpers_cleanup)(p);
15661 }
15662
15663 /*
15664 * Clean up any DTrace probes associated with this process.
15665 */
15666 /*
15667 * APPLE NOTE: We release ptss pages/entries in dtrace_fasttrap_exit_ptr(),
15668 * call this after dtrace_helpers_cleanup()
15669 */
15670 proc_lock(p);
15671 if (p->p_dtrace_probes && dtrace_fasttrap_exit_ptr) {
15672 (*dtrace_fasttrap_exit_ptr)(p);
15673 }
15674 proc_unlock(p);
15675}
15676
2d21ac55
A
15677/*
15678 * DTrace Hook Functions
15679 */
6d2010ae 15680
6d2010ae 15681/*
fe8ab488
A
15682 * APPLE NOTE: dtrace_modctl_* routines for kext support.
15683 * Used to manipulate the modctl list within dtrace xnu.
6d2010ae
A
15684 */
15685
15686modctl_t *dtrace_modctl_list;
15687
15688static void
15689dtrace_modctl_add(struct modctl * newctl)
15690{
15691 struct modctl *nextp, *prevp;
15692
15693 ASSERT(newctl != NULL);
5ba3f43e 15694 LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
6d2010ae
A
15695
15696 // Insert new module at the front of the list,
15697
15698 newctl->mod_next = dtrace_modctl_list;
15699 dtrace_modctl_list = newctl;
15700
15701 /*
15702 * If a module exists with the same name, then that module
15703 * must have been unloaded with enabled probes. We will move
15704 * the unloaded module to the new module's stale chain and
15705 * then stop traversing the list.
15706 */
15707
15708 prevp = newctl;
15709 nextp = newctl->mod_next;
15710
15711 while (nextp != NULL) {
15712 if (nextp->mod_loaded) {
15713 /* This is a loaded module. Keep traversing. */
15714 prevp = nextp;
15715 nextp = nextp->mod_next;
15716 continue;
15717 }
15718 else {
15719 /* Found an unloaded module */
15720 if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
15721 /* Names don't match. Keep traversing. */
15722 prevp = nextp;
15723 nextp = nextp->mod_next;
15724 continue;
15725 }
15726 else {
15727 /* We found a stale entry, move it. We're done. */
15728 prevp->mod_next = nextp->mod_next;
15729 newctl->mod_stale = nextp;
15730 nextp->mod_next = NULL;
15731 break;
15732 }
15733 }
15734 }
15735}
15736
15737static modctl_t *
15738dtrace_modctl_lookup(struct kmod_info * kmod)
15739{
5ba3f43e 15740 LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
6d2010ae
A
15741
15742 struct modctl * ctl;
15743
15744 for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
15745 if (ctl->mod_id == kmod->id)
15746 return(ctl);
15747 }
15748 return (NULL);
15749}
15750
15751/*
15752 * This routine is called from dtrace_module_unloaded().
15753 * It removes a modctl structure and its stale chain
15754 * from the kext shadow list.
15755 */
15756static void
15757dtrace_modctl_remove(struct modctl * ctl)
15758{
15759 ASSERT(ctl != NULL);
5ba3f43e 15760 LCK_MTX_ASSERT(&mod_lock, LCK_MTX_ASSERT_OWNED);
6d2010ae
A
15761 modctl_t *prevp, *nextp, *curp;
15762
15763 // Remove stale chain first
15764 for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
15765 nextp = curp->mod_stale;
15766 /* There should NEVER be user symbols allocated at this point */
15767 ASSERT(curp->mod_user_symbols == NULL);
15768 kmem_free(curp, sizeof(modctl_t));
15769 }
15770
15771 prevp = NULL;
15772 curp = dtrace_modctl_list;
15773
15774 while (curp != ctl) {
15775 prevp = curp;
15776 curp = curp->mod_next;
15777 }
15778
15779 if (prevp != NULL) {
15780 prevp->mod_next = ctl->mod_next;
15781 }
15782 else {
15783 dtrace_modctl_list = ctl->mod_next;
15784 }
15785
15786 /* There should NEVER be user symbols allocated at this point */
15787 ASSERT(ctl->mod_user_symbols == NULL);
15788
15789 kmem_free (ctl, sizeof(modctl_t));
15790}
15791
6d2010ae
A
15792/*
15793 * APPLE NOTE: The kext loader will call dtrace_module_loaded
15794 * when the kext is loaded in memory, but before calling the
15795 * kext's start routine.
15796 *
15797 * Return 0 on success
15798 * Return -1 on failure
15799 */
15800
6d2010ae 15801static int
316670eb 15802dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
2d21ac55
A
15803{
15804 dtrace_provider_t *prv;
15805
6d2010ae
A
15806 /*
15807 * If kernel symbols have been disabled, return immediately
15808 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
15809 */
15810 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
15811 return 0;
15812
15813 struct modctl *ctl = NULL;
15814 if (!kmod || kmod->address == 0 || kmod->size == 0)
15815 return(-1);
15816
15817 lck_mtx_lock(&dtrace_provider_lock);
15818 lck_mtx_lock(&mod_lock);
15819
15820 /*
15821 * Have we seen this kext before?
15822 */
2d21ac55 15823
6d2010ae
A
15824 ctl = dtrace_modctl_lookup(kmod);
15825
15826 if (ctl != NULL) {
15827 /* bail... we already have this kext in the modctl list */
15828 lck_mtx_unlock(&mod_lock);
15829 lck_mtx_unlock(&dtrace_provider_lock);
15830 if (dtrace_err_verbose)
15831 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);
15832 return(-1);
15833 }
15834 else {
15835 ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
15836 if (ctl == NULL) {
15837 if (dtrace_err_verbose)
15838 cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
15839 lck_mtx_unlock(&mod_lock);
15840 lck_mtx_unlock(&dtrace_provider_lock);
15841 return (-1);
15842 }
15843 ctl->mod_next = NULL;
15844 ctl->mod_stale = NULL;
15845 strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
15846 ctl->mod_loadcnt = kmod->id;
15847 ctl->mod_nenabled = 0;
15848 ctl->mod_address = kmod->address;
15849 ctl->mod_size = kmod->size;
15850 ctl->mod_id = kmod->id;
15851 ctl->mod_loaded = 1;
15852 ctl->mod_flags = 0;
15853 ctl->mod_user_symbols = NULL;
15854
15855 /*
15856 * Find the UUID for this module, if it has one
15857 */
15858 kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
15859 struct load_command* load_cmd = (struct load_command *)&header[1];
15860 uint32_t i;
15861 for (i = 0; i < header->ncmds; i++) {
15862 if (load_cmd->cmd == LC_UUID) {
15863 struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
15864 memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
15865 ctl->mod_flags |= MODCTL_HAS_UUID;
15866 break;
15867 }
15868 load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
15869 }
15870
15871 if (ctl->mod_address == g_kernel_kmod_info.address) {
15872 ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
15873 }
15874 }
15875 dtrace_modctl_add(ctl);
15876
15877 /*
15878 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
15879 */
15880 lck_mtx_lock(&dtrace_lock);
15881
15882 /*
316670eb
A
15883 * DTrace must decide if it will instrument modules lazily via
15884 * userspace symbols (default mode), or instrument immediately via
15885 * kernel symbols (non-default mode)
15886 *
15887 * When in default/lazy mode, DTrace will only support modules
15888 * built with a valid UUID.
15889 *
15890 * Overriding the default can be done explicitly in one of
15891 * the following two ways.
15892 *
15893 * A module can force symbols from kernel space using the plist key,
15894 * OSBundleForceDTraceInit (see kmod.h). If this per kext state is set,
15895 * we fall through and instrument this module now.
15896 *
15897 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
15898 * from kernel space (see dtrace_impl.h). If this system state is set
15899 * to a non-userspace mode, we fall through and instrument the module now.
6d2010ae 15900 */
316670eb
A
15901
15902 if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
15903 (!(flag & KMOD_DTRACE_FORCE_INIT)))
15904 {
15905 /* We will instrument the module lazily -- this is the default */
6d2010ae
A
15906 lck_mtx_unlock(&dtrace_lock);
15907 lck_mtx_unlock(&mod_lock);
15908 lck_mtx_unlock(&dtrace_provider_lock);
15909 return 0;
15910 }
15911
316670eb 15912 /* We will instrument the module immediately using kernel symbols */
6d2010ae
A
15913 ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
15914
15915 lck_mtx_unlock(&dtrace_lock);
6d2010ae 15916
2d21ac55
A
15917 /*
15918 * We're going to call each providers per-module provide operation
15919 * specifying only this module.
15920 */
15921 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
6d2010ae
A
15922 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15923
6d2010ae 15924 /*
fe8ab488
A
15925 * APPLE NOTE: The contract with the kext loader is that once this function
15926 * has completed, it may delete kernel symbols at will.
15927 * We must set this while still holding the mod_lock.
6d2010ae
A
15928 */
15929 ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
6d2010ae 15930
2d21ac55
A
15931 lck_mtx_unlock(&mod_lock);
15932 lck_mtx_unlock(&dtrace_provider_lock);
6d2010ae 15933
2d21ac55
A
15934 /*
15935 * If we have any retained enablings, we need to match against them.
15936 * Enabling probes requires that cpu_lock be held, and we cannot hold
15937 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15938 * module. (In particular, this happens when loading scheduling
15939 * classes.) So if we have any retained enablings, we need to dispatch
15940 * our task queue to do the match for us.
15941 */
15942 lck_mtx_lock(&dtrace_lock);
6d2010ae 15943
2d21ac55
A
15944 if (dtrace_retained == NULL) {
15945 lck_mtx_unlock(&dtrace_lock);
6d2010ae 15946 return 0;
2d21ac55 15947 }
6d2010ae 15948
6d2010ae
A
15949 /* APPLE NOTE!
15950 *
15951 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
15952 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
15953 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
15954 * the delay call as well.
15955 */
15956 lck_mtx_unlock(&dtrace_lock);
15957
15958 dtrace_enabling_matchall();
15959
15960 return 0;
2d21ac55
A
15961}
15962
6d2010ae
A
15963/*
15964 * Return 0 on success
15965 * Return -1 on failure
15966 */
15967static int
15968dtrace_module_unloaded(struct kmod_info *kmod)
2d21ac55 15969{
6d2010ae
A
15970 dtrace_probe_t template, *probe, *first, *next;
15971 dtrace_provider_t *prov;
15972 struct modctl *ctl = NULL;
15973 struct modctl *syncctl = NULL;
15974 struct modctl *nextsyncctl = NULL;
15975 int syncmode = 0;
15976
15977 lck_mtx_lock(&dtrace_provider_lock);
15978 lck_mtx_lock(&mod_lock);
15979 lck_mtx_lock(&dtrace_lock);
2d21ac55 15980
6d2010ae
A
15981 if (kmod == NULL) {
15982 syncmode = 1;
15983 }
15984 else {
15985 ctl = dtrace_modctl_lookup(kmod);
15986 if (ctl == NULL)
15987 {
15988 lck_mtx_unlock(&dtrace_lock);
15989 lck_mtx_unlock(&mod_lock);
15990 lck_mtx_unlock(&dtrace_provider_lock);
15991 return (-1);
15992 }
15993 ctl->mod_loaded = 0;
15994 ctl->mod_address = 0;
15995 ctl->mod_size = 0;
15996 }
15997
15998 if (dtrace_bymod == NULL) {
15999 /*
16000 * The DTrace module is loaded (obviously) but not attached;
16001 * we don't have any work to do.
16002 */
16003 if (ctl != NULL)
16004 (void)dtrace_modctl_remove(ctl);
6d2010ae 16005 lck_mtx_unlock(&dtrace_lock);
fe8ab488
A
16006 lck_mtx_unlock(&mod_lock);
16007 lck_mtx_unlock(&dtrace_provider_lock);
6d2010ae
A
16008 return(0);
16009 }
16010
16011 /* Syncmode set means we target and traverse entire modctl list. */
16012 if (syncmode)
16013 nextsyncctl = dtrace_modctl_list;
16014
16015syncloop:
16016 if (syncmode)
16017 {
16018 /* find a stale modctl struct */
16019 for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
16020 if (syncctl->mod_address == 0)
16021 break;
16022 }
16023 if (syncctl==NULL)
16024 {
16025 /* We have no more work to do */
6d2010ae 16026 lck_mtx_unlock(&dtrace_lock);
fe8ab488
A
16027 lck_mtx_unlock(&mod_lock);
16028 lck_mtx_unlock(&dtrace_provider_lock);
6d2010ae
A
16029 return(0);
16030 }
16031 else {
16032 /* keep track of next syncctl in case this one is removed */
16033 nextsyncctl = syncctl->mod_next;
16034 ctl = syncctl;
16035 }
16036 }
16037
16038 template.dtpr_mod = ctl->mod_modname;
16039
16040 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16041 probe != NULL; probe = probe->dtpr_nextmod) {
16042 if (probe->dtpr_ecb != NULL) {
16043 /*
16044 * This shouldn't _actually_ be possible -- we're
16045 * unloading a module that has an enabled probe in it.
16046 * (It's normally up to the provider to make sure that
16047 * this can't happen.) However, because dtps_enable()
16048 * doesn't have a failure mode, there can be an
16049 * enable/unload race. Upshot: we don't want to
16050 * assert, but we're not going to disable the
16051 * probe, either.
16052 */
16053
16054
16055 if (syncmode) {
16056 /* We're syncing, let's look at next in list */
16057 goto syncloop;
16058 }
16059
6d2010ae 16060 lck_mtx_unlock(&dtrace_lock);
fe8ab488
A
16061 lck_mtx_unlock(&mod_lock);
16062 lck_mtx_unlock(&dtrace_provider_lock);
6d2010ae
A
16063
16064 if (dtrace_err_verbose) {
16065 cmn_err(CE_WARN, "unloaded module '%s' had "
16066 "enabled probes", ctl->mod_modname);
16067 }
16068 return(-1);
16069 }
16070 }
16071
16072 probe = first;
16073
16074 for (first = NULL; probe != NULL; probe = next) {
16075 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16076
16077 dtrace_probes[probe->dtpr_id - 1] = NULL;
fe8ab488 16078 probe->dtpr_provider->dtpv_probe_count--;
6d2010ae
A
16079
16080 next = probe->dtpr_nextmod;
16081 dtrace_hash_remove(dtrace_bymod, probe);
16082 dtrace_hash_remove(dtrace_byfunc, probe);
16083 dtrace_hash_remove(dtrace_byname, probe);
16084
16085 if (first == NULL) {
16086 first = probe;
16087 probe->dtpr_nextmod = NULL;
16088 } else {
16089 probe->dtpr_nextmod = first;
16090 first = probe;
16091 }
16092 }
16093
16094 /*
16095 * We've removed all of the module's probes from the hash chains and
16096 * from the probe array. Now issue a dtrace_sync() to be sure that
16097 * everyone has cleared out from any probe array processing.
16098 */
16099 dtrace_sync();
16100
16101 for (probe = first; probe != NULL; probe = first) {
16102 first = probe->dtpr_nextmod;
16103 prov = probe->dtpr_provider;
16104 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16105 probe->dtpr_arg);
16106 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16107 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16108 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16109 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16110
16111 zfree(dtrace_probe_t_zone, probe);
16112 }
16113
16114 dtrace_modctl_remove(ctl);
16115
16116 if (syncmode)
16117 goto syncloop;
16118
16119 lck_mtx_unlock(&dtrace_lock);
16120 lck_mtx_unlock(&mod_lock);
16121 lck_mtx_unlock(&dtrace_provider_lock);
16122
16123 return(0);
16124}
6d2010ae
A
16125
16126void
16127dtrace_suspend(void)
16128{
16129 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16130}
16131
16132void
2d21ac55
A
16133dtrace_resume(void)
16134{
16135 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16136}
16137
16138static int
16139dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16140{
5ba3f43e 16141 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
16142 lck_mtx_lock(&dtrace_lock);
16143
16144 switch (what) {
16145 case CPU_CONFIG: {
16146 dtrace_state_t *state;
16147 dtrace_optval_t *opt, rs, c;
16148
16149 /*
16150 * For now, we only allocate a new buffer for anonymous state.
16151 */
16152 if ((state = dtrace_anon.dta_state) == NULL)
16153 break;
16154
16155 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16156 break;
16157
16158 opt = state->dts_options;
16159 c = opt[DTRACEOPT_CPU];
16160
16161 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16162 break;
16163
16164 /*
16165 * Regardless of what the actual policy is, we're going to
16166 * temporarily set our resize policy to be manual. We're
16167 * also going to temporarily set our CPU option to denote
16168 * the newly configured CPU.
16169 */
16170 rs = opt[DTRACEOPT_BUFRESIZE];
16171 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16172 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16173
16174 (void) dtrace_state_buffers(state);
16175
16176 opt[DTRACEOPT_BUFRESIZE] = rs;
16177 opt[DTRACEOPT_CPU] = c;
16178
16179 break;
16180 }
16181
16182 case CPU_UNCONFIG:
16183 /*
16184 * We don't free the buffer in the CPU_UNCONFIG case. (The
16185 * buffer will be freed when the consumer exits.)
16186 */
16187 break;
16188
16189 default:
16190 break;
16191 }
16192
16193 lck_mtx_unlock(&dtrace_lock);
16194 return (0);
16195}
16196
16197static void
16198dtrace_cpu_setup_initial(processorid_t cpu)
16199{
16200 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16201}
16202
16203static void
16204dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16205{
16206 if (dtrace_toxranges >= dtrace_toxranges_max) {
16207 int osize, nsize;
16208 dtrace_toxrange_t *range;
16209
16210 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16211
16212 if (osize == 0) {
16213 ASSERT(dtrace_toxrange == NULL);
16214 ASSERT(dtrace_toxranges_max == 0);
16215 dtrace_toxranges_max = 1;
16216 } else {
16217 dtrace_toxranges_max <<= 1;
16218 }
16219
16220 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16221 range = kmem_zalloc(nsize, KM_SLEEP);
16222
16223 if (dtrace_toxrange != NULL) {
16224 ASSERT(osize != 0);
16225 bcopy(dtrace_toxrange, range, osize);
16226 kmem_free(dtrace_toxrange, osize);
16227 }
16228
16229 dtrace_toxrange = range;
16230 }
16231
fe8ab488
A
16232 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16233 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
2d21ac55
A
16234
16235 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16236 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16237 dtrace_toxranges++;
16238}
16239
16240/*
16241 * DTrace Driver Cookbook Functions
16242 */
16243/*ARGSUSED*/
16244static int
16245dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16246{
b0d623f7 16247#pragma unused(cmd) /* __APPLE__ */
2d21ac55
A
16248 dtrace_provider_id_t id;
16249 dtrace_state_t *state = NULL;
16250 dtrace_enabling_t *enab;
16251
16252 lck_mtx_lock(&cpu_lock);
16253 lck_mtx_lock(&dtrace_provider_lock);
16254 lck_mtx_lock(&dtrace_lock);
16255
b0d623f7 16256 /* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
2d21ac55
A
16257
16258 ddi_report_dev(devi);
16259 dtrace_devi = devi;
16260
16261 dtrace_modload = dtrace_module_loaded;
16262 dtrace_modunload = dtrace_module_unloaded;
16263 dtrace_cpu_init = dtrace_cpu_setup_initial;
16264 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16265 dtrace_helpers_fork = dtrace_helpers_duplicate;
16266 dtrace_cpustart_init = dtrace_suspend;
16267 dtrace_cpustart_fini = dtrace_resume;
16268 dtrace_debugger_init = dtrace_suspend;
16269 dtrace_debugger_fini = dtrace_resume;
2d21ac55
A
16270
16271 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16272
5ba3f43e 16273 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
2d21ac55
A
16274
16275 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16276 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
2d21ac55
A
16277 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16278 1, INT_MAX, 0);
16279
16280 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
c910b4d9 16281 sizeof (dtrace_dstate_percpu_t) * (int)NCPU, DTRACE_STATE_ALIGN,
2d21ac55
A
16282 NULL, NULL, NULL, NULL, NULL, 0);
16283
5ba3f43e 16284 LCK_MTX_ASSERT(&cpu_lock, LCK_MTX_ASSERT_OWNED);
39037602 16285
2d21ac55
A
16286 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16287 offsetof(dtrace_probe_t, dtpr_nextmod),
16288 offsetof(dtrace_probe_t, dtpr_prevmod));
16289
16290 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16291 offsetof(dtrace_probe_t, dtpr_nextfunc),
16292 offsetof(dtrace_probe_t, dtpr_prevfunc));
16293
16294 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16295 offsetof(dtrace_probe_t, dtpr_nextname),
16296 offsetof(dtrace_probe_t, dtpr_prevname));
16297
16298 if (dtrace_retain_max < 1) {
16299 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16300 "setting to 1", dtrace_retain_max);
16301 dtrace_retain_max = 1;
16302 }
16303
16304 /*
16305 * Now discover our toxic ranges.
16306 */
16307 dtrace_toxic_ranges(dtrace_toxrange_add);
16308
16309 /*
16310 * Before we register ourselves as a provider to our own framework,
16311 * we would like to assert that dtrace_provider is NULL -- but that's
16312 * not true if we were loaded as a dependency of a DTrace provider.
16313 * Once we've registered, we can assert that dtrace_provider is our
16314 * pseudo provider.
16315 */
16316 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16317 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16318
16319 ASSERT(dtrace_provider != NULL);
16320 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16321
fe8ab488 16322#if defined (__x86_64__)
2d21ac55
A
16323 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16324 dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
16325 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16326 dtrace_provider, NULL, NULL, "END", 0, NULL);
16327 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16328 dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
5ba3f43e
A
16329#elif (defined(__arm__) || defined(__arm64__))
16330 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16331 dtrace_provider, NULL, NULL, "BEGIN", 2, NULL);
16332 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16333 dtrace_provider, NULL, NULL, "END", 1, NULL);
16334 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16335 dtrace_provider, NULL, NULL, "ERROR", 4, NULL);
2d21ac55
A
16336#else
16337#error Unknown Architecture
fe8ab488 16338#endif
2d21ac55
A
16339
16340 dtrace_anon_property();
16341 lck_mtx_unlock(&cpu_lock);
16342
16343 /*
16344 * If DTrace helper tracing is enabled, we need to allocate the
16345 * trace buffer and initialize the values.
16346 */
16347 if (dtrace_helptrace_enabled) {
16348 ASSERT(dtrace_helptrace_buffer == NULL);
16349 dtrace_helptrace_buffer =
16350 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16351 dtrace_helptrace_next = 0;
16352 }
16353
16354 /*
16355 * If there are already providers, we must ask them to provide their
16356 * probes, and then match any anonymous enabling against them. Note
16357 * that there should be no other retained enablings at this time:
16358 * the only retained enablings at this time should be the anonymous
16359 * enabling.
16360 */
16361 if (dtrace_anon.dta_enabling != NULL) {
16362 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16363
6d2010ae 16364 /*
fe8ab488 16365 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
6d2010ae
A
16366 */
16367 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
16368 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
16369 }
6d2010ae 16370
2d21ac55
A
16371 dtrace_enabling_provide(NULL);
16372 state = dtrace_anon.dta_state;
16373
16374 /*
16375 * We couldn't hold cpu_lock across the above call to
16376 * dtrace_enabling_provide(), but we must hold it to actually
16377 * enable the probes. We have to drop all of our locks, pick
16378 * up cpu_lock, and regain our locks before matching the
16379 * retained anonymous enabling.
16380 */
16381 lck_mtx_unlock(&dtrace_lock);
16382 lck_mtx_unlock(&dtrace_provider_lock);
16383
16384 lck_mtx_lock(&cpu_lock);
16385 lck_mtx_lock(&dtrace_provider_lock);
16386 lck_mtx_lock(&dtrace_lock);
16387
16388 if ((enab = dtrace_anon.dta_enabling) != NULL)
39037602 16389 (void) dtrace_enabling_match(enab, NULL, NULL);
2d21ac55
A
16390
16391 lck_mtx_unlock(&cpu_lock);
16392 }
16393
16394 lck_mtx_unlock(&dtrace_lock);
16395 lck_mtx_unlock(&dtrace_provider_lock);
16396
16397 if (state != NULL) {
16398 /*
16399 * If we created any anonymous state, set it going now.
16400 */
16401 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16402 }
16403
16404 return (DDI_SUCCESS);
16405}
16406
2d21ac55
A
16407/*ARGSUSED*/
16408static int
16409dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16410{
16411#pragma unused(flag, otyp)
16412 dtrace_state_t *state;
16413 uint32_t priv;
16414 uid_t uid;
16415 zoneid_t zoneid;
b0d623f7 16416 int rv;
2d21ac55 16417
fe8ab488 16418 /* APPLE: Darwin puts Helper on its own major device. */
2d21ac55
A
16419
16420 /*
16421 * If no DTRACE_PRIV_* bits are set in the credential, then the
16422 * caller lacks sufficient permission to do anything with DTrace.
16423 */
16424 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16425 if (priv == DTRACE_PRIV_NONE)
16426 return (EACCES);
16427
2d21ac55 16428 /*
fe8ab488 16429 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
2d21ac55
A
16430 * It certainly can't be later than now!
16431 */
16432 fasttrap_init();
2d21ac55
A
16433
16434 /*
16435 * Ask all providers to provide all their probes.
16436 */
16437 lck_mtx_lock(&dtrace_provider_lock);
16438 dtrace_probe_provide(NULL, NULL);
16439 lck_mtx_unlock(&dtrace_provider_lock);
16440
16441 lck_mtx_lock(&cpu_lock);
16442 lck_mtx_lock(&dtrace_lock);
16443 dtrace_opens++;
16444 dtrace_membar_producer();
16445
16446 /*
16447 * If the kernel debugger is active (that is, if the kernel debugger
16448 * modified text in some way), we won't allow the open.
16449 */
16450 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16451 dtrace_opens--;
b0d623f7 16452 lck_mtx_unlock(&dtrace_lock);
fe8ab488
A
16453 lck_mtx_unlock(&cpu_lock);
16454 return (EBUSY);
16455 }
2d21ac55 16456
fe8ab488
A
16457 rv = dtrace_state_create(devp, cred_p, &state);
16458 lck_mtx_unlock(&cpu_lock);
2d21ac55 16459
fe8ab488
A
16460 if (rv != 0 || state == NULL) {
16461 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16462 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16463 lck_mtx_unlock(&dtrace_lock);
16464 /* propagate EAGAIN or ERESTART */
16465 return (rv);
16466 }
16467
16468 lck_mtx_unlock(&dtrace_lock);
2d21ac55 16469
fe8ab488 16470 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
2d21ac55 16471
fe8ab488
A
16472 /*
16473 * If we are currently lazy, transition states.
16474 *
16475 * Unlike dtrace_close, we do not need to check the
16476 * value of dtrace_opens, as any positive value (and
16477 * we count as 1) means we transition states.
16478 */
16479 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
16480 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
39037602
A
16481 /*
16482 * We do not need to hold the exclusive lock while processing
16483 * DOF on processes. We do need to make sure the mode does not get
16484 * changed to DTRACE_DOF_MODE_LAZY_ON during that stage though
16485 * (which should not happen anyway since it only happens in
16486 * dtrace_close). There is no way imcomplete USDT probes can be
16487 * activate by any DTrace clients here since they all have to
16488 * call dtrace_open and be blocked on dtrace_dof_mode_lock
16489 */
16490 lck_rw_lock_exclusive_to_shared(&dtrace_dof_mode_lock);
fe8ab488
A
16491 /*
16492 * Iterate all existing processes and load lazy dofs.
16493 */
16494 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
16495 dtrace_lazy_dofs_proc_iterate_doit,
16496 NULL,
16497 dtrace_lazy_dofs_proc_iterate_filter,
16498 NULL);
39037602
A
16499
16500 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16501 }
16502 else {
16503 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
fe8ab488 16504 }
2d21ac55 16505
2d21ac55 16506
fe8ab488
A
16507 /*
16508 * Update kernel symbol state.
16509 *
16510 * We must own the provider and dtrace locks.
16511 *
16512 * NOTE! It may appear there is a race by setting this value so late
16513 * after dtrace_probe_provide. However, any kext loaded after the
16514 * call to probe provide and before we set LAZY_OFF will be marked as
16515 * eligible for symbols from userspace. The same dtrace that is currently
16516 * calling dtrace_open() (this call!) will get a list of kexts needing
16517 * symbols and fill them in, thus closing the race window.
16518 *
16519 * We want to set this value only after it certain it will succeed, as
16520 * this significantly reduces the complexity of error exits.
16521 */
16522 lck_mtx_lock(&dtrace_lock);
16523 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
16524 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
2d21ac55 16525 }
fe8ab488 16526 lck_mtx_unlock(&dtrace_lock);
2d21ac55 16527
fe8ab488
A
16528 return (0);
16529}
2d21ac55 16530
fe8ab488
A
16531/*ARGSUSED*/
16532static int
16533dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16534{
16535#pragma unused(flag, otyp, cred_p) /* __APPLE__ */
16536 minor_t minor = getminor(dev);
16537 dtrace_state_t *state;
2d21ac55 16538
fe8ab488 16539 /* APPLE NOTE: Darwin puts Helper on its own major device. */
39037602 16540 state = dtrace_state_get(minor);
fe8ab488
A
16541
16542 lck_mtx_lock(&cpu_lock);
16543 lck_mtx_lock(&dtrace_lock);
2d21ac55 16544
fe8ab488 16545 if (state->dts_anon) {
2d21ac55 16546 /*
fe8ab488 16547 * There is anonymous state. Destroy that first.
2d21ac55 16548 */
fe8ab488
A
16549 ASSERT(dtrace_anon.dta_state == NULL);
16550 dtrace_state_destroy(state->dts_anon);
16551 }
2d21ac55 16552
fe8ab488
A
16553 dtrace_state_destroy(state);
16554 ASSERT(dtrace_opens > 0);
2d21ac55 16555
fe8ab488
A
16556 /*
16557 * Only relinquish control of the kernel debugger interface when there
16558 * are no consumers and no anonymous enablings.
16559 */
16560 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16561 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16562
16563 lck_mtx_unlock(&dtrace_lock);
16564 lck_mtx_unlock(&cpu_lock);
2d21ac55 16565
fe8ab488
A
16566 /*
16567 * Lock ordering requires the dof mode lock be taken before
16568 * the dtrace_lock.
16569 */
16570 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
16571 lck_mtx_lock(&dtrace_lock);
16572
16573 if (dtrace_opens == 0) {
16574 /*
16575 * If we are currently lazy-off, and this is the last close, transition to
16576 * lazy state.
16577 */
16578 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
16579 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
2d21ac55
A
16580 }
16581
fe8ab488
A
16582 /*
16583 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
16584 */
16585 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
16586 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
16587 }
2d21ac55 16588 }
fe8ab488
A
16589
16590 lck_mtx_unlock(&dtrace_lock);
16591 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
16592
16593 /*
16594 * Kext probes may be retained past the end of the kext's lifespan. The
16595 * probes are kept until the last reference to them has been removed.
16596 * Since closing an active dtrace context is likely to drop that last reference,
16597 * lets take a shot at cleaning out the orphaned probes now.
16598 */
16599 dtrace_module_unloaded(NULL);
2d21ac55 16600
fe8ab488 16601 return (0);
2d21ac55 16602}
fe8ab488 16603
2d21ac55
A
16604/*ARGSUSED*/
16605static int
b0d623f7 16606dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
2d21ac55 16607{
b0d623f7
A
16608#pragma unused(rv)
16609 /*
16610 * Safe to check this outside the dof mode lock
16611 */
16612 if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
16613 return KERN_SUCCESS;
2d21ac55
A
16614
16615 switch (cmd) {
5ba3f43e
A
16616#if defined (__arm64__)
16617 case DTRACEHIOC_ADDDOF_U32:
16618 case DTRACEHIOC_ADDDOF_U64:
16619#else
39236c6e 16620 case DTRACEHIOC_ADDDOF:
5ba3f43e 16621#endif /* __arm64__*/
39236c6e 16622 {
b0d623f7
A
16623 dof_helper_t *dhp = NULL;
16624 size_t dof_ioctl_data_size;
16625 dof_ioctl_data_t* multi_dof;
16626 unsigned int i;
16627 int rval = 0;
16628 user_addr_t user_address = *(user_addr_t*)arg;
16629 uint64_t dof_count;
16630 int multi_dof_claimed = 0;
16631 proc_t* p = current_proc();
2d21ac55 16632
5ba3f43e
A
16633 /*
16634 * If this is a restricted process and dtrace is restricted,
16635 * do not allow DOFs to be registered
16636 */
16637 if (dtrace_is_restricted() &&
16638 !dtrace_are_restrictions_relaxed() &&
16639 !dtrace_can_attach_to_proc(current_proc())) {
16640 return (EACCES);
16641 }
16642
b0d623f7
A
16643 /*
16644 * Read the number of DOF sections being passed in.
16645 */
16646 if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
16647 &dof_count,
16648 sizeof(dof_count))) {
16649 dtrace_dof_error(NULL, "failed to copyin dofiod_count");
16650 return (EFAULT);
16651 }
5ba3f43e 16652
b0d623f7
A
16653 /*
16654 * Range check the count.
16655 */
16656 if (dof_count == 0 || dof_count > 1024) {
16657 dtrace_dof_error(NULL, "dofiod_count is not valid");
16658 return (EINVAL);
16659 }
16660
16661 /*
16662 * Allocate a correctly sized structure and copyin the data.
16663 */
16664 dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
16665 if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
16666 return (ENOMEM);
16667
16668 /* NOTE! We can no longer exit this method via return */
16669 if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
16670 dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
16671 rval = EFAULT;
16672 goto cleanup;
16673 }
16674
16675 /*
16676 * Check that the count didn't change between the first copyin and the second.
16677 */
16678 if (multi_dof->dofiod_count != dof_count) {
16679 rval = EINVAL;
16680 goto cleanup;
16681 }
16682
16683 /*
16684 * Try to process lazily first.
16685 */
16686 rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
16687
16688 /*
16689 * If rval is EACCES, we must be non-lazy.
16690 */
16691 if (rval == EACCES) {
16692 rval = 0;
16693 /*
16694 * Process each dof_helper_t
16695 */
16696 i = 0;
16697 do {
16698 dhp = &multi_dof->dofiod_helpers[i];
16699
16700 dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
16701
16702 if (dof != NULL) {
16703 lck_mtx_lock(&dtrace_lock);
16704
16705 /*
16706 * dtrace_helper_slurp() takes responsibility for the dof --
16707 * it may free it now or it may save it and free it later.
16708 */
16709 if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
16710 rval = EINVAL;
16711 }
16712
16713 lck_mtx_unlock(&dtrace_lock);
16714 }
16715 } while (++i < multi_dof->dofiod_count && rval == 0);
16716 }
16717
16718 /*
16719 * We need to copyout the multi_dof struct, because it contains
16720 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
16721 *
16722 * This could certainly be better optimized.
16723 */
16724 if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
16725 dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
16726 /* Don't overwrite pre-existing error code */
16727 if (rval == 0) rval = EFAULT;
16728 }
16729
16730 cleanup:
16731 /*
16732 * If we had to allocate struct memory, free it.
16733 */
16734 if (multi_dof != NULL && !multi_dof_claimed) {
16735 kmem_free(multi_dof, dof_ioctl_data_size);
16736 }
16737
16738 return rval;
16739 }
16740
16741 case DTRACEHIOC_REMOVE: {
16742 int generation = *(int*)arg;
16743 proc_t* p = current_proc();
16744
16745 /*
16746 * Try lazy first.
16747 */
16748 int rval = dtrace_lazy_dofs_remove(p, generation);
16749
16750 /*
16751 * EACCES means non-lazy
16752 */
16753 if (rval == EACCES) {
16754 lck_mtx_lock(&dtrace_lock);
16755 rval = dtrace_helper_destroygen(p, generation);
16756 lck_mtx_unlock(&dtrace_lock);
16757 }
16758
16759 return (rval);
16760 }
16761
16762 default:
16763 break;
16764 }
16765
16766 return ENOTTY;
16767}
16768
16769/*ARGSUSED*/
16770static int
16771dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
16772{
16773#pragma unused(md)
16774 minor_t minor = getminor(dev);
16775 dtrace_state_t *state;
16776 int rval;
16777
16778 /* Darwin puts Helper on its own major device. */
16779
39037602 16780 state = dtrace_state_get(minor);
b0d623f7
A
16781
16782 if (state->dts_anon) {
16783 ASSERT(dtrace_anon.dta_state == NULL);
16784 state = state->dts_anon;
16785 }
16786
16787 switch (cmd) {
16788 case DTRACEIOC_PROVIDER: {
16789 dtrace_providerdesc_t pvd;
16790 dtrace_provider_t *pvp;
16791
16792 if (copyin(arg, &pvd, sizeof (pvd)) != 0)
16793 return (EFAULT);
16794
16795 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16796 lck_mtx_lock(&dtrace_provider_lock);
16797
16798 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16799 if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
16800 break;
16801 }
16802
16803 lck_mtx_unlock(&dtrace_provider_lock);
16804
16805 if (pvp == NULL)
16806 return (ESRCH);
16807
16808 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16809 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16810 if (copyout(&pvd, arg, sizeof (pvd)) != 0)
16811 return (EFAULT);
16812
16813 return (0);
16814 }
16815
16816 case DTRACEIOC_EPROBE: {
16817 dtrace_eprobedesc_t epdesc;
16818 dtrace_ecb_t *ecb;
16819 dtrace_action_t *act;
16820 void *buf;
16821 size_t size;
16822 uintptr_t dest;
16823 int nrecs;
16824
16825 if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
16826 return (EFAULT);
16827
16828 lck_mtx_lock(&dtrace_lock);
16829
16830 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16831 lck_mtx_unlock(&dtrace_lock);
16832 return (EINVAL);
16833 }
16834
16835 if (ecb->dte_probe == NULL) {
16836 lck_mtx_unlock(&dtrace_lock);
16837 return (EINVAL);
16838 }
16839
16840 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16841 epdesc.dtepd_uarg = ecb->dte_uarg;
16842 epdesc.dtepd_size = ecb->dte_size;
16843
16844 nrecs = epdesc.dtepd_nrecs;
16845 epdesc.dtepd_nrecs = 0;
16846 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16847 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16848 continue;
16849
16850 epdesc.dtepd_nrecs++;
16851 }
16852
16853 /*
16854 * Now that we have the size, we need to allocate a temporary
16855 * buffer in which to store the complete description. We need
16856 * the temporary buffer to be able to drop dtrace_lock()
16857 * across the copyout(), below.
16858 */
16859 size = sizeof (dtrace_eprobedesc_t) +
16860 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16861
16862 buf = kmem_alloc(size, KM_SLEEP);
16863 dest = (uintptr_t)buf;
16864
16865 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16866 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16867
16868 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16869 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16870 continue;
16871
16872 if (nrecs-- == 0)
16873 break;
16874
16875 bcopy(&act->dta_rec, (void *)dest,
16876 sizeof (dtrace_recdesc_t));
16877 dest += sizeof (dtrace_recdesc_t);
16878 }
16879
16880 lck_mtx_unlock(&dtrace_lock);
16881
16882 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16883 kmem_free(buf, size);
16884 return (EFAULT);
16885 }
16886
16887 kmem_free(buf, size);
16888 return (0);
16889 }
16890
16891 case DTRACEIOC_AGGDESC: {
16892 dtrace_aggdesc_t aggdesc;
16893 dtrace_action_t *act;
16894 dtrace_aggregation_t *agg;
16895 int nrecs;
16896 uint32_t offs;
16897 dtrace_recdesc_t *lrec;
16898 void *buf;
16899 size_t size;
16900 uintptr_t dest;
16901
16902 if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
16903 return (EFAULT);
16904
16905 lck_mtx_lock(&dtrace_lock);
16906
16907 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16908 lck_mtx_unlock(&dtrace_lock);
16909 return (EINVAL);
16910 }
16911
16912 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16913
16914 nrecs = aggdesc.dtagd_nrecs;
16915 aggdesc.dtagd_nrecs = 0;
16916
16917 offs = agg->dtag_base;
16918 lrec = &agg->dtag_action.dta_rec;
16919 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16920
16921 for (act = agg->dtag_first; ; act = act->dta_next) {
16922 ASSERT(act->dta_intuple ||
16923 DTRACEACT_ISAGG(act->dta_kind));
16924
16925 /*
16926 * If this action has a record size of zero, it
16927 * denotes an argument to the aggregating action.
16928 * Because the presence of this record doesn't (or
16929 * shouldn't) affect the way the data is interpreted,
16930 * we don't copy it out to save user-level the
16931 * confusion of dealing with a zero-length record.
16932 */
16933 if (act->dta_rec.dtrd_size == 0) {
16934 ASSERT(agg->dtag_hasarg);
16935 continue;
16936 }
16937
16938 aggdesc.dtagd_nrecs++;
16939
16940 if (act == &agg->dtag_action)
16941 break;
16942 }
16943
16944 /*
16945 * Now that we have the size, we need to allocate a temporary
16946 * buffer in which to store the complete description. We need
16947 * the temporary buffer to be able to drop dtrace_lock()
16948 * across the copyout(), below.
16949 */
16950 size = sizeof (dtrace_aggdesc_t) +
16951 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16952
16953 buf = kmem_alloc(size, KM_SLEEP);
16954 dest = (uintptr_t)buf;
16955
16956 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16957 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16958
16959 for (act = agg->dtag_first; ; act = act->dta_next) {
16960 dtrace_recdesc_t rec = act->dta_rec;
16961
16962 /*
16963 * See the comment in the above loop for why we pass
16964 * over zero-length records.
16965 */
16966 if (rec.dtrd_size == 0) {
16967 ASSERT(agg->dtag_hasarg);
16968 continue;
16969 }
16970
16971 if (nrecs-- == 0)
16972 break;
16973
16974 rec.dtrd_offset -= offs;
16975 bcopy(&rec, (void *)dest, sizeof (rec));
16976 dest += sizeof (dtrace_recdesc_t);
16977
16978 if (act == &agg->dtag_action)
16979 break;
16980 }
16981
16982 lck_mtx_unlock(&dtrace_lock);
16983
16984 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16985 kmem_free(buf, size);
16986 return (EFAULT);
16987 }
16988
16989 kmem_free(buf, size);
16990 return (0);
16991 }
16992
16993 case DTRACEIOC_ENABLE: {
16994 dof_hdr_t *dof;
16995 dtrace_enabling_t *enab = NULL;
16996 dtrace_vstate_t *vstate;
16997 int err = 0;
16998
16999 *rv = 0;
17000
17001 /*
17002 * If a NULL argument has been passed, we take this as our
17003 * cue to reevaluate our enablings.
17004 */
fe8ab488 17005 if (arg == 0) {
b0d623f7
A
17006 dtrace_enabling_matchall();
17007
17008 return (0);
17009 }
17010
17011 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17012 return (rval);
17013
17014 lck_mtx_lock(&cpu_lock);
17015 lck_mtx_lock(&dtrace_lock);
17016 vstate = &state->dts_vstate;
17017
17018 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17019 lck_mtx_unlock(&dtrace_lock);
17020 lck_mtx_unlock(&cpu_lock);
17021 dtrace_dof_destroy(dof);
17022 return (EBUSY);
17023 }
17024
17025 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17026 lck_mtx_unlock(&dtrace_lock);
17027 lck_mtx_unlock(&cpu_lock);
17028 dtrace_dof_destroy(dof);
17029 return (EINVAL);
17030 }
17031
17032 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17033 dtrace_enabling_destroy(enab);
17034 lck_mtx_unlock(&dtrace_lock);
17035 lck_mtx_unlock(&cpu_lock);
17036 dtrace_dof_destroy(dof);
17037 return (rval);
17038 }
17039
39037602 17040 if ((err = dtrace_enabling_match(enab, rv, NULL)) == 0) {
b0d623f7
A
17041 err = dtrace_enabling_retain(enab);
17042 } else {
17043 dtrace_enabling_destroy(enab);
17044 }
17045
b0d623f7 17046 lck_mtx_unlock(&dtrace_lock);
fe8ab488 17047 lck_mtx_unlock(&cpu_lock);
b0d623f7
A
17048 dtrace_dof_destroy(dof);
17049
17050 return (err);
17051 }
17052
17053 case DTRACEIOC_REPLICATE: {
17054 dtrace_repldesc_t desc;
17055 dtrace_probedesc_t *match = &desc.dtrpd_match;
17056 dtrace_probedesc_t *create = &desc.dtrpd_create;
17057 int err;
17058
17059 if (copyin(arg, &desc, sizeof (desc)) != 0)
17060 return (EFAULT);
17061
17062 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17063 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17064 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17065 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17066
17067 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17068 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17069 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17070 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17071
17072 lck_mtx_lock(&dtrace_lock);
17073 err = dtrace_enabling_replicate(state, match, create);
17074 lck_mtx_unlock(&dtrace_lock);
17075
17076 return (err);
17077 }
17078
17079 case DTRACEIOC_PROBEMATCH:
17080 case DTRACEIOC_PROBES: {
17081 dtrace_probe_t *probe = NULL;
17082 dtrace_probedesc_t desc;
17083 dtrace_probekey_t pkey;
17084 dtrace_id_t i;
17085 int m = 0;
17086 uint32_t priv;
17087 uid_t uid;
17088 zoneid_t zoneid;
17089
17090 if (copyin(arg, &desc, sizeof (desc)) != 0)
17091 return (EFAULT);
17092
17093 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17094 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17095 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17096 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17097
17098 /*
17099 * Before we attempt to match this probe, we want to give
17100 * all providers the opportunity to provide it.
17101 */
17102 if (desc.dtpd_id == DTRACE_IDNONE) {
17103 lck_mtx_lock(&dtrace_provider_lock);
17104 dtrace_probe_provide(&desc, NULL);
17105 lck_mtx_unlock(&dtrace_provider_lock);
17106 desc.dtpd_id++;
17107 }
17108
17109 if (cmd == DTRACEIOC_PROBEMATCH) {
17110 dtrace_probekey(&desc, &pkey);
17111 pkey.dtpk_id = DTRACE_IDNONE;
17112 }
17113
17114 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17115
17116 lck_mtx_lock(&dtrace_lock);
17117
17118 if (cmd == DTRACEIOC_PROBEMATCH) {
17119 /* Quiet compiler warning */
17120 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
17121 if ((probe = dtrace_probes[i - 1]) != NULL &&
17122 (m = dtrace_match_probe(probe, &pkey,
17123 priv, uid, zoneid)) != 0)
17124 break;
17125 }
17126
17127 if (m < 0) {
17128 lck_mtx_unlock(&dtrace_lock);
17129 return (EINVAL);
17130 }
17131
17132 } else {
17133 /* Quiet compiler warning */
17134 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
17135 if ((probe = dtrace_probes[i - 1]) != NULL &&
17136 dtrace_match_priv(probe, priv, uid, zoneid))
17137 break;
17138 }
17139 }
17140
17141 if (probe == NULL) {
17142 lck_mtx_unlock(&dtrace_lock);
17143 return (ESRCH);
17144 }
17145
17146 dtrace_probe_description(probe, &desc);
17147 lck_mtx_unlock(&dtrace_lock);
17148
17149 if (copyout(&desc, arg, sizeof (desc)) != 0)
17150 return (EFAULT);
17151
17152 return (0);
17153 }
17154
17155 case DTRACEIOC_PROBEARG: {
17156 dtrace_argdesc_t desc;
17157 dtrace_probe_t *probe;
17158 dtrace_provider_t *prov;
17159
17160 if (copyin(arg, &desc, sizeof (desc)) != 0)
17161 return (EFAULT);
17162
17163 if (desc.dtargd_id == DTRACE_IDNONE)
17164 return (EINVAL);
17165
17166 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17167 return (EINVAL);
17168
17169 lck_mtx_lock(&dtrace_provider_lock);
17170 lck_mtx_lock(&mod_lock);
17171 lck_mtx_lock(&dtrace_lock);
17172
17173 /* Quiet compiler warning */
17174 if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
17175 lck_mtx_unlock(&dtrace_lock);
17176 lck_mtx_unlock(&mod_lock);
17177 lck_mtx_unlock(&dtrace_provider_lock);
17178 return (EINVAL);
17179 }
17180
17181 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17182 lck_mtx_unlock(&dtrace_lock);
17183 lck_mtx_unlock(&mod_lock);
17184 lck_mtx_unlock(&dtrace_provider_lock);
17185 return (EINVAL);
17186 }
17187
17188 lck_mtx_unlock(&dtrace_lock);
17189
17190 prov = probe->dtpr_provider;
17191
17192 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17193 /*
17194 * There isn't any typed information for this probe.
17195 * Set the argument number to DTRACE_ARGNONE.
17196 */
17197 desc.dtargd_ndx = DTRACE_ARGNONE;
17198 } else {
17199 desc.dtargd_native[0] = '\0';
17200 desc.dtargd_xlate[0] = '\0';
17201 desc.dtargd_mapping = desc.dtargd_ndx;
17202
17203 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17204 probe->dtpr_id, probe->dtpr_arg, &desc);
17205 }
17206
17207 lck_mtx_unlock(&mod_lock);
17208 lck_mtx_unlock(&dtrace_provider_lock);
17209
17210 if (copyout(&desc, arg, sizeof (desc)) != 0)
17211 return (EFAULT);
17212
17213 return (0);
17214 }
17215
17216 case DTRACEIOC_GO: {
17217 processorid_t cpuid;
17218 rval = dtrace_state_go(state, &cpuid);
17219
17220 if (rval != 0)
17221 return (rval);
17222
17223 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
17224 return (EFAULT);
17225
17226 return (0);
17227 }
17228
17229 case DTRACEIOC_STOP: {
17230 processorid_t cpuid;
17231
17232 lck_mtx_lock(&dtrace_lock);
17233 rval = dtrace_state_stop(state, &cpuid);
17234 lck_mtx_unlock(&dtrace_lock);
17235
17236 if (rval != 0)
17237 return (rval);
17238
17239 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
17240 return (EFAULT);
17241
17242 return (0);
17243 }
17244
17245 case DTRACEIOC_DOFGET: {
17246 dof_hdr_t hdr, *dof;
17247 uint64_t len;
17248
17249 if (copyin(arg, &hdr, sizeof (hdr)) != 0)
17250 return (EFAULT);
17251
17252 lck_mtx_lock(&dtrace_lock);
17253 dof = dtrace_dof_create(state);
17254 lck_mtx_unlock(&dtrace_lock);
17255
17256 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17257 rval = copyout(dof, arg, len);
17258 dtrace_dof_destroy(dof);
17259
17260 return (rval == 0 ? 0 : EFAULT);
17261 }
17262
39037602
A
17263 case DTRACEIOC_SLEEP: {
17264 int64_t time;
17265 uint64_t abstime;
17266 uint64_t rvalue = DTRACE_WAKE_TIMEOUT;
17267
17268 if (copyin(arg, &time, sizeof(time)) != 0)
17269 return (EFAULT);
17270
17271 nanoseconds_to_absolutetime((uint64_t)time, &abstime);
17272 clock_absolutetime_interval_to_deadline(abstime, &abstime);
17273
17274 if (assert_wait_deadline(state, THREAD_ABORTSAFE, abstime) == THREAD_WAITING) {
17275 if (state->dts_buf_over_limit > 0) {
17276 clear_wait(current_thread(), THREAD_INTERRUPTED);
17277 rvalue = DTRACE_WAKE_BUF_LIMIT;
17278 } else {
17279 thread_block(THREAD_CONTINUE_NULL);
17280 if (state->dts_buf_over_limit > 0) {
17281 rvalue = DTRACE_WAKE_BUF_LIMIT;
17282 }
17283 }
17284 }
17285
17286 if (copyout(&rvalue, arg, sizeof(rvalue)) != 0)
17287 return (EFAULT);
17288
17289 return (0);
17290 }
17291
17292 case DTRACEIOC_SIGNAL: {
17293 wakeup(state);
17294 return (0);
17295 }
17296
b0d623f7
A
17297 case DTRACEIOC_AGGSNAP:
17298 case DTRACEIOC_BUFSNAP: {
17299 dtrace_bufdesc_t desc;
17300 caddr_t cached;
39037602 17301 boolean_t over_limit;
b0d623f7
A
17302 dtrace_buffer_t *buf;
17303
17304 if (copyin(arg, &desc, sizeof (desc)) != 0)
17305 return (EFAULT);
17306
17307 if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17308 return (EINVAL);
17309
17310 lck_mtx_lock(&dtrace_lock);
17311
17312 if (cmd == DTRACEIOC_BUFSNAP) {
17313 buf = &state->dts_buffer[desc.dtbd_cpu];
17314 } else {
17315 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17316 }
17317
17318 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17319 size_t sz = buf->dtb_offset;
17320
17321 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17322 lck_mtx_unlock(&dtrace_lock);
17323 return (EBUSY);
17324 }
17325
17326 /*
17327 * If this buffer has already been consumed, we're
17328 * going to indicate that there's nothing left here
17329 * to consume.
17330 */
17331 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17332 lck_mtx_unlock(&dtrace_lock);
17333
17334 desc.dtbd_size = 0;
17335 desc.dtbd_drops = 0;
17336 desc.dtbd_errors = 0;
17337 desc.dtbd_oldest = 0;
17338 sz = sizeof (desc);
17339
17340 if (copyout(&desc, arg, sz) != 0)
17341 return (EFAULT);
17342
17343 return (0);
17344 }
17345
17346 /*
17347 * If this is a ring buffer that has wrapped, we want
17348 * to copy the whole thing out.
17349 */
17350 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17351 dtrace_buffer_polish(buf);
17352 sz = buf->dtb_size;
17353 }
17354
17355 if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
17356 lck_mtx_unlock(&dtrace_lock);
17357 return (EFAULT);
17358 }
17359
17360 desc.dtbd_size = sz;
17361 desc.dtbd_drops = buf->dtb_drops;
17362 desc.dtbd_errors = buf->dtb_errors;
17363 desc.dtbd_oldest = buf->dtb_xamot_offset;
04b8595b 17364 desc.dtbd_timestamp = dtrace_gethrtime();
b0d623f7
A
17365
17366 lck_mtx_unlock(&dtrace_lock);
17367
17368 if (copyout(&desc, arg, sizeof (desc)) != 0)
17369 return (EFAULT);
17370
17371 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17372
17373 return (0);
17374 }
17375
17376 if (buf->dtb_tomax == NULL) {
17377 ASSERT(buf->dtb_xamot == NULL);
17378 lck_mtx_unlock(&dtrace_lock);
17379 return (ENOENT);
17380 }
17381
17382 cached = buf->dtb_tomax;
39037602
A
17383 over_limit = buf->dtb_cur_limit == buf->dtb_size;
17384
b0d623f7
A
17385 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17386
17387 dtrace_xcall(desc.dtbd_cpu,
17388 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17389
17390 state->dts_errors += buf->dtb_xamot_errors;
17391
17392 /*
17393 * If the buffers did not actually switch, then the cross call
17394 * did not take place -- presumably because the given CPU is
17395 * not in the ready set. If this is the case, we'll return
17396 * ENOENT.
17397 */
17398 if (buf->dtb_tomax == cached) {
17399 ASSERT(buf->dtb_xamot != cached);
17400 lck_mtx_unlock(&dtrace_lock);
17401 return (ENOENT);
17402 }
17403
17404 ASSERT(cached == buf->dtb_xamot);
39037602
A
17405 /*
17406 * At this point we know the buffer have switched, so we
17407 * can decrement the over limit count if the buffer was over
17408 * its limit. The new buffer might already be over its limit
17409 * yet, but we don't care since we're guaranteed not to be
17410 * checking the buffer over limit count at this point.
17411 */
17412 if (over_limit) {
17413 uint32_t old = atomic_add_32(&state->dts_buf_over_limit, -1);
17414 #pragma unused(old)
17415
17416 /*
17417 * Verify that we didn't underflow the value
17418 */
17419 ASSERT(old != 0);
17420 }
b0d623f7
A
17421
17422 /*
17423 * We have our snapshot; now copy it out.
17424 */
5ba3f43e
A
17425 if (dtrace_buffer_copyout(buf->dtb_xamot,
17426 (user_addr_t)desc.dtbd_data,
b0d623f7
A
17427 buf->dtb_xamot_offset) != 0) {
17428 lck_mtx_unlock(&dtrace_lock);
17429 return (EFAULT);
17430 }
17431
17432 desc.dtbd_size = buf->dtb_xamot_offset;
17433 desc.dtbd_drops = buf->dtb_xamot_drops;
17434 desc.dtbd_errors = buf->dtb_xamot_errors;
17435 desc.dtbd_oldest = 0;
04b8595b 17436 desc.dtbd_timestamp = buf->dtb_switched;
b0d623f7
A
17437
17438 lck_mtx_unlock(&dtrace_lock);
17439
17440 /*
17441 * Finally, copy out the buffer description.
17442 */
17443 if (copyout(&desc, arg, sizeof (desc)) != 0)
17444 return (EFAULT);
17445
17446 return (0);
17447 }
17448
17449 case DTRACEIOC_CONF: {
17450 dtrace_conf_t conf;
17451
17452 bzero(&conf, sizeof (conf));
17453 conf.dtc_difversion = DIF_VERSION;
17454 conf.dtc_difintregs = DIF_DIR_NREGS;
17455 conf.dtc_diftupregs = DIF_DTR_NREGS;
17456 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17457
17458 if (copyout(&conf, arg, sizeof (conf)) != 0)
17459 return (EFAULT);
17460
17461 return (0);
17462 }
17463
17464 case DTRACEIOC_STATUS: {
17465 dtrace_status_t stat;
17466 dtrace_dstate_t *dstate;
17467 int i, j;
17468 uint64_t nerrs;
17469
17470 /*
17471 * See the comment in dtrace_state_deadman() for the reason
17472 * for setting dts_laststatus to INT64_MAX before setting
17473 * it to the correct value.
17474 */
17475 state->dts_laststatus = INT64_MAX;
17476 dtrace_membar_producer();
17477 state->dts_laststatus = dtrace_gethrtime();
17478
17479 bzero(&stat, sizeof (stat));
17480
17481 lck_mtx_lock(&dtrace_lock);
17482
17483 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17484 lck_mtx_unlock(&dtrace_lock);
17485 return (ENOENT);
17486 }
17487
17488 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17489 stat.dtst_exiting = 1;
17490
17491 nerrs = state->dts_errors;
17492 dstate = &state->dts_vstate.dtvs_dynvars;
17493
17494 for (i = 0; i < (int)NCPU; i++) {
17495 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17496
17497 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17498 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17499 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17500
17501 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17502 stat.dtst_filled++;
17503
17504 nerrs += state->dts_buffer[i].dtb_errors;
17505
17506 for (j = 0; j < state->dts_nspeculations; j++) {
17507 dtrace_speculation_t *spec;
17508 dtrace_buffer_t *buf;
17509
17510 spec = &state->dts_speculations[j];
17511 buf = &spec->dtsp_buffer[i];
17512 stat.dtst_specdrops += buf->dtb_xamot_drops;
17513 }
17514 }
17515
17516 stat.dtst_specdrops_busy = state->dts_speculations_busy;
17517 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17518 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17519 stat.dtst_dblerrors = state->dts_dblerrors;
17520 stat.dtst_killed =
17521 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17522 stat.dtst_errors = nerrs;
17523
17524 lck_mtx_unlock(&dtrace_lock);
17525
17526 if (copyout(&stat, arg, sizeof (stat)) != 0)
17527 return (EFAULT);
17528
17529 return (0);
17530 }
17531
17532 case DTRACEIOC_FORMAT: {
17533 dtrace_fmtdesc_t fmt;
17534 char *str;
17535 int len;
17536
17537 if (copyin(arg, &fmt, sizeof (fmt)) != 0)
17538 return (EFAULT);
17539
17540 lck_mtx_lock(&dtrace_lock);
17541
17542 if (fmt.dtfd_format == 0 ||
17543 fmt.dtfd_format > state->dts_nformats) {
17544 lck_mtx_unlock(&dtrace_lock);
17545 return (EINVAL);
17546 }
17547
17548 /*
17549 * Format strings are allocated contiguously and they are
17550 * never freed; if a format index is less than the number
17551 * of formats, we can assert that the format map is non-NULL
17552 * and that the format for the specified index is non-NULL.
17553 */
17554 ASSERT(state->dts_formats != NULL);
17555 str = state->dts_formats[fmt.dtfd_format - 1];
17556 ASSERT(str != NULL);
17557
17558 len = strlen(str) + 1;
17559
17560 if (len > fmt.dtfd_length) {
17561 fmt.dtfd_length = len;
17562
17563 if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
17564 lck_mtx_unlock(&dtrace_lock);
17565 return (EINVAL);
17566 }
17567 } else {
17568 if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
17569 lck_mtx_unlock(&dtrace_lock);
17570 return (EINVAL);
17571 }
17572 }
17573
17574 lck_mtx_unlock(&dtrace_lock);
17575 return (0);
17576 }
17577
6d2010ae
A
17578 case DTRACEIOC_MODUUIDSLIST: {
17579 size_t module_uuids_list_size;
17580 dtrace_module_uuids_list_t* uuids_list;
17581 uint64_t dtmul_count;
fe8ab488
A
17582
17583 /*
17584 * Security restrictions make this operation illegal, if this is enabled DTrace
17585 * must refuse to provide any fbt probes.
17586 */
3e170ce0 17587 if (dtrace_fbt_probes_restricted()) {
fe8ab488
A
17588 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17589 return (EPERM);
17590 }
17591
6d2010ae
A
17592 /*
17593 * Fail if the kernel symbol mode makes this operation illegal.
17594 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17595 * for them without holding the dtrace_lock.
17596 */
17597 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17598 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17599 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
17600 return (EPERM);
17601 }
17602
17603 /*
17604 * Read the number of symbolsdesc structs being passed in.
17605 */
17606 if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
17607 &dtmul_count,
17608 sizeof(dtmul_count))) {
17609 cmn_err(CE_WARN, "failed to copyin dtmul_count");
17610 return (EFAULT);
17611 }
17612
17613 /*
17614 * Range check the count. More than 2k kexts is probably an error.
17615 */
17616 if (dtmul_count > 2048) {
17617 cmn_err(CE_WARN, "dtmul_count is not valid");
17618 return (EINVAL);
17619 }
17620
17621 /*
17622 * For all queries, we return EINVAL when the user specified
17623 * count does not match the actual number of modules we find
17624 * available.
17625 *
17626 * If the user specified count is zero, then this serves as a
17627 * simple query to count the available modules in need of symbols.
17628 */
17629
17630 rval = 0;
17631
17632 if (dtmul_count == 0)
17633 {
17634 lck_mtx_lock(&mod_lock);
17635 struct modctl* ctl = dtrace_modctl_list;
17636 while (ctl) {
fe8ab488
A
17637 /* Update the private probes bit */
17638 if (dtrace_provide_private_probes)
17639 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17640
6d2010ae
A
17641 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17642 if (!MOD_SYMBOLS_DONE(ctl)) {
17643 dtmul_count++;
17644 rval = EINVAL;
17645 }
17646 ctl = ctl->mod_next;
17647 }
17648 lck_mtx_unlock(&mod_lock);
17649
17650 if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
17651 return (EFAULT);
17652 else
17653 return (rval);
17654 }
17655
17656 /*
17657 * If we reach this point, then we have a request for full list data.
17658 * Allocate a correctly sized structure and copyin the data.
17659 */
17660 module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
17661 if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
17662 return (ENOMEM);
17663
17664 /* NOTE! We can no longer exit this method via return */
17665 if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
17666 cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
17667 rval = EFAULT;
17668 goto moduuidslist_cleanup;
17669 }
17670
17671 /*
17672 * Check that the count didn't change between the first copyin and the second.
17673 */
17674 if (uuids_list->dtmul_count != dtmul_count) {
17675 rval = EINVAL;
17676 goto moduuidslist_cleanup;
17677 }
17678
17679 /*
17680 * Build the list of UUID's that need symbols
17681 */
17682 lck_mtx_lock(&mod_lock);
17683
17684 dtmul_count = 0;
17685
17686 struct modctl* ctl = dtrace_modctl_list;
17687 while (ctl) {
fe8ab488
A
17688 /* Update the private probes bit */
17689 if (dtrace_provide_private_probes)
17690 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17691
6d2010ae
A
17692 /*
17693 * We assume that userspace symbols will be "better" than kernel level symbols,
17694 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
17695 * are available, add user syms if the module might use them.
17696 */
17697 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17698 if (!MOD_SYMBOLS_DONE(ctl)) {
17699 UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
17700 if (dtmul_count++ < uuids_list->dtmul_count) {
17701 memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
17702 }
17703 }
17704 ctl = ctl->mod_next;
17705 }
17706
17707 lck_mtx_unlock(&mod_lock);
17708
17709 if (uuids_list->dtmul_count < dtmul_count)
17710 rval = EINVAL;
17711
17712 uuids_list->dtmul_count = dtmul_count;
17713
17714 /*
17715 * Copyout the symbols list (or at least the count!)
17716 */
17717 if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
17718 cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
17719 rval = EFAULT;
17720 }
17721
17722 moduuidslist_cleanup:
17723 /*
17724 * If we had to allocate struct memory, free it.
17725 */
17726 if (uuids_list != NULL) {
17727 kmem_free(uuids_list, module_uuids_list_size);
17728 }
17729
17730 return rval;
17731 }
17732
17733 case DTRACEIOC_PROVMODSYMS: {
17734 size_t module_symbols_size;
17735 dtrace_module_symbols_t* module_symbols;
17736 uint64_t dtmodsyms_count;
fe8ab488
A
17737
17738 /*
17739 * Security restrictions make this operation illegal, if this is enabled DTrace
17740 * must refuse to provide any fbt probes.
17741 */
3e170ce0 17742 if (dtrace_fbt_probes_restricted()) {
fe8ab488
A
17743 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17744 return (EPERM);
17745 }
17746
6d2010ae
A
17747 /*
17748 * Fail if the kernel symbol mode makes this operation illegal.
17749 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17750 * for them without holding the dtrace_lock.
17751 */
17752 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17753 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17754 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
17755 return (EPERM);
17756 }
17757
17758 /*
17759 * Read the number of module symbols structs being passed in.
17760 */
17761 if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
17762 &dtmodsyms_count,
17763 sizeof(dtmodsyms_count))) {
17764 cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
17765 return (EFAULT);
17766 }
17767
17768 /*
17769 * Range check the count. How much data can we pass around?
17770 * FIX ME!
17771 */
17772 if (dtmodsyms_count == 0 || (dtmodsyms_count > 100 * 1024)) {
17773 cmn_err(CE_WARN, "dtmodsyms_count is not valid");
17774 return (EINVAL);
17775 }
17776
17777 /*
17778 * Allocate a correctly sized structure and copyin the data.
17779 */
17780 module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
17781 if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
17782 return (ENOMEM);
17783
17784 rval = 0;
17785
17786 /* NOTE! We can no longer exit this method via return */
17787 if (copyin(arg, module_symbols, module_symbols_size) != 0) {
39037602 17788 cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t");
6d2010ae
A
17789 rval = EFAULT;
17790 goto module_symbols_cleanup;
17791 }
17792
17793 /*
17794 * Check that the count didn't change between the first copyin and the second.
17795 */
17796 if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
17797 rval = EINVAL;
17798 goto module_symbols_cleanup;
17799 }
17800
17801 /*
17802 * Find the modctl to add symbols to.
17803 */
17804 lck_mtx_lock(&dtrace_provider_lock);
17805 lck_mtx_lock(&mod_lock);
17806
17807 struct modctl* ctl = dtrace_modctl_list;
17808 while (ctl) {
fe8ab488
A
17809 /* Update the private probes bit */
17810 if (dtrace_provide_private_probes)
17811 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17812
6d2010ae
A
17813 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17814 if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl)) {
17815 if (memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
17816 /* BINGO! */
17817 ctl->mod_user_symbols = module_symbols;
17818 break;
17819 }
17820 }
17821 ctl = ctl->mod_next;
17822 }
17823
17824 if (ctl) {
17825 dtrace_provider_t *prv;
17826
17827 /*
17828 * We're going to call each providers per-module provide operation
17829 * specifying only this module.
17830 */
17831 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
17832 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
17833
17834 /*
17835 * We gave every provider a chance to provide with the user syms, go ahead and clear them
17836 */
17837 ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
17838 }
17839
17840 lck_mtx_unlock(&mod_lock);
17841 lck_mtx_unlock(&dtrace_provider_lock);
17842
17843 module_symbols_cleanup:
17844 /*
17845 * If we had to allocate struct memory, free it.
17846 */
17847 if (module_symbols != NULL) {
17848 kmem_free(module_symbols, module_symbols_size);
17849 }
17850
17851 return rval;
17852 }
fe8ab488
A
17853
17854 case DTRACEIOC_PROCWAITFOR: {
17855 dtrace_procdesc_t pdesc = {
3e170ce0 17856 .p_name = {0},
fe8ab488
A
17857 .p_pid = -1
17858 };
17859
17860 if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
17861 goto proc_waitfor_error;
17862
17863 if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
17864 goto proc_waitfor_error;
17865
17866 if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
17867 goto proc_waitfor_error;
17868
17869 return 0;
17870
17871 proc_waitfor_error:
17872 /* The process was suspended, revert this since the client will not do it. */
17873 if (pdesc.p_pid != -1) {
17874 proc_t *proc = proc_find(pdesc.p_pid);
17875 if (proc != PROC_NULL) {
17876 task_pidresume(proc->task);
17877 proc_rele(proc);
17878 }
17879 }
17880
17881 return rval;
17882 }
17883
17884 default:
17885 break;
b0d623f7
A
17886 }
17887
17888 return (ENOTTY);
17889}
b0d623f7 17890
fe8ab488
A
17891/*
17892 * APPLE NOTE: dtrace_detach not implemented
17893 */
b0d623f7
A
17894#if !defined(__APPLE__)
17895/*ARGSUSED*/
17896static int
17897dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17898{
17899 dtrace_state_t *state;
17900
17901 switch (cmd) {
17902 case DDI_DETACH:
17903 break;
17904
17905 case DDI_SUSPEND:
17906 return (DDI_SUCCESS);
17907
17908 default:
17909 return (DDI_FAILURE);
17910 }
17911
17912 lck_mtx_lock(&cpu_lock);
17913 lck_mtx_lock(&dtrace_provider_lock);
17914 lck_mtx_lock(&dtrace_lock);
2d21ac55
A
17915
17916 ASSERT(dtrace_opens == 0);
17917
17918 if (dtrace_helpers > 0) {
2d21ac55 17919 lck_mtx_unlock(&dtrace_lock);
fe8ab488 17920 lck_mtx_unlock(&dtrace_provider_lock);
2d21ac55
A
17921 lck_mtx_unlock(&cpu_lock);
17922 return (DDI_FAILURE);
17923 }
17924
17925 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
2d21ac55 17926 lck_mtx_unlock(&dtrace_lock);
fe8ab488 17927 lck_mtx_unlock(&dtrace_provider_lock);
2d21ac55
A
17928 lck_mtx_unlock(&cpu_lock);
17929 return (DDI_FAILURE);
17930 }
17931
17932 dtrace_provider = NULL;
17933
17934 if ((state = dtrace_anon_grab()) != NULL) {
17935 /*
17936 * If there were ECBs on this state, the provider should
17937 * have not been allowed to detach; assert that there is
17938 * none.
17939 */
17940 ASSERT(state->dts_necbs == 0);
17941 dtrace_state_destroy(state);
17942
17943 /*
17944 * If we're being detached with anonymous state, we need to
17945 * indicate to the kernel debugger that DTrace is now inactive.
17946 */
17947 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17948 }
17949
17950 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17951 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17952 dtrace_cpu_init = NULL;
17953 dtrace_helpers_cleanup = NULL;
17954 dtrace_helpers_fork = NULL;
17955 dtrace_cpustart_init = NULL;
17956 dtrace_cpustart_fini = NULL;
17957 dtrace_debugger_init = NULL;
17958 dtrace_debugger_fini = NULL;
17959 dtrace_kreloc_init = NULL;
17960 dtrace_kreloc_fini = NULL;
17961 dtrace_modload = NULL;
17962 dtrace_modunload = NULL;
17963
17964 lck_mtx_unlock(&cpu_lock);
17965
17966 if (dtrace_helptrace_enabled) {
17967 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17968 dtrace_helptrace_buffer = NULL;
17969 }
17970
17971 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17972 dtrace_probes = NULL;
17973 dtrace_nprobes = 0;
17974
17975 dtrace_hash_destroy(dtrace_bymod);
17976 dtrace_hash_destroy(dtrace_byfunc);
17977 dtrace_hash_destroy(dtrace_byname);
17978 dtrace_bymod = NULL;
17979 dtrace_byfunc = NULL;
17980 dtrace_byname = NULL;
17981
17982 kmem_cache_destroy(dtrace_state_cache);
2d21ac55
A
17983 vmem_destroy(dtrace_arena);
17984
17985 if (dtrace_toxrange != NULL) {
17986 kmem_free(dtrace_toxrange,
17987 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17988 dtrace_toxrange = NULL;
17989 dtrace_toxranges = 0;
17990 dtrace_toxranges_max = 0;
17991 }
17992
17993 ddi_remove_minor_node(dtrace_devi, NULL);
17994 dtrace_devi = NULL;
17995
17996 ddi_soft_state_fini(&dtrace_softstate);
17997
17998 ASSERT(dtrace_vtime_references == 0);
17999 ASSERT(dtrace_opens == 0);
18000 ASSERT(dtrace_retained == NULL);
18001
18002 lck_mtx_unlock(&dtrace_lock);
18003 lck_mtx_unlock(&dtrace_provider_lock);
18004
18005 /*
18006 * We don't destroy the task queue until after we have dropped our
18007 * locks (taskq_destroy() may block on running tasks). To prevent
18008 * attempting to do work after we have effectively detached but before
18009 * the task queue has been destroyed, all tasks dispatched via the
18010 * task queue must check that DTrace is still attached before
18011 * performing any operation.
18012 */
18013 taskq_destroy(dtrace_taskq);
18014 dtrace_taskq = NULL;
18015
18016 return (DDI_SUCCESS);
18017}
fe8ab488 18018#endif /* __APPLE__ */
2d21ac55
A
18019
18020d_open_t _dtrace_open, helper_open;
18021d_close_t _dtrace_close, helper_close;
18022d_ioctl_t _dtrace_ioctl, helper_ioctl;
18023
18024int
18025_dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
18026{
18027#pragma unused(p)
18028 dev_t locdev = dev;
18029
18030 return dtrace_open( &locdev, flags, devtype, CRED());
18031}
18032
18033int
18034helper_open(dev_t dev, int flags, int devtype, struct proc *p)
18035{
18036#pragma unused(dev,flags,devtype,p)
18037 return 0;
18038}
18039
18040int
18041_dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
18042{
18043#pragma unused(p)
18044 return dtrace_close( dev, flags, devtype, CRED());
18045}
18046
18047int
18048helper_close(dev_t dev, int flags, int devtype, struct proc *p)
18049{
18050#pragma unused(dev,flags,devtype,p)
18051 return 0;
18052}
18053
18054int
18055_dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
18056{
18057#pragma unused(p)
18058 int err, rv = 0;
b0d623f7
A
18059 user_addr_t uaddrp;
18060
18061 if (proc_is64bit(p))
18062 uaddrp = *(user_addr_t *)data;
18063 else
18064 uaddrp = (user_addr_t) *(uint32_t *)data;
2d21ac55 18065
b0d623f7 18066 err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
2d21ac55 18067
b0d623f7 18068 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
2d21ac55
A
18069 if (err != 0) {
18070 ASSERT( (err & 0xfffff000) == 0 );
b0d623f7 18071 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
2d21ac55
A
18072 } else if (rv != 0) {
18073 ASSERT( (rv & 0xfff00000) == 0 );
b0d623f7 18074 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
2d21ac55
A
18075 } else
18076 return 0;
18077}
18078
18079int
18080helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
18081{
18082#pragma unused(dev,fflag,p)
18083 int err, rv = 0;
18084
b0d623f7
A
18085 err = dtrace_ioctl_helper(cmd, data, &rv);
18086 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
2d21ac55
A
18087 if (err != 0) {
18088 ASSERT( (err & 0xfffff000) == 0 );
b0d623f7 18089 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
2d21ac55
A
18090 } else if (rv != 0) {
18091 ASSERT( (rv & 0xfff00000) == 0 );
b0d623f7 18092 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
2d21ac55
A
18093 } else
18094 return 0;
18095}
18096
18097#define HELPER_MAJOR -24 /* let the kernel pick the device number */
18098
18099/*
18100 * A struct describing which functions will get invoked for certain
18101 * actions.
18102 */
18103static struct cdevsw helper_cdevsw =
18104{
18105 helper_open, /* open */
18106 helper_close, /* close */
18107 eno_rdwrt, /* read */
18108 eno_rdwrt, /* write */
18109 helper_ioctl, /* ioctl */
18110 (stop_fcn_t *)nulldev, /* stop */
18111 (reset_fcn_t *)nulldev, /* reset */
18112 NULL, /* tty's */
18113 eno_select, /* select */
18114 eno_mmap, /* mmap */
18115 eno_strat, /* strategy */
18116 eno_getc, /* getc */
18117 eno_putc, /* putc */
18118 0 /* type */
18119};
18120
18121static int helper_majdevno = 0;
18122
18123static int gDTraceInited = 0;
18124
18125void
18126helper_init( void )
18127{
18128 /*
18129 * Once the "helper" is initialized, it can take ioctl calls that use locks
18130 * and zones initialized in dtrace_init. Make certain dtrace_init was called
18131 * before us.
18132 */
18133
18134 if (!gDTraceInited) {
18135 panic("helper_init before dtrace_init\n");
18136 }
18137
18138 if (0 >= helper_majdevno)
18139 {
18140 helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
18141
18142 if (helper_majdevno < 0) {
18143 printf("helper_init: failed to allocate a major number!\n");
18144 return;
18145 }
18146
18147 if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
18148 DTRACEMNR_HELPER, 0 )) {
18149 printf("dtrace_init: failed to devfs_make_node for helper!\n");
18150 return;
18151 }
18152 } else
18153 panic("helper_init: called twice!\n");
18154}
18155
18156#undef HELPER_MAJOR
18157
2d21ac55
A
18158static int
18159dtrace_clone_func(dev_t dev, int action)
18160{
18161#pragma unused(dev)
18162
18163 if (action == DEVFS_CLONE_ALLOC) {
39037602 18164 return dtrace_state_reserve();
2d21ac55
A
18165 }
18166 else if (action == DEVFS_CLONE_FREE) {
18167 return 0;
18168 }
18169 else return -1;
18170}
18171
39037602
A
18172void dtrace_ast(void);
18173
18174void
18175dtrace_ast(void)
18176{
18177 int i;
18178 uint32_t clients = atomic_and_32(&dtrace_wake_clients, 0);
18179 if (clients == 0)
18180 return;
18181 /**
18182 * We disable preemption here to be sure that we won't get
18183 * interrupted by a wakeup to a thread that is higher
18184 * priority than us, so that we do issue all wakeups
18185 */
18186 disable_preemption();
18187 for (i = 0; i < DTRACE_NCLIENTS; i++) {
18188 if (clients & (1 << i)) {
18189 dtrace_state_t *state = dtrace_state_get(i);
18190 if (state) {
18191 wakeup(state);
18192 }
18193
18194 }
18195 }
18196 enable_preemption();
18197}
18198
18199
2d21ac55
A
18200#define DTRACE_MAJOR -24 /* let the kernel pick the device number */
18201
18202static struct cdevsw dtrace_cdevsw =
18203{
18204 _dtrace_open, /* open */
18205 _dtrace_close, /* close */
18206 eno_rdwrt, /* read */
18207 eno_rdwrt, /* write */
18208 _dtrace_ioctl, /* ioctl */
18209 (stop_fcn_t *)nulldev, /* stop */
18210 (reset_fcn_t *)nulldev, /* reset */
18211 NULL, /* tty's */
18212 eno_select, /* select */
18213 eno_mmap, /* mmap */
18214 eno_strat, /* strategy */
18215 eno_getc, /* getc */
18216 eno_putc, /* putc */
18217 0 /* type */
18218};
18219
18220lck_attr_t* dtrace_lck_attr;
18221lck_grp_attr_t* dtrace_lck_grp_attr;
18222lck_grp_t* dtrace_lck_grp;
18223
18224static int gMajDevNo;
18225
18226void
18227dtrace_init( void )
18228{
18229 if (0 == gDTraceInited) {
39236c6e 18230 int i, ncpu;
fe8ab488 18231 size_t size = sizeof(dtrace_buffer_memory_maxsize);
2d21ac55 18232
39236c6e
A
18233 /*
18234 * DTrace allocates buffers based on the maximum number
18235 * of enabled cpus. This call avoids any race when finding
18236 * that count.
18237 */
18238 ASSERT(dtrace_max_cpus == 0);
18239 ncpu = dtrace_max_cpus = ml_get_max_cpus();
fe8ab488
A
18240
18241 /*
18242 * Retrieve the size of the physical memory in order to define
18243 * the state buffer memory maximal size. If we cannot retrieve
18244 * this value, we'll consider that we have 1Gb of memory per CPU, that's
18245 * still better than raising a kernel panic.
18246 */
18247 if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
18248 &size, NULL, 0))
18249 {
18250 dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
18251 printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
18252 dtrace_buffer_memory_maxsize);
18253 }
18254
18255 /*
18256 * Finally, divide by three to prevent DTrace from eating too
18257 * much memory.
18258 */
18259 dtrace_buffer_memory_maxsize /= 3;
18260 ASSERT(dtrace_buffer_memory_maxsize > 0);
18261
2d21ac55
A
18262 gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
18263
18264 if (gMajDevNo < 0) {
18265 printf("dtrace_init: failed to allocate a major number!\n");
18266 gDTraceInited = 0;
18267 return;
18268 }
18269
18270 if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
18271 dtrace_clone_func, DTRACEMNR_DTRACE, 0 )) {
18272 printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
18273 gDTraceInited = 0;
18274 return;
18275 }
18276
18277#if defined(DTRACE_MEMORY_ZONES)
2d21ac55
A
18278 /*
18279 * Initialize the dtrace kalloc-emulation zones.
18280 */
18281 dtrace_alloc_init();
2d21ac55
A
18282#endif /* DTRACE_MEMORY_ZONES */
18283
18284 /*
18285 * Allocate the dtrace_probe_t zone
18286 */
18287 dtrace_probe_t_zone = zinit(sizeof(dtrace_probe_t),
18288 1024 * sizeof(dtrace_probe_t),
18289 sizeof(dtrace_probe_t),
18290 "dtrace.dtrace_probe_t");
18291
18292 /*
18293 * Create the dtrace lock group and attrs.
18294 */
18295 dtrace_lck_attr = lck_attr_alloc_init();
18296 dtrace_lck_grp_attr= lck_grp_attr_alloc_init();
18297 dtrace_lck_grp = lck_grp_alloc_init("dtrace", dtrace_lck_grp_attr);
18298
18299 /*
18300 * We have to initialize all locks explicitly
18301 */
18302 lck_mtx_init(&dtrace_lock, dtrace_lck_grp, dtrace_lck_attr);
18303 lck_mtx_init(&dtrace_provider_lock, dtrace_lck_grp, dtrace_lck_attr);
18304 lck_mtx_init(&dtrace_meta_lock, dtrace_lck_grp, dtrace_lck_attr);
fe8ab488 18305 lck_mtx_init(&dtrace_procwaitfor_lock, dtrace_lck_grp, dtrace_lck_attr);
b0d623f7 18306#if DEBUG
2d21ac55
A
18307 lck_mtx_init(&dtrace_errlock, dtrace_lck_grp, dtrace_lck_attr);
18308#endif
18309 lck_rw_init(&dtrace_dof_mode_lock, dtrace_lck_grp, dtrace_lck_attr);
18310
18311 /*
18312 * The cpu_core structure consists of per-CPU state available in any context.
18313 * On some architectures, this may mean that the page(s) containing the
18314 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
18315 * is up to the platform to assure that this is performed properly. Note that
18316 * the structure is sized to avoid false sharing.
18317 */
18318 lck_mtx_init(&cpu_lock, dtrace_lck_grp, dtrace_lck_attr);
fe8ab488 18319 lck_mtx_init(&cyc_lock, dtrace_lck_grp, dtrace_lck_attr);
2d21ac55
A
18320 lck_mtx_init(&mod_lock, dtrace_lck_grp, dtrace_lck_attr);
18321
fe8ab488
A
18322 /*
18323 * Initialize the CPU offline/online hooks.
18324 */
18325 dtrace_install_cpu_hooks();
18326
6d2010ae
A
18327 dtrace_modctl_list = NULL;
18328
2d21ac55
A
18329 cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
18330 for (i = 0; i < ncpu; ++i) {
18331 lck_mtx_init(&cpu_core[i].cpuc_pid_lock, dtrace_lck_grp, dtrace_lck_attr);
18332 }
18333
6d2010ae 18334 cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
2d21ac55
A
18335 for (i = 0; i < ncpu; ++i) {
18336 cpu_list[i].cpu_id = (processorid_t)i;
18337 cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
fe8ab488 18338 LIST_INIT(&cpu_list[i].cpu_cyc_list);
2d21ac55
A
18339 lck_rw_init(&cpu_list[i].cpu_ft_lock, dtrace_lck_grp, dtrace_lck_attr);
18340 }
18341
18342 lck_mtx_lock(&cpu_lock);
18343 for (i = 0; i < ncpu; ++i)
39037602 18344 /* FIXME: track CPU configuration */
2d21ac55
A
18345 dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
18346 lck_mtx_unlock(&cpu_lock);
18347
18348 (void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
18349
316670eb 18350 dtrace_isa_init();
2d21ac55
A
18351 /*
18352 * See dtrace_impl.h for a description of dof modes.
18353 * The default is lazy dof.
18354 *
b0d623f7 18355 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
2d21ac55
A
18356 * makes no sense...
18357 */
593a1d5f 18358 if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
5ba3f43e
A
18359#if CONFIG_EMBEDDED
18360 /* Disable DOF mode by default for performance reasons */
18361 dtrace_dof_mode = DTRACE_DOF_MODE_NEVER;
18362#else
2d21ac55 18363 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
5ba3f43e 18364#endif
2d21ac55
A
18365 }
18366
18367 /*
18368 * Sanity check of dof mode value.
18369 */
18370 switch (dtrace_dof_mode) {
18371 case DTRACE_DOF_MODE_NEVER:
18372 case DTRACE_DOF_MODE_LAZY_ON:
18373 /* valid modes, but nothing else we need to do */
18374 break;
18375
18376 case DTRACE_DOF_MODE_LAZY_OFF:
18377 case DTRACE_DOF_MODE_NON_LAZY:
18378 /* Cannot wait for a dtrace_open to init fasttrap */
18379 fasttrap_init();
18380 break;
18381
18382 default:
18383 /* Invalid, clamp to non lazy */
18384 dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
18385 fasttrap_init();
18386 break;
18387 }
18388
6d2010ae
A
18389 /*
18390 * See dtrace_impl.h for a description of kernel symbol modes.
18391 * The default is to wait for symbols from userspace (lazy symbols).
18392 */
18393 if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
18394 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
18395 }
3e170ce0
A
18396
18397 dtrace_restriction_policy_load();
18398
2d21ac55
A
18399 gDTraceInited = 1;
18400
18401 } else
18402 panic("dtrace_init: called twice!\n");
18403}
18404
18405void
18406dtrace_postinit(void)
18407{
6d2010ae
A
18408 /*
18409 * Called from bsd_init after all provider's *_init() routines have been
18410 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
18411 * to go.
18412 */
18413 dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0), 0 ); /* Punning a dev_t to a dev_info_t* */
18414
18415 /*
18416 * Add the mach_kernel to the module list for lazy processing
18417 */
18418 struct kmod_info fake_kernel_kmod;
18419 memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
18420
18421 strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
18422 fake_kernel_kmod.id = 1;
18423 fake_kernel_kmod.address = g_kernel_kmod_info.address;
18424 fake_kernel_kmod.size = g_kernel_kmod_info.size;
18425
316670eb 18426 if (dtrace_module_loaded(&fake_kernel_kmod, 0) != 0) {
6d2010ae
A
18427 printf("dtrace_postinit: Could not register mach_kernel modctl\n");
18428 }
5ba3f43e
A
18429
18430 if (!PE_parse_boot_argn("dtrace_provide_private_probes", &dtrace_provide_private_probes, sizeof (dtrace_provide_private_probes))) {
18431 dtrace_provide_private_probes = 0;
18432 }
6d2010ae
A
18433
18434 (void)OSKextRegisterKextsWithDTrace();
2d21ac55
A
18435}
18436#undef DTRACE_MAJOR
18437
18438/*
18439 * Routines used to register interest in cpu's being added to or removed
18440 * from the system.
18441 */
18442void
18443register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
18444{
18445#pragma unused(ignore1,ignore2)
18446}
18447
18448void
18449unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
18450{
18451#pragma unused(ignore1,ignore2)
18452}