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, 2014 by Delphix. All rights reserved.
31 * DTrace - Dynamic Tracing for Solaris
33 * This is the implementation of the Solaris Dynamic Tracing framework
34 * (DTrace). The user-visible interface to DTrace is described at length in
35 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
36 * library, the in-kernel DTrace framework, and the DTrace providers are
37 * described in the block comments in the <sys/dtrace.h> header file. The
38 * internal architecture of DTrace is described in the block comments in the
39 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
40 * implementation very much assume mastery of all of these sources; if one has
41 * an unanswered question about the implementation, one should consult them
44 * The functions here are ordered roughly as follows:
46 * - Probe context functions
47 * - Probe hashing functions
48 * - Non-probe context utility functions
49 * - Matching functions
50 * - Provider-to-Framework API functions
51 * - Probe management functions
52 * - DIF object functions
54 * - Predicate functions
57 * - Enabling functions
59 * - Anonymous enabling functions
60 * - Consumer state functions
63 * - Driver cookbook functions
65 * Each group of functions begins with a block comment labelled the "DTrace
66 * [Group] Functions", allowing one to find each block by searching forward
67 * on capital-f functions.
69 #include <sys/errno.h>
74 #include <sys/modctl.h>
76 #include <sys/systm.h>
79 #include <sys/sunddi.h>
81 #include <sys/cpuvar.h>
84 #include <sys/strsubr.h>
86 #include <sys/sysmacros.h>
87 #include <sys/dtrace_impl.h>
88 #include <sys/atomic.h>
89 #include <sys/cmn_err.h>
91 #include <sys/mutex_impl.h>
92 #include <sys/rwlock_impl.h>
94 #include <sys/ctf_api.h>
96 #include <sys/panic.h>
97 #include <sys/priv_impl.h>
99 #include <sys/policy.h>
101 #include <sys/cred_impl.h>
102 #include <sys/procfs_isa.h>
104 #include <sys/taskq.h>
106 #include <sys/mkdev.h>
109 #include <sys/zone.h>
110 #include <sys/socket.h>
111 #include <netinet/in.h>
112 #include "strtolctype.h"
114 /* FreeBSD includes: */
116 #include <sys/callout.h>
117 #include <sys/ctype.h>
118 #include <sys/eventhandler.h>
119 #include <sys/limits.h>
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_statvar_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 = MSEC2NSEC(500); /* 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 * These variables should be set dynamically to enable helper tracing. The
356 * only variables that should be set are dtrace_helptrace_enable (which should
357 * be set to a non-zero value to allocate helper tracing buffers on the next
358 * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
359 * non-zero value to deallocate helper tracing buffers on the next close of
360 * /dev/dtrace). When (and only when) helper tracing is disabled, the
361 * buffer size may also be set via dtrace_helptrace_bufsize.
363 int dtrace_helptrace_enable = 0;
364 int dtrace_helptrace_disable = 0;
365 int dtrace_helptrace_bufsize = 16 * 1024 * 1024;
366 uint32_t dtrace_helptrace_nlocals;
367 static dtrace_helptrace_t *dtrace_helptrace_buffer;
368 static uint32_t dtrace_helptrace_next = 0;
369 static int dtrace_helptrace_wrapped = 0;
372 * DTrace Error Hashing
374 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
375 * table. This is very useful for checking coverage of tests that are
376 * expected to induce DIF or DOF processing errors, and may be useful for
377 * debugging problems in the DIF code generator or in DOF generation . The
378 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
381 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
382 static const char *dtrace_errlast;
383 static kthread_t *dtrace_errthread;
384 static kmutex_t dtrace_errlock;
388 * DTrace Macros and Constants
390 * These are various macros that are useful in various spots in the
391 * implementation, along with a few random constants that have no meaning
392 * outside of the implementation. There is no real structure to this cpp
393 * mishmash -- but is there ever?
395 #define DTRACE_HASHSTR(hash, probe) \
396 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
398 #define DTRACE_HASHNEXT(hash, probe) \
399 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
401 #define DTRACE_HASHPREV(hash, probe) \
402 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
404 #define DTRACE_HASHEQ(hash, lhs, rhs) \
405 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
406 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
408 #define DTRACE_AGGHASHSIZE_SLEW 17
410 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
413 * The key for a thread-local variable consists of the lower 61 bits of the
414 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
415 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
416 * equal to a variable identifier. This is necessary (but not sufficient) to
417 * assure that global associative arrays never collide with thread-local
418 * variables. To guarantee that they cannot collide, we must also define the
419 * order for keying dynamic variables. That order is:
421 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
423 * Because the variable-key and the tls-key are in orthogonal spaces, there is
424 * no way for a global variable key signature to match a thread-local key
428 #define DTRACE_TLS_THRKEY(where) { \
430 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
431 for (; actv; actv >>= 1) \
433 ASSERT(intr < (1 << 3)); \
434 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
435 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
438 #define DTRACE_TLS_THRKEY(where) { \
439 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
441 uint_t actv = _c->cpu_intr_actv; \
442 for (; actv; actv >>= 1) \
444 ASSERT(intr < (1 << 3)); \
445 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
446 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
450 #define DT_BSWAP_8(x) ((x) & 0xff)
451 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
452 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
453 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
455 #define DT_MASK_LO 0x00000000FFFFFFFFULL
457 #define DTRACE_STORE(type, tomax, offset, what) \
458 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
461 #define DTRACE_ALIGNCHECK(addr, size, flags) \
462 if (addr & (size - 1)) { \
463 *flags |= CPU_DTRACE_BADALIGN; \
464 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
468 #define DTRACE_ALIGNCHECK(addr, size, flags)
472 * Test whether a range of memory starting at testaddr of size testsz falls
473 * within the range of memory described by addr, sz. We take care to avoid
474 * problems with overflow and underflow of the unsigned quantities, and
475 * disallow all negative sizes. Ranges of size 0 are allowed.
477 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
478 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
479 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
480 (testaddr) + (testsz) >= (testaddr))
483 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
484 * alloc_sz on the righthand side of the comparison in order to avoid overflow
485 * or underflow in the comparison with it. This is simpler than the INRANGE
486 * check above, because we know that the dtms_scratch_ptr is valid in the
487 * range. Allocations of size zero are allowed.
489 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
490 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
491 (mstate)->dtms_scratch_ptr >= (alloc_sz))
493 #define DTRACE_LOADFUNC(bits) \
496 dtrace_load##bits(uintptr_t addr) \
498 size_t size = bits / NBBY; \
500 uint##bits##_t rval; \
502 volatile uint16_t *flags = (volatile uint16_t *) \
503 &cpu_core[curcpu].cpuc_dtrace_flags; \
505 DTRACE_ALIGNCHECK(addr, size, flags); \
507 for (i = 0; i < dtrace_toxranges; i++) { \
508 if (addr >= dtrace_toxrange[i].dtt_limit) \
511 if (addr + size <= dtrace_toxrange[i].dtt_base) \
515 * This address falls within a toxic region; return 0. \
517 *flags |= CPU_DTRACE_BADADDR; \
518 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
522 *flags |= CPU_DTRACE_NOFAULT; \
524 rval = *((volatile uint##bits##_t *)addr); \
525 *flags &= ~CPU_DTRACE_NOFAULT; \
527 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
531 #define dtrace_loadptr dtrace_load64
533 #define dtrace_loadptr dtrace_load32
536 #define DTRACE_DYNHASH_FREE 0
537 #define DTRACE_DYNHASH_SINK 1
538 #define DTRACE_DYNHASH_VALID 2
540 #define DTRACE_MATCH_NEXT 0
541 #define DTRACE_MATCH_DONE 1
542 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
543 #define DTRACE_STATE_ALIGN 64
545 #define DTRACE_FLAGS2FLT(flags) \
546 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
547 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
548 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
549 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
550 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
551 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
552 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
553 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
554 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
557 #define DTRACEACT_ISSTRING(act) \
558 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
559 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
561 /* Function prototype definitions: */
562 static size_t dtrace_strlen(const char *, size_t);
563 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
564 static void dtrace_enabling_provide(dtrace_provider_t *);
565 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
566 static void dtrace_enabling_matchall(void);
567 static void dtrace_enabling_reap(void);
568 static dtrace_state_t *dtrace_anon_grab(void);
569 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
570 dtrace_state_t *, uint64_t, uint64_t);
571 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
572 static void dtrace_buffer_drop(dtrace_buffer_t *);
573 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
574 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
575 dtrace_state_t *, dtrace_mstate_t *);
576 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
578 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
579 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
580 uint16_t dtrace_load16(uintptr_t);
581 uint32_t dtrace_load32(uintptr_t);
582 uint64_t dtrace_load64(uintptr_t);
583 uint8_t dtrace_load8(uintptr_t);
584 void dtrace_dynvar_clean(dtrace_dstate_t *);
585 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
586 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
587 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
588 static int dtrace_priv_proc(dtrace_state_t *);
589 static void dtrace_getf_barrier(void);
592 * DTrace Probe Context Functions
594 * These functions are called from probe context. Because probe context is
595 * any context in which C may be called, arbitrarily locks may be held,
596 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
597 * As a result, functions called from probe context may only call other DTrace
598 * support functions -- they may not interact at all with the system at large.
599 * (Note that the ASSERT macro is made probe-context safe by redefining it in
600 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
601 * loads are to be performed from probe context, they _must_ be in terms of
602 * the safe dtrace_load*() variants.
604 * Some functions in this block are not actually called from probe context;
605 * for these functions, there will be a comment above the function reading
606 * "Note: not called from probe context."
609 dtrace_panic(const char *format, ...)
613 va_start(alist, format);
615 vpanic(format, alist);
617 dtrace_vpanic(format, alist);
623 dtrace_assfail(const char *a, const char *f, int l)
625 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
628 * We just need something here that even the most clever compiler
629 * cannot optimize away.
631 return (a[(uintptr_t)f]);
635 * Atomically increment a specified error counter from probe context.
638 dtrace_error(uint32_t *counter)
641 * Most counters stored to in probe context are per-CPU counters.
642 * However, there are some error conditions that are sufficiently
643 * arcane that they don't merit per-CPU storage. If these counters
644 * are incremented concurrently on different CPUs, scalability will be
645 * adversely affected -- but we don't expect them to be white-hot in a
646 * correctly constructed enabling...
653 if ((nval = oval + 1) == 0) {
655 * If the counter would wrap, set it to 1 -- assuring
656 * that the counter is never zero when we have seen
657 * errors. (The counter must be 32-bits because we
658 * aren't guaranteed a 64-bit compare&swap operation.)
659 * To save this code both the infamy of being fingered
660 * by a priggish news story and the indignity of being
661 * the target of a neo-puritan witch trial, we're
662 * carefully avoiding any colorful description of the
663 * likelihood of this condition -- but suffice it to
664 * say that it is only slightly more likely than the
665 * overflow of predicate cache IDs, as discussed in
666 * dtrace_predicate_create().
670 } while (dtrace_cas32(counter, oval, nval) != oval);
674 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
675 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
683 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
685 if (dest < mstate->dtms_scratch_base)
688 if (dest + size < dest)
691 if (dest + size > mstate->dtms_scratch_ptr)
698 dtrace_canstore_statvar(uint64_t addr, size_t sz,
699 dtrace_statvar_t **svars, int nsvars)
702 size_t maxglobalsize, maxlocalsize;
707 maxglobalsize = dtrace_statvar_maxsize;
708 maxlocalsize = (maxglobalsize + sizeof (uint64_t)) * NCPU;
710 for (i = 0; i < nsvars; i++) {
711 dtrace_statvar_t *svar = svars[i];
715 if (svar == NULL || (size = svar->dtsv_size) == 0)
718 scope = svar->dtsv_var.dtdv_scope;
721 * We verify that our size is valid in the spirit of providing
722 * defense in depth: we want to prevent attackers from using
723 * DTrace to escalate an orthogonal kernel heap corruption bug
724 * into the ability to store to arbitrary locations in memory.
726 VERIFY((scope == DIFV_SCOPE_GLOBAL && size < maxglobalsize) ||
727 (scope == DIFV_SCOPE_LOCAL && size < maxlocalsize));
729 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
737 * Check to see if the address is within a memory region to which a store may
738 * be issued. This includes the DTrace scratch areas, and any DTrace variable
739 * region. The caller of dtrace_canstore() is responsible for performing any
740 * alignment checks that are needed before stores are actually executed.
743 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
744 dtrace_vstate_t *vstate)
747 * First, check to see if the address is in scratch space...
749 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
750 mstate->dtms_scratch_size))
754 * Now check to see if it's a dynamic variable. This check will pick
755 * up both thread-local variables and any global dynamically-allocated
758 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
759 vstate->dtvs_dynvars.dtds_size)) {
760 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
761 uintptr_t base = (uintptr_t)dstate->dtds_base +
762 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
766 * Before we assume that we can store here, we need to make
767 * sure that it isn't in our metadata -- storing to our
768 * dynamic variable metadata would corrupt our state. For
769 * the range to not include any dynamic variable metadata,
772 * (1) Start above the hash table that is at the base of
773 * the dynamic variable space
775 * (2) Have a starting chunk offset that is beyond the
776 * dtrace_dynvar_t that is at the base of every chunk
778 * (3) Not span a chunk boundary
784 chunkoffs = (addr - base) % dstate->dtds_chunksize;
786 if (chunkoffs < sizeof (dtrace_dynvar_t))
789 if (chunkoffs + sz > dstate->dtds_chunksize)
796 * Finally, check the static local and global variables. These checks
797 * take the longest, so we perform them last.
799 if (dtrace_canstore_statvar(addr, sz,
800 vstate->dtvs_locals, vstate->dtvs_nlocals))
803 if (dtrace_canstore_statvar(addr, sz,
804 vstate->dtvs_globals, vstate->dtvs_nglobals))
812 * Convenience routine to check to see if the address is within a memory
813 * region in which a load may be issued given the user's privilege level;
814 * if not, it sets the appropriate error flags and loads 'addr' into the
815 * illegal value slot.
817 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
818 * appropriate memory access protection.
821 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
822 dtrace_vstate_t *vstate)
824 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
828 * If we hold the privilege to read from kernel memory, then
829 * everything is readable.
831 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
835 * You can obviously read that which you can store.
837 if (dtrace_canstore(addr, sz, mstate, vstate))
841 * We're allowed to read from our own string table.
843 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
844 mstate->dtms_difo->dtdo_strlen))
847 if (vstate->dtvs_state != NULL &&
848 dtrace_priv_proc(vstate->dtvs_state)) {
852 * When we have privileges to the current process, there are
853 * several context-related kernel structures that are safe to
854 * read, even absent the privilege to read from kernel memory.
855 * These reads are safe because these structures contain only
856 * state that (1) we're permitted to read, (2) is harmless or
857 * (3) contains pointers to additional kernel state that we're
858 * not permitted to read (and as such, do not present an
859 * opportunity for privilege escalation). Finally (and
860 * critically), because of the nature of their relation with
861 * the current thread context, the memory associated with these
862 * structures cannot change over the duration of probe context,
863 * and it is therefore impossible for this memory to be
864 * deallocated and reallocated as something else while it's
865 * being operated upon.
867 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
870 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
871 sz, curthread->t_procp, sizeof (proc_t))) {
875 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
876 curthread->t_cred, sizeof (cred_t))) {
881 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
882 &(p->p_pidp->pid_id), sizeof (pid_t))) {
886 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
887 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
893 if ((fp = mstate->dtms_getf) != NULL) {
894 uintptr_t psz = sizeof (void *);
899 * When getf() returns a file_t, the enabling is implicitly
900 * granted the (transient) right to read the returned file_t
901 * as well as the v_path and v_op->vnop_name of the underlying
902 * vnode. These accesses are allowed after a successful
903 * getf() because the members that they refer to cannot change
904 * once set -- and the barrier logic in the kernel's closef()
905 * path assures that the file_t and its referenced vode_t
906 * cannot themselves be stale (that is, it impossible for
907 * either dtms_getf itself or its f_vnode member to reference
910 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
913 if ((vp = fp->f_vnode) != NULL) {
915 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
917 if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
918 vp->v_path, strlen(vp->v_path) + 1)) {
923 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
927 if ((op = vp->v_op) != NULL &&
928 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
932 if (op != NULL && op->vnop_name != NULL &&
933 DTRACE_INRANGE(addr, sz, op->vnop_name,
934 strlen(op->vnop_name) + 1)) {
941 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
947 * Convenience routine to check to see if a given string is within a memory
948 * region in which a load may be issued given the user's privilege level;
949 * this exists so that we don't need to issue unnecessary dtrace_strlen()
950 * calls in the event that the user has all privileges.
953 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
954 dtrace_vstate_t *vstate)
959 * If we hold the privilege to read from kernel memory, then
960 * everything is readable.
962 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
965 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
966 if (dtrace_canload(addr, strsz, mstate, vstate))
973 * Convenience routine to check to see if a given variable is within a memory
974 * region in which a load may be issued given the user's privilege level.
977 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
978 dtrace_vstate_t *vstate)
981 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
984 * If we hold the privilege to read from kernel memory, then
985 * everything is readable.
987 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
990 if (type->dtdt_kind == DIF_TYPE_STRING)
991 sz = dtrace_strlen(src,
992 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
994 sz = type->dtdt_size;
996 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
1000 * Convert a string to a signed integer using safe loads.
1002 * NOTE: This function uses various macros from strtolctype.h to manipulate
1003 * digit values, etc -- these have all been checked to ensure they make
1004 * no additional function calls.
1007 dtrace_strtoll(char *input, int base, size_t limit)
1009 uintptr_t pos = (uintptr_t)input;
1012 boolean_t neg = B_FALSE;
1014 uintptr_t end = pos + limit;
1017 * Consume any whitespace preceding digits.
1019 while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1023 * Handle an explicit sign if one is present.
1025 if (c == '-' || c == '+') {
1028 c = dtrace_load8(++pos);
1032 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1035 if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1036 cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1042 * Read in contiguous digits until the first non-digit character.
1044 for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1045 c = dtrace_load8(++pos))
1046 val = val * base + x;
1048 return (neg ? -val : val);
1052 * Compare two strings using safe loads.
1055 dtrace_strncmp(char *s1, char *s2, size_t limit)
1058 volatile uint16_t *flags;
1060 if (s1 == s2 || limit == 0)
1063 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1069 c1 = dtrace_load8((uintptr_t)s1++);
1075 c2 = dtrace_load8((uintptr_t)s2++);
1080 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1086 * Compute strlen(s) for a string using safe memory accesses. The additional
1087 * len parameter is used to specify a maximum length to ensure completion.
1090 dtrace_strlen(const char *s, size_t lim)
1094 for (len = 0; len != lim; len++) {
1095 if (dtrace_load8((uintptr_t)s++) == '\0')
1103 * Check if an address falls within a toxic region.
1106 dtrace_istoxic(uintptr_t kaddr, size_t size)
1108 uintptr_t taddr, tsize;
1111 for (i = 0; i < dtrace_toxranges; i++) {
1112 taddr = dtrace_toxrange[i].dtt_base;
1113 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1115 if (kaddr - taddr < tsize) {
1116 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1117 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1121 if (taddr - kaddr < size) {
1122 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1123 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1132 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1133 * memory specified by the DIF program. The dst is assumed to be safe memory
1134 * that we can store to directly because it is managed by DTrace. As with
1135 * standard bcopy, overlapping copies are handled properly.
1138 dtrace_bcopy(const void *src, void *dst, size_t len)
1142 const uint8_t *s2 = src;
1146 *s1++ = dtrace_load8((uintptr_t)s2++);
1147 } while (--len != 0);
1153 *--s1 = dtrace_load8((uintptr_t)--s2);
1154 } while (--len != 0);
1160 * Copy src to dst using safe memory accesses, up to either the specified
1161 * length, or the point that a nul byte is encountered. The src is assumed to
1162 * be unsafe memory specified by the DIF program. The dst is assumed to be
1163 * safe memory that we can store to directly because it is managed by DTrace.
1164 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1167 dtrace_strcpy(const void *src, void *dst, size_t len)
1170 uint8_t *s1 = dst, c;
1171 const uint8_t *s2 = src;
1174 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1175 } while (--len != 0 && c != '\0');
1180 * Copy src to dst, deriving the size and type from the specified (BYREF)
1181 * variable type. The src is assumed to be unsafe memory specified by the DIF
1182 * program. The dst is assumed to be DTrace variable memory that is of the
1183 * specified type; we assume that we can store to directly.
1186 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1188 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1190 if (type->dtdt_kind == DIF_TYPE_STRING) {
1191 dtrace_strcpy(src, dst, type->dtdt_size);
1193 dtrace_bcopy(src, dst, type->dtdt_size);
1198 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1199 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1200 * safe memory that we can access directly because it is managed by DTrace.
1203 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1205 volatile uint16_t *flags;
1207 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1212 if (s1 == NULL || s2 == NULL)
1215 if (s1 != s2 && len != 0) {
1216 const uint8_t *ps1 = s1;
1217 const uint8_t *ps2 = s2;
1220 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1222 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1228 * Zero the specified region using a simple byte-by-byte loop. Note that this
1229 * is for safe DTrace-managed memory only.
1232 dtrace_bzero(void *dst, size_t len)
1236 for (cp = dst; len != 0; len--)
1241 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1245 result[0] = addend1[0] + addend2[0];
1246 result[1] = addend1[1] + addend2[1] +
1247 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1254 * Shift the 128-bit value in a by b. If b is positive, shift left.
1255 * If b is negative, shift right.
1258 dtrace_shift_128(uint64_t *a, int b)
1268 a[0] = a[1] >> (b - 64);
1272 mask = 1LL << (64 - b);
1274 a[0] |= ((a[1] & mask) << (64 - b));
1279 a[1] = a[0] << (b - 64);
1283 mask = a[0] >> (64 - b);
1291 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1292 * use native multiplication on those, and then re-combine into the
1293 * resulting 128-bit value.
1295 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1302 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1304 uint64_t hi1, hi2, lo1, lo2;
1307 hi1 = factor1 >> 32;
1308 hi2 = factor2 >> 32;
1310 lo1 = factor1 & DT_MASK_LO;
1311 lo2 = factor2 & DT_MASK_LO;
1313 product[0] = lo1 * lo2;
1314 product[1] = hi1 * hi2;
1318 dtrace_shift_128(tmp, 32);
1319 dtrace_add_128(product, tmp, product);
1323 dtrace_shift_128(tmp, 32);
1324 dtrace_add_128(product, tmp, product);
1328 * This privilege check should be used by actions and subroutines to
1329 * verify that the user credentials of the process that enabled the
1330 * invoking ECB match the target credentials
1333 dtrace_priv_proc_common_user(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 &&
1344 s_cr->cr_uid == cr->cr_uid &&
1345 s_cr->cr_uid == cr->cr_ruid &&
1346 s_cr->cr_uid == cr->cr_suid &&
1347 s_cr->cr_gid == cr->cr_gid &&
1348 s_cr->cr_gid == cr->cr_rgid &&
1349 s_cr->cr_gid == cr->cr_sgid)
1356 * This privilege check should be used by actions and subroutines to
1357 * verify that the zone of the process that enabled the invoking ECB
1358 * matches the target credentials
1361 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1364 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1367 * We should always have a non-NULL state cred here, since if cred
1368 * is null (anonymous tracing), we fast-path bypass this routine.
1370 ASSERT(s_cr != NULL);
1372 if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1382 * This privilege check should be used by actions and subroutines to
1383 * verify that the process has not setuid or changed credentials.
1386 dtrace_priv_proc_common_nocd(void)
1390 if ((proc = ttoproc(curthread)) != NULL &&
1391 !(proc->p_flag & SNOCD))
1398 dtrace_priv_proc_destructive(dtrace_state_t *state)
1400 int action = state->dts_cred.dcr_action;
1402 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1403 dtrace_priv_proc_common_zone(state) == 0)
1406 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1407 dtrace_priv_proc_common_user(state) == 0)
1410 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1411 dtrace_priv_proc_common_nocd() == 0)
1417 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1423 dtrace_priv_proc_control(dtrace_state_t *state)
1425 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1428 if (dtrace_priv_proc_common_zone(state) &&
1429 dtrace_priv_proc_common_user(state) &&
1430 dtrace_priv_proc_common_nocd())
1433 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1439 dtrace_priv_proc(dtrace_state_t *state)
1441 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1444 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1450 dtrace_priv_kernel(dtrace_state_t *state)
1452 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1455 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1461 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1463 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1466 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1472 * Determine if the dte_cond of the specified ECB allows for processing of
1473 * the current probe to continue. Note that this routine may allow continued
1474 * processing, but with access(es) stripped from the mstate's dtms_access
1478 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1481 dtrace_probe_t *probe = ecb->dte_probe;
1482 dtrace_provider_t *prov = probe->dtpr_provider;
1483 dtrace_pops_t *pops = &prov->dtpv_pops;
1484 int mode = DTRACE_MODE_NOPRIV_DROP;
1486 ASSERT(ecb->dte_cond);
1489 if (pops->dtps_mode != NULL) {
1490 mode = pops->dtps_mode(prov->dtpv_arg,
1491 probe->dtpr_id, probe->dtpr_arg);
1493 ASSERT((mode & DTRACE_MODE_USER) ||
1494 (mode & DTRACE_MODE_KERNEL));
1495 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1496 (mode & DTRACE_MODE_NOPRIV_DROP));
1500 * If the dte_cond bits indicate that this consumer is only allowed to
1501 * see user-mode firings of this probe, call the provider's dtps_mode()
1502 * entry point to check that the probe was fired while in a user
1503 * context. If that's not the case, use the policy specified by the
1504 * provider to determine if we drop the probe or merely restrict
1507 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1508 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1510 if (!(mode & DTRACE_MODE_USER)) {
1511 if (mode & DTRACE_MODE_NOPRIV_DROP)
1514 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1520 * This is more subtle than it looks. We have to be absolutely certain
1521 * that CRED() isn't going to change out from under us so it's only
1522 * legit to examine that structure if we're in constrained situations.
1523 * Currently, the only times we'll this check is if a non-super-user
1524 * has enabled the profile or syscall providers -- providers that
1525 * allow visibility of all processes. For the profile case, the check
1526 * above will ensure that we're examining a user context.
1528 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1530 cred_t *s_cr = state->dts_cred.dcr_cred;
1533 ASSERT(s_cr != NULL);
1535 if ((cr = CRED()) == NULL ||
1536 s_cr->cr_uid != cr->cr_uid ||
1537 s_cr->cr_uid != cr->cr_ruid ||
1538 s_cr->cr_uid != cr->cr_suid ||
1539 s_cr->cr_gid != cr->cr_gid ||
1540 s_cr->cr_gid != cr->cr_rgid ||
1541 s_cr->cr_gid != cr->cr_sgid ||
1542 (proc = ttoproc(curthread)) == NULL ||
1543 (proc->p_flag & SNOCD)) {
1544 if (mode & DTRACE_MODE_NOPRIV_DROP)
1548 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1555 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1556 * in our zone, check to see if our mode policy is to restrict rather
1557 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1558 * and DTRACE_ACCESS_ARGS
1560 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1562 cred_t *s_cr = state->dts_cred.dcr_cred;
1564 ASSERT(s_cr != NULL);
1566 if ((cr = CRED()) == NULL ||
1567 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1568 if (mode & DTRACE_MODE_NOPRIV_DROP)
1571 mstate->dtms_access &=
1572 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1581 * Note: not called from probe context. This function is called
1582 * asynchronously (and at a regular interval) from outside of probe context to
1583 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1584 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1587 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1589 dtrace_dynvar_t *dirty;
1590 dtrace_dstate_percpu_t *dcpu;
1591 dtrace_dynvar_t **rinsep;
1594 for (i = 0; i < NCPU; i++) {
1595 dcpu = &dstate->dtds_percpu[i];
1596 rinsep = &dcpu->dtdsc_rinsing;
1599 * If the dirty list is NULL, there is no dirty work to do.
1601 if (dcpu->dtdsc_dirty == NULL)
1604 if (dcpu->dtdsc_rinsing != NULL) {
1606 * If the rinsing list is non-NULL, then it is because
1607 * this CPU was selected to accept another CPU's
1608 * dirty list -- and since that time, dirty buffers
1609 * have accumulated. This is a highly unlikely
1610 * condition, but we choose to ignore the dirty
1611 * buffers -- they'll be picked up a future cleanse.
1616 if (dcpu->dtdsc_clean != NULL) {
1618 * If the clean list is non-NULL, then we're in a
1619 * situation where a CPU has done deallocations (we
1620 * have a non-NULL dirty list) but no allocations (we
1621 * also have a non-NULL clean list). We can't simply
1622 * move the dirty list into the clean list on this
1623 * CPU, yet we also don't want to allow this condition
1624 * to persist, lest a short clean list prevent a
1625 * massive dirty list from being cleaned (which in
1626 * turn could lead to otherwise avoidable dynamic
1627 * drops). To deal with this, we look for some CPU
1628 * with a NULL clean list, NULL dirty list, and NULL
1629 * rinsing list -- and then we borrow this CPU to
1630 * rinse our dirty list.
1632 for (j = 0; j < NCPU; j++) {
1633 dtrace_dstate_percpu_t *rinser;
1635 rinser = &dstate->dtds_percpu[j];
1637 if (rinser->dtdsc_rinsing != NULL)
1640 if (rinser->dtdsc_dirty != NULL)
1643 if (rinser->dtdsc_clean != NULL)
1646 rinsep = &rinser->dtdsc_rinsing;
1652 * We were unable to find another CPU that
1653 * could accept this dirty list -- we are
1654 * therefore unable to clean it now.
1656 dtrace_dynvar_failclean++;
1664 * Atomically move the dirty list aside.
1667 dirty = dcpu->dtdsc_dirty;
1670 * Before we zap the dirty list, set the rinsing list.
1671 * (This allows for a potential assertion in
1672 * dtrace_dynvar(): if a free dynamic variable appears
1673 * on a hash chain, either the dirty list or the
1674 * rinsing list for some CPU must be non-NULL.)
1677 dtrace_membar_producer();
1678 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1679 dirty, NULL) != dirty);
1684 * We have no work to do; we can simply return.
1691 for (i = 0; i < NCPU; i++) {
1692 dcpu = &dstate->dtds_percpu[i];
1694 if (dcpu->dtdsc_rinsing == NULL)
1698 * We are now guaranteed that no hash chain contains a pointer
1699 * into this dirty list; we can make it clean.
1701 ASSERT(dcpu->dtdsc_clean == NULL);
1702 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1703 dcpu->dtdsc_rinsing = NULL;
1707 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1708 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1709 * This prevents a race whereby a CPU incorrectly decides that
1710 * the state should be something other than DTRACE_DSTATE_CLEAN
1711 * after dtrace_dynvar_clean() has completed.
1715 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1719 * Depending on the value of the op parameter, this function looks-up,
1720 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1721 * allocation is requested, this function will return a pointer to a
1722 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1723 * variable can be allocated. If NULL is returned, the appropriate counter
1724 * will be incremented.
1727 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1728 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1729 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1731 uint64_t hashval = DTRACE_DYNHASH_VALID;
1732 dtrace_dynhash_t *hash = dstate->dtds_hash;
1733 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1734 processorid_t me = curcpu, cpu = me;
1735 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1736 size_t bucket, ksize;
1737 size_t chunksize = dstate->dtds_chunksize;
1738 uintptr_t kdata, lock, nstate;
1744 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1745 * algorithm. For the by-value portions, we perform the algorithm in
1746 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1747 * bit, and seems to have only a minute effect on distribution. For
1748 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1749 * over each referenced byte. It's painful to do this, but it's much
1750 * better than pathological hash distribution. The efficacy of the
1751 * hashing algorithm (and a comparison with other algorithms) may be
1752 * found by running the ::dtrace_dynstat MDB dcmd.
1754 for (i = 0; i < nkeys; i++) {
1755 if (key[i].dttk_size == 0) {
1756 uint64_t val = key[i].dttk_value;
1758 hashval += (val >> 48) & 0xffff;
1759 hashval += (hashval << 10);
1760 hashval ^= (hashval >> 6);
1762 hashval += (val >> 32) & 0xffff;
1763 hashval += (hashval << 10);
1764 hashval ^= (hashval >> 6);
1766 hashval += (val >> 16) & 0xffff;
1767 hashval += (hashval << 10);
1768 hashval ^= (hashval >> 6);
1770 hashval += val & 0xffff;
1771 hashval += (hashval << 10);
1772 hashval ^= (hashval >> 6);
1775 * This is incredibly painful, but it beats the hell
1776 * out of the alternative.
1778 uint64_t j, size = key[i].dttk_size;
1779 uintptr_t base = (uintptr_t)key[i].dttk_value;
1781 if (!dtrace_canload(base, size, mstate, vstate))
1784 for (j = 0; j < size; j++) {
1785 hashval += dtrace_load8(base + j);
1786 hashval += (hashval << 10);
1787 hashval ^= (hashval >> 6);
1792 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1795 hashval += (hashval << 3);
1796 hashval ^= (hashval >> 11);
1797 hashval += (hashval << 15);
1800 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1801 * comes out to be one of our two sentinel hash values. If this
1802 * actually happens, we set the hashval to be a value known to be a
1803 * non-sentinel value.
1805 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1806 hashval = DTRACE_DYNHASH_VALID;
1809 * Yes, it's painful to do a divide here. If the cycle count becomes
1810 * important here, tricks can be pulled to reduce it. (However, it's
1811 * critical that hash collisions be kept to an absolute minimum;
1812 * they're much more painful than a divide.) It's better to have a
1813 * solution that generates few collisions and still keeps things
1814 * relatively simple.
1816 bucket = hashval % dstate->dtds_hashsize;
1818 if (op == DTRACE_DYNVAR_DEALLOC) {
1819 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1822 while ((lock = *lockp) & 1)
1825 if (dtrace_casptr((volatile void *)lockp,
1826 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1830 dtrace_membar_producer();
1835 lock = hash[bucket].dtdh_lock;
1837 dtrace_membar_consumer();
1839 start = hash[bucket].dtdh_chain;
1840 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1841 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1842 op != DTRACE_DYNVAR_DEALLOC));
1844 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1845 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1846 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1848 if (dvar->dtdv_hashval != hashval) {
1849 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1851 * We've reached the sink, and therefore the
1852 * end of the hash chain; we can kick out of
1853 * the loop knowing that we have seen a valid
1854 * snapshot of state.
1856 ASSERT(dvar->dtdv_next == NULL);
1857 ASSERT(dvar == &dtrace_dynhash_sink);
1861 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1863 * We've gone off the rails: somewhere along
1864 * the line, one of the members of this hash
1865 * chain was deleted. Note that we could also
1866 * detect this by simply letting this loop run
1867 * to completion, as we would eventually hit
1868 * the end of the dirty list. However, we
1869 * want to avoid running the length of the
1870 * dirty list unnecessarily (it might be quite
1871 * long), so we catch this as early as
1872 * possible by detecting the hash marker. In
1873 * this case, we simply set dvar to NULL and
1874 * break; the conditional after the loop will
1875 * send us back to top.
1884 if (dtuple->dtt_nkeys != nkeys)
1887 for (i = 0; i < nkeys; i++, dkey++) {
1888 if (dkey->dttk_size != key[i].dttk_size)
1889 goto next; /* size or type mismatch */
1891 if (dkey->dttk_size != 0) {
1893 (void *)(uintptr_t)key[i].dttk_value,
1894 (void *)(uintptr_t)dkey->dttk_value,
1898 if (dkey->dttk_value != key[i].dttk_value)
1903 if (op != DTRACE_DYNVAR_DEALLOC)
1906 ASSERT(dvar->dtdv_next == NULL ||
1907 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1910 ASSERT(hash[bucket].dtdh_chain != dvar);
1911 ASSERT(start != dvar);
1912 ASSERT(prev->dtdv_next == dvar);
1913 prev->dtdv_next = dvar->dtdv_next;
1915 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1916 start, dvar->dtdv_next) != start) {
1918 * We have failed to atomically swing the
1919 * hash table head pointer, presumably because
1920 * of a conflicting allocation on another CPU.
1921 * We need to reread the hash chain and try
1928 dtrace_membar_producer();
1931 * Now set the hash value to indicate that it's free.
1933 ASSERT(hash[bucket].dtdh_chain != dvar);
1934 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1936 dtrace_membar_producer();
1939 * Set the next pointer to point at the dirty list, and
1940 * atomically swing the dirty pointer to the newly freed dvar.
1943 next = dcpu->dtdsc_dirty;
1944 dvar->dtdv_next = next;
1945 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1948 * Finally, unlock this hash bucket.
1950 ASSERT(hash[bucket].dtdh_lock == lock);
1952 hash[bucket].dtdh_lock++;
1962 * If dvar is NULL, it is because we went off the rails:
1963 * one of the elements that we traversed in the hash chain
1964 * was deleted while we were traversing it. In this case,
1965 * we assert that we aren't doing a dealloc (deallocs lock
1966 * the hash bucket to prevent themselves from racing with
1967 * one another), and retry the hash chain traversal.
1969 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1973 if (op != DTRACE_DYNVAR_ALLOC) {
1975 * If we are not to allocate a new variable, we want to
1976 * return NULL now. Before we return, check that the value
1977 * of the lock word hasn't changed. If it has, we may have
1978 * seen an inconsistent snapshot.
1980 if (op == DTRACE_DYNVAR_NOALLOC) {
1981 if (hash[bucket].dtdh_lock != lock)
1984 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1985 ASSERT(hash[bucket].dtdh_lock == lock);
1987 hash[bucket].dtdh_lock++;
1994 * We need to allocate a new dynamic variable. The size we need is the
1995 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1996 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1997 * the size of any referred-to data (dsize). We then round the final
1998 * size up to the chunksize for allocation.
2000 for (ksize = 0, i = 0; i < nkeys; i++)
2001 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2004 * This should be pretty much impossible, but could happen if, say,
2005 * strange DIF specified the tuple. Ideally, this should be an
2006 * assertion and not an error condition -- but that requires that the
2007 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2008 * bullet-proof. (That is, it must not be able to be fooled by
2009 * malicious DIF.) Given the lack of backwards branches in DIF,
2010 * solving this would presumably not amount to solving the Halting
2011 * Problem -- but it still seems awfully hard.
2013 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2014 ksize + dsize > chunksize) {
2015 dcpu->dtdsc_drops++;
2019 nstate = DTRACE_DSTATE_EMPTY;
2023 free = dcpu->dtdsc_free;
2026 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2029 if (clean == NULL) {
2031 * We're out of dynamic variable space on
2032 * this CPU. Unless we have tried all CPUs,
2033 * we'll try to allocate from a different
2036 switch (dstate->dtds_state) {
2037 case DTRACE_DSTATE_CLEAN: {
2038 void *sp = &dstate->dtds_state;
2043 if (dcpu->dtdsc_dirty != NULL &&
2044 nstate == DTRACE_DSTATE_EMPTY)
2045 nstate = DTRACE_DSTATE_DIRTY;
2047 if (dcpu->dtdsc_rinsing != NULL)
2048 nstate = DTRACE_DSTATE_RINSING;
2050 dcpu = &dstate->dtds_percpu[cpu];
2055 (void) dtrace_cas32(sp,
2056 DTRACE_DSTATE_CLEAN, nstate);
2059 * To increment the correct bean
2060 * counter, take another lap.
2065 case DTRACE_DSTATE_DIRTY:
2066 dcpu->dtdsc_dirty_drops++;
2069 case DTRACE_DSTATE_RINSING:
2070 dcpu->dtdsc_rinsing_drops++;
2073 case DTRACE_DSTATE_EMPTY:
2074 dcpu->dtdsc_drops++;
2078 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2083 * The clean list appears to be non-empty. We want to
2084 * move the clean list to the free list; we start by
2085 * moving the clean pointer aside.
2087 if (dtrace_casptr(&dcpu->dtdsc_clean,
2088 clean, NULL) != clean) {
2090 * We are in one of two situations:
2092 * (a) The clean list was switched to the
2093 * free list by another CPU.
2095 * (b) The clean list was added to by the
2098 * In either of these situations, we can
2099 * just reattempt the free list allocation.
2104 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2107 * Now we'll move the clean list to our free list.
2108 * It's impossible for this to fail: the only way
2109 * the free list can be updated is through this
2110 * code path, and only one CPU can own the clean list.
2111 * Thus, it would only be possible for this to fail if
2112 * this code were racing with dtrace_dynvar_clean().
2113 * (That is, if dtrace_dynvar_clean() updated the clean
2114 * list, and we ended up racing to update the free
2115 * list.) This race is prevented by the dtrace_sync()
2116 * in dtrace_dynvar_clean() -- which flushes the
2117 * owners of the clean lists out before resetting
2120 dcpu = &dstate->dtds_percpu[me];
2121 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2122 ASSERT(rval == NULL);
2127 new_free = dvar->dtdv_next;
2128 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2131 * We have now allocated a new chunk. We copy the tuple keys into the
2132 * tuple array and copy any referenced key data into the data space
2133 * following the tuple array. As we do this, we relocate dttk_value
2134 * in the final tuple to point to the key data address in the chunk.
2136 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2137 dvar->dtdv_data = (void *)(kdata + ksize);
2138 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2140 for (i = 0; i < nkeys; i++) {
2141 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2142 size_t kesize = key[i].dttk_size;
2146 (const void *)(uintptr_t)key[i].dttk_value,
2147 (void *)kdata, kesize);
2148 dkey->dttk_value = kdata;
2149 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2151 dkey->dttk_value = key[i].dttk_value;
2154 dkey->dttk_size = kesize;
2157 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2158 dvar->dtdv_hashval = hashval;
2159 dvar->dtdv_next = start;
2161 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2165 * The cas has failed. Either another CPU is adding an element to
2166 * this hash chain, or another CPU is deleting an element from this
2167 * hash chain. The simplest way to deal with both of these cases
2168 * (though not necessarily the most efficient) is to free our
2169 * allocated block and tail-call ourselves. Note that the free is
2170 * to the dirty list and _not_ to the free list. This is to prevent
2171 * races with allocators, above.
2173 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2175 dtrace_membar_producer();
2178 free = dcpu->dtdsc_dirty;
2179 dvar->dtdv_next = free;
2180 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2182 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2187 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2189 if ((int64_t)nval < (int64_t)*oval)
2195 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2197 if ((int64_t)nval > (int64_t)*oval)
2202 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2204 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2205 int64_t val = (int64_t)nval;
2208 for (i = 0; i < zero; i++) {
2209 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2215 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2216 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2217 quanta[i - 1] += incr;
2222 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2230 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2232 uint64_t arg = *lquanta++;
2233 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2234 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2235 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2236 int32_t val = (int32_t)nval, level;
2239 ASSERT(levels != 0);
2243 * This is an underflow.
2249 level = (val - base) / step;
2251 if (level < levels) {
2252 lquanta[level + 1] += incr;
2257 * This is an overflow.
2259 lquanta[levels + 1] += incr;
2263 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2264 uint16_t high, uint16_t nsteps, int64_t value)
2266 int64_t this = 1, last, next;
2267 int base = 1, order;
2269 ASSERT(factor <= nsteps);
2270 ASSERT(nsteps % factor == 0);
2272 for (order = 0; order < low; order++)
2276 * If our value is less than our factor taken to the power of the
2277 * low order of magnitude, it goes into the zeroth bucket.
2279 if (value < (last = this))
2282 for (this *= factor; order <= high; order++) {
2283 int nbuckets = this > nsteps ? nsteps : this;
2285 if ((next = this * factor) < this) {
2287 * We should not generally get log/linear quantizations
2288 * with a high magnitude that allows 64-bits to
2289 * overflow, but we nonetheless protect against this
2290 * by explicitly checking for overflow, and clamping
2291 * our value accordingly.
2298 * If our value lies within this order of magnitude,
2299 * determine its position by taking the offset within
2300 * the order of magnitude, dividing by the bucket
2301 * width, and adding to our (accumulated) base.
2303 return (base + (value - last) / (this / nbuckets));
2306 base += nbuckets - (nbuckets / factor);
2312 * Our value is greater than or equal to our factor taken to the
2313 * power of one plus the high magnitude -- return the top bucket.
2319 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2321 uint64_t arg = *llquanta++;
2322 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2323 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2324 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2325 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2327 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2328 low, high, nsteps, nval)] += incr;
2333 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2341 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2343 int64_t snval = (int64_t)nval;
2350 * What we want to say here is:
2352 * data[2] += nval * nval;
2354 * But given that nval is 64-bit, we could easily overflow, so
2355 * we do this as 128-bit arithmetic.
2360 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2361 dtrace_add_128(data + 2, tmp, data + 2);
2366 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2373 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2379 * Aggregate given the tuple in the principal data buffer, and the aggregating
2380 * action denoted by the specified dtrace_aggregation_t. The aggregation
2381 * buffer is specified as the buf parameter. This routine does not return
2382 * failure; if there is no space in the aggregation buffer, the data will be
2383 * dropped, and a corresponding counter incremented.
2386 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2387 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2389 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2390 uint32_t i, ndx, size, fsize;
2391 uint32_t align = sizeof (uint64_t) - 1;
2392 dtrace_aggbuffer_t *agb;
2393 dtrace_aggkey_t *key;
2394 uint32_t hashval = 0, limit, isstr;
2395 caddr_t tomax, data, kdata;
2396 dtrace_actkind_t action;
2397 dtrace_action_t *act;
2403 if (!agg->dtag_hasarg) {
2405 * Currently, only quantize() and lquantize() take additional
2406 * arguments, and they have the same semantics: an increment
2407 * value that defaults to 1 when not present. If additional
2408 * aggregating actions take arguments, the setting of the
2409 * default argument value will presumably have to become more
2415 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2416 size = rec->dtrd_offset - agg->dtag_base;
2417 fsize = size + rec->dtrd_size;
2419 ASSERT(dbuf->dtb_tomax != NULL);
2420 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2422 if ((tomax = buf->dtb_tomax) == NULL) {
2423 dtrace_buffer_drop(buf);
2428 * The metastructure is always at the bottom of the buffer.
2430 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2431 sizeof (dtrace_aggbuffer_t));
2433 if (buf->dtb_offset == 0) {
2435 * We just kludge up approximately 1/8th of the size to be
2436 * buckets. If this guess ends up being routinely
2437 * off-the-mark, we may need to dynamically readjust this
2438 * based on past performance.
2440 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2442 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2443 (uintptr_t)tomax || hashsize == 0) {
2445 * We've been given a ludicrously small buffer;
2446 * increment our drop count and leave.
2448 dtrace_buffer_drop(buf);
2453 * And now, a pathetic attempt to try to get a an odd (or
2454 * perchance, a prime) hash size for better hash distribution.
2456 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2457 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2459 agb->dtagb_hashsize = hashsize;
2460 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2461 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2462 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2464 for (i = 0; i < agb->dtagb_hashsize; i++)
2465 agb->dtagb_hash[i] = NULL;
2468 ASSERT(agg->dtag_first != NULL);
2469 ASSERT(agg->dtag_first->dta_intuple);
2472 * Calculate the hash value based on the key. Note that we _don't_
2473 * include the aggid in the hashing (but we will store it as part of
2474 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2475 * algorithm: a simple, quick algorithm that has no known funnels, and
2476 * gets good distribution in practice. The efficacy of the hashing
2477 * algorithm (and a comparison with other algorithms) may be found by
2478 * running the ::dtrace_aggstat MDB dcmd.
2480 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2481 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2482 limit = i + act->dta_rec.dtrd_size;
2483 ASSERT(limit <= size);
2484 isstr = DTRACEACT_ISSTRING(act);
2486 for (; i < limit; i++) {
2488 hashval += (hashval << 10);
2489 hashval ^= (hashval >> 6);
2491 if (isstr && data[i] == '\0')
2496 hashval += (hashval << 3);
2497 hashval ^= (hashval >> 11);
2498 hashval += (hashval << 15);
2501 * Yes, the divide here is expensive -- but it's generally the least
2502 * of the performance issues given the amount of data that we iterate
2503 * over to compute hash values, compare data, etc.
2505 ndx = hashval % agb->dtagb_hashsize;
2507 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2508 ASSERT((caddr_t)key >= tomax);
2509 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2511 if (hashval != key->dtak_hashval || key->dtak_size != size)
2514 kdata = key->dtak_data;
2515 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2517 for (act = agg->dtag_first; act->dta_intuple;
2518 act = act->dta_next) {
2519 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2520 limit = i + act->dta_rec.dtrd_size;
2521 ASSERT(limit <= size);
2522 isstr = DTRACEACT_ISSTRING(act);
2524 for (; i < limit; i++) {
2525 if (kdata[i] != data[i])
2528 if (isstr && data[i] == '\0')
2533 if (action != key->dtak_action) {
2535 * We are aggregating on the same value in the same
2536 * aggregation with two different aggregating actions.
2537 * (This should have been picked up in the compiler,
2538 * so we may be dealing with errant or devious DIF.)
2539 * This is an error condition; we indicate as much,
2542 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2547 * This is a hit: we need to apply the aggregator to
2548 * the value at this key.
2550 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2557 * We didn't find it. We need to allocate some zero-filled space,
2558 * link it into the hash table appropriately, and apply the aggregator
2559 * to the (zero-filled) value.
2561 offs = buf->dtb_offset;
2562 while (offs & (align - 1))
2563 offs += sizeof (uint32_t);
2566 * If we don't have enough room to both allocate a new key _and_
2567 * its associated data, increment the drop count and return.
2569 if ((uintptr_t)tomax + offs + fsize >
2570 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2571 dtrace_buffer_drop(buf);
2576 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2577 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2578 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2580 key->dtak_data = kdata = tomax + offs;
2581 buf->dtb_offset = offs + fsize;
2584 * Now copy the data across.
2586 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2588 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2592 * Because strings are not zeroed out by default, we need to iterate
2593 * looking for actions that store strings, and we need to explicitly
2594 * pad these strings out with zeroes.
2596 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2599 if (!DTRACEACT_ISSTRING(act))
2602 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2603 limit = i + act->dta_rec.dtrd_size;
2604 ASSERT(limit <= size);
2606 for (nul = 0; i < limit; i++) {
2612 if (data[i] != '\0')
2619 for (i = size; i < fsize; i++)
2622 key->dtak_hashval = hashval;
2623 key->dtak_size = size;
2624 key->dtak_action = action;
2625 key->dtak_next = agb->dtagb_hash[ndx];
2626 agb->dtagb_hash[ndx] = key;
2629 * Finally, apply the aggregator.
2631 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2632 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2636 * Given consumer state, this routine finds a speculation in the INACTIVE
2637 * state and transitions it into the ACTIVE state. If there is no speculation
2638 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2639 * incremented -- it is up to the caller to take appropriate action.
2642 dtrace_speculation(dtrace_state_t *state)
2645 dtrace_speculation_state_t current;
2646 uint32_t *stat = &state->dts_speculations_unavail, count;
2648 while (i < state->dts_nspeculations) {
2649 dtrace_speculation_t *spec = &state->dts_speculations[i];
2651 current = spec->dtsp_state;
2653 if (current != DTRACESPEC_INACTIVE) {
2654 if (current == DTRACESPEC_COMMITTINGMANY ||
2655 current == DTRACESPEC_COMMITTING ||
2656 current == DTRACESPEC_DISCARDING)
2657 stat = &state->dts_speculations_busy;
2662 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2663 current, DTRACESPEC_ACTIVE) == current)
2668 * We couldn't find a speculation. If we found as much as a single
2669 * busy speculation buffer, we'll attribute this failure as "busy"
2670 * instead of "unavail".
2674 } while (dtrace_cas32(stat, count, count + 1) != count);
2680 * This routine commits an active speculation. If the specified speculation
2681 * is not in a valid state to perform a commit(), this routine will silently do
2682 * nothing. The state of the specified speculation is transitioned according
2683 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2686 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2687 dtrace_specid_t which)
2689 dtrace_speculation_t *spec;
2690 dtrace_buffer_t *src, *dest;
2691 uintptr_t daddr, saddr, dlimit, slimit;
2692 dtrace_speculation_state_t current, new = 0;
2699 if (which > state->dts_nspeculations) {
2700 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2704 spec = &state->dts_speculations[which - 1];
2705 src = &spec->dtsp_buffer[cpu];
2706 dest = &state->dts_buffer[cpu];
2709 current = spec->dtsp_state;
2711 if (current == DTRACESPEC_COMMITTINGMANY)
2715 case DTRACESPEC_INACTIVE:
2716 case DTRACESPEC_DISCARDING:
2719 case DTRACESPEC_COMMITTING:
2721 * This is only possible if we are (a) commit()'ing
2722 * without having done a prior speculate() on this CPU
2723 * and (b) racing with another commit() on a different
2724 * CPU. There's nothing to do -- we just assert that
2727 ASSERT(src->dtb_offset == 0);
2730 case DTRACESPEC_ACTIVE:
2731 new = DTRACESPEC_COMMITTING;
2734 case DTRACESPEC_ACTIVEONE:
2736 * This speculation is active on one CPU. If our
2737 * buffer offset is non-zero, we know that the one CPU
2738 * must be us. Otherwise, we are committing on a
2739 * different CPU from the speculate(), and we must
2740 * rely on being asynchronously cleaned.
2742 if (src->dtb_offset != 0) {
2743 new = DTRACESPEC_COMMITTING;
2748 case DTRACESPEC_ACTIVEMANY:
2749 new = DTRACESPEC_COMMITTINGMANY;
2755 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2756 current, new) != current);
2759 * We have set the state to indicate that we are committing this
2760 * speculation. Now reserve the necessary space in the destination
2763 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2764 sizeof (uint64_t), state, NULL)) < 0) {
2765 dtrace_buffer_drop(dest);
2770 * We have sufficient space to copy the speculative buffer into the
2771 * primary buffer. First, modify the speculative buffer, filling
2772 * in the timestamp of all entries with the current time. The data
2773 * must have the commit() time rather than the time it was traced,
2774 * so that all entries in the primary buffer are in timestamp order.
2776 timestamp = dtrace_gethrtime();
2777 saddr = (uintptr_t)src->dtb_tomax;
2778 slimit = saddr + src->dtb_offset;
2779 while (saddr < slimit) {
2781 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2783 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2784 saddr += sizeof (dtrace_epid_t);
2787 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2788 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2790 ASSERT3U(saddr + size, <=, slimit);
2791 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2792 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2794 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2800 * Copy the buffer across. (Note that this is a
2801 * highly subobtimal bcopy(); in the unlikely event that this becomes
2802 * a serious performance issue, a high-performance DTrace-specific
2803 * bcopy() should obviously be invented.)
2805 daddr = (uintptr_t)dest->dtb_tomax + offs;
2806 dlimit = daddr + src->dtb_offset;
2807 saddr = (uintptr_t)src->dtb_tomax;
2810 * First, the aligned portion.
2812 while (dlimit - daddr >= sizeof (uint64_t)) {
2813 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2815 daddr += sizeof (uint64_t);
2816 saddr += sizeof (uint64_t);
2820 * Now any left-over bit...
2822 while (dlimit - daddr)
2823 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2826 * Finally, commit the reserved space in the destination buffer.
2828 dest->dtb_offset = offs + src->dtb_offset;
2832 * If we're lucky enough to be the only active CPU on this speculation
2833 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2835 if (current == DTRACESPEC_ACTIVE ||
2836 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2837 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2838 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2840 ASSERT(rval == DTRACESPEC_COMMITTING);
2843 src->dtb_offset = 0;
2844 src->dtb_xamot_drops += src->dtb_drops;
2849 * This routine discards an active speculation. If the specified speculation
2850 * is not in a valid state to perform a discard(), this routine will silently
2851 * do nothing. The state of the specified speculation is transitioned
2852 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2855 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2856 dtrace_specid_t which)
2858 dtrace_speculation_t *spec;
2859 dtrace_speculation_state_t current, new = 0;
2860 dtrace_buffer_t *buf;
2865 if (which > state->dts_nspeculations) {
2866 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2870 spec = &state->dts_speculations[which - 1];
2871 buf = &spec->dtsp_buffer[cpu];
2874 current = spec->dtsp_state;
2877 case DTRACESPEC_INACTIVE:
2878 case DTRACESPEC_COMMITTINGMANY:
2879 case DTRACESPEC_COMMITTING:
2880 case DTRACESPEC_DISCARDING:
2883 case DTRACESPEC_ACTIVE:
2884 case DTRACESPEC_ACTIVEMANY:
2885 new = DTRACESPEC_DISCARDING;
2888 case DTRACESPEC_ACTIVEONE:
2889 if (buf->dtb_offset != 0) {
2890 new = DTRACESPEC_INACTIVE;
2892 new = DTRACESPEC_DISCARDING;
2899 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2900 current, new) != current);
2902 buf->dtb_offset = 0;
2907 * Note: not called from probe context. This function is called
2908 * asynchronously from cross call context to clean any speculations that are
2909 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2910 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2914 dtrace_speculation_clean_here(dtrace_state_t *state)
2916 dtrace_icookie_t cookie;
2917 processorid_t cpu = curcpu;
2918 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2921 cookie = dtrace_interrupt_disable();
2923 if (dest->dtb_tomax == NULL) {
2924 dtrace_interrupt_enable(cookie);
2928 for (i = 0; i < state->dts_nspeculations; i++) {
2929 dtrace_speculation_t *spec = &state->dts_speculations[i];
2930 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2932 if (src->dtb_tomax == NULL)
2935 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2936 src->dtb_offset = 0;
2940 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2943 if (src->dtb_offset == 0)
2946 dtrace_speculation_commit(state, cpu, i + 1);
2949 dtrace_interrupt_enable(cookie);
2953 * Note: not called from probe context. This function is called
2954 * asynchronously (and at a regular interval) to clean any speculations that
2955 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2956 * is work to be done, it cross calls all CPUs to perform that work;
2957 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2958 * INACTIVE state until they have been cleaned by all CPUs.
2961 dtrace_speculation_clean(dtrace_state_t *state)
2966 for (i = 0; i < state->dts_nspeculations; i++) {
2967 dtrace_speculation_t *spec = &state->dts_speculations[i];
2969 ASSERT(!spec->dtsp_cleaning);
2971 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2972 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2976 spec->dtsp_cleaning = 1;
2982 dtrace_xcall(DTRACE_CPUALL,
2983 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2986 * We now know that all CPUs have committed or discarded their
2987 * speculation buffers, as appropriate. We can now set the state
2990 for (i = 0; i < state->dts_nspeculations; i++) {
2991 dtrace_speculation_t *spec = &state->dts_speculations[i];
2992 dtrace_speculation_state_t current, new;
2994 if (!spec->dtsp_cleaning)
2997 current = spec->dtsp_state;
2998 ASSERT(current == DTRACESPEC_DISCARDING ||
2999 current == DTRACESPEC_COMMITTINGMANY);
3001 new = DTRACESPEC_INACTIVE;
3003 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3004 ASSERT(rv == current);
3005 spec->dtsp_cleaning = 0;
3010 * Called as part of a speculate() to get the speculative buffer associated
3011 * with a given speculation. Returns NULL if the specified speculation is not
3012 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
3013 * the active CPU is not the specified CPU -- the speculation will be
3014 * atomically transitioned into the ACTIVEMANY state.
3016 static dtrace_buffer_t *
3017 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3018 dtrace_specid_t which)
3020 dtrace_speculation_t *spec;
3021 dtrace_speculation_state_t current, new = 0;
3022 dtrace_buffer_t *buf;
3027 if (which > state->dts_nspeculations) {
3028 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3032 spec = &state->dts_speculations[which - 1];
3033 buf = &spec->dtsp_buffer[cpuid];
3036 current = spec->dtsp_state;
3039 case DTRACESPEC_INACTIVE:
3040 case DTRACESPEC_COMMITTINGMANY:
3041 case DTRACESPEC_DISCARDING:
3044 case DTRACESPEC_COMMITTING:
3045 ASSERT(buf->dtb_offset == 0);
3048 case DTRACESPEC_ACTIVEONE:
3050 * This speculation is currently active on one CPU.
3051 * Check the offset in the buffer; if it's non-zero,
3052 * that CPU must be us (and we leave the state alone).
3053 * If it's zero, assume that we're starting on a new
3054 * CPU -- and change the state to indicate that the
3055 * speculation is active on more than one CPU.
3057 if (buf->dtb_offset != 0)
3060 new = DTRACESPEC_ACTIVEMANY;
3063 case DTRACESPEC_ACTIVEMANY:
3066 case DTRACESPEC_ACTIVE:
3067 new = DTRACESPEC_ACTIVEONE;
3073 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3074 current, new) != current);
3076 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3081 * Return a string. In the event that the user lacks the privilege to access
3082 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3083 * don't fail access checking.
3085 * dtrace_dif_variable() uses this routine as a helper for various
3086 * builtin values such as 'execname' and 'probefunc.'
3089 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3090 dtrace_mstate_t *mstate)
3092 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3097 * The easy case: this probe is allowed to read all of memory, so
3098 * we can just return this as a vanilla pointer.
3100 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3104 * This is the tougher case: we copy the string in question from
3105 * kernel memory into scratch memory and return it that way: this
3106 * ensures that we won't trip up when access checking tests the
3107 * BYREF return value.
3109 strsz = dtrace_strlen((char *)addr, size) + 1;
3111 if (mstate->dtms_scratch_ptr + strsz >
3112 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3113 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3117 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3119 ret = mstate->dtms_scratch_ptr;
3120 mstate->dtms_scratch_ptr += strsz;
3125 * Return a string from a memoy address which is known to have one or
3126 * more concatenated, individually zero terminated, sub-strings.
3127 * In the event that the user lacks the privilege to access
3128 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3129 * don't fail access checking.
3131 * dtrace_dif_variable() uses this routine as a helper for various
3132 * builtin values such as 'execargs'.
3135 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3136 dtrace_mstate_t *mstate)
3142 if (mstate->dtms_scratch_ptr + strsz >
3143 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3144 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3148 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3151 /* Replace sub-string termination characters with a space. */
3152 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3157 ret = mstate->dtms_scratch_ptr;
3158 mstate->dtms_scratch_ptr += strsz;
3163 * This function implements the DIF emulator's variable lookups. The emulator
3164 * passes a reserved variable identifier and optional built-in array index.
3167 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3171 * If we're accessing one of the uncached arguments, we'll turn this
3172 * into a reference in the args array.
3174 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3175 ndx = v - DIF_VAR_ARG0;
3181 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3182 if (ndx >= sizeof (mstate->dtms_arg) /
3183 sizeof (mstate->dtms_arg[0])) {
3184 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3185 dtrace_provider_t *pv;
3188 pv = mstate->dtms_probe->dtpr_provider;
3189 if (pv->dtpv_pops.dtps_getargval != NULL)
3190 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3191 mstate->dtms_probe->dtpr_id,
3192 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3194 val = dtrace_getarg(ndx, aframes);
3197 * This is regrettably required to keep the compiler
3198 * from tail-optimizing the call to dtrace_getarg().
3199 * The condition always evaluates to true, but the
3200 * compiler has no way of figuring that out a priori.
3201 * (None of this would be necessary if the compiler
3202 * could be relied upon to _always_ tail-optimize
3203 * the call to dtrace_getarg() -- but it can't.)
3205 if (mstate->dtms_probe != NULL)
3211 return (mstate->dtms_arg[ndx]);
3214 case DIF_VAR_UREGS: {
3217 if (!dtrace_priv_proc(state))
3220 if ((lwp = curthread->t_lwp) == NULL) {
3221 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3222 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3226 return (dtrace_getreg(lwp->lwp_regs, ndx));
3230 case DIF_VAR_UREGS: {
3231 struct trapframe *tframe;
3233 if (!dtrace_priv_proc(state))
3236 if ((tframe = curthread->td_frame) == NULL) {
3237 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3238 cpu_core[curcpu].cpuc_dtrace_illval = 0;
3242 return (dtrace_getreg(tframe, ndx));
3246 case DIF_VAR_CURTHREAD:
3247 if (!dtrace_priv_proc(state))
3249 return ((uint64_t)(uintptr_t)curthread);
3251 case DIF_VAR_TIMESTAMP:
3252 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3253 mstate->dtms_timestamp = dtrace_gethrtime();
3254 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3256 return (mstate->dtms_timestamp);
3258 case DIF_VAR_VTIMESTAMP:
3259 ASSERT(dtrace_vtime_references != 0);
3260 return (curthread->t_dtrace_vtime);
3262 case DIF_VAR_WALLTIMESTAMP:
3263 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3264 mstate->dtms_walltimestamp = dtrace_gethrestime();
3265 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3267 return (mstate->dtms_walltimestamp);
3271 if (!dtrace_priv_kernel(state))
3273 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3274 mstate->dtms_ipl = dtrace_getipl();
3275 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3277 return (mstate->dtms_ipl);
3281 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3282 return (mstate->dtms_epid);
3285 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3286 return (mstate->dtms_probe->dtpr_id);
3288 case DIF_VAR_STACKDEPTH:
3289 if (!dtrace_priv_kernel(state))
3291 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3292 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3294 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3295 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3297 return (mstate->dtms_stackdepth);
3299 case DIF_VAR_USTACKDEPTH:
3300 if (!dtrace_priv_proc(state))
3302 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3304 * See comment in DIF_VAR_PID.
3306 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3308 mstate->dtms_ustackdepth = 0;
3310 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3311 mstate->dtms_ustackdepth =
3312 dtrace_getustackdepth();
3313 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3315 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3317 return (mstate->dtms_ustackdepth);
3319 case DIF_VAR_CALLER:
3320 if (!dtrace_priv_kernel(state))
3322 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3323 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3325 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3327 * If this is an unanchored probe, we are
3328 * required to go through the slow path:
3329 * dtrace_caller() only guarantees correct
3330 * results for anchored probes.
3332 pc_t caller[2] = {0, 0};
3334 dtrace_getpcstack(caller, 2, aframes,
3335 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3336 mstate->dtms_caller = caller[1];
3337 } else if ((mstate->dtms_caller =
3338 dtrace_caller(aframes)) == -1) {
3340 * We have failed to do this the quick way;
3341 * we must resort to the slower approach of
3342 * calling dtrace_getpcstack().
3346 dtrace_getpcstack(&caller, 1, aframes, NULL);
3347 mstate->dtms_caller = caller;
3350 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3352 return (mstate->dtms_caller);
3354 case DIF_VAR_UCALLER:
3355 if (!dtrace_priv_proc(state))
3358 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3362 * dtrace_getupcstack() fills in the first uint64_t
3363 * with the current PID. The second uint64_t will
3364 * be the program counter at user-level. The third
3365 * uint64_t will contain the caller, which is what
3369 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3370 dtrace_getupcstack(ustack, 3);
3371 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3372 mstate->dtms_ucaller = ustack[2];
3373 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3376 return (mstate->dtms_ucaller);
3378 case DIF_VAR_PROBEPROV:
3379 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3380 return (dtrace_dif_varstr(
3381 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3384 case DIF_VAR_PROBEMOD:
3385 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3386 return (dtrace_dif_varstr(
3387 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3390 case DIF_VAR_PROBEFUNC:
3391 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3392 return (dtrace_dif_varstr(
3393 (uintptr_t)mstate->dtms_probe->dtpr_func,
3396 case DIF_VAR_PROBENAME:
3397 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3398 return (dtrace_dif_varstr(
3399 (uintptr_t)mstate->dtms_probe->dtpr_name,
3403 if (!dtrace_priv_proc(state))
3408 * Note that we are assuming that an unanchored probe is
3409 * always due to a high-level interrupt. (And we're assuming
3410 * that there is only a single high level interrupt.)
3412 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3413 return (pid0.pid_id);
3416 * It is always safe to dereference one's own t_procp pointer:
3417 * it always points to a valid, allocated proc structure.
3418 * Further, it is always safe to dereference the p_pidp member
3419 * of one's own proc structure. (These are truisms becuase
3420 * threads and processes don't clean up their own state --
3421 * they leave that task to whomever reaps them.)
3423 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3425 return ((uint64_t)curproc->p_pid);
3429 if (!dtrace_priv_proc(state))
3434 * See comment in DIF_VAR_PID.
3436 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3437 return (pid0.pid_id);
3440 * It is always safe to dereference one's own t_procp pointer:
3441 * it always points to a valid, allocated proc structure.
3442 * (This is true because threads don't clean up their own
3443 * state -- they leave that task to whomever reaps them.)
3445 return ((uint64_t)curthread->t_procp->p_ppid);
3447 if (curproc->p_pid == proc0.p_pid)
3448 return (curproc->p_pid);
3450 return (curproc->p_pptr->p_pid);
3456 * See comment in DIF_VAR_PID.
3458 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3462 return ((uint64_t)curthread->t_tid);
3464 case DIF_VAR_EXECARGS: {
3465 struct pargs *p_args = curthread->td_proc->p_args;
3470 return (dtrace_dif_varstrz(
3471 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3474 case DIF_VAR_EXECNAME:
3476 if (!dtrace_priv_proc(state))
3480 * See comment in DIF_VAR_PID.
3482 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3483 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3486 * It is always safe to dereference one's own t_procp pointer:
3487 * it always points to a valid, allocated proc structure.
3488 * (This is true because threads don't clean up their own
3489 * state -- they leave that task to whomever reaps them.)
3491 return (dtrace_dif_varstr(
3492 (uintptr_t)curthread->t_procp->p_user.u_comm,
3495 return (dtrace_dif_varstr(
3496 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3499 case DIF_VAR_ZONENAME:
3501 if (!dtrace_priv_proc(state))
3505 * See comment in DIF_VAR_PID.
3507 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3508 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3511 * It is always safe to dereference one's own t_procp pointer:
3512 * it always points to a valid, allocated proc structure.
3513 * (This is true because threads don't clean up their own
3514 * state -- they leave that task to whomever reaps them.)
3516 return (dtrace_dif_varstr(
3517 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3524 if (!dtrace_priv_proc(state))
3529 * See comment in DIF_VAR_PID.
3531 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3532 return ((uint64_t)p0.p_cred->cr_uid);
3535 * It is always safe to dereference one's own t_procp pointer:
3536 * it always points to a valid, allocated proc structure.
3537 * (This is true because threads don't clean up their own
3538 * state -- they leave that task to whomever reaps them.)
3540 * Additionally, it is safe to dereference one's own process
3541 * credential, since this is never NULL after process birth.
3543 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3545 return ((uint64_t)curthread->td_ucred->cr_uid);
3549 if (!dtrace_priv_proc(state))
3554 * See comment in DIF_VAR_PID.
3556 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3557 return ((uint64_t)p0.p_cred->cr_gid);
3560 * It is always safe to dereference one's own t_procp pointer:
3561 * it always points to a valid, allocated proc structure.
3562 * (This is true because threads don't clean up their own
3563 * state -- they leave that task to whomever reaps them.)
3565 * Additionally, it is safe to dereference one's own process
3566 * credential, since this is never NULL after process birth.
3568 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3570 return ((uint64_t)curthread->td_ucred->cr_gid);
3573 case DIF_VAR_ERRNO: {
3576 if (!dtrace_priv_proc(state))
3580 * See comment in DIF_VAR_PID.
3582 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3586 * It is always safe to dereference one's own t_lwp pointer in
3587 * the event that this pointer is non-NULL. (This is true
3588 * because threads and lwps don't clean up their own state --
3589 * they leave that task to whomever reaps them.)
3591 if ((lwp = curthread->t_lwp) == NULL)
3594 return ((uint64_t)lwp->lwp_errno);
3596 return (curthread->td_errno);
3605 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3611 typedef enum dtrace_json_state {
3612 DTRACE_JSON_REST = 1,
3615 DTRACE_JSON_STRING_ESCAPE,
3616 DTRACE_JSON_STRING_ESCAPE_UNICODE,
3620 DTRACE_JSON_IDENTIFIER,
3622 DTRACE_JSON_NUMBER_FRAC,
3623 DTRACE_JSON_NUMBER_EXP,
3624 DTRACE_JSON_COLLECT_OBJECT
3625 } dtrace_json_state_t;
3628 * This function possesses just enough knowledge about JSON to extract a single
3629 * value from a JSON string and store it in the scratch buffer. It is able
3630 * to extract nested object values, and members of arrays by index.
3632 * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3633 * be looked up as we descend into the object tree. e.g.
3635 * foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3638 * The run time of this function must be bounded above by strsize to limit the
3639 * amount of work done in probe context. As such, it is implemented as a
3640 * simple state machine, reading one character at a time using safe loads
3641 * until we find the requested element, hit a parsing error or run off the
3642 * end of the object or string.
3644 * As there is no way for a subroutine to return an error without interrupting
3645 * clause execution, we simply return NULL in the event of a missing key or any
3646 * other error condition. Each NULL return in this function is commented with
3647 * the error condition it represents -- parsing or otherwise.
3649 * The set of states for the state machine closely matches the JSON
3650 * specification (http://json.org/). Briefly:
3653 * Skip whitespace until we find either a top-level Object, moving
3654 * to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3656 * DTRACE_JSON_OBJECT:
3657 * Locate the next key String in an Object. Sets a flag to denote
3658 * the next String as a key string and moves to DTRACE_JSON_STRING.
3660 * DTRACE_JSON_COLON:
3661 * Skip whitespace until we find the colon that separates key Strings
3662 * from their values. Once found, move to DTRACE_JSON_VALUE.
3664 * DTRACE_JSON_VALUE:
3665 * Detects the type of the next value (String, Number, Identifier, Object
3666 * or Array) and routes to the states that process that type. Here we also
3667 * deal with the element selector list if we are requested to traverse down
3668 * into the object tree.
3670 * DTRACE_JSON_COMMA:
3671 * Skip whitespace until we find the comma that separates key-value pairs
3672 * in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3673 * (similarly DTRACE_JSON_VALUE). All following literal value processing
3674 * states return to this state at the end of their value, unless otherwise
3677 * DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3678 * Processes a Number literal from the JSON, including any exponent
3679 * component that may be present. Numbers are returned as strings, which
3680 * may be passed to strtoll() if an integer is required.
3682 * DTRACE_JSON_IDENTIFIER:
3683 * Processes a "true", "false" or "null" literal in the JSON.
3685 * DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3686 * DTRACE_JSON_STRING_ESCAPE_UNICODE:
3687 * Processes a String literal from the JSON, whether the String denotes
3688 * a key, a value or part of a larger Object. Handles all escape sequences
3689 * present in the specification, including four-digit unicode characters,
3690 * but merely includes the escape sequence without converting it to the
3691 * actual escaped character. If the String is flagged as a key, we
3692 * move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3694 * DTRACE_JSON_COLLECT_OBJECT:
3695 * This state collects an entire Object (or Array), correctly handling
3696 * embedded strings. If the full element selector list matches this nested
3697 * object, we return the Object in full as a string. If not, we use this
3698 * state to skip to the next value at this level and continue processing.
3700 * NOTE: This function uses various macros from strtolctype.h to manipulate
3701 * digit values, etc -- these have all been checked to ensure they make
3702 * no additional function calls.
3705 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3708 dtrace_json_state_t state = DTRACE_JSON_REST;
3709 int64_t array_elem = INT64_MIN;
3710 int64_t array_pos = 0;
3711 uint8_t escape_unicount = 0;
3712 boolean_t string_is_key = B_FALSE;
3713 boolean_t collect_object = B_FALSE;
3714 boolean_t found_key = B_FALSE;
3715 boolean_t in_array = B_FALSE;
3716 uint32_t braces = 0, brackets = 0;
3717 char *elem = elemlist;
3721 for (cur = json; cur < json + size; cur++) {
3722 char cc = dtrace_load8(cur);
3727 case DTRACE_JSON_REST:
3732 state = DTRACE_JSON_OBJECT;
3739 array_elem = dtrace_strtoll(elem, 10, size);
3740 found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3741 state = DTRACE_JSON_VALUE;
3746 * ERROR: expected to find a top-level object or array.
3749 case DTRACE_JSON_OBJECT:
3754 state = DTRACE_JSON_STRING;
3755 string_is_key = B_TRUE;
3760 * ERROR: either the object did not start with a key
3761 * string, or we've run off the end of the object
3762 * without finding the requested key.
3765 case DTRACE_JSON_STRING:
3768 state = DTRACE_JSON_STRING_ESCAPE;
3773 if (collect_object) {
3775 * We don't reset the dest here, as
3776 * the string is part of a larger
3777 * object being collected.
3780 collect_object = B_FALSE;
3781 state = DTRACE_JSON_COLLECT_OBJECT;
3785 dd = dest; /* reset string buffer */
3786 if (string_is_key) {
3787 if (dtrace_strncmp(dest, elem,
3790 } else if (found_key) {
3793 * We expected an object, not
3800 state = string_is_key ? DTRACE_JSON_COLON :
3802 string_is_key = B_FALSE;
3808 case DTRACE_JSON_STRING_ESCAPE:
3811 escape_unicount = 0;
3812 state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3814 state = DTRACE_JSON_STRING;
3817 case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3818 if (!isxdigit(cc)) {
3820 * ERROR: invalid unicode escape, expected
3821 * four valid hexidecimal digits.
3827 if (++escape_unicount == 4)
3828 state = DTRACE_JSON_STRING;
3830 case DTRACE_JSON_COLON:
3835 state = DTRACE_JSON_VALUE;
3840 * ERROR: expected a colon.
3843 case DTRACE_JSON_COMMA:
3849 state = DTRACE_JSON_VALUE;
3850 if (++array_pos == array_elem)
3853 state = DTRACE_JSON_OBJECT;
3859 * ERROR: either we hit an unexpected character, or
3860 * we reached the end of the object or array without
3861 * finding the requested key.
3864 case DTRACE_JSON_IDENTIFIER:
3871 dd = dest; /* reset string buffer */
3873 if (dtrace_strncmp(dest, "true", 5) == 0 ||
3874 dtrace_strncmp(dest, "false", 6) == 0 ||
3875 dtrace_strncmp(dest, "null", 5) == 0) {
3879 * ERROR: We expected an object,
3880 * not this identifier.
3887 state = DTRACE_JSON_COMMA;
3893 * ERROR: we did not recognise the identifier as one
3894 * of those in the JSON specification.
3897 case DTRACE_JSON_NUMBER:
3900 state = DTRACE_JSON_NUMBER_FRAC;
3904 if (cc == 'x' || cc == 'X') {
3906 * ERROR: specification explicitly excludes
3907 * hexidecimal or octal numbers.
3913 case DTRACE_JSON_NUMBER_FRAC:
3914 if (cc == 'e' || cc == 'E') {
3916 state = DTRACE_JSON_NUMBER_EXP;
3920 if (cc == '+' || cc == '-') {
3922 * ERROR: expect sign as part of exponent only.
3927 case DTRACE_JSON_NUMBER_EXP:
3928 if (isdigit(cc) || cc == '+' || cc == '-') {
3934 dd = dest; /* reset string buffer */
3938 * ERROR: We expected an object, not
3947 state = DTRACE_JSON_COMMA;
3949 case DTRACE_JSON_VALUE:
3953 if (cc == '{' || cc == '[') {
3954 if (nelems > 1 && found_key) {
3955 in_array = cc == '[' ? B_TRUE : B_FALSE;
3957 * If our element selector directs us
3958 * to descend into this nested object,
3959 * then move to the next selector
3960 * element in the list and restart the
3963 while (*elem != '\0')
3965 elem++; /* skip the inter-element NUL */
3969 state = DTRACE_JSON_VALUE;
3971 array_elem = dtrace_strtoll(
3973 found_key = array_elem == 0 ?
3976 found_key = B_FALSE;
3977 state = DTRACE_JSON_OBJECT;
3983 * Otherwise, we wish to either skip this
3984 * nested object or return it in full.
3991 state = DTRACE_JSON_COLLECT_OBJECT;
3996 state = DTRACE_JSON_STRING;
4002 * Here we deal with true, false and null.
4005 state = DTRACE_JSON_IDENTIFIER;
4009 if (cc == '-' || isdigit(cc)) {
4011 state = DTRACE_JSON_NUMBER;
4016 * ERROR: unexpected character at start of value.
4019 case DTRACE_JSON_COLLECT_OBJECT:
4022 * ERROR: unexpected end of input.
4028 collect_object = B_TRUE;
4029 state = DTRACE_JSON_STRING;
4034 if (brackets-- == 0) {
4036 * ERROR: unbalanced brackets.
4040 } else if (cc == '}') {
4041 if (braces-- == 0) {
4043 * ERROR: unbalanced braces.
4047 } else if (cc == '{') {
4049 } else if (cc == '[') {
4053 if (brackets == 0 && braces == 0) {
4058 dd = dest; /* reset string buffer */
4059 state = DTRACE_JSON_COMMA;
4068 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4069 * Notice that we don't bother validating the proper number of arguments or
4070 * their types in the tuple stack. This isn't needed because all argument
4071 * interpretation is safe because of our load safety -- the worst that can
4072 * happen is that a bogus program can obtain bogus results.
4075 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4076 dtrace_key_t *tupregs, int nargs,
4077 dtrace_mstate_t *mstate, dtrace_state_t *state)
4079 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4080 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4081 dtrace_vstate_t *vstate = &state->dts_vstate;
4094 struct thread *lowner;
4096 struct lock_object *li;
4103 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4107 case DIF_SUBR_MUTEX_OWNED:
4108 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4114 m.mx = dtrace_load64(tupregs[0].dttk_value);
4115 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4116 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4118 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4121 case DIF_SUBR_MUTEX_OWNER:
4122 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4128 m.mx = dtrace_load64(tupregs[0].dttk_value);
4129 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4130 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4131 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4136 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4137 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4143 m.mx = dtrace_load64(tupregs[0].dttk_value);
4144 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4147 case DIF_SUBR_MUTEX_TYPE_SPIN:
4148 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4154 m.mx = dtrace_load64(tupregs[0].dttk_value);
4155 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4158 case DIF_SUBR_RW_READ_HELD: {
4161 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4167 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4168 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4172 case DIF_SUBR_RW_WRITE_HELD:
4173 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4179 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4180 regs[rd] = _RW_WRITE_HELD(&r.ri);
4183 case DIF_SUBR_RW_ISWRITER:
4184 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4190 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4191 regs[rd] = _RW_ISWRITER(&r.ri);
4194 #else /* !illumos */
4195 case DIF_SUBR_MUTEX_OWNED:
4196 if (!dtrace_canload(tupregs[0].dttk_value,
4197 sizeof (struct lock_object), mstate, vstate)) {
4201 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4202 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4205 case DIF_SUBR_MUTEX_OWNER:
4206 if (!dtrace_canload(tupregs[0].dttk_value,
4207 sizeof (struct lock_object), mstate, vstate)) {
4211 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4212 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4213 regs[rd] = (uintptr_t)lowner;
4216 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4217 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4222 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4223 /* XXX - should be only LC_SLEEPABLE? */
4224 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
4225 (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
4228 case DIF_SUBR_MUTEX_TYPE_SPIN:
4229 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4234 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4235 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4238 case DIF_SUBR_RW_READ_HELD:
4239 case DIF_SUBR_SX_SHARED_HELD:
4240 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4245 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4246 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4250 case DIF_SUBR_RW_WRITE_HELD:
4251 case DIF_SUBR_SX_EXCLUSIVE_HELD:
4252 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4257 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4258 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4259 regs[rd] = (lowner == curthread);
4262 case DIF_SUBR_RW_ISWRITER:
4263 case DIF_SUBR_SX_ISEXCLUSIVE:
4264 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4269 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4270 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4273 #endif /* illumos */
4275 case DIF_SUBR_BCOPY: {
4277 * We need to be sure that the destination is in the scratch
4278 * region -- no other region is allowed.
4280 uintptr_t src = tupregs[0].dttk_value;
4281 uintptr_t dest = tupregs[1].dttk_value;
4282 size_t size = tupregs[2].dttk_value;
4284 if (!dtrace_inscratch(dest, size, mstate)) {
4285 *flags |= CPU_DTRACE_BADADDR;
4290 if (!dtrace_canload(src, size, mstate, vstate)) {
4295 dtrace_bcopy((void *)src, (void *)dest, size);
4299 case DIF_SUBR_ALLOCA:
4300 case DIF_SUBR_COPYIN: {
4301 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4303 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4304 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4307 * This action doesn't require any credential checks since
4308 * probes will not activate in user contexts to which the
4309 * enabling user does not have permissions.
4313 * Rounding up the user allocation size could have overflowed
4314 * a large, bogus allocation (like -1ULL) to 0.
4316 if (scratch_size < size ||
4317 !DTRACE_INSCRATCH(mstate, scratch_size)) {
4318 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4323 if (subr == DIF_SUBR_COPYIN) {
4324 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4325 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4326 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4329 mstate->dtms_scratch_ptr += scratch_size;
4334 case DIF_SUBR_COPYINTO: {
4335 uint64_t size = tupregs[1].dttk_value;
4336 uintptr_t dest = tupregs[2].dttk_value;
4339 * This action doesn't require any credential checks since
4340 * probes will not activate in user contexts to which the
4341 * enabling user does not have permissions.
4343 if (!dtrace_inscratch(dest, size, mstate)) {
4344 *flags |= CPU_DTRACE_BADADDR;
4349 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4350 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4351 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4355 case DIF_SUBR_COPYINSTR: {
4356 uintptr_t dest = mstate->dtms_scratch_ptr;
4357 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4359 if (nargs > 1 && tupregs[1].dttk_value < size)
4360 size = tupregs[1].dttk_value + 1;
4363 * This action doesn't require any credential checks since
4364 * probes will not activate in user contexts to which the
4365 * enabling user does not have permissions.
4367 if (!DTRACE_INSCRATCH(mstate, size)) {
4368 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4373 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4374 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4375 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4377 ((char *)dest)[size - 1] = '\0';
4378 mstate->dtms_scratch_ptr += size;
4384 case DIF_SUBR_MSGSIZE:
4385 case DIF_SUBR_MSGDSIZE: {
4386 uintptr_t baddr = tupregs[0].dttk_value, daddr;
4387 uintptr_t wptr, rptr;
4391 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4393 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4399 wptr = dtrace_loadptr(baddr +
4400 offsetof(mblk_t, b_wptr));
4402 rptr = dtrace_loadptr(baddr +
4403 offsetof(mblk_t, b_rptr));
4406 *flags |= CPU_DTRACE_BADADDR;
4407 *illval = tupregs[0].dttk_value;
4411 daddr = dtrace_loadptr(baddr +
4412 offsetof(mblk_t, b_datap));
4414 baddr = dtrace_loadptr(baddr +
4415 offsetof(mblk_t, b_cont));
4418 * We want to prevent against denial-of-service here,
4419 * so we're only going to search the list for
4420 * dtrace_msgdsize_max mblks.
4422 if (cont++ > dtrace_msgdsize_max) {
4423 *flags |= CPU_DTRACE_ILLOP;
4427 if (subr == DIF_SUBR_MSGDSIZE) {
4428 if (dtrace_load8(daddr +
4429 offsetof(dblk_t, db_type)) != M_DATA)
4433 count += wptr - rptr;
4436 if (!(*flags & CPU_DTRACE_FAULT))
4443 case DIF_SUBR_PROGENYOF: {
4444 pid_t pid = tupregs[0].dttk_value;
4448 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4450 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4452 if (p->p_pidp->pid_id == pid) {
4454 if (p->p_pid == pid) {
4461 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4467 case DIF_SUBR_SPECULATION:
4468 regs[rd] = dtrace_speculation(state);
4471 case DIF_SUBR_COPYOUT: {
4472 uintptr_t kaddr = tupregs[0].dttk_value;
4473 uintptr_t uaddr = tupregs[1].dttk_value;
4474 uint64_t size = tupregs[2].dttk_value;
4476 if (!dtrace_destructive_disallow &&
4477 dtrace_priv_proc_control(state) &&
4478 !dtrace_istoxic(kaddr, size) &&
4479 dtrace_canload(kaddr, size, mstate, vstate)) {
4480 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4481 dtrace_copyout(kaddr, uaddr, size, flags);
4482 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4487 case DIF_SUBR_COPYOUTSTR: {
4488 uintptr_t kaddr = tupregs[0].dttk_value;
4489 uintptr_t uaddr = tupregs[1].dttk_value;
4490 uint64_t size = tupregs[2].dttk_value;
4492 if (!dtrace_destructive_disallow &&
4493 dtrace_priv_proc_control(state) &&
4494 !dtrace_istoxic(kaddr, size) &&
4495 dtrace_strcanload(kaddr, size, mstate, vstate)) {
4496 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4497 dtrace_copyoutstr(kaddr, uaddr, size, flags);
4498 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4503 case DIF_SUBR_STRLEN: {
4505 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4506 sz = dtrace_strlen((char *)addr,
4507 state->dts_options[DTRACEOPT_STRSIZE]);
4509 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4519 case DIF_SUBR_STRCHR:
4520 case DIF_SUBR_STRRCHR: {
4522 * We're going to iterate over the string looking for the
4523 * specified character. We will iterate until we have reached
4524 * the string length or we have found the character. If this
4525 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4526 * of the specified character instead of the first.
4528 uintptr_t saddr = tupregs[0].dttk_value;
4529 uintptr_t addr = tupregs[0].dttk_value;
4530 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4531 char c, target = (char)tupregs[1].dttk_value;
4533 for (regs[rd] = 0; addr < limit; addr++) {
4534 if ((c = dtrace_load8(addr)) == target) {
4537 if (subr == DIF_SUBR_STRCHR)
4545 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4553 case DIF_SUBR_STRSTR:
4554 case DIF_SUBR_INDEX:
4555 case DIF_SUBR_RINDEX: {
4557 * We're going to iterate over the string looking for the
4558 * specified string. We will iterate until we have reached
4559 * the string length or we have found the string. (Yes, this
4560 * is done in the most naive way possible -- but considering
4561 * that the string we're searching for is likely to be
4562 * relatively short, the complexity of Rabin-Karp or similar
4563 * hardly seems merited.)
4565 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4566 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4567 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4568 size_t len = dtrace_strlen(addr, size);
4569 size_t sublen = dtrace_strlen(substr, size);
4570 char *limit = addr + len, *orig = addr;
4571 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4574 regs[rd] = notfound;
4576 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4581 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4588 * strstr() and index()/rindex() have similar semantics if
4589 * both strings are the empty string: strstr() returns a
4590 * pointer to the (empty) string, and index() and rindex()
4591 * both return index 0 (regardless of any position argument).
4593 if (sublen == 0 && len == 0) {
4594 if (subr == DIF_SUBR_STRSTR)
4595 regs[rd] = (uintptr_t)addr;
4601 if (subr != DIF_SUBR_STRSTR) {
4602 if (subr == DIF_SUBR_RINDEX) {
4609 * Both index() and rindex() take an optional position
4610 * argument that denotes the starting position.
4613 int64_t pos = (int64_t)tupregs[2].dttk_value;
4616 * If the position argument to index() is
4617 * negative, Perl implicitly clamps it at
4618 * zero. This semantic is a little surprising
4619 * given the special meaning of negative
4620 * positions to similar Perl functions like
4621 * substr(), but it appears to reflect a
4622 * notion that index() can start from a
4623 * negative index and increment its way up to
4624 * the string. Given this notion, Perl's
4625 * rindex() is at least self-consistent in
4626 * that it implicitly clamps positions greater
4627 * than the string length to be the string
4628 * length. Where Perl completely loses
4629 * coherence, however, is when the specified
4630 * substring is the empty string (""). In
4631 * this case, even if the position is
4632 * negative, rindex() returns 0 -- and even if
4633 * the position is greater than the length,
4634 * index() returns the string length. These
4635 * semantics violate the notion that index()
4636 * should never return a value less than the
4637 * specified position and that rindex() should
4638 * never return a value greater than the
4639 * specified position. (One assumes that
4640 * these semantics are artifacts of Perl's
4641 * implementation and not the results of
4642 * deliberate design -- it beggars belief that
4643 * even Larry Wall could desire such oddness.)
4644 * While in the abstract one would wish for
4645 * consistent position semantics across
4646 * substr(), index() and rindex() -- or at the
4647 * very least self-consistent position
4648 * semantics for index() and rindex() -- we
4649 * instead opt to keep with the extant Perl
4650 * semantics, in all their broken glory. (Do
4651 * we have more desire to maintain Perl's
4652 * semantics than Perl does? Probably.)
4654 if (subr == DIF_SUBR_RINDEX) {
4678 for (regs[rd] = notfound; addr != limit; addr += inc) {
4679 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4680 if (subr != DIF_SUBR_STRSTR) {
4682 * As D index() and rindex() are
4683 * modeled on Perl (and not on awk),
4684 * we return a zero-based (and not a
4685 * one-based) index. (For you Perl
4686 * weenies: no, we're not going to add
4687 * $[ -- and shouldn't you be at a con
4690 regs[rd] = (uintptr_t)(addr - orig);
4694 ASSERT(subr == DIF_SUBR_STRSTR);
4695 regs[rd] = (uintptr_t)addr;
4703 case DIF_SUBR_STRTOK: {
4704 uintptr_t addr = tupregs[0].dttk_value;
4705 uintptr_t tokaddr = tupregs[1].dttk_value;
4706 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4707 uintptr_t limit, toklimit = tokaddr + size;
4708 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
4709 char *dest = (char *)mstate->dtms_scratch_ptr;
4713 * Check both the token buffer and (later) the input buffer,
4714 * since both could be non-scratch addresses.
4716 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4721 if (!DTRACE_INSCRATCH(mstate, size)) {
4722 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4729 * If the address specified is NULL, we use our saved
4730 * strtok pointer from the mstate. Note that this
4731 * means that the saved strtok pointer is _only_
4732 * valid within multiple enablings of the same probe --
4733 * it behaves like an implicit clause-local variable.
4735 addr = mstate->dtms_strtok;
4738 * If the user-specified address is non-NULL we must
4739 * access check it. This is the only time we have
4740 * a chance to do so, since this address may reside
4741 * in the string table of this clause-- future calls
4742 * (when we fetch addr from mstate->dtms_strtok)
4743 * would fail this access check.
4745 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4752 * First, zero the token map, and then process the token
4753 * string -- setting a bit in the map for every character
4754 * found in the token string.
4756 for (i = 0; i < sizeof (tokmap); i++)
4759 for (; tokaddr < toklimit; tokaddr++) {
4760 if ((c = dtrace_load8(tokaddr)) == '\0')
4763 ASSERT((c >> 3) < sizeof (tokmap));
4764 tokmap[c >> 3] |= (1 << (c & 0x7));
4767 for (limit = addr + size; addr < limit; addr++) {
4769 * We're looking for a character that is _not_ contained
4770 * in the token string.
4772 if ((c = dtrace_load8(addr)) == '\0')
4775 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4781 * We reached the end of the string without finding
4782 * any character that was not in the token string.
4783 * We return NULL in this case, and we set the saved
4784 * address to NULL as well.
4787 mstate->dtms_strtok = 0;
4792 * From here on, we're copying into the destination string.
4794 for (i = 0; addr < limit && i < size - 1; addr++) {
4795 if ((c = dtrace_load8(addr)) == '\0')
4798 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4807 regs[rd] = (uintptr_t)dest;
4808 mstate->dtms_scratch_ptr += size;
4809 mstate->dtms_strtok = addr;
4813 case DIF_SUBR_SUBSTR: {
4814 uintptr_t s = tupregs[0].dttk_value;
4815 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4816 char *d = (char *)mstate->dtms_scratch_ptr;
4817 int64_t index = (int64_t)tupregs[1].dttk_value;
4818 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4819 size_t len = dtrace_strlen((char *)s, size);
4822 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4827 if (!DTRACE_INSCRATCH(mstate, size)) {
4828 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4834 remaining = (int64_t)size;
4839 if (index < 0 && index + remaining > 0) {
4845 if (index >= len || index < 0) {
4847 } else if (remaining < 0) {
4848 remaining += len - index;
4849 } else if (index + remaining > size) {
4850 remaining = size - index;
4853 for (i = 0; i < remaining; i++) {
4854 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4860 mstate->dtms_scratch_ptr += size;
4861 regs[rd] = (uintptr_t)d;
4865 case DIF_SUBR_JSON: {
4866 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4867 uintptr_t json = tupregs[0].dttk_value;
4868 size_t jsonlen = dtrace_strlen((char *)json, size);
4869 uintptr_t elem = tupregs[1].dttk_value;
4870 size_t elemlen = dtrace_strlen((char *)elem, size);
4872 char *dest = (char *)mstate->dtms_scratch_ptr;
4873 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4874 char *ee = elemlist;
4878 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4879 !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4884 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4885 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4891 * Read the element selector and split it up into a packed list
4894 for (cur = elem; cur < elem + elemlen; cur++) {
4895 char cc = dtrace_load8(cur);
4897 if (cur == elem && cc == '[') {
4899 * If the first element selector key is
4900 * actually an array index then ignore the
4909 if (cc == '.' || cc == '[') {
4918 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4919 nelems, dest)) != 0)
4920 mstate->dtms_scratch_ptr += jsonlen + 1;
4924 case DIF_SUBR_TOUPPER:
4925 case DIF_SUBR_TOLOWER: {
4926 uintptr_t s = tupregs[0].dttk_value;
4927 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4928 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4929 size_t len = dtrace_strlen((char *)s, size);
4930 char lower, upper, convert;
4933 if (subr == DIF_SUBR_TOUPPER) {
4943 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4948 if (!DTRACE_INSCRATCH(mstate, size)) {
4949 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4954 for (i = 0; i < size - 1; i++) {
4955 if ((c = dtrace_load8(s + i)) == '\0')
4958 if (c >= lower && c <= upper)
4959 c = convert + (c - lower);
4966 regs[rd] = (uintptr_t)dest;
4967 mstate->dtms_scratch_ptr += size;
4972 case DIF_SUBR_GETMAJOR:
4974 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4976 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4980 case DIF_SUBR_GETMINOR:
4982 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4984 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4988 case DIF_SUBR_DDI_PATHNAME: {
4990 * This one is a galactic mess. We are going to roughly
4991 * emulate ddi_pathname(), but it's made more complicated
4992 * by the fact that we (a) want to include the minor name and
4993 * (b) must proceed iteratively instead of recursively.
4995 uintptr_t dest = mstate->dtms_scratch_ptr;
4996 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4997 char *start = (char *)dest, *end = start + size - 1;
4998 uintptr_t daddr = tupregs[0].dttk_value;
4999 int64_t minor = (int64_t)tupregs[1].dttk_value;
5001 int i, len, depth = 0;
5004 * Due to all the pointer jumping we do and context we must
5005 * rely upon, we just mandate that the user must have kernel
5006 * read privileges to use this routine.
5008 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5009 *flags |= CPU_DTRACE_KPRIV;
5014 if (!DTRACE_INSCRATCH(mstate, size)) {
5015 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5023 * We want to have a name for the minor. In order to do this,
5024 * we need to walk the minor list from the devinfo. We want
5025 * to be sure that we don't infinitely walk a circular list,
5026 * so we check for circularity by sending a scout pointer
5027 * ahead two elements for every element that we iterate over;
5028 * if the list is circular, these will ultimately point to the
5029 * same element. You may recognize this little trick as the
5030 * answer to a stupid interview question -- one that always
5031 * seems to be asked by those who had to have it laboriously
5032 * explained to them, and who can't even concisely describe
5033 * the conditions under which one would be forced to resort to
5034 * this technique. Needless to say, those conditions are
5035 * found here -- and probably only here. Is this the only use
5036 * of this infamous trick in shipping, production code? If it
5037 * isn't, it probably should be...
5040 uintptr_t maddr = dtrace_loadptr(daddr +
5041 offsetof(struct dev_info, devi_minor));
5043 uintptr_t next = offsetof(struct ddi_minor_data, next);
5044 uintptr_t name = offsetof(struct ddi_minor_data,
5045 d_minor) + offsetof(struct ddi_minor, name);
5046 uintptr_t dev = offsetof(struct ddi_minor_data,
5047 d_minor) + offsetof(struct ddi_minor, dev);
5051 scout = dtrace_loadptr(maddr + next);
5053 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5056 m = dtrace_load64(maddr + dev) & MAXMIN64;
5058 m = dtrace_load32(maddr + dev) & MAXMIN;
5061 maddr = dtrace_loadptr(maddr + next);
5066 scout = dtrace_loadptr(scout + next);
5071 scout = dtrace_loadptr(scout + next);
5076 if (scout == maddr) {
5077 *flags |= CPU_DTRACE_ILLOP;
5085 * We have the minor data. Now we need to
5086 * copy the minor's name into the end of the
5089 s = (char *)dtrace_loadptr(maddr + name);
5090 len = dtrace_strlen(s, size);
5092 if (*flags & CPU_DTRACE_FAULT)
5096 if ((end -= (len + 1)) < start)
5102 for (i = 1; i <= len; i++)
5103 end[i] = dtrace_load8((uintptr_t)s++);
5108 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5109 ddi_node_state_t devi_state;
5111 devi_state = dtrace_load32(daddr +
5112 offsetof(struct dev_info, devi_node_state));
5114 if (*flags & CPU_DTRACE_FAULT)
5117 if (devi_state >= DS_INITIALIZED) {
5118 s = (char *)dtrace_loadptr(daddr +
5119 offsetof(struct dev_info, devi_addr));
5120 len = dtrace_strlen(s, size);
5122 if (*flags & CPU_DTRACE_FAULT)
5126 if ((end -= (len + 1)) < start)
5132 for (i = 1; i <= len; i++)
5133 end[i] = dtrace_load8((uintptr_t)s++);
5137 * Now for the node name...
5139 s = (char *)dtrace_loadptr(daddr +
5140 offsetof(struct dev_info, devi_node_name));
5142 daddr = dtrace_loadptr(daddr +
5143 offsetof(struct dev_info, devi_parent));
5146 * If our parent is NULL (that is, if we're the root
5147 * node), we're going to use the special path
5153 len = dtrace_strlen(s, size);
5154 if (*flags & CPU_DTRACE_FAULT)
5157 if ((end -= (len + 1)) < start)
5160 for (i = 1; i <= len; i++)
5161 end[i] = dtrace_load8((uintptr_t)s++);
5164 if (depth++ > dtrace_devdepth_max) {
5165 *flags |= CPU_DTRACE_ILLOP;
5171 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5174 regs[rd] = (uintptr_t)end;
5175 mstate->dtms_scratch_ptr += size;
5182 case DIF_SUBR_STRJOIN: {
5183 char *d = (char *)mstate->dtms_scratch_ptr;
5184 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5185 uintptr_t s1 = tupregs[0].dttk_value;
5186 uintptr_t s2 = tupregs[1].dttk_value;
5189 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
5190 !dtrace_strcanload(s2, size, mstate, vstate)) {
5195 if (!DTRACE_INSCRATCH(mstate, size)) {
5196 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5203 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5208 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
5216 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5221 if ((d[i++] = dtrace_load8(s2++)) == '\0')
5226 mstate->dtms_scratch_ptr += i;
5227 regs[rd] = (uintptr_t)d;
5233 case DIF_SUBR_STRTOLL: {
5234 uintptr_t s = tupregs[0].dttk_value;
5235 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5239 if ((base = tupregs[1].dttk_value) <= 1 ||
5240 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5241 *flags |= CPU_DTRACE_ILLOP;
5246 if (!dtrace_strcanload(s, size, mstate, vstate)) {
5247 regs[rd] = INT64_MIN;
5251 regs[rd] = dtrace_strtoll((char *)s, base, size);
5255 case DIF_SUBR_LLTOSTR: {
5256 int64_t i = (int64_t)tupregs[0].dttk_value;
5257 uint64_t val, digit;
5258 uint64_t size = 65; /* enough room for 2^64 in binary */
5259 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5263 if ((base = tupregs[1].dttk_value) <= 1 ||
5264 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5265 *flags |= CPU_DTRACE_ILLOP;
5270 val = (base == 10 && i < 0) ? i * -1 : i;
5272 if (!DTRACE_INSCRATCH(mstate, size)) {
5273 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5278 for (*end-- = '\0'; val; val /= base) {
5279 if ((digit = val % base) <= '9' - '0') {
5280 *end-- = '0' + digit;
5282 *end-- = 'a' + (digit - ('9' - '0') - 1);
5286 if (i == 0 && base == 16)
5292 if (i == 0 || base == 8 || base == 16)
5295 if (i < 0 && base == 10)
5298 regs[rd] = (uintptr_t)end + 1;
5299 mstate->dtms_scratch_ptr += size;
5303 case DIF_SUBR_HTONS:
5304 case DIF_SUBR_NTOHS:
5305 #if BYTE_ORDER == BIG_ENDIAN
5306 regs[rd] = (uint16_t)tupregs[0].dttk_value;
5308 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5313 case DIF_SUBR_HTONL:
5314 case DIF_SUBR_NTOHL:
5315 #if BYTE_ORDER == BIG_ENDIAN
5316 regs[rd] = (uint32_t)tupregs[0].dttk_value;
5318 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5323 case DIF_SUBR_HTONLL:
5324 case DIF_SUBR_NTOHLL:
5325 #if BYTE_ORDER == BIG_ENDIAN
5326 regs[rd] = (uint64_t)tupregs[0].dttk_value;
5328 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5333 case DIF_SUBR_DIRNAME:
5334 case DIF_SUBR_BASENAME: {
5335 char *dest = (char *)mstate->dtms_scratch_ptr;
5336 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5337 uintptr_t src = tupregs[0].dttk_value;
5338 int i, j, len = dtrace_strlen((char *)src, size);
5339 int lastbase = -1, firstbase = -1, lastdir = -1;
5342 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5347 if (!DTRACE_INSCRATCH(mstate, size)) {
5348 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5354 * The basename and dirname for a zero-length string is
5359 src = (uintptr_t)".";
5363 * Start from the back of the string, moving back toward the
5364 * front until we see a character that isn't a slash. That
5365 * character is the last character in the basename.
5367 for (i = len - 1; i >= 0; i--) {
5368 if (dtrace_load8(src + i) != '/')
5376 * Starting from the last character in the basename, move
5377 * towards the front until we find a slash. The character
5378 * that we processed immediately before that is the first
5379 * character in the basename.
5381 for (; i >= 0; i--) {
5382 if (dtrace_load8(src + i) == '/')
5390 * Now keep going until we find a non-slash character. That
5391 * character is the last character in the dirname.
5393 for (; i >= 0; i--) {
5394 if (dtrace_load8(src + i) != '/')
5401 ASSERT(!(lastbase == -1 && firstbase != -1));
5402 ASSERT(!(firstbase == -1 && lastdir != -1));
5404 if (lastbase == -1) {
5406 * We didn't find a non-slash character. We know that
5407 * the length is non-zero, so the whole string must be
5408 * slashes. In either the dirname or the basename
5409 * case, we return '/'.
5411 ASSERT(firstbase == -1);
5412 firstbase = lastbase = lastdir = 0;
5415 if (firstbase == -1) {
5417 * The entire string consists only of a basename
5418 * component. If we're looking for dirname, we need
5419 * to change our string to be just "."; if we're
5420 * looking for a basename, we'll just set the first
5421 * character of the basename to be 0.
5423 if (subr == DIF_SUBR_DIRNAME) {
5424 ASSERT(lastdir == -1);
5425 src = (uintptr_t)".";
5432 if (subr == DIF_SUBR_DIRNAME) {
5433 if (lastdir == -1) {
5435 * We know that we have a slash in the name --
5436 * or lastdir would be set to 0, above. And
5437 * because lastdir is -1, we know that this
5438 * slash must be the first character. (That
5439 * is, the full string must be of the form
5440 * "/basename".) In this case, the last
5441 * character of the directory name is 0.
5449 ASSERT(subr == DIF_SUBR_BASENAME);
5450 ASSERT(firstbase != -1 && lastbase != -1);
5455 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5456 dest[j] = dtrace_load8(src + i);
5459 regs[rd] = (uintptr_t)dest;
5460 mstate->dtms_scratch_ptr += size;
5464 case DIF_SUBR_GETF: {
5465 uintptr_t fd = tupregs[0].dttk_value;
5466 struct filedesc *fdp;
5469 if (!dtrace_priv_proc(state)) {
5473 fdp = curproc->p_fd;
5474 FILEDESC_SLOCK(fdp);
5475 fp = fget_locked(fdp, fd);
5476 mstate->dtms_getf = fp;
5477 regs[rd] = (uintptr_t)fp;
5478 FILEDESC_SUNLOCK(fdp);
5482 case DIF_SUBR_CLEANPATH: {
5483 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5484 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5485 uintptr_t src = tupregs[0].dttk_value;
5491 if (!dtrace_strcanload(src, size, mstate, vstate)) {
5496 if (!DTRACE_INSCRATCH(mstate, size)) {
5497 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5503 * Move forward, loading each character.
5506 c = dtrace_load8(src + i++);
5508 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
5516 c = dtrace_load8(src + i++);
5520 * We have two slashes -- we can just advance
5521 * to the next character.
5528 * This is not "." and it's not ".." -- we can
5529 * just store the "/" and this character and
5537 c = dtrace_load8(src + i++);
5541 * This is a "/./" component. We're not going
5542 * to store anything in the destination buffer;
5543 * we're just going to go to the next component.
5550 * This is not ".." -- we can just store the
5551 * "/." and this character and continue
5560 c = dtrace_load8(src + i++);
5562 if (c != '/' && c != '\0') {
5564 * This is not ".." -- it's "..[mumble]".
5565 * We'll store the "/.." and this character
5566 * and continue processing.
5576 * This is "/../" or "/..\0". We need to back up
5577 * our destination pointer until we find a "/".
5580 while (j != 0 && dest[--j] != '/')
5585 } while (c != '\0');
5590 if (mstate->dtms_getf != NULL &&
5591 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5592 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5594 * If we've done a getf() as a part of this ECB and we
5595 * don't have kernel access (and we're not in the global
5596 * zone), check if the path we cleaned up begins with
5597 * the zone's root path, and trim it off if so. Note
5598 * that this is an output cleanliness issue, not a
5599 * security issue: knowing one's zone root path does
5600 * not enable privilege escalation.
5602 if (strstr(dest, z->zone_rootpath) == dest)
5603 dest += strlen(z->zone_rootpath) - 1;
5607 regs[rd] = (uintptr_t)dest;
5608 mstate->dtms_scratch_ptr += size;
5612 case DIF_SUBR_INET_NTOA:
5613 case DIF_SUBR_INET_NTOA6:
5614 case DIF_SUBR_INET_NTOP: {
5619 if (subr == DIF_SUBR_INET_NTOP) {
5620 af = (int)tupregs[0].dttk_value;
5623 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5627 if (af == AF_INET) {
5632 * Safely load the IPv4 address.
5634 ip4 = dtrace_load32(tupregs[argi].dttk_value);
5637 * Check an IPv4 string will fit in scratch.
5639 size = INET_ADDRSTRLEN;
5640 if (!DTRACE_INSCRATCH(mstate, size)) {
5641 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5645 base = (char *)mstate->dtms_scratch_ptr;
5646 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5649 * Stringify as a dotted decimal quad.
5652 ptr8 = (uint8_t *)&ip4;
5653 for (i = 3; i >= 0; i--) {
5659 for (; val; val /= 10) {
5660 *end-- = '0' + (val % 10);
5667 ASSERT(end + 1 >= base);
5669 } else if (af == AF_INET6) {
5670 struct in6_addr ip6;
5671 int firstzero, tryzero, numzero, v6end;
5673 const char digits[] = "0123456789abcdef";
5676 * Stringify using RFC 1884 convention 2 - 16 bit
5677 * hexadecimal values with a zero-run compression.
5678 * Lower case hexadecimal digits are used.
5679 * eg, fe80::214:4fff:fe0b:76c8.
5680 * The IPv4 embedded form is returned for inet_ntop,
5681 * just the IPv4 string is returned for inet_ntoa6.
5685 * Safely load the IPv6 address.
5688 (void *)(uintptr_t)tupregs[argi].dttk_value,
5689 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5692 * Check an IPv6 string will fit in scratch.
5694 size = INET6_ADDRSTRLEN;
5695 if (!DTRACE_INSCRATCH(mstate, size)) {
5696 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5700 base = (char *)mstate->dtms_scratch_ptr;
5701 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5705 * Find the longest run of 16 bit zero values
5706 * for the single allowed zero compression - "::".
5711 for (i = 0; i < sizeof (struct in6_addr); i++) {
5713 if (ip6._S6_un._S6_u8[i] == 0 &&
5715 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5717 tryzero == -1 && i % 2 == 0) {
5722 if (tryzero != -1 &&
5724 (ip6._S6_un._S6_u8[i] != 0 ||
5726 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5728 i == sizeof (struct in6_addr) - 1)) {
5730 if (i - tryzero <= numzero) {
5735 firstzero = tryzero;
5736 numzero = i - i % 2 - tryzero;
5740 if (ip6._S6_un._S6_u8[i] == 0 &&
5742 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5744 i == sizeof (struct in6_addr) - 1)
5748 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5751 * Check for an IPv4 embedded address.
5753 v6end = sizeof (struct in6_addr) - 2;
5754 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5755 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5756 for (i = sizeof (struct in6_addr) - 1;
5757 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5758 ASSERT(end >= base);
5761 val = ip6._S6_un._S6_u8[i];
5763 val = ip6.__u6_addr.__u6_addr8[i];
5769 for (; val; val /= 10) {
5770 *end-- = '0' + val % 10;
5774 if (i > DTRACE_V4MAPPED_OFFSET)
5778 if (subr == DIF_SUBR_INET_NTOA6)
5782 * Set v6end to skip the IPv4 address that
5783 * we have already stringified.
5789 * Build the IPv6 string by working through the
5790 * address in reverse.
5792 for (i = v6end; i >= 0; i -= 2) {
5793 ASSERT(end >= base);
5795 if (i == firstzero + numzero - 2) {
5802 if (i < 14 && i != firstzero - 2)
5806 val = (ip6._S6_un._S6_u8[i] << 8) +
5807 ip6._S6_un._S6_u8[i + 1];
5809 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5810 ip6.__u6_addr.__u6_addr8[i + 1];
5816 for (; val; val /= 16) {
5817 *end-- = digits[val % 16];
5821 ASSERT(end + 1 >= base);
5825 * The user didn't use AH_INET or AH_INET6.
5827 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5832 inetout: regs[rd] = (uintptr_t)end + 1;
5833 mstate->dtms_scratch_ptr += size;
5837 case DIF_SUBR_MEMREF: {
5838 uintptr_t size = 2 * sizeof(uintptr_t);
5839 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5840 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5842 /* address and length */
5843 memref[0] = tupregs[0].dttk_value;
5844 memref[1] = tupregs[1].dttk_value;
5846 regs[rd] = (uintptr_t) memref;
5847 mstate->dtms_scratch_ptr += scratch_size;
5852 case DIF_SUBR_MEMSTR: {
5853 char *str = (char *)mstate->dtms_scratch_ptr;
5854 uintptr_t mem = tupregs[0].dttk_value;
5855 char c = tupregs[1].dttk_value;
5856 size_t size = tupregs[2].dttk_value;
5865 if (!dtrace_canload(mem, size - 1, mstate, vstate))
5868 if (!DTRACE_INSCRATCH(mstate, size)) {
5869 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5873 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5874 *flags |= CPU_DTRACE_ILLOP;
5878 for (i = 0; i < size - 1; i++) {
5879 n = dtrace_load8(mem++);
5880 str[i] = (n == 0) ? c : n;
5884 regs[rd] = (uintptr_t)str;
5885 mstate->dtms_scratch_ptr += size;
5890 case DIF_SUBR_TYPEREF: {
5891 uintptr_t size = 4 * sizeof(uintptr_t);
5892 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5893 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5895 /* address, num_elements, type_str, type_len */
5896 typeref[0] = tupregs[0].dttk_value;
5897 typeref[1] = tupregs[1].dttk_value;
5898 typeref[2] = tupregs[2].dttk_value;
5899 typeref[3] = tupregs[3].dttk_value;
5901 regs[rd] = (uintptr_t) typeref;
5902 mstate->dtms_scratch_ptr += scratch_size;
5909 * Emulate the execution of DTrace IR instructions specified by the given
5910 * DIF object. This function is deliberately void of assertions as all of
5911 * the necessary checks are handled by a call to dtrace_difo_validate().
5914 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5915 dtrace_vstate_t *vstate, dtrace_state_t *state)
5917 const dif_instr_t *text = difo->dtdo_buf;
5918 const uint_t textlen = difo->dtdo_len;
5919 const char *strtab = difo->dtdo_strtab;
5920 const uint64_t *inttab = difo->dtdo_inttab;
5923 dtrace_statvar_t *svar;
5924 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5926 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5927 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5929 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5930 uint64_t regs[DIF_DIR_NREGS];
5933 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5935 uint_t pc = 0, id, opc = 0;
5941 * We stash the current DIF object into the machine state: we need it
5942 * for subsequent access checking.
5944 mstate->dtms_difo = difo;
5946 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5948 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5952 r1 = DIF_INSTR_R1(instr);
5953 r2 = DIF_INSTR_R2(instr);
5954 rd = DIF_INSTR_RD(instr);
5956 switch (DIF_INSTR_OP(instr)) {
5958 regs[rd] = regs[r1] | regs[r2];
5961 regs[rd] = regs[r1] ^ regs[r2];
5964 regs[rd] = regs[r1] & regs[r2];
5967 regs[rd] = regs[r1] << regs[r2];
5970 regs[rd] = regs[r1] >> regs[r2];
5973 regs[rd] = regs[r1] - regs[r2];
5976 regs[rd] = regs[r1] + regs[r2];
5979 regs[rd] = regs[r1] * regs[r2];
5982 if (regs[r2] == 0) {
5984 *flags |= CPU_DTRACE_DIVZERO;
5986 regs[rd] = (int64_t)regs[r1] /
5992 if (regs[r2] == 0) {
5994 *flags |= CPU_DTRACE_DIVZERO;
5996 regs[rd] = regs[r1] / regs[r2];
6001 if (regs[r2] == 0) {
6003 *flags |= CPU_DTRACE_DIVZERO;
6005 regs[rd] = (int64_t)regs[r1] %
6011 if (regs[r2] == 0) {
6013 *flags |= CPU_DTRACE_DIVZERO;
6015 regs[rd] = regs[r1] % regs[r2];
6020 regs[rd] = ~regs[r1];
6023 regs[rd] = regs[r1];
6026 cc_r = regs[r1] - regs[r2];
6030 cc_c = regs[r1] < regs[r2];
6033 cc_n = cc_v = cc_c = 0;
6034 cc_z = regs[r1] == 0;
6037 pc = DIF_INSTR_LABEL(instr);
6041 pc = DIF_INSTR_LABEL(instr);
6045 pc = DIF_INSTR_LABEL(instr);
6048 if ((cc_z | (cc_n ^ cc_v)) == 0)
6049 pc = DIF_INSTR_LABEL(instr);
6052 if ((cc_c | cc_z) == 0)
6053 pc = DIF_INSTR_LABEL(instr);
6056 if ((cc_n ^ cc_v) == 0)
6057 pc = DIF_INSTR_LABEL(instr);
6061 pc = DIF_INSTR_LABEL(instr);
6065 pc = DIF_INSTR_LABEL(instr);
6069 pc = DIF_INSTR_LABEL(instr);
6072 if (cc_z | (cc_n ^ cc_v))
6073 pc = DIF_INSTR_LABEL(instr);
6077 pc = DIF_INSTR_LABEL(instr);
6080 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6084 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6087 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6091 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6094 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6098 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6101 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6105 regs[rd] = dtrace_load8(regs[r1]);
6108 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6112 regs[rd] = dtrace_load16(regs[r1]);
6115 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6119 regs[rd] = dtrace_load32(regs[r1]);
6122 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6126 regs[rd] = dtrace_load64(regs[r1]);
6129 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6131 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6132 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6135 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6136 regs[rd] = (int16_t)
6137 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6138 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6141 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6142 regs[rd] = (int32_t)
6143 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6144 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6147 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6149 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6150 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6153 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6155 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6156 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6159 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6161 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6162 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6165 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6167 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6168 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6177 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6180 regs[rd] = (uint64_t)(uintptr_t)
6181 (strtab + DIF_INSTR_STRING(instr));
6184 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6185 uintptr_t s1 = regs[r1];
6186 uintptr_t s2 = regs[r2];
6189 !dtrace_strcanload(s1, sz, mstate, vstate))
6192 !dtrace_strcanload(s2, sz, mstate, vstate))
6195 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
6203 regs[rd] = dtrace_dif_variable(mstate, state,
6207 id = DIF_INSTR_VAR(instr);
6209 if (id >= DIF_VAR_OTHER_UBASE) {
6212 id -= DIF_VAR_OTHER_UBASE;
6213 svar = vstate->dtvs_globals[id];
6214 ASSERT(svar != NULL);
6215 v = &svar->dtsv_var;
6217 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6218 regs[rd] = svar->dtsv_data;
6222 a = (uintptr_t)svar->dtsv_data;
6224 if (*(uint8_t *)a == UINT8_MAX) {
6226 * If the 0th byte is set to UINT8_MAX
6227 * then this is to be treated as a
6228 * reference to a NULL variable.
6232 regs[rd] = a + sizeof (uint64_t);
6238 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6242 id = DIF_INSTR_VAR(instr);
6244 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6245 id -= DIF_VAR_OTHER_UBASE;
6247 svar = vstate->dtvs_globals[id];
6248 ASSERT(svar != NULL);
6249 v = &svar->dtsv_var;
6251 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6252 uintptr_t a = (uintptr_t)svar->dtsv_data;
6255 ASSERT(svar->dtsv_size != 0);
6257 if (regs[rd] == 0) {
6258 *(uint8_t *)a = UINT8_MAX;
6262 a += sizeof (uint64_t);
6264 if (!dtrace_vcanload(
6265 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6269 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6270 (void *)a, &v->dtdv_type);
6274 svar->dtsv_data = regs[rd];
6279 * There are no DTrace built-in thread-local arrays at
6280 * present. This opcode is saved for future work.
6282 *flags |= CPU_DTRACE_ILLOP;
6287 id = DIF_INSTR_VAR(instr);
6289 if (id < DIF_VAR_OTHER_UBASE) {
6291 * For now, this has no meaning.
6297 id -= DIF_VAR_OTHER_UBASE;
6299 ASSERT(id < vstate->dtvs_nlocals);
6300 ASSERT(vstate->dtvs_locals != NULL);
6302 svar = vstate->dtvs_locals[id];
6303 ASSERT(svar != NULL);
6304 v = &svar->dtsv_var;
6306 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6307 uintptr_t a = (uintptr_t)svar->dtsv_data;
6308 size_t sz = v->dtdv_type.dtdt_size;
6310 sz += sizeof (uint64_t);
6311 ASSERT(svar->dtsv_size == NCPU * sz);
6314 if (*(uint8_t *)a == UINT8_MAX) {
6316 * If the 0th byte is set to UINT8_MAX
6317 * then this is to be treated as a
6318 * reference to a NULL variable.
6322 regs[rd] = a + sizeof (uint64_t);
6328 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6329 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6330 regs[rd] = tmp[curcpu];
6334 id = DIF_INSTR_VAR(instr);
6336 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6337 id -= DIF_VAR_OTHER_UBASE;
6338 ASSERT(id < vstate->dtvs_nlocals);
6340 ASSERT(vstate->dtvs_locals != NULL);
6341 svar = vstate->dtvs_locals[id];
6342 ASSERT(svar != NULL);
6343 v = &svar->dtsv_var;
6345 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6346 uintptr_t a = (uintptr_t)svar->dtsv_data;
6347 size_t sz = v->dtdv_type.dtdt_size;
6349 sz += sizeof (uint64_t);
6350 ASSERT(svar->dtsv_size == NCPU * sz);
6353 if (regs[rd] == 0) {
6354 *(uint8_t *)a = UINT8_MAX;
6358 a += sizeof (uint64_t);
6361 if (!dtrace_vcanload(
6362 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6366 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6367 (void *)a, &v->dtdv_type);
6371 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6372 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6373 tmp[curcpu] = regs[rd];
6377 dtrace_dynvar_t *dvar;
6380 id = DIF_INSTR_VAR(instr);
6381 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6382 id -= DIF_VAR_OTHER_UBASE;
6383 v = &vstate->dtvs_tlocals[id];
6385 key = &tupregs[DIF_DTR_NREGS];
6386 key[0].dttk_value = (uint64_t)id;
6387 key[0].dttk_size = 0;
6388 DTRACE_TLS_THRKEY(key[1].dttk_value);
6389 key[1].dttk_size = 0;
6391 dvar = dtrace_dynvar(dstate, 2, key,
6392 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6400 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6401 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6403 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6410 dtrace_dynvar_t *dvar;
6413 id = DIF_INSTR_VAR(instr);
6414 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6415 id -= DIF_VAR_OTHER_UBASE;
6417 key = &tupregs[DIF_DTR_NREGS];
6418 key[0].dttk_value = (uint64_t)id;
6419 key[0].dttk_size = 0;
6420 DTRACE_TLS_THRKEY(key[1].dttk_value);
6421 key[1].dttk_size = 0;
6422 v = &vstate->dtvs_tlocals[id];
6424 dvar = dtrace_dynvar(dstate, 2, key,
6425 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6426 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6427 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6428 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6431 * Given that we're storing to thread-local data,
6432 * we need to flush our predicate cache.
6434 curthread->t_predcache = 0;
6439 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6440 if (!dtrace_vcanload(
6441 (void *)(uintptr_t)regs[rd],
6442 &v->dtdv_type, mstate, vstate))
6445 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6446 dvar->dtdv_data, &v->dtdv_type);
6448 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6455 regs[rd] = (int64_t)regs[r1] >> regs[r2];
6459 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6460 regs, tupregs, ttop, mstate, state);
6464 if (ttop == DIF_DTR_NREGS) {
6465 *flags |= CPU_DTRACE_TUPOFLOW;
6469 if (r1 == DIF_TYPE_STRING) {
6471 * If this is a string type and the size is 0,
6472 * we'll use the system-wide default string
6473 * size. Note that we are _not_ looking at
6474 * the value of the DTRACEOPT_STRSIZE option;
6475 * had this been set, we would expect to have
6476 * a non-zero size value in the "pushtr".
6478 tupregs[ttop].dttk_size =
6479 dtrace_strlen((char *)(uintptr_t)regs[rd],
6480 regs[r2] ? regs[r2] :
6481 dtrace_strsize_default) + 1;
6483 if (regs[r2] > LONG_MAX) {
6484 *flags |= CPU_DTRACE_ILLOP;
6488 tupregs[ttop].dttk_size = regs[r2];
6491 tupregs[ttop++].dttk_value = regs[rd];
6495 if (ttop == DIF_DTR_NREGS) {
6496 *flags |= CPU_DTRACE_TUPOFLOW;
6500 tupregs[ttop].dttk_value = regs[rd];
6501 tupregs[ttop++].dttk_size = 0;
6509 case DIF_OP_FLUSHTS:
6514 case DIF_OP_LDTAA: {
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_LDTAA) {
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 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6544 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6545 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6547 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6554 case DIF_OP_STTAA: {
6555 dtrace_dynvar_t *dvar;
6556 dtrace_key_t *key = tupregs;
6557 uint_t nkeys = ttop;
6559 id = DIF_INSTR_VAR(instr);
6560 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6561 id -= DIF_VAR_OTHER_UBASE;
6563 key[nkeys].dttk_value = (uint64_t)id;
6564 key[nkeys++].dttk_size = 0;
6566 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6567 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6568 key[nkeys++].dttk_size = 0;
6569 v = &vstate->dtvs_tlocals[id];
6571 v = &vstate->dtvs_globals[id]->dtsv_var;
6574 dvar = dtrace_dynvar(dstate, nkeys, key,
6575 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6576 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6577 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6578 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6583 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6584 if (!dtrace_vcanload(
6585 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6589 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6590 dvar->dtdv_data, &v->dtdv_type);
6592 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6598 case DIF_OP_ALLOCS: {
6599 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6600 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6603 * Rounding up the user allocation size could have
6604 * overflowed large, bogus allocations (like -1ULL) to
6607 if (size < regs[r1] ||
6608 !DTRACE_INSCRATCH(mstate, size)) {
6609 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6614 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6615 mstate->dtms_scratch_ptr += size;
6621 if (!dtrace_canstore(regs[rd], regs[r2],
6623 *flags |= CPU_DTRACE_BADADDR;
6628 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6631 dtrace_bcopy((void *)(uintptr_t)regs[r1],
6632 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6636 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6637 *flags |= CPU_DTRACE_BADADDR;
6641 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6645 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6646 *flags |= CPU_DTRACE_BADADDR;
6651 *flags |= CPU_DTRACE_BADALIGN;
6655 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6659 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6660 *flags |= CPU_DTRACE_BADADDR;
6665 *flags |= CPU_DTRACE_BADALIGN;
6669 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6673 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6674 *flags |= CPU_DTRACE_BADADDR;
6679 *flags |= CPU_DTRACE_BADALIGN;
6683 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6688 if (!(*flags & CPU_DTRACE_FAULT))
6691 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6692 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6698 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6700 dtrace_probe_t *probe = ecb->dte_probe;
6701 dtrace_provider_t *prov = probe->dtpr_provider;
6702 char c[DTRACE_FULLNAMELEN + 80], *str;
6703 char *msg = "dtrace: breakpoint action at probe ";
6704 char *ecbmsg = " (ecb ";
6705 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6706 uintptr_t val = (uintptr_t)ecb;
6707 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6709 if (dtrace_destructive_disallow)
6713 * It's impossible to be taking action on the NULL probe.
6715 ASSERT(probe != NULL);
6718 * This is a poor man's (destitute man's?) sprintf(): we want to
6719 * print the provider name, module name, function name and name of
6720 * the probe, along with the hex address of the ECB with the breakpoint
6721 * action -- all of which we must place in the character buffer by
6724 while (*msg != '\0')
6727 for (str = prov->dtpv_name; *str != '\0'; str++)
6731 for (str = probe->dtpr_mod; *str != '\0'; str++)
6735 for (str = probe->dtpr_func; *str != '\0'; str++)
6739 for (str = probe->dtpr_name; *str != '\0'; str++)
6742 while (*ecbmsg != '\0')
6745 while (shift >= 0) {
6746 mask = (uintptr_t)0xf << shift;
6748 if (val >= ((uintptr_t)1 << shift))
6749 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6759 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6764 dtrace_action_panic(dtrace_ecb_t *ecb)
6766 dtrace_probe_t *probe = ecb->dte_probe;
6769 * It's impossible to be taking action on the NULL probe.
6771 ASSERT(probe != NULL);
6773 if (dtrace_destructive_disallow)
6776 if (dtrace_panicked != NULL)
6779 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6783 * We won the right to panic. (We want to be sure that only one
6784 * thread calls panic() from dtrace_probe(), and that panic() is
6785 * called exactly once.)
6787 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6788 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6789 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6793 dtrace_action_raise(uint64_t sig)
6795 if (dtrace_destructive_disallow)
6799 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6805 * raise() has a queue depth of 1 -- we ignore all subsequent
6806 * invocations of the raise() action.
6808 if (curthread->t_dtrace_sig == 0)
6809 curthread->t_dtrace_sig = (uint8_t)sig;
6811 curthread->t_sig_check = 1;
6814 struct proc *p = curproc;
6816 kern_psignal(p, sig);
6822 dtrace_action_stop(void)
6824 if (dtrace_destructive_disallow)
6828 if (!curthread->t_dtrace_stop) {
6829 curthread->t_dtrace_stop = 1;
6830 curthread->t_sig_check = 1;
6834 struct proc *p = curproc;
6836 kern_psignal(p, SIGSTOP);
6842 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6845 volatile uint16_t *flags;
6849 cpu_t *cpu = &solaris_cpu[curcpu];
6852 if (dtrace_destructive_disallow)
6855 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
6857 now = dtrace_gethrtime();
6859 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6861 * We need to advance the mark to the current time.
6863 cpu->cpu_dtrace_chillmark = now;
6864 cpu->cpu_dtrace_chilled = 0;
6868 * Now check to see if the requested chill time would take us over
6869 * the maximum amount of time allowed in the chill interval. (Or
6870 * worse, if the calculation itself induces overflow.)
6872 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6873 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6874 *flags |= CPU_DTRACE_ILLOP;
6878 while (dtrace_gethrtime() - now < val)
6882 * Normally, we assure that the value of the variable "timestamp" does
6883 * not change within an ECB. The presence of chill() represents an
6884 * exception to this rule, however.
6886 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6887 cpu->cpu_dtrace_chilled += val;
6891 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6892 uint64_t *buf, uint64_t arg)
6894 int nframes = DTRACE_USTACK_NFRAMES(arg);
6895 int strsize = DTRACE_USTACK_STRSIZE(arg);
6896 uint64_t *pcs = &buf[1], *fps;
6897 char *str = (char *)&pcs[nframes];
6898 int size, offs = 0, i, j;
6899 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6900 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6904 * Should be taking a faster path if string space has not been
6907 ASSERT(strsize != 0);
6910 * We will first allocate some temporary space for the frame pointers.
6912 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6913 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6914 (nframes * sizeof (uint64_t));
6916 if (!DTRACE_INSCRATCH(mstate, size)) {
6918 * Not enough room for our frame pointers -- need to indicate
6919 * that we ran out of scratch space.
6921 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6925 mstate->dtms_scratch_ptr += size;
6926 saved = mstate->dtms_scratch_ptr;
6929 * Now get a stack with both program counters and frame pointers.
6931 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6932 dtrace_getufpstack(buf, fps, nframes + 1);
6933 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6936 * If that faulted, we're cooked.
6938 if (*flags & CPU_DTRACE_FAULT)
6942 * Now we want to walk up the stack, calling the USTACK helper. For
6943 * each iteration, we restore the scratch pointer.
6945 for (i = 0; i < nframes; i++) {
6946 mstate->dtms_scratch_ptr = saved;
6948 if (offs >= strsize)
6951 sym = (char *)(uintptr_t)dtrace_helper(
6952 DTRACE_HELPER_ACTION_USTACK,
6953 mstate, state, pcs[i], fps[i]);
6956 * If we faulted while running the helper, we're going to
6957 * clear the fault and null out the corresponding string.
6959 if (*flags & CPU_DTRACE_FAULT) {
6960 *flags &= ~CPU_DTRACE_FAULT;
6970 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6973 * Now copy in the string that the helper returned to us.
6975 for (j = 0; offs + j < strsize; j++) {
6976 if ((str[offs + j] = sym[j]) == '\0')
6980 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6985 if (offs >= strsize) {
6987 * If we didn't have room for all of the strings, we don't
6988 * abort processing -- this needn't be a fatal error -- but we
6989 * still want to increment a counter (dts_stkstroverflows) to
6990 * allow this condition to be warned about. (If this is from
6991 * a jstack() action, it is easily tuned via jstackstrsize.)
6993 dtrace_error(&state->dts_stkstroverflows);
6996 while (offs < strsize)
7000 mstate->dtms_scratch_ptr = old;
7004 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7005 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7007 volatile uint16_t *flags;
7008 uint64_t val = *valp;
7009 size_t valoffs = *valoffsp;
7011 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7012 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7015 * If this is a string, we're going to only load until we find the zero
7016 * byte -- after which we'll store zero bytes.
7018 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7022 for (s = 0; s < size; s++) {
7023 if (c != '\0' && dtkind == DIF_TF_BYREF) {
7024 c = dtrace_load8(val++);
7025 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7026 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7027 c = dtrace_fuword8((void *)(uintptr_t)val++);
7028 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7029 if (*flags & CPU_DTRACE_FAULT)
7033 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7035 if (c == '\0' && intuple)
7040 while (valoffs < end) {
7041 if (dtkind == DIF_TF_BYREF) {
7042 c = dtrace_load8(val++);
7043 } else if (dtkind == DIF_TF_BYUREF) {
7044 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7045 c = dtrace_fuword8((void *)(uintptr_t)val++);
7046 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7047 if (*flags & CPU_DTRACE_FAULT)
7051 DTRACE_STORE(uint8_t, tomax,
7057 *valoffsp = valoffs;
7061 * If you're looking for the epicenter of DTrace, you just found it. This
7062 * is the function called by the provider to fire a probe -- from which all
7063 * subsequent probe-context DTrace activity emanates.
7066 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7067 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7069 processorid_t cpuid;
7070 dtrace_icookie_t cookie;
7071 dtrace_probe_t *probe;
7072 dtrace_mstate_t mstate;
7074 dtrace_action_t *act;
7078 volatile uint16_t *flags;
7081 if (panicstr != NULL)
7086 * Kick out immediately if this CPU is still being born (in which case
7087 * curthread will be set to -1) or the current thread can't allow
7088 * probes in its current context.
7090 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7094 cookie = dtrace_interrupt_disable();
7095 probe = dtrace_probes[id - 1];
7097 onintr = CPU_ON_INTR(CPU);
7099 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7100 probe->dtpr_predcache == curthread->t_predcache) {
7102 * We have hit in the predicate cache; we know that
7103 * this predicate would evaluate to be false.
7105 dtrace_interrupt_enable(cookie);
7110 if (panic_quiesce) {
7112 if (panicstr != NULL) {
7115 * We don't trace anything if we're panicking.
7117 dtrace_interrupt_enable(cookie);
7121 now = mstate.dtms_timestamp = dtrace_gethrtime();
7122 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7123 vtime = dtrace_vtime_references != 0;
7125 if (vtime && curthread->t_dtrace_start)
7126 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7128 mstate.dtms_difo = NULL;
7129 mstate.dtms_probe = probe;
7130 mstate.dtms_strtok = 0;
7131 mstate.dtms_arg[0] = arg0;
7132 mstate.dtms_arg[1] = arg1;
7133 mstate.dtms_arg[2] = arg2;
7134 mstate.dtms_arg[3] = arg3;
7135 mstate.dtms_arg[4] = arg4;
7137 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7139 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7140 dtrace_predicate_t *pred = ecb->dte_predicate;
7141 dtrace_state_t *state = ecb->dte_state;
7142 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7143 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7144 dtrace_vstate_t *vstate = &state->dts_vstate;
7145 dtrace_provider_t *prov = probe->dtpr_provider;
7146 uint64_t tracememsize = 0;
7151 * A little subtlety with the following (seemingly innocuous)
7152 * declaration of the automatic 'val': by looking at the
7153 * code, you might think that it could be declared in the
7154 * action processing loop, below. (That is, it's only used in
7155 * the action processing loop.) However, it must be declared
7156 * out of that scope because in the case of DIF expression
7157 * arguments to aggregating actions, one iteration of the
7158 * action loop will use the last iteration's value.
7162 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7163 mstate.dtms_getf = NULL;
7165 *flags &= ~CPU_DTRACE_ERROR;
7167 if (prov == dtrace_provider) {
7169 * If dtrace itself is the provider of this probe,
7170 * we're only going to continue processing the ECB if
7171 * arg0 (the dtrace_state_t) is equal to the ECB's
7172 * creating state. (This prevents disjoint consumers
7173 * from seeing one another's metaprobes.)
7175 if (arg0 != (uint64_t)(uintptr_t)state)
7179 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7181 * We're not currently active. If our provider isn't
7182 * the dtrace pseudo provider, we're not interested.
7184 if (prov != dtrace_provider)
7188 * Now we must further check if we are in the BEGIN
7189 * probe. If we are, we will only continue processing
7190 * if we're still in WARMUP -- if one BEGIN enabling
7191 * has invoked the exit() action, we don't want to
7192 * evaluate subsequent BEGIN enablings.
7194 if (probe->dtpr_id == dtrace_probeid_begin &&
7195 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7196 ASSERT(state->dts_activity ==
7197 DTRACE_ACTIVITY_DRAINING);
7202 if (ecb->dte_cond) {
7204 * If the dte_cond bits indicate that this
7205 * consumer is only allowed to see user-mode firings
7206 * of this probe, call the provider's dtps_usermode()
7207 * entry point to check that the probe was fired
7208 * while in a user context. Skip this ECB if that's
7211 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7212 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7213 probe->dtpr_id, probe->dtpr_arg) == 0)
7218 * This is more subtle than it looks. We have to be
7219 * absolutely certain that CRED() isn't going to
7220 * change out from under us so it's only legit to
7221 * examine that structure if we're in constrained
7222 * situations. Currently, the only times we'll this
7223 * check is if a non-super-user has enabled the
7224 * profile or syscall providers -- providers that
7225 * allow visibility of all processes. For the
7226 * profile case, the check above will ensure that
7227 * we're examining a user context.
7229 if (ecb->dte_cond & DTRACE_COND_OWNER) {
7232 ecb->dte_state->dts_cred.dcr_cred;
7235 ASSERT(s_cr != NULL);
7237 if ((cr = CRED()) == NULL ||
7238 s_cr->cr_uid != cr->cr_uid ||
7239 s_cr->cr_uid != cr->cr_ruid ||
7240 s_cr->cr_uid != cr->cr_suid ||
7241 s_cr->cr_gid != cr->cr_gid ||
7242 s_cr->cr_gid != cr->cr_rgid ||
7243 s_cr->cr_gid != cr->cr_sgid ||
7244 (proc = ttoproc(curthread)) == NULL ||
7245 (proc->p_flag & SNOCD))
7249 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7252 ecb->dte_state->dts_cred.dcr_cred;
7254 ASSERT(s_cr != NULL);
7256 if ((cr = CRED()) == NULL ||
7257 s_cr->cr_zone->zone_id !=
7258 cr->cr_zone->zone_id)
7264 if (now - state->dts_alive > dtrace_deadman_timeout) {
7266 * We seem to be dead. Unless we (a) have kernel
7267 * destructive permissions (b) have explicitly enabled
7268 * destructive actions and (c) destructive actions have
7269 * not been disabled, we're going to transition into
7270 * the KILLED state, from which no further processing
7271 * on this state will be performed.
7273 if (!dtrace_priv_kernel_destructive(state) ||
7274 !state->dts_cred.dcr_destructive ||
7275 dtrace_destructive_disallow) {
7276 void *activity = &state->dts_activity;
7277 dtrace_activity_t current;
7280 current = state->dts_activity;
7281 } while (dtrace_cas32(activity, current,
7282 DTRACE_ACTIVITY_KILLED) != current);
7288 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7289 ecb->dte_alignment, state, &mstate)) < 0)
7292 tomax = buf->dtb_tomax;
7293 ASSERT(tomax != NULL);
7295 if (ecb->dte_size != 0) {
7296 dtrace_rechdr_t dtrh;
7297 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7298 mstate.dtms_timestamp = dtrace_gethrtime();
7299 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7301 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7302 dtrh.dtrh_epid = ecb->dte_epid;
7303 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7304 mstate.dtms_timestamp);
7305 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7308 mstate.dtms_epid = ecb->dte_epid;
7309 mstate.dtms_present |= DTRACE_MSTATE_EPID;
7311 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7312 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7314 mstate.dtms_access = 0;
7317 dtrace_difo_t *dp = pred->dtp_difo;
7320 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7322 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7323 dtrace_cacheid_t cid = probe->dtpr_predcache;
7325 if (cid != DTRACE_CACHEIDNONE && !onintr) {
7327 * Update the predicate cache...
7329 ASSERT(cid == pred->dtp_cacheid);
7330 curthread->t_predcache = cid;
7337 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7338 act != NULL; act = act->dta_next) {
7341 dtrace_recdesc_t *rec = &act->dta_rec;
7343 size = rec->dtrd_size;
7344 valoffs = offs + rec->dtrd_offset;
7346 if (DTRACEACT_ISAGG(act->dta_kind)) {
7348 dtrace_aggregation_t *agg;
7350 agg = (dtrace_aggregation_t *)act;
7352 if ((dp = act->dta_difo) != NULL)
7353 v = dtrace_dif_emulate(dp,
7354 &mstate, vstate, state);
7356 if (*flags & CPU_DTRACE_ERROR)
7360 * Note that we always pass the expression
7361 * value from the previous iteration of the
7362 * action loop. This value will only be used
7363 * if there is an expression argument to the
7364 * aggregating action, denoted by the
7365 * dtag_hasarg field.
7367 dtrace_aggregate(agg, buf,
7368 offs, aggbuf, v, val);
7372 switch (act->dta_kind) {
7373 case DTRACEACT_STOP:
7374 if (dtrace_priv_proc_destructive(state))
7375 dtrace_action_stop();
7378 case DTRACEACT_BREAKPOINT:
7379 if (dtrace_priv_kernel_destructive(state))
7380 dtrace_action_breakpoint(ecb);
7383 case DTRACEACT_PANIC:
7384 if (dtrace_priv_kernel_destructive(state))
7385 dtrace_action_panic(ecb);
7388 case DTRACEACT_STACK:
7389 if (!dtrace_priv_kernel(state))
7392 dtrace_getpcstack((pc_t *)(tomax + valoffs),
7393 size / sizeof (pc_t), probe->dtpr_aframes,
7394 DTRACE_ANCHORED(probe) ? NULL :
7398 case DTRACEACT_JSTACK:
7399 case DTRACEACT_USTACK:
7400 if (!dtrace_priv_proc(state))
7404 * See comment in DIF_VAR_PID.
7406 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7408 int depth = DTRACE_USTACK_NFRAMES(
7411 dtrace_bzero((void *)(tomax + valoffs),
7412 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7413 + depth * sizeof (uint64_t));
7418 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7419 curproc->p_dtrace_helpers != NULL) {
7421 * This is the slow path -- we have
7422 * allocated string space, and we're
7423 * getting the stack of a process that
7424 * has helpers. Call into a separate
7425 * routine to perform this processing.
7427 dtrace_action_ustack(&mstate, state,
7428 (uint64_t *)(tomax + valoffs),
7433 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7434 dtrace_getupcstack((uint64_t *)
7436 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7437 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7447 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7449 if (*flags & CPU_DTRACE_ERROR)
7452 switch (act->dta_kind) {
7453 case DTRACEACT_SPECULATE: {
7454 dtrace_rechdr_t *dtrh;
7456 ASSERT(buf == &state->dts_buffer[cpuid]);
7457 buf = dtrace_speculation_buffer(state,
7461 *flags |= CPU_DTRACE_DROP;
7465 offs = dtrace_buffer_reserve(buf,
7466 ecb->dte_needed, ecb->dte_alignment,
7470 *flags |= CPU_DTRACE_DROP;
7474 tomax = buf->dtb_tomax;
7475 ASSERT(tomax != NULL);
7477 if (ecb->dte_size == 0)
7480 ASSERT3U(ecb->dte_size, >=,
7481 sizeof (dtrace_rechdr_t));
7482 dtrh = ((void *)(tomax + offs));
7483 dtrh->dtrh_epid = ecb->dte_epid;
7485 * When the speculation is committed, all of
7486 * the records in the speculative buffer will
7487 * have their timestamps set to the commit
7488 * time. Until then, it is set to a sentinel
7489 * value, for debugability.
7491 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7495 case DTRACEACT_PRINTM: {
7496 /* The DIF returns a 'memref'. */
7497 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7499 /* Get the size from the memref. */
7503 * Check if the size exceeds the allocated
7506 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7508 *flags |= CPU_DTRACE_DROP;
7512 /* Store the size in the buffer first. */
7513 DTRACE_STORE(uintptr_t, tomax,
7517 * Offset the buffer address to the start
7520 valoffs += sizeof(uintptr_t);
7523 * Reset to the memory address rather than
7524 * the memref array, then let the BYREF
7525 * code below do the work to store the
7526 * memory data in the buffer.
7532 case DTRACEACT_PRINTT: {
7533 /* The DIF returns a 'typeref'. */
7534 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
7539 * Get the type string length and round it
7540 * up so that the data that follows is
7541 * aligned for easy access.
7543 size_t typs = strlen((char *) typeref[2]) + 1;
7544 typs = roundup(typs, sizeof(uintptr_t));
7547 *Get the size from the typeref using the
7548 * number of elements and the type size.
7550 size = typeref[1] * typeref[3];
7553 * Check if the size exceeds the allocated
7556 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7558 *flags |= CPU_DTRACE_DROP;
7562 /* Store the size in the buffer first. */
7563 DTRACE_STORE(uintptr_t, tomax,
7565 valoffs += sizeof(uintptr_t);
7567 /* Store the type size in the buffer. */
7568 DTRACE_STORE(uintptr_t, tomax,
7569 valoffs, typeref[3]);
7570 valoffs += sizeof(uintptr_t);
7574 for (s = 0; s < typs; s++) {
7576 c = dtrace_load8(val++);
7578 DTRACE_STORE(uint8_t, tomax,
7583 * Reset to the memory address rather than
7584 * the typeref array, then let the BYREF
7585 * code below do the work to store the
7586 * memory data in the buffer.
7592 case DTRACEACT_CHILL:
7593 if (dtrace_priv_kernel_destructive(state))
7594 dtrace_action_chill(&mstate, val);
7597 case DTRACEACT_RAISE:
7598 if (dtrace_priv_proc_destructive(state))
7599 dtrace_action_raise(val);
7602 case DTRACEACT_COMMIT:
7606 * We need to commit our buffer state.
7609 buf->dtb_offset = offs + ecb->dte_size;
7610 buf = &state->dts_buffer[cpuid];
7611 dtrace_speculation_commit(state, cpuid, val);
7615 case DTRACEACT_DISCARD:
7616 dtrace_speculation_discard(state, cpuid, val);
7619 case DTRACEACT_DIFEXPR:
7620 case DTRACEACT_LIBACT:
7621 case DTRACEACT_PRINTF:
7622 case DTRACEACT_PRINTA:
7623 case DTRACEACT_SYSTEM:
7624 case DTRACEACT_FREOPEN:
7625 case DTRACEACT_TRACEMEM:
7628 case DTRACEACT_TRACEMEM_DYNSIZE:
7634 if (!dtrace_priv_kernel(state))
7638 case DTRACEACT_USYM:
7639 case DTRACEACT_UMOD:
7640 case DTRACEACT_UADDR: {
7642 struct pid *pid = curthread->t_procp->p_pidp;
7645 if (!dtrace_priv_proc(state))
7648 DTRACE_STORE(uint64_t, tomax,
7650 valoffs, (uint64_t)pid->pid_id);
7652 valoffs, (uint64_t) curproc->p_pid);
7654 DTRACE_STORE(uint64_t, tomax,
7655 valoffs + sizeof (uint64_t), val);
7660 case DTRACEACT_EXIT: {
7662 * For the exit action, we are going to attempt
7663 * to atomically set our activity to be
7664 * draining. If this fails (either because
7665 * another CPU has beat us to the exit action,
7666 * or because our current activity is something
7667 * other than ACTIVE or WARMUP), we will
7668 * continue. This assures that the exit action
7669 * can be successfully recorded at most once
7670 * when we're in the ACTIVE state. If we're
7671 * encountering the exit() action while in
7672 * COOLDOWN, however, we want to honor the new
7673 * status code. (We know that we're the only
7674 * thread in COOLDOWN, so there is no race.)
7676 void *activity = &state->dts_activity;
7677 dtrace_activity_t current = state->dts_activity;
7679 if (current == DTRACE_ACTIVITY_COOLDOWN)
7682 if (current != DTRACE_ACTIVITY_WARMUP)
7683 current = DTRACE_ACTIVITY_ACTIVE;
7685 if (dtrace_cas32(activity, current,
7686 DTRACE_ACTIVITY_DRAINING) != current) {
7687 *flags |= CPU_DTRACE_DROP;
7698 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7699 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7700 uintptr_t end = valoffs + size;
7702 if (tracememsize != 0 &&
7703 valoffs + tracememsize < end) {
7704 end = valoffs + tracememsize;
7708 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7709 !dtrace_vcanload((void *)(uintptr_t)val,
7710 &dp->dtdo_rtype, &mstate, vstate))
7713 dtrace_store_by_ref(dp, tomax, size, &valoffs,
7714 &val, end, act->dta_intuple,
7715 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7716 DIF_TF_BYREF: DIF_TF_BYUREF);
7724 case sizeof (uint8_t):
7725 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7727 case sizeof (uint16_t):
7728 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7730 case sizeof (uint32_t):
7731 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7733 case sizeof (uint64_t):
7734 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7738 * Any other size should have been returned by
7739 * reference, not by value.
7746 if (*flags & CPU_DTRACE_DROP)
7749 if (*flags & CPU_DTRACE_FAULT) {
7751 dtrace_action_t *err;
7755 if (probe->dtpr_id == dtrace_probeid_error) {
7757 * There's nothing we can do -- we had an
7758 * error on the error probe. We bump an
7759 * error counter to at least indicate that
7760 * this condition happened.
7762 dtrace_error(&state->dts_dblerrors);
7768 * Before recursing on dtrace_probe(), we
7769 * need to explicitly clear out our start
7770 * time to prevent it from being accumulated
7771 * into t_dtrace_vtime.
7773 curthread->t_dtrace_start = 0;
7777 * Iterate over the actions to figure out which action
7778 * we were processing when we experienced the error.
7779 * Note that act points _past_ the faulting action; if
7780 * act is ecb->dte_action, the fault was in the
7781 * predicate, if it's ecb->dte_action->dta_next it's
7782 * in action #1, and so on.
7784 for (err = ecb->dte_action, ndx = 0;
7785 err != act; err = err->dta_next, ndx++)
7788 dtrace_probe_error(state, ecb->dte_epid, ndx,
7789 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7790 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7791 cpu_core[cpuid].cpuc_dtrace_illval);
7797 buf->dtb_offset = offs + ecb->dte_size;
7801 curthread->t_dtrace_start = dtrace_gethrtime();
7803 dtrace_interrupt_enable(cookie);
7807 * DTrace Probe Hashing Functions
7809 * The functions in this section (and indeed, the functions in remaining
7810 * sections) are not _called_ from probe context. (Any exceptions to this are
7811 * marked with a "Note:".) Rather, they are called from elsewhere in the
7812 * DTrace framework to look-up probes in, add probes to and remove probes from
7813 * the DTrace probe hashes. (Each probe is hashed by each element of the
7814 * probe tuple -- allowing for fast lookups, regardless of what was
7818 dtrace_hash_str(const char *p)
7824 hval = (hval << 4) + *p++;
7825 if ((g = (hval & 0xf0000000)) != 0)
7832 static dtrace_hash_t *
7833 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7835 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7837 hash->dth_stroffs = stroffs;
7838 hash->dth_nextoffs = nextoffs;
7839 hash->dth_prevoffs = prevoffs;
7842 hash->dth_mask = hash->dth_size - 1;
7844 hash->dth_tab = kmem_zalloc(hash->dth_size *
7845 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7851 dtrace_hash_destroy(dtrace_hash_t *hash)
7856 for (i = 0; i < hash->dth_size; i++)
7857 ASSERT(hash->dth_tab[i] == NULL);
7860 kmem_free(hash->dth_tab,
7861 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7862 kmem_free(hash, sizeof (dtrace_hash_t));
7866 dtrace_hash_resize(dtrace_hash_t *hash)
7868 int size = hash->dth_size, i, ndx;
7869 int new_size = hash->dth_size << 1;
7870 int new_mask = new_size - 1;
7871 dtrace_hashbucket_t **new_tab, *bucket, *next;
7873 ASSERT((new_size & new_mask) == 0);
7875 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7877 for (i = 0; i < size; i++) {
7878 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7879 dtrace_probe_t *probe = bucket->dthb_chain;
7881 ASSERT(probe != NULL);
7882 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7884 next = bucket->dthb_next;
7885 bucket->dthb_next = new_tab[ndx];
7886 new_tab[ndx] = bucket;
7890 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7891 hash->dth_tab = new_tab;
7892 hash->dth_size = new_size;
7893 hash->dth_mask = new_mask;
7897 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7899 int hashval = DTRACE_HASHSTR(hash, new);
7900 int ndx = hashval & hash->dth_mask;
7901 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7902 dtrace_probe_t **nextp, **prevp;
7904 for (; bucket != NULL; bucket = bucket->dthb_next) {
7905 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7909 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7910 dtrace_hash_resize(hash);
7911 dtrace_hash_add(hash, new);
7915 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7916 bucket->dthb_next = hash->dth_tab[ndx];
7917 hash->dth_tab[ndx] = bucket;
7918 hash->dth_nbuckets++;
7921 nextp = DTRACE_HASHNEXT(hash, new);
7922 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7923 *nextp = bucket->dthb_chain;
7925 if (bucket->dthb_chain != NULL) {
7926 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7927 ASSERT(*prevp == NULL);
7931 bucket->dthb_chain = new;
7935 static dtrace_probe_t *
7936 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7938 int hashval = DTRACE_HASHSTR(hash, template);
7939 int ndx = hashval & hash->dth_mask;
7940 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7942 for (; bucket != NULL; bucket = bucket->dthb_next) {
7943 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7944 return (bucket->dthb_chain);
7951 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7953 int hashval = DTRACE_HASHSTR(hash, template);
7954 int ndx = hashval & hash->dth_mask;
7955 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7957 for (; bucket != NULL; bucket = bucket->dthb_next) {
7958 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7959 return (bucket->dthb_len);
7966 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7968 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7969 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7971 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7972 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7975 * Find the bucket that we're removing this probe from.
7977 for (; bucket != NULL; bucket = bucket->dthb_next) {
7978 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7982 ASSERT(bucket != NULL);
7984 if (*prevp == NULL) {
7985 if (*nextp == NULL) {
7987 * The removed probe was the only probe on this
7988 * bucket; we need to remove the bucket.
7990 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7992 ASSERT(bucket->dthb_chain == probe);
7996 hash->dth_tab[ndx] = bucket->dthb_next;
7998 while (b->dthb_next != bucket)
8000 b->dthb_next = bucket->dthb_next;
8003 ASSERT(hash->dth_nbuckets > 0);
8004 hash->dth_nbuckets--;
8005 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8009 bucket->dthb_chain = *nextp;
8011 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8015 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8019 * DTrace Utility Functions
8021 * These are random utility functions that are _not_ called from probe context.
8024 dtrace_badattr(const dtrace_attribute_t *a)
8026 return (a->dtat_name > DTRACE_STABILITY_MAX ||
8027 a->dtat_data > DTRACE_STABILITY_MAX ||
8028 a->dtat_class > DTRACE_CLASS_MAX);
8032 * Return a duplicate copy of a string. If the specified string is NULL,
8033 * this function returns a zero-length string.
8036 dtrace_strdup(const char *str)
8038 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8041 (void) strcpy(new, str);
8046 #define DTRACE_ISALPHA(c) \
8047 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8050 dtrace_badname(const char *s)
8054 if (s == NULL || (c = *s++) == '\0')
8057 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8060 while ((c = *s++) != '\0') {
8061 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8062 c != '-' && c != '_' && c != '.' && c != '`')
8070 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8075 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8077 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8079 priv = DTRACE_PRIV_ALL;
8081 *uidp = crgetuid(cr);
8082 *zoneidp = crgetzoneid(cr);
8085 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8086 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8087 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8088 priv |= DTRACE_PRIV_USER;
8089 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8090 priv |= DTRACE_PRIV_PROC;
8091 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8092 priv |= DTRACE_PRIV_OWNER;
8093 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8094 priv |= DTRACE_PRIV_ZONEOWNER;
8097 priv = DTRACE_PRIV_ALL;
8103 #ifdef DTRACE_ERRDEBUG
8105 dtrace_errdebug(const char *str)
8107 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8110 mutex_enter(&dtrace_errlock);
8111 dtrace_errlast = str;
8112 dtrace_errthread = curthread;
8114 while (occupied++ < DTRACE_ERRHASHSZ) {
8115 if (dtrace_errhash[hval].dter_msg == str) {
8116 dtrace_errhash[hval].dter_count++;
8120 if (dtrace_errhash[hval].dter_msg != NULL) {
8121 hval = (hval + 1) % DTRACE_ERRHASHSZ;
8125 dtrace_errhash[hval].dter_msg = str;
8126 dtrace_errhash[hval].dter_count = 1;
8130 panic("dtrace: undersized error hash");
8132 mutex_exit(&dtrace_errlock);
8137 * DTrace Matching Functions
8139 * These functions are used to match groups of probes, given some elements of
8140 * a probe tuple, or some globbed expressions for elements of a probe tuple.
8143 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8146 if (priv != DTRACE_PRIV_ALL) {
8147 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8148 uint32_t match = priv & ppriv;
8151 * No PRIV_DTRACE_* privileges...
8153 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8154 DTRACE_PRIV_KERNEL)) == 0)
8158 * No matching bits, but there were bits to match...
8160 if (match == 0 && ppriv != 0)
8164 * Need to have permissions to the process, but don't...
8166 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8167 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8172 * Need to be in the same zone unless we possess the
8173 * privilege to examine all zones.
8175 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8176 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8185 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8186 * consists of input pattern strings and an ops-vector to evaluate them.
8187 * This function returns >0 for match, 0 for no match, and <0 for error.
8190 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8191 uint32_t priv, uid_t uid, zoneid_t zoneid)
8193 dtrace_provider_t *pvp = prp->dtpr_provider;
8196 if (pvp->dtpv_defunct)
8199 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8202 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8205 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8208 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8211 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8218 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8219 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
8220 * libc's version, the kernel version only applies to 8-bit ASCII strings.
8221 * In addition, all of the recursion cases except for '*' matching have been
8222 * unwound. For '*', we still implement recursive evaluation, but a depth
8223 * counter is maintained and matching is aborted if we recurse too deep.
8224 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8227 dtrace_match_glob(const char *s, const char *p, int depth)
8233 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8237 s = ""; /* treat NULL as empty string */
8246 if ((c = *p++) == '\0')
8247 return (s1 == '\0');
8251 int ok = 0, notflag = 0;
8262 if ((c = *p++) == '\0')
8266 if (c == '-' && lc != '\0' && *p != ']') {
8267 if ((c = *p++) == '\0')
8269 if (c == '\\' && (c = *p++) == '\0')
8273 if (s1 < lc || s1 > c)
8277 } else if (lc <= s1 && s1 <= c)
8280 } else if (c == '\\' && (c = *p++) == '\0')
8283 lc = c; /* save left-hand 'c' for next iteration */
8293 if ((c = *p++) == '\0')
8305 if ((c = *p++) == '\0')
8321 p++; /* consecutive *'s are identical to a single one */
8326 for (s = olds; *s != '\0'; s++) {
8327 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8337 dtrace_match_string(const char *s, const char *p, int depth)
8339 return (s != NULL && strcmp(s, p) == 0);
8344 dtrace_match_nul(const char *s, const char *p, int depth)
8346 return (1); /* always match the empty pattern */
8351 dtrace_match_nonzero(const char *s, const char *p, int depth)
8353 return (s != NULL && s[0] != '\0');
8357 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8358 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8360 dtrace_probe_t template, *probe;
8361 dtrace_hash_t *hash = NULL;
8362 int len, best = INT_MAX, nmatched = 0;
8365 ASSERT(MUTEX_HELD(&dtrace_lock));
8368 * If the probe ID is specified in the key, just lookup by ID and
8369 * invoke the match callback once if a matching probe is found.
8371 if (pkp->dtpk_id != DTRACE_IDNONE) {
8372 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8373 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8374 (void) (*matched)(probe, arg);
8380 template.dtpr_mod = (char *)pkp->dtpk_mod;
8381 template.dtpr_func = (char *)pkp->dtpk_func;
8382 template.dtpr_name = (char *)pkp->dtpk_name;
8385 * We want to find the most distinct of the module name, function
8386 * name, and name. So for each one that is not a glob pattern or
8387 * empty string, we perform a lookup in the corresponding hash and
8388 * use the hash table with the fewest collisions to do our search.
8390 if (pkp->dtpk_mmatch == &dtrace_match_string &&
8391 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8393 hash = dtrace_bymod;
8396 if (pkp->dtpk_fmatch == &dtrace_match_string &&
8397 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8399 hash = dtrace_byfunc;
8402 if (pkp->dtpk_nmatch == &dtrace_match_string &&
8403 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8405 hash = dtrace_byname;
8409 * If we did not select a hash table, iterate over every probe and
8410 * invoke our callback for each one that matches our input probe key.
8413 for (i = 0; i < dtrace_nprobes; i++) {
8414 if ((probe = dtrace_probes[i]) == NULL ||
8415 dtrace_match_probe(probe, pkp, priv, uid,
8421 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8429 * If we selected a hash table, iterate over each probe of the same key
8430 * name and invoke the callback for every probe that matches the other
8431 * attributes of our input probe key.
8433 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8434 probe = *(DTRACE_HASHNEXT(hash, probe))) {
8436 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8441 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8449 * Return the function pointer dtrace_probecmp() should use to compare the
8450 * specified pattern with a string. For NULL or empty patterns, we select
8451 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
8452 * For non-empty non-glob strings, we use dtrace_match_string().
8454 static dtrace_probekey_f *
8455 dtrace_probekey_func(const char *p)
8459 if (p == NULL || *p == '\0')
8460 return (&dtrace_match_nul);
8462 while ((c = *p++) != '\0') {
8463 if (c == '[' || c == '?' || c == '*' || c == '\\')
8464 return (&dtrace_match_glob);
8467 return (&dtrace_match_string);
8471 * Build a probe comparison key for use with dtrace_match_probe() from the
8472 * given probe description. By convention, a null key only matches anchored
8473 * probes: if each field is the empty string, reset dtpk_fmatch to
8474 * dtrace_match_nonzero().
8477 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8479 pkp->dtpk_prov = pdp->dtpd_provider;
8480 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8482 pkp->dtpk_mod = pdp->dtpd_mod;
8483 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8485 pkp->dtpk_func = pdp->dtpd_func;
8486 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8488 pkp->dtpk_name = pdp->dtpd_name;
8489 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8491 pkp->dtpk_id = pdp->dtpd_id;
8493 if (pkp->dtpk_id == DTRACE_IDNONE &&
8494 pkp->dtpk_pmatch == &dtrace_match_nul &&
8495 pkp->dtpk_mmatch == &dtrace_match_nul &&
8496 pkp->dtpk_fmatch == &dtrace_match_nul &&
8497 pkp->dtpk_nmatch == &dtrace_match_nul)
8498 pkp->dtpk_fmatch = &dtrace_match_nonzero;
8502 * DTrace Provider-to-Framework API Functions
8504 * These functions implement much of the Provider-to-Framework API, as
8505 * described in <sys/dtrace.h>. The parts of the API not in this section are
8506 * the functions in the API for probe management (found below), and
8507 * dtrace_probe() itself (found above).
8511 * Register the calling provider with the DTrace framework. This should
8512 * generally be called by DTrace providers in their attach(9E) entry point.
8515 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8516 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8518 dtrace_provider_t *provider;
8520 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8521 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8522 "arguments", name ? name : "<NULL>");
8526 if (name[0] == '\0' || dtrace_badname(name)) {
8527 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8528 "provider name", name);
8532 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8533 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8534 pops->dtps_destroy == NULL ||
8535 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8536 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8537 "provider ops", name);
8541 if (dtrace_badattr(&pap->dtpa_provider) ||
8542 dtrace_badattr(&pap->dtpa_mod) ||
8543 dtrace_badattr(&pap->dtpa_func) ||
8544 dtrace_badattr(&pap->dtpa_name) ||
8545 dtrace_badattr(&pap->dtpa_args)) {
8546 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8547 "provider attributes", name);
8551 if (priv & ~DTRACE_PRIV_ALL) {
8552 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8553 "privilege attributes", name);
8557 if ((priv & DTRACE_PRIV_KERNEL) &&
8558 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8559 pops->dtps_usermode == NULL) {
8560 cmn_err(CE_WARN, "failed to register provider '%s': need "
8561 "dtps_usermode() op for given privilege attributes", name);
8565 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8566 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8567 (void) strcpy(provider->dtpv_name, name);
8569 provider->dtpv_attr = *pap;
8570 provider->dtpv_priv.dtpp_flags = priv;
8572 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8573 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8575 provider->dtpv_pops = *pops;
8577 if (pops->dtps_provide == NULL) {
8578 ASSERT(pops->dtps_provide_module != NULL);
8579 provider->dtpv_pops.dtps_provide =
8580 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8583 if (pops->dtps_provide_module == NULL) {
8584 ASSERT(pops->dtps_provide != NULL);
8585 provider->dtpv_pops.dtps_provide_module =
8586 (void (*)(void *, modctl_t *))dtrace_nullop;
8589 if (pops->dtps_suspend == NULL) {
8590 ASSERT(pops->dtps_resume == NULL);
8591 provider->dtpv_pops.dtps_suspend =
8592 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8593 provider->dtpv_pops.dtps_resume =
8594 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8597 provider->dtpv_arg = arg;
8598 *idp = (dtrace_provider_id_t)provider;
8600 if (pops == &dtrace_provider_ops) {
8601 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8602 ASSERT(MUTEX_HELD(&dtrace_lock));
8603 ASSERT(dtrace_anon.dta_enabling == NULL);
8606 * We make sure that the DTrace provider is at the head of
8607 * the provider chain.
8609 provider->dtpv_next = dtrace_provider;
8610 dtrace_provider = provider;
8614 mutex_enter(&dtrace_provider_lock);
8615 mutex_enter(&dtrace_lock);
8618 * If there is at least one provider registered, we'll add this
8619 * provider after the first provider.
8621 if (dtrace_provider != NULL) {
8622 provider->dtpv_next = dtrace_provider->dtpv_next;
8623 dtrace_provider->dtpv_next = provider;
8625 dtrace_provider = provider;
8628 if (dtrace_retained != NULL) {
8629 dtrace_enabling_provide(provider);
8632 * Now we need to call dtrace_enabling_matchall() -- which
8633 * will acquire cpu_lock and dtrace_lock. We therefore need
8634 * to drop all of our locks before calling into it...
8636 mutex_exit(&dtrace_lock);
8637 mutex_exit(&dtrace_provider_lock);
8638 dtrace_enabling_matchall();
8643 mutex_exit(&dtrace_lock);
8644 mutex_exit(&dtrace_provider_lock);
8650 * Unregister the specified provider from the DTrace framework. This should
8651 * generally be called by DTrace providers in their detach(9E) entry point.
8654 dtrace_unregister(dtrace_provider_id_t id)
8656 dtrace_provider_t *old = (dtrace_provider_t *)id;
8657 dtrace_provider_t *prev = NULL;
8658 int i, self = 0, noreap = 0;
8659 dtrace_probe_t *probe, *first = NULL;
8661 if (old->dtpv_pops.dtps_enable ==
8662 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8664 * If DTrace itself is the provider, we're called with locks
8667 ASSERT(old == dtrace_provider);
8669 ASSERT(dtrace_devi != NULL);
8671 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8672 ASSERT(MUTEX_HELD(&dtrace_lock));
8675 if (dtrace_provider->dtpv_next != NULL) {
8677 * There's another provider here; return failure.
8682 mutex_enter(&dtrace_provider_lock);
8684 mutex_enter(&mod_lock);
8686 mutex_enter(&dtrace_lock);
8690 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8691 * probes, we refuse to let providers slither away, unless this
8692 * provider has already been explicitly invalidated.
8694 if (!old->dtpv_defunct &&
8695 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8696 dtrace_anon.dta_state->dts_necbs > 0))) {
8698 mutex_exit(&dtrace_lock);
8700 mutex_exit(&mod_lock);
8702 mutex_exit(&dtrace_provider_lock);
8708 * Attempt to destroy the probes associated with this provider.
8710 for (i = 0; i < dtrace_nprobes; i++) {
8711 if ((probe = dtrace_probes[i]) == NULL)
8714 if (probe->dtpr_provider != old)
8717 if (probe->dtpr_ecb == NULL)
8721 * If we are trying to unregister a defunct provider, and the
8722 * provider was made defunct within the interval dictated by
8723 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8724 * attempt to reap our enablings. To denote that the provider
8725 * should reattempt to unregister itself at some point in the
8726 * future, we will return a differentiable error code (EAGAIN
8727 * instead of EBUSY) in this case.
8729 if (dtrace_gethrtime() - old->dtpv_defunct >
8730 dtrace_unregister_defunct_reap)
8734 mutex_exit(&dtrace_lock);
8736 mutex_exit(&mod_lock);
8738 mutex_exit(&dtrace_provider_lock);
8744 (void) taskq_dispatch(dtrace_taskq,
8745 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8751 * All of the probes for this provider are disabled; we can safely
8752 * remove all of them from their hash chains and from the probe array.
8754 for (i = 0; i < dtrace_nprobes; i++) {
8755 if ((probe = dtrace_probes[i]) == NULL)
8758 if (probe->dtpr_provider != old)
8761 dtrace_probes[i] = NULL;
8763 dtrace_hash_remove(dtrace_bymod, probe);
8764 dtrace_hash_remove(dtrace_byfunc, probe);
8765 dtrace_hash_remove(dtrace_byname, probe);
8767 if (first == NULL) {
8769 probe->dtpr_nextmod = NULL;
8771 probe->dtpr_nextmod = first;
8777 * The provider's probes have been removed from the hash chains and
8778 * from the probe array. Now issue a dtrace_sync() to be sure that
8779 * everyone has cleared out from any probe array processing.
8783 for (probe = first; probe != NULL; probe = first) {
8784 first = probe->dtpr_nextmod;
8786 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8788 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8789 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8790 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8792 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8794 free_unr(dtrace_arena, probe->dtpr_id);
8796 kmem_free(probe, sizeof (dtrace_probe_t));
8799 if ((prev = dtrace_provider) == old) {
8801 ASSERT(self || dtrace_devi == NULL);
8802 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8804 dtrace_provider = old->dtpv_next;
8806 while (prev != NULL && prev->dtpv_next != old)
8807 prev = prev->dtpv_next;
8810 panic("attempt to unregister non-existent "
8811 "dtrace provider %p\n", (void *)id);
8814 prev->dtpv_next = old->dtpv_next;
8818 mutex_exit(&dtrace_lock);
8820 mutex_exit(&mod_lock);
8822 mutex_exit(&dtrace_provider_lock);
8825 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8826 kmem_free(old, sizeof (dtrace_provider_t));
8832 * Invalidate the specified provider. All subsequent probe lookups for the
8833 * specified provider will fail, but its probes will not be removed.
8836 dtrace_invalidate(dtrace_provider_id_t id)
8838 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8840 ASSERT(pvp->dtpv_pops.dtps_enable !=
8841 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8843 mutex_enter(&dtrace_provider_lock);
8844 mutex_enter(&dtrace_lock);
8846 pvp->dtpv_defunct = dtrace_gethrtime();
8848 mutex_exit(&dtrace_lock);
8849 mutex_exit(&dtrace_provider_lock);
8853 * Indicate whether or not DTrace has attached.
8856 dtrace_attached(void)
8859 * dtrace_provider will be non-NULL iff the DTrace driver has
8860 * attached. (It's non-NULL because DTrace is always itself a
8863 return (dtrace_provider != NULL);
8867 * Remove all the unenabled probes for the given provider. This function is
8868 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8869 * -- just as many of its associated probes as it can.
8872 dtrace_condense(dtrace_provider_id_t id)
8874 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8876 dtrace_probe_t *probe;
8879 * Make sure this isn't the dtrace provider itself.
8881 ASSERT(prov->dtpv_pops.dtps_enable !=
8882 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8884 mutex_enter(&dtrace_provider_lock);
8885 mutex_enter(&dtrace_lock);
8888 * Attempt to destroy the probes associated with this provider.
8890 for (i = 0; i < dtrace_nprobes; i++) {
8891 if ((probe = dtrace_probes[i]) == NULL)
8894 if (probe->dtpr_provider != prov)
8897 if (probe->dtpr_ecb != NULL)
8900 dtrace_probes[i] = NULL;
8902 dtrace_hash_remove(dtrace_bymod, probe);
8903 dtrace_hash_remove(dtrace_byfunc, probe);
8904 dtrace_hash_remove(dtrace_byname, probe);
8906 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8908 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8909 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8910 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8911 kmem_free(probe, sizeof (dtrace_probe_t));
8913 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8915 free_unr(dtrace_arena, i + 1);
8919 mutex_exit(&dtrace_lock);
8920 mutex_exit(&dtrace_provider_lock);
8926 * DTrace Probe Management Functions
8928 * The functions in this section perform the DTrace probe management,
8929 * including functions to create probes, look-up probes, and call into the
8930 * providers to request that probes be provided. Some of these functions are
8931 * in the Provider-to-Framework API; these functions can be identified by the
8932 * fact that they are not declared "static".
8936 * Create a probe with the specified module name, function name, and name.
8939 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8940 const char *func, const char *name, int aframes, void *arg)
8942 dtrace_probe_t *probe, **probes;
8943 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8946 if (provider == dtrace_provider) {
8947 ASSERT(MUTEX_HELD(&dtrace_lock));
8949 mutex_enter(&dtrace_lock);
8953 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8954 VM_BESTFIT | VM_SLEEP);
8956 id = alloc_unr(dtrace_arena);
8958 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8960 probe->dtpr_id = id;
8961 probe->dtpr_gen = dtrace_probegen++;
8962 probe->dtpr_mod = dtrace_strdup(mod);
8963 probe->dtpr_func = dtrace_strdup(func);
8964 probe->dtpr_name = dtrace_strdup(name);
8965 probe->dtpr_arg = arg;
8966 probe->dtpr_aframes = aframes;
8967 probe->dtpr_provider = provider;
8969 dtrace_hash_add(dtrace_bymod, probe);
8970 dtrace_hash_add(dtrace_byfunc, probe);
8971 dtrace_hash_add(dtrace_byname, probe);
8973 if (id - 1 >= dtrace_nprobes) {
8974 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8975 size_t nsize = osize << 1;
8979 ASSERT(dtrace_probes == NULL);
8980 nsize = sizeof (dtrace_probe_t *);
8983 probes = kmem_zalloc(nsize, KM_SLEEP);
8985 if (dtrace_probes == NULL) {
8987 dtrace_probes = probes;
8990 dtrace_probe_t **oprobes = dtrace_probes;
8992 bcopy(oprobes, probes, osize);
8993 dtrace_membar_producer();
8994 dtrace_probes = probes;
8999 * All CPUs are now seeing the new probes array; we can
9000 * safely free the old array.
9002 kmem_free(oprobes, osize);
9003 dtrace_nprobes <<= 1;
9006 ASSERT(id - 1 < dtrace_nprobes);
9009 ASSERT(dtrace_probes[id - 1] == NULL);
9010 dtrace_probes[id - 1] = probe;
9012 if (provider != dtrace_provider)
9013 mutex_exit(&dtrace_lock);
9018 static dtrace_probe_t *
9019 dtrace_probe_lookup_id(dtrace_id_t id)
9021 ASSERT(MUTEX_HELD(&dtrace_lock));
9023 if (id == 0 || id > dtrace_nprobes)
9026 return (dtrace_probes[id - 1]);
9030 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9032 *((dtrace_id_t *)arg) = probe->dtpr_id;
9034 return (DTRACE_MATCH_DONE);
9038 * Look up a probe based on provider and one or more of module name, function
9039 * name and probe name.
9042 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9043 char *func, char *name)
9045 dtrace_probekey_t pkey;
9049 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9050 pkey.dtpk_pmatch = &dtrace_match_string;
9051 pkey.dtpk_mod = mod;
9052 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9053 pkey.dtpk_func = func;
9054 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9055 pkey.dtpk_name = name;
9056 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9057 pkey.dtpk_id = DTRACE_IDNONE;
9059 mutex_enter(&dtrace_lock);
9060 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9061 dtrace_probe_lookup_match, &id);
9062 mutex_exit(&dtrace_lock);
9064 ASSERT(match == 1 || match == 0);
9065 return (match ? id : 0);
9069 * Returns the probe argument associated with the specified probe.
9072 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9074 dtrace_probe_t *probe;
9077 mutex_enter(&dtrace_lock);
9079 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9080 probe->dtpr_provider == (dtrace_provider_t *)id)
9081 rval = probe->dtpr_arg;
9083 mutex_exit(&dtrace_lock);
9089 * Copy a probe into a probe description.
9092 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9094 bzero(pdp, sizeof (dtrace_probedesc_t));
9095 pdp->dtpd_id = prp->dtpr_id;
9097 (void) strncpy(pdp->dtpd_provider,
9098 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9100 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9101 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9102 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9106 * Called to indicate that a probe -- or probes -- should be provided by a
9107 * specfied provider. If the specified description is NULL, the provider will
9108 * be told to provide all of its probes. (This is done whenever a new
9109 * consumer comes along, or whenever a retained enabling is to be matched.) If
9110 * the specified description is non-NULL, the provider is given the
9111 * opportunity to dynamically provide the specified probe, allowing providers
9112 * to support the creation of probes on-the-fly. (So-called _autocreated_
9113 * probes.) If the provider is NULL, the operations will be applied to all
9114 * providers; if the provider is non-NULL the operations will only be applied
9115 * to the specified provider. The dtrace_provider_lock must be held, and the
9116 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9117 * will need to grab the dtrace_lock when it reenters the framework through
9118 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9121 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9128 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9132 prv = dtrace_provider;
9137 * First, call the blanket provide operation.
9139 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9143 * Now call the per-module provide operation. We will grab
9144 * mod_lock to prevent the list from being modified. Note
9145 * that this also prevents the mod_busy bits from changing.
9146 * (mod_busy can only be changed with mod_lock held.)
9148 mutex_enter(&mod_lock);
9152 if (ctl->mod_busy || ctl->mod_mp == NULL)
9155 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9157 } while ((ctl = ctl->mod_next) != &modules);
9159 mutex_exit(&mod_lock);
9161 } while (all && (prv = prv->dtpv_next) != NULL);
9166 * Iterate over each probe, and call the Framework-to-Provider API function
9170 dtrace_probe_foreach(uintptr_t offs)
9172 dtrace_provider_t *prov;
9173 void (*func)(void *, dtrace_id_t, void *);
9174 dtrace_probe_t *probe;
9175 dtrace_icookie_t cookie;
9179 * We disable interrupts to walk through the probe array. This is
9180 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9181 * won't see stale data.
9183 cookie = dtrace_interrupt_disable();
9185 for (i = 0; i < dtrace_nprobes; i++) {
9186 if ((probe = dtrace_probes[i]) == NULL)
9189 if (probe->dtpr_ecb == NULL) {
9191 * This probe isn't enabled -- don't call the function.
9196 prov = probe->dtpr_provider;
9197 func = *((void(**)(void *, dtrace_id_t, void *))
9198 ((uintptr_t)&prov->dtpv_pops + offs));
9200 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9203 dtrace_interrupt_enable(cookie);
9208 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9210 dtrace_probekey_t pkey;
9215 ASSERT(MUTEX_HELD(&dtrace_lock));
9216 dtrace_ecb_create_cache = NULL;
9220 * If we're passed a NULL description, we're being asked to
9221 * create an ECB with a NULL probe.
9223 (void) dtrace_ecb_create_enable(NULL, enab);
9227 dtrace_probekey(desc, &pkey);
9228 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9229 &priv, &uid, &zoneid);
9231 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9236 * DTrace Helper Provider Functions
9239 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9241 attr->dtat_name = DOF_ATTR_NAME(dofattr);
9242 attr->dtat_data = DOF_ATTR_DATA(dofattr);
9243 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9247 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9248 const dof_provider_t *dofprov, char *strtab)
9250 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9251 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9252 dofprov->dofpv_provattr);
9253 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9254 dofprov->dofpv_modattr);
9255 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9256 dofprov->dofpv_funcattr);
9257 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9258 dofprov->dofpv_nameattr);
9259 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9260 dofprov->dofpv_argsattr);
9264 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9266 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9267 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9268 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9269 dof_provider_t *provider;
9271 uint32_t *off, *enoff;
9275 dtrace_helper_provdesc_t dhpv;
9276 dtrace_helper_probedesc_t dhpb;
9277 dtrace_meta_t *meta = dtrace_meta_pid;
9278 dtrace_mops_t *mops = &meta->dtm_mops;
9281 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9282 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9283 provider->dofpv_strtab * dof->dofh_secsize);
9284 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9285 provider->dofpv_probes * dof->dofh_secsize);
9286 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9287 provider->dofpv_prargs * dof->dofh_secsize);
9288 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9289 provider->dofpv_proffs * dof->dofh_secsize);
9291 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9292 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9293 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9297 * See dtrace_helper_provider_validate().
9299 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9300 provider->dofpv_prenoffs != DOF_SECT_NONE) {
9301 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9302 provider->dofpv_prenoffs * dof->dofh_secsize);
9303 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9306 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9309 * Create the provider.
9311 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9313 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9319 * Create the probes.
9321 for (i = 0; i < nprobes; i++) {
9322 probe = (dof_probe_t *)(uintptr_t)(daddr +
9323 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9325 /* See the check in dtrace_helper_provider_validate(). */
9326 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9329 dhpb.dthpb_mod = dhp->dofhp_mod;
9330 dhpb.dthpb_func = strtab + probe->dofpr_func;
9331 dhpb.dthpb_name = strtab + probe->dofpr_name;
9332 dhpb.dthpb_base = probe->dofpr_addr;
9333 dhpb.dthpb_offs = off + probe->dofpr_offidx;
9334 dhpb.dthpb_noffs = probe->dofpr_noffs;
9335 if (enoff != NULL) {
9336 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9337 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9339 dhpb.dthpb_enoffs = NULL;
9340 dhpb.dthpb_nenoffs = 0;
9342 dhpb.dthpb_args = arg + probe->dofpr_argidx;
9343 dhpb.dthpb_nargc = probe->dofpr_nargc;
9344 dhpb.dthpb_xargc = probe->dofpr_xargc;
9345 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9346 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9348 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9353 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9355 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9356 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9359 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9361 for (i = 0; i < dof->dofh_secnum; i++) {
9362 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9363 dof->dofh_secoff + i * dof->dofh_secsize);
9365 if (sec->dofs_type != DOF_SECT_PROVIDER)
9368 dtrace_helper_provide_one(dhp, sec, pid);
9372 * We may have just created probes, so we must now rematch against
9373 * any retained enablings. Note that this call will acquire both
9374 * cpu_lock and dtrace_lock; the fact that we are holding
9375 * dtrace_meta_lock now is what defines the ordering with respect to
9376 * these three locks.
9378 dtrace_enabling_matchall();
9382 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9384 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9385 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9387 dof_provider_t *provider;
9389 dtrace_helper_provdesc_t dhpv;
9390 dtrace_meta_t *meta = dtrace_meta_pid;
9391 dtrace_mops_t *mops = &meta->dtm_mops;
9393 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9394 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9395 provider->dofpv_strtab * dof->dofh_secsize);
9397 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9400 * Create the provider.
9402 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9404 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9410 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9412 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9413 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9416 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9418 for (i = 0; i < dof->dofh_secnum; i++) {
9419 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9420 dof->dofh_secoff + i * dof->dofh_secsize);
9422 if (sec->dofs_type != DOF_SECT_PROVIDER)
9425 dtrace_helper_provider_remove_one(dhp, sec, pid);
9430 * DTrace Meta Provider-to-Framework API Functions
9432 * These functions implement the Meta Provider-to-Framework API, as described
9433 * in <sys/dtrace.h>.
9436 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9437 dtrace_meta_provider_id_t *idp)
9439 dtrace_meta_t *meta;
9440 dtrace_helpers_t *help, *next;
9443 *idp = DTRACE_METAPROVNONE;
9446 * We strictly don't need the name, but we hold onto it for
9447 * debuggability. All hail error queues!
9450 cmn_err(CE_WARN, "failed to register meta-provider: "
9456 mops->dtms_create_probe == NULL ||
9457 mops->dtms_provide_pid == NULL ||
9458 mops->dtms_remove_pid == NULL) {
9459 cmn_err(CE_WARN, "failed to register meta-register %s: "
9460 "invalid ops", name);
9464 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9465 meta->dtm_mops = *mops;
9466 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9467 (void) strcpy(meta->dtm_name, name);
9468 meta->dtm_arg = arg;
9470 mutex_enter(&dtrace_meta_lock);
9471 mutex_enter(&dtrace_lock);
9473 if (dtrace_meta_pid != NULL) {
9474 mutex_exit(&dtrace_lock);
9475 mutex_exit(&dtrace_meta_lock);
9476 cmn_err(CE_WARN, "failed to register meta-register %s: "
9477 "user-land meta-provider exists", name);
9478 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9479 kmem_free(meta, sizeof (dtrace_meta_t));
9483 dtrace_meta_pid = meta;
9484 *idp = (dtrace_meta_provider_id_t)meta;
9487 * If there are providers and probes ready to go, pass them
9488 * off to the new meta provider now.
9491 help = dtrace_deferred_pid;
9492 dtrace_deferred_pid = NULL;
9494 mutex_exit(&dtrace_lock);
9496 while (help != NULL) {
9497 for (i = 0; i < help->dthps_nprovs; i++) {
9498 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9502 next = help->dthps_next;
9503 help->dthps_next = NULL;
9504 help->dthps_prev = NULL;
9505 help->dthps_deferred = 0;
9509 mutex_exit(&dtrace_meta_lock);
9515 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9517 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9519 mutex_enter(&dtrace_meta_lock);
9520 mutex_enter(&dtrace_lock);
9522 if (old == dtrace_meta_pid) {
9523 pp = &dtrace_meta_pid;
9525 panic("attempt to unregister non-existent "
9526 "dtrace meta-provider %p\n", (void *)old);
9529 if (old->dtm_count != 0) {
9530 mutex_exit(&dtrace_lock);
9531 mutex_exit(&dtrace_meta_lock);
9537 mutex_exit(&dtrace_lock);
9538 mutex_exit(&dtrace_meta_lock);
9540 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9541 kmem_free(old, sizeof (dtrace_meta_t));
9548 * DTrace DIF Object Functions
9551 dtrace_difo_err(uint_t pc, const char *format, ...)
9553 if (dtrace_err_verbose) {
9556 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
9557 va_start(alist, format);
9558 (void) vuprintf(format, alist);
9562 #ifdef DTRACE_ERRDEBUG
9563 dtrace_errdebug(format);
9569 * Validate a DTrace DIF object by checking the IR instructions. The following
9570 * rules are currently enforced by dtrace_difo_validate():
9572 * 1. Each instruction must have a valid opcode
9573 * 2. Each register, string, variable, or subroutine reference must be valid
9574 * 3. No instruction can modify register %r0 (must be zero)
9575 * 4. All instruction reserved bits must be set to zero
9576 * 5. The last instruction must be a "ret" instruction
9577 * 6. All branch targets must reference a valid instruction _after_ the branch
9580 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9584 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9588 kcheckload = cr == NULL ||
9589 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9591 dp->dtdo_destructive = 0;
9593 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9594 dif_instr_t instr = dp->dtdo_buf[pc];
9596 uint_t r1 = DIF_INSTR_R1(instr);
9597 uint_t r2 = DIF_INSTR_R2(instr);
9598 uint_t rd = DIF_INSTR_RD(instr);
9599 uint_t rs = DIF_INSTR_RS(instr);
9600 uint_t label = DIF_INSTR_LABEL(instr);
9601 uint_t v = DIF_INSTR_VAR(instr);
9602 uint_t subr = DIF_INSTR_SUBR(instr);
9603 uint_t type = DIF_INSTR_TYPE(instr);
9604 uint_t op = DIF_INSTR_OP(instr);
9622 err += efunc(pc, "invalid register %u\n", r1);
9624 err += efunc(pc, "invalid register %u\n", r2);
9626 err += efunc(pc, "invalid register %u\n", rd);
9628 err += efunc(pc, "cannot write to %r0\n");
9634 err += efunc(pc, "invalid register %u\n", r1);
9636 err += efunc(pc, "non-zero reserved bits\n");
9638 err += efunc(pc, "invalid register %u\n", rd);
9640 err += efunc(pc, "cannot write to %r0\n");
9650 err += efunc(pc, "invalid register %u\n", r1);
9652 err += efunc(pc, "non-zero reserved bits\n");
9654 err += efunc(pc, "invalid register %u\n", rd);
9656 err += efunc(pc, "cannot write to %r0\n");
9658 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9659 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9669 err += efunc(pc, "invalid register %u\n", r1);
9671 err += efunc(pc, "non-zero reserved bits\n");
9673 err += efunc(pc, "invalid register %u\n", rd);
9675 err += efunc(pc, "cannot write to %r0\n");
9685 err += efunc(pc, "invalid register %u\n", r1);
9687 err += efunc(pc, "non-zero reserved bits\n");
9689 err += efunc(pc, "invalid register %u\n", rd);
9691 err += efunc(pc, "cannot write to %r0\n");
9698 err += efunc(pc, "invalid register %u\n", r1);
9700 err += efunc(pc, "non-zero reserved bits\n");
9702 err += efunc(pc, "invalid register %u\n", rd);
9704 err += efunc(pc, "cannot write to 0 address\n");
9709 err += efunc(pc, "invalid register %u\n", r1);
9711 err += efunc(pc, "invalid register %u\n", r2);
9713 err += efunc(pc, "non-zero reserved bits\n");
9717 err += efunc(pc, "invalid register %u\n", r1);
9718 if (r2 != 0 || rd != 0)
9719 err += efunc(pc, "non-zero reserved bits\n");
9732 if (label >= dp->dtdo_len) {
9733 err += efunc(pc, "invalid branch target %u\n",
9737 err += efunc(pc, "backward branch to %u\n",
9742 if (r1 != 0 || r2 != 0)
9743 err += efunc(pc, "non-zero reserved bits\n");
9745 err += efunc(pc, "invalid register %u\n", rd);
9749 case DIF_OP_FLUSHTS:
9750 if (r1 != 0 || r2 != 0 || rd != 0)
9751 err += efunc(pc, "non-zero reserved bits\n");
9754 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9755 err += efunc(pc, "invalid integer ref %u\n",
9756 DIF_INSTR_INTEGER(instr));
9759 err += efunc(pc, "invalid register %u\n", rd);
9761 err += efunc(pc, "cannot write to %r0\n");
9764 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9765 err += efunc(pc, "invalid string ref %u\n",
9766 DIF_INSTR_STRING(instr));
9769 err += efunc(pc, "invalid register %u\n", rd);
9771 err += efunc(pc, "cannot write to %r0\n");
9775 if (r1 > DIF_VAR_ARRAY_MAX)
9776 err += efunc(pc, "invalid array %u\n", r1);
9778 err += efunc(pc, "invalid register %u\n", r2);
9780 err += efunc(pc, "invalid register %u\n", rd);
9782 err += efunc(pc, "cannot write to %r0\n");
9789 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9790 err += efunc(pc, "invalid variable %u\n", v);
9792 err += efunc(pc, "invalid register %u\n", rd);
9794 err += efunc(pc, "cannot write to %r0\n");
9801 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9802 err += efunc(pc, "invalid variable %u\n", v);
9804 err += efunc(pc, "invalid register %u\n", rd);
9807 if (subr > DIF_SUBR_MAX)
9808 err += efunc(pc, "invalid subr %u\n", subr);
9810 err += efunc(pc, "invalid register %u\n", rd);
9812 err += efunc(pc, "cannot write to %r0\n");
9814 if (subr == DIF_SUBR_COPYOUT ||
9815 subr == DIF_SUBR_COPYOUTSTR) {
9816 dp->dtdo_destructive = 1;
9819 if (subr == DIF_SUBR_GETF) {
9821 * If we have a getf() we need to record that
9822 * in our state. Note that our state can be
9823 * NULL if this is a helper -- but in that
9824 * case, the call to getf() is itself illegal,
9825 * and will be caught (slightly later) when
9826 * the helper is validated.
9828 if (vstate->dtvs_state != NULL)
9829 vstate->dtvs_state->dts_getf++;
9834 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9835 err += efunc(pc, "invalid ref type %u\n", type);
9837 err += efunc(pc, "invalid register %u\n", r2);
9839 err += efunc(pc, "invalid register %u\n", rs);
9842 if (type != DIF_TYPE_CTF)
9843 err += efunc(pc, "invalid val type %u\n", type);
9845 err += efunc(pc, "invalid register %u\n", r2);
9847 err += efunc(pc, "invalid register %u\n", rs);
9850 err += efunc(pc, "invalid opcode %u\n",
9851 DIF_INSTR_OP(instr));
9855 if (dp->dtdo_len != 0 &&
9856 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9857 err += efunc(dp->dtdo_len - 1,
9858 "expected 'ret' as last DIF instruction\n");
9861 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9863 * If we're not returning by reference, the size must be either
9864 * 0 or the size of one of the base types.
9866 switch (dp->dtdo_rtype.dtdt_size) {
9868 case sizeof (uint8_t):
9869 case sizeof (uint16_t):
9870 case sizeof (uint32_t):
9871 case sizeof (uint64_t):
9875 err += efunc(dp->dtdo_len - 1, "bad return size\n");
9879 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9880 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9881 dtrace_diftype_t *vt, *et;
9884 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9885 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9886 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9887 err += efunc(i, "unrecognized variable scope %d\n",
9892 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9893 v->dtdv_kind != DIFV_KIND_SCALAR) {
9894 err += efunc(i, "unrecognized variable type %d\n",
9899 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9900 err += efunc(i, "%d exceeds variable id limit\n", id);
9904 if (id < DIF_VAR_OTHER_UBASE)
9908 * For user-defined variables, we need to check that this
9909 * definition is identical to any previous definition that we
9912 ndx = id - DIF_VAR_OTHER_UBASE;
9914 switch (v->dtdv_scope) {
9915 case DIFV_SCOPE_GLOBAL:
9916 if (ndx < vstate->dtvs_nglobals) {
9917 dtrace_statvar_t *svar;
9919 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9920 existing = &svar->dtsv_var;
9925 case DIFV_SCOPE_THREAD:
9926 if (ndx < vstate->dtvs_ntlocals)
9927 existing = &vstate->dtvs_tlocals[ndx];
9930 case DIFV_SCOPE_LOCAL:
9931 if (ndx < vstate->dtvs_nlocals) {
9932 dtrace_statvar_t *svar;
9934 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9935 existing = &svar->dtsv_var;
9943 if (vt->dtdt_flags & DIF_TF_BYREF) {
9944 if (vt->dtdt_size == 0) {
9945 err += efunc(i, "zero-sized variable\n");
9949 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9950 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9951 vt->dtdt_size > dtrace_statvar_maxsize) {
9952 err += efunc(i, "oversized by-ref static\n");
9957 if (existing == NULL || existing->dtdv_id == 0)
9960 ASSERT(existing->dtdv_id == v->dtdv_id);
9961 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9963 if (existing->dtdv_kind != v->dtdv_kind)
9964 err += efunc(i, "%d changed variable kind\n", id);
9966 et = &existing->dtdv_type;
9968 if (vt->dtdt_flags != et->dtdt_flags) {
9969 err += efunc(i, "%d changed variable type flags\n", id);
9973 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9974 err += efunc(i, "%d changed variable type size\n", id);
9983 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9984 * are much more constrained than normal DIFOs. Specifically, they may
9987 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9988 * miscellaneous string routines
9989 * 2. Access DTrace variables other than the args[] array, and the
9990 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9991 * 3. Have thread-local variables.
9992 * 4. Have dynamic variables.
9995 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9997 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10001 for (pc = 0; pc < dp->dtdo_len; pc++) {
10002 dif_instr_t instr = dp->dtdo_buf[pc];
10004 uint_t v = DIF_INSTR_VAR(instr);
10005 uint_t subr = DIF_INSTR_SUBR(instr);
10006 uint_t op = DIF_INSTR_OP(instr);
10043 case DIF_OP_ALLOCS:
10061 case DIF_OP_FLUSHTS:
10068 case DIF_OP_PUSHTR:
10069 case DIF_OP_PUSHTV:
10073 if (v >= DIF_VAR_OTHER_UBASE)
10076 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10079 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10080 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10081 v == DIF_VAR_EXECARGS ||
10082 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10083 v == DIF_VAR_UID || v == DIF_VAR_GID)
10086 err += efunc(pc, "illegal variable %u\n", v);
10093 err += efunc(pc, "illegal dynamic variable load\n");
10099 err += efunc(pc, "illegal dynamic variable store\n");
10103 if (subr == DIF_SUBR_ALLOCA ||
10104 subr == DIF_SUBR_BCOPY ||
10105 subr == DIF_SUBR_COPYIN ||
10106 subr == DIF_SUBR_COPYINTO ||
10107 subr == DIF_SUBR_COPYINSTR ||
10108 subr == DIF_SUBR_INDEX ||
10109 subr == DIF_SUBR_INET_NTOA ||
10110 subr == DIF_SUBR_INET_NTOA6 ||
10111 subr == DIF_SUBR_INET_NTOP ||
10112 subr == DIF_SUBR_JSON ||
10113 subr == DIF_SUBR_LLTOSTR ||
10114 subr == DIF_SUBR_STRTOLL ||
10115 subr == DIF_SUBR_RINDEX ||
10116 subr == DIF_SUBR_STRCHR ||
10117 subr == DIF_SUBR_STRJOIN ||
10118 subr == DIF_SUBR_STRRCHR ||
10119 subr == DIF_SUBR_STRSTR ||
10120 subr == DIF_SUBR_HTONS ||
10121 subr == DIF_SUBR_HTONL ||
10122 subr == DIF_SUBR_HTONLL ||
10123 subr == DIF_SUBR_NTOHS ||
10124 subr == DIF_SUBR_NTOHL ||
10125 subr == DIF_SUBR_NTOHLL ||
10126 subr == DIF_SUBR_MEMREF ||
10128 subr == DIF_SUBR_MEMSTR ||
10130 subr == DIF_SUBR_TYPEREF)
10133 err += efunc(pc, "invalid subr %u\n", subr);
10137 err += efunc(pc, "invalid opcode %u\n",
10138 DIF_INSTR_OP(instr));
10146 * Returns 1 if the expression in the DIF object can be cached on a per-thread
10150 dtrace_difo_cacheable(dtrace_difo_t *dp)
10157 for (i = 0; i < dp->dtdo_varlen; i++) {
10158 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10160 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10163 switch (v->dtdv_id) {
10164 case DIF_VAR_CURTHREAD:
10167 case DIF_VAR_EXECARGS:
10168 case DIF_VAR_EXECNAME:
10169 case DIF_VAR_ZONENAME:
10178 * This DIF object may be cacheable. Now we need to look for any
10179 * array loading instructions, any memory loading instructions, or
10180 * any stores to thread-local variables.
10182 for (i = 0; i < dp->dtdo_len; i++) {
10183 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10185 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10186 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10187 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10188 op == DIF_OP_LDGA || op == DIF_OP_STTS)
10196 dtrace_difo_hold(dtrace_difo_t *dp)
10200 ASSERT(MUTEX_HELD(&dtrace_lock));
10203 ASSERT(dp->dtdo_refcnt != 0);
10206 * We need to check this DIF object for references to the variable
10207 * DIF_VAR_VTIMESTAMP.
10209 for (i = 0; i < dp->dtdo_varlen; i++) {
10210 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10212 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10215 if (dtrace_vtime_references++ == 0)
10216 dtrace_vtime_enable();
10221 * This routine calculates the dynamic variable chunksize for a given DIF
10222 * object. The calculation is not fool-proof, and can probably be tricked by
10223 * malicious DIF -- but it works for all compiler-generated DIF. Because this
10224 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10225 * if a dynamic variable size exceeds the chunksize.
10228 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10231 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10232 const dif_instr_t *text = dp->dtdo_buf;
10233 uint_t pc, srd = 0;
10235 size_t size, ksize;
10238 for (pc = 0; pc < dp->dtdo_len; pc++) {
10239 dif_instr_t instr = text[pc];
10240 uint_t op = DIF_INSTR_OP(instr);
10241 uint_t rd = DIF_INSTR_RD(instr);
10242 uint_t r1 = DIF_INSTR_R1(instr);
10246 dtrace_key_t *key = tupregs;
10250 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10255 key = &tupregs[DIF_DTR_NREGS];
10256 key[0].dttk_size = 0;
10257 key[1].dttk_size = 0;
10259 scope = DIFV_SCOPE_THREAD;
10266 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10267 key[nkeys++].dttk_size = 0;
10269 key[nkeys++].dttk_size = 0;
10271 if (op == DIF_OP_STTAA) {
10272 scope = DIFV_SCOPE_THREAD;
10274 scope = DIFV_SCOPE_GLOBAL;
10279 case DIF_OP_PUSHTR:
10280 if (ttop == DIF_DTR_NREGS)
10283 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10285 * If the register for the size of the "pushtr"
10286 * is %r0 (or the value is 0) and the type is
10287 * a string, we'll use the system-wide default
10290 tupregs[ttop++].dttk_size =
10291 dtrace_strsize_default;
10296 if (sval > LONG_MAX)
10299 tupregs[ttop++].dttk_size = sval;
10304 case DIF_OP_PUSHTV:
10305 if (ttop == DIF_DTR_NREGS)
10308 tupregs[ttop++].dttk_size = 0;
10311 case DIF_OP_FLUSHTS:
10328 * We have a dynamic variable allocation; calculate its size.
10330 for (ksize = 0, i = 0; i < nkeys; i++)
10331 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10333 size = sizeof (dtrace_dynvar_t);
10334 size += sizeof (dtrace_key_t) * (nkeys - 1);
10338 * Now we need to determine the size of the stored data.
10340 id = DIF_INSTR_VAR(instr);
10342 for (i = 0; i < dp->dtdo_varlen; i++) {
10343 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10345 if (v->dtdv_id == id && v->dtdv_scope == scope) {
10346 size += v->dtdv_type.dtdt_size;
10351 if (i == dp->dtdo_varlen)
10355 * We have the size. If this is larger than the chunk size
10356 * for our dynamic variable state, reset the chunk size.
10358 size = P2ROUNDUP(size, sizeof (uint64_t));
10361 * Before setting the chunk size, check that we're not going
10362 * to set it to a negative value...
10364 if (size > LONG_MAX)
10368 * ...and make certain that we didn't badly overflow.
10370 if (size < ksize || size < sizeof (dtrace_dynvar_t))
10373 if (size > vstate->dtvs_dynvars.dtds_chunksize)
10374 vstate->dtvs_dynvars.dtds_chunksize = size;
10379 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10381 int i, oldsvars, osz, nsz, otlocals, ntlocals;
10384 ASSERT(MUTEX_HELD(&dtrace_lock));
10385 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10387 for (i = 0; i < dp->dtdo_varlen; i++) {
10388 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10389 dtrace_statvar_t *svar, ***svarp = NULL;
10391 uint8_t scope = v->dtdv_scope;
10394 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10397 id -= DIF_VAR_OTHER_UBASE;
10400 case DIFV_SCOPE_THREAD:
10401 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10402 dtrace_difv_t *tlocals;
10404 if ((ntlocals = (otlocals << 1)) == 0)
10407 osz = otlocals * sizeof (dtrace_difv_t);
10408 nsz = ntlocals * sizeof (dtrace_difv_t);
10410 tlocals = kmem_zalloc(nsz, KM_SLEEP);
10413 bcopy(vstate->dtvs_tlocals,
10415 kmem_free(vstate->dtvs_tlocals, osz);
10418 vstate->dtvs_tlocals = tlocals;
10419 vstate->dtvs_ntlocals = ntlocals;
10422 vstate->dtvs_tlocals[id] = *v;
10425 case DIFV_SCOPE_LOCAL:
10426 np = &vstate->dtvs_nlocals;
10427 svarp = &vstate->dtvs_locals;
10429 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10430 dsize = NCPU * (v->dtdv_type.dtdt_size +
10431 sizeof (uint64_t));
10433 dsize = NCPU * sizeof (uint64_t);
10437 case DIFV_SCOPE_GLOBAL:
10438 np = &vstate->dtvs_nglobals;
10439 svarp = &vstate->dtvs_globals;
10441 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10442 dsize = v->dtdv_type.dtdt_size +
10451 while (id >= (oldsvars = *np)) {
10452 dtrace_statvar_t **statics;
10453 int newsvars, oldsize, newsize;
10455 if ((newsvars = (oldsvars << 1)) == 0)
10458 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10459 newsize = newsvars * sizeof (dtrace_statvar_t *);
10461 statics = kmem_zalloc(newsize, KM_SLEEP);
10463 if (oldsize != 0) {
10464 bcopy(*svarp, statics, oldsize);
10465 kmem_free(*svarp, oldsize);
10472 if ((svar = (*svarp)[id]) == NULL) {
10473 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10474 svar->dtsv_var = *v;
10476 if ((svar->dtsv_size = dsize) != 0) {
10477 svar->dtsv_data = (uint64_t)(uintptr_t)
10478 kmem_zalloc(dsize, KM_SLEEP);
10481 (*svarp)[id] = svar;
10484 svar->dtsv_refcnt++;
10487 dtrace_difo_chunksize(dp, vstate);
10488 dtrace_difo_hold(dp);
10491 static dtrace_difo_t *
10492 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10494 dtrace_difo_t *new;
10497 ASSERT(dp->dtdo_buf != NULL);
10498 ASSERT(dp->dtdo_refcnt != 0);
10500 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10502 ASSERT(dp->dtdo_buf != NULL);
10503 sz = dp->dtdo_len * sizeof (dif_instr_t);
10504 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10505 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10506 new->dtdo_len = dp->dtdo_len;
10508 if (dp->dtdo_strtab != NULL) {
10509 ASSERT(dp->dtdo_strlen != 0);
10510 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10511 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10512 new->dtdo_strlen = dp->dtdo_strlen;
10515 if (dp->dtdo_inttab != NULL) {
10516 ASSERT(dp->dtdo_intlen != 0);
10517 sz = dp->dtdo_intlen * sizeof (uint64_t);
10518 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10519 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10520 new->dtdo_intlen = dp->dtdo_intlen;
10523 if (dp->dtdo_vartab != NULL) {
10524 ASSERT(dp->dtdo_varlen != 0);
10525 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10526 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10527 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10528 new->dtdo_varlen = dp->dtdo_varlen;
10531 dtrace_difo_init(new, vstate);
10536 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10540 ASSERT(dp->dtdo_refcnt == 0);
10542 for (i = 0; i < dp->dtdo_varlen; i++) {
10543 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10544 dtrace_statvar_t *svar, **svarp = NULL;
10546 uint8_t scope = v->dtdv_scope;
10550 case DIFV_SCOPE_THREAD:
10553 case DIFV_SCOPE_LOCAL:
10554 np = &vstate->dtvs_nlocals;
10555 svarp = vstate->dtvs_locals;
10558 case DIFV_SCOPE_GLOBAL:
10559 np = &vstate->dtvs_nglobals;
10560 svarp = vstate->dtvs_globals;
10567 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10570 id -= DIF_VAR_OTHER_UBASE;
10574 ASSERT(svar != NULL);
10575 ASSERT(svar->dtsv_refcnt > 0);
10577 if (--svar->dtsv_refcnt > 0)
10580 if (svar->dtsv_size != 0) {
10581 ASSERT(svar->dtsv_data != 0);
10582 kmem_free((void *)(uintptr_t)svar->dtsv_data,
10586 kmem_free(svar, sizeof (dtrace_statvar_t));
10590 if (dp->dtdo_buf != NULL)
10591 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10592 if (dp->dtdo_inttab != NULL)
10593 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10594 if (dp->dtdo_strtab != NULL)
10595 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10596 if (dp->dtdo_vartab != NULL)
10597 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10599 kmem_free(dp, sizeof (dtrace_difo_t));
10603 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10607 ASSERT(MUTEX_HELD(&dtrace_lock));
10608 ASSERT(dp->dtdo_refcnt != 0);
10610 for (i = 0; i < dp->dtdo_varlen; i++) {
10611 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10613 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10616 ASSERT(dtrace_vtime_references > 0);
10617 if (--dtrace_vtime_references == 0)
10618 dtrace_vtime_disable();
10621 if (--dp->dtdo_refcnt == 0)
10622 dtrace_difo_destroy(dp, vstate);
10626 * DTrace Format Functions
10629 dtrace_format_add(dtrace_state_t *state, char *str)
10632 uint16_t ndx, len = strlen(str) + 1;
10634 fmt = kmem_zalloc(len, KM_SLEEP);
10635 bcopy(str, fmt, len);
10637 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10638 if (state->dts_formats[ndx] == NULL) {
10639 state->dts_formats[ndx] = fmt;
10644 if (state->dts_nformats == USHRT_MAX) {
10646 * This is only likely if a denial-of-service attack is being
10647 * attempted. As such, it's okay to fail silently here.
10649 kmem_free(fmt, len);
10654 * For simplicity, we always resize the formats array to be exactly the
10655 * number of formats.
10657 ndx = state->dts_nformats++;
10658 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10660 if (state->dts_formats != NULL) {
10662 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10663 kmem_free(state->dts_formats, ndx * sizeof (char *));
10666 state->dts_formats = new;
10667 state->dts_formats[ndx] = fmt;
10673 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10677 ASSERT(state->dts_formats != NULL);
10678 ASSERT(format <= state->dts_nformats);
10679 ASSERT(state->dts_formats[format - 1] != NULL);
10681 fmt = state->dts_formats[format - 1];
10682 kmem_free(fmt, strlen(fmt) + 1);
10683 state->dts_formats[format - 1] = NULL;
10687 dtrace_format_destroy(dtrace_state_t *state)
10691 if (state->dts_nformats == 0) {
10692 ASSERT(state->dts_formats == NULL);
10696 ASSERT(state->dts_formats != NULL);
10698 for (i = 0; i < state->dts_nformats; i++) {
10699 char *fmt = state->dts_formats[i];
10704 kmem_free(fmt, strlen(fmt) + 1);
10707 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10708 state->dts_nformats = 0;
10709 state->dts_formats = NULL;
10713 * DTrace Predicate Functions
10715 static dtrace_predicate_t *
10716 dtrace_predicate_create(dtrace_difo_t *dp)
10718 dtrace_predicate_t *pred;
10720 ASSERT(MUTEX_HELD(&dtrace_lock));
10721 ASSERT(dp->dtdo_refcnt != 0);
10723 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10724 pred->dtp_difo = dp;
10725 pred->dtp_refcnt = 1;
10727 if (!dtrace_difo_cacheable(dp))
10730 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10732 * This is only theoretically possible -- we have had 2^32
10733 * cacheable predicates on this machine. We cannot allow any
10734 * more predicates to become cacheable: as unlikely as it is,
10735 * there may be a thread caching a (now stale) predicate cache
10736 * ID. (N.B.: the temptation is being successfully resisted to
10737 * have this cmn_err() "Holy shit -- we executed this code!")
10742 pred->dtp_cacheid = dtrace_predcache_id++;
10748 dtrace_predicate_hold(dtrace_predicate_t *pred)
10750 ASSERT(MUTEX_HELD(&dtrace_lock));
10751 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10752 ASSERT(pred->dtp_refcnt > 0);
10754 pred->dtp_refcnt++;
10758 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10760 dtrace_difo_t *dp = pred->dtp_difo;
10762 ASSERT(MUTEX_HELD(&dtrace_lock));
10763 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10764 ASSERT(pred->dtp_refcnt > 0);
10766 if (--pred->dtp_refcnt == 0) {
10767 dtrace_difo_release(pred->dtp_difo, vstate);
10768 kmem_free(pred, sizeof (dtrace_predicate_t));
10773 * DTrace Action Description Functions
10775 static dtrace_actdesc_t *
10776 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10777 uint64_t uarg, uint64_t arg)
10779 dtrace_actdesc_t *act;
10782 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10783 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10786 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10787 act->dtad_kind = kind;
10788 act->dtad_ntuple = ntuple;
10789 act->dtad_uarg = uarg;
10790 act->dtad_arg = arg;
10791 act->dtad_refcnt = 1;
10797 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10799 ASSERT(act->dtad_refcnt >= 1);
10800 act->dtad_refcnt++;
10804 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10806 dtrace_actkind_t kind = act->dtad_kind;
10809 ASSERT(act->dtad_refcnt >= 1);
10811 if (--act->dtad_refcnt != 0)
10814 if ((dp = act->dtad_difo) != NULL)
10815 dtrace_difo_release(dp, vstate);
10817 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10818 char *str = (char *)(uintptr_t)act->dtad_arg;
10821 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10822 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10826 kmem_free(str, strlen(str) + 1);
10829 kmem_free(act, sizeof (dtrace_actdesc_t));
10833 * DTrace ECB Functions
10835 static dtrace_ecb_t *
10836 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10839 dtrace_epid_t epid;
10841 ASSERT(MUTEX_HELD(&dtrace_lock));
10843 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10844 ecb->dte_predicate = NULL;
10845 ecb->dte_probe = probe;
10848 * The default size is the size of the default action: recording
10851 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10852 ecb->dte_alignment = sizeof (dtrace_epid_t);
10854 epid = state->dts_epid++;
10856 if (epid - 1 >= state->dts_necbs) {
10857 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10858 int necbs = state->dts_necbs << 1;
10860 ASSERT(epid == state->dts_necbs + 1);
10863 ASSERT(oecbs == NULL);
10867 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10870 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10872 dtrace_membar_producer();
10873 state->dts_ecbs = ecbs;
10875 if (oecbs != NULL) {
10877 * If this state is active, we must dtrace_sync()
10878 * before we can free the old dts_ecbs array: we're
10879 * coming in hot, and there may be active ring
10880 * buffer processing (which indexes into the dts_ecbs
10881 * array) on another CPU.
10883 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10886 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10889 dtrace_membar_producer();
10890 state->dts_necbs = necbs;
10893 ecb->dte_state = state;
10895 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10896 dtrace_membar_producer();
10897 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10903 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10905 dtrace_probe_t *probe = ecb->dte_probe;
10907 ASSERT(MUTEX_HELD(&cpu_lock));
10908 ASSERT(MUTEX_HELD(&dtrace_lock));
10909 ASSERT(ecb->dte_next == NULL);
10911 if (probe == NULL) {
10913 * This is the NULL probe -- there's nothing to do.
10918 if (probe->dtpr_ecb == NULL) {
10919 dtrace_provider_t *prov = probe->dtpr_provider;
10922 * We're the first ECB on this probe.
10924 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10926 if (ecb->dte_predicate != NULL)
10927 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10929 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10930 probe->dtpr_id, probe->dtpr_arg);
10933 * This probe is already active. Swing the last pointer to
10934 * point to the new ECB, and issue a dtrace_sync() to assure
10935 * that all CPUs have seen the change.
10937 ASSERT(probe->dtpr_ecb_last != NULL);
10938 probe->dtpr_ecb_last->dte_next = ecb;
10939 probe->dtpr_ecb_last = ecb;
10940 probe->dtpr_predcache = 0;
10947 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10949 dtrace_action_t *act;
10950 uint32_t curneeded = UINT32_MAX;
10951 uint32_t aggbase = UINT32_MAX;
10954 * If we record anything, we always record the dtrace_rechdr_t. (And
10955 * we always record it first.)
10957 ecb->dte_size = sizeof (dtrace_rechdr_t);
10958 ecb->dte_alignment = sizeof (dtrace_epid_t);
10960 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10961 dtrace_recdesc_t *rec = &act->dta_rec;
10962 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10964 ecb->dte_alignment = MAX(ecb->dte_alignment,
10965 rec->dtrd_alignment);
10967 if (DTRACEACT_ISAGG(act->dta_kind)) {
10968 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10970 ASSERT(rec->dtrd_size != 0);
10971 ASSERT(agg->dtag_first != NULL);
10972 ASSERT(act->dta_prev->dta_intuple);
10973 ASSERT(aggbase != UINT32_MAX);
10974 ASSERT(curneeded != UINT32_MAX);
10976 agg->dtag_base = aggbase;
10978 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10979 rec->dtrd_offset = curneeded;
10980 curneeded += rec->dtrd_size;
10981 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10983 aggbase = UINT32_MAX;
10984 curneeded = UINT32_MAX;
10985 } else if (act->dta_intuple) {
10986 if (curneeded == UINT32_MAX) {
10988 * This is the first record in a tuple. Align
10989 * curneeded to be at offset 4 in an 8-byte
10992 ASSERT(act->dta_prev == NULL ||
10993 !act->dta_prev->dta_intuple);
10994 ASSERT3U(aggbase, ==, UINT32_MAX);
10995 curneeded = P2PHASEUP(ecb->dte_size,
10996 sizeof (uint64_t), sizeof (dtrace_aggid_t));
10998 aggbase = curneeded - sizeof (dtrace_aggid_t);
10999 ASSERT(IS_P2ALIGNED(aggbase,
11000 sizeof (uint64_t)));
11002 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11003 rec->dtrd_offset = curneeded;
11004 curneeded += rec->dtrd_size;
11006 /* tuples must be followed by an aggregation */
11007 ASSERT(act->dta_prev == NULL ||
11008 !act->dta_prev->dta_intuple);
11010 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11011 rec->dtrd_alignment);
11012 rec->dtrd_offset = ecb->dte_size;
11013 ecb->dte_size += rec->dtrd_size;
11014 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11018 if ((act = ecb->dte_action) != NULL &&
11019 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11020 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11022 * If the size is still sizeof (dtrace_rechdr_t), then all
11023 * actions store no data; set the size to 0.
11028 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11029 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11030 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11034 static dtrace_action_t *
11035 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11037 dtrace_aggregation_t *agg;
11038 size_t size = sizeof (uint64_t);
11039 int ntuple = desc->dtad_ntuple;
11040 dtrace_action_t *act;
11041 dtrace_recdesc_t *frec;
11042 dtrace_aggid_t aggid;
11043 dtrace_state_t *state = ecb->dte_state;
11045 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11046 agg->dtag_ecb = ecb;
11048 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11050 switch (desc->dtad_kind) {
11051 case DTRACEAGG_MIN:
11052 agg->dtag_initial = INT64_MAX;
11053 agg->dtag_aggregate = dtrace_aggregate_min;
11056 case DTRACEAGG_MAX:
11057 agg->dtag_initial = INT64_MIN;
11058 agg->dtag_aggregate = dtrace_aggregate_max;
11061 case DTRACEAGG_COUNT:
11062 agg->dtag_aggregate = dtrace_aggregate_count;
11065 case DTRACEAGG_QUANTIZE:
11066 agg->dtag_aggregate = dtrace_aggregate_quantize;
11067 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11071 case DTRACEAGG_LQUANTIZE: {
11072 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11073 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11075 agg->dtag_initial = desc->dtad_arg;
11076 agg->dtag_aggregate = dtrace_aggregate_lquantize;
11078 if (step == 0 || levels == 0)
11081 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11085 case DTRACEAGG_LLQUANTIZE: {
11086 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11087 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11088 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11089 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11092 agg->dtag_initial = desc->dtad_arg;
11093 agg->dtag_aggregate = dtrace_aggregate_llquantize;
11095 if (factor < 2 || low >= high || nsteps < factor)
11099 * Now check that the number of steps evenly divides a power
11100 * of the factor. (This assures both integer bucket size and
11101 * linearity within each magnitude.)
11103 for (v = factor; v < nsteps; v *= factor)
11106 if ((v % nsteps) || (nsteps % factor))
11109 size = (dtrace_aggregate_llquantize_bucket(factor,
11110 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11114 case DTRACEAGG_AVG:
11115 agg->dtag_aggregate = dtrace_aggregate_avg;
11116 size = sizeof (uint64_t) * 2;
11119 case DTRACEAGG_STDDEV:
11120 agg->dtag_aggregate = dtrace_aggregate_stddev;
11121 size = sizeof (uint64_t) * 4;
11124 case DTRACEAGG_SUM:
11125 agg->dtag_aggregate = dtrace_aggregate_sum;
11132 agg->dtag_action.dta_rec.dtrd_size = size;
11138 * We must make sure that we have enough actions for the n-tuple.
11140 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11141 if (DTRACEACT_ISAGG(act->dta_kind))
11144 if (--ntuple == 0) {
11146 * This is the action with which our n-tuple begins.
11148 agg->dtag_first = act;
11154 * This n-tuple is short by ntuple elements. Return failure.
11156 ASSERT(ntuple != 0);
11158 kmem_free(agg, sizeof (dtrace_aggregation_t));
11163 * If the last action in the tuple has a size of zero, it's actually
11164 * an expression argument for the aggregating action.
11166 ASSERT(ecb->dte_action_last != NULL);
11167 act = ecb->dte_action_last;
11169 if (act->dta_kind == DTRACEACT_DIFEXPR) {
11170 ASSERT(act->dta_difo != NULL);
11172 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11173 agg->dtag_hasarg = 1;
11177 * We need to allocate an id for this aggregation.
11180 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11181 VM_BESTFIT | VM_SLEEP);
11183 aggid = alloc_unr(state->dts_aggid_arena);
11186 if (aggid - 1 >= state->dts_naggregations) {
11187 dtrace_aggregation_t **oaggs = state->dts_aggregations;
11188 dtrace_aggregation_t **aggs;
11189 int naggs = state->dts_naggregations << 1;
11190 int onaggs = state->dts_naggregations;
11192 ASSERT(aggid == state->dts_naggregations + 1);
11195 ASSERT(oaggs == NULL);
11199 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11201 if (oaggs != NULL) {
11202 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11203 kmem_free(oaggs, onaggs * sizeof (*aggs));
11206 state->dts_aggregations = aggs;
11207 state->dts_naggregations = naggs;
11210 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11211 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11213 frec = &agg->dtag_first->dta_rec;
11214 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11215 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11217 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11218 ASSERT(!act->dta_intuple);
11219 act->dta_intuple = 1;
11222 return (&agg->dtag_action);
11226 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11228 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11229 dtrace_state_t *state = ecb->dte_state;
11230 dtrace_aggid_t aggid = agg->dtag_id;
11232 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11234 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11236 free_unr(state->dts_aggid_arena, aggid);
11239 ASSERT(state->dts_aggregations[aggid - 1] == agg);
11240 state->dts_aggregations[aggid - 1] = NULL;
11242 kmem_free(agg, sizeof (dtrace_aggregation_t));
11246 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11248 dtrace_action_t *action, *last;
11249 dtrace_difo_t *dp = desc->dtad_difo;
11250 uint32_t size = 0, align = sizeof (uint8_t), mask;
11251 uint16_t format = 0;
11252 dtrace_recdesc_t *rec;
11253 dtrace_state_t *state = ecb->dte_state;
11254 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11255 uint64_t arg = desc->dtad_arg;
11257 ASSERT(MUTEX_HELD(&dtrace_lock));
11258 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11260 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11262 * If this is an aggregating action, there must be neither
11263 * a speculate nor a commit on the action chain.
11265 dtrace_action_t *act;
11267 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11268 if (act->dta_kind == DTRACEACT_COMMIT)
11271 if (act->dta_kind == DTRACEACT_SPECULATE)
11275 action = dtrace_ecb_aggregation_create(ecb, desc);
11277 if (action == NULL)
11280 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11281 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11282 dp != NULL && dp->dtdo_destructive)) {
11283 state->dts_destructive = 1;
11286 switch (desc->dtad_kind) {
11287 case DTRACEACT_PRINTF:
11288 case DTRACEACT_PRINTA:
11289 case DTRACEACT_SYSTEM:
11290 case DTRACEACT_FREOPEN:
11291 case DTRACEACT_DIFEXPR:
11293 * We know that our arg is a string -- turn it into a
11297 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11298 desc->dtad_kind == DTRACEACT_DIFEXPR);
11303 ASSERT(arg > KERNELBASE);
11305 format = dtrace_format_add(state,
11306 (char *)(uintptr_t)arg);
11310 case DTRACEACT_LIBACT:
11311 case DTRACEACT_TRACEMEM:
11312 case DTRACEACT_TRACEMEM_DYNSIZE:
11316 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11319 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11320 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11323 size = opt[DTRACEOPT_STRSIZE];
11328 case DTRACEACT_STACK:
11329 if ((nframes = arg) == 0) {
11330 nframes = opt[DTRACEOPT_STACKFRAMES];
11331 ASSERT(nframes > 0);
11335 size = nframes * sizeof (pc_t);
11338 case DTRACEACT_JSTACK:
11339 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11340 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11342 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11343 nframes = opt[DTRACEOPT_JSTACKFRAMES];
11345 arg = DTRACE_USTACK_ARG(nframes, strsize);
11348 case DTRACEACT_USTACK:
11349 if (desc->dtad_kind != DTRACEACT_JSTACK &&
11350 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11351 strsize = DTRACE_USTACK_STRSIZE(arg);
11352 nframes = opt[DTRACEOPT_USTACKFRAMES];
11353 ASSERT(nframes > 0);
11354 arg = DTRACE_USTACK_ARG(nframes, strsize);
11358 * Save a slot for the pid.
11360 size = (nframes + 1) * sizeof (uint64_t);
11361 size += DTRACE_USTACK_STRSIZE(arg);
11362 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11366 case DTRACEACT_SYM:
11367 case DTRACEACT_MOD:
11368 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11369 sizeof (uint64_t)) ||
11370 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11374 case DTRACEACT_USYM:
11375 case DTRACEACT_UMOD:
11376 case DTRACEACT_UADDR:
11378 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11379 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11383 * We have a slot for the pid, plus a slot for the
11384 * argument. To keep things simple (aligned with
11385 * bitness-neutral sizing), we store each as a 64-bit
11388 size = 2 * sizeof (uint64_t);
11391 case DTRACEACT_STOP:
11392 case DTRACEACT_BREAKPOINT:
11393 case DTRACEACT_PANIC:
11396 case DTRACEACT_CHILL:
11397 case DTRACEACT_DISCARD:
11398 case DTRACEACT_RAISE:
11403 case DTRACEACT_EXIT:
11405 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11406 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11410 case DTRACEACT_SPECULATE:
11411 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11417 state->dts_speculates = 1;
11420 case DTRACEACT_PRINTM:
11421 size = dp->dtdo_rtype.dtdt_size;
11424 case DTRACEACT_PRINTT:
11425 size = dp->dtdo_rtype.dtdt_size;
11428 case DTRACEACT_COMMIT: {
11429 dtrace_action_t *act = ecb->dte_action;
11431 for (; act != NULL; act = act->dta_next) {
11432 if (act->dta_kind == DTRACEACT_COMMIT)
11445 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11447 * If this is a data-storing action or a speculate,
11448 * we must be sure that there isn't a commit on the
11451 dtrace_action_t *act = ecb->dte_action;
11453 for (; act != NULL; act = act->dta_next) {
11454 if (act->dta_kind == DTRACEACT_COMMIT)
11459 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11460 action->dta_rec.dtrd_size = size;
11463 action->dta_refcnt = 1;
11464 rec = &action->dta_rec;
11465 size = rec->dtrd_size;
11467 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11468 if (!(size & mask)) {
11474 action->dta_kind = desc->dtad_kind;
11476 if ((action->dta_difo = dp) != NULL)
11477 dtrace_difo_hold(dp);
11479 rec->dtrd_action = action->dta_kind;
11480 rec->dtrd_arg = arg;
11481 rec->dtrd_uarg = desc->dtad_uarg;
11482 rec->dtrd_alignment = (uint16_t)align;
11483 rec->dtrd_format = format;
11485 if ((last = ecb->dte_action_last) != NULL) {
11486 ASSERT(ecb->dte_action != NULL);
11487 action->dta_prev = last;
11488 last->dta_next = action;
11490 ASSERT(ecb->dte_action == NULL);
11491 ecb->dte_action = action;
11494 ecb->dte_action_last = action;
11500 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11502 dtrace_action_t *act = ecb->dte_action, *next;
11503 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11507 if (act != NULL && act->dta_refcnt > 1) {
11508 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11511 for (; act != NULL; act = next) {
11512 next = act->dta_next;
11513 ASSERT(next != NULL || act == ecb->dte_action_last);
11514 ASSERT(act->dta_refcnt == 1);
11516 if ((format = act->dta_rec.dtrd_format) != 0)
11517 dtrace_format_remove(ecb->dte_state, format);
11519 if ((dp = act->dta_difo) != NULL)
11520 dtrace_difo_release(dp, vstate);
11522 if (DTRACEACT_ISAGG(act->dta_kind)) {
11523 dtrace_ecb_aggregation_destroy(ecb, act);
11525 kmem_free(act, sizeof (dtrace_action_t));
11530 ecb->dte_action = NULL;
11531 ecb->dte_action_last = NULL;
11536 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11539 * We disable the ECB by removing it from its probe.
11541 dtrace_ecb_t *pecb, *prev = NULL;
11542 dtrace_probe_t *probe = ecb->dte_probe;
11544 ASSERT(MUTEX_HELD(&dtrace_lock));
11546 if (probe == NULL) {
11548 * This is the NULL probe; there is nothing to disable.
11553 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11559 ASSERT(pecb != NULL);
11561 if (prev == NULL) {
11562 probe->dtpr_ecb = ecb->dte_next;
11564 prev->dte_next = ecb->dte_next;
11567 if (ecb == probe->dtpr_ecb_last) {
11568 ASSERT(ecb->dte_next == NULL);
11569 probe->dtpr_ecb_last = prev;
11573 * The ECB has been disconnected from the probe; now sync to assure
11574 * that all CPUs have seen the change before returning.
11578 if (probe->dtpr_ecb == NULL) {
11580 * That was the last ECB on the probe; clear the predicate
11581 * cache ID for the probe, disable it and sync one more time
11582 * to assure that we'll never hit it again.
11584 dtrace_provider_t *prov = probe->dtpr_provider;
11586 ASSERT(ecb->dte_next == NULL);
11587 ASSERT(probe->dtpr_ecb_last == NULL);
11588 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11589 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11590 probe->dtpr_id, probe->dtpr_arg);
11594 * There is at least one ECB remaining on the probe. If there
11595 * is _exactly_ one, set the probe's predicate cache ID to be
11596 * the predicate cache ID of the remaining ECB.
11598 ASSERT(probe->dtpr_ecb_last != NULL);
11599 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11601 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11602 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11604 ASSERT(probe->dtpr_ecb->dte_next == NULL);
11607 probe->dtpr_predcache = p->dtp_cacheid;
11610 ecb->dte_next = NULL;
11615 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11617 dtrace_state_t *state = ecb->dte_state;
11618 dtrace_vstate_t *vstate = &state->dts_vstate;
11619 dtrace_predicate_t *pred;
11620 dtrace_epid_t epid = ecb->dte_epid;
11622 ASSERT(MUTEX_HELD(&dtrace_lock));
11623 ASSERT(ecb->dte_next == NULL);
11624 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11626 if ((pred = ecb->dte_predicate) != NULL)
11627 dtrace_predicate_release(pred, vstate);
11629 dtrace_ecb_action_remove(ecb);
11631 ASSERT(state->dts_ecbs[epid - 1] == ecb);
11632 state->dts_ecbs[epid - 1] = NULL;
11634 kmem_free(ecb, sizeof (dtrace_ecb_t));
11637 static dtrace_ecb_t *
11638 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11639 dtrace_enabling_t *enab)
11642 dtrace_predicate_t *pred;
11643 dtrace_actdesc_t *act;
11644 dtrace_provider_t *prov;
11645 dtrace_ecbdesc_t *desc = enab->dten_current;
11647 ASSERT(MUTEX_HELD(&dtrace_lock));
11648 ASSERT(state != NULL);
11650 ecb = dtrace_ecb_add(state, probe);
11651 ecb->dte_uarg = desc->dted_uarg;
11653 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11654 dtrace_predicate_hold(pred);
11655 ecb->dte_predicate = pred;
11658 if (probe != NULL) {
11660 * If the provider shows more leg than the consumer is old
11661 * enough to see, we need to enable the appropriate implicit
11662 * predicate bits to prevent the ecb from activating at
11665 * Providers specifying DTRACE_PRIV_USER at register time
11666 * are stating that they need the /proc-style privilege
11667 * model to be enforced, and this is what DTRACE_COND_OWNER
11668 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11670 prov = probe->dtpr_provider;
11671 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11672 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11673 ecb->dte_cond |= DTRACE_COND_OWNER;
11675 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11676 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11677 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11680 * If the provider shows us kernel innards and the user
11681 * is lacking sufficient privilege, enable the
11682 * DTRACE_COND_USERMODE implicit predicate.
11684 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11685 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11686 ecb->dte_cond |= DTRACE_COND_USERMODE;
11689 if (dtrace_ecb_create_cache != NULL) {
11691 * If we have a cached ecb, we'll use its action list instead
11692 * of creating our own (saving both time and space).
11694 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11695 dtrace_action_t *act = cached->dte_action;
11698 ASSERT(act->dta_refcnt > 0);
11700 ecb->dte_action = act;
11701 ecb->dte_action_last = cached->dte_action_last;
11702 ecb->dte_needed = cached->dte_needed;
11703 ecb->dte_size = cached->dte_size;
11704 ecb->dte_alignment = cached->dte_alignment;
11710 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11711 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11712 dtrace_ecb_destroy(ecb);
11717 dtrace_ecb_resize(ecb);
11719 return (dtrace_ecb_create_cache = ecb);
11723 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11726 dtrace_enabling_t *enab = arg;
11727 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11729 ASSERT(state != NULL);
11731 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11733 * This probe was created in a generation for which this
11734 * enabling has previously created ECBs; we don't want to
11735 * enable it again, so just kick out.
11737 return (DTRACE_MATCH_NEXT);
11740 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11741 return (DTRACE_MATCH_DONE);
11743 dtrace_ecb_enable(ecb);
11744 return (DTRACE_MATCH_NEXT);
11747 static dtrace_ecb_t *
11748 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11752 ASSERT(MUTEX_HELD(&dtrace_lock));
11754 if (id == 0 || id > state->dts_necbs)
11757 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11758 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11760 return (state->dts_ecbs[id - 1]);
11763 static dtrace_aggregation_t *
11764 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11766 dtrace_aggregation_t *agg;
11768 ASSERT(MUTEX_HELD(&dtrace_lock));
11770 if (id == 0 || id > state->dts_naggregations)
11773 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11774 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11775 agg->dtag_id == id);
11777 return (state->dts_aggregations[id - 1]);
11781 * DTrace Buffer Functions
11783 * The following functions manipulate DTrace buffers. Most of these functions
11784 * are called in the context of establishing or processing consumer state;
11785 * exceptions are explicitly noted.
11789 * Note: called from cross call context. This function switches the two
11790 * buffers on a given CPU. The atomicity of this operation is assured by
11791 * disabling interrupts while the actual switch takes place; the disabling of
11792 * interrupts serializes the execution with any execution of dtrace_probe() on
11796 dtrace_buffer_switch(dtrace_buffer_t *buf)
11798 caddr_t tomax = buf->dtb_tomax;
11799 caddr_t xamot = buf->dtb_xamot;
11800 dtrace_icookie_t cookie;
11803 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11804 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11806 cookie = dtrace_interrupt_disable();
11807 now = dtrace_gethrtime();
11808 buf->dtb_tomax = xamot;
11809 buf->dtb_xamot = tomax;
11810 buf->dtb_xamot_drops = buf->dtb_drops;
11811 buf->dtb_xamot_offset = buf->dtb_offset;
11812 buf->dtb_xamot_errors = buf->dtb_errors;
11813 buf->dtb_xamot_flags = buf->dtb_flags;
11814 buf->dtb_offset = 0;
11815 buf->dtb_drops = 0;
11816 buf->dtb_errors = 0;
11817 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11818 buf->dtb_interval = now - buf->dtb_switched;
11819 buf->dtb_switched = now;
11820 dtrace_interrupt_enable(cookie);
11824 * Note: called from cross call context. This function activates a buffer
11825 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11826 * is guaranteed by the disabling of interrupts.
11829 dtrace_buffer_activate(dtrace_state_t *state)
11831 dtrace_buffer_t *buf;
11832 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11834 buf = &state->dts_buffer[curcpu];
11836 if (buf->dtb_tomax != NULL) {
11838 * We might like to assert that the buffer is marked inactive,
11839 * but this isn't necessarily true: the buffer for the CPU
11840 * that processes the BEGIN probe has its buffer activated
11841 * manually. In this case, we take the (harmless) action
11842 * re-clearing the bit INACTIVE bit.
11844 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11847 dtrace_interrupt_enable(cookie);
11851 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11852 processorid_t cpu, int *factor)
11857 dtrace_buffer_t *buf;
11858 int allocated = 0, desired = 0;
11861 ASSERT(MUTEX_HELD(&cpu_lock));
11862 ASSERT(MUTEX_HELD(&dtrace_lock));
11866 if (size > dtrace_nonroot_maxsize &&
11867 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11873 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11876 buf = &bufs[cp->cpu_id];
11879 * If there is already a buffer allocated for this CPU, it
11880 * is only possible that this is a DR event. In this case,
11882 if (buf->dtb_tomax != NULL) {
11883 ASSERT(buf->dtb_size == size);
11887 ASSERT(buf->dtb_xamot == NULL);
11889 if ((buf->dtb_tomax = kmem_zalloc(size,
11890 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11893 buf->dtb_size = size;
11894 buf->dtb_flags = flags;
11895 buf->dtb_offset = 0;
11896 buf->dtb_drops = 0;
11898 if (flags & DTRACEBUF_NOSWITCH)
11901 if ((buf->dtb_xamot = kmem_zalloc(size,
11902 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11904 } while ((cp = cp->cpu_next) != cpu_list);
11912 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11915 buf = &bufs[cp->cpu_id];
11918 if (buf->dtb_xamot != NULL) {
11919 ASSERT(buf->dtb_tomax != NULL);
11920 ASSERT(buf->dtb_size == size);
11921 kmem_free(buf->dtb_xamot, size);
11925 if (buf->dtb_tomax != NULL) {
11926 ASSERT(buf->dtb_size == size);
11927 kmem_free(buf->dtb_tomax, size);
11931 buf->dtb_tomax = NULL;
11932 buf->dtb_xamot = NULL;
11934 } while ((cp = cp->cpu_next) != cpu_list);
11939 #if defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
11941 * FreeBSD isn't good at limiting the amount of memory we
11942 * ask to malloc, so let's place a limit here before trying
11943 * to do something that might well end in tears at bedtime.
11945 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
11949 ASSERT(MUTEX_HELD(&dtrace_lock));
11951 if (cpu != DTRACE_CPUALL && cpu != i)
11957 * If there is already a buffer allocated for this CPU, it
11958 * is only possible that this is a DR event. In this case,
11959 * the buffer size must match our specified size.
11961 if (buf->dtb_tomax != NULL) {
11962 ASSERT(buf->dtb_size == size);
11966 ASSERT(buf->dtb_xamot == NULL);
11968 if ((buf->dtb_tomax = kmem_zalloc(size,
11969 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11972 buf->dtb_size = size;
11973 buf->dtb_flags = flags;
11974 buf->dtb_offset = 0;
11975 buf->dtb_drops = 0;
11977 if (flags & DTRACEBUF_NOSWITCH)
11980 if ((buf->dtb_xamot = kmem_zalloc(size,
11981 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11989 * Error allocating memory, so free the buffers that were
11990 * allocated before the failed allocation.
11993 if (cpu != DTRACE_CPUALL && cpu != i)
11999 if (buf->dtb_xamot != NULL) {
12000 ASSERT(buf->dtb_tomax != NULL);
12001 ASSERT(buf->dtb_size == size);
12002 kmem_free(buf->dtb_xamot, size);
12006 if (buf->dtb_tomax != NULL) {
12007 ASSERT(buf->dtb_size == size);
12008 kmem_free(buf->dtb_tomax, size);
12012 buf->dtb_tomax = NULL;
12013 buf->dtb_xamot = NULL;
12018 *factor = desired / (allocated > 0 ? allocated : 1);
12024 * Note: called from probe context. This function just increments the drop
12025 * count on a buffer. It has been made a function to allow for the
12026 * possibility of understanding the source of mysterious drop counts. (A
12027 * problem for which one may be particularly disappointed that DTrace cannot
12028 * be used to understand DTrace.)
12031 dtrace_buffer_drop(dtrace_buffer_t *buf)
12037 * Note: called from probe context. This function is called to reserve space
12038 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
12039 * mstate. Returns the new offset in the buffer, or a negative value if an
12040 * error has occurred.
12043 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12044 dtrace_state_t *state, dtrace_mstate_t *mstate)
12046 intptr_t offs = buf->dtb_offset, soffs;
12051 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12054 if ((tomax = buf->dtb_tomax) == NULL) {
12055 dtrace_buffer_drop(buf);
12059 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12060 while (offs & (align - 1)) {
12062 * Assert that our alignment is off by a number which
12063 * is itself sizeof (uint32_t) aligned.
12065 ASSERT(!((align - (offs & (align - 1))) &
12066 (sizeof (uint32_t) - 1)));
12067 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12068 offs += sizeof (uint32_t);
12071 if ((soffs = offs + needed) > buf->dtb_size) {
12072 dtrace_buffer_drop(buf);
12076 if (mstate == NULL)
12079 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12080 mstate->dtms_scratch_size = buf->dtb_size - soffs;
12081 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12086 if (buf->dtb_flags & DTRACEBUF_FILL) {
12087 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12088 (buf->dtb_flags & DTRACEBUF_FULL))
12093 total = needed + (offs & (align - 1));
12096 * For a ring buffer, life is quite a bit more complicated. Before
12097 * we can store any padding, we need to adjust our wrapping offset.
12098 * (If we've never before wrapped or we're not about to, no adjustment
12101 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12102 offs + total > buf->dtb_size) {
12103 woffs = buf->dtb_xamot_offset;
12105 if (offs + total > buf->dtb_size) {
12107 * We can't fit in the end of the buffer. First, a
12108 * sanity check that we can fit in the buffer at all.
12110 if (total > buf->dtb_size) {
12111 dtrace_buffer_drop(buf);
12116 * We're going to be storing at the top of the buffer,
12117 * so now we need to deal with the wrapped offset. We
12118 * only reset our wrapped offset to 0 if it is
12119 * currently greater than the current offset. If it
12120 * is less than the current offset, it is because a
12121 * previous allocation induced a wrap -- but the
12122 * allocation didn't subsequently take the space due
12123 * to an error or false predicate evaluation. In this
12124 * case, we'll just leave the wrapped offset alone: if
12125 * the wrapped offset hasn't been advanced far enough
12126 * for this allocation, it will be adjusted in the
12129 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12137 * Now we know that we're going to be storing to the
12138 * top of the buffer and that there is room for us
12139 * there. We need to clear the buffer from the current
12140 * offset to the end (there may be old gunk there).
12142 while (offs < buf->dtb_size)
12146 * We need to set our offset to zero. And because we
12147 * are wrapping, we need to set the bit indicating as
12148 * much. We can also adjust our needed space back
12149 * down to the space required by the ECB -- we know
12150 * that the top of the buffer is aligned.
12154 buf->dtb_flags |= DTRACEBUF_WRAPPED;
12157 * There is room for us in the buffer, so we simply
12158 * need to check the wrapped offset.
12160 if (woffs < offs) {
12162 * The wrapped offset is less than the offset.
12163 * This can happen if we allocated buffer space
12164 * that induced a wrap, but then we didn't
12165 * subsequently take the space due to an error
12166 * or false predicate evaluation. This is
12167 * okay; we know that _this_ allocation isn't
12168 * going to induce a wrap. We still can't
12169 * reset the wrapped offset to be zero,
12170 * however: the space may have been trashed in
12171 * the previous failed probe attempt. But at
12172 * least the wrapped offset doesn't need to
12173 * be adjusted at all...
12179 while (offs + total > woffs) {
12180 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12183 if (epid == DTRACE_EPIDNONE) {
12184 size = sizeof (uint32_t);
12186 ASSERT3U(epid, <=, state->dts_necbs);
12187 ASSERT(state->dts_ecbs[epid - 1] != NULL);
12189 size = state->dts_ecbs[epid - 1]->dte_size;
12192 ASSERT(woffs + size <= buf->dtb_size);
12195 if (woffs + size == buf->dtb_size) {
12197 * We've reached the end of the buffer; we want
12198 * to set the wrapped offset to 0 and break
12199 * out. However, if the offs is 0, then we're
12200 * in a strange edge-condition: the amount of
12201 * space that we want to reserve plus the size
12202 * of the record that we're overwriting is
12203 * greater than the size of the buffer. This
12204 * is problematic because if we reserve the
12205 * space but subsequently don't consume it (due
12206 * to a failed predicate or error) the wrapped
12207 * offset will be 0 -- yet the EPID at offset 0
12208 * will not be committed. This situation is
12209 * relatively easy to deal with: if we're in
12210 * this case, the buffer is indistinguishable
12211 * from one that hasn't wrapped; we need only
12212 * finish the job by clearing the wrapped bit,
12213 * explicitly setting the offset to be 0, and
12214 * zero'ing out the old data in the buffer.
12217 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12218 buf->dtb_offset = 0;
12221 while (woffs < buf->dtb_size)
12222 tomax[woffs++] = 0;
12233 * We have a wrapped offset. It may be that the wrapped offset
12234 * has become zero -- that's okay.
12236 buf->dtb_xamot_offset = woffs;
12241 * Now we can plow the buffer with any necessary padding.
12243 while (offs & (align - 1)) {
12245 * Assert that our alignment is off by a number which
12246 * is itself sizeof (uint32_t) aligned.
12248 ASSERT(!((align - (offs & (align - 1))) &
12249 (sizeof (uint32_t) - 1)));
12250 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12251 offs += sizeof (uint32_t);
12254 if (buf->dtb_flags & DTRACEBUF_FILL) {
12255 if (offs + needed > buf->dtb_size - state->dts_reserve) {
12256 buf->dtb_flags |= DTRACEBUF_FULL;
12261 if (mstate == NULL)
12265 * For ring buffers and fill buffers, the scratch space is always
12266 * the inactive buffer.
12268 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12269 mstate->dtms_scratch_size = buf->dtb_size;
12270 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12276 dtrace_buffer_polish(dtrace_buffer_t *buf)
12278 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12279 ASSERT(MUTEX_HELD(&dtrace_lock));
12281 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12285 * We need to polish the ring buffer. There are three cases:
12287 * - The first (and presumably most common) is that there is no gap
12288 * between the buffer offset and the wrapped offset. In this case,
12289 * there is nothing in the buffer that isn't valid data; we can
12290 * mark the buffer as polished and return.
12292 * - The second (less common than the first but still more common
12293 * than the third) is that there is a gap between the buffer offset
12294 * and the wrapped offset, and the wrapped offset is larger than the
12295 * buffer offset. This can happen because of an alignment issue, or
12296 * can happen because of a call to dtrace_buffer_reserve() that
12297 * didn't subsequently consume the buffer space. In this case,
12298 * we need to zero the data from the buffer offset to the wrapped
12301 * - The third (and least common) is that there is a gap between the
12302 * buffer offset and the wrapped offset, but the wrapped offset is
12303 * _less_ than the buffer offset. This can only happen because a
12304 * call to dtrace_buffer_reserve() induced a wrap, but the space
12305 * was not subsequently consumed. In this case, we need to zero the
12306 * space from the offset to the end of the buffer _and_ from the
12307 * top of the buffer to the wrapped offset.
12309 if (buf->dtb_offset < buf->dtb_xamot_offset) {
12310 bzero(buf->dtb_tomax + buf->dtb_offset,
12311 buf->dtb_xamot_offset - buf->dtb_offset);
12314 if (buf->dtb_offset > buf->dtb_xamot_offset) {
12315 bzero(buf->dtb_tomax + buf->dtb_offset,
12316 buf->dtb_size - buf->dtb_offset);
12317 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12322 * This routine determines if data generated at the specified time has likely
12323 * been entirely consumed at user-level. This routine is called to determine
12324 * if an ECB on a defunct probe (but for an active enabling) can be safely
12325 * disabled and destroyed.
12328 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12332 for (i = 0; i < NCPU; i++) {
12333 dtrace_buffer_t *buf = &bufs[i];
12335 if (buf->dtb_size == 0)
12338 if (buf->dtb_flags & DTRACEBUF_RING)
12341 if (!buf->dtb_switched && buf->dtb_offset != 0)
12344 if (buf->dtb_switched - buf->dtb_interval < when)
12352 dtrace_buffer_free(dtrace_buffer_t *bufs)
12356 for (i = 0; i < NCPU; i++) {
12357 dtrace_buffer_t *buf = &bufs[i];
12359 if (buf->dtb_tomax == NULL) {
12360 ASSERT(buf->dtb_xamot == NULL);
12361 ASSERT(buf->dtb_size == 0);
12365 if (buf->dtb_xamot != NULL) {
12366 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12367 kmem_free(buf->dtb_xamot, buf->dtb_size);
12370 kmem_free(buf->dtb_tomax, buf->dtb_size);
12372 buf->dtb_tomax = NULL;
12373 buf->dtb_xamot = NULL;
12378 * DTrace Enabling Functions
12380 static dtrace_enabling_t *
12381 dtrace_enabling_create(dtrace_vstate_t *vstate)
12383 dtrace_enabling_t *enab;
12385 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12386 enab->dten_vstate = vstate;
12392 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12394 dtrace_ecbdesc_t **ndesc;
12395 size_t osize, nsize;
12398 * We can't add to enablings after we've enabled them, or after we've
12401 ASSERT(enab->dten_probegen == 0);
12402 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12404 if (enab->dten_ndesc < enab->dten_maxdesc) {
12405 enab->dten_desc[enab->dten_ndesc++] = ecb;
12409 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12411 if (enab->dten_maxdesc == 0) {
12412 enab->dten_maxdesc = 1;
12414 enab->dten_maxdesc <<= 1;
12417 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12419 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12420 ndesc = kmem_zalloc(nsize, KM_SLEEP);
12421 bcopy(enab->dten_desc, ndesc, osize);
12422 if (enab->dten_desc != NULL)
12423 kmem_free(enab->dten_desc, osize);
12425 enab->dten_desc = ndesc;
12426 enab->dten_desc[enab->dten_ndesc++] = ecb;
12430 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12431 dtrace_probedesc_t *pd)
12433 dtrace_ecbdesc_t *new;
12434 dtrace_predicate_t *pred;
12435 dtrace_actdesc_t *act;
12438 * We're going to create a new ECB description that matches the
12439 * specified ECB in every way, but has the specified probe description.
12441 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12443 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12444 dtrace_predicate_hold(pred);
12446 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12447 dtrace_actdesc_hold(act);
12449 new->dted_action = ecb->dted_action;
12450 new->dted_pred = ecb->dted_pred;
12451 new->dted_probe = *pd;
12452 new->dted_uarg = ecb->dted_uarg;
12454 dtrace_enabling_add(enab, new);
12458 dtrace_enabling_dump(dtrace_enabling_t *enab)
12462 for (i = 0; i < enab->dten_ndesc; i++) {
12463 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12465 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12466 desc->dtpd_provider, desc->dtpd_mod,
12467 desc->dtpd_func, desc->dtpd_name);
12472 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12475 dtrace_ecbdesc_t *ep;
12476 dtrace_vstate_t *vstate = enab->dten_vstate;
12478 ASSERT(MUTEX_HELD(&dtrace_lock));
12480 for (i = 0; i < enab->dten_ndesc; i++) {
12481 dtrace_actdesc_t *act, *next;
12482 dtrace_predicate_t *pred;
12484 ep = enab->dten_desc[i];
12486 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12487 dtrace_predicate_release(pred, vstate);
12489 for (act = ep->dted_action; act != NULL; act = next) {
12490 next = act->dtad_next;
12491 dtrace_actdesc_release(act, vstate);
12494 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12497 if (enab->dten_desc != NULL)
12498 kmem_free(enab->dten_desc,
12499 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12502 * If this was a retained enabling, decrement the dts_nretained count
12503 * and take it off of the dtrace_retained list.
12505 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12506 dtrace_retained == enab) {
12507 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12508 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12509 enab->dten_vstate->dtvs_state->dts_nretained--;
12510 dtrace_retained_gen++;
12513 if (enab->dten_prev == NULL) {
12514 if (dtrace_retained == enab) {
12515 dtrace_retained = enab->dten_next;
12517 if (dtrace_retained != NULL)
12518 dtrace_retained->dten_prev = NULL;
12521 ASSERT(enab != dtrace_retained);
12522 ASSERT(dtrace_retained != NULL);
12523 enab->dten_prev->dten_next = enab->dten_next;
12526 if (enab->dten_next != NULL) {
12527 ASSERT(dtrace_retained != NULL);
12528 enab->dten_next->dten_prev = enab->dten_prev;
12531 kmem_free(enab, sizeof (dtrace_enabling_t));
12535 dtrace_enabling_retain(dtrace_enabling_t *enab)
12537 dtrace_state_t *state;
12539 ASSERT(MUTEX_HELD(&dtrace_lock));
12540 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12541 ASSERT(enab->dten_vstate != NULL);
12543 state = enab->dten_vstate->dtvs_state;
12544 ASSERT(state != NULL);
12547 * We only allow each state to retain dtrace_retain_max enablings.
12549 if (state->dts_nretained >= dtrace_retain_max)
12552 state->dts_nretained++;
12553 dtrace_retained_gen++;
12555 if (dtrace_retained == NULL) {
12556 dtrace_retained = enab;
12560 enab->dten_next = dtrace_retained;
12561 dtrace_retained->dten_prev = enab;
12562 dtrace_retained = enab;
12568 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12569 dtrace_probedesc_t *create)
12571 dtrace_enabling_t *new, *enab;
12572 int found = 0, err = ENOENT;
12574 ASSERT(MUTEX_HELD(&dtrace_lock));
12575 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12576 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12577 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12578 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12580 new = dtrace_enabling_create(&state->dts_vstate);
12583 * Iterate over all retained enablings, looking for enablings that
12584 * match the specified state.
12586 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12590 * dtvs_state can only be NULL for helper enablings -- and
12591 * helper enablings can't be retained.
12593 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12595 if (enab->dten_vstate->dtvs_state != state)
12599 * Now iterate over each probe description; we're looking for
12600 * an exact match to the specified probe description.
12602 for (i = 0; i < enab->dten_ndesc; i++) {
12603 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12604 dtrace_probedesc_t *pd = &ep->dted_probe;
12606 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12609 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12612 if (strcmp(pd->dtpd_func, match->dtpd_func))
12615 if (strcmp(pd->dtpd_name, match->dtpd_name))
12619 * We have a winning probe! Add it to our growing
12623 dtrace_enabling_addlike(new, ep, create);
12627 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12628 dtrace_enabling_destroy(new);
12636 dtrace_enabling_retract(dtrace_state_t *state)
12638 dtrace_enabling_t *enab, *next;
12640 ASSERT(MUTEX_HELD(&dtrace_lock));
12643 * Iterate over all retained enablings, destroy the enablings retained
12644 * for the specified state.
12646 for (enab = dtrace_retained; enab != NULL; enab = next) {
12647 next = enab->dten_next;
12650 * dtvs_state can only be NULL for helper enablings -- and
12651 * helper enablings can't be retained.
12653 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12655 if (enab->dten_vstate->dtvs_state == state) {
12656 ASSERT(state->dts_nretained > 0);
12657 dtrace_enabling_destroy(enab);
12661 ASSERT(state->dts_nretained == 0);
12665 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12670 ASSERT(MUTEX_HELD(&cpu_lock));
12671 ASSERT(MUTEX_HELD(&dtrace_lock));
12673 for (i = 0; i < enab->dten_ndesc; i++) {
12674 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12676 enab->dten_current = ep;
12677 enab->dten_error = 0;
12679 matched += dtrace_probe_enable(&ep->dted_probe, enab);
12681 if (enab->dten_error != 0) {
12683 * If we get an error half-way through enabling the
12684 * probes, we kick out -- perhaps with some number of
12685 * them enabled. Leaving enabled probes enabled may
12686 * be slightly confusing for user-level, but we expect
12687 * that no one will attempt to actually drive on in
12688 * the face of such errors. If this is an anonymous
12689 * enabling (indicated with a NULL nmatched pointer),
12690 * we cmn_err() a message. We aren't expecting to
12691 * get such an error -- such as it can exist at all,
12692 * it would be a result of corrupted DOF in the driver
12695 if (nmatched == NULL) {
12696 cmn_err(CE_WARN, "dtrace_enabling_match() "
12697 "error on %p: %d", (void *)ep,
12701 return (enab->dten_error);
12705 enab->dten_probegen = dtrace_probegen;
12706 if (nmatched != NULL)
12707 *nmatched = matched;
12713 dtrace_enabling_matchall(void)
12715 dtrace_enabling_t *enab;
12717 mutex_enter(&cpu_lock);
12718 mutex_enter(&dtrace_lock);
12721 * Iterate over all retained enablings to see if any probes match
12722 * against them. We only perform this operation on enablings for which
12723 * we have sufficient permissions by virtue of being in the global zone
12724 * or in the same zone as the DTrace client. Because we can be called
12725 * after dtrace_detach() has been called, we cannot assert that there
12726 * are retained enablings. We can safely load from dtrace_retained,
12727 * however: the taskq_destroy() at the end of dtrace_detach() will
12728 * block pending our completion.
12730 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12732 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12734 if (INGLOBALZONE(curproc) ||
12735 cr != NULL && getzoneid() == crgetzoneid(cr))
12737 (void) dtrace_enabling_match(enab, NULL);
12740 mutex_exit(&dtrace_lock);
12741 mutex_exit(&cpu_lock);
12745 * If an enabling is to be enabled without having matched probes (that is, if
12746 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12747 * enabling must be _primed_ by creating an ECB for every ECB description.
12748 * This must be done to assure that we know the number of speculations, the
12749 * number of aggregations, the minimum buffer size needed, etc. before we
12750 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
12751 * enabling any probes, we create ECBs for every ECB decription, but with a
12752 * NULL probe -- which is exactly what this function does.
12755 dtrace_enabling_prime(dtrace_state_t *state)
12757 dtrace_enabling_t *enab;
12760 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12761 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12763 if (enab->dten_vstate->dtvs_state != state)
12767 * We don't want to prime an enabling more than once, lest
12768 * we allow a malicious user to induce resource exhaustion.
12769 * (The ECBs that result from priming an enabling aren't
12770 * leaked -- but they also aren't deallocated until the
12771 * consumer state is destroyed.)
12773 if (enab->dten_primed)
12776 for (i = 0; i < enab->dten_ndesc; i++) {
12777 enab->dten_current = enab->dten_desc[i];
12778 (void) dtrace_probe_enable(NULL, enab);
12781 enab->dten_primed = 1;
12786 * Called to indicate that probes should be provided due to retained
12787 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
12788 * must take an initial lap through the enabling calling the dtps_provide()
12789 * entry point explicitly to allow for autocreated probes.
12792 dtrace_enabling_provide(dtrace_provider_t *prv)
12795 dtrace_probedesc_t desc;
12796 dtrace_genid_t gen;
12798 ASSERT(MUTEX_HELD(&dtrace_lock));
12799 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12803 prv = dtrace_provider;
12807 dtrace_enabling_t *enab;
12808 void *parg = prv->dtpv_arg;
12811 gen = dtrace_retained_gen;
12812 for (enab = dtrace_retained; enab != NULL;
12813 enab = enab->dten_next) {
12814 for (i = 0; i < enab->dten_ndesc; i++) {
12815 desc = enab->dten_desc[i]->dted_probe;
12816 mutex_exit(&dtrace_lock);
12817 prv->dtpv_pops.dtps_provide(parg, &desc);
12818 mutex_enter(&dtrace_lock);
12820 * Process the retained enablings again if
12821 * they have changed while we weren't holding
12824 if (gen != dtrace_retained_gen)
12828 } while (all && (prv = prv->dtpv_next) != NULL);
12830 mutex_exit(&dtrace_lock);
12831 dtrace_probe_provide(NULL, all ? NULL : prv);
12832 mutex_enter(&dtrace_lock);
12836 * Called to reap ECBs that are attached to probes from defunct providers.
12839 dtrace_enabling_reap(void)
12841 dtrace_provider_t *prov;
12842 dtrace_probe_t *probe;
12847 mutex_enter(&cpu_lock);
12848 mutex_enter(&dtrace_lock);
12850 for (i = 0; i < dtrace_nprobes; i++) {
12851 if ((probe = dtrace_probes[i]) == NULL)
12854 if (probe->dtpr_ecb == NULL)
12857 prov = probe->dtpr_provider;
12859 if ((when = prov->dtpv_defunct) == 0)
12863 * We have ECBs on a defunct provider: we want to reap these
12864 * ECBs to allow the provider to unregister. The destruction
12865 * of these ECBs must be done carefully: if we destroy the ECB
12866 * and the consumer later wishes to consume an EPID that
12867 * corresponds to the destroyed ECB (and if the EPID metadata
12868 * has not been previously consumed), the consumer will abort
12869 * processing on the unknown EPID. To reduce (but not, sadly,
12870 * eliminate) the possibility of this, we will only destroy an
12871 * ECB for a defunct provider if, for the state that
12872 * corresponds to the ECB:
12874 * (a) There is no speculative tracing (which can effectively
12875 * cache an EPID for an arbitrary amount of time).
12877 * (b) The principal buffers have been switched twice since the
12878 * provider became defunct.
12880 * (c) The aggregation buffers are of zero size or have been
12881 * switched twice since the provider became defunct.
12883 * We use dts_speculates to determine (a) and call a function
12884 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
12885 * that as soon as we've been unable to destroy one of the ECBs
12886 * associated with the probe, we quit trying -- reaping is only
12887 * fruitful in as much as we can destroy all ECBs associated
12888 * with the defunct provider's probes.
12890 while ((ecb = probe->dtpr_ecb) != NULL) {
12891 dtrace_state_t *state = ecb->dte_state;
12892 dtrace_buffer_t *buf = state->dts_buffer;
12893 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12895 if (state->dts_speculates)
12898 if (!dtrace_buffer_consumed(buf, when))
12901 if (!dtrace_buffer_consumed(aggbuf, when))
12904 dtrace_ecb_disable(ecb);
12905 ASSERT(probe->dtpr_ecb != ecb);
12906 dtrace_ecb_destroy(ecb);
12910 mutex_exit(&dtrace_lock);
12911 mutex_exit(&cpu_lock);
12915 * DTrace DOF Functions
12919 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12921 if (dtrace_err_verbose)
12922 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12924 #ifdef DTRACE_ERRDEBUG
12925 dtrace_errdebug(str);
12930 * Create DOF out of a currently enabled state. Right now, we only create
12931 * DOF containing the run-time options -- but this could be expanded to create
12932 * complete DOF representing the enabled state.
12935 dtrace_dof_create(dtrace_state_t *state)
12939 dof_optdesc_t *opt;
12940 int i, len = sizeof (dof_hdr_t) +
12941 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12942 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12944 ASSERT(MUTEX_HELD(&dtrace_lock));
12946 dof = kmem_zalloc(len, KM_SLEEP);
12947 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12948 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12949 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12950 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12952 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12953 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12954 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12955 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12956 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12957 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12959 dof->dofh_flags = 0;
12960 dof->dofh_hdrsize = sizeof (dof_hdr_t);
12961 dof->dofh_secsize = sizeof (dof_sec_t);
12962 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
12963 dof->dofh_secoff = sizeof (dof_hdr_t);
12964 dof->dofh_loadsz = len;
12965 dof->dofh_filesz = len;
12969 * Fill in the option section header...
12971 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12972 sec->dofs_type = DOF_SECT_OPTDESC;
12973 sec->dofs_align = sizeof (uint64_t);
12974 sec->dofs_flags = DOF_SECF_LOAD;
12975 sec->dofs_entsize = sizeof (dof_optdesc_t);
12977 opt = (dof_optdesc_t *)((uintptr_t)sec +
12978 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12980 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12981 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12983 for (i = 0; i < DTRACEOPT_MAX; i++) {
12984 opt[i].dofo_option = i;
12985 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12986 opt[i].dofo_value = state->dts_options[i];
12993 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12995 dof_hdr_t hdr, *dof;
12997 ASSERT(!MUTEX_HELD(&dtrace_lock));
13000 * First, we're going to copyin() the sizeof (dof_hdr_t).
13002 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13003 dtrace_dof_error(NULL, "failed to copyin DOF header");
13009 * Now we'll allocate the entire DOF and copy it in -- provided
13010 * that the length isn't outrageous.
13012 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13013 dtrace_dof_error(&hdr, "load size exceeds maximum");
13018 if (hdr.dofh_loadsz < sizeof (hdr)) {
13019 dtrace_dof_error(&hdr, "invalid load size");
13024 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13026 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13027 dof->dofh_loadsz != hdr.dofh_loadsz) {
13028 kmem_free(dof, hdr.dofh_loadsz);
13037 static __inline uchar_t
13038 dtrace_dof_char(char c) {
13057 return (c - 'A' + 10);
13064 return (c - 'a' + 10);
13066 /* Should not reach here. */
13072 dtrace_dof_property(const char *name)
13076 unsigned int len, i;
13081 * Unfortunately, array of values in .conf files are always (and
13082 * only) interpreted to be integer arrays. We must read our DOF
13083 * as an integer array, and then squeeze it into a byte array.
13085 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13086 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13089 for (i = 0; i < len; i++)
13090 buf[i] = (uchar_t)(((int *)buf)[i]);
13092 if (len < sizeof (dof_hdr_t)) {
13093 ddi_prop_free(buf);
13094 dtrace_dof_error(NULL, "truncated header");
13098 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13099 ddi_prop_free(buf);
13100 dtrace_dof_error(NULL, "truncated DOF");
13104 if (loadsz >= dtrace_dof_maxsize) {
13105 ddi_prop_free(buf);
13106 dtrace_dof_error(NULL, "oversized DOF");
13110 dof = kmem_alloc(loadsz, KM_SLEEP);
13111 bcopy(buf, dof, loadsz);
13112 ddi_prop_free(buf);
13117 if ((p_env = getenv(name)) == NULL)
13120 len = strlen(p_env) / 2;
13122 buf = kmem_alloc(len, KM_SLEEP);
13124 dof = (dof_hdr_t *) buf;
13128 for (i = 0; i < len; i++) {
13129 buf[i] = (dtrace_dof_char(p[0]) << 4) |
13130 dtrace_dof_char(p[1]);
13136 if (len < sizeof (dof_hdr_t)) {
13138 dtrace_dof_error(NULL, "truncated header");
13142 if (len < (loadsz = dof->dofh_loadsz)) {
13144 dtrace_dof_error(NULL, "truncated DOF");
13148 if (loadsz >= dtrace_dof_maxsize) {
13150 dtrace_dof_error(NULL, "oversized DOF");
13159 dtrace_dof_destroy(dof_hdr_t *dof)
13161 kmem_free(dof, dof->dofh_loadsz);
13165 * Return the dof_sec_t pointer corresponding to a given section index. If the
13166 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
13167 * a type other than DOF_SECT_NONE is specified, the header is checked against
13168 * this type and NULL is returned if the types do not match.
13171 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13173 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13174 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13176 if (i >= dof->dofh_secnum) {
13177 dtrace_dof_error(dof, "referenced section index is invalid");
13181 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13182 dtrace_dof_error(dof, "referenced section is not loadable");
13186 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13187 dtrace_dof_error(dof, "referenced section is the wrong type");
13194 static dtrace_probedesc_t *
13195 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13197 dof_probedesc_t *probe;
13199 uintptr_t daddr = (uintptr_t)dof;
13203 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13204 dtrace_dof_error(dof, "invalid probe section");
13208 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13209 dtrace_dof_error(dof, "bad alignment in probe description");
13213 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13214 dtrace_dof_error(dof, "truncated probe description");
13218 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13219 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13221 if (strtab == NULL)
13224 str = daddr + strtab->dofs_offset;
13225 size = strtab->dofs_size;
13227 if (probe->dofp_provider >= strtab->dofs_size) {
13228 dtrace_dof_error(dof, "corrupt probe provider");
13232 (void) strncpy(desc->dtpd_provider,
13233 (char *)(str + probe->dofp_provider),
13234 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13236 if (probe->dofp_mod >= strtab->dofs_size) {
13237 dtrace_dof_error(dof, "corrupt probe module");
13241 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13242 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13244 if (probe->dofp_func >= strtab->dofs_size) {
13245 dtrace_dof_error(dof, "corrupt probe function");
13249 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13250 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13252 if (probe->dofp_name >= strtab->dofs_size) {
13253 dtrace_dof_error(dof, "corrupt probe name");
13257 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13258 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13263 static dtrace_difo_t *
13264 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13269 dof_difohdr_t *dofd;
13270 uintptr_t daddr = (uintptr_t)dof;
13271 size_t max = dtrace_difo_maxsize;
13274 static const struct {
13282 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13283 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13284 sizeof (dif_instr_t), "multiple DIF sections" },
13286 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13287 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13288 sizeof (uint64_t), "multiple integer tables" },
13290 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13291 offsetof(dtrace_difo_t, dtdo_strlen), 0,
13292 sizeof (char), "multiple string tables" },
13294 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13295 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13296 sizeof (uint_t), "multiple variable tables" },
13298 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13301 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13302 dtrace_dof_error(dof, "invalid DIFO header section");
13306 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13307 dtrace_dof_error(dof, "bad alignment in DIFO header");
13311 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13312 sec->dofs_size % sizeof (dof_secidx_t)) {
13313 dtrace_dof_error(dof, "bad size in DIFO header");
13317 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13318 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13320 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13321 dp->dtdo_rtype = dofd->dofd_rtype;
13323 for (l = 0; l < n; l++) {
13328 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13329 dofd->dofd_links[l])) == NULL)
13330 goto err; /* invalid section link */
13332 if (ttl + subsec->dofs_size > max) {
13333 dtrace_dof_error(dof, "exceeds maximum size");
13337 ttl += subsec->dofs_size;
13339 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13340 if (subsec->dofs_type != difo[i].section)
13343 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13344 dtrace_dof_error(dof, "section not loaded");
13348 if (subsec->dofs_align != difo[i].align) {
13349 dtrace_dof_error(dof, "bad alignment");
13353 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13354 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13356 if (*bufp != NULL) {
13357 dtrace_dof_error(dof, difo[i].msg);
13361 if (difo[i].entsize != subsec->dofs_entsize) {
13362 dtrace_dof_error(dof, "entry size mismatch");
13366 if (subsec->dofs_entsize != 0 &&
13367 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13368 dtrace_dof_error(dof, "corrupt entry size");
13372 *lenp = subsec->dofs_size;
13373 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13374 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13375 *bufp, subsec->dofs_size);
13377 if (subsec->dofs_entsize != 0)
13378 *lenp /= subsec->dofs_entsize;
13384 * If we encounter a loadable DIFO sub-section that is not
13385 * known to us, assume this is a broken program and fail.
13387 if (difo[i].section == DOF_SECT_NONE &&
13388 (subsec->dofs_flags & DOF_SECF_LOAD)) {
13389 dtrace_dof_error(dof, "unrecognized DIFO subsection");
13394 if (dp->dtdo_buf == NULL) {
13396 * We can't have a DIF object without DIF text.
13398 dtrace_dof_error(dof, "missing DIF text");
13403 * Before we validate the DIF object, run through the variable table
13404 * looking for the strings -- if any of their size are under, we'll set
13405 * their size to be the system-wide default string size. Note that
13406 * this should _not_ happen if the "strsize" option has been set --
13407 * in this case, the compiler should have set the size to reflect the
13408 * setting of the option.
13410 for (i = 0; i < dp->dtdo_varlen; i++) {
13411 dtrace_difv_t *v = &dp->dtdo_vartab[i];
13412 dtrace_diftype_t *t = &v->dtdv_type;
13414 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13417 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13418 t->dtdt_size = dtrace_strsize_default;
13421 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13424 dtrace_difo_init(dp, vstate);
13428 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13429 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13430 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13431 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13433 kmem_free(dp, sizeof (dtrace_difo_t));
13437 static dtrace_predicate_t *
13438 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13443 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13446 return (dtrace_predicate_create(dp));
13449 static dtrace_actdesc_t *
13450 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13453 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13454 dof_actdesc_t *desc;
13455 dof_sec_t *difosec;
13457 uintptr_t daddr = (uintptr_t)dof;
13459 dtrace_actkind_t kind;
13461 if (sec->dofs_type != DOF_SECT_ACTDESC) {
13462 dtrace_dof_error(dof, "invalid action section");
13466 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13467 dtrace_dof_error(dof, "truncated action description");
13471 if (sec->dofs_align != sizeof (uint64_t)) {
13472 dtrace_dof_error(dof, "bad alignment in action description");
13476 if (sec->dofs_size < sec->dofs_entsize) {
13477 dtrace_dof_error(dof, "section entry size exceeds total size");
13481 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13482 dtrace_dof_error(dof, "bad entry size in action description");
13486 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13487 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13491 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13492 desc = (dof_actdesc_t *)(daddr +
13493 (uintptr_t)sec->dofs_offset + offs);
13494 kind = (dtrace_actkind_t)desc->dofa_kind;
13496 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13497 (kind != DTRACEACT_PRINTA ||
13498 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13499 (kind == DTRACEACT_DIFEXPR &&
13500 desc->dofa_strtab != DOF_SECIDX_NONE)) {
13506 * The argument to these actions is an index into the
13507 * DOF string table. For printf()-like actions, this
13508 * is the format string. For print(), this is the
13509 * CTF type of the expression result.
13511 if ((strtab = dtrace_dof_sect(dof,
13512 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13515 str = (char *)((uintptr_t)dof +
13516 (uintptr_t)strtab->dofs_offset);
13518 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13519 if (str[i] == '\0')
13523 if (i >= strtab->dofs_size) {
13524 dtrace_dof_error(dof, "bogus format string");
13528 if (i == desc->dofa_arg) {
13529 dtrace_dof_error(dof, "empty format string");
13533 i -= desc->dofa_arg;
13534 fmt = kmem_alloc(i + 1, KM_SLEEP);
13535 bcopy(&str[desc->dofa_arg], fmt, i + 1);
13536 arg = (uint64_t)(uintptr_t)fmt;
13538 if (kind == DTRACEACT_PRINTA) {
13539 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13542 arg = desc->dofa_arg;
13546 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13547 desc->dofa_uarg, arg);
13549 if (last != NULL) {
13550 last->dtad_next = act;
13557 if (desc->dofa_difo == DOF_SECIDX_NONE)
13560 if ((difosec = dtrace_dof_sect(dof,
13561 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13564 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13566 if (act->dtad_difo == NULL)
13570 ASSERT(first != NULL);
13574 for (act = first; act != NULL; act = next) {
13575 next = act->dtad_next;
13576 dtrace_actdesc_release(act, vstate);
13582 static dtrace_ecbdesc_t *
13583 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13586 dtrace_ecbdesc_t *ep;
13587 dof_ecbdesc_t *ecb;
13588 dtrace_probedesc_t *desc;
13589 dtrace_predicate_t *pred = NULL;
13591 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13592 dtrace_dof_error(dof, "truncated ECB description");
13596 if (sec->dofs_align != sizeof (uint64_t)) {
13597 dtrace_dof_error(dof, "bad alignment in ECB description");
13601 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13602 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13607 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13608 ep->dted_uarg = ecb->dofe_uarg;
13609 desc = &ep->dted_probe;
13611 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13614 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13615 if ((sec = dtrace_dof_sect(dof,
13616 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13619 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13622 ep->dted_pred.dtpdd_predicate = pred;
13625 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13626 if ((sec = dtrace_dof_sect(dof,
13627 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13630 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13632 if (ep->dted_action == NULL)
13640 dtrace_predicate_release(pred, vstate);
13641 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13646 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13647 * specified DOF. At present, this amounts to simply adding 'ubase' to the
13648 * site of any user SETX relocations to account for load object base address.
13649 * In the future, if we need other relocations, this function can be extended.
13652 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13654 uintptr_t daddr = (uintptr_t)dof;
13655 dof_relohdr_t *dofr =
13656 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13657 dof_sec_t *ss, *rs, *ts;
13661 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13662 sec->dofs_align != sizeof (dof_secidx_t)) {
13663 dtrace_dof_error(dof, "invalid relocation header");
13667 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13668 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13669 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13671 if (ss == NULL || rs == NULL || ts == NULL)
13672 return (-1); /* dtrace_dof_error() has been called already */
13674 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13675 rs->dofs_align != sizeof (uint64_t)) {
13676 dtrace_dof_error(dof, "invalid relocation section");
13680 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13681 n = rs->dofs_size / rs->dofs_entsize;
13683 for (i = 0; i < n; i++) {
13684 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13686 switch (r->dofr_type) {
13687 case DOF_RELO_NONE:
13689 case DOF_RELO_SETX:
13690 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13691 sizeof (uint64_t) > ts->dofs_size) {
13692 dtrace_dof_error(dof, "bad relocation offset");
13696 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13697 dtrace_dof_error(dof, "misaligned setx relo");
13701 *(uint64_t *)taddr += ubase;
13704 dtrace_dof_error(dof, "invalid relocation type");
13708 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13715 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13716 * header: it should be at the front of a memory region that is at least
13717 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13718 * size. It need not be validated in any other way.
13721 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13722 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13724 uint64_t len = dof->dofh_loadsz, seclen;
13725 uintptr_t daddr = (uintptr_t)dof;
13726 dtrace_ecbdesc_t *ep;
13727 dtrace_enabling_t *enab;
13730 ASSERT(MUTEX_HELD(&dtrace_lock));
13731 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13734 * Check the DOF header identification bytes. In addition to checking
13735 * valid settings, we also verify that unused bits/bytes are zeroed so
13736 * we can use them later without fear of regressing existing binaries.
13738 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13739 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13740 dtrace_dof_error(dof, "DOF magic string mismatch");
13744 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13745 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13746 dtrace_dof_error(dof, "DOF has invalid data model");
13750 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13751 dtrace_dof_error(dof, "DOF encoding mismatch");
13755 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13756 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13757 dtrace_dof_error(dof, "DOF version mismatch");
13761 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13762 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13766 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13767 dtrace_dof_error(dof, "DOF uses too many integer registers");
13771 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13772 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13776 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13777 if (dof->dofh_ident[i] != 0) {
13778 dtrace_dof_error(dof, "DOF has invalid ident byte set");
13783 if (dof->dofh_flags & ~DOF_FL_VALID) {
13784 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13788 if (dof->dofh_secsize == 0) {
13789 dtrace_dof_error(dof, "zero section header size");
13794 * Check that the section headers don't exceed the amount of DOF
13795 * data. Note that we cast the section size and number of sections
13796 * to uint64_t's to prevent possible overflow in the multiplication.
13798 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13800 if (dof->dofh_secoff > len || seclen > len ||
13801 dof->dofh_secoff + seclen > len) {
13802 dtrace_dof_error(dof, "truncated section headers");
13806 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13807 dtrace_dof_error(dof, "misaligned section headers");
13811 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13812 dtrace_dof_error(dof, "misaligned section size");
13817 * Take an initial pass through the section headers to be sure that
13818 * the headers don't have stray offsets. If the 'noprobes' flag is
13819 * set, do not permit sections relating to providers, probes, or args.
13821 for (i = 0; i < dof->dofh_secnum; i++) {
13822 dof_sec_t *sec = (dof_sec_t *)(daddr +
13823 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13826 switch (sec->dofs_type) {
13827 case DOF_SECT_PROVIDER:
13828 case DOF_SECT_PROBES:
13829 case DOF_SECT_PRARGS:
13830 case DOF_SECT_PROFFS:
13831 dtrace_dof_error(dof, "illegal sections "
13837 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13838 !(sec->dofs_flags & DOF_SECF_LOAD)) {
13839 dtrace_dof_error(dof, "loadable section with load "
13844 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13845 continue; /* just ignore non-loadable sections */
13847 if (!ISP2(sec->dofs_align)) {
13848 dtrace_dof_error(dof, "bad section alignment");
13852 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13853 dtrace_dof_error(dof, "misaligned section");
13857 if (sec->dofs_offset > len || sec->dofs_size > len ||
13858 sec->dofs_offset + sec->dofs_size > len) {
13859 dtrace_dof_error(dof, "corrupt section header");
13863 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13864 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13865 dtrace_dof_error(dof, "non-terminating string table");
13871 * Take a second pass through the sections and locate and perform any
13872 * relocations that are present. We do this after the first pass to
13873 * be sure that all sections have had their headers validated.
13875 for (i = 0; i < dof->dofh_secnum; i++) {
13876 dof_sec_t *sec = (dof_sec_t *)(daddr +
13877 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13879 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13880 continue; /* skip sections that are not loadable */
13882 switch (sec->dofs_type) {
13883 case DOF_SECT_URELHDR:
13884 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13890 if ((enab = *enabp) == NULL)
13891 enab = *enabp = dtrace_enabling_create(vstate);
13893 for (i = 0; i < dof->dofh_secnum; i++) {
13894 dof_sec_t *sec = (dof_sec_t *)(daddr +
13895 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13897 if (sec->dofs_type != DOF_SECT_ECBDESC)
13900 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13901 dtrace_enabling_destroy(enab);
13906 dtrace_enabling_add(enab, ep);
13913 * Process DOF for any options. This routine assumes that the DOF has been
13914 * at least processed by dtrace_dof_slurp().
13917 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13922 dof_optdesc_t *desc;
13924 for (i = 0; i < dof->dofh_secnum; i++) {
13925 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13926 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13928 if (sec->dofs_type != DOF_SECT_OPTDESC)
13931 if (sec->dofs_align != sizeof (uint64_t)) {
13932 dtrace_dof_error(dof, "bad alignment in "
13933 "option description");
13937 if ((entsize = sec->dofs_entsize) == 0) {
13938 dtrace_dof_error(dof, "zeroed option entry size");
13942 if (entsize < sizeof (dof_optdesc_t)) {
13943 dtrace_dof_error(dof, "bad option entry size");
13947 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13948 desc = (dof_optdesc_t *)((uintptr_t)dof +
13949 (uintptr_t)sec->dofs_offset + offs);
13951 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13952 dtrace_dof_error(dof, "non-zero option string");
13956 if (desc->dofo_value == DTRACEOPT_UNSET) {
13957 dtrace_dof_error(dof, "unset option");
13961 if ((rval = dtrace_state_option(state,
13962 desc->dofo_option, desc->dofo_value)) != 0) {
13963 dtrace_dof_error(dof, "rejected option");
13973 * DTrace Consumer State Functions
13976 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13978 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13981 dtrace_dynvar_t *dvar, *next, *start;
13984 ASSERT(MUTEX_HELD(&dtrace_lock));
13985 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13987 bzero(dstate, sizeof (dtrace_dstate_t));
13989 if ((dstate->dtds_chunksize = chunksize) == 0)
13990 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13992 VERIFY(dstate->dtds_chunksize < LONG_MAX);
13994 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13997 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14000 dstate->dtds_size = size;
14001 dstate->dtds_base = base;
14002 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14003 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14005 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14007 if (hashsize != 1 && (hashsize & 1))
14010 dstate->dtds_hashsize = hashsize;
14011 dstate->dtds_hash = dstate->dtds_base;
14014 * Set all of our hash buckets to point to the single sink, and (if
14015 * it hasn't already been set), set the sink's hash value to be the
14016 * sink sentinel value. The sink is needed for dynamic variable
14017 * lookups to know that they have iterated over an entire, valid hash
14020 for (i = 0; i < hashsize; i++)
14021 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14023 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14024 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14027 * Determine number of active CPUs. Divide free list evenly among
14030 start = (dtrace_dynvar_t *)
14031 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14032 limit = (uintptr_t)base + size;
14034 VERIFY((uintptr_t)start < limit);
14035 VERIFY((uintptr_t)start >= (uintptr_t)base);
14037 maxper = (limit - (uintptr_t)start) / NCPU;
14038 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14043 for (i = 0; i < NCPU; i++) {
14045 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14048 * If we don't even have enough chunks to make it once through
14049 * NCPUs, we're just going to allocate everything to the first
14050 * CPU. And if we're on the last CPU, we're going to allocate
14051 * whatever is left over. In either case, we set the limit to
14052 * be the limit of the dynamic variable space.
14054 if (maxper == 0 || i == NCPU - 1) {
14055 limit = (uintptr_t)base + size;
14058 limit = (uintptr_t)start + maxper;
14059 start = (dtrace_dynvar_t *)limit;
14062 VERIFY(limit <= (uintptr_t)base + size);
14065 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14066 dstate->dtds_chunksize);
14068 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14071 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14072 (uintptr_t)dvar <= (uintptr_t)base + size);
14073 dvar->dtdv_next = next;
14085 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14087 ASSERT(MUTEX_HELD(&cpu_lock));
14089 if (dstate->dtds_base == NULL)
14092 kmem_free(dstate->dtds_base, dstate->dtds_size);
14093 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14097 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14100 * Logical XOR, where are you?
14102 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14104 if (vstate->dtvs_nglobals > 0) {
14105 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14106 sizeof (dtrace_statvar_t *));
14109 if (vstate->dtvs_ntlocals > 0) {
14110 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14111 sizeof (dtrace_difv_t));
14114 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14116 if (vstate->dtvs_nlocals > 0) {
14117 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14118 sizeof (dtrace_statvar_t *));
14124 dtrace_state_clean(dtrace_state_t *state)
14126 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14129 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14130 dtrace_speculation_clean(state);
14134 dtrace_state_deadman(dtrace_state_t *state)
14140 now = dtrace_gethrtime();
14142 if (state != dtrace_anon.dta_state &&
14143 now - state->dts_laststatus >= dtrace_deadman_user)
14147 * We must be sure that dts_alive never appears to be less than the
14148 * value upon entry to dtrace_state_deadman(), and because we lack a
14149 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14150 * store INT64_MAX to it, followed by a memory barrier, followed by
14151 * the new value. This assures that dts_alive never appears to be
14152 * less than its true value, regardless of the order in which the
14153 * stores to the underlying storage are issued.
14155 state->dts_alive = INT64_MAX;
14156 dtrace_membar_producer();
14157 state->dts_alive = now;
14159 #else /* !illumos */
14161 dtrace_state_clean(void *arg)
14163 dtrace_state_t *state = arg;
14164 dtrace_optval_t *opt = state->dts_options;
14166 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14169 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14170 dtrace_speculation_clean(state);
14172 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14173 dtrace_state_clean, state);
14177 dtrace_state_deadman(void *arg)
14179 dtrace_state_t *state = arg;
14184 dtrace_debug_output();
14186 now = dtrace_gethrtime();
14188 if (state != dtrace_anon.dta_state &&
14189 now - state->dts_laststatus >= dtrace_deadman_user)
14193 * We must be sure that dts_alive never appears to be less than the
14194 * value upon entry to dtrace_state_deadman(), and because we lack a
14195 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14196 * store INT64_MAX to it, followed by a memory barrier, followed by
14197 * the new value. This assures that dts_alive never appears to be
14198 * less than its true value, regardless of the order in which the
14199 * stores to the underlying storage are issued.
14201 state->dts_alive = INT64_MAX;
14202 dtrace_membar_producer();
14203 state->dts_alive = now;
14205 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14206 dtrace_state_deadman, state);
14208 #endif /* illumos */
14210 static dtrace_state_t *
14212 dtrace_state_create(dev_t *devp, cred_t *cr)
14214 dtrace_state_create(struct cdev *dev)
14225 dtrace_state_t *state;
14226 dtrace_optval_t *opt;
14227 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14229 ASSERT(MUTEX_HELD(&dtrace_lock));
14230 ASSERT(MUTEX_HELD(&cpu_lock));
14233 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14234 VM_BESTFIT | VM_SLEEP);
14236 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14237 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14241 state = ddi_get_soft_state(dtrace_softstate, minor);
14248 /* Allocate memory for the state. */
14249 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14252 state->dts_epid = DTRACE_EPIDNONE + 1;
14254 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14256 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14257 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14259 if (devp != NULL) {
14260 major = getemajor(*devp);
14262 major = ddi_driver_major(dtrace_devi);
14265 state->dts_dev = makedevice(major, minor);
14268 *devp = state->dts_dev;
14270 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14271 state->dts_dev = dev;
14275 * We allocate NCPU buffers. On the one hand, this can be quite
14276 * a bit of memory per instance (nearly 36K on a Starcat). On the
14277 * other hand, it saves an additional memory reference in the probe
14280 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14281 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14284 state->dts_cleaner = CYCLIC_NONE;
14285 state->dts_deadman = CYCLIC_NONE;
14287 callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
14288 callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
14290 state->dts_vstate.dtvs_state = state;
14292 for (i = 0; i < DTRACEOPT_MAX; i++)
14293 state->dts_options[i] = DTRACEOPT_UNSET;
14296 * Set the default options.
14298 opt = state->dts_options;
14299 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14300 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14301 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14302 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14303 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14304 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14305 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14306 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14307 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14308 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14309 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14310 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14311 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14312 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14314 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14317 * Depending on the user credentials, we set flag bits which alter probe
14318 * visibility or the amount of destructiveness allowed. In the case of
14319 * actual anonymous tracing, or the possession of all privileges, all of
14320 * the normal checks are bypassed.
14322 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14323 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14324 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14327 * Set up the credentials for this instantiation. We take a
14328 * hold on the credential to prevent it from disappearing on
14329 * us; this in turn prevents the zone_t referenced by this
14330 * credential from disappearing. This means that we can
14331 * examine the credential and the zone from probe context.
14334 state->dts_cred.dcr_cred = cr;
14337 * CRA_PROC means "we have *some* privilege for dtrace" and
14338 * unlocks the use of variables like pid, zonename, etc.
14340 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14341 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14342 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14346 * dtrace_user allows use of syscall and profile providers.
14347 * If the user also has proc_owner and/or proc_zone, we
14348 * extend the scope to include additional visibility and
14349 * destructive power.
14351 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14352 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14353 state->dts_cred.dcr_visible |=
14354 DTRACE_CRV_ALLPROC;
14356 state->dts_cred.dcr_action |=
14357 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14360 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14361 state->dts_cred.dcr_visible |=
14362 DTRACE_CRV_ALLZONE;
14364 state->dts_cred.dcr_action |=
14365 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14369 * If we have all privs in whatever zone this is,
14370 * we can do destructive things to processes which
14371 * have altered credentials.
14374 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14375 cr->cr_zone->zone_privset)) {
14376 state->dts_cred.dcr_action |=
14377 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14383 * Holding the dtrace_kernel privilege also implies that
14384 * the user has the dtrace_user privilege from a visibility
14385 * perspective. But without further privileges, some
14386 * destructive actions are not available.
14388 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14390 * Make all probes in all zones visible. However,
14391 * this doesn't mean that all actions become available
14394 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14395 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14397 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14400 * Holding proc_owner means that destructive actions
14401 * for *this* zone are allowed.
14403 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14404 state->dts_cred.dcr_action |=
14405 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14408 * Holding proc_zone means that destructive actions
14409 * for this user/group ID in all zones is allowed.
14411 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14412 state->dts_cred.dcr_action |=
14413 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14417 * If we have all privs in whatever zone this is,
14418 * we can do destructive things to processes which
14419 * have altered credentials.
14421 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14422 cr->cr_zone->zone_privset)) {
14423 state->dts_cred.dcr_action |=
14424 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14430 * Holding the dtrace_proc privilege gives control over fasttrap
14431 * and pid providers. We need to grant wider destructive
14432 * privileges in the event that the user has proc_owner and/or
14435 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14436 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14437 state->dts_cred.dcr_action |=
14438 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14440 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14441 state->dts_cred.dcr_action |=
14442 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14450 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14452 dtrace_optval_t *opt = state->dts_options, size;
14453 processorid_t cpu = 0;;
14454 int flags = 0, rval, factor, divisor = 1;
14456 ASSERT(MUTEX_HELD(&dtrace_lock));
14457 ASSERT(MUTEX_HELD(&cpu_lock));
14458 ASSERT(which < DTRACEOPT_MAX);
14459 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14460 (state == dtrace_anon.dta_state &&
14461 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14463 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14466 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14467 cpu = opt[DTRACEOPT_CPU];
14469 if (which == DTRACEOPT_SPECSIZE)
14470 flags |= DTRACEBUF_NOSWITCH;
14472 if (which == DTRACEOPT_BUFSIZE) {
14473 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14474 flags |= DTRACEBUF_RING;
14476 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14477 flags |= DTRACEBUF_FILL;
14479 if (state != dtrace_anon.dta_state ||
14480 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14481 flags |= DTRACEBUF_INACTIVE;
14484 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14486 * The size must be 8-byte aligned. If the size is not 8-byte
14487 * aligned, drop it down by the difference.
14489 if (size & (sizeof (uint64_t) - 1))
14490 size -= size & (sizeof (uint64_t) - 1);
14492 if (size < state->dts_reserve) {
14494 * Buffers always must be large enough to accommodate
14495 * their prereserved space. We return E2BIG instead
14496 * of ENOMEM in this case to allow for user-level
14497 * software to differentiate the cases.
14502 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14504 if (rval != ENOMEM) {
14509 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14512 for (divisor = 2; divisor < factor; divisor <<= 1)
14520 dtrace_state_buffers(dtrace_state_t *state)
14522 dtrace_speculation_t *spec = state->dts_speculations;
14525 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14526 DTRACEOPT_BUFSIZE)) != 0)
14529 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14530 DTRACEOPT_AGGSIZE)) != 0)
14533 for (i = 0; i < state->dts_nspeculations; i++) {
14534 if ((rval = dtrace_state_buffer(state,
14535 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14543 dtrace_state_prereserve(dtrace_state_t *state)
14546 dtrace_probe_t *probe;
14548 state->dts_reserve = 0;
14550 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14554 * If our buffer policy is a "fill" buffer policy, we need to set the
14555 * prereserved space to be the space required by the END probes.
14557 probe = dtrace_probes[dtrace_probeid_end - 1];
14558 ASSERT(probe != NULL);
14560 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14561 if (ecb->dte_state != state)
14564 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14569 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14571 dtrace_optval_t *opt = state->dts_options, sz, nspec;
14572 dtrace_speculation_t *spec;
14573 dtrace_buffer_t *buf;
14575 cyc_handler_t hdlr;
14578 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14579 dtrace_icookie_t cookie;
14581 mutex_enter(&cpu_lock);
14582 mutex_enter(&dtrace_lock);
14584 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14590 * Before we can perform any checks, we must prime all of the
14591 * retained enablings that correspond to this state.
14593 dtrace_enabling_prime(state);
14595 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14600 dtrace_state_prereserve(state);
14603 * Now we want to do is try to allocate our speculations.
14604 * We do not automatically resize the number of speculations; if
14605 * this fails, we will fail the operation.
14607 nspec = opt[DTRACEOPT_NSPEC];
14608 ASSERT(nspec != DTRACEOPT_UNSET);
14610 if (nspec > INT_MAX) {
14615 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14616 KM_NOSLEEP | KM_NORMALPRI);
14618 if (spec == NULL) {
14623 state->dts_speculations = spec;
14624 state->dts_nspeculations = (int)nspec;
14626 for (i = 0; i < nspec; i++) {
14627 if ((buf = kmem_zalloc(bufsize,
14628 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
14633 spec[i].dtsp_buffer = buf;
14636 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14637 if (dtrace_anon.dta_state == NULL) {
14642 if (state->dts_necbs != 0) {
14647 state->dts_anon = dtrace_anon_grab();
14648 ASSERT(state->dts_anon != NULL);
14649 state = state->dts_anon;
14652 * We want "grabanon" to be set in the grabbed state, so we'll
14653 * copy that option value from the grabbing state into the
14656 state->dts_options[DTRACEOPT_GRABANON] =
14657 opt[DTRACEOPT_GRABANON];
14659 *cpu = dtrace_anon.dta_beganon;
14662 * If the anonymous state is active (as it almost certainly
14663 * is if the anonymous enabling ultimately matched anything),
14664 * we don't allow any further option processing -- but we
14665 * don't return failure.
14667 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14671 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14672 opt[DTRACEOPT_AGGSIZE] != 0) {
14673 if (state->dts_aggregations == NULL) {
14675 * We're not going to create an aggregation buffer
14676 * because we don't have any ECBs that contain
14677 * aggregations -- set this option to 0.
14679 opt[DTRACEOPT_AGGSIZE] = 0;
14682 * If we have an aggregation buffer, we must also have
14683 * a buffer to use as scratch.
14685 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14686 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14687 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14692 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14693 opt[DTRACEOPT_SPECSIZE] != 0) {
14694 if (!state->dts_speculates) {
14696 * We're not going to create speculation buffers
14697 * because we don't have any ECBs that actually
14698 * speculate -- set the speculation size to 0.
14700 opt[DTRACEOPT_SPECSIZE] = 0;
14705 * The bare minimum size for any buffer that we're actually going to
14706 * do anything to is sizeof (uint64_t).
14708 sz = sizeof (uint64_t);
14710 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14711 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14712 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14714 * A buffer size has been explicitly set to 0 (or to a size
14715 * that will be adjusted to 0) and we need the space -- we
14716 * need to return failure. We return ENOSPC to differentiate
14717 * it from failing to allocate a buffer due to failure to meet
14718 * the reserve (for which we return E2BIG).
14724 if ((rval = dtrace_state_buffers(state)) != 0)
14727 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14728 sz = dtrace_dstate_defsize;
14731 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14736 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14738 } while (sz >>= 1);
14740 opt[DTRACEOPT_DYNVARSIZE] = sz;
14745 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14746 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14748 if (opt[DTRACEOPT_CLEANRATE] == 0)
14749 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14751 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14752 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14754 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14755 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14757 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14759 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14760 hdlr.cyh_arg = state;
14761 hdlr.cyh_level = CY_LOW_LEVEL;
14764 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14766 state->dts_cleaner = cyclic_add(&hdlr, &when);
14768 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14769 hdlr.cyh_arg = state;
14770 hdlr.cyh_level = CY_LOW_LEVEL;
14773 when.cyt_interval = dtrace_deadman_interval;
14775 state->dts_deadman = cyclic_add(&hdlr, &when);
14777 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14778 dtrace_state_clean, state);
14779 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14780 dtrace_state_deadman, state);
14783 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14786 if (state->dts_getf != 0 &&
14787 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14789 * We don't have kernel privs but we have at least one call
14790 * to getf(); we need to bump our zone's count, and (if
14791 * this is the first enabling to have an unprivileged call
14792 * to getf()) we need to hook into closef().
14794 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14796 if (dtrace_getf++ == 0) {
14797 ASSERT(dtrace_closef == NULL);
14798 dtrace_closef = dtrace_getf_barrier;
14804 * Now it's time to actually fire the BEGIN probe. We need to disable
14805 * interrupts here both to record the CPU on which we fired the BEGIN
14806 * probe (the data from this CPU will be processed first at user
14807 * level) and to manually activate the buffer for this CPU.
14809 cookie = dtrace_interrupt_disable();
14811 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14812 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14814 dtrace_probe(dtrace_probeid_begin,
14815 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14816 dtrace_interrupt_enable(cookie);
14818 * We may have had an exit action from a BEGIN probe; only change our
14819 * state to ACTIVE if we're still in WARMUP.
14821 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14822 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14824 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14825 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14828 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14829 * want each CPU to transition its principal buffer out of the
14830 * INACTIVE state. Doing this assures that no CPU will suddenly begin
14831 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14832 * atomically transition from processing none of a state's ECBs to
14833 * processing all of them.
14835 dtrace_xcall(DTRACE_CPUALL,
14836 (dtrace_xcall_t)dtrace_buffer_activate, state);
14840 dtrace_buffer_free(state->dts_buffer);
14841 dtrace_buffer_free(state->dts_aggbuffer);
14843 if ((nspec = state->dts_nspeculations) == 0) {
14844 ASSERT(state->dts_speculations == NULL);
14848 spec = state->dts_speculations;
14849 ASSERT(spec != NULL);
14851 for (i = 0; i < state->dts_nspeculations; i++) {
14852 if ((buf = spec[i].dtsp_buffer) == NULL)
14855 dtrace_buffer_free(buf);
14856 kmem_free(buf, bufsize);
14859 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14860 state->dts_nspeculations = 0;
14861 state->dts_speculations = NULL;
14864 mutex_exit(&dtrace_lock);
14865 mutex_exit(&cpu_lock);
14871 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14873 dtrace_icookie_t cookie;
14875 ASSERT(MUTEX_HELD(&dtrace_lock));
14877 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14878 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14882 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14883 * to be sure that every CPU has seen it. See below for the details
14884 * on why this is done.
14886 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14890 * By this point, it is impossible for any CPU to be still processing
14891 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
14892 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14893 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
14894 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14895 * iff we're in the END probe.
14897 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14899 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14902 * Finally, we can release the reserve and call the END probe. We
14903 * disable interrupts across calling the END probe to allow us to
14904 * return the CPU on which we actually called the END probe. This
14905 * allows user-land to be sure that this CPU's principal buffer is
14908 state->dts_reserve = 0;
14910 cookie = dtrace_interrupt_disable();
14912 dtrace_probe(dtrace_probeid_end,
14913 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14914 dtrace_interrupt_enable(cookie);
14916 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14920 if (state->dts_getf != 0 &&
14921 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14923 * We don't have kernel privs but we have at least one call
14924 * to getf(); we need to lower our zone's count, and (if
14925 * this is the last enabling to have an unprivileged call
14926 * to getf()) we need to clear the closef() hook.
14928 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14929 ASSERT(dtrace_closef == dtrace_getf_barrier);
14930 ASSERT(dtrace_getf > 0);
14932 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14934 if (--dtrace_getf == 0)
14935 dtrace_closef = NULL;
14943 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14944 dtrace_optval_t val)
14946 ASSERT(MUTEX_HELD(&dtrace_lock));
14948 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14951 if (option >= DTRACEOPT_MAX)
14954 if (option != DTRACEOPT_CPU && val < 0)
14958 case DTRACEOPT_DESTRUCTIVE:
14959 if (dtrace_destructive_disallow)
14962 state->dts_cred.dcr_destructive = 1;
14965 case DTRACEOPT_BUFSIZE:
14966 case DTRACEOPT_DYNVARSIZE:
14967 case DTRACEOPT_AGGSIZE:
14968 case DTRACEOPT_SPECSIZE:
14969 case DTRACEOPT_STRSIZE:
14973 if (val >= LONG_MAX) {
14975 * If this is an otherwise negative value, set it to
14976 * the highest multiple of 128m less than LONG_MAX.
14977 * Technically, we're adjusting the size without
14978 * regard to the buffer resizing policy, but in fact,
14979 * this has no effect -- if we set the buffer size to
14980 * ~LONG_MAX and the buffer policy is ultimately set to
14981 * be "manual", the buffer allocation is guaranteed to
14982 * fail, if only because the allocation requires two
14983 * buffers. (We set the the size to the highest
14984 * multiple of 128m because it ensures that the size
14985 * will remain a multiple of a megabyte when
14986 * repeatedly halved -- all the way down to 15m.)
14988 val = LONG_MAX - (1 << 27) + 1;
14992 state->dts_options[option] = val;
14998 dtrace_state_destroy(dtrace_state_t *state)
15001 dtrace_vstate_t *vstate = &state->dts_vstate;
15003 minor_t minor = getminor(state->dts_dev);
15005 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15006 dtrace_speculation_t *spec = state->dts_speculations;
15007 int nspec = state->dts_nspeculations;
15010 ASSERT(MUTEX_HELD(&dtrace_lock));
15011 ASSERT(MUTEX_HELD(&cpu_lock));
15014 * First, retract any retained enablings for this state.
15016 dtrace_enabling_retract(state);
15017 ASSERT(state->dts_nretained == 0);
15019 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15020 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15022 * We have managed to come into dtrace_state_destroy() on a
15023 * hot enabling -- almost certainly because of a disorderly
15024 * shutdown of a consumer. (That is, a consumer that is
15025 * exiting without having called dtrace_stop().) In this case,
15026 * we're going to set our activity to be KILLED, and then
15027 * issue a sync to be sure that everyone is out of probe
15028 * context before we start blowing away ECBs.
15030 state->dts_activity = DTRACE_ACTIVITY_KILLED;
15035 * Release the credential hold we took in dtrace_state_create().
15037 if (state->dts_cred.dcr_cred != NULL)
15038 crfree(state->dts_cred.dcr_cred);
15041 * Now we can safely disable and destroy any enabled probes. Because
15042 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15043 * (especially if they're all enabled), we take two passes through the
15044 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15045 * in the second we disable whatever is left over.
15047 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15048 for (i = 0; i < state->dts_necbs; i++) {
15049 if ((ecb = state->dts_ecbs[i]) == NULL)
15052 if (match && ecb->dte_probe != NULL) {
15053 dtrace_probe_t *probe = ecb->dte_probe;
15054 dtrace_provider_t *prov = probe->dtpr_provider;
15056 if (!(prov->dtpv_priv.dtpp_flags & match))
15060 dtrace_ecb_disable(ecb);
15061 dtrace_ecb_destroy(ecb);
15069 * Before we free the buffers, perform one more sync to assure that
15070 * every CPU is out of probe context.
15074 dtrace_buffer_free(state->dts_buffer);
15075 dtrace_buffer_free(state->dts_aggbuffer);
15077 for (i = 0; i < nspec; i++)
15078 dtrace_buffer_free(spec[i].dtsp_buffer);
15081 if (state->dts_cleaner != CYCLIC_NONE)
15082 cyclic_remove(state->dts_cleaner);
15084 if (state->dts_deadman != CYCLIC_NONE)
15085 cyclic_remove(state->dts_deadman);
15087 callout_stop(&state->dts_cleaner);
15088 callout_drain(&state->dts_cleaner);
15089 callout_stop(&state->dts_deadman);
15090 callout_drain(&state->dts_deadman);
15093 dtrace_dstate_fini(&vstate->dtvs_dynvars);
15094 dtrace_vstate_fini(vstate);
15095 if (state->dts_ecbs != NULL)
15096 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15098 if (state->dts_aggregations != NULL) {
15100 for (i = 0; i < state->dts_naggregations; i++)
15101 ASSERT(state->dts_aggregations[i] == NULL);
15103 ASSERT(state->dts_naggregations > 0);
15104 kmem_free(state->dts_aggregations,
15105 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15108 kmem_free(state->dts_buffer, bufsize);
15109 kmem_free(state->dts_aggbuffer, bufsize);
15111 for (i = 0; i < nspec; i++)
15112 kmem_free(spec[i].dtsp_buffer, bufsize);
15115 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15117 dtrace_format_destroy(state);
15119 if (state->dts_aggid_arena != NULL) {
15121 vmem_destroy(state->dts_aggid_arena);
15123 delete_unrhdr(state->dts_aggid_arena);
15125 state->dts_aggid_arena = NULL;
15128 ddi_soft_state_free(dtrace_softstate, minor);
15129 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15134 * DTrace Anonymous Enabling Functions
15136 static dtrace_state_t *
15137 dtrace_anon_grab(void)
15139 dtrace_state_t *state;
15141 ASSERT(MUTEX_HELD(&dtrace_lock));
15143 if ((state = dtrace_anon.dta_state) == NULL) {
15144 ASSERT(dtrace_anon.dta_enabling == NULL);
15148 ASSERT(dtrace_anon.dta_enabling != NULL);
15149 ASSERT(dtrace_retained != NULL);
15151 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15152 dtrace_anon.dta_enabling = NULL;
15153 dtrace_anon.dta_state = NULL;
15159 dtrace_anon_property(void)
15162 dtrace_state_t *state;
15164 char c[32]; /* enough for "dof-data-" + digits */
15166 ASSERT(MUTEX_HELD(&dtrace_lock));
15167 ASSERT(MUTEX_HELD(&cpu_lock));
15169 for (i = 0; ; i++) {
15170 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
15172 dtrace_err_verbose = 1;
15174 if ((dof = dtrace_dof_property(c)) == NULL) {
15175 dtrace_err_verbose = 0;
15181 * We want to create anonymous state, so we need to transition
15182 * the kernel debugger to indicate that DTrace is active. If
15183 * this fails (e.g. because the debugger has modified text in
15184 * some way), we won't continue with the processing.
15186 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15187 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15188 "enabling ignored.");
15189 dtrace_dof_destroy(dof);
15195 * If we haven't allocated an anonymous state, we'll do so now.
15197 if ((state = dtrace_anon.dta_state) == NULL) {
15199 state = dtrace_state_create(NULL, NULL);
15201 state = dtrace_state_create(NULL);
15203 dtrace_anon.dta_state = state;
15205 if (state == NULL) {
15207 * This basically shouldn't happen: the only
15208 * failure mode from dtrace_state_create() is a
15209 * failure of ddi_soft_state_zalloc() that
15210 * itself should never happen. Still, the
15211 * interface allows for a failure mode, and
15212 * we want to fail as gracefully as possible:
15213 * we'll emit an error message and cease
15214 * processing anonymous state in this case.
15216 cmn_err(CE_WARN, "failed to create "
15217 "anonymous state");
15218 dtrace_dof_destroy(dof);
15223 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15224 &dtrace_anon.dta_enabling, 0, B_TRUE);
15227 rv = dtrace_dof_options(dof, state);
15229 dtrace_err_verbose = 0;
15230 dtrace_dof_destroy(dof);
15234 * This is malformed DOF; chuck any anonymous state
15237 ASSERT(dtrace_anon.dta_enabling == NULL);
15238 dtrace_state_destroy(state);
15239 dtrace_anon.dta_state = NULL;
15243 ASSERT(dtrace_anon.dta_enabling != NULL);
15246 if (dtrace_anon.dta_enabling != NULL) {
15250 * dtrace_enabling_retain() can only fail because we are
15251 * trying to retain more enablings than are allowed -- but
15252 * we only have one anonymous enabling, and we are guaranteed
15253 * to be allowed at least one retained enabling; we assert
15254 * that dtrace_enabling_retain() returns success.
15256 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15259 dtrace_enabling_dump(dtrace_anon.dta_enabling);
15264 * DTrace Helper Functions
15267 dtrace_helper_trace(dtrace_helper_action_t *helper,
15268 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15270 uint32_t size, next, nnext, i;
15271 dtrace_helptrace_t *ent, *buffer;
15272 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15274 if ((buffer = dtrace_helptrace_buffer) == NULL)
15277 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15280 * What would a tracing framework be without its own tracing
15281 * framework? (Well, a hell of a lot simpler, for starters...)
15283 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15284 sizeof (uint64_t) - sizeof (uint64_t);
15287 * Iterate until we can allocate a slot in the trace buffer.
15290 next = dtrace_helptrace_next;
15292 if (next + size < dtrace_helptrace_bufsize) {
15293 nnext = next + size;
15297 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15300 * We have our slot; fill it in.
15302 if (nnext == size) {
15303 dtrace_helptrace_wrapped++;
15307 ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15308 ent->dtht_helper = helper;
15309 ent->dtht_where = where;
15310 ent->dtht_nlocals = vstate->dtvs_nlocals;
15312 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15313 mstate->dtms_fltoffs : -1;
15314 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15315 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15317 for (i = 0; i < vstate->dtvs_nlocals; i++) {
15318 dtrace_statvar_t *svar;
15320 if ((svar = vstate->dtvs_locals[i]) == NULL)
15323 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15324 ent->dtht_locals[i] =
15325 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15330 dtrace_helper(int which, dtrace_mstate_t *mstate,
15331 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15333 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15334 uint64_t sarg0 = mstate->dtms_arg[0];
15335 uint64_t sarg1 = mstate->dtms_arg[1];
15337 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15338 dtrace_helper_action_t *helper;
15339 dtrace_vstate_t *vstate;
15340 dtrace_difo_t *pred;
15341 int i, trace = dtrace_helptrace_buffer != NULL;
15343 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15345 if (helpers == NULL)
15348 if ((helper = helpers->dthps_actions[which]) == NULL)
15351 vstate = &helpers->dthps_vstate;
15352 mstate->dtms_arg[0] = arg0;
15353 mstate->dtms_arg[1] = arg1;
15356 * Now iterate over each helper. If its predicate evaluates to 'true',
15357 * we'll call the corresponding actions. Note that the below calls
15358 * to dtrace_dif_emulate() may set faults in machine state. This is
15359 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
15360 * the stored DIF offset with its own (which is the desired behavior).
15361 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15362 * from machine state; this is okay, too.
15364 for (; helper != NULL; helper = helper->dtha_next) {
15365 if ((pred = helper->dtha_predicate) != NULL) {
15367 dtrace_helper_trace(helper, mstate, vstate, 0);
15369 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15372 if (*flags & CPU_DTRACE_FAULT)
15376 for (i = 0; i < helper->dtha_nactions; i++) {
15378 dtrace_helper_trace(helper,
15379 mstate, vstate, i + 1);
15381 rval = dtrace_dif_emulate(helper->dtha_actions[i],
15382 mstate, vstate, state);
15384 if (*flags & CPU_DTRACE_FAULT)
15390 dtrace_helper_trace(helper, mstate, vstate,
15391 DTRACE_HELPTRACE_NEXT);
15395 dtrace_helper_trace(helper, mstate, vstate,
15396 DTRACE_HELPTRACE_DONE);
15399 * Restore the arg0 that we saved upon entry.
15401 mstate->dtms_arg[0] = sarg0;
15402 mstate->dtms_arg[1] = sarg1;
15408 dtrace_helper_trace(helper, mstate, vstate,
15409 DTRACE_HELPTRACE_ERR);
15412 * Restore the arg0 that we saved upon entry.
15414 mstate->dtms_arg[0] = sarg0;
15415 mstate->dtms_arg[1] = sarg1;
15421 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15422 dtrace_vstate_t *vstate)
15426 if (helper->dtha_predicate != NULL)
15427 dtrace_difo_release(helper->dtha_predicate, vstate);
15429 for (i = 0; i < helper->dtha_nactions; i++) {
15430 ASSERT(helper->dtha_actions[i] != NULL);
15431 dtrace_difo_release(helper->dtha_actions[i], vstate);
15434 kmem_free(helper->dtha_actions,
15435 helper->dtha_nactions * sizeof (dtrace_difo_t *));
15436 kmem_free(helper, sizeof (dtrace_helper_action_t));
15440 dtrace_helper_destroygen(int gen)
15442 proc_t *p = curproc;
15443 dtrace_helpers_t *help = p->p_dtrace_helpers;
15444 dtrace_vstate_t *vstate;
15447 ASSERT(MUTEX_HELD(&dtrace_lock));
15449 if (help == NULL || gen > help->dthps_generation)
15452 vstate = &help->dthps_vstate;
15454 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15455 dtrace_helper_action_t *last = NULL, *h, *next;
15457 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15458 next = h->dtha_next;
15460 if (h->dtha_generation == gen) {
15461 if (last != NULL) {
15462 last->dtha_next = next;
15464 help->dthps_actions[i] = next;
15467 dtrace_helper_action_destroy(h, vstate);
15475 * Interate until we've cleared out all helper providers with the
15476 * given generation number.
15479 dtrace_helper_provider_t *prov;
15482 * Look for a helper provider with the right generation. We
15483 * have to start back at the beginning of the list each time
15484 * because we drop dtrace_lock. It's unlikely that we'll make
15485 * more than two passes.
15487 for (i = 0; i < help->dthps_nprovs; i++) {
15488 prov = help->dthps_provs[i];
15490 if (prov->dthp_generation == gen)
15495 * If there were no matches, we're done.
15497 if (i == help->dthps_nprovs)
15501 * Move the last helper provider into this slot.
15503 help->dthps_nprovs--;
15504 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15505 help->dthps_provs[help->dthps_nprovs] = NULL;
15507 mutex_exit(&dtrace_lock);
15510 * If we have a meta provider, remove this helper provider.
15512 mutex_enter(&dtrace_meta_lock);
15513 if (dtrace_meta_pid != NULL) {
15514 ASSERT(dtrace_deferred_pid == NULL);
15515 dtrace_helper_provider_remove(&prov->dthp_prov,
15518 mutex_exit(&dtrace_meta_lock);
15520 dtrace_helper_provider_destroy(prov);
15522 mutex_enter(&dtrace_lock);
15529 dtrace_helper_validate(dtrace_helper_action_t *helper)
15534 if ((dp = helper->dtha_predicate) != NULL)
15535 err += dtrace_difo_validate_helper(dp);
15537 for (i = 0; i < helper->dtha_nactions; i++)
15538 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15544 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
15546 dtrace_helpers_t *help;
15547 dtrace_helper_action_t *helper, *last;
15548 dtrace_actdesc_t *act;
15549 dtrace_vstate_t *vstate;
15550 dtrace_predicate_t *pred;
15551 int count = 0, nactions = 0, i;
15553 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15556 help = curproc->p_dtrace_helpers;
15557 last = help->dthps_actions[which];
15558 vstate = &help->dthps_vstate;
15560 for (count = 0; last != NULL; last = last->dtha_next) {
15562 if (last->dtha_next == NULL)
15567 * If we already have dtrace_helper_actions_max helper actions for this
15568 * helper action type, we'll refuse to add a new one.
15570 if (count >= dtrace_helper_actions_max)
15573 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15574 helper->dtha_generation = help->dthps_generation;
15576 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15577 ASSERT(pred->dtp_difo != NULL);
15578 dtrace_difo_hold(pred->dtp_difo);
15579 helper->dtha_predicate = pred->dtp_difo;
15582 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15583 if (act->dtad_kind != DTRACEACT_DIFEXPR)
15586 if (act->dtad_difo == NULL)
15592 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15593 (helper->dtha_nactions = nactions), KM_SLEEP);
15595 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15596 dtrace_difo_hold(act->dtad_difo);
15597 helper->dtha_actions[i++] = act->dtad_difo;
15600 if (!dtrace_helper_validate(helper))
15603 if (last == NULL) {
15604 help->dthps_actions[which] = helper;
15606 last->dtha_next = helper;
15609 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15610 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15611 dtrace_helptrace_next = 0;
15616 dtrace_helper_action_destroy(helper, vstate);
15621 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15622 dof_helper_t *dofhp)
15624 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15626 mutex_enter(&dtrace_meta_lock);
15627 mutex_enter(&dtrace_lock);
15629 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15631 * If the dtrace module is loaded but not attached, or if
15632 * there aren't isn't a meta provider registered to deal with
15633 * these provider descriptions, we need to postpone creating
15634 * the actual providers until later.
15637 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15638 dtrace_deferred_pid != help) {
15639 help->dthps_deferred = 1;
15640 help->dthps_pid = p->p_pid;
15641 help->dthps_next = dtrace_deferred_pid;
15642 help->dthps_prev = NULL;
15643 if (dtrace_deferred_pid != NULL)
15644 dtrace_deferred_pid->dthps_prev = help;
15645 dtrace_deferred_pid = help;
15648 mutex_exit(&dtrace_lock);
15650 } else if (dofhp != NULL) {
15652 * If the dtrace module is loaded and we have a particular
15653 * helper provider description, pass that off to the
15657 mutex_exit(&dtrace_lock);
15659 dtrace_helper_provide(dofhp, p->p_pid);
15663 * Otherwise, just pass all the helper provider descriptions
15664 * off to the meta provider.
15668 mutex_exit(&dtrace_lock);
15670 for (i = 0; i < help->dthps_nprovs; i++) {
15671 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15676 mutex_exit(&dtrace_meta_lock);
15680 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15682 dtrace_helpers_t *help;
15683 dtrace_helper_provider_t *hprov, **tmp_provs;
15684 uint_t tmp_maxprovs, i;
15686 ASSERT(MUTEX_HELD(&dtrace_lock));
15688 help = curproc->p_dtrace_helpers;
15689 ASSERT(help != NULL);
15692 * If we already have dtrace_helper_providers_max helper providers,
15693 * we're refuse to add a new one.
15695 if (help->dthps_nprovs >= dtrace_helper_providers_max)
15699 * Check to make sure this isn't a duplicate.
15701 for (i = 0; i < help->dthps_nprovs; i++) {
15702 if (dofhp->dofhp_dof ==
15703 help->dthps_provs[i]->dthp_prov.dofhp_dof)
15707 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15708 hprov->dthp_prov = *dofhp;
15709 hprov->dthp_ref = 1;
15710 hprov->dthp_generation = gen;
15713 * Allocate a bigger table for helper providers if it's already full.
15715 if (help->dthps_maxprovs == help->dthps_nprovs) {
15716 tmp_maxprovs = help->dthps_maxprovs;
15717 tmp_provs = help->dthps_provs;
15719 if (help->dthps_maxprovs == 0)
15720 help->dthps_maxprovs = 2;
15722 help->dthps_maxprovs *= 2;
15723 if (help->dthps_maxprovs > dtrace_helper_providers_max)
15724 help->dthps_maxprovs = dtrace_helper_providers_max;
15726 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15728 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15729 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15731 if (tmp_provs != NULL) {
15732 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15733 sizeof (dtrace_helper_provider_t *));
15734 kmem_free(tmp_provs, tmp_maxprovs *
15735 sizeof (dtrace_helper_provider_t *));
15739 help->dthps_provs[help->dthps_nprovs] = hprov;
15740 help->dthps_nprovs++;
15746 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15748 mutex_enter(&dtrace_lock);
15750 if (--hprov->dthp_ref == 0) {
15752 mutex_exit(&dtrace_lock);
15753 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15754 dtrace_dof_destroy(dof);
15755 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15757 mutex_exit(&dtrace_lock);
15762 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15764 uintptr_t daddr = (uintptr_t)dof;
15765 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15766 dof_provider_t *provider;
15767 dof_probe_t *probe;
15769 char *strtab, *typestr;
15770 dof_stridx_t typeidx;
15772 uint_t nprobes, j, k;
15774 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15776 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15777 dtrace_dof_error(dof, "misaligned section offset");
15782 * The section needs to be large enough to contain the DOF provider
15783 * structure appropriate for the given version.
15785 if (sec->dofs_size <
15786 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15787 offsetof(dof_provider_t, dofpv_prenoffs) :
15788 sizeof (dof_provider_t))) {
15789 dtrace_dof_error(dof, "provider section too small");
15793 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15794 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15795 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15796 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15797 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15799 if (str_sec == NULL || prb_sec == NULL ||
15800 arg_sec == NULL || off_sec == NULL)
15805 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15806 provider->dofpv_prenoffs != DOF_SECT_NONE &&
15807 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15808 provider->dofpv_prenoffs)) == NULL)
15811 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15813 if (provider->dofpv_name >= str_sec->dofs_size ||
15814 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15815 dtrace_dof_error(dof, "invalid provider name");
15819 if (prb_sec->dofs_entsize == 0 ||
15820 prb_sec->dofs_entsize > prb_sec->dofs_size) {
15821 dtrace_dof_error(dof, "invalid entry size");
15825 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15826 dtrace_dof_error(dof, "misaligned entry size");
15830 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15831 dtrace_dof_error(dof, "invalid entry size");
15835 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15836 dtrace_dof_error(dof, "misaligned section offset");
15840 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15841 dtrace_dof_error(dof, "invalid entry size");
15845 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15847 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15850 * Take a pass through the probes to check for errors.
15852 for (j = 0; j < nprobes; j++) {
15853 probe = (dof_probe_t *)(uintptr_t)(daddr +
15854 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15856 if (probe->dofpr_func >= str_sec->dofs_size) {
15857 dtrace_dof_error(dof, "invalid function name");
15861 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15862 dtrace_dof_error(dof, "function name too long");
15864 * Keep going if the function name is too long.
15865 * Unlike provider and probe names, we cannot reasonably
15866 * impose restrictions on function names, since they're
15867 * a property of the code being instrumented. We will
15868 * skip this probe in dtrace_helper_provide_one().
15872 if (probe->dofpr_name >= str_sec->dofs_size ||
15873 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15874 dtrace_dof_error(dof, "invalid probe name");
15879 * The offset count must not wrap the index, and the offsets
15880 * must also not overflow the section's data.
15882 if (probe->dofpr_offidx + probe->dofpr_noffs <
15883 probe->dofpr_offidx ||
15884 (probe->dofpr_offidx + probe->dofpr_noffs) *
15885 off_sec->dofs_entsize > off_sec->dofs_size) {
15886 dtrace_dof_error(dof, "invalid probe offset");
15890 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15892 * If there's no is-enabled offset section, make sure
15893 * there aren't any is-enabled offsets. Otherwise
15894 * perform the same checks as for probe offsets
15895 * (immediately above).
15897 if (enoff_sec == NULL) {
15898 if (probe->dofpr_enoffidx != 0 ||
15899 probe->dofpr_nenoffs != 0) {
15900 dtrace_dof_error(dof, "is-enabled "
15901 "offsets with null section");
15904 } else if (probe->dofpr_enoffidx +
15905 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15906 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15907 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15908 dtrace_dof_error(dof, "invalid is-enabled "
15913 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15914 dtrace_dof_error(dof, "zero probe and "
15915 "is-enabled offsets");
15918 } else if (probe->dofpr_noffs == 0) {
15919 dtrace_dof_error(dof, "zero probe offsets");
15923 if (probe->dofpr_argidx + probe->dofpr_xargc <
15924 probe->dofpr_argidx ||
15925 (probe->dofpr_argidx + probe->dofpr_xargc) *
15926 arg_sec->dofs_entsize > arg_sec->dofs_size) {
15927 dtrace_dof_error(dof, "invalid args");
15931 typeidx = probe->dofpr_nargv;
15932 typestr = strtab + probe->dofpr_nargv;
15933 for (k = 0; k < probe->dofpr_nargc; k++) {
15934 if (typeidx >= str_sec->dofs_size) {
15935 dtrace_dof_error(dof, "bad "
15936 "native argument type");
15940 typesz = strlen(typestr) + 1;
15941 if (typesz > DTRACE_ARGTYPELEN) {
15942 dtrace_dof_error(dof, "native "
15943 "argument type too long");
15950 typeidx = probe->dofpr_xargv;
15951 typestr = strtab + probe->dofpr_xargv;
15952 for (k = 0; k < probe->dofpr_xargc; k++) {
15953 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15954 dtrace_dof_error(dof, "bad "
15955 "native argument index");
15959 if (typeidx >= str_sec->dofs_size) {
15960 dtrace_dof_error(dof, "bad "
15961 "translated argument type");
15965 typesz = strlen(typestr) + 1;
15966 if (typesz > DTRACE_ARGTYPELEN) {
15967 dtrace_dof_error(dof, "translated argument "
15981 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15983 dtrace_helpers_t *help;
15984 dtrace_vstate_t *vstate;
15985 dtrace_enabling_t *enab = NULL;
15986 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15987 uintptr_t daddr = (uintptr_t)dof;
15989 ASSERT(MUTEX_HELD(&dtrace_lock));
15991 if ((help = curproc->p_dtrace_helpers) == NULL)
15992 help = dtrace_helpers_create(curproc);
15994 vstate = &help->dthps_vstate;
15996 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15997 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15998 dtrace_dof_destroy(dof);
16003 * Look for helper providers and validate their descriptions.
16006 for (i = 0; i < dof->dofh_secnum; i++) {
16007 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16008 dof->dofh_secoff + i * dof->dofh_secsize);
16010 if (sec->dofs_type != DOF_SECT_PROVIDER)
16013 if (dtrace_helper_provider_validate(dof, sec) != 0) {
16014 dtrace_enabling_destroy(enab);
16015 dtrace_dof_destroy(dof);
16024 * Now we need to walk through the ECB descriptions in the enabling.
16026 for (i = 0; i < enab->dten_ndesc; i++) {
16027 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16028 dtrace_probedesc_t *desc = &ep->dted_probe;
16030 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16033 if (strcmp(desc->dtpd_mod, "helper") != 0)
16036 if (strcmp(desc->dtpd_func, "ustack") != 0)
16039 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16042 * Adding this helper action failed -- we are now going
16043 * to rip out the entire generation and return failure.
16045 (void) dtrace_helper_destroygen(help->dthps_generation);
16046 dtrace_enabling_destroy(enab);
16047 dtrace_dof_destroy(dof);
16054 if (nhelpers < enab->dten_ndesc)
16055 dtrace_dof_error(dof, "unmatched helpers");
16057 gen = help->dthps_generation++;
16058 dtrace_enabling_destroy(enab);
16060 if (dhp != NULL && nprovs > 0) {
16061 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16062 if (dtrace_helper_provider_add(dhp, gen) == 0) {
16063 mutex_exit(&dtrace_lock);
16064 dtrace_helper_provider_register(curproc, help, dhp);
16065 mutex_enter(&dtrace_lock);
16072 dtrace_dof_destroy(dof);
16077 static dtrace_helpers_t *
16078 dtrace_helpers_create(proc_t *p)
16080 dtrace_helpers_t *help;
16082 ASSERT(MUTEX_HELD(&dtrace_lock));
16083 ASSERT(p->p_dtrace_helpers == NULL);
16085 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16086 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16087 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16089 p->p_dtrace_helpers = help;
16099 dtrace_helpers_destroy(proc_t *p)
16101 dtrace_helpers_t *help;
16102 dtrace_vstate_t *vstate;
16104 proc_t *p = curproc;
16108 mutex_enter(&dtrace_lock);
16110 ASSERT(p->p_dtrace_helpers != NULL);
16111 ASSERT(dtrace_helpers > 0);
16113 help = p->p_dtrace_helpers;
16114 vstate = &help->dthps_vstate;
16117 * We're now going to lose the help from this process.
16119 p->p_dtrace_helpers = NULL;
16123 * Destory the helper actions.
16125 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16126 dtrace_helper_action_t *h, *next;
16128 for (h = help->dthps_actions[i]; h != NULL; h = next) {
16129 next = h->dtha_next;
16130 dtrace_helper_action_destroy(h, vstate);
16135 mutex_exit(&dtrace_lock);
16138 * Destroy the helper providers.
16140 if (help->dthps_maxprovs > 0) {
16141 mutex_enter(&dtrace_meta_lock);
16142 if (dtrace_meta_pid != NULL) {
16143 ASSERT(dtrace_deferred_pid == NULL);
16145 for (i = 0; i < help->dthps_nprovs; i++) {
16146 dtrace_helper_provider_remove(
16147 &help->dthps_provs[i]->dthp_prov, p->p_pid);
16150 mutex_enter(&dtrace_lock);
16151 ASSERT(help->dthps_deferred == 0 ||
16152 help->dthps_next != NULL ||
16153 help->dthps_prev != NULL ||
16154 help == dtrace_deferred_pid);
16157 * Remove the helper from the deferred list.
16159 if (help->dthps_next != NULL)
16160 help->dthps_next->dthps_prev = help->dthps_prev;
16161 if (help->dthps_prev != NULL)
16162 help->dthps_prev->dthps_next = help->dthps_next;
16163 if (dtrace_deferred_pid == help) {
16164 dtrace_deferred_pid = help->dthps_next;
16165 ASSERT(help->dthps_prev == NULL);
16168 mutex_exit(&dtrace_lock);
16171 mutex_exit(&dtrace_meta_lock);
16173 for (i = 0; i < help->dthps_nprovs; i++) {
16174 dtrace_helper_provider_destroy(help->dthps_provs[i]);
16177 kmem_free(help->dthps_provs, help->dthps_maxprovs *
16178 sizeof (dtrace_helper_provider_t *));
16181 mutex_enter(&dtrace_lock);
16183 dtrace_vstate_fini(&help->dthps_vstate);
16184 kmem_free(help->dthps_actions,
16185 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16186 kmem_free(help, sizeof (dtrace_helpers_t));
16189 mutex_exit(&dtrace_lock);
16196 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16198 dtrace_helpers_t *help, *newhelp;
16199 dtrace_helper_action_t *helper, *new, *last;
16201 dtrace_vstate_t *vstate;
16202 int i, j, sz, hasprovs = 0;
16204 mutex_enter(&dtrace_lock);
16205 ASSERT(from->p_dtrace_helpers != NULL);
16206 ASSERT(dtrace_helpers > 0);
16208 help = from->p_dtrace_helpers;
16209 newhelp = dtrace_helpers_create(to);
16210 ASSERT(to->p_dtrace_helpers != NULL);
16212 newhelp->dthps_generation = help->dthps_generation;
16213 vstate = &newhelp->dthps_vstate;
16216 * Duplicate the helper actions.
16218 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16219 if ((helper = help->dthps_actions[i]) == NULL)
16222 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16223 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16225 new->dtha_generation = helper->dtha_generation;
16227 if ((dp = helper->dtha_predicate) != NULL) {
16228 dp = dtrace_difo_duplicate(dp, vstate);
16229 new->dtha_predicate = dp;
16232 new->dtha_nactions = helper->dtha_nactions;
16233 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16234 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16236 for (j = 0; j < new->dtha_nactions; j++) {
16237 dtrace_difo_t *dp = helper->dtha_actions[j];
16239 ASSERT(dp != NULL);
16240 dp = dtrace_difo_duplicate(dp, vstate);
16241 new->dtha_actions[j] = dp;
16244 if (last != NULL) {
16245 last->dtha_next = new;
16247 newhelp->dthps_actions[i] = new;
16255 * Duplicate the helper providers and register them with the
16256 * DTrace framework.
16258 if (help->dthps_nprovs > 0) {
16259 newhelp->dthps_nprovs = help->dthps_nprovs;
16260 newhelp->dthps_maxprovs = help->dthps_nprovs;
16261 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16262 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16263 for (i = 0; i < newhelp->dthps_nprovs; i++) {
16264 newhelp->dthps_provs[i] = help->dthps_provs[i];
16265 newhelp->dthps_provs[i]->dthp_ref++;
16271 mutex_exit(&dtrace_lock);
16274 dtrace_helper_provider_register(to, newhelp, NULL);
16278 * DTrace Hook Functions
16281 dtrace_module_loaded(modctl_t *ctl)
16283 dtrace_provider_t *prv;
16285 mutex_enter(&dtrace_provider_lock);
16287 mutex_enter(&mod_lock);
16291 ASSERT(ctl->mod_busy);
16295 * We're going to call each providers per-module provide operation
16296 * specifying only this module.
16298 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16299 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16302 mutex_exit(&mod_lock);
16304 mutex_exit(&dtrace_provider_lock);
16307 * If we have any retained enablings, we need to match against them.
16308 * Enabling probes requires that cpu_lock be held, and we cannot hold
16309 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16310 * module. (In particular, this happens when loading scheduling
16311 * classes.) So if we have any retained enablings, we need to dispatch
16312 * our task queue to do the match for us.
16314 mutex_enter(&dtrace_lock);
16316 if (dtrace_retained == NULL) {
16317 mutex_exit(&dtrace_lock);
16321 (void) taskq_dispatch(dtrace_taskq,
16322 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16324 mutex_exit(&dtrace_lock);
16327 * And now, for a little heuristic sleaze: in general, we want to
16328 * match modules as soon as they load. However, we cannot guarantee
16329 * this, because it would lead us to the lock ordering violation
16330 * outlined above. The common case, of course, is that cpu_lock is
16331 * _not_ held -- so we delay here for a clock tick, hoping that that's
16332 * long enough for the task queue to do its work. If it's not, it's
16333 * not a serious problem -- it just means that the module that we
16334 * just loaded may not be immediately instrumentable.
16341 dtrace_module_unloaded(modctl_t *ctl)
16343 dtrace_module_unloaded(modctl_t *ctl, int *error)
16346 dtrace_probe_t template, *probe, *first, *next;
16347 dtrace_provider_t *prov;
16349 char modname[DTRACE_MODNAMELEN];
16354 template.dtpr_mod = ctl->mod_modname;
16356 /* Handle the fact that ctl->filename may end in ".ko". */
16357 strlcpy(modname, ctl->filename, sizeof(modname));
16358 len = strlen(ctl->filename);
16359 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16360 modname[len - 3] = '\0';
16361 template.dtpr_mod = modname;
16364 mutex_enter(&dtrace_provider_lock);
16366 mutex_enter(&mod_lock);
16368 mutex_enter(&dtrace_lock);
16371 if (ctl->nenabled > 0) {
16372 /* Don't allow unloads if a probe is enabled. */
16373 mutex_exit(&dtrace_provider_lock);
16374 mutex_exit(&dtrace_lock);
16377 "kldunload: attempt to unload module that has DTrace probes enabled\n");
16382 if (dtrace_bymod == NULL) {
16384 * The DTrace module is loaded (obviously) but not attached;
16385 * we don't have any work to do.
16387 mutex_exit(&dtrace_provider_lock);
16389 mutex_exit(&mod_lock);
16391 mutex_exit(&dtrace_lock);
16395 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16396 probe != NULL; probe = probe->dtpr_nextmod) {
16397 if (probe->dtpr_ecb != NULL) {
16398 mutex_exit(&dtrace_provider_lock);
16400 mutex_exit(&mod_lock);
16402 mutex_exit(&dtrace_lock);
16405 * This shouldn't _actually_ be possible -- we're
16406 * unloading a module that has an enabled probe in it.
16407 * (It's normally up to the provider to make sure that
16408 * this can't happen.) However, because dtps_enable()
16409 * doesn't have a failure mode, there can be an
16410 * enable/unload race. Upshot: we don't want to
16411 * assert, but we're not going to disable the
16414 if (dtrace_err_verbose) {
16416 cmn_err(CE_WARN, "unloaded module '%s' had "
16417 "enabled probes", ctl->mod_modname);
16419 cmn_err(CE_WARN, "unloaded module '%s' had "
16420 "enabled probes", modname);
16430 for (first = NULL; probe != NULL; probe = next) {
16431 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16433 dtrace_probes[probe->dtpr_id - 1] = NULL;
16435 next = probe->dtpr_nextmod;
16436 dtrace_hash_remove(dtrace_bymod, probe);
16437 dtrace_hash_remove(dtrace_byfunc, probe);
16438 dtrace_hash_remove(dtrace_byname, probe);
16440 if (first == NULL) {
16442 probe->dtpr_nextmod = NULL;
16444 probe->dtpr_nextmod = first;
16450 * We've removed all of the module's probes from the hash chains and
16451 * from the probe array. Now issue a dtrace_sync() to be sure that
16452 * everyone has cleared out from any probe array processing.
16456 for (probe = first; probe != NULL; probe = first) {
16457 first = probe->dtpr_nextmod;
16458 prov = probe->dtpr_provider;
16459 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16461 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16462 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16463 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16465 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16467 free_unr(dtrace_arena, probe->dtpr_id);
16469 kmem_free(probe, sizeof (dtrace_probe_t));
16472 mutex_exit(&dtrace_lock);
16474 mutex_exit(&mod_lock);
16476 mutex_exit(&dtrace_provider_lock);
16481 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16484 dtrace_module_loaded(lf);
16488 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16492 /* We already have an error, so don't do anything. */
16494 dtrace_module_unloaded(lf, error);
16500 dtrace_suspend(void)
16502 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16506 dtrace_resume(void)
16508 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16513 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16515 ASSERT(MUTEX_HELD(&cpu_lock));
16516 mutex_enter(&dtrace_lock);
16520 dtrace_state_t *state;
16521 dtrace_optval_t *opt, rs, c;
16524 * For now, we only allocate a new buffer for anonymous state.
16526 if ((state = dtrace_anon.dta_state) == NULL)
16529 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16532 opt = state->dts_options;
16533 c = opt[DTRACEOPT_CPU];
16535 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16539 * Regardless of what the actual policy is, we're going to
16540 * temporarily set our resize policy to be manual. We're
16541 * also going to temporarily set our CPU option to denote
16542 * the newly configured CPU.
16544 rs = opt[DTRACEOPT_BUFRESIZE];
16545 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16546 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16548 (void) dtrace_state_buffers(state);
16550 opt[DTRACEOPT_BUFRESIZE] = rs;
16551 opt[DTRACEOPT_CPU] = c;
16558 * We don't free the buffer in the CPU_UNCONFIG case. (The
16559 * buffer will be freed when the consumer exits.)
16567 mutex_exit(&dtrace_lock);
16573 dtrace_cpu_setup_initial(processorid_t cpu)
16575 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16580 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16582 if (dtrace_toxranges >= dtrace_toxranges_max) {
16584 dtrace_toxrange_t *range;
16586 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16589 ASSERT(dtrace_toxrange == NULL);
16590 ASSERT(dtrace_toxranges_max == 0);
16591 dtrace_toxranges_max = 1;
16593 dtrace_toxranges_max <<= 1;
16596 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16597 range = kmem_zalloc(nsize, KM_SLEEP);
16599 if (dtrace_toxrange != NULL) {
16600 ASSERT(osize != 0);
16601 bcopy(dtrace_toxrange, range, osize);
16602 kmem_free(dtrace_toxrange, osize);
16605 dtrace_toxrange = range;
16608 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16609 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16611 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16612 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16613 dtrace_toxranges++;
16617 dtrace_getf_barrier()
16621 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
16622 * that contain calls to getf(), this routine will be called on every
16623 * closef() before either the underlying vnode is released or the
16624 * file_t itself is freed. By the time we are here, it is essential
16625 * that the file_t can no longer be accessed from a call to getf()
16626 * in probe context -- that assures that a dtrace_sync() can be used
16627 * to clear out any enablings referring to the old structures.
16629 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
16630 kcred->cr_zone->zone_dtrace_getf != 0)
16636 * DTrace Driver Cookbook Functions
16641 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16643 dtrace_provider_id_t id;
16644 dtrace_state_t *state = NULL;
16645 dtrace_enabling_t *enab;
16647 mutex_enter(&cpu_lock);
16648 mutex_enter(&dtrace_provider_lock);
16649 mutex_enter(&dtrace_lock);
16651 if (ddi_soft_state_init(&dtrace_softstate,
16652 sizeof (dtrace_state_t), 0) != 0) {
16653 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16654 mutex_exit(&cpu_lock);
16655 mutex_exit(&dtrace_provider_lock);
16656 mutex_exit(&dtrace_lock);
16657 return (DDI_FAILURE);
16660 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16661 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
16662 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16663 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
16664 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16665 ddi_remove_minor_node(devi, NULL);
16666 ddi_soft_state_fini(&dtrace_softstate);
16667 mutex_exit(&cpu_lock);
16668 mutex_exit(&dtrace_provider_lock);
16669 mutex_exit(&dtrace_lock);
16670 return (DDI_FAILURE);
16673 ddi_report_dev(devi);
16674 dtrace_devi = devi;
16676 dtrace_modload = dtrace_module_loaded;
16677 dtrace_modunload = dtrace_module_unloaded;
16678 dtrace_cpu_init = dtrace_cpu_setup_initial;
16679 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16680 dtrace_helpers_fork = dtrace_helpers_duplicate;
16681 dtrace_cpustart_init = dtrace_suspend;
16682 dtrace_cpustart_fini = dtrace_resume;
16683 dtrace_debugger_init = dtrace_suspend;
16684 dtrace_debugger_fini = dtrace_resume;
16686 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16688 ASSERT(MUTEX_HELD(&cpu_lock));
16690 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16691 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16692 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16693 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16694 VM_SLEEP | VMC_IDENTIFIER);
16695 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16698 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16699 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16700 NULL, NULL, NULL, NULL, NULL, 0);
16702 ASSERT(MUTEX_HELD(&cpu_lock));
16703 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16704 offsetof(dtrace_probe_t, dtpr_nextmod),
16705 offsetof(dtrace_probe_t, dtpr_prevmod));
16707 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16708 offsetof(dtrace_probe_t, dtpr_nextfunc),
16709 offsetof(dtrace_probe_t, dtpr_prevfunc));
16711 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16712 offsetof(dtrace_probe_t, dtpr_nextname),
16713 offsetof(dtrace_probe_t, dtpr_prevname));
16715 if (dtrace_retain_max < 1) {
16716 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16717 "setting to 1", dtrace_retain_max);
16718 dtrace_retain_max = 1;
16722 * Now discover our toxic ranges.
16724 dtrace_toxic_ranges(dtrace_toxrange_add);
16727 * Before we register ourselves as a provider to our own framework,
16728 * we would like to assert that dtrace_provider is NULL -- but that's
16729 * not true if we were loaded as a dependency of a DTrace provider.
16730 * Once we've registered, we can assert that dtrace_provider is our
16733 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16734 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16736 ASSERT(dtrace_provider != NULL);
16737 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16739 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16740 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16741 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16742 dtrace_provider, NULL, NULL, "END", 0, NULL);
16743 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16744 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16746 dtrace_anon_property();
16747 mutex_exit(&cpu_lock);
16750 * If there are already providers, we must ask them to provide their
16751 * probes, and then match any anonymous enabling against them. Note
16752 * that there should be no other retained enablings at this time:
16753 * the only retained enablings at this time should be the anonymous
16756 if (dtrace_anon.dta_enabling != NULL) {
16757 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16759 dtrace_enabling_provide(NULL);
16760 state = dtrace_anon.dta_state;
16763 * We couldn't hold cpu_lock across the above call to
16764 * dtrace_enabling_provide(), but we must hold it to actually
16765 * enable the probes. We have to drop all of our locks, pick
16766 * up cpu_lock, and regain our locks before matching the
16767 * retained anonymous enabling.
16769 mutex_exit(&dtrace_lock);
16770 mutex_exit(&dtrace_provider_lock);
16772 mutex_enter(&cpu_lock);
16773 mutex_enter(&dtrace_provider_lock);
16774 mutex_enter(&dtrace_lock);
16776 if ((enab = dtrace_anon.dta_enabling) != NULL)
16777 (void) dtrace_enabling_match(enab, NULL);
16779 mutex_exit(&cpu_lock);
16782 mutex_exit(&dtrace_lock);
16783 mutex_exit(&dtrace_provider_lock);
16785 if (state != NULL) {
16787 * If we created any anonymous state, set it going now.
16789 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16792 return (DDI_SUCCESS);
16794 #endif /* illumos */
16797 static void dtrace_dtr(void *);
16803 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16805 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16808 dtrace_state_t *state;
16814 if (getminor(*devp) == DTRACEMNRN_HELPER)
16818 * If this wasn't an open with the "helper" minor, then it must be
16819 * the "dtrace" minor.
16821 if (getminor(*devp) == DTRACEMNRN_DTRACE)
16824 cred_t *cred_p = NULL;
16825 cred_p = dev->si_cred;
16828 * If no DTRACE_PRIV_* bits are set in the credential, then the
16829 * caller lacks sufficient permission to do anything with DTrace.
16831 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16832 if (priv == DTRACE_PRIV_NONE) {
16839 * Ask all providers to provide all their probes.
16841 mutex_enter(&dtrace_provider_lock);
16842 dtrace_probe_provide(NULL, NULL);
16843 mutex_exit(&dtrace_provider_lock);
16845 mutex_enter(&cpu_lock);
16846 mutex_enter(&dtrace_lock);
16848 dtrace_membar_producer();
16852 * If the kernel debugger is active (that is, if the kernel debugger
16853 * modified text in some way), we won't allow the open.
16855 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16857 mutex_exit(&cpu_lock);
16858 mutex_exit(&dtrace_lock);
16862 if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
16864 * If DTrace helper tracing is enabled, we need to allocate the
16865 * trace buffer and initialize the values.
16867 dtrace_helptrace_buffer =
16868 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16869 dtrace_helptrace_next = 0;
16870 dtrace_helptrace_wrapped = 0;
16871 dtrace_helptrace_enable = 0;
16874 state = dtrace_state_create(devp, cred_p);
16876 state = dtrace_state_create(dev);
16877 devfs_set_cdevpriv(state, dtrace_dtr);
16880 mutex_exit(&cpu_lock);
16882 if (state == NULL) {
16884 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16885 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16889 mutex_exit(&dtrace_lock);
16893 mutex_exit(&dtrace_lock);
16901 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16904 dtrace_dtr(void *data)
16908 minor_t minor = getminor(dev);
16909 dtrace_state_t *state;
16911 dtrace_helptrace_t *buf = NULL;
16914 if (minor == DTRACEMNRN_HELPER)
16917 state = ddi_get_soft_state(dtrace_softstate, minor);
16919 dtrace_state_t *state = data;
16922 mutex_enter(&cpu_lock);
16923 mutex_enter(&dtrace_lock);
16926 if (state->dts_anon)
16928 if (state != NULL && state->dts_anon)
16932 * There is anonymous state. Destroy that first.
16934 ASSERT(dtrace_anon.dta_state == NULL);
16935 dtrace_state_destroy(state->dts_anon);
16938 if (dtrace_helptrace_disable) {
16940 * If we have been told to disable helper tracing, set the
16941 * buffer to NULL before calling into dtrace_state_destroy();
16942 * we take advantage of its dtrace_sync() to know that no
16943 * CPU is in probe context with enabled helper tracing
16944 * after it returns.
16946 buf = dtrace_helptrace_buffer;
16947 dtrace_helptrace_buffer = NULL;
16951 dtrace_state_destroy(state);
16953 if (state != NULL) {
16954 dtrace_state_destroy(state);
16955 kmem_free(state, 0);
16958 ASSERT(dtrace_opens > 0);
16962 * Only relinquish control of the kernel debugger interface when there
16963 * are no consumers and no anonymous enablings.
16965 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16966 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16972 kmem_free(buf, dtrace_helptrace_bufsize);
16973 dtrace_helptrace_disable = 0;
16976 mutex_exit(&dtrace_lock);
16977 mutex_exit(&cpu_lock);
16987 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16990 dof_helper_t help, *dhp = NULL;
16993 case DTRACEHIOC_ADDDOF:
16994 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16995 dtrace_dof_error(NULL, "failed to copyin DOF helper");
17000 arg = (intptr_t)help.dofhp_dof;
17003 case DTRACEHIOC_ADD: {
17004 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17009 mutex_enter(&dtrace_lock);
17012 * dtrace_helper_slurp() takes responsibility for the dof --
17013 * it may free it now or it may save it and free it later.
17015 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17022 mutex_exit(&dtrace_lock);
17026 case DTRACEHIOC_REMOVE: {
17027 mutex_enter(&dtrace_lock);
17028 rval = dtrace_helper_destroygen(arg);
17029 mutex_exit(&dtrace_lock);
17043 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17045 minor_t minor = getminor(dev);
17046 dtrace_state_t *state;
17049 if (minor == DTRACEMNRN_HELPER)
17050 return (dtrace_ioctl_helper(cmd, arg, rv));
17052 state = ddi_get_soft_state(dtrace_softstate, minor);
17054 if (state->dts_anon) {
17055 ASSERT(dtrace_anon.dta_state == NULL);
17056 state = state->dts_anon;
17060 case DTRACEIOC_PROVIDER: {
17061 dtrace_providerdesc_t pvd;
17062 dtrace_provider_t *pvp;
17064 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17067 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17068 mutex_enter(&dtrace_provider_lock);
17070 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17071 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17075 mutex_exit(&dtrace_provider_lock);
17080 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17081 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17083 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17089 case DTRACEIOC_EPROBE: {
17090 dtrace_eprobedesc_t epdesc;
17092 dtrace_action_t *act;
17098 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17101 mutex_enter(&dtrace_lock);
17103 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17104 mutex_exit(&dtrace_lock);
17108 if (ecb->dte_probe == NULL) {
17109 mutex_exit(&dtrace_lock);
17113 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17114 epdesc.dtepd_uarg = ecb->dte_uarg;
17115 epdesc.dtepd_size = ecb->dte_size;
17117 nrecs = epdesc.dtepd_nrecs;
17118 epdesc.dtepd_nrecs = 0;
17119 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17120 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17123 epdesc.dtepd_nrecs++;
17127 * Now that we have the size, we need to allocate a temporary
17128 * buffer in which to store the complete description. We need
17129 * the temporary buffer to be able to drop dtrace_lock()
17130 * across the copyout(), below.
17132 size = sizeof (dtrace_eprobedesc_t) +
17133 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17135 buf = kmem_alloc(size, KM_SLEEP);
17136 dest = (uintptr_t)buf;
17138 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17139 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17141 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17142 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17148 bcopy(&act->dta_rec, (void *)dest,
17149 sizeof (dtrace_recdesc_t));
17150 dest += sizeof (dtrace_recdesc_t);
17153 mutex_exit(&dtrace_lock);
17155 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17156 kmem_free(buf, size);
17160 kmem_free(buf, size);
17164 case DTRACEIOC_AGGDESC: {
17165 dtrace_aggdesc_t aggdesc;
17166 dtrace_action_t *act;
17167 dtrace_aggregation_t *agg;
17170 dtrace_recdesc_t *lrec;
17175 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17178 mutex_enter(&dtrace_lock);
17180 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17181 mutex_exit(&dtrace_lock);
17185 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17187 nrecs = aggdesc.dtagd_nrecs;
17188 aggdesc.dtagd_nrecs = 0;
17190 offs = agg->dtag_base;
17191 lrec = &agg->dtag_action.dta_rec;
17192 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17194 for (act = agg->dtag_first; ; act = act->dta_next) {
17195 ASSERT(act->dta_intuple ||
17196 DTRACEACT_ISAGG(act->dta_kind));
17199 * If this action has a record size of zero, it
17200 * denotes an argument to the aggregating action.
17201 * Because the presence of this record doesn't (or
17202 * shouldn't) affect the way the data is interpreted,
17203 * we don't copy it out to save user-level the
17204 * confusion of dealing with a zero-length record.
17206 if (act->dta_rec.dtrd_size == 0) {
17207 ASSERT(agg->dtag_hasarg);
17211 aggdesc.dtagd_nrecs++;
17213 if (act == &agg->dtag_action)
17218 * Now that we have the size, we need to allocate a temporary
17219 * buffer in which to store the complete description. We need
17220 * the temporary buffer to be able to drop dtrace_lock()
17221 * across the copyout(), below.
17223 size = sizeof (dtrace_aggdesc_t) +
17224 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17226 buf = kmem_alloc(size, KM_SLEEP);
17227 dest = (uintptr_t)buf;
17229 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17230 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17232 for (act = agg->dtag_first; ; act = act->dta_next) {
17233 dtrace_recdesc_t rec = act->dta_rec;
17236 * See the comment in the above loop for why we pass
17237 * over zero-length records.
17239 if (rec.dtrd_size == 0) {
17240 ASSERT(agg->dtag_hasarg);
17247 rec.dtrd_offset -= offs;
17248 bcopy(&rec, (void *)dest, sizeof (rec));
17249 dest += sizeof (dtrace_recdesc_t);
17251 if (act == &agg->dtag_action)
17255 mutex_exit(&dtrace_lock);
17257 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17258 kmem_free(buf, size);
17262 kmem_free(buf, size);
17266 case DTRACEIOC_ENABLE: {
17268 dtrace_enabling_t *enab = NULL;
17269 dtrace_vstate_t *vstate;
17275 * If a NULL argument has been passed, we take this as our
17276 * cue to reevaluate our enablings.
17279 dtrace_enabling_matchall();
17284 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17287 mutex_enter(&cpu_lock);
17288 mutex_enter(&dtrace_lock);
17289 vstate = &state->dts_vstate;
17291 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17292 mutex_exit(&dtrace_lock);
17293 mutex_exit(&cpu_lock);
17294 dtrace_dof_destroy(dof);
17298 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17299 mutex_exit(&dtrace_lock);
17300 mutex_exit(&cpu_lock);
17301 dtrace_dof_destroy(dof);
17305 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17306 dtrace_enabling_destroy(enab);
17307 mutex_exit(&dtrace_lock);
17308 mutex_exit(&cpu_lock);
17309 dtrace_dof_destroy(dof);
17313 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17314 err = dtrace_enabling_retain(enab);
17316 dtrace_enabling_destroy(enab);
17319 mutex_exit(&cpu_lock);
17320 mutex_exit(&dtrace_lock);
17321 dtrace_dof_destroy(dof);
17326 case DTRACEIOC_REPLICATE: {
17327 dtrace_repldesc_t desc;
17328 dtrace_probedesc_t *match = &desc.dtrpd_match;
17329 dtrace_probedesc_t *create = &desc.dtrpd_create;
17332 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17335 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17336 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17337 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17338 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17340 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17341 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17342 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17343 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17345 mutex_enter(&dtrace_lock);
17346 err = dtrace_enabling_replicate(state, match, create);
17347 mutex_exit(&dtrace_lock);
17352 case DTRACEIOC_PROBEMATCH:
17353 case DTRACEIOC_PROBES: {
17354 dtrace_probe_t *probe = NULL;
17355 dtrace_probedesc_t desc;
17356 dtrace_probekey_t pkey;
17363 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17366 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17367 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17368 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17369 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17372 * Before we attempt to match this probe, we want to give
17373 * all providers the opportunity to provide it.
17375 if (desc.dtpd_id == DTRACE_IDNONE) {
17376 mutex_enter(&dtrace_provider_lock);
17377 dtrace_probe_provide(&desc, NULL);
17378 mutex_exit(&dtrace_provider_lock);
17382 if (cmd == DTRACEIOC_PROBEMATCH) {
17383 dtrace_probekey(&desc, &pkey);
17384 pkey.dtpk_id = DTRACE_IDNONE;
17387 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17389 mutex_enter(&dtrace_lock);
17391 if (cmd == DTRACEIOC_PROBEMATCH) {
17392 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17393 if ((probe = dtrace_probes[i - 1]) != NULL &&
17394 (m = dtrace_match_probe(probe, &pkey,
17395 priv, uid, zoneid)) != 0)
17400 mutex_exit(&dtrace_lock);
17405 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17406 if ((probe = dtrace_probes[i - 1]) != NULL &&
17407 dtrace_match_priv(probe, priv, uid, zoneid))
17412 if (probe == NULL) {
17413 mutex_exit(&dtrace_lock);
17417 dtrace_probe_description(probe, &desc);
17418 mutex_exit(&dtrace_lock);
17420 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17426 case DTRACEIOC_PROBEARG: {
17427 dtrace_argdesc_t desc;
17428 dtrace_probe_t *probe;
17429 dtrace_provider_t *prov;
17431 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17434 if (desc.dtargd_id == DTRACE_IDNONE)
17437 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17440 mutex_enter(&dtrace_provider_lock);
17441 mutex_enter(&mod_lock);
17442 mutex_enter(&dtrace_lock);
17444 if (desc.dtargd_id > dtrace_nprobes) {
17445 mutex_exit(&dtrace_lock);
17446 mutex_exit(&mod_lock);
17447 mutex_exit(&dtrace_provider_lock);
17451 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17452 mutex_exit(&dtrace_lock);
17453 mutex_exit(&mod_lock);
17454 mutex_exit(&dtrace_provider_lock);
17458 mutex_exit(&dtrace_lock);
17460 prov = probe->dtpr_provider;
17462 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17464 * There isn't any typed information for this probe.
17465 * Set the argument number to DTRACE_ARGNONE.
17467 desc.dtargd_ndx = DTRACE_ARGNONE;
17469 desc.dtargd_native[0] = '\0';
17470 desc.dtargd_xlate[0] = '\0';
17471 desc.dtargd_mapping = desc.dtargd_ndx;
17473 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17474 probe->dtpr_id, probe->dtpr_arg, &desc);
17477 mutex_exit(&mod_lock);
17478 mutex_exit(&dtrace_provider_lock);
17480 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17486 case DTRACEIOC_GO: {
17487 processorid_t cpuid;
17488 rval = dtrace_state_go(state, &cpuid);
17493 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17499 case DTRACEIOC_STOP: {
17500 processorid_t cpuid;
17502 mutex_enter(&dtrace_lock);
17503 rval = dtrace_state_stop(state, &cpuid);
17504 mutex_exit(&dtrace_lock);
17509 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17515 case DTRACEIOC_DOFGET: {
17516 dof_hdr_t hdr, *dof;
17519 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17522 mutex_enter(&dtrace_lock);
17523 dof = dtrace_dof_create(state);
17524 mutex_exit(&dtrace_lock);
17526 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17527 rval = copyout(dof, (void *)arg, len);
17528 dtrace_dof_destroy(dof);
17530 return (rval == 0 ? 0 : EFAULT);
17533 case DTRACEIOC_AGGSNAP:
17534 case DTRACEIOC_BUFSNAP: {
17535 dtrace_bufdesc_t desc;
17537 dtrace_buffer_t *buf;
17539 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17542 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17545 mutex_enter(&dtrace_lock);
17547 if (cmd == DTRACEIOC_BUFSNAP) {
17548 buf = &state->dts_buffer[desc.dtbd_cpu];
17550 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17553 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17554 size_t sz = buf->dtb_offset;
17556 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17557 mutex_exit(&dtrace_lock);
17562 * If this buffer has already been consumed, we're
17563 * going to indicate that there's nothing left here
17566 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17567 mutex_exit(&dtrace_lock);
17569 desc.dtbd_size = 0;
17570 desc.dtbd_drops = 0;
17571 desc.dtbd_errors = 0;
17572 desc.dtbd_oldest = 0;
17573 sz = sizeof (desc);
17575 if (copyout(&desc, (void *)arg, sz) != 0)
17582 * If this is a ring buffer that has wrapped, we want
17583 * to copy the whole thing out.
17585 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17586 dtrace_buffer_polish(buf);
17587 sz = buf->dtb_size;
17590 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17591 mutex_exit(&dtrace_lock);
17595 desc.dtbd_size = sz;
17596 desc.dtbd_drops = buf->dtb_drops;
17597 desc.dtbd_errors = buf->dtb_errors;
17598 desc.dtbd_oldest = buf->dtb_xamot_offset;
17599 desc.dtbd_timestamp = dtrace_gethrtime();
17601 mutex_exit(&dtrace_lock);
17603 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17606 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17611 if (buf->dtb_tomax == NULL) {
17612 ASSERT(buf->dtb_xamot == NULL);
17613 mutex_exit(&dtrace_lock);
17617 cached = buf->dtb_tomax;
17618 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17620 dtrace_xcall(desc.dtbd_cpu,
17621 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17623 state->dts_errors += buf->dtb_xamot_errors;
17626 * If the buffers did not actually switch, then the cross call
17627 * did not take place -- presumably because the given CPU is
17628 * not in the ready set. If this is the case, we'll return
17631 if (buf->dtb_tomax == cached) {
17632 ASSERT(buf->dtb_xamot != cached);
17633 mutex_exit(&dtrace_lock);
17637 ASSERT(cached == buf->dtb_xamot);
17640 * We have our snapshot; now copy it out.
17642 if (copyout(buf->dtb_xamot, desc.dtbd_data,
17643 buf->dtb_xamot_offset) != 0) {
17644 mutex_exit(&dtrace_lock);
17648 desc.dtbd_size = buf->dtb_xamot_offset;
17649 desc.dtbd_drops = buf->dtb_xamot_drops;
17650 desc.dtbd_errors = buf->dtb_xamot_errors;
17651 desc.dtbd_oldest = 0;
17652 desc.dtbd_timestamp = buf->dtb_switched;
17654 mutex_exit(&dtrace_lock);
17657 * Finally, copy out the buffer description.
17659 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17665 case DTRACEIOC_CONF: {
17666 dtrace_conf_t conf;
17668 bzero(&conf, sizeof (conf));
17669 conf.dtc_difversion = DIF_VERSION;
17670 conf.dtc_difintregs = DIF_DIR_NREGS;
17671 conf.dtc_diftupregs = DIF_DTR_NREGS;
17672 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17674 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17680 case DTRACEIOC_STATUS: {
17681 dtrace_status_t stat;
17682 dtrace_dstate_t *dstate;
17687 * See the comment in dtrace_state_deadman() for the reason
17688 * for setting dts_laststatus to INT64_MAX before setting
17689 * it to the correct value.
17691 state->dts_laststatus = INT64_MAX;
17692 dtrace_membar_producer();
17693 state->dts_laststatus = dtrace_gethrtime();
17695 bzero(&stat, sizeof (stat));
17697 mutex_enter(&dtrace_lock);
17699 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17700 mutex_exit(&dtrace_lock);
17704 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17705 stat.dtst_exiting = 1;
17707 nerrs = state->dts_errors;
17708 dstate = &state->dts_vstate.dtvs_dynvars;
17710 for (i = 0; i < NCPU; i++) {
17711 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17713 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17714 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17715 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17717 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17718 stat.dtst_filled++;
17720 nerrs += state->dts_buffer[i].dtb_errors;
17722 for (j = 0; j < state->dts_nspeculations; j++) {
17723 dtrace_speculation_t *spec;
17724 dtrace_buffer_t *buf;
17726 spec = &state->dts_speculations[j];
17727 buf = &spec->dtsp_buffer[i];
17728 stat.dtst_specdrops += buf->dtb_xamot_drops;
17732 stat.dtst_specdrops_busy = state->dts_speculations_busy;
17733 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17734 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17735 stat.dtst_dblerrors = state->dts_dblerrors;
17737 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17738 stat.dtst_errors = nerrs;
17740 mutex_exit(&dtrace_lock);
17742 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17748 case DTRACEIOC_FORMAT: {
17749 dtrace_fmtdesc_t fmt;
17753 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17756 mutex_enter(&dtrace_lock);
17758 if (fmt.dtfd_format == 0 ||
17759 fmt.dtfd_format > state->dts_nformats) {
17760 mutex_exit(&dtrace_lock);
17765 * Format strings are allocated contiguously and they are
17766 * never freed; if a format index is less than the number
17767 * of formats, we can assert that the format map is non-NULL
17768 * and that the format for the specified index is non-NULL.
17770 ASSERT(state->dts_formats != NULL);
17771 str = state->dts_formats[fmt.dtfd_format - 1];
17772 ASSERT(str != NULL);
17774 len = strlen(str) + 1;
17776 if (len > fmt.dtfd_length) {
17777 fmt.dtfd_length = len;
17779 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17780 mutex_exit(&dtrace_lock);
17784 if (copyout(str, fmt.dtfd_string, len) != 0) {
17785 mutex_exit(&dtrace_lock);
17790 mutex_exit(&dtrace_lock);
17803 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17805 dtrace_state_t *state;
17812 return (DDI_SUCCESS);
17815 return (DDI_FAILURE);
17818 mutex_enter(&cpu_lock);
17819 mutex_enter(&dtrace_provider_lock);
17820 mutex_enter(&dtrace_lock);
17822 ASSERT(dtrace_opens == 0);
17824 if (dtrace_helpers > 0) {
17825 mutex_exit(&dtrace_provider_lock);
17826 mutex_exit(&dtrace_lock);
17827 mutex_exit(&cpu_lock);
17828 return (DDI_FAILURE);
17831 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17832 mutex_exit(&dtrace_provider_lock);
17833 mutex_exit(&dtrace_lock);
17834 mutex_exit(&cpu_lock);
17835 return (DDI_FAILURE);
17838 dtrace_provider = NULL;
17840 if ((state = dtrace_anon_grab()) != NULL) {
17842 * If there were ECBs on this state, the provider should
17843 * have not been allowed to detach; assert that there is
17846 ASSERT(state->dts_necbs == 0);
17847 dtrace_state_destroy(state);
17850 * If we're being detached with anonymous state, we need to
17851 * indicate to the kernel debugger that DTrace is now inactive.
17853 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17856 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17857 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17858 dtrace_cpu_init = NULL;
17859 dtrace_helpers_cleanup = NULL;
17860 dtrace_helpers_fork = NULL;
17861 dtrace_cpustart_init = NULL;
17862 dtrace_cpustart_fini = NULL;
17863 dtrace_debugger_init = NULL;
17864 dtrace_debugger_fini = NULL;
17865 dtrace_modload = NULL;
17866 dtrace_modunload = NULL;
17868 ASSERT(dtrace_getf == 0);
17869 ASSERT(dtrace_closef == NULL);
17871 mutex_exit(&cpu_lock);
17873 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17874 dtrace_probes = NULL;
17875 dtrace_nprobes = 0;
17877 dtrace_hash_destroy(dtrace_bymod);
17878 dtrace_hash_destroy(dtrace_byfunc);
17879 dtrace_hash_destroy(dtrace_byname);
17880 dtrace_bymod = NULL;
17881 dtrace_byfunc = NULL;
17882 dtrace_byname = NULL;
17884 kmem_cache_destroy(dtrace_state_cache);
17885 vmem_destroy(dtrace_minor);
17886 vmem_destroy(dtrace_arena);
17888 if (dtrace_toxrange != NULL) {
17889 kmem_free(dtrace_toxrange,
17890 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17891 dtrace_toxrange = NULL;
17892 dtrace_toxranges = 0;
17893 dtrace_toxranges_max = 0;
17896 ddi_remove_minor_node(dtrace_devi, NULL);
17897 dtrace_devi = NULL;
17899 ddi_soft_state_fini(&dtrace_softstate);
17901 ASSERT(dtrace_vtime_references == 0);
17902 ASSERT(dtrace_opens == 0);
17903 ASSERT(dtrace_retained == NULL);
17905 mutex_exit(&dtrace_lock);
17906 mutex_exit(&dtrace_provider_lock);
17909 * We don't destroy the task queue until after we have dropped our
17910 * locks (taskq_destroy() may block on running tasks). To prevent
17911 * attempting to do work after we have effectively detached but before
17912 * the task queue has been destroyed, all tasks dispatched via the
17913 * task queue must check that DTrace is still attached before
17914 * performing any operation.
17916 taskq_destroy(dtrace_taskq);
17917 dtrace_taskq = NULL;
17919 return (DDI_SUCCESS);
17926 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17931 case DDI_INFO_DEVT2DEVINFO:
17932 *result = (void *)dtrace_devi;
17933 error = DDI_SUCCESS;
17935 case DDI_INFO_DEVT2INSTANCE:
17936 *result = (void *)0;
17937 error = DDI_SUCCESS;
17940 error = DDI_FAILURE;
17947 static struct cb_ops dtrace_cb_ops = {
17948 dtrace_open, /* open */
17949 dtrace_close, /* close */
17950 nulldev, /* strategy */
17951 nulldev, /* print */
17955 dtrace_ioctl, /* ioctl */
17956 nodev, /* devmap */
17958 nodev, /* segmap */
17959 nochpoll, /* poll */
17960 ddi_prop_op, /* cb_prop_op */
17962 D_NEW | D_MP /* Driver compatibility flag */
17965 static struct dev_ops dtrace_ops = {
17966 DEVO_REV, /* devo_rev */
17968 dtrace_info, /* get_dev_info */
17969 nulldev, /* identify */
17970 nulldev, /* probe */
17971 dtrace_attach, /* attach */
17972 dtrace_detach, /* detach */
17974 &dtrace_cb_ops, /* driver operations */
17975 NULL, /* bus operations */
17976 nodev /* dev power */
17979 static struct modldrv modldrv = {
17980 &mod_driverops, /* module type (this is a pseudo driver) */
17981 "Dynamic Tracing", /* name of module */
17982 &dtrace_ops, /* driver ops */
17985 static struct modlinkage modlinkage = {
17994 return (mod_install(&modlinkage));
17998 _info(struct modinfo *modinfop)
18000 return (mod_info(&modlinkage, modinfop));
18006 return (mod_remove(&modlinkage));
18010 static d_ioctl_t dtrace_ioctl;
18011 static d_ioctl_t dtrace_ioctl_helper;
18012 static void dtrace_load(void *);
18013 static int dtrace_unload(void);
18014 static struct cdev *dtrace_dev;
18015 static struct cdev *helper_dev;
18017 void dtrace_invop_init(void);
18018 void dtrace_invop_uninit(void);
18020 static struct cdevsw dtrace_cdevsw = {
18021 .d_version = D_VERSION,
18022 .d_ioctl = dtrace_ioctl,
18023 .d_open = dtrace_open,
18024 .d_name = "dtrace",
18027 static struct cdevsw helper_cdevsw = {
18028 .d_version = D_VERSION,
18029 .d_ioctl = dtrace_ioctl_helper,
18030 .d_name = "helper",
18033 #include <dtrace_anon.c>
18034 #include <dtrace_ioctl.c>
18035 #include <dtrace_load.c>
18036 #include <dtrace_modevent.c>
18037 #include <dtrace_sysctl.c>
18038 #include <dtrace_unload.c>
18039 #include <dtrace_vtime.c>
18040 #include <dtrace_hacks.c>
18041 #include <dtrace_isa.c>
18043 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18044 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18045 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18047 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18048 MODULE_VERSION(dtrace, 1);
18049 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);