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 2008 Sun Microsystems, Inc. All rights reserved.
26 * Copyright (c) 2012 by Delphix. All rights reserved
27 * Use is subject to license terms.
30 #pragma ident "%Z%%M% %I% %E% SMI"
33 * DTrace - Dynamic Tracing for Solaris
35 * This is the implementation of the Solaris Dynamic Tracing framework
36 * (DTrace). The user-visible interface to DTrace is described at length in
37 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
38 * library, the in-kernel DTrace framework, and the DTrace providers are
39 * described in the block comments in the <sys/dtrace.h> header file. The
40 * internal architecture of DTrace is described in the block comments in the
41 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
42 * implementation very much assume mastery of all of these sources; if one has
43 * an unanswered question about the implementation, one should consult them
46 * The functions here are ordered roughly as follows:
48 * - Probe context functions
49 * - Probe hashing functions
50 * - Non-probe context utility functions
51 * - Matching functions
52 * - Provider-to-Framework API functions
53 * - Probe management functions
54 * - DIF object functions
56 * - Predicate functions
59 * - Enabling functions
61 * - Anonymous enabling functions
62 * - Consumer state functions
65 * - Driver cookbook functions
67 * Each group of functions begins with a block comment labelled the "DTrace
68 * [Group] Functions", allowing one to find each block by searching forward
69 * on capital-f functions.
71 #include <sys/errno.h>
76 #include <sys/modctl.h>
78 #include <sys/systm.h>
81 #include <sys/sunddi.h>
83 #include <sys/cpuvar.h>
86 #include <sys/strsubr.h>
88 #include <sys/sysmacros.h>
89 #include <sys/dtrace_impl.h>
90 #include <sys/atomic.h>
91 #include <sys/cmn_err.h>
93 #include <sys/mutex_impl.h>
94 #include <sys/rwlock_impl.h>
96 #include <sys/ctf_api.h>
98 #include <sys/panic.h>
99 #include <sys/priv_impl.h>
101 #include <sys/policy.h>
103 #include <sys/cred_impl.h>
104 #include <sys/procfs_isa.h>
106 #include <sys/taskq.h>
108 #include <sys/mkdev.h>
111 #include <sys/zone.h>
112 #include <sys/socket.h>
113 #include <netinet/in.h>
115 /* FreeBSD includes: */
117 #include <sys/callout.h>
118 #include <sys/ctype.h>
119 #include <sys/eventhandler.h>
120 #include <sys/limits.h>
122 #include <sys/kernel.h>
123 #include <sys/malloc.h>
124 #include <sys/sysctl.h>
125 #include <sys/lock.h>
126 #include <sys/mutex.h>
127 #include <sys/rwlock.h>
129 #include <sys/dtrace_bsd.h>
130 #include <netinet/in.h>
131 #include "dtrace_cddl.h"
132 #include "dtrace_debug.c"
136 * DTrace Tunable Variables
138 * The following variables may be tuned by adding a line to /etc/system that
139 * includes both the name of the DTrace module ("dtrace") and the name of the
140 * variable. For example:
142 * set dtrace:dtrace_destructive_disallow = 1
144 * In general, the only variables that one should be tuning this way are those
145 * that affect system-wide DTrace behavior, and for which the default behavior
146 * is undesirable. Most of these variables are tunable on a per-consumer
147 * basis using DTrace options, and need not be tuned on a system-wide basis.
148 * When tuning these variables, avoid pathological values; while some attempt
149 * is made to verify the integrity of these variables, they are not considered
150 * part of the supported interface to DTrace, and they are therefore not
151 * checked comprehensively. Further, these variables should not be tuned
152 * dynamically via "mdb -kw" or other means; they should only be tuned via
155 int dtrace_destructive_disallow = 0;
156 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
157 size_t dtrace_difo_maxsize = (256 * 1024);
158 dtrace_optval_t dtrace_dof_maxsize = (256 * 1024);
159 size_t dtrace_global_maxsize = (16 * 1024);
160 size_t dtrace_actions_max = (16 * 1024);
161 size_t dtrace_retain_max = 1024;
162 dtrace_optval_t dtrace_helper_actions_max = 128;
163 dtrace_optval_t dtrace_helper_providers_max = 32;
164 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
165 size_t dtrace_strsize_default = 256;
166 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
167 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
168 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
169 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
170 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
171 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
172 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
173 dtrace_optval_t dtrace_nspec_default = 1;
174 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
175 dtrace_optval_t dtrace_stackframes_default = 20;
176 dtrace_optval_t dtrace_ustackframes_default = 20;
177 dtrace_optval_t dtrace_jstackframes_default = 50;
178 dtrace_optval_t dtrace_jstackstrsize_default = 512;
179 int dtrace_msgdsize_max = 128;
180 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
181 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
182 int dtrace_devdepth_max = 32;
183 int dtrace_err_verbose;
184 hrtime_t dtrace_deadman_interval = NANOSEC;
185 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
186 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
187 hrtime_t dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
190 * DTrace External Variables
192 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
193 * available to DTrace consumers via the backtick (`) syntax. One of these,
194 * dtrace_zero, is made deliberately so: it is provided as a source of
195 * well-known, zero-filled memory. While this variable is not documented,
196 * it is used by some translators as an implementation detail.
198 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
201 * DTrace Internal Variables
204 static dev_info_t *dtrace_devi; /* device info */
207 static vmem_t *dtrace_arena; /* probe ID arena */
208 static vmem_t *dtrace_minor; /* minor number arena */
210 static taskq_t *dtrace_taskq; /* task queue */
211 static struct unrhdr *dtrace_arena; /* Probe ID number. */
213 static dtrace_probe_t **dtrace_probes; /* array of all probes */
214 static int dtrace_nprobes; /* number of probes */
215 static dtrace_provider_t *dtrace_provider; /* provider list */
216 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
217 static int dtrace_opens; /* number of opens */
218 static int dtrace_helpers; /* number of helpers */
220 static void *dtrace_softstate; /* softstate pointer */
222 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
223 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
224 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
225 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
226 static int dtrace_toxranges; /* number of toxic ranges */
227 static int dtrace_toxranges_max; /* size of toxic range array */
228 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
229 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
230 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
231 static kthread_t *dtrace_panicked; /* panicking thread */
232 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
233 static dtrace_genid_t dtrace_probegen; /* current probe generation */
234 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
235 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
236 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
238 static struct mtx dtrace_unr_mtx;
239 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
240 int dtrace_in_probe; /* non-zero if executing a probe */
241 #if defined(__i386__) || defined(__amd64__)
242 uintptr_t dtrace_in_probe_addr; /* Address of invop when already in probe */
244 static eventhandler_tag dtrace_kld_load_tag;
245 static eventhandler_tag dtrace_kld_unload_tag;
250 * DTrace is protected by three (relatively coarse-grained) locks:
252 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
253 * including enabling state, probes, ECBs, consumer state, helper state,
254 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
255 * probe context is lock-free -- synchronization is handled via the
256 * dtrace_sync() cross call mechanism.
258 * (2) dtrace_provider_lock is required when manipulating provider state, or
259 * when provider state must be held constant.
261 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
262 * when meta provider state must be held constant.
264 * The lock ordering between these three locks is dtrace_meta_lock before
265 * dtrace_provider_lock before dtrace_lock. (In particular, there are
266 * several places where dtrace_provider_lock is held by the framework as it
267 * calls into the providers -- which then call back into the framework,
268 * grabbing dtrace_lock.)
270 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
271 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
272 * role as a coarse-grained lock; it is acquired before both of these locks.
273 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
274 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
275 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
276 * acquired _between_ dtrace_provider_lock and dtrace_lock.
278 static kmutex_t dtrace_lock; /* probe state lock */
279 static kmutex_t dtrace_provider_lock; /* provider state lock */
280 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
283 /* XXX FreeBSD hacks. */
284 static kmutex_t mod_lock;
286 #define cr_suid cr_svuid
287 #define cr_sgid cr_svgid
288 #define ipaddr_t in_addr_t
289 #define mod_modname pathname
290 #define vuprintf vprintf
291 #define ttoproc(_a) ((_a)->td_proc)
292 #define crgetzoneid(_a) 0
295 #define CPU_ON_INTR(_a) 0
297 #define PRIV_EFFECTIVE (1 << 0)
298 #define PRIV_DTRACE_KERNEL (1 << 1)
299 #define PRIV_DTRACE_PROC (1 << 2)
300 #define PRIV_DTRACE_USER (1 << 3)
301 #define PRIV_PROC_OWNER (1 << 4)
302 #define PRIV_PROC_ZONE (1 << 5)
305 SYSCTL_NODE(_debug, OID_AUTO, dtrace, CTLFLAG_RD, 0, "DTrace Information");
309 #define curcpu CPU->cpu_id
314 * DTrace Provider Variables
316 * These are the variables relating to DTrace as a provider (that is, the
317 * provider of the BEGIN, END, and ERROR probes).
319 static dtrace_pattr_t dtrace_provider_attr = {
320 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
321 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
322 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
323 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
324 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
331 static dtrace_pops_t dtrace_provider_ops = {
332 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
333 (void (*)(void *, modctl_t *))dtrace_nullop,
334 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
335 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
336 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
337 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
341 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
344 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
345 static dtrace_id_t dtrace_probeid_end; /* special END probe */
346 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
349 * DTrace Helper Tracing Variables
351 uint32_t dtrace_helptrace_next = 0;
352 uint32_t dtrace_helptrace_nlocals;
353 char *dtrace_helptrace_buffer;
354 int dtrace_helptrace_bufsize = 512 * 1024;
357 int dtrace_helptrace_enabled = 1;
359 int dtrace_helptrace_enabled = 0;
363 * DTrace Error Hashing
365 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
366 * table. This is very useful for checking coverage of tests that are
367 * expected to induce DIF or DOF processing errors, and may be useful for
368 * debugging problems in the DIF code generator or in DOF generation . The
369 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
372 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
373 static const char *dtrace_errlast;
374 static kthread_t *dtrace_errthread;
375 static kmutex_t dtrace_errlock;
379 * DTrace Macros and Constants
381 * These are various macros that are useful in various spots in the
382 * implementation, along with a few random constants that have no meaning
383 * outside of the implementation. There is no real structure to this cpp
384 * mishmash -- but is there ever?
386 #define DTRACE_HASHSTR(hash, probe) \
387 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
389 #define DTRACE_HASHNEXT(hash, probe) \
390 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
392 #define DTRACE_HASHPREV(hash, probe) \
393 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
395 #define DTRACE_HASHEQ(hash, lhs, rhs) \
396 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
397 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
399 #define DTRACE_AGGHASHSIZE_SLEW 17
401 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
404 * The key for a thread-local variable consists of the lower 61 bits of the
405 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
406 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
407 * equal to a variable identifier. This is necessary (but not sufficient) to
408 * assure that global associative arrays never collide with thread-local
409 * variables. To guarantee that they cannot collide, we must also define the
410 * order for keying dynamic variables. That order is:
412 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
414 * Because the variable-key and the tls-key are in orthogonal spaces, there is
415 * no way for a global variable key signature to match a thread-local key
419 #define DTRACE_TLS_THRKEY(where) { \
421 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
422 for (; actv; actv >>= 1) \
424 ASSERT(intr < (1 << 3)); \
425 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
426 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
429 #define DTRACE_TLS_THRKEY(where) { \
430 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
432 uint_t actv = _c->cpu_intr_actv; \
433 for (; actv; actv >>= 1) \
435 ASSERT(intr < (1 << 3)); \
436 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
437 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
441 #define DT_BSWAP_8(x) ((x) & 0xff)
442 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
443 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
444 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
446 #define DT_MASK_LO 0x00000000FFFFFFFFULL
448 #define DTRACE_STORE(type, tomax, offset, what) \
449 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
452 #define DTRACE_ALIGNCHECK(addr, size, flags) \
453 if (addr & (size - 1)) { \
454 *flags |= CPU_DTRACE_BADALIGN; \
455 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
459 #define DTRACE_ALIGNCHECK(addr, size, flags)
463 * Test whether a range of memory starting at testaddr of size testsz falls
464 * within the range of memory described by addr, sz. We take care to avoid
465 * problems with overflow and underflow of the unsigned quantities, and
466 * disallow all negative sizes. Ranges of size 0 are allowed.
468 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
469 ((testaddr) - (baseaddr) < (basesz) && \
470 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
471 (testaddr) + (testsz) >= (testaddr))
474 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
475 * alloc_sz on the righthand side of the comparison in order to avoid overflow
476 * or underflow in the comparison with it. This is simpler than the INRANGE
477 * check above, because we know that the dtms_scratch_ptr is valid in the
478 * range. Allocations of size zero are allowed.
480 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
481 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
482 (mstate)->dtms_scratch_ptr >= (alloc_sz))
484 #define DTRACE_LOADFUNC(bits) \
487 dtrace_load##bits(uintptr_t addr) \
489 size_t size = bits / NBBY; \
491 uint##bits##_t rval; \
493 volatile uint16_t *flags = (volatile uint16_t *) \
494 &cpu_core[curcpu].cpuc_dtrace_flags; \
496 DTRACE_ALIGNCHECK(addr, size, flags); \
498 for (i = 0; i < dtrace_toxranges; i++) { \
499 if (addr >= dtrace_toxrange[i].dtt_limit) \
502 if (addr + size <= dtrace_toxrange[i].dtt_base) \
506 * This address falls within a toxic region; return 0. \
508 *flags |= CPU_DTRACE_BADADDR; \
509 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
513 *flags |= CPU_DTRACE_NOFAULT; \
515 rval = *((volatile uint##bits##_t *)addr); \
516 *flags &= ~CPU_DTRACE_NOFAULT; \
518 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
522 #define dtrace_loadptr dtrace_load64
524 #define dtrace_loadptr dtrace_load32
527 #define DTRACE_DYNHASH_FREE 0
528 #define DTRACE_DYNHASH_SINK 1
529 #define DTRACE_DYNHASH_VALID 2
531 #define DTRACE_MATCH_NEXT 0
532 #define DTRACE_MATCH_DONE 1
533 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
534 #define DTRACE_STATE_ALIGN 64
536 #define DTRACE_FLAGS2FLT(flags) \
537 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
538 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
539 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
540 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
541 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
542 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
543 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
544 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
545 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
548 #define DTRACEACT_ISSTRING(act) \
549 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
550 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
552 /* Function prototype definitions: */
553 static size_t dtrace_strlen(const char *, size_t);
554 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
555 static void dtrace_enabling_provide(dtrace_provider_t *);
556 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
557 static void dtrace_enabling_matchall(void);
558 static void dtrace_enabling_reap(void);
559 static dtrace_state_t *dtrace_anon_grab(void);
560 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
561 dtrace_state_t *, uint64_t, uint64_t);
562 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
563 static void dtrace_buffer_drop(dtrace_buffer_t *);
564 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
565 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
566 dtrace_state_t *, dtrace_mstate_t *);
567 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
569 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
570 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
571 uint16_t dtrace_load16(uintptr_t);
572 uint32_t dtrace_load32(uintptr_t);
573 uint64_t dtrace_load64(uintptr_t);
574 uint8_t dtrace_load8(uintptr_t);
575 void dtrace_dynvar_clean(dtrace_dstate_t *);
576 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
577 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
578 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
581 * DTrace Probe Context Functions
583 * These functions are called from probe context. Because probe context is
584 * any context in which C may be called, arbitrarily locks may be held,
585 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
586 * As a result, functions called from probe context may only call other DTrace
587 * support functions -- they may not interact at all with the system at large.
588 * (Note that the ASSERT macro is made probe-context safe by redefining it in
589 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
590 * loads are to be performed from probe context, they _must_ be in terms of
591 * the safe dtrace_load*() variants.
593 * Some functions in this block are not actually called from probe context;
594 * for these functions, there will be a comment above the function reading
595 * "Note: not called from probe context."
598 dtrace_panic(const char *format, ...)
602 va_start(alist, format);
603 dtrace_vpanic(format, alist);
608 dtrace_assfail(const char *a, const char *f, int l)
610 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
613 * We just need something here that even the most clever compiler
614 * cannot optimize away.
616 return (a[(uintptr_t)f]);
620 * Atomically increment a specified error counter from probe context.
623 dtrace_error(uint32_t *counter)
626 * Most counters stored to in probe context are per-CPU counters.
627 * However, there are some error conditions that are sufficiently
628 * arcane that they don't merit per-CPU storage. If these counters
629 * are incremented concurrently on different CPUs, scalability will be
630 * adversely affected -- but we don't expect them to be white-hot in a
631 * correctly constructed enabling...
638 if ((nval = oval + 1) == 0) {
640 * If the counter would wrap, set it to 1 -- assuring
641 * that the counter is never zero when we have seen
642 * errors. (The counter must be 32-bits because we
643 * aren't guaranteed a 64-bit compare&swap operation.)
644 * To save this code both the infamy of being fingered
645 * by a priggish news story and the indignity of being
646 * the target of a neo-puritan witch trial, we're
647 * carefully avoiding any colorful description of the
648 * likelihood of this condition -- but suffice it to
649 * say that it is only slightly more likely than the
650 * overflow of predicate cache IDs, as discussed in
651 * dtrace_predicate_create().
655 } while (dtrace_cas32(counter, oval, nval) != oval);
659 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
660 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
668 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
670 if (dest < mstate->dtms_scratch_base)
673 if (dest + size < dest)
676 if (dest + size > mstate->dtms_scratch_ptr)
683 dtrace_canstore_statvar(uint64_t addr, size_t sz,
684 dtrace_statvar_t **svars, int nsvars)
688 for (i = 0; i < nsvars; i++) {
689 dtrace_statvar_t *svar = svars[i];
691 if (svar == NULL || svar->dtsv_size == 0)
694 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
702 * Check to see if the address is within a memory region to which a store may
703 * be issued. This includes the DTrace scratch areas, and any DTrace variable
704 * region. The caller of dtrace_canstore() is responsible for performing any
705 * alignment checks that are needed before stores are actually executed.
708 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
709 dtrace_vstate_t *vstate)
712 * First, check to see if the address is in scratch space...
714 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
715 mstate->dtms_scratch_size))
719 * Now check to see if it's a dynamic variable. This check will pick
720 * up both thread-local variables and any global dynamically-allocated
723 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
724 vstate->dtvs_dynvars.dtds_size)) {
725 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
726 uintptr_t base = (uintptr_t)dstate->dtds_base +
727 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
731 * Before we assume that we can store here, we need to make
732 * sure that it isn't in our metadata -- storing to our
733 * dynamic variable metadata would corrupt our state. For
734 * the range to not include any dynamic variable metadata,
737 * (1) Start above the hash table that is at the base of
738 * the dynamic variable space
740 * (2) Have a starting chunk offset that is beyond the
741 * dtrace_dynvar_t that is at the base of every chunk
743 * (3) Not span a chunk boundary
749 chunkoffs = (addr - base) % dstate->dtds_chunksize;
751 if (chunkoffs < sizeof (dtrace_dynvar_t))
754 if (chunkoffs + sz > dstate->dtds_chunksize)
761 * Finally, check the static local and global variables. These checks
762 * take the longest, so we perform them last.
764 if (dtrace_canstore_statvar(addr, sz,
765 vstate->dtvs_locals, vstate->dtvs_nlocals))
768 if (dtrace_canstore_statvar(addr, sz,
769 vstate->dtvs_globals, vstate->dtvs_nglobals))
777 * Convenience routine to check to see if the address is within a memory
778 * region in which a load may be issued given the user's privilege level;
779 * if not, it sets the appropriate error flags and loads 'addr' into the
780 * illegal value slot.
782 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
783 * appropriate memory access protection.
786 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
787 dtrace_vstate_t *vstate)
789 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
792 * If we hold the privilege to read from kernel memory, then
793 * everything is readable.
795 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
799 * You can obviously read that which you can store.
801 if (dtrace_canstore(addr, sz, mstate, vstate))
805 * We're allowed to read from our own string table.
807 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
808 mstate->dtms_difo->dtdo_strlen))
811 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
817 * Convenience routine to check to see if a given string is within a memory
818 * region in which a load may be issued given the user's privilege level;
819 * this exists so that we don't need to issue unnecessary dtrace_strlen()
820 * calls in the event that the user has all privileges.
823 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
824 dtrace_vstate_t *vstate)
829 * If we hold the privilege to read from kernel memory, then
830 * everything is readable.
832 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
835 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
836 if (dtrace_canload(addr, strsz, mstate, vstate))
843 * Convenience routine to check to see if a given variable is within a memory
844 * region in which a load may be issued given the user's privilege level.
847 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
848 dtrace_vstate_t *vstate)
851 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
854 * If we hold the privilege to read from kernel memory, then
855 * everything is readable.
857 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
860 if (type->dtdt_kind == DIF_TYPE_STRING)
861 sz = dtrace_strlen(src,
862 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
864 sz = type->dtdt_size;
866 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
870 * Compare two strings using safe loads.
873 dtrace_strncmp(char *s1, char *s2, size_t limit)
876 volatile uint16_t *flags;
878 if (s1 == s2 || limit == 0)
881 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
887 c1 = dtrace_load8((uintptr_t)s1++);
893 c2 = dtrace_load8((uintptr_t)s2++);
898 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
904 * Compute strlen(s) for a string using safe memory accesses. The additional
905 * len parameter is used to specify a maximum length to ensure completion.
908 dtrace_strlen(const char *s, size_t lim)
912 for (len = 0; len != lim; len++) {
913 if (dtrace_load8((uintptr_t)s++) == '\0')
921 * Check if an address falls within a toxic region.
924 dtrace_istoxic(uintptr_t kaddr, size_t size)
926 uintptr_t taddr, tsize;
929 for (i = 0; i < dtrace_toxranges; i++) {
930 taddr = dtrace_toxrange[i].dtt_base;
931 tsize = dtrace_toxrange[i].dtt_limit - taddr;
933 if (kaddr - taddr < tsize) {
934 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
935 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
939 if (taddr - kaddr < size) {
940 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
941 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
950 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
951 * memory specified by the DIF program. The dst is assumed to be safe memory
952 * that we can store to directly because it is managed by DTrace. As with
953 * standard bcopy, overlapping copies are handled properly.
956 dtrace_bcopy(const void *src, void *dst, size_t len)
960 const uint8_t *s2 = src;
964 *s1++ = dtrace_load8((uintptr_t)s2++);
965 } while (--len != 0);
971 *--s1 = dtrace_load8((uintptr_t)--s2);
972 } while (--len != 0);
978 * Copy src to dst using safe memory accesses, up to either the specified
979 * length, or the point that a nul byte is encountered. The src is assumed to
980 * be unsafe memory specified by the DIF program. The dst is assumed to be
981 * safe memory that we can store to directly because it is managed by DTrace.
982 * Unlike dtrace_bcopy(), overlapping regions are not handled.
985 dtrace_strcpy(const void *src, void *dst, size_t len)
988 uint8_t *s1 = dst, c;
989 const uint8_t *s2 = src;
992 *s1++ = c = dtrace_load8((uintptr_t)s2++);
993 } while (--len != 0 && c != '\0');
998 * Copy src to dst, deriving the size and type from the specified (BYREF)
999 * variable type. The src is assumed to be unsafe memory specified by the DIF
1000 * program. The dst is assumed to be DTrace variable memory that is of the
1001 * specified type; we assume that we can store to directly.
1004 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1006 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1008 if (type->dtdt_kind == DIF_TYPE_STRING) {
1009 dtrace_strcpy(src, dst, type->dtdt_size);
1011 dtrace_bcopy(src, dst, type->dtdt_size);
1016 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1017 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1018 * safe memory that we can access directly because it is managed by DTrace.
1021 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1023 volatile uint16_t *flags;
1025 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1030 if (s1 == NULL || s2 == NULL)
1033 if (s1 != s2 && len != 0) {
1034 const uint8_t *ps1 = s1;
1035 const uint8_t *ps2 = s2;
1038 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1040 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1046 * Zero the specified region using a simple byte-by-byte loop. Note that this
1047 * is for safe DTrace-managed memory only.
1050 dtrace_bzero(void *dst, size_t len)
1054 for (cp = dst; len != 0; len--)
1059 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1063 result[0] = addend1[0] + addend2[0];
1064 result[1] = addend1[1] + addend2[1] +
1065 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1072 * Shift the 128-bit value in a by b. If b is positive, shift left.
1073 * If b is negative, shift right.
1076 dtrace_shift_128(uint64_t *a, int b)
1086 a[0] = a[1] >> (b - 64);
1090 mask = 1LL << (64 - b);
1092 a[0] |= ((a[1] & mask) << (64 - b));
1097 a[1] = a[0] << (b - 64);
1101 mask = a[0] >> (64 - b);
1109 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1110 * use native multiplication on those, and then re-combine into the
1111 * resulting 128-bit value.
1113 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1120 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1122 uint64_t hi1, hi2, lo1, lo2;
1125 hi1 = factor1 >> 32;
1126 hi2 = factor2 >> 32;
1128 lo1 = factor1 & DT_MASK_LO;
1129 lo2 = factor2 & DT_MASK_LO;
1131 product[0] = lo1 * lo2;
1132 product[1] = hi1 * hi2;
1136 dtrace_shift_128(tmp, 32);
1137 dtrace_add_128(product, tmp, product);
1141 dtrace_shift_128(tmp, 32);
1142 dtrace_add_128(product, tmp, product);
1146 * This privilege check should be used by actions and subroutines to
1147 * verify that the user credentials of the process that enabled the
1148 * invoking ECB match the target credentials
1151 dtrace_priv_proc_common_user(dtrace_state_t *state)
1153 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1156 * We should always have a non-NULL state cred here, since if cred
1157 * is null (anonymous tracing), we fast-path bypass this routine.
1159 ASSERT(s_cr != NULL);
1161 if ((cr = CRED()) != NULL &&
1162 s_cr->cr_uid == cr->cr_uid &&
1163 s_cr->cr_uid == cr->cr_ruid &&
1164 s_cr->cr_uid == cr->cr_suid &&
1165 s_cr->cr_gid == cr->cr_gid &&
1166 s_cr->cr_gid == cr->cr_rgid &&
1167 s_cr->cr_gid == cr->cr_sgid)
1174 * This privilege check should be used by actions and subroutines to
1175 * verify that the zone of the process that enabled the invoking ECB
1176 * matches the target credentials
1179 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1182 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1185 * We should always have a non-NULL state cred here, since if cred
1186 * is null (anonymous tracing), we fast-path bypass this routine.
1188 ASSERT(s_cr != NULL);
1190 if ((cr = CRED()) != NULL &&
1191 s_cr->cr_zone == cr->cr_zone)
1201 * This privilege check should be used by actions and subroutines to
1202 * verify that the process has not setuid or changed credentials.
1205 dtrace_priv_proc_common_nocd(void)
1209 if ((proc = ttoproc(curthread)) != NULL &&
1210 !(proc->p_flag & SNOCD))
1217 dtrace_priv_proc_destructive(dtrace_state_t *state)
1219 int action = state->dts_cred.dcr_action;
1221 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1222 dtrace_priv_proc_common_zone(state) == 0)
1225 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1226 dtrace_priv_proc_common_user(state) == 0)
1229 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1230 dtrace_priv_proc_common_nocd() == 0)
1236 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1242 dtrace_priv_proc_control(dtrace_state_t *state)
1244 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1247 if (dtrace_priv_proc_common_zone(state) &&
1248 dtrace_priv_proc_common_user(state) &&
1249 dtrace_priv_proc_common_nocd())
1252 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1258 dtrace_priv_proc(dtrace_state_t *state)
1260 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1263 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1269 dtrace_priv_kernel(dtrace_state_t *state)
1271 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1274 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1280 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1282 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1285 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1291 * Note: not called from probe context. This function is called
1292 * asynchronously (and at a regular interval) from outside of probe context to
1293 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1294 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1297 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1299 dtrace_dynvar_t *dirty;
1300 dtrace_dstate_percpu_t *dcpu;
1303 for (i = 0; i < NCPU; i++) {
1304 dcpu = &dstate->dtds_percpu[i];
1306 ASSERT(dcpu->dtdsc_rinsing == NULL);
1309 * If the dirty list is NULL, there is no dirty work to do.
1311 if (dcpu->dtdsc_dirty == NULL)
1315 * If the clean list is non-NULL, then we're not going to do
1316 * any work for this CPU -- it means that there has not been
1317 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1318 * since the last time we cleaned house.
1320 if (dcpu->dtdsc_clean != NULL)
1326 * Atomically move the dirty list aside.
1329 dirty = dcpu->dtdsc_dirty;
1332 * Before we zap the dirty list, set the rinsing list.
1333 * (This allows for a potential assertion in
1334 * dtrace_dynvar(): if a free dynamic variable appears
1335 * on a hash chain, either the dirty list or the
1336 * rinsing list for some CPU must be non-NULL.)
1338 dcpu->dtdsc_rinsing = dirty;
1339 dtrace_membar_producer();
1340 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1341 dirty, NULL) != dirty);
1346 * We have no work to do; we can simply return.
1353 for (i = 0; i < NCPU; i++) {
1354 dcpu = &dstate->dtds_percpu[i];
1356 if (dcpu->dtdsc_rinsing == NULL)
1360 * We are now guaranteed that no hash chain contains a pointer
1361 * into this dirty list; we can make it clean.
1363 ASSERT(dcpu->dtdsc_clean == NULL);
1364 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1365 dcpu->dtdsc_rinsing = NULL;
1369 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1370 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1371 * This prevents a race whereby a CPU incorrectly decides that
1372 * the state should be something other than DTRACE_DSTATE_CLEAN
1373 * after dtrace_dynvar_clean() has completed.
1377 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1381 * Depending on the value of the op parameter, this function looks-up,
1382 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1383 * allocation is requested, this function will return a pointer to a
1384 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1385 * variable can be allocated. If NULL is returned, the appropriate counter
1386 * will be incremented.
1389 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1390 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1391 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1393 uint64_t hashval = DTRACE_DYNHASH_VALID;
1394 dtrace_dynhash_t *hash = dstate->dtds_hash;
1395 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1396 processorid_t me = curcpu, cpu = me;
1397 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1398 size_t bucket, ksize;
1399 size_t chunksize = dstate->dtds_chunksize;
1400 uintptr_t kdata, lock, nstate;
1406 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1407 * algorithm. For the by-value portions, we perform the algorithm in
1408 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1409 * bit, and seems to have only a minute effect on distribution. For
1410 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1411 * over each referenced byte. It's painful to do this, but it's much
1412 * better than pathological hash distribution. The efficacy of the
1413 * hashing algorithm (and a comparison with other algorithms) may be
1414 * found by running the ::dtrace_dynstat MDB dcmd.
1416 for (i = 0; i < nkeys; i++) {
1417 if (key[i].dttk_size == 0) {
1418 uint64_t val = key[i].dttk_value;
1420 hashval += (val >> 48) & 0xffff;
1421 hashval += (hashval << 10);
1422 hashval ^= (hashval >> 6);
1424 hashval += (val >> 32) & 0xffff;
1425 hashval += (hashval << 10);
1426 hashval ^= (hashval >> 6);
1428 hashval += (val >> 16) & 0xffff;
1429 hashval += (hashval << 10);
1430 hashval ^= (hashval >> 6);
1432 hashval += val & 0xffff;
1433 hashval += (hashval << 10);
1434 hashval ^= (hashval >> 6);
1437 * This is incredibly painful, but it beats the hell
1438 * out of the alternative.
1440 uint64_t j, size = key[i].dttk_size;
1441 uintptr_t base = (uintptr_t)key[i].dttk_value;
1443 if (!dtrace_canload(base, size, mstate, vstate))
1446 for (j = 0; j < size; j++) {
1447 hashval += dtrace_load8(base + j);
1448 hashval += (hashval << 10);
1449 hashval ^= (hashval >> 6);
1454 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1457 hashval += (hashval << 3);
1458 hashval ^= (hashval >> 11);
1459 hashval += (hashval << 15);
1462 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1463 * comes out to be one of our two sentinel hash values. If this
1464 * actually happens, we set the hashval to be a value known to be a
1465 * non-sentinel value.
1467 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1468 hashval = DTRACE_DYNHASH_VALID;
1471 * Yes, it's painful to do a divide here. If the cycle count becomes
1472 * important here, tricks can be pulled to reduce it. (However, it's
1473 * critical that hash collisions be kept to an absolute minimum;
1474 * they're much more painful than a divide.) It's better to have a
1475 * solution that generates few collisions and still keeps things
1476 * relatively simple.
1478 bucket = hashval % dstate->dtds_hashsize;
1480 if (op == DTRACE_DYNVAR_DEALLOC) {
1481 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1484 while ((lock = *lockp) & 1)
1487 if (dtrace_casptr((volatile void *)lockp,
1488 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1492 dtrace_membar_producer();
1497 lock = hash[bucket].dtdh_lock;
1499 dtrace_membar_consumer();
1501 start = hash[bucket].dtdh_chain;
1502 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1503 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1504 op != DTRACE_DYNVAR_DEALLOC));
1506 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1507 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1508 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1510 if (dvar->dtdv_hashval != hashval) {
1511 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1513 * We've reached the sink, and therefore the
1514 * end of the hash chain; we can kick out of
1515 * the loop knowing that we have seen a valid
1516 * snapshot of state.
1518 ASSERT(dvar->dtdv_next == NULL);
1519 ASSERT(dvar == &dtrace_dynhash_sink);
1523 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1525 * We've gone off the rails: somewhere along
1526 * the line, one of the members of this hash
1527 * chain was deleted. Note that we could also
1528 * detect this by simply letting this loop run
1529 * to completion, as we would eventually hit
1530 * the end of the dirty list. However, we
1531 * want to avoid running the length of the
1532 * dirty list unnecessarily (it might be quite
1533 * long), so we catch this as early as
1534 * possible by detecting the hash marker. In
1535 * this case, we simply set dvar to NULL and
1536 * break; the conditional after the loop will
1537 * send us back to top.
1546 if (dtuple->dtt_nkeys != nkeys)
1549 for (i = 0; i < nkeys; i++, dkey++) {
1550 if (dkey->dttk_size != key[i].dttk_size)
1551 goto next; /* size or type mismatch */
1553 if (dkey->dttk_size != 0) {
1555 (void *)(uintptr_t)key[i].dttk_value,
1556 (void *)(uintptr_t)dkey->dttk_value,
1560 if (dkey->dttk_value != key[i].dttk_value)
1565 if (op != DTRACE_DYNVAR_DEALLOC)
1568 ASSERT(dvar->dtdv_next == NULL ||
1569 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1572 ASSERT(hash[bucket].dtdh_chain != dvar);
1573 ASSERT(start != dvar);
1574 ASSERT(prev->dtdv_next == dvar);
1575 prev->dtdv_next = dvar->dtdv_next;
1577 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1578 start, dvar->dtdv_next) != start) {
1580 * We have failed to atomically swing the
1581 * hash table head pointer, presumably because
1582 * of a conflicting allocation on another CPU.
1583 * We need to reread the hash chain and try
1590 dtrace_membar_producer();
1593 * Now set the hash value to indicate that it's free.
1595 ASSERT(hash[bucket].dtdh_chain != dvar);
1596 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1598 dtrace_membar_producer();
1601 * Set the next pointer to point at the dirty list, and
1602 * atomically swing the dirty pointer to the newly freed dvar.
1605 next = dcpu->dtdsc_dirty;
1606 dvar->dtdv_next = next;
1607 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1610 * Finally, unlock this hash bucket.
1612 ASSERT(hash[bucket].dtdh_lock == lock);
1614 hash[bucket].dtdh_lock++;
1624 * If dvar is NULL, it is because we went off the rails:
1625 * one of the elements that we traversed in the hash chain
1626 * was deleted while we were traversing it. In this case,
1627 * we assert that we aren't doing a dealloc (deallocs lock
1628 * the hash bucket to prevent themselves from racing with
1629 * one another), and retry the hash chain traversal.
1631 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1635 if (op != DTRACE_DYNVAR_ALLOC) {
1637 * If we are not to allocate a new variable, we want to
1638 * return NULL now. Before we return, check that the value
1639 * of the lock word hasn't changed. If it has, we may have
1640 * seen an inconsistent snapshot.
1642 if (op == DTRACE_DYNVAR_NOALLOC) {
1643 if (hash[bucket].dtdh_lock != lock)
1646 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1647 ASSERT(hash[bucket].dtdh_lock == lock);
1649 hash[bucket].dtdh_lock++;
1656 * We need to allocate a new dynamic variable. The size we need is the
1657 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1658 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1659 * the size of any referred-to data (dsize). We then round the final
1660 * size up to the chunksize for allocation.
1662 for (ksize = 0, i = 0; i < nkeys; i++)
1663 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1666 * This should be pretty much impossible, but could happen if, say,
1667 * strange DIF specified the tuple. Ideally, this should be an
1668 * assertion and not an error condition -- but that requires that the
1669 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1670 * bullet-proof. (That is, it must not be able to be fooled by
1671 * malicious DIF.) Given the lack of backwards branches in DIF,
1672 * solving this would presumably not amount to solving the Halting
1673 * Problem -- but it still seems awfully hard.
1675 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1676 ksize + dsize > chunksize) {
1677 dcpu->dtdsc_drops++;
1681 nstate = DTRACE_DSTATE_EMPTY;
1685 free = dcpu->dtdsc_free;
1688 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1691 if (clean == NULL) {
1693 * We're out of dynamic variable space on
1694 * this CPU. Unless we have tried all CPUs,
1695 * we'll try to allocate from a different
1698 switch (dstate->dtds_state) {
1699 case DTRACE_DSTATE_CLEAN: {
1700 void *sp = &dstate->dtds_state;
1705 if (dcpu->dtdsc_dirty != NULL &&
1706 nstate == DTRACE_DSTATE_EMPTY)
1707 nstate = DTRACE_DSTATE_DIRTY;
1709 if (dcpu->dtdsc_rinsing != NULL)
1710 nstate = DTRACE_DSTATE_RINSING;
1712 dcpu = &dstate->dtds_percpu[cpu];
1717 (void) dtrace_cas32(sp,
1718 DTRACE_DSTATE_CLEAN, nstate);
1721 * To increment the correct bean
1722 * counter, take another lap.
1727 case DTRACE_DSTATE_DIRTY:
1728 dcpu->dtdsc_dirty_drops++;
1731 case DTRACE_DSTATE_RINSING:
1732 dcpu->dtdsc_rinsing_drops++;
1735 case DTRACE_DSTATE_EMPTY:
1736 dcpu->dtdsc_drops++;
1740 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1745 * The clean list appears to be non-empty. We want to
1746 * move the clean list to the free list; we start by
1747 * moving the clean pointer aside.
1749 if (dtrace_casptr(&dcpu->dtdsc_clean,
1750 clean, NULL) != clean) {
1752 * We are in one of two situations:
1754 * (a) The clean list was switched to the
1755 * free list by another CPU.
1757 * (b) The clean list was added to by the
1760 * In either of these situations, we can
1761 * just reattempt the free list allocation.
1766 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1769 * Now we'll move the clean list to the free list.
1770 * It's impossible for this to fail: the only way
1771 * the free list can be updated is through this
1772 * code path, and only one CPU can own the clean list.
1773 * Thus, it would only be possible for this to fail if
1774 * this code were racing with dtrace_dynvar_clean().
1775 * (That is, if dtrace_dynvar_clean() updated the clean
1776 * list, and we ended up racing to update the free
1777 * list.) This race is prevented by the dtrace_sync()
1778 * in dtrace_dynvar_clean() -- which flushes the
1779 * owners of the clean lists out before resetting
1782 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1783 ASSERT(rval == NULL);
1788 new_free = dvar->dtdv_next;
1789 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1792 * We have now allocated a new chunk. We copy the tuple keys into the
1793 * tuple array and copy any referenced key data into the data space
1794 * following the tuple array. As we do this, we relocate dttk_value
1795 * in the final tuple to point to the key data address in the chunk.
1797 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1798 dvar->dtdv_data = (void *)(kdata + ksize);
1799 dvar->dtdv_tuple.dtt_nkeys = nkeys;
1801 for (i = 0; i < nkeys; i++) {
1802 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1803 size_t kesize = key[i].dttk_size;
1807 (const void *)(uintptr_t)key[i].dttk_value,
1808 (void *)kdata, kesize);
1809 dkey->dttk_value = kdata;
1810 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1812 dkey->dttk_value = key[i].dttk_value;
1815 dkey->dttk_size = kesize;
1818 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1819 dvar->dtdv_hashval = hashval;
1820 dvar->dtdv_next = start;
1822 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1826 * The cas has failed. Either another CPU is adding an element to
1827 * this hash chain, or another CPU is deleting an element from this
1828 * hash chain. The simplest way to deal with both of these cases
1829 * (though not necessarily the most efficient) is to free our
1830 * allocated block and tail-call ourselves. Note that the free is
1831 * to the dirty list and _not_ to the free list. This is to prevent
1832 * races with allocators, above.
1834 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1836 dtrace_membar_producer();
1839 free = dcpu->dtdsc_dirty;
1840 dvar->dtdv_next = free;
1841 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1843 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1848 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1850 if ((int64_t)nval < (int64_t)*oval)
1856 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1858 if ((int64_t)nval > (int64_t)*oval)
1863 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1865 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1866 int64_t val = (int64_t)nval;
1869 for (i = 0; i < zero; i++) {
1870 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1876 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1877 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1878 quanta[i - 1] += incr;
1883 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1891 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1893 uint64_t arg = *lquanta++;
1894 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1895 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1896 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1897 int32_t val = (int32_t)nval, level;
1900 ASSERT(levels != 0);
1904 * This is an underflow.
1910 level = (val - base) / step;
1912 if (level < levels) {
1913 lquanta[level + 1] += incr;
1918 * This is an overflow.
1920 lquanta[levels + 1] += incr;
1924 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
1925 uint16_t high, uint16_t nsteps, int64_t value)
1927 int64_t this = 1, last, next;
1928 int base = 1, order;
1930 ASSERT(factor <= nsteps);
1931 ASSERT(nsteps % factor == 0);
1933 for (order = 0; order < low; order++)
1937 * If our value is less than our factor taken to the power of the
1938 * low order of magnitude, it goes into the zeroth bucket.
1940 if (value < (last = this))
1943 for (this *= factor; order <= high; order++) {
1944 int nbuckets = this > nsteps ? nsteps : this;
1946 if ((next = this * factor) < this) {
1948 * We should not generally get log/linear quantizations
1949 * with a high magnitude that allows 64-bits to
1950 * overflow, but we nonetheless protect against this
1951 * by explicitly checking for overflow, and clamping
1952 * our value accordingly.
1959 * If our value lies within this order of magnitude,
1960 * determine its position by taking the offset within
1961 * the order of magnitude, dividing by the bucket
1962 * width, and adding to our (accumulated) base.
1964 return (base + (value - last) / (this / nbuckets));
1967 base += nbuckets - (nbuckets / factor);
1973 * Our value is greater than or equal to our factor taken to the
1974 * power of one plus the high magnitude -- return the top bucket.
1980 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
1982 uint64_t arg = *llquanta++;
1983 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
1984 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
1985 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
1986 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
1988 llquanta[dtrace_aggregate_llquantize_bucket(factor,
1989 low, high, nsteps, nval)] += incr;
1994 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2002 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2004 int64_t snval = (int64_t)nval;
2011 * What we want to say here is:
2013 * data[2] += nval * nval;
2015 * But given that nval is 64-bit, we could easily overflow, so
2016 * we do this as 128-bit arithmetic.
2021 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2022 dtrace_add_128(data + 2, tmp, data + 2);
2027 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2034 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2040 * Aggregate given the tuple in the principal data buffer, and the aggregating
2041 * action denoted by the specified dtrace_aggregation_t. The aggregation
2042 * buffer is specified as the buf parameter. This routine does not return
2043 * failure; if there is no space in the aggregation buffer, the data will be
2044 * dropped, and a corresponding counter incremented.
2047 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2048 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2050 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2051 uint32_t i, ndx, size, fsize;
2052 uint32_t align = sizeof (uint64_t) - 1;
2053 dtrace_aggbuffer_t *agb;
2054 dtrace_aggkey_t *key;
2055 uint32_t hashval = 0, limit, isstr;
2056 caddr_t tomax, data, kdata;
2057 dtrace_actkind_t action;
2058 dtrace_action_t *act;
2064 if (!agg->dtag_hasarg) {
2066 * Currently, only quantize() and lquantize() take additional
2067 * arguments, and they have the same semantics: an increment
2068 * value that defaults to 1 when not present. If additional
2069 * aggregating actions take arguments, the setting of the
2070 * default argument value will presumably have to become more
2076 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2077 size = rec->dtrd_offset - agg->dtag_base;
2078 fsize = size + rec->dtrd_size;
2080 ASSERT(dbuf->dtb_tomax != NULL);
2081 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2083 if ((tomax = buf->dtb_tomax) == NULL) {
2084 dtrace_buffer_drop(buf);
2089 * The metastructure is always at the bottom of the buffer.
2091 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2092 sizeof (dtrace_aggbuffer_t));
2094 if (buf->dtb_offset == 0) {
2096 * We just kludge up approximately 1/8th of the size to be
2097 * buckets. If this guess ends up being routinely
2098 * off-the-mark, we may need to dynamically readjust this
2099 * based on past performance.
2101 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2103 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2104 (uintptr_t)tomax || hashsize == 0) {
2106 * We've been given a ludicrously small buffer;
2107 * increment our drop count and leave.
2109 dtrace_buffer_drop(buf);
2114 * And now, a pathetic attempt to try to get a an odd (or
2115 * perchance, a prime) hash size for better hash distribution.
2117 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2118 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2120 agb->dtagb_hashsize = hashsize;
2121 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2122 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2123 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2125 for (i = 0; i < agb->dtagb_hashsize; i++)
2126 agb->dtagb_hash[i] = NULL;
2129 ASSERT(agg->dtag_first != NULL);
2130 ASSERT(agg->dtag_first->dta_intuple);
2133 * Calculate the hash value based on the key. Note that we _don't_
2134 * include the aggid in the hashing (but we will store it as part of
2135 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2136 * algorithm: a simple, quick algorithm that has no known funnels, and
2137 * gets good distribution in practice. The efficacy of the hashing
2138 * algorithm (and a comparison with other algorithms) may be found by
2139 * running the ::dtrace_aggstat MDB dcmd.
2141 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2142 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2143 limit = i + act->dta_rec.dtrd_size;
2144 ASSERT(limit <= size);
2145 isstr = DTRACEACT_ISSTRING(act);
2147 for (; i < limit; i++) {
2149 hashval += (hashval << 10);
2150 hashval ^= (hashval >> 6);
2152 if (isstr && data[i] == '\0')
2157 hashval += (hashval << 3);
2158 hashval ^= (hashval >> 11);
2159 hashval += (hashval << 15);
2162 * Yes, the divide here is expensive -- but it's generally the least
2163 * of the performance issues given the amount of data that we iterate
2164 * over to compute hash values, compare data, etc.
2166 ndx = hashval % agb->dtagb_hashsize;
2168 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2169 ASSERT((caddr_t)key >= tomax);
2170 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2172 if (hashval != key->dtak_hashval || key->dtak_size != size)
2175 kdata = key->dtak_data;
2176 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2178 for (act = agg->dtag_first; act->dta_intuple;
2179 act = act->dta_next) {
2180 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2181 limit = i + act->dta_rec.dtrd_size;
2182 ASSERT(limit <= size);
2183 isstr = DTRACEACT_ISSTRING(act);
2185 for (; i < limit; i++) {
2186 if (kdata[i] != data[i])
2189 if (isstr && data[i] == '\0')
2194 if (action != key->dtak_action) {
2196 * We are aggregating on the same value in the same
2197 * aggregation with two different aggregating actions.
2198 * (This should have been picked up in the compiler,
2199 * so we may be dealing with errant or devious DIF.)
2200 * This is an error condition; we indicate as much,
2203 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2208 * This is a hit: we need to apply the aggregator to
2209 * the value at this key.
2211 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2218 * We didn't find it. We need to allocate some zero-filled space,
2219 * link it into the hash table appropriately, and apply the aggregator
2220 * to the (zero-filled) value.
2222 offs = buf->dtb_offset;
2223 while (offs & (align - 1))
2224 offs += sizeof (uint32_t);
2227 * If we don't have enough room to both allocate a new key _and_
2228 * its associated data, increment the drop count and return.
2230 if ((uintptr_t)tomax + offs + fsize >
2231 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2232 dtrace_buffer_drop(buf);
2237 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2238 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2239 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2241 key->dtak_data = kdata = tomax + offs;
2242 buf->dtb_offset = offs + fsize;
2245 * Now copy the data across.
2247 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2249 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2253 * Because strings are not zeroed out by default, we need to iterate
2254 * looking for actions that store strings, and we need to explicitly
2255 * pad these strings out with zeroes.
2257 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2260 if (!DTRACEACT_ISSTRING(act))
2263 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2264 limit = i + act->dta_rec.dtrd_size;
2265 ASSERT(limit <= size);
2267 for (nul = 0; i < limit; i++) {
2273 if (data[i] != '\0')
2280 for (i = size; i < fsize; i++)
2283 key->dtak_hashval = hashval;
2284 key->dtak_size = size;
2285 key->dtak_action = action;
2286 key->dtak_next = agb->dtagb_hash[ndx];
2287 agb->dtagb_hash[ndx] = key;
2290 * Finally, apply the aggregator.
2292 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2293 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2297 * Given consumer state, this routine finds a speculation in the INACTIVE
2298 * state and transitions it into the ACTIVE state. If there is no speculation
2299 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2300 * incremented -- it is up to the caller to take appropriate action.
2303 dtrace_speculation(dtrace_state_t *state)
2306 dtrace_speculation_state_t current;
2307 uint32_t *stat = &state->dts_speculations_unavail, count;
2309 while (i < state->dts_nspeculations) {
2310 dtrace_speculation_t *spec = &state->dts_speculations[i];
2312 current = spec->dtsp_state;
2314 if (current != DTRACESPEC_INACTIVE) {
2315 if (current == DTRACESPEC_COMMITTINGMANY ||
2316 current == DTRACESPEC_COMMITTING ||
2317 current == DTRACESPEC_DISCARDING)
2318 stat = &state->dts_speculations_busy;
2323 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2324 current, DTRACESPEC_ACTIVE) == current)
2329 * We couldn't find a speculation. If we found as much as a single
2330 * busy speculation buffer, we'll attribute this failure as "busy"
2331 * instead of "unavail".
2335 } while (dtrace_cas32(stat, count, count + 1) != count);
2341 * This routine commits an active speculation. If the specified speculation
2342 * is not in a valid state to perform a commit(), this routine will silently do
2343 * nothing. The state of the specified speculation is transitioned according
2344 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2347 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2348 dtrace_specid_t which)
2350 dtrace_speculation_t *spec;
2351 dtrace_buffer_t *src, *dest;
2352 uintptr_t daddr, saddr, dlimit, slimit;
2353 dtrace_speculation_state_t current, new = 0;
2360 if (which > state->dts_nspeculations) {
2361 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2365 spec = &state->dts_speculations[which - 1];
2366 src = &spec->dtsp_buffer[cpu];
2367 dest = &state->dts_buffer[cpu];
2370 current = spec->dtsp_state;
2372 if (current == DTRACESPEC_COMMITTINGMANY)
2376 case DTRACESPEC_INACTIVE:
2377 case DTRACESPEC_DISCARDING:
2380 case DTRACESPEC_COMMITTING:
2382 * This is only possible if we are (a) commit()'ing
2383 * without having done a prior speculate() on this CPU
2384 * and (b) racing with another commit() on a different
2385 * CPU. There's nothing to do -- we just assert that
2388 ASSERT(src->dtb_offset == 0);
2391 case DTRACESPEC_ACTIVE:
2392 new = DTRACESPEC_COMMITTING;
2395 case DTRACESPEC_ACTIVEONE:
2397 * This speculation is active on one CPU. If our
2398 * buffer offset is non-zero, we know that the one CPU
2399 * must be us. Otherwise, we are committing on a
2400 * different CPU from the speculate(), and we must
2401 * rely on being asynchronously cleaned.
2403 if (src->dtb_offset != 0) {
2404 new = DTRACESPEC_COMMITTING;
2409 case DTRACESPEC_ACTIVEMANY:
2410 new = DTRACESPEC_COMMITTINGMANY;
2416 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2417 current, new) != current);
2420 * We have set the state to indicate that we are committing this
2421 * speculation. Now reserve the necessary space in the destination
2424 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2425 sizeof (uint64_t), state, NULL)) < 0) {
2426 dtrace_buffer_drop(dest);
2431 * We have sufficient space to copy the speculative buffer into the
2432 * primary buffer. First, modify the speculative buffer, filling
2433 * in the timestamp of all entries with the current time. The data
2434 * must have the commit() time rather than the time it was traced,
2435 * so that all entries in the primary buffer are in timestamp order.
2437 timestamp = dtrace_gethrtime();
2438 saddr = (uintptr_t)src->dtb_tomax;
2439 slimit = saddr + src->dtb_offset;
2440 while (saddr < slimit) {
2442 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2444 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2445 saddr += sizeof (dtrace_epid_t);
2448 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2449 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2451 ASSERT3U(saddr + size, <=, slimit);
2452 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2453 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2455 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2461 * Copy the buffer across. (Note that this is a
2462 * highly subobtimal bcopy(); in the unlikely event that this becomes
2463 * a serious performance issue, a high-performance DTrace-specific
2464 * bcopy() should obviously be invented.)
2466 daddr = (uintptr_t)dest->dtb_tomax + offs;
2467 dlimit = daddr + src->dtb_offset;
2468 saddr = (uintptr_t)src->dtb_tomax;
2471 * First, the aligned portion.
2473 while (dlimit - daddr >= sizeof (uint64_t)) {
2474 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2476 daddr += sizeof (uint64_t);
2477 saddr += sizeof (uint64_t);
2481 * Now any left-over bit...
2483 while (dlimit - daddr)
2484 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2487 * Finally, commit the reserved space in the destination buffer.
2489 dest->dtb_offset = offs + src->dtb_offset;
2493 * If we're lucky enough to be the only active CPU on this speculation
2494 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2496 if (current == DTRACESPEC_ACTIVE ||
2497 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2498 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2499 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2501 ASSERT(rval == DTRACESPEC_COMMITTING);
2504 src->dtb_offset = 0;
2505 src->dtb_xamot_drops += src->dtb_drops;
2510 * This routine discards an active speculation. If the specified speculation
2511 * is not in a valid state to perform a discard(), this routine will silently
2512 * do nothing. The state of the specified speculation is transitioned
2513 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2516 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2517 dtrace_specid_t which)
2519 dtrace_speculation_t *spec;
2520 dtrace_speculation_state_t current, new = 0;
2521 dtrace_buffer_t *buf;
2526 if (which > state->dts_nspeculations) {
2527 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2531 spec = &state->dts_speculations[which - 1];
2532 buf = &spec->dtsp_buffer[cpu];
2535 current = spec->dtsp_state;
2538 case DTRACESPEC_INACTIVE:
2539 case DTRACESPEC_COMMITTINGMANY:
2540 case DTRACESPEC_COMMITTING:
2541 case DTRACESPEC_DISCARDING:
2544 case DTRACESPEC_ACTIVE:
2545 case DTRACESPEC_ACTIVEMANY:
2546 new = DTRACESPEC_DISCARDING;
2549 case DTRACESPEC_ACTIVEONE:
2550 if (buf->dtb_offset != 0) {
2551 new = DTRACESPEC_INACTIVE;
2553 new = DTRACESPEC_DISCARDING;
2560 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2561 current, new) != current);
2563 buf->dtb_offset = 0;
2568 * Note: not called from probe context. This function is called
2569 * asynchronously from cross call context to clean any speculations that are
2570 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2571 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2575 dtrace_speculation_clean_here(dtrace_state_t *state)
2577 dtrace_icookie_t cookie;
2578 processorid_t cpu = curcpu;
2579 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2582 cookie = dtrace_interrupt_disable();
2584 if (dest->dtb_tomax == NULL) {
2585 dtrace_interrupt_enable(cookie);
2589 for (i = 0; i < state->dts_nspeculations; i++) {
2590 dtrace_speculation_t *spec = &state->dts_speculations[i];
2591 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2593 if (src->dtb_tomax == NULL)
2596 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2597 src->dtb_offset = 0;
2601 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2604 if (src->dtb_offset == 0)
2607 dtrace_speculation_commit(state, cpu, i + 1);
2610 dtrace_interrupt_enable(cookie);
2614 * Note: not called from probe context. This function is called
2615 * asynchronously (and at a regular interval) to clean any speculations that
2616 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2617 * is work to be done, it cross calls all CPUs to perform that work;
2618 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2619 * INACTIVE state until they have been cleaned by all CPUs.
2622 dtrace_speculation_clean(dtrace_state_t *state)
2627 for (i = 0; i < state->dts_nspeculations; i++) {
2628 dtrace_speculation_t *spec = &state->dts_speculations[i];
2630 ASSERT(!spec->dtsp_cleaning);
2632 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2633 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2637 spec->dtsp_cleaning = 1;
2643 dtrace_xcall(DTRACE_CPUALL,
2644 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2647 * We now know that all CPUs have committed or discarded their
2648 * speculation buffers, as appropriate. We can now set the state
2651 for (i = 0; i < state->dts_nspeculations; i++) {
2652 dtrace_speculation_t *spec = &state->dts_speculations[i];
2653 dtrace_speculation_state_t current, new;
2655 if (!spec->dtsp_cleaning)
2658 current = spec->dtsp_state;
2659 ASSERT(current == DTRACESPEC_DISCARDING ||
2660 current == DTRACESPEC_COMMITTINGMANY);
2662 new = DTRACESPEC_INACTIVE;
2664 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2665 ASSERT(rv == current);
2666 spec->dtsp_cleaning = 0;
2671 * Called as part of a speculate() to get the speculative buffer associated
2672 * with a given speculation. Returns NULL if the specified speculation is not
2673 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2674 * the active CPU is not the specified CPU -- the speculation will be
2675 * atomically transitioned into the ACTIVEMANY state.
2677 static dtrace_buffer_t *
2678 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2679 dtrace_specid_t which)
2681 dtrace_speculation_t *spec;
2682 dtrace_speculation_state_t current, new = 0;
2683 dtrace_buffer_t *buf;
2688 if (which > state->dts_nspeculations) {
2689 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2693 spec = &state->dts_speculations[which - 1];
2694 buf = &spec->dtsp_buffer[cpuid];
2697 current = spec->dtsp_state;
2700 case DTRACESPEC_INACTIVE:
2701 case DTRACESPEC_COMMITTINGMANY:
2702 case DTRACESPEC_DISCARDING:
2705 case DTRACESPEC_COMMITTING:
2706 ASSERT(buf->dtb_offset == 0);
2709 case DTRACESPEC_ACTIVEONE:
2711 * This speculation is currently active on one CPU.
2712 * Check the offset in the buffer; if it's non-zero,
2713 * that CPU must be us (and we leave the state alone).
2714 * If it's zero, assume that we're starting on a new
2715 * CPU -- and change the state to indicate that the
2716 * speculation is active on more than one CPU.
2718 if (buf->dtb_offset != 0)
2721 new = DTRACESPEC_ACTIVEMANY;
2724 case DTRACESPEC_ACTIVEMANY:
2727 case DTRACESPEC_ACTIVE:
2728 new = DTRACESPEC_ACTIVEONE;
2734 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2735 current, new) != current);
2737 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2742 * Return a string. In the event that the user lacks the privilege to access
2743 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2744 * don't fail access checking.
2746 * dtrace_dif_variable() uses this routine as a helper for various
2747 * builtin values such as 'execname' and 'probefunc.'
2750 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2751 dtrace_mstate_t *mstate)
2753 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2758 * The easy case: this probe is allowed to read all of memory, so
2759 * we can just return this as a vanilla pointer.
2761 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2765 * This is the tougher case: we copy the string in question from
2766 * kernel memory into scratch memory and return it that way: this
2767 * ensures that we won't trip up when access checking tests the
2768 * BYREF return value.
2770 strsz = dtrace_strlen((char *)addr, size) + 1;
2772 if (mstate->dtms_scratch_ptr + strsz >
2773 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2774 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2778 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2780 ret = mstate->dtms_scratch_ptr;
2781 mstate->dtms_scratch_ptr += strsz;
2786 * Return a string from a memoy address which is known to have one or
2787 * more concatenated, individually zero terminated, sub-strings.
2788 * In the event that the user lacks the privilege to access
2789 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2790 * don't fail access checking.
2792 * dtrace_dif_variable() uses this routine as a helper for various
2793 * builtin values such as 'execargs'.
2796 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
2797 dtrace_mstate_t *mstate)
2803 if (mstate->dtms_scratch_ptr + strsz >
2804 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2805 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2809 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2812 /* Replace sub-string termination characters with a space. */
2813 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
2818 ret = mstate->dtms_scratch_ptr;
2819 mstate->dtms_scratch_ptr += strsz;
2824 * This function implements the DIF emulator's variable lookups. The emulator
2825 * passes a reserved variable identifier and optional built-in array index.
2828 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2832 * If we're accessing one of the uncached arguments, we'll turn this
2833 * into a reference in the args array.
2835 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2836 ndx = v - DIF_VAR_ARG0;
2842 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2843 if (ndx >= sizeof (mstate->dtms_arg) /
2844 sizeof (mstate->dtms_arg[0])) {
2845 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2846 dtrace_provider_t *pv;
2849 pv = mstate->dtms_probe->dtpr_provider;
2850 if (pv->dtpv_pops.dtps_getargval != NULL)
2851 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2852 mstate->dtms_probe->dtpr_id,
2853 mstate->dtms_probe->dtpr_arg, ndx, aframes);
2855 val = dtrace_getarg(ndx, aframes);
2858 * This is regrettably required to keep the compiler
2859 * from tail-optimizing the call to dtrace_getarg().
2860 * The condition always evaluates to true, but the
2861 * compiler has no way of figuring that out a priori.
2862 * (None of this would be necessary if the compiler
2863 * could be relied upon to _always_ tail-optimize
2864 * the call to dtrace_getarg() -- but it can't.)
2866 if (mstate->dtms_probe != NULL)
2872 return (mstate->dtms_arg[ndx]);
2875 case DIF_VAR_UREGS: {
2878 if (!dtrace_priv_proc(state))
2881 if ((lwp = curthread->t_lwp) == NULL) {
2882 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2883 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
2887 return (dtrace_getreg(lwp->lwp_regs, ndx));
2891 case DIF_VAR_UREGS: {
2892 struct trapframe *tframe;
2894 if (!dtrace_priv_proc(state))
2897 if ((tframe = curthread->td_frame) == NULL) {
2898 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2899 cpu_core[curcpu].cpuc_dtrace_illval = 0;
2903 return (dtrace_getreg(tframe, ndx));
2907 case DIF_VAR_CURTHREAD:
2908 if (!dtrace_priv_kernel(state))
2910 return ((uint64_t)(uintptr_t)curthread);
2912 case DIF_VAR_TIMESTAMP:
2913 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2914 mstate->dtms_timestamp = dtrace_gethrtime();
2915 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2917 return (mstate->dtms_timestamp);
2919 case DIF_VAR_VTIMESTAMP:
2920 ASSERT(dtrace_vtime_references != 0);
2921 return (curthread->t_dtrace_vtime);
2923 case DIF_VAR_WALLTIMESTAMP:
2924 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2925 mstate->dtms_walltimestamp = dtrace_gethrestime();
2926 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2928 return (mstate->dtms_walltimestamp);
2932 if (!dtrace_priv_kernel(state))
2934 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2935 mstate->dtms_ipl = dtrace_getipl();
2936 mstate->dtms_present |= DTRACE_MSTATE_IPL;
2938 return (mstate->dtms_ipl);
2942 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2943 return (mstate->dtms_epid);
2946 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2947 return (mstate->dtms_probe->dtpr_id);
2949 case DIF_VAR_STACKDEPTH:
2950 if (!dtrace_priv_kernel(state))
2952 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2953 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2955 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2956 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2958 return (mstate->dtms_stackdepth);
2960 case DIF_VAR_USTACKDEPTH:
2961 if (!dtrace_priv_proc(state))
2963 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2965 * See comment in DIF_VAR_PID.
2967 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2969 mstate->dtms_ustackdepth = 0;
2971 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2972 mstate->dtms_ustackdepth =
2973 dtrace_getustackdepth();
2974 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2976 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2978 return (mstate->dtms_ustackdepth);
2980 case DIF_VAR_CALLER:
2981 if (!dtrace_priv_kernel(state))
2983 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2984 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2986 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2988 * If this is an unanchored probe, we are
2989 * required to go through the slow path:
2990 * dtrace_caller() only guarantees correct
2991 * results for anchored probes.
2993 pc_t caller[2] = {0, 0};
2995 dtrace_getpcstack(caller, 2, aframes,
2996 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2997 mstate->dtms_caller = caller[1];
2998 } else if ((mstate->dtms_caller =
2999 dtrace_caller(aframes)) == -1) {
3001 * We have failed to do this the quick way;
3002 * we must resort to the slower approach of
3003 * calling dtrace_getpcstack().
3007 dtrace_getpcstack(&caller, 1, aframes, NULL);
3008 mstate->dtms_caller = caller;
3011 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3013 return (mstate->dtms_caller);
3015 case DIF_VAR_UCALLER:
3016 if (!dtrace_priv_proc(state))
3019 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3023 * dtrace_getupcstack() fills in the first uint64_t
3024 * with the current PID. The second uint64_t will
3025 * be the program counter at user-level. The third
3026 * uint64_t will contain the caller, which is what
3030 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3031 dtrace_getupcstack(ustack, 3);
3032 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3033 mstate->dtms_ucaller = ustack[2];
3034 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3037 return (mstate->dtms_ucaller);
3039 case DIF_VAR_PROBEPROV:
3040 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3041 return (dtrace_dif_varstr(
3042 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3045 case DIF_VAR_PROBEMOD:
3046 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3047 return (dtrace_dif_varstr(
3048 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3051 case DIF_VAR_PROBEFUNC:
3052 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3053 return (dtrace_dif_varstr(
3054 (uintptr_t)mstate->dtms_probe->dtpr_func,
3057 case DIF_VAR_PROBENAME:
3058 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3059 return (dtrace_dif_varstr(
3060 (uintptr_t)mstate->dtms_probe->dtpr_name,
3064 if (!dtrace_priv_proc(state))
3069 * Note that we are assuming that an unanchored probe is
3070 * always due to a high-level interrupt. (And we're assuming
3071 * that there is only a single high level interrupt.)
3073 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3074 return (pid0.pid_id);
3077 * It is always safe to dereference one's own t_procp pointer:
3078 * it always points to a valid, allocated proc structure.
3079 * Further, it is always safe to dereference the p_pidp member
3080 * of one's own proc structure. (These are truisms becuase
3081 * threads and processes don't clean up their own state --
3082 * they leave that task to whomever reaps them.)
3084 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3086 return ((uint64_t)curproc->p_pid);
3090 if (!dtrace_priv_proc(state))
3095 * See comment in DIF_VAR_PID.
3097 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3098 return (pid0.pid_id);
3101 * It is always safe to dereference one's own t_procp pointer:
3102 * it always points to a valid, allocated proc structure.
3103 * (This is true because threads don't clean up their own
3104 * state -- they leave that task to whomever reaps them.)
3106 return ((uint64_t)curthread->t_procp->p_ppid);
3108 return ((uint64_t)curproc->p_pptr->p_pid);
3114 * See comment in DIF_VAR_PID.
3116 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3120 return ((uint64_t)curthread->t_tid);
3122 case DIF_VAR_EXECARGS: {
3123 struct pargs *p_args = curthread->td_proc->p_args;
3128 return (dtrace_dif_varstrz(
3129 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3132 case DIF_VAR_EXECNAME:
3134 if (!dtrace_priv_proc(state))
3138 * See comment in DIF_VAR_PID.
3140 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3141 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3144 * It is always safe to dereference one's own t_procp pointer:
3145 * it always points to a valid, allocated proc structure.
3146 * (This is true because threads don't clean up their own
3147 * state -- they leave that task to whomever reaps them.)
3149 return (dtrace_dif_varstr(
3150 (uintptr_t)curthread->t_procp->p_user.u_comm,
3153 return (dtrace_dif_varstr(
3154 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3157 case DIF_VAR_ZONENAME:
3159 if (!dtrace_priv_proc(state))
3163 * See comment in DIF_VAR_PID.
3165 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3166 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3169 * It is always safe to dereference one's own t_procp pointer:
3170 * it always points to a valid, allocated proc structure.
3171 * (This is true because threads don't clean up their own
3172 * state -- they leave that task to whomever reaps them.)
3174 return (dtrace_dif_varstr(
3175 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3182 if (!dtrace_priv_proc(state))
3187 * See comment in DIF_VAR_PID.
3189 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3190 return ((uint64_t)p0.p_cred->cr_uid);
3194 * It is always safe to dereference one's own t_procp pointer:
3195 * it always points to a valid, allocated proc structure.
3196 * (This is true because threads don't clean up their own
3197 * state -- they leave that task to whomever reaps them.)
3199 * Additionally, it is safe to dereference one's own process
3200 * credential, since this is never NULL after process birth.
3202 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3205 if (!dtrace_priv_proc(state))
3210 * See comment in DIF_VAR_PID.
3212 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3213 return ((uint64_t)p0.p_cred->cr_gid);
3217 * It is always safe to dereference one's own t_procp pointer:
3218 * it always points to a valid, allocated proc structure.
3219 * (This is true because threads don't clean up their own
3220 * state -- they leave that task to whomever reaps them.)
3222 * Additionally, it is safe to dereference one's own process
3223 * credential, since this is never NULL after process birth.
3225 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3227 case DIF_VAR_ERRNO: {
3230 if (!dtrace_priv_proc(state))
3234 * See comment in DIF_VAR_PID.
3236 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3240 * It is always safe to dereference one's own t_lwp pointer in
3241 * the event that this pointer is non-NULL. (This is true
3242 * because threads and lwps don't clean up their own state --
3243 * they leave that task to whomever reaps them.)
3245 if ((lwp = curthread->t_lwp) == NULL)
3248 return ((uint64_t)lwp->lwp_errno);
3250 return (curthread->td_errno);
3259 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3265 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3266 * Notice that we don't bother validating the proper number of arguments or
3267 * their types in the tuple stack. This isn't needed because all argument
3268 * interpretation is safe because of our load safety -- the worst that can
3269 * happen is that a bogus program can obtain bogus results.
3272 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3273 dtrace_key_t *tupregs, int nargs,
3274 dtrace_mstate_t *mstate, dtrace_state_t *state)
3276 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3277 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3278 dtrace_vstate_t *vstate = &state->dts_vstate;
3291 struct thread *lowner;
3293 struct lock_object *li;
3300 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3304 case DIF_SUBR_MUTEX_OWNED:
3305 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3311 m.mx = dtrace_load64(tupregs[0].dttk_value);
3312 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3313 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3315 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3318 case DIF_SUBR_MUTEX_OWNER:
3319 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3325 m.mx = dtrace_load64(tupregs[0].dttk_value);
3326 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3327 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3328 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3333 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3334 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3340 m.mx = dtrace_load64(tupregs[0].dttk_value);
3341 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3344 case DIF_SUBR_MUTEX_TYPE_SPIN:
3345 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3351 m.mx = dtrace_load64(tupregs[0].dttk_value);
3352 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3355 case DIF_SUBR_RW_READ_HELD: {
3358 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3364 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3365 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3369 case DIF_SUBR_RW_WRITE_HELD:
3370 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3376 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3377 regs[rd] = _RW_WRITE_HELD(&r.ri);
3380 case DIF_SUBR_RW_ISWRITER:
3381 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3387 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3388 regs[rd] = _RW_ISWRITER(&r.ri);
3392 case DIF_SUBR_MUTEX_OWNED:
3393 if (!dtrace_canload(tupregs[0].dttk_value,
3394 sizeof (struct lock_object), mstate, vstate)) {
3398 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3399 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3402 case DIF_SUBR_MUTEX_OWNER:
3403 if (!dtrace_canload(tupregs[0].dttk_value,
3404 sizeof (struct lock_object), mstate, vstate)) {
3408 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3409 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3410 regs[rd] = (uintptr_t)lowner;
3413 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3414 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3419 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3420 /* XXX - should be only LC_SLEEPABLE? */
3421 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3422 (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3425 case DIF_SUBR_MUTEX_TYPE_SPIN:
3426 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3431 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3432 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3435 case DIF_SUBR_RW_READ_HELD:
3436 case DIF_SUBR_SX_SHARED_HELD:
3437 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3442 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3443 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3447 case DIF_SUBR_RW_WRITE_HELD:
3448 case DIF_SUBR_SX_EXCLUSIVE_HELD:
3449 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3454 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3455 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3456 regs[rd] = (lowner == curthread);
3459 case DIF_SUBR_RW_ISWRITER:
3460 case DIF_SUBR_SX_ISEXCLUSIVE:
3461 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3466 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3467 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3470 #endif /* ! defined(sun) */
3472 case DIF_SUBR_BCOPY: {
3474 * We need to be sure that the destination is in the scratch
3475 * region -- no other region is allowed.
3477 uintptr_t src = tupregs[0].dttk_value;
3478 uintptr_t dest = tupregs[1].dttk_value;
3479 size_t size = tupregs[2].dttk_value;
3481 if (!dtrace_inscratch(dest, size, mstate)) {
3482 *flags |= CPU_DTRACE_BADADDR;
3487 if (!dtrace_canload(src, size, mstate, vstate)) {
3492 dtrace_bcopy((void *)src, (void *)dest, size);
3496 case DIF_SUBR_ALLOCA:
3497 case DIF_SUBR_COPYIN: {
3498 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3500 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3501 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3504 * This action doesn't require any credential checks since
3505 * probes will not activate in user contexts to which the
3506 * enabling user does not have permissions.
3510 * Rounding up the user allocation size could have overflowed
3511 * a large, bogus allocation (like -1ULL) to 0.
3513 if (scratch_size < size ||
3514 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3515 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3520 if (subr == DIF_SUBR_COPYIN) {
3521 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3522 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3523 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3526 mstate->dtms_scratch_ptr += scratch_size;
3531 case DIF_SUBR_COPYINTO: {
3532 uint64_t size = tupregs[1].dttk_value;
3533 uintptr_t dest = tupregs[2].dttk_value;
3536 * This action doesn't require any credential checks since
3537 * probes will not activate in user contexts to which the
3538 * enabling user does not have permissions.
3540 if (!dtrace_inscratch(dest, size, mstate)) {
3541 *flags |= CPU_DTRACE_BADADDR;
3546 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3547 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3548 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3552 case DIF_SUBR_COPYINSTR: {
3553 uintptr_t dest = mstate->dtms_scratch_ptr;
3554 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3556 if (nargs > 1 && tupregs[1].dttk_value < size)
3557 size = tupregs[1].dttk_value + 1;
3560 * This action doesn't require any credential checks since
3561 * probes will not activate in user contexts to which the
3562 * enabling user does not have permissions.
3564 if (!DTRACE_INSCRATCH(mstate, size)) {
3565 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3570 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3571 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3572 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3574 ((char *)dest)[size - 1] = '\0';
3575 mstate->dtms_scratch_ptr += size;
3581 case DIF_SUBR_MSGSIZE:
3582 case DIF_SUBR_MSGDSIZE: {
3583 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3584 uintptr_t wptr, rptr;
3588 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3590 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3596 wptr = dtrace_loadptr(baddr +
3597 offsetof(mblk_t, b_wptr));
3599 rptr = dtrace_loadptr(baddr +
3600 offsetof(mblk_t, b_rptr));
3603 *flags |= CPU_DTRACE_BADADDR;
3604 *illval = tupregs[0].dttk_value;
3608 daddr = dtrace_loadptr(baddr +
3609 offsetof(mblk_t, b_datap));
3611 baddr = dtrace_loadptr(baddr +
3612 offsetof(mblk_t, b_cont));
3615 * We want to prevent against denial-of-service here,
3616 * so we're only going to search the list for
3617 * dtrace_msgdsize_max mblks.
3619 if (cont++ > dtrace_msgdsize_max) {
3620 *flags |= CPU_DTRACE_ILLOP;
3624 if (subr == DIF_SUBR_MSGDSIZE) {
3625 if (dtrace_load8(daddr +
3626 offsetof(dblk_t, db_type)) != M_DATA)
3630 count += wptr - rptr;
3633 if (!(*flags & CPU_DTRACE_FAULT))
3640 case DIF_SUBR_PROGENYOF: {
3641 pid_t pid = tupregs[0].dttk_value;
3645 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3647 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3649 if (p->p_pidp->pid_id == pid) {
3651 if (p->p_pid == pid) {
3658 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3664 case DIF_SUBR_SPECULATION:
3665 regs[rd] = dtrace_speculation(state);
3668 case DIF_SUBR_COPYOUT: {
3669 uintptr_t kaddr = tupregs[0].dttk_value;
3670 uintptr_t uaddr = tupregs[1].dttk_value;
3671 uint64_t size = tupregs[2].dttk_value;
3673 if (!dtrace_destructive_disallow &&
3674 dtrace_priv_proc_control(state) &&
3675 !dtrace_istoxic(kaddr, size)) {
3676 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3677 dtrace_copyout(kaddr, uaddr, size, flags);
3678 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3683 case DIF_SUBR_COPYOUTSTR: {
3684 uintptr_t kaddr = tupregs[0].dttk_value;
3685 uintptr_t uaddr = tupregs[1].dttk_value;
3686 uint64_t size = tupregs[2].dttk_value;
3688 if (!dtrace_destructive_disallow &&
3689 dtrace_priv_proc_control(state) &&
3690 !dtrace_istoxic(kaddr, size)) {
3691 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3692 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3693 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3698 case DIF_SUBR_STRLEN: {
3700 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3701 sz = dtrace_strlen((char *)addr,
3702 state->dts_options[DTRACEOPT_STRSIZE]);
3704 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3714 case DIF_SUBR_STRCHR:
3715 case DIF_SUBR_STRRCHR: {
3717 * We're going to iterate over the string looking for the
3718 * specified character. We will iterate until we have reached
3719 * the string length or we have found the character. If this
3720 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3721 * of the specified character instead of the first.
3723 uintptr_t saddr = tupregs[0].dttk_value;
3724 uintptr_t addr = tupregs[0].dttk_value;
3725 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3726 char c, target = (char)tupregs[1].dttk_value;
3728 for (regs[rd] = 0; addr < limit; addr++) {
3729 if ((c = dtrace_load8(addr)) == target) {
3732 if (subr == DIF_SUBR_STRCHR)
3740 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3748 case DIF_SUBR_STRSTR:
3749 case DIF_SUBR_INDEX:
3750 case DIF_SUBR_RINDEX: {
3752 * We're going to iterate over the string looking for the
3753 * specified string. We will iterate until we have reached
3754 * the string length or we have found the string. (Yes, this
3755 * is done in the most naive way possible -- but considering
3756 * that the string we're searching for is likely to be
3757 * relatively short, the complexity of Rabin-Karp or similar
3758 * hardly seems merited.)
3760 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3761 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3762 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3763 size_t len = dtrace_strlen(addr, size);
3764 size_t sublen = dtrace_strlen(substr, size);
3765 char *limit = addr + len, *orig = addr;
3766 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3769 regs[rd] = notfound;
3771 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3776 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3783 * strstr() and index()/rindex() have similar semantics if
3784 * both strings are the empty string: strstr() returns a
3785 * pointer to the (empty) string, and index() and rindex()
3786 * both return index 0 (regardless of any position argument).
3788 if (sublen == 0 && len == 0) {
3789 if (subr == DIF_SUBR_STRSTR)
3790 regs[rd] = (uintptr_t)addr;
3796 if (subr != DIF_SUBR_STRSTR) {
3797 if (subr == DIF_SUBR_RINDEX) {
3804 * Both index() and rindex() take an optional position
3805 * argument that denotes the starting position.
3808 int64_t pos = (int64_t)tupregs[2].dttk_value;
3811 * If the position argument to index() is
3812 * negative, Perl implicitly clamps it at
3813 * zero. This semantic is a little surprising
3814 * given the special meaning of negative
3815 * positions to similar Perl functions like
3816 * substr(), but it appears to reflect a
3817 * notion that index() can start from a
3818 * negative index and increment its way up to
3819 * the string. Given this notion, Perl's
3820 * rindex() is at least self-consistent in
3821 * that it implicitly clamps positions greater
3822 * than the string length to be the string
3823 * length. Where Perl completely loses
3824 * coherence, however, is when the specified
3825 * substring is the empty string (""). In
3826 * this case, even if the position is
3827 * negative, rindex() returns 0 -- and even if
3828 * the position is greater than the length,
3829 * index() returns the string length. These
3830 * semantics violate the notion that index()
3831 * should never return a value less than the
3832 * specified position and that rindex() should
3833 * never return a value greater than the
3834 * specified position. (One assumes that
3835 * these semantics are artifacts of Perl's
3836 * implementation and not the results of
3837 * deliberate design -- it beggars belief that
3838 * even Larry Wall could desire such oddness.)
3839 * While in the abstract one would wish for
3840 * consistent position semantics across
3841 * substr(), index() and rindex() -- or at the
3842 * very least self-consistent position
3843 * semantics for index() and rindex() -- we
3844 * instead opt to keep with the extant Perl
3845 * semantics, in all their broken glory. (Do
3846 * we have more desire to maintain Perl's
3847 * semantics than Perl does? Probably.)
3849 if (subr == DIF_SUBR_RINDEX) {
3873 for (regs[rd] = notfound; addr != limit; addr += inc) {
3874 if (dtrace_strncmp(addr, substr, sublen) == 0) {
3875 if (subr != DIF_SUBR_STRSTR) {
3877 * As D index() and rindex() are
3878 * modeled on Perl (and not on awk),
3879 * we return a zero-based (and not a
3880 * one-based) index. (For you Perl
3881 * weenies: no, we're not going to add
3882 * $[ -- and shouldn't you be at a con
3885 regs[rd] = (uintptr_t)(addr - orig);
3889 ASSERT(subr == DIF_SUBR_STRSTR);
3890 regs[rd] = (uintptr_t)addr;
3898 case DIF_SUBR_STRTOK: {
3899 uintptr_t addr = tupregs[0].dttk_value;
3900 uintptr_t tokaddr = tupregs[1].dttk_value;
3901 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3902 uintptr_t limit, toklimit = tokaddr + size;
3903 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
3904 char *dest = (char *)mstate->dtms_scratch_ptr;
3908 * Check both the token buffer and (later) the input buffer,
3909 * since both could be non-scratch addresses.
3911 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3916 if (!DTRACE_INSCRATCH(mstate, size)) {
3917 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3924 * If the address specified is NULL, we use our saved
3925 * strtok pointer from the mstate. Note that this
3926 * means that the saved strtok pointer is _only_
3927 * valid within multiple enablings of the same probe --
3928 * it behaves like an implicit clause-local variable.
3930 addr = mstate->dtms_strtok;
3933 * If the user-specified address is non-NULL we must
3934 * access check it. This is the only time we have
3935 * a chance to do so, since this address may reside
3936 * in the string table of this clause-- future calls
3937 * (when we fetch addr from mstate->dtms_strtok)
3938 * would fail this access check.
3940 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3947 * First, zero the token map, and then process the token
3948 * string -- setting a bit in the map for every character
3949 * found in the token string.
3951 for (i = 0; i < sizeof (tokmap); i++)
3954 for (; tokaddr < toklimit; tokaddr++) {
3955 if ((c = dtrace_load8(tokaddr)) == '\0')
3958 ASSERT((c >> 3) < sizeof (tokmap));
3959 tokmap[c >> 3] |= (1 << (c & 0x7));
3962 for (limit = addr + size; addr < limit; addr++) {
3964 * We're looking for a character that is _not_ contained
3965 * in the token string.
3967 if ((c = dtrace_load8(addr)) == '\0')
3970 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3976 * We reached the end of the string without finding
3977 * any character that was not in the token string.
3978 * We return NULL in this case, and we set the saved
3979 * address to NULL as well.
3982 mstate->dtms_strtok = 0;
3987 * From here on, we're copying into the destination string.
3989 for (i = 0; addr < limit && i < size - 1; addr++) {
3990 if ((c = dtrace_load8(addr)) == '\0')
3993 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4002 regs[rd] = (uintptr_t)dest;
4003 mstate->dtms_scratch_ptr += size;
4004 mstate->dtms_strtok = addr;
4008 case DIF_SUBR_SUBSTR: {
4009 uintptr_t s = tupregs[0].dttk_value;
4010 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4011 char *d = (char *)mstate->dtms_scratch_ptr;
4012 int64_t index = (int64_t)tupregs[1].dttk_value;
4013 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4014 size_t len = dtrace_strlen((char *)s, size);
4017 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4022 if (!DTRACE_INSCRATCH(mstate, size)) {
4023 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4029 remaining = (int64_t)size;
4034 if (index < 0 && index + remaining > 0) {
4040 if (index >= len || index < 0) {
4042 } else if (remaining < 0) {
4043 remaining += len - index;
4044 } else if (index + remaining > size) {
4045 remaining = size - index;
4048 for (i = 0; i < remaining; i++) {
4049 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4055 mstate->dtms_scratch_ptr += size;
4056 regs[rd] = (uintptr_t)d;
4060 case DIF_SUBR_TOUPPER:
4061 case DIF_SUBR_TOLOWER: {
4062 uintptr_t s = tupregs[0].dttk_value;
4063 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4064 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4065 size_t len = dtrace_strlen((char *)s, size);
4066 char lower, upper, convert;
4069 if (subr == DIF_SUBR_TOUPPER) {
4079 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4084 if (!DTRACE_INSCRATCH(mstate, size)) {
4085 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4090 for (i = 0; i < size - 1; i++) {
4091 if ((c = dtrace_load8(s + i)) == '\0')
4094 if (c >= lower && c <= upper)
4095 c = convert + (c - lower);
4102 regs[rd] = (uintptr_t)dest;
4103 mstate->dtms_scratch_ptr += size;
4108 case DIF_SUBR_GETMAJOR:
4110 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4112 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4116 case DIF_SUBR_GETMINOR:
4118 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4120 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4124 case DIF_SUBR_DDI_PATHNAME: {
4126 * This one is a galactic mess. We are going to roughly
4127 * emulate ddi_pathname(), but it's made more complicated
4128 * by the fact that we (a) want to include the minor name and
4129 * (b) must proceed iteratively instead of recursively.
4131 uintptr_t dest = mstate->dtms_scratch_ptr;
4132 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4133 char *start = (char *)dest, *end = start + size - 1;
4134 uintptr_t daddr = tupregs[0].dttk_value;
4135 int64_t minor = (int64_t)tupregs[1].dttk_value;
4137 int i, len, depth = 0;
4140 * Due to all the pointer jumping we do and context we must
4141 * rely upon, we just mandate that the user must have kernel
4142 * read privileges to use this routine.
4144 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4145 *flags |= CPU_DTRACE_KPRIV;
4150 if (!DTRACE_INSCRATCH(mstate, size)) {
4151 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4159 * We want to have a name for the minor. In order to do this,
4160 * we need to walk the minor list from the devinfo. We want
4161 * to be sure that we don't infinitely walk a circular list,
4162 * so we check for circularity by sending a scout pointer
4163 * ahead two elements for every element that we iterate over;
4164 * if the list is circular, these will ultimately point to the
4165 * same element. You may recognize this little trick as the
4166 * answer to a stupid interview question -- one that always
4167 * seems to be asked by those who had to have it laboriously
4168 * explained to them, and who can't even concisely describe
4169 * the conditions under which one would be forced to resort to
4170 * this technique. Needless to say, those conditions are
4171 * found here -- and probably only here. Is this the only use
4172 * of this infamous trick in shipping, production code? If it
4173 * isn't, it probably should be...
4176 uintptr_t maddr = dtrace_loadptr(daddr +
4177 offsetof(struct dev_info, devi_minor));
4179 uintptr_t next = offsetof(struct ddi_minor_data, next);
4180 uintptr_t name = offsetof(struct ddi_minor_data,
4181 d_minor) + offsetof(struct ddi_minor, name);
4182 uintptr_t dev = offsetof(struct ddi_minor_data,
4183 d_minor) + offsetof(struct ddi_minor, dev);
4187 scout = dtrace_loadptr(maddr + next);
4189 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4192 m = dtrace_load64(maddr + dev) & MAXMIN64;
4194 m = dtrace_load32(maddr + dev) & MAXMIN;
4197 maddr = dtrace_loadptr(maddr + next);
4202 scout = dtrace_loadptr(scout + next);
4207 scout = dtrace_loadptr(scout + next);
4212 if (scout == maddr) {
4213 *flags |= CPU_DTRACE_ILLOP;
4221 * We have the minor data. Now we need to
4222 * copy the minor's name into the end of the
4225 s = (char *)dtrace_loadptr(maddr + name);
4226 len = dtrace_strlen(s, size);
4228 if (*flags & CPU_DTRACE_FAULT)
4232 if ((end -= (len + 1)) < start)
4238 for (i = 1; i <= len; i++)
4239 end[i] = dtrace_load8((uintptr_t)s++);
4244 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4245 ddi_node_state_t devi_state;
4247 devi_state = dtrace_load32(daddr +
4248 offsetof(struct dev_info, devi_node_state));
4250 if (*flags & CPU_DTRACE_FAULT)
4253 if (devi_state >= DS_INITIALIZED) {
4254 s = (char *)dtrace_loadptr(daddr +
4255 offsetof(struct dev_info, devi_addr));
4256 len = dtrace_strlen(s, size);
4258 if (*flags & CPU_DTRACE_FAULT)
4262 if ((end -= (len + 1)) < start)
4268 for (i = 1; i <= len; i++)
4269 end[i] = dtrace_load8((uintptr_t)s++);
4273 * Now for the node name...
4275 s = (char *)dtrace_loadptr(daddr +
4276 offsetof(struct dev_info, devi_node_name));
4278 daddr = dtrace_loadptr(daddr +
4279 offsetof(struct dev_info, devi_parent));
4282 * If our parent is NULL (that is, if we're the root
4283 * node), we're going to use the special path
4289 len = dtrace_strlen(s, size);
4290 if (*flags & CPU_DTRACE_FAULT)
4293 if ((end -= (len + 1)) < start)
4296 for (i = 1; i <= len; i++)
4297 end[i] = dtrace_load8((uintptr_t)s++);
4300 if (depth++ > dtrace_devdepth_max) {
4301 *flags |= CPU_DTRACE_ILLOP;
4307 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4310 regs[rd] = (uintptr_t)end;
4311 mstate->dtms_scratch_ptr += size;
4318 case DIF_SUBR_STRJOIN: {
4319 char *d = (char *)mstate->dtms_scratch_ptr;
4320 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4321 uintptr_t s1 = tupregs[0].dttk_value;
4322 uintptr_t s2 = tupregs[1].dttk_value;
4325 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4326 !dtrace_strcanload(s2, size, mstate, vstate)) {
4331 if (!DTRACE_INSCRATCH(mstate, size)) {
4332 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4339 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4344 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4352 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4357 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4362 mstate->dtms_scratch_ptr += i;
4363 regs[rd] = (uintptr_t)d;
4369 case DIF_SUBR_LLTOSTR: {
4370 int64_t i = (int64_t)tupregs[0].dttk_value;
4371 uint64_t val, digit;
4372 uint64_t size = 65; /* enough room for 2^64 in binary */
4373 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4377 if ((base = tupregs[1].dttk_value) <= 1 ||
4378 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4379 *flags |= CPU_DTRACE_ILLOP;
4384 val = (base == 10 && i < 0) ? i * -1 : i;
4386 if (!DTRACE_INSCRATCH(mstate, size)) {
4387 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4392 for (*end-- = '\0'; val; val /= base) {
4393 if ((digit = val % base) <= '9' - '0') {
4394 *end-- = '0' + digit;
4396 *end-- = 'a' + (digit - ('9' - '0') - 1);
4400 if (i == 0 && base == 16)
4406 if (i == 0 || base == 8 || base == 16)
4409 if (i < 0 && base == 10)
4412 regs[rd] = (uintptr_t)end + 1;
4413 mstate->dtms_scratch_ptr += size;
4417 case DIF_SUBR_HTONS:
4418 case DIF_SUBR_NTOHS:
4419 #if BYTE_ORDER == BIG_ENDIAN
4420 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4422 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4427 case DIF_SUBR_HTONL:
4428 case DIF_SUBR_NTOHL:
4429 #if BYTE_ORDER == BIG_ENDIAN
4430 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4432 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4437 case DIF_SUBR_HTONLL:
4438 case DIF_SUBR_NTOHLL:
4439 #if BYTE_ORDER == BIG_ENDIAN
4440 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4442 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4447 case DIF_SUBR_DIRNAME:
4448 case DIF_SUBR_BASENAME: {
4449 char *dest = (char *)mstate->dtms_scratch_ptr;
4450 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4451 uintptr_t src = tupregs[0].dttk_value;
4452 int i, j, len = dtrace_strlen((char *)src, size);
4453 int lastbase = -1, firstbase = -1, lastdir = -1;
4456 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4461 if (!DTRACE_INSCRATCH(mstate, size)) {
4462 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4468 * The basename and dirname for a zero-length string is
4473 src = (uintptr_t)".";
4477 * Start from the back of the string, moving back toward the
4478 * front until we see a character that isn't a slash. That
4479 * character is the last character in the basename.
4481 for (i = len - 1; i >= 0; i--) {
4482 if (dtrace_load8(src + i) != '/')
4490 * Starting from the last character in the basename, move
4491 * towards the front until we find a slash. The character
4492 * that we processed immediately before that is the first
4493 * character in the basename.
4495 for (; i >= 0; i--) {
4496 if (dtrace_load8(src + i) == '/')
4504 * Now keep going until we find a non-slash character. That
4505 * character is the last character in the dirname.
4507 for (; i >= 0; i--) {
4508 if (dtrace_load8(src + i) != '/')
4515 ASSERT(!(lastbase == -1 && firstbase != -1));
4516 ASSERT(!(firstbase == -1 && lastdir != -1));
4518 if (lastbase == -1) {
4520 * We didn't find a non-slash character. We know that
4521 * the length is non-zero, so the whole string must be
4522 * slashes. In either the dirname or the basename
4523 * case, we return '/'.
4525 ASSERT(firstbase == -1);
4526 firstbase = lastbase = lastdir = 0;
4529 if (firstbase == -1) {
4531 * The entire string consists only of a basename
4532 * component. If we're looking for dirname, we need
4533 * to change our string to be just "."; if we're
4534 * looking for a basename, we'll just set the first
4535 * character of the basename to be 0.
4537 if (subr == DIF_SUBR_DIRNAME) {
4538 ASSERT(lastdir == -1);
4539 src = (uintptr_t)".";
4546 if (subr == DIF_SUBR_DIRNAME) {
4547 if (lastdir == -1) {
4549 * We know that we have a slash in the name --
4550 * or lastdir would be set to 0, above. And
4551 * because lastdir is -1, we know that this
4552 * slash must be the first character. (That
4553 * is, the full string must be of the form
4554 * "/basename".) In this case, the last
4555 * character of the directory name is 0.
4563 ASSERT(subr == DIF_SUBR_BASENAME);
4564 ASSERT(firstbase != -1 && lastbase != -1);
4569 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4570 dest[j] = dtrace_load8(src + i);
4573 regs[rd] = (uintptr_t)dest;
4574 mstate->dtms_scratch_ptr += size;
4578 case DIF_SUBR_CLEANPATH: {
4579 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4580 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4581 uintptr_t src = tupregs[0].dttk_value;
4584 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4589 if (!DTRACE_INSCRATCH(mstate, size)) {
4590 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4596 * Move forward, loading each character.
4599 c = dtrace_load8(src + i++);
4601 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
4609 c = dtrace_load8(src + i++);
4613 * We have two slashes -- we can just advance
4614 * to the next character.
4621 * This is not "." and it's not ".." -- we can
4622 * just store the "/" and this character and
4630 c = dtrace_load8(src + i++);
4634 * This is a "/./" component. We're not going
4635 * to store anything in the destination buffer;
4636 * we're just going to go to the next component.
4643 * This is not ".." -- we can just store the
4644 * "/." and this character and continue
4653 c = dtrace_load8(src + i++);
4655 if (c != '/' && c != '\0') {
4657 * This is not ".." -- it's "..[mumble]".
4658 * We'll store the "/.." and this character
4659 * and continue processing.
4669 * This is "/../" or "/..\0". We need to back up
4670 * our destination pointer until we find a "/".
4673 while (j != 0 && dest[--j] != '/')
4678 } while (c != '\0');
4681 regs[rd] = (uintptr_t)dest;
4682 mstate->dtms_scratch_ptr += size;
4686 case DIF_SUBR_INET_NTOA:
4687 case DIF_SUBR_INET_NTOA6:
4688 case DIF_SUBR_INET_NTOP: {
4693 if (subr == DIF_SUBR_INET_NTOP) {
4694 af = (int)tupregs[0].dttk_value;
4697 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4701 if (af == AF_INET) {
4706 * Safely load the IPv4 address.
4708 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4711 * Check an IPv4 string will fit in scratch.
4713 size = INET_ADDRSTRLEN;
4714 if (!DTRACE_INSCRATCH(mstate, size)) {
4715 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4719 base = (char *)mstate->dtms_scratch_ptr;
4720 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4723 * Stringify as a dotted decimal quad.
4726 ptr8 = (uint8_t *)&ip4;
4727 for (i = 3; i >= 0; i--) {
4733 for (; val; val /= 10) {
4734 *end-- = '0' + (val % 10);
4741 ASSERT(end + 1 >= base);
4743 } else if (af == AF_INET6) {
4744 struct in6_addr ip6;
4745 int firstzero, tryzero, numzero, v6end;
4747 const char digits[] = "0123456789abcdef";
4750 * Stringify using RFC 1884 convention 2 - 16 bit
4751 * hexadecimal values with a zero-run compression.
4752 * Lower case hexadecimal digits are used.
4753 * eg, fe80::214:4fff:fe0b:76c8.
4754 * The IPv4 embedded form is returned for inet_ntop,
4755 * just the IPv4 string is returned for inet_ntoa6.
4759 * Safely load the IPv6 address.
4762 (void *)(uintptr_t)tupregs[argi].dttk_value,
4763 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4766 * Check an IPv6 string will fit in scratch.
4768 size = INET6_ADDRSTRLEN;
4769 if (!DTRACE_INSCRATCH(mstate, size)) {
4770 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4774 base = (char *)mstate->dtms_scratch_ptr;
4775 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4779 * Find the longest run of 16 bit zero values
4780 * for the single allowed zero compression - "::".
4785 for (i = 0; i < sizeof (struct in6_addr); i++) {
4787 if (ip6._S6_un._S6_u8[i] == 0 &&
4789 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4791 tryzero == -1 && i % 2 == 0) {
4796 if (tryzero != -1 &&
4798 (ip6._S6_un._S6_u8[i] != 0 ||
4800 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
4802 i == sizeof (struct in6_addr) - 1)) {
4804 if (i - tryzero <= numzero) {
4809 firstzero = tryzero;
4810 numzero = i - i % 2 - tryzero;
4814 if (ip6._S6_un._S6_u8[i] == 0 &&
4816 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4818 i == sizeof (struct in6_addr) - 1)
4822 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4825 * Check for an IPv4 embedded address.
4827 v6end = sizeof (struct in6_addr) - 2;
4828 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4829 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4830 for (i = sizeof (struct in6_addr) - 1;
4831 i >= DTRACE_V4MAPPED_OFFSET; i--) {
4832 ASSERT(end >= base);
4835 val = ip6._S6_un._S6_u8[i];
4837 val = ip6.__u6_addr.__u6_addr8[i];
4843 for (; val; val /= 10) {
4844 *end-- = '0' + val % 10;
4848 if (i > DTRACE_V4MAPPED_OFFSET)
4852 if (subr == DIF_SUBR_INET_NTOA6)
4856 * Set v6end to skip the IPv4 address that
4857 * we have already stringified.
4863 * Build the IPv6 string by working through the
4864 * address in reverse.
4866 for (i = v6end; i >= 0; i -= 2) {
4867 ASSERT(end >= base);
4869 if (i == firstzero + numzero - 2) {
4876 if (i < 14 && i != firstzero - 2)
4880 val = (ip6._S6_un._S6_u8[i] << 8) +
4881 ip6._S6_un._S6_u8[i + 1];
4883 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
4884 ip6.__u6_addr.__u6_addr8[i + 1];
4890 for (; val; val /= 16) {
4891 *end-- = digits[val % 16];
4895 ASSERT(end + 1 >= base);
4899 * The user didn't use AH_INET or AH_INET6.
4901 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4906 inetout: regs[rd] = (uintptr_t)end + 1;
4907 mstate->dtms_scratch_ptr += size;
4911 case DIF_SUBR_MEMREF: {
4912 uintptr_t size = 2 * sizeof(uintptr_t);
4913 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4914 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
4916 /* address and length */
4917 memref[0] = tupregs[0].dttk_value;
4918 memref[1] = tupregs[1].dttk_value;
4920 regs[rd] = (uintptr_t) memref;
4921 mstate->dtms_scratch_ptr += scratch_size;
4925 case DIF_SUBR_TYPEREF: {
4926 uintptr_t size = 4 * sizeof(uintptr_t);
4927 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4928 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
4930 /* address, num_elements, type_str, type_len */
4931 typeref[0] = tupregs[0].dttk_value;
4932 typeref[1] = tupregs[1].dttk_value;
4933 typeref[2] = tupregs[2].dttk_value;
4934 typeref[3] = tupregs[3].dttk_value;
4936 regs[rd] = (uintptr_t) typeref;
4937 mstate->dtms_scratch_ptr += scratch_size;
4944 * Emulate the execution of DTrace IR instructions specified by the given
4945 * DIF object. This function is deliberately void of assertions as all of
4946 * the necessary checks are handled by a call to dtrace_difo_validate().
4949 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4950 dtrace_vstate_t *vstate, dtrace_state_t *state)
4952 const dif_instr_t *text = difo->dtdo_buf;
4953 const uint_t textlen = difo->dtdo_len;
4954 const char *strtab = difo->dtdo_strtab;
4955 const uint64_t *inttab = difo->dtdo_inttab;
4958 dtrace_statvar_t *svar;
4959 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4961 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4962 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4964 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4965 uint64_t regs[DIF_DIR_NREGS];
4968 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4970 uint_t pc = 0, id, opc = 0;
4976 * We stash the current DIF object into the machine state: we need it
4977 * for subsequent access checking.
4979 mstate->dtms_difo = difo;
4981 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4983 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4987 r1 = DIF_INSTR_R1(instr);
4988 r2 = DIF_INSTR_R2(instr);
4989 rd = DIF_INSTR_RD(instr);
4991 switch (DIF_INSTR_OP(instr)) {
4993 regs[rd] = regs[r1] | regs[r2];
4996 regs[rd] = regs[r1] ^ regs[r2];
4999 regs[rd] = regs[r1] & regs[r2];
5002 regs[rd] = regs[r1] << regs[r2];
5005 regs[rd] = regs[r1] >> regs[r2];
5008 regs[rd] = regs[r1] - regs[r2];
5011 regs[rd] = regs[r1] + regs[r2];
5014 regs[rd] = regs[r1] * regs[r2];
5017 if (regs[r2] == 0) {
5019 *flags |= CPU_DTRACE_DIVZERO;
5021 regs[rd] = (int64_t)regs[r1] /
5027 if (regs[r2] == 0) {
5029 *flags |= CPU_DTRACE_DIVZERO;
5031 regs[rd] = regs[r1] / regs[r2];
5036 if (regs[r2] == 0) {
5038 *flags |= CPU_DTRACE_DIVZERO;
5040 regs[rd] = (int64_t)regs[r1] %
5046 if (regs[r2] == 0) {
5048 *flags |= CPU_DTRACE_DIVZERO;
5050 regs[rd] = regs[r1] % regs[r2];
5055 regs[rd] = ~regs[r1];
5058 regs[rd] = regs[r1];
5061 cc_r = regs[r1] - regs[r2];
5065 cc_c = regs[r1] < regs[r2];
5068 cc_n = cc_v = cc_c = 0;
5069 cc_z = regs[r1] == 0;
5072 pc = DIF_INSTR_LABEL(instr);
5076 pc = DIF_INSTR_LABEL(instr);
5080 pc = DIF_INSTR_LABEL(instr);
5083 if ((cc_z | (cc_n ^ cc_v)) == 0)
5084 pc = DIF_INSTR_LABEL(instr);
5087 if ((cc_c | cc_z) == 0)
5088 pc = DIF_INSTR_LABEL(instr);
5091 if ((cc_n ^ cc_v) == 0)
5092 pc = DIF_INSTR_LABEL(instr);
5096 pc = DIF_INSTR_LABEL(instr);
5100 pc = DIF_INSTR_LABEL(instr);
5104 pc = DIF_INSTR_LABEL(instr);
5107 if (cc_z | (cc_n ^ cc_v))
5108 pc = DIF_INSTR_LABEL(instr);
5112 pc = DIF_INSTR_LABEL(instr);
5115 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5116 *flags |= CPU_DTRACE_KPRIV;
5122 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5125 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5126 *flags |= CPU_DTRACE_KPRIV;
5132 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5135 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5136 *flags |= CPU_DTRACE_KPRIV;
5142 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5145 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5146 *flags |= CPU_DTRACE_KPRIV;
5152 regs[rd] = dtrace_load8(regs[r1]);
5155 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5156 *flags |= CPU_DTRACE_KPRIV;
5162 regs[rd] = dtrace_load16(regs[r1]);
5165 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5166 *flags |= CPU_DTRACE_KPRIV;
5172 regs[rd] = dtrace_load32(regs[r1]);
5175 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5176 *flags |= CPU_DTRACE_KPRIV;
5182 regs[rd] = dtrace_load64(regs[r1]);
5186 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5189 regs[rd] = (int16_t)
5190 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5193 regs[rd] = (int32_t)
5194 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5198 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5202 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5206 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5210 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5219 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5222 regs[rd] = (uint64_t)(uintptr_t)
5223 (strtab + DIF_INSTR_STRING(instr));
5226 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5227 uintptr_t s1 = regs[r1];
5228 uintptr_t s2 = regs[r2];
5231 !dtrace_strcanload(s1, sz, mstate, vstate))
5234 !dtrace_strcanload(s2, sz, mstate, vstate))
5237 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5245 regs[rd] = dtrace_dif_variable(mstate, state,
5249 id = DIF_INSTR_VAR(instr);
5251 if (id >= DIF_VAR_OTHER_UBASE) {
5254 id -= DIF_VAR_OTHER_UBASE;
5255 svar = vstate->dtvs_globals[id];
5256 ASSERT(svar != NULL);
5257 v = &svar->dtsv_var;
5259 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5260 regs[rd] = svar->dtsv_data;
5264 a = (uintptr_t)svar->dtsv_data;
5266 if (*(uint8_t *)a == UINT8_MAX) {
5268 * If the 0th byte is set to UINT8_MAX
5269 * then this is to be treated as a
5270 * reference to a NULL variable.
5274 regs[rd] = a + sizeof (uint64_t);
5280 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5284 id = DIF_INSTR_VAR(instr);
5286 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5287 id -= DIF_VAR_OTHER_UBASE;
5289 svar = vstate->dtvs_globals[id];
5290 ASSERT(svar != NULL);
5291 v = &svar->dtsv_var;
5293 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5294 uintptr_t a = (uintptr_t)svar->dtsv_data;
5297 ASSERT(svar->dtsv_size != 0);
5299 if (regs[rd] == 0) {
5300 *(uint8_t *)a = UINT8_MAX;
5304 a += sizeof (uint64_t);
5306 if (!dtrace_vcanload(
5307 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5311 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5312 (void *)a, &v->dtdv_type);
5316 svar->dtsv_data = regs[rd];
5321 * There are no DTrace built-in thread-local arrays at
5322 * present. This opcode is saved for future work.
5324 *flags |= CPU_DTRACE_ILLOP;
5329 id = DIF_INSTR_VAR(instr);
5331 if (id < DIF_VAR_OTHER_UBASE) {
5333 * For now, this has no meaning.
5339 id -= DIF_VAR_OTHER_UBASE;
5341 ASSERT(id < vstate->dtvs_nlocals);
5342 ASSERT(vstate->dtvs_locals != NULL);
5344 svar = vstate->dtvs_locals[id];
5345 ASSERT(svar != NULL);
5346 v = &svar->dtsv_var;
5348 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5349 uintptr_t a = (uintptr_t)svar->dtsv_data;
5350 size_t sz = v->dtdv_type.dtdt_size;
5352 sz += sizeof (uint64_t);
5353 ASSERT(svar->dtsv_size == NCPU * sz);
5356 if (*(uint8_t *)a == UINT8_MAX) {
5358 * If the 0th byte is set to UINT8_MAX
5359 * then this is to be treated as a
5360 * reference to a NULL variable.
5364 regs[rd] = a + sizeof (uint64_t);
5370 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5371 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5372 regs[rd] = tmp[curcpu];
5376 id = DIF_INSTR_VAR(instr);
5378 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5379 id -= DIF_VAR_OTHER_UBASE;
5380 ASSERT(id < vstate->dtvs_nlocals);
5382 ASSERT(vstate->dtvs_locals != NULL);
5383 svar = vstate->dtvs_locals[id];
5384 ASSERT(svar != NULL);
5385 v = &svar->dtsv_var;
5387 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5388 uintptr_t a = (uintptr_t)svar->dtsv_data;
5389 size_t sz = v->dtdv_type.dtdt_size;
5391 sz += sizeof (uint64_t);
5392 ASSERT(svar->dtsv_size == NCPU * sz);
5395 if (regs[rd] == 0) {
5396 *(uint8_t *)a = UINT8_MAX;
5400 a += sizeof (uint64_t);
5403 if (!dtrace_vcanload(
5404 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5408 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5409 (void *)a, &v->dtdv_type);
5413 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5414 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5415 tmp[curcpu] = regs[rd];
5419 dtrace_dynvar_t *dvar;
5422 id = DIF_INSTR_VAR(instr);
5423 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5424 id -= DIF_VAR_OTHER_UBASE;
5425 v = &vstate->dtvs_tlocals[id];
5427 key = &tupregs[DIF_DTR_NREGS];
5428 key[0].dttk_value = (uint64_t)id;
5429 key[0].dttk_size = 0;
5430 DTRACE_TLS_THRKEY(key[1].dttk_value);
5431 key[1].dttk_size = 0;
5433 dvar = dtrace_dynvar(dstate, 2, key,
5434 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5442 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5443 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5445 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5452 dtrace_dynvar_t *dvar;
5455 id = DIF_INSTR_VAR(instr);
5456 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5457 id -= DIF_VAR_OTHER_UBASE;
5459 key = &tupregs[DIF_DTR_NREGS];
5460 key[0].dttk_value = (uint64_t)id;
5461 key[0].dttk_size = 0;
5462 DTRACE_TLS_THRKEY(key[1].dttk_value);
5463 key[1].dttk_size = 0;
5464 v = &vstate->dtvs_tlocals[id];
5466 dvar = dtrace_dynvar(dstate, 2, key,
5467 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5468 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5469 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5470 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5473 * Given that we're storing to thread-local data,
5474 * we need to flush our predicate cache.
5476 curthread->t_predcache = 0;
5481 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5482 if (!dtrace_vcanload(
5483 (void *)(uintptr_t)regs[rd],
5484 &v->dtdv_type, mstate, vstate))
5487 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5488 dvar->dtdv_data, &v->dtdv_type);
5490 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5497 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5501 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5502 regs, tupregs, ttop, mstate, state);
5506 if (ttop == DIF_DTR_NREGS) {
5507 *flags |= CPU_DTRACE_TUPOFLOW;
5511 if (r1 == DIF_TYPE_STRING) {
5513 * If this is a string type and the size is 0,
5514 * we'll use the system-wide default string
5515 * size. Note that we are _not_ looking at
5516 * the value of the DTRACEOPT_STRSIZE option;
5517 * had this been set, we would expect to have
5518 * a non-zero size value in the "pushtr".
5520 tupregs[ttop].dttk_size =
5521 dtrace_strlen((char *)(uintptr_t)regs[rd],
5522 regs[r2] ? regs[r2] :
5523 dtrace_strsize_default) + 1;
5525 tupregs[ttop].dttk_size = regs[r2];
5528 tupregs[ttop++].dttk_value = regs[rd];
5532 if (ttop == DIF_DTR_NREGS) {
5533 *flags |= CPU_DTRACE_TUPOFLOW;
5537 tupregs[ttop].dttk_value = regs[rd];
5538 tupregs[ttop++].dttk_size = 0;
5546 case DIF_OP_FLUSHTS:
5551 case DIF_OP_LDTAA: {
5552 dtrace_dynvar_t *dvar;
5553 dtrace_key_t *key = tupregs;
5554 uint_t nkeys = ttop;
5556 id = DIF_INSTR_VAR(instr);
5557 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5558 id -= DIF_VAR_OTHER_UBASE;
5560 key[nkeys].dttk_value = (uint64_t)id;
5561 key[nkeys++].dttk_size = 0;
5563 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5564 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5565 key[nkeys++].dttk_size = 0;
5566 v = &vstate->dtvs_tlocals[id];
5568 v = &vstate->dtvs_globals[id]->dtsv_var;
5571 dvar = dtrace_dynvar(dstate, nkeys, key,
5572 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5573 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5574 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5581 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5582 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5584 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5591 case DIF_OP_STTAA: {
5592 dtrace_dynvar_t *dvar;
5593 dtrace_key_t *key = tupregs;
5594 uint_t nkeys = ttop;
5596 id = DIF_INSTR_VAR(instr);
5597 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5598 id -= DIF_VAR_OTHER_UBASE;
5600 key[nkeys].dttk_value = (uint64_t)id;
5601 key[nkeys++].dttk_size = 0;
5603 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5604 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5605 key[nkeys++].dttk_size = 0;
5606 v = &vstate->dtvs_tlocals[id];
5608 v = &vstate->dtvs_globals[id]->dtsv_var;
5611 dvar = dtrace_dynvar(dstate, nkeys, key,
5612 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5613 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5614 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5615 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5620 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5621 if (!dtrace_vcanload(
5622 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5626 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5627 dvar->dtdv_data, &v->dtdv_type);
5629 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5635 case DIF_OP_ALLOCS: {
5636 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5637 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5640 * Rounding up the user allocation size could have
5641 * overflowed large, bogus allocations (like -1ULL) to
5644 if (size < regs[r1] ||
5645 !DTRACE_INSCRATCH(mstate, size)) {
5646 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5651 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5652 mstate->dtms_scratch_ptr += size;
5658 if (!dtrace_canstore(regs[rd], regs[r2],
5660 *flags |= CPU_DTRACE_BADADDR;
5665 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5668 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5669 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5673 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5674 *flags |= CPU_DTRACE_BADADDR;
5678 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5682 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5683 *flags |= CPU_DTRACE_BADADDR;
5688 *flags |= CPU_DTRACE_BADALIGN;
5692 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5696 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5697 *flags |= CPU_DTRACE_BADADDR;
5702 *flags |= CPU_DTRACE_BADALIGN;
5706 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5710 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5711 *flags |= CPU_DTRACE_BADADDR;
5716 *flags |= CPU_DTRACE_BADALIGN;
5720 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5725 if (!(*flags & CPU_DTRACE_FAULT))
5728 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5729 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5735 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5737 dtrace_probe_t *probe = ecb->dte_probe;
5738 dtrace_provider_t *prov = probe->dtpr_provider;
5739 char c[DTRACE_FULLNAMELEN + 80], *str;
5740 char *msg = "dtrace: breakpoint action at probe ";
5741 char *ecbmsg = " (ecb ";
5742 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5743 uintptr_t val = (uintptr_t)ecb;
5744 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5746 if (dtrace_destructive_disallow)
5750 * It's impossible to be taking action on the NULL probe.
5752 ASSERT(probe != NULL);
5755 * This is a poor man's (destitute man's?) sprintf(): we want to
5756 * print the provider name, module name, function name and name of
5757 * the probe, along with the hex address of the ECB with the breakpoint
5758 * action -- all of which we must place in the character buffer by
5761 while (*msg != '\0')
5764 for (str = prov->dtpv_name; *str != '\0'; str++)
5768 for (str = probe->dtpr_mod; *str != '\0'; str++)
5772 for (str = probe->dtpr_func; *str != '\0'; str++)
5776 for (str = probe->dtpr_name; *str != '\0'; str++)
5779 while (*ecbmsg != '\0')
5782 while (shift >= 0) {
5783 mask = (uintptr_t)0xf << shift;
5785 if (val >= ((uintptr_t)1 << shift))
5786 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5796 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
5801 dtrace_action_panic(dtrace_ecb_t *ecb)
5803 dtrace_probe_t *probe = ecb->dte_probe;
5806 * It's impossible to be taking action on the NULL probe.
5808 ASSERT(probe != NULL);
5810 if (dtrace_destructive_disallow)
5813 if (dtrace_panicked != NULL)
5816 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5820 * We won the right to panic. (We want to be sure that only one
5821 * thread calls panic() from dtrace_probe(), and that panic() is
5822 * called exactly once.)
5824 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5825 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5826 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5830 dtrace_action_raise(uint64_t sig)
5832 if (dtrace_destructive_disallow)
5836 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5842 * raise() has a queue depth of 1 -- we ignore all subsequent
5843 * invocations of the raise() action.
5845 if (curthread->t_dtrace_sig == 0)
5846 curthread->t_dtrace_sig = (uint8_t)sig;
5848 curthread->t_sig_check = 1;
5851 struct proc *p = curproc;
5853 kern_psignal(p, sig);
5859 dtrace_action_stop(void)
5861 if (dtrace_destructive_disallow)
5865 if (!curthread->t_dtrace_stop) {
5866 curthread->t_dtrace_stop = 1;
5867 curthread->t_sig_check = 1;
5871 struct proc *p = curproc;
5873 kern_psignal(p, SIGSTOP);
5879 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5882 volatile uint16_t *flags;
5886 cpu_t *cpu = &solaris_cpu[curcpu];
5889 if (dtrace_destructive_disallow)
5892 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5894 now = dtrace_gethrtime();
5896 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5898 * We need to advance the mark to the current time.
5900 cpu->cpu_dtrace_chillmark = now;
5901 cpu->cpu_dtrace_chilled = 0;
5905 * Now check to see if the requested chill time would take us over
5906 * the maximum amount of time allowed in the chill interval. (Or
5907 * worse, if the calculation itself induces overflow.)
5909 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5910 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5911 *flags |= CPU_DTRACE_ILLOP;
5915 while (dtrace_gethrtime() - now < val)
5919 * Normally, we assure that the value of the variable "timestamp" does
5920 * not change within an ECB. The presence of chill() represents an
5921 * exception to this rule, however.
5923 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5924 cpu->cpu_dtrace_chilled += val;
5928 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5929 uint64_t *buf, uint64_t arg)
5931 int nframes = DTRACE_USTACK_NFRAMES(arg);
5932 int strsize = DTRACE_USTACK_STRSIZE(arg);
5933 uint64_t *pcs = &buf[1], *fps;
5934 char *str = (char *)&pcs[nframes];
5935 int size, offs = 0, i, j;
5936 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5937 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5941 * Should be taking a faster path if string space has not been
5944 ASSERT(strsize != 0);
5947 * We will first allocate some temporary space for the frame pointers.
5949 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5950 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5951 (nframes * sizeof (uint64_t));
5953 if (!DTRACE_INSCRATCH(mstate, size)) {
5955 * Not enough room for our frame pointers -- need to indicate
5956 * that we ran out of scratch space.
5958 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5962 mstate->dtms_scratch_ptr += size;
5963 saved = mstate->dtms_scratch_ptr;
5966 * Now get a stack with both program counters and frame pointers.
5968 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5969 dtrace_getufpstack(buf, fps, nframes + 1);
5970 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5973 * If that faulted, we're cooked.
5975 if (*flags & CPU_DTRACE_FAULT)
5979 * Now we want to walk up the stack, calling the USTACK helper. For
5980 * each iteration, we restore the scratch pointer.
5982 for (i = 0; i < nframes; i++) {
5983 mstate->dtms_scratch_ptr = saved;
5985 if (offs >= strsize)
5988 sym = (char *)(uintptr_t)dtrace_helper(
5989 DTRACE_HELPER_ACTION_USTACK,
5990 mstate, state, pcs[i], fps[i]);
5993 * If we faulted while running the helper, we're going to
5994 * clear the fault and null out the corresponding string.
5996 if (*flags & CPU_DTRACE_FAULT) {
5997 *flags &= ~CPU_DTRACE_FAULT;
6007 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6010 * Now copy in the string that the helper returned to us.
6012 for (j = 0; offs + j < strsize; j++) {
6013 if ((str[offs + j] = sym[j]) == '\0')
6017 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6022 if (offs >= strsize) {
6024 * If we didn't have room for all of the strings, we don't
6025 * abort processing -- this needn't be a fatal error -- but we
6026 * still want to increment a counter (dts_stkstroverflows) to
6027 * allow this condition to be warned about. (If this is from
6028 * a jstack() action, it is easily tuned via jstackstrsize.)
6030 dtrace_error(&state->dts_stkstroverflows);
6033 while (offs < strsize)
6037 mstate->dtms_scratch_ptr = old;
6041 * If you're looking for the epicenter of DTrace, you just found it. This
6042 * is the function called by the provider to fire a probe -- from which all
6043 * subsequent probe-context DTrace activity emanates.
6046 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6047 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6049 processorid_t cpuid;
6050 dtrace_icookie_t cookie;
6051 dtrace_probe_t *probe;
6052 dtrace_mstate_t mstate;
6054 dtrace_action_t *act;
6058 volatile uint16_t *flags;
6061 if (panicstr != NULL)
6066 * Kick out immediately if this CPU is still being born (in which case
6067 * curthread will be set to -1) or the current thread can't allow
6068 * probes in its current context.
6070 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6074 cookie = dtrace_interrupt_disable();
6075 probe = dtrace_probes[id - 1];
6077 onintr = CPU_ON_INTR(CPU);
6079 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6080 probe->dtpr_predcache == curthread->t_predcache) {
6082 * We have hit in the predicate cache; we know that
6083 * this predicate would evaluate to be false.
6085 dtrace_interrupt_enable(cookie);
6090 if (panic_quiesce) {
6092 if (panicstr != NULL) {
6095 * We don't trace anything if we're panicking.
6097 dtrace_interrupt_enable(cookie);
6101 now = dtrace_gethrtime();
6102 vtime = dtrace_vtime_references != 0;
6104 if (vtime && curthread->t_dtrace_start)
6105 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6107 mstate.dtms_difo = NULL;
6108 mstate.dtms_probe = probe;
6109 mstate.dtms_strtok = 0;
6110 mstate.dtms_arg[0] = arg0;
6111 mstate.dtms_arg[1] = arg1;
6112 mstate.dtms_arg[2] = arg2;
6113 mstate.dtms_arg[3] = arg3;
6114 mstate.dtms_arg[4] = arg4;
6116 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6118 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6119 dtrace_predicate_t *pred = ecb->dte_predicate;
6120 dtrace_state_t *state = ecb->dte_state;
6121 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6122 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6123 dtrace_vstate_t *vstate = &state->dts_vstate;
6124 dtrace_provider_t *prov = probe->dtpr_provider;
6125 uint64_t tracememsize = 0;
6130 * A little subtlety with the following (seemingly innocuous)
6131 * declaration of the automatic 'val': by looking at the
6132 * code, you might think that it could be declared in the
6133 * action processing loop, below. (That is, it's only used in
6134 * the action processing loop.) However, it must be declared
6135 * out of that scope because in the case of DIF expression
6136 * arguments to aggregating actions, one iteration of the
6137 * action loop will use the last iteration's value.
6141 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6142 *flags &= ~CPU_DTRACE_ERROR;
6144 if (prov == dtrace_provider) {
6146 * If dtrace itself is the provider of this probe,
6147 * we're only going to continue processing the ECB if
6148 * arg0 (the dtrace_state_t) is equal to the ECB's
6149 * creating state. (This prevents disjoint consumers
6150 * from seeing one another's metaprobes.)
6152 if (arg0 != (uint64_t)(uintptr_t)state)
6156 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6158 * We're not currently active. If our provider isn't
6159 * the dtrace pseudo provider, we're not interested.
6161 if (prov != dtrace_provider)
6165 * Now we must further check if we are in the BEGIN
6166 * probe. If we are, we will only continue processing
6167 * if we're still in WARMUP -- if one BEGIN enabling
6168 * has invoked the exit() action, we don't want to
6169 * evaluate subsequent BEGIN enablings.
6171 if (probe->dtpr_id == dtrace_probeid_begin &&
6172 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6173 ASSERT(state->dts_activity ==
6174 DTRACE_ACTIVITY_DRAINING);
6179 if (ecb->dte_cond) {
6181 * If the dte_cond bits indicate that this
6182 * consumer is only allowed to see user-mode firings
6183 * of this probe, call the provider's dtps_usermode()
6184 * entry point to check that the probe was fired
6185 * while in a user context. Skip this ECB if that's
6188 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6189 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6190 probe->dtpr_id, probe->dtpr_arg) == 0)
6195 * This is more subtle than it looks. We have to be
6196 * absolutely certain that CRED() isn't going to
6197 * change out from under us so it's only legit to
6198 * examine that structure if we're in constrained
6199 * situations. Currently, the only times we'll this
6200 * check is if a non-super-user has enabled the
6201 * profile or syscall providers -- providers that
6202 * allow visibility of all processes. For the
6203 * profile case, the check above will ensure that
6204 * we're examining a user context.
6206 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6209 ecb->dte_state->dts_cred.dcr_cred;
6212 ASSERT(s_cr != NULL);
6214 if ((cr = CRED()) == NULL ||
6215 s_cr->cr_uid != cr->cr_uid ||
6216 s_cr->cr_uid != cr->cr_ruid ||
6217 s_cr->cr_uid != cr->cr_suid ||
6218 s_cr->cr_gid != cr->cr_gid ||
6219 s_cr->cr_gid != cr->cr_rgid ||
6220 s_cr->cr_gid != cr->cr_sgid ||
6221 (proc = ttoproc(curthread)) == NULL ||
6222 (proc->p_flag & SNOCD))
6226 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6229 ecb->dte_state->dts_cred.dcr_cred;
6231 ASSERT(s_cr != NULL);
6233 if ((cr = CRED()) == NULL ||
6234 s_cr->cr_zone->zone_id !=
6235 cr->cr_zone->zone_id)
6241 if (now - state->dts_alive > dtrace_deadman_timeout) {
6243 * We seem to be dead. Unless we (a) have kernel
6244 * destructive permissions (b) have explicitly enabled
6245 * destructive actions and (c) destructive actions have
6246 * not been disabled, we're going to transition into
6247 * the KILLED state, from which no further processing
6248 * on this state will be performed.
6250 if (!dtrace_priv_kernel_destructive(state) ||
6251 !state->dts_cred.dcr_destructive ||
6252 dtrace_destructive_disallow) {
6253 void *activity = &state->dts_activity;
6254 dtrace_activity_t current;
6257 current = state->dts_activity;
6258 } while (dtrace_cas32(activity, current,
6259 DTRACE_ACTIVITY_KILLED) != current);
6265 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6266 ecb->dte_alignment, state, &mstate)) < 0)
6269 tomax = buf->dtb_tomax;
6270 ASSERT(tomax != NULL);
6272 if (ecb->dte_size != 0) {
6273 dtrace_rechdr_t dtrh;
6274 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6275 mstate.dtms_timestamp = dtrace_gethrtime();
6276 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6278 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6279 dtrh.dtrh_epid = ecb->dte_epid;
6280 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6281 mstate.dtms_timestamp);
6282 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6285 mstate.dtms_epid = ecb->dte_epid;
6286 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6288 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6289 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6291 mstate.dtms_access = 0;
6294 dtrace_difo_t *dp = pred->dtp_difo;
6297 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6299 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6300 dtrace_cacheid_t cid = probe->dtpr_predcache;
6302 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6304 * Update the predicate cache...
6306 ASSERT(cid == pred->dtp_cacheid);
6307 curthread->t_predcache = cid;
6314 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6315 act != NULL; act = act->dta_next) {
6318 dtrace_recdesc_t *rec = &act->dta_rec;
6320 size = rec->dtrd_size;
6321 valoffs = offs + rec->dtrd_offset;
6323 if (DTRACEACT_ISAGG(act->dta_kind)) {
6325 dtrace_aggregation_t *agg;
6327 agg = (dtrace_aggregation_t *)act;
6329 if ((dp = act->dta_difo) != NULL)
6330 v = dtrace_dif_emulate(dp,
6331 &mstate, vstate, state);
6333 if (*flags & CPU_DTRACE_ERROR)
6337 * Note that we always pass the expression
6338 * value from the previous iteration of the
6339 * action loop. This value will only be used
6340 * if there is an expression argument to the
6341 * aggregating action, denoted by the
6342 * dtag_hasarg field.
6344 dtrace_aggregate(agg, buf,
6345 offs, aggbuf, v, val);
6349 switch (act->dta_kind) {
6350 case DTRACEACT_STOP:
6351 if (dtrace_priv_proc_destructive(state))
6352 dtrace_action_stop();
6355 case DTRACEACT_BREAKPOINT:
6356 if (dtrace_priv_kernel_destructive(state))
6357 dtrace_action_breakpoint(ecb);
6360 case DTRACEACT_PANIC:
6361 if (dtrace_priv_kernel_destructive(state))
6362 dtrace_action_panic(ecb);
6365 case DTRACEACT_STACK:
6366 if (!dtrace_priv_kernel(state))
6369 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6370 size / sizeof (pc_t), probe->dtpr_aframes,
6371 DTRACE_ANCHORED(probe) ? NULL :
6375 case DTRACEACT_JSTACK:
6376 case DTRACEACT_USTACK:
6377 if (!dtrace_priv_proc(state))
6381 * See comment in DIF_VAR_PID.
6383 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6385 int depth = DTRACE_USTACK_NFRAMES(
6388 dtrace_bzero((void *)(tomax + valoffs),
6389 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6390 + depth * sizeof (uint64_t));
6395 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6396 curproc->p_dtrace_helpers != NULL) {
6398 * This is the slow path -- we have
6399 * allocated string space, and we're
6400 * getting the stack of a process that
6401 * has helpers. Call into a separate
6402 * routine to perform this processing.
6404 dtrace_action_ustack(&mstate, state,
6405 (uint64_t *)(tomax + valoffs),
6410 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6411 dtrace_getupcstack((uint64_t *)
6413 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6414 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6424 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6426 if (*flags & CPU_DTRACE_ERROR)
6429 switch (act->dta_kind) {
6430 case DTRACEACT_SPECULATE: {
6431 dtrace_rechdr_t *dtrh;
6433 ASSERT(buf == &state->dts_buffer[cpuid]);
6434 buf = dtrace_speculation_buffer(state,
6438 *flags |= CPU_DTRACE_DROP;
6442 offs = dtrace_buffer_reserve(buf,
6443 ecb->dte_needed, ecb->dte_alignment,
6447 *flags |= CPU_DTRACE_DROP;
6451 tomax = buf->dtb_tomax;
6452 ASSERT(tomax != NULL);
6454 if (ecb->dte_size == 0)
6457 ASSERT3U(ecb->dte_size, >=,
6458 sizeof (dtrace_rechdr_t));
6459 dtrh = ((void *)(tomax + offs));
6460 dtrh->dtrh_epid = ecb->dte_epid;
6462 * When the speculation is committed, all of
6463 * the records in the speculative buffer will
6464 * have their timestamps set to the commit
6465 * time. Until then, it is set to a sentinel
6466 * value, for debugability.
6468 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6472 case DTRACEACT_PRINTM: {
6473 /* The DIF returns a 'memref'. */
6474 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6476 /* Get the size from the memref. */
6480 * Check if the size exceeds the allocated
6483 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6485 *flags |= CPU_DTRACE_DROP;
6489 /* Store the size in the buffer first. */
6490 DTRACE_STORE(uintptr_t, tomax,
6494 * Offset the buffer address to the start
6497 valoffs += sizeof(uintptr_t);
6500 * Reset to the memory address rather than
6501 * the memref array, then let the BYREF
6502 * code below do the work to store the
6503 * memory data in the buffer.
6509 case DTRACEACT_PRINTT: {
6510 /* The DIF returns a 'typeref'. */
6511 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6516 * Get the type string length and round it
6517 * up so that the data that follows is
6518 * aligned for easy access.
6520 size_t typs = strlen((char *) typeref[2]) + 1;
6521 typs = roundup(typs, sizeof(uintptr_t));
6524 *Get the size from the typeref using the
6525 * number of elements and the type size.
6527 size = typeref[1] * typeref[3];
6530 * Check if the size exceeds the allocated
6533 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6535 *flags |= CPU_DTRACE_DROP;
6539 /* Store the size in the buffer first. */
6540 DTRACE_STORE(uintptr_t, tomax,
6542 valoffs += sizeof(uintptr_t);
6544 /* Store the type size in the buffer. */
6545 DTRACE_STORE(uintptr_t, tomax,
6546 valoffs, typeref[3]);
6547 valoffs += sizeof(uintptr_t);
6551 for (s = 0; s < typs; s++) {
6553 c = dtrace_load8(val++);
6555 DTRACE_STORE(uint8_t, tomax,
6560 * Reset to the memory address rather than
6561 * the typeref array, then let the BYREF
6562 * code below do the work to store the
6563 * memory data in the buffer.
6569 case DTRACEACT_CHILL:
6570 if (dtrace_priv_kernel_destructive(state))
6571 dtrace_action_chill(&mstate, val);
6574 case DTRACEACT_RAISE:
6575 if (dtrace_priv_proc_destructive(state))
6576 dtrace_action_raise(val);
6579 case DTRACEACT_COMMIT:
6583 * We need to commit our buffer state.
6586 buf->dtb_offset = offs + ecb->dte_size;
6587 buf = &state->dts_buffer[cpuid];
6588 dtrace_speculation_commit(state, cpuid, val);
6592 case DTRACEACT_DISCARD:
6593 dtrace_speculation_discard(state, cpuid, val);
6596 case DTRACEACT_DIFEXPR:
6597 case DTRACEACT_LIBACT:
6598 case DTRACEACT_PRINTF:
6599 case DTRACEACT_PRINTA:
6600 case DTRACEACT_SYSTEM:
6601 case DTRACEACT_FREOPEN:
6602 case DTRACEACT_TRACEMEM:
6605 case DTRACEACT_TRACEMEM_DYNSIZE:
6611 if (!dtrace_priv_kernel(state))
6615 case DTRACEACT_USYM:
6616 case DTRACEACT_UMOD:
6617 case DTRACEACT_UADDR: {
6619 struct pid *pid = curthread->t_procp->p_pidp;
6622 if (!dtrace_priv_proc(state))
6625 DTRACE_STORE(uint64_t, tomax,
6627 valoffs, (uint64_t)pid->pid_id);
6629 valoffs, (uint64_t) curproc->p_pid);
6631 DTRACE_STORE(uint64_t, tomax,
6632 valoffs + sizeof (uint64_t), val);
6637 case DTRACEACT_EXIT: {
6639 * For the exit action, we are going to attempt
6640 * to atomically set our activity to be
6641 * draining. If this fails (either because
6642 * another CPU has beat us to the exit action,
6643 * or because our current activity is something
6644 * other than ACTIVE or WARMUP), we will
6645 * continue. This assures that the exit action
6646 * can be successfully recorded at most once
6647 * when we're in the ACTIVE state. If we're
6648 * encountering the exit() action while in
6649 * COOLDOWN, however, we want to honor the new
6650 * status code. (We know that we're the only
6651 * thread in COOLDOWN, so there is no race.)
6653 void *activity = &state->dts_activity;
6654 dtrace_activity_t current = state->dts_activity;
6656 if (current == DTRACE_ACTIVITY_COOLDOWN)
6659 if (current != DTRACE_ACTIVITY_WARMUP)
6660 current = DTRACE_ACTIVITY_ACTIVE;
6662 if (dtrace_cas32(activity, current,
6663 DTRACE_ACTIVITY_DRAINING) != current) {
6664 *flags |= CPU_DTRACE_DROP;
6675 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6676 uintptr_t end = valoffs + size;
6678 if (tracememsize != 0 &&
6679 valoffs + tracememsize < end) {
6680 end = valoffs + tracememsize;
6684 if (!dtrace_vcanload((void *)(uintptr_t)val,
6685 &dp->dtdo_rtype, &mstate, vstate))
6689 * If this is a string, we're going to only
6690 * load until we find the zero byte -- after
6691 * which we'll store zero bytes.
6693 if (dp->dtdo_rtype.dtdt_kind ==
6696 int intuple = act->dta_intuple;
6699 for (s = 0; s < size; s++) {
6701 c = dtrace_load8(val++);
6703 DTRACE_STORE(uint8_t, tomax,
6706 if (c == '\0' && intuple)
6713 while (valoffs < end) {
6714 DTRACE_STORE(uint8_t, tomax, valoffs++,
6715 dtrace_load8(val++));
6725 case sizeof (uint8_t):
6726 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6728 case sizeof (uint16_t):
6729 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6731 case sizeof (uint32_t):
6732 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6734 case sizeof (uint64_t):
6735 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6739 * Any other size should have been returned by
6740 * reference, not by value.
6747 if (*flags & CPU_DTRACE_DROP)
6750 if (*flags & CPU_DTRACE_FAULT) {
6752 dtrace_action_t *err;
6756 if (probe->dtpr_id == dtrace_probeid_error) {
6758 * There's nothing we can do -- we had an
6759 * error on the error probe. We bump an
6760 * error counter to at least indicate that
6761 * this condition happened.
6763 dtrace_error(&state->dts_dblerrors);
6769 * Before recursing on dtrace_probe(), we
6770 * need to explicitly clear out our start
6771 * time to prevent it from being accumulated
6772 * into t_dtrace_vtime.
6774 curthread->t_dtrace_start = 0;
6778 * Iterate over the actions to figure out which action
6779 * we were processing when we experienced the error.
6780 * Note that act points _past_ the faulting action; if
6781 * act is ecb->dte_action, the fault was in the
6782 * predicate, if it's ecb->dte_action->dta_next it's
6783 * in action #1, and so on.
6785 for (err = ecb->dte_action, ndx = 0;
6786 err != act; err = err->dta_next, ndx++)
6789 dtrace_probe_error(state, ecb->dte_epid, ndx,
6790 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6791 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6792 cpu_core[cpuid].cpuc_dtrace_illval);
6798 buf->dtb_offset = offs + ecb->dte_size;
6802 curthread->t_dtrace_start = dtrace_gethrtime();
6804 dtrace_interrupt_enable(cookie);
6808 * DTrace Probe Hashing Functions
6810 * The functions in this section (and indeed, the functions in remaining
6811 * sections) are not _called_ from probe context. (Any exceptions to this are
6812 * marked with a "Note:".) Rather, they are called from elsewhere in the
6813 * DTrace framework to look-up probes in, add probes to and remove probes from
6814 * the DTrace probe hashes. (Each probe is hashed by each element of the
6815 * probe tuple -- allowing for fast lookups, regardless of what was
6819 dtrace_hash_str(const char *p)
6825 hval = (hval << 4) + *p++;
6826 if ((g = (hval & 0xf0000000)) != 0)
6833 static dtrace_hash_t *
6834 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6836 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6838 hash->dth_stroffs = stroffs;
6839 hash->dth_nextoffs = nextoffs;
6840 hash->dth_prevoffs = prevoffs;
6843 hash->dth_mask = hash->dth_size - 1;
6845 hash->dth_tab = kmem_zalloc(hash->dth_size *
6846 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6852 dtrace_hash_destroy(dtrace_hash_t *hash)
6857 for (i = 0; i < hash->dth_size; i++)
6858 ASSERT(hash->dth_tab[i] == NULL);
6861 kmem_free(hash->dth_tab,
6862 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6863 kmem_free(hash, sizeof (dtrace_hash_t));
6867 dtrace_hash_resize(dtrace_hash_t *hash)
6869 int size = hash->dth_size, i, ndx;
6870 int new_size = hash->dth_size << 1;
6871 int new_mask = new_size - 1;
6872 dtrace_hashbucket_t **new_tab, *bucket, *next;
6874 ASSERT((new_size & new_mask) == 0);
6876 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6878 for (i = 0; i < size; i++) {
6879 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6880 dtrace_probe_t *probe = bucket->dthb_chain;
6882 ASSERT(probe != NULL);
6883 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6885 next = bucket->dthb_next;
6886 bucket->dthb_next = new_tab[ndx];
6887 new_tab[ndx] = bucket;
6891 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6892 hash->dth_tab = new_tab;
6893 hash->dth_size = new_size;
6894 hash->dth_mask = new_mask;
6898 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6900 int hashval = DTRACE_HASHSTR(hash, new);
6901 int ndx = hashval & hash->dth_mask;
6902 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6903 dtrace_probe_t **nextp, **prevp;
6905 for (; bucket != NULL; bucket = bucket->dthb_next) {
6906 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6910 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6911 dtrace_hash_resize(hash);
6912 dtrace_hash_add(hash, new);
6916 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6917 bucket->dthb_next = hash->dth_tab[ndx];
6918 hash->dth_tab[ndx] = bucket;
6919 hash->dth_nbuckets++;
6922 nextp = DTRACE_HASHNEXT(hash, new);
6923 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6924 *nextp = bucket->dthb_chain;
6926 if (bucket->dthb_chain != NULL) {
6927 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6928 ASSERT(*prevp == NULL);
6932 bucket->dthb_chain = new;
6936 static dtrace_probe_t *
6937 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6939 int hashval = DTRACE_HASHSTR(hash, template);
6940 int ndx = hashval & hash->dth_mask;
6941 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6943 for (; bucket != NULL; bucket = bucket->dthb_next) {
6944 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6945 return (bucket->dthb_chain);
6952 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6954 int hashval = DTRACE_HASHSTR(hash, template);
6955 int ndx = hashval & hash->dth_mask;
6956 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6958 for (; bucket != NULL; bucket = bucket->dthb_next) {
6959 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6960 return (bucket->dthb_len);
6967 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6969 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6970 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6972 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6973 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6976 * Find the bucket that we're removing this probe from.
6978 for (; bucket != NULL; bucket = bucket->dthb_next) {
6979 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6983 ASSERT(bucket != NULL);
6985 if (*prevp == NULL) {
6986 if (*nextp == NULL) {
6988 * The removed probe was the only probe on this
6989 * bucket; we need to remove the bucket.
6991 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6993 ASSERT(bucket->dthb_chain == probe);
6997 hash->dth_tab[ndx] = bucket->dthb_next;
6999 while (b->dthb_next != bucket)
7001 b->dthb_next = bucket->dthb_next;
7004 ASSERT(hash->dth_nbuckets > 0);
7005 hash->dth_nbuckets--;
7006 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7010 bucket->dthb_chain = *nextp;
7012 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7016 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7020 * DTrace Utility Functions
7022 * These are random utility functions that are _not_ called from probe context.
7025 dtrace_badattr(const dtrace_attribute_t *a)
7027 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7028 a->dtat_data > DTRACE_STABILITY_MAX ||
7029 a->dtat_class > DTRACE_CLASS_MAX);
7033 * Return a duplicate copy of a string. If the specified string is NULL,
7034 * this function returns a zero-length string.
7037 dtrace_strdup(const char *str)
7039 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7042 (void) strcpy(new, str);
7047 #define DTRACE_ISALPHA(c) \
7048 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7051 dtrace_badname(const char *s)
7055 if (s == NULL || (c = *s++) == '\0')
7058 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7061 while ((c = *s++) != '\0') {
7062 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7063 c != '-' && c != '_' && c != '.' && c != '`')
7071 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7076 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7078 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7080 priv = DTRACE_PRIV_ALL;
7082 *uidp = crgetuid(cr);
7083 *zoneidp = crgetzoneid(cr);
7086 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7087 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7088 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7089 priv |= DTRACE_PRIV_USER;
7090 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7091 priv |= DTRACE_PRIV_PROC;
7092 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7093 priv |= DTRACE_PRIV_OWNER;
7094 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7095 priv |= DTRACE_PRIV_ZONEOWNER;
7098 priv = DTRACE_PRIV_ALL;
7104 #ifdef DTRACE_ERRDEBUG
7106 dtrace_errdebug(const char *str)
7108 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7111 mutex_enter(&dtrace_errlock);
7112 dtrace_errlast = str;
7113 dtrace_errthread = curthread;
7115 while (occupied++ < DTRACE_ERRHASHSZ) {
7116 if (dtrace_errhash[hval].dter_msg == str) {
7117 dtrace_errhash[hval].dter_count++;
7121 if (dtrace_errhash[hval].dter_msg != NULL) {
7122 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7126 dtrace_errhash[hval].dter_msg = str;
7127 dtrace_errhash[hval].dter_count = 1;
7131 panic("dtrace: undersized error hash");
7133 mutex_exit(&dtrace_errlock);
7138 * DTrace Matching Functions
7140 * These functions are used to match groups of probes, given some elements of
7141 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7144 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7147 if (priv != DTRACE_PRIV_ALL) {
7148 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7149 uint32_t match = priv & ppriv;
7152 * No PRIV_DTRACE_* privileges...
7154 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7155 DTRACE_PRIV_KERNEL)) == 0)
7159 * No matching bits, but there were bits to match...
7161 if (match == 0 && ppriv != 0)
7165 * Need to have permissions to the process, but don't...
7167 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7168 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7173 * Need to be in the same zone unless we possess the
7174 * privilege to examine all zones.
7176 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7177 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7186 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7187 * consists of input pattern strings and an ops-vector to evaluate them.
7188 * This function returns >0 for match, 0 for no match, and <0 for error.
7191 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7192 uint32_t priv, uid_t uid, zoneid_t zoneid)
7194 dtrace_provider_t *pvp = prp->dtpr_provider;
7197 if (pvp->dtpv_defunct)
7200 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7203 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7206 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7209 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7212 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7219 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7220 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7221 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7222 * In addition, all of the recursion cases except for '*' matching have been
7223 * unwound. For '*', we still implement recursive evaluation, but a depth
7224 * counter is maintained and matching is aborted if we recurse too deep.
7225 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7228 dtrace_match_glob(const char *s, const char *p, int depth)
7234 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7238 s = ""; /* treat NULL as empty string */
7247 if ((c = *p++) == '\0')
7248 return (s1 == '\0');
7252 int ok = 0, notflag = 0;
7263 if ((c = *p++) == '\0')
7267 if (c == '-' && lc != '\0' && *p != ']') {
7268 if ((c = *p++) == '\0')
7270 if (c == '\\' && (c = *p++) == '\0')
7274 if (s1 < lc || s1 > c)
7278 } else if (lc <= s1 && s1 <= c)
7281 } else if (c == '\\' && (c = *p++) == '\0')
7284 lc = c; /* save left-hand 'c' for next iteration */
7294 if ((c = *p++) == '\0')
7306 if ((c = *p++) == '\0')
7322 p++; /* consecutive *'s are identical to a single one */
7327 for (s = olds; *s != '\0'; s++) {
7328 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7338 dtrace_match_string(const char *s, const char *p, int depth)
7340 return (s != NULL && strcmp(s, p) == 0);
7345 dtrace_match_nul(const char *s, const char *p, int depth)
7347 return (1); /* always match the empty pattern */
7352 dtrace_match_nonzero(const char *s, const char *p, int depth)
7354 return (s != NULL && s[0] != '\0');
7358 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7359 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7361 dtrace_probe_t template, *probe;
7362 dtrace_hash_t *hash = NULL;
7363 int len, best = INT_MAX, nmatched = 0;
7366 ASSERT(MUTEX_HELD(&dtrace_lock));
7369 * If the probe ID is specified in the key, just lookup by ID and
7370 * invoke the match callback once if a matching probe is found.
7372 if (pkp->dtpk_id != DTRACE_IDNONE) {
7373 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7374 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7375 (void) (*matched)(probe, arg);
7381 template.dtpr_mod = (char *)pkp->dtpk_mod;
7382 template.dtpr_func = (char *)pkp->dtpk_func;
7383 template.dtpr_name = (char *)pkp->dtpk_name;
7386 * We want to find the most distinct of the module name, function
7387 * name, and name. So for each one that is not a glob pattern or
7388 * empty string, we perform a lookup in the corresponding hash and
7389 * use the hash table with the fewest collisions to do our search.
7391 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7392 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7394 hash = dtrace_bymod;
7397 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7398 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7400 hash = dtrace_byfunc;
7403 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7404 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7406 hash = dtrace_byname;
7410 * If we did not select a hash table, iterate over every probe and
7411 * invoke our callback for each one that matches our input probe key.
7414 for (i = 0; i < dtrace_nprobes; i++) {
7415 if ((probe = dtrace_probes[i]) == NULL ||
7416 dtrace_match_probe(probe, pkp, priv, uid,
7422 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7430 * If we selected a hash table, iterate over each probe of the same key
7431 * name and invoke the callback for every probe that matches the other
7432 * attributes of our input probe key.
7434 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7435 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7437 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7442 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7450 * Return the function pointer dtrace_probecmp() should use to compare the
7451 * specified pattern with a string. For NULL or empty patterns, we select
7452 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7453 * For non-empty non-glob strings, we use dtrace_match_string().
7455 static dtrace_probekey_f *
7456 dtrace_probekey_func(const char *p)
7460 if (p == NULL || *p == '\0')
7461 return (&dtrace_match_nul);
7463 while ((c = *p++) != '\0') {
7464 if (c == '[' || c == '?' || c == '*' || c == '\\')
7465 return (&dtrace_match_glob);
7468 return (&dtrace_match_string);
7472 * Build a probe comparison key for use with dtrace_match_probe() from the
7473 * given probe description. By convention, a null key only matches anchored
7474 * probes: if each field is the empty string, reset dtpk_fmatch to
7475 * dtrace_match_nonzero().
7478 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7480 pkp->dtpk_prov = pdp->dtpd_provider;
7481 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7483 pkp->dtpk_mod = pdp->dtpd_mod;
7484 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7486 pkp->dtpk_func = pdp->dtpd_func;
7487 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7489 pkp->dtpk_name = pdp->dtpd_name;
7490 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7492 pkp->dtpk_id = pdp->dtpd_id;
7494 if (pkp->dtpk_id == DTRACE_IDNONE &&
7495 pkp->dtpk_pmatch == &dtrace_match_nul &&
7496 pkp->dtpk_mmatch == &dtrace_match_nul &&
7497 pkp->dtpk_fmatch == &dtrace_match_nul &&
7498 pkp->dtpk_nmatch == &dtrace_match_nul)
7499 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7503 * DTrace Provider-to-Framework API Functions
7505 * These functions implement much of the Provider-to-Framework API, as
7506 * described in <sys/dtrace.h>. The parts of the API not in this section are
7507 * the functions in the API for probe management (found below), and
7508 * dtrace_probe() itself (found above).
7512 * Register the calling provider with the DTrace framework. This should
7513 * generally be called by DTrace providers in their attach(9E) entry point.
7516 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7517 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7519 dtrace_provider_t *provider;
7521 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7522 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7523 "arguments", name ? name : "<NULL>");
7527 if (name[0] == '\0' || dtrace_badname(name)) {
7528 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7529 "provider name", name);
7533 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7534 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7535 pops->dtps_destroy == NULL ||
7536 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7537 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7538 "provider ops", name);
7542 if (dtrace_badattr(&pap->dtpa_provider) ||
7543 dtrace_badattr(&pap->dtpa_mod) ||
7544 dtrace_badattr(&pap->dtpa_func) ||
7545 dtrace_badattr(&pap->dtpa_name) ||
7546 dtrace_badattr(&pap->dtpa_args)) {
7547 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7548 "provider attributes", name);
7552 if (priv & ~DTRACE_PRIV_ALL) {
7553 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7554 "privilege attributes", name);
7558 if ((priv & DTRACE_PRIV_KERNEL) &&
7559 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7560 pops->dtps_usermode == NULL) {
7561 cmn_err(CE_WARN, "failed to register provider '%s': need "
7562 "dtps_usermode() op for given privilege attributes", name);
7566 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7567 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7568 (void) strcpy(provider->dtpv_name, name);
7570 provider->dtpv_attr = *pap;
7571 provider->dtpv_priv.dtpp_flags = priv;
7573 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7574 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7576 provider->dtpv_pops = *pops;
7578 if (pops->dtps_provide == NULL) {
7579 ASSERT(pops->dtps_provide_module != NULL);
7580 provider->dtpv_pops.dtps_provide =
7581 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7584 if (pops->dtps_provide_module == NULL) {
7585 ASSERT(pops->dtps_provide != NULL);
7586 provider->dtpv_pops.dtps_provide_module =
7587 (void (*)(void *, modctl_t *))dtrace_nullop;
7590 if (pops->dtps_suspend == NULL) {
7591 ASSERT(pops->dtps_resume == NULL);
7592 provider->dtpv_pops.dtps_suspend =
7593 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7594 provider->dtpv_pops.dtps_resume =
7595 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7598 provider->dtpv_arg = arg;
7599 *idp = (dtrace_provider_id_t)provider;
7601 if (pops == &dtrace_provider_ops) {
7602 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7603 ASSERT(MUTEX_HELD(&dtrace_lock));
7604 ASSERT(dtrace_anon.dta_enabling == NULL);
7607 * We make sure that the DTrace provider is at the head of
7608 * the provider chain.
7610 provider->dtpv_next = dtrace_provider;
7611 dtrace_provider = provider;
7615 mutex_enter(&dtrace_provider_lock);
7616 mutex_enter(&dtrace_lock);
7619 * If there is at least one provider registered, we'll add this
7620 * provider after the first provider.
7622 if (dtrace_provider != NULL) {
7623 provider->dtpv_next = dtrace_provider->dtpv_next;
7624 dtrace_provider->dtpv_next = provider;
7626 dtrace_provider = provider;
7629 if (dtrace_retained != NULL) {
7630 dtrace_enabling_provide(provider);
7633 * Now we need to call dtrace_enabling_matchall() -- which
7634 * will acquire cpu_lock and dtrace_lock. We therefore need
7635 * to drop all of our locks before calling into it...
7637 mutex_exit(&dtrace_lock);
7638 mutex_exit(&dtrace_provider_lock);
7639 dtrace_enabling_matchall();
7644 mutex_exit(&dtrace_lock);
7645 mutex_exit(&dtrace_provider_lock);
7651 * Unregister the specified provider from the DTrace framework. This should
7652 * generally be called by DTrace providers in their detach(9E) entry point.
7655 dtrace_unregister(dtrace_provider_id_t id)
7657 dtrace_provider_t *old = (dtrace_provider_t *)id;
7658 dtrace_provider_t *prev = NULL;
7659 int i, self = 0, noreap = 0;
7660 dtrace_probe_t *probe, *first = NULL;
7662 if (old->dtpv_pops.dtps_enable ==
7663 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7665 * If DTrace itself is the provider, we're called with locks
7668 ASSERT(old == dtrace_provider);
7670 ASSERT(dtrace_devi != NULL);
7672 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7673 ASSERT(MUTEX_HELD(&dtrace_lock));
7676 if (dtrace_provider->dtpv_next != NULL) {
7678 * There's another provider here; return failure.
7683 mutex_enter(&dtrace_provider_lock);
7684 mutex_enter(&mod_lock);
7685 mutex_enter(&dtrace_lock);
7689 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7690 * probes, we refuse to let providers slither away, unless this
7691 * provider has already been explicitly invalidated.
7693 if (!old->dtpv_defunct &&
7694 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7695 dtrace_anon.dta_state->dts_necbs > 0))) {
7697 mutex_exit(&dtrace_lock);
7698 mutex_exit(&mod_lock);
7699 mutex_exit(&dtrace_provider_lock);
7705 * Attempt to destroy the probes associated with this provider.
7707 for (i = 0; i < dtrace_nprobes; i++) {
7708 if ((probe = dtrace_probes[i]) == NULL)
7711 if (probe->dtpr_provider != old)
7714 if (probe->dtpr_ecb == NULL)
7718 * If we are trying to unregister a defunct provider, and the
7719 * provider was made defunct within the interval dictated by
7720 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7721 * attempt to reap our enablings. To denote that the provider
7722 * should reattempt to unregister itself at some point in the
7723 * future, we will return a differentiable error code (EAGAIN
7724 * instead of EBUSY) in this case.
7726 if (dtrace_gethrtime() - old->dtpv_defunct >
7727 dtrace_unregister_defunct_reap)
7731 mutex_exit(&dtrace_lock);
7732 mutex_exit(&mod_lock);
7733 mutex_exit(&dtrace_provider_lock);
7739 (void) taskq_dispatch(dtrace_taskq,
7740 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7746 * All of the probes for this provider are disabled; we can safely
7747 * remove all of them from their hash chains and from the probe array.
7749 for (i = 0; i < dtrace_nprobes; i++) {
7750 if ((probe = dtrace_probes[i]) == NULL)
7753 if (probe->dtpr_provider != old)
7756 dtrace_probes[i] = NULL;
7758 dtrace_hash_remove(dtrace_bymod, probe);
7759 dtrace_hash_remove(dtrace_byfunc, probe);
7760 dtrace_hash_remove(dtrace_byname, probe);
7762 if (first == NULL) {
7764 probe->dtpr_nextmod = NULL;
7766 probe->dtpr_nextmod = first;
7772 * The provider's probes have been removed from the hash chains and
7773 * from the probe array. Now issue a dtrace_sync() to be sure that
7774 * everyone has cleared out from any probe array processing.
7778 for (probe = first; probe != NULL; probe = first) {
7779 first = probe->dtpr_nextmod;
7781 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7783 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7784 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7785 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7787 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7789 free_unr(dtrace_arena, probe->dtpr_id);
7791 kmem_free(probe, sizeof (dtrace_probe_t));
7794 if ((prev = dtrace_provider) == old) {
7796 ASSERT(self || dtrace_devi == NULL);
7797 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7799 dtrace_provider = old->dtpv_next;
7801 while (prev != NULL && prev->dtpv_next != old)
7802 prev = prev->dtpv_next;
7805 panic("attempt to unregister non-existent "
7806 "dtrace provider %p\n", (void *)id);
7809 prev->dtpv_next = old->dtpv_next;
7813 mutex_exit(&dtrace_lock);
7814 mutex_exit(&mod_lock);
7815 mutex_exit(&dtrace_provider_lock);
7818 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7819 kmem_free(old, sizeof (dtrace_provider_t));
7825 * Invalidate the specified provider. All subsequent probe lookups for the
7826 * specified provider will fail, but its probes will not be removed.
7829 dtrace_invalidate(dtrace_provider_id_t id)
7831 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7833 ASSERT(pvp->dtpv_pops.dtps_enable !=
7834 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7836 mutex_enter(&dtrace_provider_lock);
7837 mutex_enter(&dtrace_lock);
7839 pvp->dtpv_defunct = dtrace_gethrtime();
7841 mutex_exit(&dtrace_lock);
7842 mutex_exit(&dtrace_provider_lock);
7846 * Indicate whether or not DTrace has attached.
7849 dtrace_attached(void)
7852 * dtrace_provider will be non-NULL iff the DTrace driver has
7853 * attached. (It's non-NULL because DTrace is always itself a
7856 return (dtrace_provider != NULL);
7860 * Remove all the unenabled probes for the given provider. This function is
7861 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7862 * -- just as many of its associated probes as it can.
7865 dtrace_condense(dtrace_provider_id_t id)
7867 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7869 dtrace_probe_t *probe;
7872 * Make sure this isn't the dtrace provider itself.
7874 ASSERT(prov->dtpv_pops.dtps_enable !=
7875 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7877 mutex_enter(&dtrace_provider_lock);
7878 mutex_enter(&dtrace_lock);
7881 * Attempt to destroy the probes associated with this provider.
7883 for (i = 0; i < dtrace_nprobes; i++) {
7884 if ((probe = dtrace_probes[i]) == NULL)
7887 if (probe->dtpr_provider != prov)
7890 if (probe->dtpr_ecb != NULL)
7893 dtrace_probes[i] = NULL;
7895 dtrace_hash_remove(dtrace_bymod, probe);
7896 dtrace_hash_remove(dtrace_byfunc, probe);
7897 dtrace_hash_remove(dtrace_byname, probe);
7899 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7901 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7902 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7903 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7904 kmem_free(probe, sizeof (dtrace_probe_t));
7906 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7908 free_unr(dtrace_arena, i + 1);
7912 mutex_exit(&dtrace_lock);
7913 mutex_exit(&dtrace_provider_lock);
7919 * DTrace Probe Management Functions
7921 * The functions in this section perform the DTrace probe management,
7922 * including functions to create probes, look-up probes, and call into the
7923 * providers to request that probes be provided. Some of these functions are
7924 * in the Provider-to-Framework API; these functions can be identified by the
7925 * fact that they are not declared "static".
7929 * Create a probe with the specified module name, function name, and name.
7932 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7933 const char *func, const char *name, int aframes, void *arg)
7935 dtrace_probe_t *probe, **probes;
7936 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7939 if (provider == dtrace_provider) {
7940 ASSERT(MUTEX_HELD(&dtrace_lock));
7942 mutex_enter(&dtrace_lock);
7946 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7947 VM_BESTFIT | VM_SLEEP);
7949 id = alloc_unr(dtrace_arena);
7951 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7953 probe->dtpr_id = id;
7954 probe->dtpr_gen = dtrace_probegen++;
7955 probe->dtpr_mod = dtrace_strdup(mod);
7956 probe->dtpr_func = dtrace_strdup(func);
7957 probe->dtpr_name = dtrace_strdup(name);
7958 probe->dtpr_arg = arg;
7959 probe->dtpr_aframes = aframes;
7960 probe->dtpr_provider = provider;
7962 dtrace_hash_add(dtrace_bymod, probe);
7963 dtrace_hash_add(dtrace_byfunc, probe);
7964 dtrace_hash_add(dtrace_byname, probe);
7966 if (id - 1 >= dtrace_nprobes) {
7967 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7968 size_t nsize = osize << 1;
7972 ASSERT(dtrace_probes == NULL);
7973 nsize = sizeof (dtrace_probe_t *);
7976 probes = kmem_zalloc(nsize, KM_SLEEP);
7978 if (dtrace_probes == NULL) {
7980 dtrace_probes = probes;
7983 dtrace_probe_t **oprobes = dtrace_probes;
7985 bcopy(oprobes, probes, osize);
7986 dtrace_membar_producer();
7987 dtrace_probes = probes;
7992 * All CPUs are now seeing the new probes array; we can
7993 * safely free the old array.
7995 kmem_free(oprobes, osize);
7996 dtrace_nprobes <<= 1;
7999 ASSERT(id - 1 < dtrace_nprobes);
8002 ASSERT(dtrace_probes[id - 1] == NULL);
8003 dtrace_probes[id - 1] = probe;
8005 if (provider != dtrace_provider)
8006 mutex_exit(&dtrace_lock);
8011 static dtrace_probe_t *
8012 dtrace_probe_lookup_id(dtrace_id_t id)
8014 ASSERT(MUTEX_HELD(&dtrace_lock));
8016 if (id == 0 || id > dtrace_nprobes)
8019 return (dtrace_probes[id - 1]);
8023 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8025 *((dtrace_id_t *)arg) = probe->dtpr_id;
8027 return (DTRACE_MATCH_DONE);
8031 * Look up a probe based on provider and one or more of module name, function
8032 * name and probe name.
8035 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8036 char *func, char *name)
8038 dtrace_probekey_t pkey;
8042 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8043 pkey.dtpk_pmatch = &dtrace_match_string;
8044 pkey.dtpk_mod = mod;
8045 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8046 pkey.dtpk_func = func;
8047 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8048 pkey.dtpk_name = name;
8049 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8050 pkey.dtpk_id = DTRACE_IDNONE;
8052 mutex_enter(&dtrace_lock);
8053 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8054 dtrace_probe_lookup_match, &id);
8055 mutex_exit(&dtrace_lock);
8057 ASSERT(match == 1 || match == 0);
8058 return (match ? id : 0);
8062 * Returns the probe argument associated with the specified probe.
8065 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8067 dtrace_probe_t *probe;
8070 mutex_enter(&dtrace_lock);
8072 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8073 probe->dtpr_provider == (dtrace_provider_t *)id)
8074 rval = probe->dtpr_arg;
8076 mutex_exit(&dtrace_lock);
8082 * Copy a probe into a probe description.
8085 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8087 bzero(pdp, sizeof (dtrace_probedesc_t));
8088 pdp->dtpd_id = prp->dtpr_id;
8090 (void) strncpy(pdp->dtpd_provider,
8091 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8093 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8094 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8095 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8099 * Called to indicate that a probe -- or probes -- should be provided by a
8100 * specfied provider. If the specified description is NULL, the provider will
8101 * be told to provide all of its probes. (This is done whenever a new
8102 * consumer comes along, or whenever a retained enabling is to be matched.) If
8103 * the specified description is non-NULL, the provider is given the
8104 * opportunity to dynamically provide the specified probe, allowing providers
8105 * to support the creation of probes on-the-fly. (So-called _autocreated_
8106 * probes.) If the provider is NULL, the operations will be applied to all
8107 * providers; if the provider is non-NULL the operations will only be applied
8108 * to the specified provider. The dtrace_provider_lock must be held, and the
8109 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8110 * will need to grab the dtrace_lock when it reenters the framework through
8111 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8114 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8121 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8125 prv = dtrace_provider;
8130 * First, call the blanket provide operation.
8132 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8135 * Now call the per-module provide operation. We will grab
8136 * mod_lock to prevent the list from being modified. Note
8137 * that this also prevents the mod_busy bits from changing.
8138 * (mod_busy can only be changed with mod_lock held.)
8140 mutex_enter(&mod_lock);
8145 if (ctl->mod_busy || ctl->mod_mp == NULL)
8148 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8150 } while ((ctl = ctl->mod_next) != &modules);
8153 mutex_exit(&mod_lock);
8154 } while (all && (prv = prv->dtpv_next) != NULL);
8159 * Iterate over each probe, and call the Framework-to-Provider API function
8163 dtrace_probe_foreach(uintptr_t offs)
8165 dtrace_provider_t *prov;
8166 void (*func)(void *, dtrace_id_t, void *);
8167 dtrace_probe_t *probe;
8168 dtrace_icookie_t cookie;
8172 * We disable interrupts to walk through the probe array. This is
8173 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8174 * won't see stale data.
8176 cookie = dtrace_interrupt_disable();
8178 for (i = 0; i < dtrace_nprobes; i++) {
8179 if ((probe = dtrace_probes[i]) == NULL)
8182 if (probe->dtpr_ecb == NULL) {
8184 * This probe isn't enabled -- don't call the function.
8189 prov = probe->dtpr_provider;
8190 func = *((void(**)(void *, dtrace_id_t, void *))
8191 ((uintptr_t)&prov->dtpv_pops + offs));
8193 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8196 dtrace_interrupt_enable(cookie);
8201 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8203 dtrace_probekey_t pkey;
8208 ASSERT(MUTEX_HELD(&dtrace_lock));
8209 dtrace_ecb_create_cache = NULL;
8213 * If we're passed a NULL description, we're being asked to
8214 * create an ECB with a NULL probe.
8216 (void) dtrace_ecb_create_enable(NULL, enab);
8220 dtrace_probekey(desc, &pkey);
8221 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8222 &priv, &uid, &zoneid);
8224 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8229 * DTrace Helper Provider Functions
8232 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8234 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8235 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8236 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8240 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8241 const dof_provider_t *dofprov, char *strtab)
8243 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8244 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8245 dofprov->dofpv_provattr);
8246 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8247 dofprov->dofpv_modattr);
8248 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8249 dofprov->dofpv_funcattr);
8250 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8251 dofprov->dofpv_nameattr);
8252 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8253 dofprov->dofpv_argsattr);
8257 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8259 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8260 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8261 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8262 dof_provider_t *provider;
8264 uint32_t *off, *enoff;
8268 dtrace_helper_provdesc_t dhpv;
8269 dtrace_helper_probedesc_t dhpb;
8270 dtrace_meta_t *meta = dtrace_meta_pid;
8271 dtrace_mops_t *mops = &meta->dtm_mops;
8274 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8275 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8276 provider->dofpv_strtab * dof->dofh_secsize);
8277 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8278 provider->dofpv_probes * dof->dofh_secsize);
8279 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8280 provider->dofpv_prargs * dof->dofh_secsize);
8281 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8282 provider->dofpv_proffs * dof->dofh_secsize);
8284 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8285 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8286 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8290 * See dtrace_helper_provider_validate().
8292 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8293 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8294 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8295 provider->dofpv_prenoffs * dof->dofh_secsize);
8296 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8299 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8302 * Create the provider.
8304 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8306 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8312 * Create the probes.
8314 for (i = 0; i < nprobes; i++) {
8315 probe = (dof_probe_t *)(uintptr_t)(daddr +
8316 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8318 dhpb.dthpb_mod = dhp->dofhp_mod;
8319 dhpb.dthpb_func = strtab + probe->dofpr_func;
8320 dhpb.dthpb_name = strtab + probe->dofpr_name;
8321 dhpb.dthpb_base = probe->dofpr_addr;
8322 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8323 dhpb.dthpb_noffs = probe->dofpr_noffs;
8324 if (enoff != NULL) {
8325 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8326 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8328 dhpb.dthpb_enoffs = NULL;
8329 dhpb.dthpb_nenoffs = 0;
8331 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8332 dhpb.dthpb_nargc = probe->dofpr_nargc;
8333 dhpb.dthpb_xargc = probe->dofpr_xargc;
8334 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8335 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8337 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8342 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8344 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8345 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8348 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8350 for (i = 0; i < dof->dofh_secnum; i++) {
8351 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8352 dof->dofh_secoff + i * dof->dofh_secsize);
8354 if (sec->dofs_type != DOF_SECT_PROVIDER)
8357 dtrace_helper_provide_one(dhp, sec, pid);
8361 * We may have just created probes, so we must now rematch against
8362 * any retained enablings. Note that this call will acquire both
8363 * cpu_lock and dtrace_lock; the fact that we are holding
8364 * dtrace_meta_lock now is what defines the ordering with respect to
8365 * these three locks.
8367 dtrace_enabling_matchall();
8371 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8373 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8374 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8376 dof_provider_t *provider;
8378 dtrace_helper_provdesc_t dhpv;
8379 dtrace_meta_t *meta = dtrace_meta_pid;
8380 dtrace_mops_t *mops = &meta->dtm_mops;
8382 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8383 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8384 provider->dofpv_strtab * dof->dofh_secsize);
8386 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8389 * Create the provider.
8391 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8393 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8399 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8401 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8402 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8405 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8407 for (i = 0; i < dof->dofh_secnum; i++) {
8408 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8409 dof->dofh_secoff + i * dof->dofh_secsize);
8411 if (sec->dofs_type != DOF_SECT_PROVIDER)
8414 dtrace_helper_provider_remove_one(dhp, sec, pid);
8419 * DTrace Meta Provider-to-Framework API Functions
8421 * These functions implement the Meta Provider-to-Framework API, as described
8422 * in <sys/dtrace.h>.
8425 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8426 dtrace_meta_provider_id_t *idp)
8428 dtrace_meta_t *meta;
8429 dtrace_helpers_t *help, *next;
8432 *idp = DTRACE_METAPROVNONE;
8435 * We strictly don't need the name, but we hold onto it for
8436 * debuggability. All hail error queues!
8439 cmn_err(CE_WARN, "failed to register meta-provider: "
8445 mops->dtms_create_probe == NULL ||
8446 mops->dtms_provide_pid == NULL ||
8447 mops->dtms_remove_pid == NULL) {
8448 cmn_err(CE_WARN, "failed to register meta-register %s: "
8449 "invalid ops", name);
8453 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8454 meta->dtm_mops = *mops;
8455 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8456 (void) strcpy(meta->dtm_name, name);
8457 meta->dtm_arg = arg;
8459 mutex_enter(&dtrace_meta_lock);
8460 mutex_enter(&dtrace_lock);
8462 if (dtrace_meta_pid != NULL) {
8463 mutex_exit(&dtrace_lock);
8464 mutex_exit(&dtrace_meta_lock);
8465 cmn_err(CE_WARN, "failed to register meta-register %s: "
8466 "user-land meta-provider exists", name);
8467 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8468 kmem_free(meta, sizeof (dtrace_meta_t));
8472 dtrace_meta_pid = meta;
8473 *idp = (dtrace_meta_provider_id_t)meta;
8476 * If there are providers and probes ready to go, pass them
8477 * off to the new meta provider now.
8480 help = dtrace_deferred_pid;
8481 dtrace_deferred_pid = NULL;
8483 mutex_exit(&dtrace_lock);
8485 while (help != NULL) {
8486 for (i = 0; i < help->dthps_nprovs; i++) {
8487 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8491 next = help->dthps_next;
8492 help->dthps_next = NULL;
8493 help->dthps_prev = NULL;
8494 help->dthps_deferred = 0;
8498 mutex_exit(&dtrace_meta_lock);
8504 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8506 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8508 mutex_enter(&dtrace_meta_lock);
8509 mutex_enter(&dtrace_lock);
8511 if (old == dtrace_meta_pid) {
8512 pp = &dtrace_meta_pid;
8514 panic("attempt to unregister non-existent "
8515 "dtrace meta-provider %p\n", (void *)old);
8518 if (old->dtm_count != 0) {
8519 mutex_exit(&dtrace_lock);
8520 mutex_exit(&dtrace_meta_lock);
8526 mutex_exit(&dtrace_lock);
8527 mutex_exit(&dtrace_meta_lock);
8529 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8530 kmem_free(old, sizeof (dtrace_meta_t));
8537 * DTrace DIF Object Functions
8540 dtrace_difo_err(uint_t pc, const char *format, ...)
8542 if (dtrace_err_verbose) {
8545 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8546 va_start(alist, format);
8547 (void) vuprintf(format, alist);
8551 #ifdef DTRACE_ERRDEBUG
8552 dtrace_errdebug(format);
8558 * Validate a DTrace DIF object by checking the IR instructions. The following
8559 * rules are currently enforced by dtrace_difo_validate():
8561 * 1. Each instruction must have a valid opcode
8562 * 2. Each register, string, variable, or subroutine reference must be valid
8563 * 3. No instruction can modify register %r0 (must be zero)
8564 * 4. All instruction reserved bits must be set to zero
8565 * 5. The last instruction must be a "ret" instruction
8566 * 6. All branch targets must reference a valid instruction _after_ the branch
8569 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8573 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8577 kcheckload = cr == NULL ||
8578 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8580 dp->dtdo_destructive = 0;
8582 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8583 dif_instr_t instr = dp->dtdo_buf[pc];
8585 uint_t r1 = DIF_INSTR_R1(instr);
8586 uint_t r2 = DIF_INSTR_R2(instr);
8587 uint_t rd = DIF_INSTR_RD(instr);
8588 uint_t rs = DIF_INSTR_RS(instr);
8589 uint_t label = DIF_INSTR_LABEL(instr);
8590 uint_t v = DIF_INSTR_VAR(instr);
8591 uint_t subr = DIF_INSTR_SUBR(instr);
8592 uint_t type = DIF_INSTR_TYPE(instr);
8593 uint_t op = DIF_INSTR_OP(instr);
8611 err += efunc(pc, "invalid register %u\n", r1);
8613 err += efunc(pc, "invalid register %u\n", r2);
8615 err += efunc(pc, "invalid register %u\n", rd);
8617 err += efunc(pc, "cannot write to %r0\n");
8623 err += efunc(pc, "invalid register %u\n", r1);
8625 err += efunc(pc, "non-zero reserved bits\n");
8627 err += efunc(pc, "invalid register %u\n", rd);
8629 err += efunc(pc, "cannot write to %r0\n");
8639 err += efunc(pc, "invalid register %u\n", r1);
8641 err += efunc(pc, "non-zero reserved bits\n");
8643 err += efunc(pc, "invalid register %u\n", rd);
8645 err += efunc(pc, "cannot write to %r0\n");
8647 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8648 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8658 err += efunc(pc, "invalid register %u\n", r1);
8660 err += efunc(pc, "non-zero reserved bits\n");
8662 err += efunc(pc, "invalid register %u\n", rd);
8664 err += efunc(pc, "cannot write to %r0\n");
8674 err += efunc(pc, "invalid register %u\n", r1);
8676 err += efunc(pc, "non-zero reserved bits\n");
8678 err += efunc(pc, "invalid register %u\n", rd);
8680 err += efunc(pc, "cannot write to %r0\n");
8687 err += efunc(pc, "invalid register %u\n", r1);
8689 err += efunc(pc, "non-zero reserved bits\n");
8691 err += efunc(pc, "invalid register %u\n", rd);
8693 err += efunc(pc, "cannot write to 0 address\n");
8698 err += efunc(pc, "invalid register %u\n", r1);
8700 err += efunc(pc, "invalid register %u\n", r2);
8702 err += efunc(pc, "non-zero reserved bits\n");
8706 err += efunc(pc, "invalid register %u\n", r1);
8707 if (r2 != 0 || rd != 0)
8708 err += efunc(pc, "non-zero reserved bits\n");
8721 if (label >= dp->dtdo_len) {
8722 err += efunc(pc, "invalid branch target %u\n",
8726 err += efunc(pc, "backward branch to %u\n",
8731 if (r1 != 0 || r2 != 0)
8732 err += efunc(pc, "non-zero reserved bits\n");
8734 err += efunc(pc, "invalid register %u\n", rd);
8738 case DIF_OP_FLUSHTS:
8739 if (r1 != 0 || r2 != 0 || rd != 0)
8740 err += efunc(pc, "non-zero reserved bits\n");
8743 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8744 err += efunc(pc, "invalid integer ref %u\n",
8745 DIF_INSTR_INTEGER(instr));
8748 err += efunc(pc, "invalid register %u\n", rd);
8750 err += efunc(pc, "cannot write to %r0\n");
8753 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8754 err += efunc(pc, "invalid string ref %u\n",
8755 DIF_INSTR_STRING(instr));
8758 err += efunc(pc, "invalid register %u\n", rd);
8760 err += efunc(pc, "cannot write to %r0\n");
8764 if (r1 > DIF_VAR_ARRAY_MAX)
8765 err += efunc(pc, "invalid array %u\n", r1);
8767 err += efunc(pc, "invalid register %u\n", r2);
8769 err += efunc(pc, "invalid register %u\n", rd);
8771 err += efunc(pc, "cannot write to %r0\n");
8778 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8779 err += efunc(pc, "invalid variable %u\n", v);
8781 err += efunc(pc, "invalid register %u\n", rd);
8783 err += efunc(pc, "cannot write to %r0\n");
8790 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8791 err += efunc(pc, "invalid variable %u\n", v);
8793 err += efunc(pc, "invalid register %u\n", rd);
8796 if (subr > DIF_SUBR_MAX)
8797 err += efunc(pc, "invalid subr %u\n", subr);
8799 err += efunc(pc, "invalid register %u\n", rd);
8801 err += efunc(pc, "cannot write to %r0\n");
8803 if (subr == DIF_SUBR_COPYOUT ||
8804 subr == DIF_SUBR_COPYOUTSTR) {
8805 dp->dtdo_destructive = 1;
8809 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8810 err += efunc(pc, "invalid ref type %u\n", type);
8812 err += efunc(pc, "invalid register %u\n", r2);
8814 err += efunc(pc, "invalid register %u\n", rs);
8817 if (type != DIF_TYPE_CTF)
8818 err += efunc(pc, "invalid val type %u\n", type);
8820 err += efunc(pc, "invalid register %u\n", r2);
8822 err += efunc(pc, "invalid register %u\n", rs);
8825 err += efunc(pc, "invalid opcode %u\n",
8826 DIF_INSTR_OP(instr));
8830 if (dp->dtdo_len != 0 &&
8831 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8832 err += efunc(dp->dtdo_len - 1,
8833 "expected 'ret' as last DIF instruction\n");
8836 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8838 * If we're not returning by reference, the size must be either
8839 * 0 or the size of one of the base types.
8841 switch (dp->dtdo_rtype.dtdt_size) {
8843 case sizeof (uint8_t):
8844 case sizeof (uint16_t):
8845 case sizeof (uint32_t):
8846 case sizeof (uint64_t):
8850 err += efunc(dp->dtdo_len - 1, "bad return size");
8854 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8855 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8856 dtrace_diftype_t *vt, *et;
8859 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8860 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8861 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8862 err += efunc(i, "unrecognized variable scope %d\n",
8867 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8868 v->dtdv_kind != DIFV_KIND_SCALAR) {
8869 err += efunc(i, "unrecognized variable type %d\n",
8874 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8875 err += efunc(i, "%d exceeds variable id limit\n", id);
8879 if (id < DIF_VAR_OTHER_UBASE)
8883 * For user-defined variables, we need to check that this
8884 * definition is identical to any previous definition that we
8887 ndx = id - DIF_VAR_OTHER_UBASE;
8889 switch (v->dtdv_scope) {
8890 case DIFV_SCOPE_GLOBAL:
8891 if (ndx < vstate->dtvs_nglobals) {
8892 dtrace_statvar_t *svar;
8894 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8895 existing = &svar->dtsv_var;
8900 case DIFV_SCOPE_THREAD:
8901 if (ndx < vstate->dtvs_ntlocals)
8902 existing = &vstate->dtvs_tlocals[ndx];
8905 case DIFV_SCOPE_LOCAL:
8906 if (ndx < vstate->dtvs_nlocals) {
8907 dtrace_statvar_t *svar;
8909 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8910 existing = &svar->dtsv_var;
8918 if (vt->dtdt_flags & DIF_TF_BYREF) {
8919 if (vt->dtdt_size == 0) {
8920 err += efunc(i, "zero-sized variable\n");
8924 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8925 vt->dtdt_size > dtrace_global_maxsize) {
8926 err += efunc(i, "oversized by-ref global\n");
8931 if (existing == NULL || existing->dtdv_id == 0)
8934 ASSERT(existing->dtdv_id == v->dtdv_id);
8935 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8937 if (existing->dtdv_kind != v->dtdv_kind)
8938 err += efunc(i, "%d changed variable kind\n", id);
8940 et = &existing->dtdv_type;
8942 if (vt->dtdt_flags != et->dtdt_flags) {
8943 err += efunc(i, "%d changed variable type flags\n", id);
8947 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8948 err += efunc(i, "%d changed variable type size\n", id);
8957 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
8958 * are much more constrained than normal DIFOs. Specifically, they may
8961 * 1. Make calls to subroutines other than copyin(), copyinstr() or
8962 * miscellaneous string routines
8963 * 2. Access DTrace variables other than the args[] array, and the
8964 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8965 * 3. Have thread-local variables.
8966 * 4. Have dynamic variables.
8969 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8971 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8975 for (pc = 0; pc < dp->dtdo_len; pc++) {
8976 dif_instr_t instr = dp->dtdo_buf[pc];
8978 uint_t v = DIF_INSTR_VAR(instr);
8979 uint_t subr = DIF_INSTR_SUBR(instr);
8980 uint_t op = DIF_INSTR_OP(instr);
9035 case DIF_OP_FLUSHTS:
9047 if (v >= DIF_VAR_OTHER_UBASE)
9050 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9053 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9054 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9055 v == DIF_VAR_EXECARGS ||
9056 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9057 v == DIF_VAR_UID || v == DIF_VAR_GID)
9060 err += efunc(pc, "illegal variable %u\n", v);
9067 err += efunc(pc, "illegal dynamic variable load\n");
9073 err += efunc(pc, "illegal dynamic variable store\n");
9077 if (subr == DIF_SUBR_ALLOCA ||
9078 subr == DIF_SUBR_BCOPY ||
9079 subr == DIF_SUBR_COPYIN ||
9080 subr == DIF_SUBR_COPYINTO ||
9081 subr == DIF_SUBR_COPYINSTR ||
9082 subr == DIF_SUBR_INDEX ||
9083 subr == DIF_SUBR_INET_NTOA ||
9084 subr == DIF_SUBR_INET_NTOA6 ||
9085 subr == DIF_SUBR_INET_NTOP ||
9086 subr == DIF_SUBR_LLTOSTR ||
9087 subr == DIF_SUBR_RINDEX ||
9088 subr == DIF_SUBR_STRCHR ||
9089 subr == DIF_SUBR_STRJOIN ||
9090 subr == DIF_SUBR_STRRCHR ||
9091 subr == DIF_SUBR_STRSTR ||
9092 subr == DIF_SUBR_HTONS ||
9093 subr == DIF_SUBR_HTONL ||
9094 subr == DIF_SUBR_HTONLL ||
9095 subr == DIF_SUBR_NTOHS ||
9096 subr == DIF_SUBR_NTOHL ||
9097 subr == DIF_SUBR_NTOHLL ||
9098 subr == DIF_SUBR_MEMREF ||
9099 subr == DIF_SUBR_TYPEREF)
9102 err += efunc(pc, "invalid subr %u\n", subr);
9106 err += efunc(pc, "invalid opcode %u\n",
9107 DIF_INSTR_OP(instr));
9115 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9119 dtrace_difo_cacheable(dtrace_difo_t *dp)
9126 for (i = 0; i < dp->dtdo_varlen; i++) {
9127 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9129 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9132 switch (v->dtdv_id) {
9133 case DIF_VAR_CURTHREAD:
9136 case DIF_VAR_EXECARGS:
9137 case DIF_VAR_EXECNAME:
9138 case DIF_VAR_ZONENAME:
9147 * This DIF object may be cacheable. Now we need to look for any
9148 * array loading instructions, any memory loading instructions, or
9149 * any stores to thread-local variables.
9151 for (i = 0; i < dp->dtdo_len; i++) {
9152 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9154 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9155 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9156 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9157 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9165 dtrace_difo_hold(dtrace_difo_t *dp)
9169 ASSERT(MUTEX_HELD(&dtrace_lock));
9172 ASSERT(dp->dtdo_refcnt != 0);
9175 * We need to check this DIF object for references to the variable
9176 * DIF_VAR_VTIMESTAMP.
9178 for (i = 0; i < dp->dtdo_varlen; i++) {
9179 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9181 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9184 if (dtrace_vtime_references++ == 0)
9185 dtrace_vtime_enable();
9190 * This routine calculates the dynamic variable chunksize for a given DIF
9191 * object. The calculation is not fool-proof, and can probably be tricked by
9192 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9193 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9194 * if a dynamic variable size exceeds the chunksize.
9197 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9200 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9201 const dif_instr_t *text = dp->dtdo_buf;
9207 for (pc = 0; pc < dp->dtdo_len; pc++) {
9208 dif_instr_t instr = text[pc];
9209 uint_t op = DIF_INSTR_OP(instr);
9210 uint_t rd = DIF_INSTR_RD(instr);
9211 uint_t r1 = DIF_INSTR_R1(instr);
9215 dtrace_key_t *key = tupregs;
9219 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9224 key = &tupregs[DIF_DTR_NREGS];
9225 key[0].dttk_size = 0;
9226 key[1].dttk_size = 0;
9228 scope = DIFV_SCOPE_THREAD;
9235 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9236 key[nkeys++].dttk_size = 0;
9238 key[nkeys++].dttk_size = 0;
9240 if (op == DIF_OP_STTAA) {
9241 scope = DIFV_SCOPE_THREAD;
9243 scope = DIFV_SCOPE_GLOBAL;
9249 if (ttop == DIF_DTR_NREGS)
9252 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9254 * If the register for the size of the "pushtr"
9255 * is %r0 (or the value is 0) and the type is
9256 * a string, we'll use the system-wide default
9259 tupregs[ttop++].dttk_size =
9260 dtrace_strsize_default;
9265 tupregs[ttop++].dttk_size = sval;
9271 if (ttop == DIF_DTR_NREGS)
9274 tupregs[ttop++].dttk_size = 0;
9277 case DIF_OP_FLUSHTS:
9294 * We have a dynamic variable allocation; calculate its size.
9296 for (ksize = 0, i = 0; i < nkeys; i++)
9297 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9299 size = sizeof (dtrace_dynvar_t);
9300 size += sizeof (dtrace_key_t) * (nkeys - 1);
9304 * Now we need to determine the size of the stored data.
9306 id = DIF_INSTR_VAR(instr);
9308 for (i = 0; i < dp->dtdo_varlen; i++) {
9309 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9311 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9312 size += v->dtdv_type.dtdt_size;
9317 if (i == dp->dtdo_varlen)
9321 * We have the size. If this is larger than the chunk size
9322 * for our dynamic variable state, reset the chunk size.
9324 size = P2ROUNDUP(size, sizeof (uint64_t));
9326 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9327 vstate->dtvs_dynvars.dtds_chunksize = size;
9332 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9334 int i, oldsvars, osz, nsz, otlocals, ntlocals;
9337 ASSERT(MUTEX_HELD(&dtrace_lock));
9338 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9340 for (i = 0; i < dp->dtdo_varlen; i++) {
9341 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9342 dtrace_statvar_t *svar, ***svarp = NULL;
9344 uint8_t scope = v->dtdv_scope;
9347 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9350 id -= DIF_VAR_OTHER_UBASE;
9353 case DIFV_SCOPE_THREAD:
9354 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9355 dtrace_difv_t *tlocals;
9357 if ((ntlocals = (otlocals << 1)) == 0)
9360 osz = otlocals * sizeof (dtrace_difv_t);
9361 nsz = ntlocals * sizeof (dtrace_difv_t);
9363 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9366 bcopy(vstate->dtvs_tlocals,
9368 kmem_free(vstate->dtvs_tlocals, osz);
9371 vstate->dtvs_tlocals = tlocals;
9372 vstate->dtvs_ntlocals = ntlocals;
9375 vstate->dtvs_tlocals[id] = *v;
9378 case DIFV_SCOPE_LOCAL:
9379 np = &vstate->dtvs_nlocals;
9380 svarp = &vstate->dtvs_locals;
9382 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9383 dsize = NCPU * (v->dtdv_type.dtdt_size +
9386 dsize = NCPU * sizeof (uint64_t);
9390 case DIFV_SCOPE_GLOBAL:
9391 np = &vstate->dtvs_nglobals;
9392 svarp = &vstate->dtvs_globals;
9394 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9395 dsize = v->dtdv_type.dtdt_size +
9404 while (id >= (oldsvars = *np)) {
9405 dtrace_statvar_t **statics;
9406 int newsvars, oldsize, newsize;
9408 if ((newsvars = (oldsvars << 1)) == 0)
9411 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9412 newsize = newsvars * sizeof (dtrace_statvar_t *);
9414 statics = kmem_zalloc(newsize, KM_SLEEP);
9417 bcopy(*svarp, statics, oldsize);
9418 kmem_free(*svarp, oldsize);
9425 if ((svar = (*svarp)[id]) == NULL) {
9426 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9427 svar->dtsv_var = *v;
9429 if ((svar->dtsv_size = dsize) != 0) {
9430 svar->dtsv_data = (uint64_t)(uintptr_t)
9431 kmem_zalloc(dsize, KM_SLEEP);
9434 (*svarp)[id] = svar;
9437 svar->dtsv_refcnt++;
9440 dtrace_difo_chunksize(dp, vstate);
9441 dtrace_difo_hold(dp);
9444 static dtrace_difo_t *
9445 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9450 ASSERT(dp->dtdo_buf != NULL);
9451 ASSERT(dp->dtdo_refcnt != 0);
9453 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9455 ASSERT(dp->dtdo_buf != NULL);
9456 sz = dp->dtdo_len * sizeof (dif_instr_t);
9457 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9458 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9459 new->dtdo_len = dp->dtdo_len;
9461 if (dp->dtdo_strtab != NULL) {
9462 ASSERT(dp->dtdo_strlen != 0);
9463 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9464 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9465 new->dtdo_strlen = dp->dtdo_strlen;
9468 if (dp->dtdo_inttab != NULL) {
9469 ASSERT(dp->dtdo_intlen != 0);
9470 sz = dp->dtdo_intlen * sizeof (uint64_t);
9471 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9472 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9473 new->dtdo_intlen = dp->dtdo_intlen;
9476 if (dp->dtdo_vartab != NULL) {
9477 ASSERT(dp->dtdo_varlen != 0);
9478 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9479 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9480 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9481 new->dtdo_varlen = dp->dtdo_varlen;
9484 dtrace_difo_init(new, vstate);
9489 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9493 ASSERT(dp->dtdo_refcnt == 0);
9495 for (i = 0; i < dp->dtdo_varlen; i++) {
9496 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9497 dtrace_statvar_t *svar, **svarp = NULL;
9499 uint8_t scope = v->dtdv_scope;
9503 case DIFV_SCOPE_THREAD:
9506 case DIFV_SCOPE_LOCAL:
9507 np = &vstate->dtvs_nlocals;
9508 svarp = vstate->dtvs_locals;
9511 case DIFV_SCOPE_GLOBAL:
9512 np = &vstate->dtvs_nglobals;
9513 svarp = vstate->dtvs_globals;
9520 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9523 id -= DIF_VAR_OTHER_UBASE;
9527 ASSERT(svar != NULL);
9528 ASSERT(svar->dtsv_refcnt > 0);
9530 if (--svar->dtsv_refcnt > 0)
9533 if (svar->dtsv_size != 0) {
9534 ASSERT(svar->dtsv_data != 0);
9535 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9539 kmem_free(svar, sizeof (dtrace_statvar_t));
9543 if (dp->dtdo_buf != NULL)
9544 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9545 if (dp->dtdo_inttab != NULL)
9546 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9547 if (dp->dtdo_strtab != NULL)
9548 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9549 if (dp->dtdo_vartab != NULL)
9550 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9552 kmem_free(dp, sizeof (dtrace_difo_t));
9556 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9560 ASSERT(MUTEX_HELD(&dtrace_lock));
9561 ASSERT(dp->dtdo_refcnt != 0);
9563 for (i = 0; i < dp->dtdo_varlen; i++) {
9564 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9566 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9569 ASSERT(dtrace_vtime_references > 0);
9570 if (--dtrace_vtime_references == 0)
9571 dtrace_vtime_disable();
9574 if (--dp->dtdo_refcnt == 0)
9575 dtrace_difo_destroy(dp, vstate);
9579 * DTrace Format Functions
9582 dtrace_format_add(dtrace_state_t *state, char *str)
9585 uint16_t ndx, len = strlen(str) + 1;
9587 fmt = kmem_zalloc(len, KM_SLEEP);
9588 bcopy(str, fmt, len);
9590 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9591 if (state->dts_formats[ndx] == NULL) {
9592 state->dts_formats[ndx] = fmt;
9597 if (state->dts_nformats == USHRT_MAX) {
9599 * This is only likely if a denial-of-service attack is being
9600 * attempted. As such, it's okay to fail silently here.
9602 kmem_free(fmt, len);
9607 * For simplicity, we always resize the formats array to be exactly the
9608 * number of formats.
9610 ndx = state->dts_nformats++;
9611 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9613 if (state->dts_formats != NULL) {
9615 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9616 kmem_free(state->dts_formats, ndx * sizeof (char *));
9619 state->dts_formats = new;
9620 state->dts_formats[ndx] = fmt;
9626 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9630 ASSERT(state->dts_formats != NULL);
9631 ASSERT(format <= state->dts_nformats);
9632 ASSERT(state->dts_formats[format - 1] != NULL);
9634 fmt = state->dts_formats[format - 1];
9635 kmem_free(fmt, strlen(fmt) + 1);
9636 state->dts_formats[format - 1] = NULL;
9640 dtrace_format_destroy(dtrace_state_t *state)
9644 if (state->dts_nformats == 0) {
9645 ASSERT(state->dts_formats == NULL);
9649 ASSERT(state->dts_formats != NULL);
9651 for (i = 0; i < state->dts_nformats; i++) {
9652 char *fmt = state->dts_formats[i];
9657 kmem_free(fmt, strlen(fmt) + 1);
9660 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9661 state->dts_nformats = 0;
9662 state->dts_formats = NULL;
9666 * DTrace Predicate Functions
9668 static dtrace_predicate_t *
9669 dtrace_predicate_create(dtrace_difo_t *dp)
9671 dtrace_predicate_t *pred;
9673 ASSERT(MUTEX_HELD(&dtrace_lock));
9674 ASSERT(dp->dtdo_refcnt != 0);
9676 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9677 pred->dtp_difo = dp;
9678 pred->dtp_refcnt = 1;
9680 if (!dtrace_difo_cacheable(dp))
9683 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9685 * This is only theoretically possible -- we have had 2^32
9686 * cacheable predicates on this machine. We cannot allow any
9687 * more predicates to become cacheable: as unlikely as it is,
9688 * there may be a thread caching a (now stale) predicate cache
9689 * ID. (N.B.: the temptation is being successfully resisted to
9690 * have this cmn_err() "Holy shit -- we executed this code!")
9695 pred->dtp_cacheid = dtrace_predcache_id++;
9701 dtrace_predicate_hold(dtrace_predicate_t *pred)
9703 ASSERT(MUTEX_HELD(&dtrace_lock));
9704 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9705 ASSERT(pred->dtp_refcnt > 0);
9711 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9713 dtrace_difo_t *dp = pred->dtp_difo;
9715 ASSERT(MUTEX_HELD(&dtrace_lock));
9716 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9717 ASSERT(pred->dtp_refcnt > 0);
9719 if (--pred->dtp_refcnt == 0) {
9720 dtrace_difo_release(pred->dtp_difo, vstate);
9721 kmem_free(pred, sizeof (dtrace_predicate_t));
9726 * DTrace Action Description Functions
9728 static dtrace_actdesc_t *
9729 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9730 uint64_t uarg, uint64_t arg)
9732 dtrace_actdesc_t *act;
9735 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9736 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9739 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9740 act->dtad_kind = kind;
9741 act->dtad_ntuple = ntuple;
9742 act->dtad_uarg = uarg;
9743 act->dtad_arg = arg;
9744 act->dtad_refcnt = 1;
9750 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9752 ASSERT(act->dtad_refcnt >= 1);
9757 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9759 dtrace_actkind_t kind = act->dtad_kind;
9762 ASSERT(act->dtad_refcnt >= 1);
9764 if (--act->dtad_refcnt != 0)
9767 if ((dp = act->dtad_difo) != NULL)
9768 dtrace_difo_release(dp, vstate);
9770 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9771 char *str = (char *)(uintptr_t)act->dtad_arg;
9774 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9775 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9779 kmem_free(str, strlen(str) + 1);
9782 kmem_free(act, sizeof (dtrace_actdesc_t));
9786 * DTrace ECB Functions
9788 static dtrace_ecb_t *
9789 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9794 ASSERT(MUTEX_HELD(&dtrace_lock));
9796 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9797 ecb->dte_predicate = NULL;
9798 ecb->dte_probe = probe;
9801 * The default size is the size of the default action: recording
9804 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9805 ecb->dte_alignment = sizeof (dtrace_epid_t);
9807 epid = state->dts_epid++;
9809 if (epid - 1 >= state->dts_necbs) {
9810 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9811 int necbs = state->dts_necbs << 1;
9813 ASSERT(epid == state->dts_necbs + 1);
9816 ASSERT(oecbs == NULL);
9820 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9823 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9825 dtrace_membar_producer();
9826 state->dts_ecbs = ecbs;
9828 if (oecbs != NULL) {
9830 * If this state is active, we must dtrace_sync()
9831 * before we can free the old dts_ecbs array: we're
9832 * coming in hot, and there may be active ring
9833 * buffer processing (which indexes into the dts_ecbs
9834 * array) on another CPU.
9836 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9839 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9842 dtrace_membar_producer();
9843 state->dts_necbs = necbs;
9846 ecb->dte_state = state;
9848 ASSERT(state->dts_ecbs[epid - 1] == NULL);
9849 dtrace_membar_producer();
9850 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9856 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9858 dtrace_probe_t *probe = ecb->dte_probe;
9860 ASSERT(MUTEX_HELD(&cpu_lock));
9861 ASSERT(MUTEX_HELD(&dtrace_lock));
9862 ASSERT(ecb->dte_next == NULL);
9864 if (probe == NULL) {
9866 * This is the NULL probe -- there's nothing to do.
9871 if (probe->dtpr_ecb == NULL) {
9872 dtrace_provider_t *prov = probe->dtpr_provider;
9875 * We're the first ECB on this probe.
9877 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9879 if (ecb->dte_predicate != NULL)
9880 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9882 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9883 probe->dtpr_id, probe->dtpr_arg);
9886 * This probe is already active. Swing the last pointer to
9887 * point to the new ECB, and issue a dtrace_sync() to assure
9888 * that all CPUs have seen the change.
9890 ASSERT(probe->dtpr_ecb_last != NULL);
9891 probe->dtpr_ecb_last->dte_next = ecb;
9892 probe->dtpr_ecb_last = ecb;
9893 probe->dtpr_predcache = 0;
9900 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9902 dtrace_action_t *act;
9903 uint32_t curneeded = UINT32_MAX;
9904 uint32_t aggbase = UINT32_MAX;
9907 * If we record anything, we always record the dtrace_rechdr_t. (And
9908 * we always record it first.)
9910 ecb->dte_size = sizeof (dtrace_rechdr_t);
9911 ecb->dte_alignment = sizeof (dtrace_epid_t);
9913 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9914 dtrace_recdesc_t *rec = &act->dta_rec;
9915 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9917 ecb->dte_alignment = MAX(ecb->dte_alignment,
9918 rec->dtrd_alignment);
9920 if (DTRACEACT_ISAGG(act->dta_kind)) {
9921 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9923 ASSERT(rec->dtrd_size != 0);
9924 ASSERT(agg->dtag_first != NULL);
9925 ASSERT(act->dta_prev->dta_intuple);
9926 ASSERT(aggbase != UINT32_MAX);
9927 ASSERT(curneeded != UINT32_MAX);
9929 agg->dtag_base = aggbase;
9931 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9932 rec->dtrd_offset = curneeded;
9933 curneeded += rec->dtrd_size;
9934 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9936 aggbase = UINT32_MAX;
9937 curneeded = UINT32_MAX;
9938 } else if (act->dta_intuple) {
9939 if (curneeded == UINT32_MAX) {
9941 * This is the first record in a tuple. Align
9942 * curneeded to be at offset 4 in an 8-byte
9945 ASSERT(act->dta_prev == NULL ||
9946 !act->dta_prev->dta_intuple);
9947 ASSERT3U(aggbase, ==, UINT32_MAX);
9948 curneeded = P2PHASEUP(ecb->dte_size,
9949 sizeof (uint64_t), sizeof (dtrace_aggid_t));
9951 aggbase = curneeded - sizeof (dtrace_aggid_t);
9952 ASSERT(IS_P2ALIGNED(aggbase,
9953 sizeof (uint64_t)));
9955 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9956 rec->dtrd_offset = curneeded;
9957 curneeded += rec->dtrd_size;
9959 /* tuples must be followed by an aggregation */
9960 ASSERT(act->dta_prev == NULL ||
9961 !act->dta_prev->dta_intuple);
9963 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
9964 rec->dtrd_alignment);
9965 rec->dtrd_offset = ecb->dte_size;
9966 ecb->dte_size += rec->dtrd_size;
9967 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
9971 if ((act = ecb->dte_action) != NULL &&
9972 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9973 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
9975 * If the size is still sizeof (dtrace_rechdr_t), then all
9976 * actions store no data; set the size to 0.
9981 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
9982 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
9983 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
9987 static dtrace_action_t *
9988 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9990 dtrace_aggregation_t *agg;
9991 size_t size = sizeof (uint64_t);
9992 int ntuple = desc->dtad_ntuple;
9993 dtrace_action_t *act;
9994 dtrace_recdesc_t *frec;
9995 dtrace_aggid_t aggid;
9996 dtrace_state_t *state = ecb->dte_state;
9998 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9999 agg->dtag_ecb = ecb;
10001 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10003 switch (desc->dtad_kind) {
10004 case DTRACEAGG_MIN:
10005 agg->dtag_initial = INT64_MAX;
10006 agg->dtag_aggregate = dtrace_aggregate_min;
10009 case DTRACEAGG_MAX:
10010 agg->dtag_initial = INT64_MIN;
10011 agg->dtag_aggregate = dtrace_aggregate_max;
10014 case DTRACEAGG_COUNT:
10015 agg->dtag_aggregate = dtrace_aggregate_count;
10018 case DTRACEAGG_QUANTIZE:
10019 agg->dtag_aggregate = dtrace_aggregate_quantize;
10020 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10024 case DTRACEAGG_LQUANTIZE: {
10025 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10026 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10028 agg->dtag_initial = desc->dtad_arg;
10029 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10031 if (step == 0 || levels == 0)
10034 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10038 case DTRACEAGG_LLQUANTIZE: {
10039 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10040 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10041 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10042 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10045 agg->dtag_initial = desc->dtad_arg;
10046 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10048 if (factor < 2 || low >= high || nsteps < factor)
10052 * Now check that the number of steps evenly divides a power
10053 * of the factor. (This assures both integer bucket size and
10054 * linearity within each magnitude.)
10056 for (v = factor; v < nsteps; v *= factor)
10059 if ((v % nsteps) || (nsteps % factor))
10062 size = (dtrace_aggregate_llquantize_bucket(factor,
10063 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10067 case DTRACEAGG_AVG:
10068 agg->dtag_aggregate = dtrace_aggregate_avg;
10069 size = sizeof (uint64_t) * 2;
10072 case DTRACEAGG_STDDEV:
10073 agg->dtag_aggregate = dtrace_aggregate_stddev;
10074 size = sizeof (uint64_t) * 4;
10077 case DTRACEAGG_SUM:
10078 agg->dtag_aggregate = dtrace_aggregate_sum;
10085 agg->dtag_action.dta_rec.dtrd_size = size;
10091 * We must make sure that we have enough actions for the n-tuple.
10093 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10094 if (DTRACEACT_ISAGG(act->dta_kind))
10097 if (--ntuple == 0) {
10099 * This is the action with which our n-tuple begins.
10101 agg->dtag_first = act;
10107 * This n-tuple is short by ntuple elements. Return failure.
10109 ASSERT(ntuple != 0);
10111 kmem_free(agg, sizeof (dtrace_aggregation_t));
10116 * If the last action in the tuple has a size of zero, it's actually
10117 * an expression argument for the aggregating action.
10119 ASSERT(ecb->dte_action_last != NULL);
10120 act = ecb->dte_action_last;
10122 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10123 ASSERT(act->dta_difo != NULL);
10125 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10126 agg->dtag_hasarg = 1;
10130 * We need to allocate an id for this aggregation.
10133 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10134 VM_BESTFIT | VM_SLEEP);
10136 aggid = alloc_unr(state->dts_aggid_arena);
10139 if (aggid - 1 >= state->dts_naggregations) {
10140 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10141 dtrace_aggregation_t **aggs;
10142 int naggs = state->dts_naggregations << 1;
10143 int onaggs = state->dts_naggregations;
10145 ASSERT(aggid == state->dts_naggregations + 1);
10148 ASSERT(oaggs == NULL);
10152 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10154 if (oaggs != NULL) {
10155 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10156 kmem_free(oaggs, onaggs * sizeof (*aggs));
10159 state->dts_aggregations = aggs;
10160 state->dts_naggregations = naggs;
10163 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10164 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10166 frec = &agg->dtag_first->dta_rec;
10167 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10168 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10170 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10171 ASSERT(!act->dta_intuple);
10172 act->dta_intuple = 1;
10175 return (&agg->dtag_action);
10179 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10181 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10182 dtrace_state_t *state = ecb->dte_state;
10183 dtrace_aggid_t aggid = agg->dtag_id;
10185 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10187 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10189 free_unr(state->dts_aggid_arena, aggid);
10192 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10193 state->dts_aggregations[aggid - 1] = NULL;
10195 kmem_free(agg, sizeof (dtrace_aggregation_t));
10199 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10201 dtrace_action_t *action, *last;
10202 dtrace_difo_t *dp = desc->dtad_difo;
10203 uint32_t size = 0, align = sizeof (uint8_t), mask;
10204 uint16_t format = 0;
10205 dtrace_recdesc_t *rec;
10206 dtrace_state_t *state = ecb->dte_state;
10207 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10208 uint64_t arg = desc->dtad_arg;
10210 ASSERT(MUTEX_HELD(&dtrace_lock));
10211 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10213 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10215 * If this is an aggregating action, there must be neither
10216 * a speculate nor a commit on the action chain.
10218 dtrace_action_t *act;
10220 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10221 if (act->dta_kind == DTRACEACT_COMMIT)
10224 if (act->dta_kind == DTRACEACT_SPECULATE)
10228 action = dtrace_ecb_aggregation_create(ecb, desc);
10230 if (action == NULL)
10233 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10234 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10235 dp != NULL && dp->dtdo_destructive)) {
10236 state->dts_destructive = 1;
10239 switch (desc->dtad_kind) {
10240 case DTRACEACT_PRINTF:
10241 case DTRACEACT_PRINTA:
10242 case DTRACEACT_SYSTEM:
10243 case DTRACEACT_FREOPEN:
10244 case DTRACEACT_DIFEXPR:
10246 * We know that our arg is a string -- turn it into a
10250 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10251 desc->dtad_kind == DTRACEACT_DIFEXPR);
10256 ASSERT(arg > KERNELBASE);
10258 format = dtrace_format_add(state,
10259 (char *)(uintptr_t)arg);
10263 case DTRACEACT_LIBACT:
10264 case DTRACEACT_TRACEMEM:
10265 case DTRACEACT_TRACEMEM_DYNSIZE:
10269 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10272 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10273 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10276 size = opt[DTRACEOPT_STRSIZE];
10281 case DTRACEACT_STACK:
10282 if ((nframes = arg) == 0) {
10283 nframes = opt[DTRACEOPT_STACKFRAMES];
10284 ASSERT(nframes > 0);
10288 size = nframes * sizeof (pc_t);
10291 case DTRACEACT_JSTACK:
10292 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10293 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10295 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10296 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10298 arg = DTRACE_USTACK_ARG(nframes, strsize);
10301 case DTRACEACT_USTACK:
10302 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10303 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10304 strsize = DTRACE_USTACK_STRSIZE(arg);
10305 nframes = opt[DTRACEOPT_USTACKFRAMES];
10306 ASSERT(nframes > 0);
10307 arg = DTRACE_USTACK_ARG(nframes, strsize);
10311 * Save a slot for the pid.
10313 size = (nframes + 1) * sizeof (uint64_t);
10314 size += DTRACE_USTACK_STRSIZE(arg);
10315 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10319 case DTRACEACT_SYM:
10320 case DTRACEACT_MOD:
10321 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10322 sizeof (uint64_t)) ||
10323 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10327 case DTRACEACT_USYM:
10328 case DTRACEACT_UMOD:
10329 case DTRACEACT_UADDR:
10331 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10332 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10336 * We have a slot for the pid, plus a slot for the
10337 * argument. To keep things simple (aligned with
10338 * bitness-neutral sizing), we store each as a 64-bit
10341 size = 2 * sizeof (uint64_t);
10344 case DTRACEACT_STOP:
10345 case DTRACEACT_BREAKPOINT:
10346 case DTRACEACT_PANIC:
10349 case DTRACEACT_CHILL:
10350 case DTRACEACT_DISCARD:
10351 case DTRACEACT_RAISE:
10356 case DTRACEACT_EXIT:
10358 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10359 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10363 case DTRACEACT_SPECULATE:
10364 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10370 state->dts_speculates = 1;
10373 case DTRACEACT_PRINTM:
10374 size = dp->dtdo_rtype.dtdt_size;
10377 case DTRACEACT_PRINTT:
10378 size = dp->dtdo_rtype.dtdt_size;
10381 case DTRACEACT_COMMIT: {
10382 dtrace_action_t *act = ecb->dte_action;
10384 for (; act != NULL; act = act->dta_next) {
10385 if (act->dta_kind == DTRACEACT_COMMIT)
10398 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10400 * If this is a data-storing action or a speculate,
10401 * we must be sure that there isn't a commit on the
10404 dtrace_action_t *act = ecb->dte_action;
10406 for (; act != NULL; act = act->dta_next) {
10407 if (act->dta_kind == DTRACEACT_COMMIT)
10412 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10413 action->dta_rec.dtrd_size = size;
10416 action->dta_refcnt = 1;
10417 rec = &action->dta_rec;
10418 size = rec->dtrd_size;
10420 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10421 if (!(size & mask)) {
10427 action->dta_kind = desc->dtad_kind;
10429 if ((action->dta_difo = dp) != NULL)
10430 dtrace_difo_hold(dp);
10432 rec->dtrd_action = action->dta_kind;
10433 rec->dtrd_arg = arg;
10434 rec->dtrd_uarg = desc->dtad_uarg;
10435 rec->dtrd_alignment = (uint16_t)align;
10436 rec->dtrd_format = format;
10438 if ((last = ecb->dte_action_last) != NULL) {
10439 ASSERT(ecb->dte_action != NULL);
10440 action->dta_prev = last;
10441 last->dta_next = action;
10443 ASSERT(ecb->dte_action == NULL);
10444 ecb->dte_action = action;
10447 ecb->dte_action_last = action;
10453 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10455 dtrace_action_t *act = ecb->dte_action, *next;
10456 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10460 if (act != NULL && act->dta_refcnt > 1) {
10461 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10464 for (; act != NULL; act = next) {
10465 next = act->dta_next;
10466 ASSERT(next != NULL || act == ecb->dte_action_last);
10467 ASSERT(act->dta_refcnt == 1);
10469 if ((format = act->dta_rec.dtrd_format) != 0)
10470 dtrace_format_remove(ecb->dte_state, format);
10472 if ((dp = act->dta_difo) != NULL)
10473 dtrace_difo_release(dp, vstate);
10475 if (DTRACEACT_ISAGG(act->dta_kind)) {
10476 dtrace_ecb_aggregation_destroy(ecb, act);
10478 kmem_free(act, sizeof (dtrace_action_t));
10483 ecb->dte_action = NULL;
10484 ecb->dte_action_last = NULL;
10489 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10492 * We disable the ECB by removing it from its probe.
10494 dtrace_ecb_t *pecb, *prev = NULL;
10495 dtrace_probe_t *probe = ecb->dte_probe;
10497 ASSERT(MUTEX_HELD(&dtrace_lock));
10499 if (probe == NULL) {
10501 * This is the NULL probe; there is nothing to disable.
10506 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10512 ASSERT(pecb != NULL);
10514 if (prev == NULL) {
10515 probe->dtpr_ecb = ecb->dte_next;
10517 prev->dte_next = ecb->dte_next;
10520 if (ecb == probe->dtpr_ecb_last) {
10521 ASSERT(ecb->dte_next == NULL);
10522 probe->dtpr_ecb_last = prev;
10526 * The ECB has been disconnected from the probe; now sync to assure
10527 * that all CPUs have seen the change before returning.
10531 if (probe->dtpr_ecb == NULL) {
10533 * That was the last ECB on the probe; clear the predicate
10534 * cache ID for the probe, disable it and sync one more time
10535 * to assure that we'll never hit it again.
10537 dtrace_provider_t *prov = probe->dtpr_provider;
10539 ASSERT(ecb->dte_next == NULL);
10540 ASSERT(probe->dtpr_ecb_last == NULL);
10541 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10542 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10543 probe->dtpr_id, probe->dtpr_arg);
10547 * There is at least one ECB remaining on the probe. If there
10548 * is _exactly_ one, set the probe's predicate cache ID to be
10549 * the predicate cache ID of the remaining ECB.
10551 ASSERT(probe->dtpr_ecb_last != NULL);
10552 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10554 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10555 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10557 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10560 probe->dtpr_predcache = p->dtp_cacheid;
10563 ecb->dte_next = NULL;
10568 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10570 dtrace_state_t *state = ecb->dte_state;
10571 dtrace_vstate_t *vstate = &state->dts_vstate;
10572 dtrace_predicate_t *pred;
10573 dtrace_epid_t epid = ecb->dte_epid;
10575 ASSERT(MUTEX_HELD(&dtrace_lock));
10576 ASSERT(ecb->dte_next == NULL);
10577 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10579 if ((pred = ecb->dte_predicate) != NULL)
10580 dtrace_predicate_release(pred, vstate);
10582 dtrace_ecb_action_remove(ecb);
10584 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10585 state->dts_ecbs[epid - 1] = NULL;
10587 kmem_free(ecb, sizeof (dtrace_ecb_t));
10590 static dtrace_ecb_t *
10591 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10592 dtrace_enabling_t *enab)
10595 dtrace_predicate_t *pred;
10596 dtrace_actdesc_t *act;
10597 dtrace_provider_t *prov;
10598 dtrace_ecbdesc_t *desc = enab->dten_current;
10600 ASSERT(MUTEX_HELD(&dtrace_lock));
10601 ASSERT(state != NULL);
10603 ecb = dtrace_ecb_add(state, probe);
10604 ecb->dte_uarg = desc->dted_uarg;
10606 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10607 dtrace_predicate_hold(pred);
10608 ecb->dte_predicate = pred;
10611 if (probe != NULL) {
10613 * If the provider shows more leg than the consumer is old
10614 * enough to see, we need to enable the appropriate implicit
10615 * predicate bits to prevent the ecb from activating at
10618 * Providers specifying DTRACE_PRIV_USER at register time
10619 * are stating that they need the /proc-style privilege
10620 * model to be enforced, and this is what DTRACE_COND_OWNER
10621 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10623 prov = probe->dtpr_provider;
10624 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10625 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10626 ecb->dte_cond |= DTRACE_COND_OWNER;
10628 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10629 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10630 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10633 * If the provider shows us kernel innards and the user
10634 * is lacking sufficient privilege, enable the
10635 * DTRACE_COND_USERMODE implicit predicate.
10637 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10638 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10639 ecb->dte_cond |= DTRACE_COND_USERMODE;
10642 if (dtrace_ecb_create_cache != NULL) {
10644 * If we have a cached ecb, we'll use its action list instead
10645 * of creating our own (saving both time and space).
10647 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10648 dtrace_action_t *act = cached->dte_action;
10651 ASSERT(act->dta_refcnt > 0);
10653 ecb->dte_action = act;
10654 ecb->dte_action_last = cached->dte_action_last;
10655 ecb->dte_needed = cached->dte_needed;
10656 ecb->dte_size = cached->dte_size;
10657 ecb->dte_alignment = cached->dte_alignment;
10663 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10664 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10665 dtrace_ecb_destroy(ecb);
10670 dtrace_ecb_resize(ecb);
10672 return (dtrace_ecb_create_cache = ecb);
10676 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10679 dtrace_enabling_t *enab = arg;
10680 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10682 ASSERT(state != NULL);
10684 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10686 * This probe was created in a generation for which this
10687 * enabling has previously created ECBs; we don't want to
10688 * enable it again, so just kick out.
10690 return (DTRACE_MATCH_NEXT);
10693 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10694 return (DTRACE_MATCH_DONE);
10696 dtrace_ecb_enable(ecb);
10697 return (DTRACE_MATCH_NEXT);
10700 static dtrace_ecb_t *
10701 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10705 ASSERT(MUTEX_HELD(&dtrace_lock));
10707 if (id == 0 || id > state->dts_necbs)
10710 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10711 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10713 return (state->dts_ecbs[id - 1]);
10716 static dtrace_aggregation_t *
10717 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10719 dtrace_aggregation_t *agg;
10721 ASSERT(MUTEX_HELD(&dtrace_lock));
10723 if (id == 0 || id > state->dts_naggregations)
10726 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10727 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10728 agg->dtag_id == id);
10730 return (state->dts_aggregations[id - 1]);
10734 * DTrace Buffer Functions
10736 * The following functions manipulate DTrace buffers. Most of these functions
10737 * are called in the context of establishing or processing consumer state;
10738 * exceptions are explicitly noted.
10742 * Note: called from cross call context. This function switches the two
10743 * buffers on a given CPU. The atomicity of this operation is assured by
10744 * disabling interrupts while the actual switch takes place; the disabling of
10745 * interrupts serializes the execution with any execution of dtrace_probe() on
10749 dtrace_buffer_switch(dtrace_buffer_t *buf)
10751 caddr_t tomax = buf->dtb_tomax;
10752 caddr_t xamot = buf->dtb_xamot;
10753 dtrace_icookie_t cookie;
10756 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10757 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10759 cookie = dtrace_interrupt_disable();
10760 now = dtrace_gethrtime();
10761 buf->dtb_tomax = xamot;
10762 buf->dtb_xamot = tomax;
10763 buf->dtb_xamot_drops = buf->dtb_drops;
10764 buf->dtb_xamot_offset = buf->dtb_offset;
10765 buf->dtb_xamot_errors = buf->dtb_errors;
10766 buf->dtb_xamot_flags = buf->dtb_flags;
10767 buf->dtb_offset = 0;
10768 buf->dtb_drops = 0;
10769 buf->dtb_errors = 0;
10770 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10771 buf->dtb_interval = now - buf->dtb_switched;
10772 buf->dtb_switched = now;
10773 dtrace_interrupt_enable(cookie);
10777 * Note: called from cross call context. This function activates a buffer
10778 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10779 * is guaranteed by the disabling of interrupts.
10782 dtrace_buffer_activate(dtrace_state_t *state)
10784 dtrace_buffer_t *buf;
10785 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10787 buf = &state->dts_buffer[curcpu];
10789 if (buf->dtb_tomax != NULL) {
10791 * We might like to assert that the buffer is marked inactive,
10792 * but this isn't necessarily true: the buffer for the CPU
10793 * that processes the BEGIN probe has its buffer activated
10794 * manually. In this case, we take the (harmless) action
10795 * re-clearing the bit INACTIVE bit.
10797 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10800 dtrace_interrupt_enable(cookie);
10804 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10810 dtrace_buffer_t *buf;
10813 ASSERT(MUTEX_HELD(&cpu_lock));
10814 ASSERT(MUTEX_HELD(&dtrace_lock));
10816 if (size > dtrace_nonroot_maxsize &&
10817 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10823 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10826 buf = &bufs[cp->cpu_id];
10829 * If there is already a buffer allocated for this CPU, it
10830 * is only possible that this is a DR event. In this case,
10832 if (buf->dtb_tomax != NULL) {
10833 ASSERT(buf->dtb_size == size);
10837 ASSERT(buf->dtb_xamot == NULL);
10839 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10842 buf->dtb_size = size;
10843 buf->dtb_flags = flags;
10844 buf->dtb_offset = 0;
10845 buf->dtb_drops = 0;
10847 if (flags & DTRACEBUF_NOSWITCH)
10850 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10852 } while ((cp = cp->cpu_next) != cpu_list);
10860 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10863 buf = &bufs[cp->cpu_id];
10865 if (buf->dtb_xamot != NULL) {
10866 ASSERT(buf->dtb_tomax != NULL);
10867 ASSERT(buf->dtb_size == size);
10868 kmem_free(buf->dtb_xamot, size);
10871 if (buf->dtb_tomax != NULL) {
10872 ASSERT(buf->dtb_size == size);
10873 kmem_free(buf->dtb_tomax, size);
10876 buf->dtb_tomax = NULL;
10877 buf->dtb_xamot = NULL;
10879 } while ((cp = cp->cpu_next) != cpu_list);
10885 #if defined(__amd64__)
10887 * FreeBSD isn't good at limiting the amount of memory we
10888 * ask to malloc, so let's place a limit here before trying
10889 * to do something that might well end in tears at bedtime.
10891 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
10895 ASSERT(MUTEX_HELD(&dtrace_lock));
10897 if (cpu != DTRACE_CPUALL && cpu != i)
10903 * If there is already a buffer allocated for this CPU, it
10904 * is only possible that this is a DR event. In this case,
10905 * the buffer size must match our specified size.
10907 if (buf->dtb_tomax != NULL) {
10908 ASSERT(buf->dtb_size == size);
10912 ASSERT(buf->dtb_xamot == NULL);
10914 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10917 buf->dtb_size = size;
10918 buf->dtb_flags = flags;
10919 buf->dtb_offset = 0;
10920 buf->dtb_drops = 0;
10922 if (flags & DTRACEBUF_NOSWITCH)
10925 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10933 * Error allocating memory, so free the buffers that were
10934 * allocated before the failed allocation.
10937 if (cpu != DTRACE_CPUALL && cpu != i)
10942 if (buf->dtb_xamot != NULL) {
10943 ASSERT(buf->dtb_tomax != NULL);
10944 ASSERT(buf->dtb_size == size);
10945 kmem_free(buf->dtb_xamot, size);
10948 if (buf->dtb_tomax != NULL) {
10949 ASSERT(buf->dtb_size == size);
10950 kmem_free(buf->dtb_tomax, size);
10953 buf->dtb_tomax = NULL;
10954 buf->dtb_xamot = NULL;
10964 * Note: called from probe context. This function just increments the drop
10965 * count on a buffer. It has been made a function to allow for the
10966 * possibility of understanding the source of mysterious drop counts. (A
10967 * problem for which one may be particularly disappointed that DTrace cannot
10968 * be used to understand DTrace.)
10971 dtrace_buffer_drop(dtrace_buffer_t *buf)
10977 * Note: called from probe context. This function is called to reserve space
10978 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
10979 * mstate. Returns the new offset in the buffer, or a negative value if an
10980 * error has occurred.
10983 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10984 dtrace_state_t *state, dtrace_mstate_t *mstate)
10986 intptr_t offs = buf->dtb_offset, soffs;
10991 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10994 if ((tomax = buf->dtb_tomax) == NULL) {
10995 dtrace_buffer_drop(buf);
10999 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11000 while (offs & (align - 1)) {
11002 * Assert that our alignment is off by a number which
11003 * is itself sizeof (uint32_t) aligned.
11005 ASSERT(!((align - (offs & (align - 1))) &
11006 (sizeof (uint32_t) - 1)));
11007 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11008 offs += sizeof (uint32_t);
11011 if ((soffs = offs + needed) > buf->dtb_size) {
11012 dtrace_buffer_drop(buf);
11016 if (mstate == NULL)
11019 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11020 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11021 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11026 if (buf->dtb_flags & DTRACEBUF_FILL) {
11027 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11028 (buf->dtb_flags & DTRACEBUF_FULL))
11033 total = needed + (offs & (align - 1));
11036 * For a ring buffer, life is quite a bit more complicated. Before
11037 * we can store any padding, we need to adjust our wrapping offset.
11038 * (If we've never before wrapped or we're not about to, no adjustment
11041 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11042 offs + total > buf->dtb_size) {
11043 woffs = buf->dtb_xamot_offset;
11045 if (offs + total > buf->dtb_size) {
11047 * We can't fit in the end of the buffer. First, a
11048 * sanity check that we can fit in the buffer at all.
11050 if (total > buf->dtb_size) {
11051 dtrace_buffer_drop(buf);
11056 * We're going to be storing at the top of the buffer,
11057 * so now we need to deal with the wrapped offset. We
11058 * only reset our wrapped offset to 0 if it is
11059 * currently greater than the current offset. If it
11060 * is less than the current offset, it is because a
11061 * previous allocation induced a wrap -- but the
11062 * allocation didn't subsequently take the space due
11063 * to an error or false predicate evaluation. In this
11064 * case, we'll just leave the wrapped offset alone: if
11065 * the wrapped offset hasn't been advanced far enough
11066 * for this allocation, it will be adjusted in the
11069 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11077 * Now we know that we're going to be storing to the
11078 * top of the buffer and that there is room for us
11079 * there. We need to clear the buffer from the current
11080 * offset to the end (there may be old gunk there).
11082 while (offs < buf->dtb_size)
11086 * We need to set our offset to zero. And because we
11087 * are wrapping, we need to set the bit indicating as
11088 * much. We can also adjust our needed space back
11089 * down to the space required by the ECB -- we know
11090 * that the top of the buffer is aligned.
11094 buf->dtb_flags |= DTRACEBUF_WRAPPED;
11097 * There is room for us in the buffer, so we simply
11098 * need to check the wrapped offset.
11100 if (woffs < offs) {
11102 * The wrapped offset is less than the offset.
11103 * This can happen if we allocated buffer space
11104 * that induced a wrap, but then we didn't
11105 * subsequently take the space due to an error
11106 * or false predicate evaluation. This is
11107 * okay; we know that _this_ allocation isn't
11108 * going to induce a wrap. We still can't
11109 * reset the wrapped offset to be zero,
11110 * however: the space may have been trashed in
11111 * the previous failed probe attempt. But at
11112 * least the wrapped offset doesn't need to
11113 * be adjusted at all...
11119 while (offs + total > woffs) {
11120 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11123 if (epid == DTRACE_EPIDNONE) {
11124 size = sizeof (uint32_t);
11126 ASSERT3U(epid, <=, state->dts_necbs);
11127 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11129 size = state->dts_ecbs[epid - 1]->dte_size;
11132 ASSERT(woffs + size <= buf->dtb_size);
11135 if (woffs + size == buf->dtb_size) {
11137 * We've reached the end of the buffer; we want
11138 * to set the wrapped offset to 0 and break
11139 * out. However, if the offs is 0, then we're
11140 * in a strange edge-condition: the amount of
11141 * space that we want to reserve plus the size
11142 * of the record that we're overwriting is
11143 * greater than the size of the buffer. This
11144 * is problematic because if we reserve the
11145 * space but subsequently don't consume it (due
11146 * to a failed predicate or error) the wrapped
11147 * offset will be 0 -- yet the EPID at offset 0
11148 * will not be committed. This situation is
11149 * relatively easy to deal with: if we're in
11150 * this case, the buffer is indistinguishable
11151 * from one that hasn't wrapped; we need only
11152 * finish the job by clearing the wrapped bit,
11153 * explicitly setting the offset to be 0, and
11154 * zero'ing out the old data in the buffer.
11157 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11158 buf->dtb_offset = 0;
11161 while (woffs < buf->dtb_size)
11162 tomax[woffs++] = 0;
11173 * We have a wrapped offset. It may be that the wrapped offset
11174 * has become zero -- that's okay.
11176 buf->dtb_xamot_offset = woffs;
11181 * Now we can plow the buffer with any necessary padding.
11183 while (offs & (align - 1)) {
11185 * Assert that our alignment is off by a number which
11186 * is itself sizeof (uint32_t) aligned.
11188 ASSERT(!((align - (offs & (align - 1))) &
11189 (sizeof (uint32_t) - 1)));
11190 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11191 offs += sizeof (uint32_t);
11194 if (buf->dtb_flags & DTRACEBUF_FILL) {
11195 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11196 buf->dtb_flags |= DTRACEBUF_FULL;
11201 if (mstate == NULL)
11205 * For ring buffers and fill buffers, the scratch space is always
11206 * the inactive buffer.
11208 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11209 mstate->dtms_scratch_size = buf->dtb_size;
11210 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11216 dtrace_buffer_polish(dtrace_buffer_t *buf)
11218 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11219 ASSERT(MUTEX_HELD(&dtrace_lock));
11221 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11225 * We need to polish the ring buffer. There are three cases:
11227 * - The first (and presumably most common) is that there is no gap
11228 * between the buffer offset and the wrapped offset. In this case,
11229 * there is nothing in the buffer that isn't valid data; we can
11230 * mark the buffer as polished and return.
11232 * - The second (less common than the first but still more common
11233 * than the third) is that there is a gap between the buffer offset
11234 * and the wrapped offset, and the wrapped offset is larger than the
11235 * buffer offset. This can happen because of an alignment issue, or
11236 * can happen because of a call to dtrace_buffer_reserve() that
11237 * didn't subsequently consume the buffer space. In this case,
11238 * we need to zero the data from the buffer offset to the wrapped
11241 * - The third (and least common) is that there is a gap between the
11242 * buffer offset and the wrapped offset, but the wrapped offset is
11243 * _less_ than the buffer offset. This can only happen because a
11244 * call to dtrace_buffer_reserve() induced a wrap, but the space
11245 * was not subsequently consumed. In this case, we need to zero the
11246 * space from the offset to the end of the buffer _and_ from the
11247 * top of the buffer to the wrapped offset.
11249 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11250 bzero(buf->dtb_tomax + buf->dtb_offset,
11251 buf->dtb_xamot_offset - buf->dtb_offset);
11254 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11255 bzero(buf->dtb_tomax + buf->dtb_offset,
11256 buf->dtb_size - buf->dtb_offset);
11257 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11262 * This routine determines if data generated at the specified time has likely
11263 * been entirely consumed at user-level. This routine is called to determine
11264 * if an ECB on a defunct probe (but for an active enabling) can be safely
11265 * disabled and destroyed.
11268 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11272 for (i = 0; i < NCPU; i++) {
11273 dtrace_buffer_t *buf = &bufs[i];
11275 if (buf->dtb_size == 0)
11278 if (buf->dtb_flags & DTRACEBUF_RING)
11281 if (!buf->dtb_switched && buf->dtb_offset != 0)
11284 if (buf->dtb_switched - buf->dtb_interval < when)
11292 dtrace_buffer_free(dtrace_buffer_t *bufs)
11296 for (i = 0; i < NCPU; i++) {
11297 dtrace_buffer_t *buf = &bufs[i];
11299 if (buf->dtb_tomax == NULL) {
11300 ASSERT(buf->dtb_xamot == NULL);
11301 ASSERT(buf->dtb_size == 0);
11305 if (buf->dtb_xamot != NULL) {
11306 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11307 kmem_free(buf->dtb_xamot, buf->dtb_size);
11310 kmem_free(buf->dtb_tomax, buf->dtb_size);
11312 buf->dtb_tomax = NULL;
11313 buf->dtb_xamot = NULL;
11318 * DTrace Enabling Functions
11320 static dtrace_enabling_t *
11321 dtrace_enabling_create(dtrace_vstate_t *vstate)
11323 dtrace_enabling_t *enab;
11325 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11326 enab->dten_vstate = vstate;
11332 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11334 dtrace_ecbdesc_t **ndesc;
11335 size_t osize, nsize;
11338 * We can't add to enablings after we've enabled them, or after we've
11341 ASSERT(enab->dten_probegen == 0);
11342 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11344 if (enab->dten_ndesc < enab->dten_maxdesc) {
11345 enab->dten_desc[enab->dten_ndesc++] = ecb;
11349 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11351 if (enab->dten_maxdesc == 0) {
11352 enab->dten_maxdesc = 1;
11354 enab->dten_maxdesc <<= 1;
11357 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11359 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11360 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11361 bcopy(enab->dten_desc, ndesc, osize);
11362 if (enab->dten_desc != NULL)
11363 kmem_free(enab->dten_desc, osize);
11365 enab->dten_desc = ndesc;
11366 enab->dten_desc[enab->dten_ndesc++] = ecb;
11370 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11371 dtrace_probedesc_t *pd)
11373 dtrace_ecbdesc_t *new;
11374 dtrace_predicate_t *pred;
11375 dtrace_actdesc_t *act;
11378 * We're going to create a new ECB description that matches the
11379 * specified ECB in every way, but has the specified probe description.
11381 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11383 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11384 dtrace_predicate_hold(pred);
11386 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11387 dtrace_actdesc_hold(act);
11389 new->dted_action = ecb->dted_action;
11390 new->dted_pred = ecb->dted_pred;
11391 new->dted_probe = *pd;
11392 new->dted_uarg = ecb->dted_uarg;
11394 dtrace_enabling_add(enab, new);
11398 dtrace_enabling_dump(dtrace_enabling_t *enab)
11402 for (i = 0; i < enab->dten_ndesc; i++) {
11403 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11405 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11406 desc->dtpd_provider, desc->dtpd_mod,
11407 desc->dtpd_func, desc->dtpd_name);
11412 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11415 dtrace_ecbdesc_t *ep;
11416 dtrace_vstate_t *vstate = enab->dten_vstate;
11418 ASSERT(MUTEX_HELD(&dtrace_lock));
11420 for (i = 0; i < enab->dten_ndesc; i++) {
11421 dtrace_actdesc_t *act, *next;
11422 dtrace_predicate_t *pred;
11424 ep = enab->dten_desc[i];
11426 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11427 dtrace_predicate_release(pred, vstate);
11429 for (act = ep->dted_action; act != NULL; act = next) {
11430 next = act->dtad_next;
11431 dtrace_actdesc_release(act, vstate);
11434 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11437 if (enab->dten_desc != NULL)
11438 kmem_free(enab->dten_desc,
11439 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11442 * If this was a retained enabling, decrement the dts_nretained count
11443 * and take it off of the dtrace_retained list.
11445 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11446 dtrace_retained == enab) {
11447 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11448 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11449 enab->dten_vstate->dtvs_state->dts_nretained--;
11452 if (enab->dten_prev == NULL) {
11453 if (dtrace_retained == enab) {
11454 dtrace_retained = enab->dten_next;
11456 if (dtrace_retained != NULL)
11457 dtrace_retained->dten_prev = NULL;
11460 ASSERT(enab != dtrace_retained);
11461 ASSERT(dtrace_retained != NULL);
11462 enab->dten_prev->dten_next = enab->dten_next;
11465 if (enab->dten_next != NULL) {
11466 ASSERT(dtrace_retained != NULL);
11467 enab->dten_next->dten_prev = enab->dten_prev;
11470 kmem_free(enab, sizeof (dtrace_enabling_t));
11474 dtrace_enabling_retain(dtrace_enabling_t *enab)
11476 dtrace_state_t *state;
11478 ASSERT(MUTEX_HELD(&dtrace_lock));
11479 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11480 ASSERT(enab->dten_vstate != NULL);
11482 state = enab->dten_vstate->dtvs_state;
11483 ASSERT(state != NULL);
11486 * We only allow each state to retain dtrace_retain_max enablings.
11488 if (state->dts_nretained >= dtrace_retain_max)
11491 state->dts_nretained++;
11493 if (dtrace_retained == NULL) {
11494 dtrace_retained = enab;
11498 enab->dten_next = dtrace_retained;
11499 dtrace_retained->dten_prev = enab;
11500 dtrace_retained = enab;
11506 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11507 dtrace_probedesc_t *create)
11509 dtrace_enabling_t *new, *enab;
11510 int found = 0, err = ENOENT;
11512 ASSERT(MUTEX_HELD(&dtrace_lock));
11513 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11514 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11515 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11516 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11518 new = dtrace_enabling_create(&state->dts_vstate);
11521 * Iterate over all retained enablings, looking for enablings that
11522 * match the specified state.
11524 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11528 * dtvs_state can only be NULL for helper enablings -- and
11529 * helper enablings can't be retained.
11531 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11533 if (enab->dten_vstate->dtvs_state != state)
11537 * Now iterate over each probe description; we're looking for
11538 * an exact match to the specified probe description.
11540 for (i = 0; i < enab->dten_ndesc; i++) {
11541 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11542 dtrace_probedesc_t *pd = &ep->dted_probe;
11544 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11547 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11550 if (strcmp(pd->dtpd_func, match->dtpd_func))
11553 if (strcmp(pd->dtpd_name, match->dtpd_name))
11557 * We have a winning probe! Add it to our growing
11561 dtrace_enabling_addlike(new, ep, create);
11565 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11566 dtrace_enabling_destroy(new);
11574 dtrace_enabling_retract(dtrace_state_t *state)
11576 dtrace_enabling_t *enab, *next;
11578 ASSERT(MUTEX_HELD(&dtrace_lock));
11581 * Iterate over all retained enablings, destroy the enablings retained
11582 * for the specified state.
11584 for (enab = dtrace_retained; enab != NULL; enab = next) {
11585 next = enab->dten_next;
11588 * dtvs_state can only be NULL for helper enablings -- and
11589 * helper enablings can't be retained.
11591 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11593 if (enab->dten_vstate->dtvs_state == state) {
11594 ASSERT(state->dts_nretained > 0);
11595 dtrace_enabling_destroy(enab);
11599 ASSERT(state->dts_nretained == 0);
11603 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11608 ASSERT(MUTEX_HELD(&cpu_lock));
11609 ASSERT(MUTEX_HELD(&dtrace_lock));
11611 for (i = 0; i < enab->dten_ndesc; i++) {
11612 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11614 enab->dten_current = ep;
11615 enab->dten_error = 0;
11617 matched += dtrace_probe_enable(&ep->dted_probe, enab);
11619 if (enab->dten_error != 0) {
11621 * If we get an error half-way through enabling the
11622 * probes, we kick out -- perhaps with some number of
11623 * them enabled. Leaving enabled probes enabled may
11624 * be slightly confusing for user-level, but we expect
11625 * that no one will attempt to actually drive on in
11626 * the face of such errors. If this is an anonymous
11627 * enabling (indicated with a NULL nmatched pointer),
11628 * we cmn_err() a message. We aren't expecting to
11629 * get such an error -- such as it can exist at all,
11630 * it would be a result of corrupted DOF in the driver
11633 if (nmatched == NULL) {
11634 cmn_err(CE_WARN, "dtrace_enabling_match() "
11635 "error on %p: %d", (void *)ep,
11639 return (enab->dten_error);
11643 enab->dten_probegen = dtrace_probegen;
11644 if (nmatched != NULL)
11645 *nmatched = matched;
11651 dtrace_enabling_matchall(void)
11653 dtrace_enabling_t *enab;
11655 mutex_enter(&cpu_lock);
11656 mutex_enter(&dtrace_lock);
11659 * Iterate over all retained enablings to see if any probes match
11660 * against them. We only perform this operation on enablings for which
11661 * we have sufficient permissions by virtue of being in the global zone
11662 * or in the same zone as the DTrace client. Because we can be called
11663 * after dtrace_detach() has been called, we cannot assert that there
11664 * are retained enablings. We can safely load from dtrace_retained,
11665 * however: the taskq_destroy() at the end of dtrace_detach() will
11666 * block pending our completion.
11668 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11670 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11672 if (INGLOBALZONE(curproc) || getzoneid() == crgetzoneid(cr))
11674 (void) dtrace_enabling_match(enab, NULL);
11677 mutex_exit(&dtrace_lock);
11678 mutex_exit(&cpu_lock);
11682 * If an enabling is to be enabled without having matched probes (that is, if
11683 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11684 * enabling must be _primed_ by creating an ECB for every ECB description.
11685 * This must be done to assure that we know the number of speculations, the
11686 * number of aggregations, the minimum buffer size needed, etc. before we
11687 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11688 * enabling any probes, we create ECBs for every ECB decription, but with a
11689 * NULL probe -- which is exactly what this function does.
11692 dtrace_enabling_prime(dtrace_state_t *state)
11694 dtrace_enabling_t *enab;
11697 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11698 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11700 if (enab->dten_vstate->dtvs_state != state)
11704 * We don't want to prime an enabling more than once, lest
11705 * we allow a malicious user to induce resource exhaustion.
11706 * (The ECBs that result from priming an enabling aren't
11707 * leaked -- but they also aren't deallocated until the
11708 * consumer state is destroyed.)
11710 if (enab->dten_primed)
11713 for (i = 0; i < enab->dten_ndesc; i++) {
11714 enab->dten_current = enab->dten_desc[i];
11715 (void) dtrace_probe_enable(NULL, enab);
11718 enab->dten_primed = 1;
11723 * Called to indicate that probes should be provided due to retained
11724 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11725 * must take an initial lap through the enabling calling the dtps_provide()
11726 * entry point explicitly to allow for autocreated probes.
11729 dtrace_enabling_provide(dtrace_provider_t *prv)
11732 dtrace_probedesc_t desc;
11734 ASSERT(MUTEX_HELD(&dtrace_lock));
11735 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11739 prv = dtrace_provider;
11743 dtrace_enabling_t *enab = dtrace_retained;
11744 void *parg = prv->dtpv_arg;
11746 for (; enab != NULL; enab = enab->dten_next) {
11747 for (i = 0; i < enab->dten_ndesc; i++) {
11748 desc = enab->dten_desc[i]->dted_probe;
11749 mutex_exit(&dtrace_lock);
11750 prv->dtpv_pops.dtps_provide(parg, &desc);
11751 mutex_enter(&dtrace_lock);
11754 } while (all && (prv = prv->dtpv_next) != NULL);
11756 mutex_exit(&dtrace_lock);
11757 dtrace_probe_provide(NULL, all ? NULL : prv);
11758 mutex_enter(&dtrace_lock);
11762 * Called to reap ECBs that are attached to probes from defunct providers.
11765 dtrace_enabling_reap(void)
11767 dtrace_provider_t *prov;
11768 dtrace_probe_t *probe;
11773 mutex_enter(&cpu_lock);
11774 mutex_enter(&dtrace_lock);
11776 for (i = 0; i < dtrace_nprobes; i++) {
11777 if ((probe = dtrace_probes[i]) == NULL)
11780 if (probe->dtpr_ecb == NULL)
11783 prov = probe->dtpr_provider;
11785 if ((when = prov->dtpv_defunct) == 0)
11789 * We have ECBs on a defunct provider: we want to reap these
11790 * ECBs to allow the provider to unregister. The destruction
11791 * of these ECBs must be done carefully: if we destroy the ECB
11792 * and the consumer later wishes to consume an EPID that
11793 * corresponds to the destroyed ECB (and if the EPID metadata
11794 * has not been previously consumed), the consumer will abort
11795 * processing on the unknown EPID. To reduce (but not, sadly,
11796 * eliminate) the possibility of this, we will only destroy an
11797 * ECB for a defunct provider if, for the state that
11798 * corresponds to the ECB:
11800 * (a) There is no speculative tracing (which can effectively
11801 * cache an EPID for an arbitrary amount of time).
11803 * (b) The principal buffers have been switched twice since the
11804 * provider became defunct.
11806 * (c) The aggregation buffers are of zero size or have been
11807 * switched twice since the provider became defunct.
11809 * We use dts_speculates to determine (a) and call a function
11810 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
11811 * that as soon as we've been unable to destroy one of the ECBs
11812 * associated with the probe, we quit trying -- reaping is only
11813 * fruitful in as much as we can destroy all ECBs associated
11814 * with the defunct provider's probes.
11816 while ((ecb = probe->dtpr_ecb) != NULL) {
11817 dtrace_state_t *state = ecb->dte_state;
11818 dtrace_buffer_t *buf = state->dts_buffer;
11819 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11821 if (state->dts_speculates)
11824 if (!dtrace_buffer_consumed(buf, when))
11827 if (!dtrace_buffer_consumed(aggbuf, when))
11830 dtrace_ecb_disable(ecb);
11831 ASSERT(probe->dtpr_ecb != ecb);
11832 dtrace_ecb_destroy(ecb);
11836 mutex_exit(&dtrace_lock);
11837 mutex_exit(&cpu_lock);
11841 * DTrace DOF Functions
11845 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11847 if (dtrace_err_verbose)
11848 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11850 #ifdef DTRACE_ERRDEBUG
11851 dtrace_errdebug(str);
11856 * Create DOF out of a currently enabled state. Right now, we only create
11857 * DOF containing the run-time options -- but this could be expanded to create
11858 * complete DOF representing the enabled state.
11861 dtrace_dof_create(dtrace_state_t *state)
11865 dof_optdesc_t *opt;
11866 int i, len = sizeof (dof_hdr_t) +
11867 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11868 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11870 ASSERT(MUTEX_HELD(&dtrace_lock));
11872 dof = kmem_zalloc(len, KM_SLEEP);
11873 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11874 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11875 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11876 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11878 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11879 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11880 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11881 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11882 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11883 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11885 dof->dofh_flags = 0;
11886 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11887 dof->dofh_secsize = sizeof (dof_sec_t);
11888 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11889 dof->dofh_secoff = sizeof (dof_hdr_t);
11890 dof->dofh_loadsz = len;
11891 dof->dofh_filesz = len;
11895 * Fill in the option section header...
11897 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11898 sec->dofs_type = DOF_SECT_OPTDESC;
11899 sec->dofs_align = sizeof (uint64_t);
11900 sec->dofs_flags = DOF_SECF_LOAD;
11901 sec->dofs_entsize = sizeof (dof_optdesc_t);
11903 opt = (dof_optdesc_t *)((uintptr_t)sec +
11904 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11906 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11907 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11909 for (i = 0; i < DTRACEOPT_MAX; i++) {
11910 opt[i].dofo_option = i;
11911 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11912 opt[i].dofo_value = state->dts_options[i];
11919 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11921 dof_hdr_t hdr, *dof;
11923 ASSERT(!MUTEX_HELD(&dtrace_lock));
11926 * First, we're going to copyin() the sizeof (dof_hdr_t).
11928 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11929 dtrace_dof_error(NULL, "failed to copyin DOF header");
11935 * Now we'll allocate the entire DOF and copy it in -- provided
11936 * that the length isn't outrageous.
11938 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11939 dtrace_dof_error(&hdr, "load size exceeds maximum");
11944 if (hdr.dofh_loadsz < sizeof (hdr)) {
11945 dtrace_dof_error(&hdr, "invalid load size");
11950 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11952 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
11953 kmem_free(dof, hdr.dofh_loadsz);
11962 static __inline uchar_t
11963 dtrace_dof_char(char c) {
11982 return (c - 'A' + 10);
11989 return (c - 'a' + 10);
11991 /* Should not reach here. */
11997 dtrace_dof_property(const char *name)
12001 unsigned int len, i;
12006 * Unfortunately, array of values in .conf files are always (and
12007 * only) interpreted to be integer arrays. We must read our DOF
12008 * as an integer array, and then squeeze it into a byte array.
12010 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12011 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12014 for (i = 0; i < len; i++)
12015 buf[i] = (uchar_t)(((int *)buf)[i]);
12017 if (len < sizeof (dof_hdr_t)) {
12018 ddi_prop_free(buf);
12019 dtrace_dof_error(NULL, "truncated header");
12023 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12024 ddi_prop_free(buf);
12025 dtrace_dof_error(NULL, "truncated DOF");
12029 if (loadsz >= dtrace_dof_maxsize) {
12030 ddi_prop_free(buf);
12031 dtrace_dof_error(NULL, "oversized DOF");
12035 dof = kmem_alloc(loadsz, KM_SLEEP);
12036 bcopy(buf, dof, loadsz);
12037 ddi_prop_free(buf);
12042 if ((p_env = getenv(name)) == NULL)
12045 len = strlen(p_env) / 2;
12047 buf = kmem_alloc(len, KM_SLEEP);
12049 dof = (dof_hdr_t *) buf;
12053 for (i = 0; i < len; i++) {
12054 buf[i] = (dtrace_dof_char(p[0]) << 4) |
12055 dtrace_dof_char(p[1]);
12061 if (len < sizeof (dof_hdr_t)) {
12063 dtrace_dof_error(NULL, "truncated header");
12067 if (len < (loadsz = dof->dofh_loadsz)) {
12069 dtrace_dof_error(NULL, "truncated DOF");
12073 if (loadsz >= dtrace_dof_maxsize) {
12075 dtrace_dof_error(NULL, "oversized DOF");
12084 dtrace_dof_destroy(dof_hdr_t *dof)
12086 kmem_free(dof, dof->dofh_loadsz);
12090 * Return the dof_sec_t pointer corresponding to a given section index. If the
12091 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
12092 * a type other than DOF_SECT_NONE is specified, the header is checked against
12093 * this type and NULL is returned if the types do not match.
12096 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12098 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12099 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12101 if (i >= dof->dofh_secnum) {
12102 dtrace_dof_error(dof, "referenced section index is invalid");
12106 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12107 dtrace_dof_error(dof, "referenced section is not loadable");
12111 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12112 dtrace_dof_error(dof, "referenced section is the wrong type");
12119 static dtrace_probedesc_t *
12120 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12122 dof_probedesc_t *probe;
12124 uintptr_t daddr = (uintptr_t)dof;
12128 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12129 dtrace_dof_error(dof, "invalid probe section");
12133 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12134 dtrace_dof_error(dof, "bad alignment in probe description");
12138 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12139 dtrace_dof_error(dof, "truncated probe description");
12143 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12144 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12146 if (strtab == NULL)
12149 str = daddr + strtab->dofs_offset;
12150 size = strtab->dofs_size;
12152 if (probe->dofp_provider >= strtab->dofs_size) {
12153 dtrace_dof_error(dof, "corrupt probe provider");
12157 (void) strncpy(desc->dtpd_provider,
12158 (char *)(str + probe->dofp_provider),
12159 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12161 if (probe->dofp_mod >= strtab->dofs_size) {
12162 dtrace_dof_error(dof, "corrupt probe module");
12166 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12167 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12169 if (probe->dofp_func >= strtab->dofs_size) {
12170 dtrace_dof_error(dof, "corrupt probe function");
12174 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12175 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12177 if (probe->dofp_name >= strtab->dofs_size) {
12178 dtrace_dof_error(dof, "corrupt probe name");
12182 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12183 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12188 static dtrace_difo_t *
12189 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12194 dof_difohdr_t *dofd;
12195 uintptr_t daddr = (uintptr_t)dof;
12196 size_t max = dtrace_difo_maxsize;
12199 static const struct {
12207 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12208 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12209 sizeof (dif_instr_t), "multiple DIF sections" },
12211 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12212 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12213 sizeof (uint64_t), "multiple integer tables" },
12215 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12216 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12217 sizeof (char), "multiple string tables" },
12219 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12220 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12221 sizeof (uint_t), "multiple variable tables" },
12223 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12226 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12227 dtrace_dof_error(dof, "invalid DIFO header section");
12231 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12232 dtrace_dof_error(dof, "bad alignment in DIFO header");
12236 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12237 sec->dofs_size % sizeof (dof_secidx_t)) {
12238 dtrace_dof_error(dof, "bad size in DIFO header");
12242 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12243 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12245 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12246 dp->dtdo_rtype = dofd->dofd_rtype;
12248 for (l = 0; l < n; l++) {
12253 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12254 dofd->dofd_links[l])) == NULL)
12255 goto err; /* invalid section link */
12257 if (ttl + subsec->dofs_size > max) {
12258 dtrace_dof_error(dof, "exceeds maximum size");
12262 ttl += subsec->dofs_size;
12264 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12265 if (subsec->dofs_type != difo[i].section)
12268 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12269 dtrace_dof_error(dof, "section not loaded");
12273 if (subsec->dofs_align != difo[i].align) {
12274 dtrace_dof_error(dof, "bad alignment");
12278 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12279 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12281 if (*bufp != NULL) {
12282 dtrace_dof_error(dof, difo[i].msg);
12286 if (difo[i].entsize != subsec->dofs_entsize) {
12287 dtrace_dof_error(dof, "entry size mismatch");
12291 if (subsec->dofs_entsize != 0 &&
12292 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12293 dtrace_dof_error(dof, "corrupt entry size");
12297 *lenp = subsec->dofs_size;
12298 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12299 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12300 *bufp, subsec->dofs_size);
12302 if (subsec->dofs_entsize != 0)
12303 *lenp /= subsec->dofs_entsize;
12309 * If we encounter a loadable DIFO sub-section that is not
12310 * known to us, assume this is a broken program and fail.
12312 if (difo[i].section == DOF_SECT_NONE &&
12313 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12314 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12319 if (dp->dtdo_buf == NULL) {
12321 * We can't have a DIF object without DIF text.
12323 dtrace_dof_error(dof, "missing DIF text");
12328 * Before we validate the DIF object, run through the variable table
12329 * looking for the strings -- if any of their size are under, we'll set
12330 * their size to be the system-wide default string size. Note that
12331 * this should _not_ happen if the "strsize" option has been set --
12332 * in this case, the compiler should have set the size to reflect the
12333 * setting of the option.
12335 for (i = 0; i < dp->dtdo_varlen; i++) {
12336 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12337 dtrace_diftype_t *t = &v->dtdv_type;
12339 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12342 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12343 t->dtdt_size = dtrace_strsize_default;
12346 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12349 dtrace_difo_init(dp, vstate);
12353 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12354 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12355 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12356 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12358 kmem_free(dp, sizeof (dtrace_difo_t));
12362 static dtrace_predicate_t *
12363 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12368 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12371 return (dtrace_predicate_create(dp));
12374 static dtrace_actdesc_t *
12375 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12378 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12379 dof_actdesc_t *desc;
12380 dof_sec_t *difosec;
12382 uintptr_t daddr = (uintptr_t)dof;
12384 dtrace_actkind_t kind;
12386 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12387 dtrace_dof_error(dof, "invalid action section");
12391 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12392 dtrace_dof_error(dof, "truncated action description");
12396 if (sec->dofs_align != sizeof (uint64_t)) {
12397 dtrace_dof_error(dof, "bad alignment in action description");
12401 if (sec->dofs_size < sec->dofs_entsize) {
12402 dtrace_dof_error(dof, "section entry size exceeds total size");
12406 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12407 dtrace_dof_error(dof, "bad entry size in action description");
12411 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12412 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12416 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12417 desc = (dof_actdesc_t *)(daddr +
12418 (uintptr_t)sec->dofs_offset + offs);
12419 kind = (dtrace_actkind_t)desc->dofa_kind;
12421 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12422 (kind != DTRACEACT_PRINTA ||
12423 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12424 (kind == DTRACEACT_DIFEXPR &&
12425 desc->dofa_strtab != DOF_SECIDX_NONE)) {
12431 * The argument to these actions is an index into the
12432 * DOF string table. For printf()-like actions, this
12433 * is the format string. For print(), this is the
12434 * CTF type of the expression result.
12436 if ((strtab = dtrace_dof_sect(dof,
12437 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12440 str = (char *)((uintptr_t)dof +
12441 (uintptr_t)strtab->dofs_offset);
12443 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12444 if (str[i] == '\0')
12448 if (i >= strtab->dofs_size) {
12449 dtrace_dof_error(dof, "bogus format string");
12453 if (i == desc->dofa_arg) {
12454 dtrace_dof_error(dof, "empty format string");
12458 i -= desc->dofa_arg;
12459 fmt = kmem_alloc(i + 1, KM_SLEEP);
12460 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12461 arg = (uint64_t)(uintptr_t)fmt;
12463 if (kind == DTRACEACT_PRINTA) {
12464 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12467 arg = desc->dofa_arg;
12471 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12472 desc->dofa_uarg, arg);
12474 if (last != NULL) {
12475 last->dtad_next = act;
12482 if (desc->dofa_difo == DOF_SECIDX_NONE)
12485 if ((difosec = dtrace_dof_sect(dof,
12486 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12489 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12491 if (act->dtad_difo == NULL)
12495 ASSERT(first != NULL);
12499 for (act = first; act != NULL; act = next) {
12500 next = act->dtad_next;
12501 dtrace_actdesc_release(act, vstate);
12507 static dtrace_ecbdesc_t *
12508 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12511 dtrace_ecbdesc_t *ep;
12512 dof_ecbdesc_t *ecb;
12513 dtrace_probedesc_t *desc;
12514 dtrace_predicate_t *pred = NULL;
12516 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12517 dtrace_dof_error(dof, "truncated ECB description");
12521 if (sec->dofs_align != sizeof (uint64_t)) {
12522 dtrace_dof_error(dof, "bad alignment in ECB description");
12526 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12527 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12532 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12533 ep->dted_uarg = ecb->dofe_uarg;
12534 desc = &ep->dted_probe;
12536 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12539 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12540 if ((sec = dtrace_dof_sect(dof,
12541 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12544 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12547 ep->dted_pred.dtpdd_predicate = pred;
12550 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12551 if ((sec = dtrace_dof_sect(dof,
12552 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12555 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12557 if (ep->dted_action == NULL)
12565 dtrace_predicate_release(pred, vstate);
12566 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12571 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12572 * specified DOF. At present, this amounts to simply adding 'ubase' to the
12573 * site of any user SETX relocations to account for load object base address.
12574 * In the future, if we need other relocations, this function can be extended.
12577 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12579 uintptr_t daddr = (uintptr_t)dof;
12580 dof_relohdr_t *dofr =
12581 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12582 dof_sec_t *ss, *rs, *ts;
12586 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12587 sec->dofs_align != sizeof (dof_secidx_t)) {
12588 dtrace_dof_error(dof, "invalid relocation header");
12592 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12593 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12594 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12596 if (ss == NULL || rs == NULL || ts == NULL)
12597 return (-1); /* dtrace_dof_error() has been called already */
12599 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12600 rs->dofs_align != sizeof (uint64_t)) {
12601 dtrace_dof_error(dof, "invalid relocation section");
12605 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12606 n = rs->dofs_size / rs->dofs_entsize;
12608 for (i = 0; i < n; i++) {
12609 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12611 switch (r->dofr_type) {
12612 case DOF_RELO_NONE:
12614 case DOF_RELO_SETX:
12615 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12616 sizeof (uint64_t) > ts->dofs_size) {
12617 dtrace_dof_error(dof, "bad relocation offset");
12621 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12622 dtrace_dof_error(dof, "misaligned setx relo");
12626 *(uint64_t *)taddr += ubase;
12629 dtrace_dof_error(dof, "invalid relocation type");
12633 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12640 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12641 * header: it should be at the front of a memory region that is at least
12642 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12643 * size. It need not be validated in any other way.
12646 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12647 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12649 uint64_t len = dof->dofh_loadsz, seclen;
12650 uintptr_t daddr = (uintptr_t)dof;
12651 dtrace_ecbdesc_t *ep;
12652 dtrace_enabling_t *enab;
12655 ASSERT(MUTEX_HELD(&dtrace_lock));
12656 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12659 * Check the DOF header identification bytes. In addition to checking
12660 * valid settings, we also verify that unused bits/bytes are zeroed so
12661 * we can use them later without fear of regressing existing binaries.
12663 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12664 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12665 dtrace_dof_error(dof, "DOF magic string mismatch");
12669 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12670 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12671 dtrace_dof_error(dof, "DOF has invalid data model");
12675 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12676 dtrace_dof_error(dof, "DOF encoding mismatch");
12680 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12681 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12682 dtrace_dof_error(dof, "DOF version mismatch");
12686 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12687 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12691 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12692 dtrace_dof_error(dof, "DOF uses too many integer registers");
12696 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12697 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12701 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12702 if (dof->dofh_ident[i] != 0) {
12703 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12708 if (dof->dofh_flags & ~DOF_FL_VALID) {
12709 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12713 if (dof->dofh_secsize == 0) {
12714 dtrace_dof_error(dof, "zero section header size");
12719 * Check that the section headers don't exceed the amount of DOF
12720 * data. Note that we cast the section size and number of sections
12721 * to uint64_t's to prevent possible overflow in the multiplication.
12723 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12725 if (dof->dofh_secoff > len || seclen > len ||
12726 dof->dofh_secoff + seclen > len) {
12727 dtrace_dof_error(dof, "truncated section headers");
12731 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12732 dtrace_dof_error(dof, "misaligned section headers");
12736 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12737 dtrace_dof_error(dof, "misaligned section size");
12742 * Take an initial pass through the section headers to be sure that
12743 * the headers don't have stray offsets. If the 'noprobes' flag is
12744 * set, do not permit sections relating to providers, probes, or args.
12746 for (i = 0; i < dof->dofh_secnum; i++) {
12747 dof_sec_t *sec = (dof_sec_t *)(daddr +
12748 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12751 switch (sec->dofs_type) {
12752 case DOF_SECT_PROVIDER:
12753 case DOF_SECT_PROBES:
12754 case DOF_SECT_PRARGS:
12755 case DOF_SECT_PROFFS:
12756 dtrace_dof_error(dof, "illegal sections "
12762 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12763 continue; /* just ignore non-loadable sections */
12765 if (sec->dofs_align & (sec->dofs_align - 1)) {
12766 dtrace_dof_error(dof, "bad section alignment");
12770 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12771 dtrace_dof_error(dof, "misaligned section");
12775 if (sec->dofs_offset > len || sec->dofs_size > len ||
12776 sec->dofs_offset + sec->dofs_size > len) {
12777 dtrace_dof_error(dof, "corrupt section header");
12781 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12782 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12783 dtrace_dof_error(dof, "non-terminating string table");
12789 * Take a second pass through the sections and locate and perform any
12790 * relocations that are present. We do this after the first pass to
12791 * be sure that all sections have had their headers validated.
12793 for (i = 0; i < dof->dofh_secnum; i++) {
12794 dof_sec_t *sec = (dof_sec_t *)(daddr +
12795 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12797 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12798 continue; /* skip sections that are not loadable */
12800 switch (sec->dofs_type) {
12801 case DOF_SECT_URELHDR:
12802 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12808 if ((enab = *enabp) == NULL)
12809 enab = *enabp = dtrace_enabling_create(vstate);
12811 for (i = 0; i < dof->dofh_secnum; i++) {
12812 dof_sec_t *sec = (dof_sec_t *)(daddr +
12813 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12815 if (sec->dofs_type != DOF_SECT_ECBDESC)
12818 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12819 dtrace_enabling_destroy(enab);
12824 dtrace_enabling_add(enab, ep);
12831 * Process DOF for any options. This routine assumes that the DOF has been
12832 * at least processed by dtrace_dof_slurp().
12835 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12840 dof_optdesc_t *desc;
12842 for (i = 0; i < dof->dofh_secnum; i++) {
12843 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12844 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12846 if (sec->dofs_type != DOF_SECT_OPTDESC)
12849 if (sec->dofs_align != sizeof (uint64_t)) {
12850 dtrace_dof_error(dof, "bad alignment in "
12851 "option description");
12855 if ((entsize = sec->dofs_entsize) == 0) {
12856 dtrace_dof_error(dof, "zeroed option entry size");
12860 if (entsize < sizeof (dof_optdesc_t)) {
12861 dtrace_dof_error(dof, "bad option entry size");
12865 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12866 desc = (dof_optdesc_t *)((uintptr_t)dof +
12867 (uintptr_t)sec->dofs_offset + offs);
12869 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12870 dtrace_dof_error(dof, "non-zero option string");
12874 if (desc->dofo_value == DTRACEOPT_UNSET) {
12875 dtrace_dof_error(dof, "unset option");
12879 if ((rval = dtrace_state_option(state,
12880 desc->dofo_option, desc->dofo_value)) != 0) {
12881 dtrace_dof_error(dof, "rejected option");
12891 * DTrace Consumer State Functions
12894 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12896 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12899 dtrace_dynvar_t *dvar, *next, *start;
12902 ASSERT(MUTEX_HELD(&dtrace_lock));
12903 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12905 bzero(dstate, sizeof (dtrace_dstate_t));
12907 if ((dstate->dtds_chunksize = chunksize) == 0)
12908 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12910 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12913 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12916 dstate->dtds_size = size;
12917 dstate->dtds_base = base;
12918 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12919 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12921 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12923 if (hashsize != 1 && (hashsize & 1))
12926 dstate->dtds_hashsize = hashsize;
12927 dstate->dtds_hash = dstate->dtds_base;
12930 * Set all of our hash buckets to point to the single sink, and (if
12931 * it hasn't already been set), set the sink's hash value to be the
12932 * sink sentinel value. The sink is needed for dynamic variable
12933 * lookups to know that they have iterated over an entire, valid hash
12936 for (i = 0; i < hashsize; i++)
12937 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12939 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12940 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12943 * Determine number of active CPUs. Divide free list evenly among
12946 start = (dtrace_dynvar_t *)
12947 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12948 limit = (uintptr_t)base + size;
12950 maxper = (limit - (uintptr_t)start) / NCPU;
12951 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12956 for (i = 0; i < NCPU; i++) {
12958 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12961 * If we don't even have enough chunks to make it once through
12962 * NCPUs, we're just going to allocate everything to the first
12963 * CPU. And if we're on the last CPU, we're going to allocate
12964 * whatever is left over. In either case, we set the limit to
12965 * be the limit of the dynamic variable space.
12967 if (maxper == 0 || i == NCPU - 1) {
12968 limit = (uintptr_t)base + size;
12971 limit = (uintptr_t)start + maxper;
12972 start = (dtrace_dynvar_t *)limit;
12975 ASSERT(limit <= (uintptr_t)base + size);
12978 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12979 dstate->dtds_chunksize);
12981 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12984 dvar->dtdv_next = next;
12996 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12998 ASSERT(MUTEX_HELD(&cpu_lock));
13000 if (dstate->dtds_base == NULL)
13003 kmem_free(dstate->dtds_base, dstate->dtds_size);
13004 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13008 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13011 * Logical XOR, where are you?
13013 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13015 if (vstate->dtvs_nglobals > 0) {
13016 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13017 sizeof (dtrace_statvar_t *));
13020 if (vstate->dtvs_ntlocals > 0) {
13021 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13022 sizeof (dtrace_difv_t));
13025 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13027 if (vstate->dtvs_nlocals > 0) {
13028 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13029 sizeof (dtrace_statvar_t *));
13035 dtrace_state_clean(dtrace_state_t *state)
13037 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13040 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13041 dtrace_speculation_clean(state);
13045 dtrace_state_deadman(dtrace_state_t *state)
13051 now = dtrace_gethrtime();
13053 if (state != dtrace_anon.dta_state &&
13054 now - state->dts_laststatus >= dtrace_deadman_user)
13058 * We must be sure that dts_alive never appears to be less than the
13059 * value upon entry to dtrace_state_deadman(), and because we lack a
13060 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13061 * store INT64_MAX to it, followed by a memory barrier, followed by
13062 * the new value. This assures that dts_alive never appears to be
13063 * less than its true value, regardless of the order in which the
13064 * stores to the underlying storage are issued.
13066 state->dts_alive = INT64_MAX;
13067 dtrace_membar_producer();
13068 state->dts_alive = now;
13072 dtrace_state_clean(void *arg)
13074 dtrace_state_t *state = arg;
13075 dtrace_optval_t *opt = state->dts_options;
13077 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13080 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13081 dtrace_speculation_clean(state);
13083 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13084 dtrace_state_clean, state);
13088 dtrace_state_deadman(void *arg)
13090 dtrace_state_t *state = arg;
13095 dtrace_debug_output();
13097 now = dtrace_gethrtime();
13099 if (state != dtrace_anon.dta_state &&
13100 now - state->dts_laststatus >= dtrace_deadman_user)
13104 * We must be sure that dts_alive never appears to be less than the
13105 * value upon entry to dtrace_state_deadman(), and because we lack a
13106 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13107 * store INT64_MAX to it, followed by a memory barrier, followed by
13108 * the new value. This assures that dts_alive never appears to be
13109 * less than its true value, regardless of the order in which the
13110 * stores to the underlying storage are issued.
13112 state->dts_alive = INT64_MAX;
13113 dtrace_membar_producer();
13114 state->dts_alive = now;
13116 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13117 dtrace_state_deadman, state);
13121 static dtrace_state_t *
13123 dtrace_state_create(dev_t *devp, cred_t *cr)
13125 dtrace_state_create(struct cdev *dev)
13136 dtrace_state_t *state;
13137 dtrace_optval_t *opt;
13138 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13140 ASSERT(MUTEX_HELD(&dtrace_lock));
13141 ASSERT(MUTEX_HELD(&cpu_lock));
13144 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13145 VM_BESTFIT | VM_SLEEP);
13147 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13148 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13152 state = ddi_get_soft_state(dtrace_softstate, minor);
13159 /* Allocate memory for the state. */
13160 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13163 state->dts_epid = DTRACE_EPIDNONE + 1;
13165 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13167 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13168 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13170 if (devp != NULL) {
13171 major = getemajor(*devp);
13173 major = ddi_driver_major(dtrace_devi);
13176 state->dts_dev = makedevice(major, minor);
13179 *devp = state->dts_dev;
13181 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13182 state->dts_dev = dev;
13186 * We allocate NCPU buffers. On the one hand, this can be quite
13187 * a bit of memory per instance (nearly 36K on a Starcat). On the
13188 * other hand, it saves an additional memory reference in the probe
13191 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13192 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13195 state->dts_cleaner = CYCLIC_NONE;
13196 state->dts_deadman = CYCLIC_NONE;
13198 callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13199 callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13201 state->dts_vstate.dtvs_state = state;
13203 for (i = 0; i < DTRACEOPT_MAX; i++)
13204 state->dts_options[i] = DTRACEOPT_UNSET;
13207 * Set the default options.
13209 opt = state->dts_options;
13210 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13211 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13212 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13213 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13214 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13215 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13216 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13217 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13218 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13219 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13220 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13221 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13222 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13223 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13225 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13228 * Depending on the user credentials, we set flag bits which alter probe
13229 * visibility or the amount of destructiveness allowed. In the case of
13230 * actual anonymous tracing, or the possession of all privileges, all of
13231 * the normal checks are bypassed.
13233 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13234 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13235 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13238 * Set up the credentials for this instantiation. We take a
13239 * hold on the credential to prevent it from disappearing on
13240 * us; this in turn prevents the zone_t referenced by this
13241 * credential from disappearing. This means that we can
13242 * examine the credential and the zone from probe context.
13245 state->dts_cred.dcr_cred = cr;
13248 * CRA_PROC means "we have *some* privilege for dtrace" and
13249 * unlocks the use of variables like pid, zonename, etc.
13251 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13252 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13253 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13257 * dtrace_user allows use of syscall and profile providers.
13258 * If the user also has proc_owner and/or proc_zone, we
13259 * extend the scope to include additional visibility and
13260 * destructive power.
13262 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13263 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13264 state->dts_cred.dcr_visible |=
13265 DTRACE_CRV_ALLPROC;
13267 state->dts_cred.dcr_action |=
13268 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13271 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13272 state->dts_cred.dcr_visible |=
13273 DTRACE_CRV_ALLZONE;
13275 state->dts_cred.dcr_action |=
13276 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13280 * If we have all privs in whatever zone this is,
13281 * we can do destructive things to processes which
13282 * have altered credentials.
13285 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13286 cr->cr_zone->zone_privset)) {
13287 state->dts_cred.dcr_action |=
13288 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13294 * Holding the dtrace_kernel privilege also implies that
13295 * the user has the dtrace_user privilege from a visibility
13296 * perspective. But without further privileges, some
13297 * destructive actions are not available.
13299 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13301 * Make all probes in all zones visible. However,
13302 * this doesn't mean that all actions become available
13305 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13306 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13308 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13311 * Holding proc_owner means that destructive actions
13312 * for *this* zone are allowed.
13314 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13315 state->dts_cred.dcr_action |=
13316 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13319 * Holding proc_zone means that destructive actions
13320 * for this user/group ID in all zones is allowed.
13322 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13323 state->dts_cred.dcr_action |=
13324 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13328 * If we have all privs in whatever zone this is,
13329 * we can do destructive things to processes which
13330 * have altered credentials.
13332 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13333 cr->cr_zone->zone_privset)) {
13334 state->dts_cred.dcr_action |=
13335 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13341 * Holding the dtrace_proc privilege gives control over fasttrap
13342 * and pid providers. We need to grant wider destructive
13343 * privileges in the event that the user has proc_owner and/or
13346 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13347 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13348 state->dts_cred.dcr_action |=
13349 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13351 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13352 state->dts_cred.dcr_action |=
13353 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13361 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13363 dtrace_optval_t *opt = state->dts_options, size;
13364 processorid_t cpu = 0;;
13365 int flags = 0, rval;
13367 ASSERT(MUTEX_HELD(&dtrace_lock));
13368 ASSERT(MUTEX_HELD(&cpu_lock));
13369 ASSERT(which < DTRACEOPT_MAX);
13370 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13371 (state == dtrace_anon.dta_state &&
13372 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13374 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13377 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13378 cpu = opt[DTRACEOPT_CPU];
13380 if (which == DTRACEOPT_SPECSIZE)
13381 flags |= DTRACEBUF_NOSWITCH;
13383 if (which == DTRACEOPT_BUFSIZE) {
13384 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13385 flags |= DTRACEBUF_RING;
13387 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13388 flags |= DTRACEBUF_FILL;
13390 if (state != dtrace_anon.dta_state ||
13391 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13392 flags |= DTRACEBUF_INACTIVE;
13395 for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
13397 * The size must be 8-byte aligned. If the size is not 8-byte
13398 * aligned, drop it down by the difference.
13400 if (size & (sizeof (uint64_t) - 1))
13401 size -= size & (sizeof (uint64_t) - 1);
13403 if (size < state->dts_reserve) {
13405 * Buffers always must be large enough to accommodate
13406 * their prereserved space. We return E2BIG instead
13407 * of ENOMEM in this case to allow for user-level
13408 * software to differentiate the cases.
13413 rval = dtrace_buffer_alloc(buf, size, flags, cpu);
13415 if (rval != ENOMEM) {
13420 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13428 dtrace_state_buffers(dtrace_state_t *state)
13430 dtrace_speculation_t *spec = state->dts_speculations;
13433 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13434 DTRACEOPT_BUFSIZE)) != 0)
13437 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13438 DTRACEOPT_AGGSIZE)) != 0)
13441 for (i = 0; i < state->dts_nspeculations; i++) {
13442 if ((rval = dtrace_state_buffer(state,
13443 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13451 dtrace_state_prereserve(dtrace_state_t *state)
13454 dtrace_probe_t *probe;
13456 state->dts_reserve = 0;
13458 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13462 * If our buffer policy is a "fill" buffer policy, we need to set the
13463 * prereserved space to be the space required by the END probes.
13465 probe = dtrace_probes[dtrace_probeid_end - 1];
13466 ASSERT(probe != NULL);
13468 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13469 if (ecb->dte_state != state)
13472 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13477 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13479 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13480 dtrace_speculation_t *spec;
13481 dtrace_buffer_t *buf;
13483 cyc_handler_t hdlr;
13486 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13487 dtrace_icookie_t cookie;
13489 mutex_enter(&cpu_lock);
13490 mutex_enter(&dtrace_lock);
13492 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13498 * Before we can perform any checks, we must prime all of the
13499 * retained enablings that correspond to this state.
13501 dtrace_enabling_prime(state);
13503 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13508 dtrace_state_prereserve(state);
13511 * Now we want to do is try to allocate our speculations.
13512 * We do not automatically resize the number of speculations; if
13513 * this fails, we will fail the operation.
13515 nspec = opt[DTRACEOPT_NSPEC];
13516 ASSERT(nspec != DTRACEOPT_UNSET);
13518 if (nspec > INT_MAX) {
13523 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13525 if (spec == NULL) {
13530 state->dts_speculations = spec;
13531 state->dts_nspeculations = (int)nspec;
13533 for (i = 0; i < nspec; i++) {
13534 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13539 spec[i].dtsp_buffer = buf;
13542 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13543 if (dtrace_anon.dta_state == NULL) {
13548 if (state->dts_necbs != 0) {
13553 state->dts_anon = dtrace_anon_grab();
13554 ASSERT(state->dts_anon != NULL);
13555 state = state->dts_anon;
13558 * We want "grabanon" to be set in the grabbed state, so we'll
13559 * copy that option value from the grabbing state into the
13562 state->dts_options[DTRACEOPT_GRABANON] =
13563 opt[DTRACEOPT_GRABANON];
13565 *cpu = dtrace_anon.dta_beganon;
13568 * If the anonymous state is active (as it almost certainly
13569 * is if the anonymous enabling ultimately matched anything),
13570 * we don't allow any further option processing -- but we
13571 * don't return failure.
13573 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13577 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13578 opt[DTRACEOPT_AGGSIZE] != 0) {
13579 if (state->dts_aggregations == NULL) {
13581 * We're not going to create an aggregation buffer
13582 * because we don't have any ECBs that contain
13583 * aggregations -- set this option to 0.
13585 opt[DTRACEOPT_AGGSIZE] = 0;
13588 * If we have an aggregation buffer, we must also have
13589 * a buffer to use as scratch.
13591 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13592 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13593 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13598 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13599 opt[DTRACEOPT_SPECSIZE] != 0) {
13600 if (!state->dts_speculates) {
13602 * We're not going to create speculation buffers
13603 * because we don't have any ECBs that actually
13604 * speculate -- set the speculation size to 0.
13606 opt[DTRACEOPT_SPECSIZE] = 0;
13611 * The bare minimum size for any buffer that we're actually going to
13612 * do anything to is sizeof (uint64_t).
13614 sz = sizeof (uint64_t);
13616 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13617 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13618 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13620 * A buffer size has been explicitly set to 0 (or to a size
13621 * that will be adjusted to 0) and we need the space -- we
13622 * need to return failure. We return ENOSPC to differentiate
13623 * it from failing to allocate a buffer due to failure to meet
13624 * the reserve (for which we return E2BIG).
13630 if ((rval = dtrace_state_buffers(state)) != 0)
13633 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13634 sz = dtrace_dstate_defsize;
13637 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13642 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13644 } while (sz >>= 1);
13646 opt[DTRACEOPT_DYNVARSIZE] = sz;
13651 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13652 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13654 if (opt[DTRACEOPT_CLEANRATE] == 0)
13655 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13657 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13658 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13660 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13661 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13663 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13665 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13666 hdlr.cyh_arg = state;
13667 hdlr.cyh_level = CY_LOW_LEVEL;
13670 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13672 state->dts_cleaner = cyclic_add(&hdlr, &when);
13674 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13675 hdlr.cyh_arg = state;
13676 hdlr.cyh_level = CY_LOW_LEVEL;
13679 when.cyt_interval = dtrace_deadman_interval;
13681 state->dts_deadman = cyclic_add(&hdlr, &when);
13683 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13684 dtrace_state_clean, state);
13685 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13686 dtrace_state_deadman, state);
13689 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13692 * Now it's time to actually fire the BEGIN probe. We need to disable
13693 * interrupts here both to record the CPU on which we fired the BEGIN
13694 * probe (the data from this CPU will be processed first at user
13695 * level) and to manually activate the buffer for this CPU.
13697 cookie = dtrace_interrupt_disable();
13699 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13700 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13702 dtrace_probe(dtrace_probeid_begin,
13703 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13704 dtrace_interrupt_enable(cookie);
13706 * We may have had an exit action from a BEGIN probe; only change our
13707 * state to ACTIVE if we're still in WARMUP.
13709 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13710 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13712 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13713 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13716 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13717 * want each CPU to transition its principal buffer out of the
13718 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13719 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13720 * atomically transition from processing none of a state's ECBs to
13721 * processing all of them.
13723 dtrace_xcall(DTRACE_CPUALL,
13724 (dtrace_xcall_t)dtrace_buffer_activate, state);
13728 dtrace_buffer_free(state->dts_buffer);
13729 dtrace_buffer_free(state->dts_aggbuffer);
13731 if ((nspec = state->dts_nspeculations) == 0) {
13732 ASSERT(state->dts_speculations == NULL);
13736 spec = state->dts_speculations;
13737 ASSERT(spec != NULL);
13739 for (i = 0; i < state->dts_nspeculations; i++) {
13740 if ((buf = spec[i].dtsp_buffer) == NULL)
13743 dtrace_buffer_free(buf);
13744 kmem_free(buf, bufsize);
13747 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13748 state->dts_nspeculations = 0;
13749 state->dts_speculations = NULL;
13752 mutex_exit(&dtrace_lock);
13753 mutex_exit(&cpu_lock);
13759 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13761 dtrace_icookie_t cookie;
13763 ASSERT(MUTEX_HELD(&dtrace_lock));
13765 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13766 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13770 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13771 * to be sure that every CPU has seen it. See below for the details
13772 * on why this is done.
13774 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13778 * By this point, it is impossible for any CPU to be still processing
13779 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13780 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13781 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13782 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13783 * iff we're in the END probe.
13785 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13787 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13790 * Finally, we can release the reserve and call the END probe. We
13791 * disable interrupts across calling the END probe to allow us to
13792 * return the CPU on which we actually called the END probe. This
13793 * allows user-land to be sure that this CPU's principal buffer is
13796 state->dts_reserve = 0;
13798 cookie = dtrace_interrupt_disable();
13800 dtrace_probe(dtrace_probeid_end,
13801 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13802 dtrace_interrupt_enable(cookie);
13804 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13811 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13812 dtrace_optval_t val)
13814 ASSERT(MUTEX_HELD(&dtrace_lock));
13816 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13819 if (option >= DTRACEOPT_MAX)
13822 if (option != DTRACEOPT_CPU && val < 0)
13826 case DTRACEOPT_DESTRUCTIVE:
13827 if (dtrace_destructive_disallow)
13830 state->dts_cred.dcr_destructive = 1;
13833 case DTRACEOPT_BUFSIZE:
13834 case DTRACEOPT_DYNVARSIZE:
13835 case DTRACEOPT_AGGSIZE:
13836 case DTRACEOPT_SPECSIZE:
13837 case DTRACEOPT_STRSIZE:
13841 if (val >= LONG_MAX) {
13843 * If this is an otherwise negative value, set it to
13844 * the highest multiple of 128m less than LONG_MAX.
13845 * Technically, we're adjusting the size without
13846 * regard to the buffer resizing policy, but in fact,
13847 * this has no effect -- if we set the buffer size to
13848 * ~LONG_MAX and the buffer policy is ultimately set to
13849 * be "manual", the buffer allocation is guaranteed to
13850 * fail, if only because the allocation requires two
13851 * buffers. (We set the the size to the highest
13852 * multiple of 128m because it ensures that the size
13853 * will remain a multiple of a megabyte when
13854 * repeatedly halved -- all the way down to 15m.)
13856 val = LONG_MAX - (1 << 27) + 1;
13860 state->dts_options[option] = val;
13866 dtrace_state_destroy(dtrace_state_t *state)
13869 dtrace_vstate_t *vstate = &state->dts_vstate;
13871 minor_t minor = getminor(state->dts_dev);
13873 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13874 dtrace_speculation_t *spec = state->dts_speculations;
13875 int nspec = state->dts_nspeculations;
13878 ASSERT(MUTEX_HELD(&dtrace_lock));
13879 ASSERT(MUTEX_HELD(&cpu_lock));
13882 * First, retract any retained enablings for this state.
13884 dtrace_enabling_retract(state);
13885 ASSERT(state->dts_nretained == 0);
13887 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13888 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13890 * We have managed to come into dtrace_state_destroy() on a
13891 * hot enabling -- almost certainly because of a disorderly
13892 * shutdown of a consumer. (That is, a consumer that is
13893 * exiting without having called dtrace_stop().) In this case,
13894 * we're going to set our activity to be KILLED, and then
13895 * issue a sync to be sure that everyone is out of probe
13896 * context before we start blowing away ECBs.
13898 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13903 * Release the credential hold we took in dtrace_state_create().
13905 if (state->dts_cred.dcr_cred != NULL)
13906 crfree(state->dts_cred.dcr_cred);
13909 * Now we can safely disable and destroy any enabled probes. Because
13910 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13911 * (especially if they're all enabled), we take two passes through the
13912 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13913 * in the second we disable whatever is left over.
13915 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13916 for (i = 0; i < state->dts_necbs; i++) {
13917 if ((ecb = state->dts_ecbs[i]) == NULL)
13920 if (match && ecb->dte_probe != NULL) {
13921 dtrace_probe_t *probe = ecb->dte_probe;
13922 dtrace_provider_t *prov = probe->dtpr_provider;
13924 if (!(prov->dtpv_priv.dtpp_flags & match))
13928 dtrace_ecb_disable(ecb);
13929 dtrace_ecb_destroy(ecb);
13937 * Before we free the buffers, perform one more sync to assure that
13938 * every CPU is out of probe context.
13942 dtrace_buffer_free(state->dts_buffer);
13943 dtrace_buffer_free(state->dts_aggbuffer);
13945 for (i = 0; i < nspec; i++)
13946 dtrace_buffer_free(spec[i].dtsp_buffer);
13949 if (state->dts_cleaner != CYCLIC_NONE)
13950 cyclic_remove(state->dts_cleaner);
13952 if (state->dts_deadman != CYCLIC_NONE)
13953 cyclic_remove(state->dts_deadman);
13955 callout_stop(&state->dts_cleaner);
13956 callout_drain(&state->dts_cleaner);
13957 callout_stop(&state->dts_deadman);
13958 callout_drain(&state->dts_deadman);
13961 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13962 dtrace_vstate_fini(vstate);
13963 if (state->dts_ecbs != NULL)
13964 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13966 if (state->dts_aggregations != NULL) {
13968 for (i = 0; i < state->dts_naggregations; i++)
13969 ASSERT(state->dts_aggregations[i] == NULL);
13971 ASSERT(state->dts_naggregations > 0);
13972 kmem_free(state->dts_aggregations,
13973 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13976 kmem_free(state->dts_buffer, bufsize);
13977 kmem_free(state->dts_aggbuffer, bufsize);
13979 for (i = 0; i < nspec; i++)
13980 kmem_free(spec[i].dtsp_buffer, bufsize);
13983 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13985 dtrace_format_destroy(state);
13987 if (state->dts_aggid_arena != NULL) {
13989 vmem_destroy(state->dts_aggid_arena);
13991 delete_unrhdr(state->dts_aggid_arena);
13993 state->dts_aggid_arena = NULL;
13996 ddi_soft_state_free(dtrace_softstate, minor);
13997 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14002 * DTrace Anonymous Enabling Functions
14004 static dtrace_state_t *
14005 dtrace_anon_grab(void)
14007 dtrace_state_t *state;
14009 ASSERT(MUTEX_HELD(&dtrace_lock));
14011 if ((state = dtrace_anon.dta_state) == NULL) {
14012 ASSERT(dtrace_anon.dta_enabling == NULL);
14016 ASSERT(dtrace_anon.dta_enabling != NULL);
14017 ASSERT(dtrace_retained != NULL);
14019 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14020 dtrace_anon.dta_enabling = NULL;
14021 dtrace_anon.dta_state = NULL;
14027 dtrace_anon_property(void)
14030 dtrace_state_t *state;
14032 char c[32]; /* enough for "dof-data-" + digits */
14034 ASSERT(MUTEX_HELD(&dtrace_lock));
14035 ASSERT(MUTEX_HELD(&cpu_lock));
14037 for (i = 0; ; i++) {
14038 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14040 dtrace_err_verbose = 1;
14042 if ((dof = dtrace_dof_property(c)) == NULL) {
14043 dtrace_err_verbose = 0;
14049 * We want to create anonymous state, so we need to transition
14050 * the kernel debugger to indicate that DTrace is active. If
14051 * this fails (e.g. because the debugger has modified text in
14052 * some way), we won't continue with the processing.
14054 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14055 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14056 "enabling ignored.");
14057 dtrace_dof_destroy(dof);
14063 * If we haven't allocated an anonymous state, we'll do so now.
14065 if ((state = dtrace_anon.dta_state) == NULL) {
14067 state = dtrace_state_create(NULL, NULL);
14069 state = dtrace_state_create(NULL);
14071 dtrace_anon.dta_state = state;
14073 if (state == NULL) {
14075 * This basically shouldn't happen: the only
14076 * failure mode from dtrace_state_create() is a
14077 * failure of ddi_soft_state_zalloc() that
14078 * itself should never happen. Still, the
14079 * interface allows for a failure mode, and
14080 * we want to fail as gracefully as possible:
14081 * we'll emit an error message and cease
14082 * processing anonymous state in this case.
14084 cmn_err(CE_WARN, "failed to create "
14085 "anonymous state");
14086 dtrace_dof_destroy(dof);
14091 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14092 &dtrace_anon.dta_enabling, 0, B_TRUE);
14095 rv = dtrace_dof_options(dof, state);
14097 dtrace_err_verbose = 0;
14098 dtrace_dof_destroy(dof);
14102 * This is malformed DOF; chuck any anonymous state
14105 ASSERT(dtrace_anon.dta_enabling == NULL);
14106 dtrace_state_destroy(state);
14107 dtrace_anon.dta_state = NULL;
14111 ASSERT(dtrace_anon.dta_enabling != NULL);
14114 if (dtrace_anon.dta_enabling != NULL) {
14118 * dtrace_enabling_retain() can only fail because we are
14119 * trying to retain more enablings than are allowed -- but
14120 * we only have one anonymous enabling, and we are guaranteed
14121 * to be allowed at least one retained enabling; we assert
14122 * that dtrace_enabling_retain() returns success.
14124 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14127 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14132 * DTrace Helper Functions
14135 dtrace_helper_trace(dtrace_helper_action_t *helper,
14136 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14138 uint32_t size, next, nnext, i;
14139 dtrace_helptrace_t *ent;
14140 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14142 if (!dtrace_helptrace_enabled)
14145 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14148 * What would a tracing framework be without its own tracing
14149 * framework? (Well, a hell of a lot simpler, for starters...)
14151 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14152 sizeof (uint64_t) - sizeof (uint64_t);
14155 * Iterate until we can allocate a slot in the trace buffer.
14158 next = dtrace_helptrace_next;
14160 if (next + size < dtrace_helptrace_bufsize) {
14161 nnext = next + size;
14165 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14168 * We have our slot; fill it in.
14173 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14174 ent->dtht_helper = helper;
14175 ent->dtht_where = where;
14176 ent->dtht_nlocals = vstate->dtvs_nlocals;
14178 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14179 mstate->dtms_fltoffs : -1;
14180 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14181 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14183 for (i = 0; i < vstate->dtvs_nlocals; i++) {
14184 dtrace_statvar_t *svar;
14186 if ((svar = vstate->dtvs_locals[i]) == NULL)
14189 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14190 ent->dtht_locals[i] =
14191 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14196 dtrace_helper(int which, dtrace_mstate_t *mstate,
14197 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14199 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14200 uint64_t sarg0 = mstate->dtms_arg[0];
14201 uint64_t sarg1 = mstate->dtms_arg[1];
14203 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14204 dtrace_helper_action_t *helper;
14205 dtrace_vstate_t *vstate;
14206 dtrace_difo_t *pred;
14207 int i, trace = dtrace_helptrace_enabled;
14209 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14211 if (helpers == NULL)
14214 if ((helper = helpers->dthps_actions[which]) == NULL)
14217 vstate = &helpers->dthps_vstate;
14218 mstate->dtms_arg[0] = arg0;
14219 mstate->dtms_arg[1] = arg1;
14222 * Now iterate over each helper. If its predicate evaluates to 'true',
14223 * we'll call the corresponding actions. Note that the below calls
14224 * to dtrace_dif_emulate() may set faults in machine state. This is
14225 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
14226 * the stored DIF offset with its own (which is the desired behavior).
14227 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14228 * from machine state; this is okay, too.
14230 for (; helper != NULL; helper = helper->dtha_next) {
14231 if ((pred = helper->dtha_predicate) != NULL) {
14233 dtrace_helper_trace(helper, mstate, vstate, 0);
14235 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14238 if (*flags & CPU_DTRACE_FAULT)
14242 for (i = 0; i < helper->dtha_nactions; i++) {
14244 dtrace_helper_trace(helper,
14245 mstate, vstate, i + 1);
14247 rval = dtrace_dif_emulate(helper->dtha_actions[i],
14248 mstate, vstate, state);
14250 if (*flags & CPU_DTRACE_FAULT)
14256 dtrace_helper_trace(helper, mstate, vstate,
14257 DTRACE_HELPTRACE_NEXT);
14261 dtrace_helper_trace(helper, mstate, vstate,
14262 DTRACE_HELPTRACE_DONE);
14265 * Restore the arg0 that we saved upon entry.
14267 mstate->dtms_arg[0] = sarg0;
14268 mstate->dtms_arg[1] = sarg1;
14274 dtrace_helper_trace(helper, mstate, vstate,
14275 DTRACE_HELPTRACE_ERR);
14278 * Restore the arg0 that we saved upon entry.
14280 mstate->dtms_arg[0] = sarg0;
14281 mstate->dtms_arg[1] = sarg1;
14287 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14288 dtrace_vstate_t *vstate)
14292 if (helper->dtha_predicate != NULL)
14293 dtrace_difo_release(helper->dtha_predicate, vstate);
14295 for (i = 0; i < helper->dtha_nactions; i++) {
14296 ASSERT(helper->dtha_actions[i] != NULL);
14297 dtrace_difo_release(helper->dtha_actions[i], vstate);
14300 kmem_free(helper->dtha_actions,
14301 helper->dtha_nactions * sizeof (dtrace_difo_t *));
14302 kmem_free(helper, sizeof (dtrace_helper_action_t));
14306 dtrace_helper_destroygen(int gen)
14308 proc_t *p = curproc;
14309 dtrace_helpers_t *help = p->p_dtrace_helpers;
14310 dtrace_vstate_t *vstate;
14313 ASSERT(MUTEX_HELD(&dtrace_lock));
14315 if (help == NULL || gen > help->dthps_generation)
14318 vstate = &help->dthps_vstate;
14320 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14321 dtrace_helper_action_t *last = NULL, *h, *next;
14323 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14324 next = h->dtha_next;
14326 if (h->dtha_generation == gen) {
14327 if (last != NULL) {
14328 last->dtha_next = next;
14330 help->dthps_actions[i] = next;
14333 dtrace_helper_action_destroy(h, vstate);
14341 * Interate until we've cleared out all helper providers with the
14342 * given generation number.
14345 dtrace_helper_provider_t *prov;
14348 * Look for a helper provider with the right generation. We
14349 * have to start back at the beginning of the list each time
14350 * because we drop dtrace_lock. It's unlikely that we'll make
14351 * more than two passes.
14353 for (i = 0; i < help->dthps_nprovs; i++) {
14354 prov = help->dthps_provs[i];
14356 if (prov->dthp_generation == gen)
14361 * If there were no matches, we're done.
14363 if (i == help->dthps_nprovs)
14367 * Move the last helper provider into this slot.
14369 help->dthps_nprovs--;
14370 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14371 help->dthps_provs[help->dthps_nprovs] = NULL;
14373 mutex_exit(&dtrace_lock);
14376 * If we have a meta provider, remove this helper provider.
14378 mutex_enter(&dtrace_meta_lock);
14379 if (dtrace_meta_pid != NULL) {
14380 ASSERT(dtrace_deferred_pid == NULL);
14381 dtrace_helper_provider_remove(&prov->dthp_prov,
14384 mutex_exit(&dtrace_meta_lock);
14386 dtrace_helper_provider_destroy(prov);
14388 mutex_enter(&dtrace_lock);
14395 dtrace_helper_validate(dtrace_helper_action_t *helper)
14400 if ((dp = helper->dtha_predicate) != NULL)
14401 err += dtrace_difo_validate_helper(dp);
14403 for (i = 0; i < helper->dtha_nactions; i++)
14404 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14410 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14412 dtrace_helpers_t *help;
14413 dtrace_helper_action_t *helper, *last;
14414 dtrace_actdesc_t *act;
14415 dtrace_vstate_t *vstate;
14416 dtrace_predicate_t *pred;
14417 int count = 0, nactions = 0, i;
14419 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14422 help = curproc->p_dtrace_helpers;
14423 last = help->dthps_actions[which];
14424 vstate = &help->dthps_vstate;
14426 for (count = 0; last != NULL; last = last->dtha_next) {
14428 if (last->dtha_next == NULL)
14433 * If we already have dtrace_helper_actions_max helper actions for this
14434 * helper action type, we'll refuse to add a new one.
14436 if (count >= dtrace_helper_actions_max)
14439 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14440 helper->dtha_generation = help->dthps_generation;
14442 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14443 ASSERT(pred->dtp_difo != NULL);
14444 dtrace_difo_hold(pred->dtp_difo);
14445 helper->dtha_predicate = pred->dtp_difo;
14448 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14449 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14452 if (act->dtad_difo == NULL)
14458 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14459 (helper->dtha_nactions = nactions), KM_SLEEP);
14461 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14462 dtrace_difo_hold(act->dtad_difo);
14463 helper->dtha_actions[i++] = act->dtad_difo;
14466 if (!dtrace_helper_validate(helper))
14469 if (last == NULL) {
14470 help->dthps_actions[which] = helper;
14472 last->dtha_next = helper;
14475 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14476 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14477 dtrace_helptrace_next = 0;
14482 dtrace_helper_action_destroy(helper, vstate);
14487 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14488 dof_helper_t *dofhp)
14490 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14492 mutex_enter(&dtrace_meta_lock);
14493 mutex_enter(&dtrace_lock);
14495 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14497 * If the dtrace module is loaded but not attached, or if
14498 * there aren't isn't a meta provider registered to deal with
14499 * these provider descriptions, we need to postpone creating
14500 * the actual providers until later.
14503 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14504 dtrace_deferred_pid != help) {
14505 help->dthps_deferred = 1;
14506 help->dthps_pid = p->p_pid;
14507 help->dthps_next = dtrace_deferred_pid;
14508 help->dthps_prev = NULL;
14509 if (dtrace_deferred_pid != NULL)
14510 dtrace_deferred_pid->dthps_prev = help;
14511 dtrace_deferred_pid = help;
14514 mutex_exit(&dtrace_lock);
14516 } else if (dofhp != NULL) {
14518 * If the dtrace module is loaded and we have a particular
14519 * helper provider description, pass that off to the
14523 mutex_exit(&dtrace_lock);
14525 dtrace_helper_provide(dofhp, p->p_pid);
14529 * Otherwise, just pass all the helper provider descriptions
14530 * off to the meta provider.
14534 mutex_exit(&dtrace_lock);
14536 for (i = 0; i < help->dthps_nprovs; i++) {
14537 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14542 mutex_exit(&dtrace_meta_lock);
14546 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14548 dtrace_helpers_t *help;
14549 dtrace_helper_provider_t *hprov, **tmp_provs;
14550 uint_t tmp_maxprovs, i;
14552 ASSERT(MUTEX_HELD(&dtrace_lock));
14554 help = curproc->p_dtrace_helpers;
14555 ASSERT(help != NULL);
14558 * If we already have dtrace_helper_providers_max helper providers,
14559 * we're refuse to add a new one.
14561 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14565 * Check to make sure this isn't a duplicate.
14567 for (i = 0; i < help->dthps_nprovs; i++) {
14568 if (dofhp->dofhp_addr ==
14569 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14573 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14574 hprov->dthp_prov = *dofhp;
14575 hprov->dthp_ref = 1;
14576 hprov->dthp_generation = gen;
14579 * Allocate a bigger table for helper providers if it's already full.
14581 if (help->dthps_maxprovs == help->dthps_nprovs) {
14582 tmp_maxprovs = help->dthps_maxprovs;
14583 tmp_provs = help->dthps_provs;
14585 if (help->dthps_maxprovs == 0)
14586 help->dthps_maxprovs = 2;
14588 help->dthps_maxprovs *= 2;
14589 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14590 help->dthps_maxprovs = dtrace_helper_providers_max;
14592 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14594 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14595 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14597 if (tmp_provs != NULL) {
14598 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14599 sizeof (dtrace_helper_provider_t *));
14600 kmem_free(tmp_provs, tmp_maxprovs *
14601 sizeof (dtrace_helper_provider_t *));
14605 help->dthps_provs[help->dthps_nprovs] = hprov;
14606 help->dthps_nprovs++;
14612 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14614 mutex_enter(&dtrace_lock);
14616 if (--hprov->dthp_ref == 0) {
14618 mutex_exit(&dtrace_lock);
14619 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14620 dtrace_dof_destroy(dof);
14621 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14623 mutex_exit(&dtrace_lock);
14628 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14630 uintptr_t daddr = (uintptr_t)dof;
14631 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14632 dof_provider_t *provider;
14633 dof_probe_t *probe;
14635 char *strtab, *typestr;
14636 dof_stridx_t typeidx;
14638 uint_t nprobes, j, k;
14640 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14642 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14643 dtrace_dof_error(dof, "misaligned section offset");
14648 * The section needs to be large enough to contain the DOF provider
14649 * structure appropriate for the given version.
14651 if (sec->dofs_size <
14652 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14653 offsetof(dof_provider_t, dofpv_prenoffs) :
14654 sizeof (dof_provider_t))) {
14655 dtrace_dof_error(dof, "provider section too small");
14659 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14660 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14661 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14662 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14663 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14665 if (str_sec == NULL || prb_sec == NULL ||
14666 arg_sec == NULL || off_sec == NULL)
14671 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14672 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14673 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14674 provider->dofpv_prenoffs)) == NULL)
14677 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14679 if (provider->dofpv_name >= str_sec->dofs_size ||
14680 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14681 dtrace_dof_error(dof, "invalid provider name");
14685 if (prb_sec->dofs_entsize == 0 ||
14686 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14687 dtrace_dof_error(dof, "invalid entry size");
14691 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14692 dtrace_dof_error(dof, "misaligned entry size");
14696 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14697 dtrace_dof_error(dof, "invalid entry size");
14701 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14702 dtrace_dof_error(dof, "misaligned section offset");
14706 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14707 dtrace_dof_error(dof, "invalid entry size");
14711 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14713 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14716 * Take a pass through the probes to check for errors.
14718 for (j = 0; j < nprobes; j++) {
14719 probe = (dof_probe_t *)(uintptr_t)(daddr +
14720 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14722 if (probe->dofpr_func >= str_sec->dofs_size) {
14723 dtrace_dof_error(dof, "invalid function name");
14727 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14728 dtrace_dof_error(dof, "function name too long");
14732 if (probe->dofpr_name >= str_sec->dofs_size ||
14733 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14734 dtrace_dof_error(dof, "invalid probe name");
14739 * The offset count must not wrap the index, and the offsets
14740 * must also not overflow the section's data.
14742 if (probe->dofpr_offidx + probe->dofpr_noffs <
14743 probe->dofpr_offidx ||
14744 (probe->dofpr_offidx + probe->dofpr_noffs) *
14745 off_sec->dofs_entsize > off_sec->dofs_size) {
14746 dtrace_dof_error(dof, "invalid probe offset");
14750 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14752 * If there's no is-enabled offset section, make sure
14753 * there aren't any is-enabled offsets. Otherwise
14754 * perform the same checks as for probe offsets
14755 * (immediately above).
14757 if (enoff_sec == NULL) {
14758 if (probe->dofpr_enoffidx != 0 ||
14759 probe->dofpr_nenoffs != 0) {
14760 dtrace_dof_error(dof, "is-enabled "
14761 "offsets with null section");
14764 } else if (probe->dofpr_enoffidx +
14765 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14766 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14767 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14768 dtrace_dof_error(dof, "invalid is-enabled "
14773 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14774 dtrace_dof_error(dof, "zero probe and "
14775 "is-enabled offsets");
14778 } else if (probe->dofpr_noffs == 0) {
14779 dtrace_dof_error(dof, "zero probe offsets");
14783 if (probe->dofpr_argidx + probe->dofpr_xargc <
14784 probe->dofpr_argidx ||
14785 (probe->dofpr_argidx + probe->dofpr_xargc) *
14786 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14787 dtrace_dof_error(dof, "invalid args");
14791 typeidx = probe->dofpr_nargv;
14792 typestr = strtab + probe->dofpr_nargv;
14793 for (k = 0; k < probe->dofpr_nargc; k++) {
14794 if (typeidx >= str_sec->dofs_size) {
14795 dtrace_dof_error(dof, "bad "
14796 "native argument type");
14800 typesz = strlen(typestr) + 1;
14801 if (typesz > DTRACE_ARGTYPELEN) {
14802 dtrace_dof_error(dof, "native "
14803 "argument type too long");
14810 typeidx = probe->dofpr_xargv;
14811 typestr = strtab + probe->dofpr_xargv;
14812 for (k = 0; k < probe->dofpr_xargc; k++) {
14813 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14814 dtrace_dof_error(dof, "bad "
14815 "native argument index");
14819 if (typeidx >= str_sec->dofs_size) {
14820 dtrace_dof_error(dof, "bad "
14821 "translated argument type");
14825 typesz = strlen(typestr) + 1;
14826 if (typesz > DTRACE_ARGTYPELEN) {
14827 dtrace_dof_error(dof, "translated argument "
14841 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14843 dtrace_helpers_t *help;
14844 dtrace_vstate_t *vstate;
14845 dtrace_enabling_t *enab = NULL;
14846 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14847 uintptr_t daddr = (uintptr_t)dof;
14849 ASSERT(MUTEX_HELD(&dtrace_lock));
14851 if ((help = curproc->p_dtrace_helpers) == NULL)
14852 help = dtrace_helpers_create(curproc);
14854 vstate = &help->dthps_vstate;
14856 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14857 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14858 dtrace_dof_destroy(dof);
14863 * Look for helper providers and validate their descriptions.
14866 for (i = 0; i < dof->dofh_secnum; i++) {
14867 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14868 dof->dofh_secoff + i * dof->dofh_secsize);
14870 if (sec->dofs_type != DOF_SECT_PROVIDER)
14873 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14874 dtrace_enabling_destroy(enab);
14875 dtrace_dof_destroy(dof);
14884 * Now we need to walk through the ECB descriptions in the enabling.
14886 for (i = 0; i < enab->dten_ndesc; i++) {
14887 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14888 dtrace_probedesc_t *desc = &ep->dted_probe;
14890 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14893 if (strcmp(desc->dtpd_mod, "helper") != 0)
14896 if (strcmp(desc->dtpd_func, "ustack") != 0)
14899 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14902 * Adding this helper action failed -- we are now going
14903 * to rip out the entire generation and return failure.
14905 (void) dtrace_helper_destroygen(help->dthps_generation);
14906 dtrace_enabling_destroy(enab);
14907 dtrace_dof_destroy(dof);
14914 if (nhelpers < enab->dten_ndesc)
14915 dtrace_dof_error(dof, "unmatched helpers");
14917 gen = help->dthps_generation++;
14918 dtrace_enabling_destroy(enab);
14920 if (dhp != NULL && nprovs > 0) {
14921 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14922 if (dtrace_helper_provider_add(dhp, gen) == 0) {
14923 mutex_exit(&dtrace_lock);
14924 dtrace_helper_provider_register(curproc, help, dhp);
14925 mutex_enter(&dtrace_lock);
14932 dtrace_dof_destroy(dof);
14937 static dtrace_helpers_t *
14938 dtrace_helpers_create(proc_t *p)
14940 dtrace_helpers_t *help;
14942 ASSERT(MUTEX_HELD(&dtrace_lock));
14943 ASSERT(p->p_dtrace_helpers == NULL);
14945 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14946 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14947 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14949 p->p_dtrace_helpers = help;
14959 dtrace_helpers_destroy(proc_t *p)
14961 dtrace_helpers_t *help;
14962 dtrace_vstate_t *vstate;
14964 proc_t *p = curproc;
14968 mutex_enter(&dtrace_lock);
14970 ASSERT(p->p_dtrace_helpers != NULL);
14971 ASSERT(dtrace_helpers > 0);
14973 help = p->p_dtrace_helpers;
14974 vstate = &help->dthps_vstate;
14977 * We're now going to lose the help from this process.
14979 p->p_dtrace_helpers = NULL;
14983 * Destory the helper actions.
14985 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14986 dtrace_helper_action_t *h, *next;
14988 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14989 next = h->dtha_next;
14990 dtrace_helper_action_destroy(h, vstate);
14995 mutex_exit(&dtrace_lock);
14998 * Destroy the helper providers.
15000 if (help->dthps_maxprovs > 0) {
15001 mutex_enter(&dtrace_meta_lock);
15002 if (dtrace_meta_pid != NULL) {
15003 ASSERT(dtrace_deferred_pid == NULL);
15005 for (i = 0; i < help->dthps_nprovs; i++) {
15006 dtrace_helper_provider_remove(
15007 &help->dthps_provs[i]->dthp_prov, p->p_pid);
15010 mutex_enter(&dtrace_lock);
15011 ASSERT(help->dthps_deferred == 0 ||
15012 help->dthps_next != NULL ||
15013 help->dthps_prev != NULL ||
15014 help == dtrace_deferred_pid);
15017 * Remove the helper from the deferred list.
15019 if (help->dthps_next != NULL)
15020 help->dthps_next->dthps_prev = help->dthps_prev;
15021 if (help->dthps_prev != NULL)
15022 help->dthps_prev->dthps_next = help->dthps_next;
15023 if (dtrace_deferred_pid == help) {
15024 dtrace_deferred_pid = help->dthps_next;
15025 ASSERT(help->dthps_prev == NULL);
15028 mutex_exit(&dtrace_lock);
15031 mutex_exit(&dtrace_meta_lock);
15033 for (i = 0; i < help->dthps_nprovs; i++) {
15034 dtrace_helper_provider_destroy(help->dthps_provs[i]);
15037 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15038 sizeof (dtrace_helper_provider_t *));
15041 mutex_enter(&dtrace_lock);
15043 dtrace_vstate_fini(&help->dthps_vstate);
15044 kmem_free(help->dthps_actions,
15045 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15046 kmem_free(help, sizeof (dtrace_helpers_t));
15049 mutex_exit(&dtrace_lock);
15056 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15058 dtrace_helpers_t *help, *newhelp;
15059 dtrace_helper_action_t *helper, *new, *last;
15061 dtrace_vstate_t *vstate;
15062 int i, j, sz, hasprovs = 0;
15064 mutex_enter(&dtrace_lock);
15065 ASSERT(from->p_dtrace_helpers != NULL);
15066 ASSERT(dtrace_helpers > 0);
15068 help = from->p_dtrace_helpers;
15069 newhelp = dtrace_helpers_create(to);
15070 ASSERT(to->p_dtrace_helpers != NULL);
15072 newhelp->dthps_generation = help->dthps_generation;
15073 vstate = &newhelp->dthps_vstate;
15076 * Duplicate the helper actions.
15078 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15079 if ((helper = help->dthps_actions[i]) == NULL)
15082 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15083 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15085 new->dtha_generation = helper->dtha_generation;
15087 if ((dp = helper->dtha_predicate) != NULL) {
15088 dp = dtrace_difo_duplicate(dp, vstate);
15089 new->dtha_predicate = dp;
15092 new->dtha_nactions = helper->dtha_nactions;
15093 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15094 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15096 for (j = 0; j < new->dtha_nactions; j++) {
15097 dtrace_difo_t *dp = helper->dtha_actions[j];
15099 ASSERT(dp != NULL);
15100 dp = dtrace_difo_duplicate(dp, vstate);
15101 new->dtha_actions[j] = dp;
15104 if (last != NULL) {
15105 last->dtha_next = new;
15107 newhelp->dthps_actions[i] = new;
15115 * Duplicate the helper providers and register them with the
15116 * DTrace framework.
15118 if (help->dthps_nprovs > 0) {
15119 newhelp->dthps_nprovs = help->dthps_nprovs;
15120 newhelp->dthps_maxprovs = help->dthps_nprovs;
15121 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15122 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15123 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15124 newhelp->dthps_provs[i] = help->dthps_provs[i];
15125 newhelp->dthps_provs[i]->dthp_ref++;
15131 mutex_exit(&dtrace_lock);
15134 dtrace_helper_provider_register(to, newhelp, NULL);
15138 * DTrace Hook Functions
15141 dtrace_module_loaded(modctl_t *ctl)
15143 dtrace_provider_t *prv;
15145 mutex_enter(&dtrace_provider_lock);
15146 mutex_enter(&mod_lock);
15149 ASSERT(ctl->mod_busy);
15153 * We're going to call each providers per-module provide operation
15154 * specifying only this module.
15156 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15157 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15159 mutex_exit(&mod_lock);
15160 mutex_exit(&dtrace_provider_lock);
15163 * If we have any retained enablings, we need to match against them.
15164 * Enabling probes requires that cpu_lock be held, and we cannot hold
15165 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15166 * module. (In particular, this happens when loading scheduling
15167 * classes.) So if we have any retained enablings, we need to dispatch
15168 * our task queue to do the match for us.
15170 mutex_enter(&dtrace_lock);
15172 if (dtrace_retained == NULL) {
15173 mutex_exit(&dtrace_lock);
15177 (void) taskq_dispatch(dtrace_taskq,
15178 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15180 mutex_exit(&dtrace_lock);
15183 * And now, for a little heuristic sleaze: in general, we want to
15184 * match modules as soon as they load. However, we cannot guarantee
15185 * this, because it would lead us to the lock ordering violation
15186 * outlined above. The common case, of course, is that cpu_lock is
15187 * _not_ held -- so we delay here for a clock tick, hoping that that's
15188 * long enough for the task queue to do its work. If it's not, it's
15189 * not a serious problem -- it just means that the module that we
15190 * just loaded may not be immediately instrumentable.
15197 dtrace_module_unloaded(modctl_t *ctl)
15199 dtrace_module_unloaded(modctl_t *ctl, int *error)
15202 dtrace_probe_t template, *probe, *first, *next;
15203 dtrace_provider_t *prov;
15205 char modname[DTRACE_MODNAMELEN];
15210 template.dtpr_mod = ctl->mod_modname;
15212 /* Handle the fact that ctl->filename may end in ".ko". */
15213 strlcpy(modname, ctl->filename, sizeof(modname));
15214 len = strlen(ctl->filename);
15215 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15216 modname[len - 3] = '\0';
15217 template.dtpr_mod = modname;
15220 mutex_enter(&dtrace_provider_lock);
15221 mutex_enter(&mod_lock);
15222 mutex_enter(&dtrace_lock);
15225 if (ctl->nenabled > 0) {
15226 /* Don't allow unloads if a probe is enabled. */
15227 mutex_exit(&dtrace_provider_lock);
15228 mutex_exit(&dtrace_lock);
15231 "kldunload: attempt to unload module that has DTrace probes enabled\n");
15236 if (dtrace_bymod == NULL) {
15238 * The DTrace module is loaded (obviously) but not attached;
15239 * we don't have any work to do.
15241 mutex_exit(&dtrace_provider_lock);
15242 mutex_exit(&mod_lock);
15243 mutex_exit(&dtrace_lock);
15247 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15248 probe != NULL; probe = probe->dtpr_nextmod) {
15249 if (probe->dtpr_ecb != NULL) {
15250 mutex_exit(&dtrace_provider_lock);
15251 mutex_exit(&mod_lock);
15252 mutex_exit(&dtrace_lock);
15255 * This shouldn't _actually_ be possible -- we're
15256 * unloading a module that has an enabled probe in it.
15257 * (It's normally up to the provider to make sure that
15258 * this can't happen.) However, because dtps_enable()
15259 * doesn't have a failure mode, there can be an
15260 * enable/unload race. Upshot: we don't want to
15261 * assert, but we're not going to disable the
15264 if (dtrace_err_verbose) {
15266 cmn_err(CE_WARN, "unloaded module '%s' had "
15267 "enabled probes", ctl->mod_modname);
15269 cmn_err(CE_WARN, "unloaded module '%s' had "
15270 "enabled probes", modname);
15280 for (first = NULL; probe != NULL; probe = next) {
15281 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15283 dtrace_probes[probe->dtpr_id - 1] = NULL;
15285 next = probe->dtpr_nextmod;
15286 dtrace_hash_remove(dtrace_bymod, probe);
15287 dtrace_hash_remove(dtrace_byfunc, probe);
15288 dtrace_hash_remove(dtrace_byname, probe);
15290 if (first == NULL) {
15292 probe->dtpr_nextmod = NULL;
15294 probe->dtpr_nextmod = first;
15300 * We've removed all of the module's probes from the hash chains and
15301 * from the probe array. Now issue a dtrace_sync() to be sure that
15302 * everyone has cleared out from any probe array processing.
15306 for (probe = first; probe != NULL; probe = first) {
15307 first = probe->dtpr_nextmod;
15308 prov = probe->dtpr_provider;
15309 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15311 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15312 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15313 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15315 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15317 free_unr(dtrace_arena, probe->dtpr_id);
15319 kmem_free(probe, sizeof (dtrace_probe_t));
15322 mutex_exit(&dtrace_lock);
15323 mutex_exit(&mod_lock);
15324 mutex_exit(&dtrace_provider_lock);
15329 dtrace_kld_load(void *arg __unused, linker_file_t lf)
15332 dtrace_module_loaded(lf);
15336 dtrace_kld_unload(void *arg __unused, linker_file_t lf, int *error)
15340 /* We already have an error, so don't do anything. */
15342 dtrace_module_unloaded(lf, error);
15348 dtrace_suspend(void)
15350 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15354 dtrace_resume(void)
15356 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15361 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15363 ASSERT(MUTEX_HELD(&cpu_lock));
15364 mutex_enter(&dtrace_lock);
15368 dtrace_state_t *state;
15369 dtrace_optval_t *opt, rs, c;
15372 * For now, we only allocate a new buffer for anonymous state.
15374 if ((state = dtrace_anon.dta_state) == NULL)
15377 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15380 opt = state->dts_options;
15381 c = opt[DTRACEOPT_CPU];
15383 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15387 * Regardless of what the actual policy is, we're going to
15388 * temporarily set our resize policy to be manual. We're
15389 * also going to temporarily set our CPU option to denote
15390 * the newly configured CPU.
15392 rs = opt[DTRACEOPT_BUFRESIZE];
15393 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15394 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15396 (void) dtrace_state_buffers(state);
15398 opt[DTRACEOPT_BUFRESIZE] = rs;
15399 opt[DTRACEOPT_CPU] = c;
15406 * We don't free the buffer in the CPU_UNCONFIG case. (The
15407 * buffer will be freed when the consumer exits.)
15415 mutex_exit(&dtrace_lock);
15421 dtrace_cpu_setup_initial(processorid_t cpu)
15423 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15428 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15430 if (dtrace_toxranges >= dtrace_toxranges_max) {
15432 dtrace_toxrange_t *range;
15434 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15437 ASSERT(dtrace_toxrange == NULL);
15438 ASSERT(dtrace_toxranges_max == 0);
15439 dtrace_toxranges_max = 1;
15441 dtrace_toxranges_max <<= 1;
15444 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15445 range = kmem_zalloc(nsize, KM_SLEEP);
15447 if (dtrace_toxrange != NULL) {
15448 ASSERT(osize != 0);
15449 bcopy(dtrace_toxrange, range, osize);
15450 kmem_free(dtrace_toxrange, osize);
15453 dtrace_toxrange = range;
15456 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15457 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15459 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15460 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15461 dtrace_toxranges++;
15465 * DTrace Driver Cookbook Functions
15470 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15472 dtrace_provider_id_t id;
15473 dtrace_state_t *state = NULL;
15474 dtrace_enabling_t *enab;
15476 mutex_enter(&cpu_lock);
15477 mutex_enter(&dtrace_provider_lock);
15478 mutex_enter(&dtrace_lock);
15480 if (ddi_soft_state_init(&dtrace_softstate,
15481 sizeof (dtrace_state_t), 0) != 0) {
15482 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15483 mutex_exit(&cpu_lock);
15484 mutex_exit(&dtrace_provider_lock);
15485 mutex_exit(&dtrace_lock);
15486 return (DDI_FAILURE);
15489 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15490 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15491 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15492 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15493 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15494 ddi_remove_minor_node(devi, NULL);
15495 ddi_soft_state_fini(&dtrace_softstate);
15496 mutex_exit(&cpu_lock);
15497 mutex_exit(&dtrace_provider_lock);
15498 mutex_exit(&dtrace_lock);
15499 return (DDI_FAILURE);
15502 ddi_report_dev(devi);
15503 dtrace_devi = devi;
15505 dtrace_modload = dtrace_module_loaded;
15506 dtrace_modunload = dtrace_module_unloaded;
15507 dtrace_cpu_init = dtrace_cpu_setup_initial;
15508 dtrace_helpers_cleanup = dtrace_helpers_destroy;
15509 dtrace_helpers_fork = dtrace_helpers_duplicate;
15510 dtrace_cpustart_init = dtrace_suspend;
15511 dtrace_cpustart_fini = dtrace_resume;
15512 dtrace_debugger_init = dtrace_suspend;
15513 dtrace_debugger_fini = dtrace_resume;
15515 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15517 ASSERT(MUTEX_HELD(&cpu_lock));
15519 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15520 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15521 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15522 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15523 VM_SLEEP | VMC_IDENTIFIER);
15524 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15527 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15528 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15529 NULL, NULL, NULL, NULL, NULL, 0);
15531 ASSERT(MUTEX_HELD(&cpu_lock));
15532 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15533 offsetof(dtrace_probe_t, dtpr_nextmod),
15534 offsetof(dtrace_probe_t, dtpr_prevmod));
15536 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15537 offsetof(dtrace_probe_t, dtpr_nextfunc),
15538 offsetof(dtrace_probe_t, dtpr_prevfunc));
15540 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15541 offsetof(dtrace_probe_t, dtpr_nextname),
15542 offsetof(dtrace_probe_t, dtpr_prevname));
15544 if (dtrace_retain_max < 1) {
15545 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15546 "setting to 1", dtrace_retain_max);
15547 dtrace_retain_max = 1;
15551 * Now discover our toxic ranges.
15553 dtrace_toxic_ranges(dtrace_toxrange_add);
15556 * Before we register ourselves as a provider to our own framework,
15557 * we would like to assert that dtrace_provider is NULL -- but that's
15558 * not true if we were loaded as a dependency of a DTrace provider.
15559 * Once we've registered, we can assert that dtrace_provider is our
15562 (void) dtrace_register("dtrace", &dtrace_provider_attr,
15563 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15565 ASSERT(dtrace_provider != NULL);
15566 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15568 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15569 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15570 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15571 dtrace_provider, NULL, NULL, "END", 0, NULL);
15572 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15573 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15575 dtrace_anon_property();
15576 mutex_exit(&cpu_lock);
15579 * If DTrace helper tracing is enabled, we need to allocate the
15580 * trace buffer and initialize the values.
15582 if (dtrace_helptrace_enabled) {
15583 ASSERT(dtrace_helptrace_buffer == NULL);
15584 dtrace_helptrace_buffer =
15585 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15586 dtrace_helptrace_next = 0;
15590 * If there are already providers, we must ask them to provide their
15591 * probes, and then match any anonymous enabling against them. Note
15592 * that there should be no other retained enablings at this time:
15593 * the only retained enablings at this time should be the anonymous
15596 if (dtrace_anon.dta_enabling != NULL) {
15597 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15599 dtrace_enabling_provide(NULL);
15600 state = dtrace_anon.dta_state;
15603 * We couldn't hold cpu_lock across the above call to
15604 * dtrace_enabling_provide(), but we must hold it to actually
15605 * enable the probes. We have to drop all of our locks, pick
15606 * up cpu_lock, and regain our locks before matching the
15607 * retained anonymous enabling.
15609 mutex_exit(&dtrace_lock);
15610 mutex_exit(&dtrace_provider_lock);
15612 mutex_enter(&cpu_lock);
15613 mutex_enter(&dtrace_provider_lock);
15614 mutex_enter(&dtrace_lock);
15616 if ((enab = dtrace_anon.dta_enabling) != NULL)
15617 (void) dtrace_enabling_match(enab, NULL);
15619 mutex_exit(&cpu_lock);
15622 mutex_exit(&dtrace_lock);
15623 mutex_exit(&dtrace_provider_lock);
15625 if (state != NULL) {
15627 * If we created any anonymous state, set it going now.
15629 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15632 return (DDI_SUCCESS);
15637 #if __FreeBSD_version >= 800039
15639 dtrace_dtr(void *data __unused)
15648 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15650 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
15653 dtrace_state_t *state;
15659 if (getminor(*devp) == DTRACEMNRN_HELPER)
15663 * If this wasn't an open with the "helper" minor, then it must be
15664 * the "dtrace" minor.
15666 ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
15668 cred_t *cred_p = NULL;
15670 #if __FreeBSD_version < 800039
15672 * The first minor device is the one that is cloned so there is
15673 * nothing more to do here.
15675 if (dev2unit(dev) == 0)
15679 * Devices are cloned, so if the DTrace state has already
15680 * been allocated, that means this device belongs to a
15681 * different client. Each client should open '/dev/dtrace'
15682 * to get a cloned device.
15684 if (dev->si_drv1 != NULL)
15688 cred_p = dev->si_cred;
15692 * If no DTRACE_PRIV_* bits are set in the credential, then the
15693 * caller lacks sufficient permission to do anything with DTrace.
15695 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15696 if (priv == DTRACE_PRIV_NONE) {
15698 #if __FreeBSD_version < 800039
15699 /* Destroy the cloned device. */
15708 * Ask all providers to provide all their probes.
15710 mutex_enter(&dtrace_provider_lock);
15711 dtrace_probe_provide(NULL, NULL);
15712 mutex_exit(&dtrace_provider_lock);
15714 mutex_enter(&cpu_lock);
15715 mutex_enter(&dtrace_lock);
15717 dtrace_membar_producer();
15721 * If the kernel debugger is active (that is, if the kernel debugger
15722 * modified text in some way), we won't allow the open.
15724 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15726 mutex_exit(&cpu_lock);
15727 mutex_exit(&dtrace_lock);
15731 state = dtrace_state_create(devp, cred_p);
15733 state = dtrace_state_create(dev);
15734 #if __FreeBSD_version < 800039
15735 dev->si_drv1 = state;
15737 devfs_set_cdevpriv(state, dtrace_dtr);
15739 /* This code actually belongs in dtrace_attach() */
15740 if (dtrace_opens == 1)
15741 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15745 mutex_exit(&cpu_lock);
15747 if (state == NULL) {
15749 if (--dtrace_opens == 0)
15750 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15754 mutex_exit(&dtrace_lock);
15756 #if __FreeBSD_version < 800039
15757 /* Destroy the cloned device. */
15764 mutex_exit(&dtrace_lock);
15772 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15774 dtrace_close(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
15778 minor_t minor = getminor(dev);
15779 dtrace_state_t *state;
15781 if (minor == DTRACEMNRN_HELPER)
15784 state = ddi_get_soft_state(dtrace_softstate, minor);
15786 #if __FreeBSD_version < 800039
15787 dtrace_state_t *state = dev->si_drv1;
15789 /* Check if this is not a cloned device. */
15790 if (dev2unit(dev) == 0)
15793 dtrace_state_t *state;
15794 devfs_get_cdevpriv((void **) &state);
15799 mutex_enter(&cpu_lock);
15800 mutex_enter(&dtrace_lock);
15802 if (state != NULL) {
15803 if (state->dts_anon) {
15805 * There is anonymous state. Destroy that first.
15807 ASSERT(dtrace_anon.dta_state == NULL);
15808 dtrace_state_destroy(state->dts_anon);
15811 dtrace_state_destroy(state);
15814 kmem_free(state, 0);
15815 #if __FreeBSD_version < 800039
15816 dev->si_drv1 = NULL;
15821 ASSERT(dtrace_opens > 0);
15823 if (--dtrace_opens == 0)
15824 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15827 /* This code actually belongs in dtrace_detach() */
15828 if ((dtrace_opens == 0) && (dtrace_taskq != NULL)) {
15829 taskq_destroy(dtrace_taskq);
15830 dtrace_taskq = NULL;
15834 mutex_exit(&dtrace_lock);
15835 mutex_exit(&cpu_lock);
15837 #if __FreeBSD_version < 800039
15838 /* Schedule this cloned device to be destroyed. */
15839 destroy_dev_sched(dev);
15848 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15851 dof_helper_t help, *dhp = NULL;
15854 case DTRACEHIOC_ADDDOF:
15855 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15856 dtrace_dof_error(NULL, "failed to copyin DOF helper");
15861 arg = (intptr_t)help.dofhp_dof;
15864 case DTRACEHIOC_ADD: {
15865 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15870 mutex_enter(&dtrace_lock);
15873 * dtrace_helper_slurp() takes responsibility for the dof --
15874 * it may free it now or it may save it and free it later.
15876 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15883 mutex_exit(&dtrace_lock);
15887 case DTRACEHIOC_REMOVE: {
15888 mutex_enter(&dtrace_lock);
15889 rval = dtrace_helper_destroygen(arg);
15890 mutex_exit(&dtrace_lock);
15904 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15906 minor_t minor = getminor(dev);
15907 dtrace_state_t *state;
15910 if (minor == DTRACEMNRN_HELPER)
15911 return (dtrace_ioctl_helper(cmd, arg, rv));
15913 state = ddi_get_soft_state(dtrace_softstate, minor);
15915 if (state->dts_anon) {
15916 ASSERT(dtrace_anon.dta_state == NULL);
15917 state = state->dts_anon;
15921 case DTRACEIOC_PROVIDER: {
15922 dtrace_providerdesc_t pvd;
15923 dtrace_provider_t *pvp;
15925 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15928 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15929 mutex_enter(&dtrace_provider_lock);
15931 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15932 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15936 mutex_exit(&dtrace_provider_lock);
15941 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15942 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15944 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15950 case DTRACEIOC_EPROBE: {
15951 dtrace_eprobedesc_t epdesc;
15953 dtrace_action_t *act;
15959 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15962 mutex_enter(&dtrace_lock);
15964 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15965 mutex_exit(&dtrace_lock);
15969 if (ecb->dte_probe == NULL) {
15970 mutex_exit(&dtrace_lock);
15974 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15975 epdesc.dtepd_uarg = ecb->dte_uarg;
15976 epdesc.dtepd_size = ecb->dte_size;
15978 nrecs = epdesc.dtepd_nrecs;
15979 epdesc.dtepd_nrecs = 0;
15980 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15981 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15984 epdesc.dtepd_nrecs++;
15988 * Now that we have the size, we need to allocate a temporary
15989 * buffer in which to store the complete description. We need
15990 * the temporary buffer to be able to drop dtrace_lock()
15991 * across the copyout(), below.
15993 size = sizeof (dtrace_eprobedesc_t) +
15994 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15996 buf = kmem_alloc(size, KM_SLEEP);
15997 dest = (uintptr_t)buf;
15999 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16000 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16002 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16003 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16009 bcopy(&act->dta_rec, (void *)dest,
16010 sizeof (dtrace_recdesc_t));
16011 dest += sizeof (dtrace_recdesc_t);
16014 mutex_exit(&dtrace_lock);
16016 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16017 kmem_free(buf, size);
16021 kmem_free(buf, size);
16025 case DTRACEIOC_AGGDESC: {
16026 dtrace_aggdesc_t aggdesc;
16027 dtrace_action_t *act;
16028 dtrace_aggregation_t *agg;
16031 dtrace_recdesc_t *lrec;
16036 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16039 mutex_enter(&dtrace_lock);
16041 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16042 mutex_exit(&dtrace_lock);
16046 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16048 nrecs = aggdesc.dtagd_nrecs;
16049 aggdesc.dtagd_nrecs = 0;
16051 offs = agg->dtag_base;
16052 lrec = &agg->dtag_action.dta_rec;
16053 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16055 for (act = agg->dtag_first; ; act = act->dta_next) {
16056 ASSERT(act->dta_intuple ||
16057 DTRACEACT_ISAGG(act->dta_kind));
16060 * If this action has a record size of zero, it
16061 * denotes an argument to the aggregating action.
16062 * Because the presence of this record doesn't (or
16063 * shouldn't) affect the way the data is interpreted,
16064 * we don't copy it out to save user-level the
16065 * confusion of dealing with a zero-length record.
16067 if (act->dta_rec.dtrd_size == 0) {
16068 ASSERT(agg->dtag_hasarg);
16072 aggdesc.dtagd_nrecs++;
16074 if (act == &agg->dtag_action)
16079 * Now that we have the size, we need to allocate a temporary
16080 * buffer in which to store the complete description. We need
16081 * the temporary buffer to be able to drop dtrace_lock()
16082 * across the copyout(), below.
16084 size = sizeof (dtrace_aggdesc_t) +
16085 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16087 buf = kmem_alloc(size, KM_SLEEP);
16088 dest = (uintptr_t)buf;
16090 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16091 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16093 for (act = agg->dtag_first; ; act = act->dta_next) {
16094 dtrace_recdesc_t rec = act->dta_rec;
16097 * See the comment in the above loop for why we pass
16098 * over zero-length records.
16100 if (rec.dtrd_size == 0) {
16101 ASSERT(agg->dtag_hasarg);
16108 rec.dtrd_offset -= offs;
16109 bcopy(&rec, (void *)dest, sizeof (rec));
16110 dest += sizeof (dtrace_recdesc_t);
16112 if (act == &agg->dtag_action)
16116 mutex_exit(&dtrace_lock);
16118 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16119 kmem_free(buf, size);
16123 kmem_free(buf, size);
16127 case DTRACEIOC_ENABLE: {
16129 dtrace_enabling_t *enab = NULL;
16130 dtrace_vstate_t *vstate;
16136 * If a NULL argument has been passed, we take this as our
16137 * cue to reevaluate our enablings.
16140 dtrace_enabling_matchall();
16145 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16148 mutex_enter(&cpu_lock);
16149 mutex_enter(&dtrace_lock);
16150 vstate = &state->dts_vstate;
16152 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16153 mutex_exit(&dtrace_lock);
16154 mutex_exit(&cpu_lock);
16155 dtrace_dof_destroy(dof);
16159 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16160 mutex_exit(&dtrace_lock);
16161 mutex_exit(&cpu_lock);
16162 dtrace_dof_destroy(dof);
16166 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16167 dtrace_enabling_destroy(enab);
16168 mutex_exit(&dtrace_lock);
16169 mutex_exit(&cpu_lock);
16170 dtrace_dof_destroy(dof);
16174 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16175 err = dtrace_enabling_retain(enab);
16177 dtrace_enabling_destroy(enab);
16180 mutex_exit(&cpu_lock);
16181 mutex_exit(&dtrace_lock);
16182 dtrace_dof_destroy(dof);
16187 case DTRACEIOC_REPLICATE: {
16188 dtrace_repldesc_t desc;
16189 dtrace_probedesc_t *match = &desc.dtrpd_match;
16190 dtrace_probedesc_t *create = &desc.dtrpd_create;
16193 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16196 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16197 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16198 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16199 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16201 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16202 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16203 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16204 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16206 mutex_enter(&dtrace_lock);
16207 err = dtrace_enabling_replicate(state, match, create);
16208 mutex_exit(&dtrace_lock);
16213 case DTRACEIOC_PROBEMATCH:
16214 case DTRACEIOC_PROBES: {
16215 dtrace_probe_t *probe = NULL;
16216 dtrace_probedesc_t desc;
16217 dtrace_probekey_t pkey;
16224 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16227 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16228 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16229 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16230 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16233 * Before we attempt to match this probe, we want to give
16234 * all providers the opportunity to provide it.
16236 if (desc.dtpd_id == DTRACE_IDNONE) {
16237 mutex_enter(&dtrace_provider_lock);
16238 dtrace_probe_provide(&desc, NULL);
16239 mutex_exit(&dtrace_provider_lock);
16243 if (cmd == DTRACEIOC_PROBEMATCH) {
16244 dtrace_probekey(&desc, &pkey);
16245 pkey.dtpk_id = DTRACE_IDNONE;
16248 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16250 mutex_enter(&dtrace_lock);
16252 if (cmd == DTRACEIOC_PROBEMATCH) {
16253 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16254 if ((probe = dtrace_probes[i - 1]) != NULL &&
16255 (m = dtrace_match_probe(probe, &pkey,
16256 priv, uid, zoneid)) != 0)
16261 mutex_exit(&dtrace_lock);
16266 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16267 if ((probe = dtrace_probes[i - 1]) != NULL &&
16268 dtrace_match_priv(probe, priv, uid, zoneid))
16273 if (probe == NULL) {
16274 mutex_exit(&dtrace_lock);
16278 dtrace_probe_description(probe, &desc);
16279 mutex_exit(&dtrace_lock);
16281 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16287 case DTRACEIOC_PROBEARG: {
16288 dtrace_argdesc_t desc;
16289 dtrace_probe_t *probe;
16290 dtrace_provider_t *prov;
16292 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16295 if (desc.dtargd_id == DTRACE_IDNONE)
16298 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16301 mutex_enter(&dtrace_provider_lock);
16302 mutex_enter(&mod_lock);
16303 mutex_enter(&dtrace_lock);
16305 if (desc.dtargd_id > dtrace_nprobes) {
16306 mutex_exit(&dtrace_lock);
16307 mutex_exit(&mod_lock);
16308 mutex_exit(&dtrace_provider_lock);
16312 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16313 mutex_exit(&dtrace_lock);
16314 mutex_exit(&mod_lock);
16315 mutex_exit(&dtrace_provider_lock);
16319 mutex_exit(&dtrace_lock);
16321 prov = probe->dtpr_provider;
16323 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16325 * There isn't any typed information for this probe.
16326 * Set the argument number to DTRACE_ARGNONE.
16328 desc.dtargd_ndx = DTRACE_ARGNONE;
16330 desc.dtargd_native[0] = '\0';
16331 desc.dtargd_xlate[0] = '\0';
16332 desc.dtargd_mapping = desc.dtargd_ndx;
16334 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16335 probe->dtpr_id, probe->dtpr_arg, &desc);
16338 mutex_exit(&mod_lock);
16339 mutex_exit(&dtrace_provider_lock);
16341 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16347 case DTRACEIOC_GO: {
16348 processorid_t cpuid;
16349 rval = dtrace_state_go(state, &cpuid);
16354 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16360 case DTRACEIOC_STOP: {
16361 processorid_t cpuid;
16363 mutex_enter(&dtrace_lock);
16364 rval = dtrace_state_stop(state, &cpuid);
16365 mutex_exit(&dtrace_lock);
16370 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16376 case DTRACEIOC_DOFGET: {
16377 dof_hdr_t hdr, *dof;
16380 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16383 mutex_enter(&dtrace_lock);
16384 dof = dtrace_dof_create(state);
16385 mutex_exit(&dtrace_lock);
16387 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16388 rval = copyout(dof, (void *)arg, len);
16389 dtrace_dof_destroy(dof);
16391 return (rval == 0 ? 0 : EFAULT);
16394 case DTRACEIOC_AGGSNAP:
16395 case DTRACEIOC_BUFSNAP: {
16396 dtrace_bufdesc_t desc;
16398 dtrace_buffer_t *buf;
16400 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16403 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16406 mutex_enter(&dtrace_lock);
16408 if (cmd == DTRACEIOC_BUFSNAP) {
16409 buf = &state->dts_buffer[desc.dtbd_cpu];
16411 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16414 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16415 size_t sz = buf->dtb_offset;
16417 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16418 mutex_exit(&dtrace_lock);
16423 * If this buffer has already been consumed, we're
16424 * going to indicate that there's nothing left here
16427 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16428 mutex_exit(&dtrace_lock);
16430 desc.dtbd_size = 0;
16431 desc.dtbd_drops = 0;
16432 desc.dtbd_errors = 0;
16433 desc.dtbd_oldest = 0;
16434 sz = sizeof (desc);
16436 if (copyout(&desc, (void *)arg, sz) != 0)
16443 * If this is a ring buffer that has wrapped, we want
16444 * to copy the whole thing out.
16446 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16447 dtrace_buffer_polish(buf);
16448 sz = buf->dtb_size;
16451 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16452 mutex_exit(&dtrace_lock);
16456 desc.dtbd_size = sz;
16457 desc.dtbd_drops = buf->dtb_drops;
16458 desc.dtbd_errors = buf->dtb_errors;
16459 desc.dtbd_oldest = buf->dtb_xamot_offset;
16460 desc.dtbd_timestamp = dtrace_gethrtime();
16462 mutex_exit(&dtrace_lock);
16464 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16467 buf->dtb_flags |= DTRACEBUF_CONSUMED;
16472 if (buf->dtb_tomax == NULL) {
16473 ASSERT(buf->dtb_xamot == NULL);
16474 mutex_exit(&dtrace_lock);
16478 cached = buf->dtb_tomax;
16479 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16481 dtrace_xcall(desc.dtbd_cpu,
16482 (dtrace_xcall_t)dtrace_buffer_switch, buf);
16484 state->dts_errors += buf->dtb_xamot_errors;
16487 * If the buffers did not actually switch, then the cross call
16488 * did not take place -- presumably because the given CPU is
16489 * not in the ready set. If this is the case, we'll return
16492 if (buf->dtb_tomax == cached) {
16493 ASSERT(buf->dtb_xamot != cached);
16494 mutex_exit(&dtrace_lock);
16498 ASSERT(cached == buf->dtb_xamot);
16501 * We have our snapshot; now copy it out.
16503 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16504 buf->dtb_xamot_offset) != 0) {
16505 mutex_exit(&dtrace_lock);
16509 desc.dtbd_size = buf->dtb_xamot_offset;
16510 desc.dtbd_drops = buf->dtb_xamot_drops;
16511 desc.dtbd_errors = buf->dtb_xamot_errors;
16512 desc.dtbd_oldest = 0;
16513 desc.dtbd_timestamp = buf->dtb_switched;
16515 mutex_exit(&dtrace_lock);
16518 * Finally, copy out the buffer description.
16520 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16526 case DTRACEIOC_CONF: {
16527 dtrace_conf_t conf;
16529 bzero(&conf, sizeof (conf));
16530 conf.dtc_difversion = DIF_VERSION;
16531 conf.dtc_difintregs = DIF_DIR_NREGS;
16532 conf.dtc_diftupregs = DIF_DTR_NREGS;
16533 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16535 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16541 case DTRACEIOC_STATUS: {
16542 dtrace_status_t stat;
16543 dtrace_dstate_t *dstate;
16548 * See the comment in dtrace_state_deadman() for the reason
16549 * for setting dts_laststatus to INT64_MAX before setting
16550 * it to the correct value.
16552 state->dts_laststatus = INT64_MAX;
16553 dtrace_membar_producer();
16554 state->dts_laststatus = dtrace_gethrtime();
16556 bzero(&stat, sizeof (stat));
16558 mutex_enter(&dtrace_lock);
16560 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16561 mutex_exit(&dtrace_lock);
16565 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16566 stat.dtst_exiting = 1;
16568 nerrs = state->dts_errors;
16569 dstate = &state->dts_vstate.dtvs_dynvars;
16571 for (i = 0; i < NCPU; i++) {
16572 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16574 stat.dtst_dyndrops += dcpu->dtdsc_drops;
16575 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16576 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16578 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16579 stat.dtst_filled++;
16581 nerrs += state->dts_buffer[i].dtb_errors;
16583 for (j = 0; j < state->dts_nspeculations; j++) {
16584 dtrace_speculation_t *spec;
16585 dtrace_buffer_t *buf;
16587 spec = &state->dts_speculations[j];
16588 buf = &spec->dtsp_buffer[i];
16589 stat.dtst_specdrops += buf->dtb_xamot_drops;
16593 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16594 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16595 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16596 stat.dtst_dblerrors = state->dts_dblerrors;
16598 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16599 stat.dtst_errors = nerrs;
16601 mutex_exit(&dtrace_lock);
16603 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16609 case DTRACEIOC_FORMAT: {
16610 dtrace_fmtdesc_t fmt;
16614 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16617 mutex_enter(&dtrace_lock);
16619 if (fmt.dtfd_format == 0 ||
16620 fmt.dtfd_format > state->dts_nformats) {
16621 mutex_exit(&dtrace_lock);
16626 * Format strings are allocated contiguously and they are
16627 * never freed; if a format index is less than the number
16628 * of formats, we can assert that the format map is non-NULL
16629 * and that the format for the specified index is non-NULL.
16631 ASSERT(state->dts_formats != NULL);
16632 str = state->dts_formats[fmt.dtfd_format - 1];
16633 ASSERT(str != NULL);
16635 len = strlen(str) + 1;
16637 if (len > fmt.dtfd_length) {
16638 fmt.dtfd_length = len;
16640 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16641 mutex_exit(&dtrace_lock);
16645 if (copyout(str, fmt.dtfd_string, len) != 0) {
16646 mutex_exit(&dtrace_lock);
16651 mutex_exit(&dtrace_lock);
16664 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16666 dtrace_state_t *state;
16673 return (DDI_SUCCESS);
16676 return (DDI_FAILURE);
16679 mutex_enter(&cpu_lock);
16680 mutex_enter(&dtrace_provider_lock);
16681 mutex_enter(&dtrace_lock);
16683 ASSERT(dtrace_opens == 0);
16685 if (dtrace_helpers > 0) {
16686 mutex_exit(&dtrace_provider_lock);
16687 mutex_exit(&dtrace_lock);
16688 mutex_exit(&cpu_lock);
16689 return (DDI_FAILURE);
16692 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16693 mutex_exit(&dtrace_provider_lock);
16694 mutex_exit(&dtrace_lock);
16695 mutex_exit(&cpu_lock);
16696 return (DDI_FAILURE);
16699 dtrace_provider = NULL;
16701 if ((state = dtrace_anon_grab()) != NULL) {
16703 * If there were ECBs on this state, the provider should
16704 * have not been allowed to detach; assert that there is
16707 ASSERT(state->dts_necbs == 0);
16708 dtrace_state_destroy(state);
16711 * If we're being detached with anonymous state, we need to
16712 * indicate to the kernel debugger that DTrace is now inactive.
16714 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16717 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16718 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16719 dtrace_cpu_init = NULL;
16720 dtrace_helpers_cleanup = NULL;
16721 dtrace_helpers_fork = NULL;
16722 dtrace_cpustart_init = NULL;
16723 dtrace_cpustart_fini = NULL;
16724 dtrace_debugger_init = NULL;
16725 dtrace_debugger_fini = NULL;
16726 dtrace_modload = NULL;
16727 dtrace_modunload = NULL;
16729 mutex_exit(&cpu_lock);
16731 if (dtrace_helptrace_enabled) {
16732 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16733 dtrace_helptrace_buffer = NULL;
16736 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16737 dtrace_probes = NULL;
16738 dtrace_nprobes = 0;
16740 dtrace_hash_destroy(dtrace_bymod);
16741 dtrace_hash_destroy(dtrace_byfunc);
16742 dtrace_hash_destroy(dtrace_byname);
16743 dtrace_bymod = NULL;
16744 dtrace_byfunc = NULL;
16745 dtrace_byname = NULL;
16747 kmem_cache_destroy(dtrace_state_cache);
16748 vmem_destroy(dtrace_minor);
16749 vmem_destroy(dtrace_arena);
16751 if (dtrace_toxrange != NULL) {
16752 kmem_free(dtrace_toxrange,
16753 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16754 dtrace_toxrange = NULL;
16755 dtrace_toxranges = 0;
16756 dtrace_toxranges_max = 0;
16759 ddi_remove_minor_node(dtrace_devi, NULL);
16760 dtrace_devi = NULL;
16762 ddi_soft_state_fini(&dtrace_softstate);
16764 ASSERT(dtrace_vtime_references == 0);
16765 ASSERT(dtrace_opens == 0);
16766 ASSERT(dtrace_retained == NULL);
16768 mutex_exit(&dtrace_lock);
16769 mutex_exit(&dtrace_provider_lock);
16772 * We don't destroy the task queue until after we have dropped our
16773 * locks (taskq_destroy() may block on running tasks). To prevent
16774 * attempting to do work after we have effectively detached but before
16775 * the task queue has been destroyed, all tasks dispatched via the
16776 * task queue must check that DTrace is still attached before
16777 * performing any operation.
16779 taskq_destroy(dtrace_taskq);
16780 dtrace_taskq = NULL;
16782 return (DDI_SUCCESS);
16789 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16794 case DDI_INFO_DEVT2DEVINFO:
16795 *result = (void *)dtrace_devi;
16796 error = DDI_SUCCESS;
16798 case DDI_INFO_DEVT2INSTANCE:
16799 *result = (void *)0;
16800 error = DDI_SUCCESS;
16803 error = DDI_FAILURE;
16810 static struct cb_ops dtrace_cb_ops = {
16811 dtrace_open, /* open */
16812 dtrace_close, /* close */
16813 nulldev, /* strategy */
16814 nulldev, /* print */
16818 dtrace_ioctl, /* ioctl */
16819 nodev, /* devmap */
16821 nodev, /* segmap */
16822 nochpoll, /* poll */
16823 ddi_prop_op, /* cb_prop_op */
16825 D_NEW | D_MP /* Driver compatibility flag */
16828 static struct dev_ops dtrace_ops = {
16829 DEVO_REV, /* devo_rev */
16831 dtrace_info, /* get_dev_info */
16832 nulldev, /* identify */
16833 nulldev, /* probe */
16834 dtrace_attach, /* attach */
16835 dtrace_detach, /* detach */
16837 &dtrace_cb_ops, /* driver operations */
16838 NULL, /* bus operations */
16839 nodev /* dev power */
16842 static struct modldrv modldrv = {
16843 &mod_driverops, /* module type (this is a pseudo driver) */
16844 "Dynamic Tracing", /* name of module */
16845 &dtrace_ops, /* driver ops */
16848 static struct modlinkage modlinkage = {
16857 return (mod_install(&modlinkage));
16861 _info(struct modinfo *modinfop)
16863 return (mod_info(&modlinkage, modinfop));
16869 return (mod_remove(&modlinkage));
16873 static d_ioctl_t dtrace_ioctl;
16874 static d_ioctl_t dtrace_ioctl_helper;
16875 static void dtrace_load(void *);
16876 static int dtrace_unload(void);
16877 #if __FreeBSD_version < 800039
16878 static void dtrace_clone(void *, struct ucred *, char *, int , struct cdev **);
16879 static struct clonedevs *dtrace_clones; /* Ptr to the array of cloned devices. */
16880 static eventhandler_tag eh_tag; /* Event handler tag. */
16882 static struct cdev *dtrace_dev;
16883 static struct cdev *helper_dev;
16886 void dtrace_invop_init(void);
16887 void dtrace_invop_uninit(void);
16889 static struct cdevsw dtrace_cdevsw = {
16890 .d_version = D_VERSION,
16891 .d_flags = D_TRACKCLOSE | D_NEEDMINOR,
16892 .d_close = dtrace_close,
16893 .d_ioctl = dtrace_ioctl,
16894 .d_open = dtrace_open,
16895 .d_name = "dtrace",
16898 static struct cdevsw helper_cdevsw = {
16899 .d_version = D_VERSION,
16900 .d_flags = D_TRACKCLOSE | D_NEEDMINOR,
16901 .d_ioctl = dtrace_ioctl_helper,
16902 .d_name = "helper",
16905 #include <dtrace_anon.c>
16906 #if __FreeBSD_version < 800039
16907 #include <dtrace_clone.c>
16909 #include <dtrace_ioctl.c>
16910 #include <dtrace_load.c>
16911 #include <dtrace_modevent.c>
16912 #include <dtrace_sysctl.c>
16913 #include <dtrace_unload.c>
16914 #include <dtrace_vtime.c>
16915 #include <dtrace_hacks.c>
16916 #include <dtrace_isa.c>
16918 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
16919 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
16920 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
16922 DEV_MODULE(dtrace, dtrace_modevent, NULL);
16923 MODULE_VERSION(dtrace, 1);
16924 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
16925 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);