4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
25 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
26 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2012 by Delphix. All rights reserved.
31 * DTrace - Dynamic Tracing for Solaris
33 * This is the implementation of the Solaris Dynamic Tracing framework
34 * (DTrace). The user-visible interface to DTrace is described at length in
35 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
36 * library, the in-kernel DTrace framework, and the DTrace providers are
37 * described in the block comments in the <sys/dtrace.h> header file. The
38 * internal architecture of DTrace is described in the block comments in the
39 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
40 * implementation very much assume mastery of all of these sources; if one has
41 * an unanswered question about the implementation, one should consult them
44 * The functions here are ordered roughly as follows:
46 * - Probe context functions
47 * - Probe hashing functions
48 * - Non-probe context utility functions
49 * - Matching functions
50 * - Provider-to-Framework API functions
51 * - Probe management functions
52 * - DIF object functions
54 * - Predicate functions
57 * - Enabling functions
59 * - Anonymous enabling functions
60 * - Consumer state functions
63 * - Driver cookbook functions
65 * Each group of functions begins with a block comment labelled the "DTrace
66 * [Group] Functions", allowing one to find each block by searching forward
67 * on capital-f functions.
69 #include <sys/errno.h>
74 #include <sys/modctl.h>
76 #include <sys/systm.h>
79 #include <sys/sunddi.h>
81 #include <sys/cpuvar.h>
84 #include <sys/strsubr.h>
86 #include <sys/sysmacros.h>
87 #include <sys/dtrace_impl.h>
88 #include <sys/atomic.h>
89 #include <sys/cmn_err.h>
91 #include <sys/mutex_impl.h>
92 #include <sys/rwlock_impl.h>
94 #include <sys/ctf_api.h>
96 #include <sys/panic.h>
97 #include <sys/priv_impl.h>
99 #include <sys/policy.h>
101 #include <sys/cred_impl.h>
102 #include <sys/procfs_isa.h>
104 #include <sys/taskq.h>
106 #include <sys/mkdev.h>
109 #include <sys/zone.h>
110 #include <sys/socket.h>
111 #include <netinet/in.h>
112 #include "strtolctype.h"
114 /* FreeBSD includes: */
116 #include <sys/callout.h>
117 #include <sys/ctype.h>
118 #include <sys/eventhandler.h>
119 #include <sys/limits.h>
121 #include <sys/kernel.h>
122 #include <sys/malloc.h>
123 #include <sys/sysctl.h>
124 #include <sys/lock.h>
125 #include <sys/mutex.h>
126 #include <sys/rwlock.h>
128 #include <sys/dtrace_bsd.h>
129 #include <netinet/in.h>
130 #include "dtrace_cddl.h"
131 #include "dtrace_debug.c"
135 * DTrace Tunable Variables
137 * The following variables may be tuned by adding a line to /etc/system that
138 * includes both the name of the DTrace module ("dtrace") and the name of the
139 * variable. For example:
141 * set dtrace:dtrace_destructive_disallow = 1
143 * In general, the only variables that one should be tuning this way are those
144 * that affect system-wide DTrace behavior, and for which the default behavior
145 * is undesirable. Most of these variables are tunable on a per-consumer
146 * basis using DTrace options, and need not be tuned on a system-wide basis.
147 * When tuning these variables, avoid pathological values; while some attempt
148 * is made to verify the integrity of these variables, they are not considered
149 * part of the supported interface to DTrace, and they are therefore not
150 * checked comprehensively. Further, these variables should not be tuned
151 * dynamically via "mdb -kw" or other means; they should only be tuned via
154 int dtrace_destructive_disallow = 0;
155 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
156 size_t dtrace_difo_maxsize = (256 * 1024);
157 dtrace_optval_t dtrace_dof_maxsize = (8 * 1024 * 1024);
158 size_t dtrace_global_maxsize = (16 * 1024);
159 size_t dtrace_actions_max = (16 * 1024);
160 size_t dtrace_retain_max = 1024;
161 dtrace_optval_t dtrace_helper_actions_max = 128;
162 dtrace_optval_t dtrace_helper_providers_max = 32;
163 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
164 size_t dtrace_strsize_default = 256;
165 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
166 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
167 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
168 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
169 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
170 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
171 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
172 dtrace_optval_t dtrace_nspec_default = 1;
173 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
174 dtrace_optval_t dtrace_stackframes_default = 20;
175 dtrace_optval_t dtrace_ustackframes_default = 20;
176 dtrace_optval_t dtrace_jstackframes_default = 50;
177 dtrace_optval_t dtrace_jstackstrsize_default = 512;
178 int dtrace_msgdsize_max = 128;
179 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
180 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
181 int dtrace_devdepth_max = 32;
182 int dtrace_err_verbose;
183 hrtime_t dtrace_deadman_interval = NANOSEC;
184 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
185 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
186 hrtime_t dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
188 int dtrace_memstr_max = 4096;
192 * DTrace External Variables
194 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
195 * available to DTrace consumers via the backtick (`) syntax. One of these,
196 * dtrace_zero, is made deliberately so: it is provided as a source of
197 * well-known, zero-filled memory. While this variable is not documented,
198 * it is used by some translators as an implementation detail.
200 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
203 * DTrace Internal Variables
206 static dev_info_t *dtrace_devi; /* device info */
209 static vmem_t *dtrace_arena; /* probe ID arena */
210 static vmem_t *dtrace_minor; /* minor number arena */
212 static taskq_t *dtrace_taskq; /* task queue */
213 static struct unrhdr *dtrace_arena; /* Probe ID number. */
215 static dtrace_probe_t **dtrace_probes; /* array of all probes */
216 static int dtrace_nprobes; /* number of probes */
217 static dtrace_provider_t *dtrace_provider; /* provider list */
218 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
219 static int dtrace_opens; /* number of opens */
220 static int dtrace_helpers; /* number of helpers */
221 static int dtrace_getf; /* number of unpriv getf()s */
223 static void *dtrace_softstate; /* softstate pointer */
225 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
226 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
227 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
228 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
229 static int dtrace_toxranges; /* number of toxic ranges */
230 static int dtrace_toxranges_max; /* size of toxic range array */
231 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
232 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
233 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
234 static kthread_t *dtrace_panicked; /* panicking thread */
235 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
236 static dtrace_genid_t dtrace_probegen; /* current probe generation */
237 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
238 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
239 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
240 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
241 static int dtrace_dynvar_failclean; /* dynvars failed to clean */
243 static struct mtx dtrace_unr_mtx;
244 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
245 int dtrace_in_probe; /* non-zero if executing a probe */
246 #if defined(__i386__) || defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
247 uintptr_t dtrace_in_probe_addr; /* Address of invop when already in probe */
249 static eventhandler_tag dtrace_kld_load_tag;
250 static eventhandler_tag dtrace_kld_unload_try_tag;
255 * DTrace is protected by three (relatively coarse-grained) locks:
257 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
258 * including enabling state, probes, ECBs, consumer state, helper state,
259 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
260 * probe context is lock-free -- synchronization is handled via the
261 * dtrace_sync() cross call mechanism.
263 * (2) dtrace_provider_lock is required when manipulating provider state, or
264 * when provider state must be held constant.
266 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
267 * when meta provider state must be held constant.
269 * The lock ordering between these three locks is dtrace_meta_lock before
270 * dtrace_provider_lock before dtrace_lock. (In particular, there are
271 * several places where dtrace_provider_lock is held by the framework as it
272 * calls into the providers -- which then call back into the framework,
273 * grabbing dtrace_lock.)
275 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
276 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
277 * role as a coarse-grained lock; it is acquired before both of these locks.
278 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
279 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
280 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
281 * acquired _between_ dtrace_provider_lock and dtrace_lock.
283 static kmutex_t dtrace_lock; /* probe state lock */
284 static kmutex_t dtrace_provider_lock; /* provider state lock */
285 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
288 /* XXX FreeBSD hacks. */
289 #define cr_suid cr_svuid
290 #define cr_sgid cr_svgid
291 #define ipaddr_t in_addr_t
292 #define mod_modname pathname
293 #define vuprintf vprintf
294 #define ttoproc(_a) ((_a)->td_proc)
295 #define crgetzoneid(_a) 0
298 #define CPU_ON_INTR(_a) 0
300 #define PRIV_EFFECTIVE (1 << 0)
301 #define PRIV_DTRACE_KERNEL (1 << 1)
302 #define PRIV_DTRACE_PROC (1 << 2)
303 #define PRIV_DTRACE_USER (1 << 3)
304 #define PRIV_PROC_OWNER (1 << 4)
305 #define PRIV_PROC_ZONE (1 << 5)
308 SYSCTL_DECL(_debug_dtrace);
309 SYSCTL_DECL(_kern_dtrace);
313 #define curcpu CPU->cpu_id
318 * DTrace Provider Variables
320 * These are the variables relating to DTrace as a provider (that is, the
321 * provider of the BEGIN, END, and ERROR probes).
323 static dtrace_pattr_t dtrace_provider_attr = {
324 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
325 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
326 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
327 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
328 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
335 static dtrace_pops_t dtrace_provider_ops = {
336 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
337 (void (*)(void *, modctl_t *))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,
341 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
345 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
348 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
349 static dtrace_id_t dtrace_probeid_end; /* special END probe */
350 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
353 * DTrace Helper Tracing Variables
355 uint32_t dtrace_helptrace_next = 0;
356 uint32_t dtrace_helptrace_nlocals;
357 char *dtrace_helptrace_buffer;
358 int dtrace_helptrace_bufsize = 512 * 1024;
361 int dtrace_helptrace_enabled = 1;
363 int dtrace_helptrace_enabled = 0;
367 * DTrace Error Hashing
369 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
370 * table. This is very useful for checking coverage of tests that are
371 * expected to induce DIF or DOF processing errors, and may be useful for
372 * debugging problems in the DIF code generator or in DOF generation . The
373 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
376 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
377 static const char *dtrace_errlast;
378 static kthread_t *dtrace_errthread;
379 static kmutex_t dtrace_errlock;
383 * DTrace Macros and Constants
385 * These are various macros that are useful in various spots in the
386 * implementation, along with a few random constants that have no meaning
387 * outside of the implementation. There is no real structure to this cpp
388 * mishmash -- but is there ever?
390 #define DTRACE_HASHSTR(hash, probe) \
391 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
393 #define DTRACE_HASHNEXT(hash, probe) \
394 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
396 #define DTRACE_HASHPREV(hash, probe) \
397 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
399 #define DTRACE_HASHEQ(hash, lhs, rhs) \
400 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
401 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
403 #define DTRACE_AGGHASHSIZE_SLEW 17
405 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
408 * The key for a thread-local variable consists of the lower 61 bits of the
409 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
410 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
411 * equal to a variable identifier. This is necessary (but not sufficient) to
412 * assure that global associative arrays never collide with thread-local
413 * variables. To guarantee that they cannot collide, we must also define the
414 * order for keying dynamic variables. That order is:
416 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
418 * Because the variable-key and the tls-key are in orthogonal spaces, there is
419 * no way for a global variable key signature to match a thread-local key
423 #define DTRACE_TLS_THRKEY(where) { \
425 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
426 for (; actv; actv >>= 1) \
428 ASSERT(intr < (1 << 3)); \
429 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
430 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
433 #define DTRACE_TLS_THRKEY(where) { \
434 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
436 uint_t actv = _c->cpu_intr_actv; \
437 for (; actv; actv >>= 1) \
439 ASSERT(intr < (1 << 3)); \
440 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
441 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
445 #define DT_BSWAP_8(x) ((x) & 0xff)
446 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
447 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
448 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
450 #define DT_MASK_LO 0x00000000FFFFFFFFULL
452 #define DTRACE_STORE(type, tomax, offset, what) \
453 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
456 #define DTRACE_ALIGNCHECK(addr, size, flags) \
457 if (addr & (size - 1)) { \
458 *flags |= CPU_DTRACE_BADALIGN; \
459 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
463 #define DTRACE_ALIGNCHECK(addr, size, flags)
467 * Test whether a range of memory starting at testaddr of size testsz falls
468 * within the range of memory described by addr, sz. We take care to avoid
469 * problems with overflow and underflow of the unsigned quantities, and
470 * disallow all negative sizes. Ranges of size 0 are allowed.
472 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
473 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
474 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
475 (testaddr) + (testsz) >= (testaddr))
478 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
479 * alloc_sz on the righthand side of the comparison in order to avoid overflow
480 * or underflow in the comparison with it. This is simpler than the INRANGE
481 * check above, because we know that the dtms_scratch_ptr is valid in the
482 * range. Allocations of size zero are allowed.
484 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
485 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
486 (mstate)->dtms_scratch_ptr >= (alloc_sz))
488 #define DTRACE_LOADFUNC(bits) \
491 dtrace_load##bits(uintptr_t addr) \
493 size_t size = bits / NBBY; \
495 uint##bits##_t rval; \
497 volatile uint16_t *flags = (volatile uint16_t *) \
498 &cpu_core[curcpu].cpuc_dtrace_flags; \
500 DTRACE_ALIGNCHECK(addr, size, flags); \
502 for (i = 0; i < dtrace_toxranges; i++) { \
503 if (addr >= dtrace_toxrange[i].dtt_limit) \
506 if (addr + size <= dtrace_toxrange[i].dtt_base) \
510 * This address falls within a toxic region; return 0. \
512 *flags |= CPU_DTRACE_BADADDR; \
513 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
517 *flags |= CPU_DTRACE_NOFAULT; \
519 rval = *((volatile uint##bits##_t *)addr); \
520 *flags &= ~CPU_DTRACE_NOFAULT; \
522 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
526 #define dtrace_loadptr dtrace_load64
528 #define dtrace_loadptr dtrace_load32
531 #define DTRACE_DYNHASH_FREE 0
532 #define DTRACE_DYNHASH_SINK 1
533 #define DTRACE_DYNHASH_VALID 2
535 #define DTRACE_MATCH_NEXT 0
536 #define DTRACE_MATCH_DONE 1
537 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
538 #define DTRACE_STATE_ALIGN 64
540 #define DTRACE_FLAGS2FLT(flags) \
541 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
542 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
543 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
544 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
545 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
546 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
547 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
548 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
549 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
552 #define DTRACEACT_ISSTRING(act) \
553 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
554 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
556 /* Function prototype definitions: */
557 static size_t dtrace_strlen(const char *, size_t);
558 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
559 static void dtrace_enabling_provide(dtrace_provider_t *);
560 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
561 static void dtrace_enabling_matchall(void);
562 static void dtrace_enabling_reap(void);
563 static dtrace_state_t *dtrace_anon_grab(void);
564 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
565 dtrace_state_t *, uint64_t, uint64_t);
566 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
567 static void dtrace_buffer_drop(dtrace_buffer_t *);
568 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
569 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
570 dtrace_state_t *, dtrace_mstate_t *);
571 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
573 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
574 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
575 uint16_t dtrace_load16(uintptr_t);
576 uint32_t dtrace_load32(uintptr_t);
577 uint64_t dtrace_load64(uintptr_t);
578 uint8_t dtrace_load8(uintptr_t);
579 void dtrace_dynvar_clean(dtrace_dstate_t *);
580 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
581 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
582 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
583 static int dtrace_priv_proc(dtrace_state_t *);
584 static void dtrace_getf_barrier(void);
587 * DTrace Probe Context Functions
589 * These functions are called from probe context. Because probe context is
590 * any context in which C may be called, arbitrarily locks may be held,
591 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
592 * As a result, functions called from probe context may only call other DTrace
593 * support functions -- they may not interact at all with the system at large.
594 * (Note that the ASSERT macro is made probe-context safe by redefining it in
595 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
596 * loads are to be performed from probe context, they _must_ be in terms of
597 * the safe dtrace_load*() variants.
599 * Some functions in this block are not actually called from probe context;
600 * for these functions, there will be a comment above the function reading
601 * "Note: not called from probe context."
604 dtrace_panic(const char *format, ...)
608 va_start(alist, format);
609 dtrace_vpanic(format, alist);
614 dtrace_assfail(const char *a, const char *f, int l)
616 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
619 * We just need something here that even the most clever compiler
620 * cannot optimize away.
622 return (a[(uintptr_t)f]);
626 * Atomically increment a specified error counter from probe context.
629 dtrace_error(uint32_t *counter)
632 * Most counters stored to in probe context are per-CPU counters.
633 * However, there are some error conditions that are sufficiently
634 * arcane that they don't merit per-CPU storage. If these counters
635 * are incremented concurrently on different CPUs, scalability will be
636 * adversely affected -- but we don't expect them to be white-hot in a
637 * correctly constructed enabling...
644 if ((nval = oval + 1) == 0) {
646 * If the counter would wrap, set it to 1 -- assuring
647 * that the counter is never zero when we have seen
648 * errors. (The counter must be 32-bits because we
649 * aren't guaranteed a 64-bit compare&swap operation.)
650 * To save this code both the infamy of being fingered
651 * by a priggish news story and the indignity of being
652 * the target of a neo-puritan witch trial, we're
653 * carefully avoiding any colorful description of the
654 * likelihood of this condition -- but suffice it to
655 * say that it is only slightly more likely than the
656 * overflow of predicate cache IDs, as discussed in
657 * dtrace_predicate_create().
661 } while (dtrace_cas32(counter, oval, nval) != oval);
665 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
666 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
674 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
676 if (dest < mstate->dtms_scratch_base)
679 if (dest + size < dest)
682 if (dest + size > mstate->dtms_scratch_ptr)
689 dtrace_canstore_statvar(uint64_t addr, size_t sz,
690 dtrace_statvar_t **svars, int nsvars)
694 for (i = 0; i < nsvars; i++) {
695 dtrace_statvar_t *svar = svars[i];
697 if (svar == NULL || svar->dtsv_size == 0)
700 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
708 * Check to see if the address is within a memory region to which a store may
709 * be issued. This includes the DTrace scratch areas, and any DTrace variable
710 * region. The caller of dtrace_canstore() is responsible for performing any
711 * alignment checks that are needed before stores are actually executed.
714 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
715 dtrace_vstate_t *vstate)
718 * First, check to see if the address is in scratch space...
720 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
721 mstate->dtms_scratch_size))
725 * Now check to see if it's a dynamic variable. This check will pick
726 * up both thread-local variables and any global dynamically-allocated
729 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
730 vstate->dtvs_dynvars.dtds_size)) {
731 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
732 uintptr_t base = (uintptr_t)dstate->dtds_base +
733 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
737 * Before we assume that we can store here, we need to make
738 * sure that it isn't in our metadata -- storing to our
739 * dynamic variable metadata would corrupt our state. For
740 * the range to not include any dynamic variable metadata,
743 * (1) Start above the hash table that is at the base of
744 * the dynamic variable space
746 * (2) Have a starting chunk offset that is beyond the
747 * dtrace_dynvar_t that is at the base of every chunk
749 * (3) Not span a chunk boundary
755 chunkoffs = (addr - base) % dstate->dtds_chunksize;
757 if (chunkoffs < sizeof (dtrace_dynvar_t))
760 if (chunkoffs + sz > dstate->dtds_chunksize)
767 * Finally, check the static local and global variables. These checks
768 * take the longest, so we perform them last.
770 if (dtrace_canstore_statvar(addr, sz,
771 vstate->dtvs_locals, vstate->dtvs_nlocals))
774 if (dtrace_canstore_statvar(addr, sz,
775 vstate->dtvs_globals, vstate->dtvs_nglobals))
783 * Convenience routine to check to see if the address is within a memory
784 * region in which a load may be issued given the user's privilege level;
785 * if not, it sets the appropriate error flags and loads 'addr' into the
786 * illegal value slot.
788 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
789 * appropriate memory access protection.
792 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
793 dtrace_vstate_t *vstate)
795 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
799 * If we hold the privilege to read from kernel memory, then
800 * everything is readable.
802 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
806 * You can obviously read that which you can store.
808 if (dtrace_canstore(addr, sz, mstate, vstate))
812 * We're allowed to read from our own string table.
814 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
815 mstate->dtms_difo->dtdo_strlen))
818 if (vstate->dtvs_state != NULL &&
819 dtrace_priv_proc(vstate->dtvs_state)) {
823 * When we have privileges to the current process, there are
824 * several context-related kernel structures that are safe to
825 * read, even absent the privilege to read from kernel memory.
826 * These reads are safe because these structures contain only
827 * state that (1) we're permitted to read, (2) is harmless or
828 * (3) contains pointers to additional kernel state that we're
829 * not permitted to read (and as such, do not present an
830 * opportunity for privilege escalation). Finally (and
831 * critically), because of the nature of their relation with
832 * the current thread context, the memory associated with these
833 * structures cannot change over the duration of probe context,
834 * and it is therefore impossible for this memory to be
835 * deallocated and reallocated as something else while it's
836 * being operated upon.
838 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
841 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
842 sz, curthread->t_procp, sizeof (proc_t))) {
846 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
847 curthread->t_cred, sizeof (cred_t))) {
852 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
853 &(p->p_pidp->pid_id), sizeof (pid_t))) {
857 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
858 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
864 if ((fp = mstate->dtms_getf) != NULL) {
865 uintptr_t psz = sizeof (void *);
870 * When getf() returns a file_t, the enabling is implicitly
871 * granted the (transient) right to read the returned file_t
872 * as well as the v_path and v_op->vnop_name of the underlying
873 * vnode. These accesses are allowed after a successful
874 * getf() because the members that they refer to cannot change
875 * once set -- and the barrier logic in the kernel's closef()
876 * path assures that the file_t and its referenced vode_t
877 * cannot themselves be stale (that is, it impossible for
878 * either dtms_getf itself or its f_vnode member to reference
881 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
884 if ((vp = fp->f_vnode) != NULL) {
886 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
888 if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
889 vp->v_path, strlen(vp->v_path) + 1)) {
894 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
898 if ((op = vp->v_op) != NULL &&
899 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
903 if (op != NULL && op->vnop_name != NULL &&
904 DTRACE_INRANGE(addr, sz, op->vnop_name,
905 strlen(op->vnop_name) + 1)) {
912 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
918 * Convenience routine to check to see if a given string is within a memory
919 * region in which a load may be issued given the user's privilege level;
920 * this exists so that we don't need to issue unnecessary dtrace_strlen()
921 * calls in the event that the user has all privileges.
924 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
925 dtrace_vstate_t *vstate)
930 * If we hold the privilege to read from kernel memory, then
931 * everything is readable.
933 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
936 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
937 if (dtrace_canload(addr, strsz, mstate, vstate))
944 * Convenience routine to check to see if a given variable is within a memory
945 * region in which a load may be issued given the user's privilege level.
948 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
949 dtrace_vstate_t *vstate)
952 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
955 * If we hold the privilege to read from kernel memory, then
956 * everything is readable.
958 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
961 if (type->dtdt_kind == DIF_TYPE_STRING)
962 sz = dtrace_strlen(src,
963 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
965 sz = type->dtdt_size;
967 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
971 * Convert a string to a signed integer using safe loads.
973 * NOTE: This function uses various macros from strtolctype.h to manipulate
974 * digit values, etc -- these have all been checked to ensure they make
975 * no additional function calls.
978 dtrace_strtoll(char *input, int base, size_t limit)
980 uintptr_t pos = (uintptr_t)input;
983 boolean_t neg = B_FALSE;
985 uintptr_t end = pos + limit;
988 * Consume any whitespace preceding digits.
990 while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
994 * Handle an explicit sign if one is present.
996 if (c == '-' || c == '+') {
999 c = dtrace_load8(++pos);
1003 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1006 if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1007 cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1013 * Read in contiguous digits until the first non-digit character.
1015 for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1016 c = dtrace_load8(++pos))
1017 val = val * base + x;
1019 return (neg ? -val : val);
1023 * Compare two strings using safe loads.
1026 dtrace_strncmp(char *s1, char *s2, size_t limit)
1029 volatile uint16_t *flags;
1031 if (s1 == s2 || limit == 0)
1034 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1040 c1 = dtrace_load8((uintptr_t)s1++);
1046 c2 = dtrace_load8((uintptr_t)s2++);
1051 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1057 * Compute strlen(s) for a string using safe memory accesses. The additional
1058 * len parameter is used to specify a maximum length to ensure completion.
1061 dtrace_strlen(const char *s, size_t lim)
1065 for (len = 0; len != lim; len++) {
1066 if (dtrace_load8((uintptr_t)s++) == '\0')
1074 * Check if an address falls within a toxic region.
1077 dtrace_istoxic(uintptr_t kaddr, size_t size)
1079 uintptr_t taddr, tsize;
1082 for (i = 0; i < dtrace_toxranges; i++) {
1083 taddr = dtrace_toxrange[i].dtt_base;
1084 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1086 if (kaddr - taddr < tsize) {
1087 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1088 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1092 if (taddr - kaddr < size) {
1093 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1094 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1103 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1104 * memory specified by the DIF program. The dst is assumed to be safe memory
1105 * that we can store to directly because it is managed by DTrace. As with
1106 * standard bcopy, overlapping copies are handled properly.
1109 dtrace_bcopy(const void *src, void *dst, size_t len)
1113 const uint8_t *s2 = src;
1117 *s1++ = dtrace_load8((uintptr_t)s2++);
1118 } while (--len != 0);
1124 *--s1 = dtrace_load8((uintptr_t)--s2);
1125 } while (--len != 0);
1131 * Copy src to dst using safe memory accesses, up to either the specified
1132 * length, or the point that a nul byte is encountered. The src is assumed to
1133 * be unsafe memory specified by the DIF program. The dst is assumed to be
1134 * safe memory that we can store to directly because it is managed by DTrace.
1135 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1138 dtrace_strcpy(const void *src, void *dst, size_t len)
1141 uint8_t *s1 = dst, c;
1142 const uint8_t *s2 = src;
1145 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1146 } while (--len != 0 && c != '\0');
1151 * Copy src to dst, deriving the size and type from the specified (BYREF)
1152 * variable type. The src is assumed to be unsafe memory specified by the DIF
1153 * program. The dst is assumed to be DTrace variable memory that is of the
1154 * specified type; we assume that we can store to directly.
1157 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1159 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1161 if (type->dtdt_kind == DIF_TYPE_STRING) {
1162 dtrace_strcpy(src, dst, type->dtdt_size);
1164 dtrace_bcopy(src, dst, type->dtdt_size);
1169 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1170 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1171 * safe memory that we can access directly because it is managed by DTrace.
1174 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1176 volatile uint16_t *flags;
1178 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1183 if (s1 == NULL || s2 == NULL)
1186 if (s1 != s2 && len != 0) {
1187 const uint8_t *ps1 = s1;
1188 const uint8_t *ps2 = s2;
1191 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1193 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1199 * Zero the specified region using a simple byte-by-byte loop. Note that this
1200 * is for safe DTrace-managed memory only.
1203 dtrace_bzero(void *dst, size_t len)
1207 for (cp = dst; len != 0; len--)
1212 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1216 result[0] = addend1[0] + addend2[0];
1217 result[1] = addend1[1] + addend2[1] +
1218 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1225 * Shift the 128-bit value in a by b. If b is positive, shift left.
1226 * If b is negative, shift right.
1229 dtrace_shift_128(uint64_t *a, int b)
1239 a[0] = a[1] >> (b - 64);
1243 mask = 1LL << (64 - b);
1245 a[0] |= ((a[1] & mask) << (64 - b));
1250 a[1] = a[0] << (b - 64);
1254 mask = a[0] >> (64 - b);
1262 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1263 * use native multiplication on those, and then re-combine into the
1264 * resulting 128-bit value.
1266 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1273 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1275 uint64_t hi1, hi2, lo1, lo2;
1278 hi1 = factor1 >> 32;
1279 hi2 = factor2 >> 32;
1281 lo1 = factor1 & DT_MASK_LO;
1282 lo2 = factor2 & DT_MASK_LO;
1284 product[0] = lo1 * lo2;
1285 product[1] = hi1 * hi2;
1289 dtrace_shift_128(tmp, 32);
1290 dtrace_add_128(product, tmp, product);
1294 dtrace_shift_128(tmp, 32);
1295 dtrace_add_128(product, tmp, product);
1299 * This privilege check should be used by actions and subroutines to
1300 * verify that the user credentials of the process that enabled the
1301 * invoking ECB match the target credentials
1304 dtrace_priv_proc_common_user(dtrace_state_t *state)
1306 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1309 * We should always have a non-NULL state cred here, since if cred
1310 * is null (anonymous tracing), we fast-path bypass this routine.
1312 ASSERT(s_cr != NULL);
1314 if ((cr = CRED()) != NULL &&
1315 s_cr->cr_uid == cr->cr_uid &&
1316 s_cr->cr_uid == cr->cr_ruid &&
1317 s_cr->cr_uid == cr->cr_suid &&
1318 s_cr->cr_gid == cr->cr_gid &&
1319 s_cr->cr_gid == cr->cr_rgid &&
1320 s_cr->cr_gid == cr->cr_sgid)
1327 * This privilege check should be used by actions and subroutines to
1328 * verify that the zone of the process that enabled the invoking ECB
1329 * matches the target credentials
1332 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1335 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1338 * We should always have a non-NULL state cred here, since if cred
1339 * is null (anonymous tracing), we fast-path bypass this routine.
1341 ASSERT(s_cr != NULL);
1343 if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1353 * This privilege check should be used by actions and subroutines to
1354 * verify that the process has not setuid or changed credentials.
1357 dtrace_priv_proc_common_nocd(void)
1361 if ((proc = ttoproc(curthread)) != NULL &&
1362 !(proc->p_flag & SNOCD))
1369 dtrace_priv_proc_destructive(dtrace_state_t *state)
1371 int action = state->dts_cred.dcr_action;
1373 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1374 dtrace_priv_proc_common_zone(state) == 0)
1377 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1378 dtrace_priv_proc_common_user(state) == 0)
1381 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1382 dtrace_priv_proc_common_nocd() == 0)
1388 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1394 dtrace_priv_proc_control(dtrace_state_t *state)
1396 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1399 if (dtrace_priv_proc_common_zone(state) &&
1400 dtrace_priv_proc_common_user(state) &&
1401 dtrace_priv_proc_common_nocd())
1404 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1410 dtrace_priv_proc(dtrace_state_t *state)
1412 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1415 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1421 dtrace_priv_kernel(dtrace_state_t *state)
1423 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1426 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1432 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1434 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1437 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1443 * Determine if the dte_cond of the specified ECB allows for processing of
1444 * the current probe to continue. Note that this routine may allow continued
1445 * processing, but with access(es) stripped from the mstate's dtms_access
1449 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1452 dtrace_probe_t *probe = ecb->dte_probe;
1453 dtrace_provider_t *prov = probe->dtpr_provider;
1454 dtrace_pops_t *pops = &prov->dtpv_pops;
1455 int mode = DTRACE_MODE_NOPRIV_DROP;
1457 ASSERT(ecb->dte_cond);
1460 if (pops->dtps_mode != NULL) {
1461 mode = pops->dtps_mode(prov->dtpv_arg,
1462 probe->dtpr_id, probe->dtpr_arg);
1464 ASSERT((mode & DTRACE_MODE_USER) ||
1465 (mode & DTRACE_MODE_KERNEL));
1466 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1467 (mode & DTRACE_MODE_NOPRIV_DROP));
1471 * If the dte_cond bits indicate that this consumer is only allowed to
1472 * see user-mode firings of this probe, call the provider's dtps_mode()
1473 * entry point to check that the probe was fired while in a user
1474 * context. If that's not the case, use the policy specified by the
1475 * provider to determine if we drop the probe or merely restrict
1478 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1479 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1481 if (!(mode & DTRACE_MODE_USER)) {
1482 if (mode & DTRACE_MODE_NOPRIV_DROP)
1485 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1491 * This is more subtle than it looks. We have to be absolutely certain
1492 * that CRED() isn't going to change out from under us so it's only
1493 * legit to examine that structure if we're in constrained situations.
1494 * Currently, the only times we'll this check is if a non-super-user
1495 * has enabled the profile or syscall providers -- providers that
1496 * allow visibility of all processes. For the profile case, the check
1497 * above will ensure that we're examining a user context.
1499 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1501 cred_t *s_cr = state->dts_cred.dcr_cred;
1504 ASSERT(s_cr != NULL);
1506 if ((cr = CRED()) == NULL ||
1507 s_cr->cr_uid != cr->cr_uid ||
1508 s_cr->cr_uid != cr->cr_ruid ||
1509 s_cr->cr_uid != cr->cr_suid ||
1510 s_cr->cr_gid != cr->cr_gid ||
1511 s_cr->cr_gid != cr->cr_rgid ||
1512 s_cr->cr_gid != cr->cr_sgid ||
1513 (proc = ttoproc(curthread)) == NULL ||
1514 (proc->p_flag & SNOCD)) {
1515 if (mode & DTRACE_MODE_NOPRIV_DROP)
1519 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1526 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1527 * in our zone, check to see if our mode policy is to restrict rather
1528 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1529 * and DTRACE_ACCESS_ARGS
1531 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1533 cred_t *s_cr = state->dts_cred.dcr_cred;
1535 ASSERT(s_cr != NULL);
1537 if ((cr = CRED()) == NULL ||
1538 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1539 if (mode & DTRACE_MODE_NOPRIV_DROP)
1542 mstate->dtms_access &=
1543 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1552 * Note: not called from probe context. This function is called
1553 * asynchronously (and at a regular interval) from outside of probe context to
1554 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1555 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1558 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1560 dtrace_dynvar_t *dirty;
1561 dtrace_dstate_percpu_t *dcpu;
1562 dtrace_dynvar_t **rinsep;
1565 for (i = 0; i < NCPU; i++) {
1566 dcpu = &dstate->dtds_percpu[i];
1567 rinsep = &dcpu->dtdsc_rinsing;
1570 * If the dirty list is NULL, there is no dirty work to do.
1572 if (dcpu->dtdsc_dirty == NULL)
1575 if (dcpu->dtdsc_rinsing != NULL) {
1577 * If the rinsing list is non-NULL, then it is because
1578 * this CPU was selected to accept another CPU's
1579 * dirty list -- and since that time, dirty buffers
1580 * have accumulated. This is a highly unlikely
1581 * condition, but we choose to ignore the dirty
1582 * buffers -- they'll be picked up a future cleanse.
1587 if (dcpu->dtdsc_clean != NULL) {
1589 * If the clean list is non-NULL, then we're in a
1590 * situation where a CPU has done deallocations (we
1591 * have a non-NULL dirty list) but no allocations (we
1592 * also have a non-NULL clean list). We can't simply
1593 * move the dirty list into the clean list on this
1594 * CPU, yet we also don't want to allow this condition
1595 * to persist, lest a short clean list prevent a
1596 * massive dirty list from being cleaned (which in
1597 * turn could lead to otherwise avoidable dynamic
1598 * drops). To deal with this, we look for some CPU
1599 * with a NULL clean list, NULL dirty list, and NULL
1600 * rinsing list -- and then we borrow this CPU to
1601 * rinse our dirty list.
1603 for (j = 0; j < NCPU; j++) {
1604 dtrace_dstate_percpu_t *rinser;
1606 rinser = &dstate->dtds_percpu[j];
1608 if (rinser->dtdsc_rinsing != NULL)
1611 if (rinser->dtdsc_dirty != NULL)
1614 if (rinser->dtdsc_clean != NULL)
1617 rinsep = &rinser->dtdsc_rinsing;
1623 * We were unable to find another CPU that
1624 * could accept this dirty list -- we are
1625 * therefore unable to clean it now.
1627 dtrace_dynvar_failclean++;
1635 * Atomically move the dirty list aside.
1638 dirty = dcpu->dtdsc_dirty;
1641 * Before we zap the dirty list, set the rinsing list.
1642 * (This allows for a potential assertion in
1643 * dtrace_dynvar(): if a free dynamic variable appears
1644 * on a hash chain, either the dirty list or the
1645 * rinsing list for some CPU must be non-NULL.)
1648 dtrace_membar_producer();
1649 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1650 dirty, NULL) != dirty);
1655 * We have no work to do; we can simply return.
1662 for (i = 0; i < NCPU; i++) {
1663 dcpu = &dstate->dtds_percpu[i];
1665 if (dcpu->dtdsc_rinsing == NULL)
1669 * We are now guaranteed that no hash chain contains a pointer
1670 * into this dirty list; we can make it clean.
1672 ASSERT(dcpu->dtdsc_clean == NULL);
1673 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1674 dcpu->dtdsc_rinsing = NULL;
1678 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1679 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1680 * This prevents a race whereby a CPU incorrectly decides that
1681 * the state should be something other than DTRACE_DSTATE_CLEAN
1682 * after dtrace_dynvar_clean() has completed.
1686 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1690 * Depending on the value of the op parameter, this function looks-up,
1691 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1692 * allocation is requested, this function will return a pointer to a
1693 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1694 * variable can be allocated. If NULL is returned, the appropriate counter
1695 * will be incremented.
1698 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1699 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1700 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1702 uint64_t hashval = DTRACE_DYNHASH_VALID;
1703 dtrace_dynhash_t *hash = dstate->dtds_hash;
1704 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1705 processorid_t me = curcpu, cpu = me;
1706 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1707 size_t bucket, ksize;
1708 size_t chunksize = dstate->dtds_chunksize;
1709 uintptr_t kdata, lock, nstate;
1715 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1716 * algorithm. For the by-value portions, we perform the algorithm in
1717 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1718 * bit, and seems to have only a minute effect on distribution. For
1719 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1720 * over each referenced byte. It's painful to do this, but it's much
1721 * better than pathological hash distribution. The efficacy of the
1722 * hashing algorithm (and a comparison with other algorithms) may be
1723 * found by running the ::dtrace_dynstat MDB dcmd.
1725 for (i = 0; i < nkeys; i++) {
1726 if (key[i].dttk_size == 0) {
1727 uint64_t val = key[i].dttk_value;
1729 hashval += (val >> 48) & 0xffff;
1730 hashval += (hashval << 10);
1731 hashval ^= (hashval >> 6);
1733 hashval += (val >> 32) & 0xffff;
1734 hashval += (hashval << 10);
1735 hashval ^= (hashval >> 6);
1737 hashval += (val >> 16) & 0xffff;
1738 hashval += (hashval << 10);
1739 hashval ^= (hashval >> 6);
1741 hashval += val & 0xffff;
1742 hashval += (hashval << 10);
1743 hashval ^= (hashval >> 6);
1746 * This is incredibly painful, but it beats the hell
1747 * out of the alternative.
1749 uint64_t j, size = key[i].dttk_size;
1750 uintptr_t base = (uintptr_t)key[i].dttk_value;
1752 if (!dtrace_canload(base, size, mstate, vstate))
1755 for (j = 0; j < size; j++) {
1756 hashval += dtrace_load8(base + j);
1757 hashval += (hashval << 10);
1758 hashval ^= (hashval >> 6);
1763 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1766 hashval += (hashval << 3);
1767 hashval ^= (hashval >> 11);
1768 hashval += (hashval << 15);
1771 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1772 * comes out to be one of our two sentinel hash values. If this
1773 * actually happens, we set the hashval to be a value known to be a
1774 * non-sentinel value.
1776 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1777 hashval = DTRACE_DYNHASH_VALID;
1780 * Yes, it's painful to do a divide here. If the cycle count becomes
1781 * important here, tricks can be pulled to reduce it. (However, it's
1782 * critical that hash collisions be kept to an absolute minimum;
1783 * they're much more painful than a divide.) It's better to have a
1784 * solution that generates few collisions and still keeps things
1785 * relatively simple.
1787 bucket = hashval % dstate->dtds_hashsize;
1789 if (op == DTRACE_DYNVAR_DEALLOC) {
1790 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1793 while ((lock = *lockp) & 1)
1796 if (dtrace_casptr((volatile void *)lockp,
1797 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1801 dtrace_membar_producer();
1806 lock = hash[bucket].dtdh_lock;
1808 dtrace_membar_consumer();
1810 start = hash[bucket].dtdh_chain;
1811 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1812 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1813 op != DTRACE_DYNVAR_DEALLOC));
1815 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1816 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1817 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1819 if (dvar->dtdv_hashval != hashval) {
1820 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1822 * We've reached the sink, and therefore the
1823 * end of the hash chain; we can kick out of
1824 * the loop knowing that we have seen a valid
1825 * snapshot of state.
1827 ASSERT(dvar->dtdv_next == NULL);
1828 ASSERT(dvar == &dtrace_dynhash_sink);
1832 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1834 * We've gone off the rails: somewhere along
1835 * the line, one of the members of this hash
1836 * chain was deleted. Note that we could also
1837 * detect this by simply letting this loop run
1838 * to completion, as we would eventually hit
1839 * the end of the dirty list. However, we
1840 * want to avoid running the length of the
1841 * dirty list unnecessarily (it might be quite
1842 * long), so we catch this as early as
1843 * possible by detecting the hash marker. In
1844 * this case, we simply set dvar to NULL and
1845 * break; the conditional after the loop will
1846 * send us back to top.
1855 if (dtuple->dtt_nkeys != nkeys)
1858 for (i = 0; i < nkeys; i++, dkey++) {
1859 if (dkey->dttk_size != key[i].dttk_size)
1860 goto next; /* size or type mismatch */
1862 if (dkey->dttk_size != 0) {
1864 (void *)(uintptr_t)key[i].dttk_value,
1865 (void *)(uintptr_t)dkey->dttk_value,
1869 if (dkey->dttk_value != key[i].dttk_value)
1874 if (op != DTRACE_DYNVAR_DEALLOC)
1877 ASSERT(dvar->dtdv_next == NULL ||
1878 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1881 ASSERT(hash[bucket].dtdh_chain != dvar);
1882 ASSERT(start != dvar);
1883 ASSERT(prev->dtdv_next == dvar);
1884 prev->dtdv_next = dvar->dtdv_next;
1886 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1887 start, dvar->dtdv_next) != start) {
1889 * We have failed to atomically swing the
1890 * hash table head pointer, presumably because
1891 * of a conflicting allocation on another CPU.
1892 * We need to reread the hash chain and try
1899 dtrace_membar_producer();
1902 * Now set the hash value to indicate that it's free.
1904 ASSERT(hash[bucket].dtdh_chain != dvar);
1905 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1907 dtrace_membar_producer();
1910 * Set the next pointer to point at the dirty list, and
1911 * atomically swing the dirty pointer to the newly freed dvar.
1914 next = dcpu->dtdsc_dirty;
1915 dvar->dtdv_next = next;
1916 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1919 * Finally, unlock this hash bucket.
1921 ASSERT(hash[bucket].dtdh_lock == lock);
1923 hash[bucket].dtdh_lock++;
1933 * If dvar is NULL, it is because we went off the rails:
1934 * one of the elements that we traversed in the hash chain
1935 * was deleted while we were traversing it. In this case,
1936 * we assert that we aren't doing a dealloc (deallocs lock
1937 * the hash bucket to prevent themselves from racing with
1938 * one another), and retry the hash chain traversal.
1940 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1944 if (op != DTRACE_DYNVAR_ALLOC) {
1946 * If we are not to allocate a new variable, we want to
1947 * return NULL now. Before we return, check that the value
1948 * of the lock word hasn't changed. If it has, we may have
1949 * seen an inconsistent snapshot.
1951 if (op == DTRACE_DYNVAR_NOALLOC) {
1952 if (hash[bucket].dtdh_lock != lock)
1955 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1956 ASSERT(hash[bucket].dtdh_lock == lock);
1958 hash[bucket].dtdh_lock++;
1965 * We need to allocate a new dynamic variable. The size we need is the
1966 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1967 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1968 * the size of any referred-to data (dsize). We then round the final
1969 * size up to the chunksize for allocation.
1971 for (ksize = 0, i = 0; i < nkeys; i++)
1972 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1975 * This should be pretty much impossible, but could happen if, say,
1976 * strange DIF specified the tuple. Ideally, this should be an
1977 * assertion and not an error condition -- but that requires that the
1978 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1979 * bullet-proof. (That is, it must not be able to be fooled by
1980 * malicious DIF.) Given the lack of backwards branches in DIF,
1981 * solving this would presumably not amount to solving the Halting
1982 * Problem -- but it still seems awfully hard.
1984 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1985 ksize + dsize > chunksize) {
1986 dcpu->dtdsc_drops++;
1990 nstate = DTRACE_DSTATE_EMPTY;
1994 free = dcpu->dtdsc_free;
1997 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2000 if (clean == NULL) {
2002 * We're out of dynamic variable space on
2003 * this CPU. Unless we have tried all CPUs,
2004 * we'll try to allocate from a different
2007 switch (dstate->dtds_state) {
2008 case DTRACE_DSTATE_CLEAN: {
2009 void *sp = &dstate->dtds_state;
2014 if (dcpu->dtdsc_dirty != NULL &&
2015 nstate == DTRACE_DSTATE_EMPTY)
2016 nstate = DTRACE_DSTATE_DIRTY;
2018 if (dcpu->dtdsc_rinsing != NULL)
2019 nstate = DTRACE_DSTATE_RINSING;
2021 dcpu = &dstate->dtds_percpu[cpu];
2026 (void) dtrace_cas32(sp,
2027 DTRACE_DSTATE_CLEAN, nstate);
2030 * To increment the correct bean
2031 * counter, take another lap.
2036 case DTRACE_DSTATE_DIRTY:
2037 dcpu->dtdsc_dirty_drops++;
2040 case DTRACE_DSTATE_RINSING:
2041 dcpu->dtdsc_rinsing_drops++;
2044 case DTRACE_DSTATE_EMPTY:
2045 dcpu->dtdsc_drops++;
2049 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2054 * The clean list appears to be non-empty. We want to
2055 * move the clean list to the free list; we start by
2056 * moving the clean pointer aside.
2058 if (dtrace_casptr(&dcpu->dtdsc_clean,
2059 clean, NULL) != clean) {
2061 * We are in one of two situations:
2063 * (a) The clean list was switched to the
2064 * free list by another CPU.
2066 * (b) The clean list was added to by the
2069 * In either of these situations, we can
2070 * just reattempt the free list allocation.
2075 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2078 * Now we'll move the clean list to our free list.
2079 * It's impossible for this to fail: the only way
2080 * the free list can be updated is through this
2081 * code path, and only one CPU can own the clean list.
2082 * Thus, it would only be possible for this to fail if
2083 * this code were racing with dtrace_dynvar_clean().
2084 * (That is, if dtrace_dynvar_clean() updated the clean
2085 * list, and we ended up racing to update the free
2086 * list.) This race is prevented by the dtrace_sync()
2087 * in dtrace_dynvar_clean() -- which flushes the
2088 * owners of the clean lists out before resetting
2091 dcpu = &dstate->dtds_percpu[me];
2092 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2093 ASSERT(rval == NULL);
2098 new_free = dvar->dtdv_next;
2099 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2102 * We have now allocated a new chunk. We copy the tuple keys into the
2103 * tuple array and copy any referenced key data into the data space
2104 * following the tuple array. As we do this, we relocate dttk_value
2105 * in the final tuple to point to the key data address in the chunk.
2107 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2108 dvar->dtdv_data = (void *)(kdata + ksize);
2109 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2111 for (i = 0; i < nkeys; i++) {
2112 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2113 size_t kesize = key[i].dttk_size;
2117 (const void *)(uintptr_t)key[i].dttk_value,
2118 (void *)kdata, kesize);
2119 dkey->dttk_value = kdata;
2120 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2122 dkey->dttk_value = key[i].dttk_value;
2125 dkey->dttk_size = kesize;
2128 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2129 dvar->dtdv_hashval = hashval;
2130 dvar->dtdv_next = start;
2132 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2136 * The cas has failed. Either another CPU is adding an element to
2137 * this hash chain, or another CPU is deleting an element from this
2138 * hash chain. The simplest way to deal with both of these cases
2139 * (though not necessarily the most efficient) is to free our
2140 * allocated block and tail-call ourselves. Note that the free is
2141 * to the dirty list and _not_ to the free list. This is to prevent
2142 * races with allocators, above.
2144 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2146 dtrace_membar_producer();
2149 free = dcpu->dtdsc_dirty;
2150 dvar->dtdv_next = free;
2151 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2153 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2158 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2160 if ((int64_t)nval < (int64_t)*oval)
2166 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2168 if ((int64_t)nval > (int64_t)*oval)
2173 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2175 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2176 int64_t val = (int64_t)nval;
2179 for (i = 0; i < zero; i++) {
2180 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2186 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2187 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2188 quanta[i - 1] += incr;
2193 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2201 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2203 uint64_t arg = *lquanta++;
2204 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2205 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2206 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2207 int32_t val = (int32_t)nval, level;
2210 ASSERT(levels != 0);
2214 * This is an underflow.
2220 level = (val - base) / step;
2222 if (level < levels) {
2223 lquanta[level + 1] += incr;
2228 * This is an overflow.
2230 lquanta[levels + 1] += incr;
2234 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2235 uint16_t high, uint16_t nsteps, int64_t value)
2237 int64_t this = 1, last, next;
2238 int base = 1, order;
2240 ASSERT(factor <= nsteps);
2241 ASSERT(nsteps % factor == 0);
2243 for (order = 0; order < low; order++)
2247 * If our value is less than our factor taken to the power of the
2248 * low order of magnitude, it goes into the zeroth bucket.
2250 if (value < (last = this))
2253 for (this *= factor; order <= high; order++) {
2254 int nbuckets = this > nsteps ? nsteps : this;
2256 if ((next = this * factor) < this) {
2258 * We should not generally get log/linear quantizations
2259 * with a high magnitude that allows 64-bits to
2260 * overflow, but we nonetheless protect against this
2261 * by explicitly checking for overflow, and clamping
2262 * our value accordingly.
2269 * If our value lies within this order of magnitude,
2270 * determine its position by taking the offset within
2271 * the order of magnitude, dividing by the bucket
2272 * width, and adding to our (accumulated) base.
2274 return (base + (value - last) / (this / nbuckets));
2277 base += nbuckets - (nbuckets / factor);
2283 * Our value is greater than or equal to our factor taken to the
2284 * power of one plus the high magnitude -- return the top bucket.
2290 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2292 uint64_t arg = *llquanta++;
2293 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2294 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2295 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2296 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2298 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2299 low, high, nsteps, nval)] += incr;
2304 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2312 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2314 int64_t snval = (int64_t)nval;
2321 * What we want to say here is:
2323 * data[2] += nval * nval;
2325 * But given that nval is 64-bit, we could easily overflow, so
2326 * we do this as 128-bit arithmetic.
2331 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2332 dtrace_add_128(data + 2, tmp, data + 2);
2337 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2344 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2350 * Aggregate given the tuple in the principal data buffer, and the aggregating
2351 * action denoted by the specified dtrace_aggregation_t. The aggregation
2352 * buffer is specified as the buf parameter. This routine does not return
2353 * failure; if there is no space in the aggregation buffer, the data will be
2354 * dropped, and a corresponding counter incremented.
2357 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2358 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2360 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2361 uint32_t i, ndx, size, fsize;
2362 uint32_t align = sizeof (uint64_t) - 1;
2363 dtrace_aggbuffer_t *agb;
2364 dtrace_aggkey_t *key;
2365 uint32_t hashval = 0, limit, isstr;
2366 caddr_t tomax, data, kdata;
2367 dtrace_actkind_t action;
2368 dtrace_action_t *act;
2374 if (!agg->dtag_hasarg) {
2376 * Currently, only quantize() and lquantize() take additional
2377 * arguments, and they have the same semantics: an increment
2378 * value that defaults to 1 when not present. If additional
2379 * aggregating actions take arguments, the setting of the
2380 * default argument value will presumably have to become more
2386 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2387 size = rec->dtrd_offset - agg->dtag_base;
2388 fsize = size + rec->dtrd_size;
2390 ASSERT(dbuf->dtb_tomax != NULL);
2391 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2393 if ((tomax = buf->dtb_tomax) == NULL) {
2394 dtrace_buffer_drop(buf);
2399 * The metastructure is always at the bottom of the buffer.
2401 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2402 sizeof (dtrace_aggbuffer_t));
2404 if (buf->dtb_offset == 0) {
2406 * We just kludge up approximately 1/8th of the size to be
2407 * buckets. If this guess ends up being routinely
2408 * off-the-mark, we may need to dynamically readjust this
2409 * based on past performance.
2411 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2413 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2414 (uintptr_t)tomax || hashsize == 0) {
2416 * We've been given a ludicrously small buffer;
2417 * increment our drop count and leave.
2419 dtrace_buffer_drop(buf);
2424 * And now, a pathetic attempt to try to get a an odd (or
2425 * perchance, a prime) hash size for better hash distribution.
2427 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2428 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2430 agb->dtagb_hashsize = hashsize;
2431 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2432 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2433 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2435 for (i = 0; i < agb->dtagb_hashsize; i++)
2436 agb->dtagb_hash[i] = NULL;
2439 ASSERT(agg->dtag_first != NULL);
2440 ASSERT(agg->dtag_first->dta_intuple);
2443 * Calculate the hash value based on the key. Note that we _don't_
2444 * include the aggid in the hashing (but we will store it as part of
2445 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2446 * algorithm: a simple, quick algorithm that has no known funnels, and
2447 * gets good distribution in practice. The efficacy of the hashing
2448 * algorithm (and a comparison with other algorithms) may be found by
2449 * running the ::dtrace_aggstat MDB dcmd.
2451 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2452 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2453 limit = i + act->dta_rec.dtrd_size;
2454 ASSERT(limit <= size);
2455 isstr = DTRACEACT_ISSTRING(act);
2457 for (; i < limit; i++) {
2459 hashval += (hashval << 10);
2460 hashval ^= (hashval >> 6);
2462 if (isstr && data[i] == '\0')
2467 hashval += (hashval << 3);
2468 hashval ^= (hashval >> 11);
2469 hashval += (hashval << 15);
2472 * Yes, the divide here is expensive -- but it's generally the least
2473 * of the performance issues given the amount of data that we iterate
2474 * over to compute hash values, compare data, etc.
2476 ndx = hashval % agb->dtagb_hashsize;
2478 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2479 ASSERT((caddr_t)key >= tomax);
2480 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2482 if (hashval != key->dtak_hashval || key->dtak_size != size)
2485 kdata = key->dtak_data;
2486 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2488 for (act = agg->dtag_first; act->dta_intuple;
2489 act = act->dta_next) {
2490 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2491 limit = i + act->dta_rec.dtrd_size;
2492 ASSERT(limit <= size);
2493 isstr = DTRACEACT_ISSTRING(act);
2495 for (; i < limit; i++) {
2496 if (kdata[i] != data[i])
2499 if (isstr && data[i] == '\0')
2504 if (action != key->dtak_action) {
2506 * We are aggregating on the same value in the same
2507 * aggregation with two different aggregating actions.
2508 * (This should have been picked up in the compiler,
2509 * so we may be dealing with errant or devious DIF.)
2510 * This is an error condition; we indicate as much,
2513 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2518 * This is a hit: we need to apply the aggregator to
2519 * the value at this key.
2521 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2528 * We didn't find it. We need to allocate some zero-filled space,
2529 * link it into the hash table appropriately, and apply the aggregator
2530 * to the (zero-filled) value.
2532 offs = buf->dtb_offset;
2533 while (offs & (align - 1))
2534 offs += sizeof (uint32_t);
2537 * If we don't have enough room to both allocate a new key _and_
2538 * its associated data, increment the drop count and return.
2540 if ((uintptr_t)tomax + offs + fsize >
2541 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2542 dtrace_buffer_drop(buf);
2547 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2548 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2549 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2551 key->dtak_data = kdata = tomax + offs;
2552 buf->dtb_offset = offs + fsize;
2555 * Now copy the data across.
2557 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2559 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2563 * Because strings are not zeroed out by default, we need to iterate
2564 * looking for actions that store strings, and we need to explicitly
2565 * pad these strings out with zeroes.
2567 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2570 if (!DTRACEACT_ISSTRING(act))
2573 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2574 limit = i + act->dta_rec.dtrd_size;
2575 ASSERT(limit <= size);
2577 for (nul = 0; i < limit; i++) {
2583 if (data[i] != '\0')
2590 for (i = size; i < fsize; i++)
2593 key->dtak_hashval = hashval;
2594 key->dtak_size = size;
2595 key->dtak_action = action;
2596 key->dtak_next = agb->dtagb_hash[ndx];
2597 agb->dtagb_hash[ndx] = key;
2600 * Finally, apply the aggregator.
2602 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2603 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2607 * Given consumer state, this routine finds a speculation in the INACTIVE
2608 * state and transitions it into the ACTIVE state. If there is no speculation
2609 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2610 * incremented -- it is up to the caller to take appropriate action.
2613 dtrace_speculation(dtrace_state_t *state)
2616 dtrace_speculation_state_t current;
2617 uint32_t *stat = &state->dts_speculations_unavail, count;
2619 while (i < state->dts_nspeculations) {
2620 dtrace_speculation_t *spec = &state->dts_speculations[i];
2622 current = spec->dtsp_state;
2624 if (current != DTRACESPEC_INACTIVE) {
2625 if (current == DTRACESPEC_COMMITTINGMANY ||
2626 current == DTRACESPEC_COMMITTING ||
2627 current == DTRACESPEC_DISCARDING)
2628 stat = &state->dts_speculations_busy;
2633 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2634 current, DTRACESPEC_ACTIVE) == current)
2639 * We couldn't find a speculation. If we found as much as a single
2640 * busy speculation buffer, we'll attribute this failure as "busy"
2641 * instead of "unavail".
2645 } while (dtrace_cas32(stat, count, count + 1) != count);
2651 * This routine commits an active speculation. If the specified speculation
2652 * is not in a valid state to perform a commit(), this routine will silently do
2653 * nothing. The state of the specified speculation is transitioned according
2654 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2657 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2658 dtrace_specid_t which)
2660 dtrace_speculation_t *spec;
2661 dtrace_buffer_t *src, *dest;
2662 uintptr_t daddr, saddr, dlimit, slimit;
2663 dtrace_speculation_state_t current, new = 0;
2670 if (which > state->dts_nspeculations) {
2671 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2675 spec = &state->dts_speculations[which - 1];
2676 src = &spec->dtsp_buffer[cpu];
2677 dest = &state->dts_buffer[cpu];
2680 current = spec->dtsp_state;
2682 if (current == DTRACESPEC_COMMITTINGMANY)
2686 case DTRACESPEC_INACTIVE:
2687 case DTRACESPEC_DISCARDING:
2690 case DTRACESPEC_COMMITTING:
2692 * This is only possible if we are (a) commit()'ing
2693 * without having done a prior speculate() on this CPU
2694 * and (b) racing with another commit() on a different
2695 * CPU. There's nothing to do -- we just assert that
2698 ASSERT(src->dtb_offset == 0);
2701 case DTRACESPEC_ACTIVE:
2702 new = DTRACESPEC_COMMITTING;
2705 case DTRACESPEC_ACTIVEONE:
2707 * This speculation is active on one CPU. If our
2708 * buffer offset is non-zero, we know that the one CPU
2709 * must be us. Otherwise, we are committing on a
2710 * different CPU from the speculate(), and we must
2711 * rely on being asynchronously cleaned.
2713 if (src->dtb_offset != 0) {
2714 new = DTRACESPEC_COMMITTING;
2719 case DTRACESPEC_ACTIVEMANY:
2720 new = DTRACESPEC_COMMITTINGMANY;
2726 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2727 current, new) != current);
2730 * We have set the state to indicate that we are committing this
2731 * speculation. Now reserve the necessary space in the destination
2734 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2735 sizeof (uint64_t), state, NULL)) < 0) {
2736 dtrace_buffer_drop(dest);
2741 * We have sufficient space to copy the speculative buffer into the
2742 * primary buffer. First, modify the speculative buffer, filling
2743 * in the timestamp of all entries with the current time. The data
2744 * must have the commit() time rather than the time it was traced,
2745 * so that all entries in the primary buffer are in timestamp order.
2747 timestamp = dtrace_gethrtime();
2748 saddr = (uintptr_t)src->dtb_tomax;
2749 slimit = saddr + src->dtb_offset;
2750 while (saddr < slimit) {
2752 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2754 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2755 saddr += sizeof (dtrace_epid_t);
2758 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2759 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2761 ASSERT3U(saddr + size, <=, slimit);
2762 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2763 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2765 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2771 * Copy the buffer across. (Note that this is a
2772 * highly subobtimal bcopy(); in the unlikely event that this becomes
2773 * a serious performance issue, a high-performance DTrace-specific
2774 * bcopy() should obviously be invented.)
2776 daddr = (uintptr_t)dest->dtb_tomax + offs;
2777 dlimit = daddr + src->dtb_offset;
2778 saddr = (uintptr_t)src->dtb_tomax;
2781 * First, the aligned portion.
2783 while (dlimit - daddr >= sizeof (uint64_t)) {
2784 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2786 daddr += sizeof (uint64_t);
2787 saddr += sizeof (uint64_t);
2791 * Now any left-over bit...
2793 while (dlimit - daddr)
2794 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2797 * Finally, commit the reserved space in the destination buffer.
2799 dest->dtb_offset = offs + src->dtb_offset;
2803 * If we're lucky enough to be the only active CPU on this speculation
2804 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2806 if (current == DTRACESPEC_ACTIVE ||
2807 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2808 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2809 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2811 ASSERT(rval == DTRACESPEC_COMMITTING);
2814 src->dtb_offset = 0;
2815 src->dtb_xamot_drops += src->dtb_drops;
2820 * This routine discards an active speculation. If the specified speculation
2821 * is not in a valid state to perform a discard(), this routine will silently
2822 * do nothing. The state of the specified speculation is transitioned
2823 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2826 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2827 dtrace_specid_t which)
2829 dtrace_speculation_t *spec;
2830 dtrace_speculation_state_t current, new = 0;
2831 dtrace_buffer_t *buf;
2836 if (which > state->dts_nspeculations) {
2837 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2841 spec = &state->dts_speculations[which - 1];
2842 buf = &spec->dtsp_buffer[cpu];
2845 current = spec->dtsp_state;
2848 case DTRACESPEC_INACTIVE:
2849 case DTRACESPEC_COMMITTINGMANY:
2850 case DTRACESPEC_COMMITTING:
2851 case DTRACESPEC_DISCARDING:
2854 case DTRACESPEC_ACTIVE:
2855 case DTRACESPEC_ACTIVEMANY:
2856 new = DTRACESPEC_DISCARDING;
2859 case DTRACESPEC_ACTIVEONE:
2860 if (buf->dtb_offset != 0) {
2861 new = DTRACESPEC_INACTIVE;
2863 new = DTRACESPEC_DISCARDING;
2870 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2871 current, new) != current);
2873 buf->dtb_offset = 0;
2878 * Note: not called from probe context. This function is called
2879 * asynchronously from cross call context to clean any speculations that are
2880 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2881 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2885 dtrace_speculation_clean_here(dtrace_state_t *state)
2887 dtrace_icookie_t cookie;
2888 processorid_t cpu = curcpu;
2889 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2892 cookie = dtrace_interrupt_disable();
2894 if (dest->dtb_tomax == NULL) {
2895 dtrace_interrupt_enable(cookie);
2899 for (i = 0; i < state->dts_nspeculations; i++) {
2900 dtrace_speculation_t *spec = &state->dts_speculations[i];
2901 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2903 if (src->dtb_tomax == NULL)
2906 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2907 src->dtb_offset = 0;
2911 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2914 if (src->dtb_offset == 0)
2917 dtrace_speculation_commit(state, cpu, i + 1);
2920 dtrace_interrupt_enable(cookie);
2924 * Note: not called from probe context. This function is called
2925 * asynchronously (and at a regular interval) to clean any speculations that
2926 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2927 * is work to be done, it cross calls all CPUs to perform that work;
2928 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2929 * INACTIVE state until they have been cleaned by all CPUs.
2932 dtrace_speculation_clean(dtrace_state_t *state)
2937 for (i = 0; i < state->dts_nspeculations; i++) {
2938 dtrace_speculation_t *spec = &state->dts_speculations[i];
2940 ASSERT(!spec->dtsp_cleaning);
2942 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2943 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2947 spec->dtsp_cleaning = 1;
2953 dtrace_xcall(DTRACE_CPUALL,
2954 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2957 * We now know that all CPUs have committed or discarded their
2958 * speculation buffers, as appropriate. We can now set the state
2961 for (i = 0; i < state->dts_nspeculations; i++) {
2962 dtrace_speculation_t *spec = &state->dts_speculations[i];
2963 dtrace_speculation_state_t current, new;
2965 if (!spec->dtsp_cleaning)
2968 current = spec->dtsp_state;
2969 ASSERT(current == DTRACESPEC_DISCARDING ||
2970 current == DTRACESPEC_COMMITTINGMANY);
2972 new = DTRACESPEC_INACTIVE;
2974 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2975 ASSERT(rv == current);
2976 spec->dtsp_cleaning = 0;
2981 * Called as part of a speculate() to get the speculative buffer associated
2982 * with a given speculation. Returns NULL if the specified speculation is not
2983 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2984 * the active CPU is not the specified CPU -- the speculation will be
2985 * atomically transitioned into the ACTIVEMANY state.
2987 static dtrace_buffer_t *
2988 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2989 dtrace_specid_t which)
2991 dtrace_speculation_t *spec;
2992 dtrace_speculation_state_t current, new = 0;
2993 dtrace_buffer_t *buf;
2998 if (which > state->dts_nspeculations) {
2999 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3003 spec = &state->dts_speculations[which - 1];
3004 buf = &spec->dtsp_buffer[cpuid];
3007 current = spec->dtsp_state;
3010 case DTRACESPEC_INACTIVE:
3011 case DTRACESPEC_COMMITTINGMANY:
3012 case DTRACESPEC_DISCARDING:
3015 case DTRACESPEC_COMMITTING:
3016 ASSERT(buf->dtb_offset == 0);
3019 case DTRACESPEC_ACTIVEONE:
3021 * This speculation is currently active on one CPU.
3022 * Check the offset in the buffer; if it's non-zero,
3023 * that CPU must be us (and we leave the state alone).
3024 * If it's zero, assume that we're starting on a new
3025 * CPU -- and change the state to indicate that the
3026 * speculation is active on more than one CPU.
3028 if (buf->dtb_offset != 0)
3031 new = DTRACESPEC_ACTIVEMANY;
3034 case DTRACESPEC_ACTIVEMANY:
3037 case DTRACESPEC_ACTIVE:
3038 new = DTRACESPEC_ACTIVEONE;
3044 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3045 current, new) != current);
3047 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3052 * Return a string. In the event that the user lacks the privilege to access
3053 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3054 * don't fail access checking.
3056 * dtrace_dif_variable() uses this routine as a helper for various
3057 * builtin values such as 'execname' and 'probefunc.'
3060 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3061 dtrace_mstate_t *mstate)
3063 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3068 * The easy case: this probe is allowed to read all of memory, so
3069 * we can just return this as a vanilla pointer.
3071 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3075 * This is the tougher case: we copy the string in question from
3076 * kernel memory into scratch memory and return it that way: this
3077 * ensures that we won't trip up when access checking tests the
3078 * BYREF return value.
3080 strsz = dtrace_strlen((char *)addr, size) + 1;
3082 if (mstate->dtms_scratch_ptr + strsz >
3083 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3084 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3088 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3090 ret = mstate->dtms_scratch_ptr;
3091 mstate->dtms_scratch_ptr += strsz;
3096 * Return a string from a memoy address which is known to have one or
3097 * more concatenated, individually zero terminated, sub-strings.
3098 * In the event that the user lacks the privilege to access
3099 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3100 * don't fail access checking.
3102 * dtrace_dif_variable() uses this routine as a helper for various
3103 * builtin values such as 'execargs'.
3106 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3107 dtrace_mstate_t *mstate)
3113 if (mstate->dtms_scratch_ptr + strsz >
3114 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3115 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3119 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3122 /* Replace sub-string termination characters with a space. */
3123 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3128 ret = mstate->dtms_scratch_ptr;
3129 mstate->dtms_scratch_ptr += strsz;
3134 * This function implements the DIF emulator's variable lookups. The emulator
3135 * passes a reserved variable identifier and optional built-in array index.
3138 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3142 * If we're accessing one of the uncached arguments, we'll turn this
3143 * into a reference in the args array.
3145 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3146 ndx = v - DIF_VAR_ARG0;
3152 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3153 if (ndx >= sizeof (mstate->dtms_arg) /
3154 sizeof (mstate->dtms_arg[0])) {
3155 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3156 dtrace_provider_t *pv;
3159 pv = mstate->dtms_probe->dtpr_provider;
3160 if (pv->dtpv_pops.dtps_getargval != NULL)
3161 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3162 mstate->dtms_probe->dtpr_id,
3163 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3165 val = dtrace_getarg(ndx, aframes);
3168 * This is regrettably required to keep the compiler
3169 * from tail-optimizing the call to dtrace_getarg().
3170 * The condition always evaluates to true, but the
3171 * compiler has no way of figuring that out a priori.
3172 * (None of this would be necessary if the compiler
3173 * could be relied upon to _always_ tail-optimize
3174 * the call to dtrace_getarg() -- but it can't.)
3176 if (mstate->dtms_probe != NULL)
3182 return (mstate->dtms_arg[ndx]);
3185 case DIF_VAR_UREGS: {
3188 if (!dtrace_priv_proc(state))
3191 if ((lwp = curthread->t_lwp) == NULL) {
3192 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3193 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3197 return (dtrace_getreg(lwp->lwp_regs, ndx));
3201 case DIF_VAR_UREGS: {
3202 struct trapframe *tframe;
3204 if (!dtrace_priv_proc(state))
3207 if ((tframe = curthread->td_frame) == NULL) {
3208 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3209 cpu_core[curcpu].cpuc_dtrace_illval = 0;
3213 return (dtrace_getreg(tframe, ndx));
3217 case DIF_VAR_CURTHREAD:
3218 if (!dtrace_priv_proc(state))
3220 return ((uint64_t)(uintptr_t)curthread);
3222 case DIF_VAR_TIMESTAMP:
3223 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3224 mstate->dtms_timestamp = dtrace_gethrtime();
3225 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3227 return (mstate->dtms_timestamp);
3229 case DIF_VAR_VTIMESTAMP:
3230 ASSERT(dtrace_vtime_references != 0);
3231 return (curthread->t_dtrace_vtime);
3233 case DIF_VAR_WALLTIMESTAMP:
3234 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3235 mstate->dtms_walltimestamp = dtrace_gethrestime();
3236 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3238 return (mstate->dtms_walltimestamp);
3242 if (!dtrace_priv_kernel(state))
3244 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3245 mstate->dtms_ipl = dtrace_getipl();
3246 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3248 return (mstate->dtms_ipl);
3252 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3253 return (mstate->dtms_epid);
3256 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3257 return (mstate->dtms_probe->dtpr_id);
3259 case DIF_VAR_STACKDEPTH:
3260 if (!dtrace_priv_kernel(state))
3262 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3263 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3265 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3266 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3268 return (mstate->dtms_stackdepth);
3270 case DIF_VAR_USTACKDEPTH:
3271 if (!dtrace_priv_proc(state))
3273 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3275 * See comment in DIF_VAR_PID.
3277 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3279 mstate->dtms_ustackdepth = 0;
3281 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3282 mstate->dtms_ustackdepth =
3283 dtrace_getustackdepth();
3284 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3286 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3288 return (mstate->dtms_ustackdepth);
3290 case DIF_VAR_CALLER:
3291 if (!dtrace_priv_kernel(state))
3293 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3294 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3296 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3298 * If this is an unanchored probe, we are
3299 * required to go through the slow path:
3300 * dtrace_caller() only guarantees correct
3301 * results for anchored probes.
3303 pc_t caller[2] = {0, 0};
3305 dtrace_getpcstack(caller, 2, aframes,
3306 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3307 mstate->dtms_caller = caller[1];
3308 } else if ((mstate->dtms_caller =
3309 dtrace_caller(aframes)) == -1) {
3311 * We have failed to do this the quick way;
3312 * we must resort to the slower approach of
3313 * calling dtrace_getpcstack().
3317 dtrace_getpcstack(&caller, 1, aframes, NULL);
3318 mstate->dtms_caller = caller;
3321 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3323 return (mstate->dtms_caller);
3325 case DIF_VAR_UCALLER:
3326 if (!dtrace_priv_proc(state))
3329 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3333 * dtrace_getupcstack() fills in the first uint64_t
3334 * with the current PID. The second uint64_t will
3335 * be the program counter at user-level. The third
3336 * uint64_t will contain the caller, which is what
3340 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3341 dtrace_getupcstack(ustack, 3);
3342 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3343 mstate->dtms_ucaller = ustack[2];
3344 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3347 return (mstate->dtms_ucaller);
3349 case DIF_VAR_PROBEPROV:
3350 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3351 return (dtrace_dif_varstr(
3352 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3355 case DIF_VAR_PROBEMOD:
3356 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3357 return (dtrace_dif_varstr(
3358 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3361 case DIF_VAR_PROBEFUNC:
3362 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3363 return (dtrace_dif_varstr(
3364 (uintptr_t)mstate->dtms_probe->dtpr_func,
3367 case DIF_VAR_PROBENAME:
3368 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3369 return (dtrace_dif_varstr(
3370 (uintptr_t)mstate->dtms_probe->dtpr_name,
3374 if (!dtrace_priv_proc(state))
3379 * Note that we are assuming that an unanchored probe is
3380 * always due to a high-level interrupt. (And we're assuming
3381 * that there is only a single high level interrupt.)
3383 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3384 return (pid0.pid_id);
3387 * It is always safe to dereference one's own t_procp pointer:
3388 * it always points to a valid, allocated proc structure.
3389 * Further, it is always safe to dereference the p_pidp member
3390 * of one's own proc structure. (These are truisms becuase
3391 * threads and processes don't clean up their own state --
3392 * they leave that task to whomever reaps them.)
3394 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3396 return ((uint64_t)curproc->p_pid);
3400 if (!dtrace_priv_proc(state))
3405 * See comment in DIF_VAR_PID.
3407 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3408 return (pid0.pid_id);
3411 * It is always safe to dereference one's own t_procp pointer:
3412 * it always points to a valid, allocated proc structure.
3413 * (This is true because threads don't clean up their own
3414 * state -- they leave that task to whomever reaps them.)
3416 return ((uint64_t)curthread->t_procp->p_ppid);
3418 if (curproc->p_pid == proc0.p_pid)
3419 return (curproc->p_pid);
3421 return (curproc->p_pptr->p_pid);
3427 * See comment in DIF_VAR_PID.
3429 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3433 return ((uint64_t)curthread->t_tid);
3435 case DIF_VAR_EXECARGS: {
3436 struct pargs *p_args = curthread->td_proc->p_args;
3441 return (dtrace_dif_varstrz(
3442 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3445 case DIF_VAR_EXECNAME:
3447 if (!dtrace_priv_proc(state))
3451 * See comment in DIF_VAR_PID.
3453 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3454 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3457 * It is always safe to dereference one's own t_procp pointer:
3458 * it always points to a valid, allocated proc structure.
3459 * (This is true because threads don't clean up their own
3460 * state -- they leave that task to whomever reaps them.)
3462 return (dtrace_dif_varstr(
3463 (uintptr_t)curthread->t_procp->p_user.u_comm,
3466 return (dtrace_dif_varstr(
3467 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3470 case DIF_VAR_ZONENAME:
3472 if (!dtrace_priv_proc(state))
3476 * See comment in DIF_VAR_PID.
3478 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3479 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3482 * It is always safe to dereference one's own t_procp pointer:
3483 * it always points to a valid, allocated proc structure.
3484 * (This is true because threads don't clean up their own
3485 * state -- they leave that task to whomever reaps them.)
3487 return (dtrace_dif_varstr(
3488 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3495 if (!dtrace_priv_proc(state))
3500 * See comment in DIF_VAR_PID.
3502 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3503 return ((uint64_t)p0.p_cred->cr_uid);
3507 * It is always safe to dereference one's own t_procp pointer:
3508 * it always points to a valid, allocated proc structure.
3509 * (This is true because threads don't clean up their own
3510 * state -- they leave that task to whomever reaps them.)
3512 * Additionally, it is safe to dereference one's own process
3513 * credential, since this is never NULL after process birth.
3515 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3518 if (!dtrace_priv_proc(state))
3523 * See comment in DIF_VAR_PID.
3525 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3526 return ((uint64_t)p0.p_cred->cr_gid);
3530 * It is always safe to dereference one's own t_procp pointer:
3531 * it always points to a valid, allocated proc structure.
3532 * (This is true because threads don't clean up their own
3533 * state -- they leave that task to whomever reaps them.)
3535 * Additionally, it is safe to dereference one's own process
3536 * credential, since this is never NULL after process birth.
3538 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3540 case DIF_VAR_ERRNO: {
3543 if (!dtrace_priv_proc(state))
3547 * See comment in DIF_VAR_PID.
3549 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3553 * It is always safe to dereference one's own t_lwp pointer in
3554 * the event that this pointer is non-NULL. (This is true
3555 * because threads and lwps don't clean up their own state --
3556 * they leave that task to whomever reaps them.)
3558 if ((lwp = curthread->t_lwp) == NULL)
3561 return ((uint64_t)lwp->lwp_errno);
3563 return (curthread->td_errno);
3572 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3578 typedef enum dtrace_json_state {
3579 DTRACE_JSON_REST = 1,
3582 DTRACE_JSON_STRING_ESCAPE,
3583 DTRACE_JSON_STRING_ESCAPE_UNICODE,
3587 DTRACE_JSON_IDENTIFIER,
3589 DTRACE_JSON_NUMBER_FRAC,
3590 DTRACE_JSON_NUMBER_EXP,
3591 DTRACE_JSON_COLLECT_OBJECT
3592 } dtrace_json_state_t;
3595 * This function possesses just enough knowledge about JSON to extract a single
3596 * value from a JSON string and store it in the scratch buffer. It is able
3597 * to extract nested object values, and members of arrays by index.
3599 * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3600 * be looked up as we descend into the object tree. e.g.
3602 * foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3605 * The run time of this function must be bounded above by strsize to limit the
3606 * amount of work done in probe context. As such, it is implemented as a
3607 * simple state machine, reading one character at a time using safe loads
3608 * until we find the requested element, hit a parsing error or run off the
3609 * end of the object or string.
3611 * As there is no way for a subroutine to return an error without interrupting
3612 * clause execution, we simply return NULL in the event of a missing key or any
3613 * other error condition. Each NULL return in this function is commented with
3614 * the error condition it represents -- parsing or otherwise.
3616 * The set of states for the state machine closely matches the JSON
3617 * specification (http://json.org/). Briefly:
3620 * Skip whitespace until we find either a top-level Object, moving
3621 * to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3623 * DTRACE_JSON_OBJECT:
3624 * Locate the next key String in an Object. Sets a flag to denote
3625 * the next String as a key string and moves to DTRACE_JSON_STRING.
3627 * DTRACE_JSON_COLON:
3628 * Skip whitespace until we find the colon that separates key Strings
3629 * from their values. Once found, move to DTRACE_JSON_VALUE.
3631 * DTRACE_JSON_VALUE:
3632 * Detects the type of the next value (String, Number, Identifier, Object
3633 * or Array) and routes to the states that process that type. Here we also
3634 * deal with the element selector list if we are requested to traverse down
3635 * into the object tree.
3637 * DTRACE_JSON_COMMA:
3638 * Skip whitespace until we find the comma that separates key-value pairs
3639 * in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3640 * (similarly DTRACE_JSON_VALUE). All following literal value processing
3641 * states return to this state at the end of their value, unless otherwise
3644 * DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3645 * Processes a Number literal from the JSON, including any exponent
3646 * component that may be present. Numbers are returned as strings, which
3647 * may be passed to strtoll() if an integer is required.
3649 * DTRACE_JSON_IDENTIFIER:
3650 * Processes a "true", "false" or "null" literal in the JSON.
3652 * DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3653 * DTRACE_JSON_STRING_ESCAPE_UNICODE:
3654 * Processes a String literal from the JSON, whether the String denotes
3655 * a key, a value or part of a larger Object. Handles all escape sequences
3656 * present in the specification, including four-digit unicode characters,
3657 * but merely includes the escape sequence without converting it to the
3658 * actual escaped character. If the String is flagged as a key, we
3659 * move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3661 * DTRACE_JSON_COLLECT_OBJECT:
3662 * This state collects an entire Object (or Array), correctly handling
3663 * embedded strings. If the full element selector list matches this nested
3664 * object, we return the Object in full as a string. If not, we use this
3665 * state to skip to the next value at this level and continue processing.
3667 * NOTE: This function uses various macros from strtolctype.h to manipulate
3668 * digit values, etc -- these have all been checked to ensure they make
3669 * no additional function calls.
3672 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3675 dtrace_json_state_t state = DTRACE_JSON_REST;
3676 int64_t array_elem = INT64_MIN;
3677 int64_t array_pos = 0;
3678 uint8_t escape_unicount = 0;
3679 boolean_t string_is_key = B_FALSE;
3680 boolean_t collect_object = B_FALSE;
3681 boolean_t found_key = B_FALSE;
3682 boolean_t in_array = B_FALSE;
3683 uint32_t braces = 0, brackets = 0;
3684 char *elem = elemlist;
3688 for (cur = json; cur < json + size; cur++) {
3689 char cc = dtrace_load8(cur);
3694 case DTRACE_JSON_REST:
3699 state = DTRACE_JSON_OBJECT;
3706 array_elem = dtrace_strtoll(elem, 10, size);
3707 found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3708 state = DTRACE_JSON_VALUE;
3713 * ERROR: expected to find a top-level object or array.
3716 case DTRACE_JSON_OBJECT:
3721 state = DTRACE_JSON_STRING;
3722 string_is_key = B_TRUE;
3727 * ERROR: either the object did not start with a key
3728 * string, or we've run off the end of the object
3729 * without finding the requested key.
3732 case DTRACE_JSON_STRING:
3735 state = DTRACE_JSON_STRING_ESCAPE;
3740 if (collect_object) {
3742 * We don't reset the dest here, as
3743 * the string is part of a larger
3744 * object being collected.
3747 collect_object = B_FALSE;
3748 state = DTRACE_JSON_COLLECT_OBJECT;
3752 dd = dest; /* reset string buffer */
3753 if (string_is_key) {
3754 if (dtrace_strncmp(dest, elem,
3757 } else if (found_key) {
3760 * We expected an object, not
3767 state = string_is_key ? DTRACE_JSON_COLON :
3769 string_is_key = B_FALSE;
3775 case DTRACE_JSON_STRING_ESCAPE:
3778 escape_unicount = 0;
3779 state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3781 state = DTRACE_JSON_STRING;
3784 case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3785 if (!isxdigit(cc)) {
3787 * ERROR: invalid unicode escape, expected
3788 * four valid hexidecimal digits.
3794 if (++escape_unicount == 4)
3795 state = DTRACE_JSON_STRING;
3797 case DTRACE_JSON_COLON:
3802 state = DTRACE_JSON_VALUE;
3807 * ERROR: expected a colon.
3810 case DTRACE_JSON_COMMA:
3816 state = DTRACE_JSON_VALUE;
3817 if (++array_pos == array_elem)
3820 state = DTRACE_JSON_OBJECT;
3826 * ERROR: either we hit an unexpected character, or
3827 * we reached the end of the object or array without
3828 * finding the requested key.
3831 case DTRACE_JSON_IDENTIFIER:
3838 dd = dest; /* reset string buffer */
3840 if (dtrace_strncmp(dest, "true", 5) == 0 ||
3841 dtrace_strncmp(dest, "false", 6) == 0 ||
3842 dtrace_strncmp(dest, "null", 5) == 0) {
3846 * ERROR: We expected an object,
3847 * not this identifier.
3854 state = DTRACE_JSON_COMMA;
3860 * ERROR: we did not recognise the identifier as one
3861 * of those in the JSON specification.
3864 case DTRACE_JSON_NUMBER:
3867 state = DTRACE_JSON_NUMBER_FRAC;
3871 if (cc == 'x' || cc == 'X') {
3873 * ERROR: specification explicitly excludes
3874 * hexidecimal or octal numbers.
3880 case DTRACE_JSON_NUMBER_FRAC:
3881 if (cc == 'e' || cc == 'E') {
3883 state = DTRACE_JSON_NUMBER_EXP;
3887 if (cc == '+' || cc == '-') {
3889 * ERROR: expect sign as part of exponent only.
3894 case DTRACE_JSON_NUMBER_EXP:
3895 if (isdigit(cc) || cc == '+' || cc == '-') {
3901 dd = dest; /* reset string buffer */
3905 * ERROR: We expected an object, not
3914 state = DTRACE_JSON_COMMA;
3916 case DTRACE_JSON_VALUE:
3920 if (cc == '{' || cc == '[') {
3921 if (nelems > 1 && found_key) {
3922 in_array = cc == '[' ? B_TRUE : B_FALSE;
3924 * If our element selector directs us
3925 * to descend into this nested object,
3926 * then move to the next selector
3927 * element in the list and restart the
3930 while (*elem != '\0')
3932 elem++; /* skip the inter-element NUL */
3936 state = DTRACE_JSON_VALUE;
3938 array_elem = dtrace_strtoll(
3940 found_key = array_elem == 0 ?
3943 found_key = B_FALSE;
3944 state = DTRACE_JSON_OBJECT;
3950 * Otherwise, we wish to either skip this
3951 * nested object or return it in full.
3958 state = DTRACE_JSON_COLLECT_OBJECT;
3963 state = DTRACE_JSON_STRING;
3969 * Here we deal with true, false and null.
3972 state = DTRACE_JSON_IDENTIFIER;
3976 if (cc == '-' || isdigit(cc)) {
3978 state = DTRACE_JSON_NUMBER;
3983 * ERROR: unexpected character at start of value.
3986 case DTRACE_JSON_COLLECT_OBJECT:
3989 * ERROR: unexpected end of input.
3995 collect_object = B_TRUE;
3996 state = DTRACE_JSON_STRING;
4001 if (brackets-- == 0) {
4003 * ERROR: unbalanced brackets.
4007 } else if (cc == '}') {
4008 if (braces-- == 0) {
4010 * ERROR: unbalanced braces.
4014 } else if (cc == '{') {
4016 } else if (cc == '[') {
4020 if (brackets == 0 && braces == 0) {
4025 dd = dest; /* reset string buffer */
4026 state = DTRACE_JSON_COMMA;
4035 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4036 * Notice that we don't bother validating the proper number of arguments or
4037 * their types in the tuple stack. This isn't needed because all argument
4038 * interpretation is safe because of our load safety -- the worst that can
4039 * happen is that a bogus program can obtain bogus results.
4042 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4043 dtrace_key_t *tupregs, int nargs,
4044 dtrace_mstate_t *mstate, dtrace_state_t *state)
4046 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4047 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4048 dtrace_vstate_t *vstate = &state->dts_vstate;
4061 struct thread *lowner;
4063 struct lock_object *li;
4070 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4074 case DIF_SUBR_MUTEX_OWNED:
4075 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4081 m.mx = dtrace_load64(tupregs[0].dttk_value);
4082 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4083 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4085 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4088 case DIF_SUBR_MUTEX_OWNER:
4089 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4095 m.mx = dtrace_load64(tupregs[0].dttk_value);
4096 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4097 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4098 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4103 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4104 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4110 m.mx = dtrace_load64(tupregs[0].dttk_value);
4111 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4114 case DIF_SUBR_MUTEX_TYPE_SPIN:
4115 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4121 m.mx = dtrace_load64(tupregs[0].dttk_value);
4122 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4125 case DIF_SUBR_RW_READ_HELD: {
4128 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4134 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4135 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4139 case DIF_SUBR_RW_WRITE_HELD:
4140 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4146 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4147 regs[rd] = _RW_WRITE_HELD(&r.ri);
4150 case DIF_SUBR_RW_ISWRITER:
4151 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4157 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4158 regs[rd] = _RW_ISWRITER(&r.ri);
4162 case DIF_SUBR_MUTEX_OWNED:
4163 if (!dtrace_canload(tupregs[0].dttk_value,
4164 sizeof (struct lock_object), mstate, vstate)) {
4168 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4169 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4172 case DIF_SUBR_MUTEX_OWNER:
4173 if (!dtrace_canload(tupregs[0].dttk_value,
4174 sizeof (struct lock_object), mstate, vstate)) {
4178 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4179 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4180 regs[rd] = (uintptr_t)lowner;
4183 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4184 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4189 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4190 /* XXX - should be only LC_SLEEPABLE? */
4191 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
4192 (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
4195 case DIF_SUBR_MUTEX_TYPE_SPIN:
4196 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4201 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4202 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4205 case DIF_SUBR_RW_READ_HELD:
4206 case DIF_SUBR_SX_SHARED_HELD:
4207 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4212 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4213 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4217 case DIF_SUBR_RW_WRITE_HELD:
4218 case DIF_SUBR_SX_EXCLUSIVE_HELD:
4219 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4224 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4225 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4226 regs[rd] = (lowner == curthread);
4229 case DIF_SUBR_RW_ISWRITER:
4230 case DIF_SUBR_SX_ISEXCLUSIVE:
4231 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4236 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4237 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4240 #endif /* ! defined(sun) */
4242 case DIF_SUBR_BCOPY: {
4244 * We need to be sure that the destination is in the scratch
4245 * region -- no other region is allowed.
4247 uintptr_t src = tupregs[0].dttk_value;
4248 uintptr_t dest = tupregs[1].dttk_value;
4249 size_t size = tupregs[2].dttk_value;
4251 if (!dtrace_inscratch(dest, size, mstate)) {
4252 *flags |= CPU_DTRACE_BADADDR;
4257 if (!dtrace_canload(src, size, mstate, vstate)) {
4262 dtrace_bcopy((void *)src, (void *)dest, size);
4266 case DIF_SUBR_ALLOCA:
4267 case DIF_SUBR_COPYIN: {
4268 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4270 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4271 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4274 * This action doesn't require any credential checks since
4275 * probes will not activate in user contexts to which the
4276 * enabling user does not have permissions.
4280 * Rounding up the user allocation size could have overflowed
4281 * a large, bogus allocation (like -1ULL) to 0.
4283 if (scratch_size < size ||
4284 !DTRACE_INSCRATCH(mstate, scratch_size)) {
4285 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4290 if (subr == DIF_SUBR_COPYIN) {
4291 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4292 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4293 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4296 mstate->dtms_scratch_ptr += scratch_size;
4301 case DIF_SUBR_COPYINTO: {
4302 uint64_t size = tupregs[1].dttk_value;
4303 uintptr_t dest = tupregs[2].dttk_value;
4306 * This action doesn't require any credential checks since
4307 * probes will not activate in user contexts to which the
4308 * enabling user does not have permissions.
4310 if (!dtrace_inscratch(dest, size, mstate)) {
4311 *flags |= CPU_DTRACE_BADADDR;
4316 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4317 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4318 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4322 case DIF_SUBR_COPYINSTR: {
4323 uintptr_t dest = mstate->dtms_scratch_ptr;
4324 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4326 if (nargs > 1 && tupregs[1].dttk_value < size)
4327 size = tupregs[1].dttk_value + 1;
4330 * This action doesn't require any credential checks since
4331 * probes will not activate in user contexts to which the
4332 * enabling user does not have permissions.
4334 if (!DTRACE_INSCRATCH(mstate, size)) {
4335 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4340 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4341 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4342 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4344 ((char *)dest)[size - 1] = '\0';
4345 mstate->dtms_scratch_ptr += size;
4351 case DIF_SUBR_MSGSIZE:
4352 case DIF_SUBR_MSGDSIZE: {
4353 uintptr_t baddr = tupregs[0].dttk_value, daddr;
4354 uintptr_t wptr, rptr;
4358 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4360 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4366 wptr = dtrace_loadptr(baddr +
4367 offsetof(mblk_t, b_wptr));
4369 rptr = dtrace_loadptr(baddr +
4370 offsetof(mblk_t, b_rptr));
4373 *flags |= CPU_DTRACE_BADADDR;
4374 *illval = tupregs[0].dttk_value;
4378 daddr = dtrace_loadptr(baddr +
4379 offsetof(mblk_t, b_datap));
4381 baddr = dtrace_loadptr(baddr +
4382 offsetof(mblk_t, b_cont));
4385 * We want to prevent against denial-of-service here,
4386 * so we're only going to search the list for
4387 * dtrace_msgdsize_max mblks.
4389 if (cont++ > dtrace_msgdsize_max) {
4390 *flags |= CPU_DTRACE_ILLOP;
4394 if (subr == DIF_SUBR_MSGDSIZE) {
4395 if (dtrace_load8(daddr +
4396 offsetof(dblk_t, db_type)) != M_DATA)
4400 count += wptr - rptr;
4403 if (!(*flags & CPU_DTRACE_FAULT))
4410 case DIF_SUBR_PROGENYOF: {
4411 pid_t pid = tupregs[0].dttk_value;
4415 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4417 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4419 if (p->p_pidp->pid_id == pid) {
4421 if (p->p_pid == pid) {
4428 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4434 case DIF_SUBR_SPECULATION:
4435 regs[rd] = dtrace_speculation(state);
4438 case DIF_SUBR_COPYOUT: {
4439 uintptr_t kaddr = tupregs[0].dttk_value;
4440 uintptr_t uaddr = tupregs[1].dttk_value;
4441 uint64_t size = tupregs[2].dttk_value;
4443 if (!dtrace_destructive_disallow &&
4444 dtrace_priv_proc_control(state) &&
4445 !dtrace_istoxic(kaddr, size)) {
4446 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4447 dtrace_copyout(kaddr, uaddr, size, flags);
4448 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4453 case DIF_SUBR_COPYOUTSTR: {
4454 uintptr_t kaddr = tupregs[0].dttk_value;
4455 uintptr_t uaddr = tupregs[1].dttk_value;
4456 uint64_t size = tupregs[2].dttk_value;
4458 if (!dtrace_destructive_disallow &&
4459 dtrace_priv_proc_control(state) &&
4460 !dtrace_istoxic(kaddr, size)) {
4461 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4462 dtrace_copyoutstr(kaddr, uaddr, size, flags);
4463 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4468 case DIF_SUBR_STRLEN: {
4470 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4471 sz = dtrace_strlen((char *)addr,
4472 state->dts_options[DTRACEOPT_STRSIZE]);
4474 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4484 case DIF_SUBR_STRCHR:
4485 case DIF_SUBR_STRRCHR: {
4487 * We're going to iterate over the string looking for the
4488 * specified character. We will iterate until we have reached
4489 * the string length or we have found the character. If this
4490 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4491 * of the specified character instead of the first.
4493 uintptr_t saddr = tupregs[0].dttk_value;
4494 uintptr_t addr = tupregs[0].dttk_value;
4495 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4496 char c, target = (char)tupregs[1].dttk_value;
4498 for (regs[rd] = 0; addr < limit; addr++) {
4499 if ((c = dtrace_load8(addr)) == target) {
4502 if (subr == DIF_SUBR_STRCHR)
4510 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4518 case DIF_SUBR_STRSTR:
4519 case DIF_SUBR_INDEX:
4520 case DIF_SUBR_RINDEX: {
4522 * We're going to iterate over the string looking for the
4523 * specified string. We will iterate until we have reached
4524 * the string length or we have found the string. (Yes, this
4525 * is done in the most naive way possible -- but considering
4526 * that the string we're searching for is likely to be
4527 * relatively short, the complexity of Rabin-Karp or similar
4528 * hardly seems merited.)
4530 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4531 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4532 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4533 size_t len = dtrace_strlen(addr, size);
4534 size_t sublen = dtrace_strlen(substr, size);
4535 char *limit = addr + len, *orig = addr;
4536 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4539 regs[rd] = notfound;
4541 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4546 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4553 * strstr() and index()/rindex() have similar semantics if
4554 * both strings are the empty string: strstr() returns a
4555 * pointer to the (empty) string, and index() and rindex()
4556 * both return index 0 (regardless of any position argument).
4558 if (sublen == 0 && len == 0) {
4559 if (subr == DIF_SUBR_STRSTR)
4560 regs[rd] = (uintptr_t)addr;
4566 if (subr != DIF_SUBR_STRSTR) {
4567 if (subr == DIF_SUBR_RINDEX) {
4574 * Both index() and rindex() take an optional position
4575 * argument that denotes the starting position.
4578 int64_t pos = (int64_t)tupregs[2].dttk_value;
4581 * If the position argument to index() is
4582 * negative, Perl implicitly clamps it at
4583 * zero. This semantic is a little surprising
4584 * given the special meaning of negative
4585 * positions to similar Perl functions like
4586 * substr(), but it appears to reflect a
4587 * notion that index() can start from a
4588 * negative index and increment its way up to
4589 * the string. Given this notion, Perl's
4590 * rindex() is at least self-consistent in
4591 * that it implicitly clamps positions greater
4592 * than the string length to be the string
4593 * length. Where Perl completely loses
4594 * coherence, however, is when the specified
4595 * substring is the empty string (""). In
4596 * this case, even if the position is
4597 * negative, rindex() returns 0 -- and even if
4598 * the position is greater than the length,
4599 * index() returns the string length. These
4600 * semantics violate the notion that index()
4601 * should never return a value less than the
4602 * specified position and that rindex() should
4603 * never return a value greater than the
4604 * specified position. (One assumes that
4605 * these semantics are artifacts of Perl's
4606 * implementation and not the results of
4607 * deliberate design -- it beggars belief that
4608 * even Larry Wall could desire such oddness.)
4609 * While in the abstract one would wish for
4610 * consistent position semantics across
4611 * substr(), index() and rindex() -- or at the
4612 * very least self-consistent position
4613 * semantics for index() and rindex() -- we
4614 * instead opt to keep with the extant Perl
4615 * semantics, in all their broken glory. (Do
4616 * we have more desire to maintain Perl's
4617 * semantics than Perl does? Probably.)
4619 if (subr == DIF_SUBR_RINDEX) {
4643 for (regs[rd] = notfound; addr != limit; addr += inc) {
4644 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4645 if (subr != DIF_SUBR_STRSTR) {
4647 * As D index() and rindex() are
4648 * modeled on Perl (and not on awk),
4649 * we return a zero-based (and not a
4650 * one-based) index. (For you Perl
4651 * weenies: no, we're not going to add
4652 * $[ -- and shouldn't you be at a con
4655 regs[rd] = (uintptr_t)(addr - orig);
4659 ASSERT(subr == DIF_SUBR_STRSTR);
4660 regs[rd] = (uintptr_t)addr;
4668 case DIF_SUBR_STRTOK: {
4669 uintptr_t addr = tupregs[0].dttk_value;
4670 uintptr_t tokaddr = tupregs[1].dttk_value;
4671 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4672 uintptr_t limit, toklimit = tokaddr + size;
4673 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
4674 char *dest = (char *)mstate->dtms_scratch_ptr;
4678 * Check both the token buffer and (later) the input buffer,
4679 * since both could be non-scratch addresses.
4681 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4686 if (!DTRACE_INSCRATCH(mstate, size)) {
4687 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4694 * If the address specified is NULL, we use our saved
4695 * strtok pointer from the mstate. Note that this
4696 * means that the saved strtok pointer is _only_
4697 * valid within multiple enablings of the same probe --
4698 * it behaves like an implicit clause-local variable.
4700 addr = mstate->dtms_strtok;
4703 * If the user-specified address is non-NULL we must
4704 * access check it. This is the only time we have
4705 * a chance to do so, since this address may reside
4706 * in the string table of this clause-- future calls
4707 * (when we fetch addr from mstate->dtms_strtok)
4708 * would fail this access check.
4710 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4717 * First, zero the token map, and then process the token
4718 * string -- setting a bit in the map for every character
4719 * found in the token string.
4721 for (i = 0; i < sizeof (tokmap); i++)
4724 for (; tokaddr < toklimit; tokaddr++) {
4725 if ((c = dtrace_load8(tokaddr)) == '\0')
4728 ASSERT((c >> 3) < sizeof (tokmap));
4729 tokmap[c >> 3] |= (1 << (c & 0x7));
4732 for (limit = addr + size; addr < limit; addr++) {
4734 * We're looking for a character that is _not_ contained
4735 * in the token string.
4737 if ((c = dtrace_load8(addr)) == '\0')
4740 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4746 * We reached the end of the string without finding
4747 * any character that was not in the token string.
4748 * We return NULL in this case, and we set the saved
4749 * address to NULL as well.
4752 mstate->dtms_strtok = 0;
4757 * From here on, we're copying into the destination string.
4759 for (i = 0; addr < limit && i < size - 1; addr++) {
4760 if ((c = dtrace_load8(addr)) == '\0')
4763 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4772 regs[rd] = (uintptr_t)dest;
4773 mstate->dtms_scratch_ptr += size;
4774 mstate->dtms_strtok = addr;
4778 case DIF_SUBR_SUBSTR: {
4779 uintptr_t s = tupregs[0].dttk_value;
4780 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4781 char *d = (char *)mstate->dtms_scratch_ptr;
4782 int64_t index = (int64_t)tupregs[1].dttk_value;
4783 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4784 size_t len = dtrace_strlen((char *)s, size);
4787 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4792 if (!DTRACE_INSCRATCH(mstate, size)) {
4793 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4799 remaining = (int64_t)size;
4804 if (index < 0 && index + remaining > 0) {
4810 if (index >= len || index < 0) {
4812 } else if (remaining < 0) {
4813 remaining += len - index;
4814 } else if (index + remaining > size) {
4815 remaining = size - index;
4818 for (i = 0; i < remaining; i++) {
4819 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4825 mstate->dtms_scratch_ptr += size;
4826 regs[rd] = (uintptr_t)d;
4830 case DIF_SUBR_JSON: {
4831 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4832 uintptr_t json = tupregs[0].dttk_value;
4833 size_t jsonlen = dtrace_strlen((char *)json, size);
4834 uintptr_t elem = tupregs[1].dttk_value;
4835 size_t elemlen = dtrace_strlen((char *)elem, size);
4837 char *dest = (char *)mstate->dtms_scratch_ptr;
4838 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4839 char *ee = elemlist;
4843 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4844 !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4849 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4850 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4856 * Read the element selector and split it up into a packed list
4859 for (cur = elem; cur < elem + elemlen; cur++) {
4860 char cc = dtrace_load8(cur);
4862 if (cur == elem && cc == '[') {
4864 * If the first element selector key is
4865 * actually an array index then ignore the
4874 if (cc == '.' || cc == '[') {
4883 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4884 nelems, dest)) != 0)
4885 mstate->dtms_scratch_ptr += jsonlen + 1;
4889 case DIF_SUBR_TOUPPER:
4890 case DIF_SUBR_TOLOWER: {
4891 uintptr_t s = tupregs[0].dttk_value;
4892 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4893 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4894 size_t len = dtrace_strlen((char *)s, size);
4895 char lower, upper, convert;
4898 if (subr == DIF_SUBR_TOUPPER) {
4908 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4913 if (!DTRACE_INSCRATCH(mstate, size)) {
4914 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4919 for (i = 0; i < size - 1; i++) {
4920 if ((c = dtrace_load8(s + i)) == '\0')
4923 if (c >= lower && c <= upper)
4924 c = convert + (c - lower);
4931 regs[rd] = (uintptr_t)dest;
4932 mstate->dtms_scratch_ptr += size;
4937 case DIF_SUBR_GETMAJOR:
4939 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4941 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4945 case DIF_SUBR_GETMINOR:
4947 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4949 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4953 case DIF_SUBR_DDI_PATHNAME: {
4955 * This one is a galactic mess. We are going to roughly
4956 * emulate ddi_pathname(), but it's made more complicated
4957 * by the fact that we (a) want to include the minor name and
4958 * (b) must proceed iteratively instead of recursively.
4960 uintptr_t dest = mstate->dtms_scratch_ptr;
4961 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4962 char *start = (char *)dest, *end = start + size - 1;
4963 uintptr_t daddr = tupregs[0].dttk_value;
4964 int64_t minor = (int64_t)tupregs[1].dttk_value;
4966 int i, len, depth = 0;
4969 * Due to all the pointer jumping we do and context we must
4970 * rely upon, we just mandate that the user must have kernel
4971 * read privileges to use this routine.
4973 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4974 *flags |= CPU_DTRACE_KPRIV;
4979 if (!DTRACE_INSCRATCH(mstate, size)) {
4980 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4988 * We want to have a name for the minor. In order to do this,
4989 * we need to walk the minor list from the devinfo. We want
4990 * to be sure that we don't infinitely walk a circular list,
4991 * so we check for circularity by sending a scout pointer
4992 * ahead two elements for every element that we iterate over;
4993 * if the list is circular, these will ultimately point to the
4994 * same element. You may recognize this little trick as the
4995 * answer to a stupid interview question -- one that always
4996 * seems to be asked by those who had to have it laboriously
4997 * explained to them, and who can't even concisely describe
4998 * the conditions under which one would be forced to resort to
4999 * this technique. Needless to say, those conditions are
5000 * found here -- and probably only here. Is this the only use
5001 * of this infamous trick in shipping, production code? If it
5002 * isn't, it probably should be...
5005 uintptr_t maddr = dtrace_loadptr(daddr +
5006 offsetof(struct dev_info, devi_minor));
5008 uintptr_t next = offsetof(struct ddi_minor_data, next);
5009 uintptr_t name = offsetof(struct ddi_minor_data,
5010 d_minor) + offsetof(struct ddi_minor, name);
5011 uintptr_t dev = offsetof(struct ddi_minor_data,
5012 d_minor) + offsetof(struct ddi_minor, dev);
5016 scout = dtrace_loadptr(maddr + next);
5018 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5021 m = dtrace_load64(maddr + dev) & MAXMIN64;
5023 m = dtrace_load32(maddr + dev) & MAXMIN;
5026 maddr = dtrace_loadptr(maddr + next);
5031 scout = dtrace_loadptr(scout + next);
5036 scout = dtrace_loadptr(scout + next);
5041 if (scout == maddr) {
5042 *flags |= CPU_DTRACE_ILLOP;
5050 * We have the minor data. Now we need to
5051 * copy the minor's name into the end of the
5054 s = (char *)dtrace_loadptr(maddr + name);
5055 len = dtrace_strlen(s, size);
5057 if (*flags & CPU_DTRACE_FAULT)
5061 if ((end -= (len + 1)) < start)
5067 for (i = 1; i <= len; i++)
5068 end[i] = dtrace_load8((uintptr_t)s++);
5073 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5074 ddi_node_state_t devi_state;
5076 devi_state = dtrace_load32(daddr +
5077 offsetof(struct dev_info, devi_node_state));
5079 if (*flags & CPU_DTRACE_FAULT)
5082 if (devi_state >= DS_INITIALIZED) {
5083 s = (char *)dtrace_loadptr(daddr +
5084 offsetof(struct dev_info, devi_addr));
5085 len = dtrace_strlen(s, size);
5087 if (*flags & CPU_DTRACE_FAULT)
5091 if ((end -= (len + 1)) < start)
5097 for (i = 1; i <= len; i++)
5098 end[i] = dtrace_load8((uintptr_t)s++);
5102 * Now for the node name...
5104 s = (char *)dtrace_loadptr(daddr +
5105 offsetof(struct dev_info, devi_node_name));
5107 daddr = dtrace_loadptr(daddr +
5108 offsetof(struct dev_info, devi_parent));
5111 * If our parent is NULL (that is, if we're the root
5112 * node), we're going to use the special path
5118 len = dtrace_strlen(s, size);
5119 if (*flags & CPU_DTRACE_FAULT)
5122 if ((end -= (len + 1)) < start)
5125 for (i = 1; i <= len; i++)
5126 end[i] = dtrace_load8((uintptr_t)s++);
5129 if (depth++ > dtrace_devdepth_max) {
5130 *flags |= CPU_DTRACE_ILLOP;
5136 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5139 regs[rd] = (uintptr_t)end;
5140 mstate->dtms_scratch_ptr += size;
5147 case DIF_SUBR_STRJOIN: {
5148 char *d = (char *)mstate->dtms_scratch_ptr;
5149 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5150 uintptr_t s1 = tupregs[0].dttk_value;
5151 uintptr_t s2 = tupregs[1].dttk_value;
5154 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
5155 !dtrace_strcanload(s2, size, mstate, vstate)) {
5160 if (!DTRACE_INSCRATCH(mstate, size)) {
5161 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5168 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5173 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
5181 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5186 if ((d[i++] = dtrace_load8(s2++)) == '\0')
5191 mstate->dtms_scratch_ptr += i;
5192 regs[rd] = (uintptr_t)d;
5198 case DIF_SUBR_STRTOLL: {
5199 uintptr_t s = tupregs[0].dttk_value;
5200 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5204 if ((base = tupregs[1].dttk_value) <= 1 ||
5205 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5206 *flags |= CPU_DTRACE_ILLOP;
5211 if (!dtrace_strcanload(s, size, mstate, vstate)) {
5212 regs[rd] = INT64_MIN;
5216 regs[rd] = dtrace_strtoll((char *)s, base, size);
5220 case DIF_SUBR_LLTOSTR: {
5221 int64_t i = (int64_t)tupregs[0].dttk_value;
5222 uint64_t val, digit;
5223 uint64_t size = 65; /* enough room for 2^64 in binary */
5224 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5228 if ((base = tupregs[1].dttk_value) <= 1 ||
5229 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5230 *flags |= CPU_DTRACE_ILLOP;
5235 val = (base == 10 && i < 0) ? i * -1 : i;
5237 if (!DTRACE_INSCRATCH(mstate, size)) {
5238 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5243 for (*end-- = '\0'; val; val /= base) {
5244 if ((digit = val % base) <= '9' - '0') {
5245 *end-- = '0' + digit;
5247 *end-- = 'a' + (digit - ('9' - '0') - 1);
5251 if (i == 0 && base == 16)
5257 if (i == 0 || base == 8 || base == 16)
5260 if (i < 0 && base == 10)
5263 regs[rd] = (uintptr_t)end + 1;
5264 mstate->dtms_scratch_ptr += size;
5268 case DIF_SUBR_HTONS:
5269 case DIF_SUBR_NTOHS:
5270 #if BYTE_ORDER == BIG_ENDIAN
5271 regs[rd] = (uint16_t)tupregs[0].dttk_value;
5273 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5278 case DIF_SUBR_HTONL:
5279 case DIF_SUBR_NTOHL:
5280 #if BYTE_ORDER == BIG_ENDIAN
5281 regs[rd] = (uint32_t)tupregs[0].dttk_value;
5283 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5288 case DIF_SUBR_HTONLL:
5289 case DIF_SUBR_NTOHLL:
5290 #if BYTE_ORDER == BIG_ENDIAN
5291 regs[rd] = (uint64_t)tupregs[0].dttk_value;
5293 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5298 case DIF_SUBR_DIRNAME:
5299 case DIF_SUBR_BASENAME: {
5300 char *dest = (char *)mstate->dtms_scratch_ptr;
5301 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5302 uintptr_t src = tupregs[0].dttk_value;
5303 int i, j, len = dtrace_strlen((char *)src, size);
5304 int lastbase = -1, firstbase = -1, lastdir = -1;
5307 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5312 if (!DTRACE_INSCRATCH(mstate, size)) {
5313 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5319 * The basename and dirname for a zero-length string is
5324 src = (uintptr_t)".";
5328 * Start from the back of the string, moving back toward the
5329 * front until we see a character that isn't a slash. That
5330 * character is the last character in the basename.
5332 for (i = len - 1; i >= 0; i--) {
5333 if (dtrace_load8(src + i) != '/')
5341 * Starting from the last character in the basename, move
5342 * towards the front until we find a slash. The character
5343 * that we processed immediately before that is the first
5344 * character in the basename.
5346 for (; i >= 0; i--) {
5347 if (dtrace_load8(src + i) == '/')
5355 * Now keep going until we find a non-slash character. That
5356 * character is the last character in the dirname.
5358 for (; i >= 0; i--) {
5359 if (dtrace_load8(src + i) != '/')
5366 ASSERT(!(lastbase == -1 && firstbase != -1));
5367 ASSERT(!(firstbase == -1 && lastdir != -1));
5369 if (lastbase == -1) {
5371 * We didn't find a non-slash character. We know that
5372 * the length is non-zero, so the whole string must be
5373 * slashes. In either the dirname or the basename
5374 * case, we return '/'.
5376 ASSERT(firstbase == -1);
5377 firstbase = lastbase = lastdir = 0;
5380 if (firstbase == -1) {
5382 * The entire string consists only of a basename
5383 * component. If we're looking for dirname, we need
5384 * to change our string to be just "."; if we're
5385 * looking for a basename, we'll just set the first
5386 * character of the basename to be 0.
5388 if (subr == DIF_SUBR_DIRNAME) {
5389 ASSERT(lastdir == -1);
5390 src = (uintptr_t)".";
5397 if (subr == DIF_SUBR_DIRNAME) {
5398 if (lastdir == -1) {
5400 * We know that we have a slash in the name --
5401 * or lastdir would be set to 0, above. And
5402 * because lastdir is -1, we know that this
5403 * slash must be the first character. (That
5404 * is, the full string must be of the form
5405 * "/basename".) In this case, the last
5406 * character of the directory name is 0.
5414 ASSERT(subr == DIF_SUBR_BASENAME);
5415 ASSERT(firstbase != -1 && lastbase != -1);
5420 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5421 dest[j] = dtrace_load8(src + i);
5424 regs[rd] = (uintptr_t)dest;
5425 mstate->dtms_scratch_ptr += size;
5429 case DIF_SUBR_GETF: {
5430 uintptr_t fd = tupregs[0].dttk_value;
5431 struct filedesc *fdp;
5434 if (!dtrace_priv_proc(state)) {
5438 fdp = curproc->p_fd;
5439 FILEDESC_SLOCK(fdp);
5440 fp = fget_locked(fdp, fd);
5441 mstate->dtms_getf = fp;
5442 regs[rd] = (uintptr_t)fp;
5443 FILEDESC_SUNLOCK(fdp);
5447 case DIF_SUBR_CLEANPATH: {
5448 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5449 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5450 uintptr_t src = tupregs[0].dttk_value;
5456 if (!dtrace_strcanload(src, size, mstate, vstate)) {
5461 if (!DTRACE_INSCRATCH(mstate, size)) {
5462 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5468 * Move forward, loading each character.
5471 c = dtrace_load8(src + i++);
5473 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
5481 c = dtrace_load8(src + i++);
5485 * We have two slashes -- we can just advance
5486 * to the next character.
5493 * This is not "." and it's not ".." -- we can
5494 * just store the "/" and this character and
5502 c = dtrace_load8(src + i++);
5506 * This is a "/./" component. We're not going
5507 * to store anything in the destination buffer;
5508 * we're just going to go to the next component.
5515 * This is not ".." -- we can just store the
5516 * "/." and this character and continue
5525 c = dtrace_load8(src + i++);
5527 if (c != '/' && c != '\0') {
5529 * This is not ".." -- it's "..[mumble]".
5530 * We'll store the "/.." and this character
5531 * and continue processing.
5541 * This is "/../" or "/..\0". We need to back up
5542 * our destination pointer until we find a "/".
5545 while (j != 0 && dest[--j] != '/')
5550 } while (c != '\0');
5555 if (mstate->dtms_getf != NULL &&
5556 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5557 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5559 * If we've done a getf() as a part of this ECB and we
5560 * don't have kernel access (and we're not in the global
5561 * zone), check if the path we cleaned up begins with
5562 * the zone's root path, and trim it off if so. Note
5563 * that this is an output cleanliness issue, not a
5564 * security issue: knowing one's zone root path does
5565 * not enable privilege escalation.
5567 if (strstr(dest, z->zone_rootpath) == dest)
5568 dest += strlen(z->zone_rootpath) - 1;
5572 regs[rd] = (uintptr_t)dest;
5573 mstate->dtms_scratch_ptr += size;
5577 case DIF_SUBR_INET_NTOA:
5578 case DIF_SUBR_INET_NTOA6:
5579 case DIF_SUBR_INET_NTOP: {
5584 if (subr == DIF_SUBR_INET_NTOP) {
5585 af = (int)tupregs[0].dttk_value;
5588 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5592 if (af == AF_INET) {
5597 * Safely load the IPv4 address.
5599 ip4 = dtrace_load32(tupregs[argi].dttk_value);
5602 * Check an IPv4 string will fit in scratch.
5604 size = INET_ADDRSTRLEN;
5605 if (!DTRACE_INSCRATCH(mstate, size)) {
5606 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5610 base = (char *)mstate->dtms_scratch_ptr;
5611 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5614 * Stringify as a dotted decimal quad.
5617 ptr8 = (uint8_t *)&ip4;
5618 for (i = 3; i >= 0; i--) {
5624 for (; val; val /= 10) {
5625 *end-- = '0' + (val % 10);
5632 ASSERT(end + 1 >= base);
5634 } else if (af == AF_INET6) {
5635 struct in6_addr ip6;
5636 int firstzero, tryzero, numzero, v6end;
5638 const char digits[] = "0123456789abcdef";
5641 * Stringify using RFC 1884 convention 2 - 16 bit
5642 * hexadecimal values with a zero-run compression.
5643 * Lower case hexadecimal digits are used.
5644 * eg, fe80::214:4fff:fe0b:76c8.
5645 * The IPv4 embedded form is returned for inet_ntop,
5646 * just the IPv4 string is returned for inet_ntoa6.
5650 * Safely load the IPv6 address.
5653 (void *)(uintptr_t)tupregs[argi].dttk_value,
5654 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5657 * Check an IPv6 string will fit in scratch.
5659 size = INET6_ADDRSTRLEN;
5660 if (!DTRACE_INSCRATCH(mstate, size)) {
5661 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5665 base = (char *)mstate->dtms_scratch_ptr;
5666 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5670 * Find the longest run of 16 bit zero values
5671 * for the single allowed zero compression - "::".
5676 for (i = 0; i < sizeof (struct in6_addr); i++) {
5678 if (ip6._S6_un._S6_u8[i] == 0 &&
5680 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5682 tryzero == -1 && i % 2 == 0) {
5687 if (tryzero != -1 &&
5689 (ip6._S6_un._S6_u8[i] != 0 ||
5691 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5693 i == sizeof (struct in6_addr) - 1)) {
5695 if (i - tryzero <= numzero) {
5700 firstzero = tryzero;
5701 numzero = i - i % 2 - tryzero;
5705 if (ip6._S6_un._S6_u8[i] == 0 &&
5707 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5709 i == sizeof (struct in6_addr) - 1)
5713 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5716 * Check for an IPv4 embedded address.
5718 v6end = sizeof (struct in6_addr) - 2;
5719 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5720 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5721 for (i = sizeof (struct in6_addr) - 1;
5722 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5723 ASSERT(end >= base);
5726 val = ip6._S6_un._S6_u8[i];
5728 val = ip6.__u6_addr.__u6_addr8[i];
5734 for (; val; val /= 10) {
5735 *end-- = '0' + val % 10;
5739 if (i > DTRACE_V4MAPPED_OFFSET)
5743 if (subr == DIF_SUBR_INET_NTOA6)
5747 * Set v6end to skip the IPv4 address that
5748 * we have already stringified.
5754 * Build the IPv6 string by working through the
5755 * address in reverse.
5757 for (i = v6end; i >= 0; i -= 2) {
5758 ASSERT(end >= base);
5760 if (i == firstzero + numzero - 2) {
5767 if (i < 14 && i != firstzero - 2)
5771 val = (ip6._S6_un._S6_u8[i] << 8) +
5772 ip6._S6_un._S6_u8[i + 1];
5774 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5775 ip6.__u6_addr.__u6_addr8[i + 1];
5781 for (; val; val /= 16) {
5782 *end-- = digits[val % 16];
5786 ASSERT(end + 1 >= base);
5790 * The user didn't use AH_INET or AH_INET6.
5792 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5797 inetout: regs[rd] = (uintptr_t)end + 1;
5798 mstate->dtms_scratch_ptr += size;
5802 case DIF_SUBR_MEMREF: {
5803 uintptr_t size = 2 * sizeof(uintptr_t);
5804 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5805 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5807 /* address and length */
5808 memref[0] = tupregs[0].dttk_value;
5809 memref[1] = tupregs[1].dttk_value;
5811 regs[rd] = (uintptr_t) memref;
5812 mstate->dtms_scratch_ptr += scratch_size;
5817 case DIF_SUBR_MEMSTR: {
5818 char *str = (char *)mstate->dtms_scratch_ptr;
5819 uintptr_t mem = tupregs[0].dttk_value;
5820 char c = tupregs[1].dttk_value;
5821 size_t size = tupregs[2].dttk_value;
5830 if (!dtrace_canload(mem, size - 1, mstate, vstate))
5833 if (!DTRACE_INSCRATCH(mstate, size)) {
5834 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5838 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5839 *flags |= CPU_DTRACE_ILLOP;
5843 for (i = 0; i < size - 1; i++) {
5844 n = dtrace_load8(mem++);
5845 str[i] = (n == 0) ? c : n;
5849 regs[rd] = (uintptr_t)str;
5850 mstate->dtms_scratch_ptr += size;
5855 case DIF_SUBR_TYPEREF: {
5856 uintptr_t size = 4 * sizeof(uintptr_t);
5857 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5858 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5860 /* address, num_elements, type_str, type_len */
5861 typeref[0] = tupregs[0].dttk_value;
5862 typeref[1] = tupregs[1].dttk_value;
5863 typeref[2] = tupregs[2].dttk_value;
5864 typeref[3] = tupregs[3].dttk_value;
5866 regs[rd] = (uintptr_t) typeref;
5867 mstate->dtms_scratch_ptr += scratch_size;
5874 * Emulate the execution of DTrace IR instructions specified by the given
5875 * DIF object. This function is deliberately void of assertions as all of
5876 * the necessary checks are handled by a call to dtrace_difo_validate().
5879 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5880 dtrace_vstate_t *vstate, dtrace_state_t *state)
5882 const dif_instr_t *text = difo->dtdo_buf;
5883 const uint_t textlen = difo->dtdo_len;
5884 const char *strtab = difo->dtdo_strtab;
5885 const uint64_t *inttab = difo->dtdo_inttab;
5888 dtrace_statvar_t *svar;
5889 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5891 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5892 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5894 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5895 uint64_t regs[DIF_DIR_NREGS];
5898 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5900 uint_t pc = 0, id, opc = 0;
5906 * We stash the current DIF object into the machine state: we need it
5907 * for subsequent access checking.
5909 mstate->dtms_difo = difo;
5911 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5913 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5917 r1 = DIF_INSTR_R1(instr);
5918 r2 = DIF_INSTR_R2(instr);
5919 rd = DIF_INSTR_RD(instr);
5921 switch (DIF_INSTR_OP(instr)) {
5923 regs[rd] = regs[r1] | regs[r2];
5926 regs[rd] = regs[r1] ^ regs[r2];
5929 regs[rd] = regs[r1] & regs[r2];
5932 regs[rd] = regs[r1] << regs[r2];
5935 regs[rd] = regs[r1] >> regs[r2];
5938 regs[rd] = regs[r1] - regs[r2];
5941 regs[rd] = regs[r1] + regs[r2];
5944 regs[rd] = regs[r1] * regs[r2];
5947 if (regs[r2] == 0) {
5949 *flags |= CPU_DTRACE_DIVZERO;
5951 regs[rd] = (int64_t)regs[r1] /
5957 if (regs[r2] == 0) {
5959 *flags |= CPU_DTRACE_DIVZERO;
5961 regs[rd] = regs[r1] / regs[r2];
5966 if (regs[r2] == 0) {
5968 *flags |= CPU_DTRACE_DIVZERO;
5970 regs[rd] = (int64_t)regs[r1] %
5976 if (regs[r2] == 0) {
5978 *flags |= CPU_DTRACE_DIVZERO;
5980 regs[rd] = regs[r1] % regs[r2];
5985 regs[rd] = ~regs[r1];
5988 regs[rd] = regs[r1];
5991 cc_r = regs[r1] - regs[r2];
5995 cc_c = regs[r1] < regs[r2];
5998 cc_n = cc_v = cc_c = 0;
5999 cc_z = regs[r1] == 0;
6002 pc = DIF_INSTR_LABEL(instr);
6006 pc = DIF_INSTR_LABEL(instr);
6010 pc = DIF_INSTR_LABEL(instr);
6013 if ((cc_z | (cc_n ^ cc_v)) == 0)
6014 pc = DIF_INSTR_LABEL(instr);
6017 if ((cc_c | cc_z) == 0)
6018 pc = DIF_INSTR_LABEL(instr);
6021 if ((cc_n ^ cc_v) == 0)
6022 pc = DIF_INSTR_LABEL(instr);
6026 pc = DIF_INSTR_LABEL(instr);
6030 pc = DIF_INSTR_LABEL(instr);
6034 pc = DIF_INSTR_LABEL(instr);
6037 if (cc_z | (cc_n ^ cc_v))
6038 pc = DIF_INSTR_LABEL(instr);
6042 pc = DIF_INSTR_LABEL(instr);
6045 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6049 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6052 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6056 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6059 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6063 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6066 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6070 regs[rd] = dtrace_load8(regs[r1]);
6073 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6077 regs[rd] = dtrace_load16(regs[r1]);
6080 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6084 regs[rd] = dtrace_load32(regs[r1]);
6087 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6091 regs[rd] = dtrace_load64(regs[r1]);
6094 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6096 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6097 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6100 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6101 regs[rd] = (int16_t)
6102 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6103 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6106 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6107 regs[rd] = (int32_t)
6108 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6109 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6112 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6114 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6115 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6118 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6120 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6121 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6124 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6126 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6127 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6130 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6132 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6133 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6142 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6145 regs[rd] = (uint64_t)(uintptr_t)
6146 (strtab + DIF_INSTR_STRING(instr));
6149 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6150 uintptr_t s1 = regs[r1];
6151 uintptr_t s2 = regs[r2];
6154 !dtrace_strcanload(s1, sz, mstate, vstate))
6157 !dtrace_strcanload(s2, sz, mstate, vstate))
6160 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
6168 regs[rd] = dtrace_dif_variable(mstate, state,
6172 id = DIF_INSTR_VAR(instr);
6174 if (id >= DIF_VAR_OTHER_UBASE) {
6177 id -= DIF_VAR_OTHER_UBASE;
6178 svar = vstate->dtvs_globals[id];
6179 ASSERT(svar != NULL);
6180 v = &svar->dtsv_var;
6182 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6183 regs[rd] = svar->dtsv_data;
6187 a = (uintptr_t)svar->dtsv_data;
6189 if (*(uint8_t *)a == UINT8_MAX) {
6191 * If the 0th byte is set to UINT8_MAX
6192 * then this is to be treated as a
6193 * reference to a NULL variable.
6197 regs[rd] = a + sizeof (uint64_t);
6203 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6207 id = DIF_INSTR_VAR(instr);
6209 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6210 id -= DIF_VAR_OTHER_UBASE;
6212 svar = vstate->dtvs_globals[id];
6213 ASSERT(svar != NULL);
6214 v = &svar->dtsv_var;
6216 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6217 uintptr_t a = (uintptr_t)svar->dtsv_data;
6220 ASSERT(svar->dtsv_size != 0);
6222 if (regs[rd] == 0) {
6223 *(uint8_t *)a = UINT8_MAX;
6227 a += sizeof (uint64_t);
6229 if (!dtrace_vcanload(
6230 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6234 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6235 (void *)a, &v->dtdv_type);
6239 svar->dtsv_data = regs[rd];
6244 * There are no DTrace built-in thread-local arrays at
6245 * present. This opcode is saved for future work.
6247 *flags |= CPU_DTRACE_ILLOP;
6252 id = DIF_INSTR_VAR(instr);
6254 if (id < DIF_VAR_OTHER_UBASE) {
6256 * For now, this has no meaning.
6262 id -= DIF_VAR_OTHER_UBASE;
6264 ASSERT(id < vstate->dtvs_nlocals);
6265 ASSERT(vstate->dtvs_locals != NULL);
6267 svar = vstate->dtvs_locals[id];
6268 ASSERT(svar != NULL);
6269 v = &svar->dtsv_var;
6271 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6272 uintptr_t a = (uintptr_t)svar->dtsv_data;
6273 size_t sz = v->dtdv_type.dtdt_size;
6275 sz += sizeof (uint64_t);
6276 ASSERT(svar->dtsv_size == NCPU * sz);
6279 if (*(uint8_t *)a == UINT8_MAX) {
6281 * If the 0th byte is set to UINT8_MAX
6282 * then this is to be treated as a
6283 * reference to a NULL variable.
6287 regs[rd] = a + sizeof (uint64_t);
6293 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6294 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6295 regs[rd] = tmp[curcpu];
6299 id = DIF_INSTR_VAR(instr);
6301 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6302 id -= DIF_VAR_OTHER_UBASE;
6303 ASSERT(id < vstate->dtvs_nlocals);
6305 ASSERT(vstate->dtvs_locals != NULL);
6306 svar = vstate->dtvs_locals[id];
6307 ASSERT(svar != NULL);
6308 v = &svar->dtsv_var;
6310 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6311 uintptr_t a = (uintptr_t)svar->dtsv_data;
6312 size_t sz = v->dtdv_type.dtdt_size;
6314 sz += sizeof (uint64_t);
6315 ASSERT(svar->dtsv_size == NCPU * sz);
6318 if (regs[rd] == 0) {
6319 *(uint8_t *)a = UINT8_MAX;
6323 a += sizeof (uint64_t);
6326 if (!dtrace_vcanload(
6327 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6331 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6332 (void *)a, &v->dtdv_type);
6336 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6337 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6338 tmp[curcpu] = regs[rd];
6342 dtrace_dynvar_t *dvar;
6345 id = DIF_INSTR_VAR(instr);
6346 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6347 id -= DIF_VAR_OTHER_UBASE;
6348 v = &vstate->dtvs_tlocals[id];
6350 key = &tupregs[DIF_DTR_NREGS];
6351 key[0].dttk_value = (uint64_t)id;
6352 key[0].dttk_size = 0;
6353 DTRACE_TLS_THRKEY(key[1].dttk_value);
6354 key[1].dttk_size = 0;
6356 dvar = dtrace_dynvar(dstate, 2, key,
6357 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6365 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6366 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6368 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6375 dtrace_dynvar_t *dvar;
6378 id = DIF_INSTR_VAR(instr);
6379 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6380 id -= DIF_VAR_OTHER_UBASE;
6382 key = &tupregs[DIF_DTR_NREGS];
6383 key[0].dttk_value = (uint64_t)id;
6384 key[0].dttk_size = 0;
6385 DTRACE_TLS_THRKEY(key[1].dttk_value);
6386 key[1].dttk_size = 0;
6387 v = &vstate->dtvs_tlocals[id];
6389 dvar = dtrace_dynvar(dstate, 2, key,
6390 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6391 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6392 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6393 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6396 * Given that we're storing to thread-local data,
6397 * we need to flush our predicate cache.
6399 curthread->t_predcache = 0;
6404 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6405 if (!dtrace_vcanload(
6406 (void *)(uintptr_t)regs[rd],
6407 &v->dtdv_type, mstate, vstate))
6410 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6411 dvar->dtdv_data, &v->dtdv_type);
6413 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6420 regs[rd] = (int64_t)regs[r1] >> regs[r2];
6424 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6425 regs, tupregs, ttop, mstate, state);
6429 if (ttop == DIF_DTR_NREGS) {
6430 *flags |= CPU_DTRACE_TUPOFLOW;
6434 if (r1 == DIF_TYPE_STRING) {
6436 * If this is a string type and the size is 0,
6437 * we'll use the system-wide default string
6438 * size. Note that we are _not_ looking at
6439 * the value of the DTRACEOPT_STRSIZE option;
6440 * had this been set, we would expect to have
6441 * a non-zero size value in the "pushtr".
6443 tupregs[ttop].dttk_size =
6444 dtrace_strlen((char *)(uintptr_t)regs[rd],
6445 regs[r2] ? regs[r2] :
6446 dtrace_strsize_default) + 1;
6448 tupregs[ttop].dttk_size = regs[r2];
6451 tupregs[ttop++].dttk_value = regs[rd];
6455 if (ttop == DIF_DTR_NREGS) {
6456 *flags |= CPU_DTRACE_TUPOFLOW;
6460 tupregs[ttop].dttk_value = regs[rd];
6461 tupregs[ttop++].dttk_size = 0;
6469 case DIF_OP_FLUSHTS:
6474 case DIF_OP_LDTAA: {
6475 dtrace_dynvar_t *dvar;
6476 dtrace_key_t *key = tupregs;
6477 uint_t nkeys = ttop;
6479 id = DIF_INSTR_VAR(instr);
6480 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6481 id -= DIF_VAR_OTHER_UBASE;
6483 key[nkeys].dttk_value = (uint64_t)id;
6484 key[nkeys++].dttk_size = 0;
6486 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6487 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6488 key[nkeys++].dttk_size = 0;
6489 v = &vstate->dtvs_tlocals[id];
6491 v = &vstate->dtvs_globals[id]->dtsv_var;
6494 dvar = dtrace_dynvar(dstate, nkeys, key,
6495 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6496 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6497 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6504 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6505 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6507 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6514 case DIF_OP_STTAA: {
6515 dtrace_dynvar_t *dvar;
6516 dtrace_key_t *key = tupregs;
6517 uint_t nkeys = ttop;
6519 id = DIF_INSTR_VAR(instr);
6520 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6521 id -= DIF_VAR_OTHER_UBASE;
6523 key[nkeys].dttk_value = (uint64_t)id;
6524 key[nkeys++].dttk_size = 0;
6526 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6527 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6528 key[nkeys++].dttk_size = 0;
6529 v = &vstate->dtvs_tlocals[id];
6531 v = &vstate->dtvs_globals[id]->dtsv_var;
6534 dvar = dtrace_dynvar(dstate, nkeys, key,
6535 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6536 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6537 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6538 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6543 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6544 if (!dtrace_vcanload(
6545 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6549 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6550 dvar->dtdv_data, &v->dtdv_type);
6552 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6558 case DIF_OP_ALLOCS: {
6559 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6560 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6563 * Rounding up the user allocation size could have
6564 * overflowed large, bogus allocations (like -1ULL) to
6567 if (size < regs[r1] ||
6568 !DTRACE_INSCRATCH(mstate, size)) {
6569 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6574 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6575 mstate->dtms_scratch_ptr += size;
6581 if (!dtrace_canstore(regs[rd], regs[r2],
6583 *flags |= CPU_DTRACE_BADADDR;
6588 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6591 dtrace_bcopy((void *)(uintptr_t)regs[r1],
6592 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6596 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6597 *flags |= CPU_DTRACE_BADADDR;
6601 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6605 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6606 *flags |= CPU_DTRACE_BADADDR;
6611 *flags |= CPU_DTRACE_BADALIGN;
6615 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6619 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6620 *flags |= CPU_DTRACE_BADADDR;
6625 *flags |= CPU_DTRACE_BADALIGN;
6629 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6633 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6634 *flags |= CPU_DTRACE_BADADDR;
6639 *flags |= CPU_DTRACE_BADALIGN;
6643 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6648 if (!(*flags & CPU_DTRACE_FAULT))
6651 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6652 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6658 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6660 dtrace_probe_t *probe = ecb->dte_probe;
6661 dtrace_provider_t *prov = probe->dtpr_provider;
6662 char c[DTRACE_FULLNAMELEN + 80], *str;
6663 char *msg = "dtrace: breakpoint action at probe ";
6664 char *ecbmsg = " (ecb ";
6665 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6666 uintptr_t val = (uintptr_t)ecb;
6667 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6669 if (dtrace_destructive_disallow)
6673 * It's impossible to be taking action on the NULL probe.
6675 ASSERT(probe != NULL);
6678 * This is a poor man's (destitute man's?) sprintf(): we want to
6679 * print the provider name, module name, function name and name of
6680 * the probe, along with the hex address of the ECB with the breakpoint
6681 * action -- all of which we must place in the character buffer by
6684 while (*msg != '\0')
6687 for (str = prov->dtpv_name; *str != '\0'; str++)
6691 for (str = probe->dtpr_mod; *str != '\0'; str++)
6695 for (str = probe->dtpr_func; *str != '\0'; str++)
6699 for (str = probe->dtpr_name; *str != '\0'; str++)
6702 while (*ecbmsg != '\0')
6705 while (shift >= 0) {
6706 mask = (uintptr_t)0xf << shift;
6708 if (val >= ((uintptr_t)1 << shift))
6709 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6719 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6724 dtrace_action_panic(dtrace_ecb_t *ecb)
6726 dtrace_probe_t *probe = ecb->dte_probe;
6729 * It's impossible to be taking action on the NULL probe.
6731 ASSERT(probe != NULL);
6733 if (dtrace_destructive_disallow)
6736 if (dtrace_panicked != NULL)
6739 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6743 * We won the right to panic. (We want to be sure that only one
6744 * thread calls panic() from dtrace_probe(), and that panic() is
6745 * called exactly once.)
6747 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6748 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6749 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6753 dtrace_action_raise(uint64_t sig)
6755 if (dtrace_destructive_disallow)
6759 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6765 * raise() has a queue depth of 1 -- we ignore all subsequent
6766 * invocations of the raise() action.
6768 if (curthread->t_dtrace_sig == 0)
6769 curthread->t_dtrace_sig = (uint8_t)sig;
6771 curthread->t_sig_check = 1;
6774 struct proc *p = curproc;
6776 kern_psignal(p, sig);
6782 dtrace_action_stop(void)
6784 if (dtrace_destructive_disallow)
6788 if (!curthread->t_dtrace_stop) {
6789 curthread->t_dtrace_stop = 1;
6790 curthread->t_sig_check = 1;
6794 struct proc *p = curproc;
6796 kern_psignal(p, SIGSTOP);
6802 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6805 volatile uint16_t *flags;
6809 cpu_t *cpu = &solaris_cpu[curcpu];
6812 if (dtrace_destructive_disallow)
6815 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6817 now = dtrace_gethrtime();
6819 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6821 * We need to advance the mark to the current time.
6823 cpu->cpu_dtrace_chillmark = now;
6824 cpu->cpu_dtrace_chilled = 0;
6828 * Now check to see if the requested chill time would take us over
6829 * the maximum amount of time allowed in the chill interval. (Or
6830 * worse, if the calculation itself induces overflow.)
6832 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6833 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6834 *flags |= CPU_DTRACE_ILLOP;
6838 while (dtrace_gethrtime() - now < val)
6842 * Normally, we assure that the value of the variable "timestamp" does
6843 * not change within an ECB. The presence of chill() represents an
6844 * exception to this rule, however.
6846 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6847 cpu->cpu_dtrace_chilled += val;
6851 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6852 uint64_t *buf, uint64_t arg)
6854 int nframes = DTRACE_USTACK_NFRAMES(arg);
6855 int strsize = DTRACE_USTACK_STRSIZE(arg);
6856 uint64_t *pcs = &buf[1], *fps;
6857 char *str = (char *)&pcs[nframes];
6858 int size, offs = 0, i, j;
6859 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6860 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6864 * Should be taking a faster path if string space has not been
6867 ASSERT(strsize != 0);
6870 * We will first allocate some temporary space for the frame pointers.
6872 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6873 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6874 (nframes * sizeof (uint64_t));
6876 if (!DTRACE_INSCRATCH(mstate, size)) {
6878 * Not enough room for our frame pointers -- need to indicate
6879 * that we ran out of scratch space.
6881 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6885 mstate->dtms_scratch_ptr += size;
6886 saved = mstate->dtms_scratch_ptr;
6889 * Now get a stack with both program counters and frame pointers.
6891 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6892 dtrace_getufpstack(buf, fps, nframes + 1);
6893 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6896 * If that faulted, we're cooked.
6898 if (*flags & CPU_DTRACE_FAULT)
6902 * Now we want to walk up the stack, calling the USTACK helper. For
6903 * each iteration, we restore the scratch pointer.
6905 for (i = 0; i < nframes; i++) {
6906 mstate->dtms_scratch_ptr = saved;
6908 if (offs >= strsize)
6911 sym = (char *)(uintptr_t)dtrace_helper(
6912 DTRACE_HELPER_ACTION_USTACK,
6913 mstate, state, pcs[i], fps[i]);
6916 * If we faulted while running the helper, we're going to
6917 * clear the fault and null out the corresponding string.
6919 if (*flags & CPU_DTRACE_FAULT) {
6920 *flags &= ~CPU_DTRACE_FAULT;
6930 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6933 * Now copy in the string that the helper returned to us.
6935 for (j = 0; offs + j < strsize; j++) {
6936 if ((str[offs + j] = sym[j]) == '\0')
6940 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6945 if (offs >= strsize) {
6947 * If we didn't have room for all of the strings, we don't
6948 * abort processing -- this needn't be a fatal error -- but we
6949 * still want to increment a counter (dts_stkstroverflows) to
6950 * allow this condition to be warned about. (If this is from
6951 * a jstack() action, it is easily tuned via jstackstrsize.)
6953 dtrace_error(&state->dts_stkstroverflows);
6956 while (offs < strsize)
6960 mstate->dtms_scratch_ptr = old;
6964 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6965 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6967 volatile uint16_t *flags;
6968 uint64_t val = *valp;
6969 size_t valoffs = *valoffsp;
6971 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6972 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6975 * If this is a string, we're going to only load until we find the zero
6976 * byte -- after which we'll store zero bytes.
6978 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6982 for (s = 0; s < size; s++) {
6983 if (c != '\0' && dtkind == DIF_TF_BYREF) {
6984 c = dtrace_load8(val++);
6985 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6986 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6987 c = dtrace_fuword8((void *)(uintptr_t)val++);
6988 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6989 if (*flags & CPU_DTRACE_FAULT)
6993 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6995 if (c == '\0' && intuple)
7000 while (valoffs < end) {
7001 if (dtkind == DIF_TF_BYREF) {
7002 c = dtrace_load8(val++);
7003 } else if (dtkind == DIF_TF_BYUREF) {
7004 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7005 c = dtrace_fuword8((void *)(uintptr_t)val++);
7006 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7007 if (*flags & CPU_DTRACE_FAULT)
7011 DTRACE_STORE(uint8_t, tomax,
7017 *valoffsp = valoffs;
7021 * If you're looking for the epicenter of DTrace, you just found it. This
7022 * is the function called by the provider to fire a probe -- from which all
7023 * subsequent probe-context DTrace activity emanates.
7026 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7027 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7029 processorid_t cpuid;
7030 dtrace_icookie_t cookie;
7031 dtrace_probe_t *probe;
7032 dtrace_mstate_t mstate;
7034 dtrace_action_t *act;
7038 volatile uint16_t *flags;
7041 if (panicstr != NULL)
7046 * Kick out immediately if this CPU is still being born (in which case
7047 * curthread will be set to -1) or the current thread can't allow
7048 * probes in its current context.
7050 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7054 cookie = dtrace_interrupt_disable();
7055 probe = dtrace_probes[id - 1];
7057 onintr = CPU_ON_INTR(CPU);
7059 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7060 probe->dtpr_predcache == curthread->t_predcache) {
7062 * We have hit in the predicate cache; we know that
7063 * this predicate would evaluate to be false.
7065 dtrace_interrupt_enable(cookie);
7070 if (panic_quiesce) {
7072 if (panicstr != NULL) {
7075 * We don't trace anything if we're panicking.
7077 dtrace_interrupt_enable(cookie);
7081 now = dtrace_gethrtime();
7082 vtime = dtrace_vtime_references != 0;
7084 if (vtime && curthread->t_dtrace_start)
7085 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7087 mstate.dtms_difo = NULL;
7088 mstate.dtms_probe = probe;
7089 mstate.dtms_strtok = 0;
7090 mstate.dtms_arg[0] = arg0;
7091 mstate.dtms_arg[1] = arg1;
7092 mstate.dtms_arg[2] = arg2;
7093 mstate.dtms_arg[3] = arg3;
7094 mstate.dtms_arg[4] = arg4;
7096 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7098 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7099 dtrace_predicate_t *pred = ecb->dte_predicate;
7100 dtrace_state_t *state = ecb->dte_state;
7101 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7102 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7103 dtrace_vstate_t *vstate = &state->dts_vstate;
7104 dtrace_provider_t *prov = probe->dtpr_provider;
7105 uint64_t tracememsize = 0;
7110 * A little subtlety with the following (seemingly innocuous)
7111 * declaration of the automatic 'val': by looking at the
7112 * code, you might think that it could be declared in the
7113 * action processing loop, below. (That is, it's only used in
7114 * the action processing loop.) However, it must be declared
7115 * out of that scope because in the case of DIF expression
7116 * arguments to aggregating actions, one iteration of the
7117 * action loop will use the last iteration's value.
7121 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7122 mstate.dtms_getf = NULL;
7124 *flags &= ~CPU_DTRACE_ERROR;
7126 if (prov == dtrace_provider) {
7128 * If dtrace itself is the provider of this probe,
7129 * we're only going to continue processing the ECB if
7130 * arg0 (the dtrace_state_t) is equal to the ECB's
7131 * creating state. (This prevents disjoint consumers
7132 * from seeing one another's metaprobes.)
7134 if (arg0 != (uint64_t)(uintptr_t)state)
7138 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7140 * We're not currently active. If our provider isn't
7141 * the dtrace pseudo provider, we're not interested.
7143 if (prov != dtrace_provider)
7147 * Now we must further check if we are in the BEGIN
7148 * probe. If we are, we will only continue processing
7149 * if we're still in WARMUP -- if one BEGIN enabling
7150 * has invoked the exit() action, we don't want to
7151 * evaluate subsequent BEGIN enablings.
7153 if (probe->dtpr_id == dtrace_probeid_begin &&
7154 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7155 ASSERT(state->dts_activity ==
7156 DTRACE_ACTIVITY_DRAINING);
7161 if (ecb->dte_cond) {
7163 * If the dte_cond bits indicate that this
7164 * consumer is only allowed to see user-mode firings
7165 * of this probe, call the provider's dtps_usermode()
7166 * entry point to check that the probe was fired
7167 * while in a user context. Skip this ECB if that's
7170 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7171 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7172 probe->dtpr_id, probe->dtpr_arg) == 0)
7177 * This is more subtle than it looks. We have to be
7178 * absolutely certain that CRED() isn't going to
7179 * change out from under us so it's only legit to
7180 * examine that structure if we're in constrained
7181 * situations. Currently, the only times we'll this
7182 * check is if a non-super-user has enabled the
7183 * profile or syscall providers -- providers that
7184 * allow visibility of all processes. For the
7185 * profile case, the check above will ensure that
7186 * we're examining a user context.
7188 if (ecb->dte_cond & DTRACE_COND_OWNER) {
7191 ecb->dte_state->dts_cred.dcr_cred;
7194 ASSERT(s_cr != NULL);
7196 if ((cr = CRED()) == NULL ||
7197 s_cr->cr_uid != cr->cr_uid ||
7198 s_cr->cr_uid != cr->cr_ruid ||
7199 s_cr->cr_uid != cr->cr_suid ||
7200 s_cr->cr_gid != cr->cr_gid ||
7201 s_cr->cr_gid != cr->cr_rgid ||
7202 s_cr->cr_gid != cr->cr_sgid ||
7203 (proc = ttoproc(curthread)) == NULL ||
7204 (proc->p_flag & SNOCD))
7208 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7211 ecb->dte_state->dts_cred.dcr_cred;
7213 ASSERT(s_cr != NULL);
7215 if ((cr = CRED()) == NULL ||
7216 s_cr->cr_zone->zone_id !=
7217 cr->cr_zone->zone_id)
7223 if (now - state->dts_alive > dtrace_deadman_timeout) {
7225 * We seem to be dead. Unless we (a) have kernel
7226 * destructive permissions (b) have explicitly enabled
7227 * destructive actions and (c) destructive actions have
7228 * not been disabled, we're going to transition into
7229 * the KILLED state, from which no further processing
7230 * on this state will be performed.
7232 if (!dtrace_priv_kernel_destructive(state) ||
7233 !state->dts_cred.dcr_destructive ||
7234 dtrace_destructive_disallow) {
7235 void *activity = &state->dts_activity;
7236 dtrace_activity_t current;
7239 current = state->dts_activity;
7240 } while (dtrace_cas32(activity, current,
7241 DTRACE_ACTIVITY_KILLED) != current);
7247 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7248 ecb->dte_alignment, state, &mstate)) < 0)
7251 tomax = buf->dtb_tomax;
7252 ASSERT(tomax != NULL);
7254 if (ecb->dte_size != 0) {
7255 dtrace_rechdr_t dtrh;
7256 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7257 mstate.dtms_timestamp = dtrace_gethrtime();
7258 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7260 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7261 dtrh.dtrh_epid = ecb->dte_epid;
7262 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7263 mstate.dtms_timestamp);
7264 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7267 mstate.dtms_epid = ecb->dte_epid;
7268 mstate.dtms_present |= DTRACE_MSTATE_EPID;
7270 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7271 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7273 mstate.dtms_access = 0;
7276 dtrace_difo_t *dp = pred->dtp_difo;
7279 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7281 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7282 dtrace_cacheid_t cid = probe->dtpr_predcache;
7284 if (cid != DTRACE_CACHEIDNONE && !onintr) {
7286 * Update the predicate cache...
7288 ASSERT(cid == pred->dtp_cacheid);
7289 curthread->t_predcache = cid;
7296 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7297 act != NULL; act = act->dta_next) {
7300 dtrace_recdesc_t *rec = &act->dta_rec;
7302 size = rec->dtrd_size;
7303 valoffs = offs + rec->dtrd_offset;
7305 if (DTRACEACT_ISAGG(act->dta_kind)) {
7307 dtrace_aggregation_t *agg;
7309 agg = (dtrace_aggregation_t *)act;
7311 if ((dp = act->dta_difo) != NULL)
7312 v = dtrace_dif_emulate(dp,
7313 &mstate, vstate, state);
7315 if (*flags & CPU_DTRACE_ERROR)
7319 * Note that we always pass the expression
7320 * value from the previous iteration of the
7321 * action loop. This value will only be used
7322 * if there is an expression argument to the
7323 * aggregating action, denoted by the
7324 * dtag_hasarg field.
7326 dtrace_aggregate(agg, buf,
7327 offs, aggbuf, v, val);
7331 switch (act->dta_kind) {
7332 case DTRACEACT_STOP:
7333 if (dtrace_priv_proc_destructive(state))
7334 dtrace_action_stop();
7337 case DTRACEACT_BREAKPOINT:
7338 if (dtrace_priv_kernel_destructive(state))
7339 dtrace_action_breakpoint(ecb);
7342 case DTRACEACT_PANIC:
7343 if (dtrace_priv_kernel_destructive(state))
7344 dtrace_action_panic(ecb);
7347 case DTRACEACT_STACK:
7348 if (!dtrace_priv_kernel(state))
7351 dtrace_getpcstack((pc_t *)(tomax + valoffs),
7352 size / sizeof (pc_t), probe->dtpr_aframes,
7353 DTRACE_ANCHORED(probe) ? NULL :
7357 case DTRACEACT_JSTACK:
7358 case DTRACEACT_USTACK:
7359 if (!dtrace_priv_proc(state))
7363 * See comment in DIF_VAR_PID.
7365 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7367 int depth = DTRACE_USTACK_NFRAMES(
7370 dtrace_bzero((void *)(tomax + valoffs),
7371 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7372 + depth * sizeof (uint64_t));
7377 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7378 curproc->p_dtrace_helpers != NULL) {
7380 * This is the slow path -- we have
7381 * allocated string space, and we're
7382 * getting the stack of a process that
7383 * has helpers. Call into a separate
7384 * routine to perform this processing.
7386 dtrace_action_ustack(&mstate, state,
7387 (uint64_t *)(tomax + valoffs),
7392 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7393 dtrace_getupcstack((uint64_t *)
7395 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7396 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7406 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7408 if (*flags & CPU_DTRACE_ERROR)
7411 switch (act->dta_kind) {
7412 case DTRACEACT_SPECULATE: {
7413 dtrace_rechdr_t *dtrh;
7415 ASSERT(buf == &state->dts_buffer[cpuid]);
7416 buf = dtrace_speculation_buffer(state,
7420 *flags |= CPU_DTRACE_DROP;
7424 offs = dtrace_buffer_reserve(buf,
7425 ecb->dte_needed, ecb->dte_alignment,
7429 *flags |= CPU_DTRACE_DROP;
7433 tomax = buf->dtb_tomax;
7434 ASSERT(tomax != NULL);
7436 if (ecb->dte_size == 0)
7439 ASSERT3U(ecb->dte_size, >=,
7440 sizeof (dtrace_rechdr_t));
7441 dtrh = ((void *)(tomax + offs));
7442 dtrh->dtrh_epid = ecb->dte_epid;
7444 * When the speculation is committed, all of
7445 * the records in the speculative buffer will
7446 * have their timestamps set to the commit
7447 * time. Until then, it is set to a sentinel
7448 * value, for debugability.
7450 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7454 case DTRACEACT_PRINTM: {
7455 /* The DIF returns a 'memref'. */
7456 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7458 /* Get the size from the memref. */
7462 * Check if the size exceeds the allocated
7465 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7467 *flags |= CPU_DTRACE_DROP;
7471 /* Store the size in the buffer first. */
7472 DTRACE_STORE(uintptr_t, tomax,
7476 * Offset the buffer address to the start
7479 valoffs += sizeof(uintptr_t);
7482 * Reset to the memory address rather than
7483 * the memref array, then let the BYREF
7484 * code below do the work to store the
7485 * memory data in the buffer.
7491 case DTRACEACT_PRINTT: {
7492 /* The DIF returns a 'typeref'. */
7493 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
7498 * Get the type string length and round it
7499 * up so that the data that follows is
7500 * aligned for easy access.
7502 size_t typs = strlen((char *) typeref[2]) + 1;
7503 typs = roundup(typs, sizeof(uintptr_t));
7506 *Get the size from the typeref using the
7507 * number of elements and the type size.
7509 size = typeref[1] * typeref[3];
7512 * Check if the size exceeds the allocated
7515 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7517 *flags |= CPU_DTRACE_DROP;
7521 /* Store the size in the buffer first. */
7522 DTRACE_STORE(uintptr_t, tomax,
7524 valoffs += sizeof(uintptr_t);
7526 /* Store the type size in the buffer. */
7527 DTRACE_STORE(uintptr_t, tomax,
7528 valoffs, typeref[3]);
7529 valoffs += sizeof(uintptr_t);
7533 for (s = 0; s < typs; s++) {
7535 c = dtrace_load8(val++);
7537 DTRACE_STORE(uint8_t, tomax,
7542 * Reset to the memory address rather than
7543 * the typeref array, then let the BYREF
7544 * code below do the work to store the
7545 * memory data in the buffer.
7551 case DTRACEACT_CHILL:
7552 if (dtrace_priv_kernel_destructive(state))
7553 dtrace_action_chill(&mstate, val);
7556 case DTRACEACT_RAISE:
7557 if (dtrace_priv_proc_destructive(state))
7558 dtrace_action_raise(val);
7561 case DTRACEACT_COMMIT:
7565 * We need to commit our buffer state.
7568 buf->dtb_offset = offs + ecb->dte_size;
7569 buf = &state->dts_buffer[cpuid];
7570 dtrace_speculation_commit(state, cpuid, val);
7574 case DTRACEACT_DISCARD:
7575 dtrace_speculation_discard(state, cpuid, val);
7578 case DTRACEACT_DIFEXPR:
7579 case DTRACEACT_LIBACT:
7580 case DTRACEACT_PRINTF:
7581 case DTRACEACT_PRINTA:
7582 case DTRACEACT_SYSTEM:
7583 case DTRACEACT_FREOPEN:
7584 case DTRACEACT_TRACEMEM:
7587 case DTRACEACT_TRACEMEM_DYNSIZE:
7593 if (!dtrace_priv_kernel(state))
7597 case DTRACEACT_USYM:
7598 case DTRACEACT_UMOD:
7599 case DTRACEACT_UADDR: {
7601 struct pid *pid = curthread->t_procp->p_pidp;
7604 if (!dtrace_priv_proc(state))
7607 DTRACE_STORE(uint64_t, tomax,
7609 valoffs, (uint64_t)pid->pid_id);
7611 valoffs, (uint64_t) curproc->p_pid);
7613 DTRACE_STORE(uint64_t, tomax,
7614 valoffs + sizeof (uint64_t), val);
7619 case DTRACEACT_EXIT: {
7621 * For the exit action, we are going to attempt
7622 * to atomically set our activity to be
7623 * draining. If this fails (either because
7624 * another CPU has beat us to the exit action,
7625 * or because our current activity is something
7626 * other than ACTIVE or WARMUP), we will
7627 * continue. This assures that the exit action
7628 * can be successfully recorded at most once
7629 * when we're in the ACTIVE state. If we're
7630 * encountering the exit() action while in
7631 * COOLDOWN, however, we want to honor the new
7632 * status code. (We know that we're the only
7633 * thread in COOLDOWN, so there is no race.)
7635 void *activity = &state->dts_activity;
7636 dtrace_activity_t current = state->dts_activity;
7638 if (current == DTRACE_ACTIVITY_COOLDOWN)
7641 if (current != DTRACE_ACTIVITY_WARMUP)
7642 current = DTRACE_ACTIVITY_ACTIVE;
7644 if (dtrace_cas32(activity, current,
7645 DTRACE_ACTIVITY_DRAINING) != current) {
7646 *flags |= CPU_DTRACE_DROP;
7657 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7658 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7659 uintptr_t end = valoffs + size;
7661 if (tracememsize != 0 &&
7662 valoffs + tracememsize < end) {
7663 end = valoffs + tracememsize;
7667 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7668 !dtrace_vcanload((void *)(uintptr_t)val,
7669 &dp->dtdo_rtype, &mstate, vstate))
7672 dtrace_store_by_ref(dp, tomax, size, &valoffs,
7673 &val, end, act->dta_intuple,
7674 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7675 DIF_TF_BYREF: DIF_TF_BYUREF);
7683 case sizeof (uint8_t):
7684 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7686 case sizeof (uint16_t):
7687 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7689 case sizeof (uint32_t):
7690 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7692 case sizeof (uint64_t):
7693 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7697 * Any other size should have been returned by
7698 * reference, not by value.
7705 if (*flags & CPU_DTRACE_DROP)
7708 if (*flags & CPU_DTRACE_FAULT) {
7710 dtrace_action_t *err;
7714 if (probe->dtpr_id == dtrace_probeid_error) {
7716 * There's nothing we can do -- we had an
7717 * error on the error probe. We bump an
7718 * error counter to at least indicate that
7719 * this condition happened.
7721 dtrace_error(&state->dts_dblerrors);
7727 * Before recursing on dtrace_probe(), we
7728 * need to explicitly clear out our start
7729 * time to prevent it from being accumulated
7730 * into t_dtrace_vtime.
7732 curthread->t_dtrace_start = 0;
7736 * Iterate over the actions to figure out which action
7737 * we were processing when we experienced the error.
7738 * Note that act points _past_ the faulting action; if
7739 * act is ecb->dte_action, the fault was in the
7740 * predicate, if it's ecb->dte_action->dta_next it's
7741 * in action #1, and so on.
7743 for (err = ecb->dte_action, ndx = 0;
7744 err != act; err = err->dta_next, ndx++)
7747 dtrace_probe_error(state, ecb->dte_epid, ndx,
7748 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7749 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7750 cpu_core[cpuid].cpuc_dtrace_illval);
7756 buf->dtb_offset = offs + ecb->dte_size;
7760 curthread->t_dtrace_start = dtrace_gethrtime();
7762 dtrace_interrupt_enable(cookie);
7766 * DTrace Probe Hashing Functions
7768 * The functions in this section (and indeed, the functions in remaining
7769 * sections) are not _called_ from probe context. (Any exceptions to this are
7770 * marked with a "Note:".) Rather, they are called from elsewhere in the
7771 * DTrace framework to look-up probes in, add probes to and remove probes from
7772 * the DTrace probe hashes. (Each probe is hashed by each element of the
7773 * probe tuple -- allowing for fast lookups, regardless of what was
7777 dtrace_hash_str(const char *p)
7783 hval = (hval << 4) + *p++;
7784 if ((g = (hval & 0xf0000000)) != 0)
7791 static dtrace_hash_t *
7792 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7794 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7796 hash->dth_stroffs = stroffs;
7797 hash->dth_nextoffs = nextoffs;
7798 hash->dth_prevoffs = prevoffs;
7801 hash->dth_mask = hash->dth_size - 1;
7803 hash->dth_tab = kmem_zalloc(hash->dth_size *
7804 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7810 dtrace_hash_destroy(dtrace_hash_t *hash)
7815 for (i = 0; i < hash->dth_size; i++)
7816 ASSERT(hash->dth_tab[i] == NULL);
7819 kmem_free(hash->dth_tab,
7820 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7821 kmem_free(hash, sizeof (dtrace_hash_t));
7825 dtrace_hash_resize(dtrace_hash_t *hash)
7827 int size = hash->dth_size, i, ndx;
7828 int new_size = hash->dth_size << 1;
7829 int new_mask = new_size - 1;
7830 dtrace_hashbucket_t **new_tab, *bucket, *next;
7832 ASSERT((new_size & new_mask) == 0);
7834 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7836 for (i = 0; i < size; i++) {
7837 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7838 dtrace_probe_t *probe = bucket->dthb_chain;
7840 ASSERT(probe != NULL);
7841 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7843 next = bucket->dthb_next;
7844 bucket->dthb_next = new_tab[ndx];
7845 new_tab[ndx] = bucket;
7849 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7850 hash->dth_tab = new_tab;
7851 hash->dth_size = new_size;
7852 hash->dth_mask = new_mask;
7856 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7858 int hashval = DTRACE_HASHSTR(hash, new);
7859 int ndx = hashval & hash->dth_mask;
7860 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7861 dtrace_probe_t **nextp, **prevp;
7863 for (; bucket != NULL; bucket = bucket->dthb_next) {
7864 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7868 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7869 dtrace_hash_resize(hash);
7870 dtrace_hash_add(hash, new);
7874 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7875 bucket->dthb_next = hash->dth_tab[ndx];
7876 hash->dth_tab[ndx] = bucket;
7877 hash->dth_nbuckets++;
7880 nextp = DTRACE_HASHNEXT(hash, new);
7881 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7882 *nextp = bucket->dthb_chain;
7884 if (bucket->dthb_chain != NULL) {
7885 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7886 ASSERT(*prevp == NULL);
7890 bucket->dthb_chain = new;
7894 static dtrace_probe_t *
7895 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7897 int hashval = DTRACE_HASHSTR(hash, template);
7898 int ndx = hashval & hash->dth_mask;
7899 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7901 for (; bucket != NULL; bucket = bucket->dthb_next) {
7902 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7903 return (bucket->dthb_chain);
7910 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7912 int hashval = DTRACE_HASHSTR(hash, template);
7913 int ndx = hashval & hash->dth_mask;
7914 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7916 for (; bucket != NULL; bucket = bucket->dthb_next) {
7917 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7918 return (bucket->dthb_len);
7925 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7927 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7928 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7930 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7931 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7934 * Find the bucket that we're removing this probe from.
7936 for (; bucket != NULL; bucket = bucket->dthb_next) {
7937 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7941 ASSERT(bucket != NULL);
7943 if (*prevp == NULL) {
7944 if (*nextp == NULL) {
7946 * The removed probe was the only probe on this
7947 * bucket; we need to remove the bucket.
7949 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7951 ASSERT(bucket->dthb_chain == probe);
7955 hash->dth_tab[ndx] = bucket->dthb_next;
7957 while (b->dthb_next != bucket)
7959 b->dthb_next = bucket->dthb_next;
7962 ASSERT(hash->dth_nbuckets > 0);
7963 hash->dth_nbuckets--;
7964 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7968 bucket->dthb_chain = *nextp;
7970 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7974 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7978 * DTrace Utility Functions
7980 * These are random utility functions that are _not_ called from probe context.
7983 dtrace_badattr(const dtrace_attribute_t *a)
7985 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7986 a->dtat_data > DTRACE_STABILITY_MAX ||
7987 a->dtat_class > DTRACE_CLASS_MAX);
7991 * Return a duplicate copy of a string. If the specified string is NULL,
7992 * this function returns a zero-length string.
7995 dtrace_strdup(const char *str)
7997 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8000 (void) strcpy(new, str);
8005 #define DTRACE_ISALPHA(c) \
8006 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8009 dtrace_badname(const char *s)
8013 if (s == NULL || (c = *s++) == '\0')
8016 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8019 while ((c = *s++) != '\0') {
8020 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8021 c != '-' && c != '_' && c != '.' && c != '`')
8029 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8034 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8036 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8038 priv = DTRACE_PRIV_ALL;
8040 *uidp = crgetuid(cr);
8041 *zoneidp = crgetzoneid(cr);
8044 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8045 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8046 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8047 priv |= DTRACE_PRIV_USER;
8048 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8049 priv |= DTRACE_PRIV_PROC;
8050 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8051 priv |= DTRACE_PRIV_OWNER;
8052 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8053 priv |= DTRACE_PRIV_ZONEOWNER;
8056 priv = DTRACE_PRIV_ALL;
8062 #ifdef DTRACE_ERRDEBUG
8064 dtrace_errdebug(const char *str)
8066 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8069 mutex_enter(&dtrace_errlock);
8070 dtrace_errlast = str;
8071 dtrace_errthread = curthread;
8073 while (occupied++ < DTRACE_ERRHASHSZ) {
8074 if (dtrace_errhash[hval].dter_msg == str) {
8075 dtrace_errhash[hval].dter_count++;
8079 if (dtrace_errhash[hval].dter_msg != NULL) {
8080 hval = (hval + 1) % DTRACE_ERRHASHSZ;
8084 dtrace_errhash[hval].dter_msg = str;
8085 dtrace_errhash[hval].dter_count = 1;
8089 panic("dtrace: undersized error hash");
8091 mutex_exit(&dtrace_errlock);
8096 * DTrace Matching Functions
8098 * These functions are used to match groups of probes, given some elements of
8099 * a probe tuple, or some globbed expressions for elements of a probe tuple.
8102 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8105 if (priv != DTRACE_PRIV_ALL) {
8106 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8107 uint32_t match = priv & ppriv;
8110 * No PRIV_DTRACE_* privileges...
8112 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8113 DTRACE_PRIV_KERNEL)) == 0)
8117 * No matching bits, but there were bits to match...
8119 if (match == 0 && ppriv != 0)
8123 * Need to have permissions to the process, but don't...
8125 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8126 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8131 * Need to be in the same zone unless we possess the
8132 * privilege to examine all zones.
8134 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8135 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8144 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8145 * consists of input pattern strings and an ops-vector to evaluate them.
8146 * This function returns >0 for match, 0 for no match, and <0 for error.
8149 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8150 uint32_t priv, uid_t uid, zoneid_t zoneid)
8152 dtrace_provider_t *pvp = prp->dtpr_provider;
8155 if (pvp->dtpv_defunct)
8158 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8161 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8164 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8167 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8170 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8177 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8178 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
8179 * libc's version, the kernel version only applies to 8-bit ASCII strings.
8180 * In addition, all of the recursion cases except for '*' matching have been
8181 * unwound. For '*', we still implement recursive evaluation, but a depth
8182 * counter is maintained and matching is aborted if we recurse too deep.
8183 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8186 dtrace_match_glob(const char *s, const char *p, int depth)
8192 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8196 s = ""; /* treat NULL as empty string */
8205 if ((c = *p++) == '\0')
8206 return (s1 == '\0');
8210 int ok = 0, notflag = 0;
8221 if ((c = *p++) == '\0')
8225 if (c == '-' && lc != '\0' && *p != ']') {
8226 if ((c = *p++) == '\0')
8228 if (c == '\\' && (c = *p++) == '\0')
8232 if (s1 < lc || s1 > c)
8236 } else if (lc <= s1 && s1 <= c)
8239 } else if (c == '\\' && (c = *p++) == '\0')
8242 lc = c; /* save left-hand 'c' for next iteration */
8252 if ((c = *p++) == '\0')
8264 if ((c = *p++) == '\0')
8280 p++; /* consecutive *'s are identical to a single one */
8285 for (s = olds; *s != '\0'; s++) {
8286 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8296 dtrace_match_string(const char *s, const char *p, int depth)
8298 return (s != NULL && strcmp(s, p) == 0);
8303 dtrace_match_nul(const char *s, const char *p, int depth)
8305 return (1); /* always match the empty pattern */
8310 dtrace_match_nonzero(const char *s, const char *p, int depth)
8312 return (s != NULL && s[0] != '\0');
8316 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8317 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8319 dtrace_probe_t template, *probe;
8320 dtrace_hash_t *hash = NULL;
8321 int len, best = INT_MAX, nmatched = 0;
8324 ASSERT(MUTEX_HELD(&dtrace_lock));
8327 * If the probe ID is specified in the key, just lookup by ID and
8328 * invoke the match callback once if a matching probe is found.
8330 if (pkp->dtpk_id != DTRACE_IDNONE) {
8331 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8332 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8333 (void) (*matched)(probe, arg);
8339 template.dtpr_mod = (char *)pkp->dtpk_mod;
8340 template.dtpr_func = (char *)pkp->dtpk_func;
8341 template.dtpr_name = (char *)pkp->dtpk_name;
8344 * We want to find the most distinct of the module name, function
8345 * name, and name. So for each one that is not a glob pattern or
8346 * empty string, we perform a lookup in the corresponding hash and
8347 * use the hash table with the fewest collisions to do our search.
8349 if (pkp->dtpk_mmatch == &dtrace_match_string &&
8350 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8352 hash = dtrace_bymod;
8355 if (pkp->dtpk_fmatch == &dtrace_match_string &&
8356 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8358 hash = dtrace_byfunc;
8361 if (pkp->dtpk_nmatch == &dtrace_match_string &&
8362 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8364 hash = dtrace_byname;
8368 * If we did not select a hash table, iterate over every probe and
8369 * invoke our callback for each one that matches our input probe key.
8372 for (i = 0; i < dtrace_nprobes; i++) {
8373 if ((probe = dtrace_probes[i]) == NULL ||
8374 dtrace_match_probe(probe, pkp, priv, uid,
8380 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8388 * If we selected a hash table, iterate over each probe of the same key
8389 * name and invoke the callback for every probe that matches the other
8390 * attributes of our input probe key.
8392 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8393 probe = *(DTRACE_HASHNEXT(hash, probe))) {
8395 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8400 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8408 * Return the function pointer dtrace_probecmp() should use to compare the
8409 * specified pattern with a string. For NULL or empty patterns, we select
8410 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
8411 * For non-empty non-glob strings, we use dtrace_match_string().
8413 static dtrace_probekey_f *
8414 dtrace_probekey_func(const char *p)
8418 if (p == NULL || *p == '\0')
8419 return (&dtrace_match_nul);
8421 while ((c = *p++) != '\0') {
8422 if (c == '[' || c == '?' || c == '*' || c == '\\')
8423 return (&dtrace_match_glob);
8426 return (&dtrace_match_string);
8430 * Build a probe comparison key for use with dtrace_match_probe() from the
8431 * given probe description. By convention, a null key only matches anchored
8432 * probes: if each field is the empty string, reset dtpk_fmatch to
8433 * dtrace_match_nonzero().
8436 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8438 pkp->dtpk_prov = pdp->dtpd_provider;
8439 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8441 pkp->dtpk_mod = pdp->dtpd_mod;
8442 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8444 pkp->dtpk_func = pdp->dtpd_func;
8445 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8447 pkp->dtpk_name = pdp->dtpd_name;
8448 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8450 pkp->dtpk_id = pdp->dtpd_id;
8452 if (pkp->dtpk_id == DTRACE_IDNONE &&
8453 pkp->dtpk_pmatch == &dtrace_match_nul &&
8454 pkp->dtpk_mmatch == &dtrace_match_nul &&
8455 pkp->dtpk_fmatch == &dtrace_match_nul &&
8456 pkp->dtpk_nmatch == &dtrace_match_nul)
8457 pkp->dtpk_fmatch = &dtrace_match_nonzero;
8461 * DTrace Provider-to-Framework API Functions
8463 * These functions implement much of the Provider-to-Framework API, as
8464 * described in <sys/dtrace.h>. The parts of the API not in this section are
8465 * the functions in the API for probe management (found below), and
8466 * dtrace_probe() itself (found above).
8470 * Register the calling provider with the DTrace framework. This should
8471 * generally be called by DTrace providers in their attach(9E) entry point.
8474 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8475 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8477 dtrace_provider_t *provider;
8479 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8480 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8481 "arguments", name ? name : "<NULL>");
8485 if (name[0] == '\0' || dtrace_badname(name)) {
8486 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8487 "provider name", name);
8491 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8492 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8493 pops->dtps_destroy == NULL ||
8494 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8495 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8496 "provider ops", name);
8500 if (dtrace_badattr(&pap->dtpa_provider) ||
8501 dtrace_badattr(&pap->dtpa_mod) ||
8502 dtrace_badattr(&pap->dtpa_func) ||
8503 dtrace_badattr(&pap->dtpa_name) ||
8504 dtrace_badattr(&pap->dtpa_args)) {
8505 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8506 "provider attributes", name);
8510 if (priv & ~DTRACE_PRIV_ALL) {
8511 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8512 "privilege attributes", name);
8516 if ((priv & DTRACE_PRIV_KERNEL) &&
8517 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8518 pops->dtps_usermode == NULL) {
8519 cmn_err(CE_WARN, "failed to register provider '%s': need "
8520 "dtps_usermode() op for given privilege attributes", name);
8524 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8525 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8526 (void) strcpy(provider->dtpv_name, name);
8528 provider->dtpv_attr = *pap;
8529 provider->dtpv_priv.dtpp_flags = priv;
8531 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8532 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8534 provider->dtpv_pops = *pops;
8536 if (pops->dtps_provide == NULL) {
8537 ASSERT(pops->dtps_provide_module != NULL);
8538 provider->dtpv_pops.dtps_provide =
8539 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8542 if (pops->dtps_provide_module == NULL) {
8543 ASSERT(pops->dtps_provide != NULL);
8544 provider->dtpv_pops.dtps_provide_module =
8545 (void (*)(void *, modctl_t *))dtrace_nullop;
8548 if (pops->dtps_suspend == NULL) {
8549 ASSERT(pops->dtps_resume == NULL);
8550 provider->dtpv_pops.dtps_suspend =
8551 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8552 provider->dtpv_pops.dtps_resume =
8553 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8556 provider->dtpv_arg = arg;
8557 *idp = (dtrace_provider_id_t)provider;
8559 if (pops == &dtrace_provider_ops) {
8560 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8561 ASSERT(MUTEX_HELD(&dtrace_lock));
8562 ASSERT(dtrace_anon.dta_enabling == NULL);
8565 * We make sure that the DTrace provider is at the head of
8566 * the provider chain.
8568 provider->dtpv_next = dtrace_provider;
8569 dtrace_provider = provider;
8573 mutex_enter(&dtrace_provider_lock);
8574 mutex_enter(&dtrace_lock);
8577 * If there is at least one provider registered, we'll add this
8578 * provider after the first provider.
8580 if (dtrace_provider != NULL) {
8581 provider->dtpv_next = dtrace_provider->dtpv_next;
8582 dtrace_provider->dtpv_next = provider;
8584 dtrace_provider = provider;
8587 if (dtrace_retained != NULL) {
8588 dtrace_enabling_provide(provider);
8591 * Now we need to call dtrace_enabling_matchall() -- which
8592 * will acquire cpu_lock and dtrace_lock. We therefore need
8593 * to drop all of our locks before calling into it...
8595 mutex_exit(&dtrace_lock);
8596 mutex_exit(&dtrace_provider_lock);
8597 dtrace_enabling_matchall();
8602 mutex_exit(&dtrace_lock);
8603 mutex_exit(&dtrace_provider_lock);
8609 * Unregister the specified provider from the DTrace framework. This should
8610 * generally be called by DTrace providers in their detach(9E) entry point.
8613 dtrace_unregister(dtrace_provider_id_t id)
8615 dtrace_provider_t *old = (dtrace_provider_t *)id;
8616 dtrace_provider_t *prev = NULL;
8617 int i, self = 0, noreap = 0;
8618 dtrace_probe_t *probe, *first = NULL;
8620 if (old->dtpv_pops.dtps_enable ==
8621 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8623 * If DTrace itself is the provider, we're called with locks
8626 ASSERT(old == dtrace_provider);
8628 ASSERT(dtrace_devi != NULL);
8630 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8631 ASSERT(MUTEX_HELD(&dtrace_lock));
8634 if (dtrace_provider->dtpv_next != NULL) {
8636 * There's another provider here; return failure.
8641 mutex_enter(&dtrace_provider_lock);
8643 mutex_enter(&mod_lock);
8645 mutex_enter(&dtrace_lock);
8649 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8650 * probes, we refuse to let providers slither away, unless this
8651 * provider has already been explicitly invalidated.
8653 if (!old->dtpv_defunct &&
8654 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8655 dtrace_anon.dta_state->dts_necbs > 0))) {
8657 mutex_exit(&dtrace_lock);
8659 mutex_exit(&mod_lock);
8661 mutex_exit(&dtrace_provider_lock);
8667 * Attempt to destroy the probes associated with this provider.
8669 for (i = 0; i < dtrace_nprobes; i++) {
8670 if ((probe = dtrace_probes[i]) == NULL)
8673 if (probe->dtpr_provider != old)
8676 if (probe->dtpr_ecb == NULL)
8680 * If we are trying to unregister a defunct provider, and the
8681 * provider was made defunct within the interval dictated by
8682 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8683 * attempt to reap our enablings. To denote that the provider
8684 * should reattempt to unregister itself at some point in the
8685 * future, we will return a differentiable error code (EAGAIN
8686 * instead of EBUSY) in this case.
8688 if (dtrace_gethrtime() - old->dtpv_defunct >
8689 dtrace_unregister_defunct_reap)
8693 mutex_exit(&dtrace_lock);
8695 mutex_exit(&mod_lock);
8697 mutex_exit(&dtrace_provider_lock);
8703 (void) taskq_dispatch(dtrace_taskq,
8704 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8710 * All of the probes for this provider are disabled; we can safely
8711 * remove all of them from their hash chains and from the probe array.
8713 for (i = 0; i < dtrace_nprobes; i++) {
8714 if ((probe = dtrace_probes[i]) == NULL)
8717 if (probe->dtpr_provider != old)
8720 dtrace_probes[i] = NULL;
8722 dtrace_hash_remove(dtrace_bymod, probe);
8723 dtrace_hash_remove(dtrace_byfunc, probe);
8724 dtrace_hash_remove(dtrace_byname, probe);
8726 if (first == NULL) {
8728 probe->dtpr_nextmod = NULL;
8730 probe->dtpr_nextmod = first;
8736 * The provider's probes have been removed from the hash chains and
8737 * from the probe array. Now issue a dtrace_sync() to be sure that
8738 * everyone has cleared out from any probe array processing.
8742 for (probe = first; probe != NULL; probe = first) {
8743 first = probe->dtpr_nextmod;
8745 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8747 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8748 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8749 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8751 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8753 free_unr(dtrace_arena, probe->dtpr_id);
8755 kmem_free(probe, sizeof (dtrace_probe_t));
8758 if ((prev = dtrace_provider) == old) {
8760 ASSERT(self || dtrace_devi == NULL);
8761 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8763 dtrace_provider = old->dtpv_next;
8765 while (prev != NULL && prev->dtpv_next != old)
8766 prev = prev->dtpv_next;
8769 panic("attempt to unregister non-existent "
8770 "dtrace provider %p\n", (void *)id);
8773 prev->dtpv_next = old->dtpv_next;
8777 mutex_exit(&dtrace_lock);
8779 mutex_exit(&mod_lock);
8781 mutex_exit(&dtrace_provider_lock);
8784 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8785 kmem_free(old, sizeof (dtrace_provider_t));
8791 * Invalidate the specified provider. All subsequent probe lookups for the
8792 * specified provider will fail, but its probes will not be removed.
8795 dtrace_invalidate(dtrace_provider_id_t id)
8797 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8799 ASSERT(pvp->dtpv_pops.dtps_enable !=
8800 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8802 mutex_enter(&dtrace_provider_lock);
8803 mutex_enter(&dtrace_lock);
8805 pvp->dtpv_defunct = dtrace_gethrtime();
8807 mutex_exit(&dtrace_lock);
8808 mutex_exit(&dtrace_provider_lock);
8812 * Indicate whether or not DTrace has attached.
8815 dtrace_attached(void)
8818 * dtrace_provider will be non-NULL iff the DTrace driver has
8819 * attached. (It's non-NULL because DTrace is always itself a
8822 return (dtrace_provider != NULL);
8826 * Remove all the unenabled probes for the given provider. This function is
8827 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8828 * -- just as many of its associated probes as it can.
8831 dtrace_condense(dtrace_provider_id_t id)
8833 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8835 dtrace_probe_t *probe;
8838 * Make sure this isn't the dtrace provider itself.
8840 ASSERT(prov->dtpv_pops.dtps_enable !=
8841 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8843 mutex_enter(&dtrace_provider_lock);
8844 mutex_enter(&dtrace_lock);
8847 * Attempt to destroy the probes associated with this provider.
8849 for (i = 0; i < dtrace_nprobes; i++) {
8850 if ((probe = dtrace_probes[i]) == NULL)
8853 if (probe->dtpr_provider != prov)
8856 if (probe->dtpr_ecb != NULL)
8859 dtrace_probes[i] = NULL;
8861 dtrace_hash_remove(dtrace_bymod, probe);
8862 dtrace_hash_remove(dtrace_byfunc, probe);
8863 dtrace_hash_remove(dtrace_byname, probe);
8865 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8867 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8868 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8869 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8870 kmem_free(probe, sizeof (dtrace_probe_t));
8872 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8874 free_unr(dtrace_arena, i + 1);
8878 mutex_exit(&dtrace_lock);
8879 mutex_exit(&dtrace_provider_lock);
8885 * DTrace Probe Management Functions
8887 * The functions in this section perform the DTrace probe management,
8888 * including functions to create probes, look-up probes, and call into the
8889 * providers to request that probes be provided. Some of these functions are
8890 * in the Provider-to-Framework API; these functions can be identified by the
8891 * fact that they are not declared "static".
8895 * Create a probe with the specified module name, function name, and name.
8898 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8899 const char *func, const char *name, int aframes, void *arg)
8901 dtrace_probe_t *probe, **probes;
8902 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8905 if (provider == dtrace_provider) {
8906 ASSERT(MUTEX_HELD(&dtrace_lock));
8908 mutex_enter(&dtrace_lock);
8912 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8913 VM_BESTFIT | VM_SLEEP);
8915 id = alloc_unr(dtrace_arena);
8917 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8919 probe->dtpr_id = id;
8920 probe->dtpr_gen = dtrace_probegen++;
8921 probe->dtpr_mod = dtrace_strdup(mod);
8922 probe->dtpr_func = dtrace_strdup(func);
8923 probe->dtpr_name = dtrace_strdup(name);
8924 probe->dtpr_arg = arg;
8925 probe->dtpr_aframes = aframes;
8926 probe->dtpr_provider = provider;
8928 dtrace_hash_add(dtrace_bymod, probe);
8929 dtrace_hash_add(dtrace_byfunc, probe);
8930 dtrace_hash_add(dtrace_byname, probe);
8932 if (id - 1 >= dtrace_nprobes) {
8933 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8934 size_t nsize = osize << 1;
8938 ASSERT(dtrace_probes == NULL);
8939 nsize = sizeof (dtrace_probe_t *);
8942 probes = kmem_zalloc(nsize, KM_SLEEP);
8944 if (dtrace_probes == NULL) {
8946 dtrace_probes = probes;
8949 dtrace_probe_t **oprobes = dtrace_probes;
8951 bcopy(oprobes, probes, osize);
8952 dtrace_membar_producer();
8953 dtrace_probes = probes;
8958 * All CPUs are now seeing the new probes array; we can
8959 * safely free the old array.
8961 kmem_free(oprobes, osize);
8962 dtrace_nprobes <<= 1;
8965 ASSERT(id - 1 < dtrace_nprobes);
8968 ASSERT(dtrace_probes[id - 1] == NULL);
8969 dtrace_probes[id - 1] = probe;
8971 if (provider != dtrace_provider)
8972 mutex_exit(&dtrace_lock);
8977 static dtrace_probe_t *
8978 dtrace_probe_lookup_id(dtrace_id_t id)
8980 ASSERT(MUTEX_HELD(&dtrace_lock));
8982 if (id == 0 || id > dtrace_nprobes)
8985 return (dtrace_probes[id - 1]);
8989 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8991 *((dtrace_id_t *)arg) = probe->dtpr_id;
8993 return (DTRACE_MATCH_DONE);
8997 * Look up a probe based on provider and one or more of module name, function
8998 * name and probe name.
9001 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9002 char *func, char *name)
9004 dtrace_probekey_t pkey;
9008 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9009 pkey.dtpk_pmatch = &dtrace_match_string;
9010 pkey.dtpk_mod = mod;
9011 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9012 pkey.dtpk_func = func;
9013 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9014 pkey.dtpk_name = name;
9015 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9016 pkey.dtpk_id = DTRACE_IDNONE;
9018 mutex_enter(&dtrace_lock);
9019 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9020 dtrace_probe_lookup_match, &id);
9021 mutex_exit(&dtrace_lock);
9023 ASSERT(match == 1 || match == 0);
9024 return (match ? id : 0);
9028 * Returns the probe argument associated with the specified probe.
9031 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9033 dtrace_probe_t *probe;
9036 mutex_enter(&dtrace_lock);
9038 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9039 probe->dtpr_provider == (dtrace_provider_t *)id)
9040 rval = probe->dtpr_arg;
9042 mutex_exit(&dtrace_lock);
9048 * Copy a probe into a probe description.
9051 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9053 bzero(pdp, sizeof (dtrace_probedesc_t));
9054 pdp->dtpd_id = prp->dtpr_id;
9056 (void) strncpy(pdp->dtpd_provider,
9057 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9059 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9060 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9061 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9065 * Called to indicate that a probe -- or probes -- should be provided by a
9066 * specfied provider. If the specified description is NULL, the provider will
9067 * be told to provide all of its probes. (This is done whenever a new
9068 * consumer comes along, or whenever a retained enabling is to be matched.) If
9069 * the specified description is non-NULL, the provider is given the
9070 * opportunity to dynamically provide the specified probe, allowing providers
9071 * to support the creation of probes on-the-fly. (So-called _autocreated_
9072 * probes.) If the provider is NULL, the operations will be applied to all
9073 * providers; if the provider is non-NULL the operations will only be applied
9074 * to the specified provider. The dtrace_provider_lock must be held, and the
9075 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9076 * will need to grab the dtrace_lock when it reenters the framework through
9077 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9080 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9087 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9091 prv = dtrace_provider;
9096 * First, call the blanket provide operation.
9098 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9102 * Now call the per-module provide operation. We will grab
9103 * mod_lock to prevent the list from being modified. Note
9104 * that this also prevents the mod_busy bits from changing.
9105 * (mod_busy can only be changed with mod_lock held.)
9107 mutex_enter(&mod_lock);
9111 if (ctl->mod_busy || ctl->mod_mp == NULL)
9114 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9116 } while ((ctl = ctl->mod_next) != &modules);
9118 mutex_exit(&mod_lock);
9120 } while (all && (prv = prv->dtpv_next) != NULL);
9125 * Iterate over each probe, and call the Framework-to-Provider API function
9129 dtrace_probe_foreach(uintptr_t offs)
9131 dtrace_provider_t *prov;
9132 void (*func)(void *, dtrace_id_t, void *);
9133 dtrace_probe_t *probe;
9134 dtrace_icookie_t cookie;
9138 * We disable interrupts to walk through the probe array. This is
9139 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9140 * won't see stale data.
9142 cookie = dtrace_interrupt_disable();
9144 for (i = 0; i < dtrace_nprobes; i++) {
9145 if ((probe = dtrace_probes[i]) == NULL)
9148 if (probe->dtpr_ecb == NULL) {
9150 * This probe isn't enabled -- don't call the function.
9155 prov = probe->dtpr_provider;
9156 func = *((void(**)(void *, dtrace_id_t, void *))
9157 ((uintptr_t)&prov->dtpv_pops + offs));
9159 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9162 dtrace_interrupt_enable(cookie);
9167 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9169 dtrace_probekey_t pkey;
9174 ASSERT(MUTEX_HELD(&dtrace_lock));
9175 dtrace_ecb_create_cache = NULL;
9179 * If we're passed a NULL description, we're being asked to
9180 * create an ECB with a NULL probe.
9182 (void) dtrace_ecb_create_enable(NULL, enab);
9186 dtrace_probekey(desc, &pkey);
9187 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9188 &priv, &uid, &zoneid);
9190 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9195 * DTrace Helper Provider Functions
9198 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9200 attr->dtat_name = DOF_ATTR_NAME(dofattr);
9201 attr->dtat_data = DOF_ATTR_DATA(dofattr);
9202 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9206 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9207 const dof_provider_t *dofprov, char *strtab)
9209 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9210 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9211 dofprov->dofpv_provattr);
9212 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9213 dofprov->dofpv_modattr);
9214 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9215 dofprov->dofpv_funcattr);
9216 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9217 dofprov->dofpv_nameattr);
9218 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9219 dofprov->dofpv_argsattr);
9223 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9225 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9226 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9227 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9228 dof_provider_t *provider;
9230 uint32_t *off, *enoff;
9234 dtrace_helper_provdesc_t dhpv;
9235 dtrace_helper_probedesc_t dhpb;
9236 dtrace_meta_t *meta = dtrace_meta_pid;
9237 dtrace_mops_t *mops = &meta->dtm_mops;
9240 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9241 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9242 provider->dofpv_strtab * dof->dofh_secsize);
9243 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9244 provider->dofpv_probes * dof->dofh_secsize);
9245 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9246 provider->dofpv_prargs * dof->dofh_secsize);
9247 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9248 provider->dofpv_proffs * dof->dofh_secsize);
9250 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9251 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9252 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9256 * See dtrace_helper_provider_validate().
9258 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9259 provider->dofpv_prenoffs != DOF_SECT_NONE) {
9260 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9261 provider->dofpv_prenoffs * dof->dofh_secsize);
9262 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9265 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9268 * Create the provider.
9270 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9272 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9278 * Create the probes.
9280 for (i = 0; i < nprobes; i++) {
9281 probe = (dof_probe_t *)(uintptr_t)(daddr +
9282 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9284 dhpb.dthpb_mod = dhp->dofhp_mod;
9285 dhpb.dthpb_func = strtab + probe->dofpr_func;
9286 dhpb.dthpb_name = strtab + probe->dofpr_name;
9287 dhpb.dthpb_base = probe->dofpr_addr;
9288 dhpb.dthpb_offs = off + probe->dofpr_offidx;
9289 dhpb.dthpb_noffs = probe->dofpr_noffs;
9290 if (enoff != NULL) {
9291 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9292 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9294 dhpb.dthpb_enoffs = NULL;
9295 dhpb.dthpb_nenoffs = 0;
9297 dhpb.dthpb_args = arg + probe->dofpr_argidx;
9298 dhpb.dthpb_nargc = probe->dofpr_nargc;
9299 dhpb.dthpb_xargc = probe->dofpr_xargc;
9300 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9301 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9303 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9308 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9310 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9311 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9314 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9316 for (i = 0; i < dof->dofh_secnum; i++) {
9317 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9318 dof->dofh_secoff + i * dof->dofh_secsize);
9320 if (sec->dofs_type != DOF_SECT_PROVIDER)
9323 dtrace_helper_provide_one(dhp, sec, pid);
9327 * We may have just created probes, so we must now rematch against
9328 * any retained enablings. Note that this call will acquire both
9329 * cpu_lock and dtrace_lock; the fact that we are holding
9330 * dtrace_meta_lock now is what defines the ordering with respect to
9331 * these three locks.
9333 dtrace_enabling_matchall();
9337 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9339 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9340 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9342 dof_provider_t *provider;
9344 dtrace_helper_provdesc_t dhpv;
9345 dtrace_meta_t *meta = dtrace_meta_pid;
9346 dtrace_mops_t *mops = &meta->dtm_mops;
9348 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9349 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9350 provider->dofpv_strtab * dof->dofh_secsize);
9352 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9355 * Create the provider.
9357 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9359 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9365 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9367 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9368 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9371 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9373 for (i = 0; i < dof->dofh_secnum; i++) {
9374 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9375 dof->dofh_secoff + i * dof->dofh_secsize);
9377 if (sec->dofs_type != DOF_SECT_PROVIDER)
9380 dtrace_helper_provider_remove_one(dhp, sec, pid);
9385 * DTrace Meta Provider-to-Framework API Functions
9387 * These functions implement the Meta Provider-to-Framework API, as described
9388 * in <sys/dtrace.h>.
9391 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9392 dtrace_meta_provider_id_t *idp)
9394 dtrace_meta_t *meta;
9395 dtrace_helpers_t *help, *next;
9398 *idp = DTRACE_METAPROVNONE;
9401 * We strictly don't need the name, but we hold onto it for
9402 * debuggability. All hail error queues!
9405 cmn_err(CE_WARN, "failed to register meta-provider: "
9411 mops->dtms_create_probe == NULL ||
9412 mops->dtms_provide_pid == NULL ||
9413 mops->dtms_remove_pid == NULL) {
9414 cmn_err(CE_WARN, "failed to register meta-register %s: "
9415 "invalid ops", name);
9419 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9420 meta->dtm_mops = *mops;
9421 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9422 (void) strcpy(meta->dtm_name, name);
9423 meta->dtm_arg = arg;
9425 mutex_enter(&dtrace_meta_lock);
9426 mutex_enter(&dtrace_lock);
9428 if (dtrace_meta_pid != NULL) {
9429 mutex_exit(&dtrace_lock);
9430 mutex_exit(&dtrace_meta_lock);
9431 cmn_err(CE_WARN, "failed to register meta-register %s: "
9432 "user-land meta-provider exists", name);
9433 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9434 kmem_free(meta, sizeof (dtrace_meta_t));
9438 dtrace_meta_pid = meta;
9439 *idp = (dtrace_meta_provider_id_t)meta;
9442 * If there are providers and probes ready to go, pass them
9443 * off to the new meta provider now.
9446 help = dtrace_deferred_pid;
9447 dtrace_deferred_pid = NULL;
9449 mutex_exit(&dtrace_lock);
9451 while (help != NULL) {
9452 for (i = 0; i < help->dthps_nprovs; i++) {
9453 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9457 next = help->dthps_next;
9458 help->dthps_next = NULL;
9459 help->dthps_prev = NULL;
9460 help->dthps_deferred = 0;
9464 mutex_exit(&dtrace_meta_lock);
9470 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9472 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9474 mutex_enter(&dtrace_meta_lock);
9475 mutex_enter(&dtrace_lock);
9477 if (old == dtrace_meta_pid) {
9478 pp = &dtrace_meta_pid;
9480 panic("attempt to unregister non-existent "
9481 "dtrace meta-provider %p\n", (void *)old);
9484 if (old->dtm_count != 0) {
9485 mutex_exit(&dtrace_lock);
9486 mutex_exit(&dtrace_meta_lock);
9492 mutex_exit(&dtrace_lock);
9493 mutex_exit(&dtrace_meta_lock);
9495 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9496 kmem_free(old, sizeof (dtrace_meta_t));
9503 * DTrace DIF Object Functions
9506 dtrace_difo_err(uint_t pc, const char *format, ...)
9508 if (dtrace_err_verbose) {
9511 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
9512 va_start(alist, format);
9513 (void) vuprintf(format, alist);
9517 #ifdef DTRACE_ERRDEBUG
9518 dtrace_errdebug(format);
9524 * Validate a DTrace DIF object by checking the IR instructions. The following
9525 * rules are currently enforced by dtrace_difo_validate():
9527 * 1. Each instruction must have a valid opcode
9528 * 2. Each register, string, variable, or subroutine reference must be valid
9529 * 3. No instruction can modify register %r0 (must be zero)
9530 * 4. All instruction reserved bits must be set to zero
9531 * 5. The last instruction must be a "ret" instruction
9532 * 6. All branch targets must reference a valid instruction _after_ the branch
9535 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9539 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9543 kcheckload = cr == NULL ||
9544 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9546 dp->dtdo_destructive = 0;
9548 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9549 dif_instr_t instr = dp->dtdo_buf[pc];
9551 uint_t r1 = DIF_INSTR_R1(instr);
9552 uint_t r2 = DIF_INSTR_R2(instr);
9553 uint_t rd = DIF_INSTR_RD(instr);
9554 uint_t rs = DIF_INSTR_RS(instr);
9555 uint_t label = DIF_INSTR_LABEL(instr);
9556 uint_t v = DIF_INSTR_VAR(instr);
9557 uint_t subr = DIF_INSTR_SUBR(instr);
9558 uint_t type = DIF_INSTR_TYPE(instr);
9559 uint_t op = DIF_INSTR_OP(instr);
9577 err += efunc(pc, "invalid register %u\n", r1);
9579 err += efunc(pc, "invalid register %u\n", r2);
9581 err += efunc(pc, "invalid register %u\n", rd);
9583 err += efunc(pc, "cannot write to %r0\n");
9589 err += efunc(pc, "invalid register %u\n", r1);
9591 err += efunc(pc, "non-zero reserved bits\n");
9593 err += efunc(pc, "invalid register %u\n", rd);
9595 err += efunc(pc, "cannot write to %r0\n");
9605 err += efunc(pc, "invalid register %u\n", r1);
9607 err += efunc(pc, "non-zero reserved bits\n");
9609 err += efunc(pc, "invalid register %u\n", rd);
9611 err += efunc(pc, "cannot write to %r0\n");
9613 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9614 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9624 err += efunc(pc, "invalid register %u\n", r1);
9626 err += efunc(pc, "non-zero reserved bits\n");
9628 err += efunc(pc, "invalid register %u\n", rd);
9630 err += efunc(pc, "cannot write to %r0\n");
9640 err += efunc(pc, "invalid register %u\n", r1);
9642 err += efunc(pc, "non-zero reserved bits\n");
9644 err += efunc(pc, "invalid register %u\n", rd);
9646 err += efunc(pc, "cannot write to %r0\n");
9653 err += efunc(pc, "invalid register %u\n", r1);
9655 err += efunc(pc, "non-zero reserved bits\n");
9657 err += efunc(pc, "invalid register %u\n", rd);
9659 err += efunc(pc, "cannot write to 0 address\n");
9664 err += efunc(pc, "invalid register %u\n", r1);
9666 err += efunc(pc, "invalid register %u\n", r2);
9668 err += efunc(pc, "non-zero reserved bits\n");
9672 err += efunc(pc, "invalid register %u\n", r1);
9673 if (r2 != 0 || rd != 0)
9674 err += efunc(pc, "non-zero reserved bits\n");
9687 if (label >= dp->dtdo_len) {
9688 err += efunc(pc, "invalid branch target %u\n",
9692 err += efunc(pc, "backward branch to %u\n",
9697 if (r1 != 0 || r2 != 0)
9698 err += efunc(pc, "non-zero reserved bits\n");
9700 err += efunc(pc, "invalid register %u\n", rd);
9704 case DIF_OP_FLUSHTS:
9705 if (r1 != 0 || r2 != 0 || rd != 0)
9706 err += efunc(pc, "non-zero reserved bits\n");
9709 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9710 err += efunc(pc, "invalid integer ref %u\n",
9711 DIF_INSTR_INTEGER(instr));
9714 err += efunc(pc, "invalid register %u\n", rd);
9716 err += efunc(pc, "cannot write to %r0\n");
9719 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9720 err += efunc(pc, "invalid string ref %u\n",
9721 DIF_INSTR_STRING(instr));
9724 err += efunc(pc, "invalid register %u\n", rd);
9726 err += efunc(pc, "cannot write to %r0\n");
9730 if (r1 > DIF_VAR_ARRAY_MAX)
9731 err += efunc(pc, "invalid array %u\n", r1);
9733 err += efunc(pc, "invalid register %u\n", r2);
9735 err += efunc(pc, "invalid register %u\n", rd);
9737 err += efunc(pc, "cannot write to %r0\n");
9744 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9745 err += efunc(pc, "invalid variable %u\n", v);
9747 err += efunc(pc, "invalid register %u\n", rd);
9749 err += efunc(pc, "cannot write to %r0\n");
9756 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9757 err += efunc(pc, "invalid variable %u\n", v);
9759 err += efunc(pc, "invalid register %u\n", rd);
9762 if (subr > DIF_SUBR_MAX)
9763 err += efunc(pc, "invalid subr %u\n", subr);
9765 err += efunc(pc, "invalid register %u\n", rd);
9767 err += efunc(pc, "cannot write to %r0\n");
9769 if (subr == DIF_SUBR_COPYOUT ||
9770 subr == DIF_SUBR_COPYOUTSTR) {
9771 dp->dtdo_destructive = 1;
9774 if (subr == DIF_SUBR_GETF) {
9776 * If we have a getf() we need to record that
9777 * in our state. Note that our state can be
9778 * NULL if this is a helper -- but in that
9779 * case, the call to getf() is itself illegal,
9780 * and will be caught (slightly later) when
9781 * the helper is validated.
9783 if (vstate->dtvs_state != NULL)
9784 vstate->dtvs_state->dts_getf++;
9789 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9790 err += efunc(pc, "invalid ref type %u\n", type);
9792 err += efunc(pc, "invalid register %u\n", r2);
9794 err += efunc(pc, "invalid register %u\n", rs);
9797 if (type != DIF_TYPE_CTF)
9798 err += efunc(pc, "invalid val type %u\n", type);
9800 err += efunc(pc, "invalid register %u\n", r2);
9802 err += efunc(pc, "invalid register %u\n", rs);
9805 err += efunc(pc, "invalid opcode %u\n",
9806 DIF_INSTR_OP(instr));
9810 if (dp->dtdo_len != 0 &&
9811 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9812 err += efunc(dp->dtdo_len - 1,
9813 "expected 'ret' as last DIF instruction\n");
9816 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9818 * If we're not returning by reference, the size must be either
9819 * 0 or the size of one of the base types.
9821 switch (dp->dtdo_rtype.dtdt_size) {
9823 case sizeof (uint8_t):
9824 case sizeof (uint16_t):
9825 case sizeof (uint32_t):
9826 case sizeof (uint64_t):
9830 err += efunc(dp->dtdo_len - 1, "bad return size\n");
9834 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9835 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9836 dtrace_diftype_t *vt, *et;
9839 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9840 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9841 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9842 err += efunc(i, "unrecognized variable scope %d\n",
9847 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9848 v->dtdv_kind != DIFV_KIND_SCALAR) {
9849 err += efunc(i, "unrecognized variable type %d\n",
9854 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9855 err += efunc(i, "%d exceeds variable id limit\n", id);
9859 if (id < DIF_VAR_OTHER_UBASE)
9863 * For user-defined variables, we need to check that this
9864 * definition is identical to any previous definition that we
9867 ndx = id - DIF_VAR_OTHER_UBASE;
9869 switch (v->dtdv_scope) {
9870 case DIFV_SCOPE_GLOBAL:
9871 if (ndx < vstate->dtvs_nglobals) {
9872 dtrace_statvar_t *svar;
9874 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9875 existing = &svar->dtsv_var;
9880 case DIFV_SCOPE_THREAD:
9881 if (ndx < vstate->dtvs_ntlocals)
9882 existing = &vstate->dtvs_tlocals[ndx];
9885 case DIFV_SCOPE_LOCAL:
9886 if (ndx < vstate->dtvs_nlocals) {
9887 dtrace_statvar_t *svar;
9889 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9890 existing = &svar->dtsv_var;
9898 if (vt->dtdt_flags & DIF_TF_BYREF) {
9899 if (vt->dtdt_size == 0) {
9900 err += efunc(i, "zero-sized variable\n");
9904 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9905 vt->dtdt_size > dtrace_global_maxsize) {
9906 err += efunc(i, "oversized by-ref global\n");
9911 if (existing == NULL || existing->dtdv_id == 0)
9914 ASSERT(existing->dtdv_id == v->dtdv_id);
9915 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9917 if (existing->dtdv_kind != v->dtdv_kind)
9918 err += efunc(i, "%d changed variable kind\n", id);
9920 et = &existing->dtdv_type;
9922 if (vt->dtdt_flags != et->dtdt_flags) {
9923 err += efunc(i, "%d changed variable type flags\n", id);
9927 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9928 err += efunc(i, "%d changed variable type size\n", id);
9937 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9938 * are much more constrained than normal DIFOs. Specifically, they may
9941 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9942 * miscellaneous string routines
9943 * 2. Access DTrace variables other than the args[] array, and the
9944 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9945 * 3. Have thread-local variables.
9946 * 4. Have dynamic variables.
9949 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9951 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9955 for (pc = 0; pc < dp->dtdo_len; pc++) {
9956 dif_instr_t instr = dp->dtdo_buf[pc];
9958 uint_t v = DIF_INSTR_VAR(instr);
9959 uint_t subr = DIF_INSTR_SUBR(instr);
9960 uint_t op = DIF_INSTR_OP(instr);
10015 case DIF_OP_FLUSHTS:
10022 case DIF_OP_PUSHTR:
10023 case DIF_OP_PUSHTV:
10027 if (v >= DIF_VAR_OTHER_UBASE)
10030 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10033 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10034 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10035 v == DIF_VAR_EXECARGS ||
10036 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10037 v == DIF_VAR_UID || v == DIF_VAR_GID)
10040 err += efunc(pc, "illegal variable %u\n", v);
10047 err += efunc(pc, "illegal dynamic variable load\n");
10053 err += efunc(pc, "illegal dynamic variable store\n");
10057 if (subr == DIF_SUBR_ALLOCA ||
10058 subr == DIF_SUBR_BCOPY ||
10059 subr == DIF_SUBR_COPYIN ||
10060 subr == DIF_SUBR_COPYINTO ||
10061 subr == DIF_SUBR_COPYINSTR ||
10062 subr == DIF_SUBR_INDEX ||
10063 subr == DIF_SUBR_INET_NTOA ||
10064 subr == DIF_SUBR_INET_NTOA6 ||
10065 subr == DIF_SUBR_INET_NTOP ||
10066 subr == DIF_SUBR_JSON ||
10067 subr == DIF_SUBR_LLTOSTR ||
10068 subr == DIF_SUBR_STRTOLL ||
10069 subr == DIF_SUBR_RINDEX ||
10070 subr == DIF_SUBR_STRCHR ||
10071 subr == DIF_SUBR_STRJOIN ||
10072 subr == DIF_SUBR_STRRCHR ||
10073 subr == DIF_SUBR_STRSTR ||
10074 subr == DIF_SUBR_HTONS ||
10075 subr == DIF_SUBR_HTONL ||
10076 subr == DIF_SUBR_HTONLL ||
10077 subr == DIF_SUBR_NTOHS ||
10078 subr == DIF_SUBR_NTOHL ||
10079 subr == DIF_SUBR_NTOHLL ||
10080 subr == DIF_SUBR_MEMREF ||
10082 subr == DIF_SUBR_MEMSTR ||
10084 subr == DIF_SUBR_TYPEREF)
10087 err += efunc(pc, "invalid subr %u\n", subr);
10091 err += efunc(pc, "invalid opcode %u\n",
10092 DIF_INSTR_OP(instr));
10100 * Returns 1 if the expression in the DIF object can be cached on a per-thread
10104 dtrace_difo_cacheable(dtrace_difo_t *dp)
10111 for (i = 0; i < dp->dtdo_varlen; i++) {
10112 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10114 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10117 switch (v->dtdv_id) {
10118 case DIF_VAR_CURTHREAD:
10121 case DIF_VAR_EXECARGS:
10122 case DIF_VAR_EXECNAME:
10123 case DIF_VAR_ZONENAME:
10132 * This DIF object may be cacheable. Now we need to look for any
10133 * array loading instructions, any memory loading instructions, or
10134 * any stores to thread-local variables.
10136 for (i = 0; i < dp->dtdo_len; i++) {
10137 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10139 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10140 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10141 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10142 op == DIF_OP_LDGA || op == DIF_OP_STTS)
10150 dtrace_difo_hold(dtrace_difo_t *dp)
10154 ASSERT(MUTEX_HELD(&dtrace_lock));
10157 ASSERT(dp->dtdo_refcnt != 0);
10160 * We need to check this DIF object for references to the variable
10161 * DIF_VAR_VTIMESTAMP.
10163 for (i = 0; i < dp->dtdo_varlen; i++) {
10164 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10166 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10169 if (dtrace_vtime_references++ == 0)
10170 dtrace_vtime_enable();
10175 * This routine calculates the dynamic variable chunksize for a given DIF
10176 * object. The calculation is not fool-proof, and can probably be tricked by
10177 * malicious DIF -- but it works for all compiler-generated DIF. Because this
10178 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10179 * if a dynamic variable size exceeds the chunksize.
10182 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10185 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10186 const dif_instr_t *text = dp->dtdo_buf;
10187 uint_t pc, srd = 0;
10189 size_t size, ksize;
10192 for (pc = 0; pc < dp->dtdo_len; pc++) {
10193 dif_instr_t instr = text[pc];
10194 uint_t op = DIF_INSTR_OP(instr);
10195 uint_t rd = DIF_INSTR_RD(instr);
10196 uint_t r1 = DIF_INSTR_R1(instr);
10200 dtrace_key_t *key = tupregs;
10204 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10209 key = &tupregs[DIF_DTR_NREGS];
10210 key[0].dttk_size = 0;
10211 key[1].dttk_size = 0;
10213 scope = DIFV_SCOPE_THREAD;
10220 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10221 key[nkeys++].dttk_size = 0;
10223 key[nkeys++].dttk_size = 0;
10225 if (op == DIF_OP_STTAA) {
10226 scope = DIFV_SCOPE_THREAD;
10228 scope = DIFV_SCOPE_GLOBAL;
10233 case DIF_OP_PUSHTR:
10234 if (ttop == DIF_DTR_NREGS)
10237 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10239 * If the register for the size of the "pushtr"
10240 * is %r0 (or the value is 0) and the type is
10241 * a string, we'll use the system-wide default
10244 tupregs[ttop++].dttk_size =
10245 dtrace_strsize_default;
10250 tupregs[ttop++].dttk_size = sval;
10255 case DIF_OP_PUSHTV:
10256 if (ttop == DIF_DTR_NREGS)
10259 tupregs[ttop++].dttk_size = 0;
10262 case DIF_OP_FLUSHTS:
10279 * We have a dynamic variable allocation; calculate its size.
10281 for (ksize = 0, i = 0; i < nkeys; i++)
10282 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10284 size = sizeof (dtrace_dynvar_t);
10285 size += sizeof (dtrace_key_t) * (nkeys - 1);
10289 * Now we need to determine the size of the stored data.
10291 id = DIF_INSTR_VAR(instr);
10293 for (i = 0; i < dp->dtdo_varlen; i++) {
10294 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10296 if (v->dtdv_id == id && v->dtdv_scope == scope) {
10297 size += v->dtdv_type.dtdt_size;
10302 if (i == dp->dtdo_varlen)
10306 * We have the size. If this is larger than the chunk size
10307 * for our dynamic variable state, reset the chunk size.
10309 size = P2ROUNDUP(size, sizeof (uint64_t));
10311 if (size > vstate->dtvs_dynvars.dtds_chunksize)
10312 vstate->dtvs_dynvars.dtds_chunksize = size;
10317 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10319 int i, oldsvars, osz, nsz, otlocals, ntlocals;
10322 ASSERT(MUTEX_HELD(&dtrace_lock));
10323 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10325 for (i = 0; i < dp->dtdo_varlen; i++) {
10326 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10327 dtrace_statvar_t *svar, ***svarp = NULL;
10329 uint8_t scope = v->dtdv_scope;
10332 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10335 id -= DIF_VAR_OTHER_UBASE;
10338 case DIFV_SCOPE_THREAD:
10339 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10340 dtrace_difv_t *tlocals;
10342 if ((ntlocals = (otlocals << 1)) == 0)
10345 osz = otlocals * sizeof (dtrace_difv_t);
10346 nsz = ntlocals * sizeof (dtrace_difv_t);
10348 tlocals = kmem_zalloc(nsz, KM_SLEEP);
10351 bcopy(vstate->dtvs_tlocals,
10353 kmem_free(vstate->dtvs_tlocals, osz);
10356 vstate->dtvs_tlocals = tlocals;
10357 vstate->dtvs_ntlocals = ntlocals;
10360 vstate->dtvs_tlocals[id] = *v;
10363 case DIFV_SCOPE_LOCAL:
10364 np = &vstate->dtvs_nlocals;
10365 svarp = &vstate->dtvs_locals;
10367 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10368 dsize = NCPU * (v->dtdv_type.dtdt_size +
10369 sizeof (uint64_t));
10371 dsize = NCPU * sizeof (uint64_t);
10375 case DIFV_SCOPE_GLOBAL:
10376 np = &vstate->dtvs_nglobals;
10377 svarp = &vstate->dtvs_globals;
10379 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10380 dsize = v->dtdv_type.dtdt_size +
10389 while (id >= (oldsvars = *np)) {
10390 dtrace_statvar_t **statics;
10391 int newsvars, oldsize, newsize;
10393 if ((newsvars = (oldsvars << 1)) == 0)
10396 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10397 newsize = newsvars * sizeof (dtrace_statvar_t *);
10399 statics = kmem_zalloc(newsize, KM_SLEEP);
10401 if (oldsize != 0) {
10402 bcopy(*svarp, statics, oldsize);
10403 kmem_free(*svarp, oldsize);
10410 if ((svar = (*svarp)[id]) == NULL) {
10411 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10412 svar->dtsv_var = *v;
10414 if ((svar->dtsv_size = dsize) != 0) {
10415 svar->dtsv_data = (uint64_t)(uintptr_t)
10416 kmem_zalloc(dsize, KM_SLEEP);
10419 (*svarp)[id] = svar;
10422 svar->dtsv_refcnt++;
10425 dtrace_difo_chunksize(dp, vstate);
10426 dtrace_difo_hold(dp);
10429 static dtrace_difo_t *
10430 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10432 dtrace_difo_t *new;
10435 ASSERT(dp->dtdo_buf != NULL);
10436 ASSERT(dp->dtdo_refcnt != 0);
10438 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10440 ASSERT(dp->dtdo_buf != NULL);
10441 sz = dp->dtdo_len * sizeof (dif_instr_t);
10442 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10443 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10444 new->dtdo_len = dp->dtdo_len;
10446 if (dp->dtdo_strtab != NULL) {
10447 ASSERT(dp->dtdo_strlen != 0);
10448 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10449 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10450 new->dtdo_strlen = dp->dtdo_strlen;
10453 if (dp->dtdo_inttab != NULL) {
10454 ASSERT(dp->dtdo_intlen != 0);
10455 sz = dp->dtdo_intlen * sizeof (uint64_t);
10456 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10457 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10458 new->dtdo_intlen = dp->dtdo_intlen;
10461 if (dp->dtdo_vartab != NULL) {
10462 ASSERT(dp->dtdo_varlen != 0);
10463 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10464 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10465 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10466 new->dtdo_varlen = dp->dtdo_varlen;
10469 dtrace_difo_init(new, vstate);
10474 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10478 ASSERT(dp->dtdo_refcnt == 0);
10480 for (i = 0; i < dp->dtdo_varlen; i++) {
10481 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10482 dtrace_statvar_t *svar, **svarp = NULL;
10484 uint8_t scope = v->dtdv_scope;
10488 case DIFV_SCOPE_THREAD:
10491 case DIFV_SCOPE_LOCAL:
10492 np = &vstate->dtvs_nlocals;
10493 svarp = vstate->dtvs_locals;
10496 case DIFV_SCOPE_GLOBAL:
10497 np = &vstate->dtvs_nglobals;
10498 svarp = vstate->dtvs_globals;
10505 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10508 id -= DIF_VAR_OTHER_UBASE;
10512 ASSERT(svar != NULL);
10513 ASSERT(svar->dtsv_refcnt > 0);
10515 if (--svar->dtsv_refcnt > 0)
10518 if (svar->dtsv_size != 0) {
10519 ASSERT(svar->dtsv_data != 0);
10520 kmem_free((void *)(uintptr_t)svar->dtsv_data,
10524 kmem_free(svar, sizeof (dtrace_statvar_t));
10528 if (dp->dtdo_buf != NULL)
10529 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10530 if (dp->dtdo_inttab != NULL)
10531 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10532 if (dp->dtdo_strtab != NULL)
10533 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10534 if (dp->dtdo_vartab != NULL)
10535 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10537 kmem_free(dp, sizeof (dtrace_difo_t));
10541 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10545 ASSERT(MUTEX_HELD(&dtrace_lock));
10546 ASSERT(dp->dtdo_refcnt != 0);
10548 for (i = 0; i < dp->dtdo_varlen; i++) {
10549 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10551 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10554 ASSERT(dtrace_vtime_references > 0);
10555 if (--dtrace_vtime_references == 0)
10556 dtrace_vtime_disable();
10559 if (--dp->dtdo_refcnt == 0)
10560 dtrace_difo_destroy(dp, vstate);
10564 * DTrace Format Functions
10567 dtrace_format_add(dtrace_state_t *state, char *str)
10570 uint16_t ndx, len = strlen(str) + 1;
10572 fmt = kmem_zalloc(len, KM_SLEEP);
10573 bcopy(str, fmt, len);
10575 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10576 if (state->dts_formats[ndx] == NULL) {
10577 state->dts_formats[ndx] = fmt;
10582 if (state->dts_nformats == USHRT_MAX) {
10584 * This is only likely if a denial-of-service attack is being
10585 * attempted. As such, it's okay to fail silently here.
10587 kmem_free(fmt, len);
10592 * For simplicity, we always resize the formats array to be exactly the
10593 * number of formats.
10595 ndx = state->dts_nformats++;
10596 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10598 if (state->dts_formats != NULL) {
10600 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10601 kmem_free(state->dts_formats, ndx * sizeof (char *));
10604 state->dts_formats = new;
10605 state->dts_formats[ndx] = fmt;
10611 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10615 ASSERT(state->dts_formats != NULL);
10616 ASSERT(format <= state->dts_nformats);
10617 ASSERT(state->dts_formats[format - 1] != NULL);
10619 fmt = state->dts_formats[format - 1];
10620 kmem_free(fmt, strlen(fmt) + 1);
10621 state->dts_formats[format - 1] = NULL;
10625 dtrace_format_destroy(dtrace_state_t *state)
10629 if (state->dts_nformats == 0) {
10630 ASSERT(state->dts_formats == NULL);
10634 ASSERT(state->dts_formats != NULL);
10636 for (i = 0; i < state->dts_nformats; i++) {
10637 char *fmt = state->dts_formats[i];
10642 kmem_free(fmt, strlen(fmt) + 1);
10645 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10646 state->dts_nformats = 0;
10647 state->dts_formats = NULL;
10651 * DTrace Predicate Functions
10653 static dtrace_predicate_t *
10654 dtrace_predicate_create(dtrace_difo_t *dp)
10656 dtrace_predicate_t *pred;
10658 ASSERT(MUTEX_HELD(&dtrace_lock));
10659 ASSERT(dp->dtdo_refcnt != 0);
10661 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10662 pred->dtp_difo = dp;
10663 pred->dtp_refcnt = 1;
10665 if (!dtrace_difo_cacheable(dp))
10668 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10670 * This is only theoretically possible -- we have had 2^32
10671 * cacheable predicates on this machine. We cannot allow any
10672 * more predicates to become cacheable: as unlikely as it is,
10673 * there may be a thread caching a (now stale) predicate cache
10674 * ID. (N.B.: the temptation is being successfully resisted to
10675 * have this cmn_err() "Holy shit -- we executed this code!")
10680 pred->dtp_cacheid = dtrace_predcache_id++;
10686 dtrace_predicate_hold(dtrace_predicate_t *pred)
10688 ASSERT(MUTEX_HELD(&dtrace_lock));
10689 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10690 ASSERT(pred->dtp_refcnt > 0);
10692 pred->dtp_refcnt++;
10696 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10698 dtrace_difo_t *dp = pred->dtp_difo;
10700 ASSERT(MUTEX_HELD(&dtrace_lock));
10701 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10702 ASSERT(pred->dtp_refcnt > 0);
10704 if (--pred->dtp_refcnt == 0) {
10705 dtrace_difo_release(pred->dtp_difo, vstate);
10706 kmem_free(pred, sizeof (dtrace_predicate_t));
10711 * DTrace Action Description Functions
10713 static dtrace_actdesc_t *
10714 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10715 uint64_t uarg, uint64_t arg)
10717 dtrace_actdesc_t *act;
10720 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10721 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10724 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10725 act->dtad_kind = kind;
10726 act->dtad_ntuple = ntuple;
10727 act->dtad_uarg = uarg;
10728 act->dtad_arg = arg;
10729 act->dtad_refcnt = 1;
10735 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10737 ASSERT(act->dtad_refcnt >= 1);
10738 act->dtad_refcnt++;
10742 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10744 dtrace_actkind_t kind = act->dtad_kind;
10747 ASSERT(act->dtad_refcnt >= 1);
10749 if (--act->dtad_refcnt != 0)
10752 if ((dp = act->dtad_difo) != NULL)
10753 dtrace_difo_release(dp, vstate);
10755 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10756 char *str = (char *)(uintptr_t)act->dtad_arg;
10759 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10760 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10764 kmem_free(str, strlen(str) + 1);
10767 kmem_free(act, sizeof (dtrace_actdesc_t));
10771 * DTrace ECB Functions
10773 static dtrace_ecb_t *
10774 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10777 dtrace_epid_t epid;
10779 ASSERT(MUTEX_HELD(&dtrace_lock));
10781 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10782 ecb->dte_predicate = NULL;
10783 ecb->dte_probe = probe;
10786 * The default size is the size of the default action: recording
10789 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10790 ecb->dte_alignment = sizeof (dtrace_epid_t);
10792 epid = state->dts_epid++;
10794 if (epid - 1 >= state->dts_necbs) {
10795 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10796 int necbs = state->dts_necbs << 1;
10798 ASSERT(epid == state->dts_necbs + 1);
10801 ASSERT(oecbs == NULL);
10805 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10808 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10810 dtrace_membar_producer();
10811 state->dts_ecbs = ecbs;
10813 if (oecbs != NULL) {
10815 * If this state is active, we must dtrace_sync()
10816 * before we can free the old dts_ecbs array: we're
10817 * coming in hot, and there may be active ring
10818 * buffer processing (which indexes into the dts_ecbs
10819 * array) on another CPU.
10821 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10824 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10827 dtrace_membar_producer();
10828 state->dts_necbs = necbs;
10831 ecb->dte_state = state;
10833 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10834 dtrace_membar_producer();
10835 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10841 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10843 dtrace_probe_t *probe = ecb->dte_probe;
10845 ASSERT(MUTEX_HELD(&cpu_lock));
10846 ASSERT(MUTEX_HELD(&dtrace_lock));
10847 ASSERT(ecb->dte_next == NULL);
10849 if (probe == NULL) {
10851 * This is the NULL probe -- there's nothing to do.
10856 if (probe->dtpr_ecb == NULL) {
10857 dtrace_provider_t *prov = probe->dtpr_provider;
10860 * We're the first ECB on this probe.
10862 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10864 if (ecb->dte_predicate != NULL)
10865 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10867 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10868 probe->dtpr_id, probe->dtpr_arg);
10871 * This probe is already active. Swing the last pointer to
10872 * point to the new ECB, and issue a dtrace_sync() to assure
10873 * that all CPUs have seen the change.
10875 ASSERT(probe->dtpr_ecb_last != NULL);
10876 probe->dtpr_ecb_last->dte_next = ecb;
10877 probe->dtpr_ecb_last = ecb;
10878 probe->dtpr_predcache = 0;
10885 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10887 dtrace_action_t *act;
10888 uint32_t curneeded = UINT32_MAX;
10889 uint32_t aggbase = UINT32_MAX;
10892 * If we record anything, we always record the dtrace_rechdr_t. (And
10893 * we always record it first.)
10895 ecb->dte_size = sizeof (dtrace_rechdr_t);
10896 ecb->dte_alignment = sizeof (dtrace_epid_t);
10898 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10899 dtrace_recdesc_t *rec = &act->dta_rec;
10900 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10902 ecb->dte_alignment = MAX(ecb->dte_alignment,
10903 rec->dtrd_alignment);
10905 if (DTRACEACT_ISAGG(act->dta_kind)) {
10906 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10908 ASSERT(rec->dtrd_size != 0);
10909 ASSERT(agg->dtag_first != NULL);
10910 ASSERT(act->dta_prev->dta_intuple);
10911 ASSERT(aggbase != UINT32_MAX);
10912 ASSERT(curneeded != UINT32_MAX);
10914 agg->dtag_base = aggbase;
10916 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10917 rec->dtrd_offset = curneeded;
10918 curneeded += rec->dtrd_size;
10919 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10921 aggbase = UINT32_MAX;
10922 curneeded = UINT32_MAX;
10923 } else if (act->dta_intuple) {
10924 if (curneeded == UINT32_MAX) {
10926 * This is the first record in a tuple. Align
10927 * curneeded to be at offset 4 in an 8-byte
10930 ASSERT(act->dta_prev == NULL ||
10931 !act->dta_prev->dta_intuple);
10932 ASSERT3U(aggbase, ==, UINT32_MAX);
10933 curneeded = P2PHASEUP(ecb->dte_size,
10934 sizeof (uint64_t), sizeof (dtrace_aggid_t));
10936 aggbase = curneeded - sizeof (dtrace_aggid_t);
10937 ASSERT(IS_P2ALIGNED(aggbase,
10938 sizeof (uint64_t)));
10940 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10941 rec->dtrd_offset = curneeded;
10942 curneeded += rec->dtrd_size;
10944 /* tuples must be followed by an aggregation */
10945 ASSERT(act->dta_prev == NULL ||
10946 !act->dta_prev->dta_intuple);
10948 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10949 rec->dtrd_alignment);
10950 rec->dtrd_offset = ecb->dte_size;
10951 ecb->dte_size += rec->dtrd_size;
10952 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10956 if ((act = ecb->dte_action) != NULL &&
10957 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10958 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10960 * If the size is still sizeof (dtrace_rechdr_t), then all
10961 * actions store no data; set the size to 0.
10966 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10967 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10968 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10972 static dtrace_action_t *
10973 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10975 dtrace_aggregation_t *agg;
10976 size_t size = sizeof (uint64_t);
10977 int ntuple = desc->dtad_ntuple;
10978 dtrace_action_t *act;
10979 dtrace_recdesc_t *frec;
10980 dtrace_aggid_t aggid;
10981 dtrace_state_t *state = ecb->dte_state;
10983 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10984 agg->dtag_ecb = ecb;
10986 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10988 switch (desc->dtad_kind) {
10989 case DTRACEAGG_MIN:
10990 agg->dtag_initial = INT64_MAX;
10991 agg->dtag_aggregate = dtrace_aggregate_min;
10994 case DTRACEAGG_MAX:
10995 agg->dtag_initial = INT64_MIN;
10996 agg->dtag_aggregate = dtrace_aggregate_max;
10999 case DTRACEAGG_COUNT:
11000 agg->dtag_aggregate = dtrace_aggregate_count;
11003 case DTRACEAGG_QUANTIZE:
11004 agg->dtag_aggregate = dtrace_aggregate_quantize;
11005 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11009 case DTRACEAGG_LQUANTIZE: {
11010 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11011 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11013 agg->dtag_initial = desc->dtad_arg;
11014 agg->dtag_aggregate = dtrace_aggregate_lquantize;
11016 if (step == 0 || levels == 0)
11019 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11023 case DTRACEAGG_LLQUANTIZE: {
11024 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11025 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11026 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11027 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11030 agg->dtag_initial = desc->dtad_arg;
11031 agg->dtag_aggregate = dtrace_aggregate_llquantize;
11033 if (factor < 2 || low >= high || nsteps < factor)
11037 * Now check that the number of steps evenly divides a power
11038 * of the factor. (This assures both integer bucket size and
11039 * linearity within each magnitude.)
11041 for (v = factor; v < nsteps; v *= factor)
11044 if ((v % nsteps) || (nsteps % factor))
11047 size = (dtrace_aggregate_llquantize_bucket(factor,
11048 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11052 case DTRACEAGG_AVG:
11053 agg->dtag_aggregate = dtrace_aggregate_avg;
11054 size = sizeof (uint64_t) * 2;
11057 case DTRACEAGG_STDDEV:
11058 agg->dtag_aggregate = dtrace_aggregate_stddev;
11059 size = sizeof (uint64_t) * 4;
11062 case DTRACEAGG_SUM:
11063 agg->dtag_aggregate = dtrace_aggregate_sum;
11070 agg->dtag_action.dta_rec.dtrd_size = size;
11076 * We must make sure that we have enough actions for the n-tuple.
11078 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11079 if (DTRACEACT_ISAGG(act->dta_kind))
11082 if (--ntuple == 0) {
11084 * This is the action with which our n-tuple begins.
11086 agg->dtag_first = act;
11092 * This n-tuple is short by ntuple elements. Return failure.
11094 ASSERT(ntuple != 0);
11096 kmem_free(agg, sizeof (dtrace_aggregation_t));
11101 * If the last action in the tuple has a size of zero, it's actually
11102 * an expression argument for the aggregating action.
11104 ASSERT(ecb->dte_action_last != NULL);
11105 act = ecb->dte_action_last;
11107 if (act->dta_kind == DTRACEACT_DIFEXPR) {
11108 ASSERT(act->dta_difo != NULL);
11110 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11111 agg->dtag_hasarg = 1;
11115 * We need to allocate an id for this aggregation.
11118 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11119 VM_BESTFIT | VM_SLEEP);
11121 aggid = alloc_unr(state->dts_aggid_arena);
11124 if (aggid - 1 >= state->dts_naggregations) {
11125 dtrace_aggregation_t **oaggs = state->dts_aggregations;
11126 dtrace_aggregation_t **aggs;
11127 int naggs = state->dts_naggregations << 1;
11128 int onaggs = state->dts_naggregations;
11130 ASSERT(aggid == state->dts_naggregations + 1);
11133 ASSERT(oaggs == NULL);
11137 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11139 if (oaggs != NULL) {
11140 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11141 kmem_free(oaggs, onaggs * sizeof (*aggs));
11144 state->dts_aggregations = aggs;
11145 state->dts_naggregations = naggs;
11148 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11149 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11151 frec = &agg->dtag_first->dta_rec;
11152 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11153 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11155 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11156 ASSERT(!act->dta_intuple);
11157 act->dta_intuple = 1;
11160 return (&agg->dtag_action);
11164 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11166 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11167 dtrace_state_t *state = ecb->dte_state;
11168 dtrace_aggid_t aggid = agg->dtag_id;
11170 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11172 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11174 free_unr(state->dts_aggid_arena, aggid);
11177 ASSERT(state->dts_aggregations[aggid - 1] == agg);
11178 state->dts_aggregations[aggid - 1] = NULL;
11180 kmem_free(agg, sizeof (dtrace_aggregation_t));
11184 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11186 dtrace_action_t *action, *last;
11187 dtrace_difo_t *dp = desc->dtad_difo;
11188 uint32_t size = 0, align = sizeof (uint8_t), mask;
11189 uint16_t format = 0;
11190 dtrace_recdesc_t *rec;
11191 dtrace_state_t *state = ecb->dte_state;
11192 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11193 uint64_t arg = desc->dtad_arg;
11195 ASSERT(MUTEX_HELD(&dtrace_lock));
11196 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11198 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11200 * If this is an aggregating action, there must be neither
11201 * a speculate nor a commit on the action chain.
11203 dtrace_action_t *act;
11205 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11206 if (act->dta_kind == DTRACEACT_COMMIT)
11209 if (act->dta_kind == DTRACEACT_SPECULATE)
11213 action = dtrace_ecb_aggregation_create(ecb, desc);
11215 if (action == NULL)
11218 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11219 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11220 dp != NULL && dp->dtdo_destructive)) {
11221 state->dts_destructive = 1;
11224 switch (desc->dtad_kind) {
11225 case DTRACEACT_PRINTF:
11226 case DTRACEACT_PRINTA:
11227 case DTRACEACT_SYSTEM:
11228 case DTRACEACT_FREOPEN:
11229 case DTRACEACT_DIFEXPR:
11231 * We know that our arg is a string -- turn it into a
11235 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11236 desc->dtad_kind == DTRACEACT_DIFEXPR);
11241 ASSERT(arg > KERNELBASE);
11243 format = dtrace_format_add(state,
11244 (char *)(uintptr_t)arg);
11248 case DTRACEACT_LIBACT:
11249 case DTRACEACT_TRACEMEM:
11250 case DTRACEACT_TRACEMEM_DYNSIZE:
11254 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11257 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11258 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11261 size = opt[DTRACEOPT_STRSIZE];
11266 case DTRACEACT_STACK:
11267 if ((nframes = arg) == 0) {
11268 nframes = opt[DTRACEOPT_STACKFRAMES];
11269 ASSERT(nframes > 0);
11273 size = nframes * sizeof (pc_t);
11276 case DTRACEACT_JSTACK:
11277 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11278 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11280 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11281 nframes = opt[DTRACEOPT_JSTACKFRAMES];
11283 arg = DTRACE_USTACK_ARG(nframes, strsize);
11286 case DTRACEACT_USTACK:
11287 if (desc->dtad_kind != DTRACEACT_JSTACK &&
11288 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11289 strsize = DTRACE_USTACK_STRSIZE(arg);
11290 nframes = opt[DTRACEOPT_USTACKFRAMES];
11291 ASSERT(nframes > 0);
11292 arg = DTRACE_USTACK_ARG(nframes, strsize);
11296 * Save a slot for the pid.
11298 size = (nframes + 1) * sizeof (uint64_t);
11299 size += DTRACE_USTACK_STRSIZE(arg);
11300 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11304 case DTRACEACT_SYM:
11305 case DTRACEACT_MOD:
11306 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11307 sizeof (uint64_t)) ||
11308 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11312 case DTRACEACT_USYM:
11313 case DTRACEACT_UMOD:
11314 case DTRACEACT_UADDR:
11316 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11317 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11321 * We have a slot for the pid, plus a slot for the
11322 * argument. To keep things simple (aligned with
11323 * bitness-neutral sizing), we store each as a 64-bit
11326 size = 2 * sizeof (uint64_t);
11329 case DTRACEACT_STOP:
11330 case DTRACEACT_BREAKPOINT:
11331 case DTRACEACT_PANIC:
11334 case DTRACEACT_CHILL:
11335 case DTRACEACT_DISCARD:
11336 case DTRACEACT_RAISE:
11341 case DTRACEACT_EXIT:
11343 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11344 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11348 case DTRACEACT_SPECULATE:
11349 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11355 state->dts_speculates = 1;
11358 case DTRACEACT_PRINTM:
11359 size = dp->dtdo_rtype.dtdt_size;
11362 case DTRACEACT_PRINTT:
11363 size = dp->dtdo_rtype.dtdt_size;
11366 case DTRACEACT_COMMIT: {
11367 dtrace_action_t *act = ecb->dte_action;
11369 for (; act != NULL; act = act->dta_next) {
11370 if (act->dta_kind == DTRACEACT_COMMIT)
11383 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11385 * If this is a data-storing action or a speculate,
11386 * we must be sure that there isn't a commit on the
11389 dtrace_action_t *act = ecb->dte_action;
11391 for (; act != NULL; act = act->dta_next) {
11392 if (act->dta_kind == DTRACEACT_COMMIT)
11397 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11398 action->dta_rec.dtrd_size = size;
11401 action->dta_refcnt = 1;
11402 rec = &action->dta_rec;
11403 size = rec->dtrd_size;
11405 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11406 if (!(size & mask)) {
11412 action->dta_kind = desc->dtad_kind;
11414 if ((action->dta_difo = dp) != NULL)
11415 dtrace_difo_hold(dp);
11417 rec->dtrd_action = action->dta_kind;
11418 rec->dtrd_arg = arg;
11419 rec->dtrd_uarg = desc->dtad_uarg;
11420 rec->dtrd_alignment = (uint16_t)align;
11421 rec->dtrd_format = format;
11423 if ((last = ecb->dte_action_last) != NULL) {
11424 ASSERT(ecb->dte_action != NULL);
11425 action->dta_prev = last;
11426 last->dta_next = action;
11428 ASSERT(ecb->dte_action == NULL);
11429 ecb->dte_action = action;
11432 ecb->dte_action_last = action;
11438 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11440 dtrace_action_t *act = ecb->dte_action, *next;
11441 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11445 if (act != NULL && act->dta_refcnt > 1) {
11446 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11449 for (; act != NULL; act = next) {
11450 next = act->dta_next;
11451 ASSERT(next != NULL || act == ecb->dte_action_last);
11452 ASSERT(act->dta_refcnt == 1);
11454 if ((format = act->dta_rec.dtrd_format) != 0)
11455 dtrace_format_remove(ecb->dte_state, format);
11457 if ((dp = act->dta_difo) != NULL)
11458 dtrace_difo_release(dp, vstate);
11460 if (DTRACEACT_ISAGG(act->dta_kind)) {
11461 dtrace_ecb_aggregation_destroy(ecb, act);
11463 kmem_free(act, sizeof (dtrace_action_t));
11468 ecb->dte_action = NULL;
11469 ecb->dte_action_last = NULL;
11474 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11477 * We disable the ECB by removing it from its probe.
11479 dtrace_ecb_t *pecb, *prev = NULL;
11480 dtrace_probe_t *probe = ecb->dte_probe;
11482 ASSERT(MUTEX_HELD(&dtrace_lock));
11484 if (probe == NULL) {
11486 * This is the NULL probe; there is nothing to disable.
11491 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11497 ASSERT(pecb != NULL);
11499 if (prev == NULL) {
11500 probe->dtpr_ecb = ecb->dte_next;
11502 prev->dte_next = ecb->dte_next;
11505 if (ecb == probe->dtpr_ecb_last) {
11506 ASSERT(ecb->dte_next == NULL);
11507 probe->dtpr_ecb_last = prev;
11511 * The ECB has been disconnected from the probe; now sync to assure
11512 * that all CPUs have seen the change before returning.
11516 if (probe->dtpr_ecb == NULL) {
11518 * That was the last ECB on the probe; clear the predicate
11519 * cache ID for the probe, disable it and sync one more time
11520 * to assure that we'll never hit it again.
11522 dtrace_provider_t *prov = probe->dtpr_provider;
11524 ASSERT(ecb->dte_next == NULL);
11525 ASSERT(probe->dtpr_ecb_last == NULL);
11526 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11527 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11528 probe->dtpr_id, probe->dtpr_arg);
11532 * There is at least one ECB remaining on the probe. If there
11533 * is _exactly_ one, set the probe's predicate cache ID to be
11534 * the predicate cache ID of the remaining ECB.
11536 ASSERT(probe->dtpr_ecb_last != NULL);
11537 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11539 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11540 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11542 ASSERT(probe->dtpr_ecb->dte_next == NULL);
11545 probe->dtpr_predcache = p->dtp_cacheid;
11548 ecb->dte_next = NULL;
11553 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11555 dtrace_state_t *state = ecb->dte_state;
11556 dtrace_vstate_t *vstate = &state->dts_vstate;
11557 dtrace_predicate_t *pred;
11558 dtrace_epid_t epid = ecb->dte_epid;
11560 ASSERT(MUTEX_HELD(&dtrace_lock));
11561 ASSERT(ecb->dte_next == NULL);
11562 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11564 if ((pred = ecb->dte_predicate) != NULL)
11565 dtrace_predicate_release(pred, vstate);
11567 dtrace_ecb_action_remove(ecb);
11569 ASSERT(state->dts_ecbs[epid - 1] == ecb);
11570 state->dts_ecbs[epid - 1] = NULL;
11572 kmem_free(ecb, sizeof (dtrace_ecb_t));
11575 static dtrace_ecb_t *
11576 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11577 dtrace_enabling_t *enab)
11580 dtrace_predicate_t *pred;
11581 dtrace_actdesc_t *act;
11582 dtrace_provider_t *prov;
11583 dtrace_ecbdesc_t *desc = enab->dten_current;
11585 ASSERT(MUTEX_HELD(&dtrace_lock));
11586 ASSERT(state != NULL);
11588 ecb = dtrace_ecb_add(state, probe);
11589 ecb->dte_uarg = desc->dted_uarg;
11591 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11592 dtrace_predicate_hold(pred);
11593 ecb->dte_predicate = pred;
11596 if (probe != NULL) {
11598 * If the provider shows more leg than the consumer is old
11599 * enough to see, we need to enable the appropriate implicit
11600 * predicate bits to prevent the ecb from activating at
11603 * Providers specifying DTRACE_PRIV_USER at register time
11604 * are stating that they need the /proc-style privilege
11605 * model to be enforced, and this is what DTRACE_COND_OWNER
11606 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11608 prov = probe->dtpr_provider;
11609 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11610 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11611 ecb->dte_cond |= DTRACE_COND_OWNER;
11613 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11614 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11615 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11618 * If the provider shows us kernel innards and the user
11619 * is lacking sufficient privilege, enable the
11620 * DTRACE_COND_USERMODE implicit predicate.
11622 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11623 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11624 ecb->dte_cond |= DTRACE_COND_USERMODE;
11627 if (dtrace_ecb_create_cache != NULL) {
11629 * If we have a cached ecb, we'll use its action list instead
11630 * of creating our own (saving both time and space).
11632 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11633 dtrace_action_t *act = cached->dte_action;
11636 ASSERT(act->dta_refcnt > 0);
11638 ecb->dte_action = act;
11639 ecb->dte_action_last = cached->dte_action_last;
11640 ecb->dte_needed = cached->dte_needed;
11641 ecb->dte_size = cached->dte_size;
11642 ecb->dte_alignment = cached->dte_alignment;
11648 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11649 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11650 dtrace_ecb_destroy(ecb);
11655 dtrace_ecb_resize(ecb);
11657 return (dtrace_ecb_create_cache = ecb);
11661 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11664 dtrace_enabling_t *enab = arg;
11665 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11667 ASSERT(state != NULL);
11669 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11671 * This probe was created in a generation for which this
11672 * enabling has previously created ECBs; we don't want to
11673 * enable it again, so just kick out.
11675 return (DTRACE_MATCH_NEXT);
11678 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11679 return (DTRACE_MATCH_DONE);
11681 dtrace_ecb_enable(ecb);
11682 return (DTRACE_MATCH_NEXT);
11685 static dtrace_ecb_t *
11686 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11690 ASSERT(MUTEX_HELD(&dtrace_lock));
11692 if (id == 0 || id > state->dts_necbs)
11695 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11696 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11698 return (state->dts_ecbs[id - 1]);
11701 static dtrace_aggregation_t *
11702 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11704 dtrace_aggregation_t *agg;
11706 ASSERT(MUTEX_HELD(&dtrace_lock));
11708 if (id == 0 || id > state->dts_naggregations)
11711 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11712 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11713 agg->dtag_id == id);
11715 return (state->dts_aggregations[id - 1]);
11719 * DTrace Buffer Functions
11721 * The following functions manipulate DTrace buffers. Most of these functions
11722 * are called in the context of establishing or processing consumer state;
11723 * exceptions are explicitly noted.
11727 * Note: called from cross call context. This function switches the two
11728 * buffers on a given CPU. The atomicity of this operation is assured by
11729 * disabling interrupts while the actual switch takes place; the disabling of
11730 * interrupts serializes the execution with any execution of dtrace_probe() on
11734 dtrace_buffer_switch(dtrace_buffer_t *buf)
11736 caddr_t tomax = buf->dtb_tomax;
11737 caddr_t xamot = buf->dtb_xamot;
11738 dtrace_icookie_t cookie;
11741 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11742 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11744 cookie = dtrace_interrupt_disable();
11745 now = dtrace_gethrtime();
11746 buf->dtb_tomax = xamot;
11747 buf->dtb_xamot = tomax;
11748 buf->dtb_xamot_drops = buf->dtb_drops;
11749 buf->dtb_xamot_offset = buf->dtb_offset;
11750 buf->dtb_xamot_errors = buf->dtb_errors;
11751 buf->dtb_xamot_flags = buf->dtb_flags;
11752 buf->dtb_offset = 0;
11753 buf->dtb_drops = 0;
11754 buf->dtb_errors = 0;
11755 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11756 buf->dtb_interval = now - buf->dtb_switched;
11757 buf->dtb_switched = now;
11758 dtrace_interrupt_enable(cookie);
11762 * Note: called from cross call context. This function activates a buffer
11763 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11764 * is guaranteed by the disabling of interrupts.
11767 dtrace_buffer_activate(dtrace_state_t *state)
11769 dtrace_buffer_t *buf;
11770 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11772 buf = &state->dts_buffer[curcpu];
11774 if (buf->dtb_tomax != NULL) {
11776 * We might like to assert that the buffer is marked inactive,
11777 * but this isn't necessarily true: the buffer for the CPU
11778 * that processes the BEGIN probe has its buffer activated
11779 * manually. In this case, we take the (harmless) action
11780 * re-clearing the bit INACTIVE bit.
11782 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11785 dtrace_interrupt_enable(cookie);
11789 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11790 processorid_t cpu, int *factor)
11795 dtrace_buffer_t *buf;
11796 int allocated = 0, desired = 0;
11799 ASSERT(MUTEX_HELD(&cpu_lock));
11800 ASSERT(MUTEX_HELD(&dtrace_lock));
11804 if (size > dtrace_nonroot_maxsize &&
11805 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11811 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11814 buf = &bufs[cp->cpu_id];
11817 * If there is already a buffer allocated for this CPU, it
11818 * is only possible that this is a DR event. In this case,
11820 if (buf->dtb_tomax != NULL) {
11821 ASSERT(buf->dtb_size == size);
11825 ASSERT(buf->dtb_xamot == NULL);
11827 if ((buf->dtb_tomax = kmem_zalloc(size,
11828 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11831 buf->dtb_size = size;
11832 buf->dtb_flags = flags;
11833 buf->dtb_offset = 0;
11834 buf->dtb_drops = 0;
11836 if (flags & DTRACEBUF_NOSWITCH)
11839 if ((buf->dtb_xamot = kmem_zalloc(size,
11840 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11842 } while ((cp = cp->cpu_next) != cpu_list);
11850 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11853 buf = &bufs[cp->cpu_id];
11856 if (buf->dtb_xamot != NULL) {
11857 ASSERT(buf->dtb_tomax != NULL);
11858 ASSERT(buf->dtb_size == size);
11859 kmem_free(buf->dtb_xamot, size);
11863 if (buf->dtb_tomax != NULL) {
11864 ASSERT(buf->dtb_size == size);
11865 kmem_free(buf->dtb_tomax, size);
11869 buf->dtb_tomax = NULL;
11870 buf->dtb_xamot = NULL;
11872 } while ((cp = cp->cpu_next) != cpu_list);
11877 #if defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
11879 * FreeBSD isn't good at limiting the amount of memory we
11880 * ask to malloc, so let's place a limit here before trying
11881 * to do something that might well end in tears at bedtime.
11883 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
11887 ASSERT(MUTEX_HELD(&dtrace_lock));
11889 if (cpu != DTRACE_CPUALL && cpu != i)
11895 * If there is already a buffer allocated for this CPU, it
11896 * is only possible that this is a DR event. In this case,
11897 * the buffer size must match our specified size.
11899 if (buf->dtb_tomax != NULL) {
11900 ASSERT(buf->dtb_size == size);
11904 ASSERT(buf->dtb_xamot == NULL);
11906 if ((buf->dtb_tomax = kmem_zalloc(size,
11907 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11910 buf->dtb_size = size;
11911 buf->dtb_flags = flags;
11912 buf->dtb_offset = 0;
11913 buf->dtb_drops = 0;
11915 if (flags & DTRACEBUF_NOSWITCH)
11918 if ((buf->dtb_xamot = kmem_zalloc(size,
11919 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11927 * Error allocating memory, so free the buffers that were
11928 * allocated before the failed allocation.
11931 if (cpu != DTRACE_CPUALL && cpu != i)
11937 if (buf->dtb_xamot != NULL) {
11938 ASSERT(buf->dtb_tomax != NULL);
11939 ASSERT(buf->dtb_size == size);
11940 kmem_free(buf->dtb_xamot, size);
11944 if (buf->dtb_tomax != NULL) {
11945 ASSERT(buf->dtb_size == size);
11946 kmem_free(buf->dtb_tomax, size);
11950 buf->dtb_tomax = NULL;
11951 buf->dtb_xamot = NULL;
11956 *factor = desired / (allocated > 0 ? allocated : 1);
11962 * Note: called from probe context. This function just increments the drop
11963 * count on a buffer. It has been made a function to allow for the
11964 * possibility of understanding the source of mysterious drop counts. (A
11965 * problem for which one may be particularly disappointed that DTrace cannot
11966 * be used to understand DTrace.)
11969 dtrace_buffer_drop(dtrace_buffer_t *buf)
11975 * Note: called from probe context. This function is called to reserve space
11976 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
11977 * mstate. Returns the new offset in the buffer, or a negative value if an
11978 * error has occurred.
11981 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11982 dtrace_state_t *state, dtrace_mstate_t *mstate)
11984 intptr_t offs = buf->dtb_offset, soffs;
11989 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11992 if ((tomax = buf->dtb_tomax) == NULL) {
11993 dtrace_buffer_drop(buf);
11997 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11998 while (offs & (align - 1)) {
12000 * Assert that our alignment is off by a number which
12001 * is itself sizeof (uint32_t) aligned.
12003 ASSERT(!((align - (offs & (align - 1))) &
12004 (sizeof (uint32_t) - 1)));
12005 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12006 offs += sizeof (uint32_t);
12009 if ((soffs = offs + needed) > buf->dtb_size) {
12010 dtrace_buffer_drop(buf);
12014 if (mstate == NULL)
12017 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12018 mstate->dtms_scratch_size = buf->dtb_size - soffs;
12019 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12024 if (buf->dtb_flags & DTRACEBUF_FILL) {
12025 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12026 (buf->dtb_flags & DTRACEBUF_FULL))
12031 total = needed + (offs & (align - 1));
12034 * For a ring buffer, life is quite a bit more complicated. Before
12035 * we can store any padding, we need to adjust our wrapping offset.
12036 * (If we've never before wrapped or we're not about to, no adjustment
12039 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12040 offs + total > buf->dtb_size) {
12041 woffs = buf->dtb_xamot_offset;
12043 if (offs + total > buf->dtb_size) {
12045 * We can't fit in the end of the buffer. First, a
12046 * sanity check that we can fit in the buffer at all.
12048 if (total > buf->dtb_size) {
12049 dtrace_buffer_drop(buf);
12054 * We're going to be storing at the top of the buffer,
12055 * so now we need to deal with the wrapped offset. We
12056 * only reset our wrapped offset to 0 if it is
12057 * currently greater than the current offset. If it
12058 * is less than the current offset, it is because a
12059 * previous allocation induced a wrap -- but the
12060 * allocation didn't subsequently take the space due
12061 * to an error or false predicate evaluation. In this
12062 * case, we'll just leave the wrapped offset alone: if
12063 * the wrapped offset hasn't been advanced far enough
12064 * for this allocation, it will be adjusted in the
12067 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12075 * Now we know that we're going to be storing to the
12076 * top of the buffer and that there is room for us
12077 * there. We need to clear the buffer from the current
12078 * offset to the end (there may be old gunk there).
12080 while (offs < buf->dtb_size)
12084 * We need to set our offset to zero. And because we
12085 * are wrapping, we need to set the bit indicating as
12086 * much. We can also adjust our needed space back
12087 * down to the space required by the ECB -- we know
12088 * that the top of the buffer is aligned.
12092 buf->dtb_flags |= DTRACEBUF_WRAPPED;
12095 * There is room for us in the buffer, so we simply
12096 * need to check the wrapped offset.
12098 if (woffs < offs) {
12100 * The wrapped offset is less than the offset.
12101 * This can happen if we allocated buffer space
12102 * that induced a wrap, but then we didn't
12103 * subsequently take the space due to an error
12104 * or false predicate evaluation. This is
12105 * okay; we know that _this_ allocation isn't
12106 * going to induce a wrap. We still can't
12107 * reset the wrapped offset to be zero,
12108 * however: the space may have been trashed in
12109 * the previous failed probe attempt. But at
12110 * least the wrapped offset doesn't need to
12111 * be adjusted at all...
12117 while (offs + total > woffs) {
12118 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12121 if (epid == DTRACE_EPIDNONE) {
12122 size = sizeof (uint32_t);
12124 ASSERT3U(epid, <=, state->dts_necbs);
12125 ASSERT(state->dts_ecbs[epid - 1] != NULL);
12127 size = state->dts_ecbs[epid - 1]->dte_size;
12130 ASSERT(woffs + size <= buf->dtb_size);
12133 if (woffs + size == buf->dtb_size) {
12135 * We've reached the end of the buffer; we want
12136 * to set the wrapped offset to 0 and break
12137 * out. However, if the offs is 0, then we're
12138 * in a strange edge-condition: the amount of
12139 * space that we want to reserve plus the size
12140 * of the record that we're overwriting is
12141 * greater than the size of the buffer. This
12142 * is problematic because if we reserve the
12143 * space but subsequently don't consume it (due
12144 * to a failed predicate or error) the wrapped
12145 * offset will be 0 -- yet the EPID at offset 0
12146 * will not be committed. This situation is
12147 * relatively easy to deal with: if we're in
12148 * this case, the buffer is indistinguishable
12149 * from one that hasn't wrapped; we need only
12150 * finish the job by clearing the wrapped bit,
12151 * explicitly setting the offset to be 0, and
12152 * zero'ing out the old data in the buffer.
12155 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12156 buf->dtb_offset = 0;
12159 while (woffs < buf->dtb_size)
12160 tomax[woffs++] = 0;
12171 * We have a wrapped offset. It may be that the wrapped offset
12172 * has become zero -- that's okay.
12174 buf->dtb_xamot_offset = woffs;
12179 * Now we can plow the buffer with any necessary padding.
12181 while (offs & (align - 1)) {
12183 * Assert that our alignment is off by a number which
12184 * is itself sizeof (uint32_t) aligned.
12186 ASSERT(!((align - (offs & (align - 1))) &
12187 (sizeof (uint32_t) - 1)));
12188 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12189 offs += sizeof (uint32_t);
12192 if (buf->dtb_flags & DTRACEBUF_FILL) {
12193 if (offs + needed > buf->dtb_size - state->dts_reserve) {
12194 buf->dtb_flags |= DTRACEBUF_FULL;
12199 if (mstate == NULL)
12203 * For ring buffers and fill buffers, the scratch space is always
12204 * the inactive buffer.
12206 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12207 mstate->dtms_scratch_size = buf->dtb_size;
12208 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12214 dtrace_buffer_polish(dtrace_buffer_t *buf)
12216 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12217 ASSERT(MUTEX_HELD(&dtrace_lock));
12219 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12223 * We need to polish the ring buffer. There are three cases:
12225 * - The first (and presumably most common) is that there is no gap
12226 * between the buffer offset and the wrapped offset. In this case,
12227 * there is nothing in the buffer that isn't valid data; we can
12228 * mark the buffer as polished and return.
12230 * - The second (less common than the first but still more common
12231 * than the third) is that there is a gap between the buffer offset
12232 * and the wrapped offset, and the wrapped offset is larger than the
12233 * buffer offset. This can happen because of an alignment issue, or
12234 * can happen because of a call to dtrace_buffer_reserve() that
12235 * didn't subsequently consume the buffer space. In this case,
12236 * we need to zero the data from the buffer offset to the wrapped
12239 * - The third (and least common) is that there is a gap between the
12240 * buffer offset and the wrapped offset, but the wrapped offset is
12241 * _less_ than the buffer offset. This can only happen because a
12242 * call to dtrace_buffer_reserve() induced a wrap, but the space
12243 * was not subsequently consumed. In this case, we need to zero the
12244 * space from the offset to the end of the buffer _and_ from the
12245 * top of the buffer to the wrapped offset.
12247 if (buf->dtb_offset < buf->dtb_xamot_offset) {
12248 bzero(buf->dtb_tomax + buf->dtb_offset,
12249 buf->dtb_xamot_offset - buf->dtb_offset);
12252 if (buf->dtb_offset > buf->dtb_xamot_offset) {
12253 bzero(buf->dtb_tomax + buf->dtb_offset,
12254 buf->dtb_size - buf->dtb_offset);
12255 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12260 * This routine determines if data generated at the specified time has likely
12261 * been entirely consumed at user-level. This routine is called to determine
12262 * if an ECB on a defunct probe (but for an active enabling) can be safely
12263 * disabled and destroyed.
12266 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12270 for (i = 0; i < NCPU; i++) {
12271 dtrace_buffer_t *buf = &bufs[i];
12273 if (buf->dtb_size == 0)
12276 if (buf->dtb_flags & DTRACEBUF_RING)
12279 if (!buf->dtb_switched && buf->dtb_offset != 0)
12282 if (buf->dtb_switched - buf->dtb_interval < when)
12290 dtrace_buffer_free(dtrace_buffer_t *bufs)
12294 for (i = 0; i < NCPU; i++) {
12295 dtrace_buffer_t *buf = &bufs[i];
12297 if (buf->dtb_tomax == NULL) {
12298 ASSERT(buf->dtb_xamot == NULL);
12299 ASSERT(buf->dtb_size == 0);
12303 if (buf->dtb_xamot != NULL) {
12304 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12305 kmem_free(buf->dtb_xamot, buf->dtb_size);
12308 kmem_free(buf->dtb_tomax, buf->dtb_size);
12310 buf->dtb_tomax = NULL;
12311 buf->dtb_xamot = NULL;
12316 * DTrace Enabling Functions
12318 static dtrace_enabling_t *
12319 dtrace_enabling_create(dtrace_vstate_t *vstate)
12321 dtrace_enabling_t *enab;
12323 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12324 enab->dten_vstate = vstate;
12330 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12332 dtrace_ecbdesc_t **ndesc;
12333 size_t osize, nsize;
12336 * We can't add to enablings after we've enabled them, or after we've
12339 ASSERT(enab->dten_probegen == 0);
12340 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12342 if (enab->dten_ndesc < enab->dten_maxdesc) {
12343 enab->dten_desc[enab->dten_ndesc++] = ecb;
12347 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12349 if (enab->dten_maxdesc == 0) {
12350 enab->dten_maxdesc = 1;
12352 enab->dten_maxdesc <<= 1;
12355 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12357 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12358 ndesc = kmem_zalloc(nsize, KM_SLEEP);
12359 bcopy(enab->dten_desc, ndesc, osize);
12360 if (enab->dten_desc != NULL)
12361 kmem_free(enab->dten_desc, osize);
12363 enab->dten_desc = ndesc;
12364 enab->dten_desc[enab->dten_ndesc++] = ecb;
12368 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12369 dtrace_probedesc_t *pd)
12371 dtrace_ecbdesc_t *new;
12372 dtrace_predicate_t *pred;
12373 dtrace_actdesc_t *act;
12376 * We're going to create a new ECB description that matches the
12377 * specified ECB in every way, but has the specified probe description.
12379 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12381 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12382 dtrace_predicate_hold(pred);
12384 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12385 dtrace_actdesc_hold(act);
12387 new->dted_action = ecb->dted_action;
12388 new->dted_pred = ecb->dted_pred;
12389 new->dted_probe = *pd;
12390 new->dted_uarg = ecb->dted_uarg;
12392 dtrace_enabling_add(enab, new);
12396 dtrace_enabling_dump(dtrace_enabling_t *enab)
12400 for (i = 0; i < enab->dten_ndesc; i++) {
12401 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12403 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12404 desc->dtpd_provider, desc->dtpd_mod,
12405 desc->dtpd_func, desc->dtpd_name);
12410 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12413 dtrace_ecbdesc_t *ep;
12414 dtrace_vstate_t *vstate = enab->dten_vstate;
12416 ASSERT(MUTEX_HELD(&dtrace_lock));
12418 for (i = 0; i < enab->dten_ndesc; i++) {
12419 dtrace_actdesc_t *act, *next;
12420 dtrace_predicate_t *pred;
12422 ep = enab->dten_desc[i];
12424 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12425 dtrace_predicate_release(pred, vstate);
12427 for (act = ep->dted_action; act != NULL; act = next) {
12428 next = act->dtad_next;
12429 dtrace_actdesc_release(act, vstate);
12432 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12435 if (enab->dten_desc != NULL)
12436 kmem_free(enab->dten_desc,
12437 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12440 * If this was a retained enabling, decrement the dts_nretained count
12441 * and take it off of the dtrace_retained list.
12443 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12444 dtrace_retained == enab) {
12445 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12446 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12447 enab->dten_vstate->dtvs_state->dts_nretained--;
12448 dtrace_retained_gen++;
12451 if (enab->dten_prev == NULL) {
12452 if (dtrace_retained == enab) {
12453 dtrace_retained = enab->dten_next;
12455 if (dtrace_retained != NULL)
12456 dtrace_retained->dten_prev = NULL;
12459 ASSERT(enab != dtrace_retained);
12460 ASSERT(dtrace_retained != NULL);
12461 enab->dten_prev->dten_next = enab->dten_next;
12464 if (enab->dten_next != NULL) {
12465 ASSERT(dtrace_retained != NULL);
12466 enab->dten_next->dten_prev = enab->dten_prev;
12469 kmem_free(enab, sizeof (dtrace_enabling_t));
12473 dtrace_enabling_retain(dtrace_enabling_t *enab)
12475 dtrace_state_t *state;
12477 ASSERT(MUTEX_HELD(&dtrace_lock));
12478 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12479 ASSERT(enab->dten_vstate != NULL);
12481 state = enab->dten_vstate->dtvs_state;
12482 ASSERT(state != NULL);
12485 * We only allow each state to retain dtrace_retain_max enablings.
12487 if (state->dts_nretained >= dtrace_retain_max)
12490 state->dts_nretained++;
12491 dtrace_retained_gen++;
12493 if (dtrace_retained == NULL) {
12494 dtrace_retained = enab;
12498 enab->dten_next = dtrace_retained;
12499 dtrace_retained->dten_prev = enab;
12500 dtrace_retained = enab;
12506 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12507 dtrace_probedesc_t *create)
12509 dtrace_enabling_t *new, *enab;
12510 int found = 0, err = ENOENT;
12512 ASSERT(MUTEX_HELD(&dtrace_lock));
12513 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12514 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12515 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12516 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12518 new = dtrace_enabling_create(&state->dts_vstate);
12521 * Iterate over all retained enablings, looking for enablings that
12522 * match the specified state.
12524 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12528 * dtvs_state can only be NULL for helper enablings -- and
12529 * helper enablings can't be retained.
12531 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12533 if (enab->dten_vstate->dtvs_state != state)
12537 * Now iterate over each probe description; we're looking for
12538 * an exact match to the specified probe description.
12540 for (i = 0; i < enab->dten_ndesc; i++) {
12541 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12542 dtrace_probedesc_t *pd = &ep->dted_probe;
12544 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12547 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12550 if (strcmp(pd->dtpd_func, match->dtpd_func))
12553 if (strcmp(pd->dtpd_name, match->dtpd_name))
12557 * We have a winning probe! Add it to our growing
12561 dtrace_enabling_addlike(new, ep, create);
12565 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12566 dtrace_enabling_destroy(new);
12574 dtrace_enabling_retract(dtrace_state_t *state)
12576 dtrace_enabling_t *enab, *next;
12578 ASSERT(MUTEX_HELD(&dtrace_lock));
12581 * Iterate over all retained enablings, destroy the enablings retained
12582 * for the specified state.
12584 for (enab = dtrace_retained; enab != NULL; enab = next) {
12585 next = enab->dten_next;
12588 * dtvs_state can only be NULL for helper enablings -- and
12589 * helper enablings can't be retained.
12591 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12593 if (enab->dten_vstate->dtvs_state == state) {
12594 ASSERT(state->dts_nretained > 0);
12595 dtrace_enabling_destroy(enab);
12599 ASSERT(state->dts_nretained == 0);
12603 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12608 ASSERT(MUTEX_HELD(&cpu_lock));
12609 ASSERT(MUTEX_HELD(&dtrace_lock));
12611 for (i = 0; i < enab->dten_ndesc; i++) {
12612 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12614 enab->dten_current = ep;
12615 enab->dten_error = 0;
12617 matched += dtrace_probe_enable(&ep->dted_probe, enab);
12619 if (enab->dten_error != 0) {
12621 * If we get an error half-way through enabling the
12622 * probes, we kick out -- perhaps with some number of
12623 * them enabled. Leaving enabled probes enabled may
12624 * be slightly confusing for user-level, but we expect
12625 * that no one will attempt to actually drive on in
12626 * the face of such errors. If this is an anonymous
12627 * enabling (indicated with a NULL nmatched pointer),
12628 * we cmn_err() a message. We aren't expecting to
12629 * get such an error -- such as it can exist at all,
12630 * it would be a result of corrupted DOF in the driver
12633 if (nmatched == NULL) {
12634 cmn_err(CE_WARN, "dtrace_enabling_match() "
12635 "error on %p: %d", (void *)ep,
12639 return (enab->dten_error);
12643 enab->dten_probegen = dtrace_probegen;
12644 if (nmatched != NULL)
12645 *nmatched = matched;
12651 dtrace_enabling_matchall(void)
12653 dtrace_enabling_t *enab;
12655 mutex_enter(&cpu_lock);
12656 mutex_enter(&dtrace_lock);
12659 * Iterate over all retained enablings to see if any probes match
12660 * against them. We only perform this operation on enablings for which
12661 * we have sufficient permissions by virtue of being in the global zone
12662 * or in the same zone as the DTrace client. Because we can be called
12663 * after dtrace_detach() has been called, we cannot assert that there
12664 * are retained enablings. We can safely load from dtrace_retained,
12665 * however: the taskq_destroy() at the end of dtrace_detach() will
12666 * block pending our completion.
12668 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12670 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12672 if (INGLOBALZONE(curproc) ||
12673 cr != NULL && getzoneid() == crgetzoneid(cr))
12675 (void) dtrace_enabling_match(enab, NULL);
12678 mutex_exit(&dtrace_lock);
12679 mutex_exit(&cpu_lock);
12683 * If an enabling is to be enabled without having matched probes (that is, if
12684 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12685 * enabling must be _primed_ by creating an ECB for every ECB description.
12686 * This must be done to assure that we know the number of speculations, the
12687 * number of aggregations, the minimum buffer size needed, etc. before we
12688 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
12689 * enabling any probes, we create ECBs for every ECB decription, but with a
12690 * NULL probe -- which is exactly what this function does.
12693 dtrace_enabling_prime(dtrace_state_t *state)
12695 dtrace_enabling_t *enab;
12698 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12699 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12701 if (enab->dten_vstate->dtvs_state != state)
12705 * We don't want to prime an enabling more than once, lest
12706 * we allow a malicious user to induce resource exhaustion.
12707 * (The ECBs that result from priming an enabling aren't
12708 * leaked -- but they also aren't deallocated until the
12709 * consumer state is destroyed.)
12711 if (enab->dten_primed)
12714 for (i = 0; i < enab->dten_ndesc; i++) {
12715 enab->dten_current = enab->dten_desc[i];
12716 (void) dtrace_probe_enable(NULL, enab);
12719 enab->dten_primed = 1;
12724 * Called to indicate that probes should be provided due to retained
12725 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
12726 * must take an initial lap through the enabling calling the dtps_provide()
12727 * entry point explicitly to allow for autocreated probes.
12730 dtrace_enabling_provide(dtrace_provider_t *prv)
12733 dtrace_probedesc_t desc;
12734 dtrace_genid_t gen;
12736 ASSERT(MUTEX_HELD(&dtrace_lock));
12737 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12741 prv = dtrace_provider;
12745 dtrace_enabling_t *enab;
12746 void *parg = prv->dtpv_arg;
12749 gen = dtrace_retained_gen;
12750 for (enab = dtrace_retained; enab != NULL;
12751 enab = enab->dten_next) {
12752 for (i = 0; i < enab->dten_ndesc; i++) {
12753 desc = enab->dten_desc[i]->dted_probe;
12754 mutex_exit(&dtrace_lock);
12755 prv->dtpv_pops.dtps_provide(parg, &desc);
12756 mutex_enter(&dtrace_lock);
12758 * Process the retained enablings again if
12759 * they have changed while we weren't holding
12762 if (gen != dtrace_retained_gen)
12766 } while (all && (prv = prv->dtpv_next) != NULL);
12768 mutex_exit(&dtrace_lock);
12769 dtrace_probe_provide(NULL, all ? NULL : prv);
12770 mutex_enter(&dtrace_lock);
12774 * Called to reap ECBs that are attached to probes from defunct providers.
12777 dtrace_enabling_reap(void)
12779 dtrace_provider_t *prov;
12780 dtrace_probe_t *probe;
12785 mutex_enter(&cpu_lock);
12786 mutex_enter(&dtrace_lock);
12788 for (i = 0; i < dtrace_nprobes; i++) {
12789 if ((probe = dtrace_probes[i]) == NULL)
12792 if (probe->dtpr_ecb == NULL)
12795 prov = probe->dtpr_provider;
12797 if ((when = prov->dtpv_defunct) == 0)
12801 * We have ECBs on a defunct provider: we want to reap these
12802 * ECBs to allow the provider to unregister. The destruction
12803 * of these ECBs must be done carefully: if we destroy the ECB
12804 * and the consumer later wishes to consume an EPID that
12805 * corresponds to the destroyed ECB (and if the EPID metadata
12806 * has not been previously consumed), the consumer will abort
12807 * processing on the unknown EPID. To reduce (but not, sadly,
12808 * eliminate) the possibility of this, we will only destroy an
12809 * ECB for a defunct provider if, for the state that
12810 * corresponds to the ECB:
12812 * (a) There is no speculative tracing (which can effectively
12813 * cache an EPID for an arbitrary amount of time).
12815 * (b) The principal buffers have been switched twice since the
12816 * provider became defunct.
12818 * (c) The aggregation buffers are of zero size or have been
12819 * switched twice since the provider became defunct.
12821 * We use dts_speculates to determine (a) and call a function
12822 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
12823 * that as soon as we've been unable to destroy one of the ECBs
12824 * associated with the probe, we quit trying -- reaping is only
12825 * fruitful in as much as we can destroy all ECBs associated
12826 * with the defunct provider's probes.
12828 while ((ecb = probe->dtpr_ecb) != NULL) {
12829 dtrace_state_t *state = ecb->dte_state;
12830 dtrace_buffer_t *buf = state->dts_buffer;
12831 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12833 if (state->dts_speculates)
12836 if (!dtrace_buffer_consumed(buf, when))
12839 if (!dtrace_buffer_consumed(aggbuf, when))
12842 dtrace_ecb_disable(ecb);
12843 ASSERT(probe->dtpr_ecb != ecb);
12844 dtrace_ecb_destroy(ecb);
12848 mutex_exit(&dtrace_lock);
12849 mutex_exit(&cpu_lock);
12853 * DTrace DOF Functions
12857 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12859 if (dtrace_err_verbose)
12860 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12862 #ifdef DTRACE_ERRDEBUG
12863 dtrace_errdebug(str);
12868 * Create DOF out of a currently enabled state. Right now, we only create
12869 * DOF containing the run-time options -- but this could be expanded to create
12870 * complete DOF representing the enabled state.
12873 dtrace_dof_create(dtrace_state_t *state)
12877 dof_optdesc_t *opt;
12878 int i, len = sizeof (dof_hdr_t) +
12879 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12880 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12882 ASSERT(MUTEX_HELD(&dtrace_lock));
12884 dof = kmem_zalloc(len, KM_SLEEP);
12885 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12886 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12887 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12888 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12890 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12891 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12892 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12893 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12894 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12895 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12897 dof->dofh_flags = 0;
12898 dof->dofh_hdrsize = sizeof (dof_hdr_t);
12899 dof->dofh_secsize = sizeof (dof_sec_t);
12900 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
12901 dof->dofh_secoff = sizeof (dof_hdr_t);
12902 dof->dofh_loadsz = len;
12903 dof->dofh_filesz = len;
12907 * Fill in the option section header...
12909 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12910 sec->dofs_type = DOF_SECT_OPTDESC;
12911 sec->dofs_align = sizeof (uint64_t);
12912 sec->dofs_flags = DOF_SECF_LOAD;
12913 sec->dofs_entsize = sizeof (dof_optdesc_t);
12915 opt = (dof_optdesc_t *)((uintptr_t)sec +
12916 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12918 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12919 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12921 for (i = 0; i < DTRACEOPT_MAX; i++) {
12922 opt[i].dofo_option = i;
12923 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12924 opt[i].dofo_value = state->dts_options[i];
12931 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12933 dof_hdr_t hdr, *dof;
12935 ASSERT(!MUTEX_HELD(&dtrace_lock));
12938 * First, we're going to copyin() the sizeof (dof_hdr_t).
12940 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12941 dtrace_dof_error(NULL, "failed to copyin DOF header");
12947 * Now we'll allocate the entire DOF and copy it in -- provided
12948 * that the length isn't outrageous.
12950 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12951 dtrace_dof_error(&hdr, "load size exceeds maximum");
12956 if (hdr.dofh_loadsz < sizeof (hdr)) {
12957 dtrace_dof_error(&hdr, "invalid load size");
12962 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12964 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12965 dof->dofh_loadsz != hdr.dofh_loadsz) {
12966 kmem_free(dof, hdr.dofh_loadsz);
12975 static __inline uchar_t
12976 dtrace_dof_char(char c) {
12995 return (c - 'A' + 10);
13002 return (c - 'a' + 10);
13004 /* Should not reach here. */
13010 dtrace_dof_property(const char *name)
13014 unsigned int len, i;
13019 * Unfortunately, array of values in .conf files are always (and
13020 * only) interpreted to be integer arrays. We must read our DOF
13021 * as an integer array, and then squeeze it into a byte array.
13023 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13024 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13027 for (i = 0; i < len; i++)
13028 buf[i] = (uchar_t)(((int *)buf)[i]);
13030 if (len < sizeof (dof_hdr_t)) {
13031 ddi_prop_free(buf);
13032 dtrace_dof_error(NULL, "truncated header");
13036 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13037 ddi_prop_free(buf);
13038 dtrace_dof_error(NULL, "truncated DOF");
13042 if (loadsz >= dtrace_dof_maxsize) {
13043 ddi_prop_free(buf);
13044 dtrace_dof_error(NULL, "oversized DOF");
13048 dof = kmem_alloc(loadsz, KM_SLEEP);
13049 bcopy(buf, dof, loadsz);
13050 ddi_prop_free(buf);
13055 if ((p_env = getenv(name)) == NULL)
13058 len = strlen(p_env) / 2;
13060 buf = kmem_alloc(len, KM_SLEEP);
13062 dof = (dof_hdr_t *) buf;
13066 for (i = 0; i < len; i++) {
13067 buf[i] = (dtrace_dof_char(p[0]) << 4) |
13068 dtrace_dof_char(p[1]);
13074 if (len < sizeof (dof_hdr_t)) {
13076 dtrace_dof_error(NULL, "truncated header");
13080 if (len < (loadsz = dof->dofh_loadsz)) {
13082 dtrace_dof_error(NULL, "truncated DOF");
13086 if (loadsz >= dtrace_dof_maxsize) {
13088 dtrace_dof_error(NULL, "oversized DOF");
13097 dtrace_dof_destroy(dof_hdr_t *dof)
13099 kmem_free(dof, dof->dofh_loadsz);
13103 * Return the dof_sec_t pointer corresponding to a given section index. If the
13104 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
13105 * a type other than DOF_SECT_NONE is specified, the header is checked against
13106 * this type and NULL is returned if the types do not match.
13109 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13111 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13112 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13114 if (i >= dof->dofh_secnum) {
13115 dtrace_dof_error(dof, "referenced section index is invalid");
13119 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13120 dtrace_dof_error(dof, "referenced section is not loadable");
13124 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13125 dtrace_dof_error(dof, "referenced section is the wrong type");
13132 static dtrace_probedesc_t *
13133 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13135 dof_probedesc_t *probe;
13137 uintptr_t daddr = (uintptr_t)dof;
13141 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13142 dtrace_dof_error(dof, "invalid probe section");
13146 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13147 dtrace_dof_error(dof, "bad alignment in probe description");
13151 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13152 dtrace_dof_error(dof, "truncated probe description");
13156 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13157 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13159 if (strtab == NULL)
13162 str = daddr + strtab->dofs_offset;
13163 size = strtab->dofs_size;
13165 if (probe->dofp_provider >= strtab->dofs_size) {
13166 dtrace_dof_error(dof, "corrupt probe provider");
13170 (void) strncpy(desc->dtpd_provider,
13171 (char *)(str + probe->dofp_provider),
13172 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13174 if (probe->dofp_mod >= strtab->dofs_size) {
13175 dtrace_dof_error(dof, "corrupt probe module");
13179 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13180 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13182 if (probe->dofp_func >= strtab->dofs_size) {
13183 dtrace_dof_error(dof, "corrupt probe function");
13187 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13188 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13190 if (probe->dofp_name >= strtab->dofs_size) {
13191 dtrace_dof_error(dof, "corrupt probe name");
13195 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13196 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13201 static dtrace_difo_t *
13202 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13207 dof_difohdr_t *dofd;
13208 uintptr_t daddr = (uintptr_t)dof;
13209 size_t max = dtrace_difo_maxsize;
13212 static const struct {
13220 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13221 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13222 sizeof (dif_instr_t), "multiple DIF sections" },
13224 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13225 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13226 sizeof (uint64_t), "multiple integer tables" },
13228 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13229 offsetof(dtrace_difo_t, dtdo_strlen), 0,
13230 sizeof (char), "multiple string tables" },
13232 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13233 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13234 sizeof (uint_t), "multiple variable tables" },
13236 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13239 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13240 dtrace_dof_error(dof, "invalid DIFO header section");
13244 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13245 dtrace_dof_error(dof, "bad alignment in DIFO header");
13249 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13250 sec->dofs_size % sizeof (dof_secidx_t)) {
13251 dtrace_dof_error(dof, "bad size in DIFO header");
13255 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13256 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13258 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13259 dp->dtdo_rtype = dofd->dofd_rtype;
13261 for (l = 0; l < n; l++) {
13266 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13267 dofd->dofd_links[l])) == NULL)
13268 goto err; /* invalid section link */
13270 if (ttl + subsec->dofs_size > max) {
13271 dtrace_dof_error(dof, "exceeds maximum size");
13275 ttl += subsec->dofs_size;
13277 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13278 if (subsec->dofs_type != difo[i].section)
13281 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13282 dtrace_dof_error(dof, "section not loaded");
13286 if (subsec->dofs_align != difo[i].align) {
13287 dtrace_dof_error(dof, "bad alignment");
13291 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13292 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13294 if (*bufp != NULL) {
13295 dtrace_dof_error(dof, difo[i].msg);
13299 if (difo[i].entsize != subsec->dofs_entsize) {
13300 dtrace_dof_error(dof, "entry size mismatch");
13304 if (subsec->dofs_entsize != 0 &&
13305 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13306 dtrace_dof_error(dof, "corrupt entry size");
13310 *lenp = subsec->dofs_size;
13311 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13312 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13313 *bufp, subsec->dofs_size);
13315 if (subsec->dofs_entsize != 0)
13316 *lenp /= subsec->dofs_entsize;
13322 * If we encounter a loadable DIFO sub-section that is not
13323 * known to us, assume this is a broken program and fail.
13325 if (difo[i].section == DOF_SECT_NONE &&
13326 (subsec->dofs_flags & DOF_SECF_LOAD)) {
13327 dtrace_dof_error(dof, "unrecognized DIFO subsection");
13332 if (dp->dtdo_buf == NULL) {
13334 * We can't have a DIF object without DIF text.
13336 dtrace_dof_error(dof, "missing DIF text");
13341 * Before we validate the DIF object, run through the variable table
13342 * looking for the strings -- if any of their size are under, we'll set
13343 * their size to be the system-wide default string size. Note that
13344 * this should _not_ happen if the "strsize" option has been set --
13345 * in this case, the compiler should have set the size to reflect the
13346 * setting of the option.
13348 for (i = 0; i < dp->dtdo_varlen; i++) {
13349 dtrace_difv_t *v = &dp->dtdo_vartab[i];
13350 dtrace_diftype_t *t = &v->dtdv_type;
13352 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13355 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13356 t->dtdt_size = dtrace_strsize_default;
13359 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13362 dtrace_difo_init(dp, vstate);
13366 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13367 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13368 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13369 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13371 kmem_free(dp, sizeof (dtrace_difo_t));
13375 static dtrace_predicate_t *
13376 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13381 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13384 return (dtrace_predicate_create(dp));
13387 static dtrace_actdesc_t *
13388 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13391 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13392 dof_actdesc_t *desc;
13393 dof_sec_t *difosec;
13395 uintptr_t daddr = (uintptr_t)dof;
13397 dtrace_actkind_t kind;
13399 if (sec->dofs_type != DOF_SECT_ACTDESC) {
13400 dtrace_dof_error(dof, "invalid action section");
13404 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13405 dtrace_dof_error(dof, "truncated action description");
13409 if (sec->dofs_align != sizeof (uint64_t)) {
13410 dtrace_dof_error(dof, "bad alignment in action description");
13414 if (sec->dofs_size < sec->dofs_entsize) {
13415 dtrace_dof_error(dof, "section entry size exceeds total size");
13419 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13420 dtrace_dof_error(dof, "bad entry size in action description");
13424 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13425 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13429 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13430 desc = (dof_actdesc_t *)(daddr +
13431 (uintptr_t)sec->dofs_offset + offs);
13432 kind = (dtrace_actkind_t)desc->dofa_kind;
13434 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13435 (kind != DTRACEACT_PRINTA ||
13436 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13437 (kind == DTRACEACT_DIFEXPR &&
13438 desc->dofa_strtab != DOF_SECIDX_NONE)) {
13444 * The argument to these actions is an index into the
13445 * DOF string table. For printf()-like actions, this
13446 * is the format string. For print(), this is the
13447 * CTF type of the expression result.
13449 if ((strtab = dtrace_dof_sect(dof,
13450 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13453 str = (char *)((uintptr_t)dof +
13454 (uintptr_t)strtab->dofs_offset);
13456 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13457 if (str[i] == '\0')
13461 if (i >= strtab->dofs_size) {
13462 dtrace_dof_error(dof, "bogus format string");
13466 if (i == desc->dofa_arg) {
13467 dtrace_dof_error(dof, "empty format string");
13471 i -= desc->dofa_arg;
13472 fmt = kmem_alloc(i + 1, KM_SLEEP);
13473 bcopy(&str[desc->dofa_arg], fmt, i + 1);
13474 arg = (uint64_t)(uintptr_t)fmt;
13476 if (kind == DTRACEACT_PRINTA) {
13477 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13480 arg = desc->dofa_arg;
13484 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13485 desc->dofa_uarg, arg);
13487 if (last != NULL) {
13488 last->dtad_next = act;
13495 if (desc->dofa_difo == DOF_SECIDX_NONE)
13498 if ((difosec = dtrace_dof_sect(dof,
13499 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13502 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13504 if (act->dtad_difo == NULL)
13508 ASSERT(first != NULL);
13512 for (act = first; act != NULL; act = next) {
13513 next = act->dtad_next;
13514 dtrace_actdesc_release(act, vstate);
13520 static dtrace_ecbdesc_t *
13521 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13524 dtrace_ecbdesc_t *ep;
13525 dof_ecbdesc_t *ecb;
13526 dtrace_probedesc_t *desc;
13527 dtrace_predicate_t *pred = NULL;
13529 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13530 dtrace_dof_error(dof, "truncated ECB description");
13534 if (sec->dofs_align != sizeof (uint64_t)) {
13535 dtrace_dof_error(dof, "bad alignment in ECB description");
13539 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13540 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13545 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13546 ep->dted_uarg = ecb->dofe_uarg;
13547 desc = &ep->dted_probe;
13549 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13552 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13553 if ((sec = dtrace_dof_sect(dof,
13554 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13557 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13560 ep->dted_pred.dtpdd_predicate = pred;
13563 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13564 if ((sec = dtrace_dof_sect(dof,
13565 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13568 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13570 if (ep->dted_action == NULL)
13578 dtrace_predicate_release(pred, vstate);
13579 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13584 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13585 * specified DOF. At present, this amounts to simply adding 'ubase' to the
13586 * site of any user SETX relocations to account for load object base address.
13587 * In the future, if we need other relocations, this function can be extended.
13590 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13592 uintptr_t daddr = (uintptr_t)dof;
13593 dof_relohdr_t *dofr =
13594 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13595 dof_sec_t *ss, *rs, *ts;
13599 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13600 sec->dofs_align != sizeof (dof_secidx_t)) {
13601 dtrace_dof_error(dof, "invalid relocation header");
13605 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13606 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13607 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13609 if (ss == NULL || rs == NULL || ts == NULL)
13610 return (-1); /* dtrace_dof_error() has been called already */
13612 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13613 rs->dofs_align != sizeof (uint64_t)) {
13614 dtrace_dof_error(dof, "invalid relocation section");
13618 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13619 n = rs->dofs_size / rs->dofs_entsize;
13621 for (i = 0; i < n; i++) {
13622 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13624 switch (r->dofr_type) {
13625 case DOF_RELO_NONE:
13627 case DOF_RELO_SETX:
13628 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13629 sizeof (uint64_t) > ts->dofs_size) {
13630 dtrace_dof_error(dof, "bad relocation offset");
13634 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13635 dtrace_dof_error(dof, "misaligned setx relo");
13639 *(uint64_t *)taddr += ubase;
13642 dtrace_dof_error(dof, "invalid relocation type");
13646 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13653 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13654 * header: it should be at the front of a memory region that is at least
13655 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13656 * size. It need not be validated in any other way.
13659 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13660 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13662 uint64_t len = dof->dofh_loadsz, seclen;
13663 uintptr_t daddr = (uintptr_t)dof;
13664 dtrace_ecbdesc_t *ep;
13665 dtrace_enabling_t *enab;
13668 ASSERT(MUTEX_HELD(&dtrace_lock));
13669 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13672 * Check the DOF header identification bytes. In addition to checking
13673 * valid settings, we also verify that unused bits/bytes are zeroed so
13674 * we can use them later without fear of regressing existing binaries.
13676 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13677 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13678 dtrace_dof_error(dof, "DOF magic string mismatch");
13682 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13683 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13684 dtrace_dof_error(dof, "DOF has invalid data model");
13688 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13689 dtrace_dof_error(dof, "DOF encoding mismatch");
13693 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13694 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13695 dtrace_dof_error(dof, "DOF version mismatch");
13699 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13700 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13704 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13705 dtrace_dof_error(dof, "DOF uses too many integer registers");
13709 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13710 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13714 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13715 if (dof->dofh_ident[i] != 0) {
13716 dtrace_dof_error(dof, "DOF has invalid ident byte set");
13721 if (dof->dofh_flags & ~DOF_FL_VALID) {
13722 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13726 if (dof->dofh_secsize == 0) {
13727 dtrace_dof_error(dof, "zero section header size");
13732 * Check that the section headers don't exceed the amount of DOF
13733 * data. Note that we cast the section size and number of sections
13734 * to uint64_t's to prevent possible overflow in the multiplication.
13736 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13738 if (dof->dofh_secoff > len || seclen > len ||
13739 dof->dofh_secoff + seclen > len) {
13740 dtrace_dof_error(dof, "truncated section headers");
13744 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13745 dtrace_dof_error(dof, "misaligned section headers");
13749 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13750 dtrace_dof_error(dof, "misaligned section size");
13755 * Take an initial pass through the section headers to be sure that
13756 * the headers don't have stray offsets. If the 'noprobes' flag is
13757 * set, do not permit sections relating to providers, probes, or args.
13759 for (i = 0; i < dof->dofh_secnum; i++) {
13760 dof_sec_t *sec = (dof_sec_t *)(daddr +
13761 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13764 switch (sec->dofs_type) {
13765 case DOF_SECT_PROVIDER:
13766 case DOF_SECT_PROBES:
13767 case DOF_SECT_PRARGS:
13768 case DOF_SECT_PROFFS:
13769 dtrace_dof_error(dof, "illegal sections "
13775 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13776 !(sec->dofs_flags & DOF_SECF_LOAD)) {
13777 dtrace_dof_error(dof, "loadable section with load "
13782 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13783 continue; /* just ignore non-loadable sections */
13785 if (sec->dofs_align & (sec->dofs_align - 1)) {
13786 dtrace_dof_error(dof, "bad section alignment");
13790 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13791 dtrace_dof_error(dof, "misaligned section");
13795 if (sec->dofs_offset > len || sec->dofs_size > len ||
13796 sec->dofs_offset + sec->dofs_size > len) {
13797 dtrace_dof_error(dof, "corrupt section header");
13801 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13802 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13803 dtrace_dof_error(dof, "non-terminating string table");
13809 * Take a second pass through the sections and locate and perform any
13810 * relocations that are present. We do this after the first pass to
13811 * be sure that all sections have had their headers validated.
13813 for (i = 0; i < dof->dofh_secnum; i++) {
13814 dof_sec_t *sec = (dof_sec_t *)(daddr +
13815 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13817 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13818 continue; /* skip sections that are not loadable */
13820 switch (sec->dofs_type) {
13821 case DOF_SECT_URELHDR:
13822 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13828 if ((enab = *enabp) == NULL)
13829 enab = *enabp = dtrace_enabling_create(vstate);
13831 for (i = 0; i < dof->dofh_secnum; i++) {
13832 dof_sec_t *sec = (dof_sec_t *)(daddr +
13833 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13835 if (sec->dofs_type != DOF_SECT_ECBDESC)
13838 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13839 dtrace_enabling_destroy(enab);
13844 dtrace_enabling_add(enab, ep);
13851 * Process DOF for any options. This routine assumes that the DOF has been
13852 * at least processed by dtrace_dof_slurp().
13855 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13860 dof_optdesc_t *desc;
13862 for (i = 0; i < dof->dofh_secnum; i++) {
13863 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13864 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13866 if (sec->dofs_type != DOF_SECT_OPTDESC)
13869 if (sec->dofs_align != sizeof (uint64_t)) {
13870 dtrace_dof_error(dof, "bad alignment in "
13871 "option description");
13875 if ((entsize = sec->dofs_entsize) == 0) {
13876 dtrace_dof_error(dof, "zeroed option entry size");
13880 if (entsize < sizeof (dof_optdesc_t)) {
13881 dtrace_dof_error(dof, "bad option entry size");
13885 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13886 desc = (dof_optdesc_t *)((uintptr_t)dof +
13887 (uintptr_t)sec->dofs_offset + offs);
13889 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13890 dtrace_dof_error(dof, "non-zero option string");
13894 if (desc->dofo_value == DTRACEOPT_UNSET) {
13895 dtrace_dof_error(dof, "unset option");
13899 if ((rval = dtrace_state_option(state,
13900 desc->dofo_option, desc->dofo_value)) != 0) {
13901 dtrace_dof_error(dof, "rejected option");
13911 * DTrace Consumer State Functions
13914 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13916 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13919 dtrace_dynvar_t *dvar, *next, *start;
13922 ASSERT(MUTEX_HELD(&dtrace_lock));
13923 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13925 bzero(dstate, sizeof (dtrace_dstate_t));
13927 if ((dstate->dtds_chunksize = chunksize) == 0)
13928 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13930 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13933 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13936 dstate->dtds_size = size;
13937 dstate->dtds_base = base;
13938 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13939 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13941 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13943 if (hashsize != 1 && (hashsize & 1))
13946 dstate->dtds_hashsize = hashsize;
13947 dstate->dtds_hash = dstate->dtds_base;
13950 * Set all of our hash buckets to point to the single sink, and (if
13951 * it hasn't already been set), set the sink's hash value to be the
13952 * sink sentinel value. The sink is needed for dynamic variable
13953 * lookups to know that they have iterated over an entire, valid hash
13956 for (i = 0; i < hashsize; i++)
13957 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13959 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13960 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13963 * Determine number of active CPUs. Divide free list evenly among
13966 start = (dtrace_dynvar_t *)
13967 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13968 limit = (uintptr_t)base + size;
13970 maxper = (limit - (uintptr_t)start) / NCPU;
13971 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13976 for (i = 0; i < NCPU; i++) {
13978 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13981 * If we don't even have enough chunks to make it once through
13982 * NCPUs, we're just going to allocate everything to the first
13983 * CPU. And if we're on the last CPU, we're going to allocate
13984 * whatever is left over. In either case, we set the limit to
13985 * be the limit of the dynamic variable space.
13987 if (maxper == 0 || i == NCPU - 1) {
13988 limit = (uintptr_t)base + size;
13991 limit = (uintptr_t)start + maxper;
13992 start = (dtrace_dynvar_t *)limit;
13995 ASSERT(limit <= (uintptr_t)base + size);
13998 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13999 dstate->dtds_chunksize);
14001 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14004 dvar->dtdv_next = next;
14016 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14018 ASSERT(MUTEX_HELD(&cpu_lock));
14020 if (dstate->dtds_base == NULL)
14023 kmem_free(dstate->dtds_base, dstate->dtds_size);
14024 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14028 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14031 * Logical XOR, where are you?
14033 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14035 if (vstate->dtvs_nglobals > 0) {
14036 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14037 sizeof (dtrace_statvar_t *));
14040 if (vstate->dtvs_ntlocals > 0) {
14041 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14042 sizeof (dtrace_difv_t));
14045 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14047 if (vstate->dtvs_nlocals > 0) {
14048 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14049 sizeof (dtrace_statvar_t *));
14055 dtrace_state_clean(dtrace_state_t *state)
14057 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14060 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14061 dtrace_speculation_clean(state);
14065 dtrace_state_deadman(dtrace_state_t *state)
14071 now = dtrace_gethrtime();
14073 if (state != dtrace_anon.dta_state &&
14074 now - state->dts_laststatus >= dtrace_deadman_user)
14078 * We must be sure that dts_alive never appears to be less than the
14079 * value upon entry to dtrace_state_deadman(), and because we lack a
14080 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14081 * store INT64_MAX to it, followed by a memory barrier, followed by
14082 * the new value. This assures that dts_alive never appears to be
14083 * less than its true value, regardless of the order in which the
14084 * stores to the underlying storage are issued.
14086 state->dts_alive = INT64_MAX;
14087 dtrace_membar_producer();
14088 state->dts_alive = now;
14092 dtrace_state_clean(void *arg)
14094 dtrace_state_t *state = arg;
14095 dtrace_optval_t *opt = state->dts_options;
14097 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14100 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14101 dtrace_speculation_clean(state);
14103 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14104 dtrace_state_clean, state);
14108 dtrace_state_deadman(void *arg)
14110 dtrace_state_t *state = arg;
14115 dtrace_debug_output();
14117 now = dtrace_gethrtime();
14119 if (state != dtrace_anon.dta_state &&
14120 now - state->dts_laststatus >= dtrace_deadman_user)
14124 * We must be sure that dts_alive never appears to be less than the
14125 * value upon entry to dtrace_state_deadman(), and because we lack a
14126 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14127 * store INT64_MAX to it, followed by a memory barrier, followed by
14128 * the new value. This assures that dts_alive never appears to be
14129 * less than its true value, regardless of the order in which the
14130 * stores to the underlying storage are issued.
14132 state->dts_alive = INT64_MAX;
14133 dtrace_membar_producer();
14134 state->dts_alive = now;
14136 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14137 dtrace_state_deadman, state);
14141 static dtrace_state_t *
14143 dtrace_state_create(dev_t *devp, cred_t *cr)
14145 dtrace_state_create(struct cdev *dev)
14156 dtrace_state_t *state;
14157 dtrace_optval_t *opt;
14158 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14160 ASSERT(MUTEX_HELD(&dtrace_lock));
14161 ASSERT(MUTEX_HELD(&cpu_lock));
14164 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14165 VM_BESTFIT | VM_SLEEP);
14167 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14168 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14172 state = ddi_get_soft_state(dtrace_softstate, minor);
14179 /* Allocate memory for the state. */
14180 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14183 state->dts_epid = DTRACE_EPIDNONE + 1;
14185 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14187 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14188 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14190 if (devp != NULL) {
14191 major = getemajor(*devp);
14193 major = ddi_driver_major(dtrace_devi);
14196 state->dts_dev = makedevice(major, minor);
14199 *devp = state->dts_dev;
14201 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14202 state->dts_dev = dev;
14206 * We allocate NCPU buffers. On the one hand, this can be quite
14207 * a bit of memory per instance (nearly 36K on a Starcat). On the
14208 * other hand, it saves an additional memory reference in the probe
14211 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14212 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14215 state->dts_cleaner = CYCLIC_NONE;
14216 state->dts_deadman = CYCLIC_NONE;
14218 callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
14219 callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
14221 state->dts_vstate.dtvs_state = state;
14223 for (i = 0; i < DTRACEOPT_MAX; i++)
14224 state->dts_options[i] = DTRACEOPT_UNSET;
14227 * Set the default options.
14229 opt = state->dts_options;
14230 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14231 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14232 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14233 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14234 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14235 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14236 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14237 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14238 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14239 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14240 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14241 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14242 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14243 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14245 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14248 * Depending on the user credentials, we set flag bits which alter probe
14249 * visibility or the amount of destructiveness allowed. In the case of
14250 * actual anonymous tracing, or the possession of all privileges, all of
14251 * the normal checks are bypassed.
14253 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14254 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14255 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14258 * Set up the credentials for this instantiation. We take a
14259 * hold on the credential to prevent it from disappearing on
14260 * us; this in turn prevents the zone_t referenced by this
14261 * credential from disappearing. This means that we can
14262 * examine the credential and the zone from probe context.
14265 state->dts_cred.dcr_cred = cr;
14268 * CRA_PROC means "we have *some* privilege for dtrace" and
14269 * unlocks the use of variables like pid, zonename, etc.
14271 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14272 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14273 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14277 * dtrace_user allows use of syscall and profile providers.
14278 * If the user also has proc_owner and/or proc_zone, we
14279 * extend the scope to include additional visibility and
14280 * destructive power.
14282 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14283 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14284 state->dts_cred.dcr_visible |=
14285 DTRACE_CRV_ALLPROC;
14287 state->dts_cred.dcr_action |=
14288 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14291 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14292 state->dts_cred.dcr_visible |=
14293 DTRACE_CRV_ALLZONE;
14295 state->dts_cred.dcr_action |=
14296 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14300 * If we have all privs in whatever zone this is,
14301 * we can do destructive things to processes which
14302 * have altered credentials.
14305 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14306 cr->cr_zone->zone_privset)) {
14307 state->dts_cred.dcr_action |=
14308 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14314 * Holding the dtrace_kernel privilege also implies that
14315 * the user has the dtrace_user privilege from a visibility
14316 * perspective. But without further privileges, some
14317 * destructive actions are not available.
14319 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14321 * Make all probes in all zones visible. However,
14322 * this doesn't mean that all actions become available
14325 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14326 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14328 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14331 * Holding proc_owner means that destructive actions
14332 * for *this* zone are allowed.
14334 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14335 state->dts_cred.dcr_action |=
14336 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14339 * Holding proc_zone means that destructive actions
14340 * for this user/group ID in all zones is allowed.
14342 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14343 state->dts_cred.dcr_action |=
14344 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14348 * If we have all privs in whatever zone this is,
14349 * we can do destructive things to processes which
14350 * have altered credentials.
14352 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14353 cr->cr_zone->zone_privset)) {
14354 state->dts_cred.dcr_action |=
14355 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14361 * Holding the dtrace_proc privilege gives control over fasttrap
14362 * and pid providers. We need to grant wider destructive
14363 * privileges in the event that the user has proc_owner and/or
14366 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14367 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14368 state->dts_cred.dcr_action |=
14369 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14371 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14372 state->dts_cred.dcr_action |=
14373 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14381 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14383 dtrace_optval_t *opt = state->dts_options, size;
14384 processorid_t cpu = 0;;
14385 int flags = 0, rval, factor, divisor = 1;
14387 ASSERT(MUTEX_HELD(&dtrace_lock));
14388 ASSERT(MUTEX_HELD(&cpu_lock));
14389 ASSERT(which < DTRACEOPT_MAX);
14390 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14391 (state == dtrace_anon.dta_state &&
14392 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14394 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14397 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14398 cpu = opt[DTRACEOPT_CPU];
14400 if (which == DTRACEOPT_SPECSIZE)
14401 flags |= DTRACEBUF_NOSWITCH;
14403 if (which == DTRACEOPT_BUFSIZE) {
14404 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14405 flags |= DTRACEBUF_RING;
14407 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14408 flags |= DTRACEBUF_FILL;
14410 if (state != dtrace_anon.dta_state ||
14411 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14412 flags |= DTRACEBUF_INACTIVE;
14415 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14417 * The size must be 8-byte aligned. If the size is not 8-byte
14418 * aligned, drop it down by the difference.
14420 if (size & (sizeof (uint64_t) - 1))
14421 size -= size & (sizeof (uint64_t) - 1);
14423 if (size < state->dts_reserve) {
14425 * Buffers always must be large enough to accommodate
14426 * their prereserved space. We return E2BIG instead
14427 * of ENOMEM in this case to allow for user-level
14428 * software to differentiate the cases.
14433 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14435 if (rval != ENOMEM) {
14440 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14443 for (divisor = 2; divisor < factor; divisor <<= 1)
14451 dtrace_state_buffers(dtrace_state_t *state)
14453 dtrace_speculation_t *spec = state->dts_speculations;
14456 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14457 DTRACEOPT_BUFSIZE)) != 0)
14460 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14461 DTRACEOPT_AGGSIZE)) != 0)
14464 for (i = 0; i < state->dts_nspeculations; i++) {
14465 if ((rval = dtrace_state_buffer(state,
14466 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14474 dtrace_state_prereserve(dtrace_state_t *state)
14477 dtrace_probe_t *probe;
14479 state->dts_reserve = 0;
14481 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14485 * If our buffer policy is a "fill" buffer policy, we need to set the
14486 * prereserved space to be the space required by the END probes.
14488 probe = dtrace_probes[dtrace_probeid_end - 1];
14489 ASSERT(probe != NULL);
14491 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14492 if (ecb->dte_state != state)
14495 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14500 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14502 dtrace_optval_t *opt = state->dts_options, sz, nspec;
14503 dtrace_speculation_t *spec;
14504 dtrace_buffer_t *buf;
14506 cyc_handler_t hdlr;
14509 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14510 dtrace_icookie_t cookie;
14512 mutex_enter(&cpu_lock);
14513 mutex_enter(&dtrace_lock);
14515 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14521 * Before we can perform any checks, we must prime all of the
14522 * retained enablings that correspond to this state.
14524 dtrace_enabling_prime(state);
14526 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14531 dtrace_state_prereserve(state);
14534 * Now we want to do is try to allocate our speculations.
14535 * We do not automatically resize the number of speculations; if
14536 * this fails, we will fail the operation.
14538 nspec = opt[DTRACEOPT_NSPEC];
14539 ASSERT(nspec != DTRACEOPT_UNSET);
14541 if (nspec > INT_MAX) {
14546 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14547 KM_NOSLEEP | KM_NORMALPRI);
14549 if (spec == NULL) {
14554 state->dts_speculations = spec;
14555 state->dts_nspeculations = (int)nspec;
14557 for (i = 0; i < nspec; i++) {
14558 if ((buf = kmem_zalloc(bufsize,
14559 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
14564 spec[i].dtsp_buffer = buf;
14567 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14568 if (dtrace_anon.dta_state == NULL) {
14573 if (state->dts_necbs != 0) {
14578 state->dts_anon = dtrace_anon_grab();
14579 ASSERT(state->dts_anon != NULL);
14580 state = state->dts_anon;
14583 * We want "grabanon" to be set in the grabbed state, so we'll
14584 * copy that option value from the grabbing state into the
14587 state->dts_options[DTRACEOPT_GRABANON] =
14588 opt[DTRACEOPT_GRABANON];
14590 *cpu = dtrace_anon.dta_beganon;
14593 * If the anonymous state is active (as it almost certainly
14594 * is if the anonymous enabling ultimately matched anything),
14595 * we don't allow any further option processing -- but we
14596 * don't return failure.
14598 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14602 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14603 opt[DTRACEOPT_AGGSIZE] != 0) {
14604 if (state->dts_aggregations == NULL) {
14606 * We're not going to create an aggregation buffer
14607 * because we don't have any ECBs that contain
14608 * aggregations -- set this option to 0.
14610 opt[DTRACEOPT_AGGSIZE] = 0;
14613 * If we have an aggregation buffer, we must also have
14614 * a buffer to use as scratch.
14616 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14617 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14618 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14623 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14624 opt[DTRACEOPT_SPECSIZE] != 0) {
14625 if (!state->dts_speculates) {
14627 * We're not going to create speculation buffers
14628 * because we don't have any ECBs that actually
14629 * speculate -- set the speculation size to 0.
14631 opt[DTRACEOPT_SPECSIZE] = 0;
14636 * The bare minimum size for any buffer that we're actually going to
14637 * do anything to is sizeof (uint64_t).
14639 sz = sizeof (uint64_t);
14641 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14642 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14643 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14645 * A buffer size has been explicitly set to 0 (or to a size
14646 * that will be adjusted to 0) and we need the space -- we
14647 * need to return failure. We return ENOSPC to differentiate
14648 * it from failing to allocate a buffer due to failure to meet
14649 * the reserve (for which we return E2BIG).
14655 if ((rval = dtrace_state_buffers(state)) != 0)
14658 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14659 sz = dtrace_dstate_defsize;
14662 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14667 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14669 } while (sz >>= 1);
14671 opt[DTRACEOPT_DYNVARSIZE] = sz;
14676 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14677 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14679 if (opt[DTRACEOPT_CLEANRATE] == 0)
14680 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14682 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14683 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14685 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14686 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14688 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14690 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14691 hdlr.cyh_arg = state;
14692 hdlr.cyh_level = CY_LOW_LEVEL;
14695 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14697 state->dts_cleaner = cyclic_add(&hdlr, &when);
14699 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14700 hdlr.cyh_arg = state;
14701 hdlr.cyh_level = CY_LOW_LEVEL;
14704 when.cyt_interval = dtrace_deadman_interval;
14706 state->dts_deadman = cyclic_add(&hdlr, &when);
14708 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14709 dtrace_state_clean, state);
14710 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14711 dtrace_state_deadman, state);
14714 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14717 if (state->dts_getf != 0 &&
14718 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14720 * We don't have kernel privs but we have at least one call
14721 * to getf(); we need to bump our zone's count, and (if
14722 * this is the first enabling to have an unprivileged call
14723 * to getf()) we need to hook into closef().
14725 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14727 if (dtrace_getf++ == 0) {
14728 ASSERT(dtrace_closef == NULL);
14729 dtrace_closef = dtrace_getf_barrier;
14735 * Now it's time to actually fire the BEGIN probe. We need to disable
14736 * interrupts here both to record the CPU on which we fired the BEGIN
14737 * probe (the data from this CPU will be processed first at user
14738 * level) and to manually activate the buffer for this CPU.
14740 cookie = dtrace_interrupt_disable();
14742 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14743 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14745 dtrace_probe(dtrace_probeid_begin,
14746 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14747 dtrace_interrupt_enable(cookie);
14749 * We may have had an exit action from a BEGIN probe; only change our
14750 * state to ACTIVE if we're still in WARMUP.
14752 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14753 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14755 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14756 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14759 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14760 * want each CPU to transition its principal buffer out of the
14761 * INACTIVE state. Doing this assures that no CPU will suddenly begin
14762 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14763 * atomically transition from processing none of a state's ECBs to
14764 * processing all of them.
14766 dtrace_xcall(DTRACE_CPUALL,
14767 (dtrace_xcall_t)dtrace_buffer_activate, state);
14771 dtrace_buffer_free(state->dts_buffer);
14772 dtrace_buffer_free(state->dts_aggbuffer);
14774 if ((nspec = state->dts_nspeculations) == 0) {
14775 ASSERT(state->dts_speculations == NULL);
14779 spec = state->dts_speculations;
14780 ASSERT(spec != NULL);
14782 for (i = 0; i < state->dts_nspeculations; i++) {
14783 if ((buf = spec[i].dtsp_buffer) == NULL)
14786 dtrace_buffer_free(buf);
14787 kmem_free(buf, bufsize);
14790 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14791 state->dts_nspeculations = 0;
14792 state->dts_speculations = NULL;
14795 mutex_exit(&dtrace_lock);
14796 mutex_exit(&cpu_lock);
14802 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14804 dtrace_icookie_t cookie;
14806 ASSERT(MUTEX_HELD(&dtrace_lock));
14808 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14809 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14813 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14814 * to be sure that every CPU has seen it. See below for the details
14815 * on why this is done.
14817 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14821 * By this point, it is impossible for any CPU to be still processing
14822 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
14823 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14824 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
14825 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14826 * iff we're in the END probe.
14828 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14830 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14833 * Finally, we can release the reserve and call the END probe. We
14834 * disable interrupts across calling the END probe to allow us to
14835 * return the CPU on which we actually called the END probe. This
14836 * allows user-land to be sure that this CPU's principal buffer is
14839 state->dts_reserve = 0;
14841 cookie = dtrace_interrupt_disable();
14843 dtrace_probe(dtrace_probeid_end,
14844 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14845 dtrace_interrupt_enable(cookie);
14847 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14851 if (state->dts_getf != 0 &&
14852 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14854 * We don't have kernel privs but we have at least one call
14855 * to getf(); we need to lower our zone's count, and (if
14856 * this is the last enabling to have an unprivileged call
14857 * to getf()) we need to clear the closef() hook.
14859 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14860 ASSERT(dtrace_closef == dtrace_getf_barrier);
14861 ASSERT(dtrace_getf > 0);
14863 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14865 if (--dtrace_getf == 0)
14866 dtrace_closef = NULL;
14874 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14875 dtrace_optval_t val)
14877 ASSERT(MUTEX_HELD(&dtrace_lock));
14879 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14882 if (option >= DTRACEOPT_MAX)
14885 if (option != DTRACEOPT_CPU && val < 0)
14889 case DTRACEOPT_DESTRUCTIVE:
14890 if (dtrace_destructive_disallow)
14893 state->dts_cred.dcr_destructive = 1;
14896 case DTRACEOPT_BUFSIZE:
14897 case DTRACEOPT_DYNVARSIZE:
14898 case DTRACEOPT_AGGSIZE:
14899 case DTRACEOPT_SPECSIZE:
14900 case DTRACEOPT_STRSIZE:
14904 if (val >= LONG_MAX) {
14906 * If this is an otherwise negative value, set it to
14907 * the highest multiple of 128m less than LONG_MAX.
14908 * Technically, we're adjusting the size without
14909 * regard to the buffer resizing policy, but in fact,
14910 * this has no effect -- if we set the buffer size to
14911 * ~LONG_MAX and the buffer policy is ultimately set to
14912 * be "manual", the buffer allocation is guaranteed to
14913 * fail, if only because the allocation requires two
14914 * buffers. (We set the the size to the highest
14915 * multiple of 128m because it ensures that the size
14916 * will remain a multiple of a megabyte when
14917 * repeatedly halved -- all the way down to 15m.)
14919 val = LONG_MAX - (1 << 27) + 1;
14923 state->dts_options[option] = val;
14929 dtrace_state_destroy(dtrace_state_t *state)
14932 dtrace_vstate_t *vstate = &state->dts_vstate;
14934 minor_t minor = getminor(state->dts_dev);
14936 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14937 dtrace_speculation_t *spec = state->dts_speculations;
14938 int nspec = state->dts_nspeculations;
14941 ASSERT(MUTEX_HELD(&dtrace_lock));
14942 ASSERT(MUTEX_HELD(&cpu_lock));
14945 * First, retract any retained enablings for this state.
14947 dtrace_enabling_retract(state);
14948 ASSERT(state->dts_nretained == 0);
14950 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14951 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14953 * We have managed to come into dtrace_state_destroy() on a
14954 * hot enabling -- almost certainly because of a disorderly
14955 * shutdown of a consumer. (That is, a consumer that is
14956 * exiting without having called dtrace_stop().) In this case,
14957 * we're going to set our activity to be KILLED, and then
14958 * issue a sync to be sure that everyone is out of probe
14959 * context before we start blowing away ECBs.
14961 state->dts_activity = DTRACE_ACTIVITY_KILLED;
14966 * Release the credential hold we took in dtrace_state_create().
14968 if (state->dts_cred.dcr_cred != NULL)
14969 crfree(state->dts_cred.dcr_cred);
14972 * Now we can safely disable and destroy any enabled probes. Because
14973 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14974 * (especially if they're all enabled), we take two passes through the
14975 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14976 * in the second we disable whatever is left over.
14978 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14979 for (i = 0; i < state->dts_necbs; i++) {
14980 if ((ecb = state->dts_ecbs[i]) == NULL)
14983 if (match && ecb->dte_probe != NULL) {
14984 dtrace_probe_t *probe = ecb->dte_probe;
14985 dtrace_provider_t *prov = probe->dtpr_provider;
14987 if (!(prov->dtpv_priv.dtpp_flags & match))
14991 dtrace_ecb_disable(ecb);
14992 dtrace_ecb_destroy(ecb);
15000 * Before we free the buffers, perform one more sync to assure that
15001 * every CPU is out of probe context.
15005 dtrace_buffer_free(state->dts_buffer);
15006 dtrace_buffer_free(state->dts_aggbuffer);
15008 for (i = 0; i < nspec; i++)
15009 dtrace_buffer_free(spec[i].dtsp_buffer);
15012 if (state->dts_cleaner != CYCLIC_NONE)
15013 cyclic_remove(state->dts_cleaner);
15015 if (state->dts_deadman != CYCLIC_NONE)
15016 cyclic_remove(state->dts_deadman);
15018 callout_stop(&state->dts_cleaner);
15019 callout_drain(&state->dts_cleaner);
15020 callout_stop(&state->dts_deadman);
15021 callout_drain(&state->dts_deadman);
15024 dtrace_dstate_fini(&vstate->dtvs_dynvars);
15025 dtrace_vstate_fini(vstate);
15026 if (state->dts_ecbs != NULL)
15027 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15029 if (state->dts_aggregations != NULL) {
15031 for (i = 0; i < state->dts_naggregations; i++)
15032 ASSERT(state->dts_aggregations[i] == NULL);
15034 ASSERT(state->dts_naggregations > 0);
15035 kmem_free(state->dts_aggregations,
15036 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15039 kmem_free(state->dts_buffer, bufsize);
15040 kmem_free(state->dts_aggbuffer, bufsize);
15042 for (i = 0; i < nspec; i++)
15043 kmem_free(spec[i].dtsp_buffer, bufsize);
15046 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15048 dtrace_format_destroy(state);
15050 if (state->dts_aggid_arena != NULL) {
15052 vmem_destroy(state->dts_aggid_arena);
15054 delete_unrhdr(state->dts_aggid_arena);
15056 state->dts_aggid_arena = NULL;
15059 ddi_soft_state_free(dtrace_softstate, minor);
15060 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15065 * DTrace Anonymous Enabling Functions
15067 static dtrace_state_t *
15068 dtrace_anon_grab(void)
15070 dtrace_state_t *state;
15072 ASSERT(MUTEX_HELD(&dtrace_lock));
15074 if ((state = dtrace_anon.dta_state) == NULL) {
15075 ASSERT(dtrace_anon.dta_enabling == NULL);
15079 ASSERT(dtrace_anon.dta_enabling != NULL);
15080 ASSERT(dtrace_retained != NULL);
15082 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15083 dtrace_anon.dta_enabling = NULL;
15084 dtrace_anon.dta_state = NULL;
15090 dtrace_anon_property(void)
15093 dtrace_state_t *state;
15095 char c[32]; /* enough for "dof-data-" + digits */
15097 ASSERT(MUTEX_HELD(&dtrace_lock));
15098 ASSERT(MUTEX_HELD(&cpu_lock));
15100 for (i = 0; ; i++) {
15101 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
15103 dtrace_err_verbose = 1;
15105 if ((dof = dtrace_dof_property(c)) == NULL) {
15106 dtrace_err_verbose = 0;
15112 * We want to create anonymous state, so we need to transition
15113 * the kernel debugger to indicate that DTrace is active. If
15114 * this fails (e.g. because the debugger has modified text in
15115 * some way), we won't continue with the processing.
15117 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15118 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15119 "enabling ignored.");
15120 dtrace_dof_destroy(dof);
15126 * If we haven't allocated an anonymous state, we'll do so now.
15128 if ((state = dtrace_anon.dta_state) == NULL) {
15130 state = dtrace_state_create(NULL, NULL);
15132 state = dtrace_state_create(NULL);
15134 dtrace_anon.dta_state = state;
15136 if (state == NULL) {
15138 * This basically shouldn't happen: the only
15139 * failure mode from dtrace_state_create() is a
15140 * failure of ddi_soft_state_zalloc() that
15141 * itself should never happen. Still, the
15142 * interface allows for a failure mode, and
15143 * we want to fail as gracefully as possible:
15144 * we'll emit an error message and cease
15145 * processing anonymous state in this case.
15147 cmn_err(CE_WARN, "failed to create "
15148 "anonymous state");
15149 dtrace_dof_destroy(dof);
15154 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15155 &dtrace_anon.dta_enabling, 0, B_TRUE);
15158 rv = dtrace_dof_options(dof, state);
15160 dtrace_err_verbose = 0;
15161 dtrace_dof_destroy(dof);
15165 * This is malformed DOF; chuck any anonymous state
15168 ASSERT(dtrace_anon.dta_enabling == NULL);
15169 dtrace_state_destroy(state);
15170 dtrace_anon.dta_state = NULL;
15174 ASSERT(dtrace_anon.dta_enabling != NULL);
15177 if (dtrace_anon.dta_enabling != NULL) {
15181 * dtrace_enabling_retain() can only fail because we are
15182 * trying to retain more enablings than are allowed -- but
15183 * we only have one anonymous enabling, and we are guaranteed
15184 * to be allowed at least one retained enabling; we assert
15185 * that dtrace_enabling_retain() returns success.
15187 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15190 dtrace_enabling_dump(dtrace_anon.dta_enabling);
15195 * DTrace Helper Functions
15198 dtrace_helper_trace(dtrace_helper_action_t *helper,
15199 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15201 uint32_t size, next, nnext, i;
15202 dtrace_helptrace_t *ent;
15203 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15205 if (!dtrace_helptrace_enabled)
15208 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15211 * What would a tracing framework be without its own tracing
15212 * framework? (Well, a hell of a lot simpler, for starters...)
15214 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15215 sizeof (uint64_t) - sizeof (uint64_t);
15218 * Iterate until we can allocate a slot in the trace buffer.
15221 next = dtrace_helptrace_next;
15223 if (next + size < dtrace_helptrace_bufsize) {
15224 nnext = next + size;
15228 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15231 * We have our slot; fill it in.
15236 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
15237 ent->dtht_helper = helper;
15238 ent->dtht_where = where;
15239 ent->dtht_nlocals = vstate->dtvs_nlocals;
15241 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15242 mstate->dtms_fltoffs : -1;
15243 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15244 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15246 for (i = 0; i < vstate->dtvs_nlocals; i++) {
15247 dtrace_statvar_t *svar;
15249 if ((svar = vstate->dtvs_locals[i]) == NULL)
15252 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15253 ent->dtht_locals[i] =
15254 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15259 dtrace_helper(int which, dtrace_mstate_t *mstate,
15260 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15262 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15263 uint64_t sarg0 = mstate->dtms_arg[0];
15264 uint64_t sarg1 = mstate->dtms_arg[1];
15266 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15267 dtrace_helper_action_t *helper;
15268 dtrace_vstate_t *vstate;
15269 dtrace_difo_t *pred;
15270 int i, trace = dtrace_helptrace_enabled;
15272 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15274 if (helpers == NULL)
15277 if ((helper = helpers->dthps_actions[which]) == NULL)
15280 vstate = &helpers->dthps_vstate;
15281 mstate->dtms_arg[0] = arg0;
15282 mstate->dtms_arg[1] = arg1;
15285 * Now iterate over each helper. If its predicate evaluates to 'true',
15286 * we'll call the corresponding actions. Note that the below calls
15287 * to dtrace_dif_emulate() may set faults in machine state. This is
15288 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
15289 * the stored DIF offset with its own (which is the desired behavior).
15290 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15291 * from machine state; this is okay, too.
15293 for (; helper != NULL; helper = helper->dtha_next) {
15294 if ((pred = helper->dtha_predicate) != NULL) {
15296 dtrace_helper_trace(helper, mstate, vstate, 0);
15298 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15301 if (*flags & CPU_DTRACE_FAULT)
15305 for (i = 0; i < helper->dtha_nactions; i++) {
15307 dtrace_helper_trace(helper,
15308 mstate, vstate, i + 1);
15310 rval = dtrace_dif_emulate(helper->dtha_actions[i],
15311 mstate, vstate, state);
15313 if (*flags & CPU_DTRACE_FAULT)
15319 dtrace_helper_trace(helper, mstate, vstate,
15320 DTRACE_HELPTRACE_NEXT);
15324 dtrace_helper_trace(helper, mstate, vstate,
15325 DTRACE_HELPTRACE_DONE);
15328 * Restore the arg0 that we saved upon entry.
15330 mstate->dtms_arg[0] = sarg0;
15331 mstate->dtms_arg[1] = sarg1;
15337 dtrace_helper_trace(helper, mstate, vstate,
15338 DTRACE_HELPTRACE_ERR);
15341 * Restore the arg0 that we saved upon entry.
15343 mstate->dtms_arg[0] = sarg0;
15344 mstate->dtms_arg[1] = sarg1;
15350 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15351 dtrace_vstate_t *vstate)
15355 if (helper->dtha_predicate != NULL)
15356 dtrace_difo_release(helper->dtha_predicate, vstate);
15358 for (i = 0; i < helper->dtha_nactions; i++) {
15359 ASSERT(helper->dtha_actions[i] != NULL);
15360 dtrace_difo_release(helper->dtha_actions[i], vstate);
15363 kmem_free(helper->dtha_actions,
15364 helper->dtha_nactions * sizeof (dtrace_difo_t *));
15365 kmem_free(helper, sizeof (dtrace_helper_action_t));
15369 dtrace_helper_destroygen(int gen)
15371 proc_t *p = curproc;
15372 dtrace_helpers_t *help = p->p_dtrace_helpers;
15373 dtrace_vstate_t *vstate;
15376 ASSERT(MUTEX_HELD(&dtrace_lock));
15378 if (help == NULL || gen > help->dthps_generation)
15381 vstate = &help->dthps_vstate;
15383 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15384 dtrace_helper_action_t *last = NULL, *h, *next;
15386 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15387 next = h->dtha_next;
15389 if (h->dtha_generation == gen) {
15390 if (last != NULL) {
15391 last->dtha_next = next;
15393 help->dthps_actions[i] = next;
15396 dtrace_helper_action_destroy(h, vstate);
15404 * Interate until we've cleared out all helper providers with the
15405 * given generation number.
15408 dtrace_helper_provider_t *prov;
15411 * Look for a helper provider with the right generation. We
15412 * have to start back at the beginning of the list each time
15413 * because we drop dtrace_lock. It's unlikely that we'll make
15414 * more than two passes.
15416 for (i = 0; i < help->dthps_nprovs; i++) {
15417 prov = help->dthps_provs[i];
15419 if (prov->dthp_generation == gen)
15424 * If there were no matches, we're done.
15426 if (i == help->dthps_nprovs)
15430 * Move the last helper provider into this slot.
15432 help->dthps_nprovs--;
15433 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15434 help->dthps_provs[help->dthps_nprovs] = NULL;
15436 mutex_exit(&dtrace_lock);
15439 * If we have a meta provider, remove this helper provider.
15441 mutex_enter(&dtrace_meta_lock);
15442 if (dtrace_meta_pid != NULL) {
15443 ASSERT(dtrace_deferred_pid == NULL);
15444 dtrace_helper_provider_remove(&prov->dthp_prov,
15447 mutex_exit(&dtrace_meta_lock);
15449 dtrace_helper_provider_destroy(prov);
15451 mutex_enter(&dtrace_lock);
15458 dtrace_helper_validate(dtrace_helper_action_t *helper)
15463 if ((dp = helper->dtha_predicate) != NULL)
15464 err += dtrace_difo_validate_helper(dp);
15466 for (i = 0; i < helper->dtha_nactions; i++)
15467 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15473 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
15475 dtrace_helpers_t *help;
15476 dtrace_helper_action_t *helper, *last;
15477 dtrace_actdesc_t *act;
15478 dtrace_vstate_t *vstate;
15479 dtrace_predicate_t *pred;
15480 int count = 0, nactions = 0, i;
15482 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15485 help = curproc->p_dtrace_helpers;
15486 last = help->dthps_actions[which];
15487 vstate = &help->dthps_vstate;
15489 for (count = 0; last != NULL; last = last->dtha_next) {
15491 if (last->dtha_next == NULL)
15496 * If we already have dtrace_helper_actions_max helper actions for this
15497 * helper action type, we'll refuse to add a new one.
15499 if (count >= dtrace_helper_actions_max)
15502 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15503 helper->dtha_generation = help->dthps_generation;
15505 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15506 ASSERT(pred->dtp_difo != NULL);
15507 dtrace_difo_hold(pred->dtp_difo);
15508 helper->dtha_predicate = pred->dtp_difo;
15511 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15512 if (act->dtad_kind != DTRACEACT_DIFEXPR)
15515 if (act->dtad_difo == NULL)
15521 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15522 (helper->dtha_nactions = nactions), KM_SLEEP);
15524 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15525 dtrace_difo_hold(act->dtad_difo);
15526 helper->dtha_actions[i++] = act->dtad_difo;
15529 if (!dtrace_helper_validate(helper))
15532 if (last == NULL) {
15533 help->dthps_actions[which] = helper;
15535 last->dtha_next = helper;
15538 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15539 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15540 dtrace_helptrace_next = 0;
15545 dtrace_helper_action_destroy(helper, vstate);
15550 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15551 dof_helper_t *dofhp)
15553 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15555 mutex_enter(&dtrace_meta_lock);
15556 mutex_enter(&dtrace_lock);
15558 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15560 * If the dtrace module is loaded but not attached, or if
15561 * there aren't isn't a meta provider registered to deal with
15562 * these provider descriptions, we need to postpone creating
15563 * the actual providers until later.
15566 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15567 dtrace_deferred_pid != help) {
15568 help->dthps_deferred = 1;
15569 help->dthps_pid = p->p_pid;
15570 help->dthps_next = dtrace_deferred_pid;
15571 help->dthps_prev = NULL;
15572 if (dtrace_deferred_pid != NULL)
15573 dtrace_deferred_pid->dthps_prev = help;
15574 dtrace_deferred_pid = help;
15577 mutex_exit(&dtrace_lock);
15579 } else if (dofhp != NULL) {
15581 * If the dtrace module is loaded and we have a particular
15582 * helper provider description, pass that off to the
15586 mutex_exit(&dtrace_lock);
15588 dtrace_helper_provide(dofhp, p->p_pid);
15592 * Otherwise, just pass all the helper provider descriptions
15593 * off to the meta provider.
15597 mutex_exit(&dtrace_lock);
15599 for (i = 0; i < help->dthps_nprovs; i++) {
15600 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15605 mutex_exit(&dtrace_meta_lock);
15609 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15611 dtrace_helpers_t *help;
15612 dtrace_helper_provider_t *hprov, **tmp_provs;
15613 uint_t tmp_maxprovs, i;
15615 ASSERT(MUTEX_HELD(&dtrace_lock));
15617 help = curproc->p_dtrace_helpers;
15618 ASSERT(help != NULL);
15621 * If we already have dtrace_helper_providers_max helper providers,
15622 * we're refuse to add a new one.
15624 if (help->dthps_nprovs >= dtrace_helper_providers_max)
15628 * Check to make sure this isn't a duplicate.
15630 for (i = 0; i < help->dthps_nprovs; i++) {
15631 if (dofhp->dofhp_dof ==
15632 help->dthps_provs[i]->dthp_prov.dofhp_dof)
15636 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15637 hprov->dthp_prov = *dofhp;
15638 hprov->dthp_ref = 1;
15639 hprov->dthp_generation = gen;
15642 * Allocate a bigger table for helper providers if it's already full.
15644 if (help->dthps_maxprovs == help->dthps_nprovs) {
15645 tmp_maxprovs = help->dthps_maxprovs;
15646 tmp_provs = help->dthps_provs;
15648 if (help->dthps_maxprovs == 0)
15649 help->dthps_maxprovs = 2;
15651 help->dthps_maxprovs *= 2;
15652 if (help->dthps_maxprovs > dtrace_helper_providers_max)
15653 help->dthps_maxprovs = dtrace_helper_providers_max;
15655 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15657 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15658 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15660 if (tmp_provs != NULL) {
15661 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15662 sizeof (dtrace_helper_provider_t *));
15663 kmem_free(tmp_provs, tmp_maxprovs *
15664 sizeof (dtrace_helper_provider_t *));
15668 help->dthps_provs[help->dthps_nprovs] = hprov;
15669 help->dthps_nprovs++;
15675 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15677 mutex_enter(&dtrace_lock);
15679 if (--hprov->dthp_ref == 0) {
15681 mutex_exit(&dtrace_lock);
15682 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15683 dtrace_dof_destroy(dof);
15684 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15686 mutex_exit(&dtrace_lock);
15691 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15693 uintptr_t daddr = (uintptr_t)dof;
15694 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15695 dof_provider_t *provider;
15696 dof_probe_t *probe;
15698 char *strtab, *typestr;
15699 dof_stridx_t typeidx;
15701 uint_t nprobes, j, k;
15703 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15705 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15706 dtrace_dof_error(dof, "misaligned section offset");
15711 * The section needs to be large enough to contain the DOF provider
15712 * structure appropriate for the given version.
15714 if (sec->dofs_size <
15715 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15716 offsetof(dof_provider_t, dofpv_prenoffs) :
15717 sizeof (dof_provider_t))) {
15718 dtrace_dof_error(dof, "provider section too small");
15722 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15723 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15724 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15725 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15726 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15728 if (str_sec == NULL || prb_sec == NULL ||
15729 arg_sec == NULL || off_sec == NULL)
15734 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15735 provider->dofpv_prenoffs != DOF_SECT_NONE &&
15736 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15737 provider->dofpv_prenoffs)) == NULL)
15740 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15742 if (provider->dofpv_name >= str_sec->dofs_size ||
15743 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15744 dtrace_dof_error(dof, "invalid provider name");
15748 if (prb_sec->dofs_entsize == 0 ||
15749 prb_sec->dofs_entsize > prb_sec->dofs_size) {
15750 dtrace_dof_error(dof, "invalid entry size");
15754 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15755 dtrace_dof_error(dof, "misaligned entry size");
15759 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15760 dtrace_dof_error(dof, "invalid entry size");
15764 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15765 dtrace_dof_error(dof, "misaligned section offset");
15769 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15770 dtrace_dof_error(dof, "invalid entry size");
15774 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15776 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15779 * Take a pass through the probes to check for errors.
15781 for (j = 0; j < nprobes; j++) {
15782 probe = (dof_probe_t *)(uintptr_t)(daddr +
15783 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15785 if (probe->dofpr_func >= str_sec->dofs_size) {
15786 dtrace_dof_error(dof, "invalid function name");
15790 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15791 dtrace_dof_error(dof, "function name too long");
15795 if (probe->dofpr_name >= str_sec->dofs_size ||
15796 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15797 dtrace_dof_error(dof, "invalid probe name");
15802 * The offset count must not wrap the index, and the offsets
15803 * must also not overflow the section's data.
15805 if (probe->dofpr_offidx + probe->dofpr_noffs <
15806 probe->dofpr_offidx ||
15807 (probe->dofpr_offidx + probe->dofpr_noffs) *
15808 off_sec->dofs_entsize > off_sec->dofs_size) {
15809 dtrace_dof_error(dof, "invalid probe offset");
15813 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15815 * If there's no is-enabled offset section, make sure
15816 * there aren't any is-enabled offsets. Otherwise
15817 * perform the same checks as for probe offsets
15818 * (immediately above).
15820 if (enoff_sec == NULL) {
15821 if (probe->dofpr_enoffidx != 0 ||
15822 probe->dofpr_nenoffs != 0) {
15823 dtrace_dof_error(dof, "is-enabled "
15824 "offsets with null section");
15827 } else if (probe->dofpr_enoffidx +
15828 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15829 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15830 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15831 dtrace_dof_error(dof, "invalid is-enabled "
15836 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15837 dtrace_dof_error(dof, "zero probe and "
15838 "is-enabled offsets");
15841 } else if (probe->dofpr_noffs == 0) {
15842 dtrace_dof_error(dof, "zero probe offsets");
15846 if (probe->dofpr_argidx + probe->dofpr_xargc <
15847 probe->dofpr_argidx ||
15848 (probe->dofpr_argidx + probe->dofpr_xargc) *
15849 arg_sec->dofs_entsize > arg_sec->dofs_size) {
15850 dtrace_dof_error(dof, "invalid args");
15854 typeidx = probe->dofpr_nargv;
15855 typestr = strtab + probe->dofpr_nargv;
15856 for (k = 0; k < probe->dofpr_nargc; k++) {
15857 if (typeidx >= str_sec->dofs_size) {
15858 dtrace_dof_error(dof, "bad "
15859 "native argument type");
15863 typesz = strlen(typestr) + 1;
15864 if (typesz > DTRACE_ARGTYPELEN) {
15865 dtrace_dof_error(dof, "native "
15866 "argument type too long");
15873 typeidx = probe->dofpr_xargv;
15874 typestr = strtab + probe->dofpr_xargv;
15875 for (k = 0; k < probe->dofpr_xargc; k++) {
15876 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15877 dtrace_dof_error(dof, "bad "
15878 "native argument index");
15882 if (typeidx >= str_sec->dofs_size) {
15883 dtrace_dof_error(dof, "bad "
15884 "translated argument type");
15888 typesz = strlen(typestr) + 1;
15889 if (typesz > DTRACE_ARGTYPELEN) {
15890 dtrace_dof_error(dof, "translated argument "
15904 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15906 dtrace_helpers_t *help;
15907 dtrace_vstate_t *vstate;
15908 dtrace_enabling_t *enab = NULL;
15909 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15910 uintptr_t daddr = (uintptr_t)dof;
15912 ASSERT(MUTEX_HELD(&dtrace_lock));
15914 if ((help = curproc->p_dtrace_helpers) == NULL)
15915 help = dtrace_helpers_create(curproc);
15917 vstate = &help->dthps_vstate;
15919 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15920 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15921 dtrace_dof_destroy(dof);
15926 * Look for helper providers and validate their descriptions.
15929 for (i = 0; i < dof->dofh_secnum; i++) {
15930 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15931 dof->dofh_secoff + i * dof->dofh_secsize);
15933 if (sec->dofs_type != DOF_SECT_PROVIDER)
15936 if (dtrace_helper_provider_validate(dof, sec) != 0) {
15937 dtrace_enabling_destroy(enab);
15938 dtrace_dof_destroy(dof);
15947 * Now we need to walk through the ECB descriptions in the enabling.
15949 for (i = 0; i < enab->dten_ndesc; i++) {
15950 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15951 dtrace_probedesc_t *desc = &ep->dted_probe;
15953 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15956 if (strcmp(desc->dtpd_mod, "helper") != 0)
15959 if (strcmp(desc->dtpd_func, "ustack") != 0)
15962 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15965 * Adding this helper action failed -- we are now going
15966 * to rip out the entire generation and return failure.
15968 (void) dtrace_helper_destroygen(help->dthps_generation);
15969 dtrace_enabling_destroy(enab);
15970 dtrace_dof_destroy(dof);
15977 if (nhelpers < enab->dten_ndesc)
15978 dtrace_dof_error(dof, "unmatched helpers");
15980 gen = help->dthps_generation++;
15981 dtrace_enabling_destroy(enab);
15983 if (dhp != NULL && nprovs > 0) {
15984 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15985 if (dtrace_helper_provider_add(dhp, gen) == 0) {
15986 mutex_exit(&dtrace_lock);
15987 dtrace_helper_provider_register(curproc, help, dhp);
15988 mutex_enter(&dtrace_lock);
15995 dtrace_dof_destroy(dof);
16000 static dtrace_helpers_t *
16001 dtrace_helpers_create(proc_t *p)
16003 dtrace_helpers_t *help;
16005 ASSERT(MUTEX_HELD(&dtrace_lock));
16006 ASSERT(p->p_dtrace_helpers == NULL);
16008 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16009 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16010 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16012 p->p_dtrace_helpers = help;
16022 dtrace_helpers_destroy(proc_t *p)
16024 dtrace_helpers_t *help;
16025 dtrace_vstate_t *vstate;
16027 proc_t *p = curproc;
16031 mutex_enter(&dtrace_lock);
16033 ASSERT(p->p_dtrace_helpers != NULL);
16034 ASSERT(dtrace_helpers > 0);
16036 help = p->p_dtrace_helpers;
16037 vstate = &help->dthps_vstate;
16040 * We're now going to lose the help from this process.
16042 p->p_dtrace_helpers = NULL;
16046 * Destory the helper actions.
16048 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16049 dtrace_helper_action_t *h, *next;
16051 for (h = help->dthps_actions[i]; h != NULL; h = next) {
16052 next = h->dtha_next;
16053 dtrace_helper_action_destroy(h, vstate);
16058 mutex_exit(&dtrace_lock);
16061 * Destroy the helper providers.
16063 if (help->dthps_maxprovs > 0) {
16064 mutex_enter(&dtrace_meta_lock);
16065 if (dtrace_meta_pid != NULL) {
16066 ASSERT(dtrace_deferred_pid == NULL);
16068 for (i = 0; i < help->dthps_nprovs; i++) {
16069 dtrace_helper_provider_remove(
16070 &help->dthps_provs[i]->dthp_prov, p->p_pid);
16073 mutex_enter(&dtrace_lock);
16074 ASSERT(help->dthps_deferred == 0 ||
16075 help->dthps_next != NULL ||
16076 help->dthps_prev != NULL ||
16077 help == dtrace_deferred_pid);
16080 * Remove the helper from the deferred list.
16082 if (help->dthps_next != NULL)
16083 help->dthps_next->dthps_prev = help->dthps_prev;
16084 if (help->dthps_prev != NULL)
16085 help->dthps_prev->dthps_next = help->dthps_next;
16086 if (dtrace_deferred_pid == help) {
16087 dtrace_deferred_pid = help->dthps_next;
16088 ASSERT(help->dthps_prev == NULL);
16091 mutex_exit(&dtrace_lock);
16094 mutex_exit(&dtrace_meta_lock);
16096 for (i = 0; i < help->dthps_nprovs; i++) {
16097 dtrace_helper_provider_destroy(help->dthps_provs[i]);
16100 kmem_free(help->dthps_provs, help->dthps_maxprovs *
16101 sizeof (dtrace_helper_provider_t *));
16104 mutex_enter(&dtrace_lock);
16106 dtrace_vstate_fini(&help->dthps_vstate);
16107 kmem_free(help->dthps_actions,
16108 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16109 kmem_free(help, sizeof (dtrace_helpers_t));
16112 mutex_exit(&dtrace_lock);
16119 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16121 dtrace_helpers_t *help, *newhelp;
16122 dtrace_helper_action_t *helper, *new, *last;
16124 dtrace_vstate_t *vstate;
16125 int i, j, sz, hasprovs = 0;
16127 mutex_enter(&dtrace_lock);
16128 ASSERT(from->p_dtrace_helpers != NULL);
16129 ASSERT(dtrace_helpers > 0);
16131 help = from->p_dtrace_helpers;
16132 newhelp = dtrace_helpers_create(to);
16133 ASSERT(to->p_dtrace_helpers != NULL);
16135 newhelp->dthps_generation = help->dthps_generation;
16136 vstate = &newhelp->dthps_vstate;
16139 * Duplicate the helper actions.
16141 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16142 if ((helper = help->dthps_actions[i]) == NULL)
16145 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16146 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16148 new->dtha_generation = helper->dtha_generation;
16150 if ((dp = helper->dtha_predicate) != NULL) {
16151 dp = dtrace_difo_duplicate(dp, vstate);
16152 new->dtha_predicate = dp;
16155 new->dtha_nactions = helper->dtha_nactions;
16156 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16157 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16159 for (j = 0; j < new->dtha_nactions; j++) {
16160 dtrace_difo_t *dp = helper->dtha_actions[j];
16162 ASSERT(dp != NULL);
16163 dp = dtrace_difo_duplicate(dp, vstate);
16164 new->dtha_actions[j] = dp;
16167 if (last != NULL) {
16168 last->dtha_next = new;
16170 newhelp->dthps_actions[i] = new;
16178 * Duplicate the helper providers and register them with the
16179 * DTrace framework.
16181 if (help->dthps_nprovs > 0) {
16182 newhelp->dthps_nprovs = help->dthps_nprovs;
16183 newhelp->dthps_maxprovs = help->dthps_nprovs;
16184 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16185 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16186 for (i = 0; i < newhelp->dthps_nprovs; i++) {
16187 newhelp->dthps_provs[i] = help->dthps_provs[i];
16188 newhelp->dthps_provs[i]->dthp_ref++;
16194 mutex_exit(&dtrace_lock);
16197 dtrace_helper_provider_register(to, newhelp, NULL);
16201 * DTrace Hook Functions
16204 dtrace_module_loaded(modctl_t *ctl)
16206 dtrace_provider_t *prv;
16208 mutex_enter(&dtrace_provider_lock);
16210 mutex_enter(&mod_lock);
16214 ASSERT(ctl->mod_busy);
16218 * We're going to call each providers per-module provide operation
16219 * specifying only this module.
16221 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16222 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16225 mutex_exit(&mod_lock);
16227 mutex_exit(&dtrace_provider_lock);
16230 * If we have any retained enablings, we need to match against them.
16231 * Enabling probes requires that cpu_lock be held, and we cannot hold
16232 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16233 * module. (In particular, this happens when loading scheduling
16234 * classes.) So if we have any retained enablings, we need to dispatch
16235 * our task queue to do the match for us.
16237 mutex_enter(&dtrace_lock);
16239 if (dtrace_retained == NULL) {
16240 mutex_exit(&dtrace_lock);
16244 (void) taskq_dispatch(dtrace_taskq,
16245 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16247 mutex_exit(&dtrace_lock);
16250 * And now, for a little heuristic sleaze: in general, we want to
16251 * match modules as soon as they load. However, we cannot guarantee
16252 * this, because it would lead us to the lock ordering violation
16253 * outlined above. The common case, of course, is that cpu_lock is
16254 * _not_ held -- so we delay here for a clock tick, hoping that that's
16255 * long enough for the task queue to do its work. If it's not, it's
16256 * not a serious problem -- it just means that the module that we
16257 * just loaded may not be immediately instrumentable.
16264 dtrace_module_unloaded(modctl_t *ctl)
16266 dtrace_module_unloaded(modctl_t *ctl, int *error)
16269 dtrace_probe_t template, *probe, *first, *next;
16270 dtrace_provider_t *prov;
16272 char modname[DTRACE_MODNAMELEN];
16277 template.dtpr_mod = ctl->mod_modname;
16279 /* Handle the fact that ctl->filename may end in ".ko". */
16280 strlcpy(modname, ctl->filename, sizeof(modname));
16281 len = strlen(ctl->filename);
16282 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16283 modname[len - 3] = '\0';
16284 template.dtpr_mod = modname;
16287 mutex_enter(&dtrace_provider_lock);
16289 mutex_enter(&mod_lock);
16291 mutex_enter(&dtrace_lock);
16294 if (ctl->nenabled > 0) {
16295 /* Don't allow unloads if a probe is enabled. */
16296 mutex_exit(&dtrace_provider_lock);
16297 mutex_exit(&dtrace_lock);
16300 "kldunload: attempt to unload module that has DTrace probes enabled\n");
16305 if (dtrace_bymod == NULL) {
16307 * The DTrace module is loaded (obviously) but not attached;
16308 * we don't have any work to do.
16310 mutex_exit(&dtrace_provider_lock);
16312 mutex_exit(&mod_lock);
16314 mutex_exit(&dtrace_lock);
16318 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16319 probe != NULL; probe = probe->dtpr_nextmod) {
16320 if (probe->dtpr_ecb != NULL) {
16321 mutex_exit(&dtrace_provider_lock);
16323 mutex_exit(&mod_lock);
16325 mutex_exit(&dtrace_lock);
16328 * This shouldn't _actually_ be possible -- we're
16329 * unloading a module that has an enabled probe in it.
16330 * (It's normally up to the provider to make sure that
16331 * this can't happen.) However, because dtps_enable()
16332 * doesn't have a failure mode, there can be an
16333 * enable/unload race. Upshot: we don't want to
16334 * assert, but we're not going to disable the
16337 if (dtrace_err_verbose) {
16339 cmn_err(CE_WARN, "unloaded module '%s' had "
16340 "enabled probes", ctl->mod_modname);
16342 cmn_err(CE_WARN, "unloaded module '%s' had "
16343 "enabled probes", modname);
16353 for (first = NULL; probe != NULL; probe = next) {
16354 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16356 dtrace_probes[probe->dtpr_id - 1] = NULL;
16358 next = probe->dtpr_nextmod;
16359 dtrace_hash_remove(dtrace_bymod, probe);
16360 dtrace_hash_remove(dtrace_byfunc, probe);
16361 dtrace_hash_remove(dtrace_byname, probe);
16363 if (first == NULL) {
16365 probe->dtpr_nextmod = NULL;
16367 probe->dtpr_nextmod = first;
16373 * We've removed all of the module's probes from the hash chains and
16374 * from the probe array. Now issue a dtrace_sync() to be sure that
16375 * everyone has cleared out from any probe array processing.
16379 for (probe = first; probe != NULL; probe = first) {
16380 first = probe->dtpr_nextmod;
16381 prov = probe->dtpr_provider;
16382 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16384 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16385 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16386 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16388 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16390 free_unr(dtrace_arena, probe->dtpr_id);
16392 kmem_free(probe, sizeof (dtrace_probe_t));
16395 mutex_exit(&dtrace_lock);
16397 mutex_exit(&mod_lock);
16399 mutex_exit(&dtrace_provider_lock);
16404 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16407 dtrace_module_loaded(lf);
16411 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16415 /* We already have an error, so don't do anything. */
16417 dtrace_module_unloaded(lf, error);
16423 dtrace_suspend(void)
16425 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16429 dtrace_resume(void)
16431 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16436 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16438 ASSERT(MUTEX_HELD(&cpu_lock));
16439 mutex_enter(&dtrace_lock);
16443 dtrace_state_t *state;
16444 dtrace_optval_t *opt, rs, c;
16447 * For now, we only allocate a new buffer for anonymous state.
16449 if ((state = dtrace_anon.dta_state) == NULL)
16452 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16455 opt = state->dts_options;
16456 c = opt[DTRACEOPT_CPU];
16458 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16462 * Regardless of what the actual policy is, we're going to
16463 * temporarily set our resize policy to be manual. We're
16464 * also going to temporarily set our CPU option to denote
16465 * the newly configured CPU.
16467 rs = opt[DTRACEOPT_BUFRESIZE];
16468 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16469 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16471 (void) dtrace_state_buffers(state);
16473 opt[DTRACEOPT_BUFRESIZE] = rs;
16474 opt[DTRACEOPT_CPU] = c;
16481 * We don't free the buffer in the CPU_UNCONFIG case. (The
16482 * buffer will be freed when the consumer exits.)
16490 mutex_exit(&dtrace_lock);
16496 dtrace_cpu_setup_initial(processorid_t cpu)
16498 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16503 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16505 if (dtrace_toxranges >= dtrace_toxranges_max) {
16507 dtrace_toxrange_t *range;
16509 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16512 ASSERT(dtrace_toxrange == NULL);
16513 ASSERT(dtrace_toxranges_max == 0);
16514 dtrace_toxranges_max = 1;
16516 dtrace_toxranges_max <<= 1;
16519 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16520 range = kmem_zalloc(nsize, KM_SLEEP);
16522 if (dtrace_toxrange != NULL) {
16523 ASSERT(osize != 0);
16524 bcopy(dtrace_toxrange, range, osize);
16525 kmem_free(dtrace_toxrange, osize);
16528 dtrace_toxrange = range;
16531 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16532 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16534 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16535 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16536 dtrace_toxranges++;
16540 dtrace_getf_barrier()
16544 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
16545 * that contain calls to getf(), this routine will be called on every
16546 * closef() before either the underlying vnode is released or the
16547 * file_t itself is freed. By the time we are here, it is essential
16548 * that the file_t can no longer be accessed from a call to getf()
16549 * in probe context -- that assures that a dtrace_sync() can be used
16550 * to clear out any enablings referring to the old structures.
16552 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
16553 kcred->cr_zone->zone_dtrace_getf != 0)
16559 * DTrace Driver Cookbook Functions
16564 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16566 dtrace_provider_id_t id;
16567 dtrace_state_t *state = NULL;
16568 dtrace_enabling_t *enab;
16570 mutex_enter(&cpu_lock);
16571 mutex_enter(&dtrace_provider_lock);
16572 mutex_enter(&dtrace_lock);
16574 if (ddi_soft_state_init(&dtrace_softstate,
16575 sizeof (dtrace_state_t), 0) != 0) {
16576 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16577 mutex_exit(&cpu_lock);
16578 mutex_exit(&dtrace_provider_lock);
16579 mutex_exit(&dtrace_lock);
16580 return (DDI_FAILURE);
16583 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16584 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
16585 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16586 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
16587 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16588 ddi_remove_minor_node(devi, NULL);
16589 ddi_soft_state_fini(&dtrace_softstate);
16590 mutex_exit(&cpu_lock);
16591 mutex_exit(&dtrace_provider_lock);
16592 mutex_exit(&dtrace_lock);
16593 return (DDI_FAILURE);
16596 ddi_report_dev(devi);
16597 dtrace_devi = devi;
16599 dtrace_modload = dtrace_module_loaded;
16600 dtrace_modunload = dtrace_module_unloaded;
16601 dtrace_cpu_init = dtrace_cpu_setup_initial;
16602 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16603 dtrace_helpers_fork = dtrace_helpers_duplicate;
16604 dtrace_cpustart_init = dtrace_suspend;
16605 dtrace_cpustart_fini = dtrace_resume;
16606 dtrace_debugger_init = dtrace_suspend;
16607 dtrace_debugger_fini = dtrace_resume;
16609 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16611 ASSERT(MUTEX_HELD(&cpu_lock));
16613 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16614 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16615 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16616 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16617 VM_SLEEP | VMC_IDENTIFIER);
16618 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16621 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16622 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16623 NULL, NULL, NULL, NULL, NULL, 0);
16625 ASSERT(MUTEX_HELD(&cpu_lock));
16626 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16627 offsetof(dtrace_probe_t, dtpr_nextmod),
16628 offsetof(dtrace_probe_t, dtpr_prevmod));
16630 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16631 offsetof(dtrace_probe_t, dtpr_nextfunc),
16632 offsetof(dtrace_probe_t, dtpr_prevfunc));
16634 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16635 offsetof(dtrace_probe_t, dtpr_nextname),
16636 offsetof(dtrace_probe_t, dtpr_prevname));
16638 if (dtrace_retain_max < 1) {
16639 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16640 "setting to 1", dtrace_retain_max);
16641 dtrace_retain_max = 1;
16645 * Now discover our toxic ranges.
16647 dtrace_toxic_ranges(dtrace_toxrange_add);
16650 * Before we register ourselves as a provider to our own framework,
16651 * we would like to assert that dtrace_provider is NULL -- but that's
16652 * not true if we were loaded as a dependency of a DTrace provider.
16653 * Once we've registered, we can assert that dtrace_provider is our
16656 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16657 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16659 ASSERT(dtrace_provider != NULL);
16660 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16662 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16663 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16664 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16665 dtrace_provider, NULL, NULL, "END", 0, NULL);
16666 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16667 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16669 dtrace_anon_property();
16670 mutex_exit(&cpu_lock);
16673 * If DTrace helper tracing is enabled, we need to allocate the
16674 * trace buffer and initialize the values.
16676 if (dtrace_helptrace_enabled) {
16677 ASSERT(dtrace_helptrace_buffer == NULL);
16678 dtrace_helptrace_buffer =
16679 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16680 dtrace_helptrace_next = 0;
16684 * If there are already providers, we must ask them to provide their
16685 * probes, and then match any anonymous enabling against them. Note
16686 * that there should be no other retained enablings at this time:
16687 * the only retained enablings at this time should be the anonymous
16690 if (dtrace_anon.dta_enabling != NULL) {
16691 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16693 dtrace_enabling_provide(NULL);
16694 state = dtrace_anon.dta_state;
16697 * We couldn't hold cpu_lock across the above call to
16698 * dtrace_enabling_provide(), but we must hold it to actually
16699 * enable the probes. We have to drop all of our locks, pick
16700 * up cpu_lock, and regain our locks before matching the
16701 * retained anonymous enabling.
16703 mutex_exit(&dtrace_lock);
16704 mutex_exit(&dtrace_provider_lock);
16706 mutex_enter(&cpu_lock);
16707 mutex_enter(&dtrace_provider_lock);
16708 mutex_enter(&dtrace_lock);
16710 if ((enab = dtrace_anon.dta_enabling) != NULL)
16711 (void) dtrace_enabling_match(enab, NULL);
16713 mutex_exit(&cpu_lock);
16716 mutex_exit(&dtrace_lock);
16717 mutex_exit(&dtrace_provider_lock);
16719 if (state != NULL) {
16721 * If we created any anonymous state, set it going now.
16723 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16726 return (DDI_SUCCESS);
16731 #if __FreeBSD_version >= 800039
16732 static void dtrace_dtr(void *);
16739 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16741 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16744 dtrace_state_t *state;
16750 if (getminor(*devp) == DTRACEMNRN_HELPER)
16754 * If this wasn't an open with the "helper" minor, then it must be
16755 * the "dtrace" minor.
16757 if (getminor(*devp) == DTRACEMNRN_DTRACE)
16760 cred_t *cred_p = NULL;
16762 #if __FreeBSD_version < 800039
16764 * The first minor device is the one that is cloned so there is
16765 * nothing more to do here.
16767 if (dev2unit(dev) == 0)
16771 * Devices are cloned, so if the DTrace state has already
16772 * been allocated, that means this device belongs to a
16773 * different client. Each client should open '/dev/dtrace'
16774 * to get a cloned device.
16776 if (dev->si_drv1 != NULL)
16780 cred_p = dev->si_cred;
16784 * If no DTRACE_PRIV_* bits are set in the credential, then the
16785 * caller lacks sufficient permission to do anything with DTrace.
16787 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16788 if (priv == DTRACE_PRIV_NONE) {
16790 #if __FreeBSD_version < 800039
16791 /* Destroy the cloned device. */
16800 * Ask all providers to provide all their probes.
16802 mutex_enter(&dtrace_provider_lock);
16803 dtrace_probe_provide(NULL, NULL);
16804 mutex_exit(&dtrace_provider_lock);
16806 mutex_enter(&cpu_lock);
16807 mutex_enter(&dtrace_lock);
16809 dtrace_membar_producer();
16813 * If the kernel debugger is active (that is, if the kernel debugger
16814 * modified text in some way), we won't allow the open.
16816 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16818 mutex_exit(&cpu_lock);
16819 mutex_exit(&dtrace_lock);
16823 state = dtrace_state_create(devp, cred_p);
16825 state = dtrace_state_create(dev);
16826 #if __FreeBSD_version < 800039
16827 dev->si_drv1 = state;
16829 devfs_set_cdevpriv(state, dtrace_dtr);
16833 mutex_exit(&cpu_lock);
16835 if (state == NULL) {
16837 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16838 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16842 mutex_exit(&dtrace_lock);
16844 #if __FreeBSD_version < 800039
16845 /* Destroy the cloned device. */
16852 mutex_exit(&dtrace_lock);
16860 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16861 #elif __FreeBSD_version < 800039
16863 dtrace_close(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
16866 dtrace_dtr(void *data)
16870 minor_t minor = getminor(dev);
16871 dtrace_state_t *state;
16873 if (minor == DTRACEMNRN_HELPER)
16876 state = ddi_get_soft_state(dtrace_softstate, minor);
16878 #if __FreeBSD_version < 800039
16879 dtrace_state_t *state = dev->si_drv1;
16881 /* Check if this is not a cloned device. */
16882 if (dev2unit(dev) == 0)
16885 dtrace_state_t *state = data;
16890 mutex_enter(&cpu_lock);
16891 mutex_enter(&dtrace_lock);
16893 if (state != NULL) {
16894 if (state->dts_anon) {
16896 * There is anonymous state. Destroy that first.
16898 ASSERT(dtrace_anon.dta_state == NULL);
16899 dtrace_state_destroy(state->dts_anon);
16902 dtrace_state_destroy(state);
16905 kmem_free(state, 0);
16906 #if __FreeBSD_version < 800039
16907 dev->si_drv1 = NULL;
16912 ASSERT(dtrace_opens > 0);
16915 * Only relinquish control of the kernel debugger interface when there
16916 * are no consumers and no anonymous enablings.
16918 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16919 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16924 mutex_exit(&dtrace_lock);
16925 mutex_exit(&cpu_lock);
16927 #if __FreeBSD_version < 800039
16928 /* Schedule this cloned device to be destroyed. */
16929 destroy_dev_sched(dev);
16932 #if defined(sun) || __FreeBSD_version < 800039
16940 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16943 dof_helper_t help, *dhp = NULL;
16946 case DTRACEHIOC_ADDDOF:
16947 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16948 dtrace_dof_error(NULL, "failed to copyin DOF helper");
16953 arg = (intptr_t)help.dofhp_dof;
16956 case DTRACEHIOC_ADD: {
16957 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16962 mutex_enter(&dtrace_lock);
16965 * dtrace_helper_slurp() takes responsibility for the dof --
16966 * it may free it now or it may save it and free it later.
16968 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16975 mutex_exit(&dtrace_lock);
16979 case DTRACEHIOC_REMOVE: {
16980 mutex_enter(&dtrace_lock);
16981 rval = dtrace_helper_destroygen(arg);
16982 mutex_exit(&dtrace_lock);
16996 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16998 minor_t minor = getminor(dev);
16999 dtrace_state_t *state;
17002 if (minor == DTRACEMNRN_HELPER)
17003 return (dtrace_ioctl_helper(cmd, arg, rv));
17005 state = ddi_get_soft_state(dtrace_softstate, minor);
17007 if (state->dts_anon) {
17008 ASSERT(dtrace_anon.dta_state == NULL);
17009 state = state->dts_anon;
17013 case DTRACEIOC_PROVIDER: {
17014 dtrace_providerdesc_t pvd;
17015 dtrace_provider_t *pvp;
17017 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17020 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17021 mutex_enter(&dtrace_provider_lock);
17023 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17024 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17028 mutex_exit(&dtrace_provider_lock);
17033 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17034 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17036 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17042 case DTRACEIOC_EPROBE: {
17043 dtrace_eprobedesc_t epdesc;
17045 dtrace_action_t *act;
17051 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17054 mutex_enter(&dtrace_lock);
17056 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17057 mutex_exit(&dtrace_lock);
17061 if (ecb->dte_probe == NULL) {
17062 mutex_exit(&dtrace_lock);
17066 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17067 epdesc.dtepd_uarg = ecb->dte_uarg;
17068 epdesc.dtepd_size = ecb->dte_size;
17070 nrecs = epdesc.dtepd_nrecs;
17071 epdesc.dtepd_nrecs = 0;
17072 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17073 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17076 epdesc.dtepd_nrecs++;
17080 * Now that we have the size, we need to allocate a temporary
17081 * buffer in which to store the complete description. We need
17082 * the temporary buffer to be able to drop dtrace_lock()
17083 * across the copyout(), below.
17085 size = sizeof (dtrace_eprobedesc_t) +
17086 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17088 buf = kmem_alloc(size, KM_SLEEP);
17089 dest = (uintptr_t)buf;
17091 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17092 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17094 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17095 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17101 bcopy(&act->dta_rec, (void *)dest,
17102 sizeof (dtrace_recdesc_t));
17103 dest += sizeof (dtrace_recdesc_t);
17106 mutex_exit(&dtrace_lock);
17108 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17109 kmem_free(buf, size);
17113 kmem_free(buf, size);
17117 case DTRACEIOC_AGGDESC: {
17118 dtrace_aggdesc_t aggdesc;
17119 dtrace_action_t *act;
17120 dtrace_aggregation_t *agg;
17123 dtrace_recdesc_t *lrec;
17128 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17131 mutex_enter(&dtrace_lock);
17133 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17134 mutex_exit(&dtrace_lock);
17138 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17140 nrecs = aggdesc.dtagd_nrecs;
17141 aggdesc.dtagd_nrecs = 0;
17143 offs = agg->dtag_base;
17144 lrec = &agg->dtag_action.dta_rec;
17145 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17147 for (act = agg->dtag_first; ; act = act->dta_next) {
17148 ASSERT(act->dta_intuple ||
17149 DTRACEACT_ISAGG(act->dta_kind));
17152 * If this action has a record size of zero, it
17153 * denotes an argument to the aggregating action.
17154 * Because the presence of this record doesn't (or
17155 * shouldn't) affect the way the data is interpreted,
17156 * we don't copy it out to save user-level the
17157 * confusion of dealing with a zero-length record.
17159 if (act->dta_rec.dtrd_size == 0) {
17160 ASSERT(agg->dtag_hasarg);
17164 aggdesc.dtagd_nrecs++;
17166 if (act == &agg->dtag_action)
17171 * Now that we have the size, we need to allocate a temporary
17172 * buffer in which to store the complete description. We need
17173 * the temporary buffer to be able to drop dtrace_lock()
17174 * across the copyout(), below.
17176 size = sizeof (dtrace_aggdesc_t) +
17177 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17179 buf = kmem_alloc(size, KM_SLEEP);
17180 dest = (uintptr_t)buf;
17182 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17183 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17185 for (act = agg->dtag_first; ; act = act->dta_next) {
17186 dtrace_recdesc_t rec = act->dta_rec;
17189 * See the comment in the above loop for why we pass
17190 * over zero-length records.
17192 if (rec.dtrd_size == 0) {
17193 ASSERT(agg->dtag_hasarg);
17200 rec.dtrd_offset -= offs;
17201 bcopy(&rec, (void *)dest, sizeof (rec));
17202 dest += sizeof (dtrace_recdesc_t);
17204 if (act == &agg->dtag_action)
17208 mutex_exit(&dtrace_lock);
17210 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17211 kmem_free(buf, size);
17215 kmem_free(buf, size);
17219 case DTRACEIOC_ENABLE: {
17221 dtrace_enabling_t *enab = NULL;
17222 dtrace_vstate_t *vstate;
17228 * If a NULL argument has been passed, we take this as our
17229 * cue to reevaluate our enablings.
17232 dtrace_enabling_matchall();
17237 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17240 mutex_enter(&cpu_lock);
17241 mutex_enter(&dtrace_lock);
17242 vstate = &state->dts_vstate;
17244 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17245 mutex_exit(&dtrace_lock);
17246 mutex_exit(&cpu_lock);
17247 dtrace_dof_destroy(dof);
17251 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17252 mutex_exit(&dtrace_lock);
17253 mutex_exit(&cpu_lock);
17254 dtrace_dof_destroy(dof);
17258 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17259 dtrace_enabling_destroy(enab);
17260 mutex_exit(&dtrace_lock);
17261 mutex_exit(&cpu_lock);
17262 dtrace_dof_destroy(dof);
17266 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17267 err = dtrace_enabling_retain(enab);
17269 dtrace_enabling_destroy(enab);
17272 mutex_exit(&cpu_lock);
17273 mutex_exit(&dtrace_lock);
17274 dtrace_dof_destroy(dof);
17279 case DTRACEIOC_REPLICATE: {
17280 dtrace_repldesc_t desc;
17281 dtrace_probedesc_t *match = &desc.dtrpd_match;
17282 dtrace_probedesc_t *create = &desc.dtrpd_create;
17285 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17288 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17289 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17290 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17291 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17293 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17294 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17295 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17296 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17298 mutex_enter(&dtrace_lock);
17299 err = dtrace_enabling_replicate(state, match, create);
17300 mutex_exit(&dtrace_lock);
17305 case DTRACEIOC_PROBEMATCH:
17306 case DTRACEIOC_PROBES: {
17307 dtrace_probe_t *probe = NULL;
17308 dtrace_probedesc_t desc;
17309 dtrace_probekey_t pkey;
17316 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17319 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17320 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17321 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17322 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17325 * Before we attempt to match this probe, we want to give
17326 * all providers the opportunity to provide it.
17328 if (desc.dtpd_id == DTRACE_IDNONE) {
17329 mutex_enter(&dtrace_provider_lock);
17330 dtrace_probe_provide(&desc, NULL);
17331 mutex_exit(&dtrace_provider_lock);
17335 if (cmd == DTRACEIOC_PROBEMATCH) {
17336 dtrace_probekey(&desc, &pkey);
17337 pkey.dtpk_id = DTRACE_IDNONE;
17340 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17342 mutex_enter(&dtrace_lock);
17344 if (cmd == DTRACEIOC_PROBEMATCH) {
17345 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17346 if ((probe = dtrace_probes[i - 1]) != NULL &&
17347 (m = dtrace_match_probe(probe, &pkey,
17348 priv, uid, zoneid)) != 0)
17353 mutex_exit(&dtrace_lock);
17358 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17359 if ((probe = dtrace_probes[i - 1]) != NULL &&
17360 dtrace_match_priv(probe, priv, uid, zoneid))
17365 if (probe == NULL) {
17366 mutex_exit(&dtrace_lock);
17370 dtrace_probe_description(probe, &desc);
17371 mutex_exit(&dtrace_lock);
17373 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17379 case DTRACEIOC_PROBEARG: {
17380 dtrace_argdesc_t desc;
17381 dtrace_probe_t *probe;
17382 dtrace_provider_t *prov;
17384 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17387 if (desc.dtargd_id == DTRACE_IDNONE)
17390 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17393 mutex_enter(&dtrace_provider_lock);
17394 mutex_enter(&mod_lock);
17395 mutex_enter(&dtrace_lock);
17397 if (desc.dtargd_id > dtrace_nprobes) {
17398 mutex_exit(&dtrace_lock);
17399 mutex_exit(&mod_lock);
17400 mutex_exit(&dtrace_provider_lock);
17404 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17405 mutex_exit(&dtrace_lock);
17406 mutex_exit(&mod_lock);
17407 mutex_exit(&dtrace_provider_lock);
17411 mutex_exit(&dtrace_lock);
17413 prov = probe->dtpr_provider;
17415 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17417 * There isn't any typed information for this probe.
17418 * Set the argument number to DTRACE_ARGNONE.
17420 desc.dtargd_ndx = DTRACE_ARGNONE;
17422 desc.dtargd_native[0] = '\0';
17423 desc.dtargd_xlate[0] = '\0';
17424 desc.dtargd_mapping = desc.dtargd_ndx;
17426 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17427 probe->dtpr_id, probe->dtpr_arg, &desc);
17430 mutex_exit(&mod_lock);
17431 mutex_exit(&dtrace_provider_lock);
17433 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17439 case DTRACEIOC_GO: {
17440 processorid_t cpuid;
17441 rval = dtrace_state_go(state, &cpuid);
17446 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17452 case DTRACEIOC_STOP: {
17453 processorid_t cpuid;
17455 mutex_enter(&dtrace_lock);
17456 rval = dtrace_state_stop(state, &cpuid);
17457 mutex_exit(&dtrace_lock);
17462 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17468 case DTRACEIOC_DOFGET: {
17469 dof_hdr_t hdr, *dof;
17472 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17475 mutex_enter(&dtrace_lock);
17476 dof = dtrace_dof_create(state);
17477 mutex_exit(&dtrace_lock);
17479 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17480 rval = copyout(dof, (void *)arg, len);
17481 dtrace_dof_destroy(dof);
17483 return (rval == 0 ? 0 : EFAULT);
17486 case DTRACEIOC_AGGSNAP:
17487 case DTRACEIOC_BUFSNAP: {
17488 dtrace_bufdesc_t desc;
17490 dtrace_buffer_t *buf;
17492 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17495 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17498 mutex_enter(&dtrace_lock);
17500 if (cmd == DTRACEIOC_BUFSNAP) {
17501 buf = &state->dts_buffer[desc.dtbd_cpu];
17503 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17506 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17507 size_t sz = buf->dtb_offset;
17509 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17510 mutex_exit(&dtrace_lock);
17515 * If this buffer has already been consumed, we're
17516 * going to indicate that there's nothing left here
17519 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17520 mutex_exit(&dtrace_lock);
17522 desc.dtbd_size = 0;
17523 desc.dtbd_drops = 0;
17524 desc.dtbd_errors = 0;
17525 desc.dtbd_oldest = 0;
17526 sz = sizeof (desc);
17528 if (copyout(&desc, (void *)arg, sz) != 0)
17535 * If this is a ring buffer that has wrapped, we want
17536 * to copy the whole thing out.
17538 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17539 dtrace_buffer_polish(buf);
17540 sz = buf->dtb_size;
17543 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17544 mutex_exit(&dtrace_lock);
17548 desc.dtbd_size = sz;
17549 desc.dtbd_drops = buf->dtb_drops;
17550 desc.dtbd_errors = buf->dtb_errors;
17551 desc.dtbd_oldest = buf->dtb_xamot_offset;
17552 desc.dtbd_timestamp = dtrace_gethrtime();
17554 mutex_exit(&dtrace_lock);
17556 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17559 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17564 if (buf->dtb_tomax == NULL) {
17565 ASSERT(buf->dtb_xamot == NULL);
17566 mutex_exit(&dtrace_lock);
17570 cached = buf->dtb_tomax;
17571 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17573 dtrace_xcall(desc.dtbd_cpu,
17574 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17576 state->dts_errors += buf->dtb_xamot_errors;
17579 * If the buffers did not actually switch, then the cross call
17580 * did not take place -- presumably because the given CPU is
17581 * not in the ready set. If this is the case, we'll return
17584 if (buf->dtb_tomax == cached) {
17585 ASSERT(buf->dtb_xamot != cached);
17586 mutex_exit(&dtrace_lock);
17590 ASSERT(cached == buf->dtb_xamot);
17593 * We have our snapshot; now copy it out.
17595 if (copyout(buf->dtb_xamot, desc.dtbd_data,
17596 buf->dtb_xamot_offset) != 0) {
17597 mutex_exit(&dtrace_lock);
17601 desc.dtbd_size = buf->dtb_xamot_offset;
17602 desc.dtbd_drops = buf->dtb_xamot_drops;
17603 desc.dtbd_errors = buf->dtb_xamot_errors;
17604 desc.dtbd_oldest = 0;
17605 desc.dtbd_timestamp = buf->dtb_switched;
17607 mutex_exit(&dtrace_lock);
17610 * Finally, copy out the buffer description.
17612 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17618 case DTRACEIOC_CONF: {
17619 dtrace_conf_t conf;
17621 bzero(&conf, sizeof (conf));
17622 conf.dtc_difversion = DIF_VERSION;
17623 conf.dtc_difintregs = DIF_DIR_NREGS;
17624 conf.dtc_diftupregs = DIF_DTR_NREGS;
17625 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17627 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17633 case DTRACEIOC_STATUS: {
17634 dtrace_status_t stat;
17635 dtrace_dstate_t *dstate;
17640 * See the comment in dtrace_state_deadman() for the reason
17641 * for setting dts_laststatus to INT64_MAX before setting
17642 * it to the correct value.
17644 state->dts_laststatus = INT64_MAX;
17645 dtrace_membar_producer();
17646 state->dts_laststatus = dtrace_gethrtime();
17648 bzero(&stat, sizeof (stat));
17650 mutex_enter(&dtrace_lock);
17652 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17653 mutex_exit(&dtrace_lock);
17657 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17658 stat.dtst_exiting = 1;
17660 nerrs = state->dts_errors;
17661 dstate = &state->dts_vstate.dtvs_dynvars;
17663 for (i = 0; i < NCPU; i++) {
17664 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17666 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17667 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17668 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17670 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17671 stat.dtst_filled++;
17673 nerrs += state->dts_buffer[i].dtb_errors;
17675 for (j = 0; j < state->dts_nspeculations; j++) {
17676 dtrace_speculation_t *spec;
17677 dtrace_buffer_t *buf;
17679 spec = &state->dts_speculations[j];
17680 buf = &spec->dtsp_buffer[i];
17681 stat.dtst_specdrops += buf->dtb_xamot_drops;
17685 stat.dtst_specdrops_busy = state->dts_speculations_busy;
17686 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17687 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17688 stat.dtst_dblerrors = state->dts_dblerrors;
17690 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17691 stat.dtst_errors = nerrs;
17693 mutex_exit(&dtrace_lock);
17695 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17701 case DTRACEIOC_FORMAT: {
17702 dtrace_fmtdesc_t fmt;
17706 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17709 mutex_enter(&dtrace_lock);
17711 if (fmt.dtfd_format == 0 ||
17712 fmt.dtfd_format > state->dts_nformats) {
17713 mutex_exit(&dtrace_lock);
17718 * Format strings are allocated contiguously and they are
17719 * never freed; if a format index is less than the number
17720 * of formats, we can assert that the format map is non-NULL
17721 * and that the format for the specified index is non-NULL.
17723 ASSERT(state->dts_formats != NULL);
17724 str = state->dts_formats[fmt.dtfd_format - 1];
17725 ASSERT(str != NULL);
17727 len = strlen(str) + 1;
17729 if (len > fmt.dtfd_length) {
17730 fmt.dtfd_length = len;
17732 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17733 mutex_exit(&dtrace_lock);
17737 if (copyout(str, fmt.dtfd_string, len) != 0) {
17738 mutex_exit(&dtrace_lock);
17743 mutex_exit(&dtrace_lock);
17756 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17758 dtrace_state_t *state;
17765 return (DDI_SUCCESS);
17768 return (DDI_FAILURE);
17771 mutex_enter(&cpu_lock);
17772 mutex_enter(&dtrace_provider_lock);
17773 mutex_enter(&dtrace_lock);
17775 ASSERT(dtrace_opens == 0);
17777 if (dtrace_helpers > 0) {
17778 mutex_exit(&dtrace_provider_lock);
17779 mutex_exit(&dtrace_lock);
17780 mutex_exit(&cpu_lock);
17781 return (DDI_FAILURE);
17784 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17785 mutex_exit(&dtrace_provider_lock);
17786 mutex_exit(&dtrace_lock);
17787 mutex_exit(&cpu_lock);
17788 return (DDI_FAILURE);
17791 dtrace_provider = NULL;
17793 if ((state = dtrace_anon_grab()) != NULL) {
17795 * If there were ECBs on this state, the provider should
17796 * have not been allowed to detach; assert that there is
17799 ASSERT(state->dts_necbs == 0);
17800 dtrace_state_destroy(state);
17803 * If we're being detached with anonymous state, we need to
17804 * indicate to the kernel debugger that DTrace is now inactive.
17806 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17809 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17810 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17811 dtrace_cpu_init = NULL;
17812 dtrace_helpers_cleanup = NULL;
17813 dtrace_helpers_fork = NULL;
17814 dtrace_cpustart_init = NULL;
17815 dtrace_cpustart_fini = NULL;
17816 dtrace_debugger_init = NULL;
17817 dtrace_debugger_fini = NULL;
17818 dtrace_modload = NULL;
17819 dtrace_modunload = NULL;
17821 ASSERT(dtrace_getf == 0);
17822 ASSERT(dtrace_closef == NULL);
17824 mutex_exit(&cpu_lock);
17826 if (dtrace_helptrace_enabled) {
17827 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17828 dtrace_helptrace_buffer = NULL;
17831 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17832 dtrace_probes = NULL;
17833 dtrace_nprobes = 0;
17835 dtrace_hash_destroy(dtrace_bymod);
17836 dtrace_hash_destroy(dtrace_byfunc);
17837 dtrace_hash_destroy(dtrace_byname);
17838 dtrace_bymod = NULL;
17839 dtrace_byfunc = NULL;
17840 dtrace_byname = NULL;
17842 kmem_cache_destroy(dtrace_state_cache);
17843 vmem_destroy(dtrace_minor);
17844 vmem_destroy(dtrace_arena);
17846 if (dtrace_toxrange != NULL) {
17847 kmem_free(dtrace_toxrange,
17848 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17849 dtrace_toxrange = NULL;
17850 dtrace_toxranges = 0;
17851 dtrace_toxranges_max = 0;
17854 ddi_remove_minor_node(dtrace_devi, NULL);
17855 dtrace_devi = NULL;
17857 ddi_soft_state_fini(&dtrace_softstate);
17859 ASSERT(dtrace_vtime_references == 0);
17860 ASSERT(dtrace_opens == 0);
17861 ASSERT(dtrace_retained == NULL);
17863 mutex_exit(&dtrace_lock);
17864 mutex_exit(&dtrace_provider_lock);
17867 * We don't destroy the task queue until after we have dropped our
17868 * locks (taskq_destroy() may block on running tasks). To prevent
17869 * attempting to do work after we have effectively detached but before
17870 * the task queue has been destroyed, all tasks dispatched via the
17871 * task queue must check that DTrace is still attached before
17872 * performing any operation.
17874 taskq_destroy(dtrace_taskq);
17875 dtrace_taskq = NULL;
17877 return (DDI_SUCCESS);
17884 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17889 case DDI_INFO_DEVT2DEVINFO:
17890 *result = (void *)dtrace_devi;
17891 error = DDI_SUCCESS;
17893 case DDI_INFO_DEVT2INSTANCE:
17894 *result = (void *)0;
17895 error = DDI_SUCCESS;
17898 error = DDI_FAILURE;
17905 static struct cb_ops dtrace_cb_ops = {
17906 dtrace_open, /* open */
17907 dtrace_close, /* close */
17908 nulldev, /* strategy */
17909 nulldev, /* print */
17913 dtrace_ioctl, /* ioctl */
17914 nodev, /* devmap */
17916 nodev, /* segmap */
17917 nochpoll, /* poll */
17918 ddi_prop_op, /* cb_prop_op */
17920 D_NEW | D_MP /* Driver compatibility flag */
17923 static struct dev_ops dtrace_ops = {
17924 DEVO_REV, /* devo_rev */
17926 dtrace_info, /* get_dev_info */
17927 nulldev, /* identify */
17928 nulldev, /* probe */
17929 dtrace_attach, /* attach */
17930 dtrace_detach, /* detach */
17932 &dtrace_cb_ops, /* driver operations */
17933 NULL, /* bus operations */
17934 nodev /* dev power */
17937 static struct modldrv modldrv = {
17938 &mod_driverops, /* module type (this is a pseudo driver) */
17939 "Dynamic Tracing", /* name of module */
17940 &dtrace_ops, /* driver ops */
17943 static struct modlinkage modlinkage = {
17952 return (mod_install(&modlinkage));
17956 _info(struct modinfo *modinfop)
17958 return (mod_info(&modlinkage, modinfop));
17964 return (mod_remove(&modlinkage));
17968 static d_ioctl_t dtrace_ioctl;
17969 static d_ioctl_t dtrace_ioctl_helper;
17970 static void dtrace_load(void *);
17971 static int dtrace_unload(void);
17972 #if __FreeBSD_version < 800039
17973 static void dtrace_clone(void *, struct ucred *, char *, int , struct cdev **);
17974 static struct clonedevs *dtrace_clones; /* Ptr to the array of cloned devices. */
17975 static eventhandler_tag eh_tag; /* Event handler tag. */
17977 static struct cdev *dtrace_dev;
17978 static struct cdev *helper_dev;
17981 void dtrace_invop_init(void);
17982 void dtrace_invop_uninit(void);
17984 static struct cdevsw dtrace_cdevsw = {
17985 .d_version = D_VERSION,
17986 #if __FreeBSD_version < 800039
17987 .d_flags = D_TRACKCLOSE | D_NEEDMINOR,
17988 .d_close = dtrace_close,
17990 .d_ioctl = dtrace_ioctl,
17991 .d_open = dtrace_open,
17992 .d_name = "dtrace",
17995 static struct cdevsw helper_cdevsw = {
17996 .d_version = D_VERSION,
17997 .d_ioctl = dtrace_ioctl_helper,
17998 .d_name = "helper",
18001 #include <dtrace_anon.c>
18002 #if __FreeBSD_version < 800039
18003 #include <dtrace_clone.c>
18005 #include <dtrace_ioctl.c>
18006 #include <dtrace_load.c>
18007 #include <dtrace_modevent.c>
18008 #include <dtrace_sysctl.c>
18009 #include <dtrace_unload.c>
18010 #include <dtrace_vtime.c>
18011 #include <dtrace_hacks.c>
18012 #include <dtrace_isa.c>
18014 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18015 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18016 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18018 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18019 MODULE_VERSION(dtrace, 1);
18020 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
18021 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);