4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
25 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
26 * Copyright (c) 2016, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
31 * DTrace - Dynamic Tracing for Solaris
33 * This is the implementation of the Solaris Dynamic Tracing framework
34 * (DTrace). The user-visible interface to DTrace is described at length in
35 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
36 * library, the in-kernel DTrace framework, and the DTrace providers are
37 * described in the block comments in the <sys/dtrace.h> header file. The
38 * internal architecture of DTrace is described in the block comments in the
39 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
40 * implementation very much assume mastery of all of these sources; if one has
41 * an unanswered question about the implementation, one should consult them
44 * The functions here are ordered roughly as follows:
46 * - Probe context functions
47 * - Probe hashing functions
48 * - Non-probe context utility functions
49 * - Matching functions
50 * - Provider-to-Framework API functions
51 * - Probe management functions
52 * - DIF object functions
54 * - Predicate functions
57 * - Enabling functions
59 * - Anonymous enabling functions
60 * - Consumer state functions
63 * - Driver cookbook functions
65 * Each group of functions begins with a block comment labelled the "DTrace
66 * [Group] Functions", allowing one to find each block by searching forward
67 * on capital-f functions.
69 #include <sys/errno.h>
70 #include <sys/param.h>
71 #include <sys/types.h>
77 #include <sys/systm.h>
78 #include <sys/endian.h>
81 #include <sys/sunddi.h>
83 #include <sys/cpuvar.h>
86 #include <sys/strsubr.h>
88 #include <sys/sysmacros.h>
89 #include <sys/dtrace_impl.h>
90 #include <sys/atomic.h>
91 #include <sys/cmn_err.h>
93 #include <sys/mutex_impl.h>
94 #include <sys/rwlock_impl.h>
96 #include <sys/ctf_api.h>
98 #include <sys/panic.h>
99 #include <sys/priv_impl.h>
102 #include <sys/cred_impl.h>
103 #include <sys/procfs_isa.h>
105 #include <sys/taskq.h>
107 #include <sys/mkdev.h>
110 #include <sys/zone.h>
111 #include <sys/socket.h>
112 #include <netinet/in.h>
113 #include "strtolctype.h"
115 /* FreeBSD includes: */
117 #include <sys/callout.h>
118 #include <sys/ctype.h>
119 #include <sys/eventhandler.h>
120 #include <sys/limits.h>
121 #include <sys/linker.h>
123 #include <sys/jail.h>
124 #include <sys/kernel.h>
125 #include <sys/malloc.h>
126 #include <sys/lock.h>
127 #include <sys/mutex.h>
128 #include <sys/ptrace.h>
129 #include <sys/random.h>
130 #include <sys/rwlock.h>
132 #include <sys/sysctl.h>
135 #include <sys/mount.h>
138 #include <sys/vnode.h>
139 #include <sys/cred.h>
141 #include <sys/dtrace_bsd.h>
143 #include <netinet/in.h>
145 #include "dtrace_cddl.h"
146 #include "dtrace_debug.c"
149 #include "dtrace_xoroshiro128_plus.h"
152 * DTrace Tunable Variables
154 * The following variables may be tuned by adding a line to /etc/system that
155 * includes both the name of the DTrace module ("dtrace") and the name of the
156 * variable. For example:
158 * set dtrace:dtrace_destructive_disallow = 1
160 * In general, the only variables that one should be tuning this way are those
161 * that affect system-wide DTrace behavior, and for which the default behavior
162 * is undesirable. Most of these variables are tunable on a per-consumer
163 * basis using DTrace options, and need not be tuned on a system-wide basis.
164 * When tuning these variables, avoid pathological values; while some attempt
165 * is made to verify the integrity of these variables, they are not considered
166 * part of the supported interface to DTrace, and they are therefore not
167 * checked comprehensively. Further, these variables should not be tuned
168 * dynamically via "mdb -kw" or other means; they should only be tuned via
171 int dtrace_destructive_disallow = 0;
173 /* Positive logic version of dtrace_destructive_disallow for loader tunable */
174 int dtrace_allow_destructive = 1;
176 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
177 size_t dtrace_difo_maxsize = (256 * 1024);
178 dtrace_optval_t dtrace_dof_maxsize = (8 * 1024 * 1024);
179 size_t dtrace_statvar_maxsize = (16 * 1024);
180 size_t dtrace_actions_max = (16 * 1024);
181 size_t dtrace_retain_max = 1024;
182 dtrace_optval_t dtrace_helper_actions_max = 128;
183 dtrace_optval_t dtrace_helper_providers_max = 32;
184 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
185 size_t dtrace_strsize_default = 256;
186 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
187 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
188 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
189 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
190 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
191 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
192 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
193 dtrace_optval_t dtrace_nspec_default = 1;
194 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
195 dtrace_optval_t dtrace_stackframes_default = 20;
196 dtrace_optval_t dtrace_ustackframes_default = 20;
197 dtrace_optval_t dtrace_jstackframes_default = 50;
198 dtrace_optval_t dtrace_jstackstrsize_default = 512;
199 int dtrace_msgdsize_max = 128;
200 hrtime_t dtrace_chill_max = MSEC2NSEC(500); /* 500 ms */
201 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
202 int dtrace_devdepth_max = 32;
203 int dtrace_err_verbose;
204 hrtime_t dtrace_deadman_interval = NANOSEC;
205 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
206 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
207 hrtime_t dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
209 int dtrace_memstr_max = 4096;
213 * DTrace External Variables
215 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
216 * available to DTrace consumers via the backtick (`) syntax. One of these,
217 * dtrace_zero, is made deliberately so: it is provided as a source of
218 * well-known, zero-filled memory. While this variable is not documented,
219 * it is used by some translators as an implementation detail.
221 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
224 * DTrace Internal Variables
227 static dev_info_t *dtrace_devi; /* device info */
230 static vmem_t *dtrace_arena; /* probe ID arena */
231 static vmem_t *dtrace_minor; /* minor number arena */
233 static taskq_t *dtrace_taskq; /* task queue */
234 static struct unrhdr *dtrace_arena; /* Probe ID number. */
236 static dtrace_probe_t **dtrace_probes; /* array of all probes */
237 static int dtrace_nprobes; /* number of probes */
238 static dtrace_provider_t *dtrace_provider; /* provider list */
239 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
240 static int dtrace_opens; /* number of opens */
241 static int dtrace_helpers; /* number of helpers */
242 static int dtrace_getf; /* number of unpriv getf()s */
244 static void *dtrace_softstate; /* softstate pointer */
246 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
247 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
248 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
249 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
250 static int dtrace_toxranges; /* number of toxic ranges */
251 static int dtrace_toxranges_max; /* size of toxic range array */
252 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
253 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
254 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
255 static kthread_t *dtrace_panicked; /* panicking thread */
256 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
257 static dtrace_genid_t dtrace_probegen; /* current probe generation */
258 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
259 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
260 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
261 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
262 static int dtrace_dynvar_failclean; /* dynvars failed to clean */
264 static struct mtx dtrace_unr_mtx;
265 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
266 static eventhandler_tag dtrace_kld_load_tag;
267 static eventhandler_tag dtrace_kld_unload_try_tag;
272 * DTrace is protected by three (relatively coarse-grained) locks:
274 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
275 * including enabling state, probes, ECBs, consumer state, helper state,
276 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
277 * probe context is lock-free -- synchronization is handled via the
278 * dtrace_sync() cross call mechanism.
280 * (2) dtrace_provider_lock is required when manipulating provider state, or
281 * when provider state must be held constant.
283 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
284 * when meta provider state must be held constant.
286 * The lock ordering between these three locks is dtrace_meta_lock before
287 * dtrace_provider_lock before dtrace_lock. (In particular, there are
288 * several places where dtrace_provider_lock is held by the framework as it
289 * calls into the providers -- which then call back into the framework,
290 * grabbing dtrace_lock.)
292 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
293 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
294 * role as a coarse-grained lock; it is acquired before both of these locks.
295 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
296 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
297 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
298 * acquired _between_ dtrace_provider_lock and dtrace_lock.
300 static kmutex_t dtrace_lock; /* probe state lock */
301 static kmutex_t dtrace_provider_lock; /* provider state lock */
302 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
305 /* XXX FreeBSD hacks. */
306 #define cr_suid cr_svuid
307 #define cr_sgid cr_svgid
308 #define ipaddr_t in_addr_t
309 #define mod_modname pathname
310 #define vuprintf vprintf
312 #define crgetzoneid(_a) 0
314 #define ttoproc(_a) ((_a)->td_proc)
316 #define CPU_ON_INTR(_a) 0
318 #define PRIV_EFFECTIVE (1 << 0)
319 #define PRIV_DTRACE_KERNEL (1 << 1)
320 #define PRIV_DTRACE_PROC (1 << 2)
321 #define PRIV_DTRACE_USER (1 << 3)
322 #define PRIV_PROC_OWNER (1 << 4)
323 #define PRIV_PROC_ZONE (1 << 5)
326 SYSCTL_DECL(_debug_dtrace);
327 SYSCTL_DECL(_kern_dtrace);
331 #define curcpu CPU->cpu_id
336 * DTrace Provider Variables
338 * These are the variables relating to DTrace as a provider (that is, the
339 * provider of the BEGIN, END, and ERROR probes).
341 static dtrace_pattr_t dtrace_provider_attr = {
342 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
343 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
344 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
345 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
346 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
353 static dtrace_pops_t dtrace_provider_ops = {
354 .dtps_provide = (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
355 .dtps_provide_module = (void (*)(void *, modctl_t *))dtrace_nullop,
356 .dtps_enable = (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
357 .dtps_disable = (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
358 .dtps_suspend = (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
359 .dtps_resume = (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
360 .dtps_getargdesc = NULL,
361 .dtps_getargval = NULL,
362 .dtps_usermode = NULL,
363 .dtps_destroy = (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
366 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
367 static dtrace_id_t dtrace_probeid_end; /* special END probe */
368 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
371 * DTrace Helper Tracing Variables
373 * These variables should be set dynamically to enable helper tracing. The
374 * only variables that should be set are dtrace_helptrace_enable (which should
375 * be set to a non-zero value to allocate helper tracing buffers on the next
376 * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
377 * non-zero value to deallocate helper tracing buffers on the next close of
378 * /dev/dtrace). When (and only when) helper tracing is disabled, the
379 * buffer size may also be set via dtrace_helptrace_bufsize.
381 int dtrace_helptrace_enable = 0;
382 int dtrace_helptrace_disable = 0;
383 int dtrace_helptrace_bufsize = 16 * 1024 * 1024;
384 uint32_t dtrace_helptrace_nlocals;
385 static dtrace_helptrace_t *dtrace_helptrace_buffer;
386 static uint32_t dtrace_helptrace_next = 0;
387 static int dtrace_helptrace_wrapped = 0;
390 * DTrace Error Hashing
392 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
393 * table. This is very useful for checking coverage of tests that are
394 * expected to induce DIF or DOF processing errors, and may be useful for
395 * debugging problems in the DIF code generator or in DOF generation . The
396 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
399 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
400 static const char *dtrace_errlast;
401 static kthread_t *dtrace_errthread;
402 static kmutex_t dtrace_errlock;
406 * DTrace Macros and Constants
408 * These are various macros that are useful in various spots in the
409 * implementation, along with a few random constants that have no meaning
410 * outside of the implementation. There is no real structure to this cpp
411 * mishmash -- but is there ever?
413 #define DTRACE_HASHSTR(hash, probe) \
414 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
416 #define DTRACE_HASHNEXT(hash, probe) \
417 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
419 #define DTRACE_HASHPREV(hash, probe) \
420 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
422 #define DTRACE_HASHEQ(hash, lhs, rhs) \
423 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
424 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
426 #define DTRACE_AGGHASHSIZE_SLEW 17
428 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
431 * The key for a thread-local variable consists of the lower 61 bits of the
432 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
433 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
434 * equal to a variable identifier. This is necessary (but not sufficient) to
435 * assure that global associative arrays never collide with thread-local
436 * variables. To guarantee that they cannot collide, we must also define the
437 * order for keying dynamic variables. That order is:
439 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
441 * Because the variable-key and the tls-key are in orthogonal spaces, there is
442 * no way for a global variable key signature to match a thread-local key
446 #define DTRACE_TLS_THRKEY(where) { \
448 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
449 for (; actv; actv >>= 1) \
451 ASSERT(intr < (1 << 3)); \
452 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
453 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
456 #define DTRACE_TLS_THRKEY(where) { \
457 solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
459 uint_t actv = _c->cpu_intr_actv; \
460 for (; actv; actv >>= 1) \
462 ASSERT(intr < (1 << 3)); \
463 (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
464 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
468 #define DT_BSWAP_8(x) ((x) & 0xff)
469 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
470 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
471 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
473 #define DT_MASK_LO 0x00000000FFFFFFFFULL
475 #define DTRACE_STORE(type, tomax, offset, what) \
476 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
478 #if !defined(__x86) && !defined(__aarch64__)
479 #define DTRACE_ALIGNCHECK(addr, size, flags) \
480 if (addr & (size - 1)) { \
481 *flags |= CPU_DTRACE_BADALIGN; \
482 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
486 #define DTRACE_ALIGNCHECK(addr, size, flags)
490 * Test whether a range of memory starting at testaddr of size testsz falls
491 * within the range of memory described by addr, sz. We take care to avoid
492 * problems with overflow and underflow of the unsigned quantities, and
493 * disallow all negative sizes. Ranges of size 0 are allowed.
495 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
496 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
497 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
498 (testaddr) + (testsz) >= (testaddr))
500 #define DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz) \
502 if ((remp) != NULL) { \
503 *(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr); \
509 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
510 * alloc_sz on the righthand side of the comparison in order to avoid overflow
511 * or underflow in the comparison with it. This is simpler than the INRANGE
512 * check above, because we know that the dtms_scratch_ptr is valid in the
513 * range. Allocations of size zero are allowed.
515 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
516 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
517 (mstate)->dtms_scratch_ptr >= (alloc_sz))
519 #define DTRACE_LOADFUNC(bits) \
522 dtrace_load##bits(uintptr_t addr) \
524 size_t size = bits / NBBY; \
526 uint##bits##_t rval; \
528 volatile uint16_t *flags = (volatile uint16_t *) \
529 &cpu_core[curcpu].cpuc_dtrace_flags; \
531 DTRACE_ALIGNCHECK(addr, size, flags); \
533 for (i = 0; i < dtrace_toxranges; i++) { \
534 if (addr >= dtrace_toxrange[i].dtt_limit) \
537 if (addr + size <= dtrace_toxrange[i].dtt_base) \
541 * This address falls within a toxic region; return 0. \
543 *flags |= CPU_DTRACE_BADADDR; \
544 cpu_core[curcpu].cpuc_dtrace_illval = addr; \
548 *flags |= CPU_DTRACE_NOFAULT; \
550 rval = *((volatile uint##bits##_t *)addr); \
551 *flags &= ~CPU_DTRACE_NOFAULT; \
553 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
557 #define dtrace_loadptr dtrace_load64
559 #define dtrace_loadptr dtrace_load32
562 #define DTRACE_DYNHASH_FREE 0
563 #define DTRACE_DYNHASH_SINK 1
564 #define DTRACE_DYNHASH_VALID 2
566 #define DTRACE_MATCH_NEXT 0
567 #define DTRACE_MATCH_DONE 1
568 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
569 #define DTRACE_STATE_ALIGN 64
571 #define DTRACE_FLAGS2FLT(flags) \
572 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
573 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
574 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
575 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
576 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
577 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
578 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
579 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
580 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
583 #define DTRACEACT_ISSTRING(act) \
584 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
585 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
587 /* Function prototype definitions: */
588 static size_t dtrace_strlen(const char *, size_t);
589 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
590 static void dtrace_enabling_provide(dtrace_provider_t *);
591 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
592 static void dtrace_enabling_matchall(void);
593 static void dtrace_enabling_reap(void);
594 static dtrace_state_t *dtrace_anon_grab(void);
595 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
596 dtrace_state_t *, uint64_t, uint64_t);
597 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
598 static void dtrace_buffer_drop(dtrace_buffer_t *);
599 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
600 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
601 dtrace_state_t *, dtrace_mstate_t *);
602 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
604 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
605 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
606 uint16_t dtrace_load16(uintptr_t);
607 uint32_t dtrace_load32(uintptr_t);
608 uint64_t dtrace_load64(uintptr_t);
609 uint8_t dtrace_load8(uintptr_t);
610 void dtrace_dynvar_clean(dtrace_dstate_t *);
611 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
612 size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
613 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
614 static int dtrace_priv_proc(dtrace_state_t *);
615 static void dtrace_getf_barrier(void);
616 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
617 dtrace_mstate_t *, dtrace_vstate_t *);
618 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
619 dtrace_mstate_t *, dtrace_vstate_t *);
622 * DTrace Probe Context Functions
624 * These functions are called from probe context. Because probe context is
625 * any context in which C may be called, arbitrarily locks may be held,
626 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
627 * As a result, functions called from probe context may only call other DTrace
628 * support functions -- they may not interact at all with the system at large.
629 * (Note that the ASSERT macro is made probe-context safe by redefining it in
630 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
631 * loads are to be performed from probe context, they _must_ be in terms of
632 * the safe dtrace_load*() variants.
634 * Some functions in this block are not actually called from probe context;
635 * for these functions, there will be a comment above the function reading
636 * "Note: not called from probe context."
639 dtrace_panic(const char *format, ...)
643 va_start(alist, format);
645 vpanic(format, alist);
647 dtrace_vpanic(format, alist);
653 dtrace_assfail(const char *a, const char *f, int l)
655 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
658 * We just need something here that even the most clever compiler
659 * cannot optimize away.
661 return (a[(uintptr_t)f]);
665 * Atomically increment a specified error counter from probe context.
668 dtrace_error(uint32_t *counter)
671 * Most counters stored to in probe context are per-CPU counters.
672 * However, there are some error conditions that are sufficiently
673 * arcane that they don't merit per-CPU storage. If these counters
674 * are incremented concurrently on different CPUs, scalability will be
675 * adversely affected -- but we don't expect them to be white-hot in a
676 * correctly constructed enabling...
683 if ((nval = oval + 1) == 0) {
685 * If the counter would wrap, set it to 1 -- assuring
686 * that the counter is never zero when we have seen
687 * errors. (The counter must be 32-bits because we
688 * aren't guaranteed a 64-bit compare&swap operation.)
689 * To save this code both the infamy of being fingered
690 * by a priggish news story and the indignity of being
691 * the target of a neo-puritan witch trial, we're
692 * carefully avoiding any colorful description of the
693 * likelihood of this condition -- but suffice it to
694 * say that it is only slightly more likely than the
695 * overflow of predicate cache IDs, as discussed in
696 * dtrace_predicate_create().
700 } while (dtrace_cas32(counter, oval, nval) != oval);
704 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
705 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
715 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
717 if (dest < mstate->dtms_scratch_base)
720 if (dest + size < dest)
723 if (dest + size > mstate->dtms_scratch_ptr)
730 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
731 dtrace_statvar_t **svars, int nsvars)
734 size_t maxglobalsize, maxlocalsize;
739 maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
740 maxlocalsize = maxglobalsize * NCPU;
742 for (i = 0; i < nsvars; i++) {
743 dtrace_statvar_t *svar = svars[i];
747 if (svar == NULL || (size = svar->dtsv_size) == 0)
750 scope = svar->dtsv_var.dtdv_scope;
753 * We verify that our size is valid in the spirit of providing
754 * defense in depth: we want to prevent attackers from using
755 * DTrace to escalate an orthogonal kernel heap corruption bug
756 * into the ability to store to arbitrary locations in memory.
758 VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
759 (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
761 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
763 DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
773 * Check to see if the address is within a memory region to which a store may
774 * be issued. This includes the DTrace scratch areas, and any DTrace variable
775 * region. The caller of dtrace_canstore() is responsible for performing any
776 * alignment checks that are needed before stores are actually executed.
779 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
780 dtrace_vstate_t *vstate)
782 return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
786 * Implementation of dtrace_canstore which communicates the upper bound of the
787 * allowed memory region.
790 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
791 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
794 * First, check to see if the address is in scratch space...
796 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
797 mstate->dtms_scratch_size)) {
798 DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
799 mstate->dtms_scratch_size);
804 * Now check to see if it's a dynamic variable. This check will pick
805 * up both thread-local variables and any global dynamically-allocated
808 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
809 vstate->dtvs_dynvars.dtds_size)) {
810 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
811 uintptr_t base = (uintptr_t)dstate->dtds_base +
812 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
814 dtrace_dynvar_t *dvar;
817 * Before we assume that we can store here, we need to make
818 * sure that it isn't in our metadata -- storing to our
819 * dynamic variable metadata would corrupt our state. For
820 * the range to not include any dynamic variable metadata,
823 * (1) Start above the hash table that is at the base of
824 * the dynamic variable space
826 * (2) Have a starting chunk offset that is beyond the
827 * dtrace_dynvar_t that is at the base of every chunk
829 * (3) Not span a chunk boundary
831 * (4) Not be in the tuple space of a dynamic variable
837 chunkoffs = (addr - base) % dstate->dtds_chunksize;
839 if (chunkoffs < sizeof (dtrace_dynvar_t))
842 if (chunkoffs + sz > dstate->dtds_chunksize)
845 dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
847 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
850 if (chunkoffs < sizeof (dtrace_dynvar_t) +
851 ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
854 DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
859 * Finally, check the static local and global variables. These checks
860 * take the longest, so we perform them last.
862 if (dtrace_canstore_statvar(addr, sz, remain,
863 vstate->dtvs_locals, vstate->dtvs_nlocals))
866 if (dtrace_canstore_statvar(addr, sz, remain,
867 vstate->dtvs_globals, vstate->dtvs_nglobals))
875 * Convenience routine to check to see if the address is within a memory
876 * region in which a load may be issued given the user's privilege level;
877 * if not, it sets the appropriate error flags and loads 'addr' into the
878 * illegal value slot.
880 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
881 * appropriate memory access protection.
884 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
885 dtrace_vstate_t *vstate)
887 return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
891 * Implementation of dtrace_canload which communicates the uppoer bound of the
892 * allowed memory region.
895 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
896 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
898 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
902 * If we hold the privilege to read from kernel memory, then
903 * everything is readable.
905 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
906 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
911 * You can obviously read that which you can store.
913 if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
917 * We're allowed to read from our own string table.
919 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
920 mstate->dtms_difo->dtdo_strlen)) {
921 DTRACE_RANGE_REMAIN(remain, addr,
922 mstate->dtms_difo->dtdo_strtab,
923 mstate->dtms_difo->dtdo_strlen);
927 if (vstate->dtvs_state != NULL &&
928 dtrace_priv_proc(vstate->dtvs_state)) {
932 * When we have privileges to the current process, there are
933 * several context-related kernel structures that are safe to
934 * read, even absent the privilege to read from kernel memory.
935 * These reads are safe because these structures contain only
936 * state that (1) we're permitted to read, (2) is harmless or
937 * (3) contains pointers to additional kernel state that we're
938 * not permitted to read (and as such, do not present an
939 * opportunity for privilege escalation). Finally (and
940 * critically), because of the nature of their relation with
941 * the current thread context, the memory associated with these
942 * structures cannot change over the duration of probe context,
943 * and it is therefore impossible for this memory to be
944 * deallocated and reallocated as something else while it's
945 * being operated upon.
947 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
948 DTRACE_RANGE_REMAIN(remain, addr, curthread,
953 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
954 sz, curthread->t_procp, sizeof (proc_t))) {
955 DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
960 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
961 curthread->t_cred, sizeof (cred_t))) {
962 DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
968 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
969 &(p->p_pidp->pid_id), sizeof (pid_t))) {
970 DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
975 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
976 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
977 DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
978 offsetof(cpu_t, cpu_pause_thread));
984 if ((fp = mstate->dtms_getf) != NULL) {
985 uintptr_t psz = sizeof (void *);
990 * When getf() returns a file_t, the enabling is implicitly
991 * granted the (transient) right to read the returned file_t
992 * as well as the v_path and v_op->vnop_name of the underlying
993 * vnode. These accesses are allowed after a successful
994 * getf() because the members that they refer to cannot change
995 * once set -- and the barrier logic in the kernel's closef()
996 * path assures that the file_t and its referenced vode_t
997 * cannot themselves be stale (that is, it impossible for
998 * either dtms_getf itself or its f_vnode member to reference
1001 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
1002 DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
1006 if ((vp = fp->f_vnode) != NULL) {
1009 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
1010 DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
1014 slen = strlen(vp->v_path) + 1;
1015 if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
1016 DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
1022 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
1023 DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
1029 if ((op = vp->v_op) != NULL &&
1030 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
1031 DTRACE_RANGE_REMAIN(remain, addr,
1032 &op->vnop_name, psz);
1036 if (op != NULL && op->vnop_name != NULL &&
1037 DTRACE_INRANGE(addr, sz, op->vnop_name,
1038 (slen = strlen(op->vnop_name) + 1))) {
1039 DTRACE_RANGE_REMAIN(remain, addr,
1040 op->vnop_name, slen);
1047 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1053 * Convenience routine to check to see if a given string is within a memory
1054 * region in which a load may be issued given the user's privilege level;
1055 * this exists so that we don't need to issue unnecessary dtrace_strlen()
1056 * calls in the event that the user has all privileges.
1059 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1060 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1065 * If we hold the privilege to read from kernel memory, then
1066 * everything is readable.
1068 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1069 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1074 * Even if the caller is uninterested in querying the remaining valid
1075 * range, it is required to ensure that the access is allowed.
1077 if (remain == NULL) {
1080 if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1083 * Perform the strlen after determining the length of the
1084 * memory region which is accessible. This prevents timing
1085 * information from being used to find NULs in memory which is
1086 * not accessible to the caller.
1088 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1090 if (strsz <= *remain) {
1099 * Convenience routine to check to see if a given variable is within a memory
1100 * region in which a load may be issued given the user's privilege level.
1103 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1104 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1107 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1110 * Calculate the max size before performing any checks since even
1111 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1112 * return the max length via 'remain'.
1114 if (type->dtdt_kind == DIF_TYPE_STRING) {
1115 dtrace_state_t *state = vstate->dtvs_state;
1117 if (state != NULL) {
1118 sz = state->dts_options[DTRACEOPT_STRSIZE];
1121 * In helper context, we have a NULL state; fall back
1122 * to using the system-wide default for the string size
1125 sz = dtrace_strsize_default;
1128 sz = type->dtdt_size;
1132 * If we hold the privilege to read from kernel memory, then
1133 * everything is readable.
1135 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1136 DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1140 if (type->dtdt_kind == DIF_TYPE_STRING) {
1141 return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1144 return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1149 * Convert a string to a signed integer using safe loads.
1151 * NOTE: This function uses various macros from strtolctype.h to manipulate
1152 * digit values, etc -- these have all been checked to ensure they make
1153 * no additional function calls.
1156 dtrace_strtoll(char *input, int base, size_t limit)
1158 uintptr_t pos = (uintptr_t)input;
1161 boolean_t neg = B_FALSE;
1163 uintptr_t end = pos + limit;
1166 * Consume any whitespace preceding digits.
1168 while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1172 * Handle an explicit sign if one is present.
1174 if (c == '-' || c == '+') {
1177 c = dtrace_load8(++pos);
1181 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1184 if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1185 cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1191 * Read in contiguous digits until the first non-digit character.
1193 for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1194 c = dtrace_load8(++pos))
1195 val = val * base + x;
1197 return (neg ? -val : val);
1201 * Compare two strings using safe loads.
1204 dtrace_strncmp(char *s1, char *s2, size_t limit)
1207 volatile uint16_t *flags;
1209 if (s1 == s2 || limit == 0)
1212 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1218 c1 = dtrace_load8((uintptr_t)s1++);
1224 c2 = dtrace_load8((uintptr_t)s2++);
1229 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1235 * Compute strlen(s) for a string using safe memory accesses. The additional
1236 * len parameter is used to specify a maximum length to ensure completion.
1239 dtrace_strlen(const char *s, size_t lim)
1243 for (len = 0; len != lim; len++) {
1244 if (dtrace_load8((uintptr_t)s++) == '\0')
1252 * Check if an address falls within a toxic region.
1255 dtrace_istoxic(uintptr_t kaddr, size_t size)
1257 uintptr_t taddr, tsize;
1260 for (i = 0; i < dtrace_toxranges; i++) {
1261 taddr = dtrace_toxrange[i].dtt_base;
1262 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1264 if (kaddr - taddr < tsize) {
1265 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1266 cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1270 if (taddr - kaddr < size) {
1271 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1272 cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1281 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1282 * memory specified by the DIF program. The dst is assumed to be safe memory
1283 * that we can store to directly because it is managed by DTrace. As with
1284 * standard bcopy, overlapping copies are handled properly.
1287 dtrace_bcopy(const void *src, void *dst, size_t len)
1291 const uint8_t *s2 = src;
1295 *s1++ = dtrace_load8((uintptr_t)s2++);
1296 } while (--len != 0);
1302 *--s1 = dtrace_load8((uintptr_t)--s2);
1303 } while (--len != 0);
1309 * Copy src to dst using safe memory accesses, up to either the specified
1310 * length, or the point that a nul byte is encountered. The src is assumed to
1311 * be unsafe memory specified by the DIF program. The dst is assumed to be
1312 * safe memory that we can store to directly because it is managed by DTrace.
1313 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1316 dtrace_strcpy(const void *src, void *dst, size_t len)
1319 uint8_t *s1 = dst, c;
1320 const uint8_t *s2 = src;
1323 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1324 } while (--len != 0 && c != '\0');
1329 * Copy src to dst, deriving the size and type from the specified (BYREF)
1330 * variable type. The src is assumed to be unsafe memory specified by the DIF
1331 * program. The dst is assumed to be DTrace variable memory that is of the
1332 * specified type; we assume that we can store to directly.
1335 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1337 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1339 if (type->dtdt_kind == DIF_TYPE_STRING) {
1340 dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1342 dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1347 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1348 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1349 * safe memory that we can access directly because it is managed by DTrace.
1352 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1354 volatile uint16_t *flags;
1356 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1361 if (s1 == NULL || s2 == NULL)
1364 if (s1 != s2 && len != 0) {
1365 const uint8_t *ps1 = s1;
1366 const uint8_t *ps2 = s2;
1369 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1371 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1377 * Zero the specified region using a simple byte-by-byte loop. Note that this
1378 * is for safe DTrace-managed memory only.
1381 dtrace_bzero(void *dst, size_t len)
1385 for (cp = dst; len != 0; len--)
1390 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1394 result[0] = addend1[0] + addend2[0];
1395 result[1] = addend1[1] + addend2[1] +
1396 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1403 * Shift the 128-bit value in a by b. If b is positive, shift left.
1404 * If b is negative, shift right.
1407 dtrace_shift_128(uint64_t *a, int b)
1417 a[0] = a[1] >> (b - 64);
1421 mask = 1LL << (64 - b);
1423 a[0] |= ((a[1] & mask) << (64 - b));
1428 a[1] = a[0] << (b - 64);
1432 mask = a[0] >> (64 - b);
1440 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1441 * use native multiplication on those, and then re-combine into the
1442 * resulting 128-bit value.
1444 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1451 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1453 uint64_t hi1, hi2, lo1, lo2;
1456 hi1 = factor1 >> 32;
1457 hi2 = factor2 >> 32;
1459 lo1 = factor1 & DT_MASK_LO;
1460 lo2 = factor2 & DT_MASK_LO;
1462 product[0] = lo1 * lo2;
1463 product[1] = hi1 * hi2;
1467 dtrace_shift_128(tmp, 32);
1468 dtrace_add_128(product, tmp, product);
1472 dtrace_shift_128(tmp, 32);
1473 dtrace_add_128(product, tmp, product);
1477 * This privilege check should be used by actions and subroutines to
1478 * verify that the user credentials of the process that enabled the
1479 * invoking ECB match the target credentials
1482 dtrace_priv_proc_common_user(dtrace_state_t *state)
1484 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1487 * We should always have a non-NULL state cred here, since if cred
1488 * is null (anonymous tracing), we fast-path bypass this routine.
1490 ASSERT(s_cr != NULL);
1492 if ((cr = CRED()) != NULL &&
1493 s_cr->cr_uid == cr->cr_uid &&
1494 s_cr->cr_uid == cr->cr_ruid &&
1495 s_cr->cr_uid == cr->cr_suid &&
1496 s_cr->cr_gid == cr->cr_gid &&
1497 s_cr->cr_gid == cr->cr_rgid &&
1498 s_cr->cr_gid == cr->cr_sgid)
1505 * This privilege check should be used by actions and subroutines to
1506 * verify that the zone of the process that enabled the invoking ECB
1507 * matches the target credentials
1510 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1513 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1516 * We should always have a non-NULL state cred here, since if cred
1517 * is null (anonymous tracing), we fast-path bypass this routine.
1519 ASSERT(s_cr != NULL);
1521 if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1531 * This privilege check should be used by actions and subroutines to
1532 * verify that the process has not setuid or changed credentials.
1535 dtrace_priv_proc_common_nocd(void)
1539 if ((proc = ttoproc(curthread)) != NULL &&
1540 !(proc->p_flag & SNOCD))
1547 dtrace_priv_proc_destructive(dtrace_state_t *state)
1549 int action = state->dts_cred.dcr_action;
1551 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1552 dtrace_priv_proc_common_zone(state) == 0)
1555 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1556 dtrace_priv_proc_common_user(state) == 0)
1559 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1560 dtrace_priv_proc_common_nocd() == 0)
1566 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1572 dtrace_priv_proc_control(dtrace_state_t *state)
1574 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1577 if (dtrace_priv_proc_common_zone(state) &&
1578 dtrace_priv_proc_common_user(state) &&
1579 dtrace_priv_proc_common_nocd())
1582 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1588 dtrace_priv_proc(dtrace_state_t *state)
1590 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1593 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1599 dtrace_priv_kernel(dtrace_state_t *state)
1601 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1604 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1610 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1612 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1615 cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1621 * Determine if the dte_cond of the specified ECB allows for processing of
1622 * the current probe to continue. Note that this routine may allow continued
1623 * processing, but with access(es) stripped from the mstate's dtms_access
1627 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1630 dtrace_probe_t *probe = ecb->dte_probe;
1631 dtrace_provider_t *prov = probe->dtpr_provider;
1632 dtrace_pops_t *pops = &prov->dtpv_pops;
1633 int mode = DTRACE_MODE_NOPRIV_DROP;
1635 ASSERT(ecb->dte_cond);
1638 if (pops->dtps_mode != NULL) {
1639 mode = pops->dtps_mode(prov->dtpv_arg,
1640 probe->dtpr_id, probe->dtpr_arg);
1642 ASSERT((mode & DTRACE_MODE_USER) ||
1643 (mode & DTRACE_MODE_KERNEL));
1644 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1645 (mode & DTRACE_MODE_NOPRIV_DROP));
1649 * If the dte_cond bits indicate that this consumer is only allowed to
1650 * see user-mode firings of this probe, call the provider's dtps_mode()
1651 * entry point to check that the probe was fired while in a user
1652 * context. If that's not the case, use the policy specified by the
1653 * provider to determine if we drop the probe or merely restrict
1656 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1657 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1659 if (!(mode & DTRACE_MODE_USER)) {
1660 if (mode & DTRACE_MODE_NOPRIV_DROP)
1663 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1669 * This is more subtle than it looks. We have to be absolutely certain
1670 * that CRED() isn't going to change out from under us so it's only
1671 * legit to examine that structure if we're in constrained situations.
1672 * Currently, the only times we'll this check is if a non-super-user
1673 * has enabled the profile or syscall providers -- providers that
1674 * allow visibility of all processes. For the profile case, the check
1675 * above will ensure that we're examining a user context.
1677 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1679 cred_t *s_cr = state->dts_cred.dcr_cred;
1682 ASSERT(s_cr != NULL);
1684 if ((cr = CRED()) == NULL ||
1685 s_cr->cr_uid != cr->cr_uid ||
1686 s_cr->cr_uid != cr->cr_ruid ||
1687 s_cr->cr_uid != cr->cr_suid ||
1688 s_cr->cr_gid != cr->cr_gid ||
1689 s_cr->cr_gid != cr->cr_rgid ||
1690 s_cr->cr_gid != cr->cr_sgid ||
1691 (proc = ttoproc(curthread)) == NULL ||
1692 (proc->p_flag & SNOCD)) {
1693 if (mode & DTRACE_MODE_NOPRIV_DROP)
1697 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1704 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1705 * in our zone, check to see if our mode policy is to restrict rather
1706 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1707 * and DTRACE_ACCESS_ARGS
1709 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1711 cred_t *s_cr = state->dts_cred.dcr_cred;
1713 ASSERT(s_cr != NULL);
1715 if ((cr = CRED()) == NULL ||
1716 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1717 if (mode & DTRACE_MODE_NOPRIV_DROP)
1720 mstate->dtms_access &=
1721 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1730 * Note: not called from probe context. This function is called
1731 * asynchronously (and at a regular interval) from outside of probe context to
1732 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1733 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1736 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1738 dtrace_dynvar_t *dirty;
1739 dtrace_dstate_percpu_t *dcpu;
1740 dtrace_dynvar_t **rinsep;
1743 for (i = 0; i < NCPU; i++) {
1744 dcpu = &dstate->dtds_percpu[i];
1745 rinsep = &dcpu->dtdsc_rinsing;
1748 * If the dirty list is NULL, there is no dirty work to do.
1750 if (dcpu->dtdsc_dirty == NULL)
1753 if (dcpu->dtdsc_rinsing != NULL) {
1755 * If the rinsing list is non-NULL, then it is because
1756 * this CPU was selected to accept another CPU's
1757 * dirty list -- and since that time, dirty buffers
1758 * have accumulated. This is a highly unlikely
1759 * condition, but we choose to ignore the dirty
1760 * buffers -- they'll be picked up a future cleanse.
1765 if (dcpu->dtdsc_clean != NULL) {
1767 * If the clean list is non-NULL, then we're in a
1768 * situation where a CPU has done deallocations (we
1769 * have a non-NULL dirty list) but no allocations (we
1770 * also have a non-NULL clean list). We can't simply
1771 * move the dirty list into the clean list on this
1772 * CPU, yet we also don't want to allow this condition
1773 * to persist, lest a short clean list prevent a
1774 * massive dirty list from being cleaned (which in
1775 * turn could lead to otherwise avoidable dynamic
1776 * drops). To deal with this, we look for some CPU
1777 * with a NULL clean list, NULL dirty list, and NULL
1778 * rinsing list -- and then we borrow this CPU to
1779 * rinse our dirty list.
1781 for (j = 0; j < NCPU; j++) {
1782 dtrace_dstate_percpu_t *rinser;
1784 rinser = &dstate->dtds_percpu[j];
1786 if (rinser->dtdsc_rinsing != NULL)
1789 if (rinser->dtdsc_dirty != NULL)
1792 if (rinser->dtdsc_clean != NULL)
1795 rinsep = &rinser->dtdsc_rinsing;
1801 * We were unable to find another CPU that
1802 * could accept this dirty list -- we are
1803 * therefore unable to clean it now.
1805 dtrace_dynvar_failclean++;
1813 * Atomically move the dirty list aside.
1816 dirty = dcpu->dtdsc_dirty;
1819 * Before we zap the dirty list, set the rinsing list.
1820 * (This allows for a potential assertion in
1821 * dtrace_dynvar(): if a free dynamic variable appears
1822 * on a hash chain, either the dirty list or the
1823 * rinsing list for some CPU must be non-NULL.)
1826 dtrace_membar_producer();
1827 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1828 dirty, NULL) != dirty);
1833 * We have no work to do; we can simply return.
1840 for (i = 0; i < NCPU; i++) {
1841 dcpu = &dstate->dtds_percpu[i];
1843 if (dcpu->dtdsc_rinsing == NULL)
1847 * We are now guaranteed that no hash chain contains a pointer
1848 * into this dirty list; we can make it clean.
1850 ASSERT(dcpu->dtdsc_clean == NULL);
1851 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1852 dcpu->dtdsc_rinsing = NULL;
1856 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1857 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1858 * This prevents a race whereby a CPU incorrectly decides that
1859 * the state should be something other than DTRACE_DSTATE_CLEAN
1860 * after dtrace_dynvar_clean() has completed.
1864 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1868 * Depending on the value of the op parameter, this function looks-up,
1869 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1870 * allocation is requested, this function will return a pointer to a
1871 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1872 * variable can be allocated. If NULL is returned, the appropriate counter
1873 * will be incremented.
1876 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1877 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1878 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1880 uint64_t hashval = DTRACE_DYNHASH_VALID;
1881 dtrace_dynhash_t *hash = dstate->dtds_hash;
1882 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1883 processorid_t me = curcpu, cpu = me;
1884 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1885 size_t bucket, ksize;
1886 size_t chunksize = dstate->dtds_chunksize;
1887 uintptr_t kdata, lock, nstate;
1893 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1894 * algorithm. For the by-value portions, we perform the algorithm in
1895 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1896 * bit, and seems to have only a minute effect on distribution. For
1897 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1898 * over each referenced byte. It's painful to do this, but it's much
1899 * better than pathological hash distribution. The efficacy of the
1900 * hashing algorithm (and a comparison with other algorithms) may be
1901 * found by running the ::dtrace_dynstat MDB dcmd.
1903 for (i = 0; i < nkeys; i++) {
1904 if (key[i].dttk_size == 0) {
1905 uint64_t val = key[i].dttk_value;
1907 hashval += (val >> 48) & 0xffff;
1908 hashval += (hashval << 10);
1909 hashval ^= (hashval >> 6);
1911 hashval += (val >> 32) & 0xffff;
1912 hashval += (hashval << 10);
1913 hashval ^= (hashval >> 6);
1915 hashval += (val >> 16) & 0xffff;
1916 hashval += (hashval << 10);
1917 hashval ^= (hashval >> 6);
1919 hashval += val & 0xffff;
1920 hashval += (hashval << 10);
1921 hashval ^= (hashval >> 6);
1924 * This is incredibly painful, but it beats the hell
1925 * out of the alternative.
1927 uint64_t j, size = key[i].dttk_size;
1928 uintptr_t base = (uintptr_t)key[i].dttk_value;
1930 if (!dtrace_canload(base, size, mstate, vstate))
1933 for (j = 0; j < size; j++) {
1934 hashval += dtrace_load8(base + j);
1935 hashval += (hashval << 10);
1936 hashval ^= (hashval >> 6);
1941 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1944 hashval += (hashval << 3);
1945 hashval ^= (hashval >> 11);
1946 hashval += (hashval << 15);
1949 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1950 * comes out to be one of our two sentinel hash values. If this
1951 * actually happens, we set the hashval to be a value known to be a
1952 * non-sentinel value.
1954 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1955 hashval = DTRACE_DYNHASH_VALID;
1958 * Yes, it's painful to do a divide here. If the cycle count becomes
1959 * important here, tricks can be pulled to reduce it. (However, it's
1960 * critical that hash collisions be kept to an absolute minimum;
1961 * they're much more painful than a divide.) It's better to have a
1962 * solution that generates few collisions and still keeps things
1963 * relatively simple.
1965 bucket = hashval % dstate->dtds_hashsize;
1967 if (op == DTRACE_DYNVAR_DEALLOC) {
1968 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1971 while ((lock = *lockp) & 1)
1974 if (dtrace_casptr((volatile void *)lockp,
1975 (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1979 dtrace_membar_producer();
1984 lock = hash[bucket].dtdh_lock;
1986 dtrace_membar_consumer();
1988 start = hash[bucket].dtdh_chain;
1989 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1990 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1991 op != DTRACE_DYNVAR_DEALLOC));
1993 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1994 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1995 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1997 if (dvar->dtdv_hashval != hashval) {
1998 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
2000 * We've reached the sink, and therefore the
2001 * end of the hash chain; we can kick out of
2002 * the loop knowing that we have seen a valid
2003 * snapshot of state.
2005 ASSERT(dvar->dtdv_next == NULL);
2006 ASSERT(dvar == &dtrace_dynhash_sink);
2010 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
2012 * We've gone off the rails: somewhere along
2013 * the line, one of the members of this hash
2014 * chain was deleted. Note that we could also
2015 * detect this by simply letting this loop run
2016 * to completion, as we would eventually hit
2017 * the end of the dirty list. However, we
2018 * want to avoid running the length of the
2019 * dirty list unnecessarily (it might be quite
2020 * long), so we catch this as early as
2021 * possible by detecting the hash marker. In
2022 * this case, we simply set dvar to NULL and
2023 * break; the conditional after the loop will
2024 * send us back to top.
2033 if (dtuple->dtt_nkeys != nkeys)
2036 for (i = 0; i < nkeys; i++, dkey++) {
2037 if (dkey->dttk_size != key[i].dttk_size)
2038 goto next; /* size or type mismatch */
2040 if (dkey->dttk_size != 0) {
2042 (void *)(uintptr_t)key[i].dttk_value,
2043 (void *)(uintptr_t)dkey->dttk_value,
2047 if (dkey->dttk_value != key[i].dttk_value)
2052 if (op != DTRACE_DYNVAR_DEALLOC)
2055 ASSERT(dvar->dtdv_next == NULL ||
2056 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
2059 ASSERT(hash[bucket].dtdh_chain != dvar);
2060 ASSERT(start != dvar);
2061 ASSERT(prev->dtdv_next == dvar);
2062 prev->dtdv_next = dvar->dtdv_next;
2064 if (dtrace_casptr(&hash[bucket].dtdh_chain,
2065 start, dvar->dtdv_next) != start) {
2067 * We have failed to atomically swing the
2068 * hash table head pointer, presumably because
2069 * of a conflicting allocation on another CPU.
2070 * We need to reread the hash chain and try
2077 dtrace_membar_producer();
2080 * Now set the hash value to indicate that it's free.
2082 ASSERT(hash[bucket].dtdh_chain != dvar);
2083 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2085 dtrace_membar_producer();
2088 * Set the next pointer to point at the dirty list, and
2089 * atomically swing the dirty pointer to the newly freed dvar.
2092 next = dcpu->dtdsc_dirty;
2093 dvar->dtdv_next = next;
2094 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
2097 * Finally, unlock this hash bucket.
2099 ASSERT(hash[bucket].dtdh_lock == lock);
2101 hash[bucket].dtdh_lock++;
2111 * If dvar is NULL, it is because we went off the rails:
2112 * one of the elements that we traversed in the hash chain
2113 * was deleted while we were traversing it. In this case,
2114 * we assert that we aren't doing a dealloc (deallocs lock
2115 * the hash bucket to prevent themselves from racing with
2116 * one another), and retry the hash chain traversal.
2118 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
2122 if (op != DTRACE_DYNVAR_ALLOC) {
2124 * If we are not to allocate a new variable, we want to
2125 * return NULL now. Before we return, check that the value
2126 * of the lock word hasn't changed. If it has, we may have
2127 * seen an inconsistent snapshot.
2129 if (op == DTRACE_DYNVAR_NOALLOC) {
2130 if (hash[bucket].dtdh_lock != lock)
2133 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2134 ASSERT(hash[bucket].dtdh_lock == lock);
2136 hash[bucket].dtdh_lock++;
2143 * We need to allocate a new dynamic variable. The size we need is the
2144 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2145 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2146 * the size of any referred-to data (dsize). We then round the final
2147 * size up to the chunksize for allocation.
2149 for (ksize = 0, i = 0; i < nkeys; i++)
2150 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2153 * This should be pretty much impossible, but could happen if, say,
2154 * strange DIF specified the tuple. Ideally, this should be an
2155 * assertion and not an error condition -- but that requires that the
2156 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2157 * bullet-proof. (That is, it must not be able to be fooled by
2158 * malicious DIF.) Given the lack of backwards branches in DIF,
2159 * solving this would presumably not amount to solving the Halting
2160 * Problem -- but it still seems awfully hard.
2162 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2163 ksize + dsize > chunksize) {
2164 dcpu->dtdsc_drops++;
2168 nstate = DTRACE_DSTATE_EMPTY;
2172 free = dcpu->dtdsc_free;
2175 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2178 if (clean == NULL) {
2180 * We're out of dynamic variable space on
2181 * this CPU. Unless we have tried all CPUs,
2182 * we'll try to allocate from a different
2185 switch (dstate->dtds_state) {
2186 case DTRACE_DSTATE_CLEAN: {
2187 void *sp = &dstate->dtds_state;
2192 if (dcpu->dtdsc_dirty != NULL &&
2193 nstate == DTRACE_DSTATE_EMPTY)
2194 nstate = DTRACE_DSTATE_DIRTY;
2196 if (dcpu->dtdsc_rinsing != NULL)
2197 nstate = DTRACE_DSTATE_RINSING;
2199 dcpu = &dstate->dtds_percpu[cpu];
2204 (void) dtrace_cas32(sp,
2205 DTRACE_DSTATE_CLEAN, nstate);
2208 * To increment the correct bean
2209 * counter, take another lap.
2214 case DTRACE_DSTATE_DIRTY:
2215 dcpu->dtdsc_dirty_drops++;
2218 case DTRACE_DSTATE_RINSING:
2219 dcpu->dtdsc_rinsing_drops++;
2222 case DTRACE_DSTATE_EMPTY:
2223 dcpu->dtdsc_drops++;
2227 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2232 * The clean list appears to be non-empty. We want to
2233 * move the clean list to the free list; we start by
2234 * moving the clean pointer aside.
2236 if (dtrace_casptr(&dcpu->dtdsc_clean,
2237 clean, NULL) != clean) {
2239 * We are in one of two situations:
2241 * (a) The clean list was switched to the
2242 * free list by another CPU.
2244 * (b) The clean list was added to by the
2247 * In either of these situations, we can
2248 * just reattempt the free list allocation.
2253 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2256 * Now we'll move the clean list to our free list.
2257 * It's impossible for this to fail: the only way
2258 * the free list can be updated is through this
2259 * code path, and only one CPU can own the clean list.
2260 * Thus, it would only be possible for this to fail if
2261 * this code were racing with dtrace_dynvar_clean().
2262 * (That is, if dtrace_dynvar_clean() updated the clean
2263 * list, and we ended up racing to update the free
2264 * list.) This race is prevented by the dtrace_sync()
2265 * in dtrace_dynvar_clean() -- which flushes the
2266 * owners of the clean lists out before resetting
2269 dcpu = &dstate->dtds_percpu[me];
2270 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2271 ASSERT(rval == NULL);
2276 new_free = dvar->dtdv_next;
2277 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2280 * We have now allocated a new chunk. We copy the tuple keys into the
2281 * tuple array and copy any referenced key data into the data space
2282 * following the tuple array. As we do this, we relocate dttk_value
2283 * in the final tuple to point to the key data address in the chunk.
2285 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2286 dvar->dtdv_data = (void *)(kdata + ksize);
2287 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2289 for (i = 0; i < nkeys; i++) {
2290 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2291 size_t kesize = key[i].dttk_size;
2295 (const void *)(uintptr_t)key[i].dttk_value,
2296 (void *)kdata, kesize);
2297 dkey->dttk_value = kdata;
2298 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2300 dkey->dttk_value = key[i].dttk_value;
2303 dkey->dttk_size = kesize;
2306 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2307 dvar->dtdv_hashval = hashval;
2308 dvar->dtdv_next = start;
2310 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2314 * The cas has failed. Either another CPU is adding an element to
2315 * this hash chain, or another CPU is deleting an element from this
2316 * hash chain. The simplest way to deal with both of these cases
2317 * (though not necessarily the most efficient) is to free our
2318 * allocated block and re-attempt it all. Note that the free is
2319 * to the dirty list and _not_ to the free list. This is to prevent
2320 * races with allocators, above.
2322 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2324 dtrace_membar_producer();
2327 free = dcpu->dtdsc_dirty;
2328 dvar->dtdv_next = free;
2329 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2336 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2338 if ((int64_t)nval < (int64_t)*oval)
2344 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2346 if ((int64_t)nval > (int64_t)*oval)
2351 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2353 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2354 int64_t val = (int64_t)nval;
2357 for (i = 0; i < zero; i++) {
2358 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2364 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2365 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2366 quanta[i - 1] += incr;
2371 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2379 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2381 uint64_t arg = *lquanta++;
2382 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2383 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2384 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2385 int32_t val = (int32_t)nval, level;
2388 ASSERT(levels != 0);
2392 * This is an underflow.
2398 level = (val - base) / step;
2400 if (level < levels) {
2401 lquanta[level + 1] += incr;
2406 * This is an overflow.
2408 lquanta[levels + 1] += incr;
2412 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2413 uint16_t high, uint16_t nsteps, int64_t value)
2415 int64_t this = 1, last, next;
2416 int base = 1, order;
2418 ASSERT(factor <= nsteps);
2419 ASSERT(nsteps % factor == 0);
2421 for (order = 0; order < low; order++)
2425 * If our value is less than our factor taken to the power of the
2426 * low order of magnitude, it goes into the zeroth bucket.
2428 if (value < (last = this))
2431 for (this *= factor; order <= high; order++) {
2432 int nbuckets = this > nsteps ? nsteps : this;
2434 if ((next = this * factor) < this) {
2436 * We should not generally get log/linear quantizations
2437 * with a high magnitude that allows 64-bits to
2438 * overflow, but we nonetheless protect against this
2439 * by explicitly checking for overflow, and clamping
2440 * our value accordingly.
2447 * If our value lies within this order of magnitude,
2448 * determine its position by taking the offset within
2449 * the order of magnitude, dividing by the bucket
2450 * width, and adding to our (accumulated) base.
2452 return (base + (value - last) / (this / nbuckets));
2455 base += nbuckets - (nbuckets / factor);
2461 * Our value is greater than or equal to our factor taken to the
2462 * power of one plus the high magnitude -- return the top bucket.
2468 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2470 uint64_t arg = *llquanta++;
2471 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2472 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2473 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2474 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2476 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2477 low, high, nsteps, nval)] += incr;
2482 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2490 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2492 int64_t snval = (int64_t)nval;
2499 * What we want to say here is:
2501 * data[2] += nval * nval;
2503 * But given that nval is 64-bit, we could easily overflow, so
2504 * we do this as 128-bit arithmetic.
2509 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2510 dtrace_add_128(data + 2, tmp, data + 2);
2515 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2522 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2528 * Aggregate given the tuple in the principal data buffer, and the aggregating
2529 * action denoted by the specified dtrace_aggregation_t. The aggregation
2530 * buffer is specified as the buf parameter. This routine does not return
2531 * failure; if there is no space in the aggregation buffer, the data will be
2532 * dropped, and a corresponding counter incremented.
2535 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2536 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2538 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2539 uint32_t i, ndx, size, fsize;
2540 uint32_t align = sizeof (uint64_t) - 1;
2541 dtrace_aggbuffer_t *agb;
2542 dtrace_aggkey_t *key;
2543 uint32_t hashval = 0, limit, isstr;
2544 caddr_t tomax, data, kdata;
2545 dtrace_actkind_t action;
2546 dtrace_action_t *act;
2552 if (!agg->dtag_hasarg) {
2554 * Currently, only quantize() and lquantize() take additional
2555 * arguments, and they have the same semantics: an increment
2556 * value that defaults to 1 when not present. If additional
2557 * aggregating actions take arguments, the setting of the
2558 * default argument value will presumably have to become more
2564 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2565 size = rec->dtrd_offset - agg->dtag_base;
2566 fsize = size + rec->dtrd_size;
2568 ASSERT(dbuf->dtb_tomax != NULL);
2569 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2571 if ((tomax = buf->dtb_tomax) == NULL) {
2572 dtrace_buffer_drop(buf);
2577 * The metastructure is always at the bottom of the buffer.
2579 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2580 sizeof (dtrace_aggbuffer_t));
2582 if (buf->dtb_offset == 0) {
2584 * We just kludge up approximately 1/8th of the size to be
2585 * buckets. If this guess ends up being routinely
2586 * off-the-mark, we may need to dynamically readjust this
2587 * based on past performance.
2589 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2591 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2592 (uintptr_t)tomax || hashsize == 0) {
2594 * We've been given a ludicrously small buffer;
2595 * increment our drop count and leave.
2597 dtrace_buffer_drop(buf);
2602 * And now, a pathetic attempt to try to get a an odd (or
2603 * perchance, a prime) hash size for better hash distribution.
2605 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2606 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2608 agb->dtagb_hashsize = hashsize;
2609 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2610 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2611 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2613 for (i = 0; i < agb->dtagb_hashsize; i++)
2614 agb->dtagb_hash[i] = NULL;
2617 ASSERT(agg->dtag_first != NULL);
2618 ASSERT(agg->dtag_first->dta_intuple);
2621 * Calculate the hash value based on the key. Note that we _don't_
2622 * include the aggid in the hashing (but we will store it as part of
2623 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2624 * algorithm: a simple, quick algorithm that has no known funnels, and
2625 * gets good distribution in practice. The efficacy of the hashing
2626 * algorithm (and a comparison with other algorithms) may be found by
2627 * running the ::dtrace_aggstat MDB dcmd.
2629 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2630 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2631 limit = i + act->dta_rec.dtrd_size;
2632 ASSERT(limit <= size);
2633 isstr = DTRACEACT_ISSTRING(act);
2635 for (; i < limit; i++) {
2637 hashval += (hashval << 10);
2638 hashval ^= (hashval >> 6);
2640 if (isstr && data[i] == '\0')
2645 hashval += (hashval << 3);
2646 hashval ^= (hashval >> 11);
2647 hashval += (hashval << 15);
2650 * Yes, the divide here is expensive -- but it's generally the least
2651 * of the performance issues given the amount of data that we iterate
2652 * over to compute hash values, compare data, etc.
2654 ndx = hashval % agb->dtagb_hashsize;
2656 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2657 ASSERT((caddr_t)key >= tomax);
2658 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2660 if (hashval != key->dtak_hashval || key->dtak_size != size)
2663 kdata = key->dtak_data;
2664 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2666 for (act = agg->dtag_first; act->dta_intuple;
2667 act = act->dta_next) {
2668 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2669 limit = i + act->dta_rec.dtrd_size;
2670 ASSERT(limit <= size);
2671 isstr = DTRACEACT_ISSTRING(act);
2673 for (; i < limit; i++) {
2674 if (kdata[i] != data[i])
2677 if (isstr && data[i] == '\0')
2682 if (action != key->dtak_action) {
2684 * We are aggregating on the same value in the same
2685 * aggregation with two different aggregating actions.
2686 * (This should have been picked up in the compiler,
2687 * so we may be dealing with errant or devious DIF.)
2688 * This is an error condition; we indicate as much,
2691 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2696 * This is a hit: we need to apply the aggregator to
2697 * the value at this key.
2699 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2706 * We didn't find it. We need to allocate some zero-filled space,
2707 * link it into the hash table appropriately, and apply the aggregator
2708 * to the (zero-filled) value.
2710 offs = buf->dtb_offset;
2711 while (offs & (align - 1))
2712 offs += sizeof (uint32_t);
2715 * If we don't have enough room to both allocate a new key _and_
2716 * its associated data, increment the drop count and return.
2718 if ((uintptr_t)tomax + offs + fsize >
2719 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2720 dtrace_buffer_drop(buf);
2725 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2726 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2727 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2729 key->dtak_data = kdata = tomax + offs;
2730 buf->dtb_offset = offs + fsize;
2733 * Now copy the data across.
2735 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2737 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2741 * Because strings are not zeroed out by default, we need to iterate
2742 * looking for actions that store strings, and we need to explicitly
2743 * pad these strings out with zeroes.
2745 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2748 if (!DTRACEACT_ISSTRING(act))
2751 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2752 limit = i + act->dta_rec.dtrd_size;
2753 ASSERT(limit <= size);
2755 for (nul = 0; i < limit; i++) {
2761 if (data[i] != '\0')
2768 for (i = size; i < fsize; i++)
2771 key->dtak_hashval = hashval;
2772 key->dtak_size = size;
2773 key->dtak_action = action;
2774 key->dtak_next = agb->dtagb_hash[ndx];
2775 agb->dtagb_hash[ndx] = key;
2778 * Finally, apply the aggregator.
2780 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2781 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2785 * Given consumer state, this routine finds a speculation in the INACTIVE
2786 * state and transitions it into the ACTIVE state. If there is no speculation
2787 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2788 * incremented -- it is up to the caller to take appropriate action.
2791 dtrace_speculation(dtrace_state_t *state)
2794 dtrace_speculation_state_t curstate;
2795 uint32_t *stat = &state->dts_speculations_unavail, count;
2797 while (i < state->dts_nspeculations) {
2798 dtrace_speculation_t *spec = &state->dts_speculations[i];
2800 curstate = spec->dtsp_state;
2802 if (curstate != DTRACESPEC_INACTIVE) {
2803 if (curstate == DTRACESPEC_COMMITTINGMANY ||
2804 curstate == DTRACESPEC_COMMITTING ||
2805 curstate == DTRACESPEC_DISCARDING)
2806 stat = &state->dts_speculations_busy;
2811 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2812 curstate, DTRACESPEC_ACTIVE) == curstate)
2817 * We couldn't find a speculation. If we found as much as a single
2818 * busy speculation buffer, we'll attribute this failure as "busy"
2819 * instead of "unavail".
2823 } while (dtrace_cas32(stat, count, count + 1) != count);
2829 * This routine commits an active speculation. If the specified speculation
2830 * is not in a valid state to perform a commit(), this routine will silently do
2831 * nothing. The state of the specified speculation is transitioned according
2832 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2835 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2836 dtrace_specid_t which)
2838 dtrace_speculation_t *spec;
2839 dtrace_buffer_t *src, *dest;
2840 uintptr_t daddr, saddr, dlimit, slimit;
2841 dtrace_speculation_state_t curstate, new = 0;
2848 if (which > state->dts_nspeculations) {
2849 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2853 spec = &state->dts_speculations[which - 1];
2854 src = &spec->dtsp_buffer[cpu];
2855 dest = &state->dts_buffer[cpu];
2858 curstate = spec->dtsp_state;
2860 if (curstate == DTRACESPEC_COMMITTINGMANY)
2864 case DTRACESPEC_INACTIVE:
2865 case DTRACESPEC_DISCARDING:
2868 case DTRACESPEC_COMMITTING:
2870 * This is only possible if we are (a) commit()'ing
2871 * without having done a prior speculate() on this CPU
2872 * and (b) racing with another commit() on a different
2873 * CPU. There's nothing to do -- we just assert that
2876 ASSERT(src->dtb_offset == 0);
2879 case DTRACESPEC_ACTIVE:
2880 new = DTRACESPEC_COMMITTING;
2883 case DTRACESPEC_ACTIVEONE:
2885 * This speculation is active on one CPU. If our
2886 * buffer offset is non-zero, we know that the one CPU
2887 * must be us. Otherwise, we are committing on a
2888 * different CPU from the speculate(), and we must
2889 * rely on being asynchronously cleaned.
2891 if (src->dtb_offset != 0) {
2892 new = DTRACESPEC_COMMITTING;
2897 case DTRACESPEC_ACTIVEMANY:
2898 new = DTRACESPEC_COMMITTINGMANY;
2904 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2905 curstate, new) != curstate);
2908 * We have set the state to indicate that we are committing this
2909 * speculation. Now reserve the necessary space in the destination
2912 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2913 sizeof (uint64_t), state, NULL)) < 0) {
2914 dtrace_buffer_drop(dest);
2919 * We have sufficient space to copy the speculative buffer into the
2920 * primary buffer. First, modify the speculative buffer, filling
2921 * in the timestamp of all entries with the curstate time. The data
2922 * must have the commit() time rather than the time it was traced,
2923 * so that all entries in the primary buffer are in timestamp order.
2925 timestamp = dtrace_gethrtime();
2926 saddr = (uintptr_t)src->dtb_tomax;
2927 slimit = saddr + src->dtb_offset;
2928 while (saddr < slimit) {
2930 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2932 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2933 saddr += sizeof (dtrace_epid_t);
2936 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2937 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2939 ASSERT3U(saddr + size, <=, slimit);
2940 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2941 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2943 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2949 * Copy the buffer across. (Note that this is a
2950 * highly subobtimal bcopy(); in the unlikely event that this becomes
2951 * a serious performance issue, a high-performance DTrace-specific
2952 * bcopy() should obviously be invented.)
2954 daddr = (uintptr_t)dest->dtb_tomax + offs;
2955 dlimit = daddr + src->dtb_offset;
2956 saddr = (uintptr_t)src->dtb_tomax;
2959 * First, the aligned portion.
2961 while (dlimit - daddr >= sizeof (uint64_t)) {
2962 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2964 daddr += sizeof (uint64_t);
2965 saddr += sizeof (uint64_t);
2969 * Now any left-over bit...
2971 while (dlimit - daddr)
2972 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2975 * Finally, commit the reserved space in the destination buffer.
2977 dest->dtb_offset = offs + src->dtb_offset;
2981 * If we're lucky enough to be the only active CPU on this speculation
2982 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2984 if (curstate == DTRACESPEC_ACTIVE ||
2985 (curstate == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2986 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2987 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2989 ASSERT(rval == DTRACESPEC_COMMITTING);
2992 src->dtb_offset = 0;
2993 src->dtb_xamot_drops += src->dtb_drops;
2998 * This routine discards an active speculation. If the specified speculation
2999 * is not in a valid state to perform a discard(), this routine will silently
3000 * do nothing. The state of the specified speculation is transitioned
3001 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
3004 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
3005 dtrace_specid_t which)
3007 dtrace_speculation_t *spec;
3008 dtrace_speculation_state_t curstate, new = 0;
3009 dtrace_buffer_t *buf;
3014 if (which > state->dts_nspeculations) {
3015 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3019 spec = &state->dts_speculations[which - 1];
3020 buf = &spec->dtsp_buffer[cpu];
3023 curstate = spec->dtsp_state;
3026 case DTRACESPEC_INACTIVE:
3027 case DTRACESPEC_COMMITTINGMANY:
3028 case DTRACESPEC_COMMITTING:
3029 case DTRACESPEC_DISCARDING:
3032 case DTRACESPEC_ACTIVE:
3033 case DTRACESPEC_ACTIVEMANY:
3034 new = DTRACESPEC_DISCARDING;
3037 case DTRACESPEC_ACTIVEONE:
3038 if (buf->dtb_offset != 0) {
3039 new = DTRACESPEC_INACTIVE;
3041 new = DTRACESPEC_DISCARDING;
3048 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3049 curstate, new) != curstate);
3051 buf->dtb_offset = 0;
3056 * Note: not called from probe context. This function is called
3057 * asynchronously from cross call context to clean any speculations that are
3058 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
3059 * transitioned back to the INACTIVE state until all CPUs have cleaned the
3063 dtrace_speculation_clean_here(dtrace_state_t *state)
3065 dtrace_icookie_t cookie;
3066 processorid_t cpu = curcpu;
3067 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
3070 cookie = dtrace_interrupt_disable();
3072 if (dest->dtb_tomax == NULL) {
3073 dtrace_interrupt_enable(cookie);
3077 for (i = 0; i < state->dts_nspeculations; i++) {
3078 dtrace_speculation_t *spec = &state->dts_speculations[i];
3079 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
3081 if (src->dtb_tomax == NULL)
3084 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
3085 src->dtb_offset = 0;
3089 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3092 if (src->dtb_offset == 0)
3095 dtrace_speculation_commit(state, cpu, i + 1);
3098 dtrace_interrupt_enable(cookie);
3102 * Note: not called from probe context. This function is called
3103 * asynchronously (and at a regular interval) to clean any speculations that
3104 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
3105 * is work to be done, it cross calls all CPUs to perform that work;
3106 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
3107 * INACTIVE state until they have been cleaned by all CPUs.
3110 dtrace_speculation_clean(dtrace_state_t *state)
3115 for (i = 0; i < state->dts_nspeculations; i++) {
3116 dtrace_speculation_t *spec = &state->dts_speculations[i];
3118 ASSERT(!spec->dtsp_cleaning);
3120 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3121 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3125 spec->dtsp_cleaning = 1;
3131 dtrace_xcall(DTRACE_CPUALL,
3132 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3135 * We now know that all CPUs have committed or discarded their
3136 * speculation buffers, as appropriate. We can now set the state
3139 for (i = 0; i < state->dts_nspeculations; i++) {
3140 dtrace_speculation_t *spec = &state->dts_speculations[i];
3141 dtrace_speculation_state_t curstate, new;
3143 if (!spec->dtsp_cleaning)
3146 curstate = spec->dtsp_state;
3147 ASSERT(curstate == DTRACESPEC_DISCARDING ||
3148 curstate == DTRACESPEC_COMMITTINGMANY);
3150 new = DTRACESPEC_INACTIVE;
3152 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, curstate, new);
3153 ASSERT(rv == curstate);
3154 spec->dtsp_cleaning = 0;
3159 * Called as part of a speculate() to get the speculative buffer associated
3160 * with a given speculation. Returns NULL if the specified speculation is not
3161 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
3162 * the active CPU is not the specified CPU -- the speculation will be
3163 * atomically transitioned into the ACTIVEMANY state.
3165 static dtrace_buffer_t *
3166 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3167 dtrace_specid_t which)
3169 dtrace_speculation_t *spec;
3170 dtrace_speculation_state_t curstate, new = 0;
3171 dtrace_buffer_t *buf;
3176 if (which > state->dts_nspeculations) {
3177 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3181 spec = &state->dts_speculations[which - 1];
3182 buf = &spec->dtsp_buffer[cpuid];
3185 curstate = spec->dtsp_state;
3188 case DTRACESPEC_INACTIVE:
3189 case DTRACESPEC_COMMITTINGMANY:
3190 case DTRACESPEC_DISCARDING:
3193 case DTRACESPEC_COMMITTING:
3194 ASSERT(buf->dtb_offset == 0);
3197 case DTRACESPEC_ACTIVEONE:
3199 * This speculation is currently active on one CPU.
3200 * Check the offset in the buffer; if it's non-zero,
3201 * that CPU must be us (and we leave the state alone).
3202 * If it's zero, assume that we're starting on a new
3203 * CPU -- and change the state to indicate that the
3204 * speculation is active on more than one CPU.
3206 if (buf->dtb_offset != 0)
3209 new = DTRACESPEC_ACTIVEMANY;
3212 case DTRACESPEC_ACTIVEMANY:
3215 case DTRACESPEC_ACTIVE:
3216 new = DTRACESPEC_ACTIVEONE;
3222 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3223 curstate, new) != curstate);
3225 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3230 * Return a string. In the event that the user lacks the privilege to access
3231 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3232 * don't fail access checking.
3234 * dtrace_dif_variable() uses this routine as a helper for various
3235 * builtin values such as 'execname' and 'probefunc.'
3238 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3239 dtrace_mstate_t *mstate)
3241 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3246 * The easy case: this probe is allowed to read all of memory, so
3247 * we can just return this as a vanilla pointer.
3249 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3253 * This is the tougher case: we copy the string in question from
3254 * kernel memory into scratch memory and return it that way: this
3255 * ensures that we won't trip up when access checking tests the
3256 * BYREF return value.
3258 strsz = dtrace_strlen((char *)addr, size) + 1;
3260 if (mstate->dtms_scratch_ptr + strsz >
3261 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3262 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3266 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3268 ret = mstate->dtms_scratch_ptr;
3269 mstate->dtms_scratch_ptr += strsz;
3274 * Return a string from a memoy address which is known to have one or
3275 * more concatenated, individually zero terminated, sub-strings.
3276 * In the event that the user lacks the privilege to access
3277 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3278 * don't fail access checking.
3280 * dtrace_dif_variable() uses this routine as a helper for various
3281 * builtin values such as 'execargs'.
3284 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3285 dtrace_mstate_t *mstate)
3291 if (mstate->dtms_scratch_ptr + strsz >
3292 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3293 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3297 dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3300 /* Replace sub-string termination characters with a space. */
3301 for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3306 ret = mstate->dtms_scratch_ptr;
3307 mstate->dtms_scratch_ptr += strsz;
3312 * This function implements the DIF emulator's variable lookups. The emulator
3313 * passes a reserved variable identifier and optional built-in array index.
3316 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3320 * If we're accessing one of the uncached arguments, we'll turn this
3321 * into a reference in the args array.
3323 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3324 ndx = v - DIF_VAR_ARG0;
3330 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3331 if (ndx >= sizeof (mstate->dtms_arg) /
3332 sizeof (mstate->dtms_arg[0])) {
3333 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3334 dtrace_provider_t *pv;
3337 pv = mstate->dtms_probe->dtpr_provider;
3338 if (pv->dtpv_pops.dtps_getargval != NULL)
3339 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3340 mstate->dtms_probe->dtpr_id,
3341 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3343 val = dtrace_getarg(ndx, aframes);
3346 * This is regrettably required to keep the compiler
3347 * from tail-optimizing the call to dtrace_getarg().
3348 * The condition always evaluates to true, but the
3349 * compiler has no way of figuring that out a priori.
3350 * (None of this would be necessary if the compiler
3351 * could be relied upon to _always_ tail-optimize
3352 * the call to dtrace_getarg() -- but it can't.)
3354 if (mstate->dtms_probe != NULL)
3360 return (mstate->dtms_arg[ndx]);
3363 case DIF_VAR_UREGS: {
3366 if (!dtrace_priv_proc(state))
3369 if ((lwp = curthread->t_lwp) == NULL) {
3370 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3371 cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3375 return (dtrace_getreg(lwp->lwp_regs, ndx));
3379 case DIF_VAR_UREGS: {
3380 struct trapframe *tframe;
3382 if (!dtrace_priv_proc(state))
3385 if ((tframe = curthread->td_frame) == NULL) {
3386 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3387 cpu_core[curcpu].cpuc_dtrace_illval = 0;
3391 return (dtrace_getreg(tframe, ndx));
3395 case DIF_VAR_CURTHREAD:
3396 if (!dtrace_priv_proc(state))
3398 return ((uint64_t)(uintptr_t)curthread);
3400 case DIF_VAR_TIMESTAMP:
3401 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3402 mstate->dtms_timestamp = dtrace_gethrtime();
3403 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3405 return (mstate->dtms_timestamp);
3407 case DIF_VAR_VTIMESTAMP:
3408 ASSERT(dtrace_vtime_references != 0);
3409 return (curthread->t_dtrace_vtime);
3411 case DIF_VAR_WALLTIMESTAMP:
3412 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3413 mstate->dtms_walltimestamp = dtrace_gethrestime();
3414 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3416 return (mstate->dtms_walltimestamp);
3420 if (!dtrace_priv_kernel(state))
3422 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3423 mstate->dtms_ipl = dtrace_getipl();
3424 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3426 return (mstate->dtms_ipl);
3430 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3431 return (mstate->dtms_epid);
3434 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3435 return (mstate->dtms_probe->dtpr_id);
3437 case DIF_VAR_STACKDEPTH:
3438 if (!dtrace_priv_kernel(state))
3440 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3441 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3443 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3444 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3446 return (mstate->dtms_stackdepth);
3448 case DIF_VAR_USTACKDEPTH:
3449 if (!dtrace_priv_proc(state))
3451 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3453 * See comment in DIF_VAR_PID.
3455 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3457 mstate->dtms_ustackdepth = 0;
3459 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3460 mstate->dtms_ustackdepth =
3461 dtrace_getustackdepth();
3462 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3464 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3466 return (mstate->dtms_ustackdepth);
3468 case DIF_VAR_CALLER:
3469 if (!dtrace_priv_kernel(state))
3471 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3472 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3474 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3476 * If this is an unanchored probe, we are
3477 * required to go through the slow path:
3478 * dtrace_caller() only guarantees correct
3479 * results for anchored probes.
3481 pc_t caller[2] = {0, 0};
3483 dtrace_getpcstack(caller, 2, aframes,
3484 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3485 mstate->dtms_caller = caller[1];
3486 } else if ((mstate->dtms_caller =
3487 dtrace_caller(aframes)) == -1) {
3489 * We have failed to do this the quick way;
3490 * we must resort to the slower approach of
3491 * calling dtrace_getpcstack().
3495 dtrace_getpcstack(&caller, 1, aframes, NULL);
3496 mstate->dtms_caller = caller;
3499 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3501 return (mstate->dtms_caller);
3503 case DIF_VAR_UCALLER:
3504 if (!dtrace_priv_proc(state))
3507 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3511 * dtrace_getupcstack() fills in the first uint64_t
3512 * with the current PID. The second uint64_t will
3513 * be the program counter at user-level. The third
3514 * uint64_t will contain the caller, which is what
3518 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3519 dtrace_getupcstack(ustack, 3);
3520 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3521 mstate->dtms_ucaller = ustack[2];
3522 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3525 return (mstate->dtms_ucaller);
3527 case DIF_VAR_PROBEPROV:
3528 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3529 return (dtrace_dif_varstr(
3530 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3533 case DIF_VAR_PROBEMOD:
3534 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3535 return (dtrace_dif_varstr(
3536 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3539 case DIF_VAR_PROBEFUNC:
3540 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3541 return (dtrace_dif_varstr(
3542 (uintptr_t)mstate->dtms_probe->dtpr_func,
3545 case DIF_VAR_PROBENAME:
3546 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3547 return (dtrace_dif_varstr(
3548 (uintptr_t)mstate->dtms_probe->dtpr_name,
3552 if (!dtrace_priv_proc(state))
3557 * Note that we are assuming that an unanchored probe is
3558 * always due to a high-level interrupt. (And we're assuming
3559 * that there is only a single high level interrupt.)
3561 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3562 return (pid0.pid_id);
3565 * It is always safe to dereference one's own t_procp pointer:
3566 * it always points to a valid, allocated proc structure.
3567 * Further, it is always safe to dereference the p_pidp member
3568 * of one's own proc structure. (These are truisms becuase
3569 * threads and processes don't clean up their own state --
3570 * they leave that task to whomever reaps them.)
3572 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3574 return ((uint64_t)curproc->p_pid);
3578 if (!dtrace_priv_proc(state))
3583 * See comment in DIF_VAR_PID.
3585 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3586 return (pid0.pid_id);
3589 * It is always safe to dereference one's own t_procp pointer:
3590 * it always points to a valid, allocated proc structure.
3591 * (This is true because threads don't clean up their own
3592 * state -- they leave that task to whomever reaps them.)
3594 return ((uint64_t)curthread->t_procp->p_ppid);
3596 if (curproc->p_pid == proc0.p_pid)
3597 return (curproc->p_pid);
3599 return (curproc->p_pptr->p_pid);
3605 * See comment in DIF_VAR_PID.
3607 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3611 return ((uint64_t)curthread->t_tid);
3613 case DIF_VAR_EXECARGS: {
3614 struct pargs *p_args = curthread->td_proc->p_args;
3619 return (dtrace_dif_varstrz(
3620 (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3623 case DIF_VAR_EXECNAME:
3625 if (!dtrace_priv_proc(state))
3629 * See comment in DIF_VAR_PID.
3631 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3632 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3635 * It is always safe to dereference one's own t_procp pointer:
3636 * it always points to a valid, allocated proc structure.
3637 * (This is true because threads don't clean up their own
3638 * state -- they leave that task to whomever reaps them.)
3640 return (dtrace_dif_varstr(
3641 (uintptr_t)curthread->t_procp->p_user.u_comm,
3644 return (dtrace_dif_varstr(
3645 (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3648 case DIF_VAR_ZONENAME:
3650 if (!dtrace_priv_proc(state))
3654 * See comment in DIF_VAR_PID.
3656 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3657 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3660 * It is always safe to dereference one's own t_procp pointer:
3661 * it always points to a valid, allocated proc structure.
3662 * (This is true because threads don't clean up their own
3663 * state -- they leave that task to whomever reaps them.)
3665 return (dtrace_dif_varstr(
3666 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3668 #elif defined(__FreeBSD__)
3670 * On FreeBSD, we introduce compatibility to zonename by falling through
3673 case DIF_VAR_JAILNAME:
3674 if (!dtrace_priv_kernel(state))
3677 return (dtrace_dif_varstr(
3678 (uintptr_t)curthread->td_ucred->cr_prison->pr_name,
3682 if (!dtrace_priv_kernel(state))
3685 return ((uint64_t)curthread->td_ucred->cr_prison->pr_id);
3691 if (!dtrace_priv_proc(state))
3696 * See comment in DIF_VAR_PID.
3698 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3699 return ((uint64_t)p0.p_cred->cr_uid);
3702 * It is always safe to dereference one's own t_procp pointer:
3703 * it always points to a valid, allocated proc structure.
3704 * (This is true because threads don't clean up their own
3705 * state -- they leave that task to whomever reaps them.)
3707 * Additionally, it is safe to dereference one's own process
3708 * credential, since this is never NULL after process birth.
3710 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3712 return ((uint64_t)curthread->td_ucred->cr_uid);
3716 if (!dtrace_priv_proc(state))
3721 * See comment in DIF_VAR_PID.
3723 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3724 return ((uint64_t)p0.p_cred->cr_gid);
3727 * It is always safe to dereference one's own t_procp pointer:
3728 * it always points to a valid, allocated proc structure.
3729 * (This is true because threads don't clean up their own
3730 * state -- they leave that task to whomever reaps them.)
3732 * Additionally, it is safe to dereference one's own process
3733 * credential, since this is never NULL after process birth.
3735 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3737 return ((uint64_t)curthread->td_ucred->cr_gid);
3740 case DIF_VAR_ERRNO: {
3743 if (!dtrace_priv_proc(state))
3747 * See comment in DIF_VAR_PID.
3749 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3753 * It is always safe to dereference one's own t_lwp pointer in
3754 * the event that this pointer is non-NULL. (This is true
3755 * because threads and lwps don't clean up their own state --
3756 * they leave that task to whomever reaps them.)
3758 if ((lwp = curthread->t_lwp) == NULL)
3761 return ((uint64_t)lwp->lwp_errno);
3763 return (curthread->td_errno);
3772 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3778 typedef enum dtrace_json_state {
3779 DTRACE_JSON_REST = 1,
3782 DTRACE_JSON_STRING_ESCAPE,
3783 DTRACE_JSON_STRING_ESCAPE_UNICODE,
3787 DTRACE_JSON_IDENTIFIER,
3789 DTRACE_JSON_NUMBER_FRAC,
3790 DTRACE_JSON_NUMBER_EXP,
3791 DTRACE_JSON_COLLECT_OBJECT
3792 } dtrace_json_state_t;
3795 * This function possesses just enough knowledge about JSON to extract a single
3796 * value from a JSON string and store it in the scratch buffer. It is able
3797 * to extract nested object values, and members of arrays by index.
3799 * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3800 * be looked up as we descend into the object tree. e.g.
3802 * foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3805 * The run time of this function must be bounded above by strsize to limit the
3806 * amount of work done in probe context. As such, it is implemented as a
3807 * simple state machine, reading one character at a time using safe loads
3808 * until we find the requested element, hit a parsing error or run off the
3809 * end of the object or string.
3811 * As there is no way for a subroutine to return an error without interrupting
3812 * clause execution, we simply return NULL in the event of a missing key or any
3813 * other error condition. Each NULL return in this function is commented with
3814 * the error condition it represents -- parsing or otherwise.
3816 * The set of states for the state machine closely matches the JSON
3817 * specification (http://json.org/). Briefly:
3820 * Skip whitespace until we find either a top-level Object, moving
3821 * to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3823 * DTRACE_JSON_OBJECT:
3824 * Locate the next key String in an Object. Sets a flag to denote
3825 * the next String as a key string and moves to DTRACE_JSON_STRING.
3827 * DTRACE_JSON_COLON:
3828 * Skip whitespace until we find the colon that separates key Strings
3829 * from their values. Once found, move to DTRACE_JSON_VALUE.
3831 * DTRACE_JSON_VALUE:
3832 * Detects the type of the next value (String, Number, Identifier, Object
3833 * or Array) and routes to the states that process that type. Here we also
3834 * deal with the element selector list if we are requested to traverse down
3835 * into the object tree.
3837 * DTRACE_JSON_COMMA:
3838 * Skip whitespace until we find the comma that separates key-value pairs
3839 * in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3840 * (similarly DTRACE_JSON_VALUE). All following literal value processing
3841 * states return to this state at the end of their value, unless otherwise
3844 * DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3845 * Processes a Number literal from the JSON, including any exponent
3846 * component that may be present. Numbers are returned as strings, which
3847 * may be passed to strtoll() if an integer is required.
3849 * DTRACE_JSON_IDENTIFIER:
3850 * Processes a "true", "false" or "null" literal in the JSON.
3852 * DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3853 * DTRACE_JSON_STRING_ESCAPE_UNICODE:
3854 * Processes a String literal from the JSON, whether the String denotes
3855 * a key, a value or part of a larger Object. Handles all escape sequences
3856 * present in the specification, including four-digit unicode characters,
3857 * but merely includes the escape sequence without converting it to the
3858 * actual escaped character. If the String is flagged as a key, we
3859 * move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3861 * DTRACE_JSON_COLLECT_OBJECT:
3862 * This state collects an entire Object (or Array), correctly handling
3863 * embedded strings. If the full element selector list matches this nested
3864 * object, we return the Object in full as a string. If not, we use this
3865 * state to skip to the next value at this level and continue processing.
3867 * NOTE: This function uses various macros from strtolctype.h to manipulate
3868 * digit values, etc -- these have all been checked to ensure they make
3869 * no additional function calls.
3872 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3875 dtrace_json_state_t state = DTRACE_JSON_REST;
3876 int64_t array_elem = INT64_MIN;
3877 int64_t array_pos = 0;
3878 uint8_t escape_unicount = 0;
3879 boolean_t string_is_key = B_FALSE;
3880 boolean_t collect_object = B_FALSE;
3881 boolean_t found_key = B_FALSE;
3882 boolean_t in_array = B_FALSE;
3883 uint32_t braces = 0, brackets = 0;
3884 char *elem = elemlist;
3888 for (cur = json; cur < json + size; cur++) {
3889 char cc = dtrace_load8(cur);
3894 case DTRACE_JSON_REST:
3899 state = DTRACE_JSON_OBJECT;
3906 array_elem = dtrace_strtoll(elem, 10, size);
3907 found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3908 state = DTRACE_JSON_VALUE;
3913 * ERROR: expected to find a top-level object or array.
3916 case DTRACE_JSON_OBJECT:
3921 state = DTRACE_JSON_STRING;
3922 string_is_key = B_TRUE;
3927 * ERROR: either the object did not start with a key
3928 * string, or we've run off the end of the object
3929 * without finding the requested key.
3932 case DTRACE_JSON_STRING:
3935 state = DTRACE_JSON_STRING_ESCAPE;
3940 if (collect_object) {
3942 * We don't reset the dest here, as
3943 * the string is part of a larger
3944 * object being collected.
3947 collect_object = B_FALSE;
3948 state = DTRACE_JSON_COLLECT_OBJECT;
3952 dd = dest; /* reset string buffer */
3953 if (string_is_key) {
3954 if (dtrace_strncmp(dest, elem,
3957 } else if (found_key) {
3960 * We expected an object, not
3967 state = string_is_key ? DTRACE_JSON_COLON :
3969 string_is_key = B_FALSE;
3975 case DTRACE_JSON_STRING_ESCAPE:
3978 escape_unicount = 0;
3979 state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3981 state = DTRACE_JSON_STRING;
3984 case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3985 if (!isxdigit(cc)) {
3987 * ERROR: invalid unicode escape, expected
3988 * four valid hexidecimal digits.
3994 if (++escape_unicount == 4)
3995 state = DTRACE_JSON_STRING;
3997 case DTRACE_JSON_COLON:
4002 state = DTRACE_JSON_VALUE;
4007 * ERROR: expected a colon.
4010 case DTRACE_JSON_COMMA:
4016 state = DTRACE_JSON_VALUE;
4017 if (++array_pos == array_elem)
4020 state = DTRACE_JSON_OBJECT;
4026 * ERROR: either we hit an unexpected character, or
4027 * we reached the end of the object or array without
4028 * finding the requested key.
4031 case DTRACE_JSON_IDENTIFIER:
4038 dd = dest; /* reset string buffer */
4040 if (dtrace_strncmp(dest, "true", 5) == 0 ||
4041 dtrace_strncmp(dest, "false", 6) == 0 ||
4042 dtrace_strncmp(dest, "null", 5) == 0) {
4046 * ERROR: We expected an object,
4047 * not this identifier.
4054 state = DTRACE_JSON_COMMA;
4060 * ERROR: we did not recognise the identifier as one
4061 * of those in the JSON specification.
4064 case DTRACE_JSON_NUMBER:
4067 state = DTRACE_JSON_NUMBER_FRAC;
4071 if (cc == 'x' || cc == 'X') {
4073 * ERROR: specification explicitly excludes
4074 * hexidecimal or octal numbers.
4080 case DTRACE_JSON_NUMBER_FRAC:
4081 if (cc == 'e' || cc == 'E') {
4083 state = DTRACE_JSON_NUMBER_EXP;
4087 if (cc == '+' || cc == '-') {
4089 * ERROR: expect sign as part of exponent only.
4094 case DTRACE_JSON_NUMBER_EXP:
4095 if (isdigit(cc) || cc == '+' || cc == '-') {
4101 dd = dest; /* reset string buffer */
4105 * ERROR: We expected an object, not
4114 state = DTRACE_JSON_COMMA;
4116 case DTRACE_JSON_VALUE:
4120 if (cc == '{' || cc == '[') {
4121 if (nelems > 1 && found_key) {
4122 in_array = cc == '[' ? B_TRUE : B_FALSE;
4124 * If our element selector directs us
4125 * to descend into this nested object,
4126 * then move to the next selector
4127 * element in the list and restart the
4130 while (*elem != '\0')
4132 elem++; /* skip the inter-element NUL */
4136 state = DTRACE_JSON_VALUE;
4138 array_elem = dtrace_strtoll(
4140 found_key = array_elem == 0 ?
4143 found_key = B_FALSE;
4144 state = DTRACE_JSON_OBJECT;
4150 * Otherwise, we wish to either skip this
4151 * nested object or return it in full.
4158 state = DTRACE_JSON_COLLECT_OBJECT;
4163 state = DTRACE_JSON_STRING;
4169 * Here we deal with true, false and null.
4172 state = DTRACE_JSON_IDENTIFIER;
4176 if (cc == '-' || isdigit(cc)) {
4178 state = DTRACE_JSON_NUMBER;
4183 * ERROR: unexpected character at start of value.
4186 case DTRACE_JSON_COLLECT_OBJECT:
4189 * ERROR: unexpected end of input.
4195 collect_object = B_TRUE;
4196 state = DTRACE_JSON_STRING;
4201 if (brackets-- == 0) {
4203 * ERROR: unbalanced brackets.
4207 } else if (cc == '}') {
4208 if (braces-- == 0) {
4210 * ERROR: unbalanced braces.
4214 } else if (cc == '{') {
4216 } else if (cc == '[') {
4220 if (brackets == 0 && braces == 0) {
4225 dd = dest; /* reset string buffer */
4226 state = DTRACE_JSON_COMMA;
4235 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4236 * Notice that we don't bother validating the proper number of arguments or
4237 * their types in the tuple stack. This isn't needed because all argument
4238 * interpretation is safe because of our load safety -- the worst that can
4239 * happen is that a bogus program can obtain bogus results.
4242 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4243 dtrace_key_t *tupregs, int nargs,
4244 dtrace_mstate_t *mstate, dtrace_state_t *state)
4246 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4247 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4248 dtrace_vstate_t *vstate = &state->dts_vstate;
4261 struct thread *lowner;
4263 struct lock_object *li;
4270 regs[rd] = dtrace_xoroshiro128_plus_next(
4271 state->dts_rstate[curcpu]);
4275 case DIF_SUBR_MUTEX_OWNED:
4276 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4282 m.mx = dtrace_load64(tupregs[0].dttk_value);
4283 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4284 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4286 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4289 case DIF_SUBR_MUTEX_OWNER:
4290 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4296 m.mx = dtrace_load64(tupregs[0].dttk_value);
4297 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4298 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4299 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4304 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4305 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4311 m.mx = dtrace_load64(tupregs[0].dttk_value);
4312 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4315 case DIF_SUBR_MUTEX_TYPE_SPIN:
4316 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4322 m.mx = dtrace_load64(tupregs[0].dttk_value);
4323 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4326 case DIF_SUBR_RW_READ_HELD: {
4329 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4335 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4336 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4340 case DIF_SUBR_RW_WRITE_HELD:
4341 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4347 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4348 regs[rd] = _RW_WRITE_HELD(&r.ri);
4351 case DIF_SUBR_RW_ISWRITER:
4352 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4358 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4359 regs[rd] = _RW_ISWRITER(&r.ri);
4362 #else /* !illumos */
4363 case DIF_SUBR_MUTEX_OWNED:
4364 if (!dtrace_canload(tupregs[0].dttk_value,
4365 sizeof (struct lock_object), mstate, vstate)) {
4369 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4370 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4371 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4372 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4375 case DIF_SUBR_MUTEX_OWNER:
4376 if (!dtrace_canload(tupregs[0].dttk_value,
4377 sizeof (struct lock_object), mstate, vstate)) {
4381 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4382 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4383 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4384 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4385 regs[rd] = (uintptr_t)lowner;
4388 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4389 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4394 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4395 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4396 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SLEEPLOCK) != 0;
4397 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4400 case DIF_SUBR_MUTEX_TYPE_SPIN:
4401 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
4406 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4407 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4408 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
4409 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4412 case DIF_SUBR_RW_READ_HELD:
4413 case DIF_SUBR_SX_SHARED_HELD:
4414 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4419 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
4420 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4421 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4423 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4426 case DIF_SUBR_RW_WRITE_HELD:
4427 case DIF_SUBR_SX_EXCLUSIVE_HELD:
4428 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4433 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4434 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4435 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
4437 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4440 case DIF_SUBR_RW_ISWRITER:
4441 case DIF_SUBR_SX_ISEXCLUSIVE:
4442 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4447 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
4448 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4449 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
4450 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4451 regs[rd] = (lowner == curthread);
4453 #endif /* illumos */
4455 case DIF_SUBR_BCOPY: {
4457 * We need to be sure that the destination is in the scratch
4458 * region -- no other region is allowed.
4460 uintptr_t src = tupregs[0].dttk_value;
4461 uintptr_t dest = tupregs[1].dttk_value;
4462 size_t size = tupregs[2].dttk_value;
4464 if (!dtrace_inscratch(dest, size, mstate)) {
4465 *flags |= CPU_DTRACE_BADADDR;
4470 if (!dtrace_canload(src, size, mstate, vstate)) {
4475 dtrace_bcopy((void *)src, (void *)dest, size);
4479 case DIF_SUBR_ALLOCA:
4480 case DIF_SUBR_COPYIN: {
4481 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4483 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4484 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4487 * This action doesn't require any credential checks since
4488 * probes will not activate in user contexts to which the
4489 * enabling user does not have permissions.
4493 * Rounding up the user allocation size could have overflowed
4494 * a large, bogus allocation (like -1ULL) to 0.
4496 if (scratch_size < size ||
4497 !DTRACE_INSCRATCH(mstate, scratch_size)) {
4498 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4503 if (subr == DIF_SUBR_COPYIN) {
4504 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4505 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4506 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4509 mstate->dtms_scratch_ptr += scratch_size;
4514 case DIF_SUBR_COPYINTO: {
4515 uint64_t size = tupregs[1].dttk_value;
4516 uintptr_t dest = tupregs[2].dttk_value;
4519 * This action doesn't require any credential checks since
4520 * probes will not activate in user contexts to which the
4521 * enabling user does not have permissions.
4523 if (!dtrace_inscratch(dest, size, mstate)) {
4524 *flags |= CPU_DTRACE_BADADDR;
4529 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4530 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4531 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4535 case DIF_SUBR_COPYINSTR: {
4536 uintptr_t dest = mstate->dtms_scratch_ptr;
4537 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4539 if (nargs > 1 && tupregs[1].dttk_value < size)
4540 size = tupregs[1].dttk_value + 1;
4543 * This action doesn't require any credential checks since
4544 * probes will not activate in user contexts to which the
4545 * enabling user does not have permissions.
4547 if (!DTRACE_INSCRATCH(mstate, size)) {
4548 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4553 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4554 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4555 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4557 ((char *)dest)[size - 1] = '\0';
4558 mstate->dtms_scratch_ptr += size;
4564 case DIF_SUBR_MSGSIZE:
4565 case DIF_SUBR_MSGDSIZE: {
4566 uintptr_t baddr = tupregs[0].dttk_value, daddr;
4567 uintptr_t wptr, rptr;
4571 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4573 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4579 wptr = dtrace_loadptr(baddr +
4580 offsetof(mblk_t, b_wptr));
4582 rptr = dtrace_loadptr(baddr +
4583 offsetof(mblk_t, b_rptr));
4586 *flags |= CPU_DTRACE_BADADDR;
4587 *illval = tupregs[0].dttk_value;
4591 daddr = dtrace_loadptr(baddr +
4592 offsetof(mblk_t, b_datap));
4594 baddr = dtrace_loadptr(baddr +
4595 offsetof(mblk_t, b_cont));
4598 * We want to prevent against denial-of-service here,
4599 * so we're only going to search the list for
4600 * dtrace_msgdsize_max mblks.
4602 if (cont++ > dtrace_msgdsize_max) {
4603 *flags |= CPU_DTRACE_ILLOP;
4607 if (subr == DIF_SUBR_MSGDSIZE) {
4608 if (dtrace_load8(daddr +
4609 offsetof(dblk_t, db_type)) != M_DATA)
4613 count += wptr - rptr;
4616 if (!(*flags & CPU_DTRACE_FAULT))
4623 case DIF_SUBR_PROGENYOF: {
4624 pid_t pid = tupregs[0].dttk_value;
4628 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4630 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4632 if (p->p_pidp->pid_id == pid) {
4634 if (p->p_pid == pid) {
4641 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4647 case DIF_SUBR_SPECULATION:
4648 regs[rd] = dtrace_speculation(state);
4651 case DIF_SUBR_COPYOUT: {
4652 uintptr_t kaddr = tupregs[0].dttk_value;
4653 uintptr_t uaddr = tupregs[1].dttk_value;
4654 uint64_t size = tupregs[2].dttk_value;
4656 if (!dtrace_destructive_disallow &&
4657 dtrace_priv_proc_control(state) &&
4658 !dtrace_istoxic(kaddr, size) &&
4659 dtrace_canload(kaddr, size, mstate, vstate)) {
4660 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4661 dtrace_copyout(kaddr, uaddr, size, flags);
4662 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4667 case DIF_SUBR_COPYOUTSTR: {
4668 uintptr_t kaddr = tupregs[0].dttk_value;
4669 uintptr_t uaddr = tupregs[1].dttk_value;
4670 uint64_t size = tupregs[2].dttk_value;
4673 if (!dtrace_destructive_disallow &&
4674 dtrace_priv_proc_control(state) &&
4675 !dtrace_istoxic(kaddr, size) &&
4676 dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4677 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4678 dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4679 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4684 case DIF_SUBR_STRLEN: {
4685 size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4686 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4689 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4694 regs[rd] = dtrace_strlen((char *)addr, lim);
4698 case DIF_SUBR_STRCHR:
4699 case DIF_SUBR_STRRCHR: {
4701 * We're going to iterate over the string looking for the
4702 * specified character. We will iterate until we have reached
4703 * the string length or we have found the character. If this
4704 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4705 * of the specified character instead of the first.
4707 uintptr_t addr = tupregs[0].dttk_value;
4708 uintptr_t addr_limit;
4709 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4711 char c, target = (char)tupregs[1].dttk_value;
4713 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4717 addr_limit = addr + lim;
4719 for (regs[rd] = 0; addr < addr_limit; addr++) {
4720 if ((c = dtrace_load8(addr)) == target) {
4723 if (subr == DIF_SUBR_STRCHR)
4733 case DIF_SUBR_STRSTR:
4734 case DIF_SUBR_INDEX:
4735 case DIF_SUBR_RINDEX: {
4737 * We're going to iterate over the string looking for the
4738 * specified string. We will iterate until we have reached
4739 * the string length or we have found the string. (Yes, this
4740 * is done in the most naive way possible -- but considering
4741 * that the string we're searching for is likely to be
4742 * relatively short, the complexity of Rabin-Karp or similar
4743 * hardly seems merited.)
4745 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4746 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4747 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4748 size_t len = dtrace_strlen(addr, size);
4749 size_t sublen = dtrace_strlen(substr, size);
4750 char *limit = addr + len, *orig = addr;
4751 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4754 regs[rd] = notfound;
4756 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4761 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4768 * strstr() and index()/rindex() have similar semantics if
4769 * both strings are the empty string: strstr() returns a
4770 * pointer to the (empty) string, and index() and rindex()
4771 * both return index 0 (regardless of any position argument).
4773 if (sublen == 0 && len == 0) {
4774 if (subr == DIF_SUBR_STRSTR)
4775 regs[rd] = (uintptr_t)addr;
4781 if (subr != DIF_SUBR_STRSTR) {
4782 if (subr == DIF_SUBR_RINDEX) {
4789 * Both index() and rindex() take an optional position
4790 * argument that denotes the starting position.
4793 int64_t pos = (int64_t)tupregs[2].dttk_value;
4796 * If the position argument to index() is
4797 * negative, Perl implicitly clamps it at
4798 * zero. This semantic is a little surprising
4799 * given the special meaning of negative
4800 * positions to similar Perl functions like
4801 * substr(), but it appears to reflect a
4802 * notion that index() can start from a
4803 * negative index and increment its way up to
4804 * the string. Given this notion, Perl's
4805 * rindex() is at least self-consistent in
4806 * that it implicitly clamps positions greater
4807 * than the string length to be the string
4808 * length. Where Perl completely loses
4809 * coherence, however, is when the specified
4810 * substring is the empty string (""). In
4811 * this case, even if the position is
4812 * negative, rindex() returns 0 -- and even if
4813 * the position is greater than the length,
4814 * index() returns the string length. These
4815 * semantics violate the notion that index()
4816 * should never return a value less than the
4817 * specified position and that rindex() should
4818 * never return a value greater than the
4819 * specified position. (One assumes that
4820 * these semantics are artifacts of Perl's
4821 * implementation and not the results of
4822 * deliberate design -- it beggars belief that
4823 * even Larry Wall could desire such oddness.)
4824 * While in the abstract one would wish for
4825 * consistent position semantics across
4826 * substr(), index() and rindex() -- or at the
4827 * very least self-consistent position
4828 * semantics for index() and rindex() -- we
4829 * instead opt to keep with the extant Perl
4830 * semantics, in all their broken glory. (Do
4831 * we have more desire to maintain Perl's
4832 * semantics than Perl does? Probably.)
4834 if (subr == DIF_SUBR_RINDEX) {
4858 for (regs[rd] = notfound; addr != limit; addr += inc) {
4859 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4860 if (subr != DIF_SUBR_STRSTR) {
4862 * As D index() and rindex() are
4863 * modeled on Perl (and not on awk),
4864 * we return a zero-based (and not a
4865 * one-based) index. (For you Perl
4866 * weenies: no, we're not going to add
4867 * $[ -- and shouldn't you be at a con
4870 regs[rd] = (uintptr_t)(addr - orig);
4874 ASSERT(subr == DIF_SUBR_STRSTR);
4875 regs[rd] = (uintptr_t)addr;
4883 case DIF_SUBR_STRTOK: {
4884 uintptr_t addr = tupregs[0].dttk_value;
4885 uintptr_t tokaddr = tupregs[1].dttk_value;
4886 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4887 uintptr_t limit, toklimit;
4889 uint8_t c = 0, tokmap[32]; /* 256 / 8 */
4890 char *dest = (char *)mstate->dtms_scratch_ptr;
4894 * Check both the token buffer and (later) the input buffer,
4895 * since both could be non-scratch addresses.
4897 if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4901 toklimit = tokaddr + clim;
4903 if (!DTRACE_INSCRATCH(mstate, size)) {
4904 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4911 * If the address specified is NULL, we use our saved
4912 * strtok pointer from the mstate. Note that this
4913 * means that the saved strtok pointer is _only_
4914 * valid within multiple enablings of the same probe --
4915 * it behaves like an implicit clause-local variable.
4917 addr = mstate->dtms_strtok;
4918 limit = mstate->dtms_strtok_limit;
4921 * If the user-specified address is non-NULL we must
4922 * access check it. This is the only time we have
4923 * a chance to do so, since this address may reside
4924 * in the string table of this clause-- future calls
4925 * (when we fetch addr from mstate->dtms_strtok)
4926 * would fail this access check.
4928 if (!dtrace_strcanload(addr, size, &clim, mstate,
4933 limit = addr + clim;
4937 * First, zero the token map, and then process the token
4938 * string -- setting a bit in the map for every character
4939 * found in the token string.
4941 for (i = 0; i < sizeof (tokmap); i++)
4944 for (; tokaddr < toklimit; tokaddr++) {
4945 if ((c = dtrace_load8(tokaddr)) == '\0')
4948 ASSERT((c >> 3) < sizeof (tokmap));
4949 tokmap[c >> 3] |= (1 << (c & 0x7));
4952 for (; addr < limit; addr++) {
4954 * We're looking for a character that is _not_
4955 * contained in the token string.
4957 if ((c = dtrace_load8(addr)) == '\0')
4960 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4966 * We reached the end of the string without finding
4967 * any character that was not in the token string.
4968 * We return NULL in this case, and we set the saved
4969 * address to NULL as well.
4972 mstate->dtms_strtok = 0;
4973 mstate->dtms_strtok_limit = 0;
4978 * From here on, we're copying into the destination string.
4980 for (i = 0; addr < limit && i < size - 1; addr++) {
4981 if ((c = dtrace_load8(addr)) == '\0')
4984 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4993 regs[rd] = (uintptr_t)dest;
4994 mstate->dtms_scratch_ptr += size;
4995 mstate->dtms_strtok = addr;
4996 mstate->dtms_strtok_limit = limit;
5000 case DIF_SUBR_SUBSTR: {
5001 uintptr_t s = tupregs[0].dttk_value;
5002 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5003 char *d = (char *)mstate->dtms_scratch_ptr;
5004 int64_t index = (int64_t)tupregs[1].dttk_value;
5005 int64_t remaining = (int64_t)tupregs[2].dttk_value;
5006 size_t len = dtrace_strlen((char *)s, size);
5009 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5014 if (!DTRACE_INSCRATCH(mstate, size)) {
5015 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5021 remaining = (int64_t)size;
5026 if (index < 0 && index + remaining > 0) {
5032 if (index >= len || index < 0) {
5034 } else if (remaining < 0) {
5035 remaining += len - index;
5036 } else if (index + remaining > size) {
5037 remaining = size - index;
5040 for (i = 0; i < remaining; i++) {
5041 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
5047 mstate->dtms_scratch_ptr += size;
5048 regs[rd] = (uintptr_t)d;
5052 case DIF_SUBR_JSON: {
5053 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5054 uintptr_t json = tupregs[0].dttk_value;
5055 size_t jsonlen = dtrace_strlen((char *)json, size);
5056 uintptr_t elem = tupregs[1].dttk_value;
5057 size_t elemlen = dtrace_strlen((char *)elem, size);
5059 char *dest = (char *)mstate->dtms_scratch_ptr;
5060 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
5061 char *ee = elemlist;
5065 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
5066 !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
5071 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
5072 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5078 * Read the element selector and split it up into a packed list
5081 for (cur = elem; cur < elem + elemlen; cur++) {
5082 char cc = dtrace_load8(cur);
5084 if (cur == elem && cc == '[') {
5086 * If the first element selector key is
5087 * actually an array index then ignore the
5096 if (cc == '.' || cc == '[') {
5105 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
5106 nelems, dest)) != 0)
5107 mstate->dtms_scratch_ptr += jsonlen + 1;
5111 case DIF_SUBR_TOUPPER:
5112 case DIF_SUBR_TOLOWER: {
5113 uintptr_t s = tupregs[0].dttk_value;
5114 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5115 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5116 size_t len = dtrace_strlen((char *)s, size);
5117 char lower, upper, convert;
5120 if (subr == DIF_SUBR_TOUPPER) {
5130 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
5135 if (!DTRACE_INSCRATCH(mstate, size)) {
5136 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5141 for (i = 0; i < size - 1; i++) {
5142 if ((c = dtrace_load8(s + i)) == '\0')
5145 if (c >= lower && c <= upper)
5146 c = convert + (c - lower);
5153 regs[rd] = (uintptr_t)dest;
5154 mstate->dtms_scratch_ptr += size;
5159 case DIF_SUBR_GETMAJOR:
5161 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
5163 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
5167 case DIF_SUBR_GETMINOR:
5169 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
5171 regs[rd] = tupregs[0].dttk_value & MAXMIN;
5175 case DIF_SUBR_DDI_PATHNAME: {
5177 * This one is a galactic mess. We are going to roughly
5178 * emulate ddi_pathname(), but it's made more complicated
5179 * by the fact that we (a) want to include the minor name and
5180 * (b) must proceed iteratively instead of recursively.
5182 uintptr_t dest = mstate->dtms_scratch_ptr;
5183 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5184 char *start = (char *)dest, *end = start + size - 1;
5185 uintptr_t daddr = tupregs[0].dttk_value;
5186 int64_t minor = (int64_t)tupregs[1].dttk_value;
5188 int i, len, depth = 0;
5191 * Due to all the pointer jumping we do and context we must
5192 * rely upon, we just mandate that the user must have kernel
5193 * read privileges to use this routine.
5195 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
5196 *flags |= CPU_DTRACE_KPRIV;
5201 if (!DTRACE_INSCRATCH(mstate, size)) {
5202 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5210 * We want to have a name for the minor. In order to do this,
5211 * we need to walk the minor list from the devinfo. We want
5212 * to be sure that we don't infinitely walk a circular list,
5213 * so we check for circularity by sending a scout pointer
5214 * ahead two elements for every element that we iterate over;
5215 * if the list is circular, these will ultimately point to the
5216 * same element. You may recognize this little trick as the
5217 * answer to a stupid interview question -- one that always
5218 * seems to be asked by those who had to have it laboriously
5219 * explained to them, and who can't even concisely describe
5220 * the conditions under which one would be forced to resort to
5221 * this technique. Needless to say, those conditions are
5222 * found here -- and probably only here. Is this the only use
5223 * of this infamous trick in shipping, production code? If it
5224 * isn't, it probably should be...
5227 uintptr_t maddr = dtrace_loadptr(daddr +
5228 offsetof(struct dev_info, devi_minor));
5230 uintptr_t next = offsetof(struct ddi_minor_data, next);
5231 uintptr_t name = offsetof(struct ddi_minor_data,
5232 d_minor) + offsetof(struct ddi_minor, name);
5233 uintptr_t dev = offsetof(struct ddi_minor_data,
5234 d_minor) + offsetof(struct ddi_minor, dev);
5238 scout = dtrace_loadptr(maddr + next);
5240 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5243 m = dtrace_load64(maddr + dev) & MAXMIN64;
5245 m = dtrace_load32(maddr + dev) & MAXMIN;
5248 maddr = dtrace_loadptr(maddr + next);
5253 scout = dtrace_loadptr(scout + next);
5258 scout = dtrace_loadptr(scout + next);
5263 if (scout == maddr) {
5264 *flags |= CPU_DTRACE_ILLOP;
5272 * We have the minor data. Now we need to
5273 * copy the minor's name into the end of the
5276 s = (char *)dtrace_loadptr(maddr + name);
5277 len = dtrace_strlen(s, size);
5279 if (*flags & CPU_DTRACE_FAULT)
5283 if ((end -= (len + 1)) < start)
5289 for (i = 1; i <= len; i++)
5290 end[i] = dtrace_load8((uintptr_t)s++);
5295 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
5296 ddi_node_state_t devi_state;
5298 devi_state = dtrace_load32(daddr +
5299 offsetof(struct dev_info, devi_node_state));
5301 if (*flags & CPU_DTRACE_FAULT)
5304 if (devi_state >= DS_INITIALIZED) {
5305 s = (char *)dtrace_loadptr(daddr +
5306 offsetof(struct dev_info, devi_addr));
5307 len = dtrace_strlen(s, size);
5309 if (*flags & CPU_DTRACE_FAULT)
5313 if ((end -= (len + 1)) < start)
5319 for (i = 1; i <= len; i++)
5320 end[i] = dtrace_load8((uintptr_t)s++);
5324 * Now for the node name...
5326 s = (char *)dtrace_loadptr(daddr +
5327 offsetof(struct dev_info, devi_node_name));
5329 daddr = dtrace_loadptr(daddr +
5330 offsetof(struct dev_info, devi_parent));
5333 * If our parent is NULL (that is, if we're the root
5334 * node), we're going to use the special path
5340 len = dtrace_strlen(s, size);
5341 if (*flags & CPU_DTRACE_FAULT)
5344 if ((end -= (len + 1)) < start)
5347 for (i = 1; i <= len; i++)
5348 end[i] = dtrace_load8((uintptr_t)s++);
5351 if (depth++ > dtrace_devdepth_max) {
5352 *flags |= CPU_DTRACE_ILLOP;
5358 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5361 regs[rd] = (uintptr_t)end;
5362 mstate->dtms_scratch_ptr += size;
5369 case DIF_SUBR_STRJOIN: {
5370 char *d = (char *)mstate->dtms_scratch_ptr;
5371 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5372 uintptr_t s1 = tupregs[0].dttk_value;
5373 uintptr_t s2 = tupregs[1].dttk_value;
5378 if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5379 !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5384 if (!DTRACE_INSCRATCH(mstate, size)) {
5385 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5392 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5396 c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5397 if ((d[i++] = c) == '\0') {
5405 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5410 c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5411 if ((d[i++] = c) == '\0')
5416 mstate->dtms_scratch_ptr += i;
5417 regs[rd] = (uintptr_t)d;
5423 case DIF_SUBR_STRTOLL: {
5424 uintptr_t s = tupregs[0].dttk_value;
5425 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5430 if ((base = tupregs[1].dttk_value) <= 1 ||
5431 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5432 *flags |= CPU_DTRACE_ILLOP;
5437 if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5438 regs[rd] = INT64_MIN;
5442 regs[rd] = dtrace_strtoll((char *)s, base, lim);
5446 case DIF_SUBR_LLTOSTR: {
5447 int64_t i = (int64_t)tupregs[0].dttk_value;
5448 uint64_t val, digit;
5449 uint64_t size = 65; /* enough room for 2^64 in binary */
5450 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5454 if ((base = tupregs[1].dttk_value) <= 1 ||
5455 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5456 *flags |= CPU_DTRACE_ILLOP;
5461 val = (base == 10 && i < 0) ? i * -1 : i;
5463 if (!DTRACE_INSCRATCH(mstate, size)) {
5464 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5469 for (*end-- = '\0'; val; val /= base) {
5470 if ((digit = val % base) <= '9' - '0') {
5471 *end-- = '0' + digit;
5473 *end-- = 'a' + (digit - ('9' - '0') - 1);
5477 if (i == 0 && base == 16)
5483 if (i == 0 || base == 8 || base == 16)
5486 if (i < 0 && base == 10)
5489 regs[rd] = (uintptr_t)end + 1;
5490 mstate->dtms_scratch_ptr += size;
5494 case DIF_SUBR_HTONS:
5495 case DIF_SUBR_NTOHS:
5496 #if BYTE_ORDER == BIG_ENDIAN
5497 regs[rd] = (uint16_t)tupregs[0].dttk_value;
5499 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5504 case DIF_SUBR_HTONL:
5505 case DIF_SUBR_NTOHL:
5506 #if BYTE_ORDER == BIG_ENDIAN
5507 regs[rd] = (uint32_t)tupregs[0].dttk_value;
5509 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5514 case DIF_SUBR_HTONLL:
5515 case DIF_SUBR_NTOHLL:
5516 #if BYTE_ORDER == BIG_ENDIAN
5517 regs[rd] = (uint64_t)tupregs[0].dttk_value;
5519 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5524 case DIF_SUBR_DIRNAME:
5525 case DIF_SUBR_BASENAME: {
5526 char *dest = (char *)mstate->dtms_scratch_ptr;
5527 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5528 uintptr_t src = tupregs[0].dttk_value;
5529 int i, j, len = dtrace_strlen((char *)src, size);
5530 int lastbase = -1, firstbase = -1, lastdir = -1;
5533 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5538 if (!DTRACE_INSCRATCH(mstate, size)) {
5539 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5545 * The basename and dirname for a zero-length string is
5550 src = (uintptr_t)".";
5554 * Start from the back of the string, moving back toward the
5555 * front until we see a character that isn't a slash. That
5556 * character is the last character in the basename.
5558 for (i = len - 1; i >= 0; i--) {
5559 if (dtrace_load8(src + i) != '/')
5567 * Starting from the last character in the basename, move
5568 * towards the front until we find a slash. The character
5569 * that we processed immediately before that is the first
5570 * character in the basename.
5572 for (; i >= 0; i--) {
5573 if (dtrace_load8(src + i) == '/')
5581 * Now keep going until we find a non-slash character. That
5582 * character is the last character in the dirname.
5584 for (; i >= 0; i--) {
5585 if (dtrace_load8(src + i) != '/')
5592 ASSERT(!(lastbase == -1 && firstbase != -1));
5593 ASSERT(!(firstbase == -1 && lastdir != -1));
5595 if (lastbase == -1) {
5597 * We didn't find a non-slash character. We know that
5598 * the length is non-zero, so the whole string must be
5599 * slashes. In either the dirname or the basename
5600 * case, we return '/'.
5602 ASSERT(firstbase == -1);
5603 firstbase = lastbase = lastdir = 0;
5606 if (firstbase == -1) {
5608 * The entire string consists only of a basename
5609 * component. If we're looking for dirname, we need
5610 * to change our string to be just "."; if we're
5611 * looking for a basename, we'll just set the first
5612 * character of the basename to be 0.
5614 if (subr == DIF_SUBR_DIRNAME) {
5615 ASSERT(lastdir == -1);
5616 src = (uintptr_t)".";
5623 if (subr == DIF_SUBR_DIRNAME) {
5624 if (lastdir == -1) {
5626 * We know that we have a slash in the name --
5627 * or lastdir would be set to 0, above. And
5628 * because lastdir is -1, we know that this
5629 * slash must be the first character. (That
5630 * is, the full string must be of the form
5631 * "/basename".) In this case, the last
5632 * character of the directory name is 0.
5640 ASSERT(subr == DIF_SUBR_BASENAME);
5641 ASSERT(firstbase != -1 && lastbase != -1);
5646 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5647 dest[j] = dtrace_load8(src + i);
5650 regs[rd] = (uintptr_t)dest;
5651 mstate->dtms_scratch_ptr += size;
5655 case DIF_SUBR_GETF: {
5656 uintptr_t fd = tupregs[0].dttk_value;
5657 struct filedesc *fdp;
5660 if (!dtrace_priv_proc(state)) {
5664 fdp = curproc->p_fd;
5665 FILEDESC_SLOCK(fdp);
5666 fp = fget_locked(fdp, fd);
5667 mstate->dtms_getf = fp;
5668 regs[rd] = (uintptr_t)fp;
5669 FILEDESC_SUNLOCK(fdp);
5673 case DIF_SUBR_CLEANPATH: {
5674 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5675 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5676 uintptr_t src = tupregs[0].dttk_value;
5683 if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5688 if (!DTRACE_INSCRATCH(mstate, size)) {
5689 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5695 * Move forward, loading each character.
5698 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5700 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
5708 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5712 * We have two slashes -- we can just advance
5713 * to the next character.
5720 * This is not "." and it's not ".." -- we can
5721 * just store the "/" and this character and
5729 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5733 * This is a "/./" component. We're not going
5734 * to store anything in the destination buffer;
5735 * we're just going to go to the next component.
5742 * This is not ".." -- we can just store the
5743 * "/." and this character and continue
5752 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5754 if (c != '/' && c != '\0') {
5756 * This is not ".." -- it's "..[mumble]".
5757 * We'll store the "/.." and this character
5758 * and continue processing.
5768 * This is "/../" or "/..\0". We need to back up
5769 * our destination pointer until we find a "/".
5772 while (j != 0 && dest[--j] != '/')
5777 } while (c != '\0');
5782 if (mstate->dtms_getf != NULL &&
5783 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5784 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5786 * If we've done a getf() as a part of this ECB and we
5787 * don't have kernel access (and we're not in the global
5788 * zone), check if the path we cleaned up begins with
5789 * the zone's root path, and trim it off if so. Note
5790 * that this is an output cleanliness issue, not a
5791 * security issue: knowing one's zone root path does
5792 * not enable privilege escalation.
5794 if (strstr(dest, z->zone_rootpath) == dest)
5795 dest += strlen(z->zone_rootpath) - 1;
5799 regs[rd] = (uintptr_t)dest;
5800 mstate->dtms_scratch_ptr += size;
5804 case DIF_SUBR_INET_NTOA:
5805 case DIF_SUBR_INET_NTOA6:
5806 case DIF_SUBR_INET_NTOP: {
5811 if (subr == DIF_SUBR_INET_NTOP) {
5812 af = (int)tupregs[0].dttk_value;
5815 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5819 if (af == AF_INET) {
5823 if (!dtrace_canload(tupregs[argi].dttk_value,
5824 sizeof (ipaddr_t), mstate, vstate)) {
5830 * Safely load the IPv4 address.
5832 ip4 = dtrace_load32(tupregs[argi].dttk_value);
5835 * Check an IPv4 string will fit in scratch.
5837 size = INET_ADDRSTRLEN;
5838 if (!DTRACE_INSCRATCH(mstate, size)) {
5839 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5843 base = (char *)mstate->dtms_scratch_ptr;
5844 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5847 * Stringify as a dotted decimal quad.
5850 ptr8 = (uint8_t *)&ip4;
5851 for (i = 3; i >= 0; i--) {
5857 for (; val; val /= 10) {
5858 *end-- = '0' + (val % 10);
5865 ASSERT(end + 1 >= base);
5867 } else if (af == AF_INET6) {
5868 struct in6_addr ip6;
5869 int firstzero, tryzero, numzero, v6end;
5871 const char digits[] = "0123456789abcdef";
5874 * Stringify using RFC 1884 convention 2 - 16 bit
5875 * hexadecimal values with a zero-run compression.
5876 * Lower case hexadecimal digits are used.
5877 * eg, fe80::214:4fff:fe0b:76c8.
5878 * The IPv4 embedded form is returned for inet_ntop,
5879 * just the IPv4 string is returned for inet_ntoa6.
5882 if (!dtrace_canload(tupregs[argi].dttk_value,
5883 sizeof (struct in6_addr), mstate, vstate)) {
5889 * Safely load the IPv6 address.
5892 (void *)(uintptr_t)tupregs[argi].dttk_value,
5893 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5896 * Check an IPv6 string will fit in scratch.
5898 size = INET6_ADDRSTRLEN;
5899 if (!DTRACE_INSCRATCH(mstate, size)) {
5900 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5904 base = (char *)mstate->dtms_scratch_ptr;
5905 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5909 * Find the longest run of 16 bit zero values
5910 * for the single allowed zero compression - "::".
5915 for (i = 0; i < sizeof (struct in6_addr); i++) {
5917 if (ip6._S6_un._S6_u8[i] == 0 &&
5919 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5921 tryzero == -1 && i % 2 == 0) {
5926 if (tryzero != -1 &&
5928 (ip6._S6_un._S6_u8[i] != 0 ||
5930 (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5932 i == sizeof (struct in6_addr) - 1)) {
5934 if (i - tryzero <= numzero) {
5939 firstzero = tryzero;
5940 numzero = i - i % 2 - tryzero;
5944 if (ip6._S6_un._S6_u8[i] == 0 &&
5946 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5948 i == sizeof (struct in6_addr) - 1)
5952 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5955 * Check for an IPv4 embedded address.
5957 v6end = sizeof (struct in6_addr) - 2;
5958 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5959 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5960 for (i = sizeof (struct in6_addr) - 1;
5961 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5962 ASSERT(end >= base);
5965 val = ip6._S6_un._S6_u8[i];
5967 val = ip6.__u6_addr.__u6_addr8[i];
5973 for (; val; val /= 10) {
5974 *end-- = '0' + val % 10;
5978 if (i > DTRACE_V4MAPPED_OFFSET)
5982 if (subr == DIF_SUBR_INET_NTOA6)
5986 * Set v6end to skip the IPv4 address that
5987 * we have already stringified.
5993 * Build the IPv6 string by working through the
5994 * address in reverse.
5996 for (i = v6end; i >= 0; i -= 2) {
5997 ASSERT(end >= base);
5999 if (i == firstzero + numzero - 2) {
6006 if (i < 14 && i != firstzero - 2)
6010 val = (ip6._S6_un._S6_u8[i] << 8) +
6011 ip6._S6_un._S6_u8[i + 1];
6013 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
6014 ip6.__u6_addr.__u6_addr8[i + 1];
6020 for (; val; val /= 16) {
6021 *end-- = digits[val % 16];
6025 ASSERT(end + 1 >= base);
6029 * The user didn't use AH_INET or AH_INET6.
6031 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6036 inetout: regs[rd] = (uintptr_t)end + 1;
6037 mstate->dtms_scratch_ptr += size;
6041 case DIF_SUBR_MEMREF: {
6042 uintptr_t size = 2 * sizeof(uintptr_t);
6043 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
6044 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
6046 /* address and length */
6047 memref[0] = tupregs[0].dttk_value;
6048 memref[1] = tupregs[1].dttk_value;
6050 regs[rd] = (uintptr_t) memref;
6051 mstate->dtms_scratch_ptr += scratch_size;
6056 case DIF_SUBR_MEMSTR: {
6057 char *str = (char *)mstate->dtms_scratch_ptr;
6058 uintptr_t mem = tupregs[0].dttk_value;
6059 char c = tupregs[1].dttk_value;
6060 size_t size = tupregs[2].dttk_value;
6069 if (!dtrace_canload(mem, size - 1, mstate, vstate))
6072 if (!DTRACE_INSCRATCH(mstate, size)) {
6073 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6077 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
6078 *flags |= CPU_DTRACE_ILLOP;
6082 for (i = 0; i < size - 1; i++) {
6083 n = dtrace_load8(mem++);
6084 str[i] = (n == 0) ? c : n;
6088 regs[rd] = (uintptr_t)str;
6089 mstate->dtms_scratch_ptr += size;
6097 * Emulate the execution of DTrace IR instructions specified by the given
6098 * DIF object. This function is deliberately void of assertions as all of
6099 * the necessary checks are handled by a call to dtrace_difo_validate().
6102 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
6103 dtrace_vstate_t *vstate, dtrace_state_t *state)
6105 const dif_instr_t *text = difo->dtdo_buf;
6106 const uint_t textlen = difo->dtdo_len;
6107 const char *strtab = difo->dtdo_strtab;
6108 const uint64_t *inttab = difo->dtdo_inttab;
6111 dtrace_statvar_t *svar;
6112 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
6114 volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6115 volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
6117 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
6118 uint64_t regs[DIF_DIR_NREGS];
6121 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
6123 uint_t pc = 0, id, opc = 0;
6129 * We stash the current DIF object into the machine state: we need it
6130 * for subsequent access checking.
6132 mstate->dtms_difo = difo;
6134 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
6136 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
6140 r1 = DIF_INSTR_R1(instr);
6141 r2 = DIF_INSTR_R2(instr);
6142 rd = DIF_INSTR_RD(instr);
6144 switch (DIF_INSTR_OP(instr)) {
6146 regs[rd] = regs[r1] | regs[r2];
6149 regs[rd] = regs[r1] ^ regs[r2];
6152 regs[rd] = regs[r1] & regs[r2];
6155 regs[rd] = regs[r1] << regs[r2];
6158 regs[rd] = regs[r1] >> regs[r2];
6161 regs[rd] = regs[r1] - regs[r2];
6164 regs[rd] = regs[r1] + regs[r2];
6167 regs[rd] = regs[r1] * regs[r2];
6170 if (regs[r2] == 0) {
6172 *flags |= CPU_DTRACE_DIVZERO;
6174 regs[rd] = (int64_t)regs[r1] /
6180 if (regs[r2] == 0) {
6182 *flags |= CPU_DTRACE_DIVZERO;
6184 regs[rd] = regs[r1] / regs[r2];
6189 if (regs[r2] == 0) {
6191 *flags |= CPU_DTRACE_DIVZERO;
6193 regs[rd] = (int64_t)regs[r1] %
6199 if (regs[r2] == 0) {
6201 *flags |= CPU_DTRACE_DIVZERO;
6203 regs[rd] = regs[r1] % regs[r2];
6208 regs[rd] = ~regs[r1];
6211 regs[rd] = regs[r1];
6214 cc_r = regs[r1] - regs[r2];
6218 cc_c = regs[r1] < regs[r2];
6221 cc_n = cc_v = cc_c = 0;
6222 cc_z = regs[r1] == 0;
6225 pc = DIF_INSTR_LABEL(instr);
6229 pc = DIF_INSTR_LABEL(instr);
6233 pc = DIF_INSTR_LABEL(instr);
6236 if ((cc_z | (cc_n ^ cc_v)) == 0)
6237 pc = DIF_INSTR_LABEL(instr);
6240 if ((cc_c | cc_z) == 0)
6241 pc = DIF_INSTR_LABEL(instr);
6244 if ((cc_n ^ cc_v) == 0)
6245 pc = DIF_INSTR_LABEL(instr);
6249 pc = DIF_INSTR_LABEL(instr);
6253 pc = DIF_INSTR_LABEL(instr);
6257 pc = DIF_INSTR_LABEL(instr);
6260 if (cc_z | (cc_n ^ cc_v))
6261 pc = DIF_INSTR_LABEL(instr);
6265 pc = DIF_INSTR_LABEL(instr);
6268 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6272 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
6275 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6279 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
6282 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6286 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
6289 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
6293 regs[rd] = dtrace_load8(regs[r1]);
6296 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
6300 regs[rd] = dtrace_load16(regs[r1]);
6303 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
6307 regs[rd] = dtrace_load32(regs[r1]);
6310 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
6314 regs[rd] = dtrace_load64(regs[r1]);
6317 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6319 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6320 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6323 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6324 regs[rd] = (int16_t)
6325 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6326 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6329 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6330 regs[rd] = (int32_t)
6331 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6332 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6335 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6337 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
6338 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6341 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6343 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
6344 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6347 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6349 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
6350 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6353 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6355 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
6356 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6365 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6368 regs[rd] = (uint64_t)(uintptr_t)
6369 (strtab + DIF_INSTR_STRING(instr));
6372 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6373 uintptr_t s1 = regs[r1];
6374 uintptr_t s2 = regs[r2];
6378 * If one of the strings is NULL then the limit becomes
6379 * 0 which compares 0 characters in dtrace_strncmp()
6380 * resulting in a false positive. dtrace_strncmp()
6381 * treats a NULL as an empty 1-char string.
6386 !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6389 !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6392 cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6401 regs[rd] = dtrace_dif_variable(mstate, state,
6405 id = DIF_INSTR_VAR(instr);
6407 if (id >= DIF_VAR_OTHER_UBASE) {
6410 id -= DIF_VAR_OTHER_UBASE;
6411 svar = vstate->dtvs_globals[id];
6412 ASSERT(svar != NULL);
6413 v = &svar->dtsv_var;
6415 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6416 regs[rd] = svar->dtsv_data;
6420 a = (uintptr_t)svar->dtsv_data;
6422 if (*(uint8_t *)a == UINT8_MAX) {
6424 * If the 0th byte is set to UINT8_MAX
6425 * then this is to be treated as a
6426 * reference to a NULL variable.
6430 regs[rd] = a + sizeof (uint64_t);
6436 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6440 id = DIF_INSTR_VAR(instr);
6442 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6443 id -= DIF_VAR_OTHER_UBASE;
6445 VERIFY(id < vstate->dtvs_nglobals);
6446 svar = vstate->dtvs_globals[id];
6447 ASSERT(svar != NULL);
6448 v = &svar->dtsv_var;
6450 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6451 uintptr_t a = (uintptr_t)svar->dtsv_data;
6455 ASSERT(svar->dtsv_size != 0);
6457 if (regs[rd] == 0) {
6458 *(uint8_t *)a = UINT8_MAX;
6462 a += sizeof (uint64_t);
6464 if (!dtrace_vcanload(
6465 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6466 &lim, mstate, vstate))
6469 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6470 (void *)a, &v->dtdv_type, lim);
6474 svar->dtsv_data = regs[rd];
6479 * There are no DTrace built-in thread-local arrays at
6480 * present. This opcode is saved for future work.
6482 *flags |= CPU_DTRACE_ILLOP;
6487 id = DIF_INSTR_VAR(instr);
6489 if (id < DIF_VAR_OTHER_UBASE) {
6491 * For now, this has no meaning.
6497 id -= DIF_VAR_OTHER_UBASE;
6499 ASSERT(id < vstate->dtvs_nlocals);
6500 ASSERT(vstate->dtvs_locals != NULL);
6502 svar = vstate->dtvs_locals[id];
6503 ASSERT(svar != NULL);
6504 v = &svar->dtsv_var;
6506 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6507 uintptr_t a = (uintptr_t)svar->dtsv_data;
6508 size_t sz = v->dtdv_type.dtdt_size;
6511 sz += sizeof (uint64_t);
6512 ASSERT(svar->dtsv_size == NCPU * sz);
6515 if (*(uint8_t *)a == UINT8_MAX) {
6517 * If the 0th byte is set to UINT8_MAX
6518 * then this is to be treated as a
6519 * reference to a NULL variable.
6523 regs[rd] = a + sizeof (uint64_t);
6529 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6530 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6531 regs[rd] = tmp[curcpu];
6535 id = DIF_INSTR_VAR(instr);
6537 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6538 id -= DIF_VAR_OTHER_UBASE;
6539 VERIFY(id < vstate->dtvs_nlocals);
6541 ASSERT(vstate->dtvs_locals != NULL);
6542 svar = vstate->dtvs_locals[id];
6543 ASSERT(svar != NULL);
6544 v = &svar->dtsv_var;
6546 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6547 uintptr_t a = (uintptr_t)svar->dtsv_data;
6548 size_t sz = v->dtdv_type.dtdt_size;
6551 sz += sizeof (uint64_t);
6552 ASSERT(svar->dtsv_size == NCPU * sz);
6555 if (regs[rd] == 0) {
6556 *(uint8_t *)a = UINT8_MAX;
6560 a += sizeof (uint64_t);
6563 if (!dtrace_vcanload(
6564 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6565 &lim, mstate, vstate))
6568 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6569 (void *)a, &v->dtdv_type, lim);
6573 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6574 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6575 tmp[curcpu] = regs[rd];
6579 dtrace_dynvar_t *dvar;
6582 id = DIF_INSTR_VAR(instr);
6583 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6584 id -= DIF_VAR_OTHER_UBASE;
6585 v = &vstate->dtvs_tlocals[id];
6587 key = &tupregs[DIF_DTR_NREGS];
6588 key[0].dttk_value = (uint64_t)id;
6589 key[0].dttk_size = 0;
6590 DTRACE_TLS_THRKEY(key[1].dttk_value);
6591 key[1].dttk_size = 0;
6593 dvar = dtrace_dynvar(dstate, 2, key,
6594 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6602 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6603 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6605 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6612 dtrace_dynvar_t *dvar;
6615 id = DIF_INSTR_VAR(instr);
6616 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6617 id -= DIF_VAR_OTHER_UBASE;
6618 VERIFY(id < vstate->dtvs_ntlocals);
6620 key = &tupregs[DIF_DTR_NREGS];
6621 key[0].dttk_value = (uint64_t)id;
6622 key[0].dttk_size = 0;
6623 DTRACE_TLS_THRKEY(key[1].dttk_value);
6624 key[1].dttk_size = 0;
6625 v = &vstate->dtvs_tlocals[id];
6627 dvar = dtrace_dynvar(dstate, 2, key,
6628 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6629 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6630 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6631 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6634 * Given that we're storing to thread-local data,
6635 * we need to flush our predicate cache.
6637 curthread->t_predcache = 0;
6642 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6645 if (!dtrace_vcanload(
6646 (void *)(uintptr_t)regs[rd],
6647 &v->dtdv_type, &lim, mstate, vstate))
6650 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6651 dvar->dtdv_data, &v->dtdv_type, lim);
6653 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6660 regs[rd] = (int64_t)regs[r1] >> regs[r2];
6664 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6665 regs, tupregs, ttop, mstate, state);
6669 if (ttop == DIF_DTR_NREGS) {
6670 *flags |= CPU_DTRACE_TUPOFLOW;
6674 if (r1 == DIF_TYPE_STRING) {
6676 * If this is a string type and the size is 0,
6677 * we'll use the system-wide default string
6678 * size. Note that we are _not_ looking at
6679 * the value of the DTRACEOPT_STRSIZE option;
6680 * had this been set, we would expect to have
6681 * a non-zero size value in the "pushtr".
6683 tupregs[ttop].dttk_size =
6684 dtrace_strlen((char *)(uintptr_t)regs[rd],
6685 regs[r2] ? regs[r2] :
6686 dtrace_strsize_default) + 1;
6688 if (regs[r2] > LONG_MAX) {
6689 *flags |= CPU_DTRACE_ILLOP;
6693 tupregs[ttop].dttk_size = regs[r2];
6696 tupregs[ttop++].dttk_value = regs[rd];
6700 if (ttop == DIF_DTR_NREGS) {
6701 *flags |= CPU_DTRACE_TUPOFLOW;
6705 tupregs[ttop].dttk_value = regs[rd];
6706 tupregs[ttop++].dttk_size = 0;
6714 case DIF_OP_FLUSHTS:
6719 case DIF_OP_LDTAA: {
6720 dtrace_dynvar_t *dvar;
6721 dtrace_key_t *key = tupregs;
6722 uint_t nkeys = ttop;
6724 id = DIF_INSTR_VAR(instr);
6725 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6726 id -= DIF_VAR_OTHER_UBASE;
6728 key[nkeys].dttk_value = (uint64_t)id;
6729 key[nkeys++].dttk_size = 0;
6731 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6732 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6733 key[nkeys++].dttk_size = 0;
6734 VERIFY(id < vstate->dtvs_ntlocals);
6735 v = &vstate->dtvs_tlocals[id];
6737 VERIFY(id < vstate->dtvs_nglobals);
6738 v = &vstate->dtvs_globals[id]->dtsv_var;
6741 dvar = dtrace_dynvar(dstate, nkeys, key,
6742 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6743 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6744 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6751 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6752 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6754 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6761 case DIF_OP_STTAA: {
6762 dtrace_dynvar_t *dvar;
6763 dtrace_key_t *key = tupregs;
6764 uint_t nkeys = ttop;
6766 id = DIF_INSTR_VAR(instr);
6767 ASSERT(id >= DIF_VAR_OTHER_UBASE);
6768 id -= DIF_VAR_OTHER_UBASE;
6770 key[nkeys].dttk_value = (uint64_t)id;
6771 key[nkeys++].dttk_size = 0;
6773 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6774 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6775 key[nkeys++].dttk_size = 0;
6776 VERIFY(id < vstate->dtvs_ntlocals);
6777 v = &vstate->dtvs_tlocals[id];
6779 VERIFY(id < vstate->dtvs_nglobals);
6780 v = &vstate->dtvs_globals[id]->dtsv_var;
6783 dvar = dtrace_dynvar(dstate, nkeys, key,
6784 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6785 v->dtdv_type.dtdt_size : sizeof (uint64_t),
6786 regs[rd] ? DTRACE_DYNVAR_ALLOC :
6787 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6792 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6795 if (!dtrace_vcanload(
6796 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6797 &lim, mstate, vstate))
6800 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6801 dvar->dtdv_data, &v->dtdv_type, lim);
6803 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6809 case DIF_OP_ALLOCS: {
6810 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6811 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6814 * Rounding up the user allocation size could have
6815 * overflowed large, bogus allocations (like -1ULL) to
6818 if (size < regs[r1] ||
6819 !DTRACE_INSCRATCH(mstate, size)) {
6820 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6825 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6826 mstate->dtms_scratch_ptr += size;
6832 if (!dtrace_canstore(regs[rd], regs[r2],
6834 *flags |= CPU_DTRACE_BADADDR;
6839 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6842 dtrace_bcopy((void *)(uintptr_t)regs[r1],
6843 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6847 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6848 *flags |= CPU_DTRACE_BADADDR;
6852 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6856 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6857 *flags |= CPU_DTRACE_BADADDR;
6862 *flags |= CPU_DTRACE_BADALIGN;
6866 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6870 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6871 *flags |= CPU_DTRACE_BADADDR;
6876 *flags |= CPU_DTRACE_BADALIGN;
6880 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6884 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6885 *flags |= CPU_DTRACE_BADADDR;
6890 *flags |= CPU_DTRACE_BADALIGN;
6894 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6899 if (!(*flags & CPU_DTRACE_FAULT))
6902 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6903 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6909 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6911 dtrace_probe_t *probe = ecb->dte_probe;
6912 dtrace_provider_t *prov = probe->dtpr_provider;
6913 char c[DTRACE_FULLNAMELEN + 80], *str;
6914 char *msg = "dtrace: breakpoint action at probe ";
6915 char *ecbmsg = " (ecb ";
6916 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6917 uintptr_t val = (uintptr_t)ecb;
6918 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6920 if (dtrace_destructive_disallow)
6924 * It's impossible to be taking action on the NULL probe.
6926 ASSERT(probe != NULL);
6929 * This is a poor man's (destitute man's?) sprintf(): we want to
6930 * print the provider name, module name, function name and name of
6931 * the probe, along with the hex address of the ECB with the breakpoint
6932 * action -- all of which we must place in the character buffer by
6935 while (*msg != '\0')
6938 for (str = prov->dtpv_name; *str != '\0'; str++)
6942 for (str = probe->dtpr_mod; *str != '\0'; str++)
6946 for (str = probe->dtpr_func; *str != '\0'; str++)
6950 for (str = probe->dtpr_name; *str != '\0'; str++)
6953 while (*ecbmsg != '\0')
6956 while (shift >= 0) {
6957 mask = (uintptr_t)0xf << shift;
6959 if (val >= ((uintptr_t)1 << shift))
6960 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6970 kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6975 dtrace_action_panic(dtrace_ecb_t *ecb)
6977 dtrace_probe_t *probe = ecb->dte_probe;
6980 * It's impossible to be taking action on the NULL probe.
6982 ASSERT(probe != NULL);
6984 if (dtrace_destructive_disallow)
6987 if (dtrace_panicked != NULL)
6990 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6994 * We won the right to panic. (We want to be sure that only one
6995 * thread calls panic() from dtrace_probe(), and that panic() is
6996 * called exactly once.)
6998 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6999 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
7000 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
7004 dtrace_action_raise(uint64_t sig)
7006 if (dtrace_destructive_disallow)
7010 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
7016 * raise() has a queue depth of 1 -- we ignore all subsequent
7017 * invocations of the raise() action.
7019 if (curthread->t_dtrace_sig == 0)
7020 curthread->t_dtrace_sig = (uint8_t)sig;
7022 curthread->t_sig_check = 1;
7025 struct proc *p = curproc;
7027 kern_psignal(p, sig);
7033 dtrace_action_stop(void)
7035 if (dtrace_destructive_disallow)
7039 if (!curthread->t_dtrace_stop) {
7040 curthread->t_dtrace_stop = 1;
7041 curthread->t_sig_check = 1;
7045 struct proc *p = curproc;
7047 kern_psignal(p, SIGSTOP);
7053 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
7056 volatile uint16_t *flags;
7060 cpu_t *cpu = &solaris_cpu[curcpu];
7063 if (dtrace_destructive_disallow)
7066 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7068 now = dtrace_gethrtime();
7070 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
7072 * We need to advance the mark to the current time.
7074 cpu->cpu_dtrace_chillmark = now;
7075 cpu->cpu_dtrace_chilled = 0;
7079 * Now check to see if the requested chill time would take us over
7080 * the maximum amount of time allowed in the chill interval. (Or
7081 * worse, if the calculation itself induces overflow.)
7083 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
7084 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
7085 *flags |= CPU_DTRACE_ILLOP;
7089 while (dtrace_gethrtime() - now < val)
7093 * Normally, we assure that the value of the variable "timestamp" does
7094 * not change within an ECB. The presence of chill() represents an
7095 * exception to this rule, however.
7097 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
7098 cpu->cpu_dtrace_chilled += val;
7102 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
7103 uint64_t *buf, uint64_t arg)
7105 int nframes = DTRACE_USTACK_NFRAMES(arg);
7106 int strsize = DTRACE_USTACK_STRSIZE(arg);
7107 uint64_t *pcs = &buf[1], *fps;
7108 char *str = (char *)&pcs[nframes];
7109 int size, offs = 0, i, j;
7111 uintptr_t old = mstate->dtms_scratch_ptr, saved;
7112 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
7116 * Should be taking a faster path if string space has not been
7119 ASSERT(strsize != 0);
7122 * We will first allocate some temporary space for the frame pointers.
7124 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
7125 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
7126 (nframes * sizeof (uint64_t));
7128 if (!DTRACE_INSCRATCH(mstate, size)) {
7130 * Not enough room for our frame pointers -- need to indicate
7131 * that we ran out of scratch space.
7133 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
7137 mstate->dtms_scratch_ptr += size;
7138 saved = mstate->dtms_scratch_ptr;
7141 * Now get a stack with both program counters and frame pointers.
7143 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7144 dtrace_getufpstack(buf, fps, nframes + 1);
7145 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7148 * If that faulted, we're cooked.
7150 if (*flags & CPU_DTRACE_FAULT)
7154 * Now we want to walk up the stack, calling the USTACK helper. For
7155 * each iteration, we restore the scratch pointer.
7157 for (i = 0; i < nframes; i++) {
7158 mstate->dtms_scratch_ptr = saved;
7160 if (offs >= strsize)
7163 sym = (char *)(uintptr_t)dtrace_helper(
7164 DTRACE_HELPER_ACTION_USTACK,
7165 mstate, state, pcs[i], fps[i]);
7168 * If we faulted while running the helper, we're going to
7169 * clear the fault and null out the corresponding string.
7171 if (*flags & CPU_DTRACE_FAULT) {
7172 *flags &= ~CPU_DTRACE_FAULT;
7182 if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
7183 &(state->dts_vstate))) {
7188 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7191 * Now copy in the string that the helper returned to us.
7193 for (j = 0; offs + j < strsize && j < rem; j++) {
7194 if ((str[offs + j] = sym[j]) == '\0')
7198 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7203 if (offs >= strsize) {
7205 * If we didn't have room for all of the strings, we don't
7206 * abort processing -- this needn't be a fatal error -- but we
7207 * still want to increment a counter (dts_stkstroverflows) to
7208 * allow this condition to be warned about. (If this is from
7209 * a jstack() action, it is easily tuned via jstackstrsize.)
7211 dtrace_error(&state->dts_stkstroverflows);
7214 while (offs < strsize)
7218 mstate->dtms_scratch_ptr = old;
7222 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
7223 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
7225 volatile uint16_t *flags;
7226 uint64_t val = *valp;
7227 size_t valoffs = *valoffsp;
7229 flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
7230 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
7233 * If this is a string, we're going to only load until we find the zero
7234 * byte -- after which we'll store zero bytes.
7236 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
7240 for (s = 0; s < size; s++) {
7241 if (c != '\0' && dtkind == DIF_TF_BYREF) {
7242 c = dtrace_load8(val++);
7243 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
7244 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7245 c = dtrace_fuword8((void *)(uintptr_t)val++);
7246 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7247 if (*flags & CPU_DTRACE_FAULT)
7251 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
7253 if (c == '\0' && intuple)
7258 while (valoffs < end) {
7259 if (dtkind == DIF_TF_BYREF) {
7260 c = dtrace_load8(val++);
7261 } else if (dtkind == DIF_TF_BYUREF) {
7262 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7263 c = dtrace_fuword8((void *)(uintptr_t)val++);
7264 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7265 if (*flags & CPU_DTRACE_FAULT)
7269 DTRACE_STORE(uint8_t, tomax,
7275 *valoffsp = valoffs;
7279 * Disables interrupts and sets the per-thread inprobe flag. When DEBUG is
7280 * defined, we also assert that we are not recursing unless the probe ID is an
7283 static dtrace_icookie_t
7284 dtrace_probe_enter(dtrace_id_t id)
7286 dtrace_icookie_t cookie;
7288 cookie = dtrace_interrupt_disable();
7291 * Unless this is an ERROR probe, we are not allowed to recurse in
7292 * dtrace_probe(). Recursing into DTrace probe usually means that a
7293 * function is instrumented that should not have been instrumented or
7294 * that the ordering guarantee of the records will be violated,
7295 * resulting in unexpected output. If there is an exception to this
7296 * assertion, a new case should be added.
7298 ASSERT(curthread->t_dtrace_inprobe == 0 ||
7299 id == dtrace_probeid_error);
7300 curthread->t_dtrace_inprobe = 1;
7306 * Clears the per-thread inprobe flag and enables interrupts.
7309 dtrace_probe_exit(dtrace_icookie_t cookie)
7312 curthread->t_dtrace_inprobe = 0;
7313 dtrace_interrupt_enable(cookie);
7317 * If you're looking for the epicenter of DTrace, you just found it. This
7318 * is the function called by the provider to fire a probe -- from which all
7319 * subsequent probe-context DTrace activity emanates.
7322 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
7323 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
7325 processorid_t cpuid;
7326 dtrace_icookie_t cookie;
7327 dtrace_probe_t *probe;
7328 dtrace_mstate_t mstate;
7330 dtrace_action_t *act;
7334 volatile uint16_t *flags;
7337 if (panicstr != NULL)
7342 * Kick out immediately if this CPU is still being born (in which case
7343 * curthread will be set to -1) or the current thread can't allow
7344 * probes in its current context.
7346 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
7350 cookie = dtrace_probe_enter(id);
7351 probe = dtrace_probes[id - 1];
7353 onintr = CPU_ON_INTR(CPU);
7355 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
7356 probe->dtpr_predcache == curthread->t_predcache) {
7358 * We have hit in the predicate cache; we know that
7359 * this predicate would evaluate to be false.
7361 dtrace_probe_exit(cookie);
7366 if (panic_quiesce) {
7368 if (panicstr != NULL) {
7371 * We don't trace anything if we're panicking.
7373 dtrace_probe_exit(cookie);
7377 now = mstate.dtms_timestamp = dtrace_gethrtime();
7378 mstate.dtms_present = DTRACE_MSTATE_TIMESTAMP;
7379 vtime = dtrace_vtime_references != 0;
7381 if (vtime && curthread->t_dtrace_start)
7382 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
7384 mstate.dtms_difo = NULL;
7385 mstate.dtms_probe = probe;
7386 mstate.dtms_strtok = 0;
7387 mstate.dtms_arg[0] = arg0;
7388 mstate.dtms_arg[1] = arg1;
7389 mstate.dtms_arg[2] = arg2;
7390 mstate.dtms_arg[3] = arg3;
7391 mstate.dtms_arg[4] = arg4;
7393 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
7395 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
7396 dtrace_predicate_t *pred = ecb->dte_predicate;
7397 dtrace_state_t *state = ecb->dte_state;
7398 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
7399 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
7400 dtrace_vstate_t *vstate = &state->dts_vstate;
7401 dtrace_provider_t *prov = probe->dtpr_provider;
7402 uint64_t tracememsize = 0;
7407 * A little subtlety with the following (seemingly innocuous)
7408 * declaration of the automatic 'val': by looking at the
7409 * code, you might think that it could be declared in the
7410 * action processing loop, below. (That is, it's only used in
7411 * the action processing loop.) However, it must be declared
7412 * out of that scope because in the case of DIF expression
7413 * arguments to aggregating actions, one iteration of the
7414 * action loop will use the last iteration's value.
7418 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7419 mstate.dtms_getf = NULL;
7421 *flags &= ~CPU_DTRACE_ERROR;
7423 if (prov == dtrace_provider) {
7425 * If dtrace itself is the provider of this probe,
7426 * we're only going to continue processing the ECB if
7427 * arg0 (the dtrace_state_t) is equal to the ECB's
7428 * creating state. (This prevents disjoint consumers
7429 * from seeing one another's metaprobes.)
7431 if (arg0 != (uint64_t)(uintptr_t)state)
7435 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7437 * We're not currently active. If our provider isn't
7438 * the dtrace pseudo provider, we're not interested.
7440 if (prov != dtrace_provider)
7444 * Now we must further check if we are in the BEGIN
7445 * probe. If we are, we will only continue processing
7446 * if we're still in WARMUP -- if one BEGIN enabling
7447 * has invoked the exit() action, we don't want to
7448 * evaluate subsequent BEGIN enablings.
7450 if (probe->dtpr_id == dtrace_probeid_begin &&
7451 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7452 ASSERT(state->dts_activity ==
7453 DTRACE_ACTIVITY_DRAINING);
7458 if (ecb->dte_cond) {
7460 * If the dte_cond bits indicate that this
7461 * consumer is only allowed to see user-mode firings
7462 * of this probe, call the provider's dtps_usermode()
7463 * entry point to check that the probe was fired
7464 * while in a user context. Skip this ECB if that's
7467 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
7468 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
7469 probe->dtpr_id, probe->dtpr_arg) == 0)
7474 * This is more subtle than it looks. We have to be
7475 * absolutely certain that CRED() isn't going to
7476 * change out from under us so it's only legit to
7477 * examine that structure if we're in constrained
7478 * situations. Currently, the only times we'll this
7479 * check is if a non-super-user has enabled the
7480 * profile or syscall providers -- providers that
7481 * allow visibility of all processes. For the
7482 * profile case, the check above will ensure that
7483 * we're examining a user context.
7485 if (ecb->dte_cond & DTRACE_COND_OWNER) {
7488 ecb->dte_state->dts_cred.dcr_cred;
7491 ASSERT(s_cr != NULL);
7493 if ((cr = CRED()) == NULL ||
7494 s_cr->cr_uid != cr->cr_uid ||
7495 s_cr->cr_uid != cr->cr_ruid ||
7496 s_cr->cr_uid != cr->cr_suid ||
7497 s_cr->cr_gid != cr->cr_gid ||
7498 s_cr->cr_gid != cr->cr_rgid ||
7499 s_cr->cr_gid != cr->cr_sgid ||
7500 (proc = ttoproc(curthread)) == NULL ||
7501 (proc->p_flag & SNOCD))
7505 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
7508 ecb->dte_state->dts_cred.dcr_cred;
7510 ASSERT(s_cr != NULL);
7512 if ((cr = CRED()) == NULL ||
7513 s_cr->cr_zone->zone_id !=
7514 cr->cr_zone->zone_id)
7520 if (now - state->dts_alive > dtrace_deadman_timeout) {
7522 * We seem to be dead. Unless we (a) have kernel
7523 * destructive permissions (b) have explicitly enabled
7524 * destructive actions and (c) destructive actions have
7525 * not been disabled, we're going to transition into
7526 * the KILLED state, from which no further processing
7527 * on this state will be performed.
7529 if (!dtrace_priv_kernel_destructive(state) ||
7530 !state->dts_cred.dcr_destructive ||
7531 dtrace_destructive_disallow) {
7532 void *activity = &state->dts_activity;
7533 dtrace_activity_t curstate;
7536 curstate = state->dts_activity;
7537 } while (dtrace_cas32(activity, curstate,
7538 DTRACE_ACTIVITY_KILLED) != curstate);
7544 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7545 ecb->dte_alignment, state, &mstate)) < 0)
7548 tomax = buf->dtb_tomax;
7549 ASSERT(tomax != NULL);
7551 if (ecb->dte_size != 0) {
7552 dtrace_rechdr_t dtrh;
7553 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7554 mstate.dtms_timestamp = dtrace_gethrtime();
7555 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7557 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7558 dtrh.dtrh_epid = ecb->dte_epid;
7559 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7560 mstate.dtms_timestamp);
7561 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7564 mstate.dtms_epid = ecb->dte_epid;
7565 mstate.dtms_present |= DTRACE_MSTATE_EPID;
7567 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7568 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
7570 mstate.dtms_access = 0;
7573 dtrace_difo_t *dp = pred->dtp_difo;
7576 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7578 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7579 dtrace_cacheid_t cid = probe->dtpr_predcache;
7581 if (cid != DTRACE_CACHEIDNONE && !onintr) {
7583 * Update the predicate cache...
7585 ASSERT(cid == pred->dtp_cacheid);
7586 curthread->t_predcache = cid;
7593 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7594 act != NULL; act = act->dta_next) {
7597 dtrace_recdesc_t *rec = &act->dta_rec;
7599 size = rec->dtrd_size;
7600 valoffs = offs + rec->dtrd_offset;
7602 if (DTRACEACT_ISAGG(act->dta_kind)) {
7604 dtrace_aggregation_t *agg;
7606 agg = (dtrace_aggregation_t *)act;
7608 if ((dp = act->dta_difo) != NULL)
7609 v = dtrace_dif_emulate(dp,
7610 &mstate, vstate, state);
7612 if (*flags & CPU_DTRACE_ERROR)
7616 * Note that we always pass the expression
7617 * value from the previous iteration of the
7618 * action loop. This value will only be used
7619 * if there is an expression argument to the
7620 * aggregating action, denoted by the
7621 * dtag_hasarg field.
7623 dtrace_aggregate(agg, buf,
7624 offs, aggbuf, v, val);
7628 switch (act->dta_kind) {
7629 case DTRACEACT_STOP:
7630 if (dtrace_priv_proc_destructive(state))
7631 dtrace_action_stop();
7634 case DTRACEACT_BREAKPOINT:
7635 if (dtrace_priv_kernel_destructive(state))
7636 dtrace_action_breakpoint(ecb);
7639 case DTRACEACT_PANIC:
7640 if (dtrace_priv_kernel_destructive(state))
7641 dtrace_action_panic(ecb);
7644 case DTRACEACT_STACK:
7645 if (!dtrace_priv_kernel(state))
7648 dtrace_getpcstack((pc_t *)(tomax + valoffs),
7649 size / sizeof (pc_t), probe->dtpr_aframes,
7650 DTRACE_ANCHORED(probe) ? NULL :
7654 case DTRACEACT_JSTACK:
7655 case DTRACEACT_USTACK:
7656 if (!dtrace_priv_proc(state))
7660 * See comment in DIF_VAR_PID.
7662 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7664 int depth = DTRACE_USTACK_NFRAMES(
7667 dtrace_bzero((void *)(tomax + valoffs),
7668 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7669 + depth * sizeof (uint64_t));
7674 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7675 curproc->p_dtrace_helpers != NULL) {
7677 * This is the slow path -- we have
7678 * allocated string space, and we're
7679 * getting the stack of a process that
7680 * has helpers. Call into a separate
7681 * routine to perform this processing.
7683 dtrace_action_ustack(&mstate, state,
7684 (uint64_t *)(tomax + valoffs),
7689 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7690 dtrace_getupcstack((uint64_t *)
7692 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7693 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7703 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7705 if (*flags & CPU_DTRACE_ERROR)
7708 switch (act->dta_kind) {
7709 case DTRACEACT_SPECULATE: {
7710 dtrace_rechdr_t *dtrh;
7712 ASSERT(buf == &state->dts_buffer[cpuid]);
7713 buf = dtrace_speculation_buffer(state,
7717 *flags |= CPU_DTRACE_DROP;
7721 offs = dtrace_buffer_reserve(buf,
7722 ecb->dte_needed, ecb->dte_alignment,
7726 *flags |= CPU_DTRACE_DROP;
7730 tomax = buf->dtb_tomax;
7731 ASSERT(tomax != NULL);
7733 if (ecb->dte_size == 0)
7736 ASSERT3U(ecb->dte_size, >=,
7737 sizeof (dtrace_rechdr_t));
7738 dtrh = ((void *)(tomax + offs));
7739 dtrh->dtrh_epid = ecb->dte_epid;
7741 * When the speculation is committed, all of
7742 * the records in the speculative buffer will
7743 * have their timestamps set to the commit
7744 * time. Until then, it is set to a sentinel
7745 * value, for debugability.
7747 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7751 case DTRACEACT_PRINTM: {
7752 /* The DIF returns a 'memref'. */
7753 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
7755 /* Get the size from the memref. */
7759 * Check if the size exceeds the allocated
7762 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
7764 *flags |= CPU_DTRACE_DROP;
7768 /* Store the size in the buffer first. */
7769 DTRACE_STORE(uintptr_t, tomax,
7773 * Offset the buffer address to the start
7776 valoffs += sizeof(uintptr_t);
7779 * Reset to the memory address rather than
7780 * the memref array, then let the BYREF
7781 * code below do the work to store the
7782 * memory data in the buffer.
7788 case DTRACEACT_CHILL:
7789 if (dtrace_priv_kernel_destructive(state))
7790 dtrace_action_chill(&mstate, val);
7793 case DTRACEACT_RAISE:
7794 if (dtrace_priv_proc_destructive(state))
7795 dtrace_action_raise(val);
7798 case DTRACEACT_COMMIT:
7802 * We need to commit our buffer state.
7805 buf->dtb_offset = offs + ecb->dte_size;
7806 buf = &state->dts_buffer[cpuid];
7807 dtrace_speculation_commit(state, cpuid, val);
7811 case DTRACEACT_DISCARD:
7812 dtrace_speculation_discard(state, cpuid, val);
7815 case DTRACEACT_DIFEXPR:
7816 case DTRACEACT_LIBACT:
7817 case DTRACEACT_PRINTF:
7818 case DTRACEACT_PRINTA:
7819 case DTRACEACT_SYSTEM:
7820 case DTRACEACT_FREOPEN:
7821 case DTRACEACT_TRACEMEM:
7824 case DTRACEACT_TRACEMEM_DYNSIZE:
7830 if (!dtrace_priv_kernel(state))
7834 case DTRACEACT_USYM:
7835 case DTRACEACT_UMOD:
7836 case DTRACEACT_UADDR: {
7838 struct pid *pid = curthread->t_procp->p_pidp;
7841 if (!dtrace_priv_proc(state))
7844 DTRACE_STORE(uint64_t, tomax,
7846 valoffs, (uint64_t)pid->pid_id);
7848 valoffs, (uint64_t) curproc->p_pid);
7850 DTRACE_STORE(uint64_t, tomax,
7851 valoffs + sizeof (uint64_t), val);
7856 case DTRACEACT_EXIT: {
7858 * For the exit action, we are going to attempt
7859 * to atomically set our activity to be
7860 * draining. If this fails (either because
7861 * another CPU has beat us to the exit action,
7862 * or because our current activity is something
7863 * other than ACTIVE or WARMUP), we will
7864 * continue. This assures that the exit action
7865 * can be successfully recorded at most once
7866 * when we're in the ACTIVE state. If we're
7867 * encountering the exit() action while in
7868 * COOLDOWN, however, we want to honor the new
7869 * status code. (We know that we're the only
7870 * thread in COOLDOWN, so there is no race.)
7872 void *activity = &state->dts_activity;
7873 dtrace_activity_t curstate = state->dts_activity;
7875 if (curstate == DTRACE_ACTIVITY_COOLDOWN)
7878 if (curstate != DTRACE_ACTIVITY_WARMUP)
7879 curstate = DTRACE_ACTIVITY_ACTIVE;
7881 if (dtrace_cas32(activity, curstate,
7882 DTRACE_ACTIVITY_DRAINING) != curstate) {
7883 *flags |= CPU_DTRACE_DROP;
7894 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7895 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7896 uintptr_t end = valoffs + size;
7898 if (tracememsize != 0 &&
7899 valoffs + tracememsize < end) {
7900 end = valoffs + tracememsize;
7904 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7905 !dtrace_vcanload((void *)(uintptr_t)val,
7906 &dp->dtdo_rtype, NULL, &mstate, vstate))
7909 dtrace_store_by_ref(dp, tomax, size, &valoffs,
7910 &val, end, act->dta_intuple,
7911 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7912 DIF_TF_BYREF: DIF_TF_BYUREF);
7920 case sizeof (uint8_t):
7921 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7923 case sizeof (uint16_t):
7924 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7926 case sizeof (uint32_t):
7927 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7929 case sizeof (uint64_t):
7930 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7934 * Any other size should have been returned by
7935 * reference, not by value.
7942 if (*flags & CPU_DTRACE_DROP)
7945 if (*flags & CPU_DTRACE_FAULT) {
7947 dtrace_action_t *err;
7951 if (probe->dtpr_id == dtrace_probeid_error) {
7953 * There's nothing we can do -- we had an
7954 * error on the error probe. We bump an
7955 * error counter to at least indicate that
7956 * this condition happened.
7958 dtrace_error(&state->dts_dblerrors);
7964 * Before recursing on dtrace_probe(), we
7965 * need to explicitly clear out our start
7966 * time to prevent it from being accumulated
7967 * into t_dtrace_vtime.
7969 curthread->t_dtrace_start = 0;
7973 * Iterate over the actions to figure out which action
7974 * we were processing when we experienced the error.
7975 * Note that act points _past_ the faulting action; if
7976 * act is ecb->dte_action, the fault was in the
7977 * predicate, if it's ecb->dte_action->dta_next it's
7978 * in action #1, and so on.
7980 for (err = ecb->dte_action, ndx = 0;
7981 err != act; err = err->dta_next, ndx++)
7984 dtrace_probe_error(state, ecb->dte_epid, ndx,
7985 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7986 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7987 cpu_core[cpuid].cpuc_dtrace_illval);
7993 buf->dtb_offset = offs + ecb->dte_size;
7997 curthread->t_dtrace_start = dtrace_gethrtime();
7999 dtrace_probe_exit(cookie);
8003 * DTrace Probe Hashing Functions
8005 * The functions in this section (and indeed, the functions in remaining
8006 * sections) are not _called_ from probe context. (Any exceptions to this are
8007 * marked with a "Note:".) Rather, they are called from elsewhere in the
8008 * DTrace framework to look-up probes in, add probes to and remove probes from
8009 * the DTrace probe hashes. (Each probe is hashed by each element of the
8010 * probe tuple -- allowing for fast lookups, regardless of what was
8014 dtrace_hash_str(const char *p)
8020 hval = (hval << 4) + *p++;
8021 if ((g = (hval & 0xf0000000)) != 0)
8028 static dtrace_hash_t *
8029 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
8031 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
8033 hash->dth_stroffs = stroffs;
8034 hash->dth_nextoffs = nextoffs;
8035 hash->dth_prevoffs = prevoffs;
8038 hash->dth_mask = hash->dth_size - 1;
8040 hash->dth_tab = kmem_zalloc(hash->dth_size *
8041 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
8047 dtrace_hash_destroy(dtrace_hash_t *hash)
8052 for (i = 0; i < hash->dth_size; i++)
8053 ASSERT(hash->dth_tab[i] == NULL);
8056 kmem_free(hash->dth_tab,
8057 hash->dth_size * sizeof (dtrace_hashbucket_t *));
8058 kmem_free(hash, sizeof (dtrace_hash_t));
8062 dtrace_hash_resize(dtrace_hash_t *hash)
8064 int size = hash->dth_size, i, ndx;
8065 int new_size = hash->dth_size << 1;
8066 int new_mask = new_size - 1;
8067 dtrace_hashbucket_t **new_tab, *bucket, *next;
8069 ASSERT((new_size & new_mask) == 0);
8071 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
8073 for (i = 0; i < size; i++) {
8074 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
8075 dtrace_probe_t *probe = bucket->dthb_chain;
8077 ASSERT(probe != NULL);
8078 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
8080 next = bucket->dthb_next;
8081 bucket->dthb_next = new_tab[ndx];
8082 new_tab[ndx] = bucket;
8086 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
8087 hash->dth_tab = new_tab;
8088 hash->dth_size = new_size;
8089 hash->dth_mask = new_mask;
8093 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
8095 int hashval = DTRACE_HASHSTR(hash, new);
8096 int ndx = hashval & hash->dth_mask;
8097 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8098 dtrace_probe_t **nextp, **prevp;
8100 for (; bucket != NULL; bucket = bucket->dthb_next) {
8101 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
8105 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
8106 dtrace_hash_resize(hash);
8107 dtrace_hash_add(hash, new);
8111 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
8112 bucket->dthb_next = hash->dth_tab[ndx];
8113 hash->dth_tab[ndx] = bucket;
8114 hash->dth_nbuckets++;
8117 nextp = DTRACE_HASHNEXT(hash, new);
8118 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
8119 *nextp = bucket->dthb_chain;
8121 if (bucket->dthb_chain != NULL) {
8122 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
8123 ASSERT(*prevp == NULL);
8127 bucket->dthb_chain = new;
8131 static dtrace_probe_t *
8132 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
8134 int hashval = DTRACE_HASHSTR(hash, template);
8135 int ndx = hashval & hash->dth_mask;
8136 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8138 for (; bucket != NULL; bucket = bucket->dthb_next) {
8139 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8140 return (bucket->dthb_chain);
8147 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
8149 int hashval = DTRACE_HASHSTR(hash, template);
8150 int ndx = hashval & hash->dth_mask;
8151 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8153 for (; bucket != NULL; bucket = bucket->dthb_next) {
8154 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
8155 return (bucket->dthb_len);
8162 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
8164 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
8165 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
8167 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
8168 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
8171 * Find the bucket that we're removing this probe from.
8173 for (; bucket != NULL; bucket = bucket->dthb_next) {
8174 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
8178 ASSERT(bucket != NULL);
8180 if (*prevp == NULL) {
8181 if (*nextp == NULL) {
8183 * The removed probe was the only probe on this
8184 * bucket; we need to remove the bucket.
8186 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
8188 ASSERT(bucket->dthb_chain == probe);
8192 hash->dth_tab[ndx] = bucket->dthb_next;
8194 while (b->dthb_next != bucket)
8196 b->dthb_next = bucket->dthb_next;
8199 ASSERT(hash->dth_nbuckets > 0);
8200 hash->dth_nbuckets--;
8201 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
8205 bucket->dthb_chain = *nextp;
8207 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
8211 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
8215 * DTrace Utility Functions
8217 * These are random utility functions that are _not_ called from probe context.
8220 dtrace_badattr(const dtrace_attribute_t *a)
8222 return (a->dtat_name > DTRACE_STABILITY_MAX ||
8223 a->dtat_data > DTRACE_STABILITY_MAX ||
8224 a->dtat_class > DTRACE_CLASS_MAX);
8228 * Return a duplicate copy of a string. If the specified string is NULL,
8229 * this function returns a zero-length string.
8232 dtrace_strdup(const char *str)
8234 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
8237 (void) strcpy(new, str);
8242 #define DTRACE_ISALPHA(c) \
8243 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
8246 dtrace_badname(const char *s)
8250 if (s == NULL || (c = *s++) == '\0')
8253 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
8256 while ((c = *s++) != '\0') {
8257 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
8258 c != '-' && c != '_' && c != '.' && c != '`')
8266 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
8271 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
8273 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
8275 priv = DTRACE_PRIV_ALL;
8277 *uidp = crgetuid(cr);
8278 *zoneidp = crgetzoneid(cr);
8281 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
8282 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
8283 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
8284 priv |= DTRACE_PRIV_USER;
8285 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
8286 priv |= DTRACE_PRIV_PROC;
8287 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
8288 priv |= DTRACE_PRIV_OWNER;
8289 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
8290 priv |= DTRACE_PRIV_ZONEOWNER;
8293 priv = DTRACE_PRIV_ALL;
8299 #ifdef DTRACE_ERRDEBUG
8301 dtrace_errdebug(const char *str)
8303 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
8306 mutex_enter(&dtrace_errlock);
8307 dtrace_errlast = str;
8308 dtrace_errthread = curthread;
8310 while (occupied++ < DTRACE_ERRHASHSZ) {
8311 if (dtrace_errhash[hval].dter_msg == str) {
8312 dtrace_errhash[hval].dter_count++;
8316 if (dtrace_errhash[hval].dter_msg != NULL) {
8317 hval = (hval + 1) % DTRACE_ERRHASHSZ;
8321 dtrace_errhash[hval].dter_msg = str;
8322 dtrace_errhash[hval].dter_count = 1;
8326 panic("dtrace: undersized error hash");
8328 mutex_exit(&dtrace_errlock);
8333 * DTrace Matching Functions
8335 * These functions are used to match groups of probes, given some elements of
8336 * a probe tuple, or some globbed expressions for elements of a probe tuple.
8339 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
8342 if (priv != DTRACE_PRIV_ALL) {
8343 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
8344 uint32_t match = priv & ppriv;
8347 * No PRIV_DTRACE_* privileges...
8349 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
8350 DTRACE_PRIV_KERNEL)) == 0)
8354 * No matching bits, but there were bits to match...
8356 if (match == 0 && ppriv != 0)
8360 * Need to have permissions to the process, but don't...
8362 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
8363 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
8368 * Need to be in the same zone unless we possess the
8369 * privilege to examine all zones.
8371 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
8372 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
8381 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
8382 * consists of input pattern strings and an ops-vector to evaluate them.
8383 * This function returns >0 for match, 0 for no match, and <0 for error.
8386 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
8387 uint32_t priv, uid_t uid, zoneid_t zoneid)
8389 dtrace_provider_t *pvp = prp->dtpr_provider;
8392 if (pvp->dtpv_defunct)
8395 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
8398 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
8401 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
8404 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
8407 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
8414 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
8415 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
8416 * libc's version, the kernel version only applies to 8-bit ASCII strings.
8417 * In addition, all of the recursion cases except for '*' matching have been
8418 * unwound. For '*', we still implement recursive evaluation, but a depth
8419 * counter is maintained and matching is aborted if we recurse too deep.
8420 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
8423 dtrace_match_glob(const char *s, const char *p, int depth)
8429 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
8433 s = ""; /* treat NULL as empty string */
8442 if ((c = *p++) == '\0')
8443 return (s1 == '\0');
8447 int ok = 0, notflag = 0;
8458 if ((c = *p++) == '\0')
8462 if (c == '-' && lc != '\0' && *p != ']') {
8463 if ((c = *p++) == '\0')
8465 if (c == '\\' && (c = *p++) == '\0')
8469 if (s1 < lc || s1 > c)
8473 } else if (lc <= s1 && s1 <= c)
8476 } else if (c == '\\' && (c = *p++) == '\0')
8479 lc = c; /* save left-hand 'c' for next iteration */
8489 if ((c = *p++) == '\0')
8501 if ((c = *p++) == '\0')
8517 p++; /* consecutive *'s are identical to a single one */
8522 for (s = olds; *s != '\0'; s++) {
8523 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8533 dtrace_match_string(const char *s, const char *p, int depth)
8535 return (s != NULL && strcmp(s, p) == 0);
8540 dtrace_match_nul(const char *s, const char *p, int depth)
8542 return (1); /* always match the empty pattern */
8547 dtrace_match_nonzero(const char *s, const char *p, int depth)
8549 return (s != NULL && s[0] != '\0');
8553 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8554 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8556 dtrace_probe_t template, *probe;
8557 dtrace_hash_t *hash = NULL;
8558 int len, best = INT_MAX, nmatched = 0;
8561 ASSERT(MUTEX_HELD(&dtrace_lock));
8564 * If the probe ID is specified in the key, just lookup by ID and
8565 * invoke the match callback once if a matching probe is found.
8567 if (pkp->dtpk_id != DTRACE_IDNONE) {
8568 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8569 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8570 (void) (*matched)(probe, arg);
8576 template.dtpr_mod = (char *)pkp->dtpk_mod;
8577 template.dtpr_func = (char *)pkp->dtpk_func;
8578 template.dtpr_name = (char *)pkp->dtpk_name;
8581 * We want to find the most distinct of the module name, function
8582 * name, and name. So for each one that is not a glob pattern or
8583 * empty string, we perform a lookup in the corresponding hash and
8584 * use the hash table with the fewest collisions to do our search.
8586 if (pkp->dtpk_mmatch == &dtrace_match_string &&
8587 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8589 hash = dtrace_bymod;
8592 if (pkp->dtpk_fmatch == &dtrace_match_string &&
8593 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8595 hash = dtrace_byfunc;
8598 if (pkp->dtpk_nmatch == &dtrace_match_string &&
8599 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8601 hash = dtrace_byname;
8605 * If we did not select a hash table, iterate over every probe and
8606 * invoke our callback for each one that matches our input probe key.
8609 for (i = 0; i < dtrace_nprobes; i++) {
8610 if ((probe = dtrace_probes[i]) == NULL ||
8611 dtrace_match_probe(probe, pkp, priv, uid,
8617 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8625 * If we selected a hash table, iterate over each probe of the same key
8626 * name and invoke the callback for every probe that matches the other
8627 * attributes of our input probe key.
8629 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8630 probe = *(DTRACE_HASHNEXT(hash, probe))) {
8632 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8637 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
8645 * Return the function pointer dtrace_probecmp() should use to compare the
8646 * specified pattern with a string. For NULL or empty patterns, we select
8647 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
8648 * For non-empty non-glob strings, we use dtrace_match_string().
8650 static dtrace_probekey_f *
8651 dtrace_probekey_func(const char *p)
8655 if (p == NULL || *p == '\0')
8656 return (&dtrace_match_nul);
8658 while ((c = *p++) != '\0') {
8659 if (c == '[' || c == '?' || c == '*' || c == '\\')
8660 return (&dtrace_match_glob);
8663 return (&dtrace_match_string);
8667 * Build a probe comparison key for use with dtrace_match_probe() from the
8668 * given probe description. By convention, a null key only matches anchored
8669 * probes: if each field is the empty string, reset dtpk_fmatch to
8670 * dtrace_match_nonzero().
8673 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8675 pkp->dtpk_prov = pdp->dtpd_provider;
8676 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8678 pkp->dtpk_mod = pdp->dtpd_mod;
8679 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8681 pkp->dtpk_func = pdp->dtpd_func;
8682 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8684 pkp->dtpk_name = pdp->dtpd_name;
8685 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8687 pkp->dtpk_id = pdp->dtpd_id;
8689 if (pkp->dtpk_id == DTRACE_IDNONE &&
8690 pkp->dtpk_pmatch == &dtrace_match_nul &&
8691 pkp->dtpk_mmatch == &dtrace_match_nul &&
8692 pkp->dtpk_fmatch == &dtrace_match_nul &&
8693 pkp->dtpk_nmatch == &dtrace_match_nul)
8694 pkp->dtpk_fmatch = &dtrace_match_nonzero;
8698 * DTrace Provider-to-Framework API Functions
8700 * These functions implement much of the Provider-to-Framework API, as
8701 * described in <sys/dtrace.h>. The parts of the API not in this section are
8702 * the functions in the API for probe management (found below), and
8703 * dtrace_probe() itself (found above).
8707 * Register the calling provider with the DTrace framework. This should
8708 * generally be called by DTrace providers in their attach(9E) entry point.
8711 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8712 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8714 dtrace_provider_t *provider;
8716 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8717 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8718 "arguments", name ? name : "<NULL>");
8722 if (name[0] == '\0' || dtrace_badname(name)) {
8723 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8724 "provider name", name);
8728 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8729 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8730 pops->dtps_destroy == NULL ||
8731 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8732 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8733 "provider ops", name);
8737 if (dtrace_badattr(&pap->dtpa_provider) ||
8738 dtrace_badattr(&pap->dtpa_mod) ||
8739 dtrace_badattr(&pap->dtpa_func) ||
8740 dtrace_badattr(&pap->dtpa_name) ||
8741 dtrace_badattr(&pap->dtpa_args)) {
8742 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8743 "provider attributes", name);
8747 if (priv & ~DTRACE_PRIV_ALL) {
8748 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8749 "privilege attributes", name);
8753 if ((priv & DTRACE_PRIV_KERNEL) &&
8754 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8755 pops->dtps_usermode == NULL) {
8756 cmn_err(CE_WARN, "failed to register provider '%s': need "
8757 "dtps_usermode() op for given privilege attributes", name);
8761 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8762 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8763 (void) strcpy(provider->dtpv_name, name);
8765 provider->dtpv_attr = *pap;
8766 provider->dtpv_priv.dtpp_flags = priv;
8768 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8769 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8771 provider->dtpv_pops = *pops;
8773 if (pops->dtps_provide == NULL) {
8774 ASSERT(pops->dtps_provide_module != NULL);
8775 provider->dtpv_pops.dtps_provide =
8776 (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
8779 if (pops->dtps_provide_module == NULL) {
8780 ASSERT(pops->dtps_provide != NULL);
8781 provider->dtpv_pops.dtps_provide_module =
8782 (void (*)(void *, modctl_t *))dtrace_nullop;
8785 if (pops->dtps_suspend == NULL) {
8786 ASSERT(pops->dtps_resume == NULL);
8787 provider->dtpv_pops.dtps_suspend =
8788 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8789 provider->dtpv_pops.dtps_resume =
8790 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8793 provider->dtpv_arg = arg;
8794 *idp = (dtrace_provider_id_t)provider;
8796 if (pops == &dtrace_provider_ops) {
8797 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8798 ASSERT(MUTEX_HELD(&dtrace_lock));
8799 ASSERT(dtrace_anon.dta_enabling == NULL);
8802 * We make sure that the DTrace provider is at the head of
8803 * the provider chain.
8805 provider->dtpv_next = dtrace_provider;
8806 dtrace_provider = provider;
8810 mutex_enter(&dtrace_provider_lock);
8811 mutex_enter(&dtrace_lock);
8814 * If there is at least one provider registered, we'll add this
8815 * provider after the first provider.
8817 if (dtrace_provider != NULL) {
8818 provider->dtpv_next = dtrace_provider->dtpv_next;
8819 dtrace_provider->dtpv_next = provider;
8821 dtrace_provider = provider;
8824 if (dtrace_retained != NULL) {
8825 dtrace_enabling_provide(provider);
8828 * Now we need to call dtrace_enabling_matchall() -- which
8829 * will acquire cpu_lock and dtrace_lock. We therefore need
8830 * to drop all of our locks before calling into it...
8832 mutex_exit(&dtrace_lock);
8833 mutex_exit(&dtrace_provider_lock);
8834 dtrace_enabling_matchall();
8839 mutex_exit(&dtrace_lock);
8840 mutex_exit(&dtrace_provider_lock);
8846 * Unregister the specified provider from the DTrace framework. This should
8847 * generally be called by DTrace providers in their detach(9E) entry point.
8850 dtrace_unregister(dtrace_provider_id_t id)
8852 dtrace_provider_t *old = (dtrace_provider_t *)id;
8853 dtrace_provider_t *prev = NULL;
8854 int i, self = 0, noreap = 0;
8855 dtrace_probe_t *probe, *first = NULL;
8857 if (old->dtpv_pops.dtps_enable ==
8858 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
8860 * If DTrace itself is the provider, we're called with locks
8863 ASSERT(old == dtrace_provider);
8865 ASSERT(dtrace_devi != NULL);
8867 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8868 ASSERT(MUTEX_HELD(&dtrace_lock));
8871 if (dtrace_provider->dtpv_next != NULL) {
8873 * There's another provider here; return failure.
8878 mutex_enter(&dtrace_provider_lock);
8880 mutex_enter(&mod_lock);
8882 mutex_enter(&dtrace_lock);
8886 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8887 * probes, we refuse to let providers slither away, unless this
8888 * provider has already been explicitly invalidated.
8890 if (!old->dtpv_defunct &&
8891 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8892 dtrace_anon.dta_state->dts_necbs > 0))) {
8894 mutex_exit(&dtrace_lock);
8896 mutex_exit(&mod_lock);
8898 mutex_exit(&dtrace_provider_lock);
8904 * Attempt to destroy the probes associated with this provider.
8906 for (i = 0; i < dtrace_nprobes; i++) {
8907 if ((probe = dtrace_probes[i]) == NULL)
8910 if (probe->dtpr_provider != old)
8913 if (probe->dtpr_ecb == NULL)
8917 * If we are trying to unregister a defunct provider, and the
8918 * provider was made defunct within the interval dictated by
8919 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8920 * attempt to reap our enablings. To denote that the provider
8921 * should reattempt to unregister itself at some point in the
8922 * future, we will return a differentiable error code (EAGAIN
8923 * instead of EBUSY) in this case.
8925 if (dtrace_gethrtime() - old->dtpv_defunct >
8926 dtrace_unregister_defunct_reap)
8930 mutex_exit(&dtrace_lock);
8932 mutex_exit(&mod_lock);
8934 mutex_exit(&dtrace_provider_lock);
8940 (void) taskq_dispatch(dtrace_taskq,
8941 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8947 * All of the probes for this provider are disabled; we can safely
8948 * remove all of them from their hash chains and from the probe array.
8950 for (i = 0; i < dtrace_nprobes; i++) {
8951 if ((probe = dtrace_probes[i]) == NULL)
8954 if (probe->dtpr_provider != old)
8957 dtrace_probes[i] = NULL;
8959 dtrace_hash_remove(dtrace_bymod, probe);
8960 dtrace_hash_remove(dtrace_byfunc, probe);
8961 dtrace_hash_remove(dtrace_byname, probe);
8963 if (first == NULL) {
8965 probe->dtpr_nextmod = NULL;
8967 probe->dtpr_nextmod = first;
8973 * The provider's probes have been removed from the hash chains and
8974 * from the probe array. Now issue a dtrace_sync() to be sure that
8975 * everyone has cleared out from any probe array processing.
8979 for (probe = first; probe != NULL; probe = first) {
8980 first = probe->dtpr_nextmod;
8982 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8984 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8985 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8986 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8988 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8990 free_unr(dtrace_arena, probe->dtpr_id);
8992 kmem_free(probe, sizeof (dtrace_probe_t));
8995 if ((prev = dtrace_provider) == old) {
8997 ASSERT(self || dtrace_devi == NULL);
8998 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
9000 dtrace_provider = old->dtpv_next;
9002 while (prev != NULL && prev->dtpv_next != old)
9003 prev = prev->dtpv_next;
9006 panic("attempt to unregister non-existent "
9007 "dtrace provider %p\n", (void *)id);
9010 prev->dtpv_next = old->dtpv_next;
9014 mutex_exit(&dtrace_lock);
9016 mutex_exit(&mod_lock);
9018 mutex_exit(&dtrace_provider_lock);
9021 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
9022 kmem_free(old, sizeof (dtrace_provider_t));
9028 * Invalidate the specified provider. All subsequent probe lookups for the
9029 * specified provider will fail, but its probes will not be removed.
9032 dtrace_invalidate(dtrace_provider_id_t id)
9034 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
9036 ASSERT(pvp->dtpv_pops.dtps_enable !=
9037 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9039 mutex_enter(&dtrace_provider_lock);
9040 mutex_enter(&dtrace_lock);
9042 pvp->dtpv_defunct = dtrace_gethrtime();
9044 mutex_exit(&dtrace_lock);
9045 mutex_exit(&dtrace_provider_lock);
9049 * Indicate whether or not DTrace has attached.
9052 dtrace_attached(void)
9055 * dtrace_provider will be non-NULL iff the DTrace driver has
9056 * attached. (It's non-NULL because DTrace is always itself a
9059 return (dtrace_provider != NULL);
9063 * Remove all the unenabled probes for the given provider. This function is
9064 * not unlike dtrace_unregister(), except that it doesn't remove the provider
9065 * -- just as many of its associated probes as it can.
9068 dtrace_condense(dtrace_provider_id_t id)
9070 dtrace_provider_t *prov = (dtrace_provider_t *)id;
9072 dtrace_probe_t *probe;
9075 * Make sure this isn't the dtrace provider itself.
9077 ASSERT(prov->dtpv_pops.dtps_enable !=
9078 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
9080 mutex_enter(&dtrace_provider_lock);
9081 mutex_enter(&dtrace_lock);
9084 * Attempt to destroy the probes associated with this provider.
9086 for (i = 0; i < dtrace_nprobes; i++) {
9087 if ((probe = dtrace_probes[i]) == NULL)
9090 if (probe->dtpr_provider != prov)
9093 if (probe->dtpr_ecb != NULL)
9096 dtrace_probes[i] = NULL;
9098 dtrace_hash_remove(dtrace_bymod, probe);
9099 dtrace_hash_remove(dtrace_byfunc, probe);
9100 dtrace_hash_remove(dtrace_byname, probe);
9102 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
9104 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
9105 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
9106 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
9107 kmem_free(probe, sizeof (dtrace_probe_t));
9109 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
9111 free_unr(dtrace_arena, i + 1);
9115 mutex_exit(&dtrace_lock);
9116 mutex_exit(&dtrace_provider_lock);
9122 * DTrace Probe Management Functions
9124 * The functions in this section perform the DTrace probe management,
9125 * including functions to create probes, look-up probes, and call into the
9126 * providers to request that probes be provided. Some of these functions are
9127 * in the Provider-to-Framework API; these functions can be identified by the
9128 * fact that they are not declared "static".
9132 * Create a probe with the specified module name, function name, and name.
9135 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
9136 const char *func, const char *name, int aframes, void *arg)
9138 dtrace_probe_t *probe, **probes;
9139 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
9142 if (provider == dtrace_provider) {
9143 ASSERT(MUTEX_HELD(&dtrace_lock));
9145 mutex_enter(&dtrace_lock);
9149 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
9150 VM_BESTFIT | VM_SLEEP);
9152 id = alloc_unr(dtrace_arena);
9154 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
9156 probe->dtpr_id = id;
9157 probe->dtpr_gen = dtrace_probegen++;
9158 probe->dtpr_mod = dtrace_strdup(mod);
9159 probe->dtpr_func = dtrace_strdup(func);
9160 probe->dtpr_name = dtrace_strdup(name);
9161 probe->dtpr_arg = arg;
9162 probe->dtpr_aframes = aframes;
9163 probe->dtpr_provider = provider;
9165 dtrace_hash_add(dtrace_bymod, probe);
9166 dtrace_hash_add(dtrace_byfunc, probe);
9167 dtrace_hash_add(dtrace_byname, probe);
9169 if (id - 1 >= dtrace_nprobes) {
9170 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
9171 size_t nsize = osize << 1;
9175 ASSERT(dtrace_probes == NULL);
9176 nsize = sizeof (dtrace_probe_t *);
9179 probes = kmem_zalloc(nsize, KM_SLEEP);
9181 if (dtrace_probes == NULL) {
9183 dtrace_probes = probes;
9186 dtrace_probe_t **oprobes = dtrace_probes;
9188 bcopy(oprobes, probes, osize);
9189 dtrace_membar_producer();
9190 dtrace_probes = probes;
9195 * All CPUs are now seeing the new probes array; we can
9196 * safely free the old array.
9198 kmem_free(oprobes, osize);
9199 dtrace_nprobes <<= 1;
9202 ASSERT(id - 1 < dtrace_nprobes);
9205 ASSERT(dtrace_probes[id - 1] == NULL);
9206 dtrace_probes[id - 1] = probe;
9208 if (provider != dtrace_provider)
9209 mutex_exit(&dtrace_lock);
9214 static dtrace_probe_t *
9215 dtrace_probe_lookup_id(dtrace_id_t id)
9217 ASSERT(MUTEX_HELD(&dtrace_lock));
9219 if (id == 0 || id > dtrace_nprobes)
9222 return (dtrace_probes[id - 1]);
9226 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
9228 *((dtrace_id_t *)arg) = probe->dtpr_id;
9230 return (DTRACE_MATCH_DONE);
9234 * Look up a probe based on provider and one or more of module name, function
9235 * name and probe name.
9238 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
9239 char *func, char *name)
9241 dtrace_probekey_t pkey;
9245 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
9246 pkey.dtpk_pmatch = &dtrace_match_string;
9247 pkey.dtpk_mod = mod;
9248 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
9249 pkey.dtpk_func = func;
9250 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
9251 pkey.dtpk_name = name;
9252 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
9253 pkey.dtpk_id = DTRACE_IDNONE;
9255 mutex_enter(&dtrace_lock);
9256 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
9257 dtrace_probe_lookup_match, &id);
9258 mutex_exit(&dtrace_lock);
9260 ASSERT(match == 1 || match == 0);
9261 return (match ? id : 0);
9265 * Returns the probe argument associated with the specified probe.
9268 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
9270 dtrace_probe_t *probe;
9273 mutex_enter(&dtrace_lock);
9275 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
9276 probe->dtpr_provider == (dtrace_provider_t *)id)
9277 rval = probe->dtpr_arg;
9279 mutex_exit(&dtrace_lock);
9285 * Copy a probe into a probe description.
9288 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
9290 bzero(pdp, sizeof (dtrace_probedesc_t));
9291 pdp->dtpd_id = prp->dtpr_id;
9293 (void) strncpy(pdp->dtpd_provider,
9294 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
9296 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
9297 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
9298 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
9302 * Called to indicate that a probe -- or probes -- should be provided by a
9303 * specfied provider. If the specified description is NULL, the provider will
9304 * be told to provide all of its probes. (This is done whenever a new
9305 * consumer comes along, or whenever a retained enabling is to be matched.) If
9306 * the specified description is non-NULL, the provider is given the
9307 * opportunity to dynamically provide the specified probe, allowing providers
9308 * to support the creation of probes on-the-fly. (So-called _autocreated_
9309 * probes.) If the provider is NULL, the operations will be applied to all
9310 * providers; if the provider is non-NULL the operations will only be applied
9311 * to the specified provider. The dtrace_provider_lock must be held, and the
9312 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
9313 * will need to grab the dtrace_lock when it reenters the framework through
9314 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
9317 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
9324 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9328 prv = dtrace_provider;
9333 * First, call the blanket provide operation.
9335 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
9339 * Now call the per-module provide operation. We will grab
9340 * mod_lock to prevent the list from being modified. Note
9341 * that this also prevents the mod_busy bits from changing.
9342 * (mod_busy can only be changed with mod_lock held.)
9344 mutex_enter(&mod_lock);
9348 if (ctl->mod_busy || ctl->mod_mp == NULL)
9351 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
9353 } while ((ctl = ctl->mod_next) != &modules);
9355 mutex_exit(&mod_lock);
9357 } while (all && (prv = prv->dtpv_next) != NULL);
9362 * Iterate over each probe, and call the Framework-to-Provider API function
9366 dtrace_probe_foreach(uintptr_t offs)
9368 dtrace_provider_t *prov;
9369 void (*func)(void *, dtrace_id_t, void *);
9370 dtrace_probe_t *probe;
9371 dtrace_icookie_t cookie;
9375 * We disable interrupts to walk through the probe array. This is
9376 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
9377 * won't see stale data.
9379 cookie = dtrace_interrupt_disable();
9381 for (i = 0; i < dtrace_nprobes; i++) {
9382 if ((probe = dtrace_probes[i]) == NULL)
9385 if (probe->dtpr_ecb == NULL) {
9387 * This probe isn't enabled -- don't call the function.
9392 prov = probe->dtpr_provider;
9393 func = *((void(**)(void *, dtrace_id_t, void *))
9394 ((uintptr_t)&prov->dtpv_pops + offs));
9396 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
9399 dtrace_interrupt_enable(cookie);
9404 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
9406 dtrace_probekey_t pkey;
9411 ASSERT(MUTEX_HELD(&dtrace_lock));
9412 dtrace_ecb_create_cache = NULL;
9416 * If we're passed a NULL description, we're being asked to
9417 * create an ECB with a NULL probe.
9419 (void) dtrace_ecb_create_enable(NULL, enab);
9423 dtrace_probekey(desc, &pkey);
9424 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
9425 &priv, &uid, &zoneid);
9427 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
9432 * DTrace Helper Provider Functions
9435 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
9437 attr->dtat_name = DOF_ATTR_NAME(dofattr);
9438 attr->dtat_data = DOF_ATTR_DATA(dofattr);
9439 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
9443 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
9444 const dof_provider_t *dofprov, char *strtab)
9446 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
9447 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
9448 dofprov->dofpv_provattr);
9449 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
9450 dofprov->dofpv_modattr);
9451 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
9452 dofprov->dofpv_funcattr);
9453 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
9454 dofprov->dofpv_nameattr);
9455 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
9456 dofprov->dofpv_argsattr);
9460 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9462 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9463 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9464 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
9465 dof_provider_t *provider;
9467 uint32_t *off, *enoff;
9471 dtrace_helper_provdesc_t dhpv;
9472 dtrace_helper_probedesc_t dhpb;
9473 dtrace_meta_t *meta = dtrace_meta_pid;
9474 dtrace_mops_t *mops = &meta->dtm_mops;
9477 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9478 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9479 provider->dofpv_strtab * dof->dofh_secsize);
9480 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9481 provider->dofpv_probes * dof->dofh_secsize);
9482 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9483 provider->dofpv_prargs * dof->dofh_secsize);
9484 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9485 provider->dofpv_proffs * dof->dofh_secsize);
9487 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9488 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
9489 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
9493 * See dtrace_helper_provider_validate().
9495 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
9496 provider->dofpv_prenoffs != DOF_SECT_NONE) {
9497 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9498 provider->dofpv_prenoffs * dof->dofh_secsize);
9499 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
9502 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
9505 * Create the provider.
9507 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9509 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
9515 * Create the probes.
9517 for (i = 0; i < nprobes; i++) {
9518 probe = (dof_probe_t *)(uintptr_t)(daddr +
9519 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9521 /* See the check in dtrace_helper_provider_validate(). */
9522 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN)
9525 dhpb.dthpb_mod = dhp->dofhp_mod;
9526 dhpb.dthpb_func = strtab + probe->dofpr_func;
9527 dhpb.dthpb_name = strtab + probe->dofpr_name;
9528 dhpb.dthpb_base = probe->dofpr_addr;
9529 dhpb.dthpb_offs = off + probe->dofpr_offidx;
9530 dhpb.dthpb_noffs = probe->dofpr_noffs;
9531 if (enoff != NULL) {
9532 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9533 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9535 dhpb.dthpb_enoffs = NULL;
9536 dhpb.dthpb_nenoffs = 0;
9538 dhpb.dthpb_args = arg + probe->dofpr_argidx;
9539 dhpb.dthpb_nargc = probe->dofpr_nargc;
9540 dhpb.dthpb_xargc = probe->dofpr_xargc;
9541 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9542 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9544 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9549 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9551 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9552 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9555 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9557 for (i = 0; i < dof->dofh_secnum; i++) {
9558 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9559 dof->dofh_secoff + i * dof->dofh_secsize);
9561 if (sec->dofs_type != DOF_SECT_PROVIDER)
9564 dtrace_helper_provide_one(dhp, sec, pid);
9568 * We may have just created probes, so we must now rematch against
9569 * any retained enablings. Note that this call will acquire both
9570 * cpu_lock and dtrace_lock; the fact that we are holding
9571 * dtrace_meta_lock now is what defines the ordering with respect to
9572 * these three locks.
9574 dtrace_enabling_matchall();
9578 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9580 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9581 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9583 dof_provider_t *provider;
9585 dtrace_helper_provdesc_t dhpv;
9586 dtrace_meta_t *meta = dtrace_meta_pid;
9587 dtrace_mops_t *mops = &meta->dtm_mops;
9589 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9590 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9591 provider->dofpv_strtab * dof->dofh_secsize);
9593 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9596 * Create the provider.
9598 dtrace_dofprov2hprov(&dhpv, provider, strtab);
9600 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9606 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9608 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9609 dof_hdr_t *dof = (dof_hdr_t *)daddr;
9612 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9614 for (i = 0; i < dof->dofh_secnum; i++) {
9615 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9616 dof->dofh_secoff + i * dof->dofh_secsize);
9618 if (sec->dofs_type != DOF_SECT_PROVIDER)
9621 dtrace_helper_provider_remove_one(dhp, sec, pid);
9626 * DTrace Meta Provider-to-Framework API Functions
9628 * These functions implement the Meta Provider-to-Framework API, as described
9629 * in <sys/dtrace.h>.
9632 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9633 dtrace_meta_provider_id_t *idp)
9635 dtrace_meta_t *meta;
9636 dtrace_helpers_t *help, *next;
9639 *idp = DTRACE_METAPROVNONE;
9642 * We strictly don't need the name, but we hold onto it for
9643 * debuggability. All hail error queues!
9646 cmn_err(CE_WARN, "failed to register meta-provider: "
9652 mops->dtms_create_probe == NULL ||
9653 mops->dtms_provide_pid == NULL ||
9654 mops->dtms_remove_pid == NULL) {
9655 cmn_err(CE_WARN, "failed to register meta-register %s: "
9656 "invalid ops", name);
9660 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9661 meta->dtm_mops = *mops;
9662 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9663 (void) strcpy(meta->dtm_name, name);
9664 meta->dtm_arg = arg;
9666 mutex_enter(&dtrace_meta_lock);
9667 mutex_enter(&dtrace_lock);
9669 if (dtrace_meta_pid != NULL) {
9670 mutex_exit(&dtrace_lock);
9671 mutex_exit(&dtrace_meta_lock);
9672 cmn_err(CE_WARN, "failed to register meta-register %s: "
9673 "user-land meta-provider exists", name);
9674 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9675 kmem_free(meta, sizeof (dtrace_meta_t));
9679 dtrace_meta_pid = meta;
9680 *idp = (dtrace_meta_provider_id_t)meta;
9683 * If there are providers and probes ready to go, pass them
9684 * off to the new meta provider now.
9687 help = dtrace_deferred_pid;
9688 dtrace_deferred_pid = NULL;
9690 mutex_exit(&dtrace_lock);
9692 while (help != NULL) {
9693 for (i = 0; i < help->dthps_nprovs; i++) {
9694 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9698 next = help->dthps_next;
9699 help->dthps_next = NULL;
9700 help->dthps_prev = NULL;
9701 help->dthps_deferred = 0;
9705 mutex_exit(&dtrace_meta_lock);
9711 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9713 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9715 mutex_enter(&dtrace_meta_lock);
9716 mutex_enter(&dtrace_lock);
9718 if (old == dtrace_meta_pid) {
9719 pp = &dtrace_meta_pid;
9721 panic("attempt to unregister non-existent "
9722 "dtrace meta-provider %p\n", (void *)old);
9725 if (old->dtm_count != 0) {
9726 mutex_exit(&dtrace_lock);
9727 mutex_exit(&dtrace_meta_lock);
9733 mutex_exit(&dtrace_lock);
9734 mutex_exit(&dtrace_meta_lock);
9736 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9737 kmem_free(old, sizeof (dtrace_meta_t));
9744 * DTrace DIF Object Functions
9747 dtrace_difo_err(uint_t pc, const char *format, ...)
9749 if (dtrace_err_verbose) {
9752 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
9753 va_start(alist, format);
9754 (void) vuprintf(format, alist);
9758 #ifdef DTRACE_ERRDEBUG
9759 dtrace_errdebug(format);
9765 * Validate a DTrace DIF object by checking the IR instructions. The following
9766 * rules are currently enforced by dtrace_difo_validate():
9768 * 1. Each instruction must have a valid opcode
9769 * 2. Each register, string, variable, or subroutine reference must be valid
9770 * 3. No instruction can modify register %r0 (must be zero)
9771 * 4. All instruction reserved bits must be set to zero
9772 * 5. The last instruction must be a "ret" instruction
9773 * 6. All branch targets must reference a valid instruction _after_ the branch
9776 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9780 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9783 int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9785 kcheckload = cr == NULL ||
9786 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9788 dp->dtdo_destructive = 0;
9790 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9791 dif_instr_t instr = dp->dtdo_buf[pc];
9793 uint_t r1 = DIF_INSTR_R1(instr);
9794 uint_t r2 = DIF_INSTR_R2(instr);
9795 uint_t rd = DIF_INSTR_RD(instr);
9796 uint_t rs = DIF_INSTR_RS(instr);
9797 uint_t label = DIF_INSTR_LABEL(instr);
9798 uint_t v = DIF_INSTR_VAR(instr);
9799 uint_t subr = DIF_INSTR_SUBR(instr);
9800 uint_t type = DIF_INSTR_TYPE(instr);
9801 uint_t op = DIF_INSTR_OP(instr);
9819 err += efunc(pc, "invalid register %u\n", r1);
9821 err += efunc(pc, "invalid register %u\n", r2);
9823 err += efunc(pc, "invalid register %u\n", rd);
9825 err += efunc(pc, "cannot write to %r0\n");
9831 err += efunc(pc, "invalid register %u\n", r1);
9833 err += efunc(pc, "non-zero reserved bits\n");
9835 err += efunc(pc, "invalid register %u\n", rd);
9837 err += efunc(pc, "cannot write to %r0\n");
9847 err += efunc(pc, "invalid register %u\n", r1);
9849 err += efunc(pc, "non-zero reserved bits\n");
9851 err += efunc(pc, "invalid register %u\n", rd);
9853 err += efunc(pc, "cannot write to %r0\n");
9855 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9856 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9866 err += efunc(pc, "invalid register %u\n", r1);
9868 err += efunc(pc, "non-zero reserved bits\n");
9870 err += efunc(pc, "invalid register %u\n", rd);
9872 err += efunc(pc, "cannot write to %r0\n");
9882 err += efunc(pc, "invalid register %u\n", r1);
9884 err += efunc(pc, "non-zero reserved bits\n");
9886 err += efunc(pc, "invalid register %u\n", rd);
9888 err += efunc(pc, "cannot write to %r0\n");
9895 err += efunc(pc, "invalid register %u\n", r1);
9897 err += efunc(pc, "non-zero reserved bits\n");
9899 err += efunc(pc, "invalid register %u\n", rd);
9901 err += efunc(pc, "cannot write to 0 address\n");
9906 err += efunc(pc, "invalid register %u\n", r1);
9908 err += efunc(pc, "invalid register %u\n", r2);
9910 err += efunc(pc, "non-zero reserved bits\n");
9914 err += efunc(pc, "invalid register %u\n", r1);
9915 if (r2 != 0 || rd != 0)
9916 err += efunc(pc, "non-zero reserved bits\n");
9929 if (label >= dp->dtdo_len) {
9930 err += efunc(pc, "invalid branch target %u\n",
9934 err += efunc(pc, "backward branch to %u\n",
9939 if (r1 != 0 || r2 != 0)
9940 err += efunc(pc, "non-zero reserved bits\n");
9942 err += efunc(pc, "invalid register %u\n", rd);
9946 case DIF_OP_FLUSHTS:
9947 if (r1 != 0 || r2 != 0 || rd != 0)
9948 err += efunc(pc, "non-zero reserved bits\n");
9951 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9952 err += efunc(pc, "invalid integer ref %u\n",
9953 DIF_INSTR_INTEGER(instr));
9956 err += efunc(pc, "invalid register %u\n", rd);
9958 err += efunc(pc, "cannot write to %r0\n");
9961 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9962 err += efunc(pc, "invalid string ref %u\n",
9963 DIF_INSTR_STRING(instr));
9966 err += efunc(pc, "invalid register %u\n", rd);
9968 err += efunc(pc, "cannot write to %r0\n");
9972 if (r1 > DIF_VAR_ARRAY_MAX)
9973 err += efunc(pc, "invalid array %u\n", r1);
9975 err += efunc(pc, "invalid register %u\n", r2);
9977 err += efunc(pc, "invalid register %u\n", rd);
9979 err += efunc(pc, "cannot write to %r0\n");
9986 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9987 err += efunc(pc, "invalid variable %u\n", v);
9989 err += efunc(pc, "invalid register %u\n", rd);
9991 err += efunc(pc, "cannot write to %r0\n");
9998 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9999 err += efunc(pc, "invalid variable %u\n", v);
10001 err += efunc(pc, "invalid register %u\n", rd);
10004 if (subr > DIF_SUBR_MAX)
10005 err += efunc(pc, "invalid subr %u\n", subr);
10007 err += efunc(pc, "invalid register %u\n", rd);
10009 err += efunc(pc, "cannot write to %r0\n");
10011 if (subr == DIF_SUBR_COPYOUT ||
10012 subr == DIF_SUBR_COPYOUTSTR) {
10013 dp->dtdo_destructive = 1;
10016 if (subr == DIF_SUBR_GETF) {
10018 * If we have a getf() we need to record that
10019 * in our state. Note that our state can be
10020 * NULL if this is a helper -- but in that
10021 * case, the call to getf() is itself illegal,
10022 * and will be caught (slightly later) when
10023 * the helper is validated.
10025 if (vstate->dtvs_state != NULL)
10026 vstate->dtvs_state->dts_getf++;
10030 case DIF_OP_PUSHTR:
10031 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
10032 err += efunc(pc, "invalid ref type %u\n", type);
10034 err += efunc(pc, "invalid register %u\n", r2);
10036 err += efunc(pc, "invalid register %u\n", rs);
10038 case DIF_OP_PUSHTV:
10039 if (type != DIF_TYPE_CTF)
10040 err += efunc(pc, "invalid val type %u\n", type);
10042 err += efunc(pc, "invalid register %u\n", r2);
10044 err += efunc(pc, "invalid register %u\n", rs);
10047 err += efunc(pc, "invalid opcode %u\n",
10048 DIF_INSTR_OP(instr));
10052 if (dp->dtdo_len != 0 &&
10053 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
10054 err += efunc(dp->dtdo_len - 1,
10055 "expected 'ret' as last DIF instruction\n");
10058 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
10060 * If we're not returning by reference, the size must be either
10061 * 0 or the size of one of the base types.
10063 switch (dp->dtdo_rtype.dtdt_size) {
10065 case sizeof (uint8_t):
10066 case sizeof (uint16_t):
10067 case sizeof (uint32_t):
10068 case sizeof (uint64_t):
10072 err += efunc(dp->dtdo_len - 1, "bad return size\n");
10076 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
10077 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
10078 dtrace_diftype_t *vt, *et;
10081 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
10082 v->dtdv_scope != DIFV_SCOPE_THREAD &&
10083 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
10084 err += efunc(i, "unrecognized variable scope %d\n",
10089 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
10090 v->dtdv_kind != DIFV_KIND_SCALAR) {
10091 err += efunc(i, "unrecognized variable type %d\n",
10096 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
10097 err += efunc(i, "%d exceeds variable id limit\n", id);
10101 if (id < DIF_VAR_OTHER_UBASE)
10105 * For user-defined variables, we need to check that this
10106 * definition is identical to any previous definition that we
10109 ndx = id - DIF_VAR_OTHER_UBASE;
10111 switch (v->dtdv_scope) {
10112 case DIFV_SCOPE_GLOBAL:
10113 if (maxglobal == -1 || ndx > maxglobal)
10116 if (ndx < vstate->dtvs_nglobals) {
10117 dtrace_statvar_t *svar;
10119 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
10120 existing = &svar->dtsv_var;
10125 case DIFV_SCOPE_THREAD:
10126 if (maxtlocal == -1 || ndx > maxtlocal)
10129 if (ndx < vstate->dtvs_ntlocals)
10130 existing = &vstate->dtvs_tlocals[ndx];
10133 case DIFV_SCOPE_LOCAL:
10134 if (maxlocal == -1 || ndx > maxlocal)
10137 if (ndx < vstate->dtvs_nlocals) {
10138 dtrace_statvar_t *svar;
10140 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
10141 existing = &svar->dtsv_var;
10147 vt = &v->dtdv_type;
10149 if (vt->dtdt_flags & DIF_TF_BYREF) {
10150 if (vt->dtdt_size == 0) {
10151 err += efunc(i, "zero-sized variable\n");
10155 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
10156 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
10157 vt->dtdt_size > dtrace_statvar_maxsize) {
10158 err += efunc(i, "oversized by-ref static\n");
10163 if (existing == NULL || existing->dtdv_id == 0)
10166 ASSERT(existing->dtdv_id == v->dtdv_id);
10167 ASSERT(existing->dtdv_scope == v->dtdv_scope);
10169 if (existing->dtdv_kind != v->dtdv_kind)
10170 err += efunc(i, "%d changed variable kind\n", id);
10172 et = &existing->dtdv_type;
10174 if (vt->dtdt_flags != et->dtdt_flags) {
10175 err += efunc(i, "%d changed variable type flags\n", id);
10179 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
10180 err += efunc(i, "%d changed variable type size\n", id);
10185 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
10186 dif_instr_t instr = dp->dtdo_buf[pc];
10188 uint_t v = DIF_INSTR_VAR(instr);
10189 uint_t op = DIF_INSTR_OP(instr);
10196 if (v > DIF_VAR_OTHER_UBASE + maxglobal)
10197 err += efunc(pc, "invalid variable %u\n", v);
10203 if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
10204 err += efunc(pc, "invalid variable %u\n", v);
10208 if (v > DIF_VAR_OTHER_UBASE + maxlocal)
10209 err += efunc(pc, "invalid variable %u\n", v);
10220 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
10221 * are much more constrained than normal DIFOs. Specifically, they may
10224 * 1. Make calls to subroutines other than copyin(), copyinstr() or
10225 * miscellaneous string routines
10226 * 2. Access DTrace variables other than the args[] array, and the
10227 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
10228 * 3. Have thread-local variables.
10229 * 4. Have dynamic variables.
10232 dtrace_difo_validate_helper(dtrace_difo_t *dp)
10234 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
10238 for (pc = 0; pc < dp->dtdo_len; pc++) {
10239 dif_instr_t instr = dp->dtdo_buf[pc];
10241 uint_t v = DIF_INSTR_VAR(instr);
10242 uint_t subr = DIF_INSTR_SUBR(instr);
10243 uint_t op = DIF_INSTR_OP(instr);
10280 case DIF_OP_ALLOCS:
10298 case DIF_OP_FLUSHTS:
10305 case DIF_OP_PUSHTR:
10306 case DIF_OP_PUSHTV:
10310 if (v >= DIF_VAR_OTHER_UBASE)
10313 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
10316 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
10317 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
10318 v == DIF_VAR_EXECARGS ||
10319 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
10320 v == DIF_VAR_UID || v == DIF_VAR_GID)
10323 err += efunc(pc, "illegal variable %u\n", v);
10330 err += efunc(pc, "illegal dynamic variable load\n");
10336 err += efunc(pc, "illegal dynamic variable store\n");
10340 if (subr == DIF_SUBR_ALLOCA ||
10341 subr == DIF_SUBR_BCOPY ||
10342 subr == DIF_SUBR_COPYIN ||
10343 subr == DIF_SUBR_COPYINTO ||
10344 subr == DIF_SUBR_COPYINSTR ||
10345 subr == DIF_SUBR_INDEX ||
10346 subr == DIF_SUBR_INET_NTOA ||
10347 subr == DIF_SUBR_INET_NTOA6 ||
10348 subr == DIF_SUBR_INET_NTOP ||
10349 subr == DIF_SUBR_JSON ||
10350 subr == DIF_SUBR_LLTOSTR ||
10351 subr == DIF_SUBR_STRTOLL ||
10352 subr == DIF_SUBR_RINDEX ||
10353 subr == DIF_SUBR_STRCHR ||
10354 subr == DIF_SUBR_STRJOIN ||
10355 subr == DIF_SUBR_STRRCHR ||
10356 subr == DIF_SUBR_STRSTR ||
10357 subr == DIF_SUBR_HTONS ||
10358 subr == DIF_SUBR_HTONL ||
10359 subr == DIF_SUBR_HTONLL ||
10360 subr == DIF_SUBR_NTOHS ||
10361 subr == DIF_SUBR_NTOHL ||
10362 subr == DIF_SUBR_NTOHLL ||
10363 subr == DIF_SUBR_MEMREF)
10366 if (subr == DIF_SUBR_MEMSTR)
10370 err += efunc(pc, "invalid subr %u\n", subr);
10374 err += efunc(pc, "invalid opcode %u\n",
10375 DIF_INSTR_OP(instr));
10383 * Returns 1 if the expression in the DIF object can be cached on a per-thread
10387 dtrace_difo_cacheable(dtrace_difo_t *dp)
10394 for (i = 0; i < dp->dtdo_varlen; i++) {
10395 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10397 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
10400 switch (v->dtdv_id) {
10401 case DIF_VAR_CURTHREAD:
10404 case DIF_VAR_EXECARGS:
10405 case DIF_VAR_EXECNAME:
10406 case DIF_VAR_ZONENAME:
10415 * This DIF object may be cacheable. Now we need to look for any
10416 * array loading instructions, any memory loading instructions, or
10417 * any stores to thread-local variables.
10419 for (i = 0; i < dp->dtdo_len; i++) {
10420 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
10422 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
10423 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
10424 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
10425 op == DIF_OP_LDGA || op == DIF_OP_STTS)
10433 dtrace_difo_hold(dtrace_difo_t *dp)
10437 ASSERT(MUTEX_HELD(&dtrace_lock));
10440 ASSERT(dp->dtdo_refcnt != 0);
10443 * We need to check this DIF object for references to the variable
10444 * DIF_VAR_VTIMESTAMP.
10446 for (i = 0; i < dp->dtdo_varlen; i++) {
10447 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10449 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10452 if (dtrace_vtime_references++ == 0)
10453 dtrace_vtime_enable();
10458 * This routine calculates the dynamic variable chunksize for a given DIF
10459 * object. The calculation is not fool-proof, and can probably be tricked by
10460 * malicious DIF -- but it works for all compiler-generated DIF. Because this
10461 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
10462 * if a dynamic variable size exceeds the chunksize.
10465 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10468 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
10469 const dif_instr_t *text = dp->dtdo_buf;
10470 uint_t pc, srd = 0;
10472 size_t size, ksize;
10475 for (pc = 0; pc < dp->dtdo_len; pc++) {
10476 dif_instr_t instr = text[pc];
10477 uint_t op = DIF_INSTR_OP(instr);
10478 uint_t rd = DIF_INSTR_RD(instr);
10479 uint_t r1 = DIF_INSTR_R1(instr);
10483 dtrace_key_t *key = tupregs;
10487 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
10492 key = &tupregs[DIF_DTR_NREGS];
10493 key[0].dttk_size = 0;
10494 key[1].dttk_size = 0;
10496 scope = DIFV_SCOPE_THREAD;
10503 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
10504 key[nkeys++].dttk_size = 0;
10506 key[nkeys++].dttk_size = 0;
10508 if (op == DIF_OP_STTAA) {
10509 scope = DIFV_SCOPE_THREAD;
10511 scope = DIFV_SCOPE_GLOBAL;
10516 case DIF_OP_PUSHTR:
10517 if (ttop == DIF_DTR_NREGS)
10520 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10522 * If the register for the size of the "pushtr"
10523 * is %r0 (or the value is 0) and the type is
10524 * a string, we'll use the system-wide default
10527 tupregs[ttop++].dttk_size =
10528 dtrace_strsize_default;
10533 if (sval > LONG_MAX)
10536 tupregs[ttop++].dttk_size = sval;
10541 case DIF_OP_PUSHTV:
10542 if (ttop == DIF_DTR_NREGS)
10545 tupregs[ttop++].dttk_size = 0;
10548 case DIF_OP_FLUSHTS:
10565 * We have a dynamic variable allocation; calculate its size.
10567 for (ksize = 0, i = 0; i < nkeys; i++)
10568 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10570 size = sizeof (dtrace_dynvar_t);
10571 size += sizeof (dtrace_key_t) * (nkeys - 1);
10575 * Now we need to determine the size of the stored data.
10577 id = DIF_INSTR_VAR(instr);
10579 for (i = 0; i < dp->dtdo_varlen; i++) {
10580 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10582 if (v->dtdv_id == id && v->dtdv_scope == scope) {
10583 size += v->dtdv_type.dtdt_size;
10588 if (i == dp->dtdo_varlen)
10592 * We have the size. If this is larger than the chunk size
10593 * for our dynamic variable state, reset the chunk size.
10595 size = P2ROUNDUP(size, sizeof (uint64_t));
10598 * Before setting the chunk size, check that we're not going
10599 * to set it to a negative value...
10601 if (size > LONG_MAX)
10605 * ...and make certain that we didn't badly overflow.
10607 if (size < ksize || size < sizeof (dtrace_dynvar_t))
10610 if (size > vstate->dtvs_dynvars.dtds_chunksize)
10611 vstate->dtvs_dynvars.dtds_chunksize = size;
10616 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10618 int i, oldsvars, osz, nsz, otlocals, ntlocals;
10621 ASSERT(MUTEX_HELD(&dtrace_lock));
10622 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10624 for (i = 0; i < dp->dtdo_varlen; i++) {
10625 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10626 dtrace_statvar_t *svar, ***svarp = NULL;
10628 uint8_t scope = v->dtdv_scope;
10631 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10634 id -= DIF_VAR_OTHER_UBASE;
10637 case DIFV_SCOPE_THREAD:
10638 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10639 dtrace_difv_t *tlocals;
10641 if ((ntlocals = (otlocals << 1)) == 0)
10644 osz = otlocals * sizeof (dtrace_difv_t);
10645 nsz = ntlocals * sizeof (dtrace_difv_t);
10647 tlocals = kmem_zalloc(nsz, KM_SLEEP);
10650 bcopy(vstate->dtvs_tlocals,
10652 kmem_free(vstate->dtvs_tlocals, osz);
10655 vstate->dtvs_tlocals = tlocals;
10656 vstate->dtvs_ntlocals = ntlocals;
10659 vstate->dtvs_tlocals[id] = *v;
10662 case DIFV_SCOPE_LOCAL:
10663 np = &vstate->dtvs_nlocals;
10664 svarp = &vstate->dtvs_locals;
10666 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10667 dsize = NCPU * (v->dtdv_type.dtdt_size +
10668 sizeof (uint64_t));
10670 dsize = NCPU * sizeof (uint64_t);
10674 case DIFV_SCOPE_GLOBAL:
10675 np = &vstate->dtvs_nglobals;
10676 svarp = &vstate->dtvs_globals;
10678 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10679 dsize = v->dtdv_type.dtdt_size +
10688 while (id >= (oldsvars = *np)) {
10689 dtrace_statvar_t **statics;
10690 int newsvars, oldsize, newsize;
10692 if ((newsvars = (oldsvars << 1)) == 0)
10695 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10696 newsize = newsvars * sizeof (dtrace_statvar_t *);
10698 statics = kmem_zalloc(newsize, KM_SLEEP);
10700 if (oldsize != 0) {
10701 bcopy(*svarp, statics, oldsize);
10702 kmem_free(*svarp, oldsize);
10709 if ((svar = (*svarp)[id]) == NULL) {
10710 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10711 svar->dtsv_var = *v;
10713 if ((svar->dtsv_size = dsize) != 0) {
10714 svar->dtsv_data = (uint64_t)(uintptr_t)
10715 kmem_zalloc(dsize, KM_SLEEP);
10718 (*svarp)[id] = svar;
10721 svar->dtsv_refcnt++;
10724 dtrace_difo_chunksize(dp, vstate);
10725 dtrace_difo_hold(dp);
10728 static dtrace_difo_t *
10729 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10731 dtrace_difo_t *new;
10734 ASSERT(dp->dtdo_buf != NULL);
10735 ASSERT(dp->dtdo_refcnt != 0);
10737 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10739 ASSERT(dp->dtdo_buf != NULL);
10740 sz = dp->dtdo_len * sizeof (dif_instr_t);
10741 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10742 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10743 new->dtdo_len = dp->dtdo_len;
10745 if (dp->dtdo_strtab != NULL) {
10746 ASSERT(dp->dtdo_strlen != 0);
10747 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10748 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10749 new->dtdo_strlen = dp->dtdo_strlen;
10752 if (dp->dtdo_inttab != NULL) {
10753 ASSERT(dp->dtdo_intlen != 0);
10754 sz = dp->dtdo_intlen * sizeof (uint64_t);
10755 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10756 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10757 new->dtdo_intlen = dp->dtdo_intlen;
10760 if (dp->dtdo_vartab != NULL) {
10761 ASSERT(dp->dtdo_varlen != 0);
10762 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10763 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10764 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10765 new->dtdo_varlen = dp->dtdo_varlen;
10768 dtrace_difo_init(new, vstate);
10773 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10777 ASSERT(dp->dtdo_refcnt == 0);
10779 for (i = 0; i < dp->dtdo_varlen; i++) {
10780 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10781 dtrace_statvar_t *svar, **svarp = NULL;
10783 uint8_t scope = v->dtdv_scope;
10787 case DIFV_SCOPE_THREAD:
10790 case DIFV_SCOPE_LOCAL:
10791 np = &vstate->dtvs_nlocals;
10792 svarp = vstate->dtvs_locals;
10795 case DIFV_SCOPE_GLOBAL:
10796 np = &vstate->dtvs_nglobals;
10797 svarp = vstate->dtvs_globals;
10804 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10807 id -= DIF_VAR_OTHER_UBASE;
10811 ASSERT(svar != NULL);
10812 ASSERT(svar->dtsv_refcnt > 0);
10814 if (--svar->dtsv_refcnt > 0)
10817 if (svar->dtsv_size != 0) {
10818 ASSERT(svar->dtsv_data != 0);
10819 kmem_free((void *)(uintptr_t)svar->dtsv_data,
10823 kmem_free(svar, sizeof (dtrace_statvar_t));
10827 if (dp->dtdo_buf != NULL)
10828 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10829 if (dp->dtdo_inttab != NULL)
10830 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10831 if (dp->dtdo_strtab != NULL)
10832 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10833 if (dp->dtdo_vartab != NULL)
10834 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10836 kmem_free(dp, sizeof (dtrace_difo_t));
10840 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10844 ASSERT(MUTEX_HELD(&dtrace_lock));
10845 ASSERT(dp->dtdo_refcnt != 0);
10847 for (i = 0; i < dp->dtdo_varlen; i++) {
10848 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10850 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10853 ASSERT(dtrace_vtime_references > 0);
10854 if (--dtrace_vtime_references == 0)
10855 dtrace_vtime_disable();
10858 if (--dp->dtdo_refcnt == 0)
10859 dtrace_difo_destroy(dp, vstate);
10863 * DTrace Format Functions
10866 dtrace_format_add(dtrace_state_t *state, char *str)
10869 uint16_t ndx, len = strlen(str) + 1;
10871 fmt = kmem_zalloc(len, KM_SLEEP);
10872 bcopy(str, fmt, len);
10874 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10875 if (state->dts_formats[ndx] == NULL) {
10876 state->dts_formats[ndx] = fmt;
10881 if (state->dts_nformats == USHRT_MAX) {
10883 * This is only likely if a denial-of-service attack is being
10884 * attempted. As such, it's okay to fail silently here.
10886 kmem_free(fmt, len);
10891 * For simplicity, we always resize the formats array to be exactly the
10892 * number of formats.
10894 ndx = state->dts_nformats++;
10895 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10897 if (state->dts_formats != NULL) {
10899 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10900 kmem_free(state->dts_formats, ndx * sizeof (char *));
10903 state->dts_formats = new;
10904 state->dts_formats[ndx] = fmt;
10910 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10914 ASSERT(state->dts_formats != NULL);
10915 ASSERT(format <= state->dts_nformats);
10916 ASSERT(state->dts_formats[format - 1] != NULL);
10918 fmt = state->dts_formats[format - 1];
10919 kmem_free(fmt, strlen(fmt) + 1);
10920 state->dts_formats[format - 1] = NULL;
10924 dtrace_format_destroy(dtrace_state_t *state)
10928 if (state->dts_nformats == 0) {
10929 ASSERT(state->dts_formats == NULL);
10933 ASSERT(state->dts_formats != NULL);
10935 for (i = 0; i < state->dts_nformats; i++) {
10936 char *fmt = state->dts_formats[i];
10941 kmem_free(fmt, strlen(fmt) + 1);
10944 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10945 state->dts_nformats = 0;
10946 state->dts_formats = NULL;
10950 * DTrace Predicate Functions
10952 static dtrace_predicate_t *
10953 dtrace_predicate_create(dtrace_difo_t *dp)
10955 dtrace_predicate_t *pred;
10957 ASSERT(MUTEX_HELD(&dtrace_lock));
10958 ASSERT(dp->dtdo_refcnt != 0);
10960 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10961 pred->dtp_difo = dp;
10962 pred->dtp_refcnt = 1;
10964 if (!dtrace_difo_cacheable(dp))
10967 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10969 * This is only theoretically possible -- we have had 2^32
10970 * cacheable predicates on this machine. We cannot allow any
10971 * more predicates to become cacheable: as unlikely as it is,
10972 * there may be a thread caching a (now stale) predicate cache
10973 * ID. (N.B.: the temptation is being successfully resisted to
10974 * have this cmn_err() "Holy shit -- we executed this code!")
10979 pred->dtp_cacheid = dtrace_predcache_id++;
10985 dtrace_predicate_hold(dtrace_predicate_t *pred)
10987 ASSERT(MUTEX_HELD(&dtrace_lock));
10988 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10989 ASSERT(pred->dtp_refcnt > 0);
10991 pred->dtp_refcnt++;
10995 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10997 dtrace_difo_t *dp = pred->dtp_difo;
10999 ASSERT(MUTEX_HELD(&dtrace_lock));
11000 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
11001 ASSERT(pred->dtp_refcnt > 0);
11003 if (--pred->dtp_refcnt == 0) {
11004 dtrace_difo_release(pred->dtp_difo, vstate);
11005 kmem_free(pred, sizeof (dtrace_predicate_t));
11010 * DTrace Action Description Functions
11012 static dtrace_actdesc_t *
11013 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
11014 uint64_t uarg, uint64_t arg)
11016 dtrace_actdesc_t *act;
11019 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
11020 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
11023 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
11024 act->dtad_kind = kind;
11025 act->dtad_ntuple = ntuple;
11026 act->dtad_uarg = uarg;
11027 act->dtad_arg = arg;
11028 act->dtad_refcnt = 1;
11034 dtrace_actdesc_hold(dtrace_actdesc_t *act)
11036 ASSERT(act->dtad_refcnt >= 1);
11037 act->dtad_refcnt++;
11041 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
11043 dtrace_actkind_t kind = act->dtad_kind;
11046 ASSERT(act->dtad_refcnt >= 1);
11048 if (--act->dtad_refcnt != 0)
11051 if ((dp = act->dtad_difo) != NULL)
11052 dtrace_difo_release(dp, vstate);
11054 if (DTRACEACT_ISPRINTFLIKE(kind)) {
11055 char *str = (char *)(uintptr_t)act->dtad_arg;
11058 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
11059 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
11063 kmem_free(str, strlen(str) + 1);
11066 kmem_free(act, sizeof (dtrace_actdesc_t));
11070 * DTrace ECB Functions
11072 static dtrace_ecb_t *
11073 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
11076 dtrace_epid_t epid;
11078 ASSERT(MUTEX_HELD(&dtrace_lock));
11080 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
11081 ecb->dte_predicate = NULL;
11082 ecb->dte_probe = probe;
11085 * The default size is the size of the default action: recording
11088 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
11089 ecb->dte_alignment = sizeof (dtrace_epid_t);
11091 epid = state->dts_epid++;
11093 if (epid - 1 >= state->dts_necbs) {
11094 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
11095 int necbs = state->dts_necbs << 1;
11097 ASSERT(epid == state->dts_necbs + 1);
11100 ASSERT(oecbs == NULL);
11104 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
11107 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
11109 dtrace_membar_producer();
11110 state->dts_ecbs = ecbs;
11112 if (oecbs != NULL) {
11114 * If this state is active, we must dtrace_sync()
11115 * before we can free the old dts_ecbs array: we're
11116 * coming in hot, and there may be active ring
11117 * buffer processing (which indexes into the dts_ecbs
11118 * array) on another CPU.
11120 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11123 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
11126 dtrace_membar_producer();
11127 state->dts_necbs = necbs;
11130 ecb->dte_state = state;
11132 ASSERT(state->dts_ecbs[epid - 1] == NULL);
11133 dtrace_membar_producer();
11134 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
11140 dtrace_ecb_enable(dtrace_ecb_t *ecb)
11142 dtrace_probe_t *probe = ecb->dte_probe;
11144 ASSERT(MUTEX_HELD(&cpu_lock));
11145 ASSERT(MUTEX_HELD(&dtrace_lock));
11146 ASSERT(ecb->dte_next == NULL);
11148 if (probe == NULL) {
11150 * This is the NULL probe -- there's nothing to do.
11155 if (probe->dtpr_ecb == NULL) {
11156 dtrace_provider_t *prov = probe->dtpr_provider;
11159 * We're the first ECB on this probe.
11161 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
11163 if (ecb->dte_predicate != NULL)
11164 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
11166 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
11167 probe->dtpr_id, probe->dtpr_arg);
11170 * This probe is already active. Swing the last pointer to
11171 * point to the new ECB, and issue a dtrace_sync() to assure
11172 * that all CPUs have seen the change.
11174 ASSERT(probe->dtpr_ecb_last != NULL);
11175 probe->dtpr_ecb_last->dte_next = ecb;
11176 probe->dtpr_ecb_last = ecb;
11177 probe->dtpr_predcache = 0;
11184 dtrace_ecb_resize(dtrace_ecb_t *ecb)
11186 dtrace_action_t *act;
11187 uint32_t curneeded = UINT32_MAX;
11188 uint32_t aggbase = UINT32_MAX;
11191 * If we record anything, we always record the dtrace_rechdr_t. (And
11192 * we always record it first.)
11194 ecb->dte_size = sizeof (dtrace_rechdr_t);
11195 ecb->dte_alignment = sizeof (dtrace_epid_t);
11197 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11198 dtrace_recdesc_t *rec = &act->dta_rec;
11199 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
11201 ecb->dte_alignment = MAX(ecb->dte_alignment,
11202 rec->dtrd_alignment);
11204 if (DTRACEACT_ISAGG(act->dta_kind)) {
11205 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11207 ASSERT(rec->dtrd_size != 0);
11208 ASSERT(agg->dtag_first != NULL);
11209 ASSERT(act->dta_prev->dta_intuple);
11210 ASSERT(aggbase != UINT32_MAX);
11211 ASSERT(curneeded != UINT32_MAX);
11213 agg->dtag_base = aggbase;
11215 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11216 rec->dtrd_offset = curneeded;
11217 if (curneeded + rec->dtrd_size < curneeded)
11219 curneeded += rec->dtrd_size;
11220 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
11222 aggbase = UINT32_MAX;
11223 curneeded = UINT32_MAX;
11224 } else if (act->dta_intuple) {
11225 if (curneeded == UINT32_MAX) {
11227 * This is the first record in a tuple. Align
11228 * curneeded to be at offset 4 in an 8-byte
11231 ASSERT(act->dta_prev == NULL ||
11232 !act->dta_prev->dta_intuple);
11233 ASSERT3U(aggbase, ==, UINT32_MAX);
11234 curneeded = P2PHASEUP(ecb->dte_size,
11235 sizeof (uint64_t), sizeof (dtrace_aggid_t));
11237 aggbase = curneeded - sizeof (dtrace_aggid_t);
11238 ASSERT(IS_P2ALIGNED(aggbase,
11239 sizeof (uint64_t)));
11241 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
11242 rec->dtrd_offset = curneeded;
11243 if (curneeded + rec->dtrd_size < curneeded)
11245 curneeded += rec->dtrd_size;
11247 /* tuples must be followed by an aggregation */
11248 ASSERT(act->dta_prev == NULL ||
11249 !act->dta_prev->dta_intuple);
11251 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
11252 rec->dtrd_alignment);
11253 rec->dtrd_offset = ecb->dte_size;
11254 if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
11256 ecb->dte_size += rec->dtrd_size;
11257 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
11261 if ((act = ecb->dte_action) != NULL &&
11262 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
11263 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
11265 * If the size is still sizeof (dtrace_rechdr_t), then all
11266 * actions store no data; set the size to 0.
11271 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
11272 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
11273 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
11278 static dtrace_action_t *
11279 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11281 dtrace_aggregation_t *agg;
11282 size_t size = sizeof (uint64_t);
11283 int ntuple = desc->dtad_ntuple;
11284 dtrace_action_t *act;
11285 dtrace_recdesc_t *frec;
11286 dtrace_aggid_t aggid;
11287 dtrace_state_t *state = ecb->dte_state;
11289 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
11290 agg->dtag_ecb = ecb;
11292 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
11294 switch (desc->dtad_kind) {
11295 case DTRACEAGG_MIN:
11296 agg->dtag_initial = INT64_MAX;
11297 agg->dtag_aggregate = dtrace_aggregate_min;
11300 case DTRACEAGG_MAX:
11301 agg->dtag_initial = INT64_MIN;
11302 agg->dtag_aggregate = dtrace_aggregate_max;
11305 case DTRACEAGG_COUNT:
11306 agg->dtag_aggregate = dtrace_aggregate_count;
11309 case DTRACEAGG_QUANTIZE:
11310 agg->dtag_aggregate = dtrace_aggregate_quantize;
11311 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
11315 case DTRACEAGG_LQUANTIZE: {
11316 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
11317 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
11319 agg->dtag_initial = desc->dtad_arg;
11320 agg->dtag_aggregate = dtrace_aggregate_lquantize;
11322 if (step == 0 || levels == 0)
11325 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
11329 case DTRACEAGG_LLQUANTIZE: {
11330 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
11331 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
11332 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
11333 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
11336 agg->dtag_initial = desc->dtad_arg;
11337 agg->dtag_aggregate = dtrace_aggregate_llquantize;
11339 if (factor < 2 || low >= high || nsteps < factor)
11343 * Now check that the number of steps evenly divides a power
11344 * of the factor. (This assures both integer bucket size and
11345 * linearity within each magnitude.)
11347 for (v = factor; v < nsteps; v *= factor)
11350 if ((v % nsteps) || (nsteps % factor))
11353 size = (dtrace_aggregate_llquantize_bucket(factor,
11354 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
11358 case DTRACEAGG_AVG:
11359 agg->dtag_aggregate = dtrace_aggregate_avg;
11360 size = sizeof (uint64_t) * 2;
11363 case DTRACEAGG_STDDEV:
11364 agg->dtag_aggregate = dtrace_aggregate_stddev;
11365 size = sizeof (uint64_t) * 4;
11368 case DTRACEAGG_SUM:
11369 agg->dtag_aggregate = dtrace_aggregate_sum;
11376 agg->dtag_action.dta_rec.dtrd_size = size;
11382 * We must make sure that we have enough actions for the n-tuple.
11384 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
11385 if (DTRACEACT_ISAGG(act->dta_kind))
11388 if (--ntuple == 0) {
11390 * This is the action with which our n-tuple begins.
11392 agg->dtag_first = act;
11398 * This n-tuple is short by ntuple elements. Return failure.
11400 ASSERT(ntuple != 0);
11402 kmem_free(agg, sizeof (dtrace_aggregation_t));
11407 * If the last action in the tuple has a size of zero, it's actually
11408 * an expression argument for the aggregating action.
11410 ASSERT(ecb->dte_action_last != NULL);
11411 act = ecb->dte_action_last;
11413 if (act->dta_kind == DTRACEACT_DIFEXPR) {
11414 ASSERT(act->dta_difo != NULL);
11416 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
11417 agg->dtag_hasarg = 1;
11421 * We need to allocate an id for this aggregation.
11424 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
11425 VM_BESTFIT | VM_SLEEP);
11427 aggid = alloc_unr(state->dts_aggid_arena);
11430 if (aggid - 1 >= state->dts_naggregations) {
11431 dtrace_aggregation_t **oaggs = state->dts_aggregations;
11432 dtrace_aggregation_t **aggs;
11433 int naggs = state->dts_naggregations << 1;
11434 int onaggs = state->dts_naggregations;
11436 ASSERT(aggid == state->dts_naggregations + 1);
11439 ASSERT(oaggs == NULL);
11443 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
11445 if (oaggs != NULL) {
11446 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
11447 kmem_free(oaggs, onaggs * sizeof (*aggs));
11450 state->dts_aggregations = aggs;
11451 state->dts_naggregations = naggs;
11454 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
11455 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
11457 frec = &agg->dtag_first->dta_rec;
11458 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
11459 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
11461 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
11462 ASSERT(!act->dta_intuple);
11463 act->dta_intuple = 1;
11466 return (&agg->dtag_action);
11470 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
11472 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
11473 dtrace_state_t *state = ecb->dte_state;
11474 dtrace_aggid_t aggid = agg->dtag_id;
11476 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
11478 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
11480 free_unr(state->dts_aggid_arena, aggid);
11483 ASSERT(state->dts_aggregations[aggid - 1] == agg);
11484 state->dts_aggregations[aggid - 1] = NULL;
11486 kmem_free(agg, sizeof (dtrace_aggregation_t));
11490 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
11492 dtrace_action_t *action, *last;
11493 dtrace_difo_t *dp = desc->dtad_difo;
11494 uint32_t size = 0, align = sizeof (uint8_t), mask;
11495 uint16_t format = 0;
11496 dtrace_recdesc_t *rec;
11497 dtrace_state_t *state = ecb->dte_state;
11498 dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
11499 uint64_t arg = desc->dtad_arg;
11501 ASSERT(MUTEX_HELD(&dtrace_lock));
11502 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
11504 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
11506 * If this is an aggregating action, there must be neither
11507 * a speculate nor a commit on the action chain.
11509 dtrace_action_t *act;
11511 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
11512 if (act->dta_kind == DTRACEACT_COMMIT)
11515 if (act->dta_kind == DTRACEACT_SPECULATE)
11519 action = dtrace_ecb_aggregation_create(ecb, desc);
11521 if (action == NULL)
11524 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
11525 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11526 dp != NULL && dp->dtdo_destructive)) {
11527 state->dts_destructive = 1;
11530 switch (desc->dtad_kind) {
11531 case DTRACEACT_PRINTF:
11532 case DTRACEACT_PRINTA:
11533 case DTRACEACT_SYSTEM:
11534 case DTRACEACT_FREOPEN:
11535 case DTRACEACT_DIFEXPR:
11537 * We know that our arg is a string -- turn it into a
11541 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11542 desc->dtad_kind == DTRACEACT_DIFEXPR);
11547 ASSERT(arg > KERNELBASE);
11549 format = dtrace_format_add(state,
11550 (char *)(uintptr_t)arg);
11554 case DTRACEACT_LIBACT:
11555 case DTRACEACT_TRACEMEM:
11556 case DTRACEACT_TRACEMEM_DYNSIZE:
11560 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11563 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11564 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11567 size = opt[DTRACEOPT_STRSIZE];
11572 case DTRACEACT_STACK:
11573 if ((nframes = arg) == 0) {
11574 nframes = opt[DTRACEOPT_STACKFRAMES];
11575 ASSERT(nframes > 0);
11579 size = nframes * sizeof (pc_t);
11582 case DTRACEACT_JSTACK:
11583 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11584 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11586 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11587 nframes = opt[DTRACEOPT_JSTACKFRAMES];
11589 arg = DTRACE_USTACK_ARG(nframes, strsize);
11592 case DTRACEACT_USTACK:
11593 if (desc->dtad_kind != DTRACEACT_JSTACK &&
11594 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11595 strsize = DTRACE_USTACK_STRSIZE(arg);
11596 nframes = opt[DTRACEOPT_USTACKFRAMES];
11597 ASSERT(nframes > 0);
11598 arg = DTRACE_USTACK_ARG(nframes, strsize);
11602 * Save a slot for the pid.
11604 size = (nframes + 1) * sizeof (uint64_t);
11605 size += DTRACE_USTACK_STRSIZE(arg);
11606 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11610 case DTRACEACT_SYM:
11611 case DTRACEACT_MOD:
11612 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11613 sizeof (uint64_t)) ||
11614 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11618 case DTRACEACT_USYM:
11619 case DTRACEACT_UMOD:
11620 case DTRACEACT_UADDR:
11622 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11623 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11627 * We have a slot for the pid, plus a slot for the
11628 * argument. To keep things simple (aligned with
11629 * bitness-neutral sizing), we store each as a 64-bit
11632 size = 2 * sizeof (uint64_t);
11635 case DTRACEACT_STOP:
11636 case DTRACEACT_BREAKPOINT:
11637 case DTRACEACT_PANIC:
11640 case DTRACEACT_CHILL:
11641 case DTRACEACT_DISCARD:
11642 case DTRACEACT_RAISE:
11647 case DTRACEACT_EXIT:
11649 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11650 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11654 case DTRACEACT_SPECULATE:
11655 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11661 state->dts_speculates = 1;
11664 case DTRACEACT_PRINTM:
11665 size = dp->dtdo_rtype.dtdt_size;
11668 case DTRACEACT_COMMIT: {
11669 dtrace_action_t *act = ecb->dte_action;
11671 for (; act != NULL; act = act->dta_next) {
11672 if (act->dta_kind == DTRACEACT_COMMIT)
11685 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11687 * If this is a data-storing action or a speculate,
11688 * we must be sure that there isn't a commit on the
11691 dtrace_action_t *act = ecb->dte_action;
11693 for (; act != NULL; act = act->dta_next) {
11694 if (act->dta_kind == DTRACEACT_COMMIT)
11699 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11700 action->dta_rec.dtrd_size = size;
11703 action->dta_refcnt = 1;
11704 rec = &action->dta_rec;
11705 size = rec->dtrd_size;
11707 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11708 if (!(size & mask)) {
11714 action->dta_kind = desc->dtad_kind;
11716 if ((action->dta_difo = dp) != NULL)
11717 dtrace_difo_hold(dp);
11719 rec->dtrd_action = action->dta_kind;
11720 rec->dtrd_arg = arg;
11721 rec->dtrd_uarg = desc->dtad_uarg;
11722 rec->dtrd_alignment = (uint16_t)align;
11723 rec->dtrd_format = format;
11725 if ((last = ecb->dte_action_last) != NULL) {
11726 ASSERT(ecb->dte_action != NULL);
11727 action->dta_prev = last;
11728 last->dta_next = action;
11730 ASSERT(ecb->dte_action == NULL);
11731 ecb->dte_action = action;
11734 ecb->dte_action_last = action;
11740 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11742 dtrace_action_t *act = ecb->dte_action, *next;
11743 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11747 if (act != NULL && act->dta_refcnt > 1) {
11748 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11751 for (; act != NULL; act = next) {
11752 next = act->dta_next;
11753 ASSERT(next != NULL || act == ecb->dte_action_last);
11754 ASSERT(act->dta_refcnt == 1);
11756 if ((format = act->dta_rec.dtrd_format) != 0)
11757 dtrace_format_remove(ecb->dte_state, format);
11759 if ((dp = act->dta_difo) != NULL)
11760 dtrace_difo_release(dp, vstate);
11762 if (DTRACEACT_ISAGG(act->dta_kind)) {
11763 dtrace_ecb_aggregation_destroy(ecb, act);
11765 kmem_free(act, sizeof (dtrace_action_t));
11770 ecb->dte_action = NULL;
11771 ecb->dte_action_last = NULL;
11776 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11779 * We disable the ECB by removing it from its probe.
11781 dtrace_ecb_t *pecb, *prev = NULL;
11782 dtrace_probe_t *probe = ecb->dte_probe;
11784 ASSERT(MUTEX_HELD(&dtrace_lock));
11786 if (probe == NULL) {
11788 * This is the NULL probe; there is nothing to disable.
11793 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11799 ASSERT(pecb != NULL);
11801 if (prev == NULL) {
11802 probe->dtpr_ecb = ecb->dte_next;
11804 prev->dte_next = ecb->dte_next;
11807 if (ecb == probe->dtpr_ecb_last) {
11808 ASSERT(ecb->dte_next == NULL);
11809 probe->dtpr_ecb_last = prev;
11813 * The ECB has been disconnected from the probe; now sync to assure
11814 * that all CPUs have seen the change before returning.
11818 if (probe->dtpr_ecb == NULL) {
11820 * That was the last ECB on the probe; clear the predicate
11821 * cache ID for the probe, disable it and sync one more time
11822 * to assure that we'll never hit it again.
11824 dtrace_provider_t *prov = probe->dtpr_provider;
11826 ASSERT(ecb->dte_next == NULL);
11827 ASSERT(probe->dtpr_ecb_last == NULL);
11828 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11829 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11830 probe->dtpr_id, probe->dtpr_arg);
11834 * There is at least one ECB remaining on the probe. If there
11835 * is _exactly_ one, set the probe's predicate cache ID to be
11836 * the predicate cache ID of the remaining ECB.
11838 ASSERT(probe->dtpr_ecb_last != NULL);
11839 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11841 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11842 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11844 ASSERT(probe->dtpr_ecb->dte_next == NULL);
11847 probe->dtpr_predcache = p->dtp_cacheid;
11850 ecb->dte_next = NULL;
11855 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11857 dtrace_state_t *state = ecb->dte_state;
11858 dtrace_vstate_t *vstate = &state->dts_vstate;
11859 dtrace_predicate_t *pred;
11860 dtrace_epid_t epid = ecb->dte_epid;
11862 ASSERT(MUTEX_HELD(&dtrace_lock));
11863 ASSERT(ecb->dte_next == NULL);
11864 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11866 if ((pred = ecb->dte_predicate) != NULL)
11867 dtrace_predicate_release(pred, vstate);
11869 dtrace_ecb_action_remove(ecb);
11871 ASSERT(state->dts_ecbs[epid - 1] == ecb);
11872 state->dts_ecbs[epid - 1] = NULL;
11874 kmem_free(ecb, sizeof (dtrace_ecb_t));
11877 static dtrace_ecb_t *
11878 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11879 dtrace_enabling_t *enab)
11882 dtrace_predicate_t *pred;
11883 dtrace_actdesc_t *act;
11884 dtrace_provider_t *prov;
11885 dtrace_ecbdesc_t *desc = enab->dten_current;
11887 ASSERT(MUTEX_HELD(&dtrace_lock));
11888 ASSERT(state != NULL);
11890 ecb = dtrace_ecb_add(state, probe);
11891 ecb->dte_uarg = desc->dted_uarg;
11893 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11894 dtrace_predicate_hold(pred);
11895 ecb->dte_predicate = pred;
11898 if (probe != NULL) {
11900 * If the provider shows more leg than the consumer is old
11901 * enough to see, we need to enable the appropriate implicit
11902 * predicate bits to prevent the ecb from activating at
11905 * Providers specifying DTRACE_PRIV_USER at register time
11906 * are stating that they need the /proc-style privilege
11907 * model to be enforced, and this is what DTRACE_COND_OWNER
11908 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11910 prov = probe->dtpr_provider;
11911 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11912 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11913 ecb->dte_cond |= DTRACE_COND_OWNER;
11915 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11916 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11917 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11920 * If the provider shows us kernel innards and the user
11921 * is lacking sufficient privilege, enable the
11922 * DTRACE_COND_USERMODE implicit predicate.
11924 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11925 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11926 ecb->dte_cond |= DTRACE_COND_USERMODE;
11929 if (dtrace_ecb_create_cache != NULL) {
11931 * If we have a cached ecb, we'll use its action list instead
11932 * of creating our own (saving both time and space).
11934 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11935 dtrace_action_t *act = cached->dte_action;
11938 ASSERT(act->dta_refcnt > 0);
11940 ecb->dte_action = act;
11941 ecb->dte_action_last = cached->dte_action_last;
11942 ecb->dte_needed = cached->dte_needed;
11943 ecb->dte_size = cached->dte_size;
11944 ecb->dte_alignment = cached->dte_alignment;
11950 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11951 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11952 dtrace_ecb_destroy(ecb);
11957 if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11958 dtrace_ecb_destroy(ecb);
11962 return (dtrace_ecb_create_cache = ecb);
11966 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11969 dtrace_enabling_t *enab = arg;
11970 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11972 ASSERT(state != NULL);
11974 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11976 * This probe was created in a generation for which this
11977 * enabling has previously created ECBs; we don't want to
11978 * enable it again, so just kick out.
11980 return (DTRACE_MATCH_NEXT);
11983 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11984 return (DTRACE_MATCH_DONE);
11986 dtrace_ecb_enable(ecb);
11987 return (DTRACE_MATCH_NEXT);
11990 static dtrace_ecb_t *
11991 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11995 ASSERT(MUTEX_HELD(&dtrace_lock));
11997 if (id == 0 || id > state->dts_necbs)
12000 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
12001 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
12003 return (state->dts_ecbs[id - 1]);
12006 static dtrace_aggregation_t *
12007 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
12009 dtrace_aggregation_t *agg;
12011 ASSERT(MUTEX_HELD(&dtrace_lock));
12013 if (id == 0 || id > state->dts_naggregations)
12016 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
12017 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
12018 agg->dtag_id == id);
12020 return (state->dts_aggregations[id - 1]);
12024 * DTrace Buffer Functions
12026 * The following functions manipulate DTrace buffers. Most of these functions
12027 * are called in the context of establishing or processing consumer state;
12028 * exceptions are explicitly noted.
12032 * Note: called from cross call context. This function switches the two
12033 * buffers on a given CPU. The atomicity of this operation is assured by
12034 * disabling interrupts while the actual switch takes place; the disabling of
12035 * interrupts serializes the execution with any execution of dtrace_probe() on
12039 dtrace_buffer_switch(dtrace_buffer_t *buf)
12041 caddr_t tomax = buf->dtb_tomax;
12042 caddr_t xamot = buf->dtb_xamot;
12043 dtrace_icookie_t cookie;
12046 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12047 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
12049 cookie = dtrace_interrupt_disable();
12050 now = dtrace_gethrtime();
12051 buf->dtb_tomax = xamot;
12052 buf->dtb_xamot = tomax;
12053 buf->dtb_xamot_drops = buf->dtb_drops;
12054 buf->dtb_xamot_offset = buf->dtb_offset;
12055 buf->dtb_xamot_errors = buf->dtb_errors;
12056 buf->dtb_xamot_flags = buf->dtb_flags;
12057 buf->dtb_offset = 0;
12058 buf->dtb_drops = 0;
12059 buf->dtb_errors = 0;
12060 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
12061 buf->dtb_interval = now - buf->dtb_switched;
12062 buf->dtb_switched = now;
12063 dtrace_interrupt_enable(cookie);
12067 * Note: called from cross call context. This function activates a buffer
12068 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
12069 * is guaranteed by the disabling of interrupts.
12072 dtrace_buffer_activate(dtrace_state_t *state)
12074 dtrace_buffer_t *buf;
12075 dtrace_icookie_t cookie = dtrace_interrupt_disable();
12077 buf = &state->dts_buffer[curcpu];
12079 if (buf->dtb_tomax != NULL) {
12081 * We might like to assert that the buffer is marked inactive,
12082 * but this isn't necessarily true: the buffer for the CPU
12083 * that processes the BEGIN probe has its buffer activated
12084 * manually. In this case, we take the (harmless) action
12085 * re-clearing the bit INACTIVE bit.
12087 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
12090 dtrace_interrupt_enable(cookie);
12095 * Activate the specified per-CPU buffer. This is used instead of
12096 * dtrace_buffer_activate() when APs have not yet started, i.e. when
12097 * activating anonymous state.
12100 dtrace_buffer_activate_cpu(dtrace_state_t *state, int cpu)
12103 if (state->dts_buffer[cpu].dtb_tomax != NULL)
12104 state->dts_buffer[cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12109 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
12110 processorid_t cpu, int *factor)
12115 dtrace_buffer_t *buf;
12116 int allocated = 0, desired = 0;
12119 ASSERT(MUTEX_HELD(&cpu_lock));
12120 ASSERT(MUTEX_HELD(&dtrace_lock));
12124 if (size > dtrace_nonroot_maxsize &&
12125 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
12131 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12134 buf = &bufs[cp->cpu_id];
12137 * If there is already a buffer allocated for this CPU, it
12138 * is only possible that this is a DR event. In this case,
12140 if (buf->dtb_tomax != NULL) {
12141 ASSERT(buf->dtb_size == size);
12145 ASSERT(buf->dtb_xamot == NULL);
12147 if ((buf->dtb_tomax = kmem_zalloc(size,
12148 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12151 buf->dtb_size = size;
12152 buf->dtb_flags = flags;
12153 buf->dtb_offset = 0;
12154 buf->dtb_drops = 0;
12156 if (flags & DTRACEBUF_NOSWITCH)
12159 if ((buf->dtb_xamot = kmem_zalloc(size,
12160 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12162 } while ((cp = cp->cpu_next) != cpu_list);
12170 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
12173 buf = &bufs[cp->cpu_id];
12176 if (buf->dtb_xamot != NULL) {
12177 ASSERT(buf->dtb_tomax != NULL);
12178 ASSERT(buf->dtb_size == size);
12179 kmem_free(buf->dtb_xamot, size);
12183 if (buf->dtb_tomax != NULL) {
12184 ASSERT(buf->dtb_size == size);
12185 kmem_free(buf->dtb_tomax, size);
12189 buf->dtb_tomax = NULL;
12190 buf->dtb_xamot = NULL;
12192 } while ((cp = cp->cpu_next) != cpu_list);
12197 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
12198 defined(__mips__) || defined(__powerpc__) || defined(__riscv)
12200 * FreeBSD isn't good at limiting the amount of memory we
12201 * ask to malloc, so let's place a limit here before trying
12202 * to do something that might well end in tears at bedtime.
12204 if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
12208 ASSERT(MUTEX_HELD(&dtrace_lock));
12210 if (cpu != DTRACE_CPUALL && cpu != i)
12216 * If there is already a buffer allocated for this CPU, it
12217 * is only possible that this is a DR event. In this case,
12218 * the buffer size must match our specified size.
12220 if (buf->dtb_tomax != NULL) {
12221 ASSERT(buf->dtb_size == size);
12225 ASSERT(buf->dtb_xamot == NULL);
12227 if ((buf->dtb_tomax = kmem_zalloc(size,
12228 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12231 buf->dtb_size = size;
12232 buf->dtb_flags = flags;
12233 buf->dtb_offset = 0;
12234 buf->dtb_drops = 0;
12236 if (flags & DTRACEBUF_NOSWITCH)
12239 if ((buf->dtb_xamot = kmem_zalloc(size,
12240 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12248 * Error allocating memory, so free the buffers that were
12249 * allocated before the failed allocation.
12252 if (cpu != DTRACE_CPUALL && cpu != i)
12258 if (buf->dtb_xamot != NULL) {
12259 ASSERT(buf->dtb_tomax != NULL);
12260 ASSERT(buf->dtb_size == size);
12261 kmem_free(buf->dtb_xamot, size);
12265 if (buf->dtb_tomax != NULL) {
12266 ASSERT(buf->dtb_size == size);
12267 kmem_free(buf->dtb_tomax, size);
12271 buf->dtb_tomax = NULL;
12272 buf->dtb_xamot = NULL;
12277 *factor = desired / (allocated > 0 ? allocated : 1);
12283 * Note: called from probe context. This function just increments the drop
12284 * count on a buffer. It has been made a function to allow for the
12285 * possibility of understanding the source of mysterious drop counts. (A
12286 * problem for which one may be particularly disappointed that DTrace cannot
12287 * be used to understand DTrace.)
12290 dtrace_buffer_drop(dtrace_buffer_t *buf)
12296 * Note: called from probe context. This function is called to reserve space
12297 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
12298 * mstate. Returns the new offset in the buffer, or a negative value if an
12299 * error has occurred.
12302 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
12303 dtrace_state_t *state, dtrace_mstate_t *mstate)
12305 intptr_t offs = buf->dtb_offset, soffs;
12310 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
12313 if ((tomax = buf->dtb_tomax) == NULL) {
12314 dtrace_buffer_drop(buf);
12318 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
12319 while (offs & (align - 1)) {
12321 * Assert that our alignment is off by a number which
12322 * is itself sizeof (uint32_t) aligned.
12324 ASSERT(!((align - (offs & (align - 1))) &
12325 (sizeof (uint32_t) - 1)));
12326 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12327 offs += sizeof (uint32_t);
12330 if ((soffs = offs + needed) > buf->dtb_size) {
12331 dtrace_buffer_drop(buf);
12335 if (mstate == NULL)
12338 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
12339 mstate->dtms_scratch_size = buf->dtb_size - soffs;
12340 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12345 if (buf->dtb_flags & DTRACEBUF_FILL) {
12346 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
12347 (buf->dtb_flags & DTRACEBUF_FULL))
12352 total = needed + (offs & (align - 1));
12355 * For a ring buffer, life is quite a bit more complicated. Before
12356 * we can store any padding, we need to adjust our wrapping offset.
12357 * (If we've never before wrapped or we're not about to, no adjustment
12360 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
12361 offs + total > buf->dtb_size) {
12362 woffs = buf->dtb_xamot_offset;
12364 if (offs + total > buf->dtb_size) {
12366 * We can't fit in the end of the buffer. First, a
12367 * sanity check that we can fit in the buffer at all.
12369 if (total > buf->dtb_size) {
12370 dtrace_buffer_drop(buf);
12375 * We're going to be storing at the top of the buffer,
12376 * so now we need to deal with the wrapped offset. We
12377 * only reset our wrapped offset to 0 if it is
12378 * currently greater than the current offset. If it
12379 * is less than the current offset, it is because a
12380 * previous allocation induced a wrap -- but the
12381 * allocation didn't subsequently take the space due
12382 * to an error or false predicate evaluation. In this
12383 * case, we'll just leave the wrapped offset alone: if
12384 * the wrapped offset hasn't been advanced far enough
12385 * for this allocation, it will be adjusted in the
12388 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
12396 * Now we know that we're going to be storing to the
12397 * top of the buffer and that there is room for us
12398 * there. We need to clear the buffer from the current
12399 * offset to the end (there may be old gunk there).
12401 while (offs < buf->dtb_size)
12405 * We need to set our offset to zero. And because we
12406 * are wrapping, we need to set the bit indicating as
12407 * much. We can also adjust our needed space back
12408 * down to the space required by the ECB -- we know
12409 * that the top of the buffer is aligned.
12413 buf->dtb_flags |= DTRACEBUF_WRAPPED;
12416 * There is room for us in the buffer, so we simply
12417 * need to check the wrapped offset.
12419 if (woffs < offs) {
12421 * The wrapped offset is less than the offset.
12422 * This can happen if we allocated buffer space
12423 * that induced a wrap, but then we didn't
12424 * subsequently take the space due to an error
12425 * or false predicate evaluation. This is
12426 * okay; we know that _this_ allocation isn't
12427 * going to induce a wrap. We still can't
12428 * reset the wrapped offset to be zero,
12429 * however: the space may have been trashed in
12430 * the previous failed probe attempt. But at
12431 * least the wrapped offset doesn't need to
12432 * be adjusted at all...
12438 while (offs + total > woffs) {
12439 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
12442 if (epid == DTRACE_EPIDNONE) {
12443 size = sizeof (uint32_t);
12445 ASSERT3U(epid, <=, state->dts_necbs);
12446 ASSERT(state->dts_ecbs[epid - 1] != NULL);
12448 size = state->dts_ecbs[epid - 1]->dte_size;
12451 ASSERT(woffs + size <= buf->dtb_size);
12454 if (woffs + size == buf->dtb_size) {
12456 * We've reached the end of the buffer; we want
12457 * to set the wrapped offset to 0 and break
12458 * out. However, if the offs is 0, then we're
12459 * in a strange edge-condition: the amount of
12460 * space that we want to reserve plus the size
12461 * of the record that we're overwriting is
12462 * greater than the size of the buffer. This
12463 * is problematic because if we reserve the
12464 * space but subsequently don't consume it (due
12465 * to a failed predicate or error) the wrapped
12466 * offset will be 0 -- yet the EPID at offset 0
12467 * will not be committed. This situation is
12468 * relatively easy to deal with: if we're in
12469 * this case, the buffer is indistinguishable
12470 * from one that hasn't wrapped; we need only
12471 * finish the job by clearing the wrapped bit,
12472 * explicitly setting the offset to be 0, and
12473 * zero'ing out the old data in the buffer.
12476 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
12477 buf->dtb_offset = 0;
12480 while (woffs < buf->dtb_size)
12481 tomax[woffs++] = 0;
12492 * We have a wrapped offset. It may be that the wrapped offset
12493 * has become zero -- that's okay.
12495 buf->dtb_xamot_offset = woffs;
12500 * Now we can plow the buffer with any necessary padding.
12502 while (offs & (align - 1)) {
12504 * Assert that our alignment is off by a number which
12505 * is itself sizeof (uint32_t) aligned.
12507 ASSERT(!((align - (offs & (align - 1))) &
12508 (sizeof (uint32_t) - 1)));
12509 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
12510 offs += sizeof (uint32_t);
12513 if (buf->dtb_flags & DTRACEBUF_FILL) {
12514 if (offs + needed > buf->dtb_size - state->dts_reserve) {
12515 buf->dtb_flags |= DTRACEBUF_FULL;
12520 if (mstate == NULL)
12524 * For ring buffers and fill buffers, the scratch space is always
12525 * the inactive buffer.
12527 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
12528 mstate->dtms_scratch_size = buf->dtb_size;
12529 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
12535 dtrace_buffer_polish(dtrace_buffer_t *buf)
12537 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
12538 ASSERT(MUTEX_HELD(&dtrace_lock));
12540 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
12544 * We need to polish the ring buffer. There are three cases:
12546 * - The first (and presumably most common) is that there is no gap
12547 * between the buffer offset and the wrapped offset. In this case,
12548 * there is nothing in the buffer that isn't valid data; we can
12549 * mark the buffer as polished and return.
12551 * - The second (less common than the first but still more common
12552 * than the third) is that there is a gap between the buffer offset
12553 * and the wrapped offset, and the wrapped offset is larger than the
12554 * buffer offset. This can happen because of an alignment issue, or
12555 * can happen because of a call to dtrace_buffer_reserve() that
12556 * didn't subsequently consume the buffer space. In this case,
12557 * we need to zero the data from the buffer offset to the wrapped
12560 * - The third (and least common) is that there is a gap between the
12561 * buffer offset and the wrapped offset, but the wrapped offset is
12562 * _less_ than the buffer offset. This can only happen because a
12563 * call to dtrace_buffer_reserve() induced a wrap, but the space
12564 * was not subsequently consumed. In this case, we need to zero the
12565 * space from the offset to the end of the buffer _and_ from the
12566 * top of the buffer to the wrapped offset.
12568 if (buf->dtb_offset < buf->dtb_xamot_offset) {
12569 bzero(buf->dtb_tomax + buf->dtb_offset,
12570 buf->dtb_xamot_offset - buf->dtb_offset);
12573 if (buf->dtb_offset > buf->dtb_xamot_offset) {
12574 bzero(buf->dtb_tomax + buf->dtb_offset,
12575 buf->dtb_size - buf->dtb_offset);
12576 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
12581 * This routine determines if data generated at the specified time has likely
12582 * been entirely consumed at user-level. This routine is called to determine
12583 * if an ECB on a defunct probe (but for an active enabling) can be safely
12584 * disabled and destroyed.
12587 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
12591 for (i = 0; i < NCPU; i++) {
12592 dtrace_buffer_t *buf = &bufs[i];
12594 if (buf->dtb_size == 0)
12597 if (buf->dtb_flags & DTRACEBUF_RING)
12600 if (!buf->dtb_switched && buf->dtb_offset != 0)
12603 if (buf->dtb_switched - buf->dtb_interval < when)
12611 dtrace_buffer_free(dtrace_buffer_t *bufs)
12615 for (i = 0; i < NCPU; i++) {
12616 dtrace_buffer_t *buf = &bufs[i];
12618 if (buf->dtb_tomax == NULL) {
12619 ASSERT(buf->dtb_xamot == NULL);
12620 ASSERT(buf->dtb_size == 0);
12624 if (buf->dtb_xamot != NULL) {
12625 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
12626 kmem_free(buf->dtb_xamot, buf->dtb_size);
12629 kmem_free(buf->dtb_tomax, buf->dtb_size);
12631 buf->dtb_tomax = NULL;
12632 buf->dtb_xamot = NULL;
12637 * DTrace Enabling Functions
12639 static dtrace_enabling_t *
12640 dtrace_enabling_create(dtrace_vstate_t *vstate)
12642 dtrace_enabling_t *enab;
12644 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12645 enab->dten_vstate = vstate;
12651 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12653 dtrace_ecbdesc_t **ndesc;
12654 size_t osize, nsize;
12657 * We can't add to enablings after we've enabled them, or after we've
12660 ASSERT(enab->dten_probegen == 0);
12661 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12663 if (enab->dten_ndesc < enab->dten_maxdesc) {
12664 enab->dten_desc[enab->dten_ndesc++] = ecb;
12668 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12670 if (enab->dten_maxdesc == 0) {
12671 enab->dten_maxdesc = 1;
12673 enab->dten_maxdesc <<= 1;
12676 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12678 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12679 ndesc = kmem_zalloc(nsize, KM_SLEEP);
12680 bcopy(enab->dten_desc, ndesc, osize);
12681 if (enab->dten_desc != NULL)
12682 kmem_free(enab->dten_desc, osize);
12684 enab->dten_desc = ndesc;
12685 enab->dten_desc[enab->dten_ndesc++] = ecb;
12689 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12690 dtrace_probedesc_t *pd)
12692 dtrace_ecbdesc_t *new;
12693 dtrace_predicate_t *pred;
12694 dtrace_actdesc_t *act;
12697 * We're going to create a new ECB description that matches the
12698 * specified ECB in every way, but has the specified probe description.
12700 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12702 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12703 dtrace_predicate_hold(pred);
12705 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12706 dtrace_actdesc_hold(act);
12708 new->dted_action = ecb->dted_action;
12709 new->dted_pred = ecb->dted_pred;
12710 new->dted_probe = *pd;
12711 new->dted_uarg = ecb->dted_uarg;
12713 dtrace_enabling_add(enab, new);
12717 dtrace_enabling_dump(dtrace_enabling_t *enab)
12721 for (i = 0; i < enab->dten_ndesc; i++) {
12722 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12725 printf("dtrace: enabling probe %d (%s:%s:%s:%s)\n", i,
12726 desc->dtpd_provider, desc->dtpd_mod,
12727 desc->dtpd_func, desc->dtpd_name);
12729 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12730 desc->dtpd_provider, desc->dtpd_mod,
12731 desc->dtpd_func, desc->dtpd_name);
12737 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12740 dtrace_ecbdesc_t *ep;
12741 dtrace_vstate_t *vstate = enab->dten_vstate;
12743 ASSERT(MUTEX_HELD(&dtrace_lock));
12745 for (i = 0; i < enab->dten_ndesc; i++) {
12746 dtrace_actdesc_t *act, *next;
12747 dtrace_predicate_t *pred;
12749 ep = enab->dten_desc[i];
12751 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12752 dtrace_predicate_release(pred, vstate);
12754 for (act = ep->dted_action; act != NULL; act = next) {
12755 next = act->dtad_next;
12756 dtrace_actdesc_release(act, vstate);
12759 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12762 if (enab->dten_desc != NULL)
12763 kmem_free(enab->dten_desc,
12764 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12767 * If this was a retained enabling, decrement the dts_nretained count
12768 * and take it off of the dtrace_retained list.
12770 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12771 dtrace_retained == enab) {
12772 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12773 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12774 enab->dten_vstate->dtvs_state->dts_nretained--;
12775 dtrace_retained_gen++;
12778 if (enab->dten_prev == NULL) {
12779 if (dtrace_retained == enab) {
12780 dtrace_retained = enab->dten_next;
12782 if (dtrace_retained != NULL)
12783 dtrace_retained->dten_prev = NULL;
12786 ASSERT(enab != dtrace_retained);
12787 ASSERT(dtrace_retained != NULL);
12788 enab->dten_prev->dten_next = enab->dten_next;
12791 if (enab->dten_next != NULL) {
12792 ASSERT(dtrace_retained != NULL);
12793 enab->dten_next->dten_prev = enab->dten_prev;
12796 kmem_free(enab, sizeof (dtrace_enabling_t));
12800 dtrace_enabling_retain(dtrace_enabling_t *enab)
12802 dtrace_state_t *state;
12804 ASSERT(MUTEX_HELD(&dtrace_lock));
12805 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12806 ASSERT(enab->dten_vstate != NULL);
12808 state = enab->dten_vstate->dtvs_state;
12809 ASSERT(state != NULL);
12812 * We only allow each state to retain dtrace_retain_max enablings.
12814 if (state->dts_nretained >= dtrace_retain_max)
12817 state->dts_nretained++;
12818 dtrace_retained_gen++;
12820 if (dtrace_retained == NULL) {
12821 dtrace_retained = enab;
12825 enab->dten_next = dtrace_retained;
12826 dtrace_retained->dten_prev = enab;
12827 dtrace_retained = enab;
12833 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12834 dtrace_probedesc_t *create)
12836 dtrace_enabling_t *new, *enab;
12837 int found = 0, err = ENOENT;
12839 ASSERT(MUTEX_HELD(&dtrace_lock));
12840 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12841 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12842 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12843 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12845 new = dtrace_enabling_create(&state->dts_vstate);
12848 * Iterate over all retained enablings, looking for enablings that
12849 * match the specified state.
12851 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12855 * dtvs_state can only be NULL for helper enablings -- and
12856 * helper enablings can't be retained.
12858 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12860 if (enab->dten_vstate->dtvs_state != state)
12864 * Now iterate over each probe description; we're looking for
12865 * an exact match to the specified probe description.
12867 for (i = 0; i < enab->dten_ndesc; i++) {
12868 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12869 dtrace_probedesc_t *pd = &ep->dted_probe;
12871 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12874 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12877 if (strcmp(pd->dtpd_func, match->dtpd_func))
12880 if (strcmp(pd->dtpd_name, match->dtpd_name))
12884 * We have a winning probe! Add it to our growing
12888 dtrace_enabling_addlike(new, ep, create);
12892 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12893 dtrace_enabling_destroy(new);
12901 dtrace_enabling_retract(dtrace_state_t *state)
12903 dtrace_enabling_t *enab, *next;
12905 ASSERT(MUTEX_HELD(&dtrace_lock));
12908 * Iterate over all retained enablings, destroy the enablings retained
12909 * for the specified state.
12911 for (enab = dtrace_retained; enab != NULL; enab = next) {
12912 next = enab->dten_next;
12915 * dtvs_state can only be NULL for helper enablings -- and
12916 * helper enablings can't be retained.
12918 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12920 if (enab->dten_vstate->dtvs_state == state) {
12921 ASSERT(state->dts_nretained > 0);
12922 dtrace_enabling_destroy(enab);
12926 ASSERT(state->dts_nretained == 0);
12930 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12935 ASSERT(MUTEX_HELD(&cpu_lock));
12936 ASSERT(MUTEX_HELD(&dtrace_lock));
12938 for (i = 0; i < enab->dten_ndesc; i++) {
12939 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12941 enab->dten_current = ep;
12942 enab->dten_error = 0;
12944 matched += dtrace_probe_enable(&ep->dted_probe, enab);
12946 if (enab->dten_error != 0) {
12948 * If we get an error half-way through enabling the
12949 * probes, we kick out -- perhaps with some number of
12950 * them enabled. Leaving enabled probes enabled may
12951 * be slightly confusing for user-level, but we expect
12952 * that no one will attempt to actually drive on in
12953 * the face of such errors. If this is an anonymous
12954 * enabling (indicated with a NULL nmatched pointer),
12955 * we cmn_err() a message. We aren't expecting to
12956 * get such an error -- such as it can exist at all,
12957 * it would be a result of corrupted DOF in the driver
12960 if (nmatched == NULL) {
12961 cmn_err(CE_WARN, "dtrace_enabling_match() "
12962 "error on %p: %d", (void *)ep,
12966 return (enab->dten_error);
12970 enab->dten_probegen = dtrace_probegen;
12971 if (nmatched != NULL)
12972 *nmatched = matched;
12978 dtrace_enabling_matchall(void)
12980 dtrace_enabling_t *enab;
12982 mutex_enter(&cpu_lock);
12983 mutex_enter(&dtrace_lock);
12986 * Iterate over all retained enablings to see if any probes match
12987 * against them. We only perform this operation on enablings for which
12988 * we have sufficient permissions by virtue of being in the global zone
12989 * or in the same zone as the DTrace client. Because we can be called
12990 * after dtrace_detach() has been called, we cannot assert that there
12991 * are retained enablings. We can safely load from dtrace_retained,
12992 * however: the taskq_destroy() at the end of dtrace_detach() will
12993 * block pending our completion.
12995 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12997 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12999 if (INGLOBALZONE(curproc) ||
13000 cr != NULL && getzoneid() == crgetzoneid(cr))
13002 (void) dtrace_enabling_match(enab, NULL);
13005 mutex_exit(&dtrace_lock);
13006 mutex_exit(&cpu_lock);
13010 * If an enabling is to be enabled without having matched probes (that is, if
13011 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
13012 * enabling must be _primed_ by creating an ECB for every ECB description.
13013 * This must be done to assure that we know the number of speculations, the
13014 * number of aggregations, the minimum buffer size needed, etc. before we
13015 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
13016 * enabling any probes, we create ECBs for every ECB decription, but with a
13017 * NULL probe -- which is exactly what this function does.
13020 dtrace_enabling_prime(dtrace_state_t *state)
13022 dtrace_enabling_t *enab;
13025 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
13026 ASSERT(enab->dten_vstate->dtvs_state != NULL);
13028 if (enab->dten_vstate->dtvs_state != state)
13032 * We don't want to prime an enabling more than once, lest
13033 * we allow a malicious user to induce resource exhaustion.
13034 * (The ECBs that result from priming an enabling aren't
13035 * leaked -- but they also aren't deallocated until the
13036 * consumer state is destroyed.)
13038 if (enab->dten_primed)
13041 for (i = 0; i < enab->dten_ndesc; i++) {
13042 enab->dten_current = enab->dten_desc[i];
13043 (void) dtrace_probe_enable(NULL, enab);
13046 enab->dten_primed = 1;
13051 * Called to indicate that probes should be provided due to retained
13052 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
13053 * must take an initial lap through the enabling calling the dtps_provide()
13054 * entry point explicitly to allow for autocreated probes.
13057 dtrace_enabling_provide(dtrace_provider_t *prv)
13060 dtrace_probedesc_t desc;
13061 dtrace_genid_t gen;
13063 ASSERT(MUTEX_HELD(&dtrace_lock));
13064 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
13068 prv = dtrace_provider;
13072 dtrace_enabling_t *enab;
13073 void *parg = prv->dtpv_arg;
13076 gen = dtrace_retained_gen;
13077 for (enab = dtrace_retained; enab != NULL;
13078 enab = enab->dten_next) {
13079 for (i = 0; i < enab->dten_ndesc; i++) {
13080 desc = enab->dten_desc[i]->dted_probe;
13081 mutex_exit(&dtrace_lock);
13082 prv->dtpv_pops.dtps_provide(parg, &desc);
13083 mutex_enter(&dtrace_lock);
13085 * Process the retained enablings again if
13086 * they have changed while we weren't holding
13089 if (gen != dtrace_retained_gen)
13093 } while (all && (prv = prv->dtpv_next) != NULL);
13095 mutex_exit(&dtrace_lock);
13096 dtrace_probe_provide(NULL, all ? NULL : prv);
13097 mutex_enter(&dtrace_lock);
13101 * Called to reap ECBs that are attached to probes from defunct providers.
13104 dtrace_enabling_reap(void)
13106 dtrace_provider_t *prov;
13107 dtrace_probe_t *probe;
13112 mutex_enter(&cpu_lock);
13113 mutex_enter(&dtrace_lock);
13115 for (i = 0; i < dtrace_nprobes; i++) {
13116 if ((probe = dtrace_probes[i]) == NULL)
13119 if (probe->dtpr_ecb == NULL)
13122 prov = probe->dtpr_provider;
13124 if ((when = prov->dtpv_defunct) == 0)
13128 * We have ECBs on a defunct provider: we want to reap these
13129 * ECBs to allow the provider to unregister. The destruction
13130 * of these ECBs must be done carefully: if we destroy the ECB
13131 * and the consumer later wishes to consume an EPID that
13132 * corresponds to the destroyed ECB (and if the EPID metadata
13133 * has not been previously consumed), the consumer will abort
13134 * processing on the unknown EPID. To reduce (but not, sadly,
13135 * eliminate) the possibility of this, we will only destroy an
13136 * ECB for a defunct provider if, for the state that
13137 * corresponds to the ECB:
13139 * (a) There is no speculative tracing (which can effectively
13140 * cache an EPID for an arbitrary amount of time).
13142 * (b) The principal buffers have been switched twice since the
13143 * provider became defunct.
13145 * (c) The aggregation buffers are of zero size or have been
13146 * switched twice since the provider became defunct.
13148 * We use dts_speculates to determine (a) and call a function
13149 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
13150 * that as soon as we've been unable to destroy one of the ECBs
13151 * associated with the probe, we quit trying -- reaping is only
13152 * fruitful in as much as we can destroy all ECBs associated
13153 * with the defunct provider's probes.
13155 while ((ecb = probe->dtpr_ecb) != NULL) {
13156 dtrace_state_t *state = ecb->dte_state;
13157 dtrace_buffer_t *buf = state->dts_buffer;
13158 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
13160 if (state->dts_speculates)
13163 if (!dtrace_buffer_consumed(buf, when))
13166 if (!dtrace_buffer_consumed(aggbuf, when))
13169 dtrace_ecb_disable(ecb);
13170 ASSERT(probe->dtpr_ecb != ecb);
13171 dtrace_ecb_destroy(ecb);
13175 mutex_exit(&dtrace_lock);
13176 mutex_exit(&cpu_lock);
13180 * DTrace DOF Functions
13184 dtrace_dof_error(dof_hdr_t *dof, const char *str)
13186 if (dtrace_err_verbose)
13187 cmn_err(CE_WARN, "failed to process DOF: %s", str);
13189 #ifdef DTRACE_ERRDEBUG
13190 dtrace_errdebug(str);
13195 * Create DOF out of a currently enabled state. Right now, we only create
13196 * DOF containing the run-time options -- but this could be expanded to create
13197 * complete DOF representing the enabled state.
13200 dtrace_dof_create(dtrace_state_t *state)
13204 dof_optdesc_t *opt;
13205 int i, len = sizeof (dof_hdr_t) +
13206 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
13207 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13209 ASSERT(MUTEX_HELD(&dtrace_lock));
13211 dof = kmem_zalloc(len, KM_SLEEP);
13212 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
13213 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
13214 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
13215 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
13217 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
13218 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
13219 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
13220 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
13221 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
13222 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
13224 dof->dofh_flags = 0;
13225 dof->dofh_hdrsize = sizeof (dof_hdr_t);
13226 dof->dofh_secsize = sizeof (dof_sec_t);
13227 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
13228 dof->dofh_secoff = sizeof (dof_hdr_t);
13229 dof->dofh_loadsz = len;
13230 dof->dofh_filesz = len;
13234 * Fill in the option section header...
13236 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
13237 sec->dofs_type = DOF_SECT_OPTDESC;
13238 sec->dofs_align = sizeof (uint64_t);
13239 sec->dofs_flags = DOF_SECF_LOAD;
13240 sec->dofs_entsize = sizeof (dof_optdesc_t);
13242 opt = (dof_optdesc_t *)((uintptr_t)sec +
13243 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
13245 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
13246 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
13248 for (i = 0; i < DTRACEOPT_MAX; i++) {
13249 opt[i].dofo_option = i;
13250 opt[i].dofo_strtab = DOF_SECIDX_NONE;
13251 opt[i].dofo_value = state->dts_options[i];
13258 dtrace_dof_copyin(uintptr_t uarg, int *errp)
13260 dof_hdr_t hdr, *dof;
13262 ASSERT(!MUTEX_HELD(&dtrace_lock));
13265 * First, we're going to copyin() the sizeof (dof_hdr_t).
13267 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
13268 dtrace_dof_error(NULL, "failed to copyin DOF header");
13274 * Now we'll allocate the entire DOF and copy it in -- provided
13275 * that the length isn't outrageous.
13277 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13278 dtrace_dof_error(&hdr, "load size exceeds maximum");
13283 if (hdr.dofh_loadsz < sizeof (hdr)) {
13284 dtrace_dof_error(&hdr, "invalid load size");
13289 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
13291 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
13292 dof->dofh_loadsz != hdr.dofh_loadsz) {
13293 kmem_free(dof, hdr.dofh_loadsz);
13303 dtrace_dof_copyin_proc(struct proc *p, uintptr_t uarg, int *errp)
13305 dof_hdr_t hdr, *dof;
13309 ASSERT(!MUTEX_HELD(&dtrace_lock));
13314 * First, we're going to copyin() the sizeof (dof_hdr_t).
13316 if (proc_readmem(td, p, uarg, &hdr, sizeof(hdr)) != sizeof(hdr)) {
13317 dtrace_dof_error(NULL, "failed to copyin DOF header");
13323 * Now we'll allocate the entire DOF and copy it in -- provided
13324 * that the length isn't outrageous.
13326 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
13327 dtrace_dof_error(&hdr, "load size exceeds maximum");
13331 loadsz = (size_t)hdr.dofh_loadsz;
13333 if (loadsz < sizeof (hdr)) {
13334 dtrace_dof_error(&hdr, "invalid load size");
13339 dof = kmem_alloc(loadsz, KM_SLEEP);
13341 if (proc_readmem(td, p, uarg, dof, loadsz) != loadsz ||
13342 dof->dofh_loadsz != loadsz) {
13343 kmem_free(dof, hdr.dofh_loadsz);
13351 static __inline uchar_t
13352 dtrace_dof_char(char c)
13373 return (c - 'A' + 10);
13380 return (c - 'a' + 10);
13382 /* Should not reach here. */
13383 return (UCHAR_MAX);
13385 #endif /* __FreeBSD__ */
13388 dtrace_dof_property(const char *name)
13392 u_char *data, *eol;
13394 size_t bytes, len, i;
13400 doffile = preload_search_by_type("dtrace_dof");
13401 if (doffile == NULL)
13404 data = preload_fetch_addr(doffile);
13405 len = preload_fetch_size(doffile);
13407 /* Look for the end of the line. All lines end in a newline. */
13408 eol = memchr(data, '\n', len);
13412 if (strncmp(name, data, strlen(name)) == 0)
13415 eol++; /* skip past the newline */
13420 /* We've found the data corresponding to the specified key. */
13422 data += strlen(name) + 1; /* skip past the '=' */
13424 if (len % 2 != 0) {
13425 dtrace_dof_error(NULL, "invalid DOF encoding length");
13429 if (bytes < sizeof(dof_hdr_t)) {
13430 dtrace_dof_error(NULL, "truncated header");
13435 * Each byte is represented by the two ASCII characters in its hex
13438 dofbuf = malloc(bytes, M_SOLARIS, M_WAITOK);
13439 for (i = 0; i < bytes; i++) {
13440 c1 = dtrace_dof_char(data[i * 2]);
13441 c2 = dtrace_dof_char(data[i * 2 + 1]);
13442 if (c1 == UCHAR_MAX || c2 == UCHAR_MAX) {
13443 dtrace_dof_error(NULL, "invalid hex char in DOF");
13446 dofbuf[i] = c1 * 16 + c2;
13449 dof = (dof_hdr_t *)dofbuf;
13450 if (bytes < dof->dofh_loadsz) {
13451 dtrace_dof_error(NULL, "truncated DOF");
13455 if (dof->dofh_loadsz >= dtrace_dof_maxsize) {
13456 dtrace_dof_error(NULL, "oversized DOF");
13463 free(dof, M_SOLARIS);
13465 #else /* __FreeBSD__ */
13468 unsigned int len, i;
13472 * Unfortunately, array of values in .conf files are always (and
13473 * only) interpreted to be integer arrays. We must read our DOF
13474 * as an integer array, and then squeeze it into a byte array.
13476 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
13477 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
13480 for (i = 0; i < len; i++)
13481 buf[i] = (uchar_t)(((int *)buf)[i]);
13483 if (len < sizeof (dof_hdr_t)) {
13484 ddi_prop_free(buf);
13485 dtrace_dof_error(NULL, "truncated header");
13489 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
13490 ddi_prop_free(buf);
13491 dtrace_dof_error(NULL, "truncated DOF");
13495 if (loadsz >= dtrace_dof_maxsize) {
13496 ddi_prop_free(buf);
13497 dtrace_dof_error(NULL, "oversized DOF");
13501 dof = kmem_alloc(loadsz, KM_SLEEP);
13502 bcopy(buf, dof, loadsz);
13503 ddi_prop_free(buf);
13506 #endif /* !__FreeBSD__ */
13510 dtrace_dof_destroy(dof_hdr_t *dof)
13512 kmem_free(dof, dof->dofh_loadsz);
13516 * Return the dof_sec_t pointer corresponding to a given section index. If the
13517 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
13518 * a type other than DOF_SECT_NONE is specified, the header is checked against
13519 * this type and NULL is returned if the types do not match.
13522 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
13524 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
13525 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
13527 if (i >= dof->dofh_secnum) {
13528 dtrace_dof_error(dof, "referenced section index is invalid");
13532 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
13533 dtrace_dof_error(dof, "referenced section is not loadable");
13537 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
13538 dtrace_dof_error(dof, "referenced section is the wrong type");
13545 static dtrace_probedesc_t *
13546 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
13548 dof_probedesc_t *probe;
13550 uintptr_t daddr = (uintptr_t)dof;
13554 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
13555 dtrace_dof_error(dof, "invalid probe section");
13559 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13560 dtrace_dof_error(dof, "bad alignment in probe description");
13564 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
13565 dtrace_dof_error(dof, "truncated probe description");
13569 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
13570 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
13572 if (strtab == NULL)
13575 str = daddr + strtab->dofs_offset;
13576 size = strtab->dofs_size;
13578 if (probe->dofp_provider >= strtab->dofs_size) {
13579 dtrace_dof_error(dof, "corrupt probe provider");
13583 (void) strncpy(desc->dtpd_provider,
13584 (char *)(str + probe->dofp_provider),
13585 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
13587 if (probe->dofp_mod >= strtab->dofs_size) {
13588 dtrace_dof_error(dof, "corrupt probe module");
13592 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
13593 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
13595 if (probe->dofp_func >= strtab->dofs_size) {
13596 dtrace_dof_error(dof, "corrupt probe function");
13600 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
13601 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
13603 if (probe->dofp_name >= strtab->dofs_size) {
13604 dtrace_dof_error(dof, "corrupt probe name");
13608 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
13609 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
13614 static dtrace_difo_t *
13615 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13620 dof_difohdr_t *dofd;
13621 uintptr_t daddr = (uintptr_t)dof;
13622 size_t max = dtrace_difo_maxsize;
13625 static const struct {
13633 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
13634 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
13635 sizeof (dif_instr_t), "multiple DIF sections" },
13637 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
13638 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
13639 sizeof (uint64_t), "multiple integer tables" },
13641 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
13642 offsetof(dtrace_difo_t, dtdo_strlen), 0,
13643 sizeof (char), "multiple string tables" },
13645 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
13646 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
13647 sizeof (uint_t), "multiple variable tables" },
13649 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
13652 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
13653 dtrace_dof_error(dof, "invalid DIFO header section");
13657 if (sec->dofs_align != sizeof (dof_secidx_t)) {
13658 dtrace_dof_error(dof, "bad alignment in DIFO header");
13662 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
13663 sec->dofs_size % sizeof (dof_secidx_t)) {
13664 dtrace_dof_error(dof, "bad size in DIFO header");
13668 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13669 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
13671 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
13672 dp->dtdo_rtype = dofd->dofd_rtype;
13674 for (l = 0; l < n; l++) {
13679 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
13680 dofd->dofd_links[l])) == NULL)
13681 goto err; /* invalid section link */
13683 if (ttl + subsec->dofs_size > max) {
13684 dtrace_dof_error(dof, "exceeds maximum size");
13688 ttl += subsec->dofs_size;
13690 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
13691 if (subsec->dofs_type != difo[i].section)
13694 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
13695 dtrace_dof_error(dof, "section not loaded");
13699 if (subsec->dofs_align != difo[i].align) {
13700 dtrace_dof_error(dof, "bad alignment");
13704 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
13705 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
13707 if (*bufp != NULL) {
13708 dtrace_dof_error(dof, difo[i].msg);
13712 if (difo[i].entsize != subsec->dofs_entsize) {
13713 dtrace_dof_error(dof, "entry size mismatch");
13717 if (subsec->dofs_entsize != 0 &&
13718 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
13719 dtrace_dof_error(dof, "corrupt entry size");
13723 *lenp = subsec->dofs_size;
13724 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
13725 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
13726 *bufp, subsec->dofs_size);
13728 if (subsec->dofs_entsize != 0)
13729 *lenp /= subsec->dofs_entsize;
13735 * If we encounter a loadable DIFO sub-section that is not
13736 * known to us, assume this is a broken program and fail.
13738 if (difo[i].section == DOF_SECT_NONE &&
13739 (subsec->dofs_flags & DOF_SECF_LOAD)) {
13740 dtrace_dof_error(dof, "unrecognized DIFO subsection");
13745 if (dp->dtdo_buf == NULL) {
13747 * We can't have a DIF object without DIF text.
13749 dtrace_dof_error(dof, "missing DIF text");
13754 * Before we validate the DIF object, run through the variable table
13755 * looking for the strings -- if any of their size are under, we'll set
13756 * their size to be the system-wide default string size. Note that
13757 * this should _not_ happen if the "strsize" option has been set --
13758 * in this case, the compiler should have set the size to reflect the
13759 * setting of the option.
13761 for (i = 0; i < dp->dtdo_varlen; i++) {
13762 dtrace_difv_t *v = &dp->dtdo_vartab[i];
13763 dtrace_diftype_t *t = &v->dtdv_type;
13765 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
13768 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
13769 t->dtdt_size = dtrace_strsize_default;
13772 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
13775 dtrace_difo_init(dp, vstate);
13779 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
13780 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
13781 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
13782 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
13784 kmem_free(dp, sizeof (dtrace_difo_t));
13788 static dtrace_predicate_t *
13789 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13794 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13797 return (dtrace_predicate_create(dp));
13800 static dtrace_actdesc_t *
13801 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13804 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13805 dof_actdesc_t *desc;
13806 dof_sec_t *difosec;
13808 uintptr_t daddr = (uintptr_t)dof;
13810 dtrace_actkind_t kind;
13812 if (sec->dofs_type != DOF_SECT_ACTDESC) {
13813 dtrace_dof_error(dof, "invalid action section");
13817 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13818 dtrace_dof_error(dof, "truncated action description");
13822 if (sec->dofs_align != sizeof (uint64_t)) {
13823 dtrace_dof_error(dof, "bad alignment in action description");
13827 if (sec->dofs_size < sec->dofs_entsize) {
13828 dtrace_dof_error(dof, "section entry size exceeds total size");
13832 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13833 dtrace_dof_error(dof, "bad entry size in action description");
13837 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13838 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13842 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13843 desc = (dof_actdesc_t *)(daddr +
13844 (uintptr_t)sec->dofs_offset + offs);
13845 kind = (dtrace_actkind_t)desc->dofa_kind;
13847 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13848 (kind != DTRACEACT_PRINTA ||
13849 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13850 (kind == DTRACEACT_DIFEXPR &&
13851 desc->dofa_strtab != DOF_SECIDX_NONE)) {
13857 * The argument to these actions is an index into the
13858 * DOF string table. For printf()-like actions, this
13859 * is the format string. For print(), this is the
13860 * CTF type of the expression result.
13862 if ((strtab = dtrace_dof_sect(dof,
13863 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13866 str = (char *)((uintptr_t)dof +
13867 (uintptr_t)strtab->dofs_offset);
13869 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13870 if (str[i] == '\0')
13874 if (i >= strtab->dofs_size) {
13875 dtrace_dof_error(dof, "bogus format string");
13879 if (i == desc->dofa_arg) {
13880 dtrace_dof_error(dof, "empty format string");
13884 i -= desc->dofa_arg;
13885 fmt = kmem_alloc(i + 1, KM_SLEEP);
13886 bcopy(&str[desc->dofa_arg], fmt, i + 1);
13887 arg = (uint64_t)(uintptr_t)fmt;
13889 if (kind == DTRACEACT_PRINTA) {
13890 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13893 arg = desc->dofa_arg;
13897 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13898 desc->dofa_uarg, arg);
13900 if (last != NULL) {
13901 last->dtad_next = act;
13908 if (desc->dofa_difo == DOF_SECIDX_NONE)
13911 if ((difosec = dtrace_dof_sect(dof,
13912 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13915 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13917 if (act->dtad_difo == NULL)
13921 ASSERT(first != NULL);
13925 for (act = first; act != NULL; act = next) {
13926 next = act->dtad_next;
13927 dtrace_actdesc_release(act, vstate);
13933 static dtrace_ecbdesc_t *
13934 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13937 dtrace_ecbdesc_t *ep;
13938 dof_ecbdesc_t *ecb;
13939 dtrace_probedesc_t *desc;
13940 dtrace_predicate_t *pred = NULL;
13942 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13943 dtrace_dof_error(dof, "truncated ECB description");
13947 if (sec->dofs_align != sizeof (uint64_t)) {
13948 dtrace_dof_error(dof, "bad alignment in ECB description");
13952 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13953 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13958 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13959 ep->dted_uarg = ecb->dofe_uarg;
13960 desc = &ep->dted_probe;
13962 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13965 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13966 if ((sec = dtrace_dof_sect(dof,
13967 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13970 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13973 ep->dted_pred.dtpdd_predicate = pred;
13976 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13977 if ((sec = dtrace_dof_sect(dof,
13978 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13981 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13983 if (ep->dted_action == NULL)
13991 dtrace_predicate_release(pred, vstate);
13992 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13997 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13998 * specified DOF. SETX relocations are computed using 'ubase', the base load
13999 * address of the object containing the DOF, and DOFREL relocations are relative
14000 * to the relocation offset within the DOF.
14003 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase,
14006 uintptr_t daddr = (uintptr_t)dof;
14008 dof_relohdr_t *dofr =
14009 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
14010 dof_sec_t *ss, *rs, *ts;
14014 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
14015 sec->dofs_align != sizeof (dof_secidx_t)) {
14016 dtrace_dof_error(dof, "invalid relocation header");
14020 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
14021 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
14022 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
14023 ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
14025 if (ss == NULL || rs == NULL || ts == NULL)
14026 return (-1); /* dtrace_dof_error() has been called already */
14028 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
14029 rs->dofs_align != sizeof (uint64_t)) {
14030 dtrace_dof_error(dof, "invalid relocation section");
14034 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
14035 n = rs->dofs_size / rs->dofs_entsize;
14037 for (i = 0; i < n; i++) {
14038 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
14040 switch (r->dofr_type) {
14041 case DOF_RELO_NONE:
14043 case DOF_RELO_SETX:
14044 case DOF_RELO_DOFREL:
14045 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
14046 sizeof (uint64_t) > ts->dofs_size) {
14047 dtrace_dof_error(dof, "bad relocation offset");
14051 if (taddr >= (uintptr_t)ts && taddr < ts_end) {
14052 dtrace_dof_error(dof, "bad relocation offset");
14056 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
14057 dtrace_dof_error(dof, "misaligned setx relo");
14061 if (r->dofr_type == DOF_RELO_SETX)
14062 *(uint64_t *)taddr += ubase;
14064 *(uint64_t *)taddr +=
14065 udaddr + ts->dofs_offset + r->dofr_offset;
14068 dtrace_dof_error(dof, "invalid relocation type");
14072 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
14079 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
14080 * header: it should be at the front of a memory region that is at least
14081 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
14082 * size. It need not be validated in any other way.
14085 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
14086 dtrace_enabling_t **enabp, uint64_t ubase, uint64_t udaddr, int noprobes)
14088 uint64_t len = dof->dofh_loadsz, seclen;
14089 uintptr_t daddr = (uintptr_t)dof;
14090 dtrace_ecbdesc_t *ep;
14091 dtrace_enabling_t *enab;
14094 ASSERT(MUTEX_HELD(&dtrace_lock));
14095 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
14098 * Check the DOF header identification bytes. In addition to checking
14099 * valid settings, we also verify that unused bits/bytes are zeroed so
14100 * we can use them later without fear of regressing existing binaries.
14102 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
14103 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
14104 dtrace_dof_error(dof, "DOF magic string mismatch");
14108 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
14109 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
14110 dtrace_dof_error(dof, "DOF has invalid data model");
14114 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
14115 dtrace_dof_error(dof, "DOF encoding mismatch");
14119 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14120 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
14121 dtrace_dof_error(dof, "DOF version mismatch");
14125 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
14126 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
14130 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
14131 dtrace_dof_error(dof, "DOF uses too many integer registers");
14135 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
14136 dtrace_dof_error(dof, "DOF uses too many tuple registers");
14140 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
14141 if (dof->dofh_ident[i] != 0) {
14142 dtrace_dof_error(dof, "DOF has invalid ident byte set");
14147 if (dof->dofh_flags & ~DOF_FL_VALID) {
14148 dtrace_dof_error(dof, "DOF has invalid flag bits set");
14152 if (dof->dofh_secsize == 0) {
14153 dtrace_dof_error(dof, "zero section header size");
14158 * Check that the section headers don't exceed the amount of DOF
14159 * data. Note that we cast the section size and number of sections
14160 * to uint64_t's to prevent possible overflow in the multiplication.
14162 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
14164 if (dof->dofh_secoff > len || seclen > len ||
14165 dof->dofh_secoff + seclen > len) {
14166 dtrace_dof_error(dof, "truncated section headers");
14170 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
14171 dtrace_dof_error(dof, "misaligned section headers");
14175 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
14176 dtrace_dof_error(dof, "misaligned section size");
14181 * Take an initial pass through the section headers to be sure that
14182 * the headers don't have stray offsets. If the 'noprobes' flag is
14183 * set, do not permit sections relating to providers, probes, or args.
14185 for (i = 0; i < dof->dofh_secnum; i++) {
14186 dof_sec_t *sec = (dof_sec_t *)(daddr +
14187 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14190 switch (sec->dofs_type) {
14191 case DOF_SECT_PROVIDER:
14192 case DOF_SECT_PROBES:
14193 case DOF_SECT_PRARGS:
14194 case DOF_SECT_PROFFS:
14195 dtrace_dof_error(dof, "illegal sections "
14201 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
14202 !(sec->dofs_flags & DOF_SECF_LOAD)) {
14203 dtrace_dof_error(dof, "loadable section with load "
14208 if (!(sec->dofs_flags & DOF_SECF_LOAD))
14209 continue; /* just ignore non-loadable sections */
14211 if (!ISP2(sec->dofs_align)) {
14212 dtrace_dof_error(dof, "bad section alignment");
14216 if (sec->dofs_offset & (sec->dofs_align - 1)) {
14217 dtrace_dof_error(dof, "misaligned section");
14221 if (sec->dofs_offset > len || sec->dofs_size > len ||
14222 sec->dofs_offset + sec->dofs_size > len) {
14223 dtrace_dof_error(dof, "corrupt section header");
14227 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
14228 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
14229 dtrace_dof_error(dof, "non-terminating string table");
14235 * Take a second pass through the sections and locate and perform any
14236 * relocations that are present. We do this after the first pass to
14237 * be sure that all sections have had their headers validated.
14239 for (i = 0; i < dof->dofh_secnum; i++) {
14240 dof_sec_t *sec = (dof_sec_t *)(daddr +
14241 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14243 if (!(sec->dofs_flags & DOF_SECF_LOAD))
14244 continue; /* skip sections that are not loadable */
14246 switch (sec->dofs_type) {
14247 case DOF_SECT_URELHDR:
14248 if (dtrace_dof_relocate(dof, sec, ubase, udaddr) != 0)
14254 if ((enab = *enabp) == NULL)
14255 enab = *enabp = dtrace_enabling_create(vstate);
14257 for (i = 0; i < dof->dofh_secnum; i++) {
14258 dof_sec_t *sec = (dof_sec_t *)(daddr +
14259 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14261 if (sec->dofs_type != DOF_SECT_ECBDESC)
14264 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
14265 dtrace_enabling_destroy(enab);
14270 dtrace_enabling_add(enab, ep);
14277 * Process DOF for any options. This routine assumes that the DOF has been
14278 * at least processed by dtrace_dof_slurp().
14281 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
14286 dof_optdesc_t *desc;
14288 for (i = 0; i < dof->dofh_secnum; i++) {
14289 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
14290 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
14292 if (sec->dofs_type != DOF_SECT_OPTDESC)
14295 if (sec->dofs_align != sizeof (uint64_t)) {
14296 dtrace_dof_error(dof, "bad alignment in "
14297 "option description");
14301 if ((entsize = sec->dofs_entsize) == 0) {
14302 dtrace_dof_error(dof, "zeroed option entry size");
14306 if (entsize < sizeof (dof_optdesc_t)) {
14307 dtrace_dof_error(dof, "bad option entry size");
14311 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
14312 desc = (dof_optdesc_t *)((uintptr_t)dof +
14313 (uintptr_t)sec->dofs_offset + offs);
14315 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
14316 dtrace_dof_error(dof, "non-zero option string");
14320 if (desc->dofo_value == DTRACEOPT_UNSET) {
14321 dtrace_dof_error(dof, "unset option");
14325 if ((rval = dtrace_state_option(state,
14326 desc->dofo_option, desc->dofo_value)) != 0) {
14327 dtrace_dof_error(dof, "rejected option");
14337 * DTrace Consumer State Functions
14340 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
14342 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
14345 dtrace_dynvar_t *dvar, *next, *start;
14348 ASSERT(MUTEX_HELD(&dtrace_lock));
14349 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
14351 bzero(dstate, sizeof (dtrace_dstate_t));
14353 if ((dstate->dtds_chunksize = chunksize) == 0)
14354 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
14356 VERIFY(dstate->dtds_chunksize < LONG_MAX);
14358 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
14361 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
14364 dstate->dtds_size = size;
14365 dstate->dtds_base = base;
14366 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
14367 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
14369 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
14371 if (hashsize != 1 && (hashsize & 1))
14374 dstate->dtds_hashsize = hashsize;
14375 dstate->dtds_hash = dstate->dtds_base;
14378 * Set all of our hash buckets to point to the single sink, and (if
14379 * it hasn't already been set), set the sink's hash value to be the
14380 * sink sentinel value. The sink is needed for dynamic variable
14381 * lookups to know that they have iterated over an entire, valid hash
14384 for (i = 0; i < hashsize; i++)
14385 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
14387 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
14388 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
14391 * Determine number of active CPUs. Divide free list evenly among
14394 start = (dtrace_dynvar_t *)
14395 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
14396 limit = (uintptr_t)base + size;
14398 VERIFY((uintptr_t)start < limit);
14399 VERIFY((uintptr_t)start >= (uintptr_t)base);
14401 maxper = (limit - (uintptr_t)start) / NCPU;
14402 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
14407 for (i = 0; i < NCPU; i++) {
14409 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
14412 * If we don't even have enough chunks to make it once through
14413 * NCPUs, we're just going to allocate everything to the first
14414 * CPU. And if we're on the last CPU, we're going to allocate
14415 * whatever is left over. In either case, we set the limit to
14416 * be the limit of the dynamic variable space.
14418 if (maxper == 0 || i == NCPU - 1) {
14419 limit = (uintptr_t)base + size;
14422 limit = (uintptr_t)start + maxper;
14423 start = (dtrace_dynvar_t *)limit;
14426 VERIFY(limit <= (uintptr_t)base + size);
14429 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
14430 dstate->dtds_chunksize);
14432 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
14435 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
14436 (uintptr_t)dvar <= (uintptr_t)base + size);
14437 dvar->dtdv_next = next;
14449 dtrace_dstate_fini(dtrace_dstate_t *dstate)
14451 ASSERT(MUTEX_HELD(&cpu_lock));
14453 if (dstate->dtds_base == NULL)
14456 kmem_free(dstate->dtds_base, dstate->dtds_size);
14457 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
14461 dtrace_vstate_fini(dtrace_vstate_t *vstate)
14464 * Logical XOR, where are you?
14466 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
14468 if (vstate->dtvs_nglobals > 0) {
14469 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
14470 sizeof (dtrace_statvar_t *));
14473 if (vstate->dtvs_ntlocals > 0) {
14474 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
14475 sizeof (dtrace_difv_t));
14478 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
14480 if (vstate->dtvs_nlocals > 0) {
14481 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
14482 sizeof (dtrace_statvar_t *));
14488 dtrace_state_clean(dtrace_state_t *state)
14490 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14493 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14494 dtrace_speculation_clean(state);
14498 dtrace_state_deadman(dtrace_state_t *state)
14504 now = dtrace_gethrtime();
14506 if (state != dtrace_anon.dta_state &&
14507 now - state->dts_laststatus >= dtrace_deadman_user)
14511 * We must be sure that dts_alive never appears to be less than the
14512 * value upon entry to dtrace_state_deadman(), and because we lack a
14513 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14514 * store INT64_MAX to it, followed by a memory barrier, followed by
14515 * the new value. This assures that dts_alive never appears to be
14516 * less than its true value, regardless of the order in which the
14517 * stores to the underlying storage are issued.
14519 state->dts_alive = INT64_MAX;
14520 dtrace_membar_producer();
14521 state->dts_alive = now;
14523 #else /* !illumos */
14525 dtrace_state_clean(void *arg)
14527 dtrace_state_t *state = arg;
14528 dtrace_optval_t *opt = state->dts_options;
14530 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
14533 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
14534 dtrace_speculation_clean(state);
14536 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
14537 dtrace_state_clean, state);
14541 dtrace_state_deadman(void *arg)
14543 dtrace_state_t *state = arg;
14548 dtrace_debug_output();
14550 now = dtrace_gethrtime();
14552 if (state != dtrace_anon.dta_state &&
14553 now - state->dts_laststatus >= dtrace_deadman_user)
14557 * We must be sure that dts_alive never appears to be less than the
14558 * value upon entry to dtrace_state_deadman(), and because we lack a
14559 * dtrace_cas64(), we cannot store to it atomically. We thus instead
14560 * store INT64_MAX to it, followed by a memory barrier, followed by
14561 * the new value. This assures that dts_alive never appears to be
14562 * less than its true value, regardless of the order in which the
14563 * stores to the underlying storage are issued.
14565 state->dts_alive = INT64_MAX;
14566 dtrace_membar_producer();
14567 state->dts_alive = now;
14569 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
14570 dtrace_state_deadman, state);
14572 #endif /* illumos */
14574 static dtrace_state_t *
14576 dtrace_state_create(dev_t *devp, cred_t *cr)
14578 dtrace_state_create(struct cdev *dev, struct ucred *cred __unused)
14589 dtrace_state_t *state;
14590 dtrace_optval_t *opt;
14591 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
14594 ASSERT(MUTEX_HELD(&dtrace_lock));
14595 ASSERT(MUTEX_HELD(&cpu_lock));
14598 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
14599 VM_BESTFIT | VM_SLEEP);
14601 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
14602 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14606 state = ddi_get_soft_state(dtrace_softstate, minor);
14613 /* Allocate memory for the state. */
14614 state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
14617 state->dts_epid = DTRACE_EPIDNONE + 1;
14619 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
14621 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
14622 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14624 if (devp != NULL) {
14625 major = getemajor(*devp);
14627 major = ddi_driver_major(dtrace_devi);
14630 state->dts_dev = makedevice(major, minor);
14633 *devp = state->dts_dev;
14635 state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
14636 state->dts_dev = dev;
14640 * We allocate NCPU buffers. On the one hand, this can be quite
14641 * a bit of memory per instance (nearly 36K on a Starcat). On the
14642 * other hand, it saves an additional memory reference in the probe
14645 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
14646 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
14649 * Allocate and initialise the per-process per-CPU random state.
14650 * SI_SUB_RANDOM < SI_SUB_DTRACE_ANON therefore entropy device is
14651 * assumed to be seeded at this point (if from Fortuna seed file).
14653 arc4random_buf(&state->dts_rstate[0], 2 * sizeof(uint64_t));
14654 for (cpu_it = 1; cpu_it < NCPU; cpu_it++) {
14656 * Each CPU is assigned a 2^64 period, non-overlapping
14659 dtrace_xoroshiro128_plus_jump(state->dts_rstate[cpu_it-1],
14660 state->dts_rstate[cpu_it]);
14664 state->dts_cleaner = CYCLIC_NONE;
14665 state->dts_deadman = CYCLIC_NONE;
14667 callout_init(&state->dts_cleaner, 1);
14668 callout_init(&state->dts_deadman, 1);
14670 state->dts_vstate.dtvs_state = state;
14672 for (i = 0; i < DTRACEOPT_MAX; i++)
14673 state->dts_options[i] = DTRACEOPT_UNSET;
14676 * Set the default options.
14678 opt = state->dts_options;
14679 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
14680 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
14681 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
14682 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
14683 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
14684 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
14685 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
14686 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
14687 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
14688 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
14689 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
14690 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
14691 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
14692 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
14694 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
14697 * Depending on the user credentials, we set flag bits which alter probe
14698 * visibility or the amount of destructiveness allowed. In the case of
14699 * actual anonymous tracing, or the possession of all privileges, all of
14700 * the normal checks are bypassed.
14702 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
14703 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
14704 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
14707 * Set up the credentials for this instantiation. We take a
14708 * hold on the credential to prevent it from disappearing on
14709 * us; this in turn prevents the zone_t referenced by this
14710 * credential from disappearing. This means that we can
14711 * examine the credential and the zone from probe context.
14714 state->dts_cred.dcr_cred = cr;
14717 * CRA_PROC means "we have *some* privilege for dtrace" and
14718 * unlocks the use of variables like pid, zonename, etc.
14720 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
14721 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14722 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
14726 * dtrace_user allows use of syscall and profile providers.
14727 * If the user also has proc_owner and/or proc_zone, we
14728 * extend the scope to include additional visibility and
14729 * destructive power.
14731 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
14732 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
14733 state->dts_cred.dcr_visible |=
14734 DTRACE_CRV_ALLPROC;
14736 state->dts_cred.dcr_action |=
14737 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14740 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
14741 state->dts_cred.dcr_visible |=
14742 DTRACE_CRV_ALLZONE;
14744 state->dts_cred.dcr_action |=
14745 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14749 * If we have all privs in whatever zone this is,
14750 * we can do destructive things to processes which
14751 * have altered credentials.
14754 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14755 cr->cr_zone->zone_privset)) {
14756 state->dts_cred.dcr_action |=
14757 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14763 * Holding the dtrace_kernel privilege also implies that
14764 * the user has the dtrace_user privilege from a visibility
14765 * perspective. But without further privileges, some
14766 * destructive actions are not available.
14768 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
14770 * Make all probes in all zones visible. However,
14771 * this doesn't mean that all actions become available
14774 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
14775 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
14777 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
14780 * Holding proc_owner means that destructive actions
14781 * for *this* zone are allowed.
14783 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14784 state->dts_cred.dcr_action |=
14785 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14788 * Holding proc_zone means that destructive actions
14789 * for this user/group ID in all zones is allowed.
14791 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14792 state->dts_cred.dcr_action |=
14793 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14797 * If we have all privs in whatever zone this is,
14798 * we can do destructive things to processes which
14799 * have altered credentials.
14801 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
14802 cr->cr_zone->zone_privset)) {
14803 state->dts_cred.dcr_action |=
14804 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
14810 * Holding the dtrace_proc privilege gives control over fasttrap
14811 * and pid providers. We need to grant wider destructive
14812 * privileges in the event that the user has proc_owner and/or
14815 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
14816 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
14817 state->dts_cred.dcr_action |=
14818 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
14820 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
14821 state->dts_cred.dcr_action |=
14822 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
14830 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
14832 dtrace_optval_t *opt = state->dts_options, size;
14833 processorid_t cpu = 0;;
14834 int flags = 0, rval, factor, divisor = 1;
14836 ASSERT(MUTEX_HELD(&dtrace_lock));
14837 ASSERT(MUTEX_HELD(&cpu_lock));
14838 ASSERT(which < DTRACEOPT_MAX);
14839 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
14840 (state == dtrace_anon.dta_state &&
14841 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
14843 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
14846 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
14847 cpu = opt[DTRACEOPT_CPU];
14849 if (which == DTRACEOPT_SPECSIZE)
14850 flags |= DTRACEBUF_NOSWITCH;
14852 if (which == DTRACEOPT_BUFSIZE) {
14853 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
14854 flags |= DTRACEBUF_RING;
14856 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
14857 flags |= DTRACEBUF_FILL;
14859 if (state != dtrace_anon.dta_state ||
14860 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14861 flags |= DTRACEBUF_INACTIVE;
14864 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
14866 * The size must be 8-byte aligned. If the size is not 8-byte
14867 * aligned, drop it down by the difference.
14869 if (size & (sizeof (uint64_t) - 1))
14870 size -= size & (sizeof (uint64_t) - 1);
14872 if (size < state->dts_reserve) {
14874 * Buffers always must be large enough to accommodate
14875 * their prereserved space. We return E2BIG instead
14876 * of ENOMEM in this case to allow for user-level
14877 * software to differentiate the cases.
14882 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
14884 if (rval != ENOMEM) {
14889 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14892 for (divisor = 2; divisor < factor; divisor <<= 1)
14900 dtrace_state_buffers(dtrace_state_t *state)
14902 dtrace_speculation_t *spec = state->dts_speculations;
14905 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14906 DTRACEOPT_BUFSIZE)) != 0)
14909 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14910 DTRACEOPT_AGGSIZE)) != 0)
14913 for (i = 0; i < state->dts_nspeculations; i++) {
14914 if ((rval = dtrace_state_buffer(state,
14915 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14923 dtrace_state_prereserve(dtrace_state_t *state)
14926 dtrace_probe_t *probe;
14928 state->dts_reserve = 0;
14930 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14934 * If our buffer policy is a "fill" buffer policy, we need to set the
14935 * prereserved space to be the space required by the END probes.
14937 probe = dtrace_probes[dtrace_probeid_end - 1];
14938 ASSERT(probe != NULL);
14940 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14941 if (ecb->dte_state != state)
14944 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14949 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14951 dtrace_optval_t *opt = state->dts_options, sz, nspec;
14952 dtrace_speculation_t *spec;
14953 dtrace_buffer_t *buf;
14955 cyc_handler_t hdlr;
14958 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14959 dtrace_icookie_t cookie;
14961 mutex_enter(&cpu_lock);
14962 mutex_enter(&dtrace_lock);
14964 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14970 * Before we can perform any checks, we must prime all of the
14971 * retained enablings that correspond to this state.
14973 dtrace_enabling_prime(state);
14975 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14980 dtrace_state_prereserve(state);
14983 * Now we want to do is try to allocate our speculations.
14984 * We do not automatically resize the number of speculations; if
14985 * this fails, we will fail the operation.
14987 nspec = opt[DTRACEOPT_NSPEC];
14988 ASSERT(nspec != DTRACEOPT_UNSET);
14990 if (nspec > INT_MAX) {
14995 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14996 KM_NOSLEEP | KM_NORMALPRI);
14998 if (spec == NULL) {
15003 state->dts_speculations = spec;
15004 state->dts_nspeculations = (int)nspec;
15006 for (i = 0; i < nspec; i++) {
15007 if ((buf = kmem_zalloc(bufsize,
15008 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
15013 spec[i].dtsp_buffer = buf;
15016 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
15017 if (dtrace_anon.dta_state == NULL) {
15022 if (state->dts_necbs != 0) {
15027 state->dts_anon = dtrace_anon_grab();
15028 ASSERT(state->dts_anon != NULL);
15029 state = state->dts_anon;
15032 * We want "grabanon" to be set in the grabbed state, so we'll
15033 * copy that option value from the grabbing state into the
15036 state->dts_options[DTRACEOPT_GRABANON] =
15037 opt[DTRACEOPT_GRABANON];
15039 *cpu = dtrace_anon.dta_beganon;
15042 * If the anonymous state is active (as it almost certainly
15043 * is if the anonymous enabling ultimately matched anything),
15044 * we don't allow any further option processing -- but we
15045 * don't return failure.
15047 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15051 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
15052 opt[DTRACEOPT_AGGSIZE] != 0) {
15053 if (state->dts_aggregations == NULL) {
15055 * We're not going to create an aggregation buffer
15056 * because we don't have any ECBs that contain
15057 * aggregations -- set this option to 0.
15059 opt[DTRACEOPT_AGGSIZE] = 0;
15062 * If we have an aggregation buffer, we must also have
15063 * a buffer to use as scratch.
15065 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
15066 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
15067 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
15072 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
15073 opt[DTRACEOPT_SPECSIZE] != 0) {
15074 if (!state->dts_speculates) {
15076 * We're not going to create speculation buffers
15077 * because we don't have any ECBs that actually
15078 * speculate -- set the speculation size to 0.
15080 opt[DTRACEOPT_SPECSIZE] = 0;
15085 * The bare minimum size for any buffer that we're actually going to
15086 * do anything to is sizeof (uint64_t).
15088 sz = sizeof (uint64_t);
15090 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
15091 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
15092 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
15094 * A buffer size has been explicitly set to 0 (or to a size
15095 * that will be adjusted to 0) and we need the space -- we
15096 * need to return failure. We return ENOSPC to differentiate
15097 * it from failing to allocate a buffer due to failure to meet
15098 * the reserve (for which we return E2BIG).
15104 if ((rval = dtrace_state_buffers(state)) != 0)
15107 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
15108 sz = dtrace_dstate_defsize;
15111 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
15116 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
15118 } while (sz >>= 1);
15120 opt[DTRACEOPT_DYNVARSIZE] = sz;
15125 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
15126 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
15128 if (opt[DTRACEOPT_CLEANRATE] == 0)
15129 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15131 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
15132 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
15134 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
15135 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
15137 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
15139 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
15140 hdlr.cyh_arg = state;
15141 hdlr.cyh_level = CY_LOW_LEVEL;
15144 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
15146 state->dts_cleaner = cyclic_add(&hdlr, &when);
15148 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
15149 hdlr.cyh_arg = state;
15150 hdlr.cyh_level = CY_LOW_LEVEL;
15153 when.cyt_interval = dtrace_deadman_interval;
15155 state->dts_deadman = cyclic_add(&hdlr, &when);
15157 callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
15158 dtrace_state_clean, state);
15159 callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
15160 dtrace_state_deadman, state);
15163 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
15166 if (state->dts_getf != 0 &&
15167 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15169 * We don't have kernel privs but we have at least one call
15170 * to getf(); we need to bump our zone's count, and (if
15171 * this is the first enabling to have an unprivileged call
15172 * to getf()) we need to hook into closef().
15174 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
15176 if (dtrace_getf++ == 0) {
15177 ASSERT(dtrace_closef == NULL);
15178 dtrace_closef = dtrace_getf_barrier;
15184 * Now it's time to actually fire the BEGIN probe. We need to disable
15185 * interrupts here both to record the CPU on which we fired the BEGIN
15186 * probe (the data from this CPU will be processed first at user
15187 * level) and to manually activate the buffer for this CPU.
15189 cookie = dtrace_interrupt_disable();
15191 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
15192 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
15194 dtrace_probe(dtrace_probeid_begin,
15195 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15196 dtrace_interrupt_enable(cookie);
15198 * We may have had an exit action from a BEGIN probe; only change our
15199 * state to ACTIVE if we're still in WARMUP.
15201 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
15202 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
15204 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
15205 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
15209 * We enable anonymous tracing before APs are started, so we must
15210 * activate buffers using the current CPU.
15212 if (state == dtrace_anon.dta_state)
15213 for (int i = 0; i < NCPU; i++)
15214 dtrace_buffer_activate_cpu(state, i);
15216 dtrace_xcall(DTRACE_CPUALL,
15217 (dtrace_xcall_t)dtrace_buffer_activate, state);
15220 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
15221 * want each CPU to transition its principal buffer out of the
15222 * INACTIVE state. Doing this assures that no CPU will suddenly begin
15223 * processing an ECB halfway down a probe's ECB chain; all CPUs will
15224 * atomically transition from processing none of a state's ECBs to
15225 * processing all of them.
15227 dtrace_xcall(DTRACE_CPUALL,
15228 (dtrace_xcall_t)dtrace_buffer_activate, state);
15233 dtrace_buffer_free(state->dts_buffer);
15234 dtrace_buffer_free(state->dts_aggbuffer);
15236 if ((nspec = state->dts_nspeculations) == 0) {
15237 ASSERT(state->dts_speculations == NULL);
15241 spec = state->dts_speculations;
15242 ASSERT(spec != NULL);
15244 for (i = 0; i < state->dts_nspeculations; i++) {
15245 if ((buf = spec[i].dtsp_buffer) == NULL)
15248 dtrace_buffer_free(buf);
15249 kmem_free(buf, bufsize);
15252 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15253 state->dts_nspeculations = 0;
15254 state->dts_speculations = NULL;
15257 mutex_exit(&dtrace_lock);
15258 mutex_exit(&cpu_lock);
15264 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
15266 dtrace_icookie_t cookie;
15268 ASSERT(MUTEX_HELD(&dtrace_lock));
15270 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
15271 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
15275 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
15276 * to be sure that every CPU has seen it. See below for the details
15277 * on why this is done.
15279 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
15283 * By this point, it is impossible for any CPU to be still processing
15284 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
15285 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
15286 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
15287 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
15288 * iff we're in the END probe.
15290 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
15292 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
15295 * Finally, we can release the reserve and call the END probe. We
15296 * disable interrupts across calling the END probe to allow us to
15297 * return the CPU on which we actually called the END probe. This
15298 * allows user-land to be sure that this CPU's principal buffer is
15301 state->dts_reserve = 0;
15303 cookie = dtrace_interrupt_disable();
15305 dtrace_probe(dtrace_probeid_end,
15306 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
15307 dtrace_interrupt_enable(cookie);
15309 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
15313 if (state->dts_getf != 0 &&
15314 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
15316 * We don't have kernel privs but we have at least one call
15317 * to getf(); we need to lower our zone's count, and (if
15318 * this is the last enabling to have an unprivileged call
15319 * to getf()) we need to clear the closef() hook.
15321 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
15322 ASSERT(dtrace_closef == dtrace_getf_barrier);
15323 ASSERT(dtrace_getf > 0);
15325 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
15327 if (--dtrace_getf == 0)
15328 dtrace_closef = NULL;
15336 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
15337 dtrace_optval_t val)
15339 ASSERT(MUTEX_HELD(&dtrace_lock));
15341 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
15344 if (option >= DTRACEOPT_MAX)
15347 if (option != DTRACEOPT_CPU && val < 0)
15351 case DTRACEOPT_DESTRUCTIVE:
15352 if (dtrace_destructive_disallow)
15355 state->dts_cred.dcr_destructive = 1;
15358 case DTRACEOPT_BUFSIZE:
15359 case DTRACEOPT_DYNVARSIZE:
15360 case DTRACEOPT_AGGSIZE:
15361 case DTRACEOPT_SPECSIZE:
15362 case DTRACEOPT_STRSIZE:
15366 if (val >= LONG_MAX) {
15368 * If this is an otherwise negative value, set it to
15369 * the highest multiple of 128m less than LONG_MAX.
15370 * Technically, we're adjusting the size without
15371 * regard to the buffer resizing policy, but in fact,
15372 * this has no effect -- if we set the buffer size to
15373 * ~LONG_MAX and the buffer policy is ultimately set to
15374 * be "manual", the buffer allocation is guaranteed to
15375 * fail, if only because the allocation requires two
15376 * buffers. (We set the the size to the highest
15377 * multiple of 128m because it ensures that the size
15378 * will remain a multiple of a megabyte when
15379 * repeatedly halved -- all the way down to 15m.)
15381 val = LONG_MAX - (1 << 27) + 1;
15385 state->dts_options[option] = val;
15391 dtrace_state_destroy(dtrace_state_t *state)
15394 dtrace_vstate_t *vstate = &state->dts_vstate;
15396 minor_t minor = getminor(state->dts_dev);
15398 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
15399 dtrace_speculation_t *spec = state->dts_speculations;
15400 int nspec = state->dts_nspeculations;
15403 ASSERT(MUTEX_HELD(&dtrace_lock));
15404 ASSERT(MUTEX_HELD(&cpu_lock));
15407 * First, retract any retained enablings for this state.
15409 dtrace_enabling_retract(state);
15410 ASSERT(state->dts_nretained == 0);
15412 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
15413 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
15415 * We have managed to come into dtrace_state_destroy() on a
15416 * hot enabling -- almost certainly because of a disorderly
15417 * shutdown of a consumer. (That is, a consumer that is
15418 * exiting without having called dtrace_stop().) In this case,
15419 * we're going to set our activity to be KILLED, and then
15420 * issue a sync to be sure that everyone is out of probe
15421 * context before we start blowing away ECBs.
15423 state->dts_activity = DTRACE_ACTIVITY_KILLED;
15428 * Release the credential hold we took in dtrace_state_create().
15430 if (state->dts_cred.dcr_cred != NULL)
15431 crfree(state->dts_cred.dcr_cred);
15434 * Now we can safely disable and destroy any enabled probes. Because
15435 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
15436 * (especially if they're all enabled), we take two passes through the
15437 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
15438 * in the second we disable whatever is left over.
15440 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
15441 for (i = 0; i < state->dts_necbs; i++) {
15442 if ((ecb = state->dts_ecbs[i]) == NULL)
15445 if (match && ecb->dte_probe != NULL) {
15446 dtrace_probe_t *probe = ecb->dte_probe;
15447 dtrace_provider_t *prov = probe->dtpr_provider;
15449 if (!(prov->dtpv_priv.dtpp_flags & match))
15453 dtrace_ecb_disable(ecb);
15454 dtrace_ecb_destroy(ecb);
15462 * Before we free the buffers, perform one more sync to assure that
15463 * every CPU is out of probe context.
15467 dtrace_buffer_free(state->dts_buffer);
15468 dtrace_buffer_free(state->dts_aggbuffer);
15470 for (i = 0; i < nspec; i++)
15471 dtrace_buffer_free(spec[i].dtsp_buffer);
15474 if (state->dts_cleaner != CYCLIC_NONE)
15475 cyclic_remove(state->dts_cleaner);
15477 if (state->dts_deadman != CYCLIC_NONE)
15478 cyclic_remove(state->dts_deadman);
15480 callout_stop(&state->dts_cleaner);
15481 callout_drain(&state->dts_cleaner);
15482 callout_stop(&state->dts_deadman);
15483 callout_drain(&state->dts_deadman);
15486 dtrace_dstate_fini(&vstate->dtvs_dynvars);
15487 dtrace_vstate_fini(vstate);
15488 if (state->dts_ecbs != NULL)
15489 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
15491 if (state->dts_aggregations != NULL) {
15493 for (i = 0; i < state->dts_naggregations; i++)
15494 ASSERT(state->dts_aggregations[i] == NULL);
15496 ASSERT(state->dts_naggregations > 0);
15497 kmem_free(state->dts_aggregations,
15498 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
15501 kmem_free(state->dts_buffer, bufsize);
15502 kmem_free(state->dts_aggbuffer, bufsize);
15504 for (i = 0; i < nspec; i++)
15505 kmem_free(spec[i].dtsp_buffer, bufsize);
15508 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
15510 dtrace_format_destroy(state);
15512 if (state->dts_aggid_arena != NULL) {
15514 vmem_destroy(state->dts_aggid_arena);
15516 delete_unrhdr(state->dts_aggid_arena);
15518 state->dts_aggid_arena = NULL;
15521 ddi_soft_state_free(dtrace_softstate, minor);
15522 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
15527 * DTrace Anonymous Enabling Functions
15529 static dtrace_state_t *
15530 dtrace_anon_grab(void)
15532 dtrace_state_t *state;
15534 ASSERT(MUTEX_HELD(&dtrace_lock));
15536 if ((state = dtrace_anon.dta_state) == NULL) {
15537 ASSERT(dtrace_anon.dta_enabling == NULL);
15541 ASSERT(dtrace_anon.dta_enabling != NULL);
15542 ASSERT(dtrace_retained != NULL);
15544 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
15545 dtrace_anon.dta_enabling = NULL;
15546 dtrace_anon.dta_state = NULL;
15552 dtrace_anon_property(void)
15555 dtrace_state_t *state;
15557 char c[32]; /* enough for "dof-data-" + digits */
15559 ASSERT(MUTEX_HELD(&dtrace_lock));
15560 ASSERT(MUTEX_HELD(&cpu_lock));
15562 for (i = 0; ; i++) {
15563 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
15565 dtrace_err_verbose = 1;
15567 if ((dof = dtrace_dof_property(c)) == NULL) {
15568 dtrace_err_verbose = 0;
15574 * We want to create anonymous state, so we need to transition
15575 * the kernel debugger to indicate that DTrace is active. If
15576 * this fails (e.g. because the debugger has modified text in
15577 * some way), we won't continue with the processing.
15579 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15580 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
15581 "enabling ignored.");
15582 dtrace_dof_destroy(dof);
15588 * If we haven't allocated an anonymous state, we'll do so now.
15590 if ((state = dtrace_anon.dta_state) == NULL) {
15591 state = dtrace_state_create(NULL, NULL);
15592 dtrace_anon.dta_state = state;
15594 if (state == NULL) {
15596 * This basically shouldn't happen: the only
15597 * failure mode from dtrace_state_create() is a
15598 * failure of ddi_soft_state_zalloc() that
15599 * itself should never happen. Still, the
15600 * interface allows for a failure mode, and
15601 * we want to fail as gracefully as possible:
15602 * we'll emit an error message and cease
15603 * processing anonymous state in this case.
15605 cmn_err(CE_WARN, "failed to create "
15606 "anonymous state");
15607 dtrace_dof_destroy(dof);
15612 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
15613 &dtrace_anon.dta_enabling, 0, 0, B_TRUE);
15616 rv = dtrace_dof_options(dof, state);
15618 dtrace_err_verbose = 0;
15619 dtrace_dof_destroy(dof);
15623 * This is malformed DOF; chuck any anonymous state
15626 ASSERT(dtrace_anon.dta_enabling == NULL);
15627 dtrace_state_destroy(state);
15628 dtrace_anon.dta_state = NULL;
15632 ASSERT(dtrace_anon.dta_enabling != NULL);
15635 if (dtrace_anon.dta_enabling != NULL) {
15639 * dtrace_enabling_retain() can only fail because we are
15640 * trying to retain more enablings than are allowed -- but
15641 * we only have one anonymous enabling, and we are guaranteed
15642 * to be allowed at least one retained enabling; we assert
15643 * that dtrace_enabling_retain() returns success.
15645 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
15648 dtrace_enabling_dump(dtrace_anon.dta_enabling);
15653 * DTrace Helper Functions
15656 dtrace_helper_trace(dtrace_helper_action_t *helper,
15657 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
15659 uint32_t size, next, nnext, i;
15660 dtrace_helptrace_t *ent, *buffer;
15661 uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
15663 if ((buffer = dtrace_helptrace_buffer) == NULL)
15666 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
15669 * What would a tracing framework be without its own tracing
15670 * framework? (Well, a hell of a lot simpler, for starters...)
15672 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
15673 sizeof (uint64_t) - sizeof (uint64_t);
15676 * Iterate until we can allocate a slot in the trace buffer.
15679 next = dtrace_helptrace_next;
15681 if (next + size < dtrace_helptrace_bufsize) {
15682 nnext = next + size;
15686 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
15689 * We have our slot; fill it in.
15691 if (nnext == size) {
15692 dtrace_helptrace_wrapped++;
15696 ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
15697 ent->dtht_helper = helper;
15698 ent->dtht_where = where;
15699 ent->dtht_nlocals = vstate->dtvs_nlocals;
15701 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
15702 mstate->dtms_fltoffs : -1;
15703 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
15704 ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
15706 for (i = 0; i < vstate->dtvs_nlocals; i++) {
15707 dtrace_statvar_t *svar;
15709 if ((svar = vstate->dtvs_locals[i]) == NULL)
15712 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
15713 ent->dtht_locals[i] =
15714 ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
15719 dtrace_helper(int which, dtrace_mstate_t *mstate,
15720 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
15722 uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
15723 uint64_t sarg0 = mstate->dtms_arg[0];
15724 uint64_t sarg1 = mstate->dtms_arg[1];
15726 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
15727 dtrace_helper_action_t *helper;
15728 dtrace_vstate_t *vstate;
15729 dtrace_difo_t *pred;
15730 int i, trace = dtrace_helptrace_buffer != NULL;
15732 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
15734 if (helpers == NULL)
15737 if ((helper = helpers->dthps_actions[which]) == NULL)
15740 vstate = &helpers->dthps_vstate;
15741 mstate->dtms_arg[0] = arg0;
15742 mstate->dtms_arg[1] = arg1;
15745 * Now iterate over each helper. If its predicate evaluates to 'true',
15746 * we'll call the corresponding actions. Note that the below calls
15747 * to dtrace_dif_emulate() may set faults in machine state. This is
15748 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
15749 * the stored DIF offset with its own (which is the desired behavior).
15750 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
15751 * from machine state; this is okay, too.
15753 for (; helper != NULL; helper = helper->dtha_next) {
15754 if ((pred = helper->dtha_predicate) != NULL) {
15756 dtrace_helper_trace(helper, mstate, vstate, 0);
15758 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
15761 if (*flags & CPU_DTRACE_FAULT)
15765 for (i = 0; i < helper->dtha_nactions; i++) {
15767 dtrace_helper_trace(helper,
15768 mstate, vstate, i + 1);
15770 rval = dtrace_dif_emulate(helper->dtha_actions[i],
15771 mstate, vstate, state);
15773 if (*flags & CPU_DTRACE_FAULT)
15779 dtrace_helper_trace(helper, mstate, vstate,
15780 DTRACE_HELPTRACE_NEXT);
15784 dtrace_helper_trace(helper, mstate, vstate,
15785 DTRACE_HELPTRACE_DONE);
15788 * Restore the arg0 that we saved upon entry.
15790 mstate->dtms_arg[0] = sarg0;
15791 mstate->dtms_arg[1] = sarg1;
15797 dtrace_helper_trace(helper, mstate, vstate,
15798 DTRACE_HELPTRACE_ERR);
15801 * Restore the arg0 that we saved upon entry.
15803 mstate->dtms_arg[0] = sarg0;
15804 mstate->dtms_arg[1] = sarg1;
15810 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
15811 dtrace_vstate_t *vstate)
15815 if (helper->dtha_predicate != NULL)
15816 dtrace_difo_release(helper->dtha_predicate, vstate);
15818 for (i = 0; i < helper->dtha_nactions; i++) {
15819 ASSERT(helper->dtha_actions[i] != NULL);
15820 dtrace_difo_release(helper->dtha_actions[i], vstate);
15823 kmem_free(helper->dtha_actions,
15824 helper->dtha_nactions * sizeof (dtrace_difo_t *));
15825 kmem_free(helper, sizeof (dtrace_helper_action_t));
15829 dtrace_helper_destroygen(dtrace_helpers_t *help, int gen)
15831 proc_t *p = curproc;
15832 dtrace_vstate_t *vstate;
15836 help = p->p_dtrace_helpers;
15838 ASSERT(MUTEX_HELD(&dtrace_lock));
15840 if (help == NULL || gen > help->dthps_generation)
15843 vstate = &help->dthps_vstate;
15845 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15846 dtrace_helper_action_t *last = NULL, *h, *next;
15848 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15849 next = h->dtha_next;
15851 if (h->dtha_generation == gen) {
15852 if (last != NULL) {
15853 last->dtha_next = next;
15855 help->dthps_actions[i] = next;
15858 dtrace_helper_action_destroy(h, vstate);
15866 * Interate until we've cleared out all helper providers with the
15867 * given generation number.
15870 dtrace_helper_provider_t *prov;
15873 * Look for a helper provider with the right generation. We
15874 * have to start back at the beginning of the list each time
15875 * because we drop dtrace_lock. It's unlikely that we'll make
15876 * more than two passes.
15878 for (i = 0; i < help->dthps_nprovs; i++) {
15879 prov = help->dthps_provs[i];
15881 if (prov->dthp_generation == gen)
15886 * If there were no matches, we're done.
15888 if (i == help->dthps_nprovs)
15892 * Move the last helper provider into this slot.
15894 help->dthps_nprovs--;
15895 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
15896 help->dthps_provs[help->dthps_nprovs] = NULL;
15898 mutex_exit(&dtrace_lock);
15901 * If we have a meta provider, remove this helper provider.
15903 mutex_enter(&dtrace_meta_lock);
15904 if (dtrace_meta_pid != NULL) {
15905 ASSERT(dtrace_deferred_pid == NULL);
15906 dtrace_helper_provider_remove(&prov->dthp_prov,
15909 mutex_exit(&dtrace_meta_lock);
15911 dtrace_helper_provider_destroy(prov);
15913 mutex_enter(&dtrace_lock);
15920 dtrace_helper_validate(dtrace_helper_action_t *helper)
15925 if ((dp = helper->dtha_predicate) != NULL)
15926 err += dtrace_difo_validate_helper(dp);
15928 for (i = 0; i < helper->dtha_nactions; i++)
15929 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
15935 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep,
15936 dtrace_helpers_t *help)
15938 dtrace_helper_action_t *helper, *last;
15939 dtrace_actdesc_t *act;
15940 dtrace_vstate_t *vstate;
15941 dtrace_predicate_t *pred;
15942 int count = 0, nactions = 0, i;
15944 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
15947 last = help->dthps_actions[which];
15948 vstate = &help->dthps_vstate;
15950 for (count = 0; last != NULL; last = last->dtha_next) {
15952 if (last->dtha_next == NULL)
15957 * If we already have dtrace_helper_actions_max helper actions for this
15958 * helper action type, we'll refuse to add a new one.
15960 if (count >= dtrace_helper_actions_max)
15963 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15964 helper->dtha_generation = help->dthps_generation;
15966 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15967 ASSERT(pred->dtp_difo != NULL);
15968 dtrace_difo_hold(pred->dtp_difo);
15969 helper->dtha_predicate = pred->dtp_difo;
15972 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15973 if (act->dtad_kind != DTRACEACT_DIFEXPR)
15976 if (act->dtad_difo == NULL)
15982 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15983 (helper->dtha_nactions = nactions), KM_SLEEP);
15985 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15986 dtrace_difo_hold(act->dtad_difo);
15987 helper->dtha_actions[i++] = act->dtad_difo;
15990 if (!dtrace_helper_validate(helper))
15993 if (last == NULL) {
15994 help->dthps_actions[which] = helper;
15996 last->dtha_next = helper;
15999 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
16000 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
16001 dtrace_helptrace_next = 0;
16006 dtrace_helper_action_destroy(helper, vstate);
16011 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
16012 dof_helper_t *dofhp)
16014 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
16016 mutex_enter(&dtrace_meta_lock);
16017 mutex_enter(&dtrace_lock);
16019 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
16021 * If the dtrace module is loaded but not attached, or if
16022 * there aren't isn't a meta provider registered to deal with
16023 * these provider descriptions, we need to postpone creating
16024 * the actual providers until later.
16027 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
16028 dtrace_deferred_pid != help) {
16029 help->dthps_deferred = 1;
16030 help->dthps_pid = p->p_pid;
16031 help->dthps_next = dtrace_deferred_pid;
16032 help->dthps_prev = NULL;
16033 if (dtrace_deferred_pid != NULL)
16034 dtrace_deferred_pid->dthps_prev = help;
16035 dtrace_deferred_pid = help;
16038 mutex_exit(&dtrace_lock);
16040 } else if (dofhp != NULL) {
16042 * If the dtrace module is loaded and we have a particular
16043 * helper provider description, pass that off to the
16047 mutex_exit(&dtrace_lock);
16049 dtrace_helper_provide(dofhp, p->p_pid);
16053 * Otherwise, just pass all the helper provider descriptions
16054 * off to the meta provider.
16058 mutex_exit(&dtrace_lock);
16060 for (i = 0; i < help->dthps_nprovs; i++) {
16061 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
16066 mutex_exit(&dtrace_meta_lock);
16070 dtrace_helper_provider_add(dof_helper_t *dofhp, dtrace_helpers_t *help, int gen)
16072 dtrace_helper_provider_t *hprov, **tmp_provs;
16073 uint_t tmp_maxprovs, i;
16075 ASSERT(MUTEX_HELD(&dtrace_lock));
16076 ASSERT(help != NULL);
16079 * If we already have dtrace_helper_providers_max helper providers,
16080 * we're refuse to add a new one.
16082 if (help->dthps_nprovs >= dtrace_helper_providers_max)
16086 * Check to make sure this isn't a duplicate.
16088 for (i = 0; i < help->dthps_nprovs; i++) {
16089 if (dofhp->dofhp_addr ==
16090 help->dthps_provs[i]->dthp_prov.dofhp_addr)
16094 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
16095 hprov->dthp_prov = *dofhp;
16096 hprov->dthp_ref = 1;
16097 hprov->dthp_generation = gen;
16100 * Allocate a bigger table for helper providers if it's already full.
16102 if (help->dthps_maxprovs == help->dthps_nprovs) {
16103 tmp_maxprovs = help->dthps_maxprovs;
16104 tmp_provs = help->dthps_provs;
16106 if (help->dthps_maxprovs == 0)
16107 help->dthps_maxprovs = 2;
16109 help->dthps_maxprovs *= 2;
16110 if (help->dthps_maxprovs > dtrace_helper_providers_max)
16111 help->dthps_maxprovs = dtrace_helper_providers_max;
16113 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
16115 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
16116 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16118 if (tmp_provs != NULL) {
16119 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
16120 sizeof (dtrace_helper_provider_t *));
16121 kmem_free(tmp_provs, tmp_maxprovs *
16122 sizeof (dtrace_helper_provider_t *));
16126 help->dthps_provs[help->dthps_nprovs] = hprov;
16127 help->dthps_nprovs++;
16133 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
16135 mutex_enter(&dtrace_lock);
16137 if (--hprov->dthp_ref == 0) {
16139 mutex_exit(&dtrace_lock);
16140 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
16141 dtrace_dof_destroy(dof);
16142 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
16144 mutex_exit(&dtrace_lock);
16149 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
16151 uintptr_t daddr = (uintptr_t)dof;
16152 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
16153 dof_provider_t *provider;
16154 dof_probe_t *probe;
16156 char *strtab, *typestr;
16157 dof_stridx_t typeidx;
16159 uint_t nprobes, j, k;
16161 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
16163 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
16164 dtrace_dof_error(dof, "misaligned section offset");
16169 * The section needs to be large enough to contain the DOF provider
16170 * structure appropriate for the given version.
16172 if (sec->dofs_size <
16173 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
16174 offsetof(dof_provider_t, dofpv_prenoffs) :
16175 sizeof (dof_provider_t))) {
16176 dtrace_dof_error(dof, "provider section too small");
16180 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
16181 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
16182 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
16183 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
16184 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
16186 if (str_sec == NULL || prb_sec == NULL ||
16187 arg_sec == NULL || off_sec == NULL)
16192 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
16193 provider->dofpv_prenoffs != DOF_SECT_NONE &&
16194 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
16195 provider->dofpv_prenoffs)) == NULL)
16198 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
16200 if (provider->dofpv_name >= str_sec->dofs_size ||
16201 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
16202 dtrace_dof_error(dof, "invalid provider name");
16206 if (prb_sec->dofs_entsize == 0 ||
16207 prb_sec->dofs_entsize > prb_sec->dofs_size) {
16208 dtrace_dof_error(dof, "invalid entry size");
16212 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
16213 dtrace_dof_error(dof, "misaligned entry size");
16217 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
16218 dtrace_dof_error(dof, "invalid entry size");
16222 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
16223 dtrace_dof_error(dof, "misaligned section offset");
16227 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
16228 dtrace_dof_error(dof, "invalid entry size");
16232 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
16234 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
16237 * Take a pass through the probes to check for errors.
16239 for (j = 0; j < nprobes; j++) {
16240 probe = (dof_probe_t *)(uintptr_t)(daddr +
16241 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
16243 if (probe->dofpr_func >= str_sec->dofs_size) {
16244 dtrace_dof_error(dof, "invalid function name");
16248 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
16249 dtrace_dof_error(dof, "function name too long");
16251 * Keep going if the function name is too long.
16252 * Unlike provider and probe names, we cannot reasonably
16253 * impose restrictions on function names, since they're
16254 * a property of the code being instrumented. We will
16255 * skip this probe in dtrace_helper_provide_one().
16259 if (probe->dofpr_name >= str_sec->dofs_size ||
16260 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
16261 dtrace_dof_error(dof, "invalid probe name");
16266 * The offset count must not wrap the index, and the offsets
16267 * must also not overflow the section's data.
16269 if (probe->dofpr_offidx + probe->dofpr_noffs <
16270 probe->dofpr_offidx ||
16271 (probe->dofpr_offidx + probe->dofpr_noffs) *
16272 off_sec->dofs_entsize > off_sec->dofs_size) {
16273 dtrace_dof_error(dof, "invalid probe offset");
16277 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
16279 * If there's no is-enabled offset section, make sure
16280 * there aren't any is-enabled offsets. Otherwise
16281 * perform the same checks as for probe offsets
16282 * (immediately above).
16284 if (enoff_sec == NULL) {
16285 if (probe->dofpr_enoffidx != 0 ||
16286 probe->dofpr_nenoffs != 0) {
16287 dtrace_dof_error(dof, "is-enabled "
16288 "offsets with null section");
16291 } else if (probe->dofpr_enoffidx +
16292 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
16293 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
16294 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
16295 dtrace_dof_error(dof, "invalid is-enabled "
16300 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
16301 dtrace_dof_error(dof, "zero probe and "
16302 "is-enabled offsets");
16305 } else if (probe->dofpr_noffs == 0) {
16306 dtrace_dof_error(dof, "zero probe offsets");
16310 if (probe->dofpr_argidx + probe->dofpr_xargc <
16311 probe->dofpr_argidx ||
16312 (probe->dofpr_argidx + probe->dofpr_xargc) *
16313 arg_sec->dofs_entsize > arg_sec->dofs_size) {
16314 dtrace_dof_error(dof, "invalid args");
16318 typeidx = probe->dofpr_nargv;
16319 typestr = strtab + probe->dofpr_nargv;
16320 for (k = 0; k < probe->dofpr_nargc; k++) {
16321 if (typeidx >= str_sec->dofs_size) {
16322 dtrace_dof_error(dof, "bad "
16323 "native argument type");
16327 typesz = strlen(typestr) + 1;
16328 if (typesz > DTRACE_ARGTYPELEN) {
16329 dtrace_dof_error(dof, "native "
16330 "argument type too long");
16337 typeidx = probe->dofpr_xargv;
16338 typestr = strtab + probe->dofpr_xargv;
16339 for (k = 0; k < probe->dofpr_xargc; k++) {
16340 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
16341 dtrace_dof_error(dof, "bad "
16342 "native argument index");
16346 if (typeidx >= str_sec->dofs_size) {
16347 dtrace_dof_error(dof, "bad "
16348 "translated argument type");
16352 typesz = strlen(typestr) + 1;
16353 if (typesz > DTRACE_ARGTYPELEN) {
16354 dtrace_dof_error(dof, "translated argument "
16368 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp, struct proc *p)
16370 dtrace_helpers_t *help;
16371 dtrace_vstate_t *vstate;
16372 dtrace_enabling_t *enab = NULL;
16373 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
16374 uintptr_t daddr = (uintptr_t)dof;
16376 ASSERT(MUTEX_HELD(&dtrace_lock));
16378 if ((help = p->p_dtrace_helpers) == NULL)
16379 help = dtrace_helpers_create(p);
16381 vstate = &help->dthps_vstate;
16383 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab, dhp->dofhp_addr,
16384 dhp->dofhp_dof, B_FALSE)) != 0) {
16385 dtrace_dof_destroy(dof);
16390 * Look for helper providers and validate their descriptions.
16392 for (i = 0; i < dof->dofh_secnum; i++) {
16393 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
16394 dof->dofh_secoff + i * dof->dofh_secsize);
16396 if (sec->dofs_type != DOF_SECT_PROVIDER)
16399 if (dtrace_helper_provider_validate(dof, sec) != 0) {
16400 dtrace_enabling_destroy(enab);
16401 dtrace_dof_destroy(dof);
16409 * Now we need to walk through the ECB descriptions in the enabling.
16411 for (i = 0; i < enab->dten_ndesc; i++) {
16412 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
16413 dtrace_probedesc_t *desc = &ep->dted_probe;
16415 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
16418 if (strcmp(desc->dtpd_mod, "helper") != 0)
16421 if (strcmp(desc->dtpd_func, "ustack") != 0)
16424 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
16427 * Adding this helper action failed -- we are now going
16428 * to rip out the entire generation and return failure.
16430 (void) dtrace_helper_destroygen(help,
16431 help->dthps_generation);
16432 dtrace_enabling_destroy(enab);
16433 dtrace_dof_destroy(dof);
16440 if (nhelpers < enab->dten_ndesc)
16441 dtrace_dof_error(dof, "unmatched helpers");
16443 gen = help->dthps_generation++;
16444 dtrace_enabling_destroy(enab);
16448 * Now that this is in-kernel, we change the sense of the
16449 * members: dofhp_dof denotes the in-kernel copy of the DOF
16450 * and dofhp_addr denotes the address at user-level.
16452 dhp->dofhp_addr = dhp->dofhp_dof;
16453 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
16455 if (dtrace_helper_provider_add(dhp, help, gen) == 0) {
16456 mutex_exit(&dtrace_lock);
16457 dtrace_helper_provider_register(p, help, dhp);
16458 mutex_enter(&dtrace_lock);
16465 dtrace_dof_destroy(dof);
16470 static dtrace_helpers_t *
16471 dtrace_helpers_create(proc_t *p)
16473 dtrace_helpers_t *help;
16475 ASSERT(MUTEX_HELD(&dtrace_lock));
16476 ASSERT(p->p_dtrace_helpers == NULL);
16478 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
16479 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
16480 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
16482 p->p_dtrace_helpers = help;
16492 dtrace_helpers_destroy(proc_t *p)
16494 dtrace_helpers_t *help;
16495 dtrace_vstate_t *vstate;
16497 proc_t *p = curproc;
16501 mutex_enter(&dtrace_lock);
16503 ASSERT(p->p_dtrace_helpers != NULL);
16504 ASSERT(dtrace_helpers > 0);
16506 help = p->p_dtrace_helpers;
16507 vstate = &help->dthps_vstate;
16510 * We're now going to lose the help from this process.
16512 p->p_dtrace_helpers = NULL;
16516 * Destory the helper actions.
16518 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16519 dtrace_helper_action_t *h, *next;
16521 for (h = help->dthps_actions[i]; h != NULL; h = next) {
16522 next = h->dtha_next;
16523 dtrace_helper_action_destroy(h, vstate);
16528 mutex_exit(&dtrace_lock);
16531 * Destroy the helper providers.
16533 if (help->dthps_maxprovs > 0) {
16534 mutex_enter(&dtrace_meta_lock);
16535 if (dtrace_meta_pid != NULL) {
16536 ASSERT(dtrace_deferred_pid == NULL);
16538 for (i = 0; i < help->dthps_nprovs; i++) {
16539 dtrace_helper_provider_remove(
16540 &help->dthps_provs[i]->dthp_prov, p->p_pid);
16543 mutex_enter(&dtrace_lock);
16544 ASSERT(help->dthps_deferred == 0 ||
16545 help->dthps_next != NULL ||
16546 help->dthps_prev != NULL ||
16547 help == dtrace_deferred_pid);
16550 * Remove the helper from the deferred list.
16552 if (help->dthps_next != NULL)
16553 help->dthps_next->dthps_prev = help->dthps_prev;
16554 if (help->dthps_prev != NULL)
16555 help->dthps_prev->dthps_next = help->dthps_next;
16556 if (dtrace_deferred_pid == help) {
16557 dtrace_deferred_pid = help->dthps_next;
16558 ASSERT(help->dthps_prev == NULL);
16561 mutex_exit(&dtrace_lock);
16564 mutex_exit(&dtrace_meta_lock);
16566 for (i = 0; i < help->dthps_nprovs; i++) {
16567 dtrace_helper_provider_destroy(help->dthps_provs[i]);
16570 kmem_free(help->dthps_provs, help->dthps_maxprovs *
16571 sizeof (dtrace_helper_provider_t *));
16574 mutex_enter(&dtrace_lock);
16576 dtrace_vstate_fini(&help->dthps_vstate);
16577 kmem_free(help->dthps_actions,
16578 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16579 kmem_free(help, sizeof (dtrace_helpers_t));
16582 mutex_exit(&dtrace_lock);
16589 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16591 dtrace_helpers_t *help, *newhelp;
16592 dtrace_helper_action_t *helper, *new, *last;
16594 dtrace_vstate_t *vstate;
16595 int i, j, sz, hasprovs = 0;
16597 mutex_enter(&dtrace_lock);
16598 ASSERT(from->p_dtrace_helpers != NULL);
16599 ASSERT(dtrace_helpers > 0);
16601 help = from->p_dtrace_helpers;
16602 newhelp = dtrace_helpers_create(to);
16603 ASSERT(to->p_dtrace_helpers != NULL);
16605 newhelp->dthps_generation = help->dthps_generation;
16606 vstate = &newhelp->dthps_vstate;
16609 * Duplicate the helper actions.
16611 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16612 if ((helper = help->dthps_actions[i]) == NULL)
16615 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16616 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16618 new->dtha_generation = helper->dtha_generation;
16620 if ((dp = helper->dtha_predicate) != NULL) {
16621 dp = dtrace_difo_duplicate(dp, vstate);
16622 new->dtha_predicate = dp;
16625 new->dtha_nactions = helper->dtha_nactions;
16626 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16627 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16629 for (j = 0; j < new->dtha_nactions; j++) {
16630 dtrace_difo_t *dp = helper->dtha_actions[j];
16632 ASSERT(dp != NULL);
16633 dp = dtrace_difo_duplicate(dp, vstate);
16634 new->dtha_actions[j] = dp;
16637 if (last != NULL) {
16638 last->dtha_next = new;
16640 newhelp->dthps_actions[i] = new;
16648 * Duplicate the helper providers and register them with the
16649 * DTrace framework.
16651 if (help->dthps_nprovs > 0) {
16652 newhelp->dthps_nprovs = help->dthps_nprovs;
16653 newhelp->dthps_maxprovs = help->dthps_nprovs;
16654 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16655 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16656 for (i = 0; i < newhelp->dthps_nprovs; i++) {
16657 newhelp->dthps_provs[i] = help->dthps_provs[i];
16658 newhelp->dthps_provs[i]->dthp_ref++;
16664 mutex_exit(&dtrace_lock);
16667 dtrace_helper_provider_register(to, newhelp, NULL);
16671 * DTrace Hook Functions
16674 dtrace_module_loaded(modctl_t *ctl)
16676 dtrace_provider_t *prv;
16678 mutex_enter(&dtrace_provider_lock);
16680 mutex_enter(&mod_lock);
16684 ASSERT(ctl->mod_busy);
16688 * We're going to call each providers per-module provide operation
16689 * specifying only this module.
16691 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16692 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16695 mutex_exit(&mod_lock);
16697 mutex_exit(&dtrace_provider_lock);
16700 * If we have any retained enablings, we need to match against them.
16701 * Enabling probes requires that cpu_lock be held, and we cannot hold
16702 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16703 * module. (In particular, this happens when loading scheduling
16704 * classes.) So if we have any retained enablings, we need to dispatch
16705 * our task queue to do the match for us.
16707 mutex_enter(&dtrace_lock);
16709 if (dtrace_retained == NULL) {
16710 mutex_exit(&dtrace_lock);
16714 (void) taskq_dispatch(dtrace_taskq,
16715 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16717 mutex_exit(&dtrace_lock);
16720 * And now, for a little heuristic sleaze: in general, we want to
16721 * match modules as soon as they load. However, we cannot guarantee
16722 * this, because it would lead us to the lock ordering violation
16723 * outlined above. The common case, of course, is that cpu_lock is
16724 * _not_ held -- so we delay here for a clock tick, hoping that that's
16725 * long enough for the task queue to do its work. If it's not, it's
16726 * not a serious problem -- it just means that the module that we
16727 * just loaded may not be immediately instrumentable.
16734 dtrace_module_unloaded(modctl_t *ctl)
16736 dtrace_module_unloaded(modctl_t *ctl, int *error)
16739 dtrace_probe_t template, *probe, *first, *next;
16740 dtrace_provider_t *prov;
16742 char modname[DTRACE_MODNAMELEN];
16747 template.dtpr_mod = ctl->mod_modname;
16749 /* Handle the fact that ctl->filename may end in ".ko". */
16750 strlcpy(modname, ctl->filename, sizeof(modname));
16751 len = strlen(ctl->filename);
16752 if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
16753 modname[len - 3] = '\0';
16754 template.dtpr_mod = modname;
16757 mutex_enter(&dtrace_provider_lock);
16759 mutex_enter(&mod_lock);
16761 mutex_enter(&dtrace_lock);
16764 if (ctl->nenabled > 0) {
16765 /* Don't allow unloads if a probe is enabled. */
16766 mutex_exit(&dtrace_provider_lock);
16767 mutex_exit(&dtrace_lock);
16770 "kldunload: attempt to unload module that has DTrace probes enabled\n");
16775 if (dtrace_bymod == NULL) {
16777 * The DTrace module is loaded (obviously) but not attached;
16778 * we don't have any work to do.
16780 mutex_exit(&dtrace_provider_lock);
16782 mutex_exit(&mod_lock);
16784 mutex_exit(&dtrace_lock);
16788 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16789 probe != NULL; probe = probe->dtpr_nextmod) {
16790 if (probe->dtpr_ecb != NULL) {
16791 mutex_exit(&dtrace_provider_lock);
16793 mutex_exit(&mod_lock);
16795 mutex_exit(&dtrace_lock);
16798 * This shouldn't _actually_ be possible -- we're
16799 * unloading a module that has an enabled probe in it.
16800 * (It's normally up to the provider to make sure that
16801 * this can't happen.) However, because dtps_enable()
16802 * doesn't have a failure mode, there can be an
16803 * enable/unload race. Upshot: we don't want to
16804 * assert, but we're not going to disable the
16807 if (dtrace_err_verbose) {
16809 cmn_err(CE_WARN, "unloaded module '%s' had "
16810 "enabled probes", ctl->mod_modname);
16812 cmn_err(CE_WARN, "unloaded module '%s' had "
16813 "enabled probes", modname);
16823 for (first = NULL; probe != NULL; probe = next) {
16824 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16826 dtrace_probes[probe->dtpr_id - 1] = NULL;
16828 next = probe->dtpr_nextmod;
16829 dtrace_hash_remove(dtrace_bymod, probe);
16830 dtrace_hash_remove(dtrace_byfunc, probe);
16831 dtrace_hash_remove(dtrace_byname, probe);
16833 if (first == NULL) {
16835 probe->dtpr_nextmod = NULL;
16837 probe->dtpr_nextmod = first;
16843 * We've removed all of the module's probes from the hash chains and
16844 * from the probe array. Now issue a dtrace_sync() to be sure that
16845 * everyone has cleared out from any probe array processing.
16849 for (probe = first; probe != NULL; probe = first) {
16850 first = probe->dtpr_nextmod;
16851 prov = probe->dtpr_provider;
16852 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16854 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16855 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16856 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16858 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16860 free_unr(dtrace_arena, probe->dtpr_id);
16862 kmem_free(probe, sizeof (dtrace_probe_t));
16865 mutex_exit(&dtrace_lock);
16867 mutex_exit(&mod_lock);
16869 mutex_exit(&dtrace_provider_lock);
16874 dtrace_kld_load(void *arg __unused, linker_file_t lf)
16877 dtrace_module_loaded(lf);
16881 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
16885 /* We already have an error, so don't do anything. */
16887 dtrace_module_unloaded(lf, error);
16893 dtrace_suspend(void)
16895 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16899 dtrace_resume(void)
16901 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16906 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16908 ASSERT(MUTEX_HELD(&cpu_lock));
16909 mutex_enter(&dtrace_lock);
16913 dtrace_state_t *state;
16914 dtrace_optval_t *opt, rs, c;
16917 * For now, we only allocate a new buffer for anonymous state.
16919 if ((state = dtrace_anon.dta_state) == NULL)
16922 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16925 opt = state->dts_options;
16926 c = opt[DTRACEOPT_CPU];
16928 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16932 * Regardless of what the actual policy is, we're going to
16933 * temporarily set our resize policy to be manual. We're
16934 * also going to temporarily set our CPU option to denote
16935 * the newly configured CPU.
16937 rs = opt[DTRACEOPT_BUFRESIZE];
16938 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16939 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16941 (void) dtrace_state_buffers(state);
16943 opt[DTRACEOPT_BUFRESIZE] = rs;
16944 opt[DTRACEOPT_CPU] = c;
16951 * We don't free the buffer in the CPU_UNCONFIG case. (The
16952 * buffer will be freed when the consumer exits.)
16960 mutex_exit(&dtrace_lock);
16966 dtrace_cpu_setup_initial(processorid_t cpu)
16968 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16973 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16975 if (dtrace_toxranges >= dtrace_toxranges_max) {
16977 dtrace_toxrange_t *range;
16979 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16982 ASSERT(dtrace_toxrange == NULL);
16983 ASSERT(dtrace_toxranges_max == 0);
16984 dtrace_toxranges_max = 1;
16986 dtrace_toxranges_max <<= 1;
16989 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16990 range = kmem_zalloc(nsize, KM_SLEEP);
16992 if (dtrace_toxrange != NULL) {
16993 ASSERT(osize != 0);
16994 bcopy(dtrace_toxrange, range, osize);
16995 kmem_free(dtrace_toxrange, osize);
16998 dtrace_toxrange = range;
17001 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
17002 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
17004 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
17005 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
17006 dtrace_toxranges++;
17010 dtrace_getf_barrier()
17014 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
17015 * that contain calls to getf(), this routine will be called on every
17016 * closef() before either the underlying vnode is released or the
17017 * file_t itself is freed. By the time we are here, it is essential
17018 * that the file_t can no longer be accessed from a call to getf()
17019 * in probe context -- that assures that a dtrace_sync() can be used
17020 * to clear out any enablings referring to the old structures.
17022 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
17023 kcred->cr_zone->zone_dtrace_getf != 0)
17029 * DTrace Driver Cookbook Functions
17034 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
17036 dtrace_provider_id_t id;
17037 dtrace_state_t *state = NULL;
17038 dtrace_enabling_t *enab;
17040 mutex_enter(&cpu_lock);
17041 mutex_enter(&dtrace_provider_lock);
17042 mutex_enter(&dtrace_lock);
17044 if (ddi_soft_state_init(&dtrace_softstate,
17045 sizeof (dtrace_state_t), 0) != 0) {
17046 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
17047 mutex_exit(&cpu_lock);
17048 mutex_exit(&dtrace_provider_lock);
17049 mutex_exit(&dtrace_lock);
17050 return (DDI_FAILURE);
17053 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
17054 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
17055 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
17056 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
17057 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
17058 ddi_remove_minor_node(devi, NULL);
17059 ddi_soft_state_fini(&dtrace_softstate);
17060 mutex_exit(&cpu_lock);
17061 mutex_exit(&dtrace_provider_lock);
17062 mutex_exit(&dtrace_lock);
17063 return (DDI_FAILURE);
17066 ddi_report_dev(devi);
17067 dtrace_devi = devi;
17069 dtrace_modload = dtrace_module_loaded;
17070 dtrace_modunload = dtrace_module_unloaded;
17071 dtrace_cpu_init = dtrace_cpu_setup_initial;
17072 dtrace_helpers_cleanup = dtrace_helpers_destroy;
17073 dtrace_helpers_fork = dtrace_helpers_duplicate;
17074 dtrace_cpustart_init = dtrace_suspend;
17075 dtrace_cpustart_fini = dtrace_resume;
17076 dtrace_debugger_init = dtrace_suspend;
17077 dtrace_debugger_fini = dtrace_resume;
17079 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17081 ASSERT(MUTEX_HELD(&cpu_lock));
17083 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
17084 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
17085 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
17086 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
17087 VM_SLEEP | VMC_IDENTIFIER);
17088 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
17091 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
17092 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
17093 NULL, NULL, NULL, NULL, NULL, 0);
17095 ASSERT(MUTEX_HELD(&cpu_lock));
17096 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
17097 offsetof(dtrace_probe_t, dtpr_nextmod),
17098 offsetof(dtrace_probe_t, dtpr_prevmod));
17100 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
17101 offsetof(dtrace_probe_t, dtpr_nextfunc),
17102 offsetof(dtrace_probe_t, dtpr_prevfunc));
17104 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
17105 offsetof(dtrace_probe_t, dtpr_nextname),
17106 offsetof(dtrace_probe_t, dtpr_prevname));
17108 if (dtrace_retain_max < 1) {
17109 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
17110 "setting to 1", dtrace_retain_max);
17111 dtrace_retain_max = 1;
17115 * Now discover our toxic ranges.
17117 dtrace_toxic_ranges(dtrace_toxrange_add);
17120 * Before we register ourselves as a provider to our own framework,
17121 * we would like to assert that dtrace_provider is NULL -- but that's
17122 * not true if we were loaded as a dependency of a DTrace provider.
17123 * Once we've registered, we can assert that dtrace_provider is our
17126 (void) dtrace_register("dtrace", &dtrace_provider_attr,
17127 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
17129 ASSERT(dtrace_provider != NULL);
17130 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
17132 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
17133 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
17134 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
17135 dtrace_provider, NULL, NULL, "END", 0, NULL);
17136 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
17137 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
17139 dtrace_anon_property();
17140 mutex_exit(&cpu_lock);
17143 * If there are already providers, we must ask them to provide their
17144 * probes, and then match any anonymous enabling against them. Note
17145 * that there should be no other retained enablings at this time:
17146 * the only retained enablings at this time should be the anonymous
17149 if (dtrace_anon.dta_enabling != NULL) {
17150 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
17152 dtrace_enabling_provide(NULL);
17153 state = dtrace_anon.dta_state;
17156 * We couldn't hold cpu_lock across the above call to
17157 * dtrace_enabling_provide(), but we must hold it to actually
17158 * enable the probes. We have to drop all of our locks, pick
17159 * up cpu_lock, and regain our locks before matching the
17160 * retained anonymous enabling.
17162 mutex_exit(&dtrace_lock);
17163 mutex_exit(&dtrace_provider_lock);
17165 mutex_enter(&cpu_lock);
17166 mutex_enter(&dtrace_provider_lock);
17167 mutex_enter(&dtrace_lock);
17169 if ((enab = dtrace_anon.dta_enabling) != NULL)
17170 (void) dtrace_enabling_match(enab, NULL);
17172 mutex_exit(&cpu_lock);
17175 mutex_exit(&dtrace_lock);
17176 mutex_exit(&dtrace_provider_lock);
17178 if (state != NULL) {
17180 * If we created any anonymous state, set it going now.
17182 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17185 return (DDI_SUCCESS);
17187 #endif /* illumos */
17190 static void dtrace_dtr(void *);
17196 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17198 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
17201 dtrace_state_t *state;
17207 if (getminor(*devp) == DTRACEMNRN_HELPER)
17211 * If this wasn't an open with the "helper" minor, then it must be
17212 * the "dtrace" minor.
17214 if (getminor(*devp) == DTRACEMNRN_DTRACE)
17217 cred_t *cred_p = NULL;
17218 cred_p = dev->si_cred;
17221 * If no DTRACE_PRIV_* bits are set in the credential, then the
17222 * caller lacks sufficient permission to do anything with DTrace.
17224 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17225 if (priv == DTRACE_PRIV_NONE) {
17232 * Ask all providers to provide all their probes.
17234 mutex_enter(&dtrace_provider_lock);
17235 dtrace_probe_provide(NULL, NULL);
17236 mutex_exit(&dtrace_provider_lock);
17238 mutex_enter(&cpu_lock);
17239 mutex_enter(&dtrace_lock);
17241 dtrace_membar_producer();
17245 * If the kernel debugger is active (that is, if the kernel debugger
17246 * modified text in some way), we won't allow the open.
17248 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17250 mutex_exit(&cpu_lock);
17251 mutex_exit(&dtrace_lock);
17255 if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
17257 * If DTrace helper tracing is enabled, we need to allocate the
17258 * trace buffer and initialize the values.
17260 dtrace_helptrace_buffer =
17261 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
17262 dtrace_helptrace_next = 0;
17263 dtrace_helptrace_wrapped = 0;
17264 dtrace_helptrace_enable = 0;
17267 state = dtrace_state_create(devp, cred_p);
17269 state = dtrace_state_create(dev, NULL);
17270 devfs_set_cdevpriv(state, dtrace_dtr);
17273 mutex_exit(&cpu_lock);
17275 if (state == NULL) {
17277 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17278 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17282 mutex_exit(&dtrace_lock);
17286 mutex_exit(&dtrace_lock);
17294 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17297 dtrace_dtr(void *data)
17301 minor_t minor = getminor(dev);
17302 dtrace_state_t *state;
17304 dtrace_helptrace_t *buf = NULL;
17307 if (minor == DTRACEMNRN_HELPER)
17310 state = ddi_get_soft_state(dtrace_softstate, minor);
17312 dtrace_state_t *state = data;
17315 mutex_enter(&cpu_lock);
17316 mutex_enter(&dtrace_lock);
17319 if (state->dts_anon)
17321 if (state != NULL && state->dts_anon)
17325 * There is anonymous state. Destroy that first.
17327 ASSERT(dtrace_anon.dta_state == NULL);
17328 dtrace_state_destroy(state->dts_anon);
17331 if (dtrace_helptrace_disable) {
17333 * If we have been told to disable helper tracing, set the
17334 * buffer to NULL before calling into dtrace_state_destroy();
17335 * we take advantage of its dtrace_sync() to know that no
17336 * CPU is in probe context with enabled helper tracing
17337 * after it returns.
17339 buf = dtrace_helptrace_buffer;
17340 dtrace_helptrace_buffer = NULL;
17344 dtrace_state_destroy(state);
17346 if (state != NULL) {
17347 dtrace_state_destroy(state);
17348 kmem_free(state, 0);
17351 ASSERT(dtrace_opens > 0);
17355 * Only relinquish control of the kernel debugger interface when there
17356 * are no consumers and no anonymous enablings.
17358 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17359 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17365 kmem_free(buf, dtrace_helptrace_bufsize);
17366 dtrace_helptrace_disable = 0;
17369 mutex_exit(&dtrace_lock);
17370 mutex_exit(&cpu_lock);
17380 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17383 dof_helper_t help, *dhp = NULL;
17386 case DTRACEHIOC_ADDDOF:
17387 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17388 dtrace_dof_error(NULL, "failed to copyin DOF helper");
17393 arg = (intptr_t)help.dofhp_dof;
17396 case DTRACEHIOC_ADD: {
17397 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17402 mutex_enter(&dtrace_lock);
17405 * dtrace_helper_slurp() takes responsibility for the dof --
17406 * it may free it now or it may save it and free it later.
17408 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17415 mutex_exit(&dtrace_lock);
17419 case DTRACEHIOC_REMOVE: {
17420 mutex_enter(&dtrace_lock);
17421 rval = dtrace_helper_destroygen(NULL, arg);
17422 mutex_exit(&dtrace_lock);
17436 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17438 minor_t minor = getminor(dev);
17439 dtrace_state_t *state;
17442 if (minor == DTRACEMNRN_HELPER)
17443 return (dtrace_ioctl_helper(cmd, arg, rv));
17445 state = ddi_get_soft_state(dtrace_softstate, minor);
17447 if (state->dts_anon) {
17448 ASSERT(dtrace_anon.dta_state == NULL);
17449 state = state->dts_anon;
17453 case DTRACEIOC_PROVIDER: {
17454 dtrace_providerdesc_t pvd;
17455 dtrace_provider_t *pvp;
17457 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17460 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17461 mutex_enter(&dtrace_provider_lock);
17463 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17464 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17468 mutex_exit(&dtrace_provider_lock);
17473 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17474 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17476 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17482 case DTRACEIOC_EPROBE: {
17483 dtrace_eprobedesc_t epdesc;
17485 dtrace_action_t *act;
17491 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17494 mutex_enter(&dtrace_lock);
17496 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17497 mutex_exit(&dtrace_lock);
17501 if (ecb->dte_probe == NULL) {
17502 mutex_exit(&dtrace_lock);
17506 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17507 epdesc.dtepd_uarg = ecb->dte_uarg;
17508 epdesc.dtepd_size = ecb->dte_size;
17510 nrecs = epdesc.dtepd_nrecs;
17511 epdesc.dtepd_nrecs = 0;
17512 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17513 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17516 epdesc.dtepd_nrecs++;
17520 * Now that we have the size, we need to allocate a temporary
17521 * buffer in which to store the complete description. We need
17522 * the temporary buffer to be able to drop dtrace_lock()
17523 * across the copyout(), below.
17525 size = sizeof (dtrace_eprobedesc_t) +
17526 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17528 buf = kmem_alloc(size, KM_SLEEP);
17529 dest = (uintptr_t)buf;
17531 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17532 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17534 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17535 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17541 bcopy(&act->dta_rec, (void *)dest,
17542 sizeof (dtrace_recdesc_t));
17543 dest += sizeof (dtrace_recdesc_t);
17546 mutex_exit(&dtrace_lock);
17548 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17549 kmem_free(buf, size);
17553 kmem_free(buf, size);
17557 case DTRACEIOC_AGGDESC: {
17558 dtrace_aggdesc_t aggdesc;
17559 dtrace_action_t *act;
17560 dtrace_aggregation_t *agg;
17563 dtrace_recdesc_t *lrec;
17568 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17571 mutex_enter(&dtrace_lock);
17573 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17574 mutex_exit(&dtrace_lock);
17578 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17580 nrecs = aggdesc.dtagd_nrecs;
17581 aggdesc.dtagd_nrecs = 0;
17583 offs = agg->dtag_base;
17584 lrec = &agg->dtag_action.dta_rec;
17585 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17587 for (act = agg->dtag_first; ; act = act->dta_next) {
17588 ASSERT(act->dta_intuple ||
17589 DTRACEACT_ISAGG(act->dta_kind));
17592 * If this action has a record size of zero, it
17593 * denotes an argument to the aggregating action.
17594 * Because the presence of this record doesn't (or
17595 * shouldn't) affect the way the data is interpreted,
17596 * we don't copy it out to save user-level the
17597 * confusion of dealing with a zero-length record.
17599 if (act->dta_rec.dtrd_size == 0) {
17600 ASSERT(agg->dtag_hasarg);
17604 aggdesc.dtagd_nrecs++;
17606 if (act == &agg->dtag_action)
17611 * Now that we have the size, we need to allocate a temporary
17612 * buffer in which to store the complete description. We need
17613 * the temporary buffer to be able to drop dtrace_lock()
17614 * across the copyout(), below.
17616 size = sizeof (dtrace_aggdesc_t) +
17617 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17619 buf = kmem_alloc(size, KM_SLEEP);
17620 dest = (uintptr_t)buf;
17622 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17623 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17625 for (act = agg->dtag_first; ; act = act->dta_next) {
17626 dtrace_recdesc_t rec = act->dta_rec;
17629 * See the comment in the above loop for why we pass
17630 * over zero-length records.
17632 if (rec.dtrd_size == 0) {
17633 ASSERT(agg->dtag_hasarg);
17640 rec.dtrd_offset -= offs;
17641 bcopy(&rec, (void *)dest, sizeof (rec));
17642 dest += sizeof (dtrace_recdesc_t);
17644 if (act == &agg->dtag_action)
17648 mutex_exit(&dtrace_lock);
17650 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17651 kmem_free(buf, size);
17655 kmem_free(buf, size);
17659 case DTRACEIOC_ENABLE: {
17661 dtrace_enabling_t *enab = NULL;
17662 dtrace_vstate_t *vstate;
17668 * If a NULL argument has been passed, we take this as our
17669 * cue to reevaluate our enablings.
17672 dtrace_enabling_matchall();
17677 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17680 mutex_enter(&cpu_lock);
17681 mutex_enter(&dtrace_lock);
17682 vstate = &state->dts_vstate;
17684 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17685 mutex_exit(&dtrace_lock);
17686 mutex_exit(&cpu_lock);
17687 dtrace_dof_destroy(dof);
17691 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17692 mutex_exit(&dtrace_lock);
17693 mutex_exit(&cpu_lock);
17694 dtrace_dof_destroy(dof);
17698 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17699 dtrace_enabling_destroy(enab);
17700 mutex_exit(&dtrace_lock);
17701 mutex_exit(&cpu_lock);
17702 dtrace_dof_destroy(dof);
17706 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17707 err = dtrace_enabling_retain(enab);
17709 dtrace_enabling_destroy(enab);
17712 mutex_exit(&cpu_lock);
17713 mutex_exit(&dtrace_lock);
17714 dtrace_dof_destroy(dof);
17719 case DTRACEIOC_REPLICATE: {
17720 dtrace_repldesc_t desc;
17721 dtrace_probedesc_t *match = &desc.dtrpd_match;
17722 dtrace_probedesc_t *create = &desc.dtrpd_create;
17725 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17728 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17729 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17730 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17731 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17733 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17734 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17735 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17736 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17738 mutex_enter(&dtrace_lock);
17739 err = dtrace_enabling_replicate(state, match, create);
17740 mutex_exit(&dtrace_lock);
17745 case DTRACEIOC_PROBEMATCH:
17746 case DTRACEIOC_PROBES: {
17747 dtrace_probe_t *probe = NULL;
17748 dtrace_probedesc_t desc;
17749 dtrace_probekey_t pkey;
17756 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17759 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17760 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17761 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17762 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17765 * Before we attempt to match this probe, we want to give
17766 * all providers the opportunity to provide it.
17768 if (desc.dtpd_id == DTRACE_IDNONE) {
17769 mutex_enter(&dtrace_provider_lock);
17770 dtrace_probe_provide(&desc, NULL);
17771 mutex_exit(&dtrace_provider_lock);
17775 if (cmd == DTRACEIOC_PROBEMATCH) {
17776 dtrace_probekey(&desc, &pkey);
17777 pkey.dtpk_id = DTRACE_IDNONE;
17780 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17782 mutex_enter(&dtrace_lock);
17784 if (cmd == DTRACEIOC_PROBEMATCH) {
17785 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17786 if ((probe = dtrace_probes[i - 1]) != NULL &&
17787 (m = dtrace_match_probe(probe, &pkey,
17788 priv, uid, zoneid)) != 0)
17793 mutex_exit(&dtrace_lock);
17798 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17799 if ((probe = dtrace_probes[i - 1]) != NULL &&
17800 dtrace_match_priv(probe, priv, uid, zoneid))
17805 if (probe == NULL) {
17806 mutex_exit(&dtrace_lock);
17810 dtrace_probe_description(probe, &desc);
17811 mutex_exit(&dtrace_lock);
17813 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17819 case DTRACEIOC_PROBEARG: {
17820 dtrace_argdesc_t desc;
17821 dtrace_probe_t *probe;
17822 dtrace_provider_t *prov;
17824 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17827 if (desc.dtargd_id == DTRACE_IDNONE)
17830 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17833 mutex_enter(&dtrace_provider_lock);
17834 mutex_enter(&mod_lock);
17835 mutex_enter(&dtrace_lock);
17837 if (desc.dtargd_id > dtrace_nprobes) {
17838 mutex_exit(&dtrace_lock);
17839 mutex_exit(&mod_lock);
17840 mutex_exit(&dtrace_provider_lock);
17844 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17845 mutex_exit(&dtrace_lock);
17846 mutex_exit(&mod_lock);
17847 mutex_exit(&dtrace_provider_lock);
17851 mutex_exit(&dtrace_lock);
17853 prov = probe->dtpr_provider;
17855 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17857 * There isn't any typed information for this probe.
17858 * Set the argument number to DTRACE_ARGNONE.
17860 desc.dtargd_ndx = DTRACE_ARGNONE;
17862 desc.dtargd_native[0] = '\0';
17863 desc.dtargd_xlate[0] = '\0';
17864 desc.dtargd_mapping = desc.dtargd_ndx;
17866 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17867 probe->dtpr_id, probe->dtpr_arg, &desc);
17870 mutex_exit(&mod_lock);
17871 mutex_exit(&dtrace_provider_lock);
17873 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17879 case DTRACEIOC_GO: {
17880 processorid_t cpuid;
17881 rval = dtrace_state_go(state, &cpuid);
17886 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17892 case DTRACEIOC_STOP: {
17893 processorid_t cpuid;
17895 mutex_enter(&dtrace_lock);
17896 rval = dtrace_state_stop(state, &cpuid);
17897 mutex_exit(&dtrace_lock);
17902 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17908 case DTRACEIOC_DOFGET: {
17909 dof_hdr_t hdr, *dof;
17912 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17915 mutex_enter(&dtrace_lock);
17916 dof = dtrace_dof_create(state);
17917 mutex_exit(&dtrace_lock);
17919 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17920 rval = copyout(dof, (void *)arg, len);
17921 dtrace_dof_destroy(dof);
17923 return (rval == 0 ? 0 : EFAULT);
17926 case DTRACEIOC_AGGSNAP:
17927 case DTRACEIOC_BUFSNAP: {
17928 dtrace_bufdesc_t desc;
17930 dtrace_buffer_t *buf;
17932 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17935 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17938 mutex_enter(&dtrace_lock);
17940 if (cmd == DTRACEIOC_BUFSNAP) {
17941 buf = &state->dts_buffer[desc.dtbd_cpu];
17943 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17946 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17947 size_t sz = buf->dtb_offset;
17949 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17950 mutex_exit(&dtrace_lock);
17955 * If this buffer has already been consumed, we're
17956 * going to indicate that there's nothing left here
17959 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17960 mutex_exit(&dtrace_lock);
17962 desc.dtbd_size = 0;
17963 desc.dtbd_drops = 0;
17964 desc.dtbd_errors = 0;
17965 desc.dtbd_oldest = 0;
17966 sz = sizeof (desc);
17968 if (copyout(&desc, (void *)arg, sz) != 0)
17975 * If this is a ring buffer that has wrapped, we want
17976 * to copy the whole thing out.
17978 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17979 dtrace_buffer_polish(buf);
17980 sz = buf->dtb_size;
17983 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17984 mutex_exit(&dtrace_lock);
17988 desc.dtbd_size = sz;
17989 desc.dtbd_drops = buf->dtb_drops;
17990 desc.dtbd_errors = buf->dtb_errors;
17991 desc.dtbd_oldest = buf->dtb_xamot_offset;
17992 desc.dtbd_timestamp = dtrace_gethrtime();
17994 mutex_exit(&dtrace_lock);
17996 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17999 buf->dtb_flags |= DTRACEBUF_CONSUMED;
18004 if (buf->dtb_tomax == NULL) {
18005 ASSERT(buf->dtb_xamot == NULL);
18006 mutex_exit(&dtrace_lock);
18010 cached = buf->dtb_tomax;
18011 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18013 dtrace_xcall(desc.dtbd_cpu,
18014 (dtrace_xcall_t)dtrace_buffer_switch, buf);
18016 state->dts_errors += buf->dtb_xamot_errors;
18019 * If the buffers did not actually switch, then the cross call
18020 * did not take place -- presumably because the given CPU is
18021 * not in the ready set. If this is the case, we'll return
18024 if (buf->dtb_tomax == cached) {
18025 ASSERT(buf->dtb_xamot != cached);
18026 mutex_exit(&dtrace_lock);
18030 ASSERT(cached == buf->dtb_xamot);
18033 * We have our snapshot; now copy it out.
18035 if (copyout(buf->dtb_xamot, desc.dtbd_data,
18036 buf->dtb_xamot_offset) != 0) {
18037 mutex_exit(&dtrace_lock);
18041 desc.dtbd_size = buf->dtb_xamot_offset;
18042 desc.dtbd_drops = buf->dtb_xamot_drops;
18043 desc.dtbd_errors = buf->dtb_xamot_errors;
18044 desc.dtbd_oldest = 0;
18045 desc.dtbd_timestamp = buf->dtb_switched;
18047 mutex_exit(&dtrace_lock);
18050 * Finally, copy out the buffer description.
18052 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
18058 case DTRACEIOC_CONF: {
18059 dtrace_conf_t conf;
18061 bzero(&conf, sizeof (conf));
18062 conf.dtc_difversion = DIF_VERSION;
18063 conf.dtc_difintregs = DIF_DIR_NREGS;
18064 conf.dtc_diftupregs = DIF_DTR_NREGS;
18065 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18067 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
18073 case DTRACEIOC_STATUS: {
18074 dtrace_status_t stat;
18075 dtrace_dstate_t *dstate;
18080 * See the comment in dtrace_state_deadman() for the reason
18081 * for setting dts_laststatus to INT64_MAX before setting
18082 * it to the correct value.
18084 state->dts_laststatus = INT64_MAX;
18085 dtrace_membar_producer();
18086 state->dts_laststatus = dtrace_gethrtime();
18088 bzero(&stat, sizeof (stat));
18090 mutex_enter(&dtrace_lock);
18092 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18093 mutex_exit(&dtrace_lock);
18097 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18098 stat.dtst_exiting = 1;
18100 nerrs = state->dts_errors;
18101 dstate = &state->dts_vstate.dtvs_dynvars;
18103 for (i = 0; i < NCPU; i++) {
18104 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18106 stat.dtst_dyndrops += dcpu->dtdsc_drops;
18107 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18108 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18110 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18111 stat.dtst_filled++;
18113 nerrs += state->dts_buffer[i].dtb_errors;
18115 for (j = 0; j < state->dts_nspeculations; j++) {
18116 dtrace_speculation_t *spec;
18117 dtrace_buffer_t *buf;
18119 spec = &state->dts_speculations[j];
18120 buf = &spec->dtsp_buffer[i];
18121 stat.dtst_specdrops += buf->dtb_xamot_drops;
18125 stat.dtst_specdrops_busy = state->dts_speculations_busy;
18126 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18127 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18128 stat.dtst_dblerrors = state->dts_dblerrors;
18130 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18131 stat.dtst_errors = nerrs;
18133 mutex_exit(&dtrace_lock);
18135 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18141 case DTRACEIOC_FORMAT: {
18142 dtrace_fmtdesc_t fmt;
18146 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18149 mutex_enter(&dtrace_lock);
18151 if (fmt.dtfd_format == 0 ||
18152 fmt.dtfd_format > state->dts_nformats) {
18153 mutex_exit(&dtrace_lock);
18158 * Format strings are allocated contiguously and they are
18159 * never freed; if a format index is less than the number
18160 * of formats, we can assert that the format map is non-NULL
18161 * and that the format for the specified index is non-NULL.
18163 ASSERT(state->dts_formats != NULL);
18164 str = state->dts_formats[fmt.dtfd_format - 1];
18165 ASSERT(str != NULL);
18167 len = strlen(str) + 1;
18169 if (len > fmt.dtfd_length) {
18170 fmt.dtfd_length = len;
18172 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18173 mutex_exit(&dtrace_lock);
18177 if (copyout(str, fmt.dtfd_string, len) != 0) {
18178 mutex_exit(&dtrace_lock);
18183 mutex_exit(&dtrace_lock);
18196 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
18198 dtrace_state_t *state;
18205 return (DDI_SUCCESS);
18208 return (DDI_FAILURE);
18211 mutex_enter(&cpu_lock);
18212 mutex_enter(&dtrace_provider_lock);
18213 mutex_enter(&dtrace_lock);
18215 ASSERT(dtrace_opens == 0);
18217 if (dtrace_helpers > 0) {
18218 mutex_exit(&dtrace_provider_lock);
18219 mutex_exit(&dtrace_lock);
18220 mutex_exit(&cpu_lock);
18221 return (DDI_FAILURE);
18224 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
18225 mutex_exit(&dtrace_provider_lock);
18226 mutex_exit(&dtrace_lock);
18227 mutex_exit(&cpu_lock);
18228 return (DDI_FAILURE);
18231 dtrace_provider = NULL;
18233 if ((state = dtrace_anon_grab()) != NULL) {
18235 * If there were ECBs on this state, the provider should
18236 * have not been allowed to detach; assert that there is
18239 ASSERT(state->dts_necbs == 0);
18240 dtrace_state_destroy(state);
18243 * If we're being detached with anonymous state, we need to
18244 * indicate to the kernel debugger that DTrace is now inactive.
18246 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
18249 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
18250 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
18251 dtrace_cpu_init = NULL;
18252 dtrace_helpers_cleanup = NULL;
18253 dtrace_helpers_fork = NULL;
18254 dtrace_cpustart_init = NULL;
18255 dtrace_cpustart_fini = NULL;
18256 dtrace_debugger_init = NULL;
18257 dtrace_debugger_fini = NULL;
18258 dtrace_modload = NULL;
18259 dtrace_modunload = NULL;
18261 ASSERT(dtrace_getf == 0);
18262 ASSERT(dtrace_closef == NULL);
18264 mutex_exit(&cpu_lock);
18266 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
18267 dtrace_probes = NULL;
18268 dtrace_nprobes = 0;
18270 dtrace_hash_destroy(dtrace_bymod);
18271 dtrace_hash_destroy(dtrace_byfunc);
18272 dtrace_hash_destroy(dtrace_byname);
18273 dtrace_bymod = NULL;
18274 dtrace_byfunc = NULL;
18275 dtrace_byname = NULL;
18277 kmem_cache_destroy(dtrace_state_cache);
18278 vmem_destroy(dtrace_minor);
18279 vmem_destroy(dtrace_arena);
18281 if (dtrace_toxrange != NULL) {
18282 kmem_free(dtrace_toxrange,
18283 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
18284 dtrace_toxrange = NULL;
18285 dtrace_toxranges = 0;
18286 dtrace_toxranges_max = 0;
18289 ddi_remove_minor_node(dtrace_devi, NULL);
18290 dtrace_devi = NULL;
18292 ddi_soft_state_fini(&dtrace_softstate);
18294 ASSERT(dtrace_vtime_references == 0);
18295 ASSERT(dtrace_opens == 0);
18296 ASSERT(dtrace_retained == NULL);
18298 mutex_exit(&dtrace_lock);
18299 mutex_exit(&dtrace_provider_lock);
18302 * We don't destroy the task queue until after we have dropped our
18303 * locks (taskq_destroy() may block on running tasks). To prevent
18304 * attempting to do work after we have effectively detached but before
18305 * the task queue has been destroyed, all tasks dispatched via the
18306 * task queue must check that DTrace is still attached before
18307 * performing any operation.
18309 taskq_destroy(dtrace_taskq);
18310 dtrace_taskq = NULL;
18312 return (DDI_SUCCESS);
18319 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
18324 case DDI_INFO_DEVT2DEVINFO:
18325 *result = (void *)dtrace_devi;
18326 error = DDI_SUCCESS;
18328 case DDI_INFO_DEVT2INSTANCE:
18329 *result = (void *)0;
18330 error = DDI_SUCCESS;
18333 error = DDI_FAILURE;
18340 static struct cb_ops dtrace_cb_ops = {
18341 dtrace_open, /* open */
18342 dtrace_close, /* close */
18343 nulldev, /* strategy */
18344 nulldev, /* print */
18348 dtrace_ioctl, /* ioctl */
18349 nodev, /* devmap */
18351 nodev, /* segmap */
18352 nochpoll, /* poll */
18353 ddi_prop_op, /* cb_prop_op */
18355 D_NEW | D_MP /* Driver compatibility flag */
18358 static struct dev_ops dtrace_ops = {
18359 DEVO_REV, /* devo_rev */
18361 dtrace_info, /* get_dev_info */
18362 nulldev, /* identify */
18363 nulldev, /* probe */
18364 dtrace_attach, /* attach */
18365 dtrace_detach, /* detach */
18367 &dtrace_cb_ops, /* driver operations */
18368 NULL, /* bus operations */
18369 nodev /* dev power */
18372 static struct modldrv modldrv = {
18373 &mod_driverops, /* module type (this is a pseudo driver) */
18374 "Dynamic Tracing", /* name of module */
18375 &dtrace_ops, /* driver ops */
18378 static struct modlinkage modlinkage = {
18387 return (mod_install(&modlinkage));
18391 _info(struct modinfo *modinfop)
18393 return (mod_info(&modlinkage, modinfop));
18399 return (mod_remove(&modlinkage));
18403 static d_ioctl_t dtrace_ioctl;
18404 static d_ioctl_t dtrace_ioctl_helper;
18405 static void dtrace_load(void *);
18406 static int dtrace_unload(void);
18407 static struct cdev *dtrace_dev;
18408 static struct cdev *helper_dev;
18410 void dtrace_invop_init(void);
18411 void dtrace_invop_uninit(void);
18413 static struct cdevsw dtrace_cdevsw = {
18414 .d_version = D_VERSION,
18415 .d_ioctl = dtrace_ioctl,
18416 .d_open = dtrace_open,
18417 .d_name = "dtrace",
18420 static struct cdevsw helper_cdevsw = {
18421 .d_version = D_VERSION,
18422 .d_ioctl = dtrace_ioctl_helper,
18423 .d_name = "helper",
18426 #include <dtrace_anon.c>
18427 #include <dtrace_ioctl.c>
18428 #include <dtrace_load.c>
18429 #include <dtrace_modevent.c>
18430 #include <dtrace_sysctl.c>
18431 #include <dtrace_unload.c>
18432 #include <dtrace_vtime.c>
18433 #include <dtrace_hacks.c>
18434 #include <dtrace_isa.c>
18436 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
18437 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
18438 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
18440 DEV_MODULE(dtrace, dtrace_modevent, NULL);
18441 MODULE_VERSION(dtrace, 1);
18442 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);