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) 2013, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2012 by Delphix. All rights reserved.
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 = (8 * 1024 * 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;
189 int dtrace_memstr_max = 4096;
193 * DTrace External Variables
195 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
196 * available to DTrace consumers via the backtick (`) syntax. One of these,
197 * dtrace_zero, is made deliberately so: it is provided as a source of
198 * well-known, zero-filled memory. While this variable is not documented,
199 * it is used by some translators as an implementation detail.
201 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
204 * DTrace Internal Variables
207 static dev_info_t *dtrace_devi; /* device info */
210 static vmem_t *dtrace_arena; /* probe ID arena */
211 static vmem_t *dtrace_minor; /* minor number arena */
213 static taskq_t *dtrace_taskq; /* task queue */
214 static struct unrhdr *dtrace_arena; /* Probe ID number. */
216 static dtrace_probe_t **dtrace_probes; /* array of all probes */
217 static int dtrace_nprobes; /* number of probes */
218 static dtrace_provider_t *dtrace_provider; /* provider list */
219 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
220 static int dtrace_opens; /* number of opens */
221 static int dtrace_helpers; /* number of helpers */
222 static int dtrace_getf; /* number of unpriv getf()s */
224 static void *dtrace_softstate; /* softstate pointer */
226 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
227 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
228 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
229 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
230 static int dtrace_toxranges; /* number of toxic ranges */
231 static int dtrace_toxranges_max; /* size of toxic range array */
232 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
233 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
234 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
235 static kthread_t *dtrace_panicked; /* panicking thread */
236 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
237 static dtrace_genid_t dtrace_probegen; /* current probe generation */
238 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
239 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
240 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
242 static struct mtx dtrace_unr_mtx;
243 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
244 int dtrace_in_probe; /* non-zero if executing a probe */
245 #if defined(__i386__) || defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
246 uintptr_t dtrace_in_probe_addr; /* Address of invop when already in probe */
248 static eventhandler_tag dtrace_kld_load_tag;
249 static eventhandler_tag dtrace_kld_unload_try_tag;
254 * DTrace is protected by three (relatively coarse-grained) locks:
256 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
257 * including enabling state, probes, ECBs, consumer state, helper state,
258 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
259 * probe context is lock-free -- synchronization is handled via the
260 * dtrace_sync() cross call mechanism.
262 * (2) dtrace_provider_lock is required when manipulating provider state, or
263 * when provider state must be held constant.
265 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
266 * when meta provider state must be held constant.
268 * The lock ordering between these three locks is dtrace_meta_lock before
269 * dtrace_provider_lock before dtrace_lock. (In particular, there are
270 * several places where dtrace_provider_lock is held by the framework as it
271 * calls into the providers -- which then call back into the framework,
272 * grabbing dtrace_lock.)
274 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
275 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
276 * role as a coarse-grained lock; it is acquired before both of these locks.
277 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
278 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
279 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
280 * acquired _between_ dtrace_provider_lock and dtrace_lock.
282 static kmutex_t dtrace_lock; /* probe state lock */
283 static kmutex_t dtrace_provider_lock; /* provider state lock */
284 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
287 /* XXX FreeBSD hacks. */
288 #define cr_suid cr_svuid
289 #define cr_sgid cr_svgid
290 #define ipaddr_t in_addr_t
291 #define mod_modname pathname
292 #define vuprintf vprintf
293 #define ttoproc(_a) ((_a)->td_proc)
294 #define crgetzoneid(_a) 0
297 #define CPU_ON_INTR(_a) 0
299 #define PRIV_EFFECTIVE (1 << 0)
300 #define PRIV_DTRACE_KERNEL (1 << 1)
301 #define PRIV_DTRACE_PROC (1 << 2)
302 #define PRIV_DTRACE_USER (1 << 3)
303 #define PRIV_PROC_OWNER (1 << 4)
304 #define PRIV_PROC_ZONE (1 << 5)
307 SYSCTL_DECL(_debug_dtrace);
308 SYSCTL_DECL(_kern_dtrace);
312 #define curcpu CPU->cpu_id
317 * DTrace Provider Variables
319 * These are the variables relating to DTrace as a provider (that is, the
320 * provider of the BEGIN, END, and ERROR probes).
322 static dtrace_pattr_t dtrace_provider_attr = {
323 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
324 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
325 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
326 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
327 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
334 static dtrace_pops_t dtrace_provider_ops = {
335 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
336 (void (*)(void *, modctl_t *))dtrace_nullop,
337 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
338 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
339 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
340 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
344 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
347 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
348 static dtrace_id_t dtrace_probeid_end; /* special END probe */
349 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
352 * DTrace Helper Tracing Variables
354 uint32_t dtrace_helptrace_next = 0;
355 uint32_t dtrace_helptrace_nlocals;
356 char *dtrace_helptrace_buffer;
357 int dtrace_helptrace_bufsize = 512 * 1024;
360 int dtrace_helptrace_enabled = 1;
362 int dtrace_helptrace_enabled = 0;
366 * DTrace Error Hashing
368 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
369 * table. This is very useful for checking coverage of tests that are
370 * expected to induce DIF or DOF processing errors, and may be useful for
371 * debugging problems in the DIF code generator or in DOF generation . The
372 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
375 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
376 static const char *dtrace_errlast;
377 static kthread_t *dtrace_errthread;
378 static kmutex_t dtrace_errlock;
382 * DTrace Macros and Constants
384 * These are various macros that are useful in various spots in the
385 * implementation, along with a few random constants that have no meaning
386 * outside of the implementation. There is no real structure to this cpp
387 * mishmash -- but is there ever?
389 #define DTRACE_HASHSTR(hash, probe) \
390 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
392 #define DTRACE_HASHNEXT(hash, probe) \
393 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
395 #define DTRACE_HASHPREV(hash, probe) \
396 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
398 #define DTRACE_HASHEQ(hash, lhs, rhs) \
399 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
400 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
402 #define DTRACE_AGGHASHSIZE_SLEW 17
404 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
407 * The key for a thread-local variable consists of the lower 61 bits of the
408 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
409 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
410 * equal to a variable identifier. This is necessary (but not sufficient) to
411 * assure that global associative arrays never collide with thread-local
412 * variables. To guarantee that they cannot collide, we must also define the
413 * order for keying dynamic variables. That order is:
415 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
417 * Because the variable-key and the tls-key are in orthogonal spaces, there is
418 * no way for a global variable key signature to match a thread-local key
422 #define DTRACE_TLS_THRKEY(where) { \
424 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
425 for (; actv; actv >>= 1) \
427 ASSERT(intr < (1 << 3)); \
428 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
429 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
432 #define DTRACE_TLS_THRKEY(where) { \
433 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
435 uint_t actv = _c->cpu_intr_actv; \
436 for (; actv; actv >>= 1) \
438 ASSERT(intr < (1 << 3)); \
439 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
440 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
444 #define DT_BSWAP_8(x) ((x) & 0xff)
445 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
446 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
447 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
449 #define DT_MASK_LO 0x00000000FFFFFFFFULL
451 #define DTRACE_STORE(type, tomax, offset, what) \
452 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
455 #define DTRACE_ALIGNCHECK(addr, size, flags) \
456 if (addr & (size - 1)) { \
457 *flags |= CPU_DTRACE_BADALIGN; \
458 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
462 #define DTRACE_ALIGNCHECK(addr, size, flags)
466 * Test whether a range of memory starting at testaddr of size testsz falls
467 * within the range of memory described by addr, sz. We take care to avoid
468 * problems with overflow and underflow of the unsigned quantities, and
469 * disallow all negative sizes. Ranges of size 0 are allowed.
471 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
472 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
473 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
474 (testaddr) + (testsz) >= (testaddr))
477 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
478 * alloc_sz on the righthand side of the comparison in order to avoid overflow
479 * or underflow in the comparison with it. This is simpler than the INRANGE
480 * check above, because we know that the dtms_scratch_ptr is valid in the
481 * range. Allocations of size zero are allowed.
483 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
484 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
485 (mstate)->dtms_scratch_ptr >= (alloc_sz))
487 #define DTRACE_LOADFUNC(bits) \
490 dtrace_load##bits(uintptr_t addr) \
492 size_t size = bits / NBBY; \
494 uint##bits##_t rval; \
496 volatile uint16_t *flags = (volatile uint16_t *) \
497 &cpu_core[curcpu].cpuc_dtrace_flags; \
499 DTRACE_ALIGNCHECK(addr, size, flags); \
501 for (i = 0; i < dtrace_toxranges; i++) { \
502 if (addr >= dtrace_toxrange[i].dtt_limit) \
505 if (addr + size <= dtrace_toxrange[i].dtt_base) \
509 * This address falls within a toxic region; return 0. \
511 *flags |= CPU_DTRACE_BADADDR; \
512 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
516 *flags |= CPU_DTRACE_NOFAULT; \
518 rval = *((volatile uint##bits##_t *)addr); \
519 *flags &= ~CPU_DTRACE_NOFAULT; \
521 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
525 #define dtrace_loadptr dtrace_load64
527 #define dtrace_loadptr dtrace_load32
530 #define DTRACE_DYNHASH_FREE 0
531 #define DTRACE_DYNHASH_SINK 1
532 #define DTRACE_DYNHASH_VALID 2
534 #define DTRACE_MATCH_NEXT 0
535 #define DTRACE_MATCH_DONE 1
536 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
537 #define DTRACE_STATE_ALIGN 64
539 #define DTRACE_FLAGS2FLT(flags) \
540 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
541 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
542 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
543 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
544 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
545 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
546 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
547 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
548 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
551 #define DTRACEACT_ISSTRING(act) \
552 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
553 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
555 /* Function prototype definitions: */
556 static size_t dtrace_strlen(const char *, size_t);
557 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
558 static void dtrace_enabling_provide(dtrace_provider_t *);
559 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
560 static void dtrace_enabling_matchall(void);
561 static void dtrace_enabling_reap(void);
562 static dtrace_state_t *dtrace_anon_grab(void);
563 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
564 dtrace_state_t *, uint64_t, uint64_t);
565 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
566 static void dtrace_buffer_drop(dtrace_buffer_t *);
567 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
568 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
569 dtrace_state_t *, dtrace_mstate_t *);
570 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
572 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
573 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
574 uint16_t dtrace_load16(uintptr_t);
575 uint32_t dtrace_load32(uintptr_t);
576 uint64_t dtrace_load64(uintptr_t);
577 uint8_t dtrace_load8(uintptr_t);
578 void dtrace_dynvar_clean(dtrace_dstate_t *);
579 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
580 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
581 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
582 static int dtrace_priv_proc(dtrace_state_t *);
583 static void dtrace_getf_barrier(void);
586 * DTrace Probe Context Functions
588 * These functions are called from probe context. Because probe context is
589 * any context in which C may be called, arbitrarily locks may be held,
590 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
591 * As a result, functions called from probe context may only call other DTrace
592 * support functions -- they may not interact at all with the system at large.
593 * (Note that the ASSERT macro is made probe-context safe by redefining it in
594 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
595 * loads are to be performed from probe context, they _must_ be in terms of
596 * the safe dtrace_load*() variants.
598 * Some functions in this block are not actually called from probe context;
599 * for these functions, there will be a comment above the function reading
600 * "Note: not called from probe context."
603 dtrace_panic(const char *format, ...)
607 va_start(alist, format);
608 dtrace_vpanic(format, alist);
613 dtrace_assfail(const char *a, const char *f, int l)
615 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
618 * We just need something here that even the most clever compiler
619 * cannot optimize away.
621 return (a[(uintptr_t)f]);
625 * Atomically increment a specified error counter from probe context.
628 dtrace_error(uint32_t *counter)
631 * Most counters stored to in probe context are per-CPU counters.
632 * However, there are some error conditions that are sufficiently
633 * arcane that they don't merit per-CPU storage. If these counters
634 * are incremented concurrently on different CPUs, scalability will be
635 * adversely affected -- but we don't expect them to be white-hot in a
636 * correctly constructed enabling...
643 if ((nval = oval + 1) == 0) {
645 * If the counter would wrap, set it to 1 -- assuring
646 * that the counter is never zero when we have seen
647 * errors. (The counter must be 32-bits because we
648 * aren't guaranteed a 64-bit compare&swap operation.)
649 * To save this code both the infamy of being fingered
650 * by a priggish news story and the indignity of being
651 * the target of a neo-puritan witch trial, we're
652 * carefully avoiding any colorful description of the
653 * likelihood of this condition -- but suffice it to
654 * say that it is only slightly more likely than the
655 * overflow of predicate cache IDs, as discussed in
656 * dtrace_predicate_create().
660 } while (dtrace_cas32(counter, oval, nval) != oval);
664 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
665 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
673 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
675 if (dest < mstate->dtms_scratch_base)
678 if (dest + size < dest)
681 if (dest + size > mstate->dtms_scratch_ptr)
688 dtrace_canstore_statvar(uint64_t addr, size_t sz,
689 dtrace_statvar_t **svars, int nsvars)
693 for (i = 0; i < nsvars; i++) {
694 dtrace_statvar_t *svar = svars[i];
696 if (svar == NULL || svar->dtsv_size == 0)
699 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
707 * Check to see if the address is within a memory region to which a store may
708 * be issued. This includes the DTrace scratch areas, and any DTrace variable
709 * region. The caller of dtrace_canstore() is responsible for performing any
710 * alignment checks that are needed before stores are actually executed.
713 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
714 dtrace_vstate_t *vstate)
717 * First, check to see if the address is in scratch space...
719 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
720 mstate->dtms_scratch_size))
724 * Now check to see if it's a dynamic variable. This check will pick
725 * up both thread-local variables and any global dynamically-allocated
728 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
729 vstate->dtvs_dynvars.dtds_size)) {
730 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
731 uintptr_t base = (uintptr_t)dstate->dtds_base +
732 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
736 * Before we assume that we can store here, we need to make
737 * sure that it isn't in our metadata -- storing to our
738 * dynamic variable metadata would corrupt our state. For
739 * the range to not include any dynamic variable metadata,
742 * (1) Start above the hash table that is at the base of
743 * the dynamic variable space
745 * (2) Have a starting chunk offset that is beyond the
746 * dtrace_dynvar_t that is at the base of every chunk
748 * (3) Not span a chunk boundary
754 chunkoffs = (addr - base) % dstate->dtds_chunksize;
756 if (chunkoffs < sizeof (dtrace_dynvar_t))
759 if (chunkoffs + sz > dstate->dtds_chunksize)
766 * Finally, check the static local and global variables. These checks
767 * take the longest, so we perform them last.
769 if (dtrace_canstore_statvar(addr, sz,
770 vstate->dtvs_locals, vstate->dtvs_nlocals))
773 if (dtrace_canstore_statvar(addr, sz,
774 vstate->dtvs_globals, vstate->dtvs_nglobals))
782 * Convenience routine to check to see if the address is within a memory
783 * region in which a load may be issued given the user's privilege level;
784 * if not, it sets the appropriate error flags and loads 'addr' into the
785 * illegal value slot.
787 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
788 * appropriate memory access protection.
791 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
792 dtrace_vstate_t *vstate)
794 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
798 * If we hold the privilege to read from kernel memory, then
799 * everything is readable.
801 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
805 * You can obviously read that which you can store.
807 if (dtrace_canstore(addr, sz, mstate, vstate))
811 * We're allowed to read from our own string table.
813 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
814 mstate->dtms_difo->dtdo_strlen))
817 if (vstate->dtvs_state != NULL &&
818 dtrace_priv_proc(vstate->dtvs_state)) {
822 * When we have privileges to the current process, there are
823 * several context-related kernel structures that are safe to
824 * read, even absent the privilege to read from kernel memory.
825 * These reads are safe because these structures contain only
826 * state that (1) we're permitted to read, (2) is harmless or
827 * (3) contains pointers to additional kernel state that we're
828 * not permitted to read (and as such, do not present an
829 * opportunity for privilege escalation). Finally (and
830 * critically), because of the nature of their relation with
831 * the current thread context, the memory associated with these
832 * structures cannot change over the duration of probe context,
833 * and it is therefore impossible for this memory to be
834 * deallocated and reallocated as something else while it's
835 * being operated upon.
837 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
840 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
841 sz, curthread->t_procp, sizeof (proc_t))) {
845 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
846 curthread->t_cred, sizeof (cred_t))) {
851 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
852 &(p->p_pidp->pid_id), sizeof (pid_t))) {
856 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
857 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
863 if ((fp = mstate->dtms_getf) != NULL) {
864 uintptr_t psz = sizeof (void *);
869 * When getf() returns a file_t, the enabling is implicitly
870 * granted the (transient) right to read the returned file_t
871 * as well as the v_path and v_op->vnop_name of the underlying
872 * vnode. These accesses are allowed after a successful
873 * getf() because the members that they refer to cannot change
874 * once set -- and the barrier logic in the kernel's closef()
875 * path assures that the file_t and its referenced vode_t
876 * cannot themselves be stale (that is, it impossible for
877 * either dtms_getf itself or its f_vnode member to reference
880 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
883 if ((vp = fp->f_vnode) != NULL) {
885 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
887 if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
888 vp->v_path, strlen(vp->v_path) + 1)) {
893 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
897 if ((op = vp->v_op) != NULL &&
898 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
902 if (op != NULL && op->vnop_name != NULL &&
903 DTRACE_INRANGE(addr, sz, op->vnop_name,
904 strlen(op->vnop_name) + 1)) {
911 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
917 * Convenience routine to check to see if a given string is within a memory
918 * region in which a load may be issued given the user's privilege level;
919 * this exists so that we don't need to issue unnecessary dtrace_strlen()
920 * calls in the event that the user has all privileges.
923 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
924 dtrace_vstate_t *vstate)
929 * If we hold the privilege to read from kernel memory, then
930 * everything is readable.
932 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
935 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
936 if (dtrace_canload(addr, strsz, mstate, vstate))
943 * Convenience routine to check to see if a given variable is within a memory
944 * region in which a load may be issued given the user's privilege level.
947 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
948 dtrace_vstate_t *vstate)
951 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
954 * If we hold the privilege to read from kernel memory, then
955 * everything is readable.
957 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
960 if (type->dtdt_kind == DIF_TYPE_STRING)
961 sz = dtrace_strlen(src,
962 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
964 sz = type->dtdt_size;
966 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
970 * Compare two strings using safe loads.
973 dtrace_strncmp(char *s1, char *s2, size_t limit)
976 volatile uint16_t *flags;
978 if (s1 == s2 || limit == 0)
981 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
987 c1 = dtrace_load8((uintptr_t)s1++);
993 c2 = dtrace_load8((uintptr_t)s2++);
998 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1004 * Compute strlen(s) for a string using safe memory accesses. The additional
1005 * len parameter is used to specify a maximum length to ensure completion.
1008 dtrace_strlen(const char *s, size_t lim)
1012 for (len = 0; len != lim; len++) {
1013 if (dtrace_load8((uintptr_t)s++) == '\0')
1021 * Check if an address falls within a toxic region.
1024 dtrace_istoxic(uintptr_t kaddr, size_t size)
1026 uintptr_t taddr, tsize;
1029 for (i = 0; i < dtrace_toxranges; i++) {
1030 taddr = dtrace_toxrange[i].dtt_base;
1031 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1033 if (kaddr - taddr < tsize) {
1034 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1035 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1039 if (taddr - kaddr < size) {
1040 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1041 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1050 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1051 * memory specified by the DIF program. The dst is assumed to be safe memory
1052 * that we can store to directly because it is managed by DTrace. As with
1053 * standard bcopy, overlapping copies are handled properly.
1056 dtrace_bcopy(const void *src, void *dst, size_t len)
1060 const uint8_t *s2 = src;
1064 *s1++ = dtrace_load8((uintptr_t)s2++);
1065 } while (--len != 0);
1071 *--s1 = dtrace_load8((uintptr_t)--s2);
1072 } while (--len != 0);
1078 * Copy src to dst using safe memory accesses, up to either the specified
1079 * length, or the point that a nul byte is encountered. The src is assumed to
1080 * be unsafe memory specified by the DIF program. The dst is assumed to be
1081 * safe memory that we can store to directly because it is managed by DTrace.
1082 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1085 dtrace_strcpy(const void *src, void *dst, size_t len)
1088 uint8_t *s1 = dst, c;
1089 const uint8_t *s2 = src;
1092 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1093 } while (--len != 0 && c != '\0');
1098 * Copy src to dst, deriving the size and type from the specified (BYREF)
1099 * variable type. The src is assumed to be unsafe memory specified by the DIF
1100 * program. The dst is assumed to be DTrace variable memory that is of the
1101 * specified type; we assume that we can store to directly.
1104 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1106 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1108 if (type->dtdt_kind == DIF_TYPE_STRING) {
1109 dtrace_strcpy(src, dst, type->dtdt_size);
1111 dtrace_bcopy(src, dst, type->dtdt_size);
1116 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1117 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1118 * safe memory that we can access directly because it is managed by DTrace.
1121 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1123 volatile uint16_t *flags;
1125 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1130 if (s1 == NULL || s2 == NULL)
1133 if (s1 != s2 && len != 0) {
1134 const uint8_t *ps1 = s1;
1135 const uint8_t *ps2 = s2;
1138 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1140 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1146 * Zero the specified region using a simple byte-by-byte loop. Note that this
1147 * is for safe DTrace-managed memory only.
1150 dtrace_bzero(void *dst, size_t len)
1154 for (cp = dst; len != 0; len--)
1159 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1163 result[0] = addend1[0] + addend2[0];
1164 result[1] = addend1[1] + addend2[1] +
1165 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1172 * Shift the 128-bit value in a by b. If b is positive, shift left.
1173 * If b is negative, shift right.
1176 dtrace_shift_128(uint64_t *a, int b)
1186 a[0] = a[1] >> (b - 64);
1190 mask = 1LL << (64 - b);
1192 a[0] |= ((a[1] & mask) << (64 - b));
1197 a[1] = a[0] << (b - 64);
1201 mask = a[0] >> (64 - b);
1209 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1210 * use native multiplication on those, and then re-combine into the
1211 * resulting 128-bit value.
1213 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1220 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1222 uint64_t hi1, hi2, lo1, lo2;
1225 hi1 = factor1 >> 32;
1226 hi2 = factor2 >> 32;
1228 lo1 = factor1 & DT_MASK_LO;
1229 lo2 = factor2 & DT_MASK_LO;
1231 product[0] = lo1 * lo2;
1232 product[1] = hi1 * hi2;
1236 dtrace_shift_128(tmp, 32);
1237 dtrace_add_128(product, tmp, product);
1241 dtrace_shift_128(tmp, 32);
1242 dtrace_add_128(product, tmp, product);
1246 * This privilege check should be used by actions and subroutines to
1247 * verify that the user credentials of the process that enabled the
1248 * invoking ECB match the target credentials
1251 dtrace_priv_proc_common_user(dtrace_state_t *state)
1253 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1256 * We should always have a non-NULL state cred here, since if cred
1257 * is null (anonymous tracing), we fast-path bypass this routine.
1259 ASSERT(s_cr != NULL);
1261 if ((cr = CRED()) != NULL &&
1262 s_cr->cr_uid == cr->cr_uid &&
1263 s_cr->cr_uid == cr->cr_ruid &&
1264 s_cr->cr_uid == cr->cr_suid &&
1265 s_cr->cr_gid == cr->cr_gid &&
1266 s_cr->cr_gid == cr->cr_rgid &&
1267 s_cr->cr_gid == cr->cr_sgid)
1274 * This privilege check should be used by actions and subroutines to
1275 * verify that the zone of the process that enabled the invoking ECB
1276 * matches the target credentials
1279 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1282 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1285 * We should always have a non-NULL state cred here, since if cred
1286 * is null (anonymous tracing), we fast-path bypass this routine.
1288 ASSERT(s_cr != NULL);
1290 if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1300 * This privilege check should be used by actions and subroutines to
1301 * verify that the process has not setuid or changed credentials.
1304 dtrace_priv_proc_common_nocd(void)
1308 if ((proc = ttoproc(curthread)) != NULL &&
1309 !(proc->p_flag & SNOCD))
1316 dtrace_priv_proc_destructive(dtrace_state_t *state)
1318 int action = state->dts_cred.dcr_action;
1320 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1321 dtrace_priv_proc_common_zone(state) == 0)
1324 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1325 dtrace_priv_proc_common_user(state) == 0)
1328 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1329 dtrace_priv_proc_common_nocd() == 0)
1335 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1341 dtrace_priv_proc_control(dtrace_state_t *state)
1343 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1346 if (dtrace_priv_proc_common_zone(state) &&
1347 dtrace_priv_proc_common_user(state) &&
1348 dtrace_priv_proc_common_nocd())
1351 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1357 dtrace_priv_proc(dtrace_state_t *state)
1359 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1362 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1368 dtrace_priv_kernel(dtrace_state_t *state)
1370 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1373 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1379 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1381 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1384 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1390 * Determine if the dte_cond of the specified ECB allows for processing of
1391 * the current probe to continue. Note that this routine may allow continued
1392 * processing, but with access(es) stripped from the mstate's dtms_access
1396 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1399 dtrace_probe_t *probe = ecb->dte_probe;
1400 dtrace_provider_t *prov = probe->dtpr_provider;
1401 dtrace_pops_t *pops = &prov->dtpv_pops;
1402 int mode = DTRACE_MODE_NOPRIV_DROP;
1404 ASSERT(ecb->dte_cond);
1407 if (pops->dtps_mode != NULL) {
1408 mode = pops->dtps_mode(prov->dtpv_arg,
1409 probe->dtpr_id, probe->dtpr_arg);
1411 ASSERT((mode & DTRACE_MODE_USER) ||
1412 (mode & DTRACE_MODE_KERNEL));
1413 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1414 (mode & DTRACE_MODE_NOPRIV_DROP));
1418 * If the dte_cond bits indicate that this consumer is only allowed to
1419 * see user-mode firings of this probe, call the provider's dtps_mode()
1420 * entry point to check that the probe was fired while in a user
1421 * context. If that's not the case, use the policy specified by the
1422 * provider to determine if we drop the probe or merely restrict
1425 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1426 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1428 if (!(mode & DTRACE_MODE_USER)) {
1429 if (mode & DTRACE_MODE_NOPRIV_DROP)
1432 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1438 * This is more subtle than it looks. We have to be absolutely certain
1439 * that CRED() isn't going to change out from under us so it's only
1440 * legit to examine that structure if we're in constrained situations.
1441 * Currently, the only times we'll this check is if a non-super-user
1442 * has enabled the profile or syscall providers -- providers that
1443 * allow visibility of all processes. For the profile case, the check
1444 * above will ensure that we're examining a user context.
1446 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1448 cred_t *s_cr = state->dts_cred.dcr_cred;
1451 ASSERT(s_cr != NULL);
1453 if ((cr = CRED()) == NULL ||
1454 s_cr->cr_uid != cr->cr_uid ||
1455 s_cr->cr_uid != cr->cr_ruid ||
1456 s_cr->cr_uid != cr->cr_suid ||
1457 s_cr->cr_gid != cr->cr_gid ||
1458 s_cr->cr_gid != cr->cr_rgid ||
1459 s_cr->cr_gid != cr->cr_sgid ||
1460 (proc = ttoproc(curthread)) == NULL ||
1461 (proc->p_flag & SNOCD)) {
1462 if (mode & DTRACE_MODE_NOPRIV_DROP)
1466 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1473 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1474 * in our zone, check to see if our mode policy is to restrict rather
1475 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1476 * and DTRACE_ACCESS_ARGS
1478 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1480 cred_t *s_cr = state->dts_cred.dcr_cred;
1482 ASSERT(s_cr != NULL);
1484 if ((cr = CRED()) == NULL ||
1485 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1486 if (mode & DTRACE_MODE_NOPRIV_DROP)
1489 mstate->dtms_access &=
1490 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1499 * Note: not called from probe context. This function is called
1500 * asynchronously (and at a regular interval) from outside of probe context to
1501 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1502 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1505 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1507 dtrace_dynvar_t *dirty;
1508 dtrace_dstate_percpu_t *dcpu;
1511 for (i = 0; i < NCPU; i++) {
1512 dcpu = &dstate->dtds_percpu[i];
1514 ASSERT(dcpu->dtdsc_rinsing == NULL);
1517 * If the dirty list is NULL, there is no dirty work to do.
1519 if (dcpu->dtdsc_dirty == NULL)
1523 * If the clean list is non-NULL, then we're not going to do
1524 * any work for this CPU -- it means that there has not been
1525 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1526 * since the last time we cleaned house.
1528 if (dcpu->dtdsc_clean != NULL)
1534 * Atomically move the dirty list aside.
1537 dirty = dcpu->dtdsc_dirty;
1540 * Before we zap the dirty list, set the rinsing list.
1541 * (This allows for a potential assertion in
1542 * dtrace_dynvar(): if a free dynamic variable appears
1543 * on a hash chain, either the dirty list or the
1544 * rinsing list for some CPU must be non-NULL.)
1546 dcpu->dtdsc_rinsing = dirty;
1547 dtrace_membar_producer();
1548 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1549 dirty, NULL) != dirty);
1554 * We have no work to do; we can simply return.
1561 for (i = 0; i < NCPU; i++) {
1562 dcpu = &dstate->dtds_percpu[i];
1564 if (dcpu->dtdsc_rinsing == NULL)
1568 * We are now guaranteed that no hash chain contains a pointer
1569 * into this dirty list; we can make it clean.
1571 ASSERT(dcpu->dtdsc_clean == NULL);
1572 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1573 dcpu->dtdsc_rinsing = NULL;
1577 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1578 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1579 * This prevents a race whereby a CPU incorrectly decides that
1580 * the state should be something other than DTRACE_DSTATE_CLEAN
1581 * after dtrace_dynvar_clean() has completed.
1585 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1589 * Depending on the value of the op parameter, this function looks-up,
1590 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1591 * allocation is requested, this function will return a pointer to a
1592 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1593 * variable can be allocated. If NULL is returned, the appropriate counter
1594 * will be incremented.
1597 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1598 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1599 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1601 uint64_t hashval = DTRACE_DYNHASH_VALID;
1602 dtrace_dynhash_t *hash = dstate->dtds_hash;
1603 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1604 processorid_t me = curcpu, cpu = me;
1605 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1606 size_t bucket, ksize;
1607 size_t chunksize = dstate->dtds_chunksize;
1608 uintptr_t kdata, lock, nstate;
1614 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1615 * algorithm. For the by-value portions, we perform the algorithm in
1616 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1617 * bit, and seems to have only a minute effect on distribution. For
1618 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1619 * over each referenced byte. It's painful to do this, but it's much
1620 * better than pathological hash distribution. The efficacy of the
1621 * hashing algorithm (and a comparison with other algorithms) may be
1622 * found by running the ::dtrace_dynstat MDB dcmd.
1624 for (i = 0; i < nkeys; i++) {
1625 if (key[i].dttk_size == 0) {
1626 uint64_t val = key[i].dttk_value;
1628 hashval += (val >> 48) & 0xffff;
1629 hashval += (hashval << 10);
1630 hashval ^= (hashval >> 6);
1632 hashval += (val >> 32) & 0xffff;
1633 hashval += (hashval << 10);
1634 hashval ^= (hashval >> 6);
1636 hashval += (val >> 16) & 0xffff;
1637 hashval += (hashval << 10);
1638 hashval ^= (hashval >> 6);
1640 hashval += val & 0xffff;
1641 hashval += (hashval << 10);
1642 hashval ^= (hashval >> 6);
1645 * This is incredibly painful, but it beats the hell
1646 * out of the alternative.
1648 uint64_t j, size = key[i].dttk_size;
1649 uintptr_t base = (uintptr_t)key[i].dttk_value;
1651 if (!dtrace_canload(base, size, mstate, vstate))
1654 for (j = 0; j < size; j++) {
1655 hashval += dtrace_load8(base + j);
1656 hashval += (hashval << 10);
1657 hashval ^= (hashval >> 6);
1662 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1665 hashval += (hashval << 3);
1666 hashval ^= (hashval >> 11);
1667 hashval += (hashval << 15);
1670 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1671 * comes out to be one of our two sentinel hash values. If this
1672 * actually happens, we set the hashval to be a value known to be a
1673 * non-sentinel value.
1675 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1676 hashval = DTRACE_DYNHASH_VALID;
1679 * Yes, it's painful to do a divide here. If the cycle count becomes
1680 * important here, tricks can be pulled to reduce it. (However, it's
1681 * critical that hash collisions be kept to an absolute minimum;
1682 * they're much more painful than a divide.) It's better to have a
1683 * solution that generates few collisions and still keeps things
1684 * relatively simple.
1686 bucket = hashval % dstate->dtds_hashsize;
1688 if (op == DTRACE_DYNVAR_DEALLOC) {
1689 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1692 while ((lock = *lockp) & 1)
1695 if (dtrace_casptr((volatile void *)lockp,
1696 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1700 dtrace_membar_producer();
1705 lock = hash[bucket].dtdh_lock;
1707 dtrace_membar_consumer();
1709 start = hash[bucket].dtdh_chain;
1710 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1711 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1712 op != DTRACE_DYNVAR_DEALLOC));
1714 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1715 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1716 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1718 if (dvar->dtdv_hashval != hashval) {
1719 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1721 * We've reached the sink, and therefore the
1722 * end of the hash chain; we can kick out of
1723 * the loop knowing that we have seen a valid
1724 * snapshot of state.
1726 ASSERT(dvar->dtdv_next == NULL);
1727 ASSERT(dvar == &dtrace_dynhash_sink);
1731 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1733 * We've gone off the rails: somewhere along
1734 * the line, one of the members of this hash
1735 * chain was deleted. Note that we could also
1736 * detect this by simply letting this loop run
1737 * to completion, as we would eventually hit
1738 * the end of the dirty list. However, we
1739 * want to avoid running the length of the
1740 * dirty list unnecessarily (it might be quite
1741 * long), so we catch this as early as
1742 * possible by detecting the hash marker. In
1743 * this case, we simply set dvar to NULL and
1744 * break; the conditional after the loop will
1745 * send us back to top.
1754 if (dtuple->dtt_nkeys != nkeys)
1757 for (i = 0; i < nkeys; i++, dkey++) {
1758 if (dkey->dttk_size != key[i].dttk_size)
1759 goto next; /* size or type mismatch */
1761 if (dkey->dttk_size != 0) {
1763 (void *)(uintptr_t)key[i].dttk_value,
1764 (void *)(uintptr_t)dkey->dttk_value,
1768 if (dkey->dttk_value != key[i].dttk_value)
1773 if (op != DTRACE_DYNVAR_DEALLOC)
1776 ASSERT(dvar->dtdv_next == NULL ||
1777 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1780 ASSERT(hash[bucket].dtdh_chain != dvar);
1781 ASSERT(start != dvar);
1782 ASSERT(prev->dtdv_next == dvar);
1783 prev->dtdv_next = dvar->dtdv_next;
1785 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1786 start, dvar->dtdv_next) != start) {
1788 * We have failed to atomically swing the
1789 * hash table head pointer, presumably because
1790 * of a conflicting allocation on another CPU.
1791 * We need to reread the hash chain and try
1798 dtrace_membar_producer();
1801 * Now set the hash value to indicate that it's free.
1803 ASSERT(hash[bucket].dtdh_chain != dvar);
1804 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1806 dtrace_membar_producer();
1809 * Set the next pointer to point at the dirty list, and
1810 * atomically swing the dirty pointer to the newly freed dvar.
1813 next = dcpu->dtdsc_dirty;
1814 dvar->dtdv_next = next;
1815 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1818 * Finally, unlock this hash bucket.
1820 ASSERT(hash[bucket].dtdh_lock == lock);
1822 hash[bucket].dtdh_lock++;
1832 * If dvar is NULL, it is because we went off the rails:
1833 * one of the elements that we traversed in the hash chain
1834 * was deleted while we were traversing it. In this case,
1835 * we assert that we aren't doing a dealloc (deallocs lock
1836 * the hash bucket to prevent themselves from racing with
1837 * one another), and retry the hash chain traversal.
1839 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1843 if (op != DTRACE_DYNVAR_ALLOC) {
1845 * If we are not to allocate a new variable, we want to
1846 * return NULL now. Before we return, check that the value
1847 * of the lock word hasn't changed. If it has, we may have
1848 * seen an inconsistent snapshot.
1850 if (op == DTRACE_DYNVAR_NOALLOC) {
1851 if (hash[bucket].dtdh_lock != lock)
1854 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1855 ASSERT(hash[bucket].dtdh_lock == lock);
1857 hash[bucket].dtdh_lock++;
1864 * We need to allocate a new dynamic variable. The size we need is the
1865 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1866 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1867 * the size of any referred-to data (dsize). We then round the final
1868 * size up to the chunksize for allocation.
1870 for (ksize = 0, i = 0; i < nkeys; i++)
1871 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1874 * This should be pretty much impossible, but could happen if, say,
1875 * strange DIF specified the tuple. Ideally, this should be an
1876 * assertion and not an error condition -- but that requires that the
1877 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1878 * bullet-proof. (That is, it must not be able to be fooled by
1879 * malicious DIF.) Given the lack of backwards branches in DIF,
1880 * solving this would presumably not amount to solving the Halting
1881 * Problem -- but it still seems awfully hard.
1883 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1884 ksize + dsize > chunksize) {
1885 dcpu->dtdsc_drops++;
1889 nstate = DTRACE_DSTATE_EMPTY;
1893 free = dcpu->dtdsc_free;
1896 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1899 if (clean == NULL) {
1901 * We're out of dynamic variable space on
1902 * this CPU. Unless we have tried all CPUs,
1903 * we'll try to allocate from a different
1906 switch (dstate->dtds_state) {
1907 case DTRACE_DSTATE_CLEAN: {
1908 void *sp = &dstate->dtds_state;
1913 if (dcpu->dtdsc_dirty != NULL &&
1914 nstate == DTRACE_DSTATE_EMPTY)
1915 nstate = DTRACE_DSTATE_DIRTY;
1917 if (dcpu->dtdsc_rinsing != NULL)
1918 nstate = DTRACE_DSTATE_RINSING;
1920 dcpu = &dstate->dtds_percpu[cpu];
1925 (void) dtrace_cas32(sp,
1926 DTRACE_DSTATE_CLEAN, nstate);
1929 * To increment the correct bean
1930 * counter, take another lap.
1935 case DTRACE_DSTATE_DIRTY:
1936 dcpu->dtdsc_dirty_drops++;
1939 case DTRACE_DSTATE_RINSING:
1940 dcpu->dtdsc_rinsing_drops++;
1943 case DTRACE_DSTATE_EMPTY:
1944 dcpu->dtdsc_drops++;
1948 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1953 * The clean list appears to be non-empty. We want to
1954 * move the clean list to the free list; we start by
1955 * moving the clean pointer aside.
1957 if (dtrace_casptr(&dcpu->dtdsc_clean,
1958 clean, NULL) != clean) {
1960 * We are in one of two situations:
1962 * (a) The clean list was switched to the
1963 * free list by another CPU.
1965 * (b) The clean list was added to by the
1968 * In either of these situations, we can
1969 * just reattempt the free list allocation.
1974 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1977 * Now we'll move the clean list to the free list.
1978 * It's impossible for this to fail: the only way
1979 * the free list can be updated is through this
1980 * code path, and only one CPU can own the clean list.
1981 * Thus, it would only be possible for this to fail if
1982 * this code were racing with dtrace_dynvar_clean().
1983 * (That is, if dtrace_dynvar_clean() updated the clean
1984 * list, and we ended up racing to update the free
1985 * list.) This race is prevented by the dtrace_sync()
1986 * in dtrace_dynvar_clean() -- which flushes the
1987 * owners of the clean lists out before resetting
1990 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1991 ASSERT(rval == NULL);
1996 new_free = dvar->dtdv_next;
1997 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2000 * We have now allocated a new chunk. We copy the tuple keys into the
2001 * tuple array and copy any referenced key data into the data space
2002 * following the tuple array. As we do this, we relocate dttk_value
2003 * in the final tuple to point to the key data address in the chunk.
2005 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2006 dvar->dtdv_data = (void *)(kdata + ksize);
2007 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2009 for (i = 0; i < nkeys; i++) {
2010 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2011 size_t kesize = key[i].dttk_size;
2015 (const void *)(uintptr_t)key[i].dttk_value,
2016 (void *)kdata, kesize);
2017 dkey->dttk_value = kdata;
2018 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2020 dkey->dttk_value = key[i].dttk_value;
2023 dkey->dttk_size = kesize;
2026 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2027 dvar->dtdv_hashval = hashval;
2028 dvar->dtdv_next = start;
2030 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2034 * The cas has failed. Either another CPU is adding an element to
2035 * this hash chain, or another CPU is deleting an element from this
2036 * hash chain. The simplest way to deal with both of these cases
2037 * (though not necessarily the most efficient) is to free our
2038 * allocated block and tail-call ourselves. Note that the free is
2039 * to the dirty list and _not_ to the free list. This is to prevent
2040 * races with allocators, above.
2042 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2044 dtrace_membar_producer();
2047 free = dcpu->dtdsc_dirty;
2048 dvar->dtdv_next = free;
2049 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2051 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2056 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2058 if ((int64_t)nval < (int64_t)*oval)
2064 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2066 if ((int64_t)nval > (int64_t)*oval)
2071 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2073 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2074 int64_t val = (int64_t)nval;
2077 for (i = 0; i < zero; i++) {
2078 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2084 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2085 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2086 quanta[i - 1] += incr;
2091 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2099 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2101 uint64_t arg = *lquanta++;
2102 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2103 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2104 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2105 int32_t val = (int32_t)nval, level;
2108 ASSERT(levels != 0);
2112 * This is an underflow.
2118 level = (val - base) / step;
2120 if (level < levels) {
2121 lquanta[level + 1] += incr;
2126 * This is an overflow.
2128 lquanta[levels + 1] += incr;
2132 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2133 uint16_t high, uint16_t nsteps, int64_t value)
2135 int64_t this = 1, last, next;
2136 int base = 1, order;
2138 ASSERT(factor <= nsteps);
2139 ASSERT(nsteps % factor == 0);
2141 for (order = 0; order < low; order++)
2145 * If our value is less than our factor taken to the power of the
2146 * low order of magnitude, it goes into the zeroth bucket.
2148 if (value < (last = this))
2151 for (this *= factor; order <= high; order++) {
2152 int nbuckets = this > nsteps ? nsteps : this;
2154 if ((next = this * factor) < this) {
2156 * We should not generally get log/linear quantizations
2157 * with a high magnitude that allows 64-bits to
2158 * overflow, but we nonetheless protect against this
2159 * by explicitly checking for overflow, and clamping
2160 * our value accordingly.
2167 * If our value lies within this order of magnitude,
2168 * determine its position by taking the offset within
2169 * the order of magnitude, dividing by the bucket
2170 * width, and adding to our (accumulated) base.
2172 return (base + (value - last) / (this / nbuckets));
2175 base += nbuckets - (nbuckets / factor);
2181 * Our value is greater than or equal to our factor taken to the
2182 * power of one plus the high magnitude -- return the top bucket.
2188 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2190 uint64_t arg = *llquanta++;
2191 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2192 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2193 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2194 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2196 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2197 low, high, nsteps, nval)] += incr;
2202 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2210 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2212 int64_t snval = (int64_t)nval;
2219 * What we want to say here is:
2221 * data[2] += nval * nval;
2223 * But given that nval is 64-bit, we could easily overflow, so
2224 * we do this as 128-bit arithmetic.
2229 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2230 dtrace_add_128(data + 2, tmp, data + 2);
2235 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2242 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2248 * Aggregate given the tuple in the principal data buffer, and the aggregating
2249 * action denoted by the specified dtrace_aggregation_t. The aggregation
2250 * buffer is specified as the buf parameter. This routine does not return
2251 * failure; if there is no space in the aggregation buffer, the data will be
2252 * dropped, and a corresponding counter incremented.
2255 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2256 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2258 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2259 uint32_t i, ndx, size, fsize;
2260 uint32_t align = sizeof (uint64_t) - 1;
2261 dtrace_aggbuffer_t *agb;
2262 dtrace_aggkey_t *key;
2263 uint32_t hashval = 0, limit, isstr;
2264 caddr_t tomax, data, kdata;
2265 dtrace_actkind_t action;
2266 dtrace_action_t *act;
2272 if (!agg->dtag_hasarg) {
2274 * Currently, only quantize() and lquantize() take additional
2275 * arguments, and they have the same semantics: an increment
2276 * value that defaults to 1 when not present. If additional
2277 * aggregating actions take arguments, the setting of the
2278 * default argument value will presumably have to become more
2284 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2285 size = rec->dtrd_offset - agg->dtag_base;
2286 fsize = size + rec->dtrd_size;
2288 ASSERT(dbuf->dtb_tomax != NULL);
2289 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2291 if ((tomax = buf->dtb_tomax) == NULL) {
2292 dtrace_buffer_drop(buf);
2297 * The metastructure is always at the bottom of the buffer.
2299 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2300 sizeof (dtrace_aggbuffer_t));
2302 if (buf->dtb_offset == 0) {
2304 * We just kludge up approximately 1/8th of the size to be
2305 * buckets. If this guess ends up being routinely
2306 * off-the-mark, we may need to dynamically readjust this
2307 * based on past performance.
2309 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2311 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2312 (uintptr_t)tomax || hashsize == 0) {
2314 * We've been given a ludicrously small buffer;
2315 * increment our drop count and leave.
2317 dtrace_buffer_drop(buf);
2322 * And now, a pathetic attempt to try to get a an odd (or
2323 * perchance, a prime) hash size for better hash distribution.
2325 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2326 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2328 agb->dtagb_hashsize = hashsize;
2329 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2330 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2331 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2333 for (i = 0; i < agb->dtagb_hashsize; i++)
2334 agb->dtagb_hash[i] = NULL;
2337 ASSERT(agg->dtag_first != NULL);
2338 ASSERT(agg->dtag_first->dta_intuple);
2341 * Calculate the hash value based on the key. Note that we _don't_
2342 * include the aggid in the hashing (but we will store it as part of
2343 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2344 * algorithm: a simple, quick algorithm that has no known funnels, and
2345 * gets good distribution in practice. The efficacy of the hashing
2346 * algorithm (and a comparison with other algorithms) may be found by
2347 * running the ::dtrace_aggstat MDB dcmd.
2349 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2350 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2351 limit = i + act->dta_rec.dtrd_size;
2352 ASSERT(limit <= size);
2353 isstr = DTRACEACT_ISSTRING(act);
2355 for (; i < limit; i++) {
2357 hashval += (hashval << 10);
2358 hashval ^= (hashval >> 6);
2360 if (isstr && data[i] == '\0')
2365 hashval += (hashval << 3);
2366 hashval ^= (hashval >> 11);
2367 hashval += (hashval << 15);
2370 * Yes, the divide here is expensive -- but it's generally the least
2371 * of the performance issues given the amount of data that we iterate
2372 * over to compute hash values, compare data, etc.
2374 ndx = hashval % agb->dtagb_hashsize;
2376 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2377 ASSERT((caddr_t)key >= tomax);
2378 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2380 if (hashval != key->dtak_hashval || key->dtak_size != size)
2383 kdata = key->dtak_data;
2384 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2386 for (act = agg->dtag_first; act->dta_intuple;
2387 act = act->dta_next) {
2388 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2389 limit = i + act->dta_rec.dtrd_size;
2390 ASSERT(limit <= size);
2391 isstr = DTRACEACT_ISSTRING(act);
2393 for (; i < limit; i++) {
2394 if (kdata[i] != data[i])
2397 if (isstr && data[i] == '\0')
2402 if (action != key->dtak_action) {
2404 * We are aggregating on the same value in the same
2405 * aggregation with two different aggregating actions.
2406 * (This should have been picked up in the compiler,
2407 * so we may be dealing with errant or devious DIF.)
2408 * This is an error condition; we indicate as much,
2411 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2416 * This is a hit: we need to apply the aggregator to
2417 * the value at this key.
2419 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2426 * We didn't find it. We need to allocate some zero-filled space,
2427 * link it into the hash table appropriately, and apply the aggregator
2428 * to the (zero-filled) value.
2430 offs = buf->dtb_offset;
2431 while (offs & (align - 1))
2432 offs += sizeof (uint32_t);
2435 * If we don't have enough room to both allocate a new key _and_
2436 * its associated data, increment the drop count and return.
2438 if ((uintptr_t)tomax + offs + fsize >
2439 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2440 dtrace_buffer_drop(buf);
2445 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2446 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2447 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2449 key->dtak_data = kdata = tomax + offs;
2450 buf->dtb_offset = offs + fsize;
2453 * Now copy the data across.
2455 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2457 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2461 * Because strings are not zeroed out by default, we need to iterate
2462 * looking for actions that store strings, and we need to explicitly
2463 * pad these strings out with zeroes.
2465 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2468 if (!DTRACEACT_ISSTRING(act))
2471 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2472 limit = i + act->dta_rec.dtrd_size;
2473 ASSERT(limit <= size);
2475 for (nul = 0; i < limit; i++) {
2481 if (data[i] != '\0')
2488 for (i = size; i < fsize; i++)
2491 key->dtak_hashval = hashval;
2492 key->dtak_size = size;
2493 key->dtak_action = action;
2494 key->dtak_next = agb->dtagb_hash[ndx];
2495 agb->dtagb_hash[ndx] = key;
2498 * Finally, apply the aggregator.
2500 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2501 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2505 * Given consumer state, this routine finds a speculation in the INACTIVE
2506 * state and transitions it into the ACTIVE state. If there is no speculation
2507 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2508 * incremented -- it is up to the caller to take appropriate action.
2511 dtrace_speculation(dtrace_state_t *state)
2514 dtrace_speculation_state_t current;
2515 uint32_t *stat = &state->dts_speculations_unavail, count;
2517 while (i < state->dts_nspeculations) {
2518 dtrace_speculation_t *spec = &state->dts_speculations[i];
2520 current = spec->dtsp_state;
2522 if (current != DTRACESPEC_INACTIVE) {
2523 if (current == DTRACESPEC_COMMITTINGMANY ||
2524 current == DTRACESPEC_COMMITTING ||
2525 current == DTRACESPEC_DISCARDING)
2526 stat = &state->dts_speculations_busy;
2531 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2532 current, DTRACESPEC_ACTIVE) == current)
2537 * We couldn't find a speculation. If we found as much as a single
2538 * busy speculation buffer, we'll attribute this failure as "busy"
2539 * instead of "unavail".
2543 } while (dtrace_cas32(stat, count, count + 1) != count);
2549 * This routine commits an active speculation. If the specified speculation
2550 * is not in a valid state to perform a commit(), this routine will silently do
2551 * nothing. The state of the specified speculation is transitioned according
2552 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2555 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2556 dtrace_specid_t which)
2558 dtrace_speculation_t *spec;
2559 dtrace_buffer_t *src, *dest;
2560 uintptr_t daddr, saddr, dlimit, slimit;
2561 dtrace_speculation_state_t current, new = 0;
2568 if (which > state->dts_nspeculations) {
2569 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2573 spec = &state->dts_speculations[which - 1];
2574 src = &spec->dtsp_buffer[cpu];
2575 dest = &state->dts_buffer[cpu];
2578 current = spec->dtsp_state;
2580 if (current == DTRACESPEC_COMMITTINGMANY)
2584 case DTRACESPEC_INACTIVE:
2585 case DTRACESPEC_DISCARDING:
2588 case DTRACESPEC_COMMITTING:
2590 * This is only possible if we are (a) commit()'ing
2591 * without having done a prior speculate() on this CPU
2592 * and (b) racing with another commit() on a different
2593 * CPU. There's nothing to do -- we just assert that
2596 ASSERT(src->dtb_offset == 0);
2599 case DTRACESPEC_ACTIVE:
2600 new = DTRACESPEC_COMMITTING;
2603 case DTRACESPEC_ACTIVEONE:
2605 * This speculation is active on one CPU. If our
2606 * buffer offset is non-zero, we know that the one CPU
2607 * must be us. Otherwise, we are committing on a
2608 * different CPU from the speculate(), and we must
2609 * rely on being asynchronously cleaned.
2611 if (src->dtb_offset != 0) {
2612 new = DTRACESPEC_COMMITTING;
2617 case DTRACESPEC_ACTIVEMANY:
2618 new = DTRACESPEC_COMMITTINGMANY;
2624 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2625 current, new) != current);
2628 * We have set the state to indicate that we are committing this
2629 * speculation. Now reserve the necessary space in the destination
2632 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2633 sizeof (uint64_t), state, NULL)) < 0) {
2634 dtrace_buffer_drop(dest);
2639 * We have sufficient space to copy the speculative buffer into the
2640 * primary buffer. First, modify the speculative buffer, filling
2641 * in the timestamp of all entries with the current time. The data
2642 * must have the commit() time rather than the time it was traced,
2643 * so that all entries in the primary buffer are in timestamp order.
2645 timestamp = dtrace_gethrtime();
2646 saddr = (uintptr_t)src->dtb_tomax;
2647 slimit = saddr + src->dtb_offset;
2648 while (saddr < slimit) {
2650 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2652 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2653 saddr += sizeof (dtrace_epid_t);
2656 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2657 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2659 ASSERT3U(saddr + size, <=, slimit);
2660 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2661 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2663 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2669 * Copy the buffer across. (Note that this is a
2670 * highly subobtimal bcopy(); in the unlikely event that this becomes
2671 * a serious performance issue, a high-performance DTrace-specific
2672 * bcopy() should obviously be invented.)
2674 daddr = (uintptr_t)dest->dtb_tomax + offs;
2675 dlimit = daddr + src->dtb_offset;
2676 saddr = (uintptr_t)src->dtb_tomax;
2679 * First, the aligned portion.
2681 while (dlimit - daddr >= sizeof (uint64_t)) {
2682 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2684 daddr += sizeof (uint64_t);
2685 saddr += sizeof (uint64_t);
2689 * Now any left-over bit...
2691 while (dlimit - daddr)
2692 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2695 * Finally, commit the reserved space in the destination buffer.
2697 dest->dtb_offset = offs + src->dtb_offset;
2701 * If we're lucky enough to be the only active CPU on this speculation
2702 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2704 if (current == DTRACESPEC_ACTIVE ||
2705 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2706 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2707 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2709 ASSERT(rval == DTRACESPEC_COMMITTING);
2712 src->dtb_offset = 0;
2713 src->dtb_xamot_drops += src->dtb_drops;
2718 * This routine discards an active speculation. If the specified speculation
2719 * is not in a valid state to perform a discard(), this routine will silently
2720 * do nothing. The state of the specified speculation is transitioned
2721 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2724 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2725 dtrace_specid_t which)
2727 dtrace_speculation_t *spec;
2728 dtrace_speculation_state_t current, new = 0;
2729 dtrace_buffer_t *buf;
2734 if (which > state->dts_nspeculations) {
2735 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2739 spec = &state->dts_speculations[which - 1];
2740 buf = &spec->dtsp_buffer[cpu];
2743 current = spec->dtsp_state;
2746 case DTRACESPEC_INACTIVE:
2747 case DTRACESPEC_COMMITTINGMANY:
2748 case DTRACESPEC_COMMITTING:
2749 case DTRACESPEC_DISCARDING:
2752 case DTRACESPEC_ACTIVE:
2753 case DTRACESPEC_ACTIVEMANY:
2754 new = DTRACESPEC_DISCARDING;
2757 case DTRACESPEC_ACTIVEONE:
2758 if (buf->dtb_offset != 0) {
2759 new = DTRACESPEC_INACTIVE;
2761 new = DTRACESPEC_DISCARDING;
2768 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2769 current, new) != current);
2771 buf->dtb_offset = 0;
2776 * Note: not called from probe context. This function is called
2777 * asynchronously from cross call context to clean any speculations that are
2778 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2779 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2783 dtrace_speculation_clean_here(dtrace_state_t *state)
2785 dtrace_icookie_t cookie;
2786 processorid_t cpu = curcpu;
2787 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2790 cookie = dtrace_interrupt_disable();
2792 if (dest->dtb_tomax == NULL) {
2793 dtrace_interrupt_enable(cookie);
2797 for (i = 0; i < state->dts_nspeculations; i++) {
2798 dtrace_speculation_t *spec = &state->dts_speculations[i];
2799 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2801 if (src->dtb_tomax == NULL)
2804 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2805 src->dtb_offset = 0;
2809 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2812 if (src->dtb_offset == 0)
2815 dtrace_speculation_commit(state, cpu, i + 1);
2818 dtrace_interrupt_enable(cookie);
2822 * Note: not called from probe context. This function is called
2823 * asynchronously (and at a regular interval) to clean any speculations that
2824 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2825 * is work to be done, it cross calls all CPUs to perform that work;
2826 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2827 * INACTIVE state until they have been cleaned by all CPUs.
2830 dtrace_speculation_clean(dtrace_state_t *state)
2835 for (i = 0; i < state->dts_nspeculations; i++) {
2836 dtrace_speculation_t *spec = &state->dts_speculations[i];
2838 ASSERT(!spec->dtsp_cleaning);
2840 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2841 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2845 spec->dtsp_cleaning = 1;
2851 dtrace_xcall(DTRACE_CPUALL,
2852 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2855 * We now know that all CPUs have committed or discarded their
2856 * speculation buffers, as appropriate. We can now set the state
2859 for (i = 0; i < state->dts_nspeculations; i++) {
2860 dtrace_speculation_t *spec = &state->dts_speculations[i];
2861 dtrace_speculation_state_t current, new;
2863 if (!spec->dtsp_cleaning)
2866 current = spec->dtsp_state;
2867 ASSERT(current == DTRACESPEC_DISCARDING ||
2868 current == DTRACESPEC_COMMITTINGMANY);
2870 new = DTRACESPEC_INACTIVE;
2872 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2873 ASSERT(rv == current);
2874 spec->dtsp_cleaning = 0;
2879 * Called as part of a speculate() to get the speculative buffer associated
2880 * with a given speculation. Returns NULL if the specified speculation is not
2881 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2882 * the active CPU is not the specified CPU -- the speculation will be
2883 * atomically transitioned into the ACTIVEMANY state.
2885 static dtrace_buffer_t *
2886 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2887 dtrace_specid_t which)
2889 dtrace_speculation_t *spec;
2890 dtrace_speculation_state_t current, new = 0;
2891 dtrace_buffer_t *buf;
2896 if (which > state->dts_nspeculations) {
2897 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2901 spec = &state->dts_speculations[which - 1];
2902 buf = &spec->dtsp_buffer[cpuid];
2905 current = spec->dtsp_state;
2908 case DTRACESPEC_INACTIVE:
2909 case DTRACESPEC_COMMITTINGMANY:
2910 case DTRACESPEC_DISCARDING:
2913 case DTRACESPEC_COMMITTING:
2914 ASSERT(buf->dtb_offset == 0);
2917 case DTRACESPEC_ACTIVEONE:
2919 * This speculation is currently active on one CPU.
2920 * Check the offset in the buffer; if it's non-zero,
2921 * that CPU must be us (and we leave the state alone).
2922 * If it's zero, assume that we're starting on a new
2923 * CPU -- and change the state to indicate that the
2924 * speculation is active on more than one CPU.
2926 if (buf->dtb_offset != 0)
2929 new = DTRACESPEC_ACTIVEMANY;
2932 case DTRACESPEC_ACTIVEMANY:
2935 case DTRACESPEC_ACTIVE:
2936 new = DTRACESPEC_ACTIVEONE;
2942 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2943 current, new) != current);
2945 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2950 * Return a string. In the event that the user lacks the privilege to access
2951 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2952 * don't fail access checking.
2954 * dtrace_dif_variable() uses this routine as a helper for various
2955 * builtin values such as 'execname' and 'probefunc.'
2958 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2959 dtrace_mstate_t *mstate)
2961 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2966 * The easy case: this probe is allowed to read all of memory, so
2967 * we can just return this as a vanilla pointer.
2969 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2973 * This is the tougher case: we copy the string in question from
2974 * kernel memory into scratch memory and return it that way: this
2975 * ensures that we won't trip up when access checking tests the
2976 * BYREF return value.
2978 strsz = dtrace_strlen((char *)addr, size) + 1;
2980 if (mstate->dtms_scratch_ptr + strsz >
2981 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2982 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2986 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2988 ret = mstate->dtms_scratch_ptr;
2989 mstate->dtms_scratch_ptr += strsz;
2994 * Return a string from a memoy address which is known to have one or
2995 * more concatenated, individually zero terminated, sub-strings.
2996 * In the event that the user lacks the privilege to access
2997 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2998 * don't fail access checking.
3000 * dtrace_dif_variable() uses this routine as a helper for various
3001 * builtin values such as 'execargs'.
3004 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3005 dtrace_mstate_t *mstate)
3011 if (mstate->dtms_scratch_ptr + strsz >
3012 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3013 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3017 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3020 /* Replace sub-string termination characters with a space. */
3021 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3026 ret = mstate->dtms_scratch_ptr;
3027 mstate->dtms_scratch_ptr += strsz;
3032 * This function implements the DIF emulator's variable lookups. The emulator
3033 * passes a reserved variable identifier and optional built-in array index.
3036 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3040 * If we're accessing one of the uncached arguments, we'll turn this
3041 * into a reference in the args array.
3043 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3044 ndx = v - DIF_VAR_ARG0;
3050 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3051 if (ndx >= sizeof (mstate->dtms_arg) /
3052 sizeof (mstate->dtms_arg[0])) {
3053 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3054 dtrace_provider_t *pv;
3057 pv = mstate->dtms_probe->dtpr_provider;
3058 if (pv->dtpv_pops.dtps_getargval != NULL)
3059 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3060 mstate->dtms_probe->dtpr_id,
3061 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3063 val = dtrace_getarg(ndx, aframes);
3066 * This is regrettably required to keep the compiler
3067 * from tail-optimizing the call to dtrace_getarg().
3068 * The condition always evaluates to true, but the
3069 * compiler has no way of figuring that out a priori.
3070 * (None of this would be necessary if the compiler
3071 * could be relied upon to _always_ tail-optimize
3072 * the call to dtrace_getarg() -- but it can't.)
3074 if (mstate->dtms_probe != NULL)
3080 return (mstate->dtms_arg[ndx]);
3083 case DIF_VAR_UREGS: {
3086 if (!dtrace_priv_proc(state))
3089 if ((lwp = curthread->t_lwp) == NULL) {
3090 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3091 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3095 return (dtrace_getreg(lwp->lwp_regs, ndx));
3099 case DIF_VAR_UREGS: {
3100 struct trapframe *tframe;
3102 if (!dtrace_priv_proc(state))
3105 if ((tframe = curthread->td_frame) == NULL) {
3106 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3107 cpu_core[curcpu].cpuc_dtrace_illval = 0;
3111 return (dtrace_getreg(tframe, ndx));
3115 case DIF_VAR_CURTHREAD:
3116 if (!dtrace_priv_proc(state))
3118 return ((uint64_t)(uintptr_t)curthread);
3120 case DIF_VAR_TIMESTAMP:
3121 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3122 mstate->dtms_timestamp = dtrace_gethrtime();
3123 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3125 return (mstate->dtms_timestamp);
3127 case DIF_VAR_VTIMESTAMP:
3128 ASSERT(dtrace_vtime_references != 0);
3129 return (curthread->t_dtrace_vtime);
3131 case DIF_VAR_WALLTIMESTAMP:
3132 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3133 mstate->dtms_walltimestamp = dtrace_gethrestime();
3134 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3136 return (mstate->dtms_walltimestamp);
3140 if (!dtrace_priv_kernel(state))
3142 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3143 mstate->dtms_ipl = dtrace_getipl();
3144 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3146 return (mstate->dtms_ipl);
3150 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3151 return (mstate->dtms_epid);
3154 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3155 return (mstate->dtms_probe->dtpr_id);
3157 case DIF_VAR_STACKDEPTH:
3158 if (!dtrace_priv_kernel(state))
3160 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3161 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3163 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3164 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3166 return (mstate->dtms_stackdepth);
3168 case DIF_VAR_USTACKDEPTH:
3169 if (!dtrace_priv_proc(state))
3171 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3173 * See comment in DIF_VAR_PID.
3175 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3177 mstate->dtms_ustackdepth = 0;
3179 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3180 mstate->dtms_ustackdepth =
3181 dtrace_getustackdepth();
3182 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3184 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3186 return (mstate->dtms_ustackdepth);
3188 case DIF_VAR_CALLER:
3189 if (!dtrace_priv_kernel(state))
3191 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3192 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3194 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3196 * If this is an unanchored probe, we are
3197 * required to go through the slow path:
3198 * dtrace_caller() only guarantees correct
3199 * results for anchored probes.
3201 pc_t caller[2] = {0, 0};
3203 dtrace_getpcstack(caller, 2, aframes,
3204 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3205 mstate->dtms_caller = caller[1];
3206 } else if ((mstate->dtms_caller =
3207 dtrace_caller(aframes)) == -1) {
3209 * We have failed to do this the quick way;
3210 * we must resort to the slower approach of
3211 * calling dtrace_getpcstack().
3215 dtrace_getpcstack(&caller, 1, aframes, NULL);
3216 mstate->dtms_caller = caller;
3219 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3221 return (mstate->dtms_caller);
3223 case DIF_VAR_UCALLER:
3224 if (!dtrace_priv_proc(state))
3227 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3231 * dtrace_getupcstack() fills in the first uint64_t
3232 * with the current PID. The second uint64_t will
3233 * be the program counter at user-level. The third
3234 * uint64_t will contain the caller, which is what
3238 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3239 dtrace_getupcstack(ustack, 3);
3240 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3241 mstate->dtms_ucaller = ustack[2];
3242 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3245 return (mstate->dtms_ucaller);
3247 case DIF_VAR_PROBEPROV:
3248 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3249 return (dtrace_dif_varstr(
3250 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3253 case DIF_VAR_PROBEMOD:
3254 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3255 return (dtrace_dif_varstr(
3256 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3259 case DIF_VAR_PROBEFUNC:
3260 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3261 return (dtrace_dif_varstr(
3262 (uintptr_t)mstate->dtms_probe->dtpr_func,
3265 case DIF_VAR_PROBENAME:
3266 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3267 return (dtrace_dif_varstr(
3268 (uintptr_t)mstate->dtms_probe->dtpr_name,
3272 if (!dtrace_priv_proc(state))
3277 * Note that we are assuming that an unanchored probe is
3278 * always due to a high-level interrupt. (And we're assuming
3279 * that there is only a single high level interrupt.)
3281 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3282 return (pid0.pid_id);
3285 * It is always safe to dereference one's own t_procp pointer:
3286 * it always points to a valid, allocated proc structure.
3287 * Further, it is always safe to dereference the p_pidp member
3288 * of one's own proc structure. (These are truisms becuase
3289 * threads and processes don't clean up their own state --
3290 * they leave that task to whomever reaps them.)
3292 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3294 return ((uint64_t)curproc->p_pid);
3298 if (!dtrace_priv_proc(state))
3303 * See comment in DIF_VAR_PID.
3305 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3306 return (pid0.pid_id);
3309 * It is always safe to dereference one's own t_procp pointer:
3310 * it always points to a valid, allocated proc structure.
3311 * (This is true because threads don't clean up their own
3312 * state -- they leave that task to whomever reaps them.)
3314 return ((uint64_t)curthread->t_procp->p_ppid);
3316 return ((uint64_t)curproc->p_pptr->p_pid);
3322 * See comment in DIF_VAR_PID.
3324 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3328 return ((uint64_t)curthread->t_tid);
3330 case DIF_VAR_EXECARGS: {
3331 struct pargs *p_args = curthread->td_proc->p_args;
3336 return (dtrace_dif_varstrz(
3337 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3340 case DIF_VAR_EXECNAME:
3342 if (!dtrace_priv_proc(state))
3346 * See comment in DIF_VAR_PID.
3348 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3349 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3352 * It is always safe to dereference one's own t_procp pointer:
3353 * it always points to a valid, allocated proc structure.
3354 * (This is true because threads don't clean up their own
3355 * state -- they leave that task to whomever reaps them.)
3357 return (dtrace_dif_varstr(
3358 (uintptr_t)curthread->t_procp->p_user.u_comm,
3361 return (dtrace_dif_varstr(
3362 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3365 case DIF_VAR_ZONENAME:
3367 if (!dtrace_priv_proc(state))
3371 * See comment in DIF_VAR_PID.
3373 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3374 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3377 * It is always safe to dereference one's own t_procp pointer:
3378 * it always points to a valid, allocated proc structure.
3379 * (This is true because threads don't clean up their own
3380 * state -- they leave that task to whomever reaps them.)
3382 return (dtrace_dif_varstr(
3383 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3390 if (!dtrace_priv_proc(state))
3395 * See comment in DIF_VAR_PID.
3397 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3398 return ((uint64_t)p0.p_cred->cr_uid);
3402 * It is always safe to dereference one's own t_procp pointer:
3403 * it always points to a valid, allocated proc structure.
3404 * (This is true because threads don't clean up their own
3405 * state -- they leave that task to whomever reaps them.)
3407 * Additionally, it is safe to dereference one's own process
3408 * credential, since this is never NULL after process birth.
3410 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3413 if (!dtrace_priv_proc(state))
3418 * See comment in DIF_VAR_PID.
3420 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3421 return ((uint64_t)p0.p_cred->cr_gid);
3425 * It is always safe to dereference one's own t_procp pointer:
3426 * it always points to a valid, allocated proc structure.
3427 * (This is true because threads don't clean up their own
3428 * state -- they leave that task to whomever reaps them.)
3430 * Additionally, it is safe to dereference one's own process
3431 * credential, since this is never NULL after process birth.
3433 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3435 case DIF_VAR_ERRNO: {
3438 if (!dtrace_priv_proc(state))
3442 * See comment in DIF_VAR_PID.
3444 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3448 * It is always safe to dereference one's own t_lwp pointer in
3449 * the event that this pointer is non-NULL. (This is true
3450 * because threads and lwps don't clean up their own state --
3451 * they leave that task to whomever reaps them.)
3453 if ((lwp = curthread->t_lwp) == NULL)
3456 return ((uint64_t)lwp->lwp_errno);
3458 return (curthread->td_errno);
3467 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3473 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3474 * Notice that we don't bother validating the proper number of arguments or
3475 * their types in the tuple stack. This isn't needed because all argument
3476 * interpretation is safe because of our load safety -- the worst that can
3477 * happen is that a bogus program can obtain bogus results.
3480 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3481 dtrace_key_t *tupregs, int nargs,
3482 dtrace_mstate_t *mstate, dtrace_state_t *state)
3484 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3485 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3486 dtrace_vstate_t *vstate = &state->dts_vstate;
3499 struct thread *lowner;
3501 struct lock_object *li;
3508 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3512 case DIF_SUBR_MUTEX_OWNED:
3513 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3519 m.mx = dtrace_load64(tupregs[0].dttk_value);
3520 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3521 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3523 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3526 case DIF_SUBR_MUTEX_OWNER:
3527 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3533 m.mx = dtrace_load64(tupregs[0].dttk_value);
3534 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3535 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3536 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3541 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3542 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3548 m.mx = dtrace_load64(tupregs[0].dttk_value);
3549 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3552 case DIF_SUBR_MUTEX_TYPE_SPIN:
3553 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3559 m.mx = dtrace_load64(tupregs[0].dttk_value);
3560 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3563 case DIF_SUBR_RW_READ_HELD: {
3566 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3572 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3573 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3577 case DIF_SUBR_RW_WRITE_HELD:
3578 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3584 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3585 regs[rd] = _RW_WRITE_HELD(&r.ri);
3588 case DIF_SUBR_RW_ISWRITER:
3589 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3595 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3596 regs[rd] = _RW_ISWRITER(&r.ri);
3600 case DIF_SUBR_MUTEX_OWNED:
3601 if (!dtrace_canload(tupregs[0].dttk_value,
3602 sizeof (struct lock_object), mstate, vstate)) {
3606 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3607 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3610 case DIF_SUBR_MUTEX_OWNER:
3611 if (!dtrace_canload(tupregs[0].dttk_value,
3612 sizeof (struct lock_object), mstate, vstate)) {
3616 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3617 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3618 regs[rd] = (uintptr_t)lowner;
3621 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3622 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3627 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3628 /* XXX - should be only LC_SLEEPABLE? */
3629 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3630 (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3633 case DIF_SUBR_MUTEX_TYPE_SPIN:
3634 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3639 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3640 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3643 case DIF_SUBR_RW_READ_HELD:
3644 case DIF_SUBR_SX_SHARED_HELD:
3645 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3650 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3651 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3655 case DIF_SUBR_RW_WRITE_HELD:
3656 case DIF_SUBR_SX_EXCLUSIVE_HELD:
3657 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3662 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3663 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3664 regs[rd] = (lowner == curthread);
3667 case DIF_SUBR_RW_ISWRITER:
3668 case DIF_SUBR_SX_ISEXCLUSIVE:
3669 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3674 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3675 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3678 #endif /* ! defined(sun) */
3680 case DIF_SUBR_BCOPY: {
3682 * We need to be sure that the destination is in the scratch
3683 * region -- no other region is allowed.
3685 uintptr_t src = tupregs[0].dttk_value;
3686 uintptr_t dest = tupregs[1].dttk_value;
3687 size_t size = tupregs[2].dttk_value;
3689 if (!dtrace_inscratch(dest, size, mstate)) {
3690 *flags |= CPU_DTRACE_BADADDR;
3695 if (!dtrace_canload(src, size, mstate, vstate)) {
3700 dtrace_bcopy((void *)src, (void *)dest, size);
3704 case DIF_SUBR_ALLOCA:
3705 case DIF_SUBR_COPYIN: {
3706 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3708 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3709 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3712 * This action doesn't require any credential checks since
3713 * probes will not activate in user contexts to which the
3714 * enabling user does not have permissions.
3718 * Rounding up the user allocation size could have overflowed
3719 * a large, bogus allocation (like -1ULL) to 0.
3721 if (scratch_size < size ||
3722 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3723 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3728 if (subr == DIF_SUBR_COPYIN) {
3729 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3730 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3731 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3734 mstate->dtms_scratch_ptr += scratch_size;
3739 case DIF_SUBR_COPYINTO: {
3740 uint64_t size = tupregs[1].dttk_value;
3741 uintptr_t dest = tupregs[2].dttk_value;
3744 * This action doesn't require any credential checks since
3745 * probes will not activate in user contexts to which the
3746 * enabling user does not have permissions.
3748 if (!dtrace_inscratch(dest, size, mstate)) {
3749 *flags |= CPU_DTRACE_BADADDR;
3754 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3755 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3756 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3760 case DIF_SUBR_COPYINSTR: {
3761 uintptr_t dest = mstate->dtms_scratch_ptr;
3762 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3764 if (nargs > 1 && tupregs[1].dttk_value < size)
3765 size = tupregs[1].dttk_value + 1;
3768 * This action doesn't require any credential checks since
3769 * probes will not activate in user contexts to which the
3770 * enabling user does not have permissions.
3772 if (!DTRACE_INSCRATCH(mstate, size)) {
3773 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3778 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3779 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3780 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3782 ((char *)dest)[size - 1] = '\0';
3783 mstate->dtms_scratch_ptr += size;
3789 case DIF_SUBR_MSGSIZE:
3790 case DIF_SUBR_MSGDSIZE: {
3791 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3792 uintptr_t wptr, rptr;
3796 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3798 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3804 wptr = dtrace_loadptr(baddr +
3805 offsetof(mblk_t, b_wptr));
3807 rptr = dtrace_loadptr(baddr +
3808 offsetof(mblk_t, b_rptr));
3811 *flags |= CPU_DTRACE_BADADDR;
3812 *illval = tupregs[0].dttk_value;
3816 daddr = dtrace_loadptr(baddr +
3817 offsetof(mblk_t, b_datap));
3819 baddr = dtrace_loadptr(baddr +
3820 offsetof(mblk_t, b_cont));
3823 * We want to prevent against denial-of-service here,
3824 * so we're only going to search the list for
3825 * dtrace_msgdsize_max mblks.
3827 if (cont++ > dtrace_msgdsize_max) {
3828 *flags |= CPU_DTRACE_ILLOP;
3832 if (subr == DIF_SUBR_MSGDSIZE) {
3833 if (dtrace_load8(daddr +
3834 offsetof(dblk_t, db_type)) != M_DATA)
3838 count += wptr - rptr;
3841 if (!(*flags & CPU_DTRACE_FAULT))
3848 case DIF_SUBR_PROGENYOF: {
3849 pid_t pid = tupregs[0].dttk_value;
3853 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3855 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3857 if (p->p_pidp->pid_id == pid) {
3859 if (p->p_pid == pid) {
3866 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3872 case DIF_SUBR_SPECULATION:
3873 regs[rd] = dtrace_speculation(state);
3876 case DIF_SUBR_COPYOUT: {
3877 uintptr_t kaddr = tupregs[0].dttk_value;
3878 uintptr_t uaddr = tupregs[1].dttk_value;
3879 uint64_t size = tupregs[2].dttk_value;
3881 if (!dtrace_destructive_disallow &&
3882 dtrace_priv_proc_control(state) &&
3883 !dtrace_istoxic(kaddr, size)) {
3884 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3885 dtrace_copyout(kaddr, uaddr, size, flags);
3886 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3891 case DIF_SUBR_COPYOUTSTR: {
3892 uintptr_t kaddr = tupregs[0].dttk_value;
3893 uintptr_t uaddr = tupregs[1].dttk_value;
3894 uint64_t size = tupregs[2].dttk_value;
3896 if (!dtrace_destructive_disallow &&
3897 dtrace_priv_proc_control(state) &&
3898 !dtrace_istoxic(kaddr, size)) {
3899 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3900 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3901 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3906 case DIF_SUBR_STRLEN: {
3908 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3909 sz = dtrace_strlen((char *)addr,
3910 state->dts_options[DTRACEOPT_STRSIZE]);
3912 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3922 case DIF_SUBR_STRCHR:
3923 case DIF_SUBR_STRRCHR: {
3925 * We're going to iterate over the string looking for the
3926 * specified character. We will iterate until we have reached
3927 * the string length or we have found the character. If this
3928 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3929 * of the specified character instead of the first.
3931 uintptr_t saddr = tupregs[0].dttk_value;
3932 uintptr_t addr = tupregs[0].dttk_value;
3933 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3934 char c, target = (char)tupregs[1].dttk_value;
3936 for (regs[rd] = 0; addr < limit; addr++) {
3937 if ((c = dtrace_load8(addr)) == target) {
3940 if (subr == DIF_SUBR_STRCHR)
3948 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3956 case DIF_SUBR_STRSTR:
3957 case DIF_SUBR_INDEX:
3958 case DIF_SUBR_RINDEX: {
3960 * We're going to iterate over the string looking for the
3961 * specified string. We will iterate until we have reached
3962 * the string length or we have found the string. (Yes, this
3963 * is done in the most naive way possible -- but considering
3964 * that the string we're searching for is likely to be
3965 * relatively short, the complexity of Rabin-Karp or similar
3966 * hardly seems merited.)
3968 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3969 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3970 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3971 size_t len = dtrace_strlen(addr, size);
3972 size_t sublen = dtrace_strlen(substr, size);
3973 char *limit = addr + len, *orig = addr;
3974 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3977 regs[rd] = notfound;
3979 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3984 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3991 * strstr() and index()/rindex() have similar semantics if
3992 * both strings are the empty string: strstr() returns a
3993 * pointer to the (empty) string, and index() and rindex()
3994 * both return index 0 (regardless of any position argument).
3996 if (sublen == 0 && len == 0) {
3997 if (subr == DIF_SUBR_STRSTR)
3998 regs[rd] = (uintptr_t)addr;
4004 if (subr != DIF_SUBR_STRSTR) {
4005 if (subr == DIF_SUBR_RINDEX) {
4012 * Both index() and rindex() take an optional position
4013 * argument that denotes the starting position.
4016 int64_t pos = (int64_t)tupregs[2].dttk_value;
4019 * If the position argument to index() is
4020 * negative, Perl implicitly clamps it at
4021 * zero. This semantic is a little surprising
4022 * given the special meaning of negative
4023 * positions to similar Perl functions like
4024 * substr(), but it appears to reflect a
4025 * notion that index() can start from a
4026 * negative index and increment its way up to
4027 * the string. Given this notion, Perl's
4028 * rindex() is at least self-consistent in
4029 * that it implicitly clamps positions greater
4030 * than the string length to be the string
4031 * length. Where Perl completely loses
4032 * coherence, however, is when the specified
4033 * substring is the empty string (""). In
4034 * this case, even if the position is
4035 * negative, rindex() returns 0 -- and even if
4036 * the position is greater than the length,
4037 * index() returns the string length. These
4038 * semantics violate the notion that index()
4039 * should never return a value less than the
4040 * specified position and that rindex() should
4041 * never return a value greater than the
4042 * specified position. (One assumes that
4043 * these semantics are artifacts of Perl's
4044 * implementation and not the results of
4045 * deliberate design -- it beggars belief that
4046 * even Larry Wall could desire such oddness.)
4047 * While in the abstract one would wish for
4048 * consistent position semantics across
4049 * substr(), index() and rindex() -- or at the
4050 * very least self-consistent position
4051 * semantics for index() and rindex() -- we
4052 * instead opt to keep with the extant Perl
4053 * semantics, in all their broken glory. (Do
4054 * we have more desire to maintain Perl's
4055 * semantics than Perl does? Probably.)
4057 if (subr == DIF_SUBR_RINDEX) {
4081 for (regs[rd] = notfound; addr != limit; addr += inc) {
4082 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4083 if (subr != DIF_SUBR_STRSTR) {
4085 * As D index() and rindex() are
4086 * modeled on Perl (and not on awk),
4087 * we return a zero-based (and not a
4088 * one-based) index. (For you Perl
4089 * weenies: no, we're not going to add
4090 * $[ -- and shouldn't you be at a con
4093 regs[rd] = (uintptr_t)(addr - orig);
4097 ASSERT(subr == DIF_SUBR_STRSTR);
4098 regs[rd] = (uintptr_t)addr;
4106 case DIF_SUBR_STRTOK: {
4107 uintptr_t addr = tupregs[0].dttk_value;
4108 uintptr_t tokaddr = tupregs[1].dttk_value;
4109 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4110 uintptr_t limit, toklimit = tokaddr + size;
4111 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
4112 char *dest = (char *)mstate->dtms_scratch_ptr;
4116 * Check both the token buffer and (later) the input buffer,
4117 * since both could be non-scratch addresses.
4119 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4124 if (!DTRACE_INSCRATCH(mstate, size)) {
4125 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4132 * If the address specified is NULL, we use our saved
4133 * strtok pointer from the mstate. Note that this
4134 * means that the saved strtok pointer is _only_
4135 * valid within multiple enablings of the same probe --
4136 * it behaves like an implicit clause-local variable.
4138 addr = mstate->dtms_strtok;
4141 * If the user-specified address is non-NULL we must
4142 * access check it. This is the only time we have
4143 * a chance to do so, since this address may reside
4144 * in the string table of this clause-- future calls
4145 * (when we fetch addr from mstate->dtms_strtok)
4146 * would fail this access check.
4148 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4155 * First, zero the token map, and then process the token
4156 * string -- setting a bit in the map for every character
4157 * found in the token string.
4159 for (i = 0; i < sizeof (tokmap); i++)
4162 for (; tokaddr < toklimit; tokaddr++) {
4163 if ((c = dtrace_load8(tokaddr)) == '\0')
4166 ASSERT((c >> 3) < sizeof (tokmap));
4167 tokmap[c >> 3] |= (1 << (c & 0x7));
4170 for (limit = addr + size; addr < limit; addr++) {
4172 * We're looking for a character that is _not_ contained
4173 * in the token string.
4175 if ((c = dtrace_load8(addr)) == '\0')
4178 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4184 * We reached the end of the string without finding
4185 * any character that was not in the token string.
4186 * We return NULL in this case, and we set the saved
4187 * address to NULL as well.
4190 mstate->dtms_strtok = 0;
4195 * From here on, we're copying into the destination string.
4197 for (i = 0; addr < limit && i < size - 1; addr++) {
4198 if ((c = dtrace_load8(addr)) == '\0')
4201 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4210 regs[rd] = (uintptr_t)dest;
4211 mstate->dtms_scratch_ptr += size;
4212 mstate->dtms_strtok = addr;
4216 case DIF_SUBR_SUBSTR: {
4217 uintptr_t s = tupregs[0].dttk_value;
4218 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4219 char *d = (char *)mstate->dtms_scratch_ptr;
4220 int64_t index = (int64_t)tupregs[1].dttk_value;
4221 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4222 size_t len = dtrace_strlen((char *)s, size);
4225 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4230 if (!DTRACE_INSCRATCH(mstate, size)) {
4231 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4237 remaining = (int64_t)size;
4242 if (index < 0 && index + remaining > 0) {
4248 if (index >= len || index < 0) {
4250 } else if (remaining < 0) {
4251 remaining += len - index;
4252 } else if (index + remaining > size) {
4253 remaining = size - index;
4256 for (i = 0; i < remaining; i++) {
4257 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4263 mstate->dtms_scratch_ptr += size;
4264 regs[rd] = (uintptr_t)d;
4268 case DIF_SUBR_TOUPPER:
4269 case DIF_SUBR_TOLOWER: {
4270 uintptr_t s = tupregs[0].dttk_value;
4271 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4272 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4273 size_t len = dtrace_strlen((char *)s, size);
4274 char lower, upper, convert;
4277 if (subr == DIF_SUBR_TOUPPER) {
4287 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4292 if (!DTRACE_INSCRATCH(mstate, size)) {
4293 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4298 for (i = 0; i < size - 1; i++) {
4299 if ((c = dtrace_load8(s + i)) == '\0')
4302 if (c >= lower && c <= upper)
4303 c = convert + (c - lower);
4310 regs[rd] = (uintptr_t)dest;
4311 mstate->dtms_scratch_ptr += size;
4316 case DIF_SUBR_GETMAJOR:
4318 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4320 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4324 case DIF_SUBR_GETMINOR:
4326 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4328 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4332 case DIF_SUBR_DDI_PATHNAME: {
4334 * This one is a galactic mess. We are going to roughly
4335 * emulate ddi_pathname(), but it's made more complicated
4336 * by the fact that we (a) want to include the minor name and
4337 * (b) must proceed iteratively instead of recursively.
4339 uintptr_t dest = mstate->dtms_scratch_ptr;
4340 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4341 char *start = (char *)dest, *end = start + size - 1;
4342 uintptr_t daddr = tupregs[0].dttk_value;
4343 int64_t minor = (int64_t)tupregs[1].dttk_value;
4345 int i, len, depth = 0;
4348 * Due to all the pointer jumping we do and context we must
4349 * rely upon, we just mandate that the user must have kernel
4350 * read privileges to use this routine.
4352 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4353 *flags |= CPU_DTRACE_KPRIV;
4358 if (!DTRACE_INSCRATCH(mstate, size)) {
4359 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4367 * We want to have a name for the minor. In order to do this,
4368 * we need to walk the minor list from the devinfo. We want
4369 * to be sure that we don't infinitely walk a circular list,
4370 * so we check for circularity by sending a scout pointer
4371 * ahead two elements for every element that we iterate over;
4372 * if the list is circular, these will ultimately point to the
4373 * same element. You may recognize this little trick as the
4374 * answer to a stupid interview question -- one that always
4375 * seems to be asked by those who had to have it laboriously
4376 * explained to them, and who can't even concisely describe
4377 * the conditions under which one would be forced to resort to
4378 * this technique. Needless to say, those conditions are
4379 * found here -- and probably only here. Is this the only use
4380 * of this infamous trick in shipping, production code? If it
4381 * isn't, it probably should be...
4384 uintptr_t maddr = dtrace_loadptr(daddr +
4385 offsetof(struct dev_info, devi_minor));
4387 uintptr_t next = offsetof(struct ddi_minor_data, next);
4388 uintptr_t name = offsetof(struct ddi_minor_data,
4389 d_minor) + offsetof(struct ddi_minor, name);
4390 uintptr_t dev = offsetof(struct ddi_minor_data,
4391 d_minor) + offsetof(struct ddi_minor, dev);
4395 scout = dtrace_loadptr(maddr + next);
4397 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4400 m = dtrace_load64(maddr + dev) & MAXMIN64;
4402 m = dtrace_load32(maddr + dev) & MAXMIN;
4405 maddr = dtrace_loadptr(maddr + next);
4410 scout = dtrace_loadptr(scout + next);
4415 scout = dtrace_loadptr(scout + next);
4420 if (scout == maddr) {
4421 *flags |= CPU_DTRACE_ILLOP;
4429 * We have the minor data. Now we need to
4430 * copy the minor's name into the end of the
4433 s = (char *)dtrace_loadptr(maddr + name);
4434 len = dtrace_strlen(s, size);
4436 if (*flags & CPU_DTRACE_FAULT)
4440 if ((end -= (len + 1)) < start)
4446 for (i = 1; i <= len; i++)
4447 end[i] = dtrace_load8((uintptr_t)s++);
4452 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4453 ddi_node_state_t devi_state;
4455 devi_state = dtrace_load32(daddr +
4456 offsetof(struct dev_info, devi_node_state));
4458 if (*flags & CPU_DTRACE_FAULT)
4461 if (devi_state >= DS_INITIALIZED) {
4462 s = (char *)dtrace_loadptr(daddr +
4463 offsetof(struct dev_info, devi_addr));
4464 len = dtrace_strlen(s, size);
4466 if (*flags & CPU_DTRACE_FAULT)
4470 if ((end -= (len + 1)) < start)
4476 for (i = 1; i <= len; i++)
4477 end[i] = dtrace_load8((uintptr_t)s++);
4481 * Now for the node name...
4483 s = (char *)dtrace_loadptr(daddr +
4484 offsetof(struct dev_info, devi_node_name));
4486 daddr = dtrace_loadptr(daddr +
4487 offsetof(struct dev_info, devi_parent));
4490 * If our parent is NULL (that is, if we're the root
4491 * node), we're going to use the special path
4497 len = dtrace_strlen(s, size);
4498 if (*flags & CPU_DTRACE_FAULT)
4501 if ((end -= (len + 1)) < start)
4504 for (i = 1; i <= len; i++)
4505 end[i] = dtrace_load8((uintptr_t)s++);
4508 if (depth++ > dtrace_devdepth_max) {
4509 *flags |= CPU_DTRACE_ILLOP;
4515 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4518 regs[rd] = (uintptr_t)end;
4519 mstate->dtms_scratch_ptr += size;
4526 case DIF_SUBR_STRJOIN: {
4527 char *d = (char *)mstate->dtms_scratch_ptr;
4528 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4529 uintptr_t s1 = tupregs[0].dttk_value;
4530 uintptr_t s2 = tupregs[1].dttk_value;
4533 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4534 !dtrace_strcanload(s2, size, mstate, vstate)) {
4539 if (!DTRACE_INSCRATCH(mstate, size)) {
4540 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4547 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4552 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4560 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4565 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4570 mstate->dtms_scratch_ptr += i;
4571 regs[rd] = (uintptr_t)d;
4577 case DIF_SUBR_LLTOSTR: {
4578 int64_t i = (int64_t)tupregs[0].dttk_value;
4579 uint64_t val, digit;
4580 uint64_t size = 65; /* enough room for 2^64 in binary */
4581 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4585 if ((base = tupregs[1].dttk_value) <= 1 ||
4586 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4587 *flags |= CPU_DTRACE_ILLOP;
4592 val = (base == 10 && i < 0) ? i * -1 : i;
4594 if (!DTRACE_INSCRATCH(mstate, size)) {
4595 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4600 for (*end-- = '\0'; val; val /= base) {
4601 if ((digit = val % base) <= '9' - '0') {
4602 *end-- = '0' + digit;
4604 *end-- = 'a' + (digit - ('9' - '0') - 1);
4608 if (i == 0 && base == 16)
4614 if (i == 0 || base == 8 || base == 16)
4617 if (i < 0 && base == 10)
4620 regs[rd] = (uintptr_t)end + 1;
4621 mstate->dtms_scratch_ptr += size;
4625 case DIF_SUBR_HTONS:
4626 case DIF_SUBR_NTOHS:
4627 #if BYTE_ORDER == BIG_ENDIAN
4628 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4630 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4635 case DIF_SUBR_HTONL:
4636 case DIF_SUBR_NTOHL:
4637 #if BYTE_ORDER == BIG_ENDIAN
4638 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4640 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4645 case DIF_SUBR_HTONLL:
4646 case DIF_SUBR_NTOHLL:
4647 #if BYTE_ORDER == BIG_ENDIAN
4648 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4650 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4655 case DIF_SUBR_DIRNAME:
4656 case DIF_SUBR_BASENAME: {
4657 char *dest = (char *)mstate->dtms_scratch_ptr;
4658 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4659 uintptr_t src = tupregs[0].dttk_value;
4660 int i, j, len = dtrace_strlen((char *)src, size);
4661 int lastbase = -1, firstbase = -1, lastdir = -1;
4664 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4669 if (!DTRACE_INSCRATCH(mstate, size)) {
4670 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4676 * The basename and dirname for a zero-length string is
4681 src = (uintptr_t)".";
4685 * Start from the back of the string, moving back toward the
4686 * front until we see a character that isn't a slash. That
4687 * character is the last character in the basename.
4689 for (i = len - 1; i >= 0; i--) {
4690 if (dtrace_load8(src + i) != '/')
4698 * Starting from the last character in the basename, move
4699 * towards the front until we find a slash. The character
4700 * that we processed immediately before that is the first
4701 * character in the basename.
4703 for (; i >= 0; i--) {
4704 if (dtrace_load8(src + i) == '/')
4712 * Now keep going until we find a non-slash character. That
4713 * character is the last character in the dirname.
4715 for (; i >= 0; i--) {
4716 if (dtrace_load8(src + i) != '/')
4723 ASSERT(!(lastbase == -1 && firstbase != -1));
4724 ASSERT(!(firstbase == -1 && lastdir != -1));
4726 if (lastbase == -1) {
4728 * We didn't find a non-slash character. We know that
4729 * the length is non-zero, so the whole string must be
4730 * slashes. In either the dirname or the basename
4731 * case, we return '/'.
4733 ASSERT(firstbase == -1);
4734 firstbase = lastbase = lastdir = 0;
4737 if (firstbase == -1) {
4739 * The entire string consists only of a basename
4740 * component. If we're looking for dirname, we need
4741 * to change our string to be just "."; if we're
4742 * looking for a basename, we'll just set the first
4743 * character of the basename to be 0.
4745 if (subr == DIF_SUBR_DIRNAME) {
4746 ASSERT(lastdir == -1);
4747 src = (uintptr_t)".";
4754 if (subr == DIF_SUBR_DIRNAME) {
4755 if (lastdir == -1) {
4757 * We know that we have a slash in the name --
4758 * or lastdir would be set to 0, above. And
4759 * because lastdir is -1, we know that this
4760 * slash must be the first character. (That
4761 * is, the full string must be of the form
4762 * "/basename".) In this case, the last
4763 * character of the directory name is 0.
4771 ASSERT(subr == DIF_SUBR_BASENAME);
4772 ASSERT(firstbase != -1 && lastbase != -1);
4777 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4778 dest[j] = dtrace_load8(src + i);
4781 regs[rd] = (uintptr_t)dest;
4782 mstate->dtms_scratch_ptr += size;
4786 case DIF_SUBR_GETF: {
4787 uintptr_t fd = tupregs[0].dttk_value;
4788 struct filedesc *fdp;
4791 if (!dtrace_priv_proc(state)) {
4795 fdp = curproc->p_fd;
4796 FILEDESC_SLOCK(fdp);
4797 fp = fget_locked(fdp, fd);
4798 mstate->dtms_getf = fp;
4799 regs[rd] = (uintptr_t)fp;
4800 FILEDESC_SUNLOCK(fdp);
4804 case DIF_SUBR_CLEANPATH: {
4805 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4806 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4807 uintptr_t src = tupregs[0].dttk_value;
4813 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4818 if (!DTRACE_INSCRATCH(mstate, size)) {
4819 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4825 * Move forward, loading each character.
4828 c = dtrace_load8(src + i++);
4830 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
4838 c = dtrace_load8(src + i++);
4842 * We have two slashes -- we can just advance
4843 * to the next character.
4850 * This is not "." and it's not ".." -- we can
4851 * just store the "/" and this character and
4859 c = dtrace_load8(src + i++);
4863 * This is a "/./" component. We're not going
4864 * to store anything in the destination buffer;
4865 * we're just going to go to the next component.
4872 * This is not ".." -- we can just store the
4873 * "/." and this character and continue
4882 c = dtrace_load8(src + i++);
4884 if (c != '/' && c != '\0') {
4886 * This is not ".." -- it's "..[mumble]".
4887 * We'll store the "/.." and this character
4888 * and continue processing.
4898 * This is "/../" or "/..\0". We need to back up
4899 * our destination pointer until we find a "/".
4902 while (j != 0 && dest[--j] != '/')
4907 } while (c != '\0');
4912 if (mstate->dtms_getf != NULL &&
4913 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
4914 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
4916 * If we've done a getf() as a part of this ECB and we
4917 * don't have kernel access (and we're not in the global
4918 * zone), check if the path we cleaned up begins with
4919 * the zone's root path, and trim it off if so. Note
4920 * that this is an output cleanliness issue, not a
4921 * security issue: knowing one's zone root path does
4922 * not enable privilege escalation.
4924 if (strstr(dest, z->zone_rootpath) == dest)
4925 dest += strlen(z->zone_rootpath) - 1;
4929 regs[rd] = (uintptr_t)dest;
4930 mstate->dtms_scratch_ptr += size;
4934 case DIF_SUBR_INET_NTOA:
4935 case DIF_SUBR_INET_NTOA6:
4936 case DIF_SUBR_INET_NTOP: {
4941 if (subr == DIF_SUBR_INET_NTOP) {
4942 af = (int)tupregs[0].dttk_value;
4945 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4949 if (af == AF_INET) {
4954 * Safely load the IPv4 address.
4956 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4959 * Check an IPv4 string will fit in scratch.
4961 size = INET_ADDRSTRLEN;
4962 if (!DTRACE_INSCRATCH(mstate, size)) {
4963 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4967 base = (char *)mstate->dtms_scratch_ptr;
4968 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4971 * Stringify as a dotted decimal quad.
4974 ptr8 = (uint8_t *)&ip4;
4975 for (i = 3; i >= 0; i--) {
4981 for (; val; val /= 10) {
4982 *end-- = '0' + (val % 10);
4989 ASSERT(end + 1 >= base);
4991 } else if (af == AF_INET6) {
4992 struct in6_addr ip6;
4993 int firstzero, tryzero, numzero, v6end;
4995 const char digits[] = "0123456789abcdef";
4998 * Stringify using RFC 1884 convention 2 - 16 bit
4999 * hexadecimal values with a zero-run compression.
5000 * Lower case hexadecimal digits are used.
5001 * eg, fe80::214:4fff:fe0b:76c8.
5002 * The IPv4 embedded form is returned for inet_ntop,
5003 * just the IPv4 string is returned for inet_ntoa6.
5007 * Safely load the IPv6 address.
5010 (void *)(uintptr_t)tupregs[argi].dttk_value,
5011 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5014 * Check an IPv6 string will fit in scratch.
5016 size = INET6_ADDRSTRLEN;
5017 if (!DTRACE_INSCRATCH(mstate, size)) {
5018 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5022 base = (char *)mstate->dtms_scratch_ptr;
5023 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5027 * Find the longest run of 16 bit zero values
5028 * for the single allowed zero compression - "::".
5033 for (i = 0; i < sizeof (struct in6_addr); i++) {
5035 if (ip6._S6_un._S6_u8[i] == 0 &&
5037 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5039 tryzero == -1 && i % 2 == 0) {
5044 if (tryzero != -1 &&
5046 (ip6._S6_un._S6_u8[i] != 0 ||
5048 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5050 i == sizeof (struct in6_addr) - 1)) {
5052 if (i - tryzero <= numzero) {
5057 firstzero = tryzero;
5058 numzero = i - i % 2 - tryzero;
5062 if (ip6._S6_un._S6_u8[i] == 0 &&
5064 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5066 i == sizeof (struct in6_addr) - 1)
5070 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5073 * Check for an IPv4 embedded address.
5075 v6end = sizeof (struct in6_addr) - 2;
5076 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5077 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5078 for (i = sizeof (struct in6_addr) - 1;
5079 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5080 ASSERT(end >= base);
5083 val = ip6._S6_un._S6_u8[i];
5085 val = ip6.__u6_addr.__u6_addr8[i];
5091 for (; val; val /= 10) {
5092 *end-- = '0' + val % 10;
5096 if (i > DTRACE_V4MAPPED_OFFSET)
5100 if (subr == DIF_SUBR_INET_NTOA6)
5104 * Set v6end to skip the IPv4 address that
5105 * we have already stringified.
5111 * Build the IPv6 string by working through the
5112 * address in reverse.
5114 for (i = v6end; i >= 0; i -= 2) {
5115 ASSERT(end >= base);
5117 if (i == firstzero + numzero - 2) {
5124 if (i < 14 && i != firstzero - 2)
5128 val = (ip6._S6_un._S6_u8[i] << 8) +
5129 ip6._S6_un._S6_u8[i + 1];
5131 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5132 ip6.__u6_addr.__u6_addr8[i + 1];
5138 for (; val; val /= 16) {
5139 *end-- = digits[val % 16];
5143 ASSERT(end + 1 >= base);
5147 * The user didn't use AH_INET or AH_INET6.
5149 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5154 inetout: regs[rd] = (uintptr_t)end + 1;
5155 mstate->dtms_scratch_ptr += size;
5159 case DIF_SUBR_MEMREF: {
5160 uintptr_t size = 2 * sizeof(uintptr_t);
5161 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5162 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5164 /* address and length */
5165 memref[0] = tupregs[0].dttk_value;
5166 memref[1] = tupregs[1].dttk_value;
5168 regs[rd] = (uintptr_t) memref;
5169 mstate->dtms_scratch_ptr += scratch_size;
5174 case DIF_SUBR_MEMSTR: {
5175 char *str = (char *)mstate->dtms_scratch_ptr;
5176 uintptr_t mem = tupregs[0].dttk_value;
5177 char c = tupregs[1].dttk_value;
5178 size_t size = tupregs[2].dttk_value;
5187 if (!dtrace_canload(mem, size - 1, mstate, vstate))
5190 if (!DTRACE_INSCRATCH(mstate, size)) {
5191 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5195 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5196 *flags |= CPU_DTRACE_ILLOP;
5200 for (i = 0; i < size - 1; i++) {
5201 n = dtrace_load8(mem++);
5202 str[i] = (n == 0) ? c : n;
5206 regs[rd] = (uintptr_t)str;
5207 mstate->dtms_scratch_ptr += size;
5212 case DIF_SUBR_TYPEREF: {
5213 uintptr_t size = 4 * sizeof(uintptr_t);
5214 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5215 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5217 /* address, num_elements, type_str, type_len */
5218 typeref[0] = tupregs[0].dttk_value;
5219 typeref[1] = tupregs[1].dttk_value;
5220 typeref[2] = tupregs[2].dttk_value;
5221 typeref[3] = tupregs[3].dttk_value;
5223 regs[rd] = (uintptr_t) typeref;
5224 mstate->dtms_scratch_ptr += scratch_size;
5231 * Emulate the execution of DTrace IR instructions specified by the given
5232 * DIF object. This function is deliberately void of assertions as all of
5233 * the necessary checks are handled by a call to dtrace_difo_validate().
5236 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5237 dtrace_vstate_t *vstate, dtrace_state_t *state)
5239 const dif_instr_t *text = difo->dtdo_buf;
5240 const uint_t textlen = difo->dtdo_len;
5241 const char *strtab = difo->dtdo_strtab;
5242 const uint64_t *inttab = difo->dtdo_inttab;
5245 dtrace_statvar_t *svar;
5246 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5248 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5249 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5251 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5252 uint64_t regs[DIF_DIR_NREGS];
5255 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5257 uint_t pc = 0, id, opc = 0;
5263 * We stash the current DIF object into the machine state: we need it
5264 * for subsequent access checking.
5266 mstate->dtms_difo = difo;
5268 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5270 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5274 r1 = DIF_INSTR_R1(instr);
5275 r2 = DIF_INSTR_R2(instr);
5276 rd = DIF_INSTR_RD(instr);
5278 switch (DIF_INSTR_OP(instr)) {
5280 regs[rd] = regs[r1] | regs[r2];
5283 regs[rd] = regs[r1] ^ regs[r2];
5286 regs[rd] = regs[r1] & regs[r2];
5289 regs[rd] = regs[r1] << regs[r2];
5292 regs[rd] = regs[r1] >> regs[r2];
5295 regs[rd] = regs[r1] - regs[r2];
5298 regs[rd] = regs[r1] + regs[r2];
5301 regs[rd] = regs[r1] * regs[r2];
5304 if (regs[r2] == 0) {
5306 *flags |= CPU_DTRACE_DIVZERO;
5308 regs[rd] = (int64_t)regs[r1] /
5314 if (regs[r2] == 0) {
5316 *flags |= CPU_DTRACE_DIVZERO;
5318 regs[rd] = regs[r1] / regs[r2];
5323 if (regs[r2] == 0) {
5325 *flags |= CPU_DTRACE_DIVZERO;
5327 regs[rd] = (int64_t)regs[r1] %
5333 if (regs[r2] == 0) {
5335 *flags |= CPU_DTRACE_DIVZERO;
5337 regs[rd] = regs[r1] % regs[r2];
5342 regs[rd] = ~regs[r1];
5345 regs[rd] = regs[r1];
5348 cc_r = regs[r1] - regs[r2];
5352 cc_c = regs[r1] < regs[r2];
5355 cc_n = cc_v = cc_c = 0;
5356 cc_z = regs[r1] == 0;
5359 pc = DIF_INSTR_LABEL(instr);
5363 pc = DIF_INSTR_LABEL(instr);
5367 pc = DIF_INSTR_LABEL(instr);
5370 if ((cc_z | (cc_n ^ cc_v)) == 0)
5371 pc = DIF_INSTR_LABEL(instr);
5374 if ((cc_c | cc_z) == 0)
5375 pc = DIF_INSTR_LABEL(instr);
5378 if ((cc_n ^ cc_v) == 0)
5379 pc = DIF_INSTR_LABEL(instr);
5383 pc = DIF_INSTR_LABEL(instr);
5387 pc = DIF_INSTR_LABEL(instr);
5391 pc = DIF_INSTR_LABEL(instr);
5394 if (cc_z | (cc_n ^ cc_v))
5395 pc = DIF_INSTR_LABEL(instr);
5399 pc = DIF_INSTR_LABEL(instr);
5402 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5406 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5409 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5413 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5416 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5420 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5423 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5427 regs[rd] = dtrace_load8(regs[r1]);
5430 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5434 regs[rd] = dtrace_load16(regs[r1]);
5437 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5441 regs[rd] = dtrace_load32(regs[r1]);
5444 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5448 regs[rd] = dtrace_load64(regs[r1]);
5452 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5455 regs[rd] = (int16_t)
5456 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5459 regs[rd] = (int32_t)
5460 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5464 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5468 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5472 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5476 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5485 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5488 regs[rd] = (uint64_t)(uintptr_t)
5489 (strtab + DIF_INSTR_STRING(instr));
5492 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5493 uintptr_t s1 = regs[r1];
5494 uintptr_t s2 = regs[r2];
5497 !dtrace_strcanload(s1, sz, mstate, vstate))
5500 !dtrace_strcanload(s2, sz, mstate, vstate))
5503 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5511 regs[rd] = dtrace_dif_variable(mstate, state,
5515 id = DIF_INSTR_VAR(instr);
5517 if (id >= DIF_VAR_OTHER_UBASE) {
5520 id -= DIF_VAR_OTHER_UBASE;
5521 svar = vstate->dtvs_globals[id];
5522 ASSERT(svar != NULL);
5523 v = &svar->dtsv_var;
5525 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5526 regs[rd] = svar->dtsv_data;
5530 a = (uintptr_t)svar->dtsv_data;
5532 if (*(uint8_t *)a == UINT8_MAX) {
5534 * If the 0th byte is set to UINT8_MAX
5535 * then this is to be treated as a
5536 * reference to a NULL variable.
5540 regs[rd] = a + sizeof (uint64_t);
5546 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5550 id = DIF_INSTR_VAR(instr);
5552 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5553 id -= DIF_VAR_OTHER_UBASE;
5555 svar = vstate->dtvs_globals[id];
5556 ASSERT(svar != NULL);
5557 v = &svar->dtsv_var;
5559 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5560 uintptr_t a = (uintptr_t)svar->dtsv_data;
5563 ASSERT(svar->dtsv_size != 0);
5565 if (regs[rd] == 0) {
5566 *(uint8_t *)a = UINT8_MAX;
5570 a += sizeof (uint64_t);
5572 if (!dtrace_vcanload(
5573 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5577 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5578 (void *)a, &v->dtdv_type);
5582 svar->dtsv_data = regs[rd];
5587 * There are no DTrace built-in thread-local arrays at
5588 * present. This opcode is saved for future work.
5590 *flags |= CPU_DTRACE_ILLOP;
5595 id = DIF_INSTR_VAR(instr);
5597 if (id < DIF_VAR_OTHER_UBASE) {
5599 * For now, this has no meaning.
5605 id -= DIF_VAR_OTHER_UBASE;
5607 ASSERT(id < vstate->dtvs_nlocals);
5608 ASSERT(vstate->dtvs_locals != NULL);
5610 svar = vstate->dtvs_locals[id];
5611 ASSERT(svar != NULL);
5612 v = &svar->dtsv_var;
5614 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5615 uintptr_t a = (uintptr_t)svar->dtsv_data;
5616 size_t sz = v->dtdv_type.dtdt_size;
5618 sz += sizeof (uint64_t);
5619 ASSERT(svar->dtsv_size == NCPU * sz);
5622 if (*(uint8_t *)a == UINT8_MAX) {
5624 * If the 0th byte is set to UINT8_MAX
5625 * then this is to be treated as a
5626 * reference to a NULL variable.
5630 regs[rd] = a + sizeof (uint64_t);
5636 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5637 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5638 regs[rd] = tmp[curcpu];
5642 id = DIF_INSTR_VAR(instr);
5644 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5645 id -= DIF_VAR_OTHER_UBASE;
5646 ASSERT(id < vstate->dtvs_nlocals);
5648 ASSERT(vstate->dtvs_locals != NULL);
5649 svar = vstate->dtvs_locals[id];
5650 ASSERT(svar != NULL);
5651 v = &svar->dtsv_var;
5653 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5654 uintptr_t a = (uintptr_t)svar->dtsv_data;
5655 size_t sz = v->dtdv_type.dtdt_size;
5657 sz += sizeof (uint64_t);
5658 ASSERT(svar->dtsv_size == NCPU * sz);
5661 if (regs[rd] == 0) {
5662 *(uint8_t *)a = UINT8_MAX;
5666 a += sizeof (uint64_t);
5669 if (!dtrace_vcanload(
5670 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5674 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5675 (void *)a, &v->dtdv_type);
5679 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5680 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5681 tmp[curcpu] = regs[rd];
5685 dtrace_dynvar_t *dvar;
5688 id = DIF_INSTR_VAR(instr);
5689 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5690 id -= DIF_VAR_OTHER_UBASE;
5691 v = &vstate->dtvs_tlocals[id];
5693 key = &tupregs[DIF_DTR_NREGS];
5694 key[0].dttk_value = (uint64_t)id;
5695 key[0].dttk_size = 0;
5696 DTRACE_TLS_THRKEY(key[1].dttk_value);
5697 key[1].dttk_size = 0;
5699 dvar = dtrace_dynvar(dstate, 2, key,
5700 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5708 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5709 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5711 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5718 dtrace_dynvar_t *dvar;
5721 id = DIF_INSTR_VAR(instr);
5722 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5723 id -= DIF_VAR_OTHER_UBASE;
5725 key = &tupregs[DIF_DTR_NREGS];
5726 key[0].dttk_value = (uint64_t)id;
5727 key[0].dttk_size = 0;
5728 DTRACE_TLS_THRKEY(key[1].dttk_value);
5729 key[1].dttk_size = 0;
5730 v = &vstate->dtvs_tlocals[id];
5732 dvar = dtrace_dynvar(dstate, 2, key,
5733 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5734 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5735 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5736 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5739 * Given that we're storing to thread-local data,
5740 * we need to flush our predicate cache.
5742 curthread->t_predcache = 0;
5747 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5748 if (!dtrace_vcanload(
5749 (void *)(uintptr_t)regs[rd],
5750 &v->dtdv_type, mstate, vstate))
5753 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5754 dvar->dtdv_data, &v->dtdv_type);
5756 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5763 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5767 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5768 regs, tupregs, ttop, mstate, state);
5772 if (ttop == DIF_DTR_NREGS) {
5773 *flags |= CPU_DTRACE_TUPOFLOW;
5777 if (r1 == DIF_TYPE_STRING) {
5779 * If this is a string type and the size is 0,
5780 * we'll use the system-wide default string
5781 * size. Note that we are _not_ looking at
5782 * the value of the DTRACEOPT_STRSIZE option;
5783 * had this been set, we would expect to have
5784 * a non-zero size value in the "pushtr".
5786 tupregs[ttop].dttk_size =
5787 dtrace_strlen((char *)(uintptr_t)regs[rd],
5788 regs[r2] ? regs[r2] :
5789 dtrace_strsize_default) + 1;
5791 tupregs[ttop].dttk_size = regs[r2];
5794 tupregs[ttop++].dttk_value = regs[rd];
5798 if (ttop == DIF_DTR_NREGS) {
5799 *flags |= CPU_DTRACE_TUPOFLOW;
5803 tupregs[ttop].dttk_value = regs[rd];
5804 tupregs[ttop++].dttk_size = 0;
5812 case DIF_OP_FLUSHTS:
5817 case DIF_OP_LDTAA: {
5818 dtrace_dynvar_t *dvar;
5819 dtrace_key_t *key = tupregs;
5820 uint_t nkeys = ttop;
5822 id = DIF_INSTR_VAR(instr);
5823 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5824 id -= DIF_VAR_OTHER_UBASE;
5826 key[nkeys].dttk_value = (uint64_t)id;
5827 key[nkeys++].dttk_size = 0;
5829 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5830 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5831 key[nkeys++].dttk_size = 0;
5832 v = &vstate->dtvs_tlocals[id];
5834 v = &vstate->dtvs_globals[id]->dtsv_var;
5837 dvar = dtrace_dynvar(dstate, nkeys, key,
5838 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5839 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5840 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5847 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5848 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5850 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5857 case DIF_OP_STTAA: {
5858 dtrace_dynvar_t *dvar;
5859 dtrace_key_t *key = tupregs;
5860 uint_t nkeys = ttop;
5862 id = DIF_INSTR_VAR(instr);
5863 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5864 id -= DIF_VAR_OTHER_UBASE;
5866 key[nkeys].dttk_value = (uint64_t)id;
5867 key[nkeys++].dttk_size = 0;
5869 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5870 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5871 key[nkeys++].dttk_size = 0;
5872 v = &vstate->dtvs_tlocals[id];
5874 v = &vstate->dtvs_globals[id]->dtsv_var;
5877 dvar = dtrace_dynvar(dstate, nkeys, key,
5878 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5879 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5880 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5881 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5886 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5887 if (!dtrace_vcanload(
5888 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5892 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5893 dvar->dtdv_data, &v->dtdv_type);
5895 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5901 case DIF_OP_ALLOCS: {
5902 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5903 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5906 * Rounding up the user allocation size could have
5907 * overflowed large, bogus allocations (like -1ULL) to
5910 if (size < regs[r1] ||
5911 !DTRACE_INSCRATCH(mstate, size)) {
5912 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5917 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5918 mstate->dtms_scratch_ptr += size;
5924 if (!dtrace_canstore(regs[rd], regs[r2],
5926 *flags |= CPU_DTRACE_BADADDR;
5931 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5934 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5935 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5939 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5940 *flags |= CPU_DTRACE_BADADDR;
5944 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5948 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5949 *flags |= CPU_DTRACE_BADADDR;
5954 *flags |= CPU_DTRACE_BADALIGN;
5958 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5962 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5963 *flags |= CPU_DTRACE_BADADDR;
5968 *flags |= CPU_DTRACE_BADALIGN;
5972 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5976 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5977 *flags |= CPU_DTRACE_BADADDR;
5982 *flags |= CPU_DTRACE_BADALIGN;
5986 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5991 if (!(*flags & CPU_DTRACE_FAULT))
5994 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5995 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6001 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6003 dtrace_probe_t *probe = ecb->dte_probe;
6004 dtrace_provider_t *prov = probe->dtpr_provider;
6005 char c[DTRACE_FULLNAMELEN + 80], *str;
6006 char *msg = "dtrace: breakpoint action at probe ";
6007 char *ecbmsg = " (ecb ";
6008 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6009 uintptr_t val = (uintptr_t)ecb;
6010 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6012 if (dtrace_destructive_disallow)
6016 * It's impossible to be taking action on the NULL probe.
6018 ASSERT(probe != NULL);
6021 * This is a poor man's (destitute man's?) sprintf(): we want to
6022 * print the provider name, module name, function name and name of
6023 * the probe, along with the hex address of the ECB with the breakpoint
6024 * action -- all of which we must place in the character buffer by
6027 while (*msg != '\0')
6030 for (str = prov->dtpv_name; *str != '\0'; str++)
6034 for (str = probe->dtpr_mod; *str != '\0'; str++)
6038 for (str = probe->dtpr_func; *str != '\0'; str++)
6042 for (str = probe->dtpr_name; *str != '\0'; str++)
6045 while (*ecbmsg != '\0')
6048 while (shift >= 0) {
6049 mask = (uintptr_t)0xf << shift;
6051 if (val >= ((uintptr_t)1 << shift))
6052 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6062 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6067 dtrace_action_panic(dtrace_ecb_t *ecb)
6069 dtrace_probe_t *probe = ecb->dte_probe;
6072 * It's impossible to be taking action on the NULL probe.
6074 ASSERT(probe != NULL);
6076 if (dtrace_destructive_disallow)
6079 if (dtrace_panicked != NULL)
6082 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6086 * We won the right to panic. (We want to be sure that only one
6087 * thread calls panic() from dtrace_probe(), and that panic() is
6088 * called exactly once.)
6090 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6091 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6092 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6096 dtrace_action_raise(uint64_t sig)
6098 if (dtrace_destructive_disallow)
6102 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6108 * raise() has a queue depth of 1 -- we ignore all subsequent
6109 * invocations of the raise() action.
6111 if (curthread->t_dtrace_sig == 0)
6112 curthread->t_dtrace_sig = (uint8_t)sig;
6114 curthread->t_sig_check = 1;
6117 struct proc *p = curproc;
6119 kern_psignal(p, sig);
6125 dtrace_action_stop(void)
6127 if (dtrace_destructive_disallow)
6131 if (!curthread->t_dtrace_stop) {
6132 curthread->t_dtrace_stop = 1;
6133 curthread->t_sig_check = 1;
6137 struct proc *p = curproc;
6139 kern_psignal(p, SIGSTOP);
6145 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6148 volatile uint16_t *flags;
6152 cpu_t *cpu = &solaris_cpu[curcpu];
6155 if (dtrace_destructive_disallow)
6158 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6160 now = dtrace_gethrtime();
6162 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6164 * We need to advance the mark to the current time.
6166 cpu->cpu_dtrace_chillmark = now;
6167 cpu->cpu_dtrace_chilled = 0;
6171 * Now check to see if the requested chill time would take us over
6172 * the maximum amount of time allowed in the chill interval. (Or
6173 * worse, if the calculation itself induces overflow.)
6175 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6176 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6177 *flags |= CPU_DTRACE_ILLOP;
6181 while (dtrace_gethrtime() - now < val)
6185 * Normally, we assure that the value of the variable "timestamp" does
6186 * not change within an ECB. The presence of chill() represents an
6187 * exception to this rule, however.
6189 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6190 cpu->cpu_dtrace_chilled += val;
6194 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6195 uint64_t *buf, uint64_t arg)
6197 int nframes = DTRACE_USTACK_NFRAMES(arg);
6198 int strsize = DTRACE_USTACK_STRSIZE(arg);
6199 uint64_t *pcs = &buf[1], *fps;
6200 char *str = (char *)&pcs[nframes];
6201 int size, offs = 0, i, j;
6202 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6203 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6207 * Should be taking a faster path if string space has not been
6210 ASSERT(strsize != 0);
6213 * We will first allocate some temporary space for the frame pointers.
6215 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6216 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6217 (nframes * sizeof (uint64_t));
6219 if (!DTRACE_INSCRATCH(mstate, size)) {
6221 * Not enough room for our frame pointers -- need to indicate
6222 * that we ran out of scratch space.
6224 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6228 mstate->dtms_scratch_ptr += size;
6229 saved = mstate->dtms_scratch_ptr;
6232 * Now get a stack with both program counters and frame pointers.
6234 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6235 dtrace_getufpstack(buf, fps, nframes + 1);
6236 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6239 * If that faulted, we're cooked.
6241 if (*flags & CPU_DTRACE_FAULT)
6245 * Now we want to walk up the stack, calling the USTACK helper. For
6246 * each iteration, we restore the scratch pointer.
6248 for (i = 0; i < nframes; i++) {
6249 mstate->dtms_scratch_ptr = saved;
6251 if (offs >= strsize)
6254 sym = (char *)(uintptr_t)dtrace_helper(
6255 DTRACE_HELPER_ACTION_USTACK,
6256 mstate, state, pcs[i], fps[i]);
6259 * If we faulted while running the helper, we're going to
6260 * clear the fault and null out the corresponding string.
6262 if (*flags & CPU_DTRACE_FAULT) {
6263 *flags &= ~CPU_DTRACE_FAULT;
6273 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6276 * Now copy in the string that the helper returned to us.
6278 for (j = 0; offs + j < strsize; j++) {
6279 if ((str[offs + j] = sym[j]) == '\0')
6283 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6288 if (offs >= strsize) {
6290 * If we didn't have room for all of the strings, we don't
6291 * abort processing -- this needn't be a fatal error -- but we
6292 * still want to increment a counter (dts_stkstroverflows) to
6293 * allow this condition to be warned about. (If this is from
6294 * a jstack() action, it is easily tuned via jstackstrsize.)
6296 dtrace_error(&state->dts_stkstroverflows);
6299 while (offs < strsize)
6303 mstate->dtms_scratch_ptr = old;
6307 * If you're looking for the epicenter of DTrace, you just found it. This
6308 * is the function called by the provider to fire a probe -- from which all
6309 * subsequent probe-context DTrace activity emanates.
6312 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6313 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6315 processorid_t cpuid;
6316 dtrace_icookie_t cookie;
6317 dtrace_probe_t *probe;
6318 dtrace_mstate_t mstate;
6320 dtrace_action_t *act;
6324 volatile uint16_t *flags;
6327 if (panicstr != NULL)
6332 * Kick out immediately if this CPU is still being born (in which case
6333 * curthread will be set to -1) or the current thread can't allow
6334 * probes in its current context.
6336 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6340 cookie = dtrace_interrupt_disable();
6341 probe = dtrace_probes[id - 1];
6343 onintr = CPU_ON_INTR(CPU);
6345 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6346 probe->dtpr_predcache == curthread->t_predcache) {
6348 * We have hit in the predicate cache; we know that
6349 * this predicate would evaluate to be false.
6351 dtrace_interrupt_enable(cookie);
6356 if (panic_quiesce) {
6358 if (panicstr != NULL) {
6361 * We don't trace anything if we're panicking.
6363 dtrace_interrupt_enable(cookie);
6367 now = dtrace_gethrtime();
6368 vtime = dtrace_vtime_references != 0;
6370 if (vtime && curthread->t_dtrace_start)
6371 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6373 mstate.dtms_difo = NULL;
6374 mstate.dtms_probe = probe;
6375 mstate.dtms_strtok = 0;
6376 mstate.dtms_arg[0] = arg0;
6377 mstate.dtms_arg[1] = arg1;
6378 mstate.dtms_arg[2] = arg2;
6379 mstate.dtms_arg[3] = arg3;
6380 mstate.dtms_arg[4] = arg4;
6382 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6384 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6385 dtrace_predicate_t *pred = ecb->dte_predicate;
6386 dtrace_state_t *state = ecb->dte_state;
6387 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6388 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6389 dtrace_vstate_t *vstate = &state->dts_vstate;
6390 dtrace_provider_t *prov = probe->dtpr_provider;
6391 uint64_t tracememsize = 0;
6396 * A little subtlety with the following (seemingly innocuous)
6397 * declaration of the automatic 'val': by looking at the
6398 * code, you might think that it could be declared in the
6399 * action processing loop, below. (That is, it's only used in
6400 * the action processing loop.) However, it must be declared
6401 * out of that scope because in the case of DIF expression
6402 * arguments to aggregating actions, one iteration of the
6403 * action loop will use the last iteration's value.
6407 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6408 mstate.dtms_getf = NULL;
6410 *flags &= ~CPU_DTRACE_ERROR;
6412 if (prov == dtrace_provider) {
6414 * If dtrace itself is the provider of this probe,
6415 * we're only going to continue processing the ECB if
6416 * arg0 (the dtrace_state_t) is equal to the ECB's
6417 * creating state. (This prevents disjoint consumers
6418 * from seeing one another's metaprobes.)
6420 if (arg0 != (uint64_t)(uintptr_t)state)
6424 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6426 * We're not currently active. If our provider isn't
6427 * the dtrace pseudo provider, we're not interested.
6429 if (prov != dtrace_provider)
6433 * Now we must further check if we are in the BEGIN
6434 * probe. If we are, we will only continue processing
6435 * if we're still in WARMUP -- if one BEGIN enabling
6436 * has invoked the exit() action, we don't want to
6437 * evaluate subsequent BEGIN enablings.
6439 if (probe->dtpr_id == dtrace_probeid_begin &&
6440 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6441 ASSERT(state->dts_activity ==
6442 DTRACE_ACTIVITY_DRAINING);
6447 if (ecb->dte_cond) {
6449 * If the dte_cond bits indicate that this
6450 * consumer is only allowed to see user-mode firings
6451 * of this probe, call the provider's dtps_usermode()
6452 * entry point to check that the probe was fired
6453 * while in a user context. Skip this ECB if that's
6456 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6457 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6458 probe->dtpr_id, probe->dtpr_arg) == 0)
6463 * This is more subtle than it looks. We have to be
6464 * absolutely certain that CRED() isn't going to
6465 * change out from under us so it's only legit to
6466 * examine that structure if we're in constrained
6467 * situations. Currently, the only times we'll this
6468 * check is if a non-super-user has enabled the
6469 * profile or syscall providers -- providers that
6470 * allow visibility of all processes. For the
6471 * profile case, the check above will ensure that
6472 * we're examining a user context.
6474 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6477 ecb->dte_state->dts_cred.dcr_cred;
6480 ASSERT(s_cr != NULL);
6482 if ((cr = CRED()) == NULL ||
6483 s_cr->cr_uid != cr->cr_uid ||
6484 s_cr->cr_uid != cr->cr_ruid ||
6485 s_cr->cr_uid != cr->cr_suid ||
6486 s_cr->cr_gid != cr->cr_gid ||
6487 s_cr->cr_gid != cr->cr_rgid ||
6488 s_cr->cr_gid != cr->cr_sgid ||
6489 (proc = ttoproc(curthread)) == NULL ||
6490 (proc->p_flag & SNOCD))
6494 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6497 ecb->dte_state->dts_cred.dcr_cred;
6499 ASSERT(s_cr != NULL);
6501 if ((cr = CRED()) == NULL ||
6502 s_cr->cr_zone->zone_id !=
6503 cr->cr_zone->zone_id)
6509 if (now - state->dts_alive > dtrace_deadman_timeout) {
6511 * We seem to be dead. Unless we (a) have kernel
6512 * destructive permissions (b) have explicitly enabled
6513 * destructive actions and (c) destructive actions have
6514 * not been disabled, we're going to transition into
6515 * the KILLED state, from which no further processing
6516 * on this state will be performed.
6518 if (!dtrace_priv_kernel_destructive(state) ||
6519 !state->dts_cred.dcr_destructive ||
6520 dtrace_destructive_disallow) {
6521 void *activity = &state->dts_activity;
6522 dtrace_activity_t current;
6525 current = state->dts_activity;
6526 } while (dtrace_cas32(activity, current,
6527 DTRACE_ACTIVITY_KILLED) != current);
6533 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6534 ecb->dte_alignment, state, &mstate)) < 0)
6537 tomax = buf->dtb_tomax;
6538 ASSERT(tomax != NULL);
6540 if (ecb->dte_size != 0) {
6541 dtrace_rechdr_t dtrh;
6542 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6543 mstate.dtms_timestamp = dtrace_gethrtime();
6544 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6546 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6547 dtrh.dtrh_epid = ecb->dte_epid;
6548 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6549 mstate.dtms_timestamp);
6550 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6553 mstate.dtms_epid = ecb->dte_epid;
6554 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6556 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6557 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6559 mstate.dtms_access = 0;
6562 dtrace_difo_t *dp = pred->dtp_difo;
6565 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6567 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6568 dtrace_cacheid_t cid = probe->dtpr_predcache;
6570 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6572 * Update the predicate cache...
6574 ASSERT(cid == pred->dtp_cacheid);
6575 curthread->t_predcache = cid;
6582 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6583 act != NULL; act = act->dta_next) {
6586 dtrace_recdesc_t *rec = &act->dta_rec;
6588 size = rec->dtrd_size;
6589 valoffs = offs + rec->dtrd_offset;
6591 if (DTRACEACT_ISAGG(act->dta_kind)) {
6593 dtrace_aggregation_t *agg;
6595 agg = (dtrace_aggregation_t *)act;
6597 if ((dp = act->dta_difo) != NULL)
6598 v = dtrace_dif_emulate(dp,
6599 &mstate, vstate, state);
6601 if (*flags & CPU_DTRACE_ERROR)
6605 * Note that we always pass the expression
6606 * value from the previous iteration of the
6607 * action loop. This value will only be used
6608 * if there is an expression argument to the
6609 * aggregating action, denoted by the
6610 * dtag_hasarg field.
6612 dtrace_aggregate(agg, buf,
6613 offs, aggbuf, v, val);
6617 switch (act->dta_kind) {
6618 case DTRACEACT_STOP:
6619 if (dtrace_priv_proc_destructive(state))
6620 dtrace_action_stop();
6623 case DTRACEACT_BREAKPOINT:
6624 if (dtrace_priv_kernel_destructive(state))
6625 dtrace_action_breakpoint(ecb);
6628 case DTRACEACT_PANIC:
6629 if (dtrace_priv_kernel_destructive(state))
6630 dtrace_action_panic(ecb);
6633 case DTRACEACT_STACK:
6634 if (!dtrace_priv_kernel(state))
6637 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6638 size / sizeof (pc_t), probe->dtpr_aframes,
6639 DTRACE_ANCHORED(probe) ? NULL :
6643 case DTRACEACT_JSTACK:
6644 case DTRACEACT_USTACK:
6645 if (!dtrace_priv_proc(state))
6649 * See comment in DIF_VAR_PID.
6651 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6653 int depth = DTRACE_USTACK_NFRAMES(
6656 dtrace_bzero((void *)(tomax + valoffs),
6657 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6658 + depth * sizeof (uint64_t));
6663 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6664 curproc->p_dtrace_helpers != NULL) {
6666 * This is the slow path -- we have
6667 * allocated string space, and we're
6668 * getting the stack of a process that
6669 * has helpers. Call into a separate
6670 * routine to perform this processing.
6672 dtrace_action_ustack(&mstate, state,
6673 (uint64_t *)(tomax + valoffs),
6678 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6679 dtrace_getupcstack((uint64_t *)
6681 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6682 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6692 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6694 if (*flags & CPU_DTRACE_ERROR)
6697 switch (act->dta_kind) {
6698 case DTRACEACT_SPECULATE: {
6699 dtrace_rechdr_t *dtrh;
6701 ASSERT(buf == &state->dts_buffer[cpuid]);
6702 buf = dtrace_speculation_buffer(state,
6706 *flags |= CPU_DTRACE_DROP;
6710 offs = dtrace_buffer_reserve(buf,
6711 ecb->dte_needed, ecb->dte_alignment,
6715 *flags |= CPU_DTRACE_DROP;
6719 tomax = buf->dtb_tomax;
6720 ASSERT(tomax != NULL);
6722 if (ecb->dte_size == 0)
6725 ASSERT3U(ecb->dte_size, >=,
6726 sizeof (dtrace_rechdr_t));
6727 dtrh = ((void *)(tomax + offs));
6728 dtrh->dtrh_epid = ecb->dte_epid;
6730 * When the speculation is committed, all of
6731 * the records in the speculative buffer will
6732 * have their timestamps set to the commit
6733 * time. Until then, it is set to a sentinel
6734 * value, for debugability.
6736 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6740 case DTRACEACT_PRINTM: {
6741 /* The DIF returns a 'memref'. */
6742 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6744 /* Get the size from the memref. */
6748 * Check if the size exceeds the allocated
6751 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6753 *flags |= CPU_DTRACE_DROP;
6757 /* Store the size in the buffer first. */
6758 DTRACE_STORE(uintptr_t, tomax,
6762 * Offset the buffer address to the start
6765 valoffs += sizeof(uintptr_t);
6768 * Reset to the memory address rather than
6769 * the memref array, then let the BYREF
6770 * code below do the work to store the
6771 * memory data in the buffer.
6777 case DTRACEACT_PRINTT: {
6778 /* The DIF returns a 'typeref'. */
6779 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6784 * Get the type string length and round it
6785 * up so that the data that follows is
6786 * aligned for easy access.
6788 size_t typs = strlen((char *) typeref[2]) + 1;
6789 typs = roundup(typs, sizeof(uintptr_t));
6792 *Get the size from the typeref using the
6793 * number of elements and the type size.
6795 size = typeref[1] * typeref[3];
6798 * Check if the size exceeds the allocated
6801 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6803 *flags |= CPU_DTRACE_DROP;
6807 /* Store the size in the buffer first. */
6808 DTRACE_STORE(uintptr_t, tomax,
6810 valoffs += sizeof(uintptr_t);
6812 /* Store the type size in the buffer. */
6813 DTRACE_STORE(uintptr_t, tomax,
6814 valoffs, typeref[3]);
6815 valoffs += sizeof(uintptr_t);
6819 for (s = 0; s < typs; s++) {
6821 c = dtrace_load8(val++);
6823 DTRACE_STORE(uint8_t, tomax,
6828 * Reset to the memory address rather than
6829 * the typeref array, then let the BYREF
6830 * code below do the work to store the
6831 * memory data in the buffer.
6837 case DTRACEACT_CHILL:
6838 if (dtrace_priv_kernel_destructive(state))
6839 dtrace_action_chill(&mstate, val);
6842 case DTRACEACT_RAISE:
6843 if (dtrace_priv_proc_destructive(state))
6844 dtrace_action_raise(val);
6847 case DTRACEACT_COMMIT:
6851 * We need to commit our buffer state.
6854 buf->dtb_offset = offs + ecb->dte_size;
6855 buf = &state->dts_buffer[cpuid];
6856 dtrace_speculation_commit(state, cpuid, val);
6860 case DTRACEACT_DISCARD:
6861 dtrace_speculation_discard(state, cpuid, val);
6864 case DTRACEACT_DIFEXPR:
6865 case DTRACEACT_LIBACT:
6866 case DTRACEACT_PRINTF:
6867 case DTRACEACT_PRINTA:
6868 case DTRACEACT_SYSTEM:
6869 case DTRACEACT_FREOPEN:
6870 case DTRACEACT_TRACEMEM:
6873 case DTRACEACT_TRACEMEM_DYNSIZE:
6879 if (!dtrace_priv_kernel(state))
6883 case DTRACEACT_USYM:
6884 case DTRACEACT_UMOD:
6885 case DTRACEACT_UADDR: {
6887 struct pid *pid = curthread->t_procp->p_pidp;
6890 if (!dtrace_priv_proc(state))
6893 DTRACE_STORE(uint64_t, tomax,
6895 valoffs, (uint64_t)pid->pid_id);
6897 valoffs, (uint64_t) curproc->p_pid);
6899 DTRACE_STORE(uint64_t, tomax,
6900 valoffs + sizeof (uint64_t), val);
6905 case DTRACEACT_EXIT: {
6907 * For the exit action, we are going to attempt
6908 * to atomically set our activity to be
6909 * draining. If this fails (either because
6910 * another CPU has beat us to the exit action,
6911 * or because our current activity is something
6912 * other than ACTIVE or WARMUP), we will
6913 * continue. This assures that the exit action
6914 * can be successfully recorded at most once
6915 * when we're in the ACTIVE state. If we're
6916 * encountering the exit() action while in
6917 * COOLDOWN, however, we want to honor the new
6918 * status code. (We know that we're the only
6919 * thread in COOLDOWN, so there is no race.)
6921 void *activity = &state->dts_activity;
6922 dtrace_activity_t current = state->dts_activity;
6924 if (current == DTRACE_ACTIVITY_COOLDOWN)
6927 if (current != DTRACE_ACTIVITY_WARMUP)
6928 current = DTRACE_ACTIVITY_ACTIVE;
6930 if (dtrace_cas32(activity, current,
6931 DTRACE_ACTIVITY_DRAINING) != current) {
6932 *flags |= CPU_DTRACE_DROP;
6943 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6944 uintptr_t end = valoffs + size;
6946 if (tracememsize != 0 &&
6947 valoffs + tracememsize < end) {
6948 end = valoffs + tracememsize;
6952 if (!dtrace_vcanload((void *)(uintptr_t)val,
6953 &dp->dtdo_rtype, &mstate, vstate))
6957 * If this is a string, we're going to only
6958 * load until we find the zero byte -- after
6959 * which we'll store zero bytes.
6961 if (dp->dtdo_rtype.dtdt_kind ==
6964 int intuple = act->dta_intuple;
6967 for (s = 0; s < size; s++) {
6969 c = dtrace_load8(val++);
6971 DTRACE_STORE(uint8_t, tomax,
6974 if (c == '\0' && intuple)
6981 while (valoffs < end) {
6982 DTRACE_STORE(uint8_t, tomax, valoffs++,
6983 dtrace_load8(val++));
6993 case sizeof (uint8_t):
6994 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6996 case sizeof (uint16_t):
6997 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6999 case sizeof (uint32_t):
7000 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7002 case sizeof (uint64_t):
7003 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7007 * Any other size should have been returned by
7008 * reference, not by value.
7015 if (*flags & CPU_DTRACE_DROP)
7018 if (*flags & CPU_DTRACE_FAULT) {
7020 dtrace_action_t *err;
7024 if (probe->dtpr_id == dtrace_probeid_error) {
7026 * There's nothing we can do -- we had an
7027 * error on the error probe. We bump an
7028 * error counter to at least indicate that
7029 * this condition happened.
7031 dtrace_error(&state->dts_dblerrors);
7037 * Before recursing on dtrace_probe(), we
7038 * need to explicitly clear out our start
7039 * time to prevent it from being accumulated
7040 * into t_dtrace_vtime.
7042 curthread->t_dtrace_start = 0;
7046 * Iterate over the actions to figure out which action
7047 * we were processing when we experienced the error.
7048 * Note that act points _past_ the faulting action; if
7049 * act is ecb->dte_action, the fault was in the
7050 * predicate, if it's ecb->dte_action->dta_next it's
7051 * in action #1, and so on.
7053 for (err = ecb->dte_action, ndx = 0;
7054 err != act; err = err->dta_next, ndx++)
7057 dtrace_probe_error(state, ecb->dte_epid, ndx,
7058 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7059 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7060 cpu_core[cpuid].cpuc_dtrace_illval);
7066 buf->dtb_offset = offs + ecb->dte_size;
7070 curthread->t_dtrace_start = dtrace_gethrtime();
7072 dtrace_interrupt_enable(cookie);
7076 * DTrace Probe Hashing Functions
7078 * The functions in this section (and indeed, the functions in remaining
7079 * sections) are not _called_ from probe context. (Any exceptions to this are
7080 * marked with a "Note:".) Rather, they are called from elsewhere in the
7081 * DTrace framework to look-up probes in, add probes to and remove probes from
7082 * the DTrace probe hashes. (Each probe is hashed by each element of the
7083 * probe tuple -- allowing for fast lookups, regardless of what was
7087 dtrace_hash_str(const char *p)
7093 hval = (hval << 4) + *p++;
7094 if ((g = (hval & 0xf0000000)) != 0)
7101 static dtrace_hash_t *
7102 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7104 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7106 hash->dth_stroffs = stroffs;
7107 hash->dth_nextoffs = nextoffs;
7108 hash->dth_prevoffs = prevoffs;
7111 hash->dth_mask = hash->dth_size - 1;
7113 hash->dth_tab = kmem_zalloc(hash->dth_size *
7114 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7120 dtrace_hash_destroy(dtrace_hash_t *hash)
7125 for (i = 0; i < hash->dth_size; i++)
7126 ASSERT(hash->dth_tab[i] == NULL);
7129 kmem_free(hash->dth_tab,
7130 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7131 kmem_free(hash, sizeof (dtrace_hash_t));
7135 dtrace_hash_resize(dtrace_hash_t *hash)
7137 int size = hash->dth_size, i, ndx;
7138 int new_size = hash->dth_size << 1;
7139 int new_mask = new_size - 1;
7140 dtrace_hashbucket_t **new_tab, *bucket, *next;
7142 ASSERT((new_size & new_mask) == 0);
7144 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7146 for (i = 0; i < size; i++) {
7147 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7148 dtrace_probe_t *probe = bucket->dthb_chain;
7150 ASSERT(probe != NULL);
7151 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7153 next = bucket->dthb_next;
7154 bucket->dthb_next = new_tab[ndx];
7155 new_tab[ndx] = bucket;
7159 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7160 hash->dth_tab = new_tab;
7161 hash->dth_size = new_size;
7162 hash->dth_mask = new_mask;
7166 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7168 int hashval = DTRACE_HASHSTR(hash, new);
7169 int ndx = hashval & hash->dth_mask;
7170 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7171 dtrace_probe_t **nextp, **prevp;
7173 for (; bucket != NULL; bucket = bucket->dthb_next) {
7174 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7178 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7179 dtrace_hash_resize(hash);
7180 dtrace_hash_add(hash, new);
7184 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7185 bucket->dthb_next = hash->dth_tab[ndx];
7186 hash->dth_tab[ndx] = bucket;
7187 hash->dth_nbuckets++;
7190 nextp = DTRACE_HASHNEXT(hash, new);
7191 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7192 *nextp = bucket->dthb_chain;
7194 if (bucket->dthb_chain != NULL) {
7195 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7196 ASSERT(*prevp == NULL);
7200 bucket->dthb_chain = new;
7204 static dtrace_probe_t *
7205 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7207 int hashval = DTRACE_HASHSTR(hash, template);
7208 int ndx = hashval & hash->dth_mask;
7209 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7211 for (; bucket != NULL; bucket = bucket->dthb_next) {
7212 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7213 return (bucket->dthb_chain);
7220 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7222 int hashval = DTRACE_HASHSTR(hash, template);
7223 int ndx = hashval & hash->dth_mask;
7224 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7226 for (; bucket != NULL; bucket = bucket->dthb_next) {
7227 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7228 return (bucket->dthb_len);
7235 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7237 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7238 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7240 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7241 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7244 * Find the bucket that we're removing this probe from.
7246 for (; bucket != NULL; bucket = bucket->dthb_next) {
7247 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7251 ASSERT(bucket != NULL);
7253 if (*prevp == NULL) {
7254 if (*nextp == NULL) {
7256 * The removed probe was the only probe on this
7257 * bucket; we need to remove the bucket.
7259 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7261 ASSERT(bucket->dthb_chain == probe);
7265 hash->dth_tab[ndx] = bucket->dthb_next;
7267 while (b->dthb_next != bucket)
7269 b->dthb_next = bucket->dthb_next;
7272 ASSERT(hash->dth_nbuckets > 0);
7273 hash->dth_nbuckets--;
7274 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7278 bucket->dthb_chain = *nextp;
7280 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7284 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7288 * DTrace Utility Functions
7290 * These are random utility functions that are _not_ called from probe context.
7293 dtrace_badattr(const dtrace_attribute_t *a)
7295 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7296 a->dtat_data > DTRACE_STABILITY_MAX ||
7297 a->dtat_class > DTRACE_CLASS_MAX);
7301 * Return a duplicate copy of a string. If the specified string is NULL,
7302 * this function returns a zero-length string.
7305 dtrace_strdup(const char *str)
7307 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7310 (void) strcpy(new, str);
7315 #define DTRACE_ISALPHA(c) \
7316 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7319 dtrace_badname(const char *s)
7323 if (s == NULL || (c = *s++) == '\0')
7326 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7329 while ((c = *s++) != '\0') {
7330 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7331 c != '-' && c != '_' && c != '.' && c != '`')
7339 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7344 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7346 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7348 priv = DTRACE_PRIV_ALL;
7350 *uidp = crgetuid(cr);
7351 *zoneidp = crgetzoneid(cr);
7354 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7355 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7356 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7357 priv |= DTRACE_PRIV_USER;
7358 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7359 priv |= DTRACE_PRIV_PROC;
7360 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7361 priv |= DTRACE_PRIV_OWNER;
7362 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7363 priv |= DTRACE_PRIV_ZONEOWNER;
7366 priv = DTRACE_PRIV_ALL;
7372 #ifdef DTRACE_ERRDEBUG
7374 dtrace_errdebug(const char *str)
7376 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7379 mutex_enter(&dtrace_errlock);
7380 dtrace_errlast = str;
7381 dtrace_errthread = curthread;
7383 while (occupied++ < DTRACE_ERRHASHSZ) {
7384 if (dtrace_errhash[hval].dter_msg == str) {
7385 dtrace_errhash[hval].dter_count++;
7389 if (dtrace_errhash[hval].dter_msg != NULL) {
7390 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7394 dtrace_errhash[hval].dter_msg = str;
7395 dtrace_errhash[hval].dter_count = 1;
7399 panic("dtrace: undersized error hash");
7401 mutex_exit(&dtrace_errlock);
7406 * DTrace Matching Functions
7408 * These functions are used to match groups of probes, given some elements of
7409 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7412 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7415 if (priv != DTRACE_PRIV_ALL) {
7416 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7417 uint32_t match = priv & ppriv;
7420 * No PRIV_DTRACE_* privileges...
7422 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7423 DTRACE_PRIV_KERNEL)) == 0)
7427 * No matching bits, but there were bits to match...
7429 if (match == 0 && ppriv != 0)
7433 * Need to have permissions to the process, but don't...
7435 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7436 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7441 * Need to be in the same zone unless we possess the
7442 * privilege to examine all zones.
7444 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7445 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7454 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7455 * consists of input pattern strings and an ops-vector to evaluate them.
7456 * This function returns >0 for match, 0 for no match, and <0 for error.
7459 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7460 uint32_t priv, uid_t uid, zoneid_t zoneid)
7462 dtrace_provider_t *pvp = prp->dtpr_provider;
7465 if (pvp->dtpv_defunct)
7468 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7471 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7474 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7477 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7480 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7487 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7488 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7489 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7490 * In addition, all of the recursion cases except for '*' matching have been
7491 * unwound. For '*', we still implement recursive evaluation, but a depth
7492 * counter is maintained and matching is aborted if we recurse too deep.
7493 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7496 dtrace_match_glob(const char *s, const char *p, int depth)
7502 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7506 s = ""; /* treat NULL as empty string */
7515 if ((c = *p++) == '\0')
7516 return (s1 == '\0');
7520 int ok = 0, notflag = 0;
7531 if ((c = *p++) == '\0')
7535 if (c == '-' && lc != '\0' && *p != ']') {
7536 if ((c = *p++) == '\0')
7538 if (c == '\\' && (c = *p++) == '\0')
7542 if (s1 < lc || s1 > c)
7546 } else if (lc <= s1 && s1 <= c)
7549 } else if (c == '\\' && (c = *p++) == '\0')
7552 lc = c; /* save left-hand 'c' for next iteration */
7562 if ((c = *p++) == '\0')
7574 if ((c = *p++) == '\0')
7590 p++; /* consecutive *'s are identical to a single one */
7595 for (s = olds; *s != '\0'; s++) {
7596 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7606 dtrace_match_string(const char *s, const char *p, int depth)
7608 return (s != NULL && strcmp(s, p) == 0);
7613 dtrace_match_nul(const char *s, const char *p, int depth)
7615 return (1); /* always match the empty pattern */
7620 dtrace_match_nonzero(const char *s, const char *p, int depth)
7622 return (s != NULL && s[0] != '\0');
7626 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7627 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7629 dtrace_probe_t template, *probe;
7630 dtrace_hash_t *hash = NULL;
7631 int len, best = INT_MAX, nmatched = 0;
7634 ASSERT(MUTEX_HELD(&dtrace_lock));
7637 * If the probe ID is specified in the key, just lookup by ID and
7638 * invoke the match callback once if a matching probe is found.
7640 if (pkp->dtpk_id != DTRACE_IDNONE) {
7641 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7642 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7643 (void) (*matched)(probe, arg);
7649 template.dtpr_mod = (char *)pkp->dtpk_mod;
7650 template.dtpr_func = (char *)pkp->dtpk_func;
7651 template.dtpr_name = (char *)pkp->dtpk_name;
7654 * We want to find the most distinct of the module name, function
7655 * name, and name. So for each one that is not a glob pattern or
7656 * empty string, we perform a lookup in the corresponding hash and
7657 * use the hash table with the fewest collisions to do our search.
7659 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7660 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7662 hash = dtrace_bymod;
7665 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7666 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7668 hash = dtrace_byfunc;
7671 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7672 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7674 hash = dtrace_byname;
7678 * If we did not select a hash table, iterate over every probe and
7679 * invoke our callback for each one that matches our input probe key.
7682 for (i = 0; i < dtrace_nprobes; i++) {
7683 if ((probe = dtrace_probes[i]) == NULL ||
7684 dtrace_match_probe(probe, pkp, priv, uid,
7690 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7698 * If we selected a hash table, iterate over each probe of the same key
7699 * name and invoke the callback for every probe that matches the other
7700 * attributes of our input probe key.
7702 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7703 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7705 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7710 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7718 * Return the function pointer dtrace_probecmp() should use to compare the
7719 * specified pattern with a string. For NULL or empty patterns, we select
7720 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7721 * For non-empty non-glob strings, we use dtrace_match_string().
7723 static dtrace_probekey_f *
7724 dtrace_probekey_func(const char *p)
7728 if (p == NULL || *p == '\0')
7729 return (&dtrace_match_nul);
7731 while ((c = *p++) != '\0') {
7732 if (c == '[' || c == '?' || c == '*' || c == '\\')
7733 return (&dtrace_match_glob);
7736 return (&dtrace_match_string);
7740 * Build a probe comparison key for use with dtrace_match_probe() from the
7741 * given probe description. By convention, a null key only matches anchored
7742 * probes: if each field is the empty string, reset dtpk_fmatch to
7743 * dtrace_match_nonzero().
7746 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7748 pkp->dtpk_prov = pdp->dtpd_provider;
7749 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7751 pkp->dtpk_mod = pdp->dtpd_mod;
7752 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7754 pkp->dtpk_func = pdp->dtpd_func;
7755 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7757 pkp->dtpk_name = pdp->dtpd_name;
7758 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7760 pkp->dtpk_id = pdp->dtpd_id;
7762 if (pkp->dtpk_id == DTRACE_IDNONE &&
7763 pkp->dtpk_pmatch == &dtrace_match_nul &&
7764 pkp->dtpk_mmatch == &dtrace_match_nul &&
7765 pkp->dtpk_fmatch == &dtrace_match_nul &&
7766 pkp->dtpk_nmatch == &dtrace_match_nul)
7767 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7771 * DTrace Provider-to-Framework API Functions
7773 * These functions implement much of the Provider-to-Framework API, as
7774 * described in <sys/dtrace.h>. The parts of the API not in this section are
7775 * the functions in the API for probe management (found below), and
7776 * dtrace_probe() itself (found above).
7780 * Register the calling provider with the DTrace framework. This should
7781 * generally be called by DTrace providers in their attach(9E) entry point.
7784 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7785 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7787 dtrace_provider_t *provider;
7789 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7790 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7791 "arguments", name ? name : "<NULL>");
7795 if (name[0] == '\0' || dtrace_badname(name)) {
7796 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7797 "provider name", name);
7801 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7802 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7803 pops->dtps_destroy == NULL ||
7804 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7805 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7806 "provider ops", name);
7810 if (dtrace_badattr(&pap->dtpa_provider) ||
7811 dtrace_badattr(&pap->dtpa_mod) ||
7812 dtrace_badattr(&pap->dtpa_func) ||
7813 dtrace_badattr(&pap->dtpa_name) ||
7814 dtrace_badattr(&pap->dtpa_args)) {
7815 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7816 "provider attributes", name);
7820 if (priv & ~DTRACE_PRIV_ALL) {
7821 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7822 "privilege attributes", name);
7826 if ((priv & DTRACE_PRIV_KERNEL) &&
7827 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7828 pops->dtps_usermode == NULL) {
7829 cmn_err(CE_WARN, "failed to register provider '%s': need "
7830 "dtps_usermode() op for given privilege attributes", name);
7834 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7835 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7836 (void) strcpy(provider->dtpv_name, name);
7838 provider->dtpv_attr = *pap;
7839 provider->dtpv_priv.dtpp_flags = priv;
7841 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7842 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7844 provider->dtpv_pops = *pops;
7846 if (pops->dtps_provide == NULL) {
7847 ASSERT(pops->dtps_provide_module != NULL);
7848 provider->dtpv_pops.dtps_provide =
7849 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7852 if (pops->dtps_provide_module == NULL) {
7853 ASSERT(pops->dtps_provide != NULL);
7854 provider->dtpv_pops.dtps_provide_module =
7855 (void (*)(void *, modctl_t *))dtrace_nullop;
7858 if (pops->dtps_suspend == NULL) {
7859 ASSERT(pops->dtps_resume == NULL);
7860 provider->dtpv_pops.dtps_suspend =
7861 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7862 provider->dtpv_pops.dtps_resume =
7863 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7866 provider->dtpv_arg = arg;
7867 *idp = (dtrace_provider_id_t)provider;
7869 if (pops == &dtrace_provider_ops) {
7870 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7871 ASSERT(MUTEX_HELD(&dtrace_lock));
7872 ASSERT(dtrace_anon.dta_enabling == NULL);
7875 * We make sure that the DTrace provider is at the head of
7876 * the provider chain.
7878 provider->dtpv_next = dtrace_provider;
7879 dtrace_provider = provider;
7883 mutex_enter(&dtrace_provider_lock);
7884 mutex_enter(&dtrace_lock);
7887 * If there is at least one provider registered, we'll add this
7888 * provider after the first provider.
7890 if (dtrace_provider != NULL) {
7891 provider->dtpv_next = dtrace_provider->dtpv_next;
7892 dtrace_provider->dtpv_next = provider;
7894 dtrace_provider = provider;
7897 if (dtrace_retained != NULL) {
7898 dtrace_enabling_provide(provider);
7901 * Now we need to call dtrace_enabling_matchall() -- which
7902 * will acquire cpu_lock and dtrace_lock. We therefore need
7903 * to drop all of our locks before calling into it...
7905 mutex_exit(&dtrace_lock);
7906 mutex_exit(&dtrace_provider_lock);
7907 dtrace_enabling_matchall();
7912 mutex_exit(&dtrace_lock);
7913 mutex_exit(&dtrace_provider_lock);
7919 * Unregister the specified provider from the DTrace framework. This should
7920 * generally be called by DTrace providers in their detach(9E) entry point.
7923 dtrace_unregister(dtrace_provider_id_t id)
7925 dtrace_provider_t *old = (dtrace_provider_t *)id;
7926 dtrace_provider_t *prev = NULL;
7927 int i, self = 0, noreap = 0;
7928 dtrace_probe_t *probe, *first = NULL;
7930 if (old->dtpv_pops.dtps_enable ==
7931 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7933 * If DTrace itself is the provider, we're called with locks
7936 ASSERT(old == dtrace_provider);
7938 ASSERT(dtrace_devi != NULL);
7940 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7941 ASSERT(MUTEX_HELD(&dtrace_lock));
7944 if (dtrace_provider->dtpv_next != NULL) {
7946 * There's another provider here; return failure.
7951 mutex_enter(&dtrace_provider_lock);
7953 mutex_enter(&mod_lock);
7955 mutex_enter(&dtrace_lock);
7959 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7960 * probes, we refuse to let providers slither away, unless this
7961 * provider has already been explicitly invalidated.
7963 if (!old->dtpv_defunct &&
7964 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7965 dtrace_anon.dta_state->dts_necbs > 0))) {
7967 mutex_exit(&dtrace_lock);
7969 mutex_exit(&mod_lock);
7971 mutex_exit(&dtrace_provider_lock);
7977 * Attempt to destroy the probes associated with this provider.
7979 for (i = 0; i < dtrace_nprobes; i++) {
7980 if ((probe = dtrace_probes[i]) == NULL)
7983 if (probe->dtpr_provider != old)
7986 if (probe->dtpr_ecb == NULL)
7990 * If we are trying to unregister a defunct provider, and the
7991 * provider was made defunct within the interval dictated by
7992 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7993 * attempt to reap our enablings. To denote that the provider
7994 * should reattempt to unregister itself at some point in the
7995 * future, we will return a differentiable error code (EAGAIN
7996 * instead of EBUSY) in this case.
7998 if (dtrace_gethrtime() - old->dtpv_defunct >
7999 dtrace_unregister_defunct_reap)
8003 mutex_exit(&dtrace_lock);
8005 mutex_exit(&mod_lock);
8007 mutex_exit(&dtrace_provider_lock);
8013 (void) taskq_dispatch(dtrace_taskq,
8014 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8020 * All of the probes for this provider are disabled; we can safely
8021 * remove all of them from their hash chains and from the probe array.
8023 for (i = 0; i < dtrace_nprobes; i++) {
8024 if ((probe = dtrace_probes[i]) == NULL)
8027 if (probe->dtpr_provider != old)
8030 dtrace_probes[i] = NULL;
8032 dtrace_hash_remove(dtrace_bymod, probe);
8033 dtrace_hash_remove(dtrace_byfunc, probe);
8034 dtrace_hash_remove(dtrace_byname, probe);
8036 if (first == NULL) {
8038 probe->dtpr_nextmod = NULL;
8040 probe->dtpr_nextmod = first;
8046 * The provider's probes have been removed from the hash chains and
8047 * from the probe array. Now issue a dtrace_sync() to be sure that
8048 * everyone has cleared out from any probe array processing.
8052 for (probe = first; probe != NULL; probe = first) {
8053 first = probe->dtpr_nextmod;
8055 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8057 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8058 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8059 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8061 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8063 free_unr(dtrace_arena, probe->dtpr_id);
8065 kmem_free(probe, sizeof (dtrace_probe_t));
8068 if ((prev = dtrace_provider) == old) {
8070 ASSERT(self || dtrace_devi == NULL);
8071 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8073 dtrace_provider = old->dtpv_next;
8075 while (prev != NULL && prev->dtpv_next != old)
8076 prev = prev->dtpv_next;
8079 panic("attempt to unregister non-existent "
8080 "dtrace provider %p\n", (void *)id);
8083 prev->dtpv_next = old->dtpv_next;
8087 mutex_exit(&dtrace_lock);
8089 mutex_exit(&mod_lock);
8091 mutex_exit(&dtrace_provider_lock);
8094 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8095 kmem_free(old, sizeof (dtrace_provider_t));
8101 * Invalidate the specified provider. All subsequent probe lookups for the
8102 * specified provider will fail, but its probes will not be removed.
8105 dtrace_invalidate(dtrace_provider_id_t id)
8107 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8109 ASSERT(pvp->dtpv_pops.dtps_enable !=
8110 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8112 mutex_enter(&dtrace_provider_lock);
8113 mutex_enter(&dtrace_lock);
8115 pvp->dtpv_defunct = dtrace_gethrtime();
8117 mutex_exit(&dtrace_lock);
8118 mutex_exit(&dtrace_provider_lock);
8122 * Indicate whether or not DTrace has attached.
8125 dtrace_attached(void)
8128 * dtrace_provider will be non-NULL iff the DTrace driver has
8129 * attached. (It's non-NULL because DTrace is always itself a
8132 return (dtrace_provider != NULL);
8136 * Remove all the unenabled probes for the given provider. This function is
8137 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8138 * -- just as many of its associated probes as it can.
8141 dtrace_condense(dtrace_provider_id_t id)
8143 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8145 dtrace_probe_t *probe;
8148 * Make sure this isn't the dtrace provider itself.
8150 ASSERT(prov->dtpv_pops.dtps_enable !=
8151 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8153 mutex_enter(&dtrace_provider_lock);
8154 mutex_enter(&dtrace_lock);
8157 * Attempt to destroy the probes associated with this provider.
8159 for (i = 0; i < dtrace_nprobes; i++) {
8160 if ((probe = dtrace_probes[i]) == NULL)
8163 if (probe->dtpr_provider != prov)
8166 if (probe->dtpr_ecb != NULL)
8169 dtrace_probes[i] = NULL;
8171 dtrace_hash_remove(dtrace_bymod, probe);
8172 dtrace_hash_remove(dtrace_byfunc, probe);
8173 dtrace_hash_remove(dtrace_byname, probe);
8175 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8177 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8178 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8179 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8180 kmem_free(probe, sizeof (dtrace_probe_t));
8182 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8184 free_unr(dtrace_arena, i + 1);
8188 mutex_exit(&dtrace_lock);
8189 mutex_exit(&dtrace_provider_lock);
8195 * DTrace Probe Management Functions
8197 * The functions in this section perform the DTrace probe management,
8198 * including functions to create probes, look-up probes, and call into the
8199 * providers to request that probes be provided. Some of these functions are
8200 * in the Provider-to-Framework API; these functions can be identified by the
8201 * fact that they are not declared "static".
8205 * Create a probe with the specified module name, function name, and name.
8208 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8209 const char *func, const char *name, int aframes, void *arg)
8211 dtrace_probe_t *probe, **probes;
8212 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8215 if (provider == dtrace_provider) {
8216 ASSERT(MUTEX_HELD(&dtrace_lock));
8218 mutex_enter(&dtrace_lock);
8222 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8223 VM_BESTFIT | VM_SLEEP);
8225 id = alloc_unr(dtrace_arena);
8227 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8229 probe->dtpr_id = id;
8230 probe->dtpr_gen = dtrace_probegen++;
8231 probe->dtpr_mod = dtrace_strdup(mod);
8232 probe->dtpr_func = dtrace_strdup(func);
8233 probe->dtpr_name = dtrace_strdup(name);
8234 probe->dtpr_arg = arg;
8235 probe->dtpr_aframes = aframes;
8236 probe->dtpr_provider = provider;
8238 dtrace_hash_add(dtrace_bymod, probe);
8239 dtrace_hash_add(dtrace_byfunc, probe);
8240 dtrace_hash_add(dtrace_byname, probe);
8242 if (id - 1 >= dtrace_nprobes) {
8243 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8244 size_t nsize = osize << 1;
8248 ASSERT(dtrace_probes == NULL);
8249 nsize = sizeof (dtrace_probe_t *);
8252 probes = kmem_zalloc(nsize, KM_SLEEP);
8254 if (dtrace_probes == NULL) {
8256 dtrace_probes = probes;
8259 dtrace_probe_t **oprobes = dtrace_probes;
8261 bcopy(oprobes, probes, osize);
8262 dtrace_membar_producer();
8263 dtrace_probes = probes;
8268 * All CPUs are now seeing the new probes array; we can
8269 * safely free the old array.
8271 kmem_free(oprobes, osize);
8272 dtrace_nprobes <<= 1;
8275 ASSERT(id - 1 < dtrace_nprobes);
8278 ASSERT(dtrace_probes[id - 1] == NULL);
8279 dtrace_probes[id - 1] = probe;
8281 if (provider != dtrace_provider)
8282 mutex_exit(&dtrace_lock);
8287 static dtrace_probe_t *
8288 dtrace_probe_lookup_id(dtrace_id_t id)
8290 ASSERT(MUTEX_HELD(&dtrace_lock));
8292 if (id == 0 || id > dtrace_nprobes)
8295 return (dtrace_probes[id - 1]);
8299 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8301 *((dtrace_id_t *)arg) = probe->dtpr_id;
8303 return (DTRACE_MATCH_DONE);
8307 * Look up a probe based on provider and one or more of module name, function
8308 * name and probe name.
8311 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8312 char *func, char *name)
8314 dtrace_probekey_t pkey;
8318 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8319 pkey.dtpk_pmatch = &dtrace_match_string;
8320 pkey.dtpk_mod = mod;
8321 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8322 pkey.dtpk_func = func;
8323 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8324 pkey.dtpk_name = name;
8325 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8326 pkey.dtpk_id = DTRACE_IDNONE;
8328 mutex_enter(&dtrace_lock);
8329 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8330 dtrace_probe_lookup_match, &id);
8331 mutex_exit(&dtrace_lock);
8333 ASSERT(match == 1 || match == 0);
8334 return (match ? id : 0);
8338 * Returns the probe argument associated with the specified probe.
8341 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8343 dtrace_probe_t *probe;
8346 mutex_enter(&dtrace_lock);
8348 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8349 probe->dtpr_provider == (dtrace_provider_t *)id)
8350 rval = probe->dtpr_arg;
8352 mutex_exit(&dtrace_lock);
8358 * Copy a probe into a probe description.
8361 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8363 bzero(pdp, sizeof (dtrace_probedesc_t));
8364 pdp->dtpd_id = prp->dtpr_id;
8366 (void) strncpy(pdp->dtpd_provider,
8367 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8369 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8370 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8371 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8375 * Called to indicate that a probe -- or probes -- should be provided by a
8376 * specfied provider. If the specified description is NULL, the provider will
8377 * be told to provide all of its probes. (This is done whenever a new
8378 * consumer comes along, or whenever a retained enabling is to be matched.) If
8379 * the specified description is non-NULL, the provider is given the
8380 * opportunity to dynamically provide the specified probe, allowing providers
8381 * to support the creation of probes on-the-fly. (So-called _autocreated_
8382 * probes.) If the provider is NULL, the operations will be applied to all
8383 * providers; if the provider is non-NULL the operations will only be applied
8384 * to the specified provider. The dtrace_provider_lock must be held, and the
8385 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8386 * will need to grab the dtrace_lock when it reenters the framework through
8387 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8390 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8397 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8401 prv = dtrace_provider;
8406 * First, call the blanket provide operation.
8408 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8412 * Now call the per-module provide operation. We will grab
8413 * mod_lock to prevent the list from being modified. Note
8414 * that this also prevents the mod_busy bits from changing.
8415 * (mod_busy can only be changed with mod_lock held.)
8417 mutex_enter(&mod_lock);
8421 if (ctl->mod_busy || ctl->mod_mp == NULL)
8424 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8426 } while ((ctl = ctl->mod_next) != &modules);
8428 mutex_exit(&mod_lock);
8430 } while (all && (prv = prv->dtpv_next) != NULL);
8435 * Iterate over each probe, and call the Framework-to-Provider API function
8439 dtrace_probe_foreach(uintptr_t offs)
8441 dtrace_provider_t *prov;
8442 void (*func)(void *, dtrace_id_t, void *);
8443 dtrace_probe_t *probe;
8444 dtrace_icookie_t cookie;
8448 * We disable interrupts to walk through the probe array. This is
8449 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8450 * won't see stale data.
8452 cookie = dtrace_interrupt_disable();
8454 for (i = 0; i < dtrace_nprobes; i++) {
8455 if ((probe = dtrace_probes[i]) == NULL)
8458 if (probe->dtpr_ecb == NULL) {
8460 * This probe isn't enabled -- don't call the function.
8465 prov = probe->dtpr_provider;
8466 func = *((void(**)(void *, dtrace_id_t, void *))
8467 ((uintptr_t)&prov->dtpv_pops + offs));
8469 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8472 dtrace_interrupt_enable(cookie);
8477 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8479 dtrace_probekey_t pkey;
8484 ASSERT(MUTEX_HELD(&dtrace_lock));
8485 dtrace_ecb_create_cache = NULL;
8489 * If we're passed a NULL description, we're being asked to
8490 * create an ECB with a NULL probe.
8492 (void) dtrace_ecb_create_enable(NULL, enab);
8496 dtrace_probekey(desc, &pkey);
8497 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8498 &priv, &uid, &zoneid);
8500 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8505 * DTrace Helper Provider Functions
8508 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8510 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8511 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8512 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8516 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8517 const dof_provider_t *dofprov, char *strtab)
8519 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8520 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8521 dofprov->dofpv_provattr);
8522 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8523 dofprov->dofpv_modattr);
8524 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8525 dofprov->dofpv_funcattr);
8526 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8527 dofprov->dofpv_nameattr);
8528 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8529 dofprov->dofpv_argsattr);
8533 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8535 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8536 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8537 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8538 dof_provider_t *provider;
8540 uint32_t *off, *enoff;
8544 dtrace_helper_provdesc_t dhpv;
8545 dtrace_helper_probedesc_t dhpb;
8546 dtrace_meta_t *meta = dtrace_meta_pid;
8547 dtrace_mops_t *mops = &meta->dtm_mops;
8550 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8551 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8552 provider->dofpv_strtab * dof->dofh_secsize);
8553 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8554 provider->dofpv_probes * dof->dofh_secsize);
8555 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8556 provider->dofpv_prargs * dof->dofh_secsize);
8557 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8558 provider->dofpv_proffs * dof->dofh_secsize);
8560 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8561 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8562 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8566 * See dtrace_helper_provider_validate().
8568 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8569 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8570 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8571 provider->dofpv_prenoffs * dof->dofh_secsize);
8572 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8575 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8578 * Create the provider.
8580 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8582 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8588 * Create the probes.
8590 for (i = 0; i < nprobes; i++) {
8591 probe = (dof_probe_t *)(uintptr_t)(daddr +
8592 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8594 dhpb.dthpb_mod = dhp->dofhp_mod;
8595 dhpb.dthpb_func = strtab + probe->dofpr_func;
8596 dhpb.dthpb_name = strtab + probe->dofpr_name;
8597 dhpb.dthpb_base = probe->dofpr_addr;
8598 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8599 dhpb.dthpb_noffs = probe->dofpr_noffs;
8600 if (enoff != NULL) {
8601 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8602 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8604 dhpb.dthpb_enoffs = NULL;
8605 dhpb.dthpb_nenoffs = 0;
8607 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8608 dhpb.dthpb_nargc = probe->dofpr_nargc;
8609 dhpb.dthpb_xargc = probe->dofpr_xargc;
8610 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8611 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8613 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8618 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8620 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8621 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8624 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8626 for (i = 0; i < dof->dofh_secnum; i++) {
8627 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8628 dof->dofh_secoff + i * dof->dofh_secsize);
8630 if (sec->dofs_type != DOF_SECT_PROVIDER)
8633 dtrace_helper_provide_one(dhp, sec, pid);
8637 * We may have just created probes, so we must now rematch against
8638 * any retained enablings. Note that this call will acquire both
8639 * cpu_lock and dtrace_lock; the fact that we are holding
8640 * dtrace_meta_lock now is what defines the ordering with respect to
8641 * these three locks.
8643 dtrace_enabling_matchall();
8647 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8649 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8650 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8652 dof_provider_t *provider;
8654 dtrace_helper_provdesc_t dhpv;
8655 dtrace_meta_t *meta = dtrace_meta_pid;
8656 dtrace_mops_t *mops = &meta->dtm_mops;
8658 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8659 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8660 provider->dofpv_strtab * dof->dofh_secsize);
8662 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8665 * Create the provider.
8667 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8669 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8675 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8677 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8678 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8681 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8683 for (i = 0; i < dof->dofh_secnum; i++) {
8684 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8685 dof->dofh_secoff + i * dof->dofh_secsize);
8687 if (sec->dofs_type != DOF_SECT_PROVIDER)
8690 dtrace_helper_provider_remove_one(dhp, sec, pid);
8695 * DTrace Meta Provider-to-Framework API Functions
8697 * These functions implement the Meta Provider-to-Framework API, as described
8698 * in <sys/dtrace.h>.
8701 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8702 dtrace_meta_provider_id_t *idp)
8704 dtrace_meta_t *meta;
8705 dtrace_helpers_t *help, *next;
8708 *idp = DTRACE_METAPROVNONE;
8711 * We strictly don't need the name, but we hold onto it for
8712 * debuggability. All hail error queues!
8715 cmn_err(CE_WARN, "failed to register meta-provider: "
8721 mops->dtms_create_probe == NULL ||
8722 mops->dtms_provide_pid == NULL ||
8723 mops->dtms_remove_pid == NULL) {
8724 cmn_err(CE_WARN, "failed to register meta-register %s: "
8725 "invalid ops", name);
8729 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8730 meta->dtm_mops = *mops;
8731 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8732 (void) strcpy(meta->dtm_name, name);
8733 meta->dtm_arg = arg;
8735 mutex_enter(&dtrace_meta_lock);
8736 mutex_enter(&dtrace_lock);
8738 if (dtrace_meta_pid != NULL) {
8739 mutex_exit(&dtrace_lock);
8740 mutex_exit(&dtrace_meta_lock);
8741 cmn_err(CE_WARN, "failed to register meta-register %s: "
8742 "user-land meta-provider exists", name);
8743 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8744 kmem_free(meta, sizeof (dtrace_meta_t));
8748 dtrace_meta_pid = meta;
8749 *idp = (dtrace_meta_provider_id_t)meta;
8752 * If there are providers and probes ready to go, pass them
8753 * off to the new meta provider now.
8756 help = dtrace_deferred_pid;
8757 dtrace_deferred_pid = NULL;
8759 mutex_exit(&dtrace_lock);
8761 while (help != NULL) {
8762 for (i = 0; i < help->dthps_nprovs; i++) {
8763 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8767 next = help->dthps_next;
8768 help->dthps_next = NULL;
8769 help->dthps_prev = NULL;
8770 help->dthps_deferred = 0;
8774 mutex_exit(&dtrace_meta_lock);
8780 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8782 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8784 mutex_enter(&dtrace_meta_lock);
8785 mutex_enter(&dtrace_lock);
8787 if (old == dtrace_meta_pid) {
8788 pp = &dtrace_meta_pid;
8790 panic("attempt to unregister non-existent "
8791 "dtrace meta-provider %p\n", (void *)old);
8794 if (old->dtm_count != 0) {
8795 mutex_exit(&dtrace_lock);
8796 mutex_exit(&dtrace_meta_lock);
8802 mutex_exit(&dtrace_lock);
8803 mutex_exit(&dtrace_meta_lock);
8805 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8806 kmem_free(old, sizeof (dtrace_meta_t));
8813 * DTrace DIF Object Functions
8816 dtrace_difo_err(uint_t pc, const char *format, ...)
8818 if (dtrace_err_verbose) {
8821 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8822 va_start(alist, format);
8823 (void) vuprintf(format, alist);
8827 #ifdef DTRACE_ERRDEBUG
8828 dtrace_errdebug(format);
8834 * Validate a DTrace DIF object by checking the IR instructions. The following
8835 * rules are currently enforced by dtrace_difo_validate():
8837 * 1. Each instruction must have a valid opcode
8838 * 2. Each register, string, variable, or subroutine reference must be valid
8839 * 3. No instruction can modify register %r0 (must be zero)
8840 * 4. All instruction reserved bits must be set to zero
8841 * 5. The last instruction must be a "ret" instruction
8842 * 6. All branch targets must reference a valid instruction _after_ the branch
8845 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8849 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8853 kcheckload = cr == NULL ||
8854 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8856 dp->dtdo_destructive = 0;
8858 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8859 dif_instr_t instr = dp->dtdo_buf[pc];
8861 uint_t r1 = DIF_INSTR_R1(instr);
8862 uint_t r2 = DIF_INSTR_R2(instr);
8863 uint_t rd = DIF_INSTR_RD(instr);
8864 uint_t rs = DIF_INSTR_RS(instr);
8865 uint_t label = DIF_INSTR_LABEL(instr);
8866 uint_t v = DIF_INSTR_VAR(instr);
8867 uint_t subr = DIF_INSTR_SUBR(instr);
8868 uint_t type = DIF_INSTR_TYPE(instr);
8869 uint_t op = DIF_INSTR_OP(instr);
8887 err += efunc(pc, "invalid register %u\n", r1);
8889 err += efunc(pc, "invalid register %u\n", r2);
8891 err += efunc(pc, "invalid register %u\n", rd);
8893 err += efunc(pc, "cannot write to %r0\n");
8899 err += efunc(pc, "invalid register %u\n", r1);
8901 err += efunc(pc, "non-zero reserved bits\n");
8903 err += efunc(pc, "invalid register %u\n", rd);
8905 err += efunc(pc, "cannot write to %r0\n");
8915 err += efunc(pc, "invalid register %u\n", r1);
8917 err += efunc(pc, "non-zero reserved bits\n");
8919 err += efunc(pc, "invalid register %u\n", rd);
8921 err += efunc(pc, "cannot write to %r0\n");
8923 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8924 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8934 err += efunc(pc, "invalid register %u\n", r1);
8936 err += efunc(pc, "non-zero reserved bits\n");
8938 err += efunc(pc, "invalid register %u\n", rd);
8940 err += efunc(pc, "cannot write to %r0\n");
8950 err += efunc(pc, "invalid register %u\n", r1);
8952 err += efunc(pc, "non-zero reserved bits\n");
8954 err += efunc(pc, "invalid register %u\n", rd);
8956 err += efunc(pc, "cannot write to %r0\n");
8963 err += efunc(pc, "invalid register %u\n", r1);
8965 err += efunc(pc, "non-zero reserved bits\n");
8967 err += efunc(pc, "invalid register %u\n", rd);
8969 err += efunc(pc, "cannot write to 0 address\n");
8974 err += efunc(pc, "invalid register %u\n", r1);
8976 err += efunc(pc, "invalid register %u\n", r2);
8978 err += efunc(pc, "non-zero reserved bits\n");
8982 err += efunc(pc, "invalid register %u\n", r1);
8983 if (r2 != 0 || rd != 0)
8984 err += efunc(pc, "non-zero reserved bits\n");
8997 if (label >= dp->dtdo_len) {
8998 err += efunc(pc, "invalid branch target %u\n",
9002 err += efunc(pc, "backward branch to %u\n",
9007 if (r1 != 0 || r2 != 0)
9008 err += efunc(pc, "non-zero reserved bits\n");
9010 err += efunc(pc, "invalid register %u\n", rd);
9014 case DIF_OP_FLUSHTS:
9015 if (r1 != 0 || r2 != 0 || rd != 0)
9016 err += efunc(pc, "non-zero reserved bits\n");
9019 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9020 err += efunc(pc, "invalid integer ref %u\n",
9021 DIF_INSTR_INTEGER(instr));
9024 err += efunc(pc, "invalid register %u\n", rd);
9026 err += efunc(pc, "cannot write to %r0\n");
9029 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9030 err += efunc(pc, "invalid string ref %u\n",
9031 DIF_INSTR_STRING(instr));
9034 err += efunc(pc, "invalid register %u\n", rd);
9036 err += efunc(pc, "cannot write to %r0\n");
9040 if (r1 > DIF_VAR_ARRAY_MAX)
9041 err += efunc(pc, "invalid array %u\n", r1);
9043 err += efunc(pc, "invalid register %u\n", r2);
9045 err += efunc(pc, "invalid register %u\n", rd);
9047 err += efunc(pc, "cannot write to %r0\n");
9054 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9055 err += efunc(pc, "invalid variable %u\n", v);
9057 err += efunc(pc, "invalid register %u\n", rd);
9059 err += efunc(pc, "cannot write to %r0\n");
9066 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9067 err += efunc(pc, "invalid variable %u\n", v);
9069 err += efunc(pc, "invalid register %u\n", rd);
9072 if (subr > DIF_SUBR_MAX)
9073 err += efunc(pc, "invalid subr %u\n", subr);
9075 err += efunc(pc, "invalid register %u\n", rd);
9077 err += efunc(pc, "cannot write to %r0\n");
9079 if (subr == DIF_SUBR_COPYOUT ||
9080 subr == DIF_SUBR_COPYOUTSTR) {
9081 dp->dtdo_destructive = 1;
9084 if (subr == DIF_SUBR_GETF) {
9086 * If we have a getf() we need to record that
9087 * in our state. Note that our state can be
9088 * NULL if this is a helper -- but in that
9089 * case, the call to getf() is itself illegal,
9090 * and will be caught (slightly later) when
9091 * the helper is validated.
9093 if (vstate->dtvs_state != NULL)
9094 vstate->dtvs_state->dts_getf++;
9099 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9100 err += efunc(pc, "invalid ref type %u\n", type);
9102 err += efunc(pc, "invalid register %u\n", r2);
9104 err += efunc(pc, "invalid register %u\n", rs);
9107 if (type != DIF_TYPE_CTF)
9108 err += efunc(pc, "invalid val type %u\n", type);
9110 err += efunc(pc, "invalid register %u\n", r2);
9112 err += efunc(pc, "invalid register %u\n", rs);
9115 err += efunc(pc, "invalid opcode %u\n",
9116 DIF_INSTR_OP(instr));
9120 if (dp->dtdo_len != 0 &&
9121 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9122 err += efunc(dp->dtdo_len - 1,
9123 "expected 'ret' as last DIF instruction\n");
9126 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
9128 * If we're not returning by reference, the size must be either
9129 * 0 or the size of one of the base types.
9131 switch (dp->dtdo_rtype.dtdt_size) {
9133 case sizeof (uint8_t):
9134 case sizeof (uint16_t):
9135 case sizeof (uint32_t):
9136 case sizeof (uint64_t):
9140 err += efunc(dp->dtdo_len - 1, "bad return size");
9144 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9145 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9146 dtrace_diftype_t *vt, *et;
9149 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9150 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9151 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9152 err += efunc(i, "unrecognized variable scope %d\n",
9157 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9158 v->dtdv_kind != DIFV_KIND_SCALAR) {
9159 err += efunc(i, "unrecognized variable type %d\n",
9164 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9165 err += efunc(i, "%d exceeds variable id limit\n", id);
9169 if (id < DIF_VAR_OTHER_UBASE)
9173 * For user-defined variables, we need to check that this
9174 * definition is identical to any previous definition that we
9177 ndx = id - DIF_VAR_OTHER_UBASE;
9179 switch (v->dtdv_scope) {
9180 case DIFV_SCOPE_GLOBAL:
9181 if (ndx < vstate->dtvs_nglobals) {
9182 dtrace_statvar_t *svar;
9184 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9185 existing = &svar->dtsv_var;
9190 case DIFV_SCOPE_THREAD:
9191 if (ndx < vstate->dtvs_ntlocals)
9192 existing = &vstate->dtvs_tlocals[ndx];
9195 case DIFV_SCOPE_LOCAL:
9196 if (ndx < vstate->dtvs_nlocals) {
9197 dtrace_statvar_t *svar;
9199 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9200 existing = &svar->dtsv_var;
9208 if (vt->dtdt_flags & DIF_TF_BYREF) {
9209 if (vt->dtdt_size == 0) {
9210 err += efunc(i, "zero-sized variable\n");
9214 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9215 vt->dtdt_size > dtrace_global_maxsize) {
9216 err += efunc(i, "oversized by-ref global\n");
9221 if (existing == NULL || existing->dtdv_id == 0)
9224 ASSERT(existing->dtdv_id == v->dtdv_id);
9225 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9227 if (existing->dtdv_kind != v->dtdv_kind)
9228 err += efunc(i, "%d changed variable kind\n", id);
9230 et = &existing->dtdv_type;
9232 if (vt->dtdt_flags != et->dtdt_flags) {
9233 err += efunc(i, "%d changed variable type flags\n", id);
9237 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9238 err += efunc(i, "%d changed variable type size\n", id);
9247 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9248 * are much more constrained than normal DIFOs. Specifically, they may
9251 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9252 * miscellaneous string routines
9253 * 2. Access DTrace variables other than the args[] array, and the
9254 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9255 * 3. Have thread-local variables.
9256 * 4. Have dynamic variables.
9259 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9261 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9265 for (pc = 0; pc < dp->dtdo_len; pc++) {
9266 dif_instr_t instr = dp->dtdo_buf[pc];
9268 uint_t v = DIF_INSTR_VAR(instr);
9269 uint_t subr = DIF_INSTR_SUBR(instr);
9270 uint_t op = DIF_INSTR_OP(instr);
9325 case DIF_OP_FLUSHTS:
9337 if (v >= DIF_VAR_OTHER_UBASE)
9340 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9343 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9344 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9345 v == DIF_VAR_EXECARGS ||
9346 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9347 v == DIF_VAR_UID || v == DIF_VAR_GID)
9350 err += efunc(pc, "illegal variable %u\n", v);
9357 err += efunc(pc, "illegal dynamic variable load\n");
9363 err += efunc(pc, "illegal dynamic variable store\n");
9367 if (subr == DIF_SUBR_ALLOCA ||
9368 subr == DIF_SUBR_BCOPY ||
9369 subr == DIF_SUBR_COPYIN ||
9370 subr == DIF_SUBR_COPYINTO ||
9371 subr == DIF_SUBR_COPYINSTR ||
9372 subr == DIF_SUBR_INDEX ||
9373 subr == DIF_SUBR_INET_NTOA ||
9374 subr == DIF_SUBR_INET_NTOA6 ||
9375 subr == DIF_SUBR_INET_NTOP ||
9376 subr == DIF_SUBR_LLTOSTR ||
9377 subr == DIF_SUBR_RINDEX ||
9378 subr == DIF_SUBR_STRCHR ||
9379 subr == DIF_SUBR_STRJOIN ||
9380 subr == DIF_SUBR_STRRCHR ||
9381 subr == DIF_SUBR_STRSTR ||
9382 subr == DIF_SUBR_HTONS ||
9383 subr == DIF_SUBR_HTONL ||
9384 subr == DIF_SUBR_HTONLL ||
9385 subr == DIF_SUBR_NTOHS ||
9386 subr == DIF_SUBR_NTOHL ||
9387 subr == DIF_SUBR_NTOHLL ||
9388 subr == DIF_SUBR_MEMREF ||
9390 subr == DIF_SUBR_MEMSTR ||
9392 subr == DIF_SUBR_TYPEREF)
9395 err += efunc(pc, "invalid subr %u\n", subr);
9399 err += efunc(pc, "invalid opcode %u\n",
9400 DIF_INSTR_OP(instr));
9408 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9412 dtrace_difo_cacheable(dtrace_difo_t *dp)
9419 for (i = 0; i < dp->dtdo_varlen; i++) {
9420 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9422 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9425 switch (v->dtdv_id) {
9426 case DIF_VAR_CURTHREAD:
9429 case DIF_VAR_EXECARGS:
9430 case DIF_VAR_EXECNAME:
9431 case DIF_VAR_ZONENAME:
9440 * This DIF object may be cacheable. Now we need to look for any
9441 * array loading instructions, any memory loading instructions, or
9442 * any stores to thread-local variables.
9444 for (i = 0; i < dp->dtdo_len; i++) {
9445 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9447 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9448 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9449 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9450 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9458 dtrace_difo_hold(dtrace_difo_t *dp)
9462 ASSERT(MUTEX_HELD(&dtrace_lock));
9465 ASSERT(dp->dtdo_refcnt != 0);
9468 * We need to check this DIF object for references to the variable
9469 * DIF_VAR_VTIMESTAMP.
9471 for (i = 0; i < dp->dtdo_varlen; i++) {
9472 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9474 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9477 if (dtrace_vtime_references++ == 0)
9478 dtrace_vtime_enable();
9483 * This routine calculates the dynamic variable chunksize for a given DIF
9484 * object. The calculation is not fool-proof, and can probably be tricked by
9485 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9486 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9487 * if a dynamic variable size exceeds the chunksize.
9490 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9493 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9494 const dif_instr_t *text = dp->dtdo_buf;
9500 for (pc = 0; pc < dp->dtdo_len; pc++) {
9501 dif_instr_t instr = text[pc];
9502 uint_t op = DIF_INSTR_OP(instr);
9503 uint_t rd = DIF_INSTR_RD(instr);
9504 uint_t r1 = DIF_INSTR_R1(instr);
9508 dtrace_key_t *key = tupregs;
9512 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9517 key = &tupregs[DIF_DTR_NREGS];
9518 key[0].dttk_size = 0;
9519 key[1].dttk_size = 0;
9521 scope = DIFV_SCOPE_THREAD;
9528 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9529 key[nkeys++].dttk_size = 0;
9531 key[nkeys++].dttk_size = 0;
9533 if (op == DIF_OP_STTAA) {
9534 scope = DIFV_SCOPE_THREAD;
9536 scope = DIFV_SCOPE_GLOBAL;
9542 if (ttop == DIF_DTR_NREGS)
9545 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9547 * If the register for the size of the "pushtr"
9548 * is %r0 (or the value is 0) and the type is
9549 * a string, we'll use the system-wide default
9552 tupregs[ttop++].dttk_size =
9553 dtrace_strsize_default;
9558 tupregs[ttop++].dttk_size = sval;
9564 if (ttop == DIF_DTR_NREGS)
9567 tupregs[ttop++].dttk_size = 0;
9570 case DIF_OP_FLUSHTS:
9587 * We have a dynamic variable allocation; calculate its size.
9589 for (ksize = 0, i = 0; i < nkeys; i++)
9590 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9592 size = sizeof (dtrace_dynvar_t);
9593 size += sizeof (dtrace_key_t) * (nkeys - 1);
9597 * Now we need to determine the size of the stored data.
9599 id = DIF_INSTR_VAR(instr);
9601 for (i = 0; i < dp->dtdo_varlen; i++) {
9602 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9604 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9605 size += v->dtdv_type.dtdt_size;
9610 if (i == dp->dtdo_varlen)
9614 * We have the size. If this is larger than the chunk size
9615 * for our dynamic variable state, reset the chunk size.
9617 size = P2ROUNDUP(size, sizeof (uint64_t));
9619 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9620 vstate->dtvs_dynvars.dtds_chunksize = size;
9625 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9627 int i, oldsvars, osz, nsz, otlocals, ntlocals;
9630 ASSERT(MUTEX_HELD(&dtrace_lock));
9631 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9633 for (i = 0; i < dp->dtdo_varlen; i++) {
9634 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9635 dtrace_statvar_t *svar, ***svarp = NULL;
9637 uint8_t scope = v->dtdv_scope;
9640 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9643 id -= DIF_VAR_OTHER_UBASE;
9646 case DIFV_SCOPE_THREAD:
9647 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9648 dtrace_difv_t *tlocals;
9650 if ((ntlocals = (otlocals << 1)) == 0)
9653 osz = otlocals * sizeof (dtrace_difv_t);
9654 nsz = ntlocals * sizeof (dtrace_difv_t);
9656 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9659 bcopy(vstate->dtvs_tlocals,
9661 kmem_free(vstate->dtvs_tlocals, osz);
9664 vstate->dtvs_tlocals = tlocals;
9665 vstate->dtvs_ntlocals = ntlocals;
9668 vstate->dtvs_tlocals[id] = *v;
9671 case DIFV_SCOPE_LOCAL:
9672 np = &vstate->dtvs_nlocals;
9673 svarp = &vstate->dtvs_locals;
9675 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9676 dsize = NCPU * (v->dtdv_type.dtdt_size +
9679 dsize = NCPU * sizeof (uint64_t);
9683 case DIFV_SCOPE_GLOBAL:
9684 np = &vstate->dtvs_nglobals;
9685 svarp = &vstate->dtvs_globals;
9687 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9688 dsize = v->dtdv_type.dtdt_size +
9697 while (id >= (oldsvars = *np)) {
9698 dtrace_statvar_t **statics;
9699 int newsvars, oldsize, newsize;
9701 if ((newsvars = (oldsvars << 1)) == 0)
9704 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9705 newsize = newsvars * sizeof (dtrace_statvar_t *);
9707 statics = kmem_zalloc(newsize, KM_SLEEP);
9710 bcopy(*svarp, statics, oldsize);
9711 kmem_free(*svarp, oldsize);
9718 if ((svar = (*svarp)[id]) == NULL) {
9719 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9720 svar->dtsv_var = *v;
9722 if ((svar->dtsv_size = dsize) != 0) {
9723 svar->dtsv_data = (uint64_t)(uintptr_t)
9724 kmem_zalloc(dsize, KM_SLEEP);
9727 (*svarp)[id] = svar;
9730 svar->dtsv_refcnt++;
9733 dtrace_difo_chunksize(dp, vstate);
9734 dtrace_difo_hold(dp);
9737 static dtrace_difo_t *
9738 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9743 ASSERT(dp->dtdo_buf != NULL);
9744 ASSERT(dp->dtdo_refcnt != 0);
9746 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9748 ASSERT(dp->dtdo_buf != NULL);
9749 sz = dp->dtdo_len * sizeof (dif_instr_t);
9750 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9751 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9752 new->dtdo_len = dp->dtdo_len;
9754 if (dp->dtdo_strtab != NULL) {
9755 ASSERT(dp->dtdo_strlen != 0);
9756 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9757 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9758 new->dtdo_strlen = dp->dtdo_strlen;
9761 if (dp->dtdo_inttab != NULL) {
9762 ASSERT(dp->dtdo_intlen != 0);
9763 sz = dp->dtdo_intlen * sizeof (uint64_t);
9764 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9765 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9766 new->dtdo_intlen = dp->dtdo_intlen;
9769 if (dp->dtdo_vartab != NULL) {
9770 ASSERT(dp->dtdo_varlen != 0);
9771 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9772 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9773 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9774 new->dtdo_varlen = dp->dtdo_varlen;
9777 dtrace_difo_init(new, vstate);
9782 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9786 ASSERT(dp->dtdo_refcnt == 0);
9788 for (i = 0; i < dp->dtdo_varlen; i++) {
9789 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9790 dtrace_statvar_t *svar, **svarp = NULL;
9792 uint8_t scope = v->dtdv_scope;
9796 case DIFV_SCOPE_THREAD:
9799 case DIFV_SCOPE_LOCAL:
9800 np = &vstate->dtvs_nlocals;
9801 svarp = vstate->dtvs_locals;
9804 case DIFV_SCOPE_GLOBAL:
9805 np = &vstate->dtvs_nglobals;
9806 svarp = vstate->dtvs_globals;
9813 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9816 id -= DIF_VAR_OTHER_UBASE;
9820 ASSERT(svar != NULL);
9821 ASSERT(svar->dtsv_refcnt > 0);
9823 if (--svar->dtsv_refcnt > 0)
9826 if (svar->dtsv_size != 0) {
9827 ASSERT(svar->dtsv_data != 0);
9828 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9832 kmem_free(svar, sizeof (dtrace_statvar_t));
9836 if (dp->dtdo_buf != NULL)
9837 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9838 if (dp->dtdo_inttab != NULL)
9839 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9840 if (dp->dtdo_strtab != NULL)
9841 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9842 if (dp->dtdo_vartab != NULL)
9843 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9845 kmem_free(dp, sizeof (dtrace_difo_t));
9849 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9853 ASSERT(MUTEX_HELD(&dtrace_lock));
9854 ASSERT(dp->dtdo_refcnt != 0);
9856 for (i = 0; i < dp->dtdo_varlen; i++) {
9857 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9859 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9862 ASSERT(dtrace_vtime_references > 0);
9863 if (--dtrace_vtime_references == 0)
9864 dtrace_vtime_disable();
9867 if (--dp->dtdo_refcnt == 0)
9868 dtrace_difo_destroy(dp, vstate);
9872 * DTrace Format Functions
9875 dtrace_format_add(dtrace_state_t *state, char *str)
9878 uint16_t ndx, len = strlen(str) + 1;
9880 fmt = kmem_zalloc(len, KM_SLEEP);
9881 bcopy(str, fmt, len);
9883 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9884 if (state->dts_formats[ndx] == NULL) {
9885 state->dts_formats[ndx] = fmt;
9890 if (state->dts_nformats == USHRT_MAX) {
9892 * This is only likely if a denial-of-service attack is being
9893 * attempted. As such, it's okay to fail silently here.
9895 kmem_free(fmt, len);
9900 * For simplicity, we always resize the formats array to be exactly the
9901 * number of formats.
9903 ndx = state->dts_nformats++;
9904 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9906 if (state->dts_formats != NULL) {
9908 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9909 kmem_free(state->dts_formats, ndx * sizeof (char *));
9912 state->dts_formats = new;
9913 state->dts_formats[ndx] = fmt;
9919 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9923 ASSERT(state->dts_formats != NULL);
9924 ASSERT(format <= state->dts_nformats);
9925 ASSERT(state->dts_formats[format - 1] != NULL);
9927 fmt = state->dts_formats[format - 1];
9928 kmem_free(fmt, strlen(fmt) + 1);
9929 state->dts_formats[format - 1] = NULL;
9933 dtrace_format_destroy(dtrace_state_t *state)
9937 if (state->dts_nformats == 0) {
9938 ASSERT(state->dts_formats == NULL);
9942 ASSERT(state->dts_formats != NULL);
9944 for (i = 0; i < state->dts_nformats; i++) {
9945 char *fmt = state->dts_formats[i];
9950 kmem_free(fmt, strlen(fmt) + 1);
9953 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9954 state->dts_nformats = 0;
9955 state->dts_formats = NULL;
9959 * DTrace Predicate Functions
9961 static dtrace_predicate_t *
9962 dtrace_predicate_create(dtrace_difo_t *dp)
9964 dtrace_predicate_t *pred;
9966 ASSERT(MUTEX_HELD(&dtrace_lock));
9967 ASSERT(dp->dtdo_refcnt != 0);
9969 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9970 pred->dtp_difo = dp;
9971 pred->dtp_refcnt = 1;
9973 if (!dtrace_difo_cacheable(dp))
9976 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9978 * This is only theoretically possible -- we have had 2^32
9979 * cacheable predicates on this machine. We cannot allow any
9980 * more predicates to become cacheable: as unlikely as it is,
9981 * there may be a thread caching a (now stale) predicate cache
9982 * ID. (N.B.: the temptation is being successfully resisted to
9983 * have this cmn_err() "Holy shit -- we executed this code!")
9988 pred->dtp_cacheid = dtrace_predcache_id++;
9994 dtrace_predicate_hold(dtrace_predicate_t *pred)
9996 ASSERT(MUTEX_HELD(&dtrace_lock));
9997 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9998 ASSERT(pred->dtp_refcnt > 0);
10000 pred->dtp_refcnt++;
10004 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10006 dtrace_difo_t *dp = pred->dtp_difo;
10008 ASSERT(MUTEX_HELD(&dtrace_lock));
10009 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10010 ASSERT(pred->dtp_refcnt > 0);
10012 if (--pred->dtp_refcnt == 0) {
10013 dtrace_difo_release(pred->dtp_difo, vstate);
10014 kmem_free(pred, sizeof (dtrace_predicate_t));
10019 * DTrace Action Description Functions
10021 static dtrace_actdesc_t *
10022 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10023 uint64_t uarg, uint64_t arg)
10025 dtrace_actdesc_t *act;
10028 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10029 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10032 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10033 act->dtad_kind = kind;
10034 act->dtad_ntuple = ntuple;
10035 act->dtad_uarg = uarg;
10036 act->dtad_arg = arg;
10037 act->dtad_refcnt = 1;
10043 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10045 ASSERT(act->dtad_refcnt >= 1);
10046 act->dtad_refcnt++;
10050 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10052 dtrace_actkind_t kind = act->dtad_kind;
10055 ASSERT(act->dtad_refcnt >= 1);
10057 if (--act->dtad_refcnt != 0)
10060 if ((dp = act->dtad_difo) != NULL)
10061 dtrace_difo_release(dp, vstate);
10063 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10064 char *str = (char *)(uintptr_t)act->dtad_arg;
10067 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10068 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10072 kmem_free(str, strlen(str) + 1);
10075 kmem_free(act, sizeof (dtrace_actdesc_t));
10079 * DTrace ECB Functions
10081 static dtrace_ecb_t *
10082 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10085 dtrace_epid_t epid;
10087 ASSERT(MUTEX_HELD(&dtrace_lock));
10089 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10090 ecb->dte_predicate = NULL;
10091 ecb->dte_probe = probe;
10094 * The default size is the size of the default action: recording
10097 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10098 ecb->dte_alignment = sizeof (dtrace_epid_t);
10100 epid = state->dts_epid++;
10102 if (epid - 1 >= state->dts_necbs) {
10103 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10104 int necbs = state->dts_necbs << 1;
10106 ASSERT(epid == state->dts_necbs + 1);
10109 ASSERT(oecbs == NULL);
10113 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10116 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10118 dtrace_membar_producer();
10119 state->dts_ecbs = ecbs;
10121 if (oecbs != NULL) {
10123 * If this state is active, we must dtrace_sync()
10124 * before we can free the old dts_ecbs array: we're
10125 * coming in hot, and there may be active ring
10126 * buffer processing (which indexes into the dts_ecbs
10127 * array) on another CPU.
10129 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10132 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10135 dtrace_membar_producer();
10136 state->dts_necbs = necbs;
10139 ecb->dte_state = state;
10141 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10142 dtrace_membar_producer();
10143 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10149 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10151 dtrace_probe_t *probe = ecb->dte_probe;
10153 ASSERT(MUTEX_HELD(&cpu_lock));
10154 ASSERT(MUTEX_HELD(&dtrace_lock));
10155 ASSERT(ecb->dte_next == NULL);
10157 if (probe == NULL) {
10159 * This is the NULL probe -- there's nothing to do.
10164 if (probe->dtpr_ecb == NULL) {
10165 dtrace_provider_t *prov = probe->dtpr_provider;
10168 * We're the first ECB on this probe.
10170 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10172 if (ecb->dte_predicate != NULL)
10173 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10175 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10176 probe->dtpr_id, probe->dtpr_arg);
10179 * This probe is already active. Swing the last pointer to
10180 * point to the new ECB, and issue a dtrace_sync() to assure
10181 * that all CPUs have seen the change.
10183 ASSERT(probe->dtpr_ecb_last != NULL);
10184 probe->dtpr_ecb_last->dte_next = ecb;
10185 probe->dtpr_ecb_last = ecb;
10186 probe->dtpr_predcache = 0;
10193 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10195 dtrace_action_t *act;
10196 uint32_t curneeded = UINT32_MAX;
10197 uint32_t aggbase = UINT32_MAX;
10200 * If we record anything, we always record the dtrace_rechdr_t. (And
10201 * we always record it first.)
10203 ecb->dte_size = sizeof (dtrace_rechdr_t);
10204 ecb->dte_alignment = sizeof (dtrace_epid_t);
10206 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10207 dtrace_recdesc_t *rec = &act->dta_rec;
10208 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10210 ecb->dte_alignment = MAX(ecb->dte_alignment,
10211 rec->dtrd_alignment);
10213 if (DTRACEACT_ISAGG(act->dta_kind)) {
10214 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10216 ASSERT(rec->dtrd_size != 0);
10217 ASSERT(agg->dtag_first != NULL);
10218 ASSERT(act->dta_prev->dta_intuple);
10219 ASSERT(aggbase != UINT32_MAX);
10220 ASSERT(curneeded != UINT32_MAX);
10222 agg->dtag_base = aggbase;
10224 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10225 rec->dtrd_offset = curneeded;
10226 curneeded += rec->dtrd_size;
10227 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10229 aggbase = UINT32_MAX;
10230 curneeded = UINT32_MAX;
10231 } else if (act->dta_intuple) {
10232 if (curneeded == UINT32_MAX) {
10234 * This is the first record in a tuple. Align
10235 * curneeded to be at offset 4 in an 8-byte
10238 ASSERT(act->dta_prev == NULL ||
10239 !act->dta_prev->dta_intuple);
10240 ASSERT3U(aggbase, ==, UINT32_MAX);
10241 curneeded = P2PHASEUP(ecb->dte_size,
10242 sizeof (uint64_t), sizeof (dtrace_aggid_t));
10244 aggbase = curneeded - sizeof (dtrace_aggid_t);
10245 ASSERT(IS_P2ALIGNED(aggbase,
10246 sizeof (uint64_t)));
10248 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10249 rec->dtrd_offset = curneeded;
10250 curneeded += rec->dtrd_size;
10252 /* tuples must be followed by an aggregation */
10253 ASSERT(act->dta_prev == NULL ||
10254 !act->dta_prev->dta_intuple);
10256 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10257 rec->dtrd_alignment);
10258 rec->dtrd_offset = ecb->dte_size;
10259 ecb->dte_size += rec->dtrd_size;
10260 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10264 if ((act = ecb->dte_action) != NULL &&
10265 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10266 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10268 * If the size is still sizeof (dtrace_rechdr_t), then all
10269 * actions store no data; set the size to 0.
10274 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10275 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10276 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10280 static dtrace_action_t *
10281 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10283 dtrace_aggregation_t *agg;
10284 size_t size = sizeof (uint64_t);
10285 int ntuple = desc->dtad_ntuple;
10286 dtrace_action_t *act;
10287 dtrace_recdesc_t *frec;
10288 dtrace_aggid_t aggid;
10289 dtrace_state_t *state = ecb->dte_state;
10291 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10292 agg->dtag_ecb = ecb;
10294 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10296 switch (desc->dtad_kind) {
10297 case DTRACEAGG_MIN:
10298 agg->dtag_initial = INT64_MAX;
10299 agg->dtag_aggregate = dtrace_aggregate_min;
10302 case DTRACEAGG_MAX:
10303 agg->dtag_initial = INT64_MIN;
10304 agg->dtag_aggregate = dtrace_aggregate_max;
10307 case DTRACEAGG_COUNT:
10308 agg->dtag_aggregate = dtrace_aggregate_count;
10311 case DTRACEAGG_QUANTIZE:
10312 agg->dtag_aggregate = dtrace_aggregate_quantize;
10313 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10317 case DTRACEAGG_LQUANTIZE: {
10318 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10319 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10321 agg->dtag_initial = desc->dtad_arg;
10322 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10324 if (step == 0 || levels == 0)
10327 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10331 case DTRACEAGG_LLQUANTIZE: {
10332 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10333 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10334 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10335 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10338 agg->dtag_initial = desc->dtad_arg;
10339 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10341 if (factor < 2 || low >= high || nsteps < factor)
10345 * Now check that the number of steps evenly divides a power
10346 * of the factor. (This assures both integer bucket size and
10347 * linearity within each magnitude.)
10349 for (v = factor; v < nsteps; v *= factor)
10352 if ((v % nsteps) || (nsteps % factor))
10355 size = (dtrace_aggregate_llquantize_bucket(factor,
10356 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10360 case DTRACEAGG_AVG:
10361 agg->dtag_aggregate = dtrace_aggregate_avg;
10362 size = sizeof (uint64_t) * 2;
10365 case DTRACEAGG_STDDEV:
10366 agg->dtag_aggregate = dtrace_aggregate_stddev;
10367 size = sizeof (uint64_t) * 4;
10370 case DTRACEAGG_SUM:
10371 agg->dtag_aggregate = dtrace_aggregate_sum;
10378 agg->dtag_action.dta_rec.dtrd_size = size;
10384 * We must make sure that we have enough actions for the n-tuple.
10386 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10387 if (DTRACEACT_ISAGG(act->dta_kind))
10390 if (--ntuple == 0) {
10392 * This is the action with which our n-tuple begins.
10394 agg->dtag_first = act;
10400 * This n-tuple is short by ntuple elements. Return failure.
10402 ASSERT(ntuple != 0);
10404 kmem_free(agg, sizeof (dtrace_aggregation_t));
10409 * If the last action in the tuple has a size of zero, it's actually
10410 * an expression argument for the aggregating action.
10412 ASSERT(ecb->dte_action_last != NULL);
10413 act = ecb->dte_action_last;
10415 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10416 ASSERT(act->dta_difo != NULL);
10418 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10419 agg->dtag_hasarg = 1;
10423 * We need to allocate an id for this aggregation.
10426 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10427 VM_BESTFIT | VM_SLEEP);
10429 aggid = alloc_unr(state->dts_aggid_arena);
10432 if (aggid - 1 >= state->dts_naggregations) {
10433 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10434 dtrace_aggregation_t **aggs;
10435 int naggs = state->dts_naggregations << 1;
10436 int onaggs = state->dts_naggregations;
10438 ASSERT(aggid == state->dts_naggregations + 1);
10441 ASSERT(oaggs == NULL);
10445 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10447 if (oaggs != NULL) {
10448 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10449 kmem_free(oaggs, onaggs * sizeof (*aggs));
10452 state->dts_aggregations = aggs;
10453 state->dts_naggregations = naggs;
10456 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10457 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10459 frec = &agg->dtag_first->dta_rec;
10460 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10461 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10463 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10464 ASSERT(!act->dta_intuple);
10465 act->dta_intuple = 1;
10468 return (&agg->dtag_action);
10472 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10474 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10475 dtrace_state_t *state = ecb->dte_state;
10476 dtrace_aggid_t aggid = agg->dtag_id;
10478 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10480 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10482 free_unr(state->dts_aggid_arena, aggid);
10485 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10486 state->dts_aggregations[aggid - 1] = NULL;
10488 kmem_free(agg, sizeof (dtrace_aggregation_t));
10492 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10494 dtrace_action_t *action, *last;
10495 dtrace_difo_t *dp = desc->dtad_difo;
10496 uint32_t size = 0, align = sizeof (uint8_t), mask;
10497 uint16_t format = 0;
10498 dtrace_recdesc_t *rec;
10499 dtrace_state_t *state = ecb->dte_state;
10500 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10501 uint64_t arg = desc->dtad_arg;
10503 ASSERT(MUTEX_HELD(&dtrace_lock));
10504 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10506 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10508 * If this is an aggregating action, there must be neither
10509 * a speculate nor a commit on the action chain.
10511 dtrace_action_t *act;
10513 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10514 if (act->dta_kind == DTRACEACT_COMMIT)
10517 if (act->dta_kind == DTRACEACT_SPECULATE)
10521 action = dtrace_ecb_aggregation_create(ecb, desc);
10523 if (action == NULL)
10526 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10527 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10528 dp != NULL && dp->dtdo_destructive)) {
10529 state->dts_destructive = 1;
10532 switch (desc->dtad_kind) {
10533 case DTRACEACT_PRINTF:
10534 case DTRACEACT_PRINTA:
10535 case DTRACEACT_SYSTEM:
10536 case DTRACEACT_FREOPEN:
10537 case DTRACEACT_DIFEXPR:
10539 * We know that our arg is a string -- turn it into a
10543 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10544 desc->dtad_kind == DTRACEACT_DIFEXPR);
10549 ASSERT(arg > KERNELBASE);
10551 format = dtrace_format_add(state,
10552 (char *)(uintptr_t)arg);
10556 case DTRACEACT_LIBACT:
10557 case DTRACEACT_TRACEMEM:
10558 case DTRACEACT_TRACEMEM_DYNSIZE:
10562 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10565 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10566 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10569 size = opt[DTRACEOPT_STRSIZE];
10574 case DTRACEACT_STACK:
10575 if ((nframes = arg) == 0) {
10576 nframes = opt[DTRACEOPT_STACKFRAMES];
10577 ASSERT(nframes > 0);
10581 size = nframes * sizeof (pc_t);
10584 case DTRACEACT_JSTACK:
10585 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10586 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10588 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10589 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10591 arg = DTRACE_USTACK_ARG(nframes, strsize);
10594 case DTRACEACT_USTACK:
10595 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10596 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10597 strsize = DTRACE_USTACK_STRSIZE(arg);
10598 nframes = opt[DTRACEOPT_USTACKFRAMES];
10599 ASSERT(nframes > 0);
10600 arg = DTRACE_USTACK_ARG(nframes, strsize);
10604 * Save a slot for the pid.
10606 size = (nframes + 1) * sizeof (uint64_t);
10607 size += DTRACE_USTACK_STRSIZE(arg);
10608 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10612 case DTRACEACT_SYM:
10613 case DTRACEACT_MOD:
10614 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10615 sizeof (uint64_t)) ||
10616 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10620 case DTRACEACT_USYM:
10621 case DTRACEACT_UMOD:
10622 case DTRACEACT_UADDR:
10624 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10625 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10629 * We have a slot for the pid, plus a slot for the
10630 * argument. To keep things simple (aligned with
10631 * bitness-neutral sizing), we store each as a 64-bit
10634 size = 2 * sizeof (uint64_t);
10637 case DTRACEACT_STOP:
10638 case DTRACEACT_BREAKPOINT:
10639 case DTRACEACT_PANIC:
10642 case DTRACEACT_CHILL:
10643 case DTRACEACT_DISCARD:
10644 case DTRACEACT_RAISE:
10649 case DTRACEACT_EXIT:
10651 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10652 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10656 case DTRACEACT_SPECULATE:
10657 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10663 state->dts_speculates = 1;
10666 case DTRACEACT_PRINTM:
10667 size = dp->dtdo_rtype.dtdt_size;
10670 case DTRACEACT_PRINTT:
10671 size = dp->dtdo_rtype.dtdt_size;
10674 case DTRACEACT_COMMIT: {
10675 dtrace_action_t *act = ecb->dte_action;
10677 for (; act != NULL; act = act->dta_next) {
10678 if (act->dta_kind == DTRACEACT_COMMIT)
10691 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10693 * If this is a data-storing action or a speculate,
10694 * we must be sure that there isn't a commit on the
10697 dtrace_action_t *act = ecb->dte_action;
10699 for (; act != NULL; act = act->dta_next) {
10700 if (act->dta_kind == DTRACEACT_COMMIT)
10705 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10706 action->dta_rec.dtrd_size = size;
10709 action->dta_refcnt = 1;
10710 rec = &action->dta_rec;
10711 size = rec->dtrd_size;
10713 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10714 if (!(size & mask)) {
10720 action->dta_kind = desc->dtad_kind;
10722 if ((action->dta_difo = dp) != NULL)
10723 dtrace_difo_hold(dp);
10725 rec->dtrd_action = action->dta_kind;
10726 rec->dtrd_arg = arg;
10727 rec->dtrd_uarg = desc->dtad_uarg;
10728 rec->dtrd_alignment = (uint16_t)align;
10729 rec->dtrd_format = format;
10731 if ((last = ecb->dte_action_last) != NULL) {
10732 ASSERT(ecb->dte_action != NULL);
10733 action->dta_prev = last;
10734 last->dta_next = action;
10736 ASSERT(ecb->dte_action == NULL);
10737 ecb->dte_action = action;
10740 ecb->dte_action_last = action;
10746 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10748 dtrace_action_t *act = ecb->dte_action, *next;
10749 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10753 if (act != NULL && act->dta_refcnt > 1) {
10754 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10757 for (; act != NULL; act = next) {
10758 next = act->dta_next;
10759 ASSERT(next != NULL || act == ecb->dte_action_last);
10760 ASSERT(act->dta_refcnt == 1);
10762 if ((format = act->dta_rec.dtrd_format) != 0)
10763 dtrace_format_remove(ecb->dte_state, format);
10765 if ((dp = act->dta_difo) != NULL)
10766 dtrace_difo_release(dp, vstate);
10768 if (DTRACEACT_ISAGG(act->dta_kind)) {
10769 dtrace_ecb_aggregation_destroy(ecb, act);
10771 kmem_free(act, sizeof (dtrace_action_t));
10776 ecb->dte_action = NULL;
10777 ecb->dte_action_last = NULL;
10782 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10785 * We disable the ECB by removing it from its probe.
10787 dtrace_ecb_t *pecb, *prev = NULL;
10788 dtrace_probe_t *probe = ecb->dte_probe;
10790 ASSERT(MUTEX_HELD(&dtrace_lock));
10792 if (probe == NULL) {
10794 * This is the NULL probe; there is nothing to disable.
10799 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10805 ASSERT(pecb != NULL);
10807 if (prev == NULL) {
10808 probe->dtpr_ecb = ecb->dte_next;
10810 prev->dte_next = ecb->dte_next;
10813 if (ecb == probe->dtpr_ecb_last) {
10814 ASSERT(ecb->dte_next == NULL);
10815 probe->dtpr_ecb_last = prev;
10819 * The ECB has been disconnected from the probe; now sync to assure
10820 * that all CPUs have seen the change before returning.
10824 if (probe->dtpr_ecb == NULL) {
10826 * That was the last ECB on the probe; clear the predicate
10827 * cache ID for the probe, disable it and sync one more time
10828 * to assure that we'll never hit it again.
10830 dtrace_provider_t *prov = probe->dtpr_provider;
10832 ASSERT(ecb->dte_next == NULL);
10833 ASSERT(probe->dtpr_ecb_last == NULL);
10834 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10835 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10836 probe->dtpr_id, probe->dtpr_arg);
10840 * There is at least one ECB remaining on the probe. If there
10841 * is _exactly_ one, set the probe's predicate cache ID to be
10842 * the predicate cache ID of the remaining ECB.
10844 ASSERT(probe->dtpr_ecb_last != NULL);
10845 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10847 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10848 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10850 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10853 probe->dtpr_predcache = p->dtp_cacheid;
10856 ecb->dte_next = NULL;
10861 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10863 dtrace_state_t *state = ecb->dte_state;
10864 dtrace_vstate_t *vstate = &state->dts_vstate;
10865 dtrace_predicate_t *pred;
10866 dtrace_epid_t epid = ecb->dte_epid;
10868 ASSERT(MUTEX_HELD(&dtrace_lock));
10869 ASSERT(ecb->dte_next == NULL);
10870 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10872 if ((pred = ecb->dte_predicate) != NULL)
10873 dtrace_predicate_release(pred, vstate);
10875 dtrace_ecb_action_remove(ecb);
10877 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10878 state->dts_ecbs[epid - 1] = NULL;
10880 kmem_free(ecb, sizeof (dtrace_ecb_t));
10883 static dtrace_ecb_t *
10884 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10885 dtrace_enabling_t *enab)
10888 dtrace_predicate_t *pred;
10889 dtrace_actdesc_t *act;
10890 dtrace_provider_t *prov;
10891 dtrace_ecbdesc_t *desc = enab->dten_current;
10893 ASSERT(MUTEX_HELD(&dtrace_lock));
10894 ASSERT(state != NULL);
10896 ecb = dtrace_ecb_add(state, probe);
10897 ecb->dte_uarg = desc->dted_uarg;
10899 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10900 dtrace_predicate_hold(pred);
10901 ecb->dte_predicate = pred;
10904 if (probe != NULL) {
10906 * If the provider shows more leg than the consumer is old
10907 * enough to see, we need to enable the appropriate implicit
10908 * predicate bits to prevent the ecb from activating at
10911 * Providers specifying DTRACE_PRIV_USER at register time
10912 * are stating that they need the /proc-style privilege
10913 * model to be enforced, and this is what DTRACE_COND_OWNER
10914 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10916 prov = probe->dtpr_provider;
10917 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10918 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10919 ecb->dte_cond |= DTRACE_COND_OWNER;
10921 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10922 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10923 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10926 * If the provider shows us kernel innards and the user
10927 * is lacking sufficient privilege, enable the
10928 * DTRACE_COND_USERMODE implicit predicate.
10930 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10931 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10932 ecb->dte_cond |= DTRACE_COND_USERMODE;
10935 if (dtrace_ecb_create_cache != NULL) {
10937 * If we have a cached ecb, we'll use its action list instead
10938 * of creating our own (saving both time and space).
10940 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10941 dtrace_action_t *act = cached->dte_action;
10944 ASSERT(act->dta_refcnt > 0);
10946 ecb->dte_action = act;
10947 ecb->dte_action_last = cached->dte_action_last;
10948 ecb->dte_needed = cached->dte_needed;
10949 ecb->dte_size = cached->dte_size;
10950 ecb->dte_alignment = cached->dte_alignment;
10956 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10957 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10958 dtrace_ecb_destroy(ecb);
10963 dtrace_ecb_resize(ecb);
10965 return (dtrace_ecb_create_cache = ecb);
10969 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10972 dtrace_enabling_t *enab = arg;
10973 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10975 ASSERT(state != NULL);
10977 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10979 * This probe was created in a generation for which this
10980 * enabling has previously created ECBs; we don't want to
10981 * enable it again, so just kick out.
10983 return (DTRACE_MATCH_NEXT);
10986 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10987 return (DTRACE_MATCH_DONE);
10989 dtrace_ecb_enable(ecb);
10990 return (DTRACE_MATCH_NEXT);
10993 static dtrace_ecb_t *
10994 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10998 ASSERT(MUTEX_HELD(&dtrace_lock));
11000 if (id == 0 || id > state->dts_necbs)
11003 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11004 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11006 return (state->dts_ecbs[id - 1]);
11009 static dtrace_aggregation_t *
11010 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11012 dtrace_aggregation_t *agg;
11014 ASSERT(MUTEX_HELD(&dtrace_lock));
11016 if (id == 0 || id > state->dts_naggregations)
11019 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11020 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11021 agg->dtag_id == id);
11023 return (state->dts_aggregations[id - 1]);
11027 * DTrace Buffer Functions
11029 * The following functions manipulate DTrace buffers. Most of these functions
11030 * are called in the context of establishing or processing consumer state;
11031 * exceptions are explicitly noted.
11035 * Note: called from cross call context. This function switches the two
11036 * buffers on a given CPU. The atomicity of this operation is assured by
11037 * disabling interrupts while the actual switch takes place; the disabling of
11038 * interrupts serializes the execution with any execution of dtrace_probe() on
11042 dtrace_buffer_switch(dtrace_buffer_t *buf)
11044 caddr_t tomax = buf->dtb_tomax;
11045 caddr_t xamot = buf->dtb_xamot;
11046 dtrace_icookie_t cookie;
11049 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11050 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11052 cookie = dtrace_interrupt_disable();
11053 now = dtrace_gethrtime();
11054 buf->dtb_tomax = xamot;
11055 buf->dtb_xamot = tomax;
11056 buf->dtb_xamot_drops = buf->dtb_drops;
11057 buf->dtb_xamot_offset = buf->dtb_offset;
11058 buf->dtb_xamot_errors = buf->dtb_errors;
11059 buf->dtb_xamot_flags = buf->dtb_flags;
11060 buf->dtb_offset = 0;
11061 buf->dtb_drops = 0;
11062 buf->dtb_errors = 0;
11063 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11064 buf->dtb_interval = now - buf->dtb_switched;
11065 buf->dtb_switched = now;
11066 dtrace_interrupt_enable(cookie);
11070 * Note: called from cross call context. This function activates a buffer
11071 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11072 * is guaranteed by the disabling of interrupts.
11075 dtrace_buffer_activate(dtrace_state_t *state)
11077 dtrace_buffer_t *buf;
11078 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11080 buf = &state->dts_buffer[curcpu];
11082 if (buf->dtb_tomax != NULL) {
11084 * We might like to assert that the buffer is marked inactive,
11085 * but this isn't necessarily true: the buffer for the CPU
11086 * that processes the BEGIN probe has its buffer activated
11087 * manually. In this case, we take the (harmless) action
11088 * re-clearing the bit INACTIVE bit.
11090 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11093 dtrace_interrupt_enable(cookie);
11097 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11098 processorid_t cpu, int *factor)
11103 dtrace_buffer_t *buf;
11104 int allocated = 0, desired = 0;
11107 ASSERT(MUTEX_HELD(&cpu_lock));
11108 ASSERT(MUTEX_HELD(&dtrace_lock));
11112 if (size > dtrace_nonroot_maxsize &&
11113 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11119 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11122 buf = &bufs[cp->cpu_id];
11125 * If there is already a buffer allocated for this CPU, it
11126 * is only possible that this is a DR event. In this case,
11128 if (buf->dtb_tomax != NULL) {
11129 ASSERT(buf->dtb_size == size);
11133 ASSERT(buf->dtb_xamot == NULL);
11135 if ((buf->dtb_tomax = kmem_zalloc(size,
11136 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11139 buf->dtb_size = size;
11140 buf->dtb_flags = flags;
11141 buf->dtb_offset = 0;
11142 buf->dtb_drops = 0;
11144 if (flags & DTRACEBUF_NOSWITCH)
11147 if ((buf->dtb_xamot = kmem_zalloc(size,
11148 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11150 } while ((cp = cp->cpu_next) != cpu_list);
11158 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11161 buf = &bufs[cp->cpu_id];
11164 if (buf->dtb_xamot != NULL) {
11165 ASSERT(buf->dtb_tomax != NULL);
11166 ASSERT(buf->dtb_size == size);
11167 kmem_free(buf->dtb_xamot, size);
11171 if (buf->dtb_tomax != NULL) {
11172 ASSERT(buf->dtb_size == size);
11173 kmem_free(buf->dtb_tomax, size);
11177 buf->dtb_tomax = NULL;
11178 buf->dtb_xamot = NULL;
11180 } while ((cp = cp->cpu_next) != cpu_list);
11185 #if defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
11187 * FreeBSD isn't good at limiting the amount of memory we
11188 * ask to malloc, so let's place a limit here before trying
11189 * to do something that might well end in tears at bedtime.
11191 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
11195 ASSERT(MUTEX_HELD(&dtrace_lock));
11197 if (cpu != DTRACE_CPUALL && cpu != i)
11203 * If there is already a buffer allocated for this CPU, it
11204 * is only possible that this is a DR event. In this case,
11205 * the buffer size must match our specified size.
11207 if (buf->dtb_tomax != NULL) {
11208 ASSERT(buf->dtb_size == size);
11212 ASSERT(buf->dtb_xamot == NULL);
11214 if ((buf->dtb_tomax = kmem_zalloc(size,
11215 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11218 buf->dtb_size = size;
11219 buf->dtb_flags = flags;
11220 buf->dtb_offset = 0;
11221 buf->dtb_drops = 0;
11223 if (flags & DTRACEBUF_NOSWITCH)
11226 if ((buf->dtb_xamot = kmem_zalloc(size,
11227 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11235 * Error allocating memory, so free the buffers that were
11236 * allocated before the failed allocation.
11239 if (cpu != DTRACE_CPUALL && cpu != i)
11245 if (buf->dtb_xamot != NULL) {
11246 ASSERT(buf->dtb_tomax != NULL);
11247 ASSERT(buf->dtb_size == size);
11248 kmem_free(buf->dtb_xamot, size);
11252 if (buf->dtb_tomax != NULL) {
11253 ASSERT(buf->dtb_size == size);
11254 kmem_free(buf->dtb_tomax, size);
11258 buf->dtb_tomax = NULL;
11259 buf->dtb_xamot = NULL;
11264 *factor = desired / (allocated > 0 ? allocated : 1);
11270 * Note: called from probe context. This function just increments the drop
11271 * count on a buffer. It has been made a function to allow for the
11272 * possibility of understanding the source of mysterious drop counts. (A
11273 * problem for which one may be particularly disappointed that DTrace cannot
11274 * be used to understand DTrace.)
11277 dtrace_buffer_drop(dtrace_buffer_t *buf)
11283 * Note: called from probe context. This function is called to reserve space
11284 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
11285 * mstate. Returns the new offset in the buffer, or a negative value if an
11286 * error has occurred.
11289 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11290 dtrace_state_t *state, dtrace_mstate_t *mstate)
11292 intptr_t offs = buf->dtb_offset, soffs;
11297 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11300 if ((tomax = buf->dtb_tomax) == NULL) {
11301 dtrace_buffer_drop(buf);
11305 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11306 while (offs & (align - 1)) {
11308 * Assert that our alignment is off by a number which
11309 * is itself sizeof (uint32_t) aligned.
11311 ASSERT(!((align - (offs & (align - 1))) &
11312 (sizeof (uint32_t) - 1)));
11313 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11314 offs += sizeof (uint32_t);
11317 if ((soffs = offs + needed) > buf->dtb_size) {
11318 dtrace_buffer_drop(buf);
11322 if (mstate == NULL)
11325 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11326 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11327 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11332 if (buf->dtb_flags & DTRACEBUF_FILL) {
11333 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11334 (buf->dtb_flags & DTRACEBUF_FULL))
11339 total = needed + (offs & (align - 1));
11342 * For a ring buffer, life is quite a bit more complicated. Before
11343 * we can store any padding, we need to adjust our wrapping offset.
11344 * (If we've never before wrapped or we're not about to, no adjustment
11347 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11348 offs + total > buf->dtb_size) {
11349 woffs = buf->dtb_xamot_offset;
11351 if (offs + total > buf->dtb_size) {
11353 * We can't fit in the end of the buffer. First, a
11354 * sanity check that we can fit in the buffer at all.
11356 if (total > buf->dtb_size) {
11357 dtrace_buffer_drop(buf);
11362 * We're going to be storing at the top of the buffer,
11363 * so now we need to deal with the wrapped offset. We
11364 * only reset our wrapped offset to 0 if it is
11365 * currently greater than the current offset. If it
11366 * is less than the current offset, it is because a
11367 * previous allocation induced a wrap -- but the
11368 * allocation didn't subsequently take the space due
11369 * to an error or false predicate evaluation. In this
11370 * case, we'll just leave the wrapped offset alone: if
11371 * the wrapped offset hasn't been advanced far enough
11372 * for this allocation, it will be adjusted in the
11375 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11383 * Now we know that we're going to be storing to the
11384 * top of the buffer and that there is room for us
11385 * there. We need to clear the buffer from the current
11386 * offset to the end (there may be old gunk there).
11388 while (offs < buf->dtb_size)
11392 * We need to set our offset to zero. And because we
11393 * are wrapping, we need to set the bit indicating as
11394 * much. We can also adjust our needed space back
11395 * down to the space required by the ECB -- we know
11396 * that the top of the buffer is aligned.
11400 buf->dtb_flags |= DTRACEBUF_WRAPPED;
11403 * There is room for us in the buffer, so we simply
11404 * need to check the wrapped offset.
11406 if (woffs < offs) {
11408 * The wrapped offset is less than the offset.
11409 * This can happen if we allocated buffer space
11410 * that induced a wrap, but then we didn't
11411 * subsequently take the space due to an error
11412 * or false predicate evaluation. This is
11413 * okay; we know that _this_ allocation isn't
11414 * going to induce a wrap. We still can't
11415 * reset the wrapped offset to be zero,
11416 * however: the space may have been trashed in
11417 * the previous failed probe attempt. But at
11418 * least the wrapped offset doesn't need to
11419 * be adjusted at all...
11425 while (offs + total > woffs) {
11426 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11429 if (epid == DTRACE_EPIDNONE) {
11430 size = sizeof (uint32_t);
11432 ASSERT3U(epid, <=, state->dts_necbs);
11433 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11435 size = state->dts_ecbs[epid - 1]->dte_size;
11438 ASSERT(woffs + size <= buf->dtb_size);
11441 if (woffs + size == buf->dtb_size) {
11443 * We've reached the end of the buffer; we want
11444 * to set the wrapped offset to 0 and break
11445 * out. However, if the offs is 0, then we're
11446 * in a strange edge-condition: the amount of
11447 * space that we want to reserve plus the size
11448 * of the record that we're overwriting is
11449 * greater than the size of the buffer. This
11450 * is problematic because if we reserve the
11451 * space but subsequently don't consume it (due
11452 * to a failed predicate or error) the wrapped
11453 * offset will be 0 -- yet the EPID at offset 0
11454 * will not be committed. This situation is
11455 * relatively easy to deal with: if we're in
11456 * this case, the buffer is indistinguishable
11457 * from one that hasn't wrapped; we need only
11458 * finish the job by clearing the wrapped bit,
11459 * explicitly setting the offset to be 0, and
11460 * zero'ing out the old data in the buffer.
11463 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11464 buf->dtb_offset = 0;
11467 while (woffs < buf->dtb_size)
11468 tomax[woffs++] = 0;
11479 * We have a wrapped offset. It may be that the wrapped offset
11480 * has become zero -- that's okay.
11482 buf->dtb_xamot_offset = woffs;
11487 * Now we can plow the buffer with any necessary padding.
11489 while (offs & (align - 1)) {
11491 * Assert that our alignment is off by a number which
11492 * is itself sizeof (uint32_t) aligned.
11494 ASSERT(!((align - (offs & (align - 1))) &
11495 (sizeof (uint32_t) - 1)));
11496 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11497 offs += sizeof (uint32_t);
11500 if (buf->dtb_flags & DTRACEBUF_FILL) {
11501 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11502 buf->dtb_flags |= DTRACEBUF_FULL;
11507 if (mstate == NULL)
11511 * For ring buffers and fill buffers, the scratch space is always
11512 * the inactive buffer.
11514 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11515 mstate->dtms_scratch_size = buf->dtb_size;
11516 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11522 dtrace_buffer_polish(dtrace_buffer_t *buf)
11524 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11525 ASSERT(MUTEX_HELD(&dtrace_lock));
11527 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11531 * We need to polish the ring buffer. There are three cases:
11533 * - The first (and presumably most common) is that there is no gap
11534 * between the buffer offset and the wrapped offset. In this case,
11535 * there is nothing in the buffer that isn't valid data; we can
11536 * mark the buffer as polished and return.
11538 * - The second (less common than the first but still more common
11539 * than the third) is that there is a gap between the buffer offset
11540 * and the wrapped offset, and the wrapped offset is larger than the
11541 * buffer offset. This can happen because of an alignment issue, or
11542 * can happen because of a call to dtrace_buffer_reserve() that
11543 * didn't subsequently consume the buffer space. In this case,
11544 * we need to zero the data from the buffer offset to the wrapped
11547 * - The third (and least common) is that there is a gap between the
11548 * buffer offset and the wrapped offset, but the wrapped offset is
11549 * _less_ than the buffer offset. This can only happen because a
11550 * call to dtrace_buffer_reserve() induced a wrap, but the space
11551 * was not subsequently consumed. In this case, we need to zero the
11552 * space from the offset to the end of the buffer _and_ from the
11553 * top of the buffer to the wrapped offset.
11555 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11556 bzero(buf->dtb_tomax + buf->dtb_offset,
11557 buf->dtb_xamot_offset - buf->dtb_offset);
11560 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11561 bzero(buf->dtb_tomax + buf->dtb_offset,
11562 buf->dtb_size - buf->dtb_offset);
11563 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11568 * This routine determines if data generated at the specified time has likely
11569 * been entirely consumed at user-level. This routine is called to determine
11570 * if an ECB on a defunct probe (but for an active enabling) can be safely
11571 * disabled and destroyed.
11574 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11578 for (i = 0; i < NCPU; i++) {
11579 dtrace_buffer_t *buf = &bufs[i];
11581 if (buf->dtb_size == 0)
11584 if (buf->dtb_flags & DTRACEBUF_RING)
11587 if (!buf->dtb_switched && buf->dtb_offset != 0)
11590 if (buf->dtb_switched - buf->dtb_interval < when)
11598 dtrace_buffer_free(dtrace_buffer_t *bufs)
11602 for (i = 0; i < NCPU; i++) {
11603 dtrace_buffer_t *buf = &bufs[i];
11605 if (buf->dtb_tomax == NULL) {
11606 ASSERT(buf->dtb_xamot == NULL);
11607 ASSERT(buf->dtb_size == 0);
11611 if (buf->dtb_xamot != NULL) {
11612 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11613 kmem_free(buf->dtb_xamot, buf->dtb_size);
11616 kmem_free(buf->dtb_tomax, buf->dtb_size);
11618 buf->dtb_tomax = NULL;
11619 buf->dtb_xamot = NULL;
11624 * DTrace Enabling Functions
11626 static dtrace_enabling_t *
11627 dtrace_enabling_create(dtrace_vstate_t *vstate)
11629 dtrace_enabling_t *enab;
11631 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11632 enab->dten_vstate = vstate;
11638 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11640 dtrace_ecbdesc_t **ndesc;
11641 size_t osize, nsize;
11644 * We can't add to enablings after we've enabled them, or after we've
11647 ASSERT(enab->dten_probegen == 0);
11648 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11650 if (enab->dten_ndesc < enab->dten_maxdesc) {
11651 enab->dten_desc[enab->dten_ndesc++] = ecb;
11655 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11657 if (enab->dten_maxdesc == 0) {
11658 enab->dten_maxdesc = 1;
11660 enab->dten_maxdesc <<= 1;
11663 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11665 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11666 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11667 bcopy(enab->dten_desc, ndesc, osize);
11668 if (enab->dten_desc != NULL)
11669 kmem_free(enab->dten_desc, osize);
11671 enab->dten_desc = ndesc;
11672 enab->dten_desc[enab->dten_ndesc++] = ecb;
11676 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11677 dtrace_probedesc_t *pd)
11679 dtrace_ecbdesc_t *new;
11680 dtrace_predicate_t *pred;
11681 dtrace_actdesc_t *act;
11684 * We're going to create a new ECB description that matches the
11685 * specified ECB in every way, but has the specified probe description.
11687 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11689 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11690 dtrace_predicate_hold(pred);
11692 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11693 dtrace_actdesc_hold(act);
11695 new->dted_action = ecb->dted_action;
11696 new->dted_pred = ecb->dted_pred;
11697 new->dted_probe = *pd;
11698 new->dted_uarg = ecb->dted_uarg;
11700 dtrace_enabling_add(enab, new);
11704 dtrace_enabling_dump(dtrace_enabling_t *enab)
11708 for (i = 0; i < enab->dten_ndesc; i++) {
11709 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11711 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11712 desc->dtpd_provider, desc->dtpd_mod,
11713 desc->dtpd_func, desc->dtpd_name);
11718 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11721 dtrace_ecbdesc_t *ep;
11722 dtrace_vstate_t *vstate = enab->dten_vstate;
11724 ASSERT(MUTEX_HELD(&dtrace_lock));
11726 for (i = 0; i < enab->dten_ndesc; i++) {
11727 dtrace_actdesc_t *act, *next;
11728 dtrace_predicate_t *pred;
11730 ep = enab->dten_desc[i];
11732 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11733 dtrace_predicate_release(pred, vstate);
11735 for (act = ep->dted_action; act != NULL; act = next) {
11736 next = act->dtad_next;
11737 dtrace_actdesc_release(act, vstate);
11740 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11743 if (enab->dten_desc != NULL)
11744 kmem_free(enab->dten_desc,
11745 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11748 * If this was a retained enabling, decrement the dts_nretained count
11749 * and take it off of the dtrace_retained list.
11751 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11752 dtrace_retained == enab) {
11753 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11754 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11755 enab->dten_vstate->dtvs_state->dts_nretained--;
11758 if (enab->dten_prev == NULL) {
11759 if (dtrace_retained == enab) {
11760 dtrace_retained = enab->dten_next;
11762 if (dtrace_retained != NULL)
11763 dtrace_retained->dten_prev = NULL;
11766 ASSERT(enab != dtrace_retained);
11767 ASSERT(dtrace_retained != NULL);
11768 enab->dten_prev->dten_next = enab->dten_next;
11771 if (enab->dten_next != NULL) {
11772 ASSERT(dtrace_retained != NULL);
11773 enab->dten_next->dten_prev = enab->dten_prev;
11776 kmem_free(enab, sizeof (dtrace_enabling_t));
11780 dtrace_enabling_retain(dtrace_enabling_t *enab)
11782 dtrace_state_t *state;
11784 ASSERT(MUTEX_HELD(&dtrace_lock));
11785 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11786 ASSERT(enab->dten_vstate != NULL);
11788 state = enab->dten_vstate->dtvs_state;
11789 ASSERT(state != NULL);
11792 * We only allow each state to retain dtrace_retain_max enablings.
11794 if (state->dts_nretained >= dtrace_retain_max)
11797 state->dts_nretained++;
11799 if (dtrace_retained == NULL) {
11800 dtrace_retained = enab;
11804 enab->dten_next = dtrace_retained;
11805 dtrace_retained->dten_prev = enab;
11806 dtrace_retained = enab;
11812 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11813 dtrace_probedesc_t *create)
11815 dtrace_enabling_t *new, *enab;
11816 int found = 0, err = ENOENT;
11818 ASSERT(MUTEX_HELD(&dtrace_lock));
11819 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11820 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11821 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11822 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11824 new = dtrace_enabling_create(&state->dts_vstate);
11827 * Iterate over all retained enablings, looking for enablings that
11828 * match the specified state.
11830 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11834 * dtvs_state can only be NULL for helper enablings -- and
11835 * helper enablings can't be retained.
11837 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11839 if (enab->dten_vstate->dtvs_state != state)
11843 * Now iterate over each probe description; we're looking for
11844 * an exact match to the specified probe description.
11846 for (i = 0; i < enab->dten_ndesc; i++) {
11847 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11848 dtrace_probedesc_t *pd = &ep->dted_probe;
11850 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11853 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11856 if (strcmp(pd->dtpd_func, match->dtpd_func))
11859 if (strcmp(pd->dtpd_name, match->dtpd_name))
11863 * We have a winning probe! Add it to our growing
11867 dtrace_enabling_addlike(new, ep, create);
11871 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11872 dtrace_enabling_destroy(new);
11880 dtrace_enabling_retract(dtrace_state_t *state)
11882 dtrace_enabling_t *enab, *next;
11884 ASSERT(MUTEX_HELD(&dtrace_lock));
11887 * Iterate over all retained enablings, destroy the enablings retained
11888 * for the specified state.
11890 for (enab = dtrace_retained; enab != NULL; enab = next) {
11891 next = enab->dten_next;
11894 * dtvs_state can only be NULL for helper enablings -- and
11895 * helper enablings can't be retained.
11897 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11899 if (enab->dten_vstate->dtvs_state == state) {
11900 ASSERT(state->dts_nretained > 0);
11901 dtrace_enabling_destroy(enab);
11905 ASSERT(state->dts_nretained == 0);
11909 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11914 ASSERT(MUTEX_HELD(&cpu_lock));
11915 ASSERT(MUTEX_HELD(&dtrace_lock));
11917 for (i = 0; i < enab->dten_ndesc; i++) {
11918 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11920 enab->dten_current = ep;
11921 enab->dten_error = 0;
11923 matched += dtrace_probe_enable(&ep->dted_probe, enab);
11925 if (enab->dten_error != 0) {
11927 * If we get an error half-way through enabling the
11928 * probes, we kick out -- perhaps with some number of
11929 * them enabled. Leaving enabled probes enabled may
11930 * be slightly confusing for user-level, but we expect
11931 * that no one will attempt to actually drive on in
11932 * the face of such errors. If this is an anonymous
11933 * enabling (indicated with a NULL nmatched pointer),
11934 * we cmn_err() a message. We aren't expecting to
11935 * get such an error -- such as it can exist at all,
11936 * it would be a result of corrupted DOF in the driver
11939 if (nmatched == NULL) {
11940 cmn_err(CE_WARN, "dtrace_enabling_match() "
11941 "error on %p: %d", (void *)ep,
11945 return (enab->dten_error);
11949 enab->dten_probegen = dtrace_probegen;
11950 if (nmatched != NULL)
11951 *nmatched = matched;
11957 dtrace_enabling_matchall(void)
11959 dtrace_enabling_t *enab;
11961 mutex_enter(&cpu_lock);
11962 mutex_enter(&dtrace_lock);
11965 * Iterate over all retained enablings to see if any probes match
11966 * against them. We only perform this operation on enablings for which
11967 * we have sufficient permissions by virtue of being in the global zone
11968 * or in the same zone as the DTrace client. Because we can be called
11969 * after dtrace_detach() has been called, we cannot assert that there
11970 * are retained enablings. We can safely load from dtrace_retained,
11971 * however: the taskq_destroy() at the end of dtrace_detach() will
11972 * block pending our completion.
11974 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11976 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11978 if (INGLOBALZONE(curproc) || getzoneid() == crgetzoneid(cr))
11980 (void) dtrace_enabling_match(enab, NULL);
11983 mutex_exit(&dtrace_lock);
11984 mutex_exit(&cpu_lock);
11988 * If an enabling is to be enabled without having matched probes (that is, if
11989 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11990 * enabling must be _primed_ by creating an ECB for every ECB description.
11991 * This must be done to assure that we know the number of speculations, the
11992 * number of aggregations, the minimum buffer size needed, etc. before we
11993 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11994 * enabling any probes, we create ECBs for every ECB decription, but with a
11995 * NULL probe -- which is exactly what this function does.
11998 dtrace_enabling_prime(dtrace_state_t *state)
12000 dtrace_enabling_t *enab;
12003 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12004 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12006 if (enab->dten_vstate->dtvs_state != state)
12010 * We don't want to prime an enabling more than once, lest
12011 * we allow a malicious user to induce resource exhaustion.
12012 * (The ECBs that result from priming an enabling aren't
12013 * leaked -- but they also aren't deallocated until the
12014 * consumer state is destroyed.)
12016 if (enab->dten_primed)
12019 for (i = 0; i < enab->dten_ndesc; i++) {
12020 enab->dten_current = enab->dten_desc[i];
12021 (void) dtrace_probe_enable(NULL, enab);
12024 enab->dten_primed = 1;
12029 * Called to indicate that probes should be provided due to retained
12030 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
12031 * must take an initial lap through the enabling calling the dtps_provide()
12032 * entry point explicitly to allow for autocreated probes.
12035 dtrace_enabling_provide(dtrace_provider_t *prv)
12038 dtrace_probedesc_t desc;
12040 ASSERT(MUTEX_HELD(&dtrace_lock));
12041 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12045 prv = dtrace_provider;
12049 dtrace_enabling_t *enab = dtrace_retained;
12050 void *parg = prv->dtpv_arg;
12052 for (; enab != NULL; enab = enab->dten_next) {
12053 for (i = 0; i < enab->dten_ndesc; i++) {
12054 desc = enab->dten_desc[i]->dted_probe;
12055 mutex_exit(&dtrace_lock);
12056 prv->dtpv_pops.dtps_provide(parg, &desc);
12057 mutex_enter(&dtrace_lock);
12060 } while (all && (prv = prv->dtpv_next) != NULL);
12062 mutex_exit(&dtrace_lock);
12063 dtrace_probe_provide(NULL, all ? NULL : prv);
12064 mutex_enter(&dtrace_lock);
12068 * Called to reap ECBs that are attached to probes from defunct providers.
12071 dtrace_enabling_reap(void)
12073 dtrace_provider_t *prov;
12074 dtrace_probe_t *probe;
12079 mutex_enter(&cpu_lock);
12080 mutex_enter(&dtrace_lock);
12082 for (i = 0; i < dtrace_nprobes; i++) {
12083 if ((probe = dtrace_probes[i]) == NULL)
12086 if (probe->dtpr_ecb == NULL)
12089 prov = probe->dtpr_provider;
12091 if ((when = prov->dtpv_defunct) == 0)
12095 * We have ECBs on a defunct provider: we want to reap these
12096 * ECBs to allow the provider to unregister. The destruction
12097 * of these ECBs must be done carefully: if we destroy the ECB
12098 * and the consumer later wishes to consume an EPID that
12099 * corresponds to the destroyed ECB (and if the EPID metadata
12100 * has not been previously consumed), the consumer will abort
12101 * processing on the unknown EPID. To reduce (but not, sadly,
12102 * eliminate) the possibility of this, we will only destroy an
12103 * ECB for a defunct provider if, for the state that
12104 * corresponds to the ECB:
12106 * (a) There is no speculative tracing (which can effectively
12107 * cache an EPID for an arbitrary amount of time).
12109 * (b) The principal buffers have been switched twice since the
12110 * provider became defunct.
12112 * (c) The aggregation buffers are of zero size or have been
12113 * switched twice since the provider became defunct.
12115 * We use dts_speculates to determine (a) and call a function
12116 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
12117 * that as soon as we've been unable to destroy one of the ECBs
12118 * associated with the probe, we quit trying -- reaping is only
12119 * fruitful in as much as we can destroy all ECBs associated
12120 * with the defunct provider's probes.
12122 while ((ecb = probe->dtpr_ecb) != NULL) {
12123 dtrace_state_t *state = ecb->dte_state;
12124 dtrace_buffer_t *buf = state->dts_buffer;
12125 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12127 if (state->dts_speculates)
12130 if (!dtrace_buffer_consumed(buf, when))
12133 if (!dtrace_buffer_consumed(aggbuf, when))
12136 dtrace_ecb_disable(ecb);
12137 ASSERT(probe->dtpr_ecb != ecb);
12138 dtrace_ecb_destroy(ecb);
12142 mutex_exit(&dtrace_lock);
12143 mutex_exit(&cpu_lock);
12147 * DTrace DOF Functions
12151 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12153 if (dtrace_err_verbose)
12154 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12156 #ifdef DTRACE_ERRDEBUG
12157 dtrace_errdebug(str);
12162 * Create DOF out of a currently enabled state. Right now, we only create
12163 * DOF containing the run-time options -- but this could be expanded to create
12164 * complete DOF representing the enabled state.
12167 dtrace_dof_create(dtrace_state_t *state)
12171 dof_optdesc_t *opt;
12172 int i, len = sizeof (dof_hdr_t) +
12173 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12174 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12176 ASSERT(MUTEX_HELD(&dtrace_lock));
12178 dof = kmem_zalloc(len, KM_SLEEP);
12179 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12180 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12181 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12182 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12184 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12185 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12186 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12187 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12188 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12189 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12191 dof->dofh_flags = 0;
12192 dof->dofh_hdrsize = sizeof (dof_hdr_t);
12193 dof->dofh_secsize = sizeof (dof_sec_t);
12194 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
12195 dof->dofh_secoff = sizeof (dof_hdr_t);
12196 dof->dofh_loadsz = len;
12197 dof->dofh_filesz = len;
12201 * Fill in the option section header...
12203 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12204 sec->dofs_type = DOF_SECT_OPTDESC;
12205 sec->dofs_align = sizeof (uint64_t);
12206 sec->dofs_flags = DOF_SECF_LOAD;
12207 sec->dofs_entsize = sizeof (dof_optdesc_t);
12209 opt = (dof_optdesc_t *)((uintptr_t)sec +
12210 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12212 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12213 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12215 for (i = 0; i < DTRACEOPT_MAX; i++) {
12216 opt[i].dofo_option = i;
12217 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12218 opt[i].dofo_value = state->dts_options[i];
12225 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12227 dof_hdr_t hdr, *dof;
12229 ASSERT(!MUTEX_HELD(&dtrace_lock));
12232 * First, we're going to copyin() the sizeof (dof_hdr_t).
12234 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12235 dtrace_dof_error(NULL, "failed to copyin DOF header");
12241 * Now we'll allocate the entire DOF and copy it in -- provided
12242 * that the length isn't outrageous.
12244 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12245 dtrace_dof_error(&hdr, "load size exceeds maximum");
12250 if (hdr.dofh_loadsz < sizeof (hdr)) {
12251 dtrace_dof_error(&hdr, "invalid load size");
12256 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12258 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
12259 kmem_free(dof, hdr.dofh_loadsz);
12268 static __inline uchar_t
12269 dtrace_dof_char(char c) {
12288 return (c - 'A' + 10);
12295 return (c - 'a' + 10);
12297 /* Should not reach here. */
12303 dtrace_dof_property(const char *name)
12307 unsigned int len, i;
12312 * Unfortunately, array of values in .conf files are always (and
12313 * only) interpreted to be integer arrays. We must read our DOF
12314 * as an integer array, and then squeeze it into a byte array.
12316 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12317 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12320 for (i = 0; i < len; i++)
12321 buf[i] = (uchar_t)(((int *)buf)[i]);
12323 if (len < sizeof (dof_hdr_t)) {
12324 ddi_prop_free(buf);
12325 dtrace_dof_error(NULL, "truncated header");
12329 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12330 ddi_prop_free(buf);
12331 dtrace_dof_error(NULL, "truncated DOF");
12335 if (loadsz >= dtrace_dof_maxsize) {
12336 ddi_prop_free(buf);
12337 dtrace_dof_error(NULL, "oversized DOF");
12341 dof = kmem_alloc(loadsz, KM_SLEEP);
12342 bcopy(buf, dof, loadsz);
12343 ddi_prop_free(buf);
12348 if ((p_env = getenv(name)) == NULL)
12351 len = strlen(p_env) / 2;
12353 buf = kmem_alloc(len, KM_SLEEP);
12355 dof = (dof_hdr_t *) buf;
12359 for (i = 0; i < len; i++) {
12360 buf[i] = (dtrace_dof_char(p[0]) << 4) |
12361 dtrace_dof_char(p[1]);
12367 if (len < sizeof (dof_hdr_t)) {
12369 dtrace_dof_error(NULL, "truncated header");
12373 if (len < (loadsz = dof->dofh_loadsz)) {
12375 dtrace_dof_error(NULL, "truncated DOF");
12379 if (loadsz >= dtrace_dof_maxsize) {
12381 dtrace_dof_error(NULL, "oversized DOF");
12390 dtrace_dof_destroy(dof_hdr_t *dof)
12392 kmem_free(dof, dof->dofh_loadsz);
12396 * Return the dof_sec_t pointer corresponding to a given section index. If the
12397 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
12398 * a type other than DOF_SECT_NONE is specified, the header is checked against
12399 * this type and NULL is returned if the types do not match.
12402 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12404 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12405 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12407 if (i >= dof->dofh_secnum) {
12408 dtrace_dof_error(dof, "referenced section index is invalid");
12412 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12413 dtrace_dof_error(dof, "referenced section is not loadable");
12417 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12418 dtrace_dof_error(dof, "referenced section is the wrong type");
12425 static dtrace_probedesc_t *
12426 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12428 dof_probedesc_t *probe;
12430 uintptr_t daddr = (uintptr_t)dof;
12434 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12435 dtrace_dof_error(dof, "invalid probe section");
12439 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12440 dtrace_dof_error(dof, "bad alignment in probe description");
12444 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12445 dtrace_dof_error(dof, "truncated probe description");
12449 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12450 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12452 if (strtab == NULL)
12455 str = daddr + strtab->dofs_offset;
12456 size = strtab->dofs_size;
12458 if (probe->dofp_provider >= strtab->dofs_size) {
12459 dtrace_dof_error(dof, "corrupt probe provider");
12463 (void) strncpy(desc->dtpd_provider,
12464 (char *)(str + probe->dofp_provider),
12465 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12467 if (probe->dofp_mod >= strtab->dofs_size) {
12468 dtrace_dof_error(dof, "corrupt probe module");
12472 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12473 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12475 if (probe->dofp_func >= strtab->dofs_size) {
12476 dtrace_dof_error(dof, "corrupt probe function");
12480 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12481 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12483 if (probe->dofp_name >= strtab->dofs_size) {
12484 dtrace_dof_error(dof, "corrupt probe name");
12488 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12489 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12494 static dtrace_difo_t *
12495 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12500 dof_difohdr_t *dofd;
12501 uintptr_t daddr = (uintptr_t)dof;
12502 size_t max = dtrace_difo_maxsize;
12505 static const struct {
12513 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12514 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12515 sizeof (dif_instr_t), "multiple DIF sections" },
12517 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12518 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12519 sizeof (uint64_t), "multiple integer tables" },
12521 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12522 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12523 sizeof (char), "multiple string tables" },
12525 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12526 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12527 sizeof (uint_t), "multiple variable tables" },
12529 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12532 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12533 dtrace_dof_error(dof, "invalid DIFO header section");
12537 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12538 dtrace_dof_error(dof, "bad alignment in DIFO header");
12542 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12543 sec->dofs_size % sizeof (dof_secidx_t)) {
12544 dtrace_dof_error(dof, "bad size in DIFO header");
12548 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12549 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12551 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12552 dp->dtdo_rtype = dofd->dofd_rtype;
12554 for (l = 0; l < n; l++) {
12559 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12560 dofd->dofd_links[l])) == NULL)
12561 goto err; /* invalid section link */
12563 if (ttl + subsec->dofs_size > max) {
12564 dtrace_dof_error(dof, "exceeds maximum size");
12568 ttl += subsec->dofs_size;
12570 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12571 if (subsec->dofs_type != difo[i].section)
12574 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12575 dtrace_dof_error(dof, "section not loaded");
12579 if (subsec->dofs_align != difo[i].align) {
12580 dtrace_dof_error(dof, "bad alignment");
12584 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12585 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12587 if (*bufp != NULL) {
12588 dtrace_dof_error(dof, difo[i].msg);
12592 if (difo[i].entsize != subsec->dofs_entsize) {
12593 dtrace_dof_error(dof, "entry size mismatch");
12597 if (subsec->dofs_entsize != 0 &&
12598 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12599 dtrace_dof_error(dof, "corrupt entry size");
12603 *lenp = subsec->dofs_size;
12604 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12605 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12606 *bufp, subsec->dofs_size);
12608 if (subsec->dofs_entsize != 0)
12609 *lenp /= subsec->dofs_entsize;
12615 * If we encounter a loadable DIFO sub-section that is not
12616 * known to us, assume this is a broken program and fail.
12618 if (difo[i].section == DOF_SECT_NONE &&
12619 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12620 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12625 if (dp->dtdo_buf == NULL) {
12627 * We can't have a DIF object without DIF text.
12629 dtrace_dof_error(dof, "missing DIF text");
12634 * Before we validate the DIF object, run through the variable table
12635 * looking for the strings -- if any of their size are under, we'll set
12636 * their size to be the system-wide default string size. Note that
12637 * this should _not_ happen if the "strsize" option has been set --
12638 * in this case, the compiler should have set the size to reflect the
12639 * setting of the option.
12641 for (i = 0; i < dp->dtdo_varlen; i++) {
12642 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12643 dtrace_diftype_t *t = &v->dtdv_type;
12645 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12648 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12649 t->dtdt_size = dtrace_strsize_default;
12652 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12655 dtrace_difo_init(dp, vstate);
12659 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12660 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12661 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12662 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12664 kmem_free(dp, sizeof (dtrace_difo_t));
12668 static dtrace_predicate_t *
12669 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12674 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12677 return (dtrace_predicate_create(dp));
12680 static dtrace_actdesc_t *
12681 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12684 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12685 dof_actdesc_t *desc;
12686 dof_sec_t *difosec;
12688 uintptr_t daddr = (uintptr_t)dof;
12690 dtrace_actkind_t kind;
12692 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12693 dtrace_dof_error(dof, "invalid action section");
12697 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12698 dtrace_dof_error(dof, "truncated action description");
12702 if (sec->dofs_align != sizeof (uint64_t)) {
12703 dtrace_dof_error(dof, "bad alignment in action description");
12707 if (sec->dofs_size < sec->dofs_entsize) {
12708 dtrace_dof_error(dof, "section entry size exceeds total size");
12712 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12713 dtrace_dof_error(dof, "bad entry size in action description");
12717 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12718 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12722 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12723 desc = (dof_actdesc_t *)(daddr +
12724 (uintptr_t)sec->dofs_offset + offs);
12725 kind = (dtrace_actkind_t)desc->dofa_kind;
12727 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12728 (kind != DTRACEACT_PRINTA ||
12729 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12730 (kind == DTRACEACT_DIFEXPR &&
12731 desc->dofa_strtab != DOF_SECIDX_NONE)) {
12737 * The argument to these actions is an index into the
12738 * DOF string table. For printf()-like actions, this
12739 * is the format string. For print(), this is the
12740 * CTF type of the expression result.
12742 if ((strtab = dtrace_dof_sect(dof,
12743 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12746 str = (char *)((uintptr_t)dof +
12747 (uintptr_t)strtab->dofs_offset);
12749 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12750 if (str[i] == '\0')
12754 if (i >= strtab->dofs_size) {
12755 dtrace_dof_error(dof, "bogus format string");
12759 if (i == desc->dofa_arg) {
12760 dtrace_dof_error(dof, "empty format string");
12764 i -= desc->dofa_arg;
12765 fmt = kmem_alloc(i + 1, KM_SLEEP);
12766 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12767 arg = (uint64_t)(uintptr_t)fmt;
12769 if (kind == DTRACEACT_PRINTA) {
12770 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12773 arg = desc->dofa_arg;
12777 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12778 desc->dofa_uarg, arg);
12780 if (last != NULL) {
12781 last->dtad_next = act;
12788 if (desc->dofa_difo == DOF_SECIDX_NONE)
12791 if ((difosec = dtrace_dof_sect(dof,
12792 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12795 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12797 if (act->dtad_difo == NULL)
12801 ASSERT(first != NULL);
12805 for (act = first; act != NULL; act = next) {
12806 next = act->dtad_next;
12807 dtrace_actdesc_release(act, vstate);
12813 static dtrace_ecbdesc_t *
12814 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12817 dtrace_ecbdesc_t *ep;
12818 dof_ecbdesc_t *ecb;
12819 dtrace_probedesc_t *desc;
12820 dtrace_predicate_t *pred = NULL;
12822 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12823 dtrace_dof_error(dof, "truncated ECB description");
12827 if (sec->dofs_align != sizeof (uint64_t)) {
12828 dtrace_dof_error(dof, "bad alignment in ECB description");
12832 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12833 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12838 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12839 ep->dted_uarg = ecb->dofe_uarg;
12840 desc = &ep->dted_probe;
12842 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12845 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12846 if ((sec = dtrace_dof_sect(dof,
12847 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12850 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12853 ep->dted_pred.dtpdd_predicate = pred;
12856 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12857 if ((sec = dtrace_dof_sect(dof,
12858 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12861 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12863 if (ep->dted_action == NULL)
12871 dtrace_predicate_release(pred, vstate);
12872 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12877 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12878 * specified DOF. At present, this amounts to simply adding 'ubase' to the
12879 * site of any user SETX relocations to account for load object base address.
12880 * In the future, if we need other relocations, this function can be extended.
12883 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12885 uintptr_t daddr = (uintptr_t)dof;
12886 dof_relohdr_t *dofr =
12887 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12888 dof_sec_t *ss, *rs, *ts;
12892 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12893 sec->dofs_align != sizeof (dof_secidx_t)) {
12894 dtrace_dof_error(dof, "invalid relocation header");
12898 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12899 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12900 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12902 if (ss == NULL || rs == NULL || ts == NULL)
12903 return (-1); /* dtrace_dof_error() has been called already */
12905 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12906 rs->dofs_align != sizeof (uint64_t)) {
12907 dtrace_dof_error(dof, "invalid relocation section");
12911 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12912 n = rs->dofs_size / rs->dofs_entsize;
12914 for (i = 0; i < n; i++) {
12915 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12917 switch (r->dofr_type) {
12918 case DOF_RELO_NONE:
12920 case DOF_RELO_SETX:
12921 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12922 sizeof (uint64_t) > ts->dofs_size) {
12923 dtrace_dof_error(dof, "bad relocation offset");
12927 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12928 dtrace_dof_error(dof, "misaligned setx relo");
12932 *(uint64_t *)taddr += ubase;
12935 dtrace_dof_error(dof, "invalid relocation type");
12939 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12946 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12947 * header: it should be at the front of a memory region that is at least
12948 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12949 * size. It need not be validated in any other way.
12952 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12953 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12955 uint64_t len = dof->dofh_loadsz, seclen;
12956 uintptr_t daddr = (uintptr_t)dof;
12957 dtrace_ecbdesc_t *ep;
12958 dtrace_enabling_t *enab;
12961 ASSERT(MUTEX_HELD(&dtrace_lock));
12962 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12965 * Check the DOF header identification bytes. In addition to checking
12966 * valid settings, we also verify that unused bits/bytes are zeroed so
12967 * we can use them later without fear of regressing existing binaries.
12969 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12970 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12971 dtrace_dof_error(dof, "DOF magic string mismatch");
12975 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12976 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12977 dtrace_dof_error(dof, "DOF has invalid data model");
12981 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12982 dtrace_dof_error(dof, "DOF encoding mismatch");
12986 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12987 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12988 dtrace_dof_error(dof, "DOF version mismatch");
12992 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12993 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12997 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12998 dtrace_dof_error(dof, "DOF uses too many integer registers");
13002 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13003 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13007 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13008 if (dof->dofh_ident[i] != 0) {
13009 dtrace_dof_error(dof, "DOF has invalid ident byte set");
13014 if (dof->dofh_flags & ~DOF_FL_VALID) {
13015 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13019 if (dof->dofh_secsize == 0) {
13020 dtrace_dof_error(dof, "zero section header size");
13025 * Check that the section headers don't exceed the amount of DOF
13026 * data. Note that we cast the section size and number of sections
13027 * to uint64_t's to prevent possible overflow in the multiplication.
13029 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13031 if (dof->dofh_secoff > len || seclen > len ||
13032 dof->dofh_secoff + seclen > len) {
13033 dtrace_dof_error(dof, "truncated section headers");
13037 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13038 dtrace_dof_error(dof, "misaligned section headers");
13042 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13043 dtrace_dof_error(dof, "misaligned section size");
13048 * Take an initial pass through the section headers to be sure that
13049 * the headers don't have stray offsets. If the 'noprobes' flag is
13050 * set, do not permit sections relating to providers, probes, or args.
13052 for (i = 0; i < dof->dofh_secnum; i++) {
13053 dof_sec_t *sec = (dof_sec_t *)(daddr +
13054 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13057 switch (sec->dofs_type) {
13058 case DOF_SECT_PROVIDER:
13059 case DOF_SECT_PROBES:
13060 case DOF_SECT_PRARGS:
13061 case DOF_SECT_PROFFS:
13062 dtrace_dof_error(dof, "illegal sections "
13068 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13069 continue; /* just ignore non-loadable sections */
13071 if (sec->dofs_align & (sec->dofs_align - 1)) {
13072 dtrace_dof_error(dof, "bad section alignment");
13076 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13077 dtrace_dof_error(dof, "misaligned section");
13081 if (sec->dofs_offset > len || sec->dofs_size > len ||
13082 sec->dofs_offset + sec->dofs_size > len) {
13083 dtrace_dof_error(dof, "corrupt section header");
13087 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13088 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13089 dtrace_dof_error(dof, "non-terminating string table");
13095 * Take a second pass through the sections and locate and perform any
13096 * relocations that are present. We do this after the first pass to
13097 * be sure that all sections have had their headers validated.
13099 for (i = 0; i < dof->dofh_secnum; i++) {
13100 dof_sec_t *sec = (dof_sec_t *)(daddr +
13101 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13103 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13104 continue; /* skip sections that are not loadable */
13106 switch (sec->dofs_type) {
13107 case DOF_SECT_URELHDR:
13108 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13114 if ((enab = *enabp) == NULL)
13115 enab = *enabp = dtrace_enabling_create(vstate);
13117 for (i = 0; i < dof->dofh_secnum; i++) {
13118 dof_sec_t *sec = (dof_sec_t *)(daddr +
13119 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13121 if (sec->dofs_type != DOF_SECT_ECBDESC)
13124 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13125 dtrace_enabling_destroy(enab);
13130 dtrace_enabling_add(enab, ep);
13137 * Process DOF for any options. This routine assumes that the DOF has been
13138 * at least processed by dtrace_dof_slurp().
13141 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13146 dof_optdesc_t *desc;
13148 for (i = 0; i < dof->dofh_secnum; i++) {
13149 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13150 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13152 if (sec->dofs_type != DOF_SECT_OPTDESC)
13155 if (sec->dofs_align != sizeof (uint64_t)) {
13156 dtrace_dof_error(dof, "bad alignment in "
13157 "option description");
13161 if ((entsize = sec->dofs_entsize) == 0) {
13162 dtrace_dof_error(dof, "zeroed option entry size");
13166 if (entsize < sizeof (dof_optdesc_t)) {
13167 dtrace_dof_error(dof, "bad option entry size");
13171 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13172 desc = (dof_optdesc_t *)((uintptr_t)dof +
13173 (uintptr_t)sec->dofs_offset + offs);
13175 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13176 dtrace_dof_error(dof, "non-zero option string");
13180 if (desc->dofo_value == DTRACEOPT_UNSET) {
13181 dtrace_dof_error(dof, "unset option");
13185 if ((rval = dtrace_state_option(state,
13186 desc->dofo_option, desc->dofo_value)) != 0) {
13187 dtrace_dof_error(dof, "rejected option");
13197 * DTrace Consumer State Functions
13200 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13202 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13205 dtrace_dynvar_t *dvar, *next, *start;
13208 ASSERT(MUTEX_HELD(&dtrace_lock));
13209 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13211 bzero(dstate, sizeof (dtrace_dstate_t));
13213 if ((dstate->dtds_chunksize = chunksize) == 0)
13214 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13216 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13219 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13222 dstate->dtds_size = size;
13223 dstate->dtds_base = base;
13224 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13225 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13227 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13229 if (hashsize != 1 && (hashsize & 1))
13232 dstate->dtds_hashsize = hashsize;
13233 dstate->dtds_hash = dstate->dtds_base;
13236 * Set all of our hash buckets to point to the single sink, and (if
13237 * it hasn't already been set), set the sink's hash value to be the
13238 * sink sentinel value. The sink is needed for dynamic variable
13239 * lookups to know that they have iterated over an entire, valid hash
13242 for (i = 0; i < hashsize; i++)
13243 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13245 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13246 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13249 * Determine number of active CPUs. Divide free list evenly among
13252 start = (dtrace_dynvar_t *)
13253 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13254 limit = (uintptr_t)base + size;
13256 maxper = (limit - (uintptr_t)start) / NCPU;
13257 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13262 for (i = 0; i < NCPU; i++) {
13264 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13267 * If we don't even have enough chunks to make it once through
13268 * NCPUs, we're just going to allocate everything to the first
13269 * CPU. And if we're on the last CPU, we're going to allocate
13270 * whatever is left over. In either case, we set the limit to
13271 * be the limit of the dynamic variable space.
13273 if (maxper == 0 || i == NCPU - 1) {
13274 limit = (uintptr_t)base + size;
13277 limit = (uintptr_t)start + maxper;
13278 start = (dtrace_dynvar_t *)limit;
13281 ASSERT(limit <= (uintptr_t)base + size);
13284 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13285 dstate->dtds_chunksize);
13287 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13290 dvar->dtdv_next = next;
13302 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13304 ASSERT(MUTEX_HELD(&cpu_lock));
13306 if (dstate->dtds_base == NULL)
13309 kmem_free(dstate->dtds_base, dstate->dtds_size);
13310 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13314 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13317 * Logical XOR, where are you?
13319 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13321 if (vstate->dtvs_nglobals > 0) {
13322 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13323 sizeof (dtrace_statvar_t *));
13326 if (vstate->dtvs_ntlocals > 0) {
13327 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13328 sizeof (dtrace_difv_t));
13331 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13333 if (vstate->dtvs_nlocals > 0) {
13334 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13335 sizeof (dtrace_statvar_t *));
13341 dtrace_state_clean(dtrace_state_t *state)
13343 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13346 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13347 dtrace_speculation_clean(state);
13351 dtrace_state_deadman(dtrace_state_t *state)
13357 now = dtrace_gethrtime();
13359 if (state != dtrace_anon.dta_state &&
13360 now - state->dts_laststatus >= dtrace_deadman_user)
13364 * We must be sure that dts_alive never appears to be less than the
13365 * value upon entry to dtrace_state_deadman(), and because we lack a
13366 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13367 * store INT64_MAX to it, followed by a memory barrier, followed by
13368 * the new value. This assures that dts_alive never appears to be
13369 * less than its true value, regardless of the order in which the
13370 * stores to the underlying storage are issued.
13372 state->dts_alive = INT64_MAX;
13373 dtrace_membar_producer();
13374 state->dts_alive = now;
13378 dtrace_state_clean(void *arg)
13380 dtrace_state_t *state = arg;
13381 dtrace_optval_t *opt = state->dts_options;
13383 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13386 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13387 dtrace_speculation_clean(state);
13389 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13390 dtrace_state_clean, state);
13394 dtrace_state_deadman(void *arg)
13396 dtrace_state_t *state = arg;
13401 dtrace_debug_output();
13403 now = dtrace_gethrtime();
13405 if (state != dtrace_anon.dta_state &&
13406 now - state->dts_laststatus >= dtrace_deadman_user)
13410 * We must be sure that dts_alive never appears to be less than the
13411 * value upon entry to dtrace_state_deadman(), and because we lack a
13412 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13413 * store INT64_MAX to it, followed by a memory barrier, followed by
13414 * the new value. This assures that dts_alive never appears to be
13415 * less than its true value, regardless of the order in which the
13416 * stores to the underlying storage are issued.
13418 state->dts_alive = INT64_MAX;
13419 dtrace_membar_producer();
13420 state->dts_alive = now;
13422 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13423 dtrace_state_deadman, state);
13427 static dtrace_state_t *
13429 dtrace_state_create(dev_t *devp, cred_t *cr)
13431 dtrace_state_create(struct cdev *dev)
13442 dtrace_state_t *state;
13443 dtrace_optval_t *opt;
13444 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13446 ASSERT(MUTEX_HELD(&dtrace_lock));
13447 ASSERT(MUTEX_HELD(&cpu_lock));
13450 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13451 VM_BESTFIT | VM_SLEEP);
13453 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13454 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13458 state = ddi_get_soft_state(dtrace_softstate, minor);
13465 /* Allocate memory for the state. */
13466 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13469 state->dts_epid = DTRACE_EPIDNONE + 1;
13471 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13473 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13474 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13476 if (devp != NULL) {
13477 major = getemajor(*devp);
13479 major = ddi_driver_major(dtrace_devi);
13482 state->dts_dev = makedevice(major, minor);
13485 *devp = state->dts_dev;
13487 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13488 state->dts_dev = dev;
13492 * We allocate NCPU buffers. On the one hand, this can be quite
13493 * a bit of memory per instance (nearly 36K on a Starcat). On the
13494 * other hand, it saves an additional memory reference in the probe
13497 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13498 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13501 state->dts_cleaner = CYCLIC_NONE;
13502 state->dts_deadman = CYCLIC_NONE;
13504 callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13505 callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13507 state->dts_vstate.dtvs_state = state;
13509 for (i = 0; i < DTRACEOPT_MAX; i++)
13510 state->dts_options[i] = DTRACEOPT_UNSET;
13513 * Set the default options.
13515 opt = state->dts_options;
13516 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13517 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13518 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13519 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13520 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13521 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13522 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13523 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13524 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13525 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13526 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13527 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13528 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13529 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13531 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13534 * Depending on the user credentials, we set flag bits which alter probe
13535 * visibility or the amount of destructiveness allowed. In the case of
13536 * actual anonymous tracing, or the possession of all privileges, all of
13537 * the normal checks are bypassed.
13539 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13540 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13541 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13544 * Set up the credentials for this instantiation. We take a
13545 * hold on the credential to prevent it from disappearing on
13546 * us; this in turn prevents the zone_t referenced by this
13547 * credential from disappearing. This means that we can
13548 * examine the credential and the zone from probe context.
13551 state->dts_cred.dcr_cred = cr;
13554 * CRA_PROC means "we have *some* privilege for dtrace" and
13555 * unlocks the use of variables like pid, zonename, etc.
13557 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13558 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13559 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13563 * dtrace_user allows use of syscall and profile providers.
13564 * If the user also has proc_owner and/or proc_zone, we
13565 * extend the scope to include additional visibility and
13566 * destructive power.
13568 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13569 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13570 state->dts_cred.dcr_visible |=
13571 DTRACE_CRV_ALLPROC;
13573 state->dts_cred.dcr_action |=
13574 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13577 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13578 state->dts_cred.dcr_visible |=
13579 DTRACE_CRV_ALLZONE;
13581 state->dts_cred.dcr_action |=
13582 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13586 * If we have all privs in whatever zone this is,
13587 * we can do destructive things to processes which
13588 * have altered credentials.
13591 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13592 cr->cr_zone->zone_privset)) {
13593 state->dts_cred.dcr_action |=
13594 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13600 * Holding the dtrace_kernel privilege also implies that
13601 * the user has the dtrace_user privilege from a visibility
13602 * perspective. But without further privileges, some
13603 * destructive actions are not available.
13605 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13607 * Make all probes in all zones visible. However,
13608 * this doesn't mean that all actions become available
13611 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13612 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13614 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13617 * Holding proc_owner means that destructive actions
13618 * for *this* zone are allowed.
13620 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13621 state->dts_cred.dcr_action |=
13622 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13625 * Holding proc_zone means that destructive actions
13626 * for this user/group ID in all zones is allowed.
13628 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13629 state->dts_cred.dcr_action |=
13630 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13634 * If we have all privs in whatever zone this is,
13635 * we can do destructive things to processes which
13636 * have altered credentials.
13638 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13639 cr->cr_zone->zone_privset)) {
13640 state->dts_cred.dcr_action |=
13641 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13647 * Holding the dtrace_proc privilege gives control over fasttrap
13648 * and pid providers. We need to grant wider destructive
13649 * privileges in the event that the user has proc_owner and/or
13652 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13653 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13654 state->dts_cred.dcr_action |=
13655 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13657 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13658 state->dts_cred.dcr_action |=
13659 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13667 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13669 dtrace_optval_t *opt = state->dts_options, size;
13670 processorid_t cpu = 0;;
13671 int flags = 0, rval, factor, divisor = 1;
13673 ASSERT(MUTEX_HELD(&dtrace_lock));
13674 ASSERT(MUTEX_HELD(&cpu_lock));
13675 ASSERT(which < DTRACEOPT_MAX);
13676 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13677 (state == dtrace_anon.dta_state &&
13678 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13680 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13683 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13684 cpu = opt[DTRACEOPT_CPU];
13686 if (which == DTRACEOPT_SPECSIZE)
13687 flags |= DTRACEBUF_NOSWITCH;
13689 if (which == DTRACEOPT_BUFSIZE) {
13690 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13691 flags |= DTRACEBUF_RING;
13693 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13694 flags |= DTRACEBUF_FILL;
13696 if (state != dtrace_anon.dta_state ||
13697 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13698 flags |= DTRACEBUF_INACTIVE;
13701 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13703 * The size must be 8-byte aligned. If the size is not 8-byte
13704 * aligned, drop it down by the difference.
13706 if (size & (sizeof (uint64_t) - 1))
13707 size -= size & (sizeof (uint64_t) - 1);
13709 if (size < state->dts_reserve) {
13711 * Buffers always must be large enough to accommodate
13712 * their prereserved space. We return E2BIG instead
13713 * of ENOMEM in this case to allow for user-level
13714 * software to differentiate the cases.
13719 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13721 if (rval != ENOMEM) {
13726 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13729 for (divisor = 2; divisor < factor; divisor <<= 1)
13737 dtrace_state_buffers(dtrace_state_t *state)
13739 dtrace_speculation_t *spec = state->dts_speculations;
13742 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13743 DTRACEOPT_BUFSIZE)) != 0)
13746 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13747 DTRACEOPT_AGGSIZE)) != 0)
13750 for (i = 0; i < state->dts_nspeculations; i++) {
13751 if ((rval = dtrace_state_buffer(state,
13752 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13760 dtrace_state_prereserve(dtrace_state_t *state)
13763 dtrace_probe_t *probe;
13765 state->dts_reserve = 0;
13767 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13771 * If our buffer policy is a "fill" buffer policy, we need to set the
13772 * prereserved space to be the space required by the END probes.
13774 probe = dtrace_probes[dtrace_probeid_end - 1];
13775 ASSERT(probe != NULL);
13777 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13778 if (ecb->dte_state != state)
13781 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13786 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13788 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13789 dtrace_speculation_t *spec;
13790 dtrace_buffer_t *buf;
13792 cyc_handler_t hdlr;
13795 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13796 dtrace_icookie_t cookie;
13798 mutex_enter(&cpu_lock);
13799 mutex_enter(&dtrace_lock);
13801 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13807 * Before we can perform any checks, we must prime all of the
13808 * retained enablings that correspond to this state.
13810 dtrace_enabling_prime(state);
13812 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13817 dtrace_state_prereserve(state);
13820 * Now we want to do is try to allocate our speculations.
13821 * We do not automatically resize the number of speculations; if
13822 * this fails, we will fail the operation.
13824 nspec = opt[DTRACEOPT_NSPEC];
13825 ASSERT(nspec != DTRACEOPT_UNSET);
13827 if (nspec > INT_MAX) {
13832 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13833 KM_NOSLEEP | KM_NORMALPRI);
13835 if (spec == NULL) {
13840 state->dts_speculations = spec;
13841 state->dts_nspeculations = (int)nspec;
13843 for (i = 0; i < nspec; i++) {
13844 if ((buf = kmem_zalloc(bufsize,
13845 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13850 spec[i].dtsp_buffer = buf;
13853 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13854 if (dtrace_anon.dta_state == NULL) {
13859 if (state->dts_necbs != 0) {
13864 state->dts_anon = dtrace_anon_grab();
13865 ASSERT(state->dts_anon != NULL);
13866 state = state->dts_anon;
13869 * We want "grabanon" to be set in the grabbed state, so we'll
13870 * copy that option value from the grabbing state into the
13873 state->dts_options[DTRACEOPT_GRABANON] =
13874 opt[DTRACEOPT_GRABANON];
13876 *cpu = dtrace_anon.dta_beganon;
13879 * If the anonymous state is active (as it almost certainly
13880 * is if the anonymous enabling ultimately matched anything),
13881 * we don't allow any further option processing -- but we
13882 * don't return failure.
13884 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13888 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13889 opt[DTRACEOPT_AGGSIZE] != 0) {
13890 if (state->dts_aggregations == NULL) {
13892 * We're not going to create an aggregation buffer
13893 * because we don't have any ECBs that contain
13894 * aggregations -- set this option to 0.
13896 opt[DTRACEOPT_AGGSIZE] = 0;
13899 * If we have an aggregation buffer, we must also have
13900 * a buffer to use as scratch.
13902 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13903 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13904 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13909 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13910 opt[DTRACEOPT_SPECSIZE] != 0) {
13911 if (!state->dts_speculates) {
13913 * We're not going to create speculation buffers
13914 * because we don't have any ECBs that actually
13915 * speculate -- set the speculation size to 0.
13917 opt[DTRACEOPT_SPECSIZE] = 0;
13922 * The bare minimum size for any buffer that we're actually going to
13923 * do anything to is sizeof (uint64_t).
13925 sz = sizeof (uint64_t);
13927 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13928 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13929 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13931 * A buffer size has been explicitly set to 0 (or to a size
13932 * that will be adjusted to 0) and we need the space -- we
13933 * need to return failure. We return ENOSPC to differentiate
13934 * it from failing to allocate a buffer due to failure to meet
13935 * the reserve (for which we return E2BIG).
13941 if ((rval = dtrace_state_buffers(state)) != 0)
13944 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13945 sz = dtrace_dstate_defsize;
13948 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13953 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13955 } while (sz >>= 1);
13957 opt[DTRACEOPT_DYNVARSIZE] = sz;
13962 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13963 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13965 if (opt[DTRACEOPT_CLEANRATE] == 0)
13966 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13968 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13969 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13971 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13972 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13974 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13976 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13977 hdlr.cyh_arg = state;
13978 hdlr.cyh_level = CY_LOW_LEVEL;
13981 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13983 state->dts_cleaner = cyclic_add(&hdlr, &when);
13985 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13986 hdlr.cyh_arg = state;
13987 hdlr.cyh_level = CY_LOW_LEVEL;
13990 when.cyt_interval = dtrace_deadman_interval;
13992 state->dts_deadman = cyclic_add(&hdlr, &when);
13994 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13995 dtrace_state_clean, state);
13996 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13997 dtrace_state_deadman, state);
14000 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14003 if (state->dts_getf != 0 &&
14004 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14006 * We don't have kernel privs but we have at least one call
14007 * to getf(); we need to bump our zone's count, and (if
14008 * this is the first enabling to have an unprivileged call
14009 * to getf()) we need to hook into closef().
14011 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14013 if (dtrace_getf++ == 0) {
14014 ASSERT(dtrace_closef == NULL);
14015 dtrace_closef = dtrace_getf_barrier;
14021 * Now it's time to actually fire the BEGIN probe. We need to disable
14022 * interrupts here both to record the CPU on which we fired the BEGIN
14023 * probe (the data from this CPU will be processed first at user
14024 * level) and to manually activate the buffer for this CPU.
14026 cookie = dtrace_interrupt_disable();
14028 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14029 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14031 dtrace_probe(dtrace_probeid_begin,
14032 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14033 dtrace_interrupt_enable(cookie);
14035 * We may have had an exit action from a BEGIN probe; only change our
14036 * state to ACTIVE if we're still in WARMUP.
14038 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14039 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14041 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14042 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14045 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14046 * want each CPU to transition its principal buffer out of the
14047 * INACTIVE state. Doing this assures that no CPU will suddenly begin
14048 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14049 * atomically transition from processing none of a state's ECBs to
14050 * processing all of them.
14052 dtrace_xcall(DTRACE_CPUALL,
14053 (dtrace_xcall_t)dtrace_buffer_activate, state);
14057 dtrace_buffer_free(state->dts_buffer);
14058 dtrace_buffer_free(state->dts_aggbuffer);
14060 if ((nspec = state->dts_nspeculations) == 0) {
14061 ASSERT(state->dts_speculations == NULL);
14065 spec = state->dts_speculations;
14066 ASSERT(spec != NULL);
14068 for (i = 0; i < state->dts_nspeculations; i++) {
14069 if ((buf = spec[i].dtsp_buffer) == NULL)
14072 dtrace_buffer_free(buf);
14073 kmem_free(buf, bufsize);
14076 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14077 state->dts_nspeculations = 0;
14078 state->dts_speculations = NULL;
14081 mutex_exit(&dtrace_lock);
14082 mutex_exit(&cpu_lock);
14088 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14090 dtrace_icookie_t cookie;
14092 ASSERT(MUTEX_HELD(&dtrace_lock));
14094 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14095 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14099 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14100 * to be sure that every CPU has seen it. See below for the details
14101 * on why this is done.
14103 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14107 * By this point, it is impossible for any CPU to be still processing
14108 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
14109 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14110 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
14111 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14112 * iff we're in the END probe.
14114 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14116 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14119 * Finally, we can release the reserve and call the END probe. We
14120 * disable interrupts across calling the END probe to allow us to
14121 * return the CPU on which we actually called the END probe. This
14122 * allows user-land to be sure that this CPU's principal buffer is
14125 state->dts_reserve = 0;
14127 cookie = dtrace_interrupt_disable();
14129 dtrace_probe(dtrace_probeid_end,
14130 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14131 dtrace_interrupt_enable(cookie);
14133 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14137 if (state->dts_getf != 0 &&
14138 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14140 * We don't have kernel privs but we have at least one call
14141 * to getf(); we need to lower our zone's count, and (if
14142 * this is the last enabling to have an unprivileged call
14143 * to getf()) we need to clear the closef() hook.
14145 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14146 ASSERT(dtrace_closef == dtrace_getf_barrier);
14147 ASSERT(dtrace_getf > 0);
14149 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14151 if (--dtrace_getf == 0)
14152 dtrace_closef = NULL;
14160 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14161 dtrace_optval_t val)
14163 ASSERT(MUTEX_HELD(&dtrace_lock));
14165 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14168 if (option >= DTRACEOPT_MAX)
14171 if (option != DTRACEOPT_CPU && val < 0)
14175 case DTRACEOPT_DESTRUCTIVE:
14176 if (dtrace_destructive_disallow)
14179 state->dts_cred.dcr_destructive = 1;
14182 case DTRACEOPT_BUFSIZE:
14183 case DTRACEOPT_DYNVARSIZE:
14184 case DTRACEOPT_AGGSIZE:
14185 case DTRACEOPT_SPECSIZE:
14186 case DTRACEOPT_STRSIZE:
14190 if (val >= LONG_MAX) {
14192 * If this is an otherwise negative value, set it to
14193 * the highest multiple of 128m less than LONG_MAX.
14194 * Technically, we're adjusting the size without
14195 * regard to the buffer resizing policy, but in fact,
14196 * this has no effect -- if we set the buffer size to
14197 * ~LONG_MAX and the buffer policy is ultimately set to
14198 * be "manual", the buffer allocation is guaranteed to
14199 * fail, if only because the allocation requires two
14200 * buffers. (We set the the size to the highest
14201 * multiple of 128m because it ensures that the size
14202 * will remain a multiple of a megabyte when
14203 * repeatedly halved -- all the way down to 15m.)
14205 val = LONG_MAX - (1 << 27) + 1;
14209 state->dts_options[option] = val;
14215 dtrace_state_destroy(dtrace_state_t *state)
14218 dtrace_vstate_t *vstate = &state->dts_vstate;
14220 minor_t minor = getminor(state->dts_dev);
14222 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14223 dtrace_speculation_t *spec = state->dts_speculations;
14224 int nspec = state->dts_nspeculations;
14227 ASSERT(MUTEX_HELD(&dtrace_lock));
14228 ASSERT(MUTEX_HELD(&cpu_lock));
14231 * First, retract any retained enablings for this state.
14233 dtrace_enabling_retract(state);
14234 ASSERT(state->dts_nretained == 0);
14236 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14237 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14239 * We have managed to come into dtrace_state_destroy() on a
14240 * hot enabling -- almost certainly because of a disorderly
14241 * shutdown of a consumer. (That is, a consumer that is
14242 * exiting without having called dtrace_stop().) In this case,
14243 * we're going to set our activity to be KILLED, and then
14244 * issue a sync to be sure that everyone is out of probe
14245 * context before we start blowing away ECBs.
14247 state->dts_activity = DTRACE_ACTIVITY_KILLED;
14252 * Release the credential hold we took in dtrace_state_create().
14254 if (state->dts_cred.dcr_cred != NULL)
14255 crfree(state->dts_cred.dcr_cred);
14258 * Now we can safely disable and destroy any enabled probes. Because
14259 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14260 * (especially if they're all enabled), we take two passes through the
14261 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14262 * in the second we disable whatever is left over.
14264 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14265 for (i = 0; i < state->dts_necbs; i++) {
14266 if ((ecb = state->dts_ecbs[i]) == NULL)
14269 if (match && ecb->dte_probe != NULL) {
14270 dtrace_probe_t *probe = ecb->dte_probe;
14271 dtrace_provider_t *prov = probe->dtpr_provider;
14273 if (!(prov->dtpv_priv.dtpp_flags & match))
14277 dtrace_ecb_disable(ecb);
14278 dtrace_ecb_destroy(ecb);
14286 * Before we free the buffers, perform one more sync to assure that
14287 * every CPU is out of probe context.
14291 dtrace_buffer_free(state->dts_buffer);
14292 dtrace_buffer_free(state->dts_aggbuffer);
14294 for (i = 0; i < nspec; i++)
14295 dtrace_buffer_free(spec[i].dtsp_buffer);
14298 if (state->dts_cleaner != CYCLIC_NONE)
14299 cyclic_remove(state->dts_cleaner);
14301 if (state->dts_deadman != CYCLIC_NONE)
14302 cyclic_remove(state->dts_deadman);
14304 callout_stop(&state->dts_cleaner);
14305 callout_drain(&state->dts_cleaner);
14306 callout_stop(&state->dts_deadman);
14307 callout_drain(&state->dts_deadman);
14310 dtrace_dstate_fini(&vstate->dtvs_dynvars);
14311 dtrace_vstate_fini(vstate);
14312 if (state->dts_ecbs != NULL)
14313 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14315 if (state->dts_aggregations != NULL) {
14317 for (i = 0; i < state->dts_naggregations; i++)
14318 ASSERT(state->dts_aggregations[i] == NULL);
14320 ASSERT(state->dts_naggregations > 0);
14321 kmem_free(state->dts_aggregations,
14322 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14325 kmem_free(state->dts_buffer, bufsize);
14326 kmem_free(state->dts_aggbuffer, bufsize);
14328 for (i = 0; i < nspec; i++)
14329 kmem_free(spec[i].dtsp_buffer, bufsize);
14332 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14334 dtrace_format_destroy(state);
14336 if (state->dts_aggid_arena != NULL) {
14338 vmem_destroy(state->dts_aggid_arena);
14340 delete_unrhdr(state->dts_aggid_arena);
14342 state->dts_aggid_arena = NULL;
14345 ddi_soft_state_free(dtrace_softstate, minor);
14346 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14351 * DTrace Anonymous Enabling Functions
14353 static dtrace_state_t *
14354 dtrace_anon_grab(void)
14356 dtrace_state_t *state;
14358 ASSERT(MUTEX_HELD(&dtrace_lock));
14360 if ((state = dtrace_anon.dta_state) == NULL) {
14361 ASSERT(dtrace_anon.dta_enabling == NULL);
14365 ASSERT(dtrace_anon.dta_enabling != NULL);
14366 ASSERT(dtrace_retained != NULL);
14368 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14369 dtrace_anon.dta_enabling = NULL;
14370 dtrace_anon.dta_state = NULL;
14376 dtrace_anon_property(void)
14379 dtrace_state_t *state;
14381 char c[32]; /* enough for "dof-data-" + digits */
14383 ASSERT(MUTEX_HELD(&dtrace_lock));
14384 ASSERT(MUTEX_HELD(&cpu_lock));
14386 for (i = 0; ; i++) {
14387 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14389 dtrace_err_verbose = 1;
14391 if ((dof = dtrace_dof_property(c)) == NULL) {
14392 dtrace_err_verbose = 0;
14398 * We want to create anonymous state, so we need to transition
14399 * the kernel debugger to indicate that DTrace is active. If
14400 * this fails (e.g. because the debugger has modified text in
14401 * some way), we won't continue with the processing.
14403 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14404 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14405 "enabling ignored.");
14406 dtrace_dof_destroy(dof);
14412 * If we haven't allocated an anonymous state, we'll do so now.
14414 if ((state = dtrace_anon.dta_state) == NULL) {
14416 state = dtrace_state_create(NULL, NULL);
14418 state = dtrace_state_create(NULL);
14420 dtrace_anon.dta_state = state;
14422 if (state == NULL) {
14424 * This basically shouldn't happen: the only
14425 * failure mode from dtrace_state_create() is a
14426 * failure of ddi_soft_state_zalloc() that
14427 * itself should never happen. Still, the
14428 * interface allows for a failure mode, and
14429 * we want to fail as gracefully as possible:
14430 * we'll emit an error message and cease
14431 * processing anonymous state in this case.
14433 cmn_err(CE_WARN, "failed to create "
14434 "anonymous state");
14435 dtrace_dof_destroy(dof);
14440 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14441 &dtrace_anon.dta_enabling, 0, B_TRUE);
14444 rv = dtrace_dof_options(dof, state);
14446 dtrace_err_verbose = 0;
14447 dtrace_dof_destroy(dof);
14451 * This is malformed DOF; chuck any anonymous state
14454 ASSERT(dtrace_anon.dta_enabling == NULL);
14455 dtrace_state_destroy(state);
14456 dtrace_anon.dta_state = NULL;
14460 ASSERT(dtrace_anon.dta_enabling != NULL);
14463 if (dtrace_anon.dta_enabling != NULL) {
14467 * dtrace_enabling_retain() can only fail because we are
14468 * trying to retain more enablings than are allowed -- but
14469 * we only have one anonymous enabling, and we are guaranteed
14470 * to be allowed at least one retained enabling; we assert
14471 * that dtrace_enabling_retain() returns success.
14473 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14476 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14481 * DTrace Helper Functions
14484 dtrace_helper_trace(dtrace_helper_action_t *helper,
14485 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14487 uint32_t size, next, nnext, i;
14488 dtrace_helptrace_t *ent;
14489 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14491 if (!dtrace_helptrace_enabled)
14494 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14497 * What would a tracing framework be without its own tracing
14498 * framework? (Well, a hell of a lot simpler, for starters...)
14500 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14501 sizeof (uint64_t) - sizeof (uint64_t);
14504 * Iterate until we can allocate a slot in the trace buffer.
14507 next = dtrace_helptrace_next;
14509 if (next + size < dtrace_helptrace_bufsize) {
14510 nnext = next + size;
14514 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14517 * We have our slot; fill it in.
14522 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14523 ent->dtht_helper = helper;
14524 ent->dtht_where = where;
14525 ent->dtht_nlocals = vstate->dtvs_nlocals;
14527 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14528 mstate->dtms_fltoffs : -1;
14529 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14530 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14532 for (i = 0; i < vstate->dtvs_nlocals; i++) {
14533 dtrace_statvar_t *svar;
14535 if ((svar = vstate->dtvs_locals[i]) == NULL)
14538 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14539 ent->dtht_locals[i] =
14540 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14545 dtrace_helper(int which, dtrace_mstate_t *mstate,
14546 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14548 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14549 uint64_t sarg0 = mstate->dtms_arg[0];
14550 uint64_t sarg1 = mstate->dtms_arg[1];
14552 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14553 dtrace_helper_action_t *helper;
14554 dtrace_vstate_t *vstate;
14555 dtrace_difo_t *pred;
14556 int i, trace = dtrace_helptrace_enabled;
14558 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14560 if (helpers == NULL)
14563 if ((helper = helpers->dthps_actions[which]) == NULL)
14566 vstate = &helpers->dthps_vstate;
14567 mstate->dtms_arg[0] = arg0;
14568 mstate->dtms_arg[1] = arg1;
14571 * Now iterate over each helper. If its predicate evaluates to 'true',
14572 * we'll call the corresponding actions. Note that the below calls
14573 * to dtrace_dif_emulate() may set faults in machine state. This is
14574 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
14575 * the stored DIF offset with its own (which is the desired behavior).
14576 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14577 * from machine state; this is okay, too.
14579 for (; helper != NULL; helper = helper->dtha_next) {
14580 if ((pred = helper->dtha_predicate) != NULL) {
14582 dtrace_helper_trace(helper, mstate, vstate, 0);
14584 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14587 if (*flags & CPU_DTRACE_FAULT)
14591 for (i = 0; i < helper->dtha_nactions; i++) {
14593 dtrace_helper_trace(helper,
14594 mstate, vstate, i + 1);
14596 rval = dtrace_dif_emulate(helper->dtha_actions[i],
14597 mstate, vstate, state);
14599 if (*flags & CPU_DTRACE_FAULT)
14605 dtrace_helper_trace(helper, mstate, vstate,
14606 DTRACE_HELPTRACE_NEXT);
14610 dtrace_helper_trace(helper, mstate, vstate,
14611 DTRACE_HELPTRACE_DONE);
14614 * Restore the arg0 that we saved upon entry.
14616 mstate->dtms_arg[0] = sarg0;
14617 mstate->dtms_arg[1] = sarg1;
14623 dtrace_helper_trace(helper, mstate, vstate,
14624 DTRACE_HELPTRACE_ERR);
14627 * Restore the arg0 that we saved upon entry.
14629 mstate->dtms_arg[0] = sarg0;
14630 mstate->dtms_arg[1] = sarg1;
14636 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14637 dtrace_vstate_t *vstate)
14641 if (helper->dtha_predicate != NULL)
14642 dtrace_difo_release(helper->dtha_predicate, vstate);
14644 for (i = 0; i < helper->dtha_nactions; i++) {
14645 ASSERT(helper->dtha_actions[i] != NULL);
14646 dtrace_difo_release(helper->dtha_actions[i], vstate);
14649 kmem_free(helper->dtha_actions,
14650 helper->dtha_nactions * sizeof (dtrace_difo_t *));
14651 kmem_free(helper, sizeof (dtrace_helper_action_t));
14655 dtrace_helper_destroygen(int gen)
14657 proc_t *p = curproc;
14658 dtrace_helpers_t *help = p->p_dtrace_helpers;
14659 dtrace_vstate_t *vstate;
14662 ASSERT(MUTEX_HELD(&dtrace_lock));
14664 if (help == NULL || gen > help->dthps_generation)
14667 vstate = &help->dthps_vstate;
14669 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14670 dtrace_helper_action_t *last = NULL, *h, *next;
14672 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14673 next = h->dtha_next;
14675 if (h->dtha_generation == gen) {
14676 if (last != NULL) {
14677 last->dtha_next = next;
14679 help->dthps_actions[i] = next;
14682 dtrace_helper_action_destroy(h, vstate);
14690 * Interate until we've cleared out all helper providers with the
14691 * given generation number.
14694 dtrace_helper_provider_t *prov;
14697 * Look for a helper provider with the right generation. We
14698 * have to start back at the beginning of the list each time
14699 * because we drop dtrace_lock. It's unlikely that we'll make
14700 * more than two passes.
14702 for (i = 0; i < help->dthps_nprovs; i++) {
14703 prov = help->dthps_provs[i];
14705 if (prov->dthp_generation == gen)
14710 * If there were no matches, we're done.
14712 if (i == help->dthps_nprovs)
14716 * Move the last helper provider into this slot.
14718 help->dthps_nprovs--;
14719 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14720 help->dthps_provs[help->dthps_nprovs] = NULL;
14722 mutex_exit(&dtrace_lock);
14725 * If we have a meta provider, remove this helper provider.
14727 mutex_enter(&dtrace_meta_lock);
14728 if (dtrace_meta_pid != NULL) {
14729 ASSERT(dtrace_deferred_pid == NULL);
14730 dtrace_helper_provider_remove(&prov->dthp_prov,
14733 mutex_exit(&dtrace_meta_lock);
14735 dtrace_helper_provider_destroy(prov);
14737 mutex_enter(&dtrace_lock);
14744 dtrace_helper_validate(dtrace_helper_action_t *helper)
14749 if ((dp = helper->dtha_predicate) != NULL)
14750 err += dtrace_difo_validate_helper(dp);
14752 for (i = 0; i < helper->dtha_nactions; i++)
14753 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14759 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14761 dtrace_helpers_t *help;
14762 dtrace_helper_action_t *helper, *last;
14763 dtrace_actdesc_t *act;
14764 dtrace_vstate_t *vstate;
14765 dtrace_predicate_t *pred;
14766 int count = 0, nactions = 0, i;
14768 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14771 help = curproc->p_dtrace_helpers;
14772 last = help->dthps_actions[which];
14773 vstate = &help->dthps_vstate;
14775 for (count = 0; last != NULL; last = last->dtha_next) {
14777 if (last->dtha_next == NULL)
14782 * If we already have dtrace_helper_actions_max helper actions for this
14783 * helper action type, we'll refuse to add a new one.
14785 if (count >= dtrace_helper_actions_max)
14788 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14789 helper->dtha_generation = help->dthps_generation;
14791 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14792 ASSERT(pred->dtp_difo != NULL);
14793 dtrace_difo_hold(pred->dtp_difo);
14794 helper->dtha_predicate = pred->dtp_difo;
14797 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14798 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14801 if (act->dtad_difo == NULL)
14807 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14808 (helper->dtha_nactions = nactions), KM_SLEEP);
14810 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14811 dtrace_difo_hold(act->dtad_difo);
14812 helper->dtha_actions[i++] = act->dtad_difo;
14815 if (!dtrace_helper_validate(helper))
14818 if (last == NULL) {
14819 help->dthps_actions[which] = helper;
14821 last->dtha_next = helper;
14824 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14825 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14826 dtrace_helptrace_next = 0;
14831 dtrace_helper_action_destroy(helper, vstate);
14836 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14837 dof_helper_t *dofhp)
14839 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14841 mutex_enter(&dtrace_meta_lock);
14842 mutex_enter(&dtrace_lock);
14844 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14846 * If the dtrace module is loaded but not attached, or if
14847 * there aren't isn't a meta provider registered to deal with
14848 * these provider descriptions, we need to postpone creating
14849 * the actual providers until later.
14852 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14853 dtrace_deferred_pid != help) {
14854 help->dthps_deferred = 1;
14855 help->dthps_pid = p->p_pid;
14856 help->dthps_next = dtrace_deferred_pid;
14857 help->dthps_prev = NULL;
14858 if (dtrace_deferred_pid != NULL)
14859 dtrace_deferred_pid->dthps_prev = help;
14860 dtrace_deferred_pid = help;
14863 mutex_exit(&dtrace_lock);
14865 } else if (dofhp != NULL) {
14867 * If the dtrace module is loaded and we have a particular
14868 * helper provider description, pass that off to the
14872 mutex_exit(&dtrace_lock);
14874 dtrace_helper_provide(dofhp, p->p_pid);
14878 * Otherwise, just pass all the helper provider descriptions
14879 * off to the meta provider.
14883 mutex_exit(&dtrace_lock);
14885 for (i = 0; i < help->dthps_nprovs; i++) {
14886 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14891 mutex_exit(&dtrace_meta_lock);
14895 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14897 dtrace_helpers_t *help;
14898 dtrace_helper_provider_t *hprov, **tmp_provs;
14899 uint_t tmp_maxprovs, i;
14901 ASSERT(MUTEX_HELD(&dtrace_lock));
14903 help = curproc->p_dtrace_helpers;
14904 ASSERT(help != NULL);
14907 * If we already have dtrace_helper_providers_max helper providers,
14908 * we're refuse to add a new one.
14910 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14914 * Check to make sure this isn't a duplicate.
14916 for (i = 0; i < help->dthps_nprovs; i++) {
14917 if (dofhp->dofhp_dof ==
14918 help->dthps_provs[i]->dthp_prov.dofhp_dof)
14922 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14923 hprov->dthp_prov = *dofhp;
14924 hprov->dthp_ref = 1;
14925 hprov->dthp_generation = gen;
14928 * Allocate a bigger table for helper providers if it's already full.
14930 if (help->dthps_maxprovs == help->dthps_nprovs) {
14931 tmp_maxprovs = help->dthps_maxprovs;
14932 tmp_provs = help->dthps_provs;
14934 if (help->dthps_maxprovs == 0)
14935 help->dthps_maxprovs = 2;
14937 help->dthps_maxprovs *= 2;
14938 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14939 help->dthps_maxprovs = dtrace_helper_providers_max;
14941 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14943 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14944 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14946 if (tmp_provs != NULL) {
14947 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14948 sizeof (dtrace_helper_provider_t *));
14949 kmem_free(tmp_provs, tmp_maxprovs *
14950 sizeof (dtrace_helper_provider_t *));
14954 help->dthps_provs[help->dthps_nprovs] = hprov;
14955 help->dthps_nprovs++;
14961 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14963 mutex_enter(&dtrace_lock);
14965 if (--hprov->dthp_ref == 0) {
14967 mutex_exit(&dtrace_lock);
14968 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14969 dtrace_dof_destroy(dof);
14970 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14972 mutex_exit(&dtrace_lock);
14977 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14979 uintptr_t daddr = (uintptr_t)dof;
14980 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14981 dof_provider_t *provider;
14982 dof_probe_t *probe;
14984 char *strtab, *typestr;
14985 dof_stridx_t typeidx;
14987 uint_t nprobes, j, k;
14989 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14991 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14992 dtrace_dof_error(dof, "misaligned section offset");
14997 * The section needs to be large enough to contain the DOF provider
14998 * structure appropriate for the given version.
15000 if (sec->dofs_size <
15001 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15002 offsetof(dof_provider_t, dofpv_prenoffs) :
15003 sizeof (dof_provider_t))) {
15004 dtrace_dof_error(dof, "provider section too small");
15008 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15009 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15010 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15011 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15012 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15014 if (str_sec == NULL || prb_sec == NULL ||
15015 arg_sec == NULL || off_sec == NULL)
15020 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15021 provider->dofpv_prenoffs != DOF_SECT_NONE &&
15022 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15023 provider->dofpv_prenoffs)) == NULL)
15026 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15028 if (provider->dofpv_name >= str_sec->dofs_size ||
15029 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15030 dtrace_dof_error(dof, "invalid provider name");
15034 if (prb_sec->dofs_entsize == 0 ||
15035 prb_sec->dofs_entsize > prb_sec->dofs_size) {
15036 dtrace_dof_error(dof, "invalid entry size");
15040 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15041 dtrace_dof_error(dof, "misaligned entry size");
15045 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15046 dtrace_dof_error(dof, "invalid entry size");
15050 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15051 dtrace_dof_error(dof, "misaligned section offset");
15055 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15056 dtrace_dof_error(dof, "invalid entry size");
15060 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15062 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15065 * Take a pass through the probes to check for errors.
15067 for (j = 0; j < nprobes; j++) {
15068 probe = (dof_probe_t *)(uintptr_t)(daddr +
15069 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15071 if (probe->dofpr_func >= str_sec->dofs_size) {
15072 dtrace_dof_error(dof, "invalid function name");
15076 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15077 dtrace_dof_error(dof, "function name too long");
15081 if (probe->dofpr_name >= str_sec->dofs_size ||
15082 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15083 dtrace_dof_error(dof, "invalid probe name");
15088 * The offset count must not wrap the index, and the offsets
15089 * must also not overflow the section's data.
15091 if (probe->dofpr_offidx + probe->dofpr_noffs <
15092 probe->dofpr_offidx ||
15093 (probe->dofpr_offidx + probe->dofpr_noffs) *
15094 off_sec->dofs_entsize > off_sec->dofs_size) {
15095 dtrace_dof_error(dof, "invalid probe offset");
15099 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15101 * If there's no is-enabled offset section, make sure
15102 * there aren't any is-enabled offsets. Otherwise
15103 * perform the same checks as for probe offsets
15104 * (immediately above).
15106 if (enoff_sec == NULL) {
15107 if (probe->dofpr_enoffidx != 0 ||
15108 probe->dofpr_nenoffs != 0) {
15109 dtrace_dof_error(dof, "is-enabled "
15110 "offsets with null section");
15113 } else if (probe->dofpr_enoffidx +
15114 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15115 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15116 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15117 dtrace_dof_error(dof, "invalid is-enabled "
15122 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15123 dtrace_dof_error(dof, "zero probe and "
15124 "is-enabled offsets");
15127 } else if (probe->dofpr_noffs == 0) {
15128 dtrace_dof_error(dof, "zero probe offsets");
15132 if (probe->dofpr_argidx + probe->dofpr_xargc <
15133 probe->dofpr_argidx ||
15134 (probe->dofpr_argidx + probe->dofpr_xargc) *
15135 arg_sec->dofs_entsize > arg_sec->dofs_size) {
15136 dtrace_dof_error(dof, "invalid args");
15140 typeidx = probe->dofpr_nargv;
15141 typestr = strtab + probe->dofpr_nargv;
15142 for (k = 0; k < probe->dofpr_nargc; k++) {
15143 if (typeidx >= str_sec->dofs_size) {
15144 dtrace_dof_error(dof, "bad "
15145 "native argument type");
15149 typesz = strlen(typestr) + 1;
15150 if (typesz > DTRACE_ARGTYPELEN) {
15151 dtrace_dof_error(dof, "native "
15152 "argument type too long");
15159 typeidx = probe->dofpr_xargv;
15160 typestr = strtab + probe->dofpr_xargv;
15161 for (k = 0; k < probe->dofpr_xargc; k++) {
15162 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15163 dtrace_dof_error(dof, "bad "
15164 "native argument index");
15168 if (typeidx >= str_sec->dofs_size) {
15169 dtrace_dof_error(dof, "bad "
15170 "translated argument type");
15174 typesz = strlen(typestr) + 1;
15175 if (typesz > DTRACE_ARGTYPELEN) {
15176 dtrace_dof_error(dof, "translated argument "
15190 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15192 dtrace_helpers_t *help;
15193 dtrace_vstate_t *vstate;
15194 dtrace_enabling_t *enab = NULL;
15195 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15196 uintptr_t daddr = (uintptr_t)dof;
15198 ASSERT(MUTEX_HELD(&dtrace_lock));
15200 if ((help = curproc->p_dtrace_helpers) == NULL)
15201 help = dtrace_helpers_create(curproc);
15203 vstate = &help->dthps_vstate;
15205 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15206 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15207 dtrace_dof_destroy(dof);
15212 * Look for helper providers and validate their descriptions.
15215 for (i = 0; i < dof->dofh_secnum; i++) {
15216 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15217 dof->dofh_secoff + i * dof->dofh_secsize);
15219 if (sec->dofs_type != DOF_SECT_PROVIDER)
15222 if (dtrace_helper_provider_validate(dof, sec) != 0) {
15223 dtrace_enabling_destroy(enab);
15224 dtrace_dof_destroy(dof);
15233 * Now we need to walk through the ECB descriptions in the enabling.
15235 for (i = 0; i < enab->dten_ndesc; i++) {
15236 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15237 dtrace_probedesc_t *desc = &ep->dted_probe;
15239 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15242 if (strcmp(desc->dtpd_mod, "helper") != 0)
15245 if (strcmp(desc->dtpd_func, "ustack") != 0)
15248 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15251 * Adding this helper action failed -- we are now going
15252 * to rip out the entire generation and return failure.
15254 (void) dtrace_helper_destroygen(help->dthps_generation);
15255 dtrace_enabling_destroy(enab);
15256 dtrace_dof_destroy(dof);
15263 if (nhelpers < enab->dten_ndesc)
15264 dtrace_dof_error(dof, "unmatched helpers");
15266 gen = help->dthps_generation++;
15267 dtrace_enabling_destroy(enab);
15269 if (dhp != NULL && nprovs > 0) {
15270 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15271 if (dtrace_helper_provider_add(dhp, gen) == 0) {
15272 mutex_exit(&dtrace_lock);
15273 dtrace_helper_provider_register(curproc, help, dhp);
15274 mutex_enter(&dtrace_lock);
15281 dtrace_dof_destroy(dof);
15286 static dtrace_helpers_t *
15287 dtrace_helpers_create(proc_t *p)
15289 dtrace_helpers_t *help;
15291 ASSERT(MUTEX_HELD(&dtrace_lock));
15292 ASSERT(p->p_dtrace_helpers == NULL);
15294 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15295 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15296 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15298 p->p_dtrace_helpers = help;
15308 dtrace_helpers_destroy(proc_t *p)
15310 dtrace_helpers_t *help;
15311 dtrace_vstate_t *vstate;
15313 proc_t *p = curproc;
15317 mutex_enter(&dtrace_lock);
15319 ASSERT(p->p_dtrace_helpers != NULL);
15320 ASSERT(dtrace_helpers > 0);
15322 help = p->p_dtrace_helpers;
15323 vstate = &help->dthps_vstate;
15326 * We're now going to lose the help from this process.
15328 p->p_dtrace_helpers = NULL;
15332 * Destory the helper actions.
15334 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15335 dtrace_helper_action_t *h, *next;
15337 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15338 next = h->dtha_next;
15339 dtrace_helper_action_destroy(h, vstate);
15344 mutex_exit(&dtrace_lock);
15347 * Destroy the helper providers.
15349 if (help->dthps_maxprovs > 0) {
15350 mutex_enter(&dtrace_meta_lock);
15351 if (dtrace_meta_pid != NULL) {
15352 ASSERT(dtrace_deferred_pid == NULL);
15354 for (i = 0; i < help->dthps_nprovs; i++) {
15355 dtrace_helper_provider_remove(
15356 &help->dthps_provs[i]->dthp_prov, p->p_pid);
15359 mutex_enter(&dtrace_lock);
15360 ASSERT(help->dthps_deferred == 0 ||
15361 help->dthps_next != NULL ||
15362 help->dthps_prev != NULL ||
15363 help == dtrace_deferred_pid);
15366 * Remove the helper from the deferred list.
15368 if (help->dthps_next != NULL)
15369 help->dthps_next->dthps_prev = help->dthps_prev;
15370 if (help->dthps_prev != NULL)
15371 help->dthps_prev->dthps_next = help->dthps_next;
15372 if (dtrace_deferred_pid == help) {
15373 dtrace_deferred_pid = help->dthps_next;
15374 ASSERT(help->dthps_prev == NULL);
15377 mutex_exit(&dtrace_lock);
15380 mutex_exit(&dtrace_meta_lock);
15382 for (i = 0; i < help->dthps_nprovs; i++) {
15383 dtrace_helper_provider_destroy(help->dthps_provs[i]);
15386 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15387 sizeof (dtrace_helper_provider_t *));
15390 mutex_enter(&dtrace_lock);
15392 dtrace_vstate_fini(&help->dthps_vstate);
15393 kmem_free(help->dthps_actions,
15394 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15395 kmem_free(help, sizeof (dtrace_helpers_t));
15398 mutex_exit(&dtrace_lock);
15405 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15407 dtrace_helpers_t *help, *newhelp;
15408 dtrace_helper_action_t *helper, *new, *last;
15410 dtrace_vstate_t *vstate;
15411 int i, j, sz, hasprovs = 0;
15413 mutex_enter(&dtrace_lock);
15414 ASSERT(from->p_dtrace_helpers != NULL);
15415 ASSERT(dtrace_helpers > 0);
15417 help = from->p_dtrace_helpers;
15418 newhelp = dtrace_helpers_create(to);
15419 ASSERT(to->p_dtrace_helpers != NULL);
15421 newhelp->dthps_generation = help->dthps_generation;
15422 vstate = &newhelp->dthps_vstate;
15425 * Duplicate the helper actions.
15427 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15428 if ((helper = help->dthps_actions[i]) == NULL)
15431 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15432 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15434 new->dtha_generation = helper->dtha_generation;
15436 if ((dp = helper->dtha_predicate) != NULL) {
15437 dp = dtrace_difo_duplicate(dp, vstate);
15438 new->dtha_predicate = dp;
15441 new->dtha_nactions = helper->dtha_nactions;
15442 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15443 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15445 for (j = 0; j < new->dtha_nactions; j++) {
15446 dtrace_difo_t *dp = helper->dtha_actions[j];
15448 ASSERT(dp != NULL);
15449 dp = dtrace_difo_duplicate(dp, vstate);
15450 new->dtha_actions[j] = dp;
15453 if (last != NULL) {
15454 last->dtha_next = new;
15456 newhelp->dthps_actions[i] = new;
15464 * Duplicate the helper providers and register them with the
15465 * DTrace framework.
15467 if (help->dthps_nprovs > 0) {
15468 newhelp->dthps_nprovs = help->dthps_nprovs;
15469 newhelp->dthps_maxprovs = help->dthps_nprovs;
15470 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15471 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15472 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15473 newhelp->dthps_provs[i] = help->dthps_provs[i];
15474 newhelp->dthps_provs[i]->dthp_ref++;
15480 mutex_exit(&dtrace_lock);
15483 dtrace_helper_provider_register(to, newhelp, NULL);
15487 * DTrace Hook Functions
15490 dtrace_module_loaded(modctl_t *ctl)
15492 dtrace_provider_t *prv;
15494 mutex_enter(&dtrace_provider_lock);
15496 mutex_enter(&mod_lock);
15500 ASSERT(ctl->mod_busy);
15504 * We're going to call each providers per-module provide operation
15505 * specifying only this module.
15507 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15508 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15511 mutex_exit(&mod_lock);
15513 mutex_exit(&dtrace_provider_lock);
15516 * If we have any retained enablings, we need to match against them.
15517 * Enabling probes requires that cpu_lock be held, and we cannot hold
15518 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15519 * module. (In particular, this happens when loading scheduling
15520 * classes.) So if we have any retained enablings, we need to dispatch
15521 * our task queue to do the match for us.
15523 mutex_enter(&dtrace_lock);
15525 if (dtrace_retained == NULL) {
15526 mutex_exit(&dtrace_lock);
15530 (void) taskq_dispatch(dtrace_taskq,
15531 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15533 mutex_exit(&dtrace_lock);
15536 * And now, for a little heuristic sleaze: in general, we want to
15537 * match modules as soon as they load. However, we cannot guarantee
15538 * this, because it would lead us to the lock ordering violation
15539 * outlined above. The common case, of course, is that cpu_lock is
15540 * _not_ held -- so we delay here for a clock tick, hoping that that's
15541 * long enough for the task queue to do its work. If it's not, it's
15542 * not a serious problem -- it just means that the module that we
15543 * just loaded may not be immediately instrumentable.
15550 dtrace_module_unloaded(modctl_t *ctl)
15552 dtrace_module_unloaded(modctl_t *ctl, int *error)
15555 dtrace_probe_t template, *probe, *first, *next;
15556 dtrace_provider_t *prov;
15558 char modname[DTRACE_MODNAMELEN];
15563 template.dtpr_mod = ctl->mod_modname;
15565 /* Handle the fact that ctl->filename may end in ".ko". */
15566 strlcpy(modname, ctl->filename, sizeof(modname));
15567 len = strlen(ctl->filename);
15568 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15569 modname[len - 3] = '\0';
15570 template.dtpr_mod = modname;
15573 mutex_enter(&dtrace_provider_lock);
15575 mutex_enter(&mod_lock);
15577 mutex_enter(&dtrace_lock);
15580 if (ctl->nenabled > 0) {
15581 /* Don't allow unloads if a probe is enabled. */
15582 mutex_exit(&dtrace_provider_lock);
15583 mutex_exit(&dtrace_lock);
15586 "kldunload: attempt to unload module that has DTrace probes enabled\n");
15591 if (dtrace_bymod == NULL) {
15593 * The DTrace module is loaded (obviously) but not attached;
15594 * we don't have any work to do.
15596 mutex_exit(&dtrace_provider_lock);
15598 mutex_exit(&mod_lock);
15600 mutex_exit(&dtrace_lock);
15604 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15605 probe != NULL; probe = probe->dtpr_nextmod) {
15606 if (probe->dtpr_ecb != NULL) {
15607 mutex_exit(&dtrace_provider_lock);
15609 mutex_exit(&mod_lock);
15611 mutex_exit(&dtrace_lock);
15614 * This shouldn't _actually_ be possible -- we're
15615 * unloading a module that has an enabled probe in it.
15616 * (It's normally up to the provider to make sure that
15617 * this can't happen.) However, because dtps_enable()
15618 * doesn't have a failure mode, there can be an
15619 * enable/unload race. Upshot: we don't want to
15620 * assert, but we're not going to disable the
15623 if (dtrace_err_verbose) {
15625 cmn_err(CE_WARN, "unloaded module '%s' had "
15626 "enabled probes", ctl->mod_modname);
15628 cmn_err(CE_WARN, "unloaded module '%s' had "
15629 "enabled probes", modname);
15639 for (first = NULL; probe != NULL; probe = next) {
15640 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15642 dtrace_probes[probe->dtpr_id - 1] = NULL;
15644 next = probe->dtpr_nextmod;
15645 dtrace_hash_remove(dtrace_bymod, probe);
15646 dtrace_hash_remove(dtrace_byfunc, probe);
15647 dtrace_hash_remove(dtrace_byname, probe);
15649 if (first == NULL) {
15651 probe->dtpr_nextmod = NULL;
15653 probe->dtpr_nextmod = first;
15659 * We've removed all of the module's probes from the hash chains and
15660 * from the probe array. Now issue a dtrace_sync() to be sure that
15661 * everyone has cleared out from any probe array processing.
15665 for (probe = first; probe != NULL; probe = first) {
15666 first = probe->dtpr_nextmod;
15667 prov = probe->dtpr_provider;
15668 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15670 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15671 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15672 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15674 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15676 free_unr(dtrace_arena, probe->dtpr_id);
15678 kmem_free(probe, sizeof (dtrace_probe_t));
15681 mutex_exit(&dtrace_lock);
15683 mutex_exit(&mod_lock);
15685 mutex_exit(&dtrace_provider_lock);
15690 dtrace_kld_load(void *arg __unused, linker_file_t lf)
15693 dtrace_module_loaded(lf);
15697 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
15701 /* We already have an error, so don't do anything. */
15703 dtrace_module_unloaded(lf, error);
15709 dtrace_suspend(void)
15711 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15715 dtrace_resume(void)
15717 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15722 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15724 ASSERT(MUTEX_HELD(&cpu_lock));
15725 mutex_enter(&dtrace_lock);
15729 dtrace_state_t *state;
15730 dtrace_optval_t *opt, rs, c;
15733 * For now, we only allocate a new buffer for anonymous state.
15735 if ((state = dtrace_anon.dta_state) == NULL)
15738 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15741 opt = state->dts_options;
15742 c = opt[DTRACEOPT_CPU];
15744 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15748 * Regardless of what the actual policy is, we're going to
15749 * temporarily set our resize policy to be manual. We're
15750 * also going to temporarily set our CPU option to denote
15751 * the newly configured CPU.
15753 rs = opt[DTRACEOPT_BUFRESIZE];
15754 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15755 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15757 (void) dtrace_state_buffers(state);
15759 opt[DTRACEOPT_BUFRESIZE] = rs;
15760 opt[DTRACEOPT_CPU] = c;
15767 * We don't free the buffer in the CPU_UNCONFIG case. (The
15768 * buffer will be freed when the consumer exits.)
15776 mutex_exit(&dtrace_lock);
15782 dtrace_cpu_setup_initial(processorid_t cpu)
15784 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15789 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15791 if (dtrace_toxranges >= dtrace_toxranges_max) {
15793 dtrace_toxrange_t *range;
15795 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15798 ASSERT(dtrace_toxrange == NULL);
15799 ASSERT(dtrace_toxranges_max == 0);
15800 dtrace_toxranges_max = 1;
15802 dtrace_toxranges_max <<= 1;
15805 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15806 range = kmem_zalloc(nsize, KM_SLEEP);
15808 if (dtrace_toxrange != NULL) {
15809 ASSERT(osize != 0);
15810 bcopy(dtrace_toxrange, range, osize);
15811 kmem_free(dtrace_toxrange, osize);
15814 dtrace_toxrange = range;
15817 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15818 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15820 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15821 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15822 dtrace_toxranges++;
15826 dtrace_getf_barrier()
15830 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15831 * that contain calls to getf(), this routine will be called on every
15832 * closef() before either the underlying vnode is released or the
15833 * file_t itself is freed. By the time we are here, it is essential
15834 * that the file_t can no longer be accessed from a call to getf()
15835 * in probe context -- that assures that a dtrace_sync() can be used
15836 * to clear out any enablings referring to the old structures.
15838 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15839 kcred->cr_zone->zone_dtrace_getf != 0)
15845 * DTrace Driver Cookbook Functions
15850 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15852 dtrace_provider_id_t id;
15853 dtrace_state_t *state = NULL;
15854 dtrace_enabling_t *enab;
15856 mutex_enter(&cpu_lock);
15857 mutex_enter(&dtrace_provider_lock);
15858 mutex_enter(&dtrace_lock);
15860 if (ddi_soft_state_init(&dtrace_softstate,
15861 sizeof (dtrace_state_t), 0) != 0) {
15862 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15863 mutex_exit(&cpu_lock);
15864 mutex_exit(&dtrace_provider_lock);
15865 mutex_exit(&dtrace_lock);
15866 return (DDI_FAILURE);
15869 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15870 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15871 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15872 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15873 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15874 ddi_remove_minor_node(devi, NULL);
15875 ddi_soft_state_fini(&dtrace_softstate);
15876 mutex_exit(&cpu_lock);
15877 mutex_exit(&dtrace_provider_lock);
15878 mutex_exit(&dtrace_lock);
15879 return (DDI_FAILURE);
15882 ddi_report_dev(devi);
15883 dtrace_devi = devi;
15885 dtrace_modload = dtrace_module_loaded;
15886 dtrace_modunload = dtrace_module_unloaded;
15887 dtrace_cpu_init = dtrace_cpu_setup_initial;
15888 dtrace_helpers_cleanup = dtrace_helpers_destroy;
15889 dtrace_helpers_fork = dtrace_helpers_duplicate;
15890 dtrace_cpustart_init = dtrace_suspend;
15891 dtrace_cpustart_fini = dtrace_resume;
15892 dtrace_debugger_init = dtrace_suspend;
15893 dtrace_debugger_fini = dtrace_resume;
15895 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15897 ASSERT(MUTEX_HELD(&cpu_lock));
15899 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15900 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15901 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15902 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15903 VM_SLEEP | VMC_IDENTIFIER);
15904 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15907 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15908 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15909 NULL, NULL, NULL, NULL, NULL, 0);
15911 ASSERT(MUTEX_HELD(&cpu_lock));
15912 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15913 offsetof(dtrace_probe_t, dtpr_nextmod),
15914 offsetof(dtrace_probe_t, dtpr_prevmod));
15916 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15917 offsetof(dtrace_probe_t, dtpr_nextfunc),
15918 offsetof(dtrace_probe_t, dtpr_prevfunc));
15920 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15921 offsetof(dtrace_probe_t, dtpr_nextname),
15922 offsetof(dtrace_probe_t, dtpr_prevname));
15924 if (dtrace_retain_max < 1) {
15925 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15926 "setting to 1", dtrace_retain_max);
15927 dtrace_retain_max = 1;
15931 * Now discover our toxic ranges.
15933 dtrace_toxic_ranges(dtrace_toxrange_add);
15936 * Before we register ourselves as a provider to our own framework,
15937 * we would like to assert that dtrace_provider is NULL -- but that's
15938 * not true if we were loaded as a dependency of a DTrace provider.
15939 * Once we've registered, we can assert that dtrace_provider is our
15942 (void) dtrace_register("dtrace", &dtrace_provider_attr,
15943 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15945 ASSERT(dtrace_provider != NULL);
15946 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15948 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15949 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15950 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15951 dtrace_provider, NULL, NULL, "END", 0, NULL);
15952 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15953 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15955 dtrace_anon_property();
15956 mutex_exit(&cpu_lock);
15959 * If DTrace helper tracing is enabled, we need to allocate the
15960 * trace buffer and initialize the values.
15962 if (dtrace_helptrace_enabled) {
15963 ASSERT(dtrace_helptrace_buffer == NULL);
15964 dtrace_helptrace_buffer =
15965 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15966 dtrace_helptrace_next = 0;
15970 * If there are already providers, we must ask them to provide their
15971 * probes, and then match any anonymous enabling against them. Note
15972 * that there should be no other retained enablings at this time:
15973 * the only retained enablings at this time should be the anonymous
15976 if (dtrace_anon.dta_enabling != NULL) {
15977 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15979 dtrace_enabling_provide(NULL);
15980 state = dtrace_anon.dta_state;
15983 * We couldn't hold cpu_lock across the above call to
15984 * dtrace_enabling_provide(), but we must hold it to actually
15985 * enable the probes. We have to drop all of our locks, pick
15986 * up cpu_lock, and regain our locks before matching the
15987 * retained anonymous enabling.
15989 mutex_exit(&dtrace_lock);
15990 mutex_exit(&dtrace_provider_lock);
15992 mutex_enter(&cpu_lock);
15993 mutex_enter(&dtrace_provider_lock);
15994 mutex_enter(&dtrace_lock);
15996 if ((enab = dtrace_anon.dta_enabling) != NULL)
15997 (void) dtrace_enabling_match(enab, NULL);
15999 mutex_exit(&cpu_lock);
16002 mutex_exit(&dtrace_lock);
16003 mutex_exit(&dtrace_provider_lock);
16005 if (state != NULL) {
16007 * If we created any anonymous state, set it going now.
16009 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16012 return (DDI_SUCCESS);
16017 static void dtrace_dtr(void *);
16023 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16025 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16028 dtrace_state_t *state;
16034 if (getminor(*devp) == DTRACEMNRN_HELPER)
16038 * If this wasn't an open with the "helper" minor, then it must be
16039 * the "dtrace" minor.
16041 ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
16043 cred_t *cred_p = NULL;
16044 cred_p = dev->si_cred;
16047 * If no DTRACE_PRIV_* bits are set in the credential, then the
16048 * caller lacks sufficient permission to do anything with DTrace.
16050 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16051 if (priv == DTRACE_PRIV_NONE) {
16058 * Ask all providers to provide all their probes.
16060 mutex_enter(&dtrace_provider_lock);
16061 dtrace_probe_provide(NULL, NULL);
16062 mutex_exit(&dtrace_provider_lock);
16064 mutex_enter(&cpu_lock);
16065 mutex_enter(&dtrace_lock);
16067 dtrace_membar_producer();
16071 * If the kernel debugger is active (that is, if the kernel debugger
16072 * modified text in some way), we won't allow the open.
16074 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16076 mutex_exit(&cpu_lock);
16077 mutex_exit(&dtrace_lock);
16081 state = dtrace_state_create(devp, cred_p);
16083 state = dtrace_state_create(dev);
16084 devfs_set_cdevpriv(state, dtrace_dtr);
16087 mutex_exit(&cpu_lock);
16089 if (state == NULL) {
16091 if (--dtrace_opens == 0)
16092 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16096 mutex_exit(&dtrace_lock);
16100 mutex_exit(&dtrace_lock);
16108 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16111 dtrace_dtr(void *data)
16115 minor_t minor = getminor(dev);
16116 dtrace_state_t *state;
16118 if (minor == DTRACEMNRN_HELPER)
16121 state = ddi_get_soft_state(dtrace_softstate, minor);
16123 dtrace_state_t *state = data;
16126 mutex_enter(&cpu_lock);
16127 mutex_enter(&dtrace_lock);
16129 if (state != NULL) {
16130 if (state->dts_anon) {
16132 * There is anonymous state. Destroy that first.
16134 ASSERT(dtrace_anon.dta_state == NULL);
16135 dtrace_state_destroy(state->dts_anon);
16138 dtrace_state_destroy(state);
16141 kmem_free(state, 0);
16145 ASSERT(dtrace_opens > 0);
16147 if (--dtrace_opens == 0)
16148 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16153 mutex_exit(&dtrace_lock);
16154 mutex_exit(&cpu_lock);
16164 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16167 dof_helper_t help, *dhp = NULL;
16170 case DTRACEHIOC_ADDDOF:
16171 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16172 dtrace_dof_error(NULL, "failed to copyin DOF helper");
16177 arg = (intptr_t)help.dofhp_dof;
16180 case DTRACEHIOC_ADD: {
16181 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16186 mutex_enter(&dtrace_lock);
16189 * dtrace_helper_slurp() takes responsibility for the dof --
16190 * it may free it now or it may save it and free it later.
16192 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16199 mutex_exit(&dtrace_lock);
16203 case DTRACEHIOC_REMOVE: {
16204 mutex_enter(&dtrace_lock);
16205 rval = dtrace_helper_destroygen(arg);
16206 mutex_exit(&dtrace_lock);
16220 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16222 minor_t minor = getminor(dev);
16223 dtrace_state_t *state;
16226 if (minor == DTRACEMNRN_HELPER)
16227 return (dtrace_ioctl_helper(cmd, arg, rv));
16229 state = ddi_get_soft_state(dtrace_softstate, minor);
16231 if (state->dts_anon) {
16232 ASSERT(dtrace_anon.dta_state == NULL);
16233 state = state->dts_anon;
16237 case DTRACEIOC_PROVIDER: {
16238 dtrace_providerdesc_t pvd;
16239 dtrace_provider_t *pvp;
16241 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16244 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16245 mutex_enter(&dtrace_provider_lock);
16247 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16248 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16252 mutex_exit(&dtrace_provider_lock);
16257 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16258 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16260 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16266 case DTRACEIOC_EPROBE: {
16267 dtrace_eprobedesc_t epdesc;
16269 dtrace_action_t *act;
16275 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16278 mutex_enter(&dtrace_lock);
16280 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16281 mutex_exit(&dtrace_lock);
16285 if (ecb->dte_probe == NULL) {
16286 mutex_exit(&dtrace_lock);
16290 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16291 epdesc.dtepd_uarg = ecb->dte_uarg;
16292 epdesc.dtepd_size = ecb->dte_size;
16294 nrecs = epdesc.dtepd_nrecs;
16295 epdesc.dtepd_nrecs = 0;
16296 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16297 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16300 epdesc.dtepd_nrecs++;
16304 * Now that we have the size, we need to allocate a temporary
16305 * buffer in which to store the complete description. We need
16306 * the temporary buffer to be able to drop dtrace_lock()
16307 * across the copyout(), below.
16309 size = sizeof (dtrace_eprobedesc_t) +
16310 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16312 buf = kmem_alloc(size, KM_SLEEP);
16313 dest = (uintptr_t)buf;
16315 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16316 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16318 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16319 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16325 bcopy(&act->dta_rec, (void *)dest,
16326 sizeof (dtrace_recdesc_t));
16327 dest += sizeof (dtrace_recdesc_t);
16330 mutex_exit(&dtrace_lock);
16332 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16333 kmem_free(buf, size);
16337 kmem_free(buf, size);
16341 case DTRACEIOC_AGGDESC: {
16342 dtrace_aggdesc_t aggdesc;
16343 dtrace_action_t *act;
16344 dtrace_aggregation_t *agg;
16347 dtrace_recdesc_t *lrec;
16352 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16355 mutex_enter(&dtrace_lock);
16357 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16358 mutex_exit(&dtrace_lock);
16362 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16364 nrecs = aggdesc.dtagd_nrecs;
16365 aggdesc.dtagd_nrecs = 0;
16367 offs = agg->dtag_base;
16368 lrec = &agg->dtag_action.dta_rec;
16369 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16371 for (act = agg->dtag_first; ; act = act->dta_next) {
16372 ASSERT(act->dta_intuple ||
16373 DTRACEACT_ISAGG(act->dta_kind));
16376 * If this action has a record size of zero, it
16377 * denotes an argument to the aggregating action.
16378 * Because the presence of this record doesn't (or
16379 * shouldn't) affect the way the data is interpreted,
16380 * we don't copy it out to save user-level the
16381 * confusion of dealing with a zero-length record.
16383 if (act->dta_rec.dtrd_size == 0) {
16384 ASSERT(agg->dtag_hasarg);
16388 aggdesc.dtagd_nrecs++;
16390 if (act == &agg->dtag_action)
16395 * Now that we have the size, we need to allocate a temporary
16396 * buffer in which to store the complete description. We need
16397 * the temporary buffer to be able to drop dtrace_lock()
16398 * across the copyout(), below.
16400 size = sizeof (dtrace_aggdesc_t) +
16401 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16403 buf = kmem_alloc(size, KM_SLEEP);
16404 dest = (uintptr_t)buf;
16406 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16407 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16409 for (act = agg->dtag_first; ; act = act->dta_next) {
16410 dtrace_recdesc_t rec = act->dta_rec;
16413 * See the comment in the above loop for why we pass
16414 * over zero-length records.
16416 if (rec.dtrd_size == 0) {
16417 ASSERT(agg->dtag_hasarg);
16424 rec.dtrd_offset -= offs;
16425 bcopy(&rec, (void *)dest, sizeof (rec));
16426 dest += sizeof (dtrace_recdesc_t);
16428 if (act == &agg->dtag_action)
16432 mutex_exit(&dtrace_lock);
16434 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16435 kmem_free(buf, size);
16439 kmem_free(buf, size);
16443 case DTRACEIOC_ENABLE: {
16445 dtrace_enabling_t *enab = NULL;
16446 dtrace_vstate_t *vstate;
16452 * If a NULL argument has been passed, we take this as our
16453 * cue to reevaluate our enablings.
16456 dtrace_enabling_matchall();
16461 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16464 mutex_enter(&cpu_lock);
16465 mutex_enter(&dtrace_lock);
16466 vstate = &state->dts_vstate;
16468 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16469 mutex_exit(&dtrace_lock);
16470 mutex_exit(&cpu_lock);
16471 dtrace_dof_destroy(dof);
16475 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16476 mutex_exit(&dtrace_lock);
16477 mutex_exit(&cpu_lock);
16478 dtrace_dof_destroy(dof);
16482 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16483 dtrace_enabling_destroy(enab);
16484 mutex_exit(&dtrace_lock);
16485 mutex_exit(&cpu_lock);
16486 dtrace_dof_destroy(dof);
16490 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16491 err = dtrace_enabling_retain(enab);
16493 dtrace_enabling_destroy(enab);
16496 mutex_exit(&cpu_lock);
16497 mutex_exit(&dtrace_lock);
16498 dtrace_dof_destroy(dof);
16503 case DTRACEIOC_REPLICATE: {
16504 dtrace_repldesc_t desc;
16505 dtrace_probedesc_t *match = &desc.dtrpd_match;
16506 dtrace_probedesc_t *create = &desc.dtrpd_create;
16509 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16512 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16513 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16514 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16515 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16517 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16518 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16519 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16520 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16522 mutex_enter(&dtrace_lock);
16523 err = dtrace_enabling_replicate(state, match, create);
16524 mutex_exit(&dtrace_lock);
16529 case DTRACEIOC_PROBEMATCH:
16530 case DTRACEIOC_PROBES: {
16531 dtrace_probe_t *probe = NULL;
16532 dtrace_probedesc_t desc;
16533 dtrace_probekey_t pkey;
16540 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16543 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16544 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16545 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16546 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16549 * Before we attempt to match this probe, we want to give
16550 * all providers the opportunity to provide it.
16552 if (desc.dtpd_id == DTRACE_IDNONE) {
16553 mutex_enter(&dtrace_provider_lock);
16554 dtrace_probe_provide(&desc, NULL);
16555 mutex_exit(&dtrace_provider_lock);
16559 if (cmd == DTRACEIOC_PROBEMATCH) {
16560 dtrace_probekey(&desc, &pkey);
16561 pkey.dtpk_id = DTRACE_IDNONE;
16564 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16566 mutex_enter(&dtrace_lock);
16568 if (cmd == DTRACEIOC_PROBEMATCH) {
16569 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16570 if ((probe = dtrace_probes[i - 1]) != NULL &&
16571 (m = dtrace_match_probe(probe, &pkey,
16572 priv, uid, zoneid)) != 0)
16577 mutex_exit(&dtrace_lock);
16582 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16583 if ((probe = dtrace_probes[i - 1]) != NULL &&
16584 dtrace_match_priv(probe, priv, uid, zoneid))
16589 if (probe == NULL) {
16590 mutex_exit(&dtrace_lock);
16594 dtrace_probe_description(probe, &desc);
16595 mutex_exit(&dtrace_lock);
16597 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16603 case DTRACEIOC_PROBEARG: {
16604 dtrace_argdesc_t desc;
16605 dtrace_probe_t *probe;
16606 dtrace_provider_t *prov;
16608 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16611 if (desc.dtargd_id == DTRACE_IDNONE)
16614 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16617 mutex_enter(&dtrace_provider_lock);
16618 mutex_enter(&mod_lock);
16619 mutex_enter(&dtrace_lock);
16621 if (desc.dtargd_id > dtrace_nprobes) {
16622 mutex_exit(&dtrace_lock);
16623 mutex_exit(&mod_lock);
16624 mutex_exit(&dtrace_provider_lock);
16628 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16629 mutex_exit(&dtrace_lock);
16630 mutex_exit(&mod_lock);
16631 mutex_exit(&dtrace_provider_lock);
16635 mutex_exit(&dtrace_lock);
16637 prov = probe->dtpr_provider;
16639 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16641 * There isn't any typed information for this probe.
16642 * Set the argument number to DTRACE_ARGNONE.
16644 desc.dtargd_ndx = DTRACE_ARGNONE;
16646 desc.dtargd_native[0] = '\0';
16647 desc.dtargd_xlate[0] = '\0';
16648 desc.dtargd_mapping = desc.dtargd_ndx;
16650 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16651 probe->dtpr_id, probe->dtpr_arg, &desc);
16654 mutex_exit(&mod_lock);
16655 mutex_exit(&dtrace_provider_lock);
16657 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16663 case DTRACEIOC_GO: {
16664 processorid_t cpuid;
16665 rval = dtrace_state_go(state, &cpuid);
16670 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16676 case DTRACEIOC_STOP: {
16677 processorid_t cpuid;
16679 mutex_enter(&dtrace_lock);
16680 rval = dtrace_state_stop(state, &cpuid);
16681 mutex_exit(&dtrace_lock);
16686 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16692 case DTRACEIOC_DOFGET: {
16693 dof_hdr_t hdr, *dof;
16696 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16699 mutex_enter(&dtrace_lock);
16700 dof = dtrace_dof_create(state);
16701 mutex_exit(&dtrace_lock);
16703 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16704 rval = copyout(dof, (void *)arg, len);
16705 dtrace_dof_destroy(dof);
16707 return (rval == 0 ? 0 : EFAULT);
16710 case DTRACEIOC_AGGSNAP:
16711 case DTRACEIOC_BUFSNAP: {
16712 dtrace_bufdesc_t desc;
16714 dtrace_buffer_t *buf;
16716 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16719 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16722 mutex_enter(&dtrace_lock);
16724 if (cmd == DTRACEIOC_BUFSNAP) {
16725 buf = &state->dts_buffer[desc.dtbd_cpu];
16727 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16730 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16731 size_t sz = buf->dtb_offset;
16733 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16734 mutex_exit(&dtrace_lock);
16739 * If this buffer has already been consumed, we're
16740 * going to indicate that there's nothing left here
16743 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16744 mutex_exit(&dtrace_lock);
16746 desc.dtbd_size = 0;
16747 desc.dtbd_drops = 0;
16748 desc.dtbd_errors = 0;
16749 desc.dtbd_oldest = 0;
16750 sz = sizeof (desc);
16752 if (copyout(&desc, (void *)arg, sz) != 0)
16759 * If this is a ring buffer that has wrapped, we want
16760 * to copy the whole thing out.
16762 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16763 dtrace_buffer_polish(buf);
16764 sz = buf->dtb_size;
16767 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16768 mutex_exit(&dtrace_lock);
16772 desc.dtbd_size = sz;
16773 desc.dtbd_drops = buf->dtb_drops;
16774 desc.dtbd_errors = buf->dtb_errors;
16775 desc.dtbd_oldest = buf->dtb_xamot_offset;
16776 desc.dtbd_timestamp = dtrace_gethrtime();
16778 mutex_exit(&dtrace_lock);
16780 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16783 buf->dtb_flags |= DTRACEBUF_CONSUMED;
16788 if (buf->dtb_tomax == NULL) {
16789 ASSERT(buf->dtb_xamot == NULL);
16790 mutex_exit(&dtrace_lock);
16794 cached = buf->dtb_tomax;
16795 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16797 dtrace_xcall(desc.dtbd_cpu,
16798 (dtrace_xcall_t)dtrace_buffer_switch, buf);
16800 state->dts_errors += buf->dtb_xamot_errors;
16803 * If the buffers did not actually switch, then the cross call
16804 * did not take place -- presumably because the given CPU is
16805 * not in the ready set. If this is the case, we'll return
16808 if (buf->dtb_tomax == cached) {
16809 ASSERT(buf->dtb_xamot != cached);
16810 mutex_exit(&dtrace_lock);
16814 ASSERT(cached == buf->dtb_xamot);
16817 * We have our snapshot; now copy it out.
16819 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16820 buf->dtb_xamot_offset) != 0) {
16821 mutex_exit(&dtrace_lock);
16825 desc.dtbd_size = buf->dtb_xamot_offset;
16826 desc.dtbd_drops = buf->dtb_xamot_drops;
16827 desc.dtbd_errors = buf->dtb_xamot_errors;
16828 desc.dtbd_oldest = 0;
16829 desc.dtbd_timestamp = buf->dtb_switched;
16831 mutex_exit(&dtrace_lock);
16834 * Finally, copy out the buffer description.
16836 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16842 case DTRACEIOC_CONF: {
16843 dtrace_conf_t conf;
16845 bzero(&conf, sizeof (conf));
16846 conf.dtc_difversion = DIF_VERSION;
16847 conf.dtc_difintregs = DIF_DIR_NREGS;
16848 conf.dtc_diftupregs = DIF_DTR_NREGS;
16849 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16851 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16857 case DTRACEIOC_STATUS: {
16858 dtrace_status_t stat;
16859 dtrace_dstate_t *dstate;
16864 * See the comment in dtrace_state_deadman() for the reason
16865 * for setting dts_laststatus to INT64_MAX before setting
16866 * it to the correct value.
16868 state->dts_laststatus = INT64_MAX;
16869 dtrace_membar_producer();
16870 state->dts_laststatus = dtrace_gethrtime();
16872 bzero(&stat, sizeof (stat));
16874 mutex_enter(&dtrace_lock);
16876 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16877 mutex_exit(&dtrace_lock);
16881 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16882 stat.dtst_exiting = 1;
16884 nerrs = state->dts_errors;
16885 dstate = &state->dts_vstate.dtvs_dynvars;
16887 for (i = 0; i < NCPU; i++) {
16888 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16890 stat.dtst_dyndrops += dcpu->dtdsc_drops;
16891 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16892 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16894 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16895 stat.dtst_filled++;
16897 nerrs += state->dts_buffer[i].dtb_errors;
16899 for (j = 0; j < state->dts_nspeculations; j++) {
16900 dtrace_speculation_t *spec;
16901 dtrace_buffer_t *buf;
16903 spec = &state->dts_speculations[j];
16904 buf = &spec->dtsp_buffer[i];
16905 stat.dtst_specdrops += buf->dtb_xamot_drops;
16909 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16910 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16911 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16912 stat.dtst_dblerrors = state->dts_dblerrors;
16914 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16915 stat.dtst_errors = nerrs;
16917 mutex_exit(&dtrace_lock);
16919 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16925 case DTRACEIOC_FORMAT: {
16926 dtrace_fmtdesc_t fmt;
16930 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16933 mutex_enter(&dtrace_lock);
16935 if (fmt.dtfd_format == 0 ||
16936 fmt.dtfd_format > state->dts_nformats) {
16937 mutex_exit(&dtrace_lock);
16942 * Format strings are allocated contiguously and they are
16943 * never freed; if a format index is less than the number
16944 * of formats, we can assert that the format map is non-NULL
16945 * and that the format for the specified index is non-NULL.
16947 ASSERT(state->dts_formats != NULL);
16948 str = state->dts_formats[fmt.dtfd_format - 1];
16949 ASSERT(str != NULL);
16951 len = strlen(str) + 1;
16953 if (len > fmt.dtfd_length) {
16954 fmt.dtfd_length = len;
16956 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16957 mutex_exit(&dtrace_lock);
16961 if (copyout(str, fmt.dtfd_string, len) != 0) {
16962 mutex_exit(&dtrace_lock);
16967 mutex_exit(&dtrace_lock);
16980 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16982 dtrace_state_t *state;
16989 return (DDI_SUCCESS);
16992 return (DDI_FAILURE);
16995 mutex_enter(&cpu_lock);
16996 mutex_enter(&dtrace_provider_lock);
16997 mutex_enter(&dtrace_lock);
16999 ASSERT(dtrace_opens == 0);
17001 if (dtrace_helpers > 0) {
17002 mutex_exit(&dtrace_provider_lock);
17003 mutex_exit(&dtrace_lock);
17004 mutex_exit(&cpu_lock);
17005 return (DDI_FAILURE);
17008 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17009 mutex_exit(&dtrace_provider_lock);
17010 mutex_exit(&dtrace_lock);
17011 mutex_exit(&cpu_lock);
17012 return (DDI_FAILURE);
17015 dtrace_provider = NULL;
17017 if ((state = dtrace_anon_grab()) != NULL) {
17019 * If there were ECBs on this state, the provider should
17020 * have not been allowed to detach; assert that there is
17023 ASSERT(state->dts_necbs == 0);
17024 dtrace_state_destroy(state);
17027 * If we're being detached with anonymous state, we need to
17028 * indicate to the kernel debugger that DTrace is now inactive.
17030 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17033 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17034 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17035 dtrace_cpu_init = NULL;
17036 dtrace_helpers_cleanup = NULL;
17037 dtrace_helpers_fork = NULL;
17038 dtrace_cpustart_init = NULL;
17039 dtrace_cpustart_fini = NULL;
17040 dtrace_debugger_init = NULL;
17041 dtrace_debugger_fini = NULL;
17042 dtrace_modload = NULL;
17043 dtrace_modunload = NULL;
17045 ASSERT(dtrace_getf == 0);
17046 ASSERT(dtrace_closef == NULL);
17048 mutex_exit(&cpu_lock);
17050 if (dtrace_helptrace_enabled) {
17051 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17052 dtrace_helptrace_buffer = NULL;
17055 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17056 dtrace_probes = NULL;
17057 dtrace_nprobes = 0;
17059 dtrace_hash_destroy(dtrace_bymod);
17060 dtrace_hash_destroy(dtrace_byfunc);
17061 dtrace_hash_destroy(dtrace_byname);
17062 dtrace_bymod = NULL;
17063 dtrace_byfunc = NULL;
17064 dtrace_byname = NULL;
17066 kmem_cache_destroy(dtrace_state_cache);
17067 vmem_destroy(dtrace_minor);
17068 vmem_destroy(dtrace_arena);
17070 if (dtrace_toxrange != NULL) {
17071 kmem_free(dtrace_toxrange,
17072 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17073 dtrace_toxrange = NULL;
17074 dtrace_toxranges = 0;
17075 dtrace_toxranges_max = 0;
17078 ddi_remove_minor_node(dtrace_devi, NULL);
17079 dtrace_devi = NULL;
17081 ddi_soft_state_fini(&dtrace_softstate);
17083 ASSERT(dtrace_vtime_references == 0);
17084 ASSERT(dtrace_opens == 0);
17085 ASSERT(dtrace_retained == NULL);
17087 mutex_exit(&dtrace_lock);
17088 mutex_exit(&dtrace_provider_lock);
17091 * We don't destroy the task queue until after we have dropped our
17092 * locks (taskq_destroy() may block on running tasks). To prevent
17093 * attempting to do work after we have effectively detached but before
17094 * the task queue has been destroyed, all tasks dispatched via the
17095 * task queue must check that DTrace is still attached before
17096 * performing any operation.
17098 taskq_destroy(dtrace_taskq);
17099 dtrace_taskq = NULL;
17101 return (DDI_SUCCESS);
17108 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17113 case DDI_INFO_DEVT2DEVINFO:
17114 *result = (void *)dtrace_devi;
17115 error = DDI_SUCCESS;
17117 case DDI_INFO_DEVT2INSTANCE:
17118 *result = (void *)0;
17119 error = DDI_SUCCESS;
17122 error = DDI_FAILURE;
17129 static struct cb_ops dtrace_cb_ops = {
17130 dtrace_open, /* open */
17131 dtrace_close, /* close */
17132 nulldev, /* strategy */
17133 nulldev, /* print */
17137 dtrace_ioctl, /* ioctl */
17138 nodev, /* devmap */
17140 nodev, /* segmap */
17141 nochpoll, /* poll */
17142 ddi_prop_op, /* cb_prop_op */
17144 D_NEW | D_MP /* Driver compatibility flag */
17147 static struct dev_ops dtrace_ops = {
17148 DEVO_REV, /* devo_rev */
17150 dtrace_info, /* get_dev_info */
17151 nulldev, /* identify */
17152 nulldev, /* probe */
17153 dtrace_attach, /* attach */
17154 dtrace_detach, /* detach */
17156 &dtrace_cb_ops, /* driver operations */
17157 NULL, /* bus operations */
17158 nodev /* dev power */
17161 static struct modldrv modldrv = {
17162 &mod_driverops, /* module type (this is a pseudo driver) */
17163 "Dynamic Tracing", /* name of module */
17164 &dtrace_ops, /* driver ops */
17167 static struct modlinkage modlinkage = {
17176 return (mod_install(&modlinkage));
17180 _info(struct modinfo *modinfop)
17182 return (mod_info(&modlinkage, modinfop));
17188 return (mod_remove(&modlinkage));
17192 static d_ioctl_t dtrace_ioctl;
17193 static d_ioctl_t dtrace_ioctl_helper;
17194 static void dtrace_load(void *);
17195 static int dtrace_unload(void);
17196 static struct cdev *dtrace_dev;
17197 static struct cdev *helper_dev;
17199 void dtrace_invop_init(void);
17200 void dtrace_invop_uninit(void);
17202 static struct cdevsw dtrace_cdevsw = {
17203 .d_version = D_VERSION,
17204 .d_ioctl = dtrace_ioctl,
17205 .d_open = dtrace_open,
17206 .d_name = "dtrace",
17209 static struct cdevsw helper_cdevsw = {
17210 .d_version = D_VERSION,
17211 .d_ioctl = dtrace_ioctl_helper,
17212 .d_name = "helper",
17215 #include <dtrace_anon.c>
17216 #include <dtrace_ioctl.c>
17217 #include <dtrace_load.c>
17218 #include <dtrace_modevent.c>
17219 #include <dtrace_sysctl.c>
17220 #include <dtrace_unload.c>
17221 #include <dtrace_vtime.c>
17222 #include <dtrace_hacks.c>
17223 #include <dtrace_isa.c>
17225 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
17226 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
17227 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
17229 DEV_MODULE(dtrace, dtrace_modevent, NULL);
17230 MODULE_VERSION(dtrace, 1);
17231 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
17232 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);