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.
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.
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]
25 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
26 * Copyright (c) 2016, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
31 * DTrace - Dynamic Tracing for Solaris
33 * This is the implementation of the Solaris Dynamic Tracing framework
34 * (DTrace). The user-visible interface to DTrace is described at length in
35 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
36 * library, the in-kernel DTrace framework, and the DTrace providers are
37 * described in the block comments in the <sys/dtrace.h> header file. The
38 * internal architecture of DTrace is described in the block comments in the
39 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
40 * implementation very much assume mastery of all of these sources; if one has
41 * an unanswered question about the implementation, one should consult them
44 * The functions here are ordered roughly as follows:
46 * - Probe context functions
47 * - Probe hashing functions
48 * - Non-probe context utility functions
49 * - Matching functions
50 * - Provider-to-Framework API functions
51 * - Probe management functions
52 * - DIF object functions
54 * - Predicate functions
57 * - Enabling functions
59 * - Anonymous enabling functions
60 * - Consumer state functions
63 * - Driver cookbook functions
65 * Each group of functions begins with a block comment labelled the "DTrace
66 * [Group] Functions", allowing one to find each block by searching forward
67 * on capital-f functions.
69 #include <sys/errno.h>
74 #include <sys/modctl.h>
76 #include <sys/systm.h>
79 #include <sys/sunddi.h>
81 #include <sys/cpuvar.h>
84 #include <sys/strsubr.h>
86 #include <sys/sysmacros.h>
87 #include <sys/dtrace_impl.h>
88 #include <sys/atomic.h>
89 #include <sys/cmn_err.h>
91 #include <sys/mutex_impl.h>
92 #include <sys/rwlock_impl.h>
94 #include <sys/ctf_api.h>
96 #include <sys/panic.h>
97 #include <sys/priv_impl.h>
99 #include <sys/policy.h>
101 #include <sys/cred_impl.h>
102 #include <sys/procfs_isa.h>
104 #include <sys/taskq.h>
106 #include <sys/mkdev.h>
109 #include <sys/zone.h>
110 #include <sys/socket.h>
111 #include <netinet/in.h>
112 #include "strtolctype.h"
114 /* FreeBSD includes: */
116 #include <sys/callout.h>
117 #include <sys/ctype.h>
118 #include <sys/eventhandler.h>
119 #include <sys/limits.h>
120 #include <sys/linker.h>
122 #include <sys/kernel.h>
123 #include <sys/malloc.h>
124 #include <sys/lock.h>
125 #include <sys/mutex.h>
126 #include <sys/ptrace.h>
127 #include <sys/rwlock.h>
129 #include <sys/sysctl.h>
131 #include <sys/dtrace_bsd.h>
133 #include <netinet/in.h>
135 #include "dtrace_cddl.h"
136 #include "dtrace_debug.c"
140 * DTrace Tunable Variables
142 * The following variables may be tuned by adding a line to /etc/system that
143 * includes both the name of the DTrace module ("dtrace") and the name of the
144 * variable. For example:
146 * set dtrace:dtrace_destructive_disallow = 1
148 * In general, the only variables that one should be tuning this way are those
149 * that affect system-wide DTrace behavior, and for which the default behavior
150 * is undesirable. Most of these variables are tunable on a per-consumer
151 * basis using DTrace options, and need not be tuned on a system-wide basis.
152 * When tuning these variables, avoid pathological values; while some attempt
153 * is made to verify the integrity of these variables, they are not considered
154 * part of the supported interface to DTrace, and they are therefore not
155 * checked comprehensively. Further, these variables should not be tuned
156 * dynamically via "mdb -kw" or other means; they should only be tuned via
159 int dtrace_destructive_disallow = 0;
160 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
161 size_t dtrace_difo_maxsize = (256 * 1024);
162 dtrace_optval_t dtrace_dof_maxsize = (8 * 1024 * 1024);
163 size_t dtrace_statvar_maxsize = (16 * 1024);
164 size_t dtrace_actions_max = (16 * 1024);
165 size_t dtrace_retain_max = 1024;
166 dtrace_optval_t dtrace_helper_actions_max = 128;
167 dtrace_optval_t dtrace_helper_providers_max = 32;
168 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
169 size_t dtrace_strsize_default = 256;
170 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
171 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
172 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
173 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
174 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
175 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
176 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
177 dtrace_optval_t dtrace_nspec_default = 1;
178 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
179 dtrace_optval_t dtrace_stackframes_default = 20;
180 dtrace_optval_t dtrace_ustackframes_default = 20;
181 dtrace_optval_t dtrace_jstackframes_default = 50;
182 dtrace_optval_t dtrace_jstackstrsize_default = 512;
183 int dtrace_msgdsize_max = 128;
184 hrtime_t dtrace_chill_max = MSEC2NSEC(500); /* 500 ms */
185 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
186 int dtrace_devdepth_max = 32;
187 int dtrace_err_verbose;
188 hrtime_t dtrace_deadman_interval = NANOSEC;
189 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
190 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
191 hrtime_t dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
193 int dtrace_memstr_max = 4096;
197 * DTrace External Variables
199 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
200 * available to DTrace consumers via the backtick (`) syntax. One of these,
201 * dtrace_zero, is made deliberately so: it is provided as a source of
202 * well-known, zero-filled memory. While this variable is not documented,
203 * it is used by some translators as an implementation detail.
205 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
208 * DTrace Internal Variables
211 static dev_info_t *dtrace_devi; /* device info */
214 static vmem_t *dtrace_arena; /* probe ID arena */
215 static vmem_t *dtrace_minor; /* minor number arena */
217 static taskq_t *dtrace_taskq; /* task queue */
218 static struct unrhdr *dtrace_arena; /* Probe ID number. */
220 static dtrace_probe_t **dtrace_probes; /* array of all probes */
221 static int dtrace_nprobes; /* number of probes */
222 static dtrace_provider_t *dtrace_provider; /* provider list */
223 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
224 static int dtrace_opens; /* number of opens */
225 static int dtrace_helpers; /* number of helpers */
226 static int dtrace_getf; /* number of unpriv getf()s */
228 static void *dtrace_softstate; /* softstate pointer */
230 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
231 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
232 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
233 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
234 static int dtrace_toxranges; /* number of toxic ranges */
235 static int dtrace_toxranges_max; /* size of toxic range array */
236 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
237 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
238 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
239 static kthread_t *dtrace_panicked; /* panicking thread */
240 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
241 static dtrace_genid_t dtrace_probegen; /* current probe generation */
242 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
243 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
244 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
245 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
246 static int dtrace_dynvar_failclean; /* dynvars failed to clean */
248 static struct mtx dtrace_unr_mtx;
249 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
250 static eventhandler_tag dtrace_kld_load_tag;
251 static eventhandler_tag dtrace_kld_unload_try_tag;
256 * DTrace is protected by three (relatively coarse-grained) locks:
258 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
259 * including enabling state, probes, ECBs, consumer state, helper state,
260 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
261 * probe context is lock-free -- synchronization is handled via the
262 * dtrace_sync() cross call mechanism.
264 * (2) dtrace_provider_lock is required when manipulating provider state, or
265 * when provider state must be held constant.
267 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
268 * when meta provider state must be held constant.
270 * The lock ordering between these three locks is dtrace_meta_lock before
271 * dtrace_provider_lock before dtrace_lock. (In particular, there are
272 * several places where dtrace_provider_lock is held by the framework as it
273 * calls into the providers -- which then call back into the framework,
274 * grabbing dtrace_lock.)
276 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
277 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
278 * role as a coarse-grained lock; it is acquired before both of these locks.
279 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
280 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
281 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
282 * acquired _between_ dtrace_provider_lock and dtrace_lock.
284 static kmutex_t dtrace_lock; /* probe state lock */
285 static kmutex_t dtrace_provider_lock; /* provider state lock */
286 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
289 /* XXX FreeBSD hacks. */
290 #define cr_suid cr_svuid
291 #define cr_sgid cr_svgid
292 #define ipaddr_t in_addr_t
293 #define mod_modname pathname
294 #define vuprintf vprintf
295 #define ttoproc(_a) ((_a)->td_proc)
296 #define crgetzoneid(_a) 0
299 #define CPU_ON_INTR(_a) 0
301 #define PRIV_EFFECTIVE (1 << 0)
302 #define PRIV_DTRACE_KERNEL (1 << 1)
303 #define PRIV_DTRACE_PROC (1 << 2)
304 #define PRIV_DTRACE_USER (1 << 3)
305 #define PRIV_PROC_OWNER (1 << 4)
306 #define PRIV_PROC_ZONE (1 << 5)
309 SYSCTL_DECL(_debug_dtrace);
310 SYSCTL_DECL(_kern_dtrace);
314 #define curcpu CPU->cpu_id
319 * DTrace Provider Variables
321 * These are the variables relating to DTrace as a provider (that is, the
322 * provider of the BEGIN, END, and ERROR probes).
324 static dtrace_pattr_t dtrace_provider_attr = {
325 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
326 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
327 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
328 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
329 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
336 static dtrace_pops_t dtrace_provider_ops = {
337 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
338 (void (*)(void *, modctl_t *))dtrace_nullop,
339 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
340 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
341 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
342 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
346 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
349 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
350 static dtrace_id_t dtrace_probeid_end; /* special END probe */
351 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
354 * DTrace Helper Tracing Variables
356 * These variables should be set dynamically to enable helper tracing. The
357 * only variables that should be set are dtrace_helptrace_enable (which should
358 * be set to a non-zero value to allocate helper tracing buffers on the next
359 * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
360 * non-zero value to deallocate helper tracing buffers on the next close of
361 * /dev/dtrace). When (and only when) helper tracing is disabled, the
362 * buffer size may also be set via dtrace_helptrace_bufsize.
364 int dtrace_helptrace_enable = 0;
365 int dtrace_helptrace_disable = 0;
366 int dtrace_helptrace_bufsize = 16 * 1024 * 1024;
367 uint32_t dtrace_helptrace_nlocals;
368 static dtrace_helptrace_t *dtrace_helptrace_buffer;
369 static uint32_t dtrace_helptrace_next = 0;
370 static int dtrace_helptrace_wrapped = 0;
373 * DTrace Error Hashing
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.
382 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
383 static const char *dtrace_errlast;
384 static kthread_t *dtrace_errthread;
385 static kmutex_t dtrace_errlock;
389 * DTrace Macros and Constants
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?
396 #define DTRACE_HASHSTR(hash, probe) \
397 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
399 #define DTRACE_HASHNEXT(hash, probe) \
400 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
402 #define DTRACE_HASHPREV(hash, probe) \
403 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
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)
409 #define DTRACE_AGGHASHSIZE_SLEW 17
411 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
414 * The key for a thread-local variable consists of the lower 61 bits of the
415 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
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:
422 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
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
429 #define DTRACE_TLS_THRKEY(where) { \
431 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
432 for (; actv; actv >>= 1) \
434 ASSERT(intr < (1 << 3)); \
435 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
436 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
439 #define DTRACE_TLS_THRKEY(where) { \
440 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
442 uint_t actv = _c->cpu_intr_actv; \
443 for (; actv; actv >>= 1) \
445 ASSERT(intr < (1 << 3)); \
446 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
447 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
451 #define DT_BSWAP_8(x) ((x) & 0xff)
452 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
453 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
454 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
456 #define DT_MASK_LO 0x00000000FFFFFFFFULL
458 #define DTRACE_STORE(type, tomax, offset, what) \
459 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
462 #define DTRACE_ALIGNCHECK(addr, size, flags) \
463 if (addr & (size - 1)) { \
464 *flags |= CPU_DTRACE_BADALIGN; \
465 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
469 #define DTRACE_ALIGNCHECK(addr, size, flags)
473 * Test whether a range of memory starting at testaddr of size testsz falls
474 * within the range of memory described by addr, sz. We take care to avoid
475 * problems with overflow and underflow of the unsigned quantities, and
476 * disallow all negative sizes. Ranges of size 0 are allowed.
478 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
479 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
480 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
481 (testaddr) + (testsz) >= (testaddr))
484 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
485 * alloc_sz on the righthand side of the comparison in order to avoid overflow
486 * or underflow in the comparison with it. This is simpler than the INRANGE
487 * check above, because we know that the dtms_scratch_ptr is valid in the
488 * range. Allocations of size zero are allowed.
490 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
491 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
492 (mstate)->dtms_scratch_ptr >= (alloc_sz))
494 #define DTRACE_LOADFUNC(bits) \
497 dtrace_load##bits(uintptr_t addr) \
499 size_t size = bits / NBBY; \
501 uint##bits##_t rval; \
503 volatile uint16_t *flags = (volatile uint16_t *) \
504 &cpu_core[curcpu].cpuc_dtrace_flags; \
506 DTRACE_ALIGNCHECK(addr, size, flags); \
508 for (i = 0; i < dtrace_toxranges; i++) { \
509 if (addr >= dtrace_toxrange[i].dtt_limit) \
512 if (addr + size <= dtrace_toxrange[i].dtt_base) \
516 * This address falls within a toxic region; return 0. \
518 *flags |= CPU_DTRACE_BADADDR; \
519 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
523 *flags |= CPU_DTRACE_NOFAULT; \
525 rval = *((volatile uint##bits##_t *)addr); \
526 *flags &= ~CPU_DTRACE_NOFAULT; \
528 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
532 #define dtrace_loadptr dtrace_load64
534 #define dtrace_loadptr dtrace_load32
537 #define DTRACE_DYNHASH_FREE 0
538 #define DTRACE_DYNHASH_SINK 1
539 #define DTRACE_DYNHASH_VALID 2
541 #define DTRACE_MATCH_NEXT 0
542 #define DTRACE_MATCH_DONE 1
543 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
544 #define DTRACE_STATE_ALIGN 64
546 #define DTRACE_FLAGS2FLT(flags) \
547 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
548 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
549 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
550 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
551 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
552 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
553 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
554 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
555 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
558 #define DTRACEACT_ISSTRING(act) \
559 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
560 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
562 /* Function prototype definitions: */
563 static size_t dtrace_strlen(const char *, size_t);
564 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
565 static void dtrace_enabling_provide(dtrace_provider_t *);
566 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
567 static void dtrace_enabling_matchall(void);
568 static void dtrace_enabling_reap(void);
569 static dtrace_state_t *dtrace_anon_grab(void);
570 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
571 dtrace_state_t *, uint64_t, uint64_t);
572 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
573 static void dtrace_buffer_drop(dtrace_buffer_t *);
574 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
575 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
576 dtrace_state_t *, dtrace_mstate_t *);
577 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
579 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
580 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
581 uint16_t dtrace_load16(uintptr_t);
582 uint32_t dtrace_load32(uintptr_t);
583 uint64_t dtrace_load64(uintptr_t);
584 uint8_t dtrace_load8(uintptr_t);
585 void dtrace_dynvar_clean(dtrace_dstate_t *);
586 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
587 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
588 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
589 static int dtrace_priv_proc(dtrace_state_t *);
590 static void dtrace_getf_barrier(void);
593 * DTrace Probe Context Functions
595 * These functions are called from probe context. Because probe context is
596 * any context in which C may be called, arbitrarily locks may be held,
597 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
598 * As a result, functions called from probe context may only call other DTrace
599 * support functions -- they may not interact at all with the system at large.
600 * (Note that the ASSERT macro is made probe-context safe by redefining it in
601 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
602 * loads are to be performed from probe context, they _must_ be in terms of
603 * the safe dtrace_load*() variants.
605 * Some functions in this block are not actually called from probe context;
606 * for these functions, there will be a comment above the function reading
607 * "Note: not called from probe context."
610 dtrace_panic(const char *format, ...)
614 va_start(alist, format);
616 vpanic(format, alist);
618 dtrace_vpanic(format, alist);
624 dtrace_assfail(const char *a, const char *f, int l)
626 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
629 * We just need something here that even the most clever compiler
630 * cannot optimize away.
632 return (a[(uintptr_t)f]);
636 * Atomically increment a specified error counter from probe context.
639 dtrace_error(uint32_t *counter)
642 * Most counters stored to in probe context are per-CPU counters.
643 * However, there are some error conditions that are sufficiently
644 * arcane that they don't merit per-CPU storage. If these counters
645 * are incremented concurrently on different CPUs, scalability will be
646 * adversely affected -- but we don't expect them to be white-hot in a
647 * correctly constructed enabling...
654 if ((nval = oval + 1) == 0) {
656 * If the counter would wrap, set it to 1 -- assuring
657 * that the counter is never zero when we have seen
658 * errors. (The counter must be 32-bits because we
659 * aren't guaranteed a 64-bit compare&swap operation.)
660 * To save this code both the infamy of being fingered
661 * by a priggish news story and the indignity of being
662 * the target of a neo-puritan witch trial, we're
663 * carefully avoiding any colorful description of the
664 * likelihood of this condition -- but suffice it to
665 * say that it is only slightly more likely than the
666 * overflow of predicate cache IDs, as discussed in
667 * dtrace_predicate_create().
671 } while (dtrace_cas32(counter, oval, nval) != oval);
675 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
676 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
686 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
688 if (dest < mstate->dtms_scratch_base)
691 if (dest + size < dest)
694 if (dest + size > mstate->dtms_scratch_ptr)
701 dtrace_canstore_statvar(uint64_t addr, size_t sz,
702 dtrace_statvar_t **svars, int nsvars)
705 size_t maxglobalsize, maxlocalsize;
710 maxglobalsize = dtrace_statvar_maxsize;
711 maxlocalsize = (maxglobalsize + sizeof (uint64_t)) * NCPU;
713 for (i = 0; i < nsvars; i++) {
714 dtrace_statvar_t *svar = svars[i];
718 if (svar == NULL || (size = svar->dtsv_size) == 0)
721 scope = svar->dtsv_var.dtdv_scope;
724 * We verify that our size is valid in the spirit of providing
725 * defense in depth: we want to prevent attackers from using
726 * DTrace to escalate an orthogonal kernel heap corruption bug
727 * into the ability to store to arbitrary locations in memory.
729 VERIFY((scope == DIFV_SCOPE_GLOBAL && size < maxglobalsize) ||
730 (scope == DIFV_SCOPE_LOCAL && size < maxlocalsize));
732 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
740 * Check to see if the address is within a memory region to which a store may
741 * be issued. This includes the DTrace scratch areas, and any DTrace variable
742 * region. The caller of dtrace_canstore() is responsible for performing any
743 * alignment checks that are needed before stores are actually executed.
746 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
747 dtrace_vstate_t *vstate)
750 * First, check to see if the address is in scratch space...
752 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
753 mstate->dtms_scratch_size))
757 * Now check to see if it's a dynamic variable. This check will pick
758 * up both thread-local variables and any global dynamically-allocated
761 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
762 vstate->dtvs_dynvars.dtds_size)) {
763 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
764 uintptr_t base = (uintptr_t)dstate->dtds_base +
765 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
767 dtrace_dynvar_t *dvar;
770 * Before we assume that we can store here, we need to make
771 * sure that it isn't in our metadata -- storing to our
772 * dynamic variable metadata would corrupt our state. For
773 * the range to not include any dynamic variable metadata,
776 * (1) Start above the hash table that is at the base of
777 * the dynamic variable space
779 * (2) Have a starting chunk offset that is beyond the
780 * dtrace_dynvar_t that is at the base of every chunk
782 * (3) Not span a chunk boundary
784 * (4) Not be in the tuple space of a dynamic variable
790 chunkoffs = (addr - base) % dstate->dtds_chunksize;
792 if (chunkoffs < sizeof (dtrace_dynvar_t))
795 if (chunkoffs + sz > dstate->dtds_chunksize)
798 dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
800 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
803 if (chunkoffs < sizeof (dtrace_dynvar_t) +
804 ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
811 * Finally, check the static local and global variables. These checks
812 * take the longest, so we perform them last.
814 if (dtrace_canstore_statvar(addr, sz,
815 vstate->dtvs_locals, vstate->dtvs_nlocals))
818 if (dtrace_canstore_statvar(addr, sz,
819 vstate->dtvs_globals, vstate->dtvs_nglobals))
827 * Convenience routine to check to see if the address is within a memory
828 * region in which a load may be issued given the user's privilege level;
829 * if not, it sets the appropriate error flags and loads 'addr' into the
830 * illegal value slot.
832 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
833 * appropriate memory access protection.
836 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
837 dtrace_vstate_t *vstate)
839 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
843 * If we hold the privilege to read from kernel memory, then
844 * everything is readable.
846 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
850 * You can obviously read that which you can store.
852 if (dtrace_canstore(addr, sz, mstate, vstate))
856 * We're allowed to read from our own string table.
858 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
859 mstate->dtms_difo->dtdo_strlen))
862 if (vstate->dtvs_state != NULL &&
863 dtrace_priv_proc(vstate->dtvs_state)) {
867 * When we have privileges to the current process, there are
868 * several context-related kernel structures that are safe to
869 * read, even absent the privilege to read from kernel memory.
870 * These reads are safe because these structures contain only
871 * state that (1) we're permitted to read, (2) is harmless or
872 * (3) contains pointers to additional kernel state that we're
873 * not permitted to read (and as such, do not present an
874 * opportunity for privilege escalation). Finally (and
875 * critically), because of the nature of their relation with
876 * the current thread context, the memory associated with these
877 * structures cannot change over the duration of probe context,
878 * and it is therefore impossible for this memory to be
879 * deallocated and reallocated as something else while it's
880 * being operated upon.
882 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
885 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
886 sz, curthread->t_procp, sizeof (proc_t))) {
890 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
891 curthread->t_cred, sizeof (cred_t))) {
896 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
897 &(p->p_pidp->pid_id), sizeof (pid_t))) {
901 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
902 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
908 if ((fp = mstate->dtms_getf) != NULL) {
909 uintptr_t psz = sizeof (void *);
914 * When getf() returns a file_t, the enabling is implicitly
915 * granted the (transient) right to read the returned file_t
916 * as well as the v_path and v_op->vnop_name of the underlying
917 * vnode. These accesses are allowed after a successful
918 * getf() because the members that they refer to cannot change
919 * once set -- and the barrier logic in the kernel's closef()
920 * path assures that the file_t and its referenced vode_t
921 * cannot themselves be stale (that is, it impossible for
922 * either dtms_getf itself or its f_vnode member to reference
925 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
928 if ((vp = fp->f_vnode) != NULL) {
930 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
932 if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
933 vp->v_path, strlen(vp->v_path) + 1)) {
938 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
942 if ((op = vp->v_op) != NULL &&
943 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
947 if (op != NULL && op->vnop_name != NULL &&
948 DTRACE_INRANGE(addr, sz, op->vnop_name,
949 strlen(op->vnop_name) + 1)) {
956 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
962 * Convenience routine to check to see if a given string is within a memory
963 * region in which a load may be issued given the user's privilege level;
964 * this exists so that we don't need to issue unnecessary dtrace_strlen()
965 * calls in the event that the user has all privileges.
968 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
969 dtrace_vstate_t *vstate)
974 * If we hold the privilege to read from kernel memory, then
975 * everything is readable.
977 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
980 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
981 if (dtrace_canload(addr, strsz, mstate, vstate))
988 * Convenience routine to check to see if a given variable is within a memory
989 * region in which a load may be issued given the user's privilege level.
992 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
993 dtrace_vstate_t *vstate)
996 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
999 * If we hold the privilege to read from kernel memory, then
1000 * everything is readable.
1002 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1005 if (type->dtdt_kind == DIF_TYPE_STRING)
1006 sz = dtrace_strlen(src,
1007 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
1009 sz = type->dtdt_size;
1011 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
1015 * Convert a string to a signed integer using safe loads.
1017 * NOTE: This function uses various macros from strtolctype.h to manipulate
1018 * digit values, etc -- these have all been checked to ensure they make
1019 * no additional function calls.
1022 dtrace_strtoll(char *input, int base, size_t limit)
1024 uintptr_t pos = (uintptr_t)input;
1027 boolean_t neg = B_FALSE;
1029 uintptr_t end = pos + limit;
1032 * Consume any whitespace preceding digits.
1034 while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1038 * Handle an explicit sign if one is present.
1040 if (c == '-' || c == '+') {
1043 c = dtrace_load8(++pos);
1047 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1050 if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1051 cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1057 * Read in contiguous digits until the first non-digit character.
1059 for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1060 c = dtrace_load8(++pos))
1061 val = val * base + x;
1063 return (neg ? -val : val);
1067 * Compare two strings using safe loads.
1070 dtrace_strncmp(char *s1, char *s2, size_t limit)
1073 volatile uint16_t *flags;
1075 if (s1 == s2 || limit == 0)
1078 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1084 c1 = dtrace_load8((uintptr_t)s1++);
1090 c2 = dtrace_load8((uintptr_t)s2++);
1095 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1101 * Compute strlen(s) for a string using safe memory accesses. The additional
1102 * len parameter is used to specify a maximum length to ensure completion.
1105 dtrace_strlen(const char *s, size_t lim)
1109 for (len = 0; len != lim; len++) {
1110 if (dtrace_load8((uintptr_t)s++) == '\0')
1118 * Check if an address falls within a toxic region.
1121 dtrace_istoxic(uintptr_t kaddr, size_t size)
1123 uintptr_t taddr, tsize;
1126 for (i = 0; i < dtrace_toxranges; i++) {
1127 taddr = dtrace_toxrange[i].dtt_base;
1128 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1130 if (kaddr - taddr < tsize) {
1131 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1132 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1136 if (taddr - kaddr < size) {
1137 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1138 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1147 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1148 * memory specified by the DIF program. The dst is assumed to be safe memory
1149 * that we can store to directly because it is managed by DTrace. As with
1150 * standard bcopy, overlapping copies are handled properly.
1153 dtrace_bcopy(const void *src, void *dst, size_t len)
1157 const uint8_t *s2 = src;
1161 *s1++ = dtrace_load8((uintptr_t)s2++);
1162 } while (--len != 0);
1168 *--s1 = dtrace_load8((uintptr_t)--s2);
1169 } while (--len != 0);
1175 * Copy src to dst using safe memory accesses, up to either the specified
1176 * length, or the point that a nul byte is encountered. The src is assumed to
1177 * be unsafe memory specified by the DIF program. The dst is assumed to be
1178 * safe memory that we can store to directly because it is managed by DTrace.
1179 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1182 dtrace_strcpy(const void *src, void *dst, size_t len)
1185 uint8_t *s1 = dst, c;
1186 const uint8_t *s2 = src;
1189 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1190 } while (--len != 0 && c != '\0');
1195 * Copy src to dst, deriving the size and type from the specified (BYREF)
1196 * variable type. The src is assumed to be unsafe memory specified by the DIF
1197 * program. The dst is assumed to be DTrace variable memory that is of the
1198 * specified type; we assume that we can store to directly.
1201 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1203 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1205 if (type->dtdt_kind == DIF_TYPE_STRING) {
1206 dtrace_strcpy(src, dst, type->dtdt_size);
1208 dtrace_bcopy(src, dst, type->dtdt_size);
1213 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1214 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1215 * safe memory that we can access directly because it is managed by DTrace.
1218 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1220 volatile uint16_t *flags;
1222 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1227 if (s1 == NULL || s2 == NULL)
1230 if (s1 != s2 && len != 0) {
1231 const uint8_t *ps1 = s1;
1232 const uint8_t *ps2 = s2;
1235 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1237 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1243 * Zero the specified region using a simple byte-by-byte loop. Note that this
1244 * is for safe DTrace-managed memory only.
1247 dtrace_bzero(void *dst, size_t len)
1251 for (cp = dst; len != 0; len--)
1256 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1260 result[0] = addend1[0] + addend2[0];
1261 result[1] = addend1[1] + addend2[1] +
1262 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1269 * Shift the 128-bit value in a by b. If b is positive, shift left.
1270 * If b is negative, shift right.
1273 dtrace_shift_128(uint64_t *a, int b)
1283 a[0] = a[1] >> (b - 64);
1287 mask = 1LL << (64 - b);
1289 a[0] |= ((a[1] & mask) << (64 - b));
1294 a[1] = a[0] << (b - 64);
1298 mask = a[0] >> (64 - b);
1306 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1307 * use native multiplication on those, and then re-combine into the
1308 * resulting 128-bit value.
1310 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1317 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1319 uint64_t hi1, hi2, lo1, lo2;
1322 hi1 = factor1 >> 32;
1323 hi2 = factor2 >> 32;
1325 lo1 = factor1 & DT_MASK_LO;
1326 lo2 = factor2 & DT_MASK_LO;
1328 product[0] = lo1 * lo2;
1329 product[1] = hi1 * hi2;
1333 dtrace_shift_128(tmp, 32);
1334 dtrace_add_128(product, tmp, product);
1338 dtrace_shift_128(tmp, 32);
1339 dtrace_add_128(product, tmp, product);
1343 * This privilege check should be used by actions and subroutines to
1344 * verify that the user credentials of the process that enabled the
1345 * invoking ECB match the target credentials
1348 dtrace_priv_proc_common_user(dtrace_state_t *state)
1350 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1353 * We should always have a non-NULL state cred here, since if cred
1354 * is null (anonymous tracing), we fast-path bypass this routine.
1356 ASSERT(s_cr != NULL);
1358 if ((cr = CRED()) != NULL &&
1359 s_cr->cr_uid == cr->cr_uid &&
1360 s_cr->cr_uid == cr->cr_ruid &&
1361 s_cr->cr_uid == cr->cr_suid &&
1362 s_cr->cr_gid == cr->cr_gid &&
1363 s_cr->cr_gid == cr->cr_rgid &&
1364 s_cr->cr_gid == cr->cr_sgid)
1371 * This privilege check should be used by actions and subroutines to
1372 * verify that the zone of the process that enabled the invoking ECB
1373 * matches the target credentials
1376 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1379 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1382 * We should always have a non-NULL state cred here, since if cred
1383 * is null (anonymous tracing), we fast-path bypass this routine.
1385 ASSERT(s_cr != NULL);
1387 if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1397 * This privilege check should be used by actions and subroutines to
1398 * verify that the process has not setuid or changed credentials.
1401 dtrace_priv_proc_common_nocd(void)
1405 if ((proc = ttoproc(curthread)) != NULL &&
1406 !(proc->p_flag & SNOCD))
1413 dtrace_priv_proc_destructive(dtrace_state_t *state)
1415 int action = state->dts_cred.dcr_action;
1417 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1418 dtrace_priv_proc_common_zone(state) == 0)
1421 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1422 dtrace_priv_proc_common_user(state) == 0)
1425 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1426 dtrace_priv_proc_common_nocd() == 0)
1432 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1438 dtrace_priv_proc_control(dtrace_state_t *state)
1440 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1443 if (dtrace_priv_proc_common_zone(state) &&
1444 dtrace_priv_proc_common_user(state) &&
1445 dtrace_priv_proc_common_nocd())
1448 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1454 dtrace_priv_proc(dtrace_state_t *state)
1456 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1459 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1465 dtrace_priv_kernel(dtrace_state_t *state)
1467 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1470 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1476 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1478 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1481 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1487 * Determine if the dte_cond of the specified ECB allows for processing of
1488 * the current probe to continue. Note that this routine may allow continued
1489 * processing, but with access(es) stripped from the mstate's dtms_access
1493 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1496 dtrace_probe_t *probe = ecb->dte_probe;
1497 dtrace_provider_t *prov = probe->dtpr_provider;
1498 dtrace_pops_t *pops = &prov->dtpv_pops;
1499 int mode = DTRACE_MODE_NOPRIV_DROP;
1501 ASSERT(ecb->dte_cond);
1504 if (pops->dtps_mode != NULL) {
1505 mode = pops->dtps_mode(prov->dtpv_arg,
1506 probe->dtpr_id, probe->dtpr_arg);
1508 ASSERT((mode & DTRACE_MODE_USER) ||
1509 (mode & DTRACE_MODE_KERNEL));
1510 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1511 (mode & DTRACE_MODE_NOPRIV_DROP));
1515 * If the dte_cond bits indicate that this consumer is only allowed to
1516 * see user-mode firings of this probe, call the provider's dtps_mode()
1517 * entry point to check that the probe was fired while in a user
1518 * context. If that's not the case, use the policy specified by the
1519 * provider to determine if we drop the probe or merely restrict
1522 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1523 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1525 if (!(mode & DTRACE_MODE_USER)) {
1526 if (mode & DTRACE_MODE_NOPRIV_DROP)
1529 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1535 * This is more subtle than it looks. We have to be absolutely certain
1536 * that CRED() isn't going to change out from under us so it's only
1537 * legit to examine that structure if we're in constrained situations.
1538 * Currently, the only times we'll this check is if a non-super-user
1539 * has enabled the profile or syscall providers -- providers that
1540 * allow visibility of all processes. For the profile case, the check
1541 * above will ensure that we're examining a user context.
1543 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1545 cred_t *s_cr = state->dts_cred.dcr_cred;
1548 ASSERT(s_cr != NULL);
1550 if ((cr = CRED()) == NULL ||
1551 s_cr->cr_uid != cr->cr_uid ||
1552 s_cr->cr_uid != cr->cr_ruid ||
1553 s_cr->cr_uid != cr->cr_suid ||
1554 s_cr->cr_gid != cr->cr_gid ||
1555 s_cr->cr_gid != cr->cr_rgid ||
1556 s_cr->cr_gid != cr->cr_sgid ||
1557 (proc = ttoproc(curthread)) == NULL ||
1558 (proc->p_flag & SNOCD)) {
1559 if (mode & DTRACE_MODE_NOPRIV_DROP)
1563 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1570 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1571 * in our zone, check to see if our mode policy is to restrict rather
1572 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1573 * and DTRACE_ACCESS_ARGS
1575 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1577 cred_t *s_cr = state->dts_cred.dcr_cred;
1579 ASSERT(s_cr != NULL);
1581 if ((cr = CRED()) == NULL ||
1582 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1583 if (mode & DTRACE_MODE_NOPRIV_DROP)
1586 mstate->dtms_access &=
1587 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1596 * Note: not called from probe context. This function is called
1597 * asynchronously (and at a regular interval) from outside of probe context to
1598 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1599 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1602 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1604 dtrace_dynvar_t *dirty;
1605 dtrace_dstate_percpu_t *dcpu;
1606 dtrace_dynvar_t **rinsep;
1609 for (i = 0; i < NCPU; i++) {
1610 dcpu = &dstate->dtds_percpu[i];
1611 rinsep = &dcpu->dtdsc_rinsing;
1614 * If the dirty list is NULL, there is no dirty work to do.
1616 if (dcpu->dtdsc_dirty == NULL)
1619 if (dcpu->dtdsc_rinsing != NULL) {
1621 * If the rinsing list is non-NULL, then it is because
1622 * this CPU was selected to accept another CPU's
1623 * dirty list -- and since that time, dirty buffers
1624 * have accumulated. This is a highly unlikely
1625 * condition, but we choose to ignore the dirty
1626 * buffers -- they'll be picked up a future cleanse.
1631 if (dcpu->dtdsc_clean != NULL) {
1633 * If the clean list is non-NULL, then we're in a
1634 * situation where a CPU has done deallocations (we
1635 * have a non-NULL dirty list) but no allocations (we
1636 * also have a non-NULL clean list). We can't simply
1637 * move the dirty list into the clean list on this
1638 * CPU, yet we also don't want to allow this condition
1639 * to persist, lest a short clean list prevent a
1640 * massive dirty list from being cleaned (which in
1641 * turn could lead to otherwise avoidable dynamic
1642 * drops). To deal with this, we look for some CPU
1643 * with a NULL clean list, NULL dirty list, and NULL
1644 * rinsing list -- and then we borrow this CPU to
1645 * rinse our dirty list.
1647 for (j = 0; j < NCPU; j++) {
1648 dtrace_dstate_percpu_t *rinser;
1650 rinser = &dstate->dtds_percpu[j];
1652 if (rinser->dtdsc_rinsing != NULL)
1655 if (rinser->dtdsc_dirty != NULL)
1658 if (rinser->dtdsc_clean != NULL)
1661 rinsep = &rinser->dtdsc_rinsing;
1667 * We were unable to find another CPU that
1668 * could accept this dirty list -- we are
1669 * therefore unable to clean it now.
1671 dtrace_dynvar_failclean++;
1679 * Atomically move the dirty list aside.
1682 dirty = dcpu->dtdsc_dirty;
1685 * Before we zap the dirty list, set the rinsing list.
1686 * (This allows for a potential assertion in
1687 * dtrace_dynvar(): if a free dynamic variable appears
1688 * on a hash chain, either the dirty list or the
1689 * rinsing list for some CPU must be non-NULL.)
1692 dtrace_membar_producer();
1693 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1694 dirty, NULL) != dirty);
1699 * We have no work to do; we can simply return.
1706 for (i = 0; i < NCPU; i++) {
1707 dcpu = &dstate->dtds_percpu[i];
1709 if (dcpu->dtdsc_rinsing == NULL)
1713 * We are now guaranteed that no hash chain contains a pointer
1714 * into this dirty list; we can make it clean.
1716 ASSERT(dcpu->dtdsc_clean == NULL);
1717 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1718 dcpu->dtdsc_rinsing = NULL;
1722 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1723 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1724 * This prevents a race whereby a CPU incorrectly decides that
1725 * the state should be something other than DTRACE_DSTATE_CLEAN
1726 * after dtrace_dynvar_clean() has completed.
1730 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1734 * Depending on the value of the op parameter, this function looks-up,
1735 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1736 * allocation is requested, this function will return a pointer to a
1737 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1738 * variable can be allocated. If NULL is returned, the appropriate counter
1739 * will be incremented.
1742 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1743 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1744 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1746 uint64_t hashval = DTRACE_DYNHASH_VALID;
1747 dtrace_dynhash_t *hash = dstate->dtds_hash;
1748 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1749 processorid_t me = curcpu, cpu = me;
1750 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1751 size_t bucket, ksize;
1752 size_t chunksize = dstate->dtds_chunksize;
1753 uintptr_t kdata, lock, nstate;
1759 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1760 * algorithm. For the by-value portions, we perform the algorithm in
1761 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1762 * bit, and seems to have only a minute effect on distribution. For
1763 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1764 * over each referenced byte. It's painful to do this, but it's much
1765 * better than pathological hash distribution. The efficacy of the
1766 * hashing algorithm (and a comparison with other algorithms) may be
1767 * found by running the ::dtrace_dynstat MDB dcmd.
1769 for (i = 0; i < nkeys; i++) {
1770 if (key[i].dttk_size == 0) {
1771 uint64_t val = key[i].dttk_value;
1773 hashval += (val >> 48) & 0xffff;
1774 hashval += (hashval << 10);
1775 hashval ^= (hashval >> 6);
1777 hashval += (val >> 32) & 0xffff;
1778 hashval += (hashval << 10);
1779 hashval ^= (hashval >> 6);
1781 hashval += (val >> 16) & 0xffff;
1782 hashval += (hashval << 10);
1783 hashval ^= (hashval >> 6);
1785 hashval += val & 0xffff;
1786 hashval += (hashval << 10);
1787 hashval ^= (hashval >> 6);
1790 * This is incredibly painful, but it beats the hell
1791 * out of the alternative.
1793 uint64_t j, size = key[i].dttk_size;
1794 uintptr_t base = (uintptr_t)key[i].dttk_value;
1796 if (!dtrace_canload(base, size, mstate, vstate))
1799 for (j = 0; j < size; j++) {
1800 hashval += dtrace_load8(base + j);
1801 hashval += (hashval << 10);
1802 hashval ^= (hashval >> 6);
1807 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1810 hashval += (hashval << 3);
1811 hashval ^= (hashval >> 11);
1812 hashval += (hashval << 15);
1815 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1816 * comes out to be one of our two sentinel hash values. If this
1817 * actually happens, we set the hashval to be a value known to be a
1818 * non-sentinel value.
1820 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1821 hashval = DTRACE_DYNHASH_VALID;
1824 * Yes, it's painful to do a divide here. If the cycle count becomes
1825 * important here, tricks can be pulled to reduce it. (However, it's
1826 * critical that hash collisions be kept to an absolute minimum;
1827 * they're much more painful than a divide.) It's better to have a
1828 * solution that generates few collisions and still keeps things
1829 * relatively simple.
1831 bucket = hashval % dstate->dtds_hashsize;
1833 if (op == DTRACE_DYNVAR_DEALLOC) {
1834 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1837 while ((lock = *lockp) & 1)
1840 if (dtrace_casptr((volatile void *)lockp,
1841 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1845 dtrace_membar_producer();
1850 lock = hash[bucket].dtdh_lock;
1852 dtrace_membar_consumer();
1854 start = hash[bucket].dtdh_chain;
1855 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1856 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1857 op != DTRACE_DYNVAR_DEALLOC));
1859 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1860 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1861 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1863 if (dvar->dtdv_hashval != hashval) {
1864 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1866 * We've reached the sink, and therefore the
1867 * end of the hash chain; we can kick out of
1868 * the loop knowing that we have seen a valid
1869 * snapshot of state.
1871 ASSERT(dvar->dtdv_next == NULL);
1872 ASSERT(dvar == &dtrace_dynhash_sink);
1876 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1878 * We've gone off the rails: somewhere along
1879 * the line, one of the members of this hash
1880 * chain was deleted. Note that we could also
1881 * detect this by simply letting this loop run
1882 * to completion, as we would eventually hit
1883 * the end of the dirty list. However, we
1884 * want to avoid running the length of the
1885 * dirty list unnecessarily (it might be quite
1886 * long), so we catch this as early as
1887 * possible by detecting the hash marker. In
1888 * this case, we simply set dvar to NULL and
1889 * break; the conditional after the loop will
1890 * send us back to top.
1899 if (dtuple->dtt_nkeys != nkeys)
1902 for (i = 0; i < nkeys; i++, dkey++) {
1903 if (dkey->dttk_size != key[i].dttk_size)
1904 goto next; /* size or type mismatch */
1906 if (dkey->dttk_size != 0) {
1908 (void *)(uintptr_t)key[i].dttk_value,
1909 (void *)(uintptr_t)dkey->dttk_value,
1913 if (dkey->dttk_value != key[i].dttk_value)
1918 if (op != DTRACE_DYNVAR_DEALLOC)
1921 ASSERT(dvar->dtdv_next == NULL ||
1922 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1925 ASSERT(hash[bucket].dtdh_chain != dvar);
1926 ASSERT(start != dvar);
1927 ASSERT(prev->dtdv_next == dvar);
1928 prev->dtdv_next = dvar->dtdv_next;
1930 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1931 start, dvar->dtdv_next) != start) {
1933 * We have failed to atomically swing the
1934 * hash table head pointer, presumably because
1935 * of a conflicting allocation on another CPU.
1936 * We need to reread the hash chain and try
1943 dtrace_membar_producer();
1946 * Now set the hash value to indicate that it's free.
1948 ASSERT(hash[bucket].dtdh_chain != dvar);
1949 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1951 dtrace_membar_producer();
1954 * Set the next pointer to point at the dirty list, and
1955 * atomically swing the dirty pointer to the newly freed dvar.
1958 next = dcpu->dtdsc_dirty;
1959 dvar->dtdv_next = next;
1960 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1963 * Finally, unlock this hash bucket.
1965 ASSERT(hash[bucket].dtdh_lock == lock);
1967 hash[bucket].dtdh_lock++;
1977 * If dvar is NULL, it is because we went off the rails:
1978 * one of the elements that we traversed in the hash chain
1979 * was deleted while we were traversing it. In this case,
1980 * we assert that we aren't doing a dealloc (deallocs lock
1981 * the hash bucket to prevent themselves from racing with
1982 * one another), and retry the hash chain traversal.
1984 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1988 if (op != DTRACE_DYNVAR_ALLOC) {
1990 * If we are not to allocate a new variable, we want to
1991 * return NULL now. Before we return, check that the value
1992 * of the lock word hasn't changed. If it has, we may have
1993 * seen an inconsistent snapshot.
1995 if (op == DTRACE_DYNVAR_NOALLOC) {
1996 if (hash[bucket].dtdh_lock != lock)
1999 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2000 ASSERT(hash[bucket].dtdh_lock == lock);
2002 hash[bucket].dtdh_lock++;
2009 * We need to allocate a new dynamic variable. The size we need is the
2010 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2011 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2012 * the size of any referred-to data (dsize). We then round the final
2013 * size up to the chunksize for allocation.
2015 for (ksize = 0, i = 0; i < nkeys; i++)
2016 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2019 * This should be pretty much impossible, but could happen if, say,
2020 * strange DIF specified the tuple. Ideally, this should be an
2021 * assertion and not an error condition -- but that requires that the
2022 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2023 * bullet-proof. (That is, it must not be able to be fooled by
2024 * malicious DIF.) Given the lack of backwards branches in DIF,
2025 * solving this would presumably not amount to solving the Halting
2026 * Problem -- but it still seems awfully hard.
2028 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2029 ksize + dsize > chunksize) {
2030 dcpu->dtdsc_drops++;
2034 nstate = DTRACE_DSTATE_EMPTY;
2038 free = dcpu->dtdsc_free;
2041 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2044 if (clean == NULL) {
2046 * We're out of dynamic variable space on
2047 * this CPU. Unless we have tried all CPUs,
2048 * we'll try to allocate from a different
2051 switch (dstate->dtds_state) {
2052 case DTRACE_DSTATE_CLEAN: {
2053 void *sp = &dstate->dtds_state;
2058 if (dcpu->dtdsc_dirty != NULL &&
2059 nstate == DTRACE_DSTATE_EMPTY)
2060 nstate = DTRACE_DSTATE_DIRTY;
2062 if (dcpu->dtdsc_rinsing != NULL)
2063 nstate = DTRACE_DSTATE_RINSING;
2065 dcpu = &dstate->dtds_percpu[cpu];
2070 (void) dtrace_cas32(sp,
2071 DTRACE_DSTATE_CLEAN, nstate);
2074 * To increment the correct bean
2075 * counter, take another lap.
2080 case DTRACE_DSTATE_DIRTY:
2081 dcpu->dtdsc_dirty_drops++;
2084 case DTRACE_DSTATE_RINSING:
2085 dcpu->dtdsc_rinsing_drops++;
2088 case DTRACE_DSTATE_EMPTY:
2089 dcpu->dtdsc_drops++;
2093 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2098 * The clean list appears to be non-empty. We want to
2099 * move the clean list to the free list; we start by
2100 * moving the clean pointer aside.
2102 if (dtrace_casptr(&dcpu->dtdsc_clean,
2103 clean, NULL) != clean) {
2105 * We are in one of two situations:
2107 * (a) The clean list was switched to the
2108 * free list by another CPU.
2110 * (b) The clean list was added to by the
2113 * In either of these situations, we can
2114 * just reattempt the free list allocation.
2119 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2122 * Now we'll move the clean list to our free list.
2123 * It's impossible for this to fail: the only way
2124 * the free list can be updated is through this
2125 * code path, and only one CPU can own the clean list.
2126 * Thus, it would only be possible for this to fail if
2127 * this code were racing with dtrace_dynvar_clean().
2128 * (That is, if dtrace_dynvar_clean() updated the clean
2129 * list, and we ended up racing to update the free
2130 * list.) This race is prevented by the dtrace_sync()
2131 * in dtrace_dynvar_clean() -- which flushes the
2132 * owners of the clean lists out before resetting
2135 dcpu = &dstate->dtds_percpu[me];
2136 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2137 ASSERT(rval == NULL);
2142 new_free = dvar->dtdv_next;
2143 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2146 * We have now allocated a new chunk. We copy the tuple keys into the
2147 * tuple array and copy any referenced key data into the data space
2148 * following the tuple array. As we do this, we relocate dttk_value
2149 * in the final tuple to point to the key data address in the chunk.
2151 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2152 dvar->dtdv_data = (void *)(kdata + ksize);
2153 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2155 for (i = 0; i < nkeys; i++) {
2156 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2157 size_t kesize = key[i].dttk_size;
2161 (const void *)(uintptr_t)key[i].dttk_value,
2162 (void *)kdata, kesize);
2163 dkey->dttk_value = kdata;
2164 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2166 dkey->dttk_value = key[i].dttk_value;
2169 dkey->dttk_size = kesize;
2172 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2173 dvar->dtdv_hashval = hashval;
2174 dvar->dtdv_next = start;
2176 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2180 * The cas has failed. Either another CPU is adding an element to
2181 * this hash chain, or another CPU is deleting an element from this
2182 * hash chain. The simplest way to deal with both of these cases
2183 * (though not necessarily the most efficient) is to free our
2184 * allocated block and re-attempt it all. Note that the free is
2185 * to the dirty list and _not_ to the free list. This is to prevent
2186 * races with allocators, above.
2188 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2190 dtrace_membar_producer();
2193 free = dcpu->dtdsc_dirty;
2194 dvar->dtdv_next = free;
2195 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2202 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2204 if ((int64_t)nval < (int64_t)*oval)
2210 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2212 if ((int64_t)nval > (int64_t)*oval)
2217 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2219 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2220 int64_t val = (int64_t)nval;
2223 for (i = 0; i < zero; i++) {
2224 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2230 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2231 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2232 quanta[i - 1] += incr;
2237 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2245 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2247 uint64_t arg = *lquanta++;
2248 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2249 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2250 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2251 int32_t val = (int32_t)nval, level;
2254 ASSERT(levels != 0);
2258 * This is an underflow.
2264 level = (val - base) / step;
2266 if (level < levels) {
2267 lquanta[level + 1] += incr;
2272 * This is an overflow.
2274 lquanta[levels + 1] += incr;
2278 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2279 uint16_t high, uint16_t nsteps, int64_t value)
2281 int64_t this = 1, last, next;
2282 int base = 1, order;
2284 ASSERT(factor <= nsteps);
2285 ASSERT(nsteps % factor == 0);
2287 for (order = 0; order < low; order++)
2291 * If our value is less than our factor taken to the power of the
2292 * low order of magnitude, it goes into the zeroth bucket.
2294 if (value < (last = this))
2297 for (this *= factor; order <= high; order++) {
2298 int nbuckets = this > nsteps ? nsteps : this;
2300 if ((next = this * factor) < this) {
2302 * We should not generally get log/linear quantizations
2303 * with a high magnitude that allows 64-bits to
2304 * overflow, but we nonetheless protect against this
2305 * by explicitly checking for overflow, and clamping
2306 * our value accordingly.
2313 * If our value lies within this order of magnitude,
2314 * determine its position by taking the offset within
2315 * the order of magnitude, dividing by the bucket
2316 * width, and adding to our (accumulated) base.
2318 return (base + (value - last) / (this / nbuckets));
2321 base += nbuckets - (nbuckets / factor);
2327 * Our value is greater than or equal to our factor taken to the
2328 * power of one plus the high magnitude -- return the top bucket.
2334 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2336 uint64_t arg = *llquanta++;
2337 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2338 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2339 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2340 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2342 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2343 low, high, nsteps, nval)] += incr;
2348 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2356 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2358 int64_t snval = (int64_t)nval;
2365 * What we want to say here is:
2367 * data[2] += nval * nval;
2369 * But given that nval is 64-bit, we could easily overflow, so
2370 * we do this as 128-bit arithmetic.
2375 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2376 dtrace_add_128(data + 2, tmp, data + 2);
2381 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2388 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2394 * Aggregate given the tuple in the principal data buffer, and the aggregating
2395 * action denoted by the specified dtrace_aggregation_t. The aggregation
2396 * buffer is specified as the buf parameter. This routine does not return
2397 * failure; if there is no space in the aggregation buffer, the data will be
2398 * dropped, and a corresponding counter incremented.
2401 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2402 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2404 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2405 uint32_t i, ndx, size, fsize;
2406 uint32_t align = sizeof (uint64_t) - 1;
2407 dtrace_aggbuffer_t *agb;
2408 dtrace_aggkey_t *key;
2409 uint32_t hashval = 0, limit, isstr;
2410 caddr_t tomax, data, kdata;
2411 dtrace_actkind_t action;
2412 dtrace_action_t *act;
2418 if (!agg->dtag_hasarg) {
2420 * Currently, only quantize() and lquantize() take additional
2421 * arguments, and they have the same semantics: an increment
2422 * value that defaults to 1 when not present. If additional
2423 * aggregating actions take arguments, the setting of the
2424 * default argument value will presumably have to become more
2430 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2431 size = rec->dtrd_offset - agg->dtag_base;
2432 fsize = size + rec->dtrd_size;
2434 ASSERT(dbuf->dtb_tomax != NULL);
2435 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2437 if ((tomax = buf->dtb_tomax) == NULL) {
2438 dtrace_buffer_drop(buf);
2443 * The metastructure is always at the bottom of the buffer.
2445 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2446 sizeof (dtrace_aggbuffer_t));
2448 if (buf->dtb_offset == 0) {
2450 * We just kludge up approximately 1/8th of the size to be
2451 * buckets. If this guess ends up being routinely
2452 * off-the-mark, we may need to dynamically readjust this
2453 * based on past performance.
2455 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2457 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2458 (uintptr_t)tomax || hashsize == 0) {
2460 * We've been given a ludicrously small buffer;
2461 * increment our drop count and leave.
2463 dtrace_buffer_drop(buf);
2468 * And now, a pathetic attempt to try to get a an odd (or
2469 * perchance, a prime) hash size for better hash distribution.
2471 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2472 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2474 agb->dtagb_hashsize = hashsize;
2475 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2476 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2477 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2479 for (i = 0; i < agb->dtagb_hashsize; i++)
2480 agb->dtagb_hash[i] = NULL;
2483 ASSERT(agg->dtag_first != NULL);
2484 ASSERT(agg->dtag_first->dta_intuple);
2487 * Calculate the hash value based on the key. Note that we _don't_
2488 * include the aggid in the hashing (but we will store it as part of
2489 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2490 * algorithm: a simple, quick algorithm that has no known funnels, and
2491 * gets good distribution in practice. The efficacy of the hashing
2492 * algorithm (and a comparison with other algorithms) may be found by
2493 * running the ::dtrace_aggstat MDB dcmd.
2495 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2496 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2497 limit = i + act->dta_rec.dtrd_size;
2498 ASSERT(limit <= size);
2499 isstr = DTRACEACT_ISSTRING(act);
2501 for (; i < limit; i++) {
2503 hashval += (hashval << 10);
2504 hashval ^= (hashval >> 6);
2506 if (isstr && data[i] == '\0')
2511 hashval += (hashval << 3);
2512 hashval ^= (hashval >> 11);
2513 hashval += (hashval << 15);
2516 * Yes, the divide here is expensive -- but it's generally the least
2517 * of the performance issues given the amount of data that we iterate
2518 * over to compute hash values, compare data, etc.
2520 ndx = hashval % agb->dtagb_hashsize;
2522 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2523 ASSERT((caddr_t)key >= tomax);
2524 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2526 if (hashval != key->dtak_hashval || key->dtak_size != size)
2529 kdata = key->dtak_data;
2530 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2532 for (act = agg->dtag_first; act->dta_intuple;
2533 act = act->dta_next) {
2534 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2535 limit = i + act->dta_rec.dtrd_size;
2536 ASSERT(limit <= size);
2537 isstr = DTRACEACT_ISSTRING(act);
2539 for (; i < limit; i++) {
2540 if (kdata[i] != data[i])
2543 if (isstr && data[i] == '\0')
2548 if (action != key->dtak_action) {
2550 * We are aggregating on the same value in the same
2551 * aggregation with two different aggregating actions.
2552 * (This should have been picked up in the compiler,
2553 * so we may be dealing with errant or devious DIF.)
2554 * This is an error condition; we indicate as much,
2557 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2562 * This is a hit: we need to apply the aggregator to
2563 * the value at this key.
2565 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2572 * We didn't find it. We need to allocate some zero-filled space,
2573 * link it into the hash table appropriately, and apply the aggregator
2574 * to the (zero-filled) value.
2576 offs = buf->dtb_offset;
2577 while (offs & (align - 1))
2578 offs += sizeof (uint32_t);
2581 * If we don't have enough room to both allocate a new key _and_
2582 * its associated data, increment the drop count and return.
2584 if ((uintptr_t)tomax + offs + fsize >
2585 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2586 dtrace_buffer_drop(buf);
2591 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2592 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2593 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2595 key->dtak_data = kdata = tomax + offs;
2596 buf->dtb_offset = offs + fsize;
2599 * Now copy the data across.
2601 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2603 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2607 * Because strings are not zeroed out by default, we need to iterate
2608 * looking for actions that store strings, and we need to explicitly
2609 * pad these strings out with zeroes.
2611 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2614 if (!DTRACEACT_ISSTRING(act))
2617 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2618 limit = i + act->dta_rec.dtrd_size;
2619 ASSERT(limit <= size);
2621 for (nul = 0; i < limit; i++) {
2627 if (data[i] != '\0')
2634 for (i = size; i < fsize; i++)
2637 key->dtak_hashval = hashval;
2638 key->dtak_size = size;
2639 key->dtak_action = action;
2640 key->dtak_next = agb->dtagb_hash[ndx];
2641 agb->dtagb_hash[ndx] = key;
2644 * Finally, apply the aggregator.
2646 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2647 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2651 * Given consumer state, this routine finds a speculation in the INACTIVE
2652 * state and transitions it into the ACTIVE state. If there is no speculation
2653 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2654 * incremented -- it is up to the caller to take appropriate action.
2657 dtrace_speculation(dtrace_state_t *state)
2660 dtrace_speculation_state_t current;
2661 uint32_t *stat = &state->dts_speculations_unavail, count;
2663 while (i < state->dts_nspeculations) {
2664 dtrace_speculation_t *spec = &state->dts_speculations[i];
2666 current = spec->dtsp_state;
2668 if (current != DTRACESPEC_INACTIVE) {
2669 if (current == DTRACESPEC_COMMITTINGMANY ||
2670 current == DTRACESPEC_COMMITTING ||
2671 current == DTRACESPEC_DISCARDING)
2672 stat = &state->dts_speculations_busy;
2677 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2678 current, DTRACESPEC_ACTIVE) == current)
2683 * We couldn't find a speculation. If we found as much as a single
2684 * busy speculation buffer, we'll attribute this failure as "busy"
2685 * instead of "unavail".
2689 } while (dtrace_cas32(stat, count, count + 1) != count);
2695 * This routine commits an active speculation. If the specified speculation
2696 * is not in a valid state to perform a commit(), this routine will silently do
2697 * nothing. The state of the specified speculation is transitioned according
2698 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2701 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2702 dtrace_specid_t which)
2704 dtrace_speculation_t *spec;
2705 dtrace_buffer_t *src, *dest;
2706 uintptr_t daddr, saddr, dlimit, slimit;
2707 dtrace_speculation_state_t current, new = 0;
2714 if (which > state->dts_nspeculations) {
2715 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2719 spec = &state->dts_speculations[which - 1];
2720 src = &spec->dtsp_buffer[cpu];
2721 dest = &state->dts_buffer[cpu];
2724 current = spec->dtsp_state;
2726 if (current == DTRACESPEC_COMMITTINGMANY)
2730 case DTRACESPEC_INACTIVE:
2731 case DTRACESPEC_DISCARDING:
2734 case DTRACESPEC_COMMITTING:
2736 * This is only possible if we are (a) commit()'ing
2737 * without having done a prior speculate() on this CPU
2738 * and (b) racing with another commit() on a different
2739 * CPU. There's nothing to do -- we just assert that
2742 ASSERT(src->dtb_offset == 0);
2745 case DTRACESPEC_ACTIVE:
2746 new = DTRACESPEC_COMMITTING;
2749 case DTRACESPEC_ACTIVEONE:
2751 * This speculation is active on one CPU. If our
2752 * buffer offset is non-zero, we know that the one CPU
2753 * must be us. Otherwise, we are committing on a
2754 * different CPU from the speculate(), and we must
2755 * rely on being asynchronously cleaned.
2757 if (src->dtb_offset != 0) {
2758 new = DTRACESPEC_COMMITTING;
2763 case DTRACESPEC_ACTIVEMANY:
2764 new = DTRACESPEC_COMMITTINGMANY;
2770 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2771 current, new) != current);
2774 * We have set the state to indicate that we are committing this
2775 * speculation. Now reserve the necessary space in the destination
2778 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2779 sizeof (uint64_t), state, NULL)) < 0) {
2780 dtrace_buffer_drop(dest);
2785 * We have sufficient space to copy the speculative buffer into the
2786 * primary buffer. First, modify the speculative buffer, filling
2787 * in the timestamp of all entries with the current time. The data
2788 * must have the commit() time rather than the time it was traced,
2789 * so that all entries in the primary buffer are in timestamp order.
2791 timestamp = dtrace_gethrtime();
2792 saddr = (uintptr_t)src->dtb_tomax;
2793 slimit = saddr + src->dtb_offset;
2794 while (saddr < slimit) {
2796 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2798 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2799 saddr += sizeof (dtrace_epid_t);
2802 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2803 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2805 ASSERT3U(saddr + size, <=, slimit);
2806 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2807 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2809 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2815 * Copy the buffer across. (Note that this is a
2816 * highly subobtimal bcopy(); in the unlikely event that this becomes
2817 * a serious performance issue, a high-performance DTrace-specific
2818 * bcopy() should obviously be invented.)
2820 daddr = (uintptr_t)dest->dtb_tomax + offs;
2821 dlimit = daddr + src->dtb_offset;
2822 saddr = (uintptr_t)src->dtb_tomax;
2825 * First, the aligned portion.
2827 while (dlimit - daddr >= sizeof (uint64_t)) {
2828 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2830 daddr += sizeof (uint64_t);
2831 saddr += sizeof (uint64_t);
2835 * Now any left-over bit...
2837 while (dlimit - daddr)
2838 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2841 * Finally, commit the reserved space in the destination buffer.
2843 dest->dtb_offset = offs + src->dtb_offset;
2847 * If we're lucky enough to be the only active CPU on this speculation
2848 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2850 if (current == DTRACESPEC_ACTIVE ||
2851 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2852 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2853 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2855 ASSERT(rval == DTRACESPEC_COMMITTING);
2858 src->dtb_offset = 0;
2859 src->dtb_xamot_drops += src->dtb_drops;
2864 * This routine discards an active speculation. If the specified speculation
2865 * is not in a valid state to perform a discard(), this routine will silently
2866 * do nothing. The state of the specified speculation is transitioned
2867 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2870 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2871 dtrace_specid_t which)
2873 dtrace_speculation_t *spec;
2874 dtrace_speculation_state_t current, new = 0;
2875 dtrace_buffer_t *buf;
2880 if (which > state->dts_nspeculations) {
2881 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2885 spec = &state->dts_speculations[which - 1];
2886 buf = &spec->dtsp_buffer[cpu];
2889 current = spec->dtsp_state;
2892 case DTRACESPEC_INACTIVE:
2893 case DTRACESPEC_COMMITTINGMANY:
2894 case DTRACESPEC_COMMITTING:
2895 case DTRACESPEC_DISCARDING:
2898 case DTRACESPEC_ACTIVE:
2899 case DTRACESPEC_ACTIVEMANY:
2900 new = DTRACESPEC_DISCARDING;
2903 case DTRACESPEC_ACTIVEONE:
2904 if (buf->dtb_offset != 0) {
2905 new = DTRACESPEC_INACTIVE;
2907 new = DTRACESPEC_DISCARDING;
2914 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2915 current, new) != current);
2917 buf->dtb_offset = 0;
2922 * Note: not called from probe context. This function is called
2923 * asynchronously from cross call context to clean any speculations that are
2924 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2925 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2929 dtrace_speculation_clean_here(dtrace_state_t *state)
2931 dtrace_icookie_t cookie;
2932 processorid_t cpu = curcpu;
2933 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2936 cookie = dtrace_interrupt_disable();
2938 if (dest->dtb_tomax == NULL) {
2939 dtrace_interrupt_enable(cookie);
2943 for (i = 0; i < state->dts_nspeculations; i++) {
2944 dtrace_speculation_t *spec = &state->dts_speculations[i];
2945 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2947 if (src->dtb_tomax == NULL)
2950 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2951 src->dtb_offset = 0;
2955 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2958 if (src->dtb_offset == 0)
2961 dtrace_speculation_commit(state, cpu, i + 1);
2964 dtrace_interrupt_enable(cookie);
2968 * Note: not called from probe context. This function is called
2969 * asynchronously (and at a regular interval) to clean any speculations that
2970 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2971 * is work to be done, it cross calls all CPUs to perform that work;
2972 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2973 * INACTIVE state until they have been cleaned by all CPUs.
2976 dtrace_speculation_clean(dtrace_state_t *state)
2981 for (i = 0; i < state->dts_nspeculations; i++) {
2982 dtrace_speculation_t *spec = &state->dts_speculations[i];
2984 ASSERT(!spec->dtsp_cleaning);
2986 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2987 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2991 spec->dtsp_cleaning = 1;
2997 dtrace_xcall(DTRACE_CPUALL,
2998 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3001 * We now know that all CPUs have committed or discarded their
3002 * speculation buffers, as appropriate. We can now set the state
3005 for (i = 0; i < state->dts_nspeculations; i++) {
3006 dtrace_speculation_t *spec = &state->dts_speculations[i];
3007 dtrace_speculation_state_t current, new;
3009 if (!spec->dtsp_cleaning)
3012 current = spec->dtsp_state;
3013 ASSERT(current == DTRACESPEC_DISCARDING ||
3014 current == DTRACESPEC_COMMITTINGMANY);
3016 new = DTRACESPEC_INACTIVE;
3018 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3019 ASSERT(rv == current);
3020 spec->dtsp_cleaning = 0;
3025 * Called as part of a speculate() to get the speculative buffer associated
3026 * with a given speculation. Returns NULL if the specified speculation is not
3027 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
3028 * the active CPU is not the specified CPU -- the speculation will be
3029 * atomically transitioned into the ACTIVEMANY state.
3031 static dtrace_buffer_t *
3032 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3033 dtrace_specid_t which)
3035 dtrace_speculation_t *spec;
3036 dtrace_speculation_state_t current, new = 0;
3037 dtrace_buffer_t *buf;
3042 if (which > state->dts_nspeculations) {
3043 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3047 spec = &state->dts_speculations[which - 1];
3048 buf = &spec->dtsp_buffer[cpuid];
3051 current = spec->dtsp_state;
3054 case DTRACESPEC_INACTIVE:
3055 case DTRACESPEC_COMMITTINGMANY:
3056 case DTRACESPEC_DISCARDING:
3059 case DTRACESPEC_COMMITTING:
3060 ASSERT(buf->dtb_offset == 0);
3063 case DTRACESPEC_ACTIVEONE:
3065 * This speculation is currently active on one CPU.
3066 * Check the offset in the buffer; if it's non-zero,
3067 * that CPU must be us (and we leave the state alone).
3068 * If it's zero, assume that we're starting on a new
3069 * CPU -- and change the state to indicate that the
3070 * speculation is active on more than one CPU.
3072 if (buf->dtb_offset != 0)
3075 new = DTRACESPEC_ACTIVEMANY;
3078 case DTRACESPEC_ACTIVEMANY:
3081 case DTRACESPEC_ACTIVE:
3082 new = DTRACESPEC_ACTIVEONE;
3088 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3089 current, new) != current);
3091 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3096 * Return a string. In the event that the user lacks the privilege to access
3097 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3098 * don't fail access checking.
3100 * dtrace_dif_variable() uses this routine as a helper for various
3101 * builtin values such as 'execname' and 'probefunc.'
3104 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3105 dtrace_mstate_t *mstate)
3107 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3112 * The easy case: this probe is allowed to read all of memory, so
3113 * we can just return this as a vanilla pointer.
3115 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3119 * This is the tougher case: we copy the string in question from
3120 * kernel memory into scratch memory and return it that way: this
3121 * ensures that we won't trip up when access checking tests the
3122 * BYREF return value.
3124 strsz = dtrace_strlen((char *)addr, size) + 1;
3126 if (mstate->dtms_scratch_ptr + strsz >
3127 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3128 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3132 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3134 ret = mstate->dtms_scratch_ptr;
3135 mstate->dtms_scratch_ptr += strsz;
3140 * Return a string from a memoy address which is known to have one or
3141 * more concatenated, individually zero terminated, sub-strings.
3142 * In the event that the user lacks the privilege to access
3143 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3144 * don't fail access checking.
3146 * dtrace_dif_variable() uses this routine as a helper for various
3147 * builtin values such as 'execargs'.
3150 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3151 dtrace_mstate_t *mstate)
3157 if (mstate->dtms_scratch_ptr + strsz >
3158 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3159 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3163 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3166 /* Replace sub-string termination characters with a space. */
3167 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3172 ret = mstate->dtms_scratch_ptr;
3173 mstate->dtms_scratch_ptr += strsz;
3178 * This function implements the DIF emulator's variable lookups. The emulator
3179 * passes a reserved variable identifier and optional built-in array index.
3182 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3186 * If we're accessing one of the uncached arguments, we'll turn this
3187 * into a reference in the args array.
3189 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3190 ndx = v - DIF_VAR_ARG0;
3196 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3197 if (ndx >= sizeof (mstate->dtms_arg) /
3198 sizeof (mstate->dtms_arg[0])) {
3199 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3200 dtrace_provider_t *pv;
3203 pv = mstate->dtms_probe->dtpr_provider;
3204 if (pv->dtpv_pops.dtps_getargval != NULL)
3205 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3206 mstate->dtms_probe->dtpr_id,
3207 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3209 val = dtrace_getarg(ndx, aframes);
3212 * This is regrettably required to keep the compiler
3213 * from tail-optimizing the call to dtrace_getarg().
3214 * The condition always evaluates to true, but the
3215 * compiler has no way of figuring that out a priori.
3216 * (None of this would be necessary if the compiler
3217 * could be relied upon to _always_ tail-optimize
3218 * the call to dtrace_getarg() -- but it can't.)
3220 if (mstate->dtms_probe != NULL)
3226 return (mstate->dtms_arg[ndx]);
3229 case DIF_VAR_UREGS: {
3232 if (!dtrace_priv_proc(state))
3235 if ((lwp = curthread->t_lwp) == NULL) {
3236 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3237 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3241 return (dtrace_getreg(lwp->lwp_regs, ndx));
3245 case DIF_VAR_UREGS: {
3246 struct trapframe *tframe;
3248 if (!dtrace_priv_proc(state))
3251 if ((tframe = curthread->td_frame) == NULL) {
3252 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3253 cpu_core[curcpu].cpuc_dtrace_illval = 0;
3257 return (dtrace_getreg(tframe, ndx));
3261 case DIF_VAR_CURTHREAD:
3262 if (!dtrace_priv_proc(state))
3264 return ((uint64_t)(uintptr_t)curthread);
3266 case DIF_VAR_TIMESTAMP:
3267 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3268 mstate->dtms_timestamp = dtrace_gethrtime();
3269 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3271 return (mstate->dtms_timestamp);
3273 case DIF_VAR_VTIMESTAMP:
3274 ASSERT(dtrace_vtime_references != 0);
3275 return (curthread->t_dtrace_vtime);
3277 case DIF_VAR_WALLTIMESTAMP:
3278 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3279 mstate->dtms_walltimestamp = dtrace_gethrestime();
3280 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3282 return (mstate->dtms_walltimestamp);
3286 if (!dtrace_priv_kernel(state))
3288 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3289 mstate->dtms_ipl = dtrace_getipl();
3290 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3292 return (mstate->dtms_ipl);
3296 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3297 return (mstate->dtms_epid);
3300 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3301 return (mstate->dtms_probe->dtpr_id);
3303 case DIF_VAR_STACKDEPTH:
3304 if (!dtrace_priv_kernel(state))
3306 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3307 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3309 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3310 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3312 return (mstate->dtms_stackdepth);
3314 case DIF_VAR_USTACKDEPTH:
3315 if (!dtrace_priv_proc(state))
3317 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3319 * See comment in DIF_VAR_PID.
3321 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3323 mstate->dtms_ustackdepth = 0;
3325 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3326 mstate->dtms_ustackdepth =
3327 dtrace_getustackdepth();
3328 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3330 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3332 return (mstate->dtms_ustackdepth);
3334 case DIF_VAR_CALLER:
3335 if (!dtrace_priv_kernel(state))
3337 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3338 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3340 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3342 * If this is an unanchored probe, we are
3343 * required to go through the slow path:
3344 * dtrace_caller() only guarantees correct
3345 * results for anchored probes.
3347 pc_t caller[2] = {0, 0};
3349 dtrace_getpcstack(caller, 2, aframes,
3350 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3351 mstate->dtms_caller = caller[1];
3352 } else if ((mstate->dtms_caller =
3353 dtrace_caller(aframes)) == -1) {
3355 * We have failed to do this the quick way;
3356 * we must resort to the slower approach of
3357 * calling dtrace_getpcstack().
3361 dtrace_getpcstack(&caller, 1, aframes, NULL);
3362 mstate->dtms_caller = caller;
3365 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3367 return (mstate->dtms_caller);
3369 case DIF_VAR_UCALLER:
3370 if (!dtrace_priv_proc(state))
3373 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3377 * dtrace_getupcstack() fills in the first uint64_t
3378 * with the current PID. The second uint64_t will
3379 * be the program counter at user-level. The third
3380 * uint64_t will contain the caller, which is what
3384 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3385 dtrace_getupcstack(ustack, 3);
3386 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3387 mstate->dtms_ucaller = ustack[2];
3388 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3391 return (mstate->dtms_ucaller);
3393 case DIF_VAR_PROBEPROV:
3394 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3395 return (dtrace_dif_varstr(
3396 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3399 case DIF_VAR_PROBEMOD:
3400 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3401 return (dtrace_dif_varstr(
3402 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3405 case DIF_VAR_PROBEFUNC:
3406 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3407 return (dtrace_dif_varstr(
3408 (uintptr_t)mstate->dtms_probe->dtpr_func,
3411 case DIF_VAR_PROBENAME:
3412 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3413 return (dtrace_dif_varstr(
3414 (uintptr_t)mstate->dtms_probe->dtpr_name,
3418 if (!dtrace_priv_proc(state))
3423 * Note that we are assuming that an unanchored probe is
3424 * always due to a high-level interrupt. (And we're assuming
3425 * that there is only a single high level interrupt.)
3427 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3428 return (pid0.pid_id);
3431 * It is always safe to dereference one's own t_procp pointer:
3432 * it always points to a valid, allocated proc structure.
3433 * Further, it is always safe to dereference the p_pidp member
3434 * of one's own proc structure. (These are truisms becuase
3435 * threads and processes don't clean up their own state --
3436 * they leave that task to whomever reaps them.)
3438 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3440 return ((uint64_t)curproc->p_pid);
3444 if (!dtrace_priv_proc(state))
3449 * See comment in DIF_VAR_PID.
3451 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3452 return (pid0.pid_id);
3455 * It is always safe to dereference one's own t_procp pointer:
3456 * it always points to a valid, allocated proc structure.
3457 * (This is true because threads don't clean up their own
3458 * state -- they leave that task to whomever reaps them.)
3460 return ((uint64_t)curthread->t_procp->p_ppid);
3462 if (curproc->p_pid == proc0.p_pid)
3463 return (curproc->p_pid);
3465 return (curproc->p_pptr->p_pid);
3471 * See comment in DIF_VAR_PID.
3473 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3477 return ((uint64_t)curthread->t_tid);
3479 case DIF_VAR_EXECARGS: {
3480 struct pargs *p_args = curthread->td_proc->p_args;
3485 return (dtrace_dif_varstrz(
3486 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3489 case DIF_VAR_EXECNAME:
3491 if (!dtrace_priv_proc(state))
3495 * See comment in DIF_VAR_PID.
3497 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3498 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3501 * It is always safe to dereference one's own t_procp pointer:
3502 * it always points to a valid, allocated proc structure.
3503 * (This is true because threads don't clean up their own
3504 * state -- they leave that task to whomever reaps them.)
3506 return (dtrace_dif_varstr(
3507 (uintptr_t)curthread->t_procp->p_user.u_comm,
3510 return (dtrace_dif_varstr(
3511 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3514 case DIF_VAR_ZONENAME:
3516 if (!dtrace_priv_proc(state))
3520 * See comment in DIF_VAR_PID.
3522 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3523 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3526 * It is always safe to dereference one's own t_procp pointer:
3527 * it always points to a valid, allocated proc structure.
3528 * (This is true because threads don't clean up their own
3529 * state -- they leave that task to whomever reaps them.)
3531 return (dtrace_dif_varstr(
3532 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3539 if (!dtrace_priv_proc(state))
3544 * See comment in DIF_VAR_PID.
3546 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3547 return ((uint64_t)p0.p_cred->cr_uid);
3550 * It is always safe to dereference one's own t_procp pointer:
3551 * it always points to a valid, allocated proc structure.
3552 * (This is true because threads don't clean up their own
3553 * state -- they leave that task to whomever reaps them.)
3555 * Additionally, it is safe to dereference one's own process
3556 * credential, since this is never NULL after process birth.
3558 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3560 return ((uint64_t)curthread->td_ucred->cr_uid);
3564 if (!dtrace_priv_proc(state))
3569 * See comment in DIF_VAR_PID.
3571 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3572 return ((uint64_t)p0.p_cred->cr_gid);
3575 * It is always safe to dereference one's own t_procp pointer:
3576 * it always points to a valid, allocated proc structure.
3577 * (This is true because threads don't clean up their own
3578 * state -- they leave that task to whomever reaps them.)
3580 * Additionally, it is safe to dereference one's own process
3581 * credential, since this is never NULL after process birth.
3583 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3585 return ((uint64_t)curthread->td_ucred->cr_gid);
3588 case DIF_VAR_ERRNO: {
3591 if (!dtrace_priv_proc(state))
3595 * See comment in DIF_VAR_PID.
3597 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3601 * It is always safe to dereference one's own t_lwp pointer in
3602 * the event that this pointer is non-NULL. (This is true
3603 * because threads and lwps don't clean up their own state --
3604 * they leave that task to whomever reaps them.)
3606 if ((lwp = curthread->t_lwp) == NULL)
3609 return ((uint64_t)lwp->lwp_errno);
3611 return (curthread->td_errno);
3620 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3626 typedef enum dtrace_json_state {
3627 DTRACE_JSON_REST = 1,
3630 DTRACE_JSON_STRING_ESCAPE,
3631 DTRACE_JSON_STRING_ESCAPE_UNICODE,
3635 DTRACE_JSON_IDENTIFIER,
3637 DTRACE_JSON_NUMBER_FRAC,
3638 DTRACE_JSON_NUMBER_EXP,
3639 DTRACE_JSON_COLLECT_OBJECT
3640 } dtrace_json_state_t;
3643 * This function possesses just enough knowledge about JSON to extract a single
3644 * value from a JSON string and store it in the scratch buffer. It is able
3645 * to extract nested object values, and members of arrays by index.
3647 * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3648 * be looked up as we descend into the object tree. e.g.
3650 * foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3653 * The run time of this function must be bounded above by strsize to limit the
3654 * amount of work done in probe context. As such, it is implemented as a
3655 * simple state machine, reading one character at a time using safe loads
3656 * until we find the requested element, hit a parsing error or run off the
3657 * end of the object or string.
3659 * As there is no way for a subroutine to return an error without interrupting
3660 * clause execution, we simply return NULL in the event of a missing key or any
3661 * other error condition. Each NULL return in this function is commented with
3662 * the error condition it represents -- parsing or otherwise.
3664 * The set of states for the state machine closely matches the JSON
3665 * specification (http://json.org/). Briefly:
3668 * Skip whitespace until we find either a top-level Object, moving
3669 * to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3671 * DTRACE_JSON_OBJECT:
3672 * Locate the next key String in an Object. Sets a flag to denote
3673 * the next String as a key string and moves to DTRACE_JSON_STRING.
3675 * DTRACE_JSON_COLON:
3676 * Skip whitespace until we find the colon that separates key Strings
3677 * from their values. Once found, move to DTRACE_JSON_VALUE.
3679 * DTRACE_JSON_VALUE:
3680 * Detects the type of the next value (String, Number, Identifier, Object
3681 * or Array) and routes to the states that process that type. Here we also
3682 * deal with the element selector list if we are requested to traverse down
3683 * into the object tree.
3685 * DTRACE_JSON_COMMA:
3686 * Skip whitespace until we find the comma that separates key-value pairs
3687 * in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3688 * (similarly DTRACE_JSON_VALUE). All following literal value processing
3689 * states return to this state at the end of their value, unless otherwise
3692 * DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3693 * Processes a Number literal from the JSON, including any exponent
3694 * component that may be present. Numbers are returned as strings, which
3695 * may be passed to strtoll() if an integer is required.
3697 * DTRACE_JSON_IDENTIFIER:
3698 * Processes a "true", "false" or "null" literal in the JSON.
3700 * DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3701 * DTRACE_JSON_STRING_ESCAPE_UNICODE:
3702 * Processes a String literal from the JSON, whether the String denotes
3703 * a key, a value or part of a larger Object. Handles all escape sequences
3704 * present in the specification, including four-digit unicode characters,
3705 * but merely includes the escape sequence without converting it to the
3706 * actual escaped character. If the String is flagged as a key, we
3707 * move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3709 * DTRACE_JSON_COLLECT_OBJECT:
3710 * This state collects an entire Object (or Array), correctly handling
3711 * embedded strings. If the full element selector list matches this nested
3712 * object, we return the Object in full as a string. If not, we use this
3713 * state to skip to the next value at this level and continue processing.
3715 * NOTE: This function uses various macros from strtolctype.h to manipulate
3716 * digit values, etc -- these have all been checked to ensure they make
3717 * no additional function calls.
3720 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3723 dtrace_json_state_t state = DTRACE_JSON_REST;
3724 int64_t array_elem = INT64_MIN;
3725 int64_t array_pos = 0;
3726 uint8_t escape_unicount = 0;
3727 boolean_t string_is_key = B_FALSE;
3728 boolean_t collect_object = B_FALSE;
3729 boolean_t found_key = B_FALSE;
3730 boolean_t in_array = B_FALSE;
3731 uint32_t braces = 0, brackets = 0;
3732 char *elem = elemlist;
3736 for (cur = json; cur < json + size; cur++) {
3737 char cc = dtrace_load8(cur);
3742 case DTRACE_JSON_REST:
3747 state = DTRACE_JSON_OBJECT;
3754 array_elem = dtrace_strtoll(elem, 10, size);
3755 found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3756 state = DTRACE_JSON_VALUE;
3761 * ERROR: expected to find a top-level object or array.
3764 case DTRACE_JSON_OBJECT:
3769 state = DTRACE_JSON_STRING;
3770 string_is_key = B_TRUE;
3775 * ERROR: either the object did not start with a key
3776 * string, or we've run off the end of the object
3777 * without finding the requested key.
3780 case DTRACE_JSON_STRING:
3783 state = DTRACE_JSON_STRING_ESCAPE;
3788 if (collect_object) {
3790 * We don't reset the dest here, as
3791 * the string is part of a larger
3792 * object being collected.
3795 collect_object = B_FALSE;
3796 state = DTRACE_JSON_COLLECT_OBJECT;
3800 dd = dest; /* reset string buffer */
3801 if (string_is_key) {
3802 if (dtrace_strncmp(dest, elem,
3805 } else if (found_key) {
3808 * We expected an object, not
3815 state = string_is_key ? DTRACE_JSON_COLON :
3817 string_is_key = B_FALSE;
3823 case DTRACE_JSON_STRING_ESCAPE:
3826 escape_unicount = 0;
3827 state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3829 state = DTRACE_JSON_STRING;
3832 case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3833 if (!isxdigit(cc)) {
3835 * ERROR: invalid unicode escape, expected
3836 * four valid hexidecimal digits.
3842 if (++escape_unicount == 4)
3843 state = DTRACE_JSON_STRING;
3845 case DTRACE_JSON_COLON:
3850 state = DTRACE_JSON_VALUE;
3855 * ERROR: expected a colon.
3858 case DTRACE_JSON_COMMA:
3864 state = DTRACE_JSON_VALUE;
3865 if (++array_pos == array_elem)
3868 state = DTRACE_JSON_OBJECT;
3874 * ERROR: either we hit an unexpected character, or
3875 * we reached the end of the object or array without
3876 * finding the requested key.
3879 case DTRACE_JSON_IDENTIFIER:
3886 dd = dest; /* reset string buffer */
3888 if (dtrace_strncmp(dest, "true", 5) == 0 ||
3889 dtrace_strncmp(dest, "false", 6) == 0 ||
3890 dtrace_strncmp(dest, "null", 5) == 0) {
3894 * ERROR: We expected an object,
3895 * not this identifier.
3902 state = DTRACE_JSON_COMMA;
3908 * ERROR: we did not recognise the identifier as one
3909 * of those in the JSON specification.
3912 case DTRACE_JSON_NUMBER:
3915 state = DTRACE_JSON_NUMBER_FRAC;
3919 if (cc == 'x' || cc == 'X') {
3921 * ERROR: specification explicitly excludes
3922 * hexidecimal or octal numbers.
3928 case DTRACE_JSON_NUMBER_FRAC:
3929 if (cc == 'e' || cc == 'E') {
3931 state = DTRACE_JSON_NUMBER_EXP;
3935 if (cc == '+' || cc == '-') {
3937 * ERROR: expect sign as part of exponent only.
3942 case DTRACE_JSON_NUMBER_EXP:
3943 if (isdigit(cc) || cc == '+' || cc == '-') {
3949 dd = dest; /* reset string buffer */
3953 * ERROR: We expected an object, not
3962 state = DTRACE_JSON_COMMA;
3964 case DTRACE_JSON_VALUE:
3968 if (cc == '{' || cc == '[') {
3969 if (nelems > 1 && found_key) {
3970 in_array = cc == '[' ? B_TRUE : B_FALSE;
3972 * If our element selector directs us
3973 * to descend into this nested object,
3974 * then move to the next selector
3975 * element in the list and restart the
3978 while (*elem != '\0')
3980 elem++; /* skip the inter-element NUL */
3984 state = DTRACE_JSON_VALUE;
3986 array_elem = dtrace_strtoll(
3988 found_key = array_elem == 0 ?
3991 found_key = B_FALSE;
3992 state = DTRACE_JSON_OBJECT;
3998 * Otherwise, we wish to either skip this
3999 * nested object or return it in full.
4006 state = DTRACE_JSON_COLLECT_OBJECT;
4011 state = DTRACE_JSON_STRING;
4017 * Here we deal with true, false and null.
4020 state = DTRACE_JSON_IDENTIFIER;
4024 if (cc == '-' || isdigit(cc)) {
4026 state = DTRACE_JSON_NUMBER;
4031 * ERROR: unexpected character at start of value.
4034 case DTRACE_JSON_COLLECT_OBJECT:
4037 * ERROR: unexpected end of input.
4043 collect_object = B_TRUE;
4044 state = DTRACE_JSON_STRING;
4049 if (brackets-- == 0) {
4051 * ERROR: unbalanced brackets.
4055 } else if (cc == '}') {
4056 if (braces-- == 0) {
4058 * ERROR: unbalanced braces.
4062 } else if (cc == '{') {
4064 } else if (cc == '[') {
4068 if (brackets == 0 && braces == 0) {
4073 dd = dest; /* reset string buffer */
4074 state = DTRACE_JSON_COMMA;
4083 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4084 * Notice that we don't bother validating the proper number of arguments or
4085 * their types in the tuple stack. This isn't needed because all argument
4086 * interpretation is safe because of our load safety -- the worst that can
4087 * happen is that a bogus program can obtain bogus results.
4090 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4091 dtrace_key_t *tupregs, int nargs,
4092 dtrace_mstate_t *mstate, dtrace_state_t *state)
4094 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4095 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4096 dtrace_vstate_t *vstate = &state->dts_vstate;
4109 struct thread *lowner;
4111 struct lock_object *li;
4118 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4122 case DIF_SUBR_MUTEX_OWNED:
4123 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4129 m.mx = dtrace_load64(tupregs[0].dttk_value);
4130 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4131 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4133 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4136 case DIF_SUBR_MUTEX_OWNER:
4137 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4143 m.mx = dtrace_load64(tupregs[0].dttk_value);
4144 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4145 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4146 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4151 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4152 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4158 m.mx = dtrace_load64(tupregs[0].dttk_value);
4159 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4162 case DIF_SUBR_MUTEX_TYPE_SPIN:
4163 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4169 m.mx = dtrace_load64(tupregs[0].dttk_value);
4170 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4173 case DIF_SUBR_RW_READ_HELD: {
4176 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4182 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4183 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4187 case DIF_SUBR_RW_WRITE_HELD:
4188 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4194 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4195 regs[rd] = _RW_WRITE_HELD(&r.ri);
4198 case DIF_SUBR_RW_ISWRITER:
4199 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4205 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4206 regs[rd] = _RW_ISWRITER(&r.ri);
4209 #else /* !illumos */
4210 case DIF_SUBR_MUTEX_OWNED:
4211 if (!dtrace_canload(tupregs[0].dttk_value,
4212 sizeof (struct lock_object), mstate, vstate)) {
4216 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4217 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4220 case DIF_SUBR_MUTEX_OWNER:
4221 if (!dtrace_canload(tupregs[0].dttk_value,
4222 sizeof (struct lock_object), mstate, vstate)) {
4226 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4227 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4228 regs[rd] = (uintptr_t)lowner;
4231 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4232 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4237 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4238 /* XXX - should be only LC_SLEEPABLE? */
4239 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
4240 (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
4243 case DIF_SUBR_MUTEX_TYPE_SPIN:
4244 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4249 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4250 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4253 case DIF_SUBR_RW_READ_HELD:
4254 case DIF_SUBR_SX_SHARED_HELD:
4255 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4260 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4261 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4265 case DIF_SUBR_RW_WRITE_HELD:
4266 case DIF_SUBR_SX_EXCLUSIVE_HELD:
4267 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4272 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4273 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4274 regs[rd] = (lowner == curthread);
4277 case DIF_SUBR_RW_ISWRITER:
4278 case DIF_SUBR_SX_ISEXCLUSIVE:
4279 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4284 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4285 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4288 #endif /* illumos */
4290 case DIF_SUBR_BCOPY: {
4292 * We need to be sure that the destination is in the scratch
4293 * region -- no other region is allowed.
4295 uintptr_t src = tupregs[0].dttk_value;
4296 uintptr_t dest = tupregs[1].dttk_value;
4297 size_t size = tupregs[2].dttk_value;
4299 if (!dtrace_inscratch(dest, size, mstate)) {
4300 *flags |= CPU_DTRACE_BADADDR;
4305 if (!dtrace_canload(src, size, mstate, vstate)) {
4310 dtrace_bcopy((void *)src, (void *)dest, size);
4314 case DIF_SUBR_ALLOCA:
4315 case DIF_SUBR_COPYIN: {
4316 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4318 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4319 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4322 * This action doesn't require any credential checks since
4323 * probes will not activate in user contexts to which the
4324 * enabling user does not have permissions.
4328 * Rounding up the user allocation size could have overflowed
4329 * a large, bogus allocation (like -1ULL) to 0.
4331 if (scratch_size < size ||
4332 !DTRACE_INSCRATCH(mstate, scratch_size)) {
4333 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4338 if (subr == DIF_SUBR_COPYIN) {
4339 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4340 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4341 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4344 mstate->dtms_scratch_ptr += scratch_size;
4349 case DIF_SUBR_COPYINTO: {
4350 uint64_t size = tupregs[1].dttk_value;
4351 uintptr_t dest = tupregs[2].dttk_value;
4354 * This action doesn't require any credential checks since
4355 * probes will not activate in user contexts to which the
4356 * enabling user does not have permissions.
4358 if (!dtrace_inscratch(dest, size, mstate)) {
4359 *flags |= CPU_DTRACE_BADADDR;
4364 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4365 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4366 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4370 case DIF_SUBR_COPYINSTR: {
4371 uintptr_t dest = mstate->dtms_scratch_ptr;
4372 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4374 if (nargs > 1 && tupregs[1].dttk_value < size)
4375 size = tupregs[1].dttk_value + 1;
4378 * This action doesn't require any credential checks since
4379 * probes will not activate in user contexts to which the
4380 * enabling user does not have permissions.
4382 if (!DTRACE_INSCRATCH(mstate, size)) {
4383 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4388 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4389 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4390 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4392 ((char *)dest)[size - 1] = '\0';
4393 mstate->dtms_scratch_ptr += size;
4399 case DIF_SUBR_MSGSIZE:
4400 case DIF_SUBR_MSGDSIZE: {
4401 uintptr_t baddr = tupregs[0].dttk_value, daddr;
4402 uintptr_t wptr, rptr;
4406 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4408 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4414 wptr = dtrace_loadptr(baddr +
4415 offsetof(mblk_t, b_wptr));
4417 rptr = dtrace_loadptr(baddr +
4418 offsetof(mblk_t, b_rptr));
4421 *flags |= CPU_DTRACE_BADADDR;
4422 *illval = tupregs[0].dttk_value;
4426 daddr = dtrace_loadptr(baddr +
4427 offsetof(mblk_t, b_datap));
4429 baddr = dtrace_loadptr(baddr +
4430 offsetof(mblk_t, b_cont));
4433 * We want to prevent against denial-of-service here,
4434 * so we're only going to search the list for
4435 * dtrace_msgdsize_max mblks.
4437 if (cont++ > dtrace_msgdsize_max) {
4438 *flags |= CPU_DTRACE_ILLOP;
4442 if (subr == DIF_SUBR_MSGDSIZE) {
4443 if (dtrace_load8(daddr +
4444 offsetof(dblk_t, db_type)) != M_DATA)
4448 count += wptr - rptr;
4451 if (!(*flags & CPU_DTRACE_FAULT))
4458 case DIF_SUBR_PROGENYOF: {
4459 pid_t pid = tupregs[0].dttk_value;
4463 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4465 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4467 if (p->p_pidp->pid_id == pid) {
4469 if (p->p_pid == pid) {
4476 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4482 case DIF_SUBR_SPECULATION:
4483 regs[rd] = dtrace_speculation(state);
4486 case DIF_SUBR_COPYOUT: {
4487 uintptr_t kaddr = tupregs[0].dttk_value;
4488 uintptr_t uaddr = tupregs[1].dttk_value;
4489 uint64_t size = tupregs[2].dttk_value;
4491 if (!dtrace_destructive_disallow &&
4492 dtrace_priv_proc_control(state) &&
4493 !dtrace_istoxic(kaddr, size) &&
4494 dtrace_canload(kaddr, size, mstate, vstate)) {
4495 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4496 dtrace_copyout(kaddr, uaddr, size, flags);
4497 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4502 case DIF_SUBR_COPYOUTSTR: {
4503 uintptr_t kaddr = tupregs[0].dttk_value;
4504 uintptr_t uaddr = tupregs[1].dttk_value;
4505 uint64_t size = tupregs[2].dttk_value;
4507 if (!dtrace_destructive_disallow &&
4508 dtrace_priv_proc_control(state) &&
4509 !dtrace_istoxic(kaddr, size) &&
4510 dtrace_strcanload(kaddr, size, mstate, vstate)) {
4511 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4512 dtrace_copyoutstr(kaddr, uaddr, size, flags);
4513 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4518 case DIF_SUBR_STRLEN: {
4520 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4521 sz = dtrace_strlen((char *)addr,
4522 state->dts_options[DTRACEOPT_STRSIZE]);
4524 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4534 case DIF_SUBR_STRCHR:
4535 case DIF_SUBR_STRRCHR: {
4537 * We're going to iterate over the string looking for the
4538 * specified character. We will iterate until we have reached
4539 * the string length or we have found the character. If this
4540 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4541 * of the specified character instead of the first.
4543 uintptr_t saddr = tupregs[0].dttk_value;
4544 uintptr_t addr = tupregs[0].dttk_value;
4545 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4546 char c, target = (char)tupregs[1].dttk_value;
4548 for (regs[rd] = 0; addr < limit; addr++) {
4549 if ((c = dtrace_load8(addr)) == target) {
4552 if (subr == DIF_SUBR_STRCHR)
4560 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4568 case DIF_SUBR_STRSTR:
4569 case DIF_SUBR_INDEX:
4570 case DIF_SUBR_RINDEX: {
4572 * We're going to iterate over the string looking for the
4573 * specified string. We will iterate until we have reached
4574 * the string length or we have found the string. (Yes, this
4575 * is done in the most naive way possible -- but considering
4576 * that the string we're searching for is likely to be
4577 * relatively short, the complexity of Rabin-Karp or similar
4578 * hardly seems merited.)
4580 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4581 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4582 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4583 size_t len = dtrace_strlen(addr, size);
4584 size_t sublen = dtrace_strlen(substr, size);
4585 char *limit = addr + len, *orig = addr;
4586 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4589 regs[rd] = notfound;
4591 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4596 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4603 * strstr() and index()/rindex() have similar semantics if
4604 * both strings are the empty string: strstr() returns a
4605 * pointer to the (empty) string, and index() and rindex()
4606 * both return index 0 (regardless of any position argument).
4608 if (sublen == 0 && len == 0) {
4609 if (subr == DIF_SUBR_STRSTR)
4610 regs[rd] = (uintptr_t)addr;
4616 if (subr != DIF_SUBR_STRSTR) {
4617 if (subr == DIF_SUBR_RINDEX) {
4624 * Both index() and rindex() take an optional position
4625 * argument that denotes the starting position.
4628 int64_t pos = (int64_t)tupregs[2].dttk_value;
4631 * If the position argument to index() is
4632 * negative, Perl implicitly clamps it at
4633 * zero. This semantic is a little surprising
4634 * given the special meaning of negative
4635 * positions to similar Perl functions like
4636 * substr(), but it appears to reflect a
4637 * notion that index() can start from a
4638 * negative index and increment its way up to
4639 * the string. Given this notion, Perl's
4640 * rindex() is at least self-consistent in
4641 * that it implicitly clamps positions greater
4642 * than the string length to be the string
4643 * length. Where Perl completely loses
4644 * coherence, however, is when the specified
4645 * substring is the empty string (""). In
4646 * this case, even if the position is
4647 * negative, rindex() returns 0 -- and even if
4648 * the position is greater than the length,
4649 * index() returns the string length. These
4650 * semantics violate the notion that index()
4651 * should never return a value less than the
4652 * specified position and that rindex() should
4653 * never return a value greater than the
4654 * specified position. (One assumes that
4655 * these semantics are artifacts of Perl's
4656 * implementation and not the results of
4657 * deliberate design -- it beggars belief that
4658 * even Larry Wall could desire such oddness.)
4659 * While in the abstract one would wish for
4660 * consistent position semantics across
4661 * substr(), index() and rindex() -- or at the
4662 * very least self-consistent position
4663 * semantics for index() and rindex() -- we
4664 * instead opt to keep with the extant Perl
4665 * semantics, in all their broken glory. (Do
4666 * we have more desire to maintain Perl's
4667 * semantics than Perl does? Probably.)
4669 if (subr == DIF_SUBR_RINDEX) {
4693 for (regs[rd] = notfound; addr != limit; addr += inc) {
4694 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4695 if (subr != DIF_SUBR_STRSTR) {
4697 * As D index() and rindex() are
4698 * modeled on Perl (and not on awk),
4699 * we return a zero-based (and not a
4700 * one-based) index. (For you Perl
4701 * weenies: no, we're not going to add
4702 * $[ -- and shouldn't you be at a con
4705 regs[rd] = (uintptr_t)(addr - orig);
4709 ASSERT(subr == DIF_SUBR_STRSTR);
4710 regs[rd] = (uintptr_t)addr;
4718 case DIF_SUBR_STRTOK: {
4719 uintptr_t addr = tupregs[0].dttk_value;
4720 uintptr_t tokaddr = tupregs[1].dttk_value;
4721 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4722 uintptr_t limit, toklimit = tokaddr + size;
4723 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
4724 char *dest = (char *)mstate->dtms_scratch_ptr;
4728 * Check both the token buffer and (later) the input buffer,
4729 * since both could be non-scratch addresses.
4731 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4736 if (!DTRACE_INSCRATCH(mstate, size)) {
4737 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4744 * If the address specified is NULL, we use our saved
4745 * strtok pointer from the mstate. Note that this
4746 * means that the saved strtok pointer is _only_
4747 * valid within multiple enablings of the same probe --
4748 * it behaves like an implicit clause-local variable.
4750 addr = mstate->dtms_strtok;
4753 * If the user-specified address is non-NULL we must
4754 * access check it. This is the only time we have
4755 * a chance to do so, since this address may reside
4756 * in the string table of this clause-- future calls
4757 * (when we fetch addr from mstate->dtms_strtok)
4758 * would fail this access check.
4760 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4767 * First, zero the token map, and then process the token
4768 * string -- setting a bit in the map for every character
4769 * found in the token string.
4771 for (i = 0; i < sizeof (tokmap); i++)
4774 for (; tokaddr < toklimit; tokaddr++) {
4775 if ((c = dtrace_load8(tokaddr)) == '\0')
4778 ASSERT((c >> 3) < sizeof (tokmap));
4779 tokmap[c >> 3] |= (1 << (c & 0x7));
4782 for (limit = addr + size; addr < limit; addr++) {
4784 * We're looking for a character that is _not_ contained
4785 * in the token string.
4787 if ((c = dtrace_load8(addr)) == '\0')
4790 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4796 * We reached the end of the string without finding
4797 * any character that was not in the token string.
4798 * We return NULL in this case, and we set the saved
4799 * address to NULL as well.
4802 mstate->dtms_strtok = 0;
4807 * From here on, we're copying into the destination string.
4809 for (i = 0; addr < limit && i < size - 1; addr++) {
4810 if ((c = dtrace_load8(addr)) == '\0')
4813 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4822 regs[rd] = (uintptr_t)dest;
4823 mstate->dtms_scratch_ptr += size;
4824 mstate->dtms_strtok = addr;
4828 case DIF_SUBR_SUBSTR: {
4829 uintptr_t s = tupregs[0].dttk_value;
4830 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4831 char *d = (char *)mstate->dtms_scratch_ptr;
4832 int64_t index = (int64_t)tupregs[1].dttk_value;
4833 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4834 size_t len = dtrace_strlen((char *)s, size);
4837 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4842 if (!DTRACE_INSCRATCH(mstate, size)) {
4843 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4849 remaining = (int64_t)size;
4854 if (index < 0 && index + remaining > 0) {
4860 if (index >= len || index < 0) {
4862 } else if (remaining < 0) {
4863 remaining += len - index;
4864 } else if (index + remaining > size) {
4865 remaining = size - index;
4868 for (i = 0; i < remaining; i++) {
4869 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4875 mstate->dtms_scratch_ptr += size;
4876 regs[rd] = (uintptr_t)d;
4880 case DIF_SUBR_JSON: {
4881 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4882 uintptr_t json = tupregs[0].dttk_value;
4883 size_t jsonlen = dtrace_strlen((char *)json, size);
4884 uintptr_t elem = tupregs[1].dttk_value;
4885 size_t elemlen = dtrace_strlen((char *)elem, size);
4887 char *dest = (char *)mstate->dtms_scratch_ptr;
4888 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4889 char *ee = elemlist;
4893 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4894 !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4899 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4900 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4906 * Read the element selector and split it up into a packed list
4909 for (cur = elem; cur < elem + elemlen; cur++) {
4910 char cc = dtrace_load8(cur);
4912 if (cur == elem && cc == '[') {
4914 * If the first element selector key is
4915 * actually an array index then ignore the
4924 if (cc == '.' || cc == '[') {
4933 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4934 nelems, dest)) != 0)
4935 mstate->dtms_scratch_ptr += jsonlen + 1;
4939 case DIF_SUBR_TOUPPER:
4940 case DIF_SUBR_TOLOWER: {
4941 uintptr_t s = tupregs[0].dttk_value;
4942 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4943 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4944 size_t len = dtrace_strlen((char *)s, size);
4945 char lower, upper, convert;
4948 if (subr == DIF_SUBR_TOUPPER) {
4958 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4963 if (!DTRACE_INSCRATCH(mstate, size)) {
4964 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4969 for (i = 0; i < size - 1; i++) {
4970 if ((c = dtrace_load8(s + i)) == '\0')
4973 if (c >= lower && c <= upper)
4974 c = convert + (c - lower);
4981 regs[rd] = (uintptr_t)dest;
4982 mstate->dtms_scratch_ptr += size;
4987 case DIF_SUBR_GETMAJOR:
4989 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4991 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4995 case DIF_SUBR_GETMINOR:
4997 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4999 regs[rd] = tupregs[0].dttk_value & MAXMIN;
5003 case DIF_SUBR_DDI_PATHNAME: {
5005 * This one is a galactic mess. We are going to roughly
5006 * emulate ddi_pathname(), but it's made more complicated
5007 * by the fact that we (a) want to include the minor name and
5008 * (b) must proceed iteratively instead of recursively.
5010 uintptr_t dest = mstate->dtms_scratch_ptr;
5011 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5012 char *start = (char *)dest, *end = start + size - 1;
5013 uintptr_t daddr = tupregs[0].dttk_value;
5014 int64_t minor = (int64_t)tupregs[1].dttk_value;
5016 int i, len, depth = 0;
5019 * Due to all the pointer jumping we do and context we must
5020 * rely upon, we just mandate that the user must have kernel
5021 * read privileges to use this routine.
5023 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5024 *flags |= CPU_DTRACE_KPRIV;
5029 if (!DTRACE_INSCRATCH(mstate, size)) {
5030 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5038 * We want to have a name for the minor. In order to do this,
5039 * we need to walk the minor list from the devinfo. We want
5040 * to be sure that we don't infinitely walk a circular list,
5041 * so we check for circularity by sending a scout pointer
5042 * ahead two elements for every element that we iterate over;
5043 * if the list is circular, these will ultimately point to the
5044 * same element. You may recognize this little trick as the
5045 * answer to a stupid interview question -- one that always
5046 * seems to be asked by those who had to have it laboriously
5047 * explained to them, and who can't even concisely describe
5048 * the conditions under which one would be forced to resort to
5049 * this technique. Needless to say, those conditions are
5050 * found here -- and probably only here. Is this the only use
5051 * of this infamous trick in shipping, production code? If it
5052 * isn't, it probably should be...
5055 uintptr_t maddr = dtrace_loadptr(daddr +
5056 offsetof(struct dev_info, devi_minor));
5058 uintptr_t next = offsetof(struct ddi_minor_data, next);
5059 uintptr_t name = offsetof(struct ddi_minor_data,
5060 d_minor) + offsetof(struct ddi_minor, name);
5061 uintptr_t dev = offsetof(struct ddi_minor_data,
5062 d_minor) + offsetof(struct ddi_minor, dev);
5066 scout = dtrace_loadptr(maddr + next);
5068 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5071 m = dtrace_load64(maddr + dev) & MAXMIN64;
5073 m = dtrace_load32(maddr + dev) & MAXMIN;
5076 maddr = dtrace_loadptr(maddr + next);
5081 scout = dtrace_loadptr(scout + next);
5086 scout = dtrace_loadptr(scout + next);
5091 if (scout == maddr) {
5092 *flags |= CPU_DTRACE_ILLOP;
5100 * We have the minor data. Now we need to
5101 * copy the minor's name into the end of the
5104 s = (char *)dtrace_loadptr(maddr + name);
5105 len = dtrace_strlen(s, size);
5107 if (*flags & CPU_DTRACE_FAULT)
5111 if ((end -= (len + 1)) < start)
5117 for (i = 1; i <= len; i++)
5118 end[i] = dtrace_load8((uintptr_t)s++);
5123 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5124 ddi_node_state_t devi_state;
5126 devi_state = dtrace_load32(daddr +
5127 offsetof(struct dev_info, devi_node_state));
5129 if (*flags & CPU_DTRACE_FAULT)
5132 if (devi_state >= DS_INITIALIZED) {
5133 s = (char *)dtrace_loadptr(daddr +
5134 offsetof(struct dev_info, devi_addr));
5135 len = dtrace_strlen(s, size);
5137 if (*flags & CPU_DTRACE_FAULT)
5141 if ((end -= (len + 1)) < start)
5147 for (i = 1; i <= len; i++)
5148 end[i] = dtrace_load8((uintptr_t)s++);
5152 * Now for the node name...
5154 s = (char *)dtrace_loadptr(daddr +
5155 offsetof(struct dev_info, devi_node_name));
5157 daddr = dtrace_loadptr(daddr +
5158 offsetof(struct dev_info, devi_parent));
5161 * If our parent is NULL (that is, if we're the root
5162 * node), we're going to use the special path
5168 len = dtrace_strlen(s, size);
5169 if (*flags & CPU_DTRACE_FAULT)
5172 if ((end -= (len + 1)) < start)
5175 for (i = 1; i <= len; i++)
5176 end[i] = dtrace_load8((uintptr_t)s++);
5179 if (depth++ > dtrace_devdepth_max) {
5180 *flags |= CPU_DTRACE_ILLOP;
5186 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5189 regs[rd] = (uintptr_t)end;
5190 mstate->dtms_scratch_ptr += size;
5197 case DIF_SUBR_STRJOIN: {
5198 char *d = (char *)mstate->dtms_scratch_ptr;
5199 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5200 uintptr_t s1 = tupregs[0].dttk_value;
5201 uintptr_t s2 = tupregs[1].dttk_value;
5204 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
5205 !dtrace_strcanload(s2, size, mstate, vstate)) {
5210 if (!DTRACE_INSCRATCH(mstate, size)) {
5211 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5218 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5223 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
5231 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5236 if ((d[i++] = dtrace_load8(s2++)) == '\0')
5241 mstate->dtms_scratch_ptr += i;
5242 regs[rd] = (uintptr_t)d;
5248 case DIF_SUBR_STRTOLL: {
5249 uintptr_t s = tupregs[0].dttk_value;
5250 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5254 if ((base = tupregs[1].dttk_value) <= 1 ||
5255 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5256 *flags |= CPU_DTRACE_ILLOP;
5261 if (!dtrace_strcanload(s, size, mstate, vstate)) {
5262 regs[rd] = INT64_MIN;
5266 regs[rd] = dtrace_strtoll((char *)s, base, size);
5270 case DIF_SUBR_LLTOSTR: {
5271 int64_t i = (int64_t)tupregs[0].dttk_value;
5272 uint64_t val, digit;
5273 uint64_t size = 65; /* enough room for 2^64 in binary */
5274 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5278 if ((base = tupregs[1].dttk_value) <= 1 ||
5279 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5280 *flags |= CPU_DTRACE_ILLOP;
5285 val = (base == 10 && i < 0) ? i * -1 : i;
5287 if (!DTRACE_INSCRATCH(mstate, size)) {
5288 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5293 for (*end-- = '\0'; val; val /= base) {
5294 if ((digit = val % base) <= '9' - '0') {
5295 *end-- = '0' + digit;
5297 *end-- = 'a' + (digit - ('9' - '0') - 1);
5301 if (i == 0 && base == 16)
5307 if (i == 0 || base == 8 || base == 16)
5310 if (i < 0 && base == 10)
5313 regs[rd] = (uintptr_t)end + 1;
5314 mstate->dtms_scratch_ptr += size;
5318 case DIF_SUBR_HTONS:
5319 case DIF_SUBR_NTOHS:
5320 #if BYTE_ORDER == BIG_ENDIAN
5321 regs[rd] = (uint16_t)tupregs[0].dttk_value;
5323 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5328 case DIF_SUBR_HTONL:
5329 case DIF_SUBR_NTOHL:
5330 #if BYTE_ORDER == BIG_ENDIAN
5331 regs[rd] = (uint32_t)tupregs[0].dttk_value;
5333 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5338 case DIF_SUBR_HTONLL:
5339 case DIF_SUBR_NTOHLL:
5340 #if BYTE_ORDER == BIG_ENDIAN
5341 regs[rd] = (uint64_t)tupregs[0].dttk_value;
5343 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5348 case DIF_SUBR_DIRNAME:
5349 case DIF_SUBR_BASENAME: {
5350 char *dest = (char *)mstate->dtms_scratch_ptr;
5351 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5352 uintptr_t src = tupregs[0].dttk_value;
5353 int i, j, len = dtrace_strlen((char *)src, size);
5354 int lastbase = -1, firstbase = -1, lastdir = -1;
5357 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5362 if (!DTRACE_INSCRATCH(mstate, size)) {
5363 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5369 * The basename and dirname for a zero-length string is
5374 src = (uintptr_t)".";
5378 * Start from the back of the string, moving back toward the
5379 * front until we see a character that isn't a slash. That
5380 * character is the last character in the basename.
5382 for (i = len - 1; i >= 0; i--) {
5383 if (dtrace_load8(src + i) != '/')
5391 * Starting from the last character in the basename, move
5392 * towards the front until we find a slash. The character
5393 * that we processed immediately before that is the first
5394 * character in the basename.
5396 for (; i >= 0; i--) {
5397 if (dtrace_load8(src + i) == '/')
5405 * Now keep going until we find a non-slash character. That
5406 * character is the last character in the dirname.
5408 for (; i >= 0; i--) {
5409 if (dtrace_load8(src + i) != '/')
5416 ASSERT(!(lastbase == -1 && firstbase != -1));
5417 ASSERT(!(firstbase == -1 && lastdir != -1));
5419 if (lastbase == -1) {
5421 * We didn't find a non-slash character. We know that
5422 * the length is non-zero, so the whole string must be
5423 * slashes. In either the dirname or the basename
5424 * case, we return '/'.
5426 ASSERT(firstbase == -1);
5427 firstbase = lastbase = lastdir = 0;
5430 if (firstbase == -1) {
5432 * The entire string consists only of a basename
5433 * component. If we're looking for dirname, we need
5434 * to change our string to be just "."; if we're
5435 * looking for a basename, we'll just set the first
5436 * character of the basename to be 0.
5438 if (subr == DIF_SUBR_DIRNAME) {
5439 ASSERT(lastdir == -1);
5440 src = (uintptr_t)".";
5447 if (subr == DIF_SUBR_DIRNAME) {
5448 if (lastdir == -1) {
5450 * We know that we have a slash in the name --
5451 * or lastdir would be set to 0, above. And
5452 * because lastdir is -1, we know that this
5453 * slash must be the first character. (That
5454 * is, the full string must be of the form
5455 * "/basename".) In this case, the last
5456 * character of the directory name is 0.
5464 ASSERT(subr == DIF_SUBR_BASENAME);
5465 ASSERT(firstbase != -1 && lastbase != -1);
5470 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5471 dest[j] = dtrace_load8(src + i);
5474 regs[rd] = (uintptr_t)dest;
5475 mstate->dtms_scratch_ptr += size;
5479 case DIF_SUBR_GETF: {
5480 uintptr_t fd = tupregs[0].dttk_value;
5481 struct filedesc *fdp;
5484 if (!dtrace_priv_proc(state)) {
5488 fdp = curproc->p_fd;
5489 FILEDESC_SLOCK(fdp);
5490 fp = fget_locked(fdp, fd);
5491 mstate->dtms_getf = fp;
5492 regs[rd] = (uintptr_t)fp;
5493 FILEDESC_SUNLOCK(fdp);
5497 case DIF_SUBR_CLEANPATH: {
5498 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5499 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5500 uintptr_t src = tupregs[0].dttk_value;
5506 if (!dtrace_strcanload(src, size, mstate, vstate)) {
5511 if (!DTRACE_INSCRATCH(mstate, size)) {
5512 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5518 * Move forward, loading each character.
5521 c = dtrace_load8(src + i++);
5523 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
5531 c = dtrace_load8(src + i++);
5535 * We have two slashes -- we can just advance
5536 * to the next character.
5543 * This is not "." and it's not ".." -- we can
5544 * just store the "/" and this character and
5552 c = dtrace_load8(src + i++);
5556 * This is a "/./" component. We're not going
5557 * to store anything in the destination buffer;
5558 * we're just going to go to the next component.
5565 * This is not ".." -- we can just store the
5566 * "/." and this character and continue
5575 c = dtrace_load8(src + i++);
5577 if (c != '/' && c != '\0') {
5579 * This is not ".." -- it's "..[mumble]".
5580 * We'll store the "/.." and this character
5581 * and continue processing.
5591 * This is "/../" or "/..\0". We need to back up
5592 * our destination pointer until we find a "/".
5595 while (j != 0 && dest[--j] != '/')
5600 } while (c != '\0');
5605 if (mstate->dtms_getf != NULL &&
5606 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5607 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5609 * If we've done a getf() as a part of this ECB and we
5610 * don't have kernel access (and we're not in the global
5611 * zone), check if the path we cleaned up begins with
5612 * the zone's root path, and trim it off if so. Note
5613 * that this is an output cleanliness issue, not a
5614 * security issue: knowing one's zone root path does
5615 * not enable privilege escalation.
5617 if (strstr(dest, z->zone_rootpath) == dest)
5618 dest += strlen(z->zone_rootpath) - 1;
5622 regs[rd] = (uintptr_t)dest;
5623 mstate->dtms_scratch_ptr += size;
5627 case DIF_SUBR_INET_NTOA:
5628 case DIF_SUBR_INET_NTOA6:
5629 case DIF_SUBR_INET_NTOP: {
5634 if (subr == DIF_SUBR_INET_NTOP) {
5635 af = (int)tupregs[0].dttk_value;
5638 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5642 if (af == AF_INET) {
5646 if (!dtrace_canload(tupregs[argi].dttk_value,
5647 sizeof (ipaddr_t), mstate, vstate)) {
5653 * Safely load the IPv4 address.
5655 ip4 = dtrace_load32(tupregs[argi].dttk_value);
5658 * Check an IPv4 string will fit in scratch.
5660 size = INET_ADDRSTRLEN;
5661 if (!DTRACE_INSCRATCH(mstate, size)) {
5662 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5666 base = (char *)mstate->dtms_scratch_ptr;
5667 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5670 * Stringify as a dotted decimal quad.
5673 ptr8 = (uint8_t *)&ip4;
5674 for (i = 3; i >= 0; i--) {
5680 for (; val; val /= 10) {
5681 *end-- = '0' + (val % 10);
5688 ASSERT(end + 1 >= base);
5690 } else if (af == AF_INET6) {
5691 struct in6_addr ip6;
5692 int firstzero, tryzero, numzero, v6end;
5694 const char digits[] = "0123456789abcdef";
5697 * Stringify using RFC 1884 convention 2 - 16 bit
5698 * hexadecimal values with a zero-run compression.
5699 * Lower case hexadecimal digits are used.
5700 * eg, fe80::214:4fff:fe0b:76c8.
5701 * The IPv4 embedded form is returned for inet_ntop,
5702 * just the IPv4 string is returned for inet_ntoa6.
5705 if (!dtrace_canload(tupregs[argi].dttk_value,
5706 sizeof (struct in6_addr), mstate, vstate)) {
5712 * Safely load the IPv6 address.
5715 (void *)(uintptr_t)tupregs[argi].dttk_value,
5716 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5719 * Check an IPv6 string will fit in scratch.
5721 size = INET6_ADDRSTRLEN;
5722 if (!DTRACE_INSCRATCH(mstate, size)) {
5723 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5727 base = (char *)mstate->dtms_scratch_ptr;
5728 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5732 * Find the longest run of 16 bit zero values
5733 * for the single allowed zero compression - "::".
5738 for (i = 0; i < sizeof (struct in6_addr); i++) {
5740 if (ip6._S6_un._S6_u8[i] == 0 &&
5742 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5744 tryzero == -1 && i % 2 == 0) {
5749 if (tryzero != -1 &&
5751 (ip6._S6_un._S6_u8[i] != 0 ||
5753 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5755 i == sizeof (struct in6_addr) - 1)) {
5757 if (i - tryzero <= numzero) {
5762 firstzero = tryzero;
5763 numzero = i - i % 2 - tryzero;
5767 if (ip6._S6_un._S6_u8[i] == 0 &&
5769 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5771 i == sizeof (struct in6_addr) - 1)
5775 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5778 * Check for an IPv4 embedded address.
5780 v6end = sizeof (struct in6_addr) - 2;
5781 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5782 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5783 for (i = sizeof (struct in6_addr) - 1;
5784 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5785 ASSERT(end >= base);
5788 val = ip6._S6_un._S6_u8[i];
5790 val = ip6.__u6_addr.__u6_addr8[i];
5796 for (; val; val /= 10) {
5797 *end-- = '0' + val % 10;
5801 if (i > DTRACE_V4MAPPED_OFFSET)
5805 if (subr == DIF_SUBR_INET_NTOA6)
5809 * Set v6end to skip the IPv4 address that
5810 * we have already stringified.
5816 * Build the IPv6 string by working through the
5817 * address in reverse.
5819 for (i = v6end; i >= 0; i -= 2) {
5820 ASSERT(end >= base);
5822 if (i == firstzero + numzero - 2) {
5829 if (i < 14 && i != firstzero - 2)
5833 val = (ip6._S6_un._S6_u8[i] << 8) +
5834 ip6._S6_un._S6_u8[i + 1];
5836 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5837 ip6.__u6_addr.__u6_addr8[i + 1];
5843 for (; val; val /= 16) {
5844 *end-- = digits[val % 16];
5848 ASSERT(end + 1 >= base);
5852 * The user didn't use AH_INET or AH_INET6.
5854 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5859 inetout: regs[rd] = (uintptr_t)end + 1;
5860 mstate->dtms_scratch_ptr += size;
5864 case DIF_SUBR_MEMREF: {
5865 uintptr_t size = 2 * sizeof(uintptr_t);
5866 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5867 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5869 /* address and length */
5870 memref[0] = tupregs[0].dttk_value;
5871 memref[1] = tupregs[1].dttk_value;
5873 regs[rd] = (uintptr_t) memref;
5874 mstate->dtms_scratch_ptr += scratch_size;
5879 case DIF_SUBR_MEMSTR: {
5880 char *str = (char *)mstate->dtms_scratch_ptr;
5881 uintptr_t mem = tupregs[0].dttk_value;
5882 char c = tupregs[1].dttk_value;
5883 size_t size = tupregs[2].dttk_value;
5892 if (!dtrace_canload(mem, size - 1, mstate, vstate))
5895 if (!DTRACE_INSCRATCH(mstate, size)) {
5896 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5900 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5901 *flags |= CPU_DTRACE_ILLOP;
5905 for (i = 0; i < size - 1; i++) {
5906 n = dtrace_load8(mem++);
5907 str[i] = (n == 0) ? c : n;
5911 regs[rd] = (uintptr_t)str;
5912 mstate->dtms_scratch_ptr += size;
5917 case DIF_SUBR_TYPEREF: {
5918 uintptr_t size = 4 * sizeof(uintptr_t);
5919 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5920 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5922 /* address, num_elements, type_str, type_len */
5923 typeref[0] = tupregs[0].dttk_value;
5924 typeref[1] = tupregs[1].dttk_value;
5925 typeref[2] = tupregs[2].dttk_value;
5926 typeref[3] = tupregs[3].dttk_value;
5928 regs[rd] = (uintptr_t) typeref;
5929 mstate->dtms_scratch_ptr += scratch_size;
5936 * Emulate the execution of DTrace IR instructions specified by the given
5937 * DIF object. This function is deliberately void of assertions as all of
5938 * the necessary checks are handled by a call to dtrace_difo_validate().
5941 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5942 dtrace_vstate_t *vstate, dtrace_state_t *state)
5944 const dif_instr_t *text = difo->dtdo_buf;
5945 const uint_t textlen = difo->dtdo_len;
5946 const char *strtab = difo->dtdo_strtab;
5947 const uint64_t *inttab = difo->dtdo_inttab;
5950 dtrace_statvar_t *svar;
5951 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5953 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5954 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5956 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5957 uint64_t regs[DIF_DIR_NREGS];
5960 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5962 uint_t pc = 0, id, opc = 0;
5968 * We stash the current DIF object into the machine state: we need it
5969 * for subsequent access checking.
5971 mstate->dtms_difo = difo;
5973 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5975 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5979 r1 = DIF_INSTR_R1(instr);
5980 r2 = DIF_INSTR_R2(instr);
5981 rd = DIF_INSTR_RD(instr);
5983 switch (DIF_INSTR_OP(instr)) {
5985 regs[rd] = regs[r1] | regs[r2];
5988 regs[rd] = regs[r1] ^ regs[r2];
5991 regs[rd] = regs[r1] & regs[r2];
5994 regs[rd] = regs[r1] << regs[r2];
5997 regs[rd] = regs[r1] >> regs[r2];
6000 regs[rd] = regs[r1] - regs[r2];
6003 regs[rd] = regs[r1] + regs[r2];
6006 regs[rd] = regs[r1] * regs[r2];
6009 if (regs[r2] == 0) {
6011 *flags |= CPU_DTRACE_DIVZERO;
6013 regs[rd] = (int64_t)regs[r1] /
6019 if (regs[r2] == 0) {
6021 *flags |= CPU_DTRACE_DIVZERO;
6023 regs[rd] = regs[r1] / regs[r2];
6028 if (regs[r2] == 0) {
6030 *flags |= CPU_DTRACE_DIVZERO;
6032 regs[rd] = (int64_t)regs[r1] %
6038 if (regs[r2] == 0) {
6040 *flags |= CPU_DTRACE_DIVZERO;
6042 regs[rd] = regs[r1] % regs[r2];
6047 regs[rd] = ~regs[r1];
6050 regs[rd] = regs[r1];
6053 cc_r = regs[r1] - regs[r2];
6057 cc_c = regs[r1] < regs[r2];
6060 cc_n = cc_v = cc_c = 0;
6061 cc_z = regs[r1] == 0;
6064 pc = DIF_INSTR_LABEL(instr);
6068 pc = DIF_INSTR_LABEL(instr);
6072 pc = DIF_INSTR_LABEL(instr);
6075 if ((cc_z | (cc_n ^ cc_v)) == 0)
6076 pc = DIF_INSTR_LABEL(instr);
6079 if ((cc_c | cc_z) == 0)
6080 pc = DIF_INSTR_LABEL(instr);
6083 if ((cc_n ^ cc_v) == 0)
6084 pc = DIF_INSTR_LABEL(instr);
6088 pc = DIF_INSTR_LABEL(instr);
6092 pc = DIF_INSTR_LABEL(instr);
6096 pc = DIF_INSTR_LABEL(instr);
6099 if (cc_z | (cc_n ^ cc_v))
6100 pc = DIF_INSTR_LABEL(instr);
6104 pc = DIF_INSTR_LABEL(instr);
6107 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6111 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6114 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6118 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6121 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6125 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6128 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6132 regs[rd] = dtrace_load8(regs[r1]);
6135 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6139 regs[rd] = dtrace_load16(regs[r1]);
6142 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6146 regs[rd] = dtrace_load32(regs[r1]);
6149 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6153 regs[rd] = dtrace_load64(regs[r1]);
6156 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6158 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6159 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6162 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6163 regs[rd] = (int16_t)
6164 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6165 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6168 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6169 regs[rd] = (int32_t)
6170 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6171 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6174 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6176 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6177 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6180 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6182 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6183 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6186 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6188 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6189 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6192 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6194 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6195 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6204 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6207 regs[rd] = (uint64_t)(uintptr_t)
6208 (strtab + DIF_INSTR_STRING(instr));
6211 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6212 uintptr_t s1 = regs[r1];
6213 uintptr_t s2 = regs[r2];
6216 !dtrace_strcanload(s1, sz, mstate, vstate))
6219 !dtrace_strcanload(s2, sz, mstate, vstate))
6222 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
6230 regs[rd] = dtrace_dif_variable(mstate, state,
6234 id = DIF_INSTR_VAR(instr);
6236 if (id >= DIF_VAR_OTHER_UBASE) {
6239 id -= DIF_VAR_OTHER_UBASE;
6240 svar = vstate->dtvs_globals[id];
6241 ASSERT(svar != NULL);
6242 v = &svar->dtsv_var;
6244 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6245 regs[rd] = svar->dtsv_data;
6249 a = (uintptr_t)svar->dtsv_data;
6251 if (*(uint8_t *)a == UINT8_MAX) {
6253 * If the 0th byte is set to UINT8_MAX
6254 * then this is to be treated as a
6255 * reference to a NULL variable.
6259 regs[rd] = a + sizeof (uint64_t);
6265 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6269 id = DIF_INSTR_VAR(instr);
6271 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6272 id -= DIF_VAR_OTHER_UBASE;
6274 VERIFY(id < vstate->dtvs_nglobals);
6275 svar = vstate->dtvs_globals[id];
6276 ASSERT(svar != NULL);
6277 v = &svar->dtsv_var;
6279 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6280 uintptr_t a = (uintptr_t)svar->dtsv_data;
6283 ASSERT(svar->dtsv_size != 0);
6285 if (regs[rd] == 0) {
6286 *(uint8_t *)a = UINT8_MAX;
6290 a += sizeof (uint64_t);
6292 if (!dtrace_vcanload(
6293 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6297 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6298 (void *)a, &v->dtdv_type);
6302 svar->dtsv_data = regs[rd];
6307 * There are no DTrace built-in thread-local arrays at
6308 * present. This opcode is saved for future work.
6310 *flags |= CPU_DTRACE_ILLOP;
6315 id = DIF_INSTR_VAR(instr);
6317 if (id < DIF_VAR_OTHER_UBASE) {
6319 * For now, this has no meaning.
6325 id -= DIF_VAR_OTHER_UBASE;
6327 ASSERT(id < vstate->dtvs_nlocals);
6328 ASSERT(vstate->dtvs_locals != NULL);
6330 svar = vstate->dtvs_locals[id];
6331 ASSERT(svar != NULL);
6332 v = &svar->dtsv_var;
6334 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6335 uintptr_t a = (uintptr_t)svar->dtsv_data;
6336 size_t sz = v->dtdv_type.dtdt_size;
6338 sz += sizeof (uint64_t);
6339 ASSERT(svar->dtsv_size == NCPU * sz);
6342 if (*(uint8_t *)a == UINT8_MAX) {
6344 * If the 0th byte is set to UINT8_MAX
6345 * then this is to be treated as a
6346 * reference to a NULL variable.
6350 regs[rd] = a + sizeof (uint64_t);
6356 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6357 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6358 regs[rd] = tmp[curcpu];
6362 id = DIF_INSTR_VAR(instr);
6364 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6365 id -= DIF_VAR_OTHER_UBASE;
6366 VERIFY(id < vstate->dtvs_nlocals);
6368 ASSERT(vstate->dtvs_locals != NULL);
6369 svar = vstate->dtvs_locals[id];
6370 ASSERT(svar != NULL);
6371 v = &svar->dtsv_var;
6373 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6374 uintptr_t a = (uintptr_t)svar->dtsv_data;
6375 size_t sz = v->dtdv_type.dtdt_size;
6377 sz += sizeof (uint64_t);
6378 ASSERT(svar->dtsv_size == NCPU * sz);
6381 if (regs[rd] == 0) {
6382 *(uint8_t *)a = UINT8_MAX;
6386 a += sizeof (uint64_t);
6389 if (!dtrace_vcanload(
6390 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6394 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6395 (void *)a, &v->dtdv_type);
6399 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6400 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6401 tmp[curcpu] = regs[rd];
6405 dtrace_dynvar_t *dvar;
6408 id = DIF_INSTR_VAR(instr);
6409 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6410 id -= DIF_VAR_OTHER_UBASE;
6411 v = &vstate->dtvs_tlocals[id];
6413 key = &tupregs[DIF_DTR_NREGS];
6414 key[0].dttk_value = (uint64_t)id;
6415 key[0].dttk_size = 0;
6416 DTRACE_TLS_THRKEY(key[1].dttk_value);
6417 key[1].dttk_size = 0;
6419 dvar = dtrace_dynvar(dstate, 2, key,
6420 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6428 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6429 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6431 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6438 dtrace_dynvar_t *dvar;
6441 id = DIF_INSTR_VAR(instr);
6442 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6443 id -= DIF_VAR_OTHER_UBASE;
6444 VERIFY(id < vstate->dtvs_ntlocals);
6446 key = &tupregs[DIF_DTR_NREGS];
6447 key[0].dttk_value = (uint64_t)id;
6448 key[0].dttk_size = 0;
6449 DTRACE_TLS_THRKEY(key[1].dttk_value);
6450 key[1].dttk_size = 0;
6451 v = &vstate->dtvs_tlocals[id];
6453 dvar = dtrace_dynvar(dstate, 2, key,
6454 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6455 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6456 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6457 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6460 * Given that we're storing to thread-local data,
6461 * we need to flush our predicate cache.
6463 curthread->t_predcache = 0;
6468 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6469 if (!dtrace_vcanload(
6470 (void *)(uintptr_t)regs[rd],
6471 &v->dtdv_type, mstate, vstate))
6474 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6475 dvar->dtdv_data, &v->dtdv_type);
6477 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6484 regs[rd] = (int64_t)regs[r1] >> regs[r2];
6488 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6489 regs, tupregs, ttop, mstate, state);
6493 if (ttop == DIF_DTR_NREGS) {
6494 *flags |= CPU_DTRACE_TUPOFLOW;
6498 if (r1 == DIF_TYPE_STRING) {
6500 * If this is a string type and the size is 0,
6501 * we'll use the system-wide default string
6502 * size. Note that we are _not_ looking at
6503 * the value of the DTRACEOPT_STRSIZE option;
6504 * had this been set, we would expect to have
6505 * a non-zero size value in the "pushtr".
6507 tupregs[ttop].dttk_size =
6508 dtrace_strlen((char *)(uintptr_t)regs[rd],
6509 regs[r2] ? regs[r2] :
6510 dtrace_strsize_default) + 1;
6512 if (regs[r2] > LONG_MAX) {
6513 *flags |= CPU_DTRACE_ILLOP;
6517 tupregs[ttop].dttk_size = regs[r2];
6520 tupregs[ttop++].dttk_value = regs[rd];
6524 if (ttop == DIF_DTR_NREGS) {
6525 *flags |= CPU_DTRACE_TUPOFLOW;
6529 tupregs[ttop].dttk_value = regs[rd];
6530 tupregs[ttop++].dttk_size = 0;
6538 case DIF_OP_FLUSHTS:
6543 case DIF_OP_LDTAA: {
6544 dtrace_dynvar_t *dvar;
6545 dtrace_key_t *key = tupregs;
6546 uint_t nkeys = ttop;
6548 id = DIF_INSTR_VAR(instr);
6549 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6550 id -= DIF_VAR_OTHER_UBASE;
6552 key[nkeys].dttk_value = (uint64_t)id;
6553 key[nkeys++].dttk_size = 0;
6555 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6556 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6557 key[nkeys++].dttk_size = 0;
6558 VERIFY(id < vstate->dtvs_ntlocals);
6559 v = &vstate->dtvs_tlocals[id];
6561 VERIFY(id < vstate->dtvs_nglobals);
6562 v = &vstate->dtvs_globals[id]->dtsv_var;
6565 dvar = dtrace_dynvar(dstate, nkeys, key,
6566 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6567 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6568 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6575 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6576 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6578 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6585 case DIF_OP_STTAA: {
6586 dtrace_dynvar_t *dvar;
6587 dtrace_key_t *key = tupregs;
6588 uint_t nkeys = ttop;
6590 id = DIF_INSTR_VAR(instr);
6591 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6592 id -= DIF_VAR_OTHER_UBASE;
6594 key[nkeys].dttk_value = (uint64_t)id;
6595 key[nkeys++].dttk_size = 0;
6597 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6598 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6599 key[nkeys++].dttk_size = 0;
6600 VERIFY(id < vstate->dtvs_ntlocals);
6601 v = &vstate->dtvs_tlocals[id];
6603 VERIFY(id < vstate->dtvs_nglobals);
6604 v = &vstate->dtvs_globals[id]->dtsv_var;
6607 dvar = dtrace_dynvar(dstate, nkeys, key,
6608 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6609 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6610 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6611 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6616 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6617 if (!dtrace_vcanload(
6618 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6622 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6623 dvar->dtdv_data, &v->dtdv_type);
6625 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6631 case DIF_OP_ALLOCS: {
6632 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6633 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6636 * Rounding up the user allocation size could have
6637 * overflowed large, bogus allocations (like -1ULL) to
6640 if (size < regs[r1] ||
6641 !DTRACE_INSCRATCH(mstate, size)) {
6642 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6647 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6648 mstate->dtms_scratch_ptr += size;
6654 if (!dtrace_canstore(regs[rd], regs[r2],
6656 *flags |= CPU_DTRACE_BADADDR;
6661 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6664 dtrace_bcopy((void *)(uintptr_t)regs[r1],
6665 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6669 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6670 *flags |= CPU_DTRACE_BADADDR;
6674 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6678 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6679 *flags |= CPU_DTRACE_BADADDR;
6684 *flags |= CPU_DTRACE_BADALIGN;
6688 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6692 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6693 *flags |= CPU_DTRACE_BADADDR;
6698 *flags |= CPU_DTRACE_BADALIGN;
6702 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6706 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6707 *flags |= CPU_DTRACE_BADADDR;
6712 *flags |= CPU_DTRACE_BADALIGN;
6716 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6721 if (!(*flags & CPU_DTRACE_FAULT))
6724 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6725 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6731 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6733 dtrace_probe_t *probe = ecb->dte_probe;
6734 dtrace_provider_t *prov = probe->dtpr_provider;
6735 char c[DTRACE_FULLNAMELEN + 80], *str;
6736 char *msg = "dtrace: breakpoint action at probe ";
6737 char *ecbmsg = " (ecb ";
6738 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6739 uintptr_t val = (uintptr_t)ecb;
6740 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6742 if (dtrace_destructive_disallow)
6746 * It's impossible to be taking action on the NULL probe.
6748 ASSERT(probe != NULL);
6751 * This is a poor man's (destitute man's?) sprintf(): we want to
6752 * print the provider name, module name, function name and name of
6753 * the probe, along with the hex address of the ECB with the breakpoint
6754 * action -- all of which we must place in the character buffer by
6757 while (*msg != '\0')
6760 for (str = prov->dtpv_name; *str != '\0'; str++)
6764 for (str = probe->dtpr_mod; *str != '\0'; str++)
6768 for (str = probe->dtpr_func; *str != '\0'; str++)
6772 for (str = probe->dtpr_name; *str != '\0'; str++)
6775 while (*ecbmsg != '\0')
6778 while (shift >= 0) {
6779 mask = (uintptr_t)0xf << shift;
6781 if (val >= ((uintptr_t)1 << shift))
6782 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6792 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6797 dtrace_action_panic(dtrace_ecb_t *ecb)
6799 dtrace_probe_t *probe = ecb->dte_probe;
6802 * It's impossible to be taking action on the NULL probe.
6804 ASSERT(probe != NULL);
6806 if (dtrace_destructive_disallow)
6809 if (dtrace_panicked != NULL)
6812 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6816 * We won the right to panic. (We want to be sure that only one
6817 * thread calls panic() from dtrace_probe(), and that panic() is
6818 * called exactly once.)
6820 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6821 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6822 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6826 dtrace_action_raise(uint64_t sig)
6828 if (dtrace_destructive_disallow)
6832 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6838 * raise() has a queue depth of 1 -- we ignore all subsequent
6839 * invocations of the raise() action.
6841 if (curthread->t_dtrace_sig == 0)
6842 curthread->t_dtrace_sig = (uint8_t)sig;
6844 curthread->t_sig_check = 1;
6847 struct proc *p = curproc;
6849 kern_psignal(p, sig);
6855 dtrace_action_stop(void)
6857 if (dtrace_destructive_disallow)
6861 if (!curthread->t_dtrace_stop) {
6862 curthread->t_dtrace_stop = 1;
6863 curthread->t_sig_check = 1;
6867 struct proc *p = curproc;
6869 kern_psignal(p, SIGSTOP);
6875 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6878 volatile uint16_t *flags;
6882 cpu_t *cpu = &solaris_cpu[curcpu];
6885 if (dtrace_destructive_disallow)
6888 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6890 now = dtrace_gethrtime();
6892 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6894 * We need to advance the mark to the current time.
6896 cpu->cpu_dtrace_chillmark = now;
6897 cpu->cpu_dtrace_chilled = 0;
6901 * Now check to see if the requested chill time would take us over
6902 * the maximum amount of time allowed in the chill interval. (Or
6903 * worse, if the calculation itself induces overflow.)
6905 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6906 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6907 *flags |= CPU_DTRACE_ILLOP;
6911 while (dtrace_gethrtime() - now < val)
6915 * Normally, we assure that the value of the variable "timestamp" does
6916 * not change within an ECB. The presence of chill() represents an
6917 * exception to this rule, however.
6919 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6920 cpu->cpu_dtrace_chilled += val;
6924 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6925 uint64_t *buf, uint64_t arg)
6927 int nframes = DTRACE_USTACK_NFRAMES(arg);
6928 int strsize = DTRACE_USTACK_STRSIZE(arg);
6929 uint64_t *pcs = &buf[1], *fps;
6930 char *str = (char *)&pcs[nframes];
6931 int size, offs = 0, i, j;
6932 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6933 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6937 * Should be taking a faster path if string space has not been
6940 ASSERT(strsize != 0);
6943 * We will first allocate some temporary space for the frame pointers.
6945 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6946 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6947 (nframes * sizeof (uint64_t));
6949 if (!DTRACE_INSCRATCH(mstate, size)) {
6951 * Not enough room for our frame pointers -- need to indicate
6952 * that we ran out of scratch space.
6954 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6958 mstate->dtms_scratch_ptr += size;
6959 saved = mstate->dtms_scratch_ptr;
6962 * Now get a stack with both program counters and frame pointers.
6964 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6965 dtrace_getufpstack(buf, fps, nframes + 1);
6966 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6969 * If that faulted, we're cooked.
6971 if (*flags & CPU_DTRACE_FAULT)
6975 * Now we want to walk up the stack, calling the USTACK helper. For
6976 * each iteration, we restore the scratch pointer.
6978 for (i = 0; i < nframes; i++) {
6979 mstate->dtms_scratch_ptr = saved;
6981 if (offs >= strsize)
6984 sym = (char *)(uintptr_t)dtrace_helper(
6985 DTRACE_HELPER_ACTION_USTACK,
6986 mstate, state, pcs[i], fps[i]);
6989 * If we faulted while running the helper, we're going to
6990 * clear the fault and null out the corresponding string.
6992 if (*flags & CPU_DTRACE_FAULT) {
6993 *flags &= ~CPU_DTRACE_FAULT;
7003 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7006 * Now copy in the string that the helper returned to us.
7008 for (j = 0; offs + j < strsize; j++) {
7009 if ((str[offs + j] = sym[j]) == '\0')
7013 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7018 if (offs >= strsize) {
7020 * If we didn't have room for all of the strings, we don't
7021 * abort processing -- this needn't be a fatal error -- but we
7022 * still want to increment a counter (dts_stkstroverflows) to
7023 * allow this condition to be warned about. (If this is from
7024 * a jstack() action, it is easily tuned via jstackstrsize.)
7026 dtrace_error(&state->dts_stkstroverflows);
7029 while (offs < strsize)
7033 mstate->dtms_scratch_ptr = old;
7037 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7038 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7040 volatile uint16_t *flags;
7041 uint64_t val = *valp;
7042 size_t valoffs = *valoffsp;
7044 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7045 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7048 * If this is a string, we're going to only load until we find the zero
7049 * byte -- after which we'll store zero bytes.
7051 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7055 for (s = 0; s < size; s++) {
7056 if (c != '\0' && dtkind == DIF_TF_BYREF) {
7057 c = dtrace_load8(val++);
7058 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7059 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7060 c = dtrace_fuword8((void *)(uintptr_t)val++);
7061 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7062 if (*flags & CPU_DTRACE_FAULT)
7066 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7068 if (c == '\0' && intuple)
7073 while (valoffs < end) {
7074 if (dtkind == DIF_TF_BYREF) {
7075 c = dtrace_load8(val++);
7076 } else if (dtkind == DIF_TF_BYUREF) {
7077 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7078 c = dtrace_fuword8((void *)(uintptr_t)val++);
7079 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7080 if (*flags & CPU_DTRACE_FAULT)
7084 DTRACE_STORE(uint8_t, tomax,
7090 *valoffsp = valoffs;
7094 * If you're looking for the epicenter of DTrace, you just found it. This
7095 * is the function called by the provider to fire a probe -- from which all
7096 * subsequent probe-context DTrace activity emanates.
7099 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7100 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7102 processorid_t cpuid;
7103 dtrace_icookie_t cookie;
7104 dtrace_probe_t *probe;
7105 dtrace_mstate_t mstate;
7107 dtrace_action_t *act;
7111 volatile uint16_t *flags;
7114 if (panicstr != NULL)
7119 * Kick out immediately if this CPU is still being born (in which case
7120 * curthread will be set to -1) or the current thread can't allow
7121 * probes in its current context.
7123 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7127 cookie = dtrace_interrupt_disable();
7128 probe = dtrace_probes[id - 1];
7130 onintr = CPU_ON_INTR(CPU);
7132 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7133 probe->dtpr_predcache == curthread->t_predcache) {
7135 * We have hit in the predicate cache; we know that
7136 * this predicate would evaluate to be false.
7138 dtrace_interrupt_enable(cookie);
7143 if (panic_quiesce) {
7145 if (panicstr != NULL) {
7148 * We don't trace anything if we're panicking.
7150 dtrace_interrupt_enable(cookie);
7154 now = mstate.dtms_timestamp = dtrace_gethrtime();
7155 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7156 vtime = dtrace_vtime_references != 0;
7158 if (vtime && curthread->t_dtrace_start)
7159 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7161 mstate.dtms_difo = NULL;
7162 mstate.dtms_probe = probe;
7163 mstate.dtms_strtok = 0;
7164 mstate.dtms_arg[0] = arg0;
7165 mstate.dtms_arg[1] = arg1;
7166 mstate.dtms_arg[2] = arg2;
7167 mstate.dtms_arg[3] = arg3;
7168 mstate.dtms_arg[4] = arg4;
7170 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7172 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7173 dtrace_predicate_t *pred = ecb->dte_predicate;
7174 dtrace_state_t *state = ecb->dte_state;
7175 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7176 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7177 dtrace_vstate_t *vstate = &state->dts_vstate;
7178 dtrace_provider_t *prov = probe->dtpr_provider;
7179 uint64_t tracememsize = 0;
7184 * A little subtlety with the following (seemingly innocuous)
7185 * declaration of the automatic 'val': by looking at the
7186 * code, you might think that it could be declared in the
7187 * action processing loop, below. (That is, it's only used in
7188 * the action processing loop.) However, it must be declared
7189 * out of that scope because in the case of DIF expression
7190 * arguments to aggregating actions, one iteration of the
7191 * action loop will use the last iteration's value.
7195 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7196 mstate.dtms_getf = NULL;
7198 *flags &= ~CPU_DTRACE_ERROR;
7200 if (prov == dtrace_provider) {
7202 * If dtrace itself is the provider of this probe,
7203 * we're only going to continue processing the ECB if
7204 * arg0 (the dtrace_state_t) is equal to the ECB's
7205 * creating state. (This prevents disjoint consumers
7206 * from seeing one another's metaprobes.)
7208 if (arg0 != (uint64_t)(uintptr_t)state)
7212 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7214 * We're not currently active. If our provider isn't
7215 * the dtrace pseudo provider, we're not interested.
7217 if (prov != dtrace_provider)
7221 * Now we must further check if we are in the BEGIN
7222 * probe. If we are, we will only continue processing
7223 * if we're still in WARMUP -- if one BEGIN enabling
7224 * has invoked the exit() action, we don't want to
7225 * evaluate subsequent BEGIN enablings.
7227 if (probe->dtpr_id == dtrace_probeid_begin &&
7228 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7229 ASSERT(state->dts_activity ==
7230 DTRACE_ACTIVITY_DRAINING);
7235 if (ecb->dte_cond) {
7237 * If the dte_cond bits indicate that this
7238 * consumer is only allowed to see user-mode firings
7239 * of this probe, call the provider's dtps_usermode()
7240 * entry point to check that the probe was fired
7241 * while in a user context. Skip this ECB if that's
7244 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7245 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7246 probe->dtpr_id, probe->dtpr_arg) == 0)
7251 * This is more subtle than it looks. We have to be
7252 * absolutely certain that CRED() isn't going to
7253 * change out from under us so it's only legit to
7254 * examine that structure if we're in constrained
7255 * situations. Currently, the only times we'll this
7256 * check is if a non-super-user has enabled the
7257 * profile or syscall providers -- providers that
7258 * allow visibility of all processes. For the
7259 * profile case, the check above will ensure that
7260 * we're examining a user context.
7262 if (ecb->dte_cond & DTRACE_COND_OWNER) {
7265 ecb->dte_state->dts_cred.dcr_cred;
7268 ASSERT(s_cr != NULL);
7270 if ((cr = CRED()) == NULL ||
7271 s_cr->cr_uid != cr->cr_uid ||
7272 s_cr->cr_uid != cr->cr_ruid ||
7273 s_cr->cr_uid != cr->cr_suid ||
7274 s_cr->cr_gid != cr->cr_gid ||
7275 s_cr->cr_gid != cr->cr_rgid ||
7276 s_cr->cr_gid != cr->cr_sgid ||
7277 (proc = ttoproc(curthread)) == NULL ||
7278 (proc->p_flag & SNOCD))
7282 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7285 ecb->dte_state->dts_cred.dcr_cred;
7287 ASSERT(s_cr != NULL);
7289 if ((cr = CRED()) == NULL ||
7290 s_cr->cr_zone->zone_id !=
7291 cr->cr_zone->zone_id)
7297 if (now - state->dts_alive > dtrace_deadman_timeout) {
7299 * We seem to be dead. Unless we (a) have kernel
7300 * destructive permissions (b) have explicitly enabled
7301 * destructive actions and (c) destructive actions have
7302 * not been disabled, we're going to transition into
7303 * the KILLED state, from which no further processing
7304 * on this state will be performed.
7306 if (!dtrace_priv_kernel_destructive(state) ||
7307 !state->dts_cred.dcr_destructive ||
7308 dtrace_destructive_disallow) {
7309 void *activity = &state->dts_activity;
7310 dtrace_activity_t current;
7313 current = state->dts_activity;
7314 } while (dtrace_cas32(activity, current,
7315 DTRACE_ACTIVITY_KILLED) != current);
7321 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7322 ecb->dte_alignment, state, &mstate)) < 0)
7325 tomax = buf->dtb_tomax;
7326 ASSERT(tomax != NULL);
7328 if (ecb->dte_size != 0) {
7329 dtrace_rechdr_t dtrh;
7330 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7331 mstate.dtms_timestamp = dtrace_gethrtime();
7332 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7334 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7335 dtrh.dtrh_epid = ecb->dte_epid;
7336 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7337 mstate.dtms_timestamp);
7338 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7341 mstate.dtms_epid = ecb->dte_epid;
7342 mstate.dtms_present |= DTRACE_MSTATE_EPID;
7344 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7345 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7347 mstate.dtms_access = 0;
7350 dtrace_difo_t *dp = pred->dtp_difo;
7353 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7355 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7356 dtrace_cacheid_t cid = probe->dtpr_predcache;
7358 if (cid != DTRACE_CACHEIDNONE && !onintr) {
7360 * Update the predicate cache...
7362 ASSERT(cid == pred->dtp_cacheid);
7363 curthread->t_predcache = cid;
7370 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7371 act != NULL; act = act->dta_next) {
7374 dtrace_recdesc_t *rec = &act->dta_rec;
7376 size = rec->dtrd_size;
7377 valoffs = offs + rec->dtrd_offset;
7379 if (DTRACEACT_ISAGG(act->dta_kind)) {
7381 dtrace_aggregation_t *agg;
7383 agg = (dtrace_aggregation_t *)act;
7385 if ((dp = act->dta_difo) != NULL)
7386 v = dtrace_dif_emulate(dp,
7387 &mstate, vstate, state);
7389 if (*flags & CPU_DTRACE_ERROR)
7393 * Note that we always pass the expression
7394 * value from the previous iteration of the
7395 * action loop. This value will only be used
7396 * if there is an expression argument to the
7397 * aggregating action, denoted by the
7398 * dtag_hasarg field.
7400 dtrace_aggregate(agg, buf,
7401 offs, aggbuf, v, val);
7405 switch (act->dta_kind) {
7406 case DTRACEACT_STOP:
7407 if (dtrace_priv_proc_destructive(state))
7408 dtrace_action_stop();
7411 case DTRACEACT_BREAKPOINT:
7412 if (dtrace_priv_kernel_destructive(state))
7413 dtrace_action_breakpoint(ecb);
7416 case DTRACEACT_PANIC:
7417 if (dtrace_priv_kernel_destructive(state))
7418 dtrace_action_panic(ecb);
7421 case DTRACEACT_STACK:
7422 if (!dtrace_priv_kernel(state))
7425 dtrace_getpcstack((pc_t *)(tomax + valoffs),
7426 size / sizeof (pc_t), probe->dtpr_aframes,
7427 DTRACE_ANCHORED(probe) ? NULL :
7431 case DTRACEACT_JSTACK:
7432 case DTRACEACT_USTACK:
7433 if (!dtrace_priv_proc(state))
7437 * See comment in DIF_VAR_PID.
7439 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7441 int depth = DTRACE_USTACK_NFRAMES(
7444 dtrace_bzero((void *)(tomax + valoffs),
7445 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7446 + depth * sizeof (uint64_t));
7451 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7452 curproc->p_dtrace_helpers != NULL) {
7454 * This is the slow path -- we have
7455 * allocated string space, and we're
7456 * getting the stack of a process that
7457 * has helpers. Call into a separate
7458 * routine to perform this processing.
7460 dtrace_action_ustack(&mstate, state,
7461 (uint64_t *)(tomax + valoffs),
7466 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7467 dtrace_getupcstack((uint64_t *)
7469 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7470 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7480 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7482 if (*flags & CPU_DTRACE_ERROR)
7485 switch (act->dta_kind) {
7486 case DTRACEACT_SPECULATE: {
7487 dtrace_rechdr_t *dtrh;
7489 ASSERT(buf == &state->dts_buffer[cpuid]);
7490 buf = dtrace_speculation_buffer(state,
7494 *flags |= CPU_DTRACE_DROP;
7498 offs = dtrace_buffer_reserve(buf,
7499 ecb->dte_needed, ecb->dte_alignment,
7503 *flags |= CPU_DTRACE_DROP;
7507 tomax = buf->dtb_tomax;
7508 ASSERT(tomax != NULL);
7510 if (ecb->dte_size == 0)
7513 ASSERT3U(ecb->dte_size, >=,
7514 sizeof (dtrace_rechdr_t));
7515 dtrh = ((void *)(tomax + offs));
7516 dtrh->dtrh_epid = ecb->dte_epid;
7518 * When the speculation is committed, all of
7519 * the records in the speculative buffer will
7520 * have their timestamps set to the commit
7521 * time. Until then, it is set to a sentinel
7522 * value, for debugability.
7524 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7528 case DTRACEACT_PRINTM: {
7529 /* The DIF returns a 'memref'. */
7530 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7532 /* Get the size from the memref. */
7536 * Check if the size exceeds the allocated
7539 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7541 *flags |= CPU_DTRACE_DROP;
7545 /* Store the size in the buffer first. */
7546 DTRACE_STORE(uintptr_t, tomax,
7550 * Offset the buffer address to the start
7553 valoffs += sizeof(uintptr_t);
7556 * Reset to the memory address rather than
7557 * the memref array, then let the BYREF
7558 * code below do the work to store the
7559 * memory data in the buffer.
7565 case DTRACEACT_PRINTT: {
7566 /* The DIF returns a 'typeref'. */
7567 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
7572 * Get the type string length and round it
7573 * up so that the data that follows is
7574 * aligned for easy access.
7576 size_t typs = strlen((char *) typeref[2]) + 1;
7577 typs = roundup(typs, sizeof(uintptr_t));
7580 *Get the size from the typeref using the
7581 * number of elements and the type size.
7583 size = typeref[1] * typeref[3];
7586 * Check if the size exceeds the allocated
7589 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7591 *flags |= CPU_DTRACE_DROP;
7595 /* Store the size in the buffer first. */
7596 DTRACE_STORE(uintptr_t, tomax,
7598 valoffs += sizeof(uintptr_t);
7600 /* Store the type size in the buffer. */
7601 DTRACE_STORE(uintptr_t, tomax,
7602 valoffs, typeref[3]);
7603 valoffs += sizeof(uintptr_t);
7607 for (s = 0; s < typs; s++) {
7609 c = dtrace_load8(val++);
7611 DTRACE_STORE(uint8_t, tomax,
7616 * Reset to the memory address rather than
7617 * the typeref array, then let the BYREF
7618 * code below do the work to store the
7619 * memory data in the buffer.
7625 case DTRACEACT_CHILL:
7626 if (dtrace_priv_kernel_destructive(state))
7627 dtrace_action_chill(&mstate, val);
7630 case DTRACEACT_RAISE:
7631 if (dtrace_priv_proc_destructive(state))
7632 dtrace_action_raise(val);
7635 case DTRACEACT_COMMIT:
7639 * We need to commit our buffer state.
7642 buf->dtb_offset = offs + ecb->dte_size;
7643 buf = &state->dts_buffer[cpuid];
7644 dtrace_speculation_commit(state, cpuid, val);
7648 case DTRACEACT_DISCARD:
7649 dtrace_speculation_discard(state, cpuid, val);
7652 case DTRACEACT_DIFEXPR:
7653 case DTRACEACT_LIBACT:
7654 case DTRACEACT_PRINTF:
7655 case DTRACEACT_PRINTA:
7656 case DTRACEACT_SYSTEM:
7657 case DTRACEACT_FREOPEN:
7658 case DTRACEACT_TRACEMEM:
7661 case DTRACEACT_TRACEMEM_DYNSIZE:
7667 if (!dtrace_priv_kernel(state))
7671 case DTRACEACT_USYM:
7672 case DTRACEACT_UMOD:
7673 case DTRACEACT_UADDR: {
7675 struct pid *pid = curthread->t_procp->p_pidp;
7678 if (!dtrace_priv_proc(state))
7681 DTRACE_STORE(uint64_t, tomax,
7683 valoffs, (uint64_t)pid->pid_id);
7685 valoffs, (uint64_t) curproc->p_pid);
7687 DTRACE_STORE(uint64_t, tomax,
7688 valoffs + sizeof (uint64_t), val);
7693 case DTRACEACT_EXIT: {
7695 * For the exit action, we are going to attempt
7696 * to atomically set our activity to be
7697 * draining. If this fails (either because
7698 * another CPU has beat us to the exit action,
7699 * or because our current activity is something
7700 * other than ACTIVE or WARMUP), we will
7701 * continue. This assures that the exit action
7702 * can be successfully recorded at most once
7703 * when we're in the ACTIVE state. If we're
7704 * encountering the exit() action while in
7705 * COOLDOWN, however, we want to honor the new
7706 * status code. (We know that we're the only
7707 * thread in COOLDOWN, so there is no race.)
7709 void *activity = &state->dts_activity;
7710 dtrace_activity_t current = state->dts_activity;
7712 if (current == DTRACE_ACTIVITY_COOLDOWN)
7715 if (current != DTRACE_ACTIVITY_WARMUP)
7716 current = DTRACE_ACTIVITY_ACTIVE;
7718 if (dtrace_cas32(activity, current,
7719 DTRACE_ACTIVITY_DRAINING) != current) {
7720 *flags |= CPU_DTRACE_DROP;
7731 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7732 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7733 uintptr_t end = valoffs + size;
7735 if (tracememsize != 0 &&
7736 valoffs + tracememsize < end) {
7737 end = valoffs + tracememsize;
7741 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7742 !dtrace_vcanload((void *)(uintptr_t)val,
7743 &dp->dtdo_rtype, &mstate, vstate))
7746 dtrace_store_by_ref(dp, tomax, size, &valoffs,
7747 &val, end, act->dta_intuple,
7748 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7749 DIF_TF_BYREF: DIF_TF_BYUREF);
7757 case sizeof (uint8_t):
7758 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7760 case sizeof (uint16_t):
7761 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7763 case sizeof (uint32_t):
7764 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7766 case sizeof (uint64_t):
7767 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7771 * Any other size should have been returned by
7772 * reference, not by value.
7779 if (*flags & CPU_DTRACE_DROP)
7782 if (*flags & CPU_DTRACE_FAULT) {
7784 dtrace_action_t *err;
7788 if (probe->dtpr_id == dtrace_probeid_error) {
7790 * There's nothing we can do -- we had an
7791 * error on the error probe. We bump an
7792 * error counter to at least indicate that
7793 * this condition happened.
7795 dtrace_error(&state->dts_dblerrors);
7801 * Before recursing on dtrace_probe(), we
7802 * need to explicitly clear out our start
7803 * time to prevent it from being accumulated
7804 * into t_dtrace_vtime.
7806 curthread->t_dtrace_start = 0;
7810 * Iterate over the actions to figure out which action
7811 * we were processing when we experienced the error.
7812 * Note that act points _past_ the faulting action; if
7813 * act is ecb->dte_action, the fault was in the
7814 * predicate, if it's ecb->dte_action->dta_next it's
7815 * in action #1, and so on.
7817 for (err = ecb->dte_action, ndx = 0;
7818 err != act; err = err->dta_next, ndx++)
7821 dtrace_probe_error(state, ecb->dte_epid, ndx,
7822 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7823 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7824 cpu_core[cpuid].cpuc_dtrace_illval);
7830 buf->dtb_offset = offs + ecb->dte_size;
7834 curthread->t_dtrace_start = dtrace_gethrtime();
7836 dtrace_interrupt_enable(cookie);
7840 * DTrace Probe Hashing Functions
7842 * The functions in this section (and indeed, the functions in remaining
7843 * sections) are not _called_ from probe context. (Any exceptions to this are
7844 * marked with a "Note:".) Rather, they are called from elsewhere in the
7845 * DTrace framework to look-up probes in, add probes to and remove probes from
7846 * the DTrace probe hashes. (Each probe is hashed by each element of the
7847 * probe tuple -- allowing for fast lookups, regardless of what was
7851 dtrace_hash_str(const char *p)
7857 hval = (hval << 4) + *p++;
7858 if ((g = (hval & 0xf0000000)) != 0)
7865 static dtrace_hash_t *
7866 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7868 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7870 hash->dth_stroffs = stroffs;
7871 hash->dth_nextoffs = nextoffs;
7872 hash->dth_prevoffs = prevoffs;
7875 hash->dth_mask = hash->dth_size - 1;
7877 hash->dth_tab = kmem_zalloc(hash->dth_size *
7878 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7884 dtrace_hash_destroy(dtrace_hash_t *hash)
7889 for (i = 0; i < hash->dth_size; i++)
7890 ASSERT(hash->dth_tab[i] == NULL);
7893 kmem_free(hash->dth_tab,
7894 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7895 kmem_free(hash, sizeof (dtrace_hash_t));
7899 dtrace_hash_resize(dtrace_hash_t *hash)
7901 int size = hash->dth_size, i, ndx;
7902 int new_size = hash->dth_size << 1;
7903 int new_mask = new_size - 1;
7904 dtrace_hashbucket_t **new_tab, *bucket, *next;
7906 ASSERT((new_size & new_mask) == 0);
7908 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7910 for (i = 0; i < size; i++) {
7911 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7912 dtrace_probe_t *probe = bucket->dthb_chain;
7914 ASSERT(probe != NULL);
7915 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7917 next = bucket->dthb_next;
7918 bucket->dthb_next = new_tab[ndx];
7919 new_tab[ndx] = bucket;
7923 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7924 hash->dth_tab = new_tab;
7925 hash->dth_size = new_size;
7926 hash->dth_mask = new_mask;
7930 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7932 int hashval = DTRACE_HASHSTR(hash, new);
7933 int ndx = hashval & hash->dth_mask;
7934 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7935 dtrace_probe_t **nextp, **prevp;
7937 for (; bucket != NULL; bucket = bucket->dthb_next) {
7938 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7942 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7943 dtrace_hash_resize(hash);
7944 dtrace_hash_add(hash, new);
7948 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7949 bucket->dthb_next = hash->dth_tab[ndx];
7950 hash->dth_tab[ndx] = bucket;
7951 hash->dth_nbuckets++;
7954 nextp = DTRACE_HASHNEXT(hash, new);
7955 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7956 *nextp = bucket->dthb_chain;
7958 if (bucket->dthb_chain != NULL) {
7959 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7960 ASSERT(*prevp == NULL);
7964 bucket->dthb_chain = new;
7968 static dtrace_probe_t *
7969 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7971 int hashval = DTRACE_HASHSTR(hash, template);
7972 int ndx = hashval & hash->dth_mask;
7973 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7975 for (; bucket != NULL; bucket = bucket->dthb_next) {
7976 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7977 return (bucket->dthb_chain);
7984 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7986 int hashval = DTRACE_HASHSTR(hash, template);
7987 int ndx = hashval & hash->dth_mask;
7988 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7990 for (; bucket != NULL; bucket = bucket->dthb_next) {
7991 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7992 return (bucket->dthb_len);
7999 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8001 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8002 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8004 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8005 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8008 * Find the bucket that we're removing this probe from.
8010 for (; bucket != NULL; bucket = bucket->dthb_next) {
8011 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8015 ASSERT(bucket != NULL);
8017 if (*prevp == NULL) {
8018 if (*nextp == NULL) {
8020 * The removed probe was the only probe on this
8021 * bucket; we need to remove the bucket.
8023 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8025 ASSERT(bucket->dthb_chain == probe);
8029 hash->dth_tab[ndx] = bucket->dthb_next;
8031 while (b->dthb_next != bucket)
8033 b->dthb_next = bucket->dthb_next;
8036 ASSERT(hash->dth_nbuckets > 0);
8037 hash->dth_nbuckets--;
8038 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8042 bucket->dthb_chain = *nextp;
8044 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8048 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8052 * DTrace Utility Functions
8054 * These are random utility functions that are _not_ called from probe context.
8057 dtrace_badattr(const dtrace_attribute_t *a)
8059 return (a->dtat_name > DTRACE_STABILITY_MAX ||
8060 a->dtat_data > DTRACE_STABILITY_MAX ||
8061 a->dtat_class > DTRACE_CLASS_MAX);
8065 * Return a duplicate copy of a string. If the specified string is NULL,
8066 * this function returns a zero-length string.
8069 dtrace_strdup(const char *str)
8071 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8074 (void) strcpy(new, str);
8079 #define DTRACE_ISALPHA(c) \
8080 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8083 dtrace_badname(const char *s)
8087 if (s == NULL || (c = *s++) == '\0')
8090 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8093 while ((c = *s++) != '\0') {
8094 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8095 c != '-' && c != '_' && c != '.' && c != '`')
8103 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8108 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8110 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8112 priv = DTRACE_PRIV_ALL;
8114 *uidp = crgetuid(cr);
8115 *zoneidp = crgetzoneid(cr);
8118 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8119 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8120 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8121 priv |= DTRACE_PRIV_USER;
8122 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8123 priv |= DTRACE_PRIV_PROC;
8124 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8125 priv |= DTRACE_PRIV_OWNER;
8126 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8127 priv |= DTRACE_PRIV_ZONEOWNER;
8130 priv = DTRACE_PRIV_ALL;
8136 #ifdef DTRACE_ERRDEBUG
8138 dtrace_errdebug(const char *str)
8140 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8143 mutex_enter(&dtrace_errlock);
8144 dtrace_errlast = str;
8145 dtrace_errthread = curthread;
8147 while (occupied++ < DTRACE_ERRHASHSZ) {
8148 if (dtrace_errhash[hval].dter_msg == str) {
8149 dtrace_errhash[hval].dter_count++;
8153 if (dtrace_errhash[hval].dter_msg != NULL) {
8154 hval = (hval + 1) % DTRACE_ERRHASHSZ;
8158 dtrace_errhash[hval].dter_msg = str;
8159 dtrace_errhash[hval].dter_count = 1;
8163 panic("dtrace: undersized error hash");
8165 mutex_exit(&dtrace_errlock);
8170 * DTrace Matching Functions
8172 * These functions are used to match groups of probes, given some elements of
8173 * a probe tuple, or some globbed expressions for elements of a probe tuple.
8176 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8179 if (priv != DTRACE_PRIV_ALL) {
8180 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8181 uint32_t match = priv & ppriv;
8184 * No PRIV_DTRACE_* privileges...
8186 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8187 DTRACE_PRIV_KERNEL)) == 0)
8191 * No matching bits, but there were bits to match...
8193 if (match == 0 && ppriv != 0)
8197 * Need to have permissions to the process, but don't...
8199 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8200 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8205 * Need to be in the same zone unless we possess the
8206 * privilege to examine all zones.
8208 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8209 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8218 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8219 * consists of input pattern strings and an ops-vector to evaluate them.
8220 * This function returns >0 for match, 0 for no match, and <0 for error.
8223 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8224 uint32_t priv, uid_t uid, zoneid_t zoneid)
8226 dtrace_provider_t *pvp = prp->dtpr_provider;
8229 if (pvp->dtpv_defunct)
8232 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8235 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8238 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8241 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8244 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8251 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8252 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
8253 * libc's version, the kernel version only applies to 8-bit ASCII strings.
8254 * In addition, all of the recursion cases except for '*' matching have been
8255 * unwound. For '*', we still implement recursive evaluation, but a depth
8256 * counter is maintained and matching is aborted if we recurse too deep.
8257 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8260 dtrace_match_glob(const char *s, const char *p, int depth)
8266 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8270 s = ""; /* treat NULL as empty string */
8279 if ((c = *p++) == '\0')
8280 return (s1 == '\0');
8284 int ok = 0, notflag = 0;
8295 if ((c = *p++) == '\0')
8299 if (c == '-' && lc != '\0' && *p != ']') {
8300 if ((c = *p++) == '\0')
8302 if (c == '\\' && (c = *p++) == '\0')
8306 if (s1 < lc || s1 > c)
8310 } else if (lc <= s1 && s1 <= c)
8313 } else if (c == '\\' && (c = *p++) == '\0')
8316 lc = c; /* save left-hand 'c' for next iteration */
8326 if ((c = *p++) == '\0')
8338 if ((c = *p++) == '\0')
8354 p++; /* consecutive *'s are identical to a single one */
8359 for (s = olds; *s != '\0'; s++) {
8360 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8370 dtrace_match_string(const char *s, const char *p, int depth)
8372 return (s != NULL && strcmp(s, p) == 0);
8377 dtrace_match_nul(const char *s, const char *p, int depth)
8379 return (1); /* always match the empty pattern */
8384 dtrace_match_nonzero(const char *s, const char *p, int depth)
8386 return (s != NULL && s[0] != '\0');
8390 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8391 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8393 dtrace_probe_t template, *probe;
8394 dtrace_hash_t *hash = NULL;
8395 int len, best = INT_MAX, nmatched = 0;
8398 ASSERT(MUTEX_HELD(&dtrace_lock));
8401 * If the probe ID is specified in the key, just lookup by ID and
8402 * invoke the match callback once if a matching probe is found.
8404 if (pkp->dtpk_id != DTRACE_IDNONE) {
8405 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8406 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8407 (void) (*matched)(probe, arg);
8413 template.dtpr_mod = (char *)pkp->dtpk_mod;
8414 template.dtpr_func = (char *)pkp->dtpk_func;
8415 template.dtpr_name = (char *)pkp->dtpk_name;
8418 * We want to find the most distinct of the module name, function
8419 * name, and name. So for each one that is not a glob pattern or
8420 * empty string, we perform a lookup in the corresponding hash and
8421 * use the hash table with the fewest collisions to do our search.
8423 if (pkp->dtpk_mmatch == &dtrace_match_string &&
8424 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8426 hash = dtrace_bymod;
8429 if (pkp->dtpk_fmatch == &dtrace_match_string &&
8430 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8432 hash = dtrace_byfunc;
8435 if (pkp->dtpk_nmatch == &dtrace_match_string &&
8436 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8438 hash = dtrace_byname;
8442 * If we did not select a hash table, iterate over every probe and
8443 * invoke our callback for each one that matches our input probe key.
8446 for (i = 0; i < dtrace_nprobes; i++) {
8447 if ((probe = dtrace_probes[i]) == NULL ||
8448 dtrace_match_probe(probe, pkp, priv, uid,
8454 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8462 * If we selected a hash table, iterate over each probe of the same key
8463 * name and invoke the callback for every probe that matches the other
8464 * attributes of our input probe key.
8466 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8467 probe = *(DTRACE_HASHNEXT(hash, probe))) {
8469 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8474 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8482 * Return the function pointer dtrace_probecmp() should use to compare the
8483 * specified pattern with a string. For NULL or empty patterns, we select
8484 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
8485 * For non-empty non-glob strings, we use dtrace_match_string().
8487 static dtrace_probekey_f *
8488 dtrace_probekey_func(const char *p)
8492 if (p == NULL || *p == '\0')
8493 return (&dtrace_match_nul);
8495 while ((c = *p++) != '\0') {
8496 if (c == '[' || c == '?' || c == '*' || c == '\\')
8497 return (&dtrace_match_glob);
8500 return (&dtrace_match_string);
8504 * Build a probe comparison key for use with dtrace_match_probe() from the
8505 * given probe description. By convention, a null key only matches anchored
8506 * probes: if each field is the empty string, reset dtpk_fmatch to
8507 * dtrace_match_nonzero().
8510 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8512 pkp->dtpk_prov = pdp->dtpd_provider;
8513 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8515 pkp->dtpk_mod = pdp->dtpd_mod;
8516 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8518 pkp->dtpk_func = pdp->dtpd_func;
8519 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8521 pkp->dtpk_name = pdp->dtpd_name;
8522 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8524 pkp->dtpk_id = pdp->dtpd_id;
8526 if (pkp->dtpk_id == DTRACE_IDNONE &&
8527 pkp->dtpk_pmatch == &dtrace_match_nul &&
8528 pkp->dtpk_mmatch == &dtrace_match_nul &&
8529 pkp->dtpk_fmatch == &dtrace_match_nul &&
8530 pkp->dtpk_nmatch == &dtrace_match_nul)
8531 pkp->dtpk_fmatch = &dtrace_match_nonzero;
8535 * DTrace Provider-to-Framework API Functions
8537 * These functions implement much of the Provider-to-Framework API, as
8538 * described in <sys/dtrace.h>. The parts of the API not in this section are
8539 * the functions in the API for probe management (found below), and
8540 * dtrace_probe() itself (found above).
8544 * Register the calling provider with the DTrace framework. This should
8545 * generally be called by DTrace providers in their attach(9E) entry point.
8548 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8549 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8551 dtrace_provider_t *provider;
8553 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8554 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8555 "arguments", name ? name : "<NULL>");
8559 if (name[0] == '\0' || dtrace_badname(name)) {
8560 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8561 "provider name", name);
8565 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8566 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8567 pops->dtps_destroy == NULL ||
8568 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8569 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8570 "provider ops", name);
8574 if (dtrace_badattr(&pap->dtpa_provider) ||
8575 dtrace_badattr(&pap->dtpa_mod) ||
8576 dtrace_badattr(&pap->dtpa_func) ||
8577 dtrace_badattr(&pap->dtpa_name) ||
8578 dtrace_badattr(&pap->dtpa_args)) {
8579 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8580 "provider attributes", name);
8584 if (priv & ~DTRACE_PRIV_ALL) {
8585 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8586 "privilege attributes", name);
8590 if ((priv & DTRACE_PRIV_KERNEL) &&
8591 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8592 pops->dtps_usermode == NULL) {
8593 cmn_err(CE_WARN, "failed to register provider '%s': need "
8594 "dtps_usermode() op for given privilege attributes", name);
8598 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8599 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8600 (void) strcpy(provider->dtpv_name, name);
8602 provider->dtpv_attr = *pap;
8603 provider->dtpv_priv.dtpp_flags = priv;
8605 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8606 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8608 provider->dtpv_pops = *pops;
8610 if (pops->dtps_provide == NULL) {
8611 ASSERT(pops->dtps_provide_module != NULL);
8612 provider->dtpv_pops.dtps_provide =
8613 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8616 if (pops->dtps_provide_module == NULL) {
8617 ASSERT(pops->dtps_provide != NULL);
8618 provider->dtpv_pops.dtps_provide_module =
8619 (void (*)(void *, modctl_t *))dtrace_nullop;
8622 if (pops->dtps_suspend == NULL) {
8623 ASSERT(pops->dtps_resume == NULL);
8624 provider->dtpv_pops.dtps_suspend =
8625 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8626 provider->dtpv_pops.dtps_resume =
8627 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8630 provider->dtpv_arg = arg;
8631 *idp = (dtrace_provider_id_t)provider;
8633 if (pops == &dtrace_provider_ops) {
8634 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8635 ASSERT(MUTEX_HELD(&dtrace_lock));
8636 ASSERT(dtrace_anon.dta_enabling == NULL);
8639 * We make sure that the DTrace provider is at the head of
8640 * the provider chain.
8642 provider->dtpv_next = dtrace_provider;
8643 dtrace_provider = provider;
8647 mutex_enter(&dtrace_provider_lock);
8648 mutex_enter(&dtrace_lock);
8651 * If there is at least one provider registered, we'll add this
8652 * provider after the first provider.
8654 if (dtrace_provider != NULL) {
8655 provider->dtpv_next = dtrace_provider->dtpv_next;
8656 dtrace_provider->dtpv_next = provider;
8658 dtrace_provider = provider;
8661 if (dtrace_retained != NULL) {
8662 dtrace_enabling_provide(provider);
8665 * Now we need to call dtrace_enabling_matchall() -- which
8666 * will acquire cpu_lock and dtrace_lock. We therefore need
8667 * to drop all of our locks before calling into it...
8669 mutex_exit(&dtrace_lock);
8670 mutex_exit(&dtrace_provider_lock);
8671 dtrace_enabling_matchall();
8676 mutex_exit(&dtrace_lock);
8677 mutex_exit(&dtrace_provider_lock);
8683 * Unregister the specified provider from the DTrace framework. This should
8684 * generally be called by DTrace providers in their detach(9E) entry point.
8687 dtrace_unregister(dtrace_provider_id_t id)
8689 dtrace_provider_t *old = (dtrace_provider_t *)id;
8690 dtrace_provider_t *prev = NULL;
8691 int i, self = 0, noreap = 0;
8692 dtrace_probe_t *probe, *first = NULL;
8694 if (old->dtpv_pops.dtps_enable ==
8695 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8697 * If DTrace itself is the provider, we're called with locks
8700 ASSERT(old == dtrace_provider);
8702 ASSERT(dtrace_devi != NULL);
8704 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8705 ASSERT(MUTEX_HELD(&dtrace_lock));
8708 if (dtrace_provider->dtpv_next != NULL) {
8710 * There's another provider here; return failure.
8715 mutex_enter(&dtrace_provider_lock);
8717 mutex_enter(&mod_lock);
8719 mutex_enter(&dtrace_lock);
8723 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8724 * probes, we refuse to let providers slither away, unless this
8725 * provider has already been explicitly invalidated.
8727 if (!old->dtpv_defunct &&
8728 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8729 dtrace_anon.dta_state->dts_necbs > 0))) {
8731 mutex_exit(&dtrace_lock);
8733 mutex_exit(&mod_lock);
8735 mutex_exit(&dtrace_provider_lock);
8741 * Attempt to destroy the probes associated with this provider.
8743 for (i = 0; i < dtrace_nprobes; i++) {
8744 if ((probe = dtrace_probes[i]) == NULL)
8747 if (probe->dtpr_provider != old)
8750 if (probe->dtpr_ecb == NULL)
8754 * If we are trying to unregister a defunct provider, and the
8755 * provider was made defunct within the interval dictated by
8756 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8757 * attempt to reap our enablings. To denote that the provider
8758 * should reattempt to unregister itself at some point in the
8759 * future, we will return a differentiable error code (EAGAIN
8760 * instead of EBUSY) in this case.
8762 if (dtrace_gethrtime() - old->dtpv_defunct >
8763 dtrace_unregister_defunct_reap)
8767 mutex_exit(&dtrace_lock);
8769 mutex_exit(&mod_lock);
8771 mutex_exit(&dtrace_provider_lock);
8777 (void) taskq_dispatch(dtrace_taskq,
8778 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8784 * All of the probes for this provider are disabled; we can safely
8785 * remove all of them from their hash chains and from the probe array.
8787 for (i = 0; i < dtrace_nprobes; i++) {
8788 if ((probe = dtrace_probes[i]) == NULL)
8791 if (probe->dtpr_provider != old)
8794 dtrace_probes[i] = NULL;
8796 dtrace_hash_remove(dtrace_bymod, probe);
8797 dtrace_hash_remove(dtrace_byfunc, probe);
8798 dtrace_hash_remove(dtrace_byname, probe);
8800 if (first == NULL) {
8802 probe->dtpr_nextmod = NULL;
8804 probe->dtpr_nextmod = first;
8810 * The provider's probes have been removed from the hash chains and
8811 * from the probe array. Now issue a dtrace_sync() to be sure that
8812 * everyone has cleared out from any probe array processing.
8816 for (probe = first; probe != NULL; probe = first) {
8817 first = probe->dtpr_nextmod;
8819 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8821 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8822 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8823 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8825 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8827 free_unr(dtrace_arena, probe->dtpr_id);
8829 kmem_free(probe, sizeof (dtrace_probe_t));
8832 if ((prev = dtrace_provider) == old) {
8834 ASSERT(self || dtrace_devi == NULL);
8835 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8837 dtrace_provider = old->dtpv_next;
8839 while (prev != NULL && prev->dtpv_next != old)
8840 prev = prev->dtpv_next;
8843 panic("attempt to unregister non-existent "
8844 "dtrace provider %p\n", (void *)id);
8847 prev->dtpv_next = old->dtpv_next;
8851 mutex_exit(&dtrace_lock);
8853 mutex_exit(&mod_lock);
8855 mutex_exit(&dtrace_provider_lock);
8858 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8859 kmem_free(old, sizeof (dtrace_provider_t));
8865 * Invalidate the specified provider. All subsequent probe lookups for the
8866 * specified provider will fail, but its probes will not be removed.
8869 dtrace_invalidate(dtrace_provider_id_t id)
8871 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8873 ASSERT(pvp->dtpv_pops.dtps_enable !=
8874 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8876 mutex_enter(&dtrace_provider_lock);
8877 mutex_enter(&dtrace_lock);
8879 pvp->dtpv_defunct = dtrace_gethrtime();
8881 mutex_exit(&dtrace_lock);
8882 mutex_exit(&dtrace_provider_lock);
8886 * Indicate whether or not DTrace has attached.
8889 dtrace_attached(void)
8892 * dtrace_provider will be non-NULL iff the DTrace driver has
8893 * attached. (It's non-NULL because DTrace is always itself a
8896 return (dtrace_provider != NULL);
8900 * Remove all the unenabled probes for the given provider. This function is
8901 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8902 * -- just as many of its associated probes as it can.
8905 dtrace_condense(dtrace_provider_id_t id)
8907 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8909 dtrace_probe_t *probe;
8912 * Make sure this isn't the dtrace provider itself.
8914 ASSERT(prov->dtpv_pops.dtps_enable !=
8915 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8917 mutex_enter(&dtrace_provider_lock);
8918 mutex_enter(&dtrace_lock);
8921 * Attempt to destroy the probes associated with this provider.
8923 for (i = 0; i < dtrace_nprobes; i++) {
8924 if ((probe = dtrace_probes[i]) == NULL)
8927 if (probe->dtpr_provider != prov)
8930 if (probe->dtpr_ecb != NULL)
8933 dtrace_probes[i] = NULL;
8935 dtrace_hash_remove(dtrace_bymod, probe);
8936 dtrace_hash_remove(dtrace_byfunc, probe);
8937 dtrace_hash_remove(dtrace_byname, probe);
8939 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8941 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8942 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8943 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8944 kmem_free(probe, sizeof (dtrace_probe_t));
8946 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8948 free_unr(dtrace_arena, i + 1);
8952 mutex_exit(&dtrace_lock);
8953 mutex_exit(&dtrace_provider_lock);
8959 * DTrace Probe Management Functions
8961 * The functions in this section perform the DTrace probe management,
8962 * including functions to create probes, look-up probes, and call into the
8963 * providers to request that probes be provided. Some of these functions are
8964 * in the Provider-to-Framework API; these functions can be identified by the
8965 * fact that they are not declared "static".
8969 * Create a probe with the specified module name, function name, and name.
8972 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8973 const char *func, const char *name, int aframes, void *arg)
8975 dtrace_probe_t *probe, **probes;
8976 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8979 if (provider == dtrace_provider) {
8980 ASSERT(MUTEX_HELD(&dtrace_lock));
8982 mutex_enter(&dtrace_lock);
8986 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8987 VM_BESTFIT | VM_SLEEP);
8989 id = alloc_unr(dtrace_arena);
8991 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8993 probe->dtpr_id = id;
8994 probe->dtpr_gen = dtrace_probegen++;
8995 probe->dtpr_mod = dtrace_strdup(mod);
8996 probe->dtpr_func = dtrace_strdup(func);
8997 probe->dtpr_name = dtrace_strdup(name);
8998 probe->dtpr_arg = arg;
8999 probe->dtpr_aframes = aframes;
9000 probe->dtpr_provider = provider;
9002 dtrace_hash_add(dtrace_bymod, probe);
9003 dtrace_hash_add(dtrace_byfunc, probe);
9004 dtrace_hash_add(dtrace_byname, probe);
9006 if (id - 1 >= dtrace_nprobes) {
9007 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9008 size_t nsize = osize << 1;
9012 ASSERT(dtrace_probes == NULL);
9013 nsize = sizeof (dtrace_probe_t *);
9016 probes = kmem_zalloc(nsize, KM_SLEEP);
9018 if (dtrace_probes == NULL) {
9020 dtrace_probes = probes;
9023 dtrace_probe_t **oprobes = dtrace_probes;
9025 bcopy(oprobes, probes, osize);
9026 dtrace_membar_producer();
9027 dtrace_probes = probes;
9032 * All CPUs are now seeing the new probes array; we can
9033 * safely free the old array.
9035 kmem_free(oprobes, osize);
9036 dtrace_nprobes <<= 1;
9039 ASSERT(id - 1 < dtrace_nprobes);
9042 ASSERT(dtrace_probes[id - 1] == NULL);
9043 dtrace_probes[id - 1] = probe;
9045 if (provider != dtrace_provider)
9046 mutex_exit(&dtrace_lock);
9051 static dtrace_probe_t *
9052 dtrace_probe_lookup_id(dtrace_id_t id)
9054 ASSERT(MUTEX_HELD(&dtrace_lock));
9056 if (id == 0 || id > dtrace_nprobes)
9059 return (dtrace_probes[id - 1]);
9063 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9065 *((dtrace_id_t *)arg) = probe->dtpr_id;
9067 return (DTRACE_MATCH_DONE);
9071 * Look up a probe based on provider and one or more of module name, function
9072 * name and probe name.
9075 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9076 char *func, char *name)
9078 dtrace_probekey_t pkey;
9082 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9083 pkey.dtpk_pmatch = &dtrace_match_string;
9084 pkey.dtpk_mod = mod;
9085 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9086 pkey.dtpk_func = func;
9087 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9088 pkey.dtpk_name = name;
9089 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9090 pkey.dtpk_id = DTRACE_IDNONE;
9092 mutex_enter(&dtrace_lock);
9093 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9094 dtrace_probe_lookup_match, &id);
9095 mutex_exit(&dtrace_lock);
9097 ASSERT(match == 1 || match == 0);
9098 return (match ? id : 0);
9102 * Returns the probe argument associated with the specified probe.
9105 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9107 dtrace_probe_t *probe;
9110 mutex_enter(&dtrace_lock);
9112 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9113 probe->dtpr_provider == (dtrace_provider_t *)id)
9114 rval = probe->dtpr_arg;
9116 mutex_exit(&dtrace_lock);
9122 * Copy a probe into a probe description.
9125 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9127 bzero(pdp, sizeof (dtrace_probedesc_t));
9128 pdp->dtpd_id = prp->dtpr_id;
9130 (void) strncpy(pdp->dtpd_provider,
9131 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9133 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9134 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9135 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9139 * Called to indicate that a probe -- or probes -- should be provided by a
9140 * specfied provider. If the specified description is NULL, the provider will
9141 * be told to provide all of its probes. (This is done whenever a new
9142 * consumer comes along, or whenever a retained enabling is to be matched.) If
9143 * the specified description is non-NULL, the provider is given the
9144 * opportunity to dynamically provide the specified probe, allowing providers
9145 * to support the creation of probes on-the-fly. (So-called _autocreated_
9146 * probes.) If the provider is NULL, the operations will be applied to all
9147 * providers; if the provider is non-NULL the operations will only be applied
9148 * to the specified provider. The dtrace_provider_lock must be held, and the
9149 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9150 * will need to grab the dtrace_lock when it reenters the framework through
9151 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9154 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9161 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9165 prv = dtrace_provider;
9170 * First, call the blanket provide operation.
9172 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9176 * Now call the per-module provide operation. We will grab
9177 * mod_lock to prevent the list from being modified. Note
9178 * that this also prevents the mod_busy bits from changing.
9179 * (mod_busy can only be changed with mod_lock held.)
9181 mutex_enter(&mod_lock);
9185 if (ctl->mod_busy || ctl->mod_mp == NULL)
9188 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9190 } while ((ctl = ctl->mod_next) != &modules);
9192 mutex_exit(&mod_lock);
9194 } while (all && (prv = prv->dtpv_next) != NULL);
9199 * Iterate over each probe, and call the Framework-to-Provider API function
9203 dtrace_probe_foreach(uintptr_t offs)
9205 dtrace_provider_t *prov;
9206 void (*func)(void *, dtrace_id_t, void *);
9207 dtrace_probe_t *probe;
9208 dtrace_icookie_t cookie;
9212 * We disable interrupts to walk through the probe array. This is
9213 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9214 * won't see stale data.
9216 cookie = dtrace_interrupt_disable();
9218 for (i = 0; i < dtrace_nprobes; i++) {
9219 if ((probe = dtrace_probes[i]) == NULL)
9222 if (probe->dtpr_ecb == NULL) {
9224 * This probe isn't enabled -- don't call the function.
9229 prov = probe->dtpr_provider;
9230 func = *((void(**)(void *, dtrace_id_t, void *))
9231 ((uintptr_t)&prov->dtpv_pops + offs));
9233 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9236 dtrace_interrupt_enable(cookie);
9241 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9243 dtrace_probekey_t pkey;
9248 ASSERT(MUTEX_HELD(&dtrace_lock));
9249 dtrace_ecb_create_cache = NULL;
9253 * If we're passed a NULL description, we're being asked to
9254 * create an ECB with a NULL probe.
9256 (void) dtrace_ecb_create_enable(NULL, enab);
9260 dtrace_probekey(desc, &pkey);
9261 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9262 &priv, &uid, &zoneid);
9264 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9269 * DTrace Helper Provider Functions
9272 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9274 attr->dtat_name = DOF_ATTR_NAME(dofattr);
9275 attr->dtat_data = DOF_ATTR_DATA(dofattr);
9276 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9280 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9281 const dof_provider_t *dofprov, char *strtab)
9283 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9284 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9285 dofprov->dofpv_provattr);
9286 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9287 dofprov->dofpv_modattr);
9288 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9289 dofprov->dofpv_funcattr);
9290 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9291 dofprov->dofpv_nameattr);
9292 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9293 dofprov->dofpv_argsattr);
9297 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9299 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9300 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9301 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9302 dof_provider_t *provider;
9304 uint32_t *off, *enoff;
9308 dtrace_helper_provdesc_t dhpv;
9309 dtrace_helper_probedesc_t dhpb;
9310 dtrace_meta_t *meta = dtrace_meta_pid;
9311 dtrace_mops_t *mops = &meta->dtm_mops;
9314 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9315 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9316 provider->dofpv_strtab * dof->dofh_secsize);
9317 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9318 provider->dofpv_probes * dof->dofh_secsize);
9319 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9320 provider->dofpv_prargs * dof->dofh_secsize);
9321 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9322 provider->dofpv_proffs * dof->dofh_secsize);
9324 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9325 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9326 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9330 * See dtrace_helper_provider_validate().
9332 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9333 provider->dofpv_prenoffs != DOF_SECT_NONE) {
9334 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9335 provider->dofpv_prenoffs * dof->dofh_secsize);
9336 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9339 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9342 * Create the provider.
9344 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9346 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9352 * Create the probes.
9354 for (i = 0; i < nprobes; i++) {
9355 probe = (dof_probe_t *)(uintptr_t)(daddr +
9356 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9358 dhpb.dthpb_mod = dhp->dofhp_mod;
9359 dhpb.dthpb_func = strtab + probe->dofpr_func;
9360 dhpb.dthpb_name = strtab + probe->dofpr_name;
9361 dhpb.dthpb_base = probe->dofpr_addr;
9362 dhpb.dthpb_offs = off + probe->dofpr_offidx;
9363 dhpb.dthpb_noffs = probe->dofpr_noffs;
9364 if (enoff != NULL) {
9365 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9366 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9368 dhpb.dthpb_enoffs = NULL;
9369 dhpb.dthpb_nenoffs = 0;
9371 dhpb.dthpb_args = arg + probe->dofpr_argidx;
9372 dhpb.dthpb_nargc = probe->dofpr_nargc;
9373 dhpb.dthpb_xargc = probe->dofpr_xargc;
9374 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9375 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9377 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9382 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9384 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9385 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9388 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9390 for (i = 0; i < dof->dofh_secnum; i++) {
9391 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9392 dof->dofh_secoff + i * dof->dofh_secsize);
9394 if (sec->dofs_type != DOF_SECT_PROVIDER)
9397 dtrace_helper_provide_one(dhp, sec, pid);
9401 * We may have just created probes, so we must now rematch against
9402 * any retained enablings. Note that this call will acquire both
9403 * cpu_lock and dtrace_lock; the fact that we are holding
9404 * dtrace_meta_lock now is what defines the ordering with respect to
9405 * these three locks.
9407 dtrace_enabling_matchall();
9411 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9413 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9414 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9416 dof_provider_t *provider;
9418 dtrace_helper_provdesc_t dhpv;
9419 dtrace_meta_t *meta = dtrace_meta_pid;
9420 dtrace_mops_t *mops = &meta->dtm_mops;
9422 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9423 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9424 provider->dofpv_strtab * dof->dofh_secsize);
9426 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9429 * Create the provider.
9431 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9433 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9439 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9441 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9442 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9445 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9447 for (i = 0; i < dof->dofh_secnum; i++) {
9448 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9449 dof->dofh_secoff + i * dof->dofh_secsize);
9451 if (sec->dofs_type != DOF_SECT_PROVIDER)
9454 dtrace_helper_provider_remove_one(dhp, sec, pid);
9459 * DTrace Meta Provider-to-Framework API Functions
9461 * These functions implement the Meta Provider-to-Framework API, as described
9462 * in <sys/dtrace.h>.
9465 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9466 dtrace_meta_provider_id_t *idp)
9468 dtrace_meta_t *meta;
9469 dtrace_helpers_t *help, *next;
9472 *idp = DTRACE_METAPROVNONE;
9475 * We strictly don't need the name, but we hold onto it for
9476 * debuggability. All hail error queues!
9479 cmn_err(CE_WARN, "failed to register meta-provider: "
9485 mops->dtms_create_probe == NULL ||
9486 mops->dtms_provide_pid == NULL ||
9487 mops->dtms_remove_pid == NULL) {
9488 cmn_err(CE_WARN, "failed to register meta-register %s: "
9489 "invalid ops", name);
9493 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9494 meta->dtm_mops = *mops;
9495 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9496 (void) strcpy(meta->dtm_name, name);
9497 meta->dtm_arg = arg;
9499 mutex_enter(&dtrace_meta_lock);
9500 mutex_enter(&dtrace_lock);
9502 if (dtrace_meta_pid != NULL) {
9503 mutex_exit(&dtrace_lock);
9504 mutex_exit(&dtrace_meta_lock);
9505 cmn_err(CE_WARN, "failed to register meta-register %s: "
9506 "user-land meta-provider exists", name);
9507 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9508 kmem_free(meta, sizeof (dtrace_meta_t));
9512 dtrace_meta_pid = meta;
9513 *idp = (dtrace_meta_provider_id_t)meta;
9516 * If there are providers and probes ready to go, pass them
9517 * off to the new meta provider now.
9520 help = dtrace_deferred_pid;
9521 dtrace_deferred_pid = NULL;
9523 mutex_exit(&dtrace_lock);
9525 while (help != NULL) {
9526 for (i = 0; i < help->dthps_nprovs; i++) {
9527 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9531 next = help->dthps_next;
9532 help->dthps_next = NULL;
9533 help->dthps_prev = NULL;
9534 help->dthps_deferred = 0;
9538 mutex_exit(&dtrace_meta_lock);
9544 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9546 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9548 mutex_enter(&dtrace_meta_lock);
9549 mutex_enter(&dtrace_lock);
9551 if (old == dtrace_meta_pid) {
9552 pp = &dtrace_meta_pid;
9554 panic("attempt to unregister non-existent "
9555 "dtrace meta-provider %p\n", (void *)old);
9558 if (old->dtm_count != 0) {
9559 mutex_exit(&dtrace_lock);
9560 mutex_exit(&dtrace_meta_lock);
9566 mutex_exit(&dtrace_lock);
9567 mutex_exit(&dtrace_meta_lock);
9569 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9570 kmem_free(old, sizeof (dtrace_meta_t));
9577 * DTrace DIF Object Functions
9580 dtrace_difo_err(uint_t pc, const char *format, ...)
9582 if (dtrace_err_verbose) {
9585 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
9586 va_start(alist, format);
9587 (void) vuprintf(format, alist);
9591 #ifdef DTRACE_ERRDEBUG
9592 dtrace_errdebug(format);
9598 * Validate a DTrace DIF object by checking the IR instructions. The following
9599 * rules are currently enforced by dtrace_difo_validate():
9601 * 1. Each instruction must have a valid opcode
9602 * 2. Each register, string, variable, or subroutine reference must be valid
9603 * 3. No instruction can modify register %r0 (must be zero)
9604 * 4. All instruction reserved bits must be set to zero
9605 * 5. The last instruction must be a "ret" instruction
9606 * 6. All branch targets must reference a valid instruction _after_ the branch
9609 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9613 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9616 int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9618 kcheckload = cr == NULL ||
9619 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9621 dp->dtdo_destructive = 0;
9623 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9624 dif_instr_t instr = dp->dtdo_buf[pc];
9626 uint_t r1 = DIF_INSTR_R1(instr);
9627 uint_t r2 = DIF_INSTR_R2(instr);
9628 uint_t rd = DIF_INSTR_RD(instr);
9629 uint_t rs = DIF_INSTR_RS(instr);
9630 uint_t label = DIF_INSTR_LABEL(instr);
9631 uint_t v = DIF_INSTR_VAR(instr);
9632 uint_t subr = DIF_INSTR_SUBR(instr);
9633 uint_t type = DIF_INSTR_TYPE(instr);
9634 uint_t op = DIF_INSTR_OP(instr);
9652 err += efunc(pc, "invalid register %u\n", r1);
9654 err += efunc(pc, "invalid register %u\n", r2);
9656 err += efunc(pc, "invalid register %u\n", rd);
9658 err += efunc(pc, "cannot write to %r0\n");
9664 err += efunc(pc, "invalid register %u\n", r1);
9666 err += efunc(pc, "non-zero reserved bits\n");
9668 err += efunc(pc, "invalid register %u\n", rd);
9670 err += efunc(pc, "cannot write to %r0\n");
9680 err += efunc(pc, "invalid register %u\n", r1);
9682 err += efunc(pc, "non-zero reserved bits\n");
9684 err += efunc(pc, "invalid register %u\n", rd);
9686 err += efunc(pc, "cannot write to %r0\n");
9688 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9689 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9699 err += efunc(pc, "invalid register %u\n", r1);
9701 err += efunc(pc, "non-zero reserved bits\n");
9703 err += efunc(pc, "invalid register %u\n", rd);
9705 err += efunc(pc, "cannot write to %r0\n");
9715 err += efunc(pc, "invalid register %u\n", r1);
9717 err += efunc(pc, "non-zero reserved bits\n");
9719 err += efunc(pc, "invalid register %u\n", rd);
9721 err += efunc(pc, "cannot write to %r0\n");
9728 err += efunc(pc, "invalid register %u\n", r1);
9730 err += efunc(pc, "non-zero reserved bits\n");
9732 err += efunc(pc, "invalid register %u\n", rd);
9734 err += efunc(pc, "cannot write to 0 address\n");
9739 err += efunc(pc, "invalid register %u\n", r1);
9741 err += efunc(pc, "invalid register %u\n", r2);
9743 err += efunc(pc, "non-zero reserved bits\n");
9747 err += efunc(pc, "invalid register %u\n", r1);
9748 if (r2 != 0 || rd != 0)
9749 err += efunc(pc, "non-zero reserved bits\n");
9762 if (label >= dp->dtdo_len) {
9763 err += efunc(pc, "invalid branch target %u\n",
9767 err += efunc(pc, "backward branch to %u\n",
9772 if (r1 != 0 || r2 != 0)
9773 err += efunc(pc, "non-zero reserved bits\n");
9775 err += efunc(pc, "invalid register %u\n", rd);
9779 case DIF_OP_FLUSHTS:
9780 if (r1 != 0 || r2 != 0 || rd != 0)
9781 err += efunc(pc, "non-zero reserved bits\n");
9784 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9785 err += efunc(pc, "invalid integer ref %u\n",
9786 DIF_INSTR_INTEGER(instr));
9789 err += efunc(pc, "invalid register %u\n", rd);
9791 err += efunc(pc, "cannot write to %r0\n");
9794 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9795 err += efunc(pc, "invalid string ref %u\n",
9796 DIF_INSTR_STRING(instr));
9799 err += efunc(pc, "invalid register %u\n", rd);
9801 err += efunc(pc, "cannot write to %r0\n");
9805 if (r1 > DIF_VAR_ARRAY_MAX)
9806 err += efunc(pc, "invalid array %u\n", r1);
9808 err += efunc(pc, "invalid register %u\n", r2);
9810 err += efunc(pc, "invalid register %u\n", rd);
9812 err += efunc(pc, "cannot write to %r0\n");
9819 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9820 err += efunc(pc, "invalid variable %u\n", v);
9822 err += efunc(pc, "invalid register %u\n", rd);
9824 err += efunc(pc, "cannot write to %r0\n");
9831 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9832 err += efunc(pc, "invalid variable %u\n", v);
9834 err += efunc(pc, "invalid register %u\n", rd);
9837 if (subr > DIF_SUBR_MAX)
9838 err += efunc(pc, "invalid subr %u\n", subr);
9840 err += efunc(pc, "invalid register %u\n", rd);
9842 err += efunc(pc, "cannot write to %r0\n");
9844 if (subr == DIF_SUBR_COPYOUT ||
9845 subr == DIF_SUBR_COPYOUTSTR) {
9846 dp->dtdo_destructive = 1;
9849 if (subr == DIF_SUBR_GETF) {
9851 * If we have a getf() we need to record that
9852 * in our state. Note that our state can be
9853 * NULL if this is a helper -- but in that
9854 * case, the call to getf() is itself illegal,
9855 * and will be caught (slightly later) when
9856 * the helper is validated.
9858 if (vstate->dtvs_state != NULL)
9859 vstate->dtvs_state->dts_getf++;
9864 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9865 err += efunc(pc, "invalid ref type %u\n", type);
9867 err += efunc(pc, "invalid register %u\n", r2);
9869 err += efunc(pc, "invalid register %u\n", rs);
9872 if (type != DIF_TYPE_CTF)
9873 err += efunc(pc, "invalid val type %u\n", type);
9875 err += efunc(pc, "invalid register %u\n", r2);
9877 err += efunc(pc, "invalid register %u\n", rs);
9880 err += efunc(pc, "invalid opcode %u\n",
9881 DIF_INSTR_OP(instr));
9885 if (dp->dtdo_len != 0 &&
9886 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9887 err += efunc(dp->dtdo_len - 1,
9888 "expected 'ret' as last DIF instruction\n");
9891 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9893 * If we're not returning by reference, the size must be either
9894 * 0 or the size of one of the base types.
9896 switch (dp->dtdo_rtype.dtdt_size) {
9898 case sizeof (uint8_t):
9899 case sizeof (uint16_t):
9900 case sizeof (uint32_t):
9901 case sizeof (uint64_t):
9905 err += efunc(dp->dtdo_len - 1, "bad return size\n");
9909 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9910 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9911 dtrace_diftype_t *vt, *et;
9914 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9915 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9916 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9917 err += efunc(i, "unrecognized variable scope %d\n",
9922 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9923 v->dtdv_kind != DIFV_KIND_SCALAR) {
9924 err += efunc(i, "unrecognized variable type %d\n",
9929 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9930 err += efunc(i, "%d exceeds variable id limit\n", id);
9934 if (id < DIF_VAR_OTHER_UBASE)
9938 * For user-defined variables, we need to check that this
9939 * definition is identical to any previous definition that we
9942 ndx = id - DIF_VAR_OTHER_UBASE;
9944 switch (v->dtdv_scope) {
9945 case DIFV_SCOPE_GLOBAL:
9946 if (maxglobal == -1 || ndx > maxglobal)
9949 if (ndx < vstate->dtvs_nglobals) {
9950 dtrace_statvar_t *svar;
9952 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9953 existing = &svar->dtsv_var;
9958 case DIFV_SCOPE_THREAD:
9959 if (maxtlocal == -1 || ndx > maxtlocal)
9962 if (ndx < vstate->dtvs_ntlocals)
9963 existing = &vstate->dtvs_tlocals[ndx];
9966 case DIFV_SCOPE_LOCAL:
9967 if (maxlocal == -1 || ndx > maxlocal)
9970 if (ndx < vstate->dtvs_nlocals) {
9971 dtrace_statvar_t *svar;
9973 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9974 existing = &svar->dtsv_var;
9982 if (vt->dtdt_flags & DIF_TF_BYREF) {
9983 if (vt->dtdt_size == 0) {
9984 err += efunc(i, "zero-sized variable\n");
9988 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9989 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9990 vt->dtdt_size > dtrace_statvar_maxsize) {
9991 err += efunc(i, "oversized by-ref static\n");
9996 if (existing == NULL || existing->dtdv_id == 0)
9999 ASSERT(existing->dtdv_id == v->dtdv_id);
10000 ASSERT(existing->dtdv_scope == v->dtdv_scope);
10002 if (existing->dtdv_kind != v->dtdv_kind)
10003 err += efunc(i, "%d changed variable kind\n", id);
10005 et = &existing->dtdv_type;
10007 if (vt->dtdt_flags != et->dtdt_flags) {
10008 err += efunc(i, "%d changed variable type flags\n", id);
10012 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10013 err += efunc(i, "%d changed variable type size\n", id);
10018 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10019 dif_instr_t instr = dp->dtdo_buf[pc];
10021 uint_t v = DIF_INSTR_VAR(instr);
10022 uint_t op = DIF_INSTR_OP(instr);
10029 if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10030 err += efunc(pc, "invalid variable %u\n", v);
10036 if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10037 err += efunc(pc, "invalid variable %u\n", v);
10041 if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10042 err += efunc(pc, "invalid variable %u\n", v);
10053 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
10054 * are much more constrained than normal DIFOs. Specifically, they may
10057 * 1. Make calls to subroutines other than copyin(), copyinstr() or
10058 * miscellaneous string routines
10059 * 2. Access DTrace variables other than the args[] array, and the
10060 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10061 * 3. Have thread-local variables.
10062 * 4. Have dynamic variables.
10065 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10067 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10071 for (pc = 0; pc < dp->dtdo_len; pc++) {
10072 dif_instr_t instr = dp->dtdo_buf[pc];
10074 uint_t v = DIF_INSTR_VAR(instr);
10075 uint_t subr = DIF_INSTR_SUBR(instr);
10076 uint_t op = DIF_INSTR_OP(instr);
10113 case DIF_OP_ALLOCS:
10131 case DIF_OP_FLUSHTS:
10138 case DIF_OP_PUSHTR:
10139 case DIF_OP_PUSHTV:
10143 if (v >= DIF_VAR_OTHER_UBASE)
10146 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10149 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10150 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10151 v == DIF_VAR_EXECARGS ||
10152 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10153 v == DIF_VAR_UID || v == DIF_VAR_GID)
10156 err += efunc(pc, "illegal variable %u\n", v);
10163 err += efunc(pc, "illegal dynamic variable load\n");
10169 err += efunc(pc, "illegal dynamic variable store\n");
10173 if (subr == DIF_SUBR_ALLOCA ||
10174 subr == DIF_SUBR_BCOPY ||
10175 subr == DIF_SUBR_COPYIN ||
10176 subr == DIF_SUBR_COPYINTO ||
10177 subr == DIF_SUBR_COPYINSTR ||
10178 subr == DIF_SUBR_INDEX ||
10179 subr == DIF_SUBR_INET_NTOA ||
10180 subr == DIF_SUBR_INET_NTOA6 ||
10181 subr == DIF_SUBR_INET_NTOP ||
10182 subr == DIF_SUBR_JSON ||
10183 subr == DIF_SUBR_LLTOSTR ||
10184 subr == DIF_SUBR_STRTOLL ||
10185 subr == DIF_SUBR_RINDEX ||
10186 subr == DIF_SUBR_STRCHR ||
10187 subr == DIF_SUBR_STRJOIN ||
10188 subr == DIF_SUBR_STRRCHR ||
10189 subr == DIF_SUBR_STRSTR ||
10190 subr == DIF_SUBR_HTONS ||
10191 subr == DIF_SUBR_HTONL ||
10192 subr == DIF_SUBR_HTONLL ||
10193 subr == DIF_SUBR_NTOHS ||
10194 subr == DIF_SUBR_NTOHL ||
10195 subr == DIF_SUBR_NTOHLL ||
10196 subr == DIF_SUBR_MEMREF ||
10198 subr == DIF_SUBR_MEMSTR ||
10200 subr == DIF_SUBR_TYPEREF)
10203 err += efunc(pc, "invalid subr %u\n", subr);
10207 err += efunc(pc, "invalid opcode %u\n",
10208 DIF_INSTR_OP(instr));
10216 * Returns 1 if the expression in the DIF object can be cached on a per-thread
10220 dtrace_difo_cacheable(dtrace_difo_t *dp)
10227 for (i = 0; i < dp->dtdo_varlen; i++) {
10228 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10230 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10233 switch (v->dtdv_id) {
10234 case DIF_VAR_CURTHREAD:
10237 case DIF_VAR_EXECARGS:
10238 case DIF_VAR_EXECNAME:
10239 case DIF_VAR_ZONENAME:
10248 * This DIF object may be cacheable. Now we need to look for any
10249 * array loading instructions, any memory loading instructions, or
10250 * any stores to thread-local variables.
10252 for (i = 0; i < dp->dtdo_len; i++) {
10253 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10255 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10256 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10257 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10258 op == DIF_OP_LDGA || op == DIF_OP_STTS)
10266 dtrace_difo_hold(dtrace_difo_t *dp)
10270 ASSERT(MUTEX_HELD(&dtrace_lock));
10273 ASSERT(dp->dtdo_refcnt != 0);
10276 * We need to check this DIF object for references to the variable
10277 * DIF_VAR_VTIMESTAMP.
10279 for (i = 0; i < dp->dtdo_varlen; i++) {
10280 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10282 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10285 if (dtrace_vtime_references++ == 0)
10286 dtrace_vtime_enable();
10291 * This routine calculates the dynamic variable chunksize for a given DIF
10292 * object. The calculation is not fool-proof, and can probably be tricked by
10293 * malicious DIF -- but it works for all compiler-generated DIF. Because this
10294 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10295 * if a dynamic variable size exceeds the chunksize.
10298 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10301 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10302 const dif_instr_t *text = dp->dtdo_buf;
10303 uint_t pc, srd = 0;
10305 size_t size, ksize;
10308 for (pc = 0; pc < dp->dtdo_len; pc++) {
10309 dif_instr_t instr = text[pc];
10310 uint_t op = DIF_INSTR_OP(instr);
10311 uint_t rd = DIF_INSTR_RD(instr);
10312 uint_t r1 = DIF_INSTR_R1(instr);
10316 dtrace_key_t *key = tupregs;
10320 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10325 key = &tupregs[DIF_DTR_NREGS];
10326 key[0].dttk_size = 0;
10327 key[1].dttk_size = 0;
10329 scope = DIFV_SCOPE_THREAD;
10336 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10337 key[nkeys++].dttk_size = 0;
10339 key[nkeys++].dttk_size = 0;
10341 if (op == DIF_OP_STTAA) {
10342 scope = DIFV_SCOPE_THREAD;
10344 scope = DIFV_SCOPE_GLOBAL;
10349 case DIF_OP_PUSHTR:
10350 if (ttop == DIF_DTR_NREGS)
10353 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10355 * If the register for the size of the "pushtr"
10356 * is %r0 (or the value is 0) and the type is
10357 * a string, we'll use the system-wide default
10360 tupregs[ttop++].dttk_size =
10361 dtrace_strsize_default;
10366 if (sval > LONG_MAX)
10369 tupregs[ttop++].dttk_size = sval;
10374 case DIF_OP_PUSHTV:
10375 if (ttop == DIF_DTR_NREGS)
10378 tupregs[ttop++].dttk_size = 0;
10381 case DIF_OP_FLUSHTS:
10398 * We have a dynamic variable allocation; calculate its size.
10400 for (ksize = 0, i = 0; i < nkeys; i++)
10401 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10403 size = sizeof (dtrace_dynvar_t);
10404 size += sizeof (dtrace_key_t) * (nkeys - 1);
10408 * Now we need to determine the size of the stored data.
10410 id = DIF_INSTR_VAR(instr);
10412 for (i = 0; i < dp->dtdo_varlen; i++) {
10413 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10415 if (v->dtdv_id == id && v->dtdv_scope == scope) {
10416 size += v->dtdv_type.dtdt_size;
10421 if (i == dp->dtdo_varlen)
10425 * We have the size. If this is larger than the chunk size
10426 * for our dynamic variable state, reset the chunk size.
10428 size = P2ROUNDUP(size, sizeof (uint64_t));
10431 * Before setting the chunk size, check that we're not going
10432 * to set it to a negative value...
10434 if (size > LONG_MAX)
10438 * ...and make certain that we didn't badly overflow.
10440 if (size < ksize || size < sizeof (dtrace_dynvar_t))
10443 if (size > vstate->dtvs_dynvars.dtds_chunksize)
10444 vstate->dtvs_dynvars.dtds_chunksize = size;
10449 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10451 int i, oldsvars, osz, nsz, otlocals, ntlocals;
10454 ASSERT(MUTEX_HELD(&dtrace_lock));
10455 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10457 for (i = 0; i < dp->dtdo_varlen; i++) {
10458 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10459 dtrace_statvar_t *svar, ***svarp = NULL;
10461 uint8_t scope = v->dtdv_scope;
10464 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10467 id -= DIF_VAR_OTHER_UBASE;
10470 case DIFV_SCOPE_THREAD:
10471 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10472 dtrace_difv_t *tlocals;
10474 if ((ntlocals = (otlocals << 1)) == 0)
10477 osz = otlocals * sizeof (dtrace_difv_t);
10478 nsz = ntlocals * sizeof (dtrace_difv_t);
10480 tlocals = kmem_zalloc(nsz, KM_SLEEP);
10483 bcopy(vstate->dtvs_tlocals,
10485 kmem_free(vstate->dtvs_tlocals, osz);
10488 vstate->dtvs_tlocals = tlocals;
10489 vstate->dtvs_ntlocals = ntlocals;
10492 vstate->dtvs_tlocals[id] = *v;
10495 case DIFV_SCOPE_LOCAL:
10496 np = &vstate->dtvs_nlocals;
10497 svarp = &vstate->dtvs_locals;
10499 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10500 dsize = NCPU * (v->dtdv_type.dtdt_size +
10501 sizeof (uint64_t));
10503 dsize = NCPU * sizeof (uint64_t);
10507 case DIFV_SCOPE_GLOBAL:
10508 np = &vstate->dtvs_nglobals;
10509 svarp = &vstate->dtvs_globals;
10511 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10512 dsize = v->dtdv_type.dtdt_size +
10521 while (id >= (oldsvars = *np)) {
10522 dtrace_statvar_t **statics;
10523 int newsvars, oldsize, newsize;
10525 if ((newsvars = (oldsvars << 1)) == 0)
10528 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10529 newsize = newsvars * sizeof (dtrace_statvar_t *);
10531 statics = kmem_zalloc(newsize, KM_SLEEP);
10533 if (oldsize != 0) {
10534 bcopy(*svarp, statics, oldsize);
10535 kmem_free(*svarp, oldsize);
10542 if ((svar = (*svarp)[id]) == NULL) {
10543 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10544 svar->dtsv_var = *v;
10546 if ((svar->dtsv_size = dsize) != 0) {
10547 svar->dtsv_data = (uint64_t)(uintptr_t)
10548 kmem_zalloc(dsize, KM_SLEEP);
10551 (*svarp)[id] = svar;
10554 svar->dtsv_refcnt++;
10557 dtrace_difo_chunksize(dp, vstate);
10558 dtrace_difo_hold(dp);
10561 static dtrace_difo_t *
10562 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10564 dtrace_difo_t *new;
10567 ASSERT(dp->dtdo_buf != NULL);
10568 ASSERT(dp->dtdo_refcnt != 0);
10570 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10572 ASSERT(dp->dtdo_buf != NULL);
10573 sz = dp->dtdo_len * sizeof (dif_instr_t);
10574 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10575 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10576 new->dtdo_len = dp->dtdo_len;
10578 if (dp->dtdo_strtab != NULL) {
10579 ASSERT(dp->dtdo_strlen != 0);
10580 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10581 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10582 new->dtdo_strlen = dp->dtdo_strlen;
10585 if (dp->dtdo_inttab != NULL) {
10586 ASSERT(dp->dtdo_intlen != 0);
10587 sz = dp->dtdo_intlen * sizeof (uint64_t);
10588 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10589 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10590 new->dtdo_intlen = dp->dtdo_intlen;
10593 if (dp->dtdo_vartab != NULL) {
10594 ASSERT(dp->dtdo_varlen != 0);
10595 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10596 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10597 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10598 new->dtdo_varlen = dp->dtdo_varlen;
10601 dtrace_difo_init(new, vstate);
10606 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10610 ASSERT(dp->dtdo_refcnt == 0);
10612 for (i = 0; i < dp->dtdo_varlen; i++) {
10613 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10614 dtrace_statvar_t *svar, **svarp = NULL;
10616 uint8_t scope = v->dtdv_scope;
10620 case DIFV_SCOPE_THREAD:
10623 case DIFV_SCOPE_LOCAL:
10624 np = &vstate->dtvs_nlocals;
10625 svarp = vstate->dtvs_locals;
10628 case DIFV_SCOPE_GLOBAL:
10629 np = &vstate->dtvs_nglobals;
10630 svarp = vstate->dtvs_globals;
10637 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10640 id -= DIF_VAR_OTHER_UBASE;
10644 ASSERT(svar != NULL);
10645 ASSERT(svar->dtsv_refcnt > 0);
10647 if (--svar->dtsv_refcnt > 0)
10650 if (svar->dtsv_size != 0) {
10651 ASSERT(svar->dtsv_data != 0);
10652 kmem_free((void *)(uintptr_t)svar->dtsv_data,
10656 kmem_free(svar, sizeof (dtrace_statvar_t));
10660 if (dp->dtdo_buf != NULL)
10661 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10662 if (dp->dtdo_inttab != NULL)
10663 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10664 if (dp->dtdo_strtab != NULL)
10665 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10666 if (dp->dtdo_vartab != NULL)
10667 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10669 kmem_free(dp, sizeof (dtrace_difo_t));
10673 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10677 ASSERT(MUTEX_HELD(&dtrace_lock));
10678 ASSERT(dp->dtdo_refcnt != 0);
10680 for (i = 0; i < dp->dtdo_varlen; i++) {
10681 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10683 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10686 ASSERT(dtrace_vtime_references > 0);
10687 if (--dtrace_vtime_references == 0)
10688 dtrace_vtime_disable();
10691 if (--dp->dtdo_refcnt == 0)
10692 dtrace_difo_destroy(dp, vstate);
10696 * DTrace Format Functions
10699 dtrace_format_add(dtrace_state_t *state, char *str)
10702 uint16_t ndx, len = strlen(str) + 1;
10704 fmt = kmem_zalloc(len, KM_SLEEP);
10705 bcopy(str, fmt, len);
10707 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10708 if (state->dts_formats[ndx] == NULL) {
10709 state->dts_formats[ndx] = fmt;
10714 if (state->dts_nformats == USHRT_MAX) {
10716 * This is only likely if a denial-of-service attack is being
10717 * attempted. As such, it's okay to fail silently here.
10719 kmem_free(fmt, len);
10724 * For simplicity, we always resize the formats array to be exactly the
10725 * number of formats.
10727 ndx = state->dts_nformats++;
10728 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10730 if (state->dts_formats != NULL) {
10732 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10733 kmem_free(state->dts_formats, ndx * sizeof (char *));
10736 state->dts_formats = new;
10737 state->dts_formats[ndx] = fmt;
10743 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10747 ASSERT(state->dts_formats != NULL);
10748 ASSERT(format <= state->dts_nformats);
10749 ASSERT(state->dts_formats[format - 1] != NULL);
10751 fmt = state->dts_formats[format - 1];
10752 kmem_free(fmt, strlen(fmt) + 1);
10753 state->dts_formats[format - 1] = NULL;
10757 dtrace_format_destroy(dtrace_state_t *state)
10761 if (state->dts_nformats == 0) {
10762 ASSERT(state->dts_formats == NULL);
10766 ASSERT(state->dts_formats != NULL);
10768 for (i = 0; i < state->dts_nformats; i++) {
10769 char *fmt = state->dts_formats[i];
10774 kmem_free(fmt, strlen(fmt) + 1);
10777 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10778 state->dts_nformats = 0;
10779 state->dts_formats = NULL;
10783 * DTrace Predicate Functions
10785 static dtrace_predicate_t *
10786 dtrace_predicate_create(dtrace_difo_t *dp)
10788 dtrace_predicate_t *pred;
10790 ASSERT(MUTEX_HELD(&dtrace_lock));
10791 ASSERT(dp->dtdo_refcnt != 0);
10793 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10794 pred->dtp_difo = dp;
10795 pred->dtp_refcnt = 1;
10797 if (!dtrace_difo_cacheable(dp))
10800 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10802 * This is only theoretically possible -- we have had 2^32
10803 * cacheable predicates on this machine. We cannot allow any
10804 * more predicates to become cacheable: as unlikely as it is,
10805 * there may be a thread caching a (now stale) predicate cache
10806 * ID. (N.B.: the temptation is being successfully resisted to
10807 * have this cmn_err() "Holy shit -- we executed this code!")
10812 pred->dtp_cacheid = dtrace_predcache_id++;
10818 dtrace_predicate_hold(dtrace_predicate_t *pred)
10820 ASSERT(MUTEX_HELD(&dtrace_lock));
10821 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10822 ASSERT(pred->dtp_refcnt > 0);
10824 pred->dtp_refcnt++;
10828 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10830 dtrace_difo_t *dp = pred->dtp_difo;
10832 ASSERT(MUTEX_HELD(&dtrace_lock));
10833 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10834 ASSERT(pred->dtp_refcnt > 0);
10836 if (--pred->dtp_refcnt == 0) {
10837 dtrace_difo_release(pred->dtp_difo, vstate);
10838 kmem_free(pred, sizeof (dtrace_predicate_t));
10843 * DTrace Action Description Functions
10845 static dtrace_actdesc_t *
10846 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10847 uint64_t uarg, uint64_t arg)
10849 dtrace_actdesc_t *act;
10852 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10853 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10856 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10857 act->dtad_kind = kind;
10858 act->dtad_ntuple = ntuple;
10859 act->dtad_uarg = uarg;
10860 act->dtad_arg = arg;
10861 act->dtad_refcnt = 1;
10867 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10869 ASSERT(act->dtad_refcnt >= 1);
10870 act->dtad_refcnt++;
10874 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10876 dtrace_actkind_t kind = act->dtad_kind;
10879 ASSERT(act->dtad_refcnt >= 1);
10881 if (--act->dtad_refcnt != 0)
10884 if ((dp = act->dtad_difo) != NULL)
10885 dtrace_difo_release(dp, vstate);
10887 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10888 char *str = (char *)(uintptr_t)act->dtad_arg;
10891 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10892 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10896 kmem_free(str, strlen(str) + 1);
10899 kmem_free(act, sizeof (dtrace_actdesc_t));
10903 * DTrace ECB Functions
10905 static dtrace_ecb_t *
10906 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10909 dtrace_epid_t epid;
10911 ASSERT(MUTEX_HELD(&dtrace_lock));
10913 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10914 ecb->dte_predicate = NULL;
10915 ecb->dte_probe = probe;
10918 * The default size is the size of the default action: recording
10921 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10922 ecb->dte_alignment = sizeof (dtrace_epid_t);
10924 epid = state->dts_epid++;
10926 if (epid - 1 >= state->dts_necbs) {
10927 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10928 int necbs = state->dts_necbs << 1;
10930 ASSERT(epid == state->dts_necbs + 1);
10933 ASSERT(oecbs == NULL);
10937 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10940 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10942 dtrace_membar_producer();
10943 state->dts_ecbs = ecbs;
10945 if (oecbs != NULL) {
10947 * If this state is active, we must dtrace_sync()
10948 * before we can free the old dts_ecbs array: we're
10949 * coming in hot, and there may be active ring
10950 * buffer processing (which indexes into the dts_ecbs
10951 * array) on another CPU.
10953 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10956 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10959 dtrace_membar_producer();
10960 state->dts_necbs = necbs;
10963 ecb->dte_state = state;
10965 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10966 dtrace_membar_producer();
10967 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10973 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10975 dtrace_probe_t *probe = ecb->dte_probe;
10977 ASSERT(MUTEX_HELD(&cpu_lock));
10978 ASSERT(MUTEX_HELD(&dtrace_lock));
10979 ASSERT(ecb->dte_next == NULL);
10981 if (probe == NULL) {
10983 * This is the NULL probe -- there's nothing to do.
10988 if (probe->dtpr_ecb == NULL) {
10989 dtrace_provider_t *prov = probe->dtpr_provider;
10992 * We're the first ECB on this probe.
10994 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10996 if (ecb->dte_predicate != NULL)
10997 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10999 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11000 probe->dtpr_id, probe->dtpr_arg);
11003 * This probe is already active. Swing the last pointer to
11004 * point to the new ECB, and issue a dtrace_sync() to assure
11005 * that all CPUs have seen the change.
11007 ASSERT(probe->dtpr_ecb_last != NULL);
11008 probe->dtpr_ecb_last->dte_next = ecb;
11009 probe->dtpr_ecb_last = ecb;
11010 probe->dtpr_predcache = 0;
11017 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11019 dtrace_action_t *act;
11020 uint32_t curneeded = UINT32_MAX;
11021 uint32_t aggbase = UINT32_MAX;
11024 * If we record anything, we always record the dtrace_rechdr_t. (And
11025 * we always record it first.)
11027 ecb->dte_size = sizeof (dtrace_rechdr_t);
11028 ecb->dte_alignment = sizeof (dtrace_epid_t);
11030 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11031 dtrace_recdesc_t *rec = &act->dta_rec;
11032 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11034 ecb->dte_alignment = MAX(ecb->dte_alignment,
11035 rec->dtrd_alignment);
11037 if (DTRACEACT_ISAGG(act->dta_kind)) {
11038 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11040 ASSERT(rec->dtrd_size != 0);
11041 ASSERT(agg->dtag_first != NULL);
11042 ASSERT(act->dta_prev->dta_intuple);
11043 ASSERT(aggbase != UINT32_MAX);
11044 ASSERT(curneeded != UINT32_MAX);
11046 agg->dtag_base = aggbase;
11048 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11049 rec->dtrd_offset = curneeded;
11050 curneeded += rec->dtrd_size;
11051 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11053 aggbase = UINT32_MAX;
11054 curneeded = UINT32_MAX;
11055 } else if (act->dta_intuple) {
11056 if (curneeded == UINT32_MAX) {
11058 * This is the first record in a tuple. Align
11059 * curneeded to be at offset 4 in an 8-byte
11062 ASSERT(act->dta_prev == NULL ||
11063 !act->dta_prev->dta_intuple);
11064 ASSERT3U(aggbase, ==, UINT32_MAX);
11065 curneeded = P2PHASEUP(ecb->dte_size,
11066 sizeof (uint64_t), sizeof (dtrace_aggid_t));
11068 aggbase = curneeded - sizeof (dtrace_aggid_t);
11069 ASSERT(IS_P2ALIGNED(aggbase,
11070 sizeof (uint64_t)));
11072 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11073 rec->dtrd_offset = curneeded;
11074 curneeded += rec->dtrd_size;
11076 /* tuples must be followed by an aggregation */
11077 ASSERT(act->dta_prev == NULL ||
11078 !act->dta_prev->dta_intuple);
11080 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11081 rec->dtrd_alignment);
11082 rec->dtrd_offset = ecb->dte_size;
11083 ecb->dte_size += rec->dtrd_size;
11084 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11088 if ((act = ecb->dte_action) != NULL &&
11089 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11090 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11092 * If the size is still sizeof (dtrace_rechdr_t), then all
11093 * actions store no data; set the size to 0.
11098 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11099 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11100 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11104 static dtrace_action_t *
11105 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11107 dtrace_aggregation_t *agg;
11108 size_t size = sizeof (uint64_t);
11109 int ntuple = desc->dtad_ntuple;
11110 dtrace_action_t *act;
11111 dtrace_recdesc_t *frec;
11112 dtrace_aggid_t aggid;
11113 dtrace_state_t *state = ecb->dte_state;
11115 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11116 agg->dtag_ecb = ecb;
11118 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11120 switch (desc->dtad_kind) {
11121 case DTRACEAGG_MIN:
11122 agg->dtag_initial = INT64_MAX;
11123 agg->dtag_aggregate = dtrace_aggregate_min;
11126 case DTRACEAGG_MAX:
11127 agg->dtag_initial = INT64_MIN;
11128 agg->dtag_aggregate = dtrace_aggregate_max;
11131 case DTRACEAGG_COUNT:
11132 agg->dtag_aggregate = dtrace_aggregate_count;
11135 case DTRACEAGG_QUANTIZE:
11136 agg->dtag_aggregate = dtrace_aggregate_quantize;
11137 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11141 case DTRACEAGG_LQUANTIZE: {
11142 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11143 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11145 agg->dtag_initial = desc->dtad_arg;
11146 agg->dtag_aggregate = dtrace_aggregate_lquantize;
11148 if (step == 0 || levels == 0)
11151 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11155 case DTRACEAGG_LLQUANTIZE: {
11156 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11157 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11158 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11159 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11162 agg->dtag_initial = desc->dtad_arg;
11163 agg->dtag_aggregate = dtrace_aggregate_llquantize;
11165 if (factor < 2 || low >= high || nsteps < factor)
11169 * Now check that the number of steps evenly divides a power
11170 * of the factor. (This assures both integer bucket size and
11171 * linearity within each magnitude.)
11173 for (v = factor; v < nsteps; v *= factor)
11176 if ((v % nsteps) || (nsteps % factor))
11179 size = (dtrace_aggregate_llquantize_bucket(factor,
11180 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11184 case DTRACEAGG_AVG:
11185 agg->dtag_aggregate = dtrace_aggregate_avg;
11186 size = sizeof (uint64_t) * 2;
11189 case DTRACEAGG_STDDEV:
11190 agg->dtag_aggregate = dtrace_aggregate_stddev;
11191 size = sizeof (uint64_t) * 4;
11194 case DTRACEAGG_SUM:
11195 agg->dtag_aggregate = dtrace_aggregate_sum;
11202 agg->dtag_action.dta_rec.dtrd_size = size;
11208 * We must make sure that we have enough actions for the n-tuple.
11210 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11211 if (DTRACEACT_ISAGG(act->dta_kind))
11214 if (--ntuple == 0) {
11216 * This is the action with which our n-tuple begins.
11218 agg->dtag_first = act;
11224 * This n-tuple is short by ntuple elements. Return failure.
11226 ASSERT(ntuple != 0);
11228 kmem_free(agg, sizeof (dtrace_aggregation_t));
11233 * If the last action in the tuple has a size of zero, it's actually
11234 * an expression argument for the aggregating action.
11236 ASSERT(ecb->dte_action_last != NULL);
11237 act = ecb->dte_action_last;
11239 if (act->dta_kind == DTRACEACT_DIFEXPR) {
11240 ASSERT(act->dta_difo != NULL);
11242 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11243 agg->dtag_hasarg = 1;
11247 * We need to allocate an id for this aggregation.
11250 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11251 VM_BESTFIT | VM_SLEEP);
11253 aggid = alloc_unr(state->dts_aggid_arena);
11256 if (aggid - 1 >= state->dts_naggregations) {
11257 dtrace_aggregation_t **oaggs = state->dts_aggregations;
11258 dtrace_aggregation_t **aggs;
11259 int naggs = state->dts_naggregations << 1;
11260 int onaggs = state->dts_naggregations;
11262 ASSERT(aggid == state->dts_naggregations + 1);
11265 ASSERT(oaggs == NULL);
11269 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11271 if (oaggs != NULL) {
11272 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11273 kmem_free(oaggs, onaggs * sizeof (*aggs));
11276 state->dts_aggregations = aggs;
11277 state->dts_naggregations = naggs;
11280 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11281 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11283 frec = &agg->dtag_first->dta_rec;
11284 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11285 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11287 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11288 ASSERT(!act->dta_intuple);
11289 act->dta_intuple = 1;
11292 return (&agg->dtag_action);
11296 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11298 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11299 dtrace_state_t *state = ecb->dte_state;
11300 dtrace_aggid_t aggid = agg->dtag_id;
11302 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11304 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11306 free_unr(state->dts_aggid_arena, aggid);
11309 ASSERT(state->dts_aggregations[aggid - 1] == agg);
11310 state->dts_aggregations[aggid - 1] = NULL;
11312 kmem_free(agg, sizeof (dtrace_aggregation_t));
11316 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11318 dtrace_action_t *action, *last;
11319 dtrace_difo_t *dp = desc->dtad_difo;
11320 uint32_t size = 0, align = sizeof (uint8_t), mask;
11321 uint16_t format = 0;
11322 dtrace_recdesc_t *rec;
11323 dtrace_state_t *state = ecb->dte_state;
11324 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11325 uint64_t arg = desc->dtad_arg;
11327 ASSERT(MUTEX_HELD(&dtrace_lock));
11328 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11330 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11332 * If this is an aggregating action, there must be neither
11333 * a speculate nor a commit on the action chain.
11335 dtrace_action_t *act;
11337 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11338 if (act->dta_kind == DTRACEACT_COMMIT)
11341 if (act->dta_kind == DTRACEACT_SPECULATE)
11345 action = dtrace_ecb_aggregation_create(ecb, desc);
11347 if (action == NULL)
11350 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11351 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11352 dp != NULL && dp->dtdo_destructive)) {
11353 state->dts_destructive = 1;
11356 switch (desc->dtad_kind) {
11357 case DTRACEACT_PRINTF:
11358 case DTRACEACT_PRINTA:
11359 case DTRACEACT_SYSTEM:
11360 case DTRACEACT_FREOPEN:
11361 case DTRACEACT_DIFEXPR:
11363 * We know that our arg is a string -- turn it into a
11367 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11368 desc->dtad_kind == DTRACEACT_DIFEXPR);
11373 ASSERT(arg > KERNELBASE);
11375 format = dtrace_format_add(state,
11376 (char *)(uintptr_t)arg);
11380 case DTRACEACT_LIBACT:
11381 case DTRACEACT_TRACEMEM:
11382 case DTRACEACT_TRACEMEM_DYNSIZE:
11386 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11389 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11390 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11393 size = opt[DTRACEOPT_STRSIZE];
11398 case DTRACEACT_STACK:
11399 if ((nframes = arg) == 0) {
11400 nframes = opt[DTRACEOPT_STACKFRAMES];
11401 ASSERT(nframes > 0);
11405 size = nframes * sizeof (pc_t);
11408 case DTRACEACT_JSTACK:
11409 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11410 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11412 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11413 nframes = opt[DTRACEOPT_JSTACKFRAMES];
11415 arg = DTRACE_USTACK_ARG(nframes, strsize);
11418 case DTRACEACT_USTACK:
11419 if (desc->dtad_kind != DTRACEACT_JSTACK &&
11420 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11421 strsize = DTRACE_USTACK_STRSIZE(arg);
11422 nframes = opt[DTRACEOPT_USTACKFRAMES];
11423 ASSERT(nframes > 0);
11424 arg = DTRACE_USTACK_ARG(nframes, strsize);
11428 * Save a slot for the pid.
11430 size = (nframes + 1) * sizeof (uint64_t);
11431 size += DTRACE_USTACK_STRSIZE(arg);
11432 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11436 case DTRACEACT_SYM:
11437 case DTRACEACT_MOD:
11438 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11439 sizeof (uint64_t)) ||
11440 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11444 case DTRACEACT_USYM:
11445 case DTRACEACT_UMOD:
11446 case DTRACEACT_UADDR:
11448 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11449 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11453 * We have a slot for the pid, plus a slot for the
11454 * argument. To keep things simple (aligned with
11455 * bitness-neutral sizing), we store each as a 64-bit
11458 size = 2 * sizeof (uint64_t);
11461 case DTRACEACT_STOP:
11462 case DTRACEACT_BREAKPOINT:
11463 case DTRACEACT_PANIC:
11466 case DTRACEACT_CHILL:
11467 case DTRACEACT_DISCARD:
11468 case DTRACEACT_RAISE:
11473 case DTRACEACT_EXIT:
11475 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11476 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11480 case DTRACEACT_SPECULATE:
11481 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11487 state->dts_speculates = 1;
11490 case DTRACEACT_PRINTM:
11491 size = dp->dtdo_rtype.dtdt_size;
11494 case DTRACEACT_PRINTT:
11495 size = dp->dtdo_rtype.dtdt_size;
11498 case DTRACEACT_COMMIT: {
11499 dtrace_action_t *act = ecb->dte_action;
11501 for (; act != NULL; act = act->dta_next) {
11502 if (act->dta_kind == DTRACEACT_COMMIT)
11515 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11517 * If this is a data-storing action or a speculate,
11518 * we must be sure that there isn't a commit on the
11521 dtrace_action_t *act = ecb->dte_action;
11523 for (; act != NULL; act = act->dta_next) {
11524 if (act->dta_kind == DTRACEACT_COMMIT)
11529 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11530 action->dta_rec.dtrd_size = size;
11533 action->dta_refcnt = 1;
11534 rec = &action->dta_rec;
11535 size = rec->dtrd_size;
11537 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11538 if (!(size & mask)) {
11544 action->dta_kind = desc->dtad_kind;
11546 if ((action->dta_difo = dp) != NULL)
11547 dtrace_difo_hold(dp);
11549 rec->dtrd_action = action->dta_kind;
11550 rec->dtrd_arg = arg;
11551 rec->dtrd_uarg = desc->dtad_uarg;
11552 rec->dtrd_alignment = (uint16_t)align;
11553 rec->dtrd_format = format;
11555 if ((last = ecb->dte_action_last) != NULL) {
11556 ASSERT(ecb->dte_action != NULL);
11557 action->dta_prev = last;
11558 last->dta_next = action;
11560 ASSERT(ecb->dte_action == NULL);
11561 ecb->dte_action = action;
11564 ecb->dte_action_last = action;
11570 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11572 dtrace_action_t *act = ecb->dte_action, *next;
11573 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11577 if (act != NULL && act->dta_refcnt > 1) {
11578 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11581 for (; act != NULL; act = next) {
11582 next = act->dta_next;
11583 ASSERT(next != NULL || act == ecb->dte_action_last);
11584 ASSERT(act->dta_refcnt == 1);
11586 if ((format = act->dta_rec.dtrd_format) != 0)
11587 dtrace_format_remove(ecb->dte_state, format);
11589 if ((dp = act->dta_difo) != NULL)
11590 dtrace_difo_release(dp, vstate);
11592 if (DTRACEACT_ISAGG(act->dta_kind)) {
11593 dtrace_ecb_aggregation_destroy(ecb, act);
11595 kmem_free(act, sizeof (dtrace_action_t));
11600 ecb->dte_action = NULL;
11601 ecb->dte_action_last = NULL;
11606 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11609 * We disable the ECB by removing it from its probe.
11611 dtrace_ecb_t *pecb, *prev = NULL;
11612 dtrace_probe_t *probe = ecb->dte_probe;
11614 ASSERT(MUTEX_HELD(&dtrace_lock));
11616 if (probe == NULL) {
11618 * This is the NULL probe; there is nothing to disable.
11623 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11629 ASSERT(pecb != NULL);
11631 if (prev == NULL) {
11632 probe->dtpr_ecb = ecb->dte_next;
11634 prev->dte_next = ecb->dte_next;
11637 if (ecb == probe->dtpr_ecb_last) {
11638 ASSERT(ecb->dte_next == NULL);
11639 probe->dtpr_ecb_last = prev;
11643 * The ECB has been disconnected from the probe; now sync to assure
11644 * that all CPUs have seen the change before returning.
11648 if (probe->dtpr_ecb == NULL) {
11650 * That was the last ECB on the probe; clear the predicate
11651 * cache ID for the probe, disable it and sync one more time
11652 * to assure that we'll never hit it again.
11654 dtrace_provider_t *prov = probe->dtpr_provider;
11656 ASSERT(ecb->dte_next == NULL);
11657 ASSERT(probe->dtpr_ecb_last == NULL);
11658 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11659 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11660 probe->dtpr_id, probe->dtpr_arg);
11664 * There is at least one ECB remaining on the probe. If there
11665 * is _exactly_ one, set the probe's predicate cache ID to be
11666 * the predicate cache ID of the remaining ECB.
11668 ASSERT(probe->dtpr_ecb_last != NULL);
11669 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11671 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11672 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11674 ASSERT(probe->dtpr_ecb->dte_next == NULL);
11677 probe->dtpr_predcache = p->dtp_cacheid;
11680 ecb->dte_next = NULL;
11685 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11687 dtrace_state_t *state = ecb->dte_state;
11688 dtrace_vstate_t *vstate = &state->dts_vstate;
11689 dtrace_predicate_t *pred;
11690 dtrace_epid_t epid = ecb->dte_epid;
11692 ASSERT(MUTEX_HELD(&dtrace_lock));
11693 ASSERT(ecb->dte_next == NULL);
11694 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11696 if ((pred = ecb->dte_predicate) != NULL)
11697 dtrace_predicate_release(pred, vstate);
11699 dtrace_ecb_action_remove(ecb);
11701 ASSERT(state->dts_ecbs[epid - 1] == ecb);
11702 state->dts_ecbs[epid - 1] = NULL;
11704 kmem_free(ecb, sizeof (dtrace_ecb_t));
11707 static dtrace_ecb_t *
11708 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11709 dtrace_enabling_t *enab)
11712 dtrace_predicate_t *pred;
11713 dtrace_actdesc_t *act;
11714 dtrace_provider_t *prov;
11715 dtrace_ecbdesc_t *desc = enab->dten_current;
11717 ASSERT(MUTEX_HELD(&dtrace_lock));
11718 ASSERT(state != NULL);
11720 ecb = dtrace_ecb_add(state, probe);
11721 ecb->dte_uarg = desc->dted_uarg;
11723 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11724 dtrace_predicate_hold(pred);
11725 ecb->dte_predicate = pred;
11728 if (probe != NULL) {
11730 * If the provider shows more leg than the consumer is old
11731 * enough to see, we need to enable the appropriate implicit
11732 * predicate bits to prevent the ecb from activating at
11735 * Providers specifying DTRACE_PRIV_USER at register time
11736 * are stating that they need the /proc-style privilege
11737 * model to be enforced, and this is what DTRACE_COND_OWNER
11738 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11740 prov = probe->dtpr_provider;
11741 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11742 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11743 ecb->dte_cond |= DTRACE_COND_OWNER;
11745 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11746 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11747 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11750 * If the provider shows us kernel innards and the user
11751 * is lacking sufficient privilege, enable the
11752 * DTRACE_COND_USERMODE implicit predicate.
11754 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11755 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11756 ecb->dte_cond |= DTRACE_COND_USERMODE;
11759 if (dtrace_ecb_create_cache != NULL) {
11761 * If we have a cached ecb, we'll use its action list instead
11762 * of creating our own (saving both time and space).
11764 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11765 dtrace_action_t *act = cached->dte_action;
11768 ASSERT(act->dta_refcnt > 0);
11770 ecb->dte_action = act;
11771 ecb->dte_action_last = cached->dte_action_last;
11772 ecb->dte_needed = cached->dte_needed;
11773 ecb->dte_size = cached->dte_size;
11774 ecb->dte_alignment = cached->dte_alignment;
11780 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11781 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11782 dtrace_ecb_destroy(ecb);
11787 dtrace_ecb_resize(ecb);
11789 return (dtrace_ecb_create_cache = ecb);
11793 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11796 dtrace_enabling_t *enab = arg;
11797 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11799 ASSERT(state != NULL);
11801 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11803 * This probe was created in a generation for which this
11804 * enabling has previously created ECBs; we don't want to
11805 * enable it again, so just kick out.
11807 return (DTRACE_MATCH_NEXT);
11810 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11811 return (DTRACE_MATCH_DONE);
11813 dtrace_ecb_enable(ecb);
11814 return (DTRACE_MATCH_NEXT);
11817 static dtrace_ecb_t *
11818 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11822 ASSERT(MUTEX_HELD(&dtrace_lock));
11824 if (id == 0 || id > state->dts_necbs)
11827 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11828 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11830 return (state->dts_ecbs[id - 1]);
11833 static dtrace_aggregation_t *
11834 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11836 dtrace_aggregation_t *agg;
11838 ASSERT(MUTEX_HELD(&dtrace_lock));
11840 if (id == 0 || id > state->dts_naggregations)
11843 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11844 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11845 agg->dtag_id == id);
11847 return (state->dts_aggregations[id - 1]);
11851 * DTrace Buffer Functions
11853 * The following functions manipulate DTrace buffers. Most of these functions
11854 * are called in the context of establishing or processing consumer state;
11855 * exceptions are explicitly noted.
11859 * Note: called from cross call context. This function switches the two
11860 * buffers on a given CPU. The atomicity of this operation is assured by
11861 * disabling interrupts while the actual switch takes place; the disabling of
11862 * interrupts serializes the execution with any execution of dtrace_probe() on
11866 dtrace_buffer_switch(dtrace_buffer_t *buf)
11868 caddr_t tomax = buf->dtb_tomax;
11869 caddr_t xamot = buf->dtb_xamot;
11870 dtrace_icookie_t cookie;
11873 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11874 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11876 cookie = dtrace_interrupt_disable();
11877 now = dtrace_gethrtime();
11878 buf->dtb_tomax = xamot;
11879 buf->dtb_xamot = tomax;
11880 buf->dtb_xamot_drops = buf->dtb_drops;
11881 buf->dtb_xamot_offset = buf->dtb_offset;
11882 buf->dtb_xamot_errors = buf->dtb_errors;
11883 buf->dtb_xamot_flags = buf->dtb_flags;
11884 buf->dtb_offset = 0;
11885 buf->dtb_drops = 0;
11886 buf->dtb_errors = 0;
11887 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11888 buf->dtb_interval = now - buf->dtb_switched;
11889 buf->dtb_switched = now;
11890 dtrace_interrupt_enable(cookie);
11894 * Note: called from cross call context. This function activates a buffer
11895 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11896 * is guaranteed by the disabling of interrupts.
11899 dtrace_buffer_activate(dtrace_state_t *state)
11901 dtrace_buffer_t *buf;
11902 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11904 buf = &state->dts_buffer[curcpu];
11906 if (buf->dtb_tomax != NULL) {
11908 * We might like to assert that the buffer is marked inactive,
11909 * but this isn't necessarily true: the buffer for the CPU
11910 * that processes the BEGIN probe has its buffer activated
11911 * manually. In this case, we take the (harmless) action
11912 * re-clearing the bit INACTIVE bit.
11914 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11917 dtrace_interrupt_enable(cookie);
11922 * Activate the specified per-CPU buffer. This is used instead of
11923 * dtrace_buffer_activate() when APs have not yet started, i.e. when
11924 * activating anonymous state.
11927 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
11930 if (state->dts_buffer[cpu].dtb_tomax != NULL)
11931 state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
11936 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11937 processorid_t cpu, int *factor)
11942 dtrace_buffer_t *buf;
11943 int allocated = 0, desired = 0;
11946 ASSERT(MUTEX_HELD(&cpu_lock));
11947 ASSERT(MUTEX_HELD(&dtrace_lock));
11951 if (size > dtrace_nonroot_maxsize &&
11952 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11958 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11961 buf = &bufs[cp->cpu_id];
11964 * If there is already a buffer allocated for this CPU, it
11965 * is only possible that this is a DR event. In this case,
11967 if (buf->dtb_tomax != NULL) {
11968 ASSERT(buf->dtb_size == size);
11972 ASSERT(buf->dtb_xamot == NULL);
11974 if ((buf->dtb_tomax = kmem_zalloc(size,
11975 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11978 buf->dtb_size = size;
11979 buf->dtb_flags = flags;
11980 buf->dtb_offset = 0;
11981 buf->dtb_drops = 0;
11983 if (flags & DTRACEBUF_NOSWITCH)
11986 if ((buf->dtb_xamot = kmem_zalloc(size,
11987 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11989 } while ((cp = cp->cpu_next) != cpu_list);
11997 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12000 buf = &bufs[cp->cpu_id];
12003 if (buf->dtb_xamot != NULL) {
12004 ASSERT(buf->dtb_tomax != NULL);
12005 ASSERT(buf->dtb_size == size);
12006 kmem_free(buf->dtb_xamot, size);
12010 if (buf->dtb_tomax != NULL) {
12011 ASSERT(buf->dtb_size == size);
12012 kmem_free(buf->dtb_tomax, size);
12016 buf->dtb_tomax = NULL;
12017 buf->dtb_xamot = NULL;
12019 } while ((cp = cp->cpu_next) != cpu_list);
12024 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12025 defined(__mips__) || defined(__powerpc__)
12027 * FreeBSD isn't good at limiting the amount of memory we
12028 * ask to malloc, so let's place a limit here before trying
12029 * to do something that might well end in tears at bedtime.
12031 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
12035 ASSERT(MUTEX_HELD(&dtrace_lock));
12037 if (cpu != DTRACE_CPUALL && cpu != i)
12043 * If there is already a buffer allocated for this CPU, it
12044 * is only possible that this is a DR event. In this case,
12045 * the buffer size must match our specified size.
12047 if (buf->dtb_tomax != NULL) {
12048 ASSERT(buf->dtb_size == size);
12052 ASSERT(buf->dtb_xamot == NULL);
12054 if ((buf->dtb_tomax = kmem_zalloc(size,
12055 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12058 buf->dtb_size = size;
12059 buf->dtb_flags = flags;
12060 buf->dtb_offset = 0;
12061 buf->dtb_drops = 0;
12063 if (flags & DTRACEBUF_NOSWITCH)
12066 if ((buf->dtb_xamot = kmem_zalloc(size,
12067 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12075 * Error allocating memory, so free the buffers that were
12076 * allocated before the failed allocation.
12079 if (cpu != DTRACE_CPUALL && cpu != i)
12085 if (buf->dtb_xamot != NULL) {
12086 ASSERT(buf->dtb_tomax != NULL);
12087 ASSERT(buf->dtb_size == size);
12088 kmem_free(buf->dtb_xamot, size);
12092 if (buf->dtb_tomax != NULL) {
12093 ASSERT(buf->dtb_size == size);
12094 kmem_free(buf->dtb_tomax, size);
12098 buf->dtb_tomax = NULL;
12099 buf->dtb_xamot = NULL;
12104 *factor = desired / (allocated > 0 ? allocated : 1);
12110 * Note: called from probe context. This function just increments the drop
12111 * count on a buffer. It has been made a function to allow for the
12112 * possibility of understanding the source of mysterious drop counts. (A
12113 * problem for which one may be particularly disappointed that DTrace cannot
12114 * be used to understand DTrace.)
12117 dtrace_buffer_drop(dtrace_buffer_t *buf)
12123 * Note: called from probe context. This function is called to reserve space
12124 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
12125 * mstate. Returns the new offset in the buffer, or a negative value if an
12126 * error has occurred.
12129 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12130 dtrace_state_t *state, dtrace_mstate_t *mstate)
12132 intptr_t offs = buf->dtb_offset, soffs;
12137 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12140 if ((tomax = buf->dtb_tomax) == NULL) {
12141 dtrace_buffer_drop(buf);
12145 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12146 while (offs & (align - 1)) {
12148 * Assert that our alignment is off by a number which
12149 * is itself sizeof (uint32_t) aligned.
12151 ASSERT(!((align - (offs & (align - 1))) &
12152 (sizeof (uint32_t) - 1)));
12153 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12154 offs += sizeof (uint32_t);
12157 if ((soffs = offs + needed) > buf->dtb_size) {
12158 dtrace_buffer_drop(buf);
12162 if (mstate == NULL)
12165 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12166 mstate->dtms_scratch_size = buf->dtb_size - soffs;
12167 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12172 if (buf->dtb_flags & DTRACEBUF_FILL) {
12173 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12174 (buf->dtb_flags & DTRACEBUF_FULL))
12179 total = needed + (offs & (align - 1));
12182 * For a ring buffer, life is quite a bit more complicated. Before
12183 * we can store any padding, we need to adjust our wrapping offset.
12184 * (If we've never before wrapped or we're not about to, no adjustment
12187 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12188 offs + total > buf->dtb_size) {
12189 woffs = buf->dtb_xamot_offset;
12191 if (offs + total > buf->dtb_size) {
12193 * We can't fit in the end of the buffer. First, a
12194 * sanity check that we can fit in the buffer at all.
12196 if (total > buf->dtb_size) {
12197 dtrace_buffer_drop(buf);
12202 * We're going to be storing at the top of the buffer,
12203 * so now we need to deal with the wrapped offset. We
12204 * only reset our wrapped offset to 0 if it is
12205 * currently greater than the current offset. If it
12206 * is less than the current offset, it is because a
12207 * previous allocation induced a wrap -- but the
12208 * allocation didn't subsequently take the space due
12209 * to an error or false predicate evaluation. In this
12210 * case, we'll just leave the wrapped offset alone: if
12211 * the wrapped offset hasn't been advanced far enough
12212 * for this allocation, it will be adjusted in the
12215 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12223 * Now we know that we're going to be storing to the
12224 * top of the buffer and that there is room for us
12225 * there. We need to clear the buffer from the current
12226 * offset to the end (there may be old gunk there).
12228 while (offs < buf->dtb_size)
12232 * We need to set our offset to zero. And because we
12233 * are wrapping, we need to set the bit indicating as
12234 * much. We can also adjust our needed space back
12235 * down to the space required by the ECB -- we know
12236 * that the top of the buffer is aligned.
12240 buf->dtb_flags |= DTRACEBUF_WRAPPED;
12243 * There is room for us in the buffer, so we simply
12244 * need to check the wrapped offset.
12246 if (woffs < offs) {
12248 * The wrapped offset is less than the offset.
12249 * This can happen if we allocated buffer space
12250 * that induced a wrap, but then we didn't
12251 * subsequently take the space due to an error
12252 * or false predicate evaluation. This is
12253 * okay; we know that _this_ allocation isn't
12254 * going to induce a wrap. We still can't
12255 * reset the wrapped offset to be zero,
12256 * however: the space may have been trashed in
12257 * the previous failed probe attempt. But at
12258 * least the wrapped offset doesn't need to
12259 * be adjusted at all...
12265 while (offs + total > woffs) {
12266 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12269 if (epid == DTRACE_EPIDNONE) {
12270 size = sizeof (uint32_t);
12272 ASSERT3U(epid, <=, state->dts_necbs);
12273 ASSERT(state->dts_ecbs[epid - 1] != NULL);
12275 size = state->dts_ecbs[epid - 1]->dte_size;
12278 ASSERT(woffs + size <= buf->dtb_size);
12281 if (woffs + size == buf->dtb_size) {
12283 * We've reached the end of the buffer; we want
12284 * to set the wrapped offset to 0 and break
12285 * out. However, if the offs is 0, then we're
12286 * in a strange edge-condition: the amount of
12287 * space that we want to reserve plus the size
12288 * of the record that we're overwriting is
12289 * greater than the size of the buffer. This
12290 * is problematic because if we reserve the
12291 * space but subsequently don't consume it (due
12292 * to a failed predicate or error) the wrapped
12293 * offset will be 0 -- yet the EPID at offset 0
12294 * will not be committed. This situation is
12295 * relatively easy to deal with: if we're in
12296 * this case, the buffer is indistinguishable
12297 * from one that hasn't wrapped; we need only
12298 * finish the job by clearing the wrapped bit,
12299 * explicitly setting the offset to be 0, and
12300 * zero'ing out the old data in the buffer.
12303 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12304 buf->dtb_offset = 0;
12307 while (woffs < buf->dtb_size)
12308 tomax[woffs++] = 0;
12319 * We have a wrapped offset. It may be that the wrapped offset
12320 * has become zero -- that's okay.
12322 buf->dtb_xamot_offset = woffs;
12327 * Now we can plow the buffer with any necessary padding.
12329 while (offs & (align - 1)) {
12331 * Assert that our alignment is off by a number which
12332 * is itself sizeof (uint32_t) aligned.
12334 ASSERT(!((align - (offs & (align - 1))) &
12335 (sizeof (uint32_t) - 1)));
12336 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12337 offs += sizeof (uint32_t);
12340 if (buf->dtb_flags & DTRACEBUF_FILL) {
12341 if (offs + needed > buf->dtb_size - state->dts_reserve) {
12342 buf->dtb_flags |= DTRACEBUF_FULL;
12347 if (mstate == NULL)
12351 * For ring buffers and fill buffers, the scratch space is always
12352 * the inactive buffer.
12354 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12355 mstate->dtms_scratch_size = buf->dtb_size;
12356 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12362 dtrace_buffer_polish(dtrace_buffer_t *buf)
12364 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12365 ASSERT(MUTEX_HELD(&dtrace_lock));
12367 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12371 * We need to polish the ring buffer. There are three cases:
12373 * - The first (and presumably most common) is that there is no gap
12374 * between the buffer offset and the wrapped offset. In this case,
12375 * there is nothing in the buffer that isn't valid data; we can
12376 * mark the buffer as polished and return.
12378 * - The second (less common than the first but still more common
12379 * than the third) is that there is a gap between the buffer offset
12380 * and the wrapped offset, and the wrapped offset is larger than the
12381 * buffer offset. This can happen because of an alignment issue, or
12382 * can happen because of a call to dtrace_buffer_reserve() that
12383 * didn't subsequently consume the buffer space. In this case,
12384 * we need to zero the data from the buffer offset to the wrapped
12387 * - The third (and least common) is that there is a gap between the
12388 * buffer offset and the wrapped offset, but the wrapped offset is
12389 * _less_ than the buffer offset. This can only happen because a
12390 * call to dtrace_buffer_reserve() induced a wrap, but the space
12391 * was not subsequently consumed. In this case, we need to zero the
12392 * space from the offset to the end of the buffer _and_ from the
12393 * top of the buffer to the wrapped offset.
12395 if (buf->dtb_offset < buf->dtb_xamot_offset) {
12396 bzero(buf->dtb_tomax + buf->dtb_offset,
12397 buf->dtb_xamot_offset - buf->dtb_offset);
12400 if (buf->dtb_offset > buf->dtb_xamot_offset) {
12401 bzero(buf->dtb_tomax + buf->dtb_offset,
12402 buf->dtb_size - buf->dtb_offset);
12403 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12408 * This routine determines if data generated at the specified time has likely
12409 * been entirely consumed at user-level. This routine is called to determine
12410 * if an ECB on a defunct probe (but for an active enabling) can be safely
12411 * disabled and destroyed.
12414 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12418 for (i = 0; i < NCPU; i++) {
12419 dtrace_buffer_t *buf = &bufs[i];
12421 if (buf->dtb_size == 0)
12424 if (buf->dtb_flags & DTRACEBUF_RING)
12427 if (!buf->dtb_switched && buf->dtb_offset != 0)
12430 if (buf->dtb_switched - buf->dtb_interval < when)
12438 dtrace_buffer_free(dtrace_buffer_t *bufs)
12442 for (i = 0; i < NCPU; i++) {
12443 dtrace_buffer_t *buf = &bufs[i];
12445 if (buf->dtb_tomax == NULL) {
12446 ASSERT(buf->dtb_xamot == NULL);
12447 ASSERT(buf->dtb_size == 0);
12451 if (buf->dtb_xamot != NULL) {
12452 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12453 kmem_free(buf->dtb_xamot, buf->dtb_size);
12456 kmem_free(buf->dtb_tomax, buf->dtb_size);
12458 buf->dtb_tomax = NULL;
12459 buf->dtb_xamot = NULL;
12464 * DTrace Enabling Functions
12466 static dtrace_enabling_t *
12467 dtrace_enabling_create(dtrace_vstate_t *vstate)
12469 dtrace_enabling_t *enab;
12471 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12472 enab->dten_vstate = vstate;
12478 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12480 dtrace_ecbdesc_t **ndesc;
12481 size_t osize, nsize;
12484 * We can't add to enablings after we've enabled them, or after we've
12487 ASSERT(enab->dten_probegen == 0);
12488 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12490 if (enab->dten_ndesc < enab->dten_maxdesc) {
12491 enab->dten_desc[enab->dten_ndesc++] = ecb;
12495 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12497 if (enab->dten_maxdesc == 0) {
12498 enab->dten_maxdesc = 1;
12500 enab->dten_maxdesc <<= 1;
12503 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12505 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12506 ndesc = kmem_zalloc(nsize, KM_SLEEP);
12507 bcopy(enab->dten_desc, ndesc, osize);
12508 if (enab->dten_desc != NULL)
12509 kmem_free(enab->dten_desc, osize);
12511 enab->dten_desc = ndesc;
12512 enab->dten_desc[enab->dten_ndesc++] = ecb;
12516 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12517 dtrace_probedesc_t *pd)
12519 dtrace_ecbdesc_t *new;
12520 dtrace_predicate_t *pred;
12521 dtrace_actdesc_t *act;
12524 * We're going to create a new ECB description that matches the
12525 * specified ECB in every way, but has the specified probe description.
12527 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12529 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12530 dtrace_predicate_hold(pred);
12532 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12533 dtrace_actdesc_hold(act);
12535 new->dted_action = ecb->dted_action;
12536 new->dted_pred = ecb->dted_pred;
12537 new->dted_probe = *pd;
12538 new->dted_uarg = ecb->dted_uarg;
12540 dtrace_enabling_add(enab, new);
12544 dtrace_enabling_dump(dtrace_enabling_t *enab)
12548 for (i = 0; i < enab->dten_ndesc; i++) {
12549 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12552 printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12553 desc->dtpd_provider, desc->dtpd_mod,
12554 desc->dtpd_func, desc->dtpd_name);
12556 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12557 desc->dtpd_provider, desc->dtpd_mod,
12558 desc->dtpd_func, desc->dtpd_name);
12564 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12567 dtrace_ecbdesc_t *ep;
12568 dtrace_vstate_t *vstate = enab->dten_vstate;
12570 ASSERT(MUTEX_HELD(&dtrace_lock));
12572 for (i = 0; i < enab->dten_ndesc; i++) {
12573 dtrace_actdesc_t *act, *next;
12574 dtrace_predicate_t *pred;
12576 ep = enab->dten_desc[i];
12578 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12579 dtrace_predicate_release(pred, vstate);
12581 for (act = ep->dted_action; act != NULL; act = next) {
12582 next = act->dtad_next;
12583 dtrace_actdesc_release(act, vstate);
12586 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12589 if (enab->dten_desc != NULL)
12590 kmem_free(enab->dten_desc,
12591 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12594 * If this was a retained enabling, decrement the dts_nretained count
12595 * and take it off of the dtrace_retained list.
12597 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12598 dtrace_retained == enab) {
12599 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12600 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12601 enab->dten_vstate->dtvs_state->dts_nretained--;
12602 dtrace_retained_gen++;
12605 if (enab->dten_prev == NULL) {
12606 if (dtrace_retained == enab) {
12607 dtrace_retained = enab->dten_next;
12609 if (dtrace_retained != NULL)
12610 dtrace_retained->dten_prev = NULL;
12613 ASSERT(enab != dtrace_retained);
12614 ASSERT(dtrace_retained != NULL);
12615 enab->dten_prev->dten_next = enab->dten_next;
12618 if (enab->dten_next != NULL) {
12619 ASSERT(dtrace_retained != NULL);
12620 enab->dten_next->dten_prev = enab->dten_prev;
12623 kmem_free(enab, sizeof (dtrace_enabling_t));
12627 dtrace_enabling_retain(dtrace_enabling_t *enab)
12629 dtrace_state_t *state;
12631 ASSERT(MUTEX_HELD(&dtrace_lock));
12632 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12633 ASSERT(enab->dten_vstate != NULL);
12635 state = enab->dten_vstate->dtvs_state;
12636 ASSERT(state != NULL);
12639 * We only allow each state to retain dtrace_retain_max enablings.
12641 if (state->dts_nretained >= dtrace_retain_max)
12644 state->dts_nretained++;
12645 dtrace_retained_gen++;
12647 if (dtrace_retained == NULL) {
12648 dtrace_retained = enab;
12652 enab->dten_next = dtrace_retained;
12653 dtrace_retained->dten_prev = enab;
12654 dtrace_retained = enab;
12660 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12661 dtrace_probedesc_t *create)
12663 dtrace_enabling_t *new, *enab;
12664 int found = 0, err = ENOENT;
12666 ASSERT(MUTEX_HELD(&dtrace_lock));
12667 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12668 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12669 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12670 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12672 new = dtrace_enabling_create(&state->dts_vstate);
12675 * Iterate over all retained enablings, looking for enablings that
12676 * match the specified state.
12678 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12682 * dtvs_state can only be NULL for helper enablings -- and
12683 * helper enablings can't be retained.
12685 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12687 if (enab->dten_vstate->dtvs_state != state)
12691 * Now iterate over each probe description; we're looking for
12692 * an exact match to the specified probe description.
12694 for (i = 0; i < enab->dten_ndesc; i++) {
12695 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12696 dtrace_probedesc_t *pd = &ep->dted_probe;
12698 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12701 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12704 if (strcmp(pd->dtpd_func, match->dtpd_func))
12707 if (strcmp(pd->dtpd_name, match->dtpd_name))
12711 * We have a winning probe! Add it to our growing
12715 dtrace_enabling_addlike(new, ep, create);
12719 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12720 dtrace_enabling_destroy(new);
12728 dtrace_enabling_retract(dtrace_state_t *state)
12730 dtrace_enabling_t *enab, *next;
12732 ASSERT(MUTEX_HELD(&dtrace_lock));
12735 * Iterate over all retained enablings, destroy the enablings retained
12736 * for the specified state.
12738 for (enab = dtrace_retained; enab != NULL; enab = next) {
12739 next = enab->dten_next;
12742 * dtvs_state can only be NULL for helper enablings -- and
12743 * helper enablings can't be retained.
12745 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12747 if (enab->dten_vstate->dtvs_state == state) {
12748 ASSERT(state->dts_nretained > 0);
12749 dtrace_enabling_destroy(enab);
12753 ASSERT(state->dts_nretained == 0);
12757 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12762 ASSERT(MUTEX_HELD(&cpu_lock));
12763 ASSERT(MUTEX_HELD(&dtrace_lock));
12765 for (i = 0; i < enab->dten_ndesc; i++) {
12766 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12768 enab->dten_current = ep;
12769 enab->dten_error = 0;
12771 matched += dtrace_probe_enable(&ep->dted_probe, enab);
12773 if (enab->dten_error != 0) {
12775 * If we get an error half-way through enabling the
12776 * probes, we kick out -- perhaps with some number of
12777 * them enabled. Leaving enabled probes enabled may
12778 * be slightly confusing for user-level, but we expect
12779 * that no one will attempt to actually drive on in
12780 * the face of such errors. If this is an anonymous
12781 * enabling (indicated with a NULL nmatched pointer),
12782 * we cmn_err() a message. We aren't expecting to
12783 * get such an error -- such as it can exist at all,
12784 * it would be a result of corrupted DOF in the driver
12787 if (nmatched == NULL) {
12788 cmn_err(CE_WARN, "dtrace_enabling_match() "
12789 "error on %p: %d", (void *)ep,
12793 return (enab->dten_error);
12797 enab->dten_probegen = dtrace_probegen;
12798 if (nmatched != NULL)
12799 *nmatched = matched;
12805 dtrace_enabling_matchall(void)
12807 dtrace_enabling_t *enab;
12809 mutex_enter(&cpu_lock);
12810 mutex_enter(&dtrace_lock);
12813 * Iterate over all retained enablings to see if any probes match
12814 * against them. We only perform this operation on enablings for which
12815 * we have sufficient permissions by virtue of being in the global zone
12816 * or in the same zone as the DTrace client. Because we can be called
12817 * after dtrace_detach() has been called, we cannot assert that there
12818 * are retained enablings. We can safely load from dtrace_retained,
12819 * however: the taskq_destroy() at the end of dtrace_detach() will
12820 * block pending our completion.
12822 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12824 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12826 if (INGLOBALZONE(curproc) ||
12827 cr != NULL && getzoneid() == crgetzoneid(cr))
12829 (void) dtrace_enabling_match(enab, NULL);
12832 mutex_exit(&dtrace_lock);
12833 mutex_exit(&cpu_lock);
12837 * If an enabling is to be enabled without having matched probes (that is, if
12838 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12839 * enabling must be _primed_ by creating an ECB for every ECB description.
12840 * This must be done to assure that we know the number of speculations, the
12841 * number of aggregations, the minimum buffer size needed, etc. before we
12842 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
12843 * enabling any probes, we create ECBs for every ECB decription, but with a
12844 * NULL probe -- which is exactly what this function does.
12847 dtrace_enabling_prime(dtrace_state_t *state)
12849 dtrace_enabling_t *enab;
12852 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12853 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12855 if (enab->dten_vstate->dtvs_state != state)
12859 * We don't want to prime an enabling more than once, lest
12860 * we allow a malicious user to induce resource exhaustion.
12861 * (The ECBs that result from priming an enabling aren't
12862 * leaked -- but they also aren't deallocated until the
12863 * consumer state is destroyed.)
12865 if (enab->dten_primed)
12868 for (i = 0; i < enab->dten_ndesc; i++) {
12869 enab->dten_current = enab->dten_desc[i];
12870 (void) dtrace_probe_enable(NULL, enab);
12873 enab->dten_primed = 1;
12878 * Called to indicate that probes should be provided due to retained
12879 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
12880 * must take an initial lap through the enabling calling the dtps_provide()
12881 * entry point explicitly to allow for autocreated probes.
12884 dtrace_enabling_provide(dtrace_provider_t *prv)
12887 dtrace_probedesc_t desc;
12888 dtrace_genid_t gen;
12890 ASSERT(MUTEX_HELD(&dtrace_lock));
12891 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12895 prv = dtrace_provider;
12899 dtrace_enabling_t *enab;
12900 void *parg = prv->dtpv_arg;
12903 gen = dtrace_retained_gen;
12904 for (enab = dtrace_retained; enab != NULL;
12905 enab = enab->dten_next) {
12906 for (i = 0; i < enab->dten_ndesc; i++) {
12907 desc = enab->dten_desc[i]->dted_probe;
12908 mutex_exit(&dtrace_lock);
12909 prv->dtpv_pops.dtps_provide(parg, &desc);
12910 mutex_enter(&dtrace_lock);
12912 * Process the retained enablings again if
12913 * they have changed while we weren't holding
12916 if (gen != dtrace_retained_gen)
12920 } while (all && (prv = prv->dtpv_next) != NULL);
12922 mutex_exit(&dtrace_lock);
12923 dtrace_probe_provide(NULL, all ? NULL : prv);
12924 mutex_enter(&dtrace_lock);
12928 * Called to reap ECBs that are attached to probes from defunct providers.
12931 dtrace_enabling_reap(void)
12933 dtrace_provider_t *prov;
12934 dtrace_probe_t *probe;
12939 mutex_enter(&cpu_lock);
12940 mutex_enter(&dtrace_lock);
12942 for (i = 0; i < dtrace_nprobes; i++) {
12943 if ((probe = dtrace_probes[i]) == NULL)
12946 if (probe->dtpr_ecb == NULL)
12949 prov = probe->dtpr_provider;
12951 if ((when = prov->dtpv_defunct) == 0)
12955 * We have ECBs on a defunct provider: we want to reap these
12956 * ECBs to allow the provider to unregister. The destruction
12957 * of these ECBs must be done carefully: if we destroy the ECB
12958 * and the consumer later wishes to consume an EPID that
12959 * corresponds to the destroyed ECB (and if the EPID metadata
12960 * has not been previously consumed), the consumer will abort
12961 * processing on the unknown EPID. To reduce (but not, sadly,
12962 * eliminate) the possibility of this, we will only destroy an
12963 * ECB for a defunct provider if, for the state that
12964 * corresponds to the ECB:
12966 * (a) There is no speculative tracing (which can effectively
12967 * cache an EPID for an arbitrary amount of time).
12969 * (b) The principal buffers have been switched twice since the
12970 * provider became defunct.
12972 * (c) The aggregation buffers are of zero size or have been
12973 * switched twice since the provider became defunct.
12975 * We use dts_speculates to determine (a) and call a function
12976 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
12977 * that as soon as we've been unable to destroy one of the ECBs
12978 * associated with the probe, we quit trying -- reaping is only
12979 * fruitful in as much as we can destroy all ECBs associated
12980 * with the defunct provider's probes.
12982 while ((ecb = probe->dtpr_ecb) != NULL) {
12983 dtrace_state_t *state = ecb->dte_state;
12984 dtrace_buffer_t *buf = state->dts_buffer;
12985 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12987 if (state->dts_speculates)
12990 if (!dtrace_buffer_consumed(buf, when))
12993 if (!dtrace_buffer_consumed(aggbuf, when))
12996 dtrace_ecb_disable(ecb);
12997 ASSERT(probe->dtpr_ecb != ecb);
12998 dtrace_ecb_destroy(ecb);
13002 mutex_exit(&dtrace_lock);
13003 mutex_exit(&cpu_lock);
13007 * DTrace DOF Functions
13011 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13013 if (dtrace_err_verbose)
13014 cmn_err(CE_WARN, "failed to process DOF: %s", str);
13016 #ifdef DTRACE_ERRDEBUG
13017 dtrace_errdebug(str);
13022 * Create DOF out of a currently enabled state. Right now, we only create
13023 * DOF containing the run-time options -- but this could be expanded to create
13024 * complete DOF representing the enabled state.
13027 dtrace_dof_create(dtrace_state_t *state)
13031 dof_optdesc_t *opt;
13032 int i, len = sizeof (dof_hdr_t) +
13033 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13034 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13036 ASSERT(MUTEX_HELD(&dtrace_lock));
13038 dof = kmem_zalloc(len, KM_SLEEP);
13039 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13040 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13041 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13042 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13044 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13045 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13046 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13047 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13048 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13049 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13051 dof->dofh_flags = 0;
13052 dof->dofh_hdrsize = sizeof (dof_hdr_t);
13053 dof->dofh_secsize = sizeof (dof_sec_t);
13054 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
13055 dof->dofh_secoff = sizeof (dof_hdr_t);
13056 dof->dofh_loadsz = len;
13057 dof->dofh_filesz = len;
13061 * Fill in the option section header...
13063 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13064 sec->dofs_type = DOF_SECT_OPTDESC;
13065 sec->dofs_align = sizeof (uint64_t);
13066 sec->dofs_flags = DOF_SECF_LOAD;
13067 sec->dofs_entsize = sizeof (dof_optdesc_t);
13069 opt = (dof_optdesc_t *)((uintptr_t)sec +
13070 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13072 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13073 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13075 for (i = 0; i < DTRACEOPT_MAX; i++) {
13076 opt[i].dofo_option = i;
13077 opt[i].dofo_strtab = DOF_SECIDX_NONE;
13078 opt[i].dofo_value = state->dts_options[i];
13085 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13087 dof_hdr_t hdr, *dof;
13089 ASSERT(!MUTEX_HELD(&dtrace_lock));
13092 * First, we're going to copyin() the sizeof (dof_hdr_t).
13094 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13095 dtrace_dof_error(NULL, "failed to copyin DOF header");
13101 * Now we'll allocate the entire DOF and copy it in -- provided
13102 * that the length isn't outrageous.
13104 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13105 dtrace_dof_error(&hdr, "load size exceeds maximum");
13110 if (hdr.dofh_loadsz < sizeof (hdr)) {
13111 dtrace_dof_error(&hdr, "invalid load size");
13116 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13118 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13119 dof->dofh_loadsz != hdr.dofh_loadsz) {
13120 kmem_free(dof, hdr.dofh_loadsz);
13130 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13132 dof_hdr_t hdr, *dof;
13136 ASSERT(!MUTEX_HELD(&dtrace_lock));
13141 * First, we're going to copyin() the sizeof (dof_hdr_t).
13143 if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13144 dtrace_dof_error(NULL, "failed to copyin DOF header");
13150 * Now we'll allocate the entire DOF and copy it in -- provided
13151 * that the length isn't outrageous.
13153 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13154 dtrace_dof_error(&hdr, "load size exceeds maximum");
13158 loadsz = (size_t)hdr.dofh_loadsz;
13160 if (loadsz < sizeof (hdr)) {
13161 dtrace_dof_error(&hdr, "invalid load size");
13166 dof = kmem_alloc(loadsz, KM_SLEEP);
13168 if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13169 dof->dofh_loadsz != loadsz) {
13170 kmem_free(dof, hdr.dofh_loadsz);
13178 static __inline uchar_t
13179 dtrace_dof_char(char c)
13200 return (c - 'A' + 10);
13207 return (c - 'a' + 10);
13209 /* Should not reach here. */
13210 return (UCHAR_MAX);
13212 #endif /* __FreeBSD__ */
13215 dtrace_dof_property(const char *name)
13219 u_char *data, *eol;
13221 size_t bytes, len, i;
13227 doffile = preload_search_by_type("dtrace_dof");
13228 if (doffile == NULL)
13231 data = preload_fetch_addr(doffile);
13232 len = preload_fetch_size(doffile);
13234 /* Look for the end of the line. All lines end in a newline. */
13235 eol = memchr(data, '\n', len);
13239 if (strncmp(name, data, strlen(name)) == 0)
13242 eol++; /* skip past the newline */
13247 /* We've found the data corresponding to the specified key. */
13249 data += strlen(name) + 1; /* skip past the '=' */
13253 if (bytes < sizeof(dof_hdr_t)) {
13254 dtrace_dof_error(NULL, "truncated header");
13259 * Each byte is represented by the two ASCII characters in its hex
13262 dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13263 for (i = 0; i < bytes; i++) {
13264 c1 = dtrace_dof_char(data[i * 2]);
13265 c2 = dtrace_dof_char(data[i * 2 + 1]);
13266 if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13267 dtrace_dof_error(NULL, "invalid hex char in DOF");
13270 dofbuf[i] = c1 * 16 + c2;
13273 dof = (dof_hdr_t *)dofbuf;
13274 if (bytes < dof->dofh_loadsz) {
13275 dtrace_dof_error(NULL, "truncated DOF");
13279 if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13280 dtrace_dof_error(NULL, "oversized DOF");
13287 free(dof, M_SOLARIS);
13289 #else /* __FreeBSD__ */
13292 unsigned int len, i;
13296 * Unfortunately, array of values in .conf files are always (and
13297 * only) interpreted to be integer arrays. We must read our DOF
13298 * as an integer array, and then squeeze it into a byte array.
13300 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13301 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13304 for (i = 0; i < len; i++)
13305 buf[i] = (uchar_t)(((int *)buf)[i]);
13307 if (len < sizeof (dof_hdr_t)) {
13308 ddi_prop_free(buf);
13309 dtrace_dof_error(NULL, "truncated header");
13313 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13314 ddi_prop_free(buf);
13315 dtrace_dof_error(NULL, "truncated DOF");
13319 if (loadsz >= dtrace_dof_maxsize) {
13320 ddi_prop_free(buf);
13321 dtrace_dof_error(NULL, "oversized DOF");
13325 dof = kmem_alloc(loadsz, KM_SLEEP);
13326 bcopy(buf, dof, loadsz);
13327 ddi_prop_free(buf);
13330 #endif /* !__FreeBSD__ */
13334 dtrace_dof_destroy(dof_hdr_t *dof)
13336 kmem_free(dof, dof->dofh_loadsz);
13340 * Return the dof_sec_t pointer corresponding to a given section index. If the
13341 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
13342 * a type other than DOF_SECT_NONE is specified, the header is checked against
13343 * this type and NULL is returned if the types do not match.
13346 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13348 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13349 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13351 if (i >= dof->dofh_secnum) {
13352 dtrace_dof_error(dof, "referenced section index is invalid");
13356 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13357 dtrace_dof_error(dof, "referenced section is not loadable");
13361 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13362 dtrace_dof_error(dof, "referenced section is the wrong type");
13369 static dtrace_probedesc_t *
13370 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13372 dof_probedesc_t *probe;
13374 uintptr_t daddr = (uintptr_t)dof;
13378 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13379 dtrace_dof_error(dof, "invalid probe section");
13383 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13384 dtrace_dof_error(dof, "bad alignment in probe description");
13388 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13389 dtrace_dof_error(dof, "truncated probe description");
13393 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13394 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13396 if (strtab == NULL)
13399 str = daddr + strtab->dofs_offset;
13400 size = strtab->dofs_size;
13402 if (probe->dofp_provider >= strtab->dofs_size) {
13403 dtrace_dof_error(dof, "corrupt probe provider");
13407 (void) strncpy(desc->dtpd_provider,
13408 (char *)(str + probe->dofp_provider),
13409 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13411 if (probe->dofp_mod >= strtab->dofs_size) {
13412 dtrace_dof_error(dof, "corrupt probe module");
13416 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13417 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13419 if (probe->dofp_func >= strtab->dofs_size) {
13420 dtrace_dof_error(dof, "corrupt probe function");
13424 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13425 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13427 if (probe->dofp_name >= strtab->dofs_size) {
13428 dtrace_dof_error(dof, "corrupt probe name");
13432 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13433 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13438 static dtrace_difo_t *
13439 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13444 dof_difohdr_t *dofd;
13445 uintptr_t daddr = (uintptr_t)dof;
13446 size_t max = dtrace_difo_maxsize;
13449 static const struct {
13457 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13458 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13459 sizeof (dif_instr_t), "multiple DIF sections" },
13461 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13462 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13463 sizeof (uint64_t), "multiple integer tables" },
13465 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13466 offsetof(dtrace_difo_t, dtdo_strlen), 0,
13467 sizeof (char), "multiple string tables" },
13469 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13470 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13471 sizeof (uint_t), "multiple variable tables" },
13473 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13476 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13477 dtrace_dof_error(dof, "invalid DIFO header section");
13481 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13482 dtrace_dof_error(dof, "bad alignment in DIFO header");
13486 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13487 sec->dofs_size % sizeof (dof_secidx_t)) {
13488 dtrace_dof_error(dof, "bad size in DIFO header");
13492 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13493 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13495 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13496 dp->dtdo_rtype = dofd->dofd_rtype;
13498 for (l = 0; l < n; l++) {
13503 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13504 dofd->dofd_links[l])) == NULL)
13505 goto err; /* invalid section link */
13507 if (ttl + subsec->dofs_size > max) {
13508 dtrace_dof_error(dof, "exceeds maximum size");
13512 ttl += subsec->dofs_size;
13514 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13515 if (subsec->dofs_type != difo[i].section)
13518 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13519 dtrace_dof_error(dof, "section not loaded");
13523 if (subsec->dofs_align != difo[i].align) {
13524 dtrace_dof_error(dof, "bad alignment");
13528 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13529 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13531 if (*bufp != NULL) {
13532 dtrace_dof_error(dof, difo[i].msg);
13536 if (difo[i].entsize != subsec->dofs_entsize) {
13537 dtrace_dof_error(dof, "entry size mismatch");
13541 if (subsec->dofs_entsize != 0 &&
13542 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13543 dtrace_dof_error(dof, "corrupt entry size");
13547 *lenp = subsec->dofs_size;
13548 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13549 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13550 *bufp, subsec->dofs_size);
13552 if (subsec->dofs_entsize != 0)
13553 *lenp /= subsec->dofs_entsize;
13559 * If we encounter a loadable DIFO sub-section that is not
13560 * known to us, assume this is a broken program and fail.
13562 if (difo[i].section == DOF_SECT_NONE &&
13563 (subsec->dofs_flags & DOF_SECF_LOAD)) {
13564 dtrace_dof_error(dof, "unrecognized DIFO subsection");
13569 if (dp->dtdo_buf == NULL) {
13571 * We can't have a DIF object without DIF text.
13573 dtrace_dof_error(dof, "missing DIF text");
13578 * Before we validate the DIF object, run through the variable table
13579 * looking for the strings -- if any of their size are under, we'll set
13580 * their size to be the system-wide default string size. Note that
13581 * this should _not_ happen if the "strsize" option has been set --
13582 * in this case, the compiler should have set the size to reflect the
13583 * setting of the option.
13585 for (i = 0; i < dp->dtdo_varlen; i++) {
13586 dtrace_difv_t *v = &dp->dtdo_vartab[i];
13587 dtrace_diftype_t *t = &v->dtdv_type;
13589 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13592 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13593 t->dtdt_size = dtrace_strsize_default;
13596 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13599 dtrace_difo_init(dp, vstate);
13603 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13604 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13605 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13606 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13608 kmem_free(dp, sizeof (dtrace_difo_t));
13612 static dtrace_predicate_t *
13613 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13618 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13621 return (dtrace_predicate_create(dp));
13624 static dtrace_actdesc_t *
13625 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13628 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13629 dof_actdesc_t *desc;
13630 dof_sec_t *difosec;
13632 uintptr_t daddr = (uintptr_t)dof;
13634 dtrace_actkind_t kind;
13636 if (sec->dofs_type != DOF_SECT_ACTDESC) {
13637 dtrace_dof_error(dof, "invalid action section");
13641 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13642 dtrace_dof_error(dof, "truncated action description");
13646 if (sec->dofs_align != sizeof (uint64_t)) {
13647 dtrace_dof_error(dof, "bad alignment in action description");
13651 if (sec->dofs_size < sec->dofs_entsize) {
13652 dtrace_dof_error(dof, "section entry size exceeds total size");
13656 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13657 dtrace_dof_error(dof, "bad entry size in action description");
13661 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13662 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13666 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13667 desc = (dof_actdesc_t *)(daddr +
13668 (uintptr_t)sec->dofs_offset + offs);
13669 kind = (dtrace_actkind_t)desc->dofa_kind;
13671 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13672 (kind != DTRACEACT_PRINTA ||
13673 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13674 (kind == DTRACEACT_DIFEXPR &&
13675 desc->dofa_strtab != DOF_SECIDX_NONE)) {
13681 * The argument to these actions is an index into the
13682 * DOF string table. For printf()-like actions, this
13683 * is the format string. For print(), this is the
13684 * CTF type of the expression result.
13686 if ((strtab = dtrace_dof_sect(dof,
13687 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13690 str = (char *)((uintptr_t)dof +
13691 (uintptr_t)strtab->dofs_offset);
13693 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13694 if (str[i] == '\0')
13698 if (i >= strtab->dofs_size) {
13699 dtrace_dof_error(dof, "bogus format string");
13703 if (i == desc->dofa_arg) {
13704 dtrace_dof_error(dof, "empty format string");
13708 i -= desc->dofa_arg;
13709 fmt = kmem_alloc(i + 1, KM_SLEEP);
13710 bcopy(&str[desc->dofa_arg], fmt, i + 1);
13711 arg = (uint64_t)(uintptr_t)fmt;
13713 if (kind == DTRACEACT_PRINTA) {
13714 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13717 arg = desc->dofa_arg;
13721 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13722 desc->dofa_uarg, arg);
13724 if (last != NULL) {
13725 last->dtad_next = act;
13732 if (desc->dofa_difo == DOF_SECIDX_NONE)
13735 if ((difosec = dtrace_dof_sect(dof,
13736 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13739 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13741 if (act->dtad_difo == NULL)
13745 ASSERT(first != NULL);
13749 for (act = first; act != NULL; act = next) {
13750 next = act->dtad_next;
13751 dtrace_actdesc_release(act, vstate);
13757 static dtrace_ecbdesc_t *
13758 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13761 dtrace_ecbdesc_t *ep;
13762 dof_ecbdesc_t *ecb;
13763 dtrace_probedesc_t *desc;
13764 dtrace_predicate_t *pred = NULL;
13766 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13767 dtrace_dof_error(dof, "truncated ECB description");
13771 if (sec->dofs_align != sizeof (uint64_t)) {
13772 dtrace_dof_error(dof, "bad alignment in ECB description");
13776 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13777 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13782 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13783 ep->dted_uarg = ecb->dofe_uarg;
13784 desc = &ep->dted_probe;
13786 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13789 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13790 if ((sec = dtrace_dof_sect(dof,
13791 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13794 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13797 ep->dted_pred.dtpdd_predicate = pred;
13800 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13801 if ((sec = dtrace_dof_sect(dof,
13802 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13805 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13807 if (ep->dted_action == NULL)
13815 dtrace_predicate_release(pred, vstate);
13816 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13821 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13822 * specified DOF. At present, this amounts to simply adding 'ubase' to the
13823 * site of any user SETX relocations to account for load object base address.
13824 * In the future, if we need other relocations, this function can be extended.
13827 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13829 uintptr_t daddr = (uintptr_t)dof;
13830 dof_relohdr_t *dofr =
13831 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13832 dof_sec_t *ss, *rs, *ts;
13836 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13837 sec->dofs_align != sizeof (dof_secidx_t)) {
13838 dtrace_dof_error(dof, "invalid relocation header");
13842 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13843 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13844 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13846 if (ss == NULL || rs == NULL || ts == NULL)
13847 return (-1); /* dtrace_dof_error() has been called already */
13849 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13850 rs->dofs_align != sizeof (uint64_t)) {
13851 dtrace_dof_error(dof, "invalid relocation section");
13855 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13856 n = rs->dofs_size / rs->dofs_entsize;
13858 for (i = 0; i < n; i++) {
13859 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13861 switch (r->dofr_type) {
13862 case DOF_RELO_NONE:
13864 case DOF_RELO_SETX:
13865 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13866 sizeof (uint64_t) > ts->dofs_size) {
13867 dtrace_dof_error(dof, "bad relocation offset");
13871 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13872 dtrace_dof_error(dof, "misaligned setx relo");
13876 *(uint64_t *)taddr += ubase;
13879 dtrace_dof_error(dof, "invalid relocation type");
13883 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13890 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13891 * header: it should be at the front of a memory region that is at least
13892 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13893 * size. It need not be validated in any other way.
13896 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13897 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13899 uint64_t len = dof->dofh_loadsz, seclen;
13900 uintptr_t daddr = (uintptr_t)dof;
13901 dtrace_ecbdesc_t *ep;
13902 dtrace_enabling_t *enab;
13905 ASSERT(MUTEX_HELD(&dtrace_lock));
13906 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13909 * Check the DOF header identification bytes. In addition to checking
13910 * valid settings, we also verify that unused bits/bytes are zeroed so
13911 * we can use them later without fear of regressing existing binaries.
13913 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13914 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13915 dtrace_dof_error(dof, "DOF magic string mismatch");
13919 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13920 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13921 dtrace_dof_error(dof, "DOF has invalid data model");
13925 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13926 dtrace_dof_error(dof, "DOF encoding mismatch");
13930 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13931 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13932 dtrace_dof_error(dof, "DOF version mismatch");
13936 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13937 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13941 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13942 dtrace_dof_error(dof, "DOF uses too many integer registers");
13946 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13947 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13951 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13952 if (dof->dofh_ident[i] != 0) {
13953 dtrace_dof_error(dof, "DOF has invalid ident byte set");
13958 if (dof->dofh_flags & ~DOF_FL_VALID) {
13959 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13963 if (dof->dofh_secsize == 0) {
13964 dtrace_dof_error(dof, "zero section header size");
13969 * Check that the section headers don't exceed the amount of DOF
13970 * data. Note that we cast the section size and number of sections
13971 * to uint64_t's to prevent possible overflow in the multiplication.
13973 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13975 if (dof->dofh_secoff > len || seclen > len ||
13976 dof->dofh_secoff + seclen > len) {
13977 dtrace_dof_error(dof, "truncated section headers");
13981 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13982 dtrace_dof_error(dof, "misaligned section headers");
13986 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13987 dtrace_dof_error(dof, "misaligned section size");
13992 * Take an initial pass through the section headers to be sure that
13993 * the headers don't have stray offsets. If the 'noprobes' flag is
13994 * set, do not permit sections relating to providers, probes, or args.
13996 for (i = 0; i < dof->dofh_secnum; i++) {
13997 dof_sec_t *sec = (dof_sec_t *)(daddr +
13998 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14001 switch (sec->dofs_type) {
14002 case DOF_SECT_PROVIDER:
14003 case DOF_SECT_PROBES:
14004 case DOF_SECT_PRARGS:
14005 case DOF_SECT_PROFFS:
14006 dtrace_dof_error(dof, "illegal sections "
14012 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14013 !(sec->dofs_flags & DOF_SECF_LOAD)) {
14014 dtrace_dof_error(dof, "loadable section with load "
14019 if (!(sec->dofs_flags & DOF_SECF_LOAD))
14020 continue; /* just ignore non-loadable sections */
14022 if (!ISP2(sec->dofs_align)) {
14023 dtrace_dof_error(dof, "bad section alignment");
14027 if (sec->dofs_offset & (sec->dofs_align - 1)) {
14028 dtrace_dof_error(dof, "misaligned section");
14032 if (sec->dofs_offset > len || sec->dofs_size > len ||
14033 sec->dofs_offset + sec->dofs_size > len) {
14034 dtrace_dof_error(dof, "corrupt section header");
14038 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14039 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14040 dtrace_dof_error(dof, "non-terminating string table");
14046 * Take a second pass through the sections and locate and perform any
14047 * relocations that are present. We do this after the first pass to
14048 * be sure that all sections have had their headers validated.
14050 for (i = 0; i < dof->dofh_secnum; i++) {
14051 dof_sec_t *sec = (dof_sec_t *)(daddr +
14052 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14054 if (!(sec->dofs_flags & DOF_SECF_LOAD))
14055 continue; /* skip sections that are not loadable */
14057 switch (sec->dofs_type) {
14058 case DOF_SECT_URELHDR:
14059 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
14065 if ((enab = *enabp) == NULL)
14066 enab = *enabp = dtrace_enabling_create(vstate);
14068 for (i = 0; i < dof->dofh_secnum; i++) {
14069 dof_sec_t *sec = (dof_sec_t *)(daddr +
14070 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14072 if (sec->dofs_type != DOF_SECT_ECBDESC)
14075 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14076 dtrace_enabling_destroy(enab);
14081 dtrace_enabling_add(enab, ep);
14088 * Process DOF for any options. This routine assumes that the DOF has been
14089 * at least processed by dtrace_dof_slurp().
14092 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14097 dof_optdesc_t *desc;
14099 for (i = 0; i < dof->dofh_secnum; i++) {
14100 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14101 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14103 if (sec->dofs_type != DOF_SECT_OPTDESC)
14106 if (sec->dofs_align != sizeof (uint64_t)) {
14107 dtrace_dof_error(dof, "bad alignment in "
14108 "option description");
14112 if ((entsize = sec->dofs_entsize) == 0) {
14113 dtrace_dof_error(dof, "zeroed option entry size");
14117 if (entsize < sizeof (dof_optdesc_t)) {
14118 dtrace_dof_error(dof, "bad option entry size");
14122 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14123 desc = (dof_optdesc_t *)((uintptr_t)dof +
14124 (uintptr_t)sec->dofs_offset + offs);
14126 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14127 dtrace_dof_error(dof, "non-zero option string");
14131 if (desc->dofo_value == DTRACEOPT_UNSET) {
14132 dtrace_dof_error(dof, "unset option");
14136 if ((rval = dtrace_state_option(state,
14137 desc->dofo_option, desc->dofo_value)) != 0) {
14138 dtrace_dof_error(dof, "rejected option");
14148 * DTrace Consumer State Functions
14151 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14153 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14156 dtrace_dynvar_t *dvar, *next, *start;
14159 ASSERT(MUTEX_HELD(&dtrace_lock));
14160 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14162 bzero(dstate, sizeof (dtrace_dstate_t));
14164 if ((dstate->dtds_chunksize = chunksize) == 0)
14165 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14167 VERIFY(dstate->dtds_chunksize < LONG_MAX);
14169 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14172 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14175 dstate->dtds_size = size;
14176 dstate->dtds_base = base;
14177 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14178 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14180 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14182 if (hashsize != 1 && (hashsize & 1))
14185 dstate->dtds_hashsize = hashsize;
14186 dstate->dtds_hash = dstate->dtds_base;
14189 * Set all of our hash buckets to point to the single sink, and (if
14190 * it hasn't already been set), set the sink's hash value to be the
14191 * sink sentinel value. The sink is needed for dynamic variable
14192 * lookups to know that they have iterated over an entire, valid hash
14195 for (i = 0; i < hashsize; i++)
14196 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14198 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14199 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14202 * Determine number of active CPUs. Divide free list evenly among
14205 start = (dtrace_dynvar_t *)
14206 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14207 limit = (uintptr_t)base + size;
14209 VERIFY((uintptr_t)start < limit);
14210 VERIFY((uintptr_t)start >= (uintptr_t)base);
14212 maxper = (limit - (uintptr_t)start) / NCPU;
14213 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14218 for (i = 0; i < NCPU; i++) {
14220 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14223 * If we don't even have enough chunks to make it once through
14224 * NCPUs, we're just going to allocate everything to the first
14225 * CPU. And if we're on the last CPU, we're going to allocate
14226 * whatever is left over. In either case, we set the limit to
14227 * be the limit of the dynamic variable space.
14229 if (maxper == 0 || i == NCPU - 1) {
14230 limit = (uintptr_t)base + size;
14233 limit = (uintptr_t)start + maxper;
14234 start = (dtrace_dynvar_t *)limit;
14237 VERIFY(limit <= (uintptr_t)base + size);
14240 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14241 dstate->dtds_chunksize);
14243 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14246 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14247 (uintptr_t)dvar <= (uintptr_t)base + size);
14248 dvar->dtdv_next = next;
14260 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14262 ASSERT(MUTEX_HELD(&cpu_lock));
14264 if (dstate->dtds_base == NULL)
14267 kmem_free(dstate->dtds_base, dstate->dtds_size);
14268 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14272 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14275 * Logical XOR, where are you?
14277 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14279 if (vstate->dtvs_nglobals > 0) {
14280 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14281 sizeof (dtrace_statvar_t *));
14284 if (vstate->dtvs_ntlocals > 0) {
14285 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14286 sizeof (dtrace_difv_t));
14289 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14291 if (vstate->dtvs_nlocals > 0) {
14292 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14293 sizeof (dtrace_statvar_t *));
14299 dtrace_state_clean(dtrace_state_t *state)
14301 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14304 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14305 dtrace_speculation_clean(state);
14309 dtrace_state_deadman(dtrace_state_t *state)
14315 now = dtrace_gethrtime();
14317 if (state != dtrace_anon.dta_state &&
14318 now - state->dts_laststatus >= dtrace_deadman_user)
14322 * We must be sure that dts_alive never appears to be less than the
14323 * value upon entry to dtrace_state_deadman(), and because we lack a
14324 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14325 * store INT64_MAX to it, followed by a memory barrier, followed by
14326 * the new value. This assures that dts_alive never appears to be
14327 * less than its true value, regardless of the order in which the
14328 * stores to the underlying storage are issued.
14330 state->dts_alive = INT64_MAX;
14331 dtrace_membar_producer();
14332 state->dts_alive = now;
14334 #else /* !illumos */
14336 dtrace_state_clean(void *arg)
14338 dtrace_state_t *state = arg;
14339 dtrace_optval_t *opt = state->dts_options;
14341 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14344 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14345 dtrace_speculation_clean(state);
14347 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14348 dtrace_state_clean, state);
14352 dtrace_state_deadman(void *arg)
14354 dtrace_state_t *state = arg;
14359 dtrace_debug_output();
14361 now = dtrace_gethrtime();
14363 if (state != dtrace_anon.dta_state &&
14364 now - state->dts_laststatus >= dtrace_deadman_user)
14368 * We must be sure that dts_alive never appears to be less than the
14369 * value upon entry to dtrace_state_deadman(), and because we lack a
14370 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14371 * store INT64_MAX to it, followed by a memory barrier, followed by
14372 * the new value. This assures that dts_alive never appears to be
14373 * less than its true value, regardless of the order in which the
14374 * stores to the underlying storage are issued.
14376 state->dts_alive = INT64_MAX;
14377 dtrace_membar_producer();
14378 state->dts_alive = now;
14380 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14381 dtrace_state_deadman, state);
14383 #endif /* illumos */
14385 static dtrace_state_t *
14387 dtrace_state_create(dev_t *devp, cred_t *cr)
14389 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14400 dtrace_state_t *state;
14401 dtrace_optval_t *opt;
14402 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14404 ASSERT(MUTEX_HELD(&dtrace_lock));
14405 ASSERT(MUTEX_HELD(&cpu_lock));
14408 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14409 VM_BESTFIT | VM_SLEEP);
14411 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14412 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14416 state = ddi_get_soft_state(dtrace_softstate, minor);
14423 /* Allocate memory for the state. */
14424 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14427 state->dts_epid = DTRACE_EPIDNONE + 1;
14429 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14431 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14432 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14434 if (devp != NULL) {
14435 major = getemajor(*devp);
14437 major = ddi_driver_major(dtrace_devi);
14440 state->dts_dev = makedevice(major, minor);
14443 *devp = state->dts_dev;
14445 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14446 state->dts_dev = dev;
14450 * We allocate NCPU buffers. On the one hand, this can be quite
14451 * a bit of memory per instance (nearly 36K on a Starcat). On the
14452 * other hand, it saves an additional memory reference in the probe
14455 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14456 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14459 state->dts_cleaner = CYCLIC_NONE;
14460 state->dts_deadman = CYCLIC_NONE;
14462 callout_init(&state->dts_cleaner, 1);
14463 callout_init(&state->dts_deadman, 1);
14465 state->dts_vstate.dtvs_state = state;
14467 for (i = 0; i < DTRACEOPT_MAX; i++)
14468 state->dts_options[i] = DTRACEOPT_UNSET;
14471 * Set the default options.
14473 opt = state->dts_options;
14474 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14475 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14476 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14477 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14478 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14479 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14480 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14481 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14482 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14483 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14484 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14485 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14486 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14487 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14489 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14492 * Depending on the user credentials, we set flag bits which alter probe
14493 * visibility or the amount of destructiveness allowed. In the case of
14494 * actual anonymous tracing, or the possession of all privileges, all of
14495 * the normal checks are bypassed.
14497 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14498 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14499 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14502 * Set up the credentials for this instantiation. We take a
14503 * hold on the credential to prevent it from disappearing on
14504 * us; this in turn prevents the zone_t referenced by this
14505 * credential from disappearing. This means that we can
14506 * examine the credential and the zone from probe context.
14509 state->dts_cred.dcr_cred = cr;
14512 * CRA_PROC means "we have *some* privilege for dtrace" and
14513 * unlocks the use of variables like pid, zonename, etc.
14515 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14516 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14517 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14521 * dtrace_user allows use of syscall and profile providers.
14522 * If the user also has proc_owner and/or proc_zone, we
14523 * extend the scope to include additional visibility and
14524 * destructive power.
14526 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14527 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14528 state->dts_cred.dcr_visible |=
14529 DTRACE_CRV_ALLPROC;
14531 state->dts_cred.dcr_action |=
14532 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14535 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14536 state->dts_cred.dcr_visible |=
14537 DTRACE_CRV_ALLZONE;
14539 state->dts_cred.dcr_action |=
14540 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14544 * If we have all privs in whatever zone this is,
14545 * we can do destructive things to processes which
14546 * have altered credentials.
14549 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14550 cr->cr_zone->zone_privset)) {
14551 state->dts_cred.dcr_action |=
14552 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14558 * Holding the dtrace_kernel privilege also implies that
14559 * the user has the dtrace_user privilege from a visibility
14560 * perspective. But without further privileges, some
14561 * destructive actions are not available.
14563 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14565 * Make all probes in all zones visible. However,
14566 * this doesn't mean that all actions become available
14569 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14570 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14572 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14575 * Holding proc_owner means that destructive actions
14576 * for *this* zone are allowed.
14578 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14579 state->dts_cred.dcr_action |=
14580 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14583 * Holding proc_zone means that destructive actions
14584 * for this user/group ID in all zones is allowed.
14586 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14587 state->dts_cred.dcr_action |=
14588 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14592 * If we have all privs in whatever zone this is,
14593 * we can do destructive things to processes which
14594 * have altered credentials.
14596 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14597 cr->cr_zone->zone_privset)) {
14598 state->dts_cred.dcr_action |=
14599 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14605 * Holding the dtrace_proc privilege gives control over fasttrap
14606 * and pid providers. We need to grant wider destructive
14607 * privileges in the event that the user has proc_owner and/or
14610 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14611 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14612 state->dts_cred.dcr_action |=
14613 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14615 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14616 state->dts_cred.dcr_action |=
14617 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14625 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14627 dtrace_optval_t *opt = state->dts_options, size;
14628 processorid_t cpu = 0;;
14629 int flags = 0, rval, factor, divisor = 1;
14631 ASSERT(MUTEX_HELD(&dtrace_lock));
14632 ASSERT(MUTEX_HELD(&cpu_lock));
14633 ASSERT(which < DTRACEOPT_MAX);
14634 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14635 (state == dtrace_anon.dta_state &&
14636 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14638 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14641 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14642 cpu = opt[DTRACEOPT_CPU];
14644 if (which == DTRACEOPT_SPECSIZE)
14645 flags |= DTRACEBUF_NOSWITCH;
14647 if (which == DTRACEOPT_BUFSIZE) {
14648 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14649 flags |= DTRACEBUF_RING;
14651 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14652 flags |= DTRACEBUF_FILL;
14654 if (state != dtrace_anon.dta_state ||
14655 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14656 flags |= DTRACEBUF_INACTIVE;
14659 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14661 * The size must be 8-byte aligned. If the size is not 8-byte
14662 * aligned, drop it down by the difference.
14664 if (size & (sizeof (uint64_t) - 1))
14665 size -= size & (sizeof (uint64_t) - 1);
14667 if (size < state->dts_reserve) {
14669 * Buffers always must be large enough to accommodate
14670 * their prereserved space. We return E2BIG instead
14671 * of ENOMEM in this case to allow for user-level
14672 * software to differentiate the cases.
14677 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14679 if (rval != ENOMEM) {
14684 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14687 for (divisor = 2; divisor < factor; divisor <<= 1)
14695 dtrace_state_buffers(dtrace_state_t *state)
14697 dtrace_speculation_t *spec = state->dts_speculations;
14700 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14701 DTRACEOPT_BUFSIZE)) != 0)
14704 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14705 DTRACEOPT_AGGSIZE)) != 0)
14708 for (i = 0; i < state->dts_nspeculations; i++) {
14709 if ((rval = dtrace_state_buffer(state,
14710 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14718 dtrace_state_prereserve(dtrace_state_t *state)
14721 dtrace_probe_t *probe;
14723 state->dts_reserve = 0;
14725 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14729 * If our buffer policy is a "fill" buffer policy, we need to set the
14730 * prereserved space to be the space required by the END probes.
14732 probe = dtrace_probes[dtrace_probeid_end - 1];
14733 ASSERT(probe != NULL);
14735 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14736 if (ecb->dte_state != state)
14739 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14744 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14746 dtrace_optval_t *opt = state->dts_options, sz, nspec;
14747 dtrace_speculation_t *spec;
14748 dtrace_buffer_t *buf;
14750 cyc_handler_t hdlr;
14753 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14754 dtrace_icookie_t cookie;
14756 mutex_enter(&cpu_lock);
14757 mutex_enter(&dtrace_lock);
14759 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14765 * Before we can perform any checks, we must prime all of the
14766 * retained enablings that correspond to this state.
14768 dtrace_enabling_prime(state);
14770 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14775 dtrace_state_prereserve(state);
14778 * Now we want to do is try to allocate our speculations.
14779 * We do not automatically resize the number of speculations; if
14780 * this fails, we will fail the operation.
14782 nspec = opt[DTRACEOPT_NSPEC];
14783 ASSERT(nspec != DTRACEOPT_UNSET);
14785 if (nspec > INT_MAX) {
14790 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14791 KM_NOSLEEP | KM_NORMALPRI);
14793 if (spec == NULL) {
14798 state->dts_speculations = spec;
14799 state->dts_nspeculations = (int)nspec;
14801 for (i = 0; i < nspec; i++) {
14802 if ((buf = kmem_zalloc(bufsize,
14803 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
14808 spec[i].dtsp_buffer = buf;
14811 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14812 if (dtrace_anon.dta_state == NULL) {
14817 if (state->dts_necbs != 0) {
14822 state->dts_anon = dtrace_anon_grab();
14823 ASSERT(state->dts_anon != NULL);
14824 state = state->dts_anon;
14827 * We want "grabanon" to be set in the grabbed state, so we'll
14828 * copy that option value from the grabbing state into the
14831 state->dts_options[DTRACEOPT_GRABANON] =
14832 opt[DTRACEOPT_GRABANON];
14834 *cpu = dtrace_anon.dta_beganon;
14837 * If the anonymous state is active (as it almost certainly
14838 * is if the anonymous enabling ultimately matched anything),
14839 * we don't allow any further option processing -- but we
14840 * don't return failure.
14842 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14846 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14847 opt[DTRACEOPT_AGGSIZE] != 0) {
14848 if (state->dts_aggregations == NULL) {
14850 * We're not going to create an aggregation buffer
14851 * because we don't have any ECBs that contain
14852 * aggregations -- set this option to 0.
14854 opt[DTRACEOPT_AGGSIZE] = 0;
14857 * If we have an aggregation buffer, we must also have
14858 * a buffer to use as scratch.
14860 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14861 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14862 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14867 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14868 opt[DTRACEOPT_SPECSIZE] != 0) {
14869 if (!state->dts_speculates) {
14871 * We're not going to create speculation buffers
14872 * because we don't have any ECBs that actually
14873 * speculate -- set the speculation size to 0.
14875 opt[DTRACEOPT_SPECSIZE] = 0;
14880 * The bare minimum size for any buffer that we're actually going to
14881 * do anything to is sizeof (uint64_t).
14883 sz = sizeof (uint64_t);
14885 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14886 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14887 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14889 * A buffer size has been explicitly set to 0 (or to a size
14890 * that will be adjusted to 0) and we need the space -- we
14891 * need to return failure. We return ENOSPC to differentiate
14892 * it from failing to allocate a buffer due to failure to meet
14893 * the reserve (for which we return E2BIG).
14899 if ((rval = dtrace_state_buffers(state)) != 0)
14902 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14903 sz = dtrace_dstate_defsize;
14906 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14911 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14913 } while (sz >>= 1);
14915 opt[DTRACEOPT_DYNVARSIZE] = sz;
14920 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14921 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14923 if (opt[DTRACEOPT_CLEANRATE] == 0)
14924 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14926 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14927 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14929 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14930 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14932 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14934 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14935 hdlr.cyh_arg = state;
14936 hdlr.cyh_level = CY_LOW_LEVEL;
14939 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14941 state->dts_cleaner = cyclic_add(&hdlr, &when);
14943 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14944 hdlr.cyh_arg = state;
14945 hdlr.cyh_level = CY_LOW_LEVEL;
14948 when.cyt_interval = dtrace_deadman_interval;
14950 state->dts_deadman = cyclic_add(&hdlr, &when);
14952 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14953 dtrace_state_clean, state);
14954 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14955 dtrace_state_deadman, state);
14958 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14961 if (state->dts_getf != 0 &&
14962 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14964 * We don't have kernel privs but we have at least one call
14965 * to getf(); we need to bump our zone's count, and (if
14966 * this is the first enabling to have an unprivileged call
14967 * to getf()) we need to hook into closef().
14969 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14971 if (dtrace_getf++ == 0) {
14972 ASSERT(dtrace_closef == NULL);
14973 dtrace_closef = dtrace_getf_barrier;
14979 * Now it's time to actually fire the BEGIN probe. We need to disable
14980 * interrupts here both to record the CPU on which we fired the BEGIN
14981 * probe (the data from this CPU will be processed first at user
14982 * level) and to manually activate the buffer for this CPU.
14984 cookie = dtrace_interrupt_disable();
14986 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14987 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14989 dtrace_probe(dtrace_probeid_begin,
14990 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14991 dtrace_interrupt_enable(cookie);
14993 * We may have had an exit action from a BEGIN probe; only change our
14994 * state to ACTIVE if we're still in WARMUP.
14996 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14997 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14999 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15000 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15004 * We enable anonymous tracing before APs are started, so we must
15005 * activate buffers using the current CPU.
15007 if (state == dtrace_anon.dta_state)
15008 for (int i = 0; i < NCPU; i++)
15009 dtrace_buffer_activate_cpu(state, i);
15011 dtrace_xcall(DTRACE_CPUALL,
15012 (dtrace_xcall_t)dtrace_buffer_activate, state);
15015 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15016 * want each CPU to transition its principal buffer out of the
15017 * INACTIVE state. Doing this assures that no CPU will suddenly begin
15018 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15019 * atomically transition from processing none of a state's ECBs to
15020 * processing all of them.
15022 dtrace_xcall(DTRACE_CPUALL,
15023 (dtrace_xcall_t)dtrace_buffer_activate, state);
15028 dtrace_buffer_free(state->dts_buffer);
15029 dtrace_buffer_free(state->dts_aggbuffer);
15031 if ((nspec = state->dts_nspeculations) == 0) {
15032 ASSERT(state->dts_speculations == NULL);
15036 spec = state->dts_speculations;
15037 ASSERT(spec != NULL);
15039 for (i = 0; i < state->dts_nspeculations; i++) {
15040 if ((buf = spec[i].dtsp_buffer) == NULL)
15043 dtrace_buffer_free(buf);
15044 kmem_free(buf, bufsize);
15047 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15048 state->dts_nspeculations = 0;
15049 state->dts_speculations = NULL;
15052 mutex_exit(&dtrace_lock);
15053 mutex_exit(&cpu_lock);
15059 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15061 dtrace_icookie_t cookie;
15063 ASSERT(MUTEX_HELD(&dtrace_lock));
15065 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15066 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15070 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15071 * to be sure that every CPU has seen it. See below for the details
15072 * on why this is done.
15074 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15078 * By this point, it is impossible for any CPU to be still processing
15079 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
15080 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15081 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
15082 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15083 * iff we're in the END probe.
15085 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15087 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15090 * Finally, we can release the reserve and call the END probe. We
15091 * disable interrupts across calling the END probe to allow us to
15092 * return the CPU on which we actually called the END probe. This
15093 * allows user-land to be sure that this CPU's principal buffer is
15096 state->dts_reserve = 0;
15098 cookie = dtrace_interrupt_disable();
15100 dtrace_probe(dtrace_probeid_end,
15101 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15102 dtrace_interrupt_enable(cookie);
15104 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15108 if (state->dts_getf != 0 &&
15109 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15111 * We don't have kernel privs but we have at least one call
15112 * to getf(); we need to lower our zone's count, and (if
15113 * this is the last enabling to have an unprivileged call
15114 * to getf()) we need to clear the closef() hook.
15116 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15117 ASSERT(dtrace_closef == dtrace_getf_barrier);
15118 ASSERT(dtrace_getf > 0);
15120 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15122 if (--dtrace_getf == 0)
15123 dtrace_closef = NULL;
15131 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15132 dtrace_optval_t val)
15134 ASSERT(MUTEX_HELD(&dtrace_lock));
15136 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15139 if (option >= DTRACEOPT_MAX)
15142 if (option != DTRACEOPT_CPU && val < 0)
15146 case DTRACEOPT_DESTRUCTIVE:
15147 if (dtrace_destructive_disallow)
15150 state->dts_cred.dcr_destructive = 1;
15153 case DTRACEOPT_BUFSIZE:
15154 case DTRACEOPT_DYNVARSIZE:
15155 case DTRACEOPT_AGGSIZE:
15156 case DTRACEOPT_SPECSIZE:
15157 case DTRACEOPT_STRSIZE:
15161 if (val >= LONG_MAX) {
15163 * If this is an otherwise negative value, set it to
15164 * the highest multiple of 128m less than LONG_MAX.
15165 * Technically, we're adjusting the size without
15166 * regard to the buffer resizing policy, but in fact,
15167 * this has no effect -- if we set the buffer size to
15168 * ~LONG_MAX and the buffer policy is ultimately set to
15169 * be "manual", the buffer allocation is guaranteed to
15170 * fail, if only because the allocation requires two
15171 * buffers. (We set the the size to the highest
15172 * multiple of 128m because it ensures that the size
15173 * will remain a multiple of a megabyte when
15174 * repeatedly halved -- all the way down to 15m.)
15176 val = LONG_MAX - (1 << 27) + 1;
15180 state->dts_options[option] = val;
15186 dtrace_state_destroy(dtrace_state_t *state)
15189 dtrace_vstate_t *vstate = &state->dts_vstate;
15191 minor_t minor = getminor(state->dts_dev);
15193 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15194 dtrace_speculation_t *spec = state->dts_speculations;
15195 int nspec = state->dts_nspeculations;
15198 ASSERT(MUTEX_HELD(&dtrace_lock));
15199 ASSERT(MUTEX_HELD(&cpu_lock));
15202 * First, retract any retained enablings for this state.
15204 dtrace_enabling_retract(state);
15205 ASSERT(state->dts_nretained == 0);
15207 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15208 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15210 * We have managed to come into dtrace_state_destroy() on a
15211 * hot enabling -- almost certainly because of a disorderly
15212 * shutdown of a consumer. (That is, a consumer that is
15213 * exiting without having called dtrace_stop().) In this case,
15214 * we're going to set our activity to be KILLED, and then
15215 * issue a sync to be sure that everyone is out of probe
15216 * context before we start blowing away ECBs.
15218 state->dts_activity = DTRACE_ACTIVITY_KILLED;
15223 * Release the credential hold we took in dtrace_state_create().
15225 if (state->dts_cred.dcr_cred != NULL)
15226 crfree(state->dts_cred.dcr_cred);
15229 * Now we can safely disable and destroy any enabled probes. Because
15230 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15231 * (especially if they're all enabled), we take two passes through the
15232 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15233 * in the second we disable whatever is left over.
15235 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15236 for (i = 0; i < state->dts_necbs; i++) {
15237 if ((ecb = state->dts_ecbs[i]) == NULL)
15240 if (match && ecb->dte_probe != NULL) {
15241 dtrace_probe_t *probe = ecb->dte_probe;
15242 dtrace_provider_t *prov = probe->dtpr_provider;
15244 if (!(prov->dtpv_priv.dtpp_flags & match))
15248 dtrace_ecb_disable(ecb);
15249 dtrace_ecb_destroy(ecb);
15257 * Before we free the buffers, perform one more sync to assure that
15258 * every CPU is out of probe context.
15262 dtrace_buffer_free(state->dts_buffer);
15263 dtrace_buffer_free(state->dts_aggbuffer);
15265 for (i = 0; i < nspec; i++)
15266 dtrace_buffer_free(spec[i].dtsp_buffer);
15269 if (state->dts_cleaner != CYCLIC_NONE)
15270 cyclic_remove(state->dts_cleaner);
15272 if (state->dts_deadman != CYCLIC_NONE)
15273 cyclic_remove(state->dts_deadman);
15275 callout_stop(&state->dts_cleaner);
15276 callout_drain(&state->dts_cleaner);
15277 callout_stop(&state->dts_deadman);
15278 callout_drain(&state->dts_deadman);
15281 dtrace_dstate_fini(&vstate->dtvs_dynvars);
15282 dtrace_vstate_fini(vstate);
15283 if (state->dts_ecbs != NULL)
15284 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15286 if (state->dts_aggregations != NULL) {
15288 for (i = 0; i < state->dts_naggregations; i++)
15289 ASSERT(state->dts_aggregations[i] == NULL);
15291 ASSERT(state->dts_naggregations > 0);
15292 kmem_free(state->dts_aggregations,
15293 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15296 kmem_free(state->dts_buffer, bufsize);
15297 kmem_free(state->dts_aggbuffer, bufsize);
15299 for (i = 0; i < nspec; i++)
15300 kmem_free(spec[i].dtsp_buffer, bufsize);
15303 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15305 dtrace_format_destroy(state);
15307 if (state->dts_aggid_arena != NULL) {
15309 vmem_destroy(state->dts_aggid_arena);
15311 delete_unrhdr(state->dts_aggid_arena);
15313 state->dts_aggid_arena = NULL;
15316 ddi_soft_state_free(dtrace_softstate, minor);
15317 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15322 * DTrace Anonymous Enabling Functions
15324 static dtrace_state_t *
15325 dtrace_anon_grab(void)
15327 dtrace_state_t *state;
15329 ASSERT(MUTEX_HELD(&dtrace_lock));
15331 if ((state = dtrace_anon.dta_state) == NULL) {
15332 ASSERT(dtrace_anon.dta_enabling == NULL);
15336 ASSERT(dtrace_anon.dta_enabling != NULL);
15337 ASSERT(dtrace_retained != NULL);
15339 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15340 dtrace_anon.dta_enabling = NULL;
15341 dtrace_anon.dta_state = NULL;
15347 dtrace_anon_property(void)
15350 dtrace_state_t *state;
15352 char c[32]; /* enough for "dof-data-" + digits */
15354 ASSERT(MUTEX_HELD(&dtrace_lock));
15355 ASSERT(MUTEX_HELD(&cpu_lock));
15357 for (i = 0; ; i++) {
15358 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
15360 dtrace_err_verbose = 1;
15362 if ((dof = dtrace_dof_property(c)) == NULL) {
15363 dtrace_err_verbose = 0;
15369 * We want to create anonymous state, so we need to transition
15370 * the kernel debugger to indicate that DTrace is active. If
15371 * this fails (e.g. because the debugger has modified text in
15372 * some way), we won't continue with the processing.
15374 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15375 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15376 "enabling ignored.");
15377 dtrace_dof_destroy(dof);
15383 * If we haven't allocated an anonymous state, we'll do so now.
15385 if ((state = dtrace_anon.dta_state) == NULL) {
15386 state = dtrace_state_create(NULL, NULL);
15387 dtrace_anon.dta_state = state;
15389 if (state == NULL) {
15391 * This basically shouldn't happen: the only
15392 * failure mode from dtrace_state_create() is a
15393 * failure of ddi_soft_state_zalloc() that
15394 * itself should never happen. Still, the
15395 * interface allows for a failure mode, and
15396 * we want to fail as gracefully as possible:
15397 * we'll emit an error message and cease
15398 * processing anonymous state in this case.
15400 cmn_err(CE_WARN, "failed to create "
15401 "anonymous state");
15402 dtrace_dof_destroy(dof);
15407 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15408 &dtrace_anon.dta_enabling, 0, B_TRUE);
15411 rv = dtrace_dof_options(dof, state);
15413 dtrace_err_verbose = 0;
15414 dtrace_dof_destroy(dof);
15418 * This is malformed DOF; chuck any anonymous state
15421 ASSERT(dtrace_anon.dta_enabling == NULL);
15422 dtrace_state_destroy(state);
15423 dtrace_anon.dta_state = NULL;
15427 ASSERT(dtrace_anon.dta_enabling != NULL);
15430 if (dtrace_anon.dta_enabling != NULL) {
15434 * dtrace_enabling_retain() can only fail because we are
15435 * trying to retain more enablings than are allowed -- but
15436 * we only have one anonymous enabling, and we are guaranteed
15437 * to be allowed at least one retained enabling; we assert
15438 * that dtrace_enabling_retain() returns success.
15440 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15443 dtrace_enabling_dump(dtrace_anon.dta_enabling);
15448 * DTrace Helper Functions
15451 dtrace_helper_trace(dtrace_helper_action_t *helper,
15452 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15454 uint32_t size, next, nnext, i;
15455 dtrace_helptrace_t *ent, *buffer;
15456 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15458 if ((buffer = dtrace_helptrace_buffer) == NULL)
15461 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15464 * What would a tracing framework be without its own tracing
15465 * framework? (Well, a hell of a lot simpler, for starters...)
15467 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15468 sizeof (uint64_t) - sizeof (uint64_t);
15471 * Iterate until we can allocate a slot in the trace buffer.
15474 next = dtrace_helptrace_next;
15476 if (next + size < dtrace_helptrace_bufsize) {
15477 nnext = next + size;
15481 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15484 * We have our slot; fill it in.
15486 if (nnext == size) {
15487 dtrace_helptrace_wrapped++;
15491 ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15492 ent->dtht_helper = helper;
15493 ent->dtht_where = where;
15494 ent->dtht_nlocals = vstate->dtvs_nlocals;
15496 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15497 mstate->dtms_fltoffs : -1;
15498 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15499 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15501 for (i = 0; i < vstate->dtvs_nlocals; i++) {
15502 dtrace_statvar_t *svar;
15504 if ((svar = vstate->dtvs_locals[i]) == NULL)
15507 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15508 ent->dtht_locals[i] =
15509 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15514 dtrace_helper(int which, dtrace_mstate_t *mstate,
15515 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15517 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15518 uint64_t sarg0 = mstate->dtms_arg[0];
15519 uint64_t sarg1 = mstate->dtms_arg[1];
15521 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15522 dtrace_helper_action_t *helper;
15523 dtrace_vstate_t *vstate;
15524 dtrace_difo_t *pred;
15525 int i, trace = dtrace_helptrace_buffer != NULL;
15527 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15529 if (helpers == NULL)
15532 if ((helper = helpers->dthps_actions[which]) == NULL)
15535 vstate = &helpers->dthps_vstate;
15536 mstate->dtms_arg[0] = arg0;
15537 mstate->dtms_arg[1] = arg1;
15540 * Now iterate over each helper. If its predicate evaluates to 'true',
15541 * we'll call the corresponding actions. Note that the below calls
15542 * to dtrace_dif_emulate() may set faults in machine state. This is
15543 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
15544 * the stored DIF offset with its own (which is the desired behavior).
15545 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15546 * from machine state; this is okay, too.
15548 for (; helper != NULL; helper = helper->dtha_next) {
15549 if ((pred = helper->dtha_predicate) != NULL) {
15551 dtrace_helper_trace(helper, mstate, vstate, 0);
15553 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15556 if (*flags & CPU_DTRACE_FAULT)
15560 for (i = 0; i < helper->dtha_nactions; i++) {
15562 dtrace_helper_trace(helper,
15563 mstate, vstate, i + 1);
15565 rval = dtrace_dif_emulate(helper->dtha_actions[i],
15566 mstate, vstate, state);
15568 if (*flags & CPU_DTRACE_FAULT)
15574 dtrace_helper_trace(helper, mstate, vstate,
15575 DTRACE_HELPTRACE_NEXT);
15579 dtrace_helper_trace(helper, mstate, vstate,
15580 DTRACE_HELPTRACE_DONE);
15583 * Restore the arg0 that we saved upon entry.
15585 mstate->dtms_arg[0] = sarg0;
15586 mstate->dtms_arg[1] = sarg1;
15592 dtrace_helper_trace(helper, mstate, vstate,
15593 DTRACE_HELPTRACE_ERR);
15596 * Restore the arg0 that we saved upon entry.
15598 mstate->dtms_arg[0] = sarg0;
15599 mstate->dtms_arg[1] = sarg1;
15605 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15606 dtrace_vstate_t *vstate)
15610 if (helper->dtha_predicate != NULL)
15611 dtrace_difo_release(helper->dtha_predicate, vstate);
15613 for (i = 0; i < helper->dtha_nactions; i++) {
15614 ASSERT(helper->dtha_actions[i] != NULL);
15615 dtrace_difo_release(helper->dtha_actions[i], vstate);
15618 kmem_free(helper->dtha_actions,
15619 helper->dtha_nactions * sizeof (dtrace_difo_t *));
15620 kmem_free(helper, sizeof (dtrace_helper_action_t));
15624 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15626 proc_t *p = curproc;
15627 dtrace_vstate_t *vstate;
15631 help = p->p_dtrace_helpers;
15633 ASSERT(MUTEX_HELD(&dtrace_lock));
15635 if (help == NULL || gen > help->dthps_generation)
15638 vstate = &help->dthps_vstate;
15640 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15641 dtrace_helper_action_t *last = NULL, *h, *next;
15643 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15644 next = h->dtha_next;
15646 if (h->dtha_generation == gen) {
15647 if (last != NULL) {
15648 last->dtha_next = next;
15650 help->dthps_actions[i] = next;
15653 dtrace_helper_action_destroy(h, vstate);
15661 * Interate until we've cleared out all helper providers with the
15662 * given generation number.
15665 dtrace_helper_provider_t *prov;
15668 * Look for a helper provider with the right generation. We
15669 * have to start back at the beginning of the list each time
15670 * because we drop dtrace_lock. It's unlikely that we'll make
15671 * more than two passes.
15673 for (i = 0; i < help->dthps_nprovs; i++) {
15674 prov = help->dthps_provs[i];
15676 if (prov->dthp_generation == gen)
15681 * If there were no matches, we're done.
15683 if (i == help->dthps_nprovs)
15687 * Move the last helper provider into this slot.
15689 help->dthps_nprovs--;
15690 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15691 help->dthps_provs[help->dthps_nprovs] = NULL;
15693 mutex_exit(&dtrace_lock);
15696 * If we have a meta provider, remove this helper provider.
15698 mutex_enter(&dtrace_meta_lock);
15699 if (dtrace_meta_pid != NULL) {
15700 ASSERT(dtrace_deferred_pid == NULL);
15701 dtrace_helper_provider_remove(&prov->dthp_prov,
15704 mutex_exit(&dtrace_meta_lock);
15706 dtrace_helper_provider_destroy(prov);
15708 mutex_enter(&dtrace_lock);
15715 dtrace_helper_validate(dtrace_helper_action_t *helper)
15720 if ((dp = helper->dtha_predicate) != NULL)
15721 err += dtrace_difo_validate_helper(dp);
15723 for (i = 0; i < helper->dtha_nactions; i++)
15724 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15730 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15731 dtrace_helpers_t *help)
15733 dtrace_helper_action_t *helper, *last;
15734 dtrace_actdesc_t *act;
15735 dtrace_vstate_t *vstate;
15736 dtrace_predicate_t *pred;
15737 int count = 0, nactions = 0, i;
15739 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15742 last = help->dthps_actions[which];
15743 vstate = &help->dthps_vstate;
15745 for (count = 0; last != NULL; last = last->dtha_next) {
15747 if (last->dtha_next == NULL)
15752 * If we already have dtrace_helper_actions_max helper actions for this
15753 * helper action type, we'll refuse to add a new one.
15755 if (count >= dtrace_helper_actions_max)
15758 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15759 helper->dtha_generation = help->dthps_generation;
15761 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15762 ASSERT(pred->dtp_difo != NULL);
15763 dtrace_difo_hold(pred->dtp_difo);
15764 helper->dtha_predicate = pred->dtp_difo;
15767 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15768 if (act->dtad_kind != DTRACEACT_DIFEXPR)
15771 if (act->dtad_difo == NULL)
15777 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15778 (helper->dtha_nactions = nactions), KM_SLEEP);
15780 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15781 dtrace_difo_hold(act->dtad_difo);
15782 helper->dtha_actions[i++] = act->dtad_difo;
15785 if (!dtrace_helper_validate(helper))
15788 if (last == NULL) {
15789 help->dthps_actions[which] = helper;
15791 last->dtha_next = helper;
15794 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15795 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15796 dtrace_helptrace_next = 0;
15801 dtrace_helper_action_destroy(helper, vstate);
15806 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15807 dof_helper_t *dofhp)
15809 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15811 mutex_enter(&dtrace_meta_lock);
15812 mutex_enter(&dtrace_lock);
15814 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15816 * If the dtrace module is loaded but not attached, or if
15817 * there aren't isn't a meta provider registered to deal with
15818 * these provider descriptions, we need to postpone creating
15819 * the actual providers until later.
15822 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15823 dtrace_deferred_pid != help) {
15824 help->dthps_deferred = 1;
15825 help->dthps_pid = p->p_pid;
15826 help->dthps_next = dtrace_deferred_pid;
15827 help->dthps_prev = NULL;
15828 if (dtrace_deferred_pid != NULL)
15829 dtrace_deferred_pid->dthps_prev = help;
15830 dtrace_deferred_pid = help;
15833 mutex_exit(&dtrace_lock);
15835 } else if (dofhp != NULL) {
15837 * If the dtrace module is loaded and we have a particular
15838 * helper provider description, pass that off to the
15842 mutex_exit(&dtrace_lock);
15844 dtrace_helper_provide(dofhp, p->p_pid);
15848 * Otherwise, just pass all the helper provider descriptions
15849 * off to the meta provider.
15853 mutex_exit(&dtrace_lock);
15855 for (i = 0; i < help->dthps_nprovs; i++) {
15856 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15861 mutex_exit(&dtrace_meta_lock);
15865 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
15867 dtrace_helper_provider_t *hprov, **tmp_provs;
15868 uint_t tmp_maxprovs, i;
15870 ASSERT(MUTEX_HELD(&dtrace_lock));
15871 ASSERT(help != NULL);
15874 * If we already have dtrace_helper_providers_max helper providers,
15875 * we're refuse to add a new one.
15877 if (help->dthps_nprovs >= dtrace_helper_providers_max)
15881 * Check to make sure this isn't a duplicate.
15883 for (i = 0; i < help->dthps_nprovs; i++) {
15884 if (dofhp->dofhp_addr ==
15885 help->dthps_provs[i]->dthp_prov.dofhp_addr)
15889 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15890 hprov->dthp_prov = *dofhp;
15891 hprov->dthp_ref = 1;
15892 hprov->dthp_generation = gen;
15895 * Allocate a bigger table for helper providers if it's already full.
15897 if (help->dthps_maxprovs == help->dthps_nprovs) {
15898 tmp_maxprovs = help->dthps_maxprovs;
15899 tmp_provs = help->dthps_provs;
15901 if (help->dthps_maxprovs == 0)
15902 help->dthps_maxprovs = 2;
15904 help->dthps_maxprovs *= 2;
15905 if (help->dthps_maxprovs > dtrace_helper_providers_max)
15906 help->dthps_maxprovs = dtrace_helper_providers_max;
15908 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15910 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15911 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15913 if (tmp_provs != NULL) {
15914 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15915 sizeof (dtrace_helper_provider_t *));
15916 kmem_free(tmp_provs, tmp_maxprovs *
15917 sizeof (dtrace_helper_provider_t *));
15921 help->dthps_provs[help->dthps_nprovs] = hprov;
15922 help->dthps_nprovs++;
15928 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15930 mutex_enter(&dtrace_lock);
15932 if (--hprov->dthp_ref == 0) {
15934 mutex_exit(&dtrace_lock);
15935 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15936 dtrace_dof_destroy(dof);
15937 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15939 mutex_exit(&dtrace_lock);
15944 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15946 uintptr_t daddr = (uintptr_t)dof;
15947 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15948 dof_provider_t *provider;
15949 dof_probe_t *probe;
15951 char *strtab, *typestr;
15952 dof_stridx_t typeidx;
15954 uint_t nprobes, j, k;
15956 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15958 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15959 dtrace_dof_error(dof, "misaligned section offset");
15964 * The section needs to be large enough to contain the DOF provider
15965 * structure appropriate for the given version.
15967 if (sec->dofs_size <
15968 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15969 offsetof(dof_provider_t, dofpv_prenoffs) :
15970 sizeof (dof_provider_t))) {
15971 dtrace_dof_error(dof, "provider section too small");
15975 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15976 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15977 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15978 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15979 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15981 if (str_sec == NULL || prb_sec == NULL ||
15982 arg_sec == NULL || off_sec == NULL)
15987 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15988 provider->dofpv_prenoffs != DOF_SECT_NONE &&
15989 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15990 provider->dofpv_prenoffs)) == NULL)
15993 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15995 if (provider->dofpv_name >= str_sec->dofs_size ||
15996 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15997 dtrace_dof_error(dof, "invalid provider name");
16001 if (prb_sec->dofs_entsize == 0 ||
16002 prb_sec->dofs_entsize > prb_sec->dofs_size) {
16003 dtrace_dof_error(dof, "invalid entry size");
16007 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16008 dtrace_dof_error(dof, "misaligned entry size");
16012 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16013 dtrace_dof_error(dof, "invalid entry size");
16017 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16018 dtrace_dof_error(dof, "misaligned section offset");
16022 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16023 dtrace_dof_error(dof, "invalid entry size");
16027 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16029 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16032 * Take a pass through the probes to check for errors.
16034 for (j = 0; j < nprobes; j++) {
16035 probe = (dof_probe_t *)(uintptr_t)(daddr +
16036 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16038 if (probe->dofpr_func >= str_sec->dofs_size) {
16039 dtrace_dof_error(dof, "invalid function name");
16043 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16044 dtrace_dof_error(dof, "function name too long");
16048 if (probe->dofpr_name >= str_sec->dofs_size ||
16049 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16050 dtrace_dof_error(dof, "invalid probe name");
16055 * The offset count must not wrap the index, and the offsets
16056 * must also not overflow the section's data.
16058 if (probe->dofpr_offidx + probe->dofpr_noffs <
16059 probe->dofpr_offidx ||
16060 (probe->dofpr_offidx + probe->dofpr_noffs) *
16061 off_sec->dofs_entsize > off_sec->dofs_size) {
16062 dtrace_dof_error(dof, "invalid probe offset");
16066 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16068 * If there's no is-enabled offset section, make sure
16069 * there aren't any is-enabled offsets. Otherwise
16070 * perform the same checks as for probe offsets
16071 * (immediately above).
16073 if (enoff_sec == NULL) {
16074 if (probe->dofpr_enoffidx != 0 ||
16075 probe->dofpr_nenoffs != 0) {
16076 dtrace_dof_error(dof, "is-enabled "
16077 "offsets with null section");
16080 } else if (probe->dofpr_enoffidx +
16081 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16082 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16083 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16084 dtrace_dof_error(dof, "invalid is-enabled "
16089 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16090 dtrace_dof_error(dof, "zero probe and "
16091 "is-enabled offsets");
16094 } else if (probe->dofpr_noffs == 0) {
16095 dtrace_dof_error(dof, "zero probe offsets");
16099 if (probe->dofpr_argidx + probe->dofpr_xargc <
16100 probe->dofpr_argidx ||
16101 (probe->dofpr_argidx + probe->dofpr_xargc) *
16102 arg_sec->dofs_entsize > arg_sec->dofs_size) {
16103 dtrace_dof_error(dof, "invalid args");
16107 typeidx = probe->dofpr_nargv;
16108 typestr = strtab + probe->dofpr_nargv;
16109 for (k = 0; k < probe->dofpr_nargc; k++) {
16110 if (typeidx >= str_sec->dofs_size) {
16111 dtrace_dof_error(dof, "bad "
16112 "native argument type");
16116 typesz = strlen(typestr) + 1;
16117 if (typesz > DTRACE_ARGTYPELEN) {
16118 dtrace_dof_error(dof, "native "
16119 "argument type too long");
16126 typeidx = probe->dofpr_xargv;
16127 typestr = strtab + probe->dofpr_xargv;
16128 for (k = 0; k < probe->dofpr_xargc; k++) {
16129 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16130 dtrace_dof_error(dof, "bad "
16131 "native argument index");
16135 if (typeidx >= str_sec->dofs_size) {
16136 dtrace_dof_error(dof, "bad "
16137 "translated argument type");
16141 typesz = strlen(typestr) + 1;
16142 if (typesz > DTRACE_ARGTYPELEN) {
16143 dtrace_dof_error(dof, "translated argument "
16158 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16160 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
16163 dtrace_helpers_t *help;
16164 dtrace_vstate_t *vstate;
16165 dtrace_enabling_t *enab = NULL;
16166 #ifndef __FreeBSD__
16167 proc_t *p = curproc;
16169 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16170 uintptr_t daddr = (uintptr_t)dof;
16172 ASSERT(MUTEX_HELD(&dtrace_lock));
16174 if ((help = p->p_dtrace_helpers) == NULL)
16175 help = dtrace_helpers_create(p);
16177 vstate = &help->dthps_vstate;
16179 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
16180 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
16181 dtrace_dof_destroy(dof);
16186 * Look for helper providers and validate their descriptions.
16189 for (i = 0; i < dof->dofh_secnum; i++) {
16190 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16191 dof->dofh_secoff + i * dof->dofh_secsize);
16193 if (sec->dofs_type != DOF_SECT_PROVIDER)
16196 if (dtrace_helper_provider_validate(dof, sec) != 0) {
16197 dtrace_enabling_destroy(enab);
16198 dtrace_dof_destroy(dof);
16207 * Now we need to walk through the ECB descriptions in the enabling.
16209 for (i = 0; i < enab->dten_ndesc; i++) {
16210 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16211 dtrace_probedesc_t *desc = &ep->dted_probe;
16213 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16216 if (strcmp(desc->dtpd_mod, "helper") != 0)
16219 if (strcmp(desc->dtpd_func, "ustack") != 0)
16222 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16225 * Adding this helper action failed -- we are now going
16226 * to rip out the entire generation and return failure.
16228 (void) dtrace_helper_destroygen(help,
16229 help->dthps_generation);
16230 dtrace_enabling_destroy(enab);
16231 dtrace_dof_destroy(dof);
16238 if (nhelpers < enab->dten_ndesc)
16239 dtrace_dof_error(dof, "unmatched helpers");
16241 gen = help->dthps_generation++;
16242 dtrace_enabling_destroy(enab);
16244 if (dhp != NULL && nprovs > 0) {
16246 * Now that this is in-kernel, we change the sense of the
16247 * members: dofhp_dof denotes the in-kernel copy of the DOF
16248 * and dofhp_addr denotes the address at user-level.
16250 dhp->dofhp_addr = dhp->dofhp_dof;
16251 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16253 if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16254 mutex_exit(&dtrace_lock);
16255 dtrace_helper_provider_register(p, help, dhp);
16256 mutex_enter(&dtrace_lock);
16263 dtrace_dof_destroy(dof);
16268 static dtrace_helpers_t *
16269 dtrace_helpers_create(proc_t *p)
16271 dtrace_helpers_t *help;
16273 ASSERT(MUTEX_HELD(&dtrace_lock));
16274 ASSERT(p->p_dtrace_helpers == NULL);
16276 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16277 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16278 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16280 p->p_dtrace_helpers = help;
16290 dtrace_helpers_destroy(proc_t *p)
16292 dtrace_helpers_t *help;
16293 dtrace_vstate_t *vstate;
16295 proc_t *p = curproc;
16299 mutex_enter(&dtrace_lock);
16301 ASSERT(p->p_dtrace_helpers != NULL);
16302 ASSERT(dtrace_helpers > 0);
16304 help = p->p_dtrace_helpers;
16305 vstate = &help->dthps_vstate;
16308 * We're now going to lose the help from this process.
16310 p->p_dtrace_helpers = NULL;
16314 * Destory the helper actions.
16316 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16317 dtrace_helper_action_t *h, *next;
16319 for (h = help->dthps_actions[i]; h != NULL; h = next) {
16320 next = h->dtha_next;
16321 dtrace_helper_action_destroy(h, vstate);
16326 mutex_exit(&dtrace_lock);
16329 * Destroy the helper providers.
16331 if (help->dthps_maxprovs > 0) {
16332 mutex_enter(&dtrace_meta_lock);
16333 if (dtrace_meta_pid != NULL) {
16334 ASSERT(dtrace_deferred_pid == NULL);
16336 for (i = 0; i < help->dthps_nprovs; i++) {
16337 dtrace_helper_provider_remove(
16338 &help->dthps_provs[i]->dthp_prov, p->p_pid);
16341 mutex_enter(&dtrace_lock);
16342 ASSERT(help->dthps_deferred == 0 ||
16343 help->dthps_next != NULL ||
16344 help->dthps_prev != NULL ||
16345 help == dtrace_deferred_pid);
16348 * Remove the helper from the deferred list.
16350 if (help->dthps_next != NULL)
16351 help->dthps_next->dthps_prev = help->dthps_prev;
16352 if (help->dthps_prev != NULL)
16353 help->dthps_prev->dthps_next = help->dthps_next;
16354 if (dtrace_deferred_pid == help) {
16355 dtrace_deferred_pid = help->dthps_next;
16356 ASSERT(help->dthps_prev == NULL);
16359 mutex_exit(&dtrace_lock);
16362 mutex_exit(&dtrace_meta_lock);
16364 for (i = 0; i < help->dthps_nprovs; i++) {
16365 dtrace_helper_provider_destroy(help->dthps_provs[i]);
16368 kmem_free(help->dthps_provs, help->dthps_maxprovs *
16369 sizeof (dtrace_helper_provider_t *));
16372 mutex_enter(&dtrace_lock);
16374 dtrace_vstate_fini(&help->dthps_vstate);
16375 kmem_free(help->dthps_actions,
16376 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16377 kmem_free(help, sizeof (dtrace_helpers_t));
16380 mutex_exit(&dtrace_lock);
16387 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16389 dtrace_helpers_t *help, *newhelp;
16390 dtrace_helper_action_t *helper, *new, *last;
16392 dtrace_vstate_t *vstate;
16393 int i, j, sz, hasprovs = 0;
16395 mutex_enter(&dtrace_lock);
16396 ASSERT(from->p_dtrace_helpers != NULL);
16397 ASSERT(dtrace_helpers > 0);
16399 help = from->p_dtrace_helpers;
16400 newhelp = dtrace_helpers_create(to);
16401 ASSERT(to->p_dtrace_helpers != NULL);
16403 newhelp->dthps_generation = help->dthps_generation;
16404 vstate = &newhelp->dthps_vstate;
16407 * Duplicate the helper actions.
16409 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16410 if ((helper = help->dthps_actions[i]) == NULL)
16413 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16414 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16416 new->dtha_generation = helper->dtha_generation;
16418 if ((dp = helper->dtha_predicate) != NULL) {
16419 dp = dtrace_difo_duplicate(dp, vstate);
16420 new->dtha_predicate = dp;
16423 new->dtha_nactions = helper->dtha_nactions;
16424 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16425 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16427 for (j = 0; j < new->dtha_nactions; j++) {
16428 dtrace_difo_t *dp = helper->dtha_actions[j];
16430 ASSERT(dp != NULL);
16431 dp = dtrace_difo_duplicate(dp, vstate);
16432 new->dtha_actions[j] = dp;
16435 if (last != NULL) {
16436 last->dtha_next = new;
16438 newhelp->dthps_actions[i] = new;
16446 * Duplicate the helper providers and register them with the
16447 * DTrace framework.
16449 if (help->dthps_nprovs > 0) {
16450 newhelp->dthps_nprovs = help->dthps_nprovs;
16451 newhelp->dthps_maxprovs = help->dthps_nprovs;
16452 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16453 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16454 for (i = 0; i < newhelp->dthps_nprovs; i++) {
16455 newhelp->dthps_provs[i] = help->dthps_provs[i];
16456 newhelp->dthps_provs[i]->dthp_ref++;
16462 mutex_exit(&dtrace_lock);
16465 dtrace_helper_provider_register(to, newhelp, NULL);
16469 * DTrace Hook Functions
16472 dtrace_module_loaded(modctl_t *ctl)
16474 dtrace_provider_t *prv;
16476 mutex_enter(&dtrace_provider_lock);
16478 mutex_enter(&mod_lock);
16482 ASSERT(ctl->mod_busy);
16486 * We're going to call each providers per-module provide operation
16487 * specifying only this module.
16489 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16490 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16493 mutex_exit(&mod_lock);
16495 mutex_exit(&dtrace_provider_lock);
16498 * If we have any retained enablings, we need to match against them.
16499 * Enabling probes requires that cpu_lock be held, and we cannot hold
16500 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16501 * module. (In particular, this happens when loading scheduling
16502 * classes.) So if we have any retained enablings, we need to dispatch
16503 * our task queue to do the match for us.
16505 mutex_enter(&dtrace_lock);
16507 if (dtrace_retained == NULL) {
16508 mutex_exit(&dtrace_lock);
16512 (void) taskq_dispatch(dtrace_taskq,
16513 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16515 mutex_exit(&dtrace_lock);
16518 * And now, for a little heuristic sleaze: in general, we want to
16519 * match modules as soon as they load. However, we cannot guarantee
16520 * this, because it would lead us to the lock ordering violation
16521 * outlined above. The common case, of course, is that cpu_lock is
16522 * _not_ held -- so we delay here for a clock tick, hoping that that's
16523 * long enough for the task queue to do its work. If it's not, it's
16524 * not a serious problem -- it just means that the module that we
16525 * just loaded may not be immediately instrumentable.
16532 dtrace_module_unloaded(modctl_t *ctl)
16534 dtrace_module_unloaded(modctl_t *ctl, int *error)
16537 dtrace_probe_t template, *probe, *first, *next;
16538 dtrace_provider_t *prov;
16540 char modname[DTRACE_MODNAMELEN];
16545 template.dtpr_mod = ctl->mod_modname;
16547 /* Handle the fact that ctl->filename may end in ".ko". */
16548 strlcpy(modname, ctl->filename, sizeof(modname));
16549 len = strlen(ctl->filename);
16550 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16551 modname[len - 3] = '\0';
16552 template.dtpr_mod = modname;
16555 mutex_enter(&dtrace_provider_lock);
16557 mutex_enter(&mod_lock);
16559 mutex_enter(&dtrace_lock);
16562 if (ctl->nenabled > 0) {
16563 /* Don't allow unloads if a probe is enabled. */
16564 mutex_exit(&dtrace_provider_lock);
16565 mutex_exit(&dtrace_lock);
16568 "kldunload: attempt to unload module that has DTrace probes enabled\n");
16573 if (dtrace_bymod == NULL) {
16575 * The DTrace module is loaded (obviously) but not attached;
16576 * we don't have any work to do.
16578 mutex_exit(&dtrace_provider_lock);
16580 mutex_exit(&mod_lock);
16582 mutex_exit(&dtrace_lock);
16586 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16587 probe != NULL; probe = probe->dtpr_nextmod) {
16588 if (probe->dtpr_ecb != NULL) {
16589 mutex_exit(&dtrace_provider_lock);
16591 mutex_exit(&mod_lock);
16593 mutex_exit(&dtrace_lock);
16596 * This shouldn't _actually_ be possible -- we're
16597 * unloading a module that has an enabled probe in it.
16598 * (It's normally up to the provider to make sure that
16599 * this can't happen.) However, because dtps_enable()
16600 * doesn't have a failure mode, there can be an
16601 * enable/unload race. Upshot: we don't want to
16602 * assert, but we're not going to disable the
16605 if (dtrace_err_verbose) {
16607 cmn_err(CE_WARN, "unloaded module '%s' had "
16608 "enabled probes", ctl->mod_modname);
16610 cmn_err(CE_WARN, "unloaded module '%s' had "
16611 "enabled probes", modname);
16621 for (first = NULL; probe != NULL; probe = next) {
16622 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16624 dtrace_probes[probe->dtpr_id - 1] = NULL;
16626 next = probe->dtpr_nextmod;
16627 dtrace_hash_remove(dtrace_bymod, probe);
16628 dtrace_hash_remove(dtrace_byfunc, probe);
16629 dtrace_hash_remove(dtrace_byname, probe);
16631 if (first == NULL) {
16633 probe->dtpr_nextmod = NULL;
16635 probe->dtpr_nextmod = first;
16641 * We've removed all of the module's probes from the hash chains and
16642 * from the probe array. Now issue a dtrace_sync() to be sure that
16643 * everyone has cleared out from any probe array processing.
16647 for (probe = first; probe != NULL; probe = first) {
16648 first = probe->dtpr_nextmod;
16649 prov = probe->dtpr_provider;
16650 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16652 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16653 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16654 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16656 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16658 free_unr(dtrace_arena, probe->dtpr_id);
16660 kmem_free(probe, sizeof (dtrace_probe_t));
16663 mutex_exit(&dtrace_lock);
16665 mutex_exit(&mod_lock);
16667 mutex_exit(&dtrace_provider_lock);
16672 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16675 dtrace_module_loaded(lf);
16679 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16683 /* We already have an error, so don't do anything. */
16685 dtrace_module_unloaded(lf, error);
16691 dtrace_suspend(void)
16693 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16697 dtrace_resume(void)
16699 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16704 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16706 ASSERT(MUTEX_HELD(&cpu_lock));
16707 mutex_enter(&dtrace_lock);
16711 dtrace_state_t *state;
16712 dtrace_optval_t *opt, rs, c;
16715 * For now, we only allocate a new buffer for anonymous state.
16717 if ((state = dtrace_anon.dta_state) == NULL)
16720 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16723 opt = state->dts_options;
16724 c = opt[DTRACEOPT_CPU];
16726 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16730 * Regardless of what the actual policy is, we're going to
16731 * temporarily set our resize policy to be manual. We're
16732 * also going to temporarily set our CPU option to denote
16733 * the newly configured CPU.
16735 rs = opt[DTRACEOPT_BUFRESIZE];
16736 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16737 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16739 (void) dtrace_state_buffers(state);
16741 opt[DTRACEOPT_BUFRESIZE] = rs;
16742 opt[DTRACEOPT_CPU] = c;
16749 * We don't free the buffer in the CPU_UNCONFIG case. (The
16750 * buffer will be freed when the consumer exits.)
16758 mutex_exit(&dtrace_lock);
16764 dtrace_cpu_setup_initial(processorid_t cpu)
16766 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16771 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16773 if (dtrace_toxranges >= dtrace_toxranges_max) {
16775 dtrace_toxrange_t *range;
16777 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16780 ASSERT(dtrace_toxrange == NULL);
16781 ASSERT(dtrace_toxranges_max == 0);
16782 dtrace_toxranges_max = 1;
16784 dtrace_toxranges_max <<= 1;
16787 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16788 range = kmem_zalloc(nsize, KM_SLEEP);
16790 if (dtrace_toxrange != NULL) {
16791 ASSERT(osize != 0);
16792 bcopy(dtrace_toxrange, range, osize);
16793 kmem_free(dtrace_toxrange, osize);
16796 dtrace_toxrange = range;
16799 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16800 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16802 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16803 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16804 dtrace_toxranges++;
16808 dtrace_getf_barrier()
16812 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
16813 * that contain calls to getf(), this routine will be called on every
16814 * closef() before either the underlying vnode is released or the
16815 * file_t itself is freed. By the time we are here, it is essential
16816 * that the file_t can no longer be accessed from a call to getf()
16817 * in probe context -- that assures that a dtrace_sync() can be used
16818 * to clear out any enablings referring to the old structures.
16820 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
16821 kcred->cr_zone->zone_dtrace_getf != 0)
16827 * DTrace Driver Cookbook Functions
16832 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16834 dtrace_provider_id_t id;
16835 dtrace_state_t *state = NULL;
16836 dtrace_enabling_t *enab;
16838 mutex_enter(&cpu_lock);
16839 mutex_enter(&dtrace_provider_lock);
16840 mutex_enter(&dtrace_lock);
16842 if (ddi_soft_state_init(&dtrace_softstate,
16843 sizeof (dtrace_state_t), 0) != 0) {
16844 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16845 mutex_exit(&cpu_lock);
16846 mutex_exit(&dtrace_provider_lock);
16847 mutex_exit(&dtrace_lock);
16848 return (DDI_FAILURE);
16851 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16852 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
16853 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16854 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
16855 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16856 ddi_remove_minor_node(devi, NULL);
16857 ddi_soft_state_fini(&dtrace_softstate);
16858 mutex_exit(&cpu_lock);
16859 mutex_exit(&dtrace_provider_lock);
16860 mutex_exit(&dtrace_lock);
16861 return (DDI_FAILURE);
16864 ddi_report_dev(devi);
16865 dtrace_devi = devi;
16867 dtrace_modload = dtrace_module_loaded;
16868 dtrace_modunload = dtrace_module_unloaded;
16869 dtrace_cpu_init = dtrace_cpu_setup_initial;
16870 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16871 dtrace_helpers_fork = dtrace_helpers_duplicate;
16872 dtrace_cpustart_init = dtrace_suspend;
16873 dtrace_cpustart_fini = dtrace_resume;
16874 dtrace_debugger_init = dtrace_suspend;
16875 dtrace_debugger_fini = dtrace_resume;
16877 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16879 ASSERT(MUTEX_HELD(&cpu_lock));
16881 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16882 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16883 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16884 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16885 VM_SLEEP | VMC_IDENTIFIER);
16886 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16889 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16890 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16891 NULL, NULL, NULL, NULL, NULL, 0);
16893 ASSERT(MUTEX_HELD(&cpu_lock));
16894 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16895 offsetof(dtrace_probe_t, dtpr_nextmod),
16896 offsetof(dtrace_probe_t, dtpr_prevmod));
16898 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16899 offsetof(dtrace_probe_t, dtpr_nextfunc),
16900 offsetof(dtrace_probe_t, dtpr_prevfunc));
16902 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16903 offsetof(dtrace_probe_t, dtpr_nextname),
16904 offsetof(dtrace_probe_t, dtpr_prevname));
16906 if (dtrace_retain_max < 1) {
16907 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16908 "setting to 1", dtrace_retain_max);
16909 dtrace_retain_max = 1;
16913 * Now discover our toxic ranges.
16915 dtrace_toxic_ranges(dtrace_toxrange_add);
16918 * Before we register ourselves as a provider to our own framework,
16919 * we would like to assert that dtrace_provider is NULL -- but that's
16920 * not true if we were loaded as a dependency of a DTrace provider.
16921 * Once we've registered, we can assert that dtrace_provider is our
16924 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16925 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16927 ASSERT(dtrace_provider != NULL);
16928 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16930 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16931 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16932 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16933 dtrace_provider, NULL, NULL, "END", 0, NULL);
16934 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16935 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16937 dtrace_anon_property();
16938 mutex_exit(&cpu_lock);
16941 * If there are already providers, we must ask them to provide their
16942 * probes, and then match any anonymous enabling against them. Note
16943 * that there should be no other retained enablings at this time:
16944 * the only retained enablings at this time should be the anonymous
16947 if (dtrace_anon.dta_enabling != NULL) {
16948 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16950 dtrace_enabling_provide(NULL);
16951 state = dtrace_anon.dta_state;
16954 * We couldn't hold cpu_lock across the above call to
16955 * dtrace_enabling_provide(), but we must hold it to actually
16956 * enable the probes. We have to drop all of our locks, pick
16957 * up cpu_lock, and regain our locks before matching the
16958 * retained anonymous enabling.
16960 mutex_exit(&dtrace_lock);
16961 mutex_exit(&dtrace_provider_lock);
16963 mutex_enter(&cpu_lock);
16964 mutex_enter(&dtrace_provider_lock);
16965 mutex_enter(&dtrace_lock);
16967 if ((enab = dtrace_anon.dta_enabling) != NULL)
16968 (void) dtrace_enabling_match(enab, NULL);
16970 mutex_exit(&cpu_lock);
16973 mutex_exit(&dtrace_lock);
16974 mutex_exit(&dtrace_provider_lock);
16976 if (state != NULL) {
16978 * If we created any anonymous state, set it going now.
16980 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16983 return (DDI_SUCCESS);
16985 #endif /* illumos */
16988 static void dtrace_dtr(void *);
16994 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16996 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16999 dtrace_state_t *state;
17005 if (getminor(*devp) == DTRACEMNRN_HELPER)
17009 * If this wasn't an open with the "helper" minor, then it must be
17010 * the "dtrace" minor.
17012 if (getminor(*devp) == DTRACEMNRN_DTRACE)
17015 cred_t *cred_p = NULL;
17016 cred_p = dev->si_cred;
17019 * If no DTRACE_PRIV_* bits are set in the credential, then the
17020 * caller lacks sufficient permission to do anything with DTrace.
17022 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17023 if (priv == DTRACE_PRIV_NONE) {
17030 * Ask all providers to provide all their probes.
17032 mutex_enter(&dtrace_provider_lock);
17033 dtrace_probe_provide(NULL, NULL);
17034 mutex_exit(&dtrace_provider_lock);
17036 mutex_enter(&cpu_lock);
17037 mutex_enter(&dtrace_lock);
17039 dtrace_membar_producer();
17043 * If the kernel debugger is active (that is, if the kernel debugger
17044 * modified text in some way), we won't allow the open.
17046 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17048 mutex_exit(&cpu_lock);
17049 mutex_exit(&dtrace_lock);
17053 if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17055 * If DTrace helper tracing is enabled, we need to allocate the
17056 * trace buffer and initialize the values.
17058 dtrace_helptrace_buffer =
17059 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17060 dtrace_helptrace_next = 0;
17061 dtrace_helptrace_wrapped = 0;
17062 dtrace_helptrace_enable = 0;
17065 state = dtrace_state_create(devp, cred_p);
17067 state = dtrace_state_create(dev, NULL);
17068 devfs_set_cdevpriv(state, dtrace_dtr);
17071 mutex_exit(&cpu_lock);
17073 if (state == NULL) {
17075 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17076 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17080 mutex_exit(&dtrace_lock);
17084 mutex_exit(&dtrace_lock);
17092 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17095 dtrace_dtr(void *data)
17099 minor_t minor = getminor(dev);
17100 dtrace_state_t *state;
17102 dtrace_helptrace_t *buf = NULL;
17105 if (minor == DTRACEMNRN_HELPER)
17108 state = ddi_get_soft_state(dtrace_softstate, minor);
17110 dtrace_state_t *state = data;
17113 mutex_enter(&cpu_lock);
17114 mutex_enter(&dtrace_lock);
17117 if (state->dts_anon)
17119 if (state != NULL && state->dts_anon)
17123 * There is anonymous state. Destroy that first.
17125 ASSERT(dtrace_anon.dta_state == NULL);
17126 dtrace_state_destroy(state->dts_anon);
17129 if (dtrace_helptrace_disable) {
17131 * If we have been told to disable helper tracing, set the
17132 * buffer to NULL before calling into dtrace_state_destroy();
17133 * we take advantage of its dtrace_sync() to know that no
17134 * CPU is in probe context with enabled helper tracing
17135 * after it returns.
17137 buf = dtrace_helptrace_buffer;
17138 dtrace_helptrace_buffer = NULL;
17142 dtrace_state_destroy(state);
17144 if (state != NULL) {
17145 dtrace_state_destroy(state);
17146 kmem_free(state, 0);
17149 ASSERT(dtrace_opens > 0);
17153 * Only relinquish control of the kernel debugger interface when there
17154 * are no consumers and no anonymous enablings.
17156 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17157 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17163 kmem_free(buf, dtrace_helptrace_bufsize);
17164 dtrace_helptrace_disable = 0;
17167 mutex_exit(&dtrace_lock);
17168 mutex_exit(&cpu_lock);
17178 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17181 dof_helper_t help, *dhp = NULL;
17184 case DTRACEHIOC_ADDDOF:
17185 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17186 dtrace_dof_error(NULL, "failed to copyin DOF helper");
17191 arg = (intptr_t)help.dofhp_dof;
17194 case DTRACEHIOC_ADD: {
17195 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17200 mutex_enter(&dtrace_lock);
17203 * dtrace_helper_slurp() takes responsibility for the dof --
17204 * it may free it now or it may save it and free it later.
17206 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17213 mutex_exit(&dtrace_lock);
17217 case DTRACEHIOC_REMOVE: {
17218 mutex_enter(&dtrace_lock);
17219 rval = dtrace_helper_destroygen(NULL, arg);
17220 mutex_exit(&dtrace_lock);
17234 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17236 minor_t minor = getminor(dev);
17237 dtrace_state_t *state;
17240 if (minor == DTRACEMNRN_HELPER)
17241 return (dtrace_ioctl_helper(cmd, arg, rv));
17243 state = ddi_get_soft_state(dtrace_softstate, minor);
17245 if (state->dts_anon) {
17246 ASSERT(dtrace_anon.dta_state == NULL);
17247 state = state->dts_anon;
17251 case DTRACEIOC_PROVIDER: {
17252 dtrace_providerdesc_t pvd;
17253 dtrace_provider_t *pvp;
17255 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17258 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17259 mutex_enter(&dtrace_provider_lock);
17261 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17262 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17266 mutex_exit(&dtrace_provider_lock);
17271 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17272 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17274 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17280 case DTRACEIOC_EPROBE: {
17281 dtrace_eprobedesc_t epdesc;
17283 dtrace_action_t *act;
17289 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17292 mutex_enter(&dtrace_lock);
17294 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17295 mutex_exit(&dtrace_lock);
17299 if (ecb->dte_probe == NULL) {
17300 mutex_exit(&dtrace_lock);
17304 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17305 epdesc.dtepd_uarg = ecb->dte_uarg;
17306 epdesc.dtepd_size = ecb->dte_size;
17308 nrecs = epdesc.dtepd_nrecs;
17309 epdesc.dtepd_nrecs = 0;
17310 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17311 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17314 epdesc.dtepd_nrecs++;
17318 * Now that we have the size, we need to allocate a temporary
17319 * buffer in which to store the complete description. We need
17320 * the temporary buffer to be able to drop dtrace_lock()
17321 * across the copyout(), below.
17323 size = sizeof (dtrace_eprobedesc_t) +
17324 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17326 buf = kmem_alloc(size, KM_SLEEP);
17327 dest = (uintptr_t)buf;
17329 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17330 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17332 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17333 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17339 bcopy(&act->dta_rec, (void *)dest,
17340 sizeof (dtrace_recdesc_t));
17341 dest += sizeof (dtrace_recdesc_t);
17344 mutex_exit(&dtrace_lock);
17346 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17347 kmem_free(buf, size);
17351 kmem_free(buf, size);
17355 case DTRACEIOC_AGGDESC: {
17356 dtrace_aggdesc_t aggdesc;
17357 dtrace_action_t *act;
17358 dtrace_aggregation_t *agg;
17361 dtrace_recdesc_t *lrec;
17366 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17369 mutex_enter(&dtrace_lock);
17371 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17372 mutex_exit(&dtrace_lock);
17376 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17378 nrecs = aggdesc.dtagd_nrecs;
17379 aggdesc.dtagd_nrecs = 0;
17381 offs = agg->dtag_base;
17382 lrec = &agg->dtag_action.dta_rec;
17383 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17385 for (act = agg->dtag_first; ; act = act->dta_next) {
17386 ASSERT(act->dta_intuple ||
17387 DTRACEACT_ISAGG(act->dta_kind));
17390 * If this action has a record size of zero, it
17391 * denotes an argument to the aggregating action.
17392 * Because the presence of this record doesn't (or
17393 * shouldn't) affect the way the data is interpreted,
17394 * we don't copy it out to save user-level the
17395 * confusion of dealing with a zero-length record.
17397 if (act->dta_rec.dtrd_size == 0) {
17398 ASSERT(agg->dtag_hasarg);
17402 aggdesc.dtagd_nrecs++;
17404 if (act == &agg->dtag_action)
17409 * Now that we have the size, we need to allocate a temporary
17410 * buffer in which to store the complete description. We need
17411 * the temporary buffer to be able to drop dtrace_lock()
17412 * across the copyout(), below.
17414 size = sizeof (dtrace_aggdesc_t) +
17415 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17417 buf = kmem_alloc(size, KM_SLEEP);
17418 dest = (uintptr_t)buf;
17420 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17421 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17423 for (act = agg->dtag_first; ; act = act->dta_next) {
17424 dtrace_recdesc_t rec = act->dta_rec;
17427 * See the comment in the above loop for why we pass
17428 * over zero-length records.
17430 if (rec.dtrd_size == 0) {
17431 ASSERT(agg->dtag_hasarg);
17438 rec.dtrd_offset -= offs;
17439 bcopy(&rec, (void *)dest, sizeof (rec));
17440 dest += sizeof (dtrace_recdesc_t);
17442 if (act == &agg->dtag_action)
17446 mutex_exit(&dtrace_lock);
17448 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17449 kmem_free(buf, size);
17453 kmem_free(buf, size);
17457 case DTRACEIOC_ENABLE: {
17459 dtrace_enabling_t *enab = NULL;
17460 dtrace_vstate_t *vstate;
17466 * If a NULL argument has been passed, we take this as our
17467 * cue to reevaluate our enablings.
17470 dtrace_enabling_matchall();
17475 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17478 mutex_enter(&cpu_lock);
17479 mutex_enter(&dtrace_lock);
17480 vstate = &state->dts_vstate;
17482 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17483 mutex_exit(&dtrace_lock);
17484 mutex_exit(&cpu_lock);
17485 dtrace_dof_destroy(dof);
17489 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17490 mutex_exit(&dtrace_lock);
17491 mutex_exit(&cpu_lock);
17492 dtrace_dof_destroy(dof);
17496 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17497 dtrace_enabling_destroy(enab);
17498 mutex_exit(&dtrace_lock);
17499 mutex_exit(&cpu_lock);
17500 dtrace_dof_destroy(dof);
17504 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17505 err = dtrace_enabling_retain(enab);
17507 dtrace_enabling_destroy(enab);
17510 mutex_exit(&cpu_lock);
17511 mutex_exit(&dtrace_lock);
17512 dtrace_dof_destroy(dof);
17517 case DTRACEIOC_REPLICATE: {
17518 dtrace_repldesc_t desc;
17519 dtrace_probedesc_t *match = &desc.dtrpd_match;
17520 dtrace_probedesc_t *create = &desc.dtrpd_create;
17523 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17526 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17527 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17528 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17529 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17531 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17532 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17533 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17534 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17536 mutex_enter(&dtrace_lock);
17537 err = dtrace_enabling_replicate(state, match, create);
17538 mutex_exit(&dtrace_lock);
17543 case DTRACEIOC_PROBEMATCH:
17544 case DTRACEIOC_PROBES: {
17545 dtrace_probe_t *probe = NULL;
17546 dtrace_probedesc_t desc;
17547 dtrace_probekey_t pkey;
17554 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17557 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17558 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17559 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17560 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17563 * Before we attempt to match this probe, we want to give
17564 * all providers the opportunity to provide it.
17566 if (desc.dtpd_id == DTRACE_IDNONE) {
17567 mutex_enter(&dtrace_provider_lock);
17568 dtrace_probe_provide(&desc, NULL);
17569 mutex_exit(&dtrace_provider_lock);
17573 if (cmd == DTRACEIOC_PROBEMATCH) {
17574 dtrace_probekey(&desc, &pkey);
17575 pkey.dtpk_id = DTRACE_IDNONE;
17578 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17580 mutex_enter(&dtrace_lock);
17582 if (cmd == DTRACEIOC_PROBEMATCH) {
17583 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17584 if ((probe = dtrace_probes[i - 1]) != NULL &&
17585 (m = dtrace_match_probe(probe, &pkey,
17586 priv, uid, zoneid)) != 0)
17591 mutex_exit(&dtrace_lock);
17596 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17597 if ((probe = dtrace_probes[i - 1]) != NULL &&
17598 dtrace_match_priv(probe, priv, uid, zoneid))
17603 if (probe == NULL) {
17604 mutex_exit(&dtrace_lock);
17608 dtrace_probe_description(probe, &desc);
17609 mutex_exit(&dtrace_lock);
17611 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17617 case DTRACEIOC_PROBEARG: {
17618 dtrace_argdesc_t desc;
17619 dtrace_probe_t *probe;
17620 dtrace_provider_t *prov;
17622 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17625 if (desc.dtargd_id == DTRACE_IDNONE)
17628 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17631 mutex_enter(&dtrace_provider_lock);
17632 mutex_enter(&mod_lock);
17633 mutex_enter(&dtrace_lock);
17635 if (desc.dtargd_id > dtrace_nprobes) {
17636 mutex_exit(&dtrace_lock);
17637 mutex_exit(&mod_lock);
17638 mutex_exit(&dtrace_provider_lock);
17642 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17643 mutex_exit(&dtrace_lock);
17644 mutex_exit(&mod_lock);
17645 mutex_exit(&dtrace_provider_lock);
17649 mutex_exit(&dtrace_lock);
17651 prov = probe->dtpr_provider;
17653 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17655 * There isn't any typed information for this probe.
17656 * Set the argument number to DTRACE_ARGNONE.
17658 desc.dtargd_ndx = DTRACE_ARGNONE;
17660 desc.dtargd_native[0] = '\0';
17661 desc.dtargd_xlate[0] = '\0';
17662 desc.dtargd_mapping = desc.dtargd_ndx;
17664 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17665 probe->dtpr_id, probe->dtpr_arg, &desc);
17668 mutex_exit(&mod_lock);
17669 mutex_exit(&dtrace_provider_lock);
17671 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17677 case DTRACEIOC_GO: {
17678 processorid_t cpuid;
17679 rval = dtrace_state_go(state, &cpuid);
17684 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17690 case DTRACEIOC_STOP: {
17691 processorid_t cpuid;
17693 mutex_enter(&dtrace_lock);
17694 rval = dtrace_state_stop(state, &cpuid);
17695 mutex_exit(&dtrace_lock);
17700 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17706 case DTRACEIOC_DOFGET: {
17707 dof_hdr_t hdr, *dof;
17710 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17713 mutex_enter(&dtrace_lock);
17714 dof = dtrace_dof_create(state);
17715 mutex_exit(&dtrace_lock);
17717 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17718 rval = copyout(dof, (void *)arg, len);
17719 dtrace_dof_destroy(dof);
17721 return (rval == 0 ? 0 : EFAULT);
17724 case DTRACEIOC_AGGSNAP:
17725 case DTRACEIOC_BUFSNAP: {
17726 dtrace_bufdesc_t desc;
17728 dtrace_buffer_t *buf;
17730 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17733 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17736 mutex_enter(&dtrace_lock);
17738 if (cmd == DTRACEIOC_BUFSNAP) {
17739 buf = &state->dts_buffer[desc.dtbd_cpu];
17741 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17744 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17745 size_t sz = buf->dtb_offset;
17747 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17748 mutex_exit(&dtrace_lock);
17753 * If this buffer has already been consumed, we're
17754 * going to indicate that there's nothing left here
17757 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17758 mutex_exit(&dtrace_lock);
17760 desc.dtbd_size = 0;
17761 desc.dtbd_drops = 0;
17762 desc.dtbd_errors = 0;
17763 desc.dtbd_oldest = 0;
17764 sz = sizeof (desc);
17766 if (copyout(&desc, (void *)arg, sz) != 0)
17773 * If this is a ring buffer that has wrapped, we want
17774 * to copy the whole thing out.
17776 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17777 dtrace_buffer_polish(buf);
17778 sz = buf->dtb_size;
17781 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17782 mutex_exit(&dtrace_lock);
17786 desc.dtbd_size = sz;
17787 desc.dtbd_drops = buf->dtb_drops;
17788 desc.dtbd_errors = buf->dtb_errors;
17789 desc.dtbd_oldest = buf->dtb_xamot_offset;
17790 desc.dtbd_timestamp = dtrace_gethrtime();
17792 mutex_exit(&dtrace_lock);
17794 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17797 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17802 if (buf->dtb_tomax == NULL) {
17803 ASSERT(buf->dtb_xamot == NULL);
17804 mutex_exit(&dtrace_lock);
17808 cached = buf->dtb_tomax;
17809 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17811 dtrace_xcall(desc.dtbd_cpu,
17812 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17814 state->dts_errors += buf->dtb_xamot_errors;
17817 * If the buffers did not actually switch, then the cross call
17818 * did not take place -- presumably because the given CPU is
17819 * not in the ready set. If this is the case, we'll return
17822 if (buf->dtb_tomax == cached) {
17823 ASSERT(buf->dtb_xamot != cached);
17824 mutex_exit(&dtrace_lock);
17828 ASSERT(cached == buf->dtb_xamot);
17831 * We have our snapshot; now copy it out.
17833 if (copyout(buf->dtb_xamot, desc.dtbd_data,
17834 buf->dtb_xamot_offset) != 0) {
17835 mutex_exit(&dtrace_lock);
17839 desc.dtbd_size = buf->dtb_xamot_offset;
17840 desc.dtbd_drops = buf->dtb_xamot_drops;
17841 desc.dtbd_errors = buf->dtb_xamot_errors;
17842 desc.dtbd_oldest = 0;
17843 desc.dtbd_timestamp = buf->dtb_switched;
17845 mutex_exit(&dtrace_lock);
17848 * Finally, copy out the buffer description.
17850 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17856 case DTRACEIOC_CONF: {
17857 dtrace_conf_t conf;
17859 bzero(&conf, sizeof (conf));
17860 conf.dtc_difversion = DIF_VERSION;
17861 conf.dtc_difintregs = DIF_DIR_NREGS;
17862 conf.dtc_diftupregs = DIF_DTR_NREGS;
17863 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17865 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17871 case DTRACEIOC_STATUS: {
17872 dtrace_status_t stat;
17873 dtrace_dstate_t *dstate;
17878 * See the comment in dtrace_state_deadman() for the reason
17879 * for setting dts_laststatus to INT64_MAX before setting
17880 * it to the correct value.
17882 state->dts_laststatus = INT64_MAX;
17883 dtrace_membar_producer();
17884 state->dts_laststatus = dtrace_gethrtime();
17886 bzero(&stat, sizeof (stat));
17888 mutex_enter(&dtrace_lock);
17890 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17891 mutex_exit(&dtrace_lock);
17895 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17896 stat.dtst_exiting = 1;
17898 nerrs = state->dts_errors;
17899 dstate = &state->dts_vstate.dtvs_dynvars;
17901 for (i = 0; i < NCPU; i++) {
17902 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17904 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17905 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17906 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17908 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17909 stat.dtst_filled++;
17911 nerrs += state->dts_buffer[i].dtb_errors;
17913 for (j = 0; j < state->dts_nspeculations; j++) {
17914 dtrace_speculation_t *spec;
17915 dtrace_buffer_t *buf;
17917 spec = &state->dts_speculations[j];
17918 buf = &spec->dtsp_buffer[i];
17919 stat.dtst_specdrops += buf->dtb_xamot_drops;
17923 stat.dtst_specdrops_busy = state->dts_speculations_busy;
17924 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17925 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17926 stat.dtst_dblerrors = state->dts_dblerrors;
17928 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17929 stat.dtst_errors = nerrs;
17931 mutex_exit(&dtrace_lock);
17933 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17939 case DTRACEIOC_FORMAT: {
17940 dtrace_fmtdesc_t fmt;
17944 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17947 mutex_enter(&dtrace_lock);
17949 if (fmt.dtfd_format == 0 ||
17950 fmt.dtfd_format > state->dts_nformats) {
17951 mutex_exit(&dtrace_lock);
17956 * Format strings are allocated contiguously and they are
17957 * never freed; if a format index is less than the number
17958 * of formats, we can assert that the format map is non-NULL
17959 * and that the format for the specified index is non-NULL.
17961 ASSERT(state->dts_formats != NULL);
17962 str = state->dts_formats[fmt.dtfd_format - 1];
17963 ASSERT(str != NULL);
17965 len = strlen(str) + 1;
17967 if (len > fmt.dtfd_length) {
17968 fmt.dtfd_length = len;
17970 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17971 mutex_exit(&dtrace_lock);
17975 if (copyout(str, fmt.dtfd_string, len) != 0) {
17976 mutex_exit(&dtrace_lock);
17981 mutex_exit(&dtrace_lock);
17994 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17996 dtrace_state_t *state;
18003 return (DDI_SUCCESS);
18006 return (DDI_FAILURE);
18009 mutex_enter(&cpu_lock);
18010 mutex_enter(&dtrace_provider_lock);
18011 mutex_enter(&dtrace_lock);
18013 ASSERT(dtrace_opens == 0);
18015 if (dtrace_helpers > 0) {
18016 mutex_exit(&dtrace_provider_lock);
18017 mutex_exit(&dtrace_lock);
18018 mutex_exit(&cpu_lock);
18019 return (DDI_FAILURE);
18022 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18023 mutex_exit(&dtrace_provider_lock);
18024 mutex_exit(&dtrace_lock);
18025 mutex_exit(&cpu_lock);
18026 return (DDI_FAILURE);
18029 dtrace_provider = NULL;
18031 if ((state = dtrace_anon_grab()) != NULL) {
18033 * If there were ECBs on this state, the provider should
18034 * have not been allowed to detach; assert that there is
18037 ASSERT(state->dts_necbs == 0);
18038 dtrace_state_destroy(state);
18041 * If we're being detached with anonymous state, we need to
18042 * indicate to the kernel debugger that DTrace is now inactive.
18044 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18047 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18048 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18049 dtrace_cpu_init = NULL;
18050 dtrace_helpers_cleanup = NULL;
18051 dtrace_helpers_fork = NULL;
18052 dtrace_cpustart_init = NULL;
18053 dtrace_cpustart_fini = NULL;
18054 dtrace_debugger_init = NULL;
18055 dtrace_debugger_fini = NULL;
18056 dtrace_modload = NULL;
18057 dtrace_modunload = NULL;
18059 ASSERT(dtrace_getf == 0);
18060 ASSERT(dtrace_closef == NULL);
18062 mutex_exit(&cpu_lock);
18064 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18065 dtrace_probes = NULL;
18066 dtrace_nprobes = 0;
18068 dtrace_hash_destroy(dtrace_bymod);
18069 dtrace_hash_destroy(dtrace_byfunc);
18070 dtrace_hash_destroy(dtrace_byname);
18071 dtrace_bymod = NULL;
18072 dtrace_byfunc = NULL;
18073 dtrace_byname = NULL;
18075 kmem_cache_destroy(dtrace_state_cache);
18076 vmem_destroy(dtrace_minor);
18077 vmem_destroy(dtrace_arena);
18079 if (dtrace_toxrange != NULL) {
18080 kmem_free(dtrace_toxrange,
18081 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18082 dtrace_toxrange = NULL;
18083 dtrace_toxranges = 0;
18084 dtrace_toxranges_max = 0;
18087 ddi_remove_minor_node(dtrace_devi, NULL);
18088 dtrace_devi = NULL;
18090 ddi_soft_state_fini(&dtrace_softstate);
18092 ASSERT(dtrace_vtime_references == 0);
18093 ASSERT(dtrace_opens == 0);
18094 ASSERT(dtrace_retained == NULL);
18096 mutex_exit(&dtrace_lock);
18097 mutex_exit(&dtrace_provider_lock);
18100 * We don't destroy the task queue until after we have dropped our
18101 * locks (taskq_destroy() may block on running tasks). To prevent
18102 * attempting to do work after we have effectively detached but before
18103 * the task queue has been destroyed, all tasks dispatched via the
18104 * task queue must check that DTrace is still attached before
18105 * performing any operation.
18107 taskq_destroy(dtrace_taskq);
18108 dtrace_taskq = NULL;
18110 return (DDI_SUCCESS);
18117 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18122 case DDI_INFO_DEVT2DEVINFO:
18123 *result = (void *)dtrace_devi;
18124 error = DDI_SUCCESS;
18126 case DDI_INFO_DEVT2INSTANCE:
18127 *result = (void *)0;
18128 error = DDI_SUCCESS;
18131 error = DDI_FAILURE;
18138 static struct cb_ops dtrace_cb_ops = {
18139 dtrace_open, /* open */
18140 dtrace_close, /* close */
18141 nulldev, /* strategy */
18142 nulldev, /* print */
18146 dtrace_ioctl, /* ioctl */
18147 nodev, /* devmap */
18149 nodev, /* segmap */
18150 nochpoll, /* poll */
18151 ddi_prop_op, /* cb_prop_op */
18153 D_NEW | D_MP /* Driver compatibility flag */
18156 static struct dev_ops dtrace_ops = {
18157 DEVO_REV, /* devo_rev */
18159 dtrace_info, /* get_dev_info */
18160 nulldev, /* identify */
18161 nulldev, /* probe */
18162 dtrace_attach, /* attach */
18163 dtrace_detach, /* detach */
18165 &dtrace_cb_ops, /* driver operations */
18166 NULL, /* bus operations */
18167 nodev /* dev power */
18170 static struct modldrv modldrv = {
18171 &mod_driverops, /* module type (this is a pseudo driver) */
18172 "Dynamic Tracing", /* name of module */
18173 &dtrace_ops, /* driver ops */
18176 static struct modlinkage modlinkage = {
18185 return (mod_install(&modlinkage));
18189 _info(struct modinfo *modinfop)
18191 return (mod_info(&modlinkage, modinfop));
18197 return (mod_remove(&modlinkage));
18201 static d_ioctl_t dtrace_ioctl;
18202 static d_ioctl_t dtrace_ioctl_helper;
18203 static void dtrace_load(void *);
18204 static int dtrace_unload(void);
18205 static struct cdev *dtrace_dev;
18206 static struct cdev *helper_dev;
18208 void dtrace_invop_init(void);
18209 void dtrace_invop_uninit(void);
18211 static struct cdevsw dtrace_cdevsw = {
18212 .d_version = D_VERSION,
18213 .d_ioctl = dtrace_ioctl,
18214 .d_open = dtrace_open,
18215 .d_name = "dtrace",
18218 static struct cdevsw helper_cdevsw = {
18219 .d_version = D_VERSION,
18220 .d_ioctl = dtrace_ioctl_helper,
18221 .d_name = "helper",
18224 #include <dtrace_anon.c>
18225 #include <dtrace_ioctl.c>
18226 #include <dtrace_load.c>
18227 #include <dtrace_modevent.c>
18228 #include <dtrace_sysctl.c>
18229 #include <dtrace_unload.c>
18230 #include <dtrace_vtime.c>
18231 #include <dtrace_hacks.c>
18232 #include <dtrace_isa.c>
18234 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18235 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18236 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18238 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18239 MODULE_VERSION(dtrace, 1);
18240 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);