VirtualBox

source: vbox/trunk/src/VBox/ExtPacks/VBoxDTrace/onnv/uts/common/dtrace/dtrace.c@ 62608

Last change on this file since 62608 was 62608, checked in by vboxsync, 9 years ago

DTrace: unused parameters.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 407.4 KB
Line 
1/*
2 * CDDL HEADER START
3 *
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.
7 *
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.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24 */
25
26/*
27 * DTrace - Dynamic Tracing for Solaris
28 *
29 * This is the implementation of the Solaris Dynamic Tracing framework
30 * (DTrace). The user-visible interface to DTrace is described at length in
31 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
32 * library, the in-kernel DTrace framework, and the DTrace providers are
33 * described in the block comments in the <sys/dtrace.h> header file. The
34 * internal architecture of DTrace is described in the block comments in the
35 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
36 * implementation very much assume mastery of all of these sources; if one has
37 * an unanswered question about the implementation, one should consult them
38 * first.
39 *
40 * The functions here are ordered roughly as follows:
41 *
42 * - Probe context functions
43 * - Probe hashing functions
44 * - Non-probe context utility functions
45 * - Matching functions
46 * - Provider-to-Framework API functions
47 * - Probe management functions
48 * - DIF object functions
49 * - Format functions
50 * - Predicate functions
51 * - ECB functions
52 * - Buffer functions
53 * - Enabling functions
54 * - DOF functions
55 * - Anonymous enabling functions
56 * - Consumer state functions
57 * - Helper functions
58 * - Hook functions
59 * - Driver cookbook functions
60 *
61 * Each group of functions begins with a block comment labelled the "DTrace
62 * [Group] Functions", allowing one to find each block by searching forward
63 * on capital-f functions.
64 */
65#ifndef VBOX
66#include <sys/errno.h>
67#include <sys/stat.h>
68#include <sys/modctl.h>
69#include <sys/conf.h>
70#include <sys/systm.h>
71#include <sys/ddi.h>
72#include <sys/sunddi.h>
73#include <sys/cpuvar.h>
74#include <sys/kmem.h>
75#include <sys/strsubr.h>
76#include <sys/sysmacros.h>
77#include <sys/dtrace_impl.h>
78#include <sys/atomic.h>
79#include <sys/cmn_err.h>
80#include <sys/mutex_impl.h>
81#include <sys/rwlock_impl.h>
82#include <sys/ctf_api.h>
83#include <sys/panic.h>
84#include <sys/priv_impl.h>
85#include <sys/policy.h>
86#include <sys/cred_impl.h>
87#include <sys/procfs_isa.h>
88#include <sys/taskq.h>
89#include <sys/mkdev.h>
90#include <sys/kdi.h>
91#include <sys/zone.h>
92#include <sys/socket.h>
93#include <netinet/in.h>
94
95#else /* VBOX */
96# include <sys/dtrace_impl.h>
97# include <VBox/sup.h>
98# include <iprt/assert.h>
99# include <iprt/cpuset.h>
100# include <iprt/mem.h>
101# include <iprt/mp.h>
102# include <iprt/string.h>
103# include <iprt/process.h>
104# include <iprt/thread.h>
105# include <iprt/timer.h>
106# include <limits.h>
107
108/*
109 * Use asm.h to implemente some of the simple stuff in dtrace_asm.s.
110 */
111# include <iprt/asm.h>
112# include <iprt/asm-amd64-x86.h>
113# define dtrace_casptr(a_ppvDst, a_pvOld, a_pvNew) \
114 VBoxDtCompareAndSwapPtr((void * volatile *)a_ppvDst, a_pvOld, a_pvNew)
115DECLINLINE(void *) VBoxDtCompareAndSwapPtr(void * volatile *ppvDst, void *pvOld, void *pvNew)
116{
117 void *pvRet;
118 ASMAtomicCmpXchgExPtrVoid(ppvDst, pvNew, pvOld, &pvRet);
119 return pvRet;
120}
121
122# define dtrace_cas32(a_pu32Dst, a_pu32Old, a_pu32New) \
123 VBoxDtCompareAndSwapU32(a_pu32Dst, a_pu32Old, a_pu32New)
124DECLINLINE(uint32_t) VBoxDtCompareAndSwapU32(uint32_t volatile *pu32Dst, uint32_t u32Old, uint32_t u32New)
125{
126 uint32_t u32Ret;
127 ASMAtomicCmpXchgExU32(pu32Dst, u32New, u32Old, &u32Ret);
128 return u32Ret;
129}
130
131#define dtrace_membar_consumer() ASMReadFence()
132#define dtrace_membar_producer() ASMWriteFence()
133#define dtrace_interrupt_disable() ASMIntDisableFlags()
134#define dtrace_interrupt_enable(a_EFL) ASMSetFlags(a_EFL)
135
136/*
137 * NULL must be set to 0 or we'll end up with a billion warnings(=errors).
138 */
139# undef NULL
140# define NULL (0)
141#endif /* VBOX */
142
143/** Check if the given address is a valid kernel address.
144 * The value can be uintptr_t or uint64_t. */
145#ifndef VBOX
146# define VBDT_IS_VALID_KRNL_ADDR(a_uAddr) ((a_uAddr) >= KERNELBASE)
147#else
148# define VBDT_IS_VALID_KRNL_ADDR(a_uAddr) \
149 ( (sizeof(a_uAddr) == sizeof(uintptr_t) || (uintptr_t)(a_uAddr) == (a_uAddr)) \
150 && RTR0MemKernelIsValidAddr((void *)(uintptr_t)(a_uAddr)) )
151#endif
152
153
154/*
155 * DTrace Tunable Variables
156 *
157 * The following variables may be tuned by adding a line to /etc/system that
158 * includes both the name of the DTrace module ("dtrace") and the name of the
159 * variable. For example:
160 *
161 * set dtrace:dtrace_destructive_disallow = 1
162 *
163 * In general, the only variables that one should be tuning this way are those
164 * that affect system-wide DTrace behavior, and for which the default behavior
165 * is undesirable. Most of these variables are tunable on a per-consumer
166 * basis using DTrace options, and need not be tuned on a system-wide basis.
167 * When tuning these variables, avoid pathological values; while some attempt
168 * is made to verify the integrity of these variables, they are not considered
169 * part of the supported interface to DTrace, and they are therefore not
170 * checked comprehensively. Further, these variables should not be tuned
171 * dynamically via "mdb -kw" or other means; they should only be tuned via
172 * /etc/system.
173 */
174int dtrace_destructive_disallow = 0;
175dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
176size_t dtrace_difo_maxsize = (256 * 1024);
177dtrace_optval_t dtrace_dof_maxsize = (256 * 1024);
178size_t dtrace_global_maxsize = (16 * 1024);
179size_t dtrace_actions_max = (16 * 1024);
180size_t dtrace_retain_max = 1024;
181dtrace_optval_t dtrace_helper_actions_max = 32;
182dtrace_optval_t dtrace_helper_providers_max = 32;
183dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
184size_t dtrace_strsize_default = 256;
185dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
186dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
187dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
188dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
189dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
190dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
191dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
192dtrace_optval_t dtrace_nspec_default = 1;
193dtrace_optval_t dtrace_specsize_default = 32 * 1024;
194dtrace_optval_t dtrace_stackframes_default = 20;
195dtrace_optval_t dtrace_ustackframes_default = 20;
196dtrace_optval_t dtrace_jstackframes_default = 50;
197dtrace_optval_t dtrace_jstackstrsize_default = 512;
198int dtrace_msgdsize_max = 128;
199hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
200hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
201int dtrace_devdepth_max = 32;
202int dtrace_err_verbose;
203hrtime_t dtrace_deadman_interval = NANOSEC;
204hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
205hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
206
207/*
208 * DTrace External Variables
209 *
210 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
211 * available to DTrace consumers via the backtick (`) syntax. One of these,
212 * dtrace_zero, is made deliberately so: it is provided as a source of
213 * well-known, zero-filled memory. While this variable is not documented,
214 * it is used by some translators as an implementation detail.
215 */
216const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
217
218/*
219 * DTrace Internal Variables
220 */
221#ifndef VBOX
222static dev_info_t *dtrace_devi; /* device info */
223#endif
224static vmem_t *dtrace_arena; /* probe ID arena */
225#ifndef VBOX
226static vmem_t *dtrace_minor; /* minor number arena */
227static taskq_t *dtrace_taskq; /* task queue */
228#endif
229static dtrace_probe_t **dtrace_probes; /* array of all probes */
230static VBDTTYPE(uint32_t,int) dtrace_nprobes; /* number of probes */
231static dtrace_provider_t *dtrace_provider; /* provider list */
232static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
233static int dtrace_opens; /* number of opens */
234static int dtrace_helpers; /* number of helpers */
235#ifndef VBOX
236static void *dtrace_softstate; /* softstate pointer */
237#endif
238static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
239static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
240static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
241static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
242static int dtrace_toxranges; /* number of toxic ranges */
243static int dtrace_toxranges_max; /* size of toxic range array */
244static dtrace_anon_t dtrace_anon; /* anonymous enabling */
245static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
246static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
247#ifndef VBOX
248static kthread_t *dtrace_panicked; /* panicking thread */
249#endif
250static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
251static dtrace_genid_t dtrace_probegen; /* current probe generation */
252static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
253static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
254static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
255static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
256static int dtrace_dynvar_failclean; /* dynvars failed to clean */
257
258/*
259 * DTrace Locking
260 * DTrace is protected by three (relatively coarse-grained) locks:
261 *
262 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
263 * including enabling state, probes, ECBs, consumer state, helper state,
264 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
265 * probe context is lock-free -- synchronization is handled via the
266 * dtrace_sync() cross call mechanism.
267 *
268 * (2) dtrace_provider_lock is required when manipulating provider state, or
269 * when provider state must be held constant.
270 *
271 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
272 * when meta provider state must be held constant.
273 *
274 * The lock ordering between these three locks is dtrace_meta_lock before
275 * dtrace_provider_lock before dtrace_lock. (In particular, there are
276 * several places where dtrace_provider_lock is held by the framework as it
277 * calls into the providers -- which then call back into the framework,
278 * grabbing dtrace_lock.)
279 *
280 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
281 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
282 * role as a coarse-grained lock; it is acquired before both of these locks.
283 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
284 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
285 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
286 * acquired _between_ dtrace_provider_lock and dtrace_lock.
287 */
288static kmutex_t dtrace_lock; /* probe state lock */
289static kmutex_t dtrace_provider_lock; /* provider state lock */
290static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
291
292/*
293 * DTrace Provider Variables
294 *
295 * These are the variables relating to DTrace as a provider (that is, the
296 * provider of the BEGIN, END, and ERROR probes).
297 */
298static dtrace_pattr_t dtrace_provider_attr = {
299{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
300{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
301{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
302{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
303{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
304};
305
306static void
307dtrace_nullop(void)
308{}
309
310static int
311dtrace_enable_nullop(void)
312{
313 return (0);
314}
315
316static dtrace_pops_t dtrace_provider_ops = {
317 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
318 (void (*)(void *, struct modctl *))dtrace_nullop,
319 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
320 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
321 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
322 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
323 NULL,
324 NULL,
325 NULL,
326 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
327};
328
329static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
330static dtrace_id_t dtrace_probeid_end; /* special END probe */
331dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
332
333/*
334 * DTrace Helper Tracing Variables
335 */
336uint32_t dtrace_helptrace_next = 0;
337uint32_t dtrace_helptrace_nlocals;
338char *dtrace_helptrace_buffer;
339int dtrace_helptrace_bufsize = 512 * 1024;
340
341#ifdef DEBUG
342int dtrace_helptrace_enabled = 1;
343#else
344int dtrace_helptrace_enabled = 0;
345#endif
346
347/*
348 * DTrace Error Hashing
349 *
350 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
351 * table. This is very useful for checking coverage of tests that are
352 * expected to induce DIF or DOF processing errors, and may be useful for
353 * debugging problems in the DIF code generator or in DOF generation . The
354 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
355 */
356#ifdef DEBUG
357static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
358static const char *dtrace_errlast;
359static kthread_t *dtrace_errthread;
360static kmutex_t dtrace_errlock;
361#endif
362
363/*
364 * DTrace Macros and Constants
365 *
366 * These are various macros that are useful in various spots in the
367 * implementation, along with a few random constants that have no meaning
368 * outside of the implementation. There is no real structure to this cpp
369 * mishmash -- but is there ever?
370 */
371#define DTRACE_HASHSTR(hash, probe) \
372 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
373
374#define DTRACE_HASHNEXT(hash, probe) \
375 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
376
377#define DTRACE_HASHPREV(hash, probe) \
378 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
379
380#define DTRACE_HASHEQ(hash, lhs, rhs) \
381 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
382 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
383
384#define DTRACE_AGGHASHSIZE_SLEW 17
385
386#define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
387
388/*
389 * The key for a thread-local variable consists of the lower 61 bits of the
390 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
391 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
392 * equal to a variable identifier. This is necessary (but not sufficient) to
393 * assure that global associative arrays never collide with thread-local
394 * variables. To guarantee that they cannot collide, we must also define the
395 * order for keying dynamic variables. That order is:
396 *
397 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
398 *
399 * Because the variable-key and the tls-key are in orthogonal spaces, there is
400 * no way for a global variable key signature to match a thread-local key
401 * signature.
402 */
403#ifndef VBOX
404#define DTRACE_TLS_THRKEY(where) { \
405 uint_t intr = 0; \
406 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
407 for (; actv; actv >>= 1) \
408 intr++; \
409 ASSERT(intr < (1 << 3)); \
410 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
411 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
412}
413#else
414#define DTRACE_TLS_THRKEY(where) do { \
415 (where) = (((uintptr_t)RTThreadNativeSelf() + DIF_VARIABLE_MAX) & (RT_BIT_64(61) - 1)) \
416 | (RTThreadIsInInterrupt(NIL_RTTHREAD) ? RT_BIT_64(61) : 0); \
417} while (0)
418#endif
419
420#define DT_BSWAP_8(x) ((x) & 0xff)
421#define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
422#define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
423#define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
424
425#define DT_MASK_LO 0x00000000FFFFFFFFULL
426
427#define DTRACE_STORE(type, tomax, offset, what) \
428 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
429
430#ifndef __i386
431#define DTRACE_ALIGNCHECK(addr, size, flags) \
432 if (addr & (size - 1)) { \
433 *flags |= CPU_DTRACE_BADALIGN; \
434 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval = addr; \
435 return (0); \
436 }
437#else
438#define DTRACE_ALIGNCHECK(addr, size, flags)
439#endif
440
441/*
442 * Test whether a range of memory starting at testaddr of size testsz falls
443 * within the range of memory described by addr, sz. We take care to avoid
444 * problems with overflow and underflow of the unsigned quantities, and
445 * disallow all negative sizes. Ranges of size 0 are allowed.
446 */
447#define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
448 ((testaddr) - (baseaddr) < (basesz) && \
449 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
450 (testaddr) + (testsz) >= (testaddr))
451
452/*
453 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
454 * alloc_sz on the righthand side of the comparison in order to avoid overflow
455 * or underflow in the comparison with it. This is simpler than the INRANGE
456 * check above, because we know that the dtms_scratch_ptr is valid in the
457 * range. Allocations of size zero are allowed.
458 */
459#define DTRACE_INSCRATCH(mstate, alloc_sz) \
460 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
461 (mstate)->dtms_scratch_ptr >= (alloc_sz))
462
463#ifndef VBOX
464#define DTRACE_LOADFUNC(bits) \
465/*CSTYLED*/ \
466VBDTSTATIC uint##bits##_t \
467dtrace_load##bits(uintptr_t addr) \
468{ \
469 size_t size = bits / NBBY; \
470 /*CSTYLED*/ \
471 uint##bits##_t rval; \
472 int i; \
473 processorid_t me = VBDT_GET_CPUID(); \
474 volatile uint16_t *flags = (volatile uint16_t *) \
475 &cpu_core[me].cpuc_dtrace_flags; \
476 \
477 DTRACE_ALIGNCHECK(addr, size, flags); \
478 \
479 for (i = 0; i < dtrace_toxranges; i++) { \
480 if (addr >= dtrace_toxrange[i].dtt_limit) \
481 continue; \
482 \
483 if (addr + size <= dtrace_toxrange[i].dtt_base) \
484 continue; \
485 \
486 /* \
487 * This address falls within a toxic region; return 0. \
488 */ \
489 *flags |= CPU_DTRACE_BADADDR; \
490 cpu_core[me].cpuc_dtrace_illval = addr; \
491 return (0); \
492 } \
493 \
494 *flags |= CPU_DTRACE_NOFAULT; \
495 /*CSTYLED*/ \
496 rval = *((volatile uint##bits##_t *)addr); \
497 *flags &= ~CPU_DTRACE_NOFAULT; \
498 \
499 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
500}
501#else /* VBOX */
502# define DTRACE_LOADFUNC(bits) \
503VBDTSTATIC uint##bits##_t \
504dtrace_load##bits(uintptr_t addr) \
505{ \
506 size_t const size = bits / NBBY; \
507 uint##bits##_t rval; \
508 processorid_t me; \
509 int i, rc; \
510 \
511 /*DTRACE_ALIGNCHECK(addr, size, flags);*/ \
512 \
513 for (i = 0; i < dtrace_toxranges; i++) { \
514 if (addr >= dtrace_toxrange[i].dtt_limit) \
515 continue; \
516 \
517 if (addr + size <= dtrace_toxrange[i].dtt_base) \
518 continue; \
519 \
520 /* \
521 * This address falls within a toxic region; return 0. \
522 */ \
523 me = VBDT_GET_CPUID(); \
524 cpu_core[me].cpuc_dtrace_flags |= CPU_DTRACE_BADADDR; \
525 cpu_core[me].cpuc_dtrace_illval = addr; \
526 return (0); \
527 } \
528 \
529 rc = RTR0MemKernelCopyFrom(&rval, (void const *)addr, size); \
530 if (RT_SUCCESS(rc)) \
531 return rval; \
532 \
533 /* \
534 * If not supported, pray it won't fault... \
535 */ \
536 if (rc == VERR_NOT_SUPPORTED) \
537 return *(uint##bits##_t const *)addr; \
538 \
539 me = VBDT_GET_CPUID(); \
540 cpu_core[me].cpuc_dtrace_flags |= CPU_DTRACE_BADADDR; \
541 cpu_core[me].cpuc_dtrace_illval = addr; \
542 return (0); \
543}
544
545#endif /* VBOX */
546
547#ifdef _LP64
548#define dtrace_loadptr dtrace_load64
549#else
550#define dtrace_loadptr dtrace_load32
551#endif
552
553#define DTRACE_DYNHASH_FREE 0
554#define DTRACE_DYNHASH_SINK 1
555#define DTRACE_DYNHASH_VALID 2
556
557#define DTRACE_MATCH_FAIL -1
558#define DTRACE_MATCH_NEXT 0
559#define DTRACE_MATCH_DONE 1
560#define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
561#define DTRACE_STATE_ALIGN 64
562
563#define DTRACE_FLAGS2FLT(flags) \
564 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
565 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
566 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
567 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
568 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
569 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
570 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
571 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
572 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
573 DTRACEFLT_UNKNOWN)
574
575#define DTRACEACT_ISSTRING(act) \
576 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
577 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
578
579static size_t dtrace_strlen(const char *, size_t);
580static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
581static void dtrace_enabling_provide(dtrace_provider_t *);
582static int dtrace_enabling_match(dtrace_enabling_t *, int *);
583static void dtrace_enabling_matchall(void);
584static dtrace_state_t *dtrace_anon_grab(void);
585#ifndef VBOX
586static uint64_t dtrace_helper(int, dtrace_mstate_t *,
587 dtrace_state_t *, uint64_t, uint64_t);
588static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
589#endif
590static void dtrace_buffer_drop(dtrace_buffer_t *);
591static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
592 dtrace_state_t *, dtrace_mstate_t *);
593static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
594 dtrace_optval_t);
595static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
596static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
597
598/*
599 * DTrace Probe Context Functions
600 *
601 * These functions are called from probe context. Because probe context is
602 * any context in which C may be called, arbitrarily locks may be held,
603 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
604 * As a result, functions called from probe context may only call other DTrace
605 * support functions -- they may not interact at all with the system at large.
606 * (Note that the ASSERT macro is made probe-context safe by redefining it in
607 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
608 * loads are to be performed from probe context, they _must_ be in terms of
609 * the safe dtrace_load*() variants.
610 *
611 * Some functions in this block are not actually called from probe context;
612 * for these functions, there will be a comment above the function reading
613 * "Note: not called from probe context."
614 */
615void
616dtrace_panic(const char *format, ...)
617{
618 va_list alist;
619
620 va_start(alist, format);
621 dtrace_vpanic(format, alist);
622 va_end(alist);
623}
624
625#ifndef VBOX /* We have our own assertion machinery. */
626int
627dtrace_assfail(const char *a, const char *f, int l)
628{
629 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
630
631 /*
632 * We just need something here that even the most clever compiler
633 * cannot optimize away.
634 */
635 return (a[(uintptr_t)f]);
636}
637#endif
638
639/*
640 * Atomically increment a specified error counter from probe context.
641 */
642static void
643dtrace_error(uint32_t *counter)
644{
645 /*
646 * Most counters stored to in probe context are per-CPU counters.
647 * However, there are some error conditions that are sufficiently
648 * arcane that they don't merit per-CPU storage. If these counters
649 * are incremented concurrently on different CPUs, scalability will be
650 * adversely affected -- but we don't expect them to be white-hot in a
651 * correctly constructed enabling...
652 */
653 uint32_t oval, nval;
654
655 do {
656 oval = *counter;
657
658 if ((nval = oval + 1) == 0) {
659 /*
660 * If the counter would wrap, set it to 1 -- assuring
661 * that the counter is never zero when we have seen
662 * errors. (The counter must be 32-bits because we
663 * aren't guaranteed a 64-bit compare&swap operation.)
664 * To save this code both the infamy of being fingered
665 * by a priggish news story and the indignity of being
666 * the target of a neo-puritan witch trial, we're
667 * carefully avoiding any colorful description of the
668 * likelihood of this condition -- but suffice it to
669 * say that it is only slightly more likely than the
670 * overflow of predicate cache IDs, as discussed in
671 * dtrace_predicate_create().
672 */
673 nval = 1;
674 }
675 } while (dtrace_cas32(counter, oval, nval) != oval);
676}
677
678/*
679 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
680 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
681 */
682DTRACE_LOADFUNC(8)
683DTRACE_LOADFUNC(16)
684DTRACE_LOADFUNC(32)
685DTRACE_LOADFUNC(64)
686
687static int
688dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
689{
690 if (dest < mstate->dtms_scratch_base)
691 return (0);
692
693 if (dest + size < dest)
694 return (0);
695
696 if (dest + size > mstate->dtms_scratch_ptr)
697 return (0);
698
699 return (1);
700}
701
702static int
703dtrace_canstore_statvar(uint64_t addr, size_t sz,
704 dtrace_statvar_t **svars, int nsvars)
705{
706 int i;
707
708 for (i = 0; i < nsvars; i++) {
709 dtrace_statvar_t *svar = svars[i];
710
711 if (svar == NULL || svar->dtsv_size == 0)
712 continue;
713
714 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
715 return (1);
716 }
717
718 return (0);
719}
720
721/*
722 * Check to see if the address is within a memory region to which a store may
723 * be issued. This includes the DTrace scratch areas, and any DTrace variable
724 * region. The caller of dtrace_canstore() is responsible for performing any
725 * alignment checks that are needed before stores are actually executed.
726 */
727static int
728dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
729 dtrace_vstate_t *vstate)
730{
731 /*
732 * First, check to see if the address is in scratch space...
733 */
734 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
735 mstate->dtms_scratch_size))
736 return (1);
737
738 /*
739 * Now check to see if it's a dynamic variable. This check will pick
740 * up both thread-local variables and any global dynamically-allocated
741 * variables.
742 */
743 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
744 vstate->dtvs_dynvars.dtds_size)) {
745 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
746 uintptr_t base = (uintptr_t)dstate->dtds_base +
747 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
748 uintptr_t chunkoffs;
749
750 /*
751 * Before we assume that we can store here, we need to make
752 * sure that it isn't in our metadata -- storing to our
753 * dynamic variable metadata would corrupt our state. For
754 * the range to not include any dynamic variable metadata,
755 * it must:
756 *
757 * (1) Start above the hash table that is at the base of
758 * the dynamic variable space
759 *
760 * (2) Have a starting chunk offset that is beyond the
761 * dtrace_dynvar_t that is at the base of every chunk
762 *
763 * (3) Not span a chunk boundary
764 *
765 */
766 if (addr < base)
767 return (0);
768
769 chunkoffs = (addr - base) % dstate->dtds_chunksize;
770
771 if (chunkoffs < sizeof (dtrace_dynvar_t))
772 return (0);
773
774 if (chunkoffs + sz > dstate->dtds_chunksize)
775 return (0);
776
777 return (1);
778 }
779
780 /*
781 * Finally, check the static local and global variables. These checks
782 * take the longest, so we perform them last.
783 */
784 if (dtrace_canstore_statvar(addr, sz,
785 vstate->dtvs_locals, vstate->dtvs_nlocals))
786 return (1);
787
788 if (dtrace_canstore_statvar(addr, sz,
789 vstate->dtvs_globals, vstate->dtvs_nglobals))
790 return (1);
791
792 return (0);
793}
794
795
796/*
797 * Convenience routine to check to see if the address is within a memory
798 * region in which a load may be issued given the user's privilege level;
799 * if not, it sets the appropriate error flags and loads 'addr' into the
800 * illegal value slot.
801 *
802 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
803 * appropriate memory access protection.
804 */
805static int
806dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
807 dtrace_vstate_t *vstate)
808{
809 volatile uintptr_t *illval = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval;
810
811 /*
812 * If we hold the privilege to read from kernel memory, then
813 * everything is readable.
814 */
815 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
816 return (1);
817
818 /*
819 * You can obviously read that which you can store.
820 */
821 if (dtrace_canstore(addr, sz, mstate, vstate))
822 return (1);
823
824 /*
825 * We're allowed to read from our own string table.
826 */
827 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
828 mstate->dtms_difo->dtdo_strlen))
829 return (1);
830
831 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
832 *illval = addr;
833 return (0);
834}
835
836/*
837 * Convenience routine to check to see if a given string is within a memory
838 * region in which a load may be issued given the user's privilege level;
839 * this exists so that we don't need to issue unnecessary dtrace_strlen()
840 * calls in the event that the user has all privileges.
841 */
842static int
843dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
844 dtrace_vstate_t *vstate)
845{
846 size_t strsz;
847
848 /*
849 * If we hold the privilege to read from kernel memory, then
850 * everything is readable.
851 */
852 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
853 return (1);
854
855 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
856 if (dtrace_canload(addr, strsz, mstate, vstate))
857 return (1);
858
859 return (0);
860}
861
862/*
863 * Convenience routine to check to see if a given variable is within a memory
864 * region in which a load may be issued given the user's privilege level.
865 */
866static int
867dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
868 dtrace_vstate_t *vstate)
869{
870 size_t sz;
871 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
872
873 /*
874 * If we hold the privilege to read from kernel memory, then
875 * everything is readable.
876 */
877 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
878 return (1);
879
880 if (type->dtdt_kind == DIF_TYPE_STRING)
881 sz = dtrace_strlen(src,
882 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
883 else
884 sz = type->dtdt_size;
885
886 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
887}
888
889/*
890 * Compare two strings using safe loads.
891 */
892static int
893dtrace_strncmp(char *s1, char *s2, size_t limit)
894{
895 uint8_t c1, c2;
896 volatile uint16_t *flags;
897
898 if (s1 == s2 || limit == 0)
899 return (0);
900
901 flags = (volatile uint16_t *)&cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
902
903 do {
904 if (s1 == NULL) {
905 c1 = '\0';
906 } else {
907 c1 = dtrace_load8((uintptr_t)s1++);
908 }
909
910 if (s2 == NULL) {
911 c2 = '\0';
912 } else {
913 c2 = dtrace_load8((uintptr_t)s2++);
914 }
915
916 if (c1 != c2)
917 return (c1 - c2);
918 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
919
920 return (0);
921}
922
923/*
924 * Compute strlen(s) for a string using safe memory accesses. The additional
925 * len parameter is used to specify a maximum length to ensure completion.
926 */
927static size_t
928dtrace_strlen(const char *s, size_t lim)
929{
930 uint_t len;
931
932 for (len = 0; len != lim; len++) {
933 if (dtrace_load8((uintptr_t)s++) == '\0')
934 break;
935 }
936
937 return (len);
938}
939
940/*
941 * Check if an address falls within a toxic region.
942 */
943static int
944dtrace_istoxic(uintptr_t kaddr, size_t size)
945{
946 uintptr_t taddr, tsize;
947 int i;
948
949 for (i = 0; i < dtrace_toxranges; i++) {
950 taddr = dtrace_toxrange[i].dtt_base;
951 tsize = dtrace_toxrange[i].dtt_limit - taddr;
952
953 if (kaddr - taddr < tsize) {
954 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
955 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval = kaddr;
956 return (1);
957 }
958
959 if (taddr - kaddr < size) {
960 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
961 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval = taddr;
962 return (1);
963 }
964 }
965
966 return (0);
967}
968
969/*
970 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
971 * memory specified by the DIF program. The dst is assumed to be safe memory
972 * that we can store to directly because it is managed by DTrace. As with
973 * standard bcopy, overlapping copies are handled properly.
974 */
975static void
976dtrace_bcopy(const void *src, void *dst, size_t len)
977{
978 if (len != 0) {
979 uint8_t *s1 = dst;
980 const uint8_t *s2 = src;
981
982 if (s1 <= s2) {
983 do {
984 *s1++ = dtrace_load8((uintptr_t)s2++);
985 } while (--len != 0);
986 } else {
987 s2 += len;
988 s1 += len;
989
990 do {
991 *--s1 = dtrace_load8((uintptr_t)--s2);
992 } while (--len != 0);
993 }
994 }
995}
996
997/*
998 * Copy src to dst using safe memory accesses, up to either the specified
999 * length, or the point that a nul byte is encountered. The src is assumed to
1000 * be unsafe memory specified by the DIF program. The dst is assumed to be
1001 * safe memory that we can store to directly because it is managed by DTrace.
1002 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1003 */
1004static void
1005dtrace_strcpy(const void *src, void *dst, size_t len)
1006{
1007 if (len != 0) {
1008 uint8_t *s1 = dst, c;
1009 const uint8_t *s2 = src;
1010
1011 do {
1012 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1013 } while (--len != 0 && c != '\0');
1014 }
1015}
1016
1017/*
1018 * Copy src to dst, deriving the size and type from the specified (BYREF)
1019 * variable type. The src is assumed to be unsafe memory specified by the DIF
1020 * program. The dst is assumed to be DTrace variable memory that is of the
1021 * specified type; we assume that we can store to directly.
1022 */
1023static void
1024dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1025{
1026 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1027
1028 if (type->dtdt_kind == DIF_TYPE_STRING) {
1029 dtrace_strcpy(src, dst, type->dtdt_size);
1030 } else {
1031 dtrace_bcopy(src, dst, type->dtdt_size);
1032 }
1033}
1034
1035/*
1036 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1037 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1038 * safe memory that we can access directly because it is managed by DTrace.
1039 */
1040static int
1041dtrace_bcmp(const void *s1, const void *s2, size_t len)
1042{
1043 volatile uint16_t *flags;
1044
1045 flags = (volatile uint16_t *)&cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
1046
1047 if (s1 == s2)
1048 return (0);
1049
1050 if (s1 == NULL || s2 == NULL)
1051 return (1);
1052
1053 if (s1 != s2 && len != 0) {
1054 const uint8_t *ps1 = s1;
1055 const uint8_t *ps2 = s2;
1056
1057 do {
1058 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1059 return (1);
1060 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1061 }
1062 return (0);
1063}
1064
1065/*
1066 * Zero the specified region using a simple byte-by-byte loop. Note that this
1067 * is for safe DTrace-managed memory only.
1068 */
1069static void
1070dtrace_bzero(void *dst, size_t len)
1071{
1072 uchar_t *cp;
1073
1074 for (cp = dst; len != 0; len--)
1075 *cp++ = 0;
1076}
1077
1078static void
1079dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1080{
1081 uint64_t result[2];
1082
1083 result[0] = addend1[0] + addend2[0];
1084 result[1] = addend1[1] + addend2[1] +
1085 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1086
1087 sum[0] = result[0];
1088 sum[1] = result[1];
1089}
1090
1091/*
1092 * Shift the 128-bit value in a by b. If b is positive, shift left.
1093 * If b is negative, shift right.
1094 */
1095static void
1096dtrace_shift_128(uint64_t *a, int b)
1097{
1098 uint64_t mask;
1099
1100 if (b == 0)
1101 return;
1102
1103 if (b < 0) {
1104 b = -b;
1105 if (b >= 64) {
1106 a[0] = a[1] >> (b - 64);
1107 a[1] = 0;
1108 } else {
1109 a[0] >>= b;
1110 mask = 1LL << (64 - b);
1111 mask -= 1;
1112 a[0] |= ((a[1] & mask) << (64 - b));
1113 a[1] >>= b;
1114 }
1115 } else {
1116 if (b >= 64) {
1117 a[1] = a[0] << (b - 64);
1118 a[0] = 0;
1119 } else {
1120 a[1] <<= b;
1121 mask = a[0] >> (64 - b);
1122 a[1] |= mask;
1123 a[0] <<= b;
1124 }
1125 }
1126}
1127
1128/*
1129 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1130 * use native multiplication on those, and then re-combine into the
1131 * resulting 128-bit value.
1132 *
1133 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1134 * hi1 * hi2 << 64 +
1135 * hi1 * lo2 << 32 +
1136 * hi2 * lo1 << 32 +
1137 * lo1 * lo2
1138 */
1139static void
1140dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1141{
1142 uint64_t hi1, hi2, lo1, lo2;
1143 uint64_t tmp[2];
1144
1145 hi1 = factor1 >> 32;
1146 hi2 = factor2 >> 32;
1147
1148 lo1 = factor1 & DT_MASK_LO;
1149 lo2 = factor2 & DT_MASK_LO;
1150
1151 product[0] = lo1 * lo2;
1152 product[1] = hi1 * hi2;
1153
1154 tmp[0] = hi1 * lo2;
1155 tmp[1] = 0;
1156 dtrace_shift_128(tmp, 32);
1157 dtrace_add_128(product, tmp, product);
1158
1159 tmp[0] = hi2 * lo1;
1160 tmp[1] = 0;
1161 dtrace_shift_128(tmp, 32);
1162 dtrace_add_128(product, tmp, product);
1163}
1164
1165/*
1166 * This privilege check should be used by actions and subroutines to
1167 * verify that the user credentials of the process that enabled the
1168 * invoking ECB match the target credentials
1169 */
1170static int
1171dtrace_priv_proc_common_user(dtrace_state_t *state)
1172{
1173 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1174
1175 /*
1176 * We should always have a non-NULL state cred here, since if cred
1177 * is null (anonymous tracing), we fast-path bypass this routine.
1178 */
1179 ASSERT(s_cr != NULL);
1180
1181 if ((cr = CRED()) != NULL &&
1182 s_cr->cr_uid == cr->cr_uid &&
1183 s_cr->cr_uid == cr->cr_ruid &&
1184 s_cr->cr_uid == cr->cr_suid &&
1185 s_cr->cr_gid == cr->cr_gid &&
1186 s_cr->cr_gid == cr->cr_rgid &&
1187 s_cr->cr_gid == cr->cr_sgid)
1188 return (1);
1189
1190 return (0);
1191}
1192
1193/*
1194 * This privilege check should be used by actions and subroutines to
1195 * verify that the zone of the process that enabled the invoking ECB
1196 * matches the target credentials
1197 */
1198static int
1199dtrace_priv_proc_common_zone(dtrace_state_t *state)
1200{
1201 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1202
1203 /*
1204 * We should always have a non-NULL state cred here, since if cred
1205 * is null (anonymous tracing), we fast-path bypass this routine.
1206 */
1207 ASSERT(s_cr != NULL);
1208
1209 if ((cr = CRED()) != NULL &&
1210 s_cr->cr_zone == cr->cr_zone)
1211 return (1);
1212
1213 return (0);
1214}
1215
1216/*
1217 * This privilege check should be used by actions and subroutines to
1218 * verify that the process has not setuid or changed credentials.
1219 */
1220static int
1221dtrace_priv_proc_common_nocd(VBDTVOID)
1222{
1223#ifndef VBOX
1224 proc_t *proc;
1225
1226 if ((proc = VBDT_GET_PROC()) != NULL &&
1227 !(proc->p_flag & SNOCD))
1228 return (1);
1229
1230 return (0);
1231#else
1232 return (1);
1233#endif
1234}
1235
1236static int
1237dtrace_priv_proc_destructive(dtrace_state_t *state)
1238{
1239 int action = state->dts_cred.dcr_action;
1240
1241 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1242 dtrace_priv_proc_common_zone(state) == 0)
1243 goto bad;
1244
1245 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1246 dtrace_priv_proc_common_user(state) == 0)
1247 goto bad;
1248
1249 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1250 dtrace_priv_proc_common_nocd() == 0)
1251 goto bad;
1252
1253 return (1);
1254
1255bad:
1256 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1257
1258 return (0);
1259}
1260
1261static int
1262dtrace_priv_proc_control(dtrace_state_t *state)
1263{
1264 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1265 return (1);
1266
1267 if (dtrace_priv_proc_common_zone(state) &&
1268 dtrace_priv_proc_common_user(state) &&
1269 dtrace_priv_proc_common_nocd())
1270 return (1);
1271
1272 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1273
1274 return (0);
1275}
1276
1277static int
1278dtrace_priv_proc(dtrace_state_t *state)
1279{
1280 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1281 return (1);
1282
1283 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1284
1285 return (0);
1286}
1287
1288static int
1289dtrace_priv_kernel(dtrace_state_t *state)
1290{
1291 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1292 return (1);
1293
1294 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1295
1296 return (0);
1297}
1298
1299static int
1300dtrace_priv_kernel_destructive(dtrace_state_t *state)
1301{
1302 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1303 return (1);
1304
1305 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1306
1307 return (0);
1308}
1309
1310/*
1311 * Note: not called from probe context. This function is called
1312 * asynchronously (and at a regular interval) from outside of probe context to
1313 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1314 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1315 */
1316VBDTSTATIC void
1317dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1318{
1319 dtrace_dynvar_t *dirty;
1320 dtrace_dstate_percpu_t *dcpu;
1321 dtrace_dynvar_t **rinsep;
1322 int i, j, work = 0;
1323
1324 for (i = 0; i < NCPU; i++) {
1325 dcpu = &dstate->dtds_percpu[i];
1326 rinsep = &dcpu->dtdsc_rinsing;
1327
1328 /*
1329 * If the dirty list is NULL, there is no dirty work to do.
1330 */
1331 if (dcpu->dtdsc_dirty == NULL)
1332 continue;
1333
1334 if (dcpu->dtdsc_rinsing != NULL) {
1335 /*
1336 * If the rinsing list is non-NULL, then it is because
1337 * this CPU was selected to accept another CPU's
1338 * dirty list -- and since that time, dirty buffers
1339 * have accumulated. This is a highly unlikely
1340 * condition, but we choose to ignore the dirty
1341 * buffers -- they'll be picked up a future cleanse.
1342 */
1343 continue;
1344 }
1345
1346 if (dcpu->dtdsc_clean != NULL) {
1347 /*
1348 * If the clean list is non-NULL, then we're in a
1349 * situation where a CPU has done deallocations (we
1350 * have a non-NULL dirty list) but no allocations (we
1351 * also have a non-NULL clean list). We can't simply
1352 * move the dirty list into the clean list on this
1353 * CPU, yet we also don't want to allow this condition
1354 * to persist, lest a short clean list prevent a
1355 * massive dirty list from being cleaned (which in
1356 * turn could lead to otherwise avoidable dynamic
1357 * drops). To deal with this, we look for some CPU
1358 * with a NULL clean list, NULL dirty list, and NULL
1359 * rinsing list -- and then we borrow this CPU to
1360 * rinse our dirty list.
1361 */
1362 for (j = 0; j < NCPU; j++) {
1363 dtrace_dstate_percpu_t *rinser;
1364
1365 rinser = &dstate->dtds_percpu[j];
1366
1367 if (rinser->dtdsc_rinsing != NULL)
1368 continue;
1369
1370 if (rinser->dtdsc_dirty != NULL)
1371 continue;
1372
1373 if (rinser->dtdsc_clean != NULL)
1374 continue;
1375
1376 rinsep = &rinser->dtdsc_rinsing;
1377 break;
1378 }
1379
1380 if (j == NCPU) {
1381 /*
1382 * We were unable to find another CPU that
1383 * could accept this dirty list -- we are
1384 * therefore unable to clean it now.
1385 */
1386 dtrace_dynvar_failclean++;
1387 continue;
1388 }
1389 }
1390
1391 work = 1;
1392
1393 /*
1394 * Atomically move the dirty list aside.
1395 */
1396 do {
1397 dirty = dcpu->dtdsc_dirty;
1398
1399 /*
1400 * Before we zap the dirty list, set the rinsing list.
1401 * (This allows for a potential assertion in
1402 * dtrace_dynvar(): if a free dynamic variable appears
1403 * on a hash chain, either the dirty list or the
1404 * rinsing list for some CPU must be non-NULL.)
1405 */
1406 *rinsep = dirty;
1407 dtrace_membar_producer();
1408 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1409 dirty, NULL) != dirty);
1410 }
1411
1412 if (!work) {
1413 /*
1414 * We have no work to do; we can simply return.
1415 */
1416 return;
1417 }
1418
1419 dtrace_sync();
1420
1421 for (i = 0; i < NCPU; i++) {
1422 dcpu = &dstate->dtds_percpu[i];
1423
1424 if (dcpu->dtdsc_rinsing == NULL)
1425 continue;
1426
1427 /*
1428 * We are now guaranteed that no hash chain contains a pointer
1429 * into this dirty list; we can make it clean.
1430 */
1431 ASSERT(dcpu->dtdsc_clean == NULL);
1432 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1433 dcpu->dtdsc_rinsing = NULL;
1434 }
1435
1436 /*
1437 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1438 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1439 * This prevents a race whereby a CPU incorrectly decides that
1440 * the state should be something other than DTRACE_DSTATE_CLEAN
1441 * after dtrace_dynvar_clean() has completed.
1442 */
1443 dtrace_sync();
1444
1445 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1446}
1447
1448/*
1449 * Depending on the value of the op parameter, this function looks-up,
1450 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1451 * allocation is requested, this function will return a pointer to a
1452 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1453 * variable can be allocated. If NULL is returned, the appropriate counter
1454 * will be incremented.
1455 */
1456VBDTSTATIC dtrace_dynvar_t *
1457dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1458 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1459 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1460{
1461 uint64_t hashval = DTRACE_DYNHASH_VALID;
1462 dtrace_dynhash_t *hash = dstate->dtds_hash;
1463 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1464 processorid_t me = VBDT_GET_CPUID(), cpu = me;
1465 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1466 size_t bucket, ksize;
1467 size_t chunksize = dstate->dtds_chunksize;
1468 uintptr_t kdata, lock, nstate;
1469 uint_t i;
1470
1471 ASSERT(nkeys != 0);
1472
1473 /*
1474 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1475 * algorithm. For the by-value portions, we perform the algorithm in
1476 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1477 * bit, and seems to have only a minute effect on distribution. For
1478 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1479 * over each referenced byte. It's painful to do this, but it's much
1480 * better than pathological hash distribution. The efficacy of the
1481 * hashing algorithm (and a comparison with other algorithms) may be
1482 * found by running the ::dtrace_dynstat MDB dcmd.
1483 */
1484 for (i = 0; i < nkeys; i++) {
1485 if (key[i].dttk_size == 0) {
1486 uint64_t val = key[i].dttk_value;
1487
1488 hashval += (val >> 48) & 0xffff;
1489 hashval += (hashval << 10);
1490 hashval ^= (hashval >> 6);
1491
1492 hashval += (val >> 32) & 0xffff;
1493 hashval += (hashval << 10);
1494 hashval ^= (hashval >> 6);
1495
1496 hashval += (val >> 16) & 0xffff;
1497 hashval += (hashval << 10);
1498 hashval ^= (hashval >> 6);
1499
1500 hashval += val & 0xffff;
1501 hashval += (hashval << 10);
1502 hashval ^= (hashval >> 6);
1503 } else {
1504 /*
1505 * This is incredibly painful, but it beats the hell
1506 * out of the alternative.
1507 */
1508 uint64_t j, size = key[i].dttk_size;
1509 uintptr_t base = (uintptr_t)key[i].dttk_value;
1510
1511 if (!dtrace_canload(base, size, mstate, vstate))
1512 break;
1513
1514 for (j = 0; j < size; j++) {
1515 hashval += dtrace_load8(base + j);
1516 hashval += (hashval << 10);
1517 hashval ^= (hashval >> 6);
1518 }
1519 }
1520 }
1521
1522 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1523 return (NULL);
1524
1525 hashval += (hashval << 3);
1526 hashval ^= (hashval >> 11);
1527 hashval += (hashval << 15);
1528
1529 /*
1530 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1531 * comes out to be one of our two sentinel hash values. If this
1532 * actually happens, we set the hashval to be a value known to be a
1533 * non-sentinel value.
1534 */
1535 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1536 hashval = DTRACE_DYNHASH_VALID;
1537
1538 /*
1539 * Yes, it's painful to do a divide here. If the cycle count becomes
1540 * important here, tricks can be pulled to reduce it. (However, it's
1541 * critical that hash collisions be kept to an absolute minimum;
1542 * they're much more painful than a divide.) It's better to have a
1543 * solution that generates few collisions and still keeps things
1544 * relatively simple.
1545 */
1546 bucket = hashval % dstate->dtds_hashsize;
1547
1548 if (op == DTRACE_DYNVAR_DEALLOC) {
1549 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1550
1551 for (;;) {
1552 while ((lock = *lockp) & 1)
1553 continue;
1554
1555 if (dtrace_casptr((void *)lockp,
1556 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1557 break;
1558 }
1559
1560 dtrace_membar_producer();
1561 }
1562
1563top:
1564 prev = NULL;
1565 lock = hash[bucket].dtdh_lock;
1566
1567 dtrace_membar_consumer();
1568
1569 start = hash[bucket].dtdh_chain;
1570 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1571 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1572 op != DTRACE_DYNVAR_DEALLOC));
1573
1574 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1575 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1576 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1577
1578 if (dvar->dtdv_hashval != hashval) {
1579 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1580 /*
1581 * We've reached the sink, and therefore the
1582 * end of the hash chain; we can kick out of
1583 * the loop knowing that we have seen a valid
1584 * snapshot of state.
1585 */
1586 ASSERT(dvar->dtdv_next == NULL);
1587 ASSERT(dvar == &dtrace_dynhash_sink);
1588 break;
1589 }
1590
1591 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1592 /*
1593 * We've gone off the rails: somewhere along
1594 * the line, one of the members of this hash
1595 * chain was deleted. Note that we could also
1596 * detect this by simply letting this loop run
1597 * to completion, as we would eventually hit
1598 * the end of the dirty list. However, we
1599 * want to avoid running the length of the
1600 * dirty list unnecessarily (it might be quite
1601 * long), so we catch this as early as
1602 * possible by detecting the hash marker. In
1603 * this case, we simply set dvar to NULL and
1604 * break; the conditional after the loop will
1605 * send us back to top.
1606 */
1607 dvar = NULL;
1608 break;
1609 }
1610
1611 goto next;
1612 }
1613
1614 if (dtuple->dtt_nkeys != nkeys)
1615 goto next;
1616
1617 for (i = 0; i < nkeys; i++, dkey++) {
1618 if (dkey->dttk_size != key[i].dttk_size)
1619 goto next; /* size or type mismatch */
1620
1621 if (dkey->dttk_size != 0) {
1622 if (dtrace_bcmp(
1623 (void *)(uintptr_t)key[i].dttk_value,
1624 (void *)(uintptr_t)dkey->dttk_value,
1625 dkey->dttk_size))
1626 goto next;
1627 } else {
1628 if (dkey->dttk_value != key[i].dttk_value)
1629 goto next;
1630 }
1631 }
1632
1633 if (op != DTRACE_DYNVAR_DEALLOC)
1634 return (dvar);
1635
1636 ASSERT(dvar->dtdv_next == NULL ||
1637 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1638
1639 if (prev != NULL) {
1640 ASSERT(hash[bucket].dtdh_chain != dvar);
1641 ASSERT(start != dvar);
1642 ASSERT(prev->dtdv_next == dvar);
1643 prev->dtdv_next = dvar->dtdv_next;
1644 } else {
1645 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1646 start, dvar->dtdv_next) != start) {
1647 /*
1648 * We have failed to atomically swing the
1649 * hash table head pointer, presumably because
1650 * of a conflicting allocation on another CPU.
1651 * We need to reread the hash chain and try
1652 * again.
1653 */
1654 goto top;
1655 }
1656 }
1657
1658 dtrace_membar_producer();
1659
1660 /*
1661 * Now set the hash value to indicate that it's free.
1662 */
1663 ASSERT(hash[bucket].dtdh_chain != dvar);
1664 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1665
1666 dtrace_membar_producer();
1667
1668 /*
1669 * Set the next pointer to point at the dirty list, and
1670 * atomically swing the dirty pointer to the newly freed dvar.
1671 */
1672 do {
1673 next = dcpu->dtdsc_dirty;
1674 dvar->dtdv_next = next;
1675 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1676
1677 /*
1678 * Finally, unlock this hash bucket.
1679 */
1680 ASSERT(hash[bucket].dtdh_lock == lock);
1681 ASSERT(lock & 1);
1682 hash[bucket].dtdh_lock++;
1683
1684 return (NULL);
1685next:
1686 prev = dvar;
1687 continue;
1688 }
1689
1690 if (dvar == NULL) {
1691 /*
1692 * If dvar is NULL, it is because we went off the rails:
1693 * one of the elements that we traversed in the hash chain
1694 * was deleted while we were traversing it. In this case,
1695 * we assert that we aren't doing a dealloc (deallocs lock
1696 * the hash bucket to prevent themselves from racing with
1697 * one another), and retry the hash chain traversal.
1698 */
1699 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1700 goto top;
1701 }
1702
1703 if (op != DTRACE_DYNVAR_ALLOC) {
1704 /*
1705 * If we are not to allocate a new variable, we want to
1706 * return NULL now. Before we return, check that the value
1707 * of the lock word hasn't changed. If it has, we may have
1708 * seen an inconsistent snapshot.
1709 */
1710 if (op == DTRACE_DYNVAR_NOALLOC) {
1711 if (hash[bucket].dtdh_lock != lock)
1712 goto top;
1713 } else {
1714 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1715 ASSERT(hash[bucket].dtdh_lock == lock);
1716 ASSERT(lock & 1);
1717 hash[bucket].dtdh_lock++;
1718 }
1719
1720 return (NULL);
1721 }
1722
1723 /*
1724 * We need to allocate a new dynamic variable. The size we need is the
1725 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1726 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1727 * the size of any referred-to data (dsize). We then round the final
1728 * size up to the chunksize for allocation.
1729 */
1730 for (ksize = 0, i = 0; i < nkeys; i++)
1731 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1732
1733 /*
1734 * This should be pretty much impossible, but could happen if, say,
1735 * strange DIF specified the tuple. Ideally, this should be an
1736 * assertion and not an error condition -- but that requires that the
1737 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1738 * bullet-proof. (That is, it must not be able to be fooled by
1739 * malicious DIF.) Given the lack of backwards branches in DIF,
1740 * solving this would presumably not amount to solving the Halting
1741 * Problem -- but it still seems awfully hard.
1742 */
1743 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1744 ksize + dsize > chunksize) {
1745 dcpu->dtdsc_drops++;
1746 return (NULL);
1747 }
1748
1749 nstate = DTRACE_DSTATE_EMPTY;
1750
1751 do {
1752retry:
1753 free = dcpu->dtdsc_free;
1754
1755 if (free == NULL) {
1756 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1757 void *rval;
1758
1759 if (clean == NULL) {
1760 /*
1761 * We're out of dynamic variable space on
1762 * this CPU. Unless we have tried all CPUs,
1763 * we'll try to allocate from a different
1764 * CPU.
1765 */
1766 switch (dstate->dtds_state) {
1767 case DTRACE_DSTATE_CLEAN: {
1768 void *sp = &dstate->dtds_state;
1769
1770 if (++cpu >= NCPU)
1771 cpu = 0;
1772
1773 if (dcpu->dtdsc_dirty != NULL &&
1774 nstate == DTRACE_DSTATE_EMPTY)
1775 nstate = DTRACE_DSTATE_DIRTY;
1776
1777 if (dcpu->dtdsc_rinsing != NULL)
1778 nstate = DTRACE_DSTATE_RINSING;
1779
1780 dcpu = &dstate->dtds_percpu[cpu];
1781
1782 if (cpu != me)
1783 goto retry;
1784
1785 (void) dtrace_cas32(sp,
1786 DTRACE_DSTATE_CLEAN, nstate);
1787
1788 /*
1789 * To increment the correct bean
1790 * counter, take another lap.
1791 */
1792 goto retry;
1793 }
1794
1795 case DTRACE_DSTATE_DIRTY:
1796 dcpu->dtdsc_dirty_drops++;
1797 break;
1798
1799 case DTRACE_DSTATE_RINSING:
1800 dcpu->dtdsc_rinsing_drops++;
1801 break;
1802
1803 case DTRACE_DSTATE_EMPTY:
1804 dcpu->dtdsc_drops++;
1805 break;
1806 }
1807
1808 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1809 return (NULL);
1810 }
1811
1812 /*
1813 * The clean list appears to be non-empty. We want to
1814 * move the clean list to the free list; we start by
1815 * moving the clean pointer aside.
1816 */
1817 if (dtrace_casptr(&dcpu->dtdsc_clean,
1818 clean, NULL) != clean) {
1819 /*
1820 * We are in one of two situations:
1821 *
1822 * (a) The clean list was switched to the
1823 * free list by another CPU.
1824 *
1825 * (b) The clean list was added to by the
1826 * cleansing cyclic.
1827 *
1828 * In either of these situations, we can
1829 * just reattempt the free list allocation.
1830 */
1831 goto retry;
1832 }
1833
1834 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1835
1836 /*
1837 * Now we'll move the clean list to our free list.
1838 * It's impossible for this to fail: the only way
1839 * the free list can be updated is through this
1840 * code path, and only one CPU can own the clean list.
1841 * Thus, it would only be possible for this to fail if
1842 * this code were racing with dtrace_dynvar_clean().
1843 * (That is, if dtrace_dynvar_clean() updated the clean
1844 * list, and we ended up racing to update the free
1845 * list.) This race is prevented by the dtrace_sync()
1846 * in dtrace_dynvar_clean() -- which flushes the
1847 * owners of the clean lists out before resetting
1848 * the clean lists.
1849 */
1850 dcpu = &dstate->dtds_percpu[me];
1851 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1852 ASSERT(rval == NULL);
1853 goto retry;
1854 }
1855
1856 dvar = free;
1857 new_free = dvar->dtdv_next;
1858 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1859
1860 /*
1861 * We have now allocated a new chunk. We copy the tuple keys into the
1862 * tuple array and copy any referenced key data into the data space
1863 * following the tuple array. As we do this, we relocate dttk_value
1864 * in the final tuple to point to the key data address in the chunk.
1865 */
1866 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1867 dvar->dtdv_data = (void *)(kdata + ksize);
1868 dvar->dtdv_tuple.dtt_nkeys = nkeys;
1869
1870 for (i = 0; i < nkeys; i++) {
1871 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1872 size_t kesize = key[i].dttk_size;
1873
1874 if (kesize != 0) {
1875 dtrace_bcopy(
1876 (const void *)(uintptr_t)key[i].dttk_value,
1877 (void *)kdata, kesize);
1878 dkey->dttk_value = kdata;
1879 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1880 } else {
1881 dkey->dttk_value = key[i].dttk_value;
1882 }
1883
1884 dkey->dttk_size = kesize;
1885 }
1886
1887 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1888 dvar->dtdv_hashval = hashval;
1889 dvar->dtdv_next = start;
1890
1891 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1892 return (dvar);
1893
1894 /*
1895 * The cas has failed. Either another CPU is adding an element to
1896 * this hash chain, or another CPU is deleting an element from this
1897 * hash chain. The simplest way to deal with both of these cases
1898 * (though not necessarily the most efficient) is to free our
1899 * allocated block and tail-call ourselves. Note that the free is
1900 * to the dirty list and _not_ to the free list. This is to prevent
1901 * races with allocators, above.
1902 */
1903 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1904
1905 dtrace_membar_producer();
1906
1907 do {
1908 free = dcpu->dtdsc_dirty;
1909 dvar->dtdv_next = free;
1910 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1911
1912 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1913}
1914
1915/*ARGSUSED*/
1916static void
1917dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1918{
1919 RT_NOREF_PV(arg);
1920 if ((int64_t)nval < (int64_t)*oval)
1921 *oval = nval;
1922}
1923
1924/*ARGSUSED*/
1925static void
1926dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1927{
1928 RT_NOREF_PV(arg);
1929 if ((int64_t)nval > (int64_t)*oval)
1930 *oval = nval;
1931}
1932
1933static void
1934dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1935{
1936 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1937 int64_t val = (int64_t)nval;
1938
1939 if (val < 0) {
1940 for (i = 0; i < zero; i++) {
1941 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1942 quanta[i] += incr;
1943 return;
1944 }
1945 }
1946 } else {
1947 for (i = zero + 1; i < VBDTCAST(int)DTRACE_QUANTIZE_NBUCKETS; i++) {
1948 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1949 quanta[i - 1] += incr;
1950 return;
1951 }
1952 }
1953
1954 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1955 return;
1956 }
1957
1958#ifndef VBOX
1959 ASSERT(0);
1960#else
1961 AssertFatalFailed();
1962#endif
1963}
1964
1965static void
1966dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1967{
1968 uint64_t arg = *lquanta++;
1969 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1970 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1971 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1972 int32_t val = (int32_t)nval, level;
1973
1974 ASSERT(step != 0);
1975 ASSERT(levels != 0);
1976
1977 if (val < base) {
1978 /*
1979 * This is an underflow.
1980 */
1981 lquanta[0] += incr;
1982 return;
1983 }
1984
1985 level = (val - base) / step;
1986
1987 if (level < levels) {
1988 lquanta[level + 1] += incr;
1989 return;
1990 }
1991
1992 /*
1993 * This is an overflow.
1994 */
1995 lquanta[levels + 1] += incr;
1996}
1997
1998/*ARGSUSED*/
1999static void
2000dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2001{
2002 RT_NOREF_PV(arg);
2003 data[0]++;
2004 data[1] += nval;
2005}
2006
2007/*ARGSUSED*/
2008static void
2009dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2010{
2011 int64_t snval = (int64_t)nval;
2012 uint64_t tmp[2];
2013 RT_NOREF_PV(arg);
2014
2015 data[0]++;
2016 data[1] += nval;
2017
2018 /*
2019 * What we want to say here is:
2020 *
2021 * data[2] += nval * nval;
2022 *
2023 * But given that nval is 64-bit, we could easily overflow, so
2024 * we do this as 128-bit arithmetic.
2025 */
2026 if (snval < 0)
2027 snval = -snval;
2028
2029 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2030 dtrace_add_128(data + 2, tmp, data + 2);
2031}
2032
2033/*ARGSUSED*/
2034static void
2035dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2036{
2037 RT_NOREF_PV(arg); RT_NOREF_PV(nval);
2038
2039 *oval = *oval + 1;
2040}
2041
2042/*ARGSUSED*/
2043static void
2044dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2045{
2046 RT_NOREF_PV(arg);
2047 *oval += nval;
2048}
2049
2050/*
2051 * Aggregate given the tuple in the principal data buffer, and the aggregating
2052 * action denoted by the specified dtrace_aggregation_t. The aggregation
2053 * buffer is specified as the buf parameter. This routine does not return
2054 * failure; if there is no space in the aggregation buffer, the data will be
2055 * dropped, and a corresponding counter incremented.
2056 */
2057static void
2058dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2059 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2060{
2061 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2062 uint32_t i, ndx, size, fsize;
2063 uint32_t align = sizeof (uint64_t) - 1;
2064 dtrace_aggbuffer_t *agb;
2065 dtrace_aggkey_t *key;
2066 uint32_t hashval = 0, limit, isstr;
2067 caddr_t tomax, data, kdata;
2068 dtrace_actkind_t action;
2069 dtrace_action_t *act;
2070 uintptr_t offs;
2071
2072 if (buf == NULL)
2073 return;
2074
2075 if (!agg->dtag_hasarg) {
2076 /*
2077 * Currently, only quantize() and lquantize() take additional
2078 * arguments, and they have the same semantics: an increment
2079 * value that defaults to 1 when not present. If additional
2080 * aggregating actions take arguments, the setting of the
2081 * default argument value will presumably have to become more
2082 * sophisticated...
2083 */
2084 arg = 1;
2085 }
2086
2087 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2088 size = rec->dtrd_offset - agg->dtag_base;
2089 fsize = size + rec->dtrd_size;
2090
2091 ASSERT(dbuf->dtb_tomax != NULL);
2092 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2093
2094 if ((tomax = buf->dtb_tomax) == NULL) {
2095 dtrace_buffer_drop(buf);
2096 return;
2097 }
2098
2099 /*
2100 * The metastructure is always at the bottom of the buffer.
2101 */
2102 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2103 sizeof (dtrace_aggbuffer_t));
2104
2105 if (buf->dtb_offset == 0) {
2106 /*
2107 * We just kludge up approximately 1/8th of the size to be
2108 * buckets. If this guess ends up being routinely
2109 * off-the-mark, we may need to dynamically readjust this
2110 * based on past performance.
2111 */
2112 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2113
2114 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2115 (uintptr_t)tomax || hashsize == 0) {
2116 /*
2117 * We've been given a ludicrously small buffer;
2118 * increment our drop count and leave.
2119 */
2120 dtrace_buffer_drop(buf);
2121 return;
2122 }
2123
2124 /*
2125 * And now, a pathetic attempt to try to get a an odd (or
2126 * perchance, a prime) hash size for better hash distribution.
2127 */
2128 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2129 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2130
2131 agb->dtagb_hashsize = hashsize;
2132 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2133 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2134 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2135
2136 for (i = 0; i < agb->dtagb_hashsize; i++)
2137 agb->dtagb_hash[i] = NULL;
2138 }
2139
2140 ASSERT(agg->dtag_first != NULL);
2141 ASSERT(agg->dtag_first->dta_intuple);
2142
2143 /*
2144 * Calculate the hash value based on the key. Note that we _don't_
2145 * include the aggid in the hashing (but we will store it as part of
2146 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2147 * algorithm: a simple, quick algorithm that has no known funnels, and
2148 * gets good distribution in practice. The efficacy of the hashing
2149 * algorithm (and a comparison with other algorithms) may be found by
2150 * running the ::dtrace_aggstat MDB dcmd.
2151 */
2152 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2153 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2154 limit = i + act->dta_rec.dtrd_size;
2155 ASSERT(limit <= size);
2156 isstr = DTRACEACT_ISSTRING(act);
2157
2158 for (; i < limit; i++) {
2159 hashval += data[i];
2160 hashval += (hashval << 10);
2161 hashval ^= (hashval >> 6);
2162
2163 if (isstr && data[i] == '\0')
2164 break;
2165 }
2166 }
2167
2168 hashval += (hashval << 3);
2169 hashval ^= (hashval >> 11);
2170 hashval += (hashval << 15);
2171
2172 /*
2173 * Yes, the divide here is expensive -- but it's generally the least
2174 * of the performance issues given the amount of data that we iterate
2175 * over to compute hash values, compare data, etc.
2176 */
2177 ndx = hashval % agb->dtagb_hashsize;
2178
2179 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2180 ASSERT((caddr_t)key >= tomax);
2181 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2182
2183 if (hashval != key->dtak_hashval || key->dtak_size != size)
2184 continue;
2185
2186 kdata = key->dtak_data;
2187 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2188
2189 for (act = agg->dtag_first; act->dta_intuple;
2190 act = act->dta_next) {
2191 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2192 limit = i + act->dta_rec.dtrd_size;
2193 ASSERT(limit <= size);
2194 isstr = DTRACEACT_ISSTRING(act);
2195
2196 for (; i < limit; i++) {
2197 if (kdata[i] != data[i])
2198 goto next;
2199
2200 if (isstr && data[i] == '\0')
2201 break;
2202 }
2203 }
2204
2205 if (action != key->dtak_action) {
2206 /*
2207 * We are aggregating on the same value in the same
2208 * aggregation with two different aggregating actions.
2209 * (This should have been picked up in the compiler,
2210 * so we may be dealing with errant or devious DIF.)
2211 * This is an error condition; we indicate as much,
2212 * and return.
2213 */
2214 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2215 return;
2216 }
2217
2218 /*
2219 * This is a hit: we need to apply the aggregator to
2220 * the value at this key.
2221 */
2222 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2223 return;
2224next:
2225 continue;
2226 }
2227
2228 /*
2229 * We didn't find it. We need to allocate some zero-filled space,
2230 * link it into the hash table appropriately, and apply the aggregator
2231 * to the (zero-filled) value.
2232 */
2233 offs = buf->dtb_offset;
2234 while (offs & (align - 1))
2235 offs += sizeof (uint32_t);
2236
2237 /*
2238 * If we don't have enough room to both allocate a new key _and_
2239 * its associated data, increment the drop count and return.
2240 */
2241 if ((uintptr_t)tomax + offs + fsize >
2242 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2243 dtrace_buffer_drop(buf);
2244 return;
2245 }
2246
2247 /*CONSTCOND*/
2248 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2249 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2250 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2251
2252 key->dtak_data = kdata = tomax + offs;
2253 buf->dtb_offset = offs + fsize;
2254
2255 /*
2256 * Now copy the data across.
2257 */
2258 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2259
2260 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2261 kdata[i] = data[i];
2262
2263 /*
2264 * Because strings are not zeroed out by default, we need to iterate
2265 * looking for actions that store strings, and we need to explicitly
2266 * pad these strings out with zeroes.
2267 */
2268 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2269 int nul;
2270
2271 if (!DTRACEACT_ISSTRING(act))
2272 continue;
2273
2274 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2275 limit = i + act->dta_rec.dtrd_size;
2276 ASSERT(limit <= size);
2277
2278 for (nul = 0; i < limit; i++) {
2279 if (nul) {
2280 kdata[i] = '\0';
2281 continue;
2282 }
2283
2284 if (data[i] != '\0')
2285 continue;
2286
2287 nul = 1;
2288 }
2289 }
2290
2291 for (i = size; i < fsize; i++)
2292 kdata[i] = 0;
2293
2294 key->dtak_hashval = hashval;
2295 key->dtak_size = size;
2296 key->dtak_action = action;
2297 key->dtak_next = agb->dtagb_hash[ndx];
2298 agb->dtagb_hash[ndx] = key;
2299
2300 /*
2301 * Finally, apply the aggregator.
2302 */
2303 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2304 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2305}
2306
2307/*
2308 * Given consumer state, this routine finds a speculation in the INACTIVE
2309 * state and transitions it into the ACTIVE state. If there is no speculation
2310 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2311 * incremented -- it is up to the caller to take appropriate action.
2312 */
2313static int
2314dtrace_speculation(dtrace_state_t *state)
2315{
2316 int i = 0;
2317 dtrace_speculation_state_t current;
2318 uint32_t *stat = &state->dts_speculations_unavail, count;
2319
2320 while (i < state->dts_nspeculations) {
2321 dtrace_speculation_t *spec = &state->dts_speculations[i];
2322
2323 current = spec->dtsp_state;
2324
2325 if (current != DTRACESPEC_INACTIVE) {
2326 if (current == DTRACESPEC_COMMITTINGMANY ||
2327 current == DTRACESPEC_COMMITTING ||
2328 current == DTRACESPEC_DISCARDING)
2329 stat = &state->dts_speculations_busy;
2330 i++;
2331 continue;
2332 }
2333
2334 if ( (dtrace_speculation_state_t)dtrace_cas32((uint32_t *)&spec->dtsp_state, current, DTRACESPEC_ACTIVE)
2335 == current)
2336 return (i + 1);
2337 }
2338
2339 /*
2340 * We couldn't find a speculation. If we found as much as a single
2341 * busy speculation buffer, we'll attribute this failure as "busy"
2342 * instead of "unavail".
2343 */
2344 do {
2345 count = *stat;
2346 } while (dtrace_cas32(stat, count, count + 1) != count);
2347
2348 return (0);
2349}
2350
2351/*
2352 * This routine commits an active speculation. If the specified speculation
2353 * is not in a valid state to perform a commit(), this routine will silently do
2354 * nothing. The state of the specified speculation is transitioned according
2355 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2356 */
2357static void
2358dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2359 dtrace_specid_t which)
2360{
2361 dtrace_speculation_t *spec;
2362 dtrace_buffer_t *src, *dest;
2363 uintptr_t daddr, saddr, dlimit;
2364 dtrace_speculation_state_t current, new VBDTUNASS(-1);
2365 intptr_t offs;
2366
2367 if (which == 0)
2368 return;
2369
2370 if (which > VBDTCAST(unsigned)state->dts_nspeculations) {
2371 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2372 return;
2373 }
2374
2375 spec = &state->dts_speculations[which - 1];
2376 src = &spec->dtsp_buffer[cpu];
2377 dest = &state->dts_buffer[cpu];
2378
2379 do {
2380 current = spec->dtsp_state;
2381
2382 if (current == DTRACESPEC_COMMITTINGMANY)
2383 break;
2384
2385 switch (current) {
2386 case DTRACESPEC_INACTIVE:
2387 case DTRACESPEC_DISCARDING:
2388 return;
2389
2390 case DTRACESPEC_COMMITTING:
2391 /*
2392 * This is only possible if we are (a) commit()'ing
2393 * without having done a prior speculate() on this CPU
2394 * and (b) racing with another commit() on a different
2395 * CPU. There's nothing to do -- we just assert that
2396 * our offset is 0.
2397 */
2398 ASSERT(src->dtb_offset == 0);
2399 return;
2400
2401 case DTRACESPEC_ACTIVE:
2402 new = DTRACESPEC_COMMITTING;
2403 break;
2404
2405 case DTRACESPEC_ACTIVEONE:
2406 /*
2407 * This speculation is active on one CPU. If our
2408 * buffer offset is non-zero, we know that the one CPU
2409 * must be us. Otherwise, we are committing on a
2410 * different CPU from the speculate(), and we must
2411 * rely on being asynchronously cleaned.
2412 */
2413 if (src->dtb_offset != 0) {
2414 new = DTRACESPEC_COMMITTING;
2415 break;
2416 }
2417 /*FALLTHROUGH*/
2418
2419 case DTRACESPEC_ACTIVEMANY:
2420 new = DTRACESPEC_COMMITTINGMANY;
2421 break;
2422
2423 default:
2424#ifndef VBOX
2425 ASSERT(0);
2426#else
2427 AssertFatalMsgFailed(("%d\n", current));
2428#endif
2429 }
2430 } while ((dtrace_speculation_state_t)dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new) != current);
2431
2432 /*
2433 * We have set the state to indicate that we are committing this
2434 * speculation. Now reserve the necessary space in the destination
2435 * buffer.
2436 */
2437 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2438 sizeof (uint64_t), state, NULL)) < 0) {
2439 dtrace_buffer_drop(dest);
2440 goto out;
2441 }
2442
2443 /*
2444 * We have the space; copy the buffer across. (Note that this is a
2445 * highly subobtimal bcopy(); in the unlikely event that this becomes
2446 * a serious performance issue, a high-performance DTrace-specific
2447 * bcopy() should obviously be invented.)
2448 */
2449 daddr = (uintptr_t)dest->dtb_tomax + offs;
2450 dlimit = daddr + src->dtb_offset;
2451 saddr = (uintptr_t)src->dtb_tomax;
2452
2453 /*
2454 * First, the aligned portion.
2455 */
2456 while (dlimit - daddr >= sizeof (uint64_t)) {
2457 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2458
2459 daddr += sizeof (uint64_t);
2460 saddr += sizeof (uint64_t);
2461 }
2462
2463 /*
2464 * Now any left-over bit...
2465 */
2466 while (dlimit - daddr)
2467 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2468
2469 /*
2470 * Finally, commit the reserved space in the destination buffer.
2471 */
2472 dest->dtb_offset = offs + src->dtb_offset;
2473
2474out:
2475 /*
2476 * If we're lucky enough to be the only active CPU on this speculation
2477 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2478 */
2479 if (current == DTRACESPEC_ACTIVE ||
2480 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2481 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2482 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2483
2484 ASSERT(rval == DTRACESPEC_COMMITTING); NOREF(rval);
2485 }
2486
2487 src->dtb_offset = 0;
2488 src->dtb_xamot_drops += src->dtb_drops;
2489 src->dtb_drops = 0;
2490}
2491
2492/*
2493 * This routine discards an active speculation. If the specified speculation
2494 * is not in a valid state to perform a discard(), this routine will silently
2495 * do nothing. The state of the specified speculation is transitioned
2496 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2497 */
2498static void
2499dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2500 dtrace_specid_t which)
2501{
2502 dtrace_speculation_t *spec;
2503 dtrace_speculation_state_t current, new;
2504 dtrace_buffer_t *buf;
2505
2506 if (which == 0)
2507 return;
2508
2509 if (which > VBDTCAST(unsigned)state->dts_nspeculations) {
2510 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2511 return;
2512 }
2513
2514 spec = &state->dts_speculations[which - 1];
2515 buf = &spec->dtsp_buffer[cpu];
2516
2517 do {
2518 current = spec->dtsp_state;
2519
2520 switch (current) {
2521 case DTRACESPEC_INACTIVE:
2522 case DTRACESPEC_COMMITTINGMANY:
2523 case DTRACESPEC_COMMITTING:
2524 case DTRACESPEC_DISCARDING:
2525 return;
2526
2527 case DTRACESPEC_ACTIVE:
2528 case DTRACESPEC_ACTIVEMANY:
2529 new = DTRACESPEC_DISCARDING;
2530 break;
2531
2532 case DTRACESPEC_ACTIVEONE:
2533 if (buf->dtb_offset != 0) {
2534 new = DTRACESPEC_INACTIVE;
2535 } else {
2536 new = DTRACESPEC_DISCARDING;
2537 }
2538 break;
2539
2540 default:
2541#ifndef VBOX
2542 ASSERT(0);
2543#else
2544 AssertFatalMsgFailed(("%d\n", current));
2545#endif
2546 }
2547 } while ((dtrace_speculation_state_t)dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new) != current);
2548
2549 buf->dtb_offset = 0;
2550 buf->dtb_drops = 0;
2551}
2552
2553/*
2554 * Note: not called from probe context. This function is called
2555 * asynchronously from cross call context to clean any speculations that are
2556 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2557 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2558 * speculation.
2559 */
2560static void
2561dtrace_speculation_clean_here(dtrace_state_t *state)
2562{
2563 dtrace_icookie_t cookie;
2564 processorid_t cpu = VBDT_GET_CPUID();
2565 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2566 dtrace_specid_t i;
2567
2568 cookie = dtrace_interrupt_disable();
2569
2570 if (dest->dtb_tomax == NULL) {
2571 dtrace_interrupt_enable(cookie);
2572 return;
2573 }
2574
2575 for (i = 0; i < VBDTCAST(unsigned)state->dts_nspeculations; i++) {
2576 dtrace_speculation_t *spec = &state->dts_speculations[i];
2577 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2578
2579 if (src->dtb_tomax == NULL)
2580 continue;
2581
2582 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2583 src->dtb_offset = 0;
2584 continue;
2585 }
2586
2587 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2588 continue;
2589
2590 if (src->dtb_offset == 0)
2591 continue;
2592
2593 dtrace_speculation_commit(state, cpu, i + 1);
2594 }
2595
2596 dtrace_interrupt_enable(cookie);
2597}
2598
2599#ifdef VBOX
2600/** */
2601static DECLCALLBACK(void) dtrace_speculation_clean_here_wrapper(RTCPUID idCpu, void *pvUser1, void *pvUser2)
2602{
2603 dtrace_speculation_clean_here((dtrace_state_t *)pvUser1);
2604 NOREF(pvUser2); NOREF(idCpu);
2605}
2606#endif
2607
2608/*
2609 * Note: not called from probe context. This function is called
2610 * asynchronously (and at a regular interval) to clean any speculations that
2611 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2612 * is work to be done, it cross calls all CPUs to perform that work;
2613 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2614 * INACTIVE state until they have been cleaned by all CPUs.
2615 */
2616static void
2617dtrace_speculation_clean(dtrace_state_t *state)
2618{
2619 int work = 0, rv;
2620 dtrace_specid_t i;
2621
2622 for (i = 0; i < VBDTCAST(unsigned)state->dts_nspeculations; i++) {
2623 dtrace_speculation_t *spec = &state->dts_speculations[i];
2624
2625 ASSERT(!spec->dtsp_cleaning);
2626
2627 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2628 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2629 continue;
2630
2631 work++;
2632 spec->dtsp_cleaning = 1;
2633 }
2634
2635 if (!work)
2636 return;
2637
2638#ifndef VBOX
2639 dtrace_xcall(DTRACE_CPUALL,
2640 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2641#else
2642 RTMpOnAll(dtrace_speculation_clean_here_wrapper, state, NULL);
2643#endif
2644
2645 /*
2646 * We now know that all CPUs have committed or discarded their
2647 * speculation buffers, as appropriate. We can now set the state
2648 * to inactive.
2649 */
2650 for (i = 0; i < VBDTCAST(unsigned)state->dts_nspeculations; i++) {
2651 dtrace_speculation_t *spec = &state->dts_speculations[i];
2652 dtrace_speculation_state_t current, new;
2653
2654 if (!spec->dtsp_cleaning)
2655 continue;
2656
2657 current = spec->dtsp_state;
2658 ASSERT(current == DTRACESPEC_DISCARDING ||
2659 current == DTRACESPEC_COMMITTINGMANY);
2660
2661 new = DTRACESPEC_INACTIVE;
2662
2663 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2664 ASSERT(VBDTCAST(dtrace_speculation_state_t)rv == current);
2665 spec->dtsp_cleaning = 0;
2666 }
2667}
2668
2669/*
2670 * Called as part of a speculate() to get the speculative buffer associated
2671 * with a given speculation. Returns NULL if the specified speculation is not
2672 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2673 * the active CPU is not the specified CPU -- the speculation will be
2674 * atomically transitioned into the ACTIVEMANY state.
2675 */
2676static dtrace_buffer_t *
2677dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2678 dtrace_specid_t which)
2679{
2680 dtrace_speculation_t *spec;
2681 dtrace_speculation_state_t current, new VBDTUNASS(-1);
2682 dtrace_buffer_t *buf;
2683
2684 if (which == 0)
2685 return (NULL);
2686
2687 if (which > VBDTCAST(unsigned)state->dts_nspeculations) {
2688 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2689 return (NULL);
2690 }
2691
2692 spec = &state->dts_speculations[which - 1];
2693 buf = &spec->dtsp_buffer[cpuid];
2694
2695 do {
2696 current = spec->dtsp_state;
2697
2698 switch (current) {
2699 case DTRACESPEC_INACTIVE:
2700 case DTRACESPEC_COMMITTINGMANY:
2701 case DTRACESPEC_DISCARDING:
2702 return (NULL);
2703
2704 case DTRACESPEC_COMMITTING:
2705 ASSERT(buf->dtb_offset == 0);
2706 return (NULL);
2707
2708 case DTRACESPEC_ACTIVEONE:
2709 /*
2710 * This speculation is currently active on one CPU.
2711 * Check the offset in the buffer; if it's non-zero,
2712 * that CPU must be us (and we leave the state alone).
2713 * If it's zero, assume that we're starting on a new
2714 * CPU -- and change the state to indicate that the
2715 * speculation is active on more than one CPU.
2716 */
2717 if (buf->dtb_offset != 0)
2718 return (buf);
2719
2720 new = DTRACESPEC_ACTIVEMANY;
2721 break;
2722
2723 case DTRACESPEC_ACTIVEMANY:
2724 return (buf);
2725
2726 case DTRACESPEC_ACTIVE:
2727 new = DTRACESPEC_ACTIVEONE;
2728 break;
2729
2730 default:
2731#ifndef VBOX
2732 ASSERT(0);
2733#else
2734 AssertFatalMsgFailed(("%d\n", current));
2735#endif
2736 }
2737 } while ((dtrace_speculation_state_t)dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new) != current);
2738
2739 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2740 return (buf);
2741}
2742
2743/*
2744 * Return a string. In the event that the user lacks the privilege to access
2745 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2746 * don't fail access checking.
2747 *
2748 * dtrace_dif_variable() uses this routine as a helper for various
2749 * builtin values such as 'execname' and 'probefunc.'
2750 */
2751VBDTSTATIC uintptr_t
2752dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2753 dtrace_mstate_t *mstate)
2754{
2755 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2756 uintptr_t ret;
2757 size_t strsz;
2758
2759 /*
2760 * The easy case: this probe is allowed to read all of memory, so
2761 * we can just return this as a vanilla pointer.
2762 */
2763 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2764 return (addr);
2765
2766 /*
2767 * This is the tougher case: we copy the string in question from
2768 * kernel memory into scratch memory and return it that way: this
2769 * ensures that we won't trip up when access checking tests the
2770 * BYREF return value.
2771 */
2772 strsz = dtrace_strlen((char *)addr, size) + 1;
2773
2774 if (mstate->dtms_scratch_ptr + strsz >
2775 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2776 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2777 return (NULL);
2778 }
2779
2780 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2781 strsz);
2782 ret = mstate->dtms_scratch_ptr;
2783 mstate->dtms_scratch_ptr += strsz;
2784 return (ret);
2785}
2786
2787/*
2788 * This function implements the DIF emulator's variable lookups. The emulator
2789 * passes a reserved variable identifier and optional built-in array index.
2790 */
2791static uint64_t
2792dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2793 uint64_t ndx)
2794{
2795 /*
2796 * If we're accessing one of the uncached arguments, we'll turn this
2797 * into a reference in the args array.
2798 */
2799 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2800 ndx = v - DIF_VAR_ARG0;
2801 v = DIF_VAR_ARGS;
2802 }
2803
2804 switch (v) {
2805 case DIF_VAR_ARGS:
2806 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2807 if (ndx >= sizeof (mstate->dtms_arg) /
2808 sizeof (mstate->dtms_arg[0])) {
2809 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2810 dtrace_provider_t *pv;
2811 uint64_t val;
2812
2813 pv = mstate->dtms_probe->dtpr_provider;
2814 if (pv->dtpv_pops.dtps_getargval != NULL)
2815 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2816 mstate->dtms_probe->dtpr_id,
2817 mstate->dtms_probe->dtpr_arg, ndx, aframes);
2818 else
2819 val = dtrace_getarg(ndx, aframes);
2820
2821 /*
2822 * This is regrettably required to keep the compiler
2823 * from tail-optimizing the call to dtrace_getarg().
2824 * The condition always evaluates to true, but the
2825 * compiler has no way of figuring that out a priori.
2826 * (None of this would be necessary if the compiler
2827 * could be relied upon to _always_ tail-optimize
2828 * the call to dtrace_getarg() -- but it can't.)
2829 */
2830 if (mstate->dtms_probe != NULL)
2831 return (val);
2832
2833#ifndef VBOX
2834 ASSERT(0);
2835#else
2836 AssertFatalFailed();
2837#endif
2838 }
2839
2840 return (mstate->dtms_arg[ndx]);
2841
2842 case DIF_VAR_UREGS: {
2843#ifndef VBOX
2844 klwp_t *lwp;
2845
2846 if (!dtrace_priv_proc(state))
2847 return (0);
2848
2849 if ((lwp = curthread->t_lwp) == NULL) {
2850 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2851 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval = NULL;
2852 return (0);
2853 }
2854
2855 return (dtrace_getreg(lwp->lwp_regs, ndx));
2856#else
2857 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2858 return (0);
2859#endif
2860 }
2861
2862 case DIF_VAR_CURTHREAD:
2863 if (!dtrace_priv_kernel(state))
2864 return (0);
2865#ifndef VBOX
2866 return ((uint64_t)(uintptr_t)curthread);
2867#else
2868 return ((uintptr_t)RTThreadNativeSelf());
2869#endif
2870
2871 case DIF_VAR_TIMESTAMP:
2872 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2873 mstate->dtms_timestamp = dtrace_gethrtime();
2874 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2875 }
2876 return (mstate->dtms_timestamp);
2877
2878 case DIF_VAR_VTIMESTAMP:
2879#ifndef VBOX
2880 ASSERT(dtrace_vtime_references != 0);
2881 return (curthread->t_dtrace_vtime);
2882#else
2883 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2884 return (0);
2885#endif
2886
2887 case DIF_VAR_WALLTIMESTAMP:
2888 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2889 mstate->dtms_walltimestamp = dtrace_gethrestime();
2890 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2891 }
2892 return (mstate->dtms_walltimestamp);
2893
2894 case DIF_VAR_IPL:
2895 if (!dtrace_priv_kernel(state))
2896 return (0);
2897 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2898 mstate->dtms_ipl = dtrace_getipl();
2899 mstate->dtms_present |= DTRACE_MSTATE_IPL;
2900 }
2901 return (mstate->dtms_ipl);
2902
2903 case DIF_VAR_EPID:
2904 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2905 return (mstate->dtms_epid);
2906
2907 case DIF_VAR_ID:
2908 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2909 return (mstate->dtms_probe->dtpr_id);
2910
2911 case DIF_VAR_STACKDEPTH:
2912 if (!dtrace_priv_kernel(state))
2913 return (0);
2914 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2915 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2916
2917 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2918 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2919 }
2920 return (mstate->dtms_stackdepth);
2921
2922 case DIF_VAR_USTACKDEPTH:
2923 if (!dtrace_priv_proc(state))
2924 return (0);
2925 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2926 /*
2927 * See comment in DIF_VAR_PID.
2928 */
2929 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2930 CPU_ON_INTR(CPU)) {
2931 mstate->dtms_ustackdepth = 0;
2932 } else {
2933 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2934 mstate->dtms_ustackdepth =
2935 dtrace_getustackdepth();
2936 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2937 }
2938 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2939 }
2940 return (mstate->dtms_ustackdepth);
2941
2942 case DIF_VAR_CALLER:
2943 if (!dtrace_priv_kernel(state))
2944 return (0);
2945 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2946 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2947
2948 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2949 /*
2950 * If this is an unanchored probe, we are
2951 * required to go through the slow path:
2952 * dtrace_caller() only guarantees correct
2953 * results for anchored probes.
2954 */
2955 pc_t caller[2];
2956
2957 dtrace_getpcstack(caller, 2, aframes,
2958 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2959 mstate->dtms_caller = caller[1];
2960 } else if ((mstate->dtms_caller =
2961 dtrace_caller(aframes)) == VBDTCAST(uintptr_t)-1) {
2962 /*
2963 * We have failed to do this the quick way;
2964 * we must resort to the slower approach of
2965 * calling dtrace_getpcstack().
2966 */
2967 pc_t caller;
2968
2969 dtrace_getpcstack(&caller, 1, aframes, NULL);
2970 mstate->dtms_caller = caller;
2971 }
2972
2973 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2974 }
2975 return (mstate->dtms_caller);
2976
2977 case DIF_VAR_UCALLER:
2978 if (!dtrace_priv_proc(state))
2979 return (0);
2980
2981 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2982 uint64_t ustack[3];
2983
2984 /*
2985 * dtrace_getupcstack() fills in the first uint64_t
2986 * with the current PID. The second uint64_t will
2987 * be the program counter at user-level. The third
2988 * uint64_t will contain the caller, which is what
2989 * we're after.
2990 */
2991 ustack[2] = NULL;
2992 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2993 dtrace_getupcstack(ustack, 3);
2994 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2995 mstate->dtms_ucaller = ustack[2];
2996 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2997 }
2998
2999 return (mstate->dtms_ucaller);
3000
3001 case DIF_VAR_PROBEPROV:
3002 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3003 return (dtrace_dif_varstr(
3004 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3005 state, mstate));
3006
3007 case DIF_VAR_PROBEMOD:
3008 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3009 return (dtrace_dif_varstr(
3010 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3011 state, mstate));
3012
3013 case DIF_VAR_PROBEFUNC:
3014 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3015 return (dtrace_dif_varstr(
3016 (uintptr_t)mstate->dtms_probe->dtpr_func,
3017 state, mstate));
3018
3019 case DIF_VAR_PROBENAME:
3020 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3021 return (dtrace_dif_varstr(
3022 (uintptr_t)mstate->dtms_probe->dtpr_name,
3023 state, mstate));
3024
3025 case DIF_VAR_PID:
3026 if (!dtrace_priv_proc(state))
3027 return (0);
3028
3029#ifndef VBOX
3030 /*
3031 * Note that we are assuming that an unanchored probe is
3032 * always due to a high-level interrupt. (And we're assuming
3033 * that there is only a single high level interrupt.)
3034 */
3035 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3036 return (pid0.pid_id);
3037
3038 /*
3039 * It is always safe to dereference one's own t_procp pointer:
3040 * it always points to a valid, allocated proc structure.
3041 * Further, it is always safe to dereference the p_pidp member
3042 * of one's own proc structure. (These are truisms becuase
3043 * threads and processes don't clean up their own state --
3044 * they leave that task to whomever reaps them.)
3045 */
3046 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3047#else
3048 return (RTProcSelf());
3049#endif
3050
3051 case DIF_VAR_PPID:
3052 if (!dtrace_priv_proc(state))
3053 return (0);
3054
3055#ifndef VBOX
3056 /*
3057 * See comment in DIF_VAR_PID.
3058 */
3059 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3060 return (pid0.pid_id);
3061
3062 /*
3063 * It is always safe to dereference one's own t_procp pointer:
3064 * it always points to a valid, allocated proc structure.
3065 * (This is true because threads don't clean up their own
3066 * state -- they leave that task to whomever reaps them.)
3067 */
3068 return ((uint64_t)curthread->t_procp->p_ppid);
3069#else
3070 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3071 return (0); /** @todo parent pid? */
3072#endif
3073
3074 case DIF_VAR_TID:
3075#ifndef VBOX
3076 /*
3077 * See comment in DIF_VAR_PID.
3078 */
3079 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3080 return (0);
3081
3082 return ((uint64_t)curthread->t_tid);
3083#else
3084 return (RTThreadNativeSelf()); /** @todo proper tid? */
3085#endif
3086
3087 case DIF_VAR_EXECNAME:
3088 if (!dtrace_priv_proc(state))
3089 return (0);
3090
3091#ifndef VBOX
3092 /*
3093 * See comment in DIF_VAR_PID.
3094 */
3095 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3096 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3097
3098 /*
3099 * It is always safe to dereference one's own t_procp pointer:
3100 * it always points to a valid, allocated proc structure.
3101 * (This is true because threads don't clean up their own
3102 * state -- they leave that task to whomever reaps them.)
3103 */
3104 return (dtrace_dif_varstr(
3105 (uintptr_t)curthread->t_procp->p_user.u_comm,
3106 state, mstate));
3107#else
3108 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3109 return (0); /** @todo execname */
3110#endif
3111
3112 case DIF_VAR_ZONENAME:
3113 if (!dtrace_priv_proc(state))
3114 return (0);
3115
3116#ifndef VBOX
3117 /*
3118 * See comment in DIF_VAR_PID.
3119 */
3120 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3121 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3122
3123 /*
3124 * It is always safe to dereference one's own t_procp pointer:
3125 * it always points to a valid, allocated proc structure.
3126 * (This is true because threads don't clean up their own
3127 * state -- they leave that task to whomever reaps them.)
3128 */
3129 return (dtrace_dif_varstr(
3130 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3131 state, mstate));
3132#else
3133 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3134 return (0);
3135#endif
3136
3137 case DIF_VAR_UID:
3138 if (!dtrace_priv_proc(state))
3139 return (0);
3140
3141#ifndef VBOX
3142 /*
3143 * See comment in DIF_VAR_PID.
3144 */
3145 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3146 return ((uint64_t)p0.p_cred->cr_uid);
3147
3148 /*
3149 * It is always safe to dereference one's own t_procp pointer:
3150 * it always points to a valid, allocated proc structure.
3151 * (This is true because threads don't clean up their own
3152 * state -- they leave that task to whomever reaps them.)
3153 *
3154 * Additionally, it is safe to dereference one's own process
3155 * credential, since this is never NULL after process birth.
3156 */
3157 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3158#else
3159 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3160 return (0);
3161#endif
3162
3163 case DIF_VAR_GID:
3164 if (!dtrace_priv_proc(state))
3165 return (0);
3166
3167#ifndef VBOX
3168 /*
3169 * See comment in DIF_VAR_PID.
3170 */
3171 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3172 return ((uint64_t)p0.p_cred->cr_gid);
3173
3174 /*
3175 * It is always safe to dereference one's own t_procp pointer:
3176 * it always points to a valid, allocated proc structure.
3177 * (This is true because threads don't clean up their own
3178 * state -- they leave that task to whomever reaps them.)
3179 *
3180 * Additionally, it is safe to dereference one's own process
3181 * credential, since this is never NULL after process birth.
3182 */
3183 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3184#else
3185 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3186 return (0);
3187#endif
3188
3189 case DIF_VAR_ERRNO: {
3190#ifndef VBOX
3191 klwp_t *lwp;
3192#endif
3193 if (!dtrace_priv_proc(state))
3194 return (0);
3195
3196#ifndef VBOX
3197 /*
3198 * See comment in DIF_VAR_PID.
3199 */
3200 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3201 return (0);
3202
3203 /*
3204 * It is always safe to dereference one's own t_lwp pointer in
3205 * the event that this pointer is non-NULL. (This is true
3206 * because threads and lwps don't clean up their own state --
3207 * they leave that task to whomever reaps them.)
3208 */
3209 if ((lwp = curthread->t_lwp) == NULL)
3210 return (0);
3211
3212 return ((uint64_t)lwp->lwp_errno);
3213#else
3214 cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3215 return (0);
3216#endif
3217 }
3218 default:
3219 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3220 return (0);
3221 }
3222}
3223
3224/*
3225 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3226 * Notice that we don't bother validating the proper number of arguments or
3227 * their types in the tuple stack. This isn't needed because all argument
3228 * interpretation is safe because of our load safety -- the worst that can
3229 * happen is that a bogus program can obtain bogus results.
3230 */
3231static void
3232dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3233 dtrace_key_t *tupregs, int nargs,
3234 dtrace_mstate_t *mstate, dtrace_state_t *state)
3235{
3236 volatile uint16_t *flags = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
3237 volatile uintptr_t *illval = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval;
3238 dtrace_vstate_t *vstate = &state->dts_vstate;
3239
3240#ifndef VBOX
3241 union {
3242 mutex_impl_t mi;
3243 uint64_t mx;
3244 } m;
3245
3246 union {
3247 krwlock_t ri;
3248 uintptr_t rw;
3249 } r;
3250#endif
3251
3252 switch (subr) {
3253 case DIF_SUBR_RAND:
3254 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3255 break;
3256
3257 case DIF_SUBR_MUTEX_OWNED:
3258#ifndef VBOX
3259 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3260 mstate, vstate)) {
3261 regs[rd] = NULL;
3262 break;
3263 }
3264
3265 m.mx = dtrace_load64(tupregs[0].dttk_value);
3266 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3267 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3268 else
3269 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3270#else
3271 regs[rd] = 0;
3272 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3273#endif
3274 break;
3275
3276 case DIF_SUBR_MUTEX_OWNER:
3277#ifndef VBOX
3278 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3279 mstate, vstate)) {
3280 regs[rd] = NULL;
3281 break;
3282 }
3283
3284 m.mx = dtrace_load64(tupregs[0].dttk_value);
3285 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3286 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3287 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3288 else
3289 regs[rd] = 0;
3290#else
3291 regs[rd] = 0;
3292 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3293#endif
3294 break;
3295
3296 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3297#ifndef VBOX
3298 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3299 mstate, vstate)) {
3300 regs[rd] = NULL;
3301 break;
3302 }
3303
3304 m.mx = dtrace_load64(tupregs[0].dttk_value);
3305 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3306#else
3307 regs[rd] = 0;
3308 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3309#endif
3310 break;
3311
3312 case DIF_SUBR_MUTEX_TYPE_SPIN:
3313#ifndef VBOX
3314 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3315 mstate, vstate)) {
3316 regs[rd] = NULL;
3317 break;
3318 }
3319
3320 m.mx = dtrace_load64(tupregs[0].dttk_value);
3321 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3322#else
3323 regs[rd] = 0;
3324 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3325#endif
3326 break;
3327
3328 case DIF_SUBR_RW_READ_HELD: {
3329#ifndef VBOX
3330 uintptr_t tmp;
3331
3332 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3333 mstate, vstate)) {
3334 regs[rd] = NULL;
3335 break;
3336 }
3337
3338 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3339 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3340#else
3341 regs[rd] = 0;
3342 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3343#endif
3344 break;
3345 }
3346
3347 case DIF_SUBR_RW_WRITE_HELD:
3348#ifndef VBOX
3349 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3350 mstate, vstate)) {
3351 regs[rd] = NULL;
3352 break;
3353 }
3354
3355 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3356 regs[rd] = _RW_WRITE_HELD(&r.ri);
3357#else
3358 regs[rd] = 0;
3359 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3360#endif
3361 break;
3362
3363 case DIF_SUBR_RW_ISWRITER:
3364#ifndef VBOX
3365 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3366 mstate, vstate)) {
3367 regs[rd] = NULL;
3368 break;
3369 }
3370
3371 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3372 regs[rd] = _RW_ISWRITER(&r.ri);
3373#else
3374 regs[rd] = 0;
3375 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3376#endif
3377 break;
3378
3379 case DIF_SUBR_BCOPY: {
3380 /*
3381 * We need to be sure that the destination is in the scratch
3382 * region -- no other region is allowed.
3383 */
3384 uintptr_t src = tupregs[0].dttk_value;
3385 uintptr_t dest = tupregs[1].dttk_value;
3386 size_t size = tupregs[2].dttk_value;
3387
3388 if (!dtrace_inscratch(dest, size, mstate)) {
3389 *flags |= CPU_DTRACE_BADADDR;
3390 *illval = regs[rd];
3391 break;
3392 }
3393
3394 if (!dtrace_canload(src, size, mstate, vstate)) {
3395 regs[rd] = NULL;
3396 break;
3397 }
3398
3399 dtrace_bcopy((void *)src, (void *)dest, size);
3400 break;
3401 }
3402
3403 case DIF_SUBR_ALLOCA:
3404 case DIF_SUBR_COPYIN: {
3405 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3406 uint64_t size =
3407 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3408 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3409
3410 /*
3411 * This action doesn't require any credential checks since
3412 * probes will not activate in user contexts to which the
3413 * enabling user does not have permissions.
3414 */
3415
3416 /*
3417 * Rounding up the user allocation size could have overflowed
3418 * a large, bogus allocation (like -1ULL) to 0.
3419 */
3420 if (scratch_size < size ||
3421 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3422 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3423 regs[rd] = NULL;
3424 break;
3425 }
3426
3427 if (subr == DIF_SUBR_COPYIN) {
3428 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3429 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3430 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3431 }
3432
3433 mstate->dtms_scratch_ptr += scratch_size;
3434 regs[rd] = dest;
3435 break;
3436 }
3437
3438 case DIF_SUBR_COPYINTO: {
3439 uint64_t size = tupregs[1].dttk_value;
3440 uintptr_t dest = tupregs[2].dttk_value;
3441
3442 /*
3443 * This action doesn't require any credential checks since
3444 * probes will not activate in user contexts to which the
3445 * enabling user does not have permissions.
3446 */
3447 if (!dtrace_inscratch(dest, size, mstate)) {
3448 *flags |= CPU_DTRACE_BADADDR;
3449 *illval = regs[rd];
3450 break;
3451 }
3452
3453 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3454 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3455 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3456 break;
3457 }
3458
3459 case DIF_SUBR_COPYINSTR: {
3460 uintptr_t dest = mstate->dtms_scratch_ptr;
3461 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3462
3463 if (nargs > 1 && tupregs[1].dttk_value < size)
3464 size = tupregs[1].dttk_value + 1;
3465
3466 /*
3467 * This action doesn't require any credential checks since
3468 * probes will not activate in user contexts to which the
3469 * enabling user does not have permissions.
3470 */
3471 if (!DTRACE_INSCRATCH(mstate, size)) {
3472 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3473 regs[rd] = NULL;
3474 break;
3475 }
3476
3477 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3478 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3479 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3480
3481 ((char *)dest)[size - 1] = '\0';
3482 mstate->dtms_scratch_ptr += size;
3483 regs[rd] = dest;
3484 break;
3485 }
3486
3487 case DIF_SUBR_MSGSIZE:
3488 case DIF_SUBR_MSGDSIZE: {
3489#ifndef VBOX
3490 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3491 uintptr_t wptr, rptr;
3492 size_t count = 0;
3493 int cont = 0;
3494
3495 while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3496
3497 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3498 vstate)) {
3499 regs[rd] = NULL;
3500 break;
3501 }
3502
3503 wptr = dtrace_loadptr(baddr +
3504 offsetof(mblk_t, b_wptr));
3505
3506 rptr = dtrace_loadptr(baddr +
3507 offsetof(mblk_t, b_rptr));
3508
3509 if (wptr < rptr) {
3510 *flags |= CPU_DTRACE_BADADDR;
3511 *illval = tupregs[0].dttk_value;
3512 break;
3513 }
3514
3515 daddr = dtrace_loadptr(baddr +
3516 offsetof(mblk_t, b_datap));
3517
3518 baddr = dtrace_loadptr(baddr +
3519 offsetof(mblk_t, b_cont));
3520
3521 /*
3522 * We want to prevent against denial-of-service here,
3523 * so we're only going to search the list for
3524 * dtrace_msgdsize_max mblks.
3525 */
3526 if (cont++ > dtrace_msgdsize_max) {
3527 *flags |= CPU_DTRACE_ILLOP;
3528 break;
3529 }
3530
3531 if (subr == DIF_SUBR_MSGDSIZE) {
3532 if (dtrace_load8(daddr +
3533 offsetof(dblk_t, db_type)) != M_DATA)
3534 continue;
3535 }
3536
3537 count += wptr - rptr;
3538 }
3539
3540 if (!(*flags & CPU_DTRACE_FAULT))
3541 regs[rd] = count;
3542
3543#else
3544 regs[rd] = 0;
3545 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3546#endif
3547 break;
3548 }
3549
3550 case DIF_SUBR_PROGENYOF: {
3551#ifndef VBOX
3552 pid_t pid = tupregs[0].dttk_value;
3553 proc_t *p;
3554 int rval = 0;
3555
3556 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3557
3558 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3559 if (p->p_pidp->pid_id == pid) {
3560 rval = 1;
3561 break;
3562 }
3563 }
3564
3565 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3566
3567 regs[rd] = rval;
3568#else
3569 regs[rd] = 0;
3570 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3571#endif
3572 break;
3573 }
3574
3575 case DIF_SUBR_SPECULATION:
3576 regs[rd] = dtrace_speculation(state);
3577 break;
3578
3579 case DIF_SUBR_COPYOUT: {
3580 uintptr_t kaddr = tupregs[0].dttk_value;
3581 uintptr_t uaddr = tupregs[1].dttk_value;
3582 uint64_t size = tupregs[2].dttk_value;
3583
3584 if (!dtrace_destructive_disallow &&
3585 dtrace_priv_proc_control(state) &&
3586 !dtrace_istoxic(kaddr, size)) {
3587 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3588 dtrace_copyout(kaddr, uaddr, size, flags);
3589 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3590 }
3591 break;
3592 }
3593
3594 case DIF_SUBR_COPYOUTSTR: {
3595 uintptr_t kaddr = tupregs[0].dttk_value;
3596 uintptr_t uaddr = tupregs[1].dttk_value;
3597 uint64_t size = tupregs[2].dttk_value;
3598
3599 if (!dtrace_destructive_disallow &&
3600 dtrace_priv_proc_control(state) &&
3601 !dtrace_istoxic(kaddr, size)) {
3602 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3603 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3604 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3605 }
3606 break;
3607 }
3608
3609 case DIF_SUBR_STRLEN: {
3610 size_t sz;
3611 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3612 sz = dtrace_strlen((char *)addr,
3613 state->dts_options[DTRACEOPT_STRSIZE]);
3614
3615 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3616 regs[rd] = NULL;
3617 break;
3618 }
3619
3620 regs[rd] = sz;
3621
3622 break;
3623 }
3624
3625 case DIF_SUBR_STRCHR:
3626 case DIF_SUBR_STRRCHR: {
3627 /*
3628 * We're going to iterate over the string looking for the
3629 * specified character. We will iterate until we have reached
3630 * the string length or we have found the character. If this
3631 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3632 * of the specified character instead of the first.
3633 */
3634 uintptr_t saddr = tupregs[0].dttk_value;
3635 uintptr_t addr = tupregs[0].dttk_value;
3636 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3637 char c, target = (char)tupregs[1].dttk_value;
3638
3639 for (regs[rd] = NULL; addr < limit; addr++) {
3640 if ((c = dtrace_load8(addr)) == target) {
3641 regs[rd] = addr;
3642
3643 if (subr == DIF_SUBR_STRCHR)
3644 break;
3645 }
3646
3647 if (c == '\0')
3648 break;
3649 }
3650
3651 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3652 regs[rd] = NULL;
3653 break;
3654 }
3655
3656 break;
3657 }
3658
3659 case DIF_SUBR_STRSTR:
3660 case DIF_SUBR_INDEX:
3661 case DIF_SUBR_RINDEX: {
3662 /*
3663 * We're going to iterate over the string looking for the
3664 * specified string. We will iterate until we have reached
3665 * the string length or we have found the string. (Yes, this
3666 * is done in the most naive way possible -- but considering
3667 * that the string we're searching for is likely to be
3668 * relatively short, the complexity of Rabin-Karp or similar
3669 * hardly seems merited.)
3670 */
3671 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3672 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3673 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3674 size_t len = dtrace_strlen(addr, size);
3675 size_t sublen = dtrace_strlen(substr, size);
3676 char *limit = addr + len, *orig = addr;
3677 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3678 int inc = 1;
3679
3680 regs[rd] = notfound;
3681
3682 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3683 regs[rd] = NULL;
3684 break;
3685 }
3686
3687 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3688 vstate)) {
3689 regs[rd] = NULL;
3690 break;
3691 }
3692
3693 /*
3694 * strstr() and index()/rindex() have similar semantics if
3695 * both strings are the empty string: strstr() returns a
3696 * pointer to the (empty) string, and index() and rindex()
3697 * both return index 0 (regardless of any position argument).
3698 */
3699 if (sublen == 0 && len == 0) {
3700 if (subr == DIF_SUBR_STRSTR)
3701 regs[rd] = (uintptr_t)addr;
3702 else
3703 regs[rd] = 0;
3704 break;
3705 }
3706
3707 if (subr != DIF_SUBR_STRSTR) {
3708 if (subr == DIF_SUBR_RINDEX) {
3709 limit = orig - 1;
3710 addr += len;
3711 inc = -1;
3712 }
3713
3714 /*
3715 * Both index() and rindex() take an optional position
3716 * argument that denotes the starting position.
3717 */
3718 if (nargs == 3) {
3719 int64_t pos = (int64_t)tupregs[2].dttk_value;
3720
3721 /*
3722 * If the position argument to index() is
3723 * negative, Perl implicitly clamps it at
3724 * zero. This semantic is a little surprising
3725 * given the special meaning of negative
3726 * positions to similar Perl functions like
3727 * substr(), but it appears to reflect a
3728 * notion that index() can start from a
3729 * negative index and increment its way up to
3730 * the string. Given this notion, Perl's
3731 * rindex() is at least self-consistent in
3732 * that it implicitly clamps positions greater
3733 * than the string length to be the string
3734 * length. Where Perl completely loses
3735 * coherence, however, is when the specified
3736 * substring is the empty string (""). In
3737 * this case, even if the position is
3738 * negative, rindex() returns 0 -- and even if
3739 * the position is greater than the length,
3740 * index() returns the string length. These
3741 * semantics violate the notion that index()
3742 * should never return a value less than the
3743 * specified position and that rindex() should
3744 * never return a value greater than the
3745 * specified position. (One assumes that
3746 * these semantics are artifacts of Perl's
3747 * implementation and not the results of
3748 * deliberate design -- it beggars belief that
3749 * even Larry Wall could desire such oddness.)
3750 * While in the abstract one would wish for
3751 * consistent position semantics across
3752 * substr(), index() and rindex() -- or at the
3753 * very least self-consistent position
3754 * semantics for index() and rindex() -- we
3755 * instead opt to keep with the extant Perl
3756 * semantics, in all their broken glory. (Do
3757 * we have more desire to maintain Perl's
3758 * semantics than Perl does? Probably.)
3759 */
3760 if (subr == DIF_SUBR_RINDEX) {
3761 if (pos < 0) {
3762 if (sublen == 0)
3763 regs[rd] = 0;
3764 break;
3765 }
3766
3767 if (VBDTCAST(uint64_t)pos > len)
3768 pos = len;
3769 } else {
3770 if (pos < 0)
3771 pos = 0;
3772
3773 if (VBDTCAST(uint64_t)pos >= len) {
3774 if (sublen == 0)
3775 regs[rd] = len;
3776 break;
3777 }
3778 }
3779
3780 addr = orig + pos;
3781 }
3782 }
3783
3784 for (regs[rd] = notfound; addr != limit; addr += inc) {
3785 if (dtrace_strncmp(addr, substr, sublen) == 0) {
3786 if (subr != DIF_SUBR_STRSTR) {
3787 /*
3788 * As D index() and rindex() are
3789 * modeled on Perl (and not on awk),
3790 * we return a zero-based (and not a
3791 * one-based) index. (For you Perl
3792 * weenies: no, we're not going to add
3793 * $[ -- and shouldn't you be at a con
3794 * or something?)
3795 */
3796 regs[rd] = (uintptr_t)(addr - orig);
3797 break;
3798 }
3799
3800 ASSERT(subr == DIF_SUBR_STRSTR);
3801 regs[rd] = (uintptr_t)addr;
3802 break;
3803 }
3804 }
3805
3806 break;
3807 }
3808
3809 case DIF_SUBR_STRTOK: {
3810 uintptr_t addr = tupregs[0].dttk_value;
3811 uintptr_t tokaddr = tupregs[1].dttk_value;
3812 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3813 uintptr_t limit, toklimit = tokaddr + size;
3814 uint8_t c VBDTUNASS(0), tokmap[32]; /* 256 / 8 */
3815 char *dest = (char *)mstate->dtms_scratch_ptr;
3816 VBDTTYPE(unsigned,int) i;
3817
3818 /*
3819 * Check both the token buffer and (later) the input buffer,
3820 * since both could be non-scratch addresses.
3821 */
3822 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3823 regs[rd] = NULL;
3824 break;
3825 }
3826
3827 if (!DTRACE_INSCRATCH(mstate, size)) {
3828 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3829 regs[rd] = NULL;
3830 break;
3831 }
3832
3833 if (addr == NULL) {
3834 /*
3835 * If the address specified is NULL, we use our saved
3836 * strtok pointer from the mstate. Note that this
3837 * means that the saved strtok pointer is _only_
3838 * valid within multiple enablings of the same probe --
3839 * it behaves like an implicit clause-local variable.
3840 */
3841 addr = mstate->dtms_strtok;
3842 } else {
3843 /*
3844 * If the user-specified address is non-NULL we must
3845 * access check it. This is the only time we have
3846 * a chance to do so, since this address may reside
3847 * in the string table of this clause-- future calls
3848 * (when we fetch addr from mstate->dtms_strtok)
3849 * would fail this access check.
3850 */
3851 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3852 regs[rd] = NULL;
3853 break;
3854 }
3855 }
3856
3857 /*
3858 * First, zero the token map, and then process the token
3859 * string -- setting a bit in the map for every character
3860 * found in the token string.
3861 */
3862 for (i = 0; i < sizeof (tokmap); i++)
3863 tokmap[i] = 0;
3864
3865 for (; tokaddr < toklimit; tokaddr++) {
3866 if ((c = dtrace_load8(tokaddr)) == '\0')
3867 break;
3868
3869 ASSERT((c >> 3) < sizeof (tokmap));
3870 tokmap[c >> 3] |= (1 << (c & 0x7));
3871 }
3872
3873 for (limit = addr + size; addr < limit; addr++) {
3874 /*
3875 * We're looking for a character that is _not_ contained
3876 * in the token string.
3877 */
3878 if ((c = dtrace_load8(addr)) == '\0')
3879 break;
3880
3881 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3882 break;
3883 }
3884
3885 if (c == '\0') {
3886 /*
3887 * We reached the end of the string without finding
3888 * any character that was not in the token string.
3889 * We return NULL in this case, and we set the saved
3890 * address to NULL as well.
3891 */
3892 regs[rd] = NULL;
3893 mstate->dtms_strtok = NULL;
3894 break;
3895 }
3896
3897 /*
3898 * From here on, we're copying into the destination string.
3899 */
3900 for (i = 0; addr < limit && i < size - 1; addr++) {
3901 if ((c = dtrace_load8(addr)) == '\0')
3902 break;
3903
3904 if (tokmap[c >> 3] & (1 << (c & 0x7)))
3905 break;
3906
3907 ASSERT(i < size);
3908 dest[i++] = c;
3909 }
3910
3911 ASSERT(i < size);
3912 dest[i] = '\0';
3913 regs[rd] = (uintptr_t)dest;
3914 mstate->dtms_scratch_ptr += size;
3915 mstate->dtms_strtok = addr;
3916 break;
3917 }
3918
3919 case DIF_SUBR_SUBSTR: {
3920 uintptr_t s = tupregs[0].dttk_value;
3921 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3922 char *d = (char *)mstate->dtms_scratch_ptr;
3923 int64_t index = (int64_t)tupregs[1].dttk_value;
3924 int64_t remaining = (int64_t)tupregs[2].dttk_value;
3925 size_t len = dtrace_strlen((char *)s, size);
3926 int64_t i;
3927
3928 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3929 regs[rd] = NULL;
3930 break;
3931 }
3932
3933 if (!DTRACE_INSCRATCH(mstate, size)) {
3934 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3935 regs[rd] = NULL;
3936 break;
3937 }
3938
3939 if (nargs <= 2)
3940 remaining = (int64_t)size;
3941
3942 if (index < 0) {
3943 index += len;
3944
3945 if (index < 0 && index + remaining > 0) {
3946 remaining += index;
3947 index = 0;
3948 }
3949 }
3950
3951 if (VBDTCAST(uint64_t)index >= len || index < 0) {
3952 remaining = 0;
3953 } else if (remaining < 0) {
3954 remaining += len - index;
3955 } else if (VBDTCAST(uint64_t)index + remaining > size) {
3956 remaining = size - index;
3957 }
3958
3959 for (i = 0; i < remaining; i++) {
3960 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
3961 break;
3962 }
3963
3964 d[i] = '\0';
3965
3966 mstate->dtms_scratch_ptr += size;
3967 regs[rd] = (uintptr_t)d;
3968 break;
3969 }
3970
3971 case DIF_SUBR_GETMAJOR:
3972#ifndef VBOX
3973#ifdef _LP64
3974 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3975#else
3976 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3977#endif
3978#else
3979 regs[rd] = 0;
3980 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3981#endif
3982 break;
3983
3984 case DIF_SUBR_GETMINOR:
3985#ifndef VBOX
3986#ifdef _LP64
3987 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3988#else
3989 regs[rd] = tupregs[0].dttk_value & MAXMIN;
3990#endif
3991#else
3992 regs[rd] = 0;
3993 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3994#endif
3995 break;
3996
3997 case DIF_SUBR_DDI_PATHNAME: {
3998#ifndef VBOX
3999 /*
4000 * This one is a galactic mess. We are going to roughly
4001 * emulate ddi_pathname(), but it's made more complicated
4002 * by the fact that we (a) want to include the minor name and
4003 * (b) must proceed iteratively instead of recursively.
4004 */
4005 uintptr_t dest = mstate->dtms_scratch_ptr;
4006 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4007 char *start = (char *)dest, *end = start + size - 1;
4008 uintptr_t daddr = tupregs[0].dttk_value;
4009 int64_t minor = (int64_t)tupregs[1].dttk_value;
4010 char *s;
4011 int i, len, depth = 0;
4012
4013 /*
4014 * Due to all the pointer jumping we do and context we must
4015 * rely upon, we just mandate that the user must have kernel
4016 * read privileges to use this routine.
4017 */
4018 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4019 *flags |= CPU_DTRACE_KPRIV;
4020 *illval = daddr;
4021 regs[rd] = NULL;
4022 }
4023
4024 if (!DTRACE_INSCRATCH(mstate, size)) {
4025 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4026 regs[rd] = NULL;
4027 break;
4028 }
4029
4030 *end = '\0';
4031
4032 /*
4033 * We want to have a name for the minor. In order to do this,
4034 * we need to walk the minor list from the devinfo. We want
4035 * to be sure that we don't infinitely walk a circular list,
4036 * so we check for circularity by sending a scout pointer
4037 * ahead two elements for every element that we iterate over;
4038 * if the list is circular, these will ultimately point to the
4039 * same element. You may recognize this little trick as the
4040 * answer to a stupid interview question -- one that always
4041 * seems to be asked by those who had to have it laboriously
4042 * explained to them, and who can't even concisely describe
4043 * the conditions under which one would be forced to resort to
4044 * this technique. Needless to say, those conditions are
4045 * found here -- and probably only here. Is this the only use
4046 * of this infamous trick in shipping, production code? If it
4047 * isn't, it probably should be...
4048 */
4049 if (minor != -1) {
4050 uintptr_t maddr = dtrace_loadptr(daddr +
4051 offsetof(struct dev_info, devi_minor));
4052
4053 uintptr_t next = offsetof(struct ddi_minor_data, next);
4054 uintptr_t name = offsetof(struct ddi_minor_data,
4055 d_minor) + offsetof(struct ddi_minor, name);
4056 uintptr_t dev = offsetof(struct ddi_minor_data,
4057 d_minor) + offsetof(struct ddi_minor, dev);
4058 uintptr_t scout;
4059
4060 if (maddr != NULL)
4061 scout = dtrace_loadptr(maddr + next);
4062
4063 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4064 uint64_t m;
4065#ifdef _LP64
4066 m = dtrace_load64(maddr + dev) & MAXMIN64;
4067#else
4068 m = dtrace_load32(maddr + dev) & MAXMIN;
4069#endif
4070 if (m != minor) {
4071 maddr = dtrace_loadptr(maddr + next);
4072
4073 if (scout == NULL)
4074 continue;
4075
4076 scout = dtrace_loadptr(scout + next);
4077
4078 if (scout == NULL)
4079 continue;
4080
4081 scout = dtrace_loadptr(scout + next);
4082
4083 if (scout == NULL)
4084 continue;
4085
4086 if (scout == maddr) {
4087 *flags |= CPU_DTRACE_ILLOP;
4088 break;
4089 }
4090
4091 continue;
4092 }
4093
4094 /*
4095 * We have the minor data. Now we need to
4096 * copy the minor's name into the end of the
4097 * pathname.
4098 */
4099 s = (char *)dtrace_loadptr(maddr + name);
4100 len = dtrace_strlen(s, size);
4101
4102 if (*flags & CPU_DTRACE_FAULT)
4103 break;
4104
4105 if (len != 0) {
4106 if ((end -= (len + 1)) < start)
4107 break;
4108
4109 *end = ':';
4110 }
4111
4112 for (i = 1; i <= len; i++)
4113 end[i] = dtrace_load8((uintptr_t)s++);
4114 break;
4115 }
4116 }
4117
4118 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4119 ddi_node_state_t devi_state;
4120
4121 devi_state = dtrace_load32(daddr +
4122 offsetof(struct dev_info, devi_node_state));
4123
4124 if (*flags & CPU_DTRACE_FAULT)
4125 break;
4126
4127 if (devi_state >= DS_INITIALIZED) {
4128 s = (char *)dtrace_loadptr(daddr +
4129 offsetof(struct dev_info, devi_addr));
4130 len = dtrace_strlen(s, size);
4131
4132 if (*flags & CPU_DTRACE_FAULT)
4133 break;
4134
4135 if (len != 0) {
4136 if ((end -= (len + 1)) < start)
4137 break;
4138
4139 *end = '@';
4140 }
4141
4142 for (i = 1; i <= len; i++)
4143 end[i] = dtrace_load8((uintptr_t)s++);
4144 }
4145
4146 /*
4147 * Now for the node name...
4148 */
4149 s = (char *)dtrace_loadptr(daddr +
4150 offsetof(struct dev_info, devi_node_name));
4151
4152 daddr = dtrace_loadptr(daddr +
4153 offsetof(struct dev_info, devi_parent));
4154
4155 /*
4156 * If our parent is NULL (that is, if we're the root
4157 * node), we're going to use the special path
4158 * "devices".
4159 */
4160 if (daddr == NULL)
4161 s = "devices";
4162
4163 len = dtrace_strlen(s, size);
4164 if (*flags & CPU_DTRACE_FAULT)
4165 break;
4166
4167 if ((end -= (len + 1)) < start)
4168 break;
4169
4170 for (i = 1; i <= len; i++)
4171 end[i] = dtrace_load8((uintptr_t)s++);
4172 *end = '/';
4173
4174 if (depth++ > dtrace_devdepth_max) {
4175 *flags |= CPU_DTRACE_ILLOP;
4176 break;
4177 }
4178 }
4179
4180 if (end < start)
4181 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4182
4183 if (daddr == NULL) {
4184 regs[rd] = (uintptr_t)end;
4185 mstate->dtms_scratch_ptr += size;
4186 }
4187
4188#else
4189 regs[rd] = 0;
4190 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4191#endif
4192 break;
4193 }
4194
4195 case DIF_SUBR_STRJOIN: {
4196 char *d = (char *)mstate->dtms_scratch_ptr;
4197 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4198 uintptr_t s1 = tupregs[0].dttk_value;
4199 uintptr_t s2 = tupregs[1].dttk_value;
4200 VBDTTYPE(unsigned,int) i = 0;
4201
4202 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4203 !dtrace_strcanload(s2, size, mstate, vstate)) {
4204 regs[rd] = NULL;
4205 break;
4206 }
4207
4208 if (!DTRACE_INSCRATCH(mstate, size)) {
4209 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4210 regs[rd] = NULL;
4211 break;
4212 }
4213
4214 for (;;) {
4215 if (i >= size) {
4216 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4217 regs[rd] = NULL;
4218 break;
4219 }
4220
4221 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4222 i--;
4223 break;
4224 }
4225 }
4226
4227 for (;;) {
4228 if (i >= size) {
4229 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4230 regs[rd] = NULL;
4231 break;
4232 }
4233
4234 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4235 break;
4236 }
4237
4238 if (i < size) {
4239 mstate->dtms_scratch_ptr += i;
4240 regs[rd] = (uintptr_t)d;
4241 }
4242
4243 break;
4244 }
4245
4246 case DIF_SUBR_LLTOSTR: {
4247 int64_t i = (int64_t)tupregs[0].dttk_value;
4248 int64_t val = i < 0 ? i * -1 : i;
4249 uint64_t size = 22; /* enough room for 2^64 in decimal */
4250 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4251
4252 if (!DTRACE_INSCRATCH(mstate, size)) {
4253 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4254 regs[rd] = NULL;
4255 break;
4256 }
4257
4258 for (*end-- = '\0'; val; val /= 10)
4259 *end-- = '0' + (val % 10);
4260
4261 if (i == 0)
4262 *end-- = '0';
4263
4264 if (i < 0)
4265 *end-- = '-';
4266
4267 regs[rd] = (uintptr_t)end + 1;
4268 mstate->dtms_scratch_ptr += size;
4269 break;
4270 }
4271
4272 case DIF_SUBR_HTONS:
4273 case DIF_SUBR_NTOHS:
4274#ifdef _BIG_ENDIAN
4275 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4276#else
4277 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4278#endif
4279 break;
4280
4281
4282 case DIF_SUBR_HTONL:
4283 case DIF_SUBR_NTOHL:
4284#ifdef _BIG_ENDIAN
4285 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4286#else
4287 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4288#endif
4289 break;
4290
4291
4292 case DIF_SUBR_HTONLL:
4293 case DIF_SUBR_NTOHLL:
4294#ifdef _BIG_ENDIAN
4295 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4296#else
4297 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4298#endif
4299 break;
4300
4301
4302 case DIF_SUBR_DIRNAME:
4303 case DIF_SUBR_BASENAME: {
4304 char *dest = (char *)mstate->dtms_scratch_ptr;
4305 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4306 uintptr_t src = tupregs[0].dttk_value;
4307 int i, j, len = VBDTCAST(int)dtrace_strlen((char *)src, size);
4308 int lastbase = -1, firstbase = -1, lastdir = -1;
4309 int start, end;
4310
4311 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4312 regs[rd] = NULL;
4313 break;
4314 }
4315
4316 if (!DTRACE_INSCRATCH(mstate, size)) {
4317 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4318 regs[rd] = NULL;
4319 break;
4320 }
4321
4322 /*
4323 * The basename and dirname for a zero-length string is
4324 * defined to be "."
4325 */
4326 if (len == 0) {
4327 len = 1;
4328 src = (uintptr_t)".";
4329 }
4330
4331 /*
4332 * Start from the back of the string, moving back toward the
4333 * front until we see a character that isn't a slash. That
4334 * character is the last character in the basename.
4335 */
4336 for (i = len - 1; i >= 0; i--) {
4337 if (dtrace_load8(src + i) != '/')
4338 break;
4339 }
4340
4341 if (i >= 0)
4342 lastbase = i;
4343
4344 /*
4345 * Starting from the last character in the basename, move
4346 * towards the front until we find a slash. The character
4347 * that we processed immediately before that is the first
4348 * character in the basename.
4349 */
4350 for (; i >= 0; i--) {
4351 if (dtrace_load8(src + i) == '/')
4352 break;
4353 }
4354
4355 if (i >= 0)
4356 firstbase = i + 1;
4357
4358 /*
4359 * Now keep going until we find a non-slash character. That
4360 * character is the last character in the dirname.
4361 */
4362 for (; i >= 0; i--) {
4363 if (dtrace_load8(src + i) != '/')
4364 break;
4365 }
4366
4367 if (i >= 0)
4368 lastdir = i;
4369
4370 ASSERT(!(lastbase == -1 && firstbase != -1));
4371 ASSERT(!(firstbase == -1 && lastdir != -1));
4372
4373 if (lastbase == -1) {
4374 /*
4375 * We didn't find a non-slash character. We know that
4376 * the length is non-zero, so the whole string must be
4377 * slashes. In either the dirname or the basename
4378 * case, we return '/'.
4379 */
4380 ASSERT(firstbase == -1);
4381 firstbase = lastbase = lastdir = 0;
4382 }
4383
4384 if (firstbase == -1) {
4385 /*
4386 * The entire string consists only of a basename
4387 * component. If we're looking for dirname, we need
4388 * to change our string to be just "."; if we're
4389 * looking for a basename, we'll just set the first
4390 * character of the basename to be 0.
4391 */
4392 if (subr == DIF_SUBR_DIRNAME) {
4393 ASSERT(lastdir == -1);
4394 src = (uintptr_t)".";
4395 lastdir = 0;
4396 } else {
4397 firstbase = 0;
4398 }
4399 }
4400
4401 if (subr == DIF_SUBR_DIRNAME) {
4402 if (lastdir == -1) {
4403 /*
4404 * We know that we have a slash in the name --
4405 * or lastdir would be set to 0, above. And
4406 * because lastdir is -1, we know that this
4407 * slash must be the first character. (That
4408 * is, the full string must be of the form
4409 * "/basename".) In this case, the last
4410 * character of the directory name is 0.
4411 */
4412 lastdir = 0;
4413 }
4414
4415 start = 0;
4416 end = lastdir;
4417 } else {
4418 ASSERT(subr == DIF_SUBR_BASENAME);
4419 ASSERT(firstbase != -1 && lastbase != -1);
4420 start = firstbase;
4421 end = lastbase;
4422 }
4423
4424 for (i = start, j = 0; i <= end && VBDTCAST(unsigned)j < size - 1; i++, j++)
4425 dest[j] = dtrace_load8(src + i);
4426
4427 dest[j] = '\0';
4428 regs[rd] = (uintptr_t)dest;
4429 mstate->dtms_scratch_ptr += size;
4430 break;
4431 }
4432
4433 case DIF_SUBR_CLEANPATH: {
4434 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4435 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4436 uintptr_t src = tupregs[0].dttk_value;
4437 int i = 0, j = 0;
4438
4439 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4440 regs[rd] = NULL;
4441 break;
4442 }
4443
4444 if (!DTRACE_INSCRATCH(mstate, size)) {
4445 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4446 regs[rd] = NULL;
4447 break;
4448 }
4449
4450 /*
4451 * Move forward, loading each character.
4452 */
4453 do {
4454 c = dtrace_load8(src + i++);
4455next:
4456 if (j + 5 >= VBDTCAST(int64_t)size) /* 5 = strlen("/..c\0") */
4457 break;
4458
4459 if (c != '/') {
4460 dest[j++] = c;
4461 continue;
4462 }
4463
4464 c = dtrace_load8(src + i++);
4465
4466 if (c == '/') {
4467 /*
4468 * We have two slashes -- we can just advance
4469 * to the next character.
4470 */
4471 goto next;
4472 }
4473
4474 if (c != '.') {
4475 /*
4476 * This is not "." and it's not ".." -- we can
4477 * just store the "/" and this character and
4478 * drive on.
4479 */
4480 dest[j++] = '/';
4481 dest[j++] = c;
4482 continue;
4483 }
4484
4485 c = dtrace_load8(src + i++);
4486
4487 if (c == '/') {
4488 /*
4489 * This is a "/./" component. We're not going
4490 * to store anything in the destination buffer;
4491 * we're just going to go to the next component.
4492 */
4493 goto next;
4494 }
4495
4496 if (c != '.') {
4497 /*
4498 * This is not ".." -- we can just store the
4499 * "/." and this character and continue
4500 * processing.
4501 */
4502 dest[j++] = '/';
4503 dest[j++] = '.';
4504 dest[j++] = c;
4505 continue;
4506 }
4507
4508 c = dtrace_load8(src + i++);
4509
4510 if (c != '/' && c != '\0') {
4511 /*
4512 * This is not ".." -- it's "..[mumble]".
4513 * We'll store the "/.." and this character
4514 * and continue processing.
4515 */
4516 dest[j++] = '/';
4517 dest[j++] = '.';
4518 dest[j++] = '.';
4519 dest[j++] = c;
4520 continue;
4521 }
4522
4523 /*
4524 * This is "/../" or "/..\0". We need to back up
4525 * our destination pointer until we find a "/".
4526 */
4527 i--;
4528 while (j != 0 && dest[--j] != '/')
4529 continue;
4530
4531 if (c == '\0')
4532 dest[++j] = '/';
4533 } while (c != '\0');
4534
4535 dest[j] = '\0';
4536 regs[rd] = (uintptr_t)dest;
4537 mstate->dtms_scratch_ptr += size;
4538 break;
4539 }
4540
4541 case DIF_SUBR_INET_NTOA:
4542 case DIF_SUBR_INET_NTOA6:
4543 case DIF_SUBR_INET_NTOP: {
4544#ifndef VBOX
4545 size_t size;
4546 int af, argi, i;
4547 char *base, *end;
4548
4549 if (subr == DIF_SUBR_INET_NTOP) {
4550 af = (int)tupregs[0].dttk_value;
4551 argi = 1;
4552 } else {
4553 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4554 argi = 0;
4555 }
4556
4557 if (af == AF_INET) {
4558 ipaddr_t ip4;
4559 uint8_t *ptr8, val;
4560
4561 /*
4562 * Safely load the IPv4 address.
4563 */
4564 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4565
4566 /*
4567 * Check an IPv4 string will fit in scratch.
4568 */
4569 size = INET_ADDRSTRLEN;
4570 if (!DTRACE_INSCRATCH(mstate, size)) {
4571 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4572 regs[rd] = NULL;
4573 break;
4574 }
4575 base = (char *)mstate->dtms_scratch_ptr;
4576 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4577
4578 /*
4579 * Stringify as a dotted decimal quad.
4580 */
4581 *end-- = '\0';
4582 ptr8 = (uint8_t *)&ip4;
4583 for (i = 3; i >= 0; i--) {
4584 val = ptr8[i];
4585
4586 if (val == 0) {
4587 *end-- = '0';
4588 } else {
4589 for (; val; val /= 10) {
4590 *end-- = '0' + (val % 10);
4591 }
4592 }
4593
4594 if (i > 0)
4595 *end-- = '.';
4596 }
4597 ASSERT(end + 1 >= base);
4598
4599 } else if (af == AF_INET6) {
4600 struct in6_addr ip6;
4601 int firstzero, tryzero, numzero, v6end;
4602 uint16_t val;
4603 const char digits[] = "0123456789abcdef";
4604
4605 /*
4606 * Stringify using RFC 1884 convention 2 - 16 bit
4607 * hexadecimal values with a zero-run compression.
4608 * Lower case hexadecimal digits are used.
4609 * eg, fe80::214:4fff:fe0b:76c8.
4610 * The IPv4 embedded form is returned for inet_ntop,
4611 * just the IPv4 string is returned for inet_ntoa6.
4612 */
4613
4614 /*
4615 * Safely load the IPv6 address.
4616 */
4617 dtrace_bcopy(
4618 (void *)(uintptr_t)tupregs[argi].dttk_value,
4619 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4620
4621 /*
4622 * Check an IPv6 string will fit in scratch.
4623 */
4624 size = INET6_ADDRSTRLEN;
4625 if (!DTRACE_INSCRATCH(mstate, size)) {
4626 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4627 regs[rd] = NULL;
4628 break;
4629 }
4630 base = (char *)mstate->dtms_scratch_ptr;
4631 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4632 *end-- = '\0';
4633
4634 /*
4635 * Find the longest run of 16 bit zero values
4636 * for the single allowed zero compression - "::".
4637 */
4638 firstzero = -1;
4639 tryzero = -1;
4640 numzero = 1;
4641 for (i = 0; i < sizeof (struct in6_addr); i++) {
4642 if (ip6._S6_un._S6_u8[i] == 0 &&
4643 tryzero == -1 && i % 2 == 0) {
4644 tryzero = i;
4645 continue;
4646 }
4647
4648 if (tryzero != -1 &&
4649 (ip6._S6_un._S6_u8[i] != 0 ||
4650 i == sizeof (struct in6_addr) - 1)) {
4651
4652 if (i - tryzero <= numzero) {
4653 tryzero = -1;
4654 continue;
4655 }
4656
4657 firstzero = tryzero;
4658 numzero = i - i % 2 - tryzero;
4659 tryzero = -1;
4660
4661 if (ip6._S6_un._S6_u8[i] == 0 &&
4662 i == sizeof (struct in6_addr) - 1)
4663 numzero += 2;
4664 }
4665 }
4666 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4667
4668 /*
4669 * Check for an IPv4 embedded address.
4670 */
4671 v6end = sizeof (struct in6_addr) - 2;
4672 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4673 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4674 for (i = sizeof (struct in6_addr) - 1;
4675 i >= DTRACE_V4MAPPED_OFFSET; i--) {
4676 ASSERT(end >= base);
4677
4678 val = ip6._S6_un._S6_u8[i];
4679
4680 if (val == 0) {
4681 *end-- = '0';
4682 } else {
4683 for (; val; val /= 10) {
4684 *end-- = '0' + val % 10;
4685 }
4686 }
4687
4688 if (i > DTRACE_V4MAPPED_OFFSET)
4689 *end-- = '.';
4690 }
4691
4692 if (subr == DIF_SUBR_INET_NTOA6)
4693 goto inetout;
4694
4695 /*
4696 * Set v6end to skip the IPv4 address that
4697 * we have already stringified.
4698 */
4699 v6end = 10;
4700 }
4701
4702 /*
4703 * Build the IPv6 string by working through the
4704 * address in reverse.
4705 */
4706 for (i = v6end; i >= 0; i -= 2) {
4707 ASSERT(end >= base);
4708
4709 if (i == firstzero + numzero - 2) {
4710 *end-- = ':';
4711 *end-- = ':';
4712 i -= numzero - 2;
4713 continue;
4714 }
4715
4716 if (i < 14 && i != firstzero - 2)
4717 *end-- = ':';
4718
4719 val = (ip6._S6_un._S6_u8[i] << 8) +
4720 ip6._S6_un._S6_u8[i + 1];
4721
4722 if (val == 0) {
4723 *end-- = '0';
4724 } else {
4725 for (; val; val /= 16) {
4726 *end-- = digits[val % 16];
4727 }
4728 }
4729 }
4730 ASSERT(end + 1 >= base);
4731
4732 } else {
4733 /*
4734 * The user didn't use AH_INET or AH_INET6.
4735 */
4736 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4737 regs[rd] = NULL;
4738 break;
4739 }
4740
4741inetout: regs[rd] = (uintptr_t)end + 1;
4742 mstate->dtms_scratch_ptr += size;
4743#else /* VBOX */
4744 regs[rd] = 0;
4745 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4746#endif /* VBOX */
4747 break;
4748 }
4749
4750 }
4751}
4752
4753/*
4754 * Emulate the execution of DTrace IR instructions specified by the given
4755 * DIF object. This function is deliberately void of assertions as all of
4756 * the necessary checks are handled by a call to dtrace_difo_validate().
4757 */
4758static uint64_t
4759dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4760 dtrace_vstate_t *vstate, dtrace_state_t *state)
4761{
4762 const dif_instr_t *text = difo->dtdo_buf;
4763 const uint_t textlen = difo->dtdo_len;
4764 const char *strtab = difo->dtdo_strtab;
4765 const uint64_t *inttab = difo->dtdo_inttab;
4766
4767 uint64_t rval = 0;
4768 dtrace_statvar_t *svar;
4769 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4770 dtrace_difv_t *v;
4771 volatile uint16_t *flags = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
4772 volatile uintptr_t *illval = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval;
4773
4774 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4775 uint64_t regs[DIF_DIR_NREGS];
4776 uint64_t *tmp;
4777
4778 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4779 int64_t cc_r;
4780 uint_t pc = 0, id, opc VBDTUNASS(0);
4781 uint8_t ttop = 0;
4782 dif_instr_t instr;
4783 uint_t r1, r2, rd;
4784
4785 /*
4786 * We stash the current DIF object into the machine state: we need it
4787 * for subsequent access checking.
4788 */
4789 mstate->dtms_difo = difo;
4790
4791 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4792
4793 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4794 opc = pc;
4795
4796 instr = text[pc++];
4797 r1 = DIF_INSTR_R1(instr);
4798 r2 = DIF_INSTR_R2(instr);
4799 rd = DIF_INSTR_RD(instr);
4800
4801 switch (DIF_INSTR_OP(instr)) {
4802 case DIF_OP_OR:
4803 regs[rd] = regs[r1] | regs[r2];
4804 break;
4805 case DIF_OP_XOR:
4806 regs[rd] = regs[r1] ^ regs[r2];
4807 break;
4808 case DIF_OP_AND:
4809 regs[rd] = regs[r1] & regs[r2];
4810 break;
4811 case DIF_OP_SLL:
4812 regs[rd] = regs[r1] << regs[r2];
4813 break;
4814 case DIF_OP_SRL:
4815 regs[rd] = regs[r1] >> regs[r2];
4816 break;
4817 case DIF_OP_SUB:
4818 regs[rd] = regs[r1] - regs[r2];
4819 break;
4820 case DIF_OP_ADD:
4821 regs[rd] = regs[r1] + regs[r2];
4822 break;
4823 case DIF_OP_MUL:
4824 regs[rd] = regs[r1] * regs[r2];
4825 break;
4826 case DIF_OP_SDIV:
4827 if (regs[r2] == 0) {
4828 regs[rd] = 0;
4829 *flags |= CPU_DTRACE_DIVZERO;
4830 } else {
4831 regs[rd] = (int64_t)regs[r1] /
4832 (int64_t)regs[r2];
4833 }
4834 break;
4835
4836 case DIF_OP_UDIV:
4837 if (regs[r2] == 0) {
4838 regs[rd] = 0;
4839 *flags |= CPU_DTRACE_DIVZERO;
4840 } else {
4841 regs[rd] = regs[r1] / regs[r2];
4842 }
4843 break;
4844
4845 case DIF_OP_SREM:
4846 if (regs[r2] == 0) {
4847 regs[rd] = 0;
4848 *flags |= CPU_DTRACE_DIVZERO;
4849 } else {
4850 regs[rd] = (int64_t)regs[r1] %
4851 (int64_t)regs[r2];
4852 }
4853 break;
4854
4855 case DIF_OP_UREM:
4856 if (regs[r2] == 0) {
4857 regs[rd] = 0;
4858 *flags |= CPU_DTRACE_DIVZERO;
4859 } else {
4860 regs[rd] = regs[r1] % regs[r2];
4861 }
4862 break;
4863
4864 case DIF_OP_NOT:
4865 regs[rd] = ~regs[r1];
4866 break;
4867 case DIF_OP_MOV:
4868 regs[rd] = regs[r1];
4869 break;
4870 case DIF_OP_CMP:
4871 cc_r = regs[r1] - regs[r2];
4872 cc_n = cc_r < 0;
4873 cc_z = cc_r == 0;
4874 cc_v = 0;
4875 cc_c = regs[r1] < regs[r2];
4876 break;
4877 case DIF_OP_TST:
4878 cc_n = cc_v = cc_c = 0;
4879 cc_z = regs[r1] == 0;
4880 break;
4881 case DIF_OP_BA:
4882 pc = DIF_INSTR_LABEL(instr);
4883 break;
4884 case DIF_OP_BE:
4885 if (cc_z)
4886 pc = DIF_INSTR_LABEL(instr);
4887 break;
4888 case DIF_OP_BNE:
4889 if (cc_z == 0)
4890 pc = DIF_INSTR_LABEL(instr);
4891 break;
4892 case DIF_OP_BG:
4893 if ((cc_z | (cc_n ^ cc_v)) == 0)
4894 pc = DIF_INSTR_LABEL(instr);
4895 break;
4896 case DIF_OP_BGU:
4897 if ((cc_c | cc_z) == 0)
4898 pc = DIF_INSTR_LABEL(instr);
4899 break;
4900 case DIF_OP_BGE:
4901 if ((cc_n ^ cc_v) == 0)
4902 pc = DIF_INSTR_LABEL(instr);
4903 break;
4904 case DIF_OP_BGEU:
4905 if (cc_c == 0)
4906 pc = DIF_INSTR_LABEL(instr);
4907 break;
4908 case DIF_OP_BL:
4909 if (cc_n ^ cc_v)
4910 pc = DIF_INSTR_LABEL(instr);
4911 break;
4912 case DIF_OP_BLU:
4913 if (cc_c)
4914 pc = DIF_INSTR_LABEL(instr);
4915 break;
4916 case DIF_OP_BLE:
4917 if (cc_z | (cc_n ^ cc_v))
4918 pc = DIF_INSTR_LABEL(instr);
4919 break;
4920 case DIF_OP_BLEU:
4921 if (cc_c | cc_z)
4922 pc = DIF_INSTR_LABEL(instr);
4923 break;
4924 case DIF_OP_RLDSB:
4925 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4926 *flags |= CPU_DTRACE_KPRIV;
4927 *illval = regs[r1];
4928 break;
4929 }
4930 /*FALLTHROUGH*/
4931 case DIF_OP_LDSB:
4932 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4933 break;
4934 case DIF_OP_RLDSH:
4935 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4936 *flags |= CPU_DTRACE_KPRIV;
4937 *illval = regs[r1];
4938 break;
4939 }
4940 /*FALLTHROUGH*/
4941 case DIF_OP_LDSH:
4942 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4943 break;
4944 case DIF_OP_RLDSW:
4945 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4946 *flags |= CPU_DTRACE_KPRIV;
4947 *illval = regs[r1];
4948 break;
4949 }
4950 /*FALLTHROUGH*/
4951 case DIF_OP_LDSW:
4952 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4953 break;
4954 case DIF_OP_RLDUB:
4955 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4956 *flags |= CPU_DTRACE_KPRIV;
4957 *illval = regs[r1];
4958 break;
4959 }
4960 /*FALLTHROUGH*/
4961 case DIF_OP_LDUB:
4962 regs[rd] = dtrace_load8(regs[r1]);
4963 break;
4964 case DIF_OP_RLDUH:
4965 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4966 *flags |= CPU_DTRACE_KPRIV;
4967 *illval = regs[r1];
4968 break;
4969 }
4970 /*FALLTHROUGH*/
4971 case DIF_OP_LDUH:
4972 regs[rd] = dtrace_load16(regs[r1]);
4973 break;
4974 case DIF_OP_RLDUW:
4975 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4976 *flags |= CPU_DTRACE_KPRIV;
4977 *illval = regs[r1];
4978 break;
4979 }
4980 /*FALLTHROUGH*/
4981 case DIF_OP_LDUW:
4982 regs[rd] = dtrace_load32(regs[r1]);
4983 break;
4984 case DIF_OP_RLDX:
4985 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4986 *flags |= CPU_DTRACE_KPRIV;
4987 *illval = regs[r1];
4988 break;
4989 }
4990 /*FALLTHROUGH*/
4991 case DIF_OP_LDX:
4992 regs[rd] = dtrace_load64(regs[r1]);
4993 break;
4994 case DIF_OP_ULDSB:
4995 regs[rd] = (int8_t)
4996 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4997 break;
4998 case DIF_OP_ULDSH:
4999 regs[rd] = (int16_t)
5000 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5001 break;
5002 case DIF_OP_ULDSW:
5003 regs[rd] = (int32_t)
5004 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5005 break;
5006 case DIF_OP_ULDUB:
5007 regs[rd] =
5008 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5009 break;
5010 case DIF_OP_ULDUH:
5011 regs[rd] =
5012 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5013 break;
5014 case DIF_OP_ULDUW:
5015 regs[rd] =
5016 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5017 break;
5018 case DIF_OP_ULDX:
5019 regs[rd] =
5020 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5021 break;
5022 case DIF_OP_RET:
5023 rval = regs[rd];
5024 pc = textlen;
5025 break;
5026 case DIF_OP_NOP:
5027 break;
5028 case DIF_OP_SETX:
5029 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5030 break;
5031 case DIF_OP_SETS:
5032 regs[rd] = (uint64_t)(uintptr_t)
5033 (strtab + DIF_INSTR_STRING(instr));
5034 break;
5035 case DIF_OP_SCMP: {
5036 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5037 uintptr_t s1 = regs[r1];
5038 uintptr_t s2 = regs[r2];
5039
5040 if (s1 != NULL &&
5041 !dtrace_strcanload(s1, sz, mstate, vstate))
5042 break;
5043 if (s2 != NULL &&
5044 !dtrace_strcanload(s2, sz, mstate, vstate))
5045 break;
5046
5047 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5048
5049 cc_n = cc_r < 0;
5050 cc_z = cc_r == 0;
5051 cc_v = cc_c = 0;
5052 break;
5053 }
5054 case DIF_OP_LDGA:
5055 regs[rd] = dtrace_dif_variable(mstate, state,
5056 r1, regs[r2]);
5057 break;
5058 case DIF_OP_LDGS:
5059 id = DIF_INSTR_VAR(instr);
5060
5061 if (id >= DIF_VAR_OTHER_UBASE) {
5062 uintptr_t a;
5063
5064 id -= DIF_VAR_OTHER_UBASE;
5065 svar = vstate->dtvs_globals[id];
5066 ASSERT(svar != NULL);
5067 v = &svar->dtsv_var;
5068
5069 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5070 regs[rd] = svar->dtsv_data;
5071 break;
5072 }
5073
5074 a = (uintptr_t)svar->dtsv_data;
5075
5076 if (*(uint8_t *)a == UINT8_MAX) {
5077 /*
5078 * If the 0th byte is set to UINT8_MAX
5079 * then this is to be treated as a
5080 * reference to a NULL variable.
5081 */
5082 regs[rd] = NULL;
5083 } else {
5084 regs[rd] = a + sizeof (uint64_t);
5085 }
5086
5087 break;
5088 }
5089
5090 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5091 break;
5092
5093 case DIF_OP_STGS:
5094 id = DIF_INSTR_VAR(instr);
5095
5096 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5097 id -= DIF_VAR_OTHER_UBASE;
5098
5099 svar = vstate->dtvs_globals[id];
5100 ASSERT(svar != NULL);
5101 v = &svar->dtsv_var;
5102
5103 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5104 uintptr_t a = (uintptr_t)svar->dtsv_data;
5105
5106 ASSERT(a != NULL);
5107 ASSERT(svar->dtsv_size != 0);
5108
5109 if (regs[rd] == NULL) {
5110 *(uint8_t *)a = UINT8_MAX;
5111 break;
5112 } else {
5113 *(uint8_t *)a = 0;
5114 a += sizeof (uint64_t);
5115 }
5116 if (!dtrace_vcanload(
5117 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5118 mstate, vstate))
5119 break;
5120
5121 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5122 (void *)a, &v->dtdv_type);
5123 break;
5124 }
5125
5126 svar->dtsv_data = regs[rd];
5127 break;
5128
5129 case DIF_OP_LDTA:
5130 /*
5131 * There are no DTrace built-in thread-local arrays at
5132 * present. This opcode is saved for future work.
5133 */
5134 *flags |= CPU_DTRACE_ILLOP;
5135 regs[rd] = 0;
5136 break;
5137
5138 case DIF_OP_LDLS:
5139 id = DIF_INSTR_VAR(instr);
5140
5141 if (id < DIF_VAR_OTHER_UBASE) {
5142 /*
5143 * For now, this has no meaning.
5144 */
5145 regs[rd] = 0;
5146 break;
5147 }
5148
5149 id -= DIF_VAR_OTHER_UBASE;
5150
5151 ASSERT(VBDTCAST(int64_t)id < vstate->dtvs_nlocals);
5152 ASSERT(vstate->dtvs_locals != NULL);
5153
5154 svar = vstate->dtvs_locals[id];
5155 ASSERT(svar != NULL);
5156 v = &svar->dtsv_var;
5157
5158 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5159 uintptr_t a = (uintptr_t)svar->dtsv_data;
5160 size_t sz = v->dtdv_type.dtdt_size;
5161
5162 sz += sizeof (uint64_t);
5163 ASSERT(svar->dtsv_size == NCPU * sz);
5164 a += VBDT_GET_CPUID() * sz;
5165
5166 if (*(uint8_t *)a == UINT8_MAX) {
5167 /*
5168 * If the 0th byte is set to UINT8_MAX
5169 * then this is to be treated as a
5170 * reference to a NULL variable.
5171 */
5172 regs[rd] = NULL;
5173 } else {
5174 regs[rd] = a + sizeof (uint64_t);
5175 }
5176
5177 break;
5178 }
5179
5180 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5181 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5182 regs[rd] = tmp[VBDT_GET_CPUID()];
5183 break;
5184
5185 case DIF_OP_STLS:
5186 id = DIF_INSTR_VAR(instr);
5187
5188 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5189 id -= DIF_VAR_OTHER_UBASE;
5190 ASSERT(VBDTCAST(int64_t)id < vstate->dtvs_nlocals);
5191
5192 ASSERT(vstate->dtvs_locals != NULL);
5193 svar = vstate->dtvs_locals[id];
5194 ASSERT(svar != NULL);
5195 v = &svar->dtsv_var;
5196
5197 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5198 uintptr_t a = (uintptr_t)svar->dtsv_data;
5199 size_t sz = v->dtdv_type.dtdt_size;
5200
5201 sz += sizeof (uint64_t);
5202 ASSERT(svar->dtsv_size == NCPU * sz);
5203 a += VBDT_GET_CPUID() * sz;
5204
5205 if (regs[rd] == NULL) {
5206 *(uint8_t *)a = UINT8_MAX;
5207 break;
5208 } else {
5209 *(uint8_t *)a = 0;
5210 a += sizeof (uint64_t);
5211 }
5212
5213 if (!dtrace_vcanload(
5214 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5215 mstate, vstate))
5216 break;
5217
5218 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5219 (void *)a, &v->dtdv_type);
5220 break;
5221 }
5222
5223 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5224 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5225 tmp[VBDT_GET_CPUID()] = regs[rd];
5226 break;
5227
5228 case DIF_OP_LDTS: {
5229 dtrace_dynvar_t *dvar;
5230 dtrace_key_t *key;
5231
5232 id = DIF_INSTR_VAR(instr);
5233 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5234 id -= DIF_VAR_OTHER_UBASE;
5235 v = &vstate->dtvs_tlocals[id];
5236
5237 key = &tupregs[DIF_DTR_NREGS];
5238 key[0].dttk_value = (uint64_t)id;
5239 key[0].dttk_size = 0;
5240 DTRACE_TLS_THRKEY(key[1].dttk_value);
5241 key[1].dttk_size = 0;
5242
5243 dvar = dtrace_dynvar(dstate, 2, key,
5244 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5245 mstate, vstate);
5246
5247 if (dvar == NULL) {
5248 regs[rd] = 0;
5249 break;
5250 }
5251
5252 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5253 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5254 } else {
5255 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5256 }
5257
5258 break;
5259 }
5260
5261 case DIF_OP_STTS: {
5262 dtrace_dynvar_t *dvar;
5263 dtrace_key_t *key;
5264
5265 id = DIF_INSTR_VAR(instr);
5266 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5267 id -= DIF_VAR_OTHER_UBASE;
5268
5269 key = &tupregs[DIF_DTR_NREGS];
5270 key[0].dttk_value = (uint64_t)id;
5271 key[0].dttk_size = 0;
5272 DTRACE_TLS_THRKEY(key[1].dttk_value);
5273 key[1].dttk_size = 0;
5274 v = &vstate->dtvs_tlocals[id];
5275
5276 dvar = dtrace_dynvar(dstate, 2, key,
5277 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5278 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5279 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5280 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5281
5282 /*
5283 * Given that we're storing to thread-local data,
5284 * we need to flush our predicate cache.
5285 */
5286 curthread->t_predcache = NULL;
5287
5288 if (dvar == NULL)
5289 break;
5290
5291 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5292 if (!dtrace_vcanload(
5293 (void *)(uintptr_t)regs[rd],
5294 &v->dtdv_type, mstate, vstate))
5295 break;
5296
5297 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5298 dvar->dtdv_data, &v->dtdv_type);
5299 } else {
5300 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5301 }
5302
5303 break;
5304 }
5305
5306 case DIF_OP_SRA:
5307 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5308 break;
5309
5310 case DIF_OP_CALL:
5311 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5312 regs, tupregs, ttop, mstate, state);
5313 break;
5314
5315 case DIF_OP_PUSHTR:
5316 if (ttop == DIF_DTR_NREGS) {
5317 *flags |= CPU_DTRACE_TUPOFLOW;
5318 break;
5319 }
5320
5321 if (r1 == DIF_TYPE_STRING) {
5322 /*
5323 * If this is a string type and the size is 0,
5324 * we'll use the system-wide default string
5325 * size. Note that we are _not_ looking at
5326 * the value of the DTRACEOPT_STRSIZE option;
5327 * had this been set, we would expect to have
5328 * a non-zero size value in the "pushtr".
5329 */
5330 tupregs[ttop].dttk_size =
5331 dtrace_strlen((char *)(uintptr_t)regs[rd],
5332 regs[r2] ? regs[r2] :
5333 dtrace_strsize_default) + 1;
5334 } else {
5335 tupregs[ttop].dttk_size = regs[r2];
5336 }
5337
5338 tupregs[ttop++].dttk_value = regs[rd];
5339 break;
5340
5341 case DIF_OP_PUSHTV:
5342 if (ttop == DIF_DTR_NREGS) {
5343 *flags |= CPU_DTRACE_TUPOFLOW;
5344 break;
5345 }
5346
5347 tupregs[ttop].dttk_value = regs[rd];
5348 tupregs[ttop++].dttk_size = 0;
5349 break;
5350
5351 case DIF_OP_POPTS:
5352 if (ttop != 0)
5353 ttop--;
5354 break;
5355
5356 case DIF_OP_FLUSHTS:
5357 ttop = 0;
5358 break;
5359
5360 case DIF_OP_LDGAA:
5361 case DIF_OP_LDTAA: {
5362 dtrace_dynvar_t *dvar;
5363 dtrace_key_t *key = tupregs;
5364 uint_t nkeys = ttop;
5365
5366 id = DIF_INSTR_VAR(instr);
5367 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5368 id -= DIF_VAR_OTHER_UBASE;
5369
5370 key[nkeys].dttk_value = (uint64_t)id;
5371 key[nkeys++].dttk_size = 0;
5372
5373 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5374 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5375 key[nkeys++].dttk_size = 0;
5376 v = &vstate->dtvs_tlocals[id];
5377 } else {
5378 v = &vstate->dtvs_globals[id]->dtsv_var;
5379 }
5380
5381 dvar = dtrace_dynvar(dstate, nkeys, key,
5382 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5383 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5384 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5385
5386 if (dvar == NULL) {
5387 regs[rd] = 0;
5388 break;
5389 }
5390
5391 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5392 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5393 } else {
5394 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5395 }
5396
5397 break;
5398 }
5399
5400 case DIF_OP_STGAA:
5401 case DIF_OP_STTAA: {
5402 dtrace_dynvar_t *dvar;
5403 dtrace_key_t *key = tupregs;
5404 uint_t nkeys = ttop;
5405
5406 id = DIF_INSTR_VAR(instr);
5407 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5408 id -= DIF_VAR_OTHER_UBASE;
5409
5410 key[nkeys].dttk_value = (uint64_t)id;
5411 key[nkeys++].dttk_size = 0;
5412
5413 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5414 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5415 key[nkeys++].dttk_size = 0;
5416 v = &vstate->dtvs_tlocals[id];
5417 } else {
5418 v = &vstate->dtvs_globals[id]->dtsv_var;
5419 }
5420
5421 dvar = dtrace_dynvar(dstate, nkeys, key,
5422 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5423 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5424 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5425 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5426
5427 if (dvar == NULL)
5428 break;
5429
5430 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5431 if (!dtrace_vcanload(
5432 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5433 mstate, vstate))
5434 break;
5435
5436 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5437 dvar->dtdv_data, &v->dtdv_type);
5438 } else {
5439 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5440 }
5441
5442 break;
5443 }
5444
5445 case DIF_OP_ALLOCS: {
5446 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5447 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5448
5449 /*
5450 * Rounding up the user allocation size could have
5451 * overflowed large, bogus allocations (like -1ULL) to
5452 * 0.
5453 */
5454 if (size < regs[r1] ||
5455 !DTRACE_INSCRATCH(mstate, size)) {
5456 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5457 regs[rd] = NULL;
5458 break;
5459 }
5460
5461 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5462 mstate->dtms_scratch_ptr += size;
5463 regs[rd] = ptr;
5464 break;
5465 }
5466
5467 case DIF_OP_COPYS:
5468 if (!dtrace_canstore(regs[rd], regs[r2],
5469 mstate, vstate)) {
5470 *flags |= CPU_DTRACE_BADADDR;
5471 *illval = regs[rd];
5472 break;
5473 }
5474
5475 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5476 break;
5477
5478 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5479 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5480 break;
5481
5482 case DIF_OP_STB:
5483 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5484 *flags |= CPU_DTRACE_BADADDR;
5485 *illval = regs[rd];
5486 break;
5487 }
5488 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5489 break;
5490
5491 case DIF_OP_STH:
5492 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5493 *flags |= CPU_DTRACE_BADADDR;
5494 *illval = regs[rd];
5495 break;
5496 }
5497 if (regs[rd] & 1) {
5498 *flags |= CPU_DTRACE_BADALIGN;
5499 *illval = regs[rd];
5500 break;
5501 }
5502 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5503 break;
5504
5505 case DIF_OP_STW:
5506 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5507 *flags |= CPU_DTRACE_BADADDR;
5508 *illval = regs[rd];
5509 break;
5510 }
5511 if (regs[rd] & 3) {
5512 *flags |= CPU_DTRACE_BADALIGN;
5513 *illval = regs[rd];
5514 break;
5515 }
5516 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5517 break;
5518
5519 case DIF_OP_STX:
5520 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5521 *flags |= CPU_DTRACE_BADADDR;
5522 *illval = regs[rd];
5523 break;
5524 }
5525 if (regs[rd] & 7) {
5526 *flags |= CPU_DTRACE_BADALIGN;
5527 *illval = regs[rd];
5528 break;
5529 }
5530 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5531 break;
5532 }
5533 }
5534
5535 if (!(*flags & CPU_DTRACE_FAULT))
5536 return (rval);
5537
5538 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5539 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5540
5541 return (0);
5542}
5543
5544#ifndef VBOX /* no destructive stuff */
5545
5546static void
5547dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5548{
5549 dtrace_probe_t *probe = ecb->dte_probe;
5550 dtrace_provider_t *prov = probe->dtpr_provider;
5551 char c[DTRACE_FULLNAMELEN + 80], *str;
5552 char *msg = "dtrace: breakpoint action at probe ";
5553 char *ecbmsg = " (ecb ";
5554 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5555 uintptr_t val = (uintptr_t)ecb;
5556 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5557
5558 if (dtrace_destructive_disallow)
5559 return;
5560
5561 /*
5562 * It's impossible to be taking action on the NULL probe.
5563 */
5564 ASSERT(probe != NULL);
5565
5566 /*
5567 * This is a poor man's (destitute man's?) sprintf(): we want to
5568 * print the provider name, module name, function name and name of
5569 * the probe, along with the hex address of the ECB with the breakpoint
5570 * action -- all of which we must place in the character buffer by
5571 * hand.
5572 */
5573 while (*msg != '\0')
5574 c[i++] = *msg++;
5575
5576 for (str = prov->dtpv_name; *str != '\0'; str++)
5577 c[i++] = *str;
5578 c[i++] = ':';
5579
5580 for (str = probe->dtpr_mod; *str != '\0'; str++)
5581 c[i++] = *str;
5582 c[i++] = ':';
5583
5584 for (str = probe->dtpr_func; *str != '\0'; str++)
5585 c[i++] = *str;
5586 c[i++] = ':';
5587
5588 for (str = probe->dtpr_name; *str != '\0'; str++)
5589 c[i++] = *str;
5590
5591 while (*ecbmsg != '\0')
5592 c[i++] = *ecbmsg++;
5593
5594 while (shift >= 0) {
5595 mask = (uintptr_t)0xf << shift;
5596
5597 if (val >= ((uintptr_t)1 << shift))
5598 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5599 shift -= 4;
5600 }
5601
5602 c[i++] = ')';
5603 c[i] = '\0';
5604
5605 debug_enter(c);
5606}
5607
5608static void
5609dtrace_action_panic(dtrace_ecb_t *ecb)
5610{
5611 dtrace_probe_t *probe = ecb->dte_probe;
5612
5613 /*
5614 * It's impossible to be taking action on the NULL probe.
5615 */
5616 ASSERT(probe != NULL);
5617
5618 if (dtrace_destructive_disallow)
5619 return;
5620
5621 if (dtrace_panicked != NULL)
5622 return;
5623
5624 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5625 return;
5626
5627 /*
5628 * We won the right to panic. (We want to be sure that only one
5629 * thread calls panic() from dtrace_probe(), and that panic() is
5630 * called exactly once.)
5631 */
5632 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5633 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5634 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5635}
5636
5637static void
5638dtrace_action_raise(uint64_t sig)
5639{
5640 if (dtrace_destructive_disallow)
5641 return;
5642
5643 if (sig >= NSIG) {
5644 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5645 return;
5646 }
5647
5648 /*
5649 * raise() has a queue depth of 1 -- we ignore all subsequent
5650 * invocations of the raise() action.
5651 */
5652 if (curthread->t_dtrace_sig == 0)
5653 curthread->t_dtrace_sig = (uint8_t)sig;
5654
5655 curthread->t_sig_check = 1;
5656 aston(curthread);
5657}
5658
5659static void
5660dtrace_action_stop(void)
5661{
5662 if (dtrace_destructive_disallow)
5663 return;
5664
5665 if (!curthread->t_dtrace_stop) {
5666 curthread->t_dtrace_stop = 1;
5667 curthread->t_sig_check = 1;
5668 aston(curthread);
5669 }
5670}
5671
5672static void
5673dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5674{
5675 hrtime_t now;
5676 volatile uint16_t *flags;
5677 cpu_t *cpu = CPU;
5678
5679 if (dtrace_destructive_disallow)
5680 return;
5681
5682 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5683
5684 now = dtrace_gethrtime();
5685
5686 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5687 /*
5688 * We need to advance the mark to the current time.
5689 */
5690 cpu->cpu_dtrace_chillmark = now;
5691 cpu->cpu_dtrace_chilled = 0;
5692 }
5693
5694 /*
5695 * Now check to see if the requested chill time would take us over
5696 * the maximum amount of time allowed in the chill interval. (Or
5697 * worse, if the calculation itself induces overflow.)
5698 */
5699 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5700 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5701 *flags |= CPU_DTRACE_ILLOP;
5702 return;
5703 }
5704
5705 while (dtrace_gethrtime() - now < val)
5706 continue;
5707
5708 /*
5709 * Normally, we assure that the value of the variable "timestamp" does
5710 * not change within an ECB. The presence of chill() represents an
5711 * exception to this rule, however.
5712 */
5713 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5714 cpu->cpu_dtrace_chilled += val;
5715}
5716
5717#endif /* !VBOX */
5718
5719static void
5720dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5721 uint64_t *buf, uint64_t arg)
5722{
5723 int nframes = DTRACE_USTACK_NFRAMES(arg);
5724 int strsize = DTRACE_USTACK_STRSIZE(arg);
5725 uint64_t *pcs = &buf[1], *fps;
5726 char *str = (char *)&pcs[nframes];
5727 int size, offs = 0, i, j;
5728 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5729#ifndef VBOX
5730 uint16_t *flags = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
5731#else
5732 uint16_t volatile *flags = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
5733#endif
5734 char *sym;
5735
5736 /*
5737 * Should be taking a faster path if string space has not been
5738 * allocated.
5739 */
5740 ASSERT(strsize != 0);
5741
5742 /*
5743 * We will first allocate some temporary space for the frame pointers.
5744 */
5745 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5746 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5747 (nframes * sizeof (uint64_t));
5748
5749 if (!DTRACE_INSCRATCH(mstate, VBDTCAST(unsigned)size)) {
5750 /*
5751 * Not enough room for our frame pointers -- need to indicate
5752 * that we ran out of scratch space.
5753 */
5754 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5755 return;
5756 }
5757
5758 mstate->dtms_scratch_ptr += size;
5759 saved = mstate->dtms_scratch_ptr;
5760
5761 /*
5762 * Now get a stack with both program counters and frame pointers.
5763 */
5764 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5765 dtrace_getufpstack(buf, fps, nframes + 1);
5766 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5767
5768 /*
5769 * If that faulted, we're cooked.
5770 */
5771 if (*flags & CPU_DTRACE_FAULT)
5772 goto out;
5773
5774 /*
5775 * Now we want to walk up the stack, calling the USTACK helper. For
5776 * each iteration, we restore the scratch pointer.
5777 */
5778 for (i = 0; i < nframes; i++) {
5779 mstate->dtms_scratch_ptr = saved;
5780
5781 if (offs >= strsize)
5782 break;
5783
5784#ifndef VBOX
5785 sym = (char *)(uintptr_t)dtrace_helper(
5786 DTRACE_HELPER_ACTION_USTACK,
5787 mstate, state, pcs[i], fps[i]);
5788#else
5789 sym = NULL;
5790#endif
5791
5792 /*
5793 * If we faulted while running the helper, we're going to
5794 * clear the fault and null out the corresponding string.
5795 */
5796 if (*flags & CPU_DTRACE_FAULT) {
5797 *flags &= ~CPU_DTRACE_FAULT;
5798 str[offs++] = '\0';
5799 continue;
5800 }
5801
5802 if (sym == NULL) {
5803 str[offs++] = '\0';
5804 continue;
5805 }
5806
5807 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5808
5809 /*
5810 * Now copy in the string that the helper returned to us.
5811 */
5812 for (j = 0; offs + j < strsize; j++) {
5813 if ((str[offs + j] = sym[j]) == '\0')
5814 break;
5815 }
5816
5817 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5818
5819 offs += j + 1;
5820 }
5821
5822 if (offs >= strsize) {
5823 /*
5824 * If we didn't have room for all of the strings, we don't
5825 * abort processing -- this needn't be a fatal error -- but we
5826 * still want to increment a counter (dts_stkstroverflows) to
5827 * allow this condition to be warned about. (If this is from
5828 * a jstack() action, it is easily tuned via jstackstrsize.)
5829 */
5830 dtrace_error(&state->dts_stkstroverflows);
5831 }
5832
5833 while (offs < strsize)
5834 str[offs++] = '\0';
5835
5836out:
5837 mstate->dtms_scratch_ptr = old;
5838}
5839
5840#ifdef VBOX
5841extern void dtrace_probe6(dtrace_id_t, uintptr_t arg0, uintptr_t arg1,
5842 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4, uintptr_t arg5);
5843# define dtrace_probe_error(a1, a2, a3, a4, a5, a6) \
5844 dtrace_probe6(dtrace_probeid_error, (uintptr_t)a1, a2, a3, a4, a5, a6)
5845#endif
5846
5847/*
5848 * If you're looking for the epicenter of DTrace, you just found it. This
5849 * is the function called by the provider to fire a probe -- from which all
5850 * subsequent probe-context DTrace activity emanates.
5851 */
5852void
5853dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5854 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5855{
5856 processorid_t cpuid;
5857 dtrace_icookie_t cookie;
5858 dtrace_probe_t *probe;
5859 dtrace_mstate_t mstate;
5860 dtrace_ecb_t *ecb;
5861 dtrace_action_t *act;
5862 intptr_t offs;
5863 size_t size;
5864 int vtime, onintr;
5865 volatile uint16_t *flags;
5866 hrtime_t now;
5867
5868#ifndef VBOX
5869 /*
5870 * Kick out immediately if this CPU is still being born (in which case
5871 * curthread will be set to -1) or the current thread can't allow
5872 * probes in its current context.
5873 */
5874 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5875 return;
5876#endif
5877
5878 cookie = dtrace_interrupt_disable();
5879 probe = dtrace_probes[id - 1];
5880 cpuid = VBDT_GET_CPUID();
5881 onintr = CPU_ON_INTR(CPU);
5882
5883 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5884 probe->dtpr_predcache == curthread->t_predcache) {
5885 /*
5886 * We have hit in the predicate cache; we know that
5887 * this predicate would evaluate to be false.
5888 */
5889 dtrace_interrupt_enable(cookie);
5890 return;
5891 }
5892
5893#ifndef VBOX
5894 if (panic_quiesce) {
5895 /*
5896 * We don't trace anything if we're panicking.
5897 */
5898 dtrace_interrupt_enable(cookie);
5899 return;
5900 }
5901#endif
5902
5903 now = dtrace_gethrtime();
5904 vtime = dtrace_vtime_references != 0;
5905
5906 if (vtime && curthread->t_dtrace_start)
5907 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5908
5909 mstate.dtms_difo = NULL;
5910 mstate.dtms_probe = probe;
5911 mstate.dtms_strtok = NULL;
5912 mstate.dtms_arg[0] = arg0;
5913 mstate.dtms_arg[1] = arg1;
5914 mstate.dtms_arg[2] = arg2;
5915 mstate.dtms_arg[3] = arg3;
5916 mstate.dtms_arg[4] = arg4;
5917
5918 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5919
5920 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5921 dtrace_predicate_t *pred = ecb->dte_predicate;
5922 dtrace_state_t *state = ecb->dte_state;
5923 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5924 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5925 dtrace_vstate_t *vstate = &state->dts_vstate;
5926 dtrace_provider_t *prov = probe->dtpr_provider;
5927 int committed = 0;
5928 caddr_t tomax;
5929
5930 /*
5931 * A little subtlety with the following (seemingly innocuous)
5932 * declaration of the automatic 'val': by looking at the
5933 * code, you might think that it could be declared in the
5934 * action processing loop, below. (That is, it's only used in
5935 * the action processing loop.) However, it must be declared
5936 * out of that scope because in the case of DIF expression
5937 * arguments to aggregating actions, one iteration of the
5938 * action loop will use the last iteration's value.
5939 */
5940#ifdef lint
5941 uint64_t val = 0;
5942#else
5943 uint64_t val VBDTUNASS(0);
5944#endif
5945
5946 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5947 *flags &= ~CPU_DTRACE_ERROR;
5948
5949 if (prov == dtrace_provider) {
5950 /*
5951 * If dtrace itself is the provider of this probe,
5952 * we're only going to continue processing the ECB if
5953 * arg0 (the dtrace_state_t) is equal to the ECB's
5954 * creating state. (This prevents disjoint consumers
5955 * from seeing one another's metaprobes.)
5956 */
5957 if (arg0 != (uint64_t)(uintptr_t)state)
5958 continue;
5959 }
5960
5961 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5962 /*
5963 * We're not currently active. If our provider isn't
5964 * the dtrace pseudo provider, we're not interested.
5965 */
5966 if (prov != dtrace_provider)
5967 continue;
5968
5969 /*
5970 * Now we must further check if we are in the BEGIN
5971 * probe. If we are, we will only continue processing
5972 * if we're still in WARMUP -- if one BEGIN enabling
5973 * has invoked the exit() action, we don't want to
5974 * evaluate subsequent BEGIN enablings.
5975 */
5976 if (probe->dtpr_id == dtrace_probeid_begin &&
5977 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5978 ASSERT(state->dts_activity ==
5979 DTRACE_ACTIVITY_DRAINING);
5980 continue;
5981 }
5982 }
5983
5984 if (ecb->dte_cond) {
5985 /*
5986 * If the dte_cond bits indicate that this
5987 * consumer is only allowed to see user-mode firings
5988 * of this probe, call the provider's dtps_usermode()
5989 * entry point to check that the probe was fired
5990 * while in a user context. Skip this ECB if that's
5991 * not the case.
5992 */
5993 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5994 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5995 probe->dtpr_id, probe->dtpr_arg) == 0)
5996 continue;
5997
5998 /*
5999 * This is more subtle than it looks. We have to be
6000 * absolutely certain that CRED() isn't going to
6001 * change out from under us so it's only legit to
6002 * examine that structure if we're in constrained
6003 * situations. Currently, the only times we'll this
6004 * check is if a non-super-user has enabled the
6005 * profile or syscall providers -- providers that
6006 * allow visibility of all processes. For the
6007 * profile case, the check above will ensure that
6008 * we're examining a user context.
6009 */
6010 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6011 cred_t *cr;
6012 cred_t *s_cr =
6013 ecb->dte_state->dts_cred.dcr_cred;
6014#ifndef VBOX
6015 proc_t *proc;
6016#endif
6017
6018 ASSERT(s_cr != NULL);
6019
6020 if ((cr = CRED()) == NULL ||
6021 s_cr->cr_uid != cr->cr_uid ||
6022 s_cr->cr_uid != cr->cr_ruid ||
6023 s_cr->cr_uid != cr->cr_suid ||
6024 s_cr->cr_gid != cr->cr_gid ||
6025 s_cr->cr_gid != cr->cr_rgid ||
6026 s_cr->cr_gid != cr->cr_sgid ||
6027#ifndef VBOX
6028 (proc = VBDT_GET_PROC()) == NULL ||
6029 (proc->p_flag & SNOCD))
6030#else
6031 0)
6032
6033#endif
6034 continue;
6035 }
6036
6037#ifndef VBOX
6038 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6039 cred_t *cr;
6040 cred_t *s_cr =
6041 ecb->dte_state->dts_cred.dcr_cred;
6042
6043 ASSERT(s_cr != NULL);
6044
6045 if ((cr = CRED()) == NULL ||
6046 s_cr->cr_zone->zone_id !=
6047 cr->cr_zone->zone_id)
6048 continue;
6049 }
6050#endif
6051 }
6052
6053 if (now - state->dts_alive > dtrace_deadman_timeout) {
6054 /*
6055 * We seem to be dead. Unless we (a) have kernel
6056 * destructive permissions (b) have expicitly enabled
6057 * destructive actions and (c) destructive actions have
6058 * not been disabled, we're going to transition into
6059 * the KILLED state, from which no further processing
6060 * on this state will be performed.
6061 */
6062 if (!dtrace_priv_kernel_destructive(state) ||
6063 !state->dts_cred.dcr_destructive ||
6064 dtrace_destructive_disallow) {
6065 void *activity = &state->dts_activity;
6066 dtrace_activity_t current;
6067
6068 do {
6069 current = state->dts_activity;
6070 } while ( (dtrace_activity_t)dtrace_cas32(activity, current, DTRACE_ACTIVITY_KILLED)
6071 != current);
6072
6073 continue;
6074 }
6075 }
6076
6077 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6078 ecb->dte_alignment, state, &mstate)) < 0)
6079 continue;
6080
6081 tomax = buf->dtb_tomax;
6082 ASSERT(tomax != NULL);
6083
6084 if (ecb->dte_size != 0)
6085 DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
6086
6087 mstate.dtms_epid = ecb->dte_epid;
6088 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6089
6090 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6091 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6092 else
6093 mstate.dtms_access = 0;
6094
6095 if (pred != NULL) {
6096 dtrace_difo_t *dp = pred->dtp_difo;
6097 int rval;
6098
6099 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6100
6101 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6102 dtrace_cacheid_t cid = probe->dtpr_predcache;
6103
6104 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6105 /*
6106 * Update the predicate cache...
6107 */
6108 ASSERT(cid == pred->dtp_cacheid);
6109 curthread->t_predcache = cid;
6110 }
6111
6112 continue;
6113 }
6114 }
6115
6116 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6117 act != NULL; act = act->dta_next) {
6118 size_t valoffs;
6119 dtrace_difo_t *dp;
6120 dtrace_recdesc_t *rec = &act->dta_rec;
6121
6122 size = rec->dtrd_size;
6123 valoffs = offs + rec->dtrd_offset;
6124
6125 if (DTRACEACT_ISAGG(act->dta_kind)) {
6126 uint64_t v = 0xbad;
6127 dtrace_aggregation_t *agg;
6128
6129 agg = (dtrace_aggregation_t *)act;
6130
6131 if ((dp = act->dta_difo) != NULL)
6132 v = dtrace_dif_emulate(dp,
6133 &mstate, vstate, state);
6134
6135 if (*flags & CPU_DTRACE_ERROR)
6136 continue;
6137
6138 /*
6139 * Note that we always pass the expression
6140 * value from the previous iteration of the
6141 * action loop. This value will only be used
6142 * if there is an expression argument to the
6143 * aggregating action, denoted by the
6144 * dtag_hasarg field.
6145 */
6146 dtrace_aggregate(agg, buf,
6147 offs, aggbuf, v, val);
6148 continue;
6149 }
6150
6151 switch (act->dta_kind) {
6152 case DTRACEACT_STOP:
6153#ifndef VBOX
6154 if (dtrace_priv_proc_destructive(state))
6155 dtrace_action_stop();
6156#else
6157 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6158#endif
6159 continue;
6160
6161 case DTRACEACT_BREAKPOINT:
6162#ifndef VBOX
6163 if (dtrace_priv_kernel_destructive(state))
6164 dtrace_action_breakpoint(ecb);
6165#else
6166 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6167#endif
6168 continue;
6169
6170 case DTRACEACT_PANIC:
6171#ifndef VBOX
6172 if (dtrace_priv_kernel_destructive(state))
6173 dtrace_action_panic(ecb);
6174#endif
6175 continue;
6176
6177 case DTRACEACT_STACK:
6178 if (!dtrace_priv_kernel(state))
6179 continue;
6180
6181 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6182 VBDTCAST(int)(size / sizeof (pc_t)), probe->dtpr_aframes,
6183 DTRACE_ANCHORED(probe) ? NULL :
6184 (uint32_t *)arg0);
6185
6186 continue;
6187
6188 case DTRACEACT_JSTACK:
6189 case DTRACEACT_USTACK:
6190 if (!dtrace_priv_proc(state))
6191 continue;
6192
6193 /*
6194 * See comment in DIF_VAR_PID.
6195 */
6196 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6197 CPU_ON_INTR(CPU)) {
6198 int depth = DTRACE_USTACK_NFRAMES(
6199 rec->dtrd_arg) + 1;
6200
6201 dtrace_bzero((void *)(tomax + valoffs),
6202 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6203 + depth * sizeof (uint64_t));
6204
6205 continue;
6206 }
6207
6208#ifndef VBOX /* no helpers */
6209 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6210 curproc->p_dtrace_helpers != NULL) {
6211 /*
6212 * This is the slow path -- we have
6213 * allocated string space, and we're
6214 * getting the stack of a process that
6215 * has helpers. Call into a separate
6216 * routine to perform this processing.
6217 */
6218 dtrace_action_ustack(&mstate, state,
6219 (uint64_t *)(tomax + valoffs),
6220 rec->dtrd_arg);
6221 continue;
6222 }
6223#endif
6224
6225 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6226 dtrace_getupcstack((uint64_t *)
6227 (tomax + valoffs),
6228 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6229 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6230 continue;
6231
6232 default:
6233 break;
6234 }
6235
6236 dp = act->dta_difo;
6237 ASSERT(dp != NULL);
6238
6239 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6240
6241 if (*flags & CPU_DTRACE_ERROR)
6242 continue;
6243
6244 switch (act->dta_kind) {
6245 case DTRACEACT_SPECULATE:
6246 ASSERT(buf == &state->dts_buffer[cpuid]);
6247 buf = dtrace_speculation_buffer(state,
6248 cpuid, val);
6249
6250 if (buf == NULL) {
6251 *flags |= CPU_DTRACE_DROP;
6252 continue;
6253 }
6254
6255 offs = dtrace_buffer_reserve(buf,
6256 ecb->dte_needed, ecb->dte_alignment,
6257 state, NULL);
6258
6259 if (offs < 0) {
6260 *flags |= CPU_DTRACE_DROP;
6261 continue;
6262 }
6263
6264 tomax = buf->dtb_tomax;
6265 ASSERT(tomax != NULL);
6266
6267 if (ecb->dte_size != 0)
6268 DTRACE_STORE(uint32_t, tomax, offs,
6269 ecb->dte_epid);
6270 continue;
6271
6272 case DTRACEACT_CHILL:
6273#ifndef VBOX
6274 if (dtrace_priv_kernel_destructive(state))
6275 dtrace_action_chill(&mstate, val);
6276#else
6277 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6278#endif
6279 continue;
6280
6281 case DTRACEACT_RAISE:
6282#ifndef VBOX
6283 if (dtrace_priv_proc_destructive(state))
6284 dtrace_action_raise(val);
6285#else
6286 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6287#endif
6288 continue;
6289
6290 case DTRACEACT_COMMIT:
6291 ASSERT(!committed);
6292
6293 /*
6294 * We need to commit our buffer state.
6295 */
6296 if (ecb->dte_size)
6297 buf->dtb_offset = offs + ecb->dte_size;
6298 buf = &state->dts_buffer[cpuid];
6299 dtrace_speculation_commit(state, cpuid, val);
6300 committed = 1;
6301 continue;
6302
6303 case DTRACEACT_DISCARD:
6304 dtrace_speculation_discard(state, cpuid, val);
6305 continue;
6306
6307 case DTRACEACT_DIFEXPR:
6308 case DTRACEACT_LIBACT:
6309 case DTRACEACT_PRINTF:
6310 case DTRACEACT_PRINTA:
6311 case DTRACEACT_SYSTEM:
6312 case DTRACEACT_FREOPEN:
6313 break;
6314
6315 case DTRACEACT_SYM:
6316 case DTRACEACT_MOD:
6317 if (!dtrace_priv_kernel(state))
6318 continue;
6319 break;
6320
6321 case DTRACEACT_USYM:
6322 case DTRACEACT_UMOD:
6323 case DTRACEACT_UADDR: {
6324#ifndef VBOX
6325 struct pid *pid = curthread->t_procp->p_pidp;
6326
6327 if (!dtrace_priv_proc(state))
6328 continue;
6329
6330 DTRACE_STORE(uint64_t, tomax,
6331 valoffs, (uint64_t)pid->pid_id);
6332 DTRACE_STORE(uint64_t, tomax,
6333 valoffs + sizeof (uint64_t), val);
6334#else
6335 DTRACE_CPUFLAG_SET(CPU_DTRACE_UPRIV);
6336#endif
6337 continue;
6338 }
6339
6340 case DTRACEACT_EXIT: {
6341 /*
6342 * For the exit action, we are going to attempt
6343 * to atomically set our activity to be
6344 * draining. If this fails (either because
6345 * another CPU has beat us to the exit action,
6346 * or because our current activity is something
6347 * other than ACTIVE or WARMUP), we will
6348 * continue. This assures that the exit action
6349 * can be successfully recorded at most once
6350 * when we're in the ACTIVE state. If we're
6351 * encountering the exit() action while in
6352 * COOLDOWN, however, we want to honor the new
6353 * status code. (We know that we're the only
6354 * thread in COOLDOWN, so there is no race.)
6355 */
6356 void *activity = &state->dts_activity;
6357 dtrace_activity_t current = state->dts_activity;
6358
6359 if (current == DTRACE_ACTIVITY_COOLDOWN)
6360 break;
6361
6362 if (current != DTRACE_ACTIVITY_WARMUP)
6363 current = DTRACE_ACTIVITY_ACTIVE;
6364
6365 if ( (dtrace_activity_t)dtrace_cas32(activity, current, DTRACE_ACTIVITY_DRAINING)
6366 != current) {
6367 *flags |= CPU_DTRACE_DROP;
6368 continue;
6369 }
6370
6371 break;
6372 }
6373
6374 default:
6375#ifndef VBOX
6376 ASSERT(0);
6377#else
6378 AssertFatalMsgFailed(("%d\n", act->dta_kind));
6379#endif
6380 }
6381
6382 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6383 uintptr_t end = valoffs + size;
6384
6385 if (!dtrace_vcanload((void *)(uintptr_t)val,
6386 &dp->dtdo_rtype, &mstate, vstate))
6387 continue;
6388
6389 /*
6390 * If this is a string, we're going to only
6391 * load until we find the zero byte -- after
6392 * which we'll store zero bytes.
6393 */
6394 if (dp->dtdo_rtype.dtdt_kind ==
6395 DIF_TYPE_STRING) {
6396 char c = '\0' + 1;
6397 int intuple = act->dta_intuple;
6398 size_t s;
6399
6400 for (s = 0; s < size; s++) {
6401 if (c != '\0')
6402 c = dtrace_load8(val++);
6403
6404 DTRACE_STORE(uint8_t, tomax,
6405 valoffs++, c);
6406
6407 if (c == '\0' && intuple)
6408 break;
6409 }
6410
6411 continue;
6412 }
6413
6414 while (valoffs < end) {
6415 DTRACE_STORE(uint8_t, tomax, valoffs++,
6416 dtrace_load8(val++));
6417 }
6418
6419 continue;
6420 }
6421
6422 switch (size) {
6423 case 0:
6424 break;
6425
6426 case sizeof (uint8_t):
6427 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6428 break;
6429 case sizeof (uint16_t):
6430 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6431 break;
6432 case sizeof (uint32_t):
6433 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6434 break;
6435 case sizeof (uint64_t):
6436 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6437 break;
6438 default:
6439 /*
6440 * Any other size should have been returned by
6441 * reference, not by value.
6442 */
6443#ifndef VBOX
6444 ASSERT(0);
6445#else
6446 AssertFatalMsgFailed(("%zu\n", size));
6447#endif
6448 break;
6449 }
6450 }
6451
6452 if (*flags & CPU_DTRACE_DROP)
6453 continue;
6454
6455 if (*flags & CPU_DTRACE_FAULT) {
6456 int ndx;
6457 dtrace_action_t *err;
6458
6459 buf->dtb_errors++;
6460
6461 if (probe->dtpr_id == dtrace_probeid_error) {
6462 /*
6463 * There's nothing we can do -- we had an
6464 * error on the error probe. We bump an
6465 * error counter to at least indicate that
6466 * this condition happened.
6467 */
6468 dtrace_error(&state->dts_dblerrors);
6469 continue;
6470 }
6471
6472 if (vtime) {
6473 /*
6474 * Before recursing on dtrace_probe(), we
6475 * need to explicitly clear out our start
6476 * time to prevent it from being accumulated
6477 * into t_dtrace_vtime.
6478 */
6479 curthread->t_dtrace_start = 0;
6480 }
6481
6482 /*
6483 * Iterate over the actions to figure out which action
6484 * we were processing when we experienced the error.
6485 * Note that act points _past_ the faulting action; if
6486 * act is ecb->dte_action, the fault was in the
6487 * predicate, if it's ecb->dte_action->dta_next it's
6488 * in action #1, and so on.
6489 */
6490 for (err = ecb->dte_action, ndx = 0;
6491 err != act; err = err->dta_next, ndx++)
6492 continue;
6493
6494 dtrace_probe_error(state, ecb->dte_epid, ndx,
6495 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6496 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6497 cpu_core[cpuid].cpuc_dtrace_illval);
6498
6499 continue;
6500 }
6501
6502 if (!committed)
6503 buf->dtb_offset = offs + ecb->dte_size;
6504 }
6505
6506 if (vtime)
6507 curthread->t_dtrace_start = dtrace_gethrtime();
6508
6509 dtrace_interrupt_enable(cookie);
6510}
6511
6512/*
6513 * DTrace Probe Hashing Functions
6514 *
6515 * The functions in this section (and indeed, the functions in remaining
6516 * sections) are not _called_ from probe context. (Any exceptions to this are
6517 * marked with a "Note:".) Rather, they are called from elsewhere in the
6518 * DTrace framework to look-up probes in, add probes to and remove probes from
6519 * the DTrace probe hashes. (Each probe is hashed by each element of the
6520 * probe tuple -- allowing for fast lookups, regardless of what was
6521 * specified.)
6522 */
6523static uint_t
6524dtrace_hash_str(char *p)
6525{
6526 unsigned int g;
6527 uint_t hval = 0;
6528
6529 while (*p) {
6530 hval = (hval << 4) + *p++;
6531 if ((g = (hval & 0xf0000000)) != 0)
6532 hval ^= g >> 24;
6533 hval &= ~g;
6534 }
6535 return (hval);
6536}
6537
6538static dtrace_hash_t *
6539dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6540{
6541 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6542
6543 hash->dth_stroffs = stroffs;
6544 hash->dth_nextoffs = nextoffs;
6545 hash->dth_prevoffs = prevoffs;
6546
6547 hash->dth_size = 1;
6548 hash->dth_mask = hash->dth_size - 1;
6549
6550 hash->dth_tab = kmem_zalloc(hash->dth_size *
6551 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6552
6553 return (hash);
6554}
6555
6556static void
6557dtrace_hash_destroy(dtrace_hash_t *hash)
6558{
6559#ifdef DEBUG
6560 int i;
6561
6562 for (i = 0; i < hash->dth_size; i++)
6563 ASSERT(hash->dth_tab[i] == NULL);
6564#endif
6565
6566 kmem_free(hash->dth_tab,
6567 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6568 kmem_free(hash, sizeof (dtrace_hash_t));
6569}
6570
6571static void
6572dtrace_hash_resize(dtrace_hash_t *hash)
6573{
6574 int size = hash->dth_size, i, ndx;
6575 int new_size = hash->dth_size << 1;
6576 int new_mask = new_size - 1;
6577 dtrace_hashbucket_t **new_tab, *bucket, *next;
6578
6579 ASSERT((new_size & new_mask) == 0);
6580
6581 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6582
6583 for (i = 0; i < size; i++) {
6584 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6585 dtrace_probe_t *probe = bucket->dthb_chain;
6586
6587 ASSERT(probe != NULL);
6588 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6589
6590 next = bucket->dthb_next;
6591 bucket->dthb_next = new_tab[ndx];
6592 new_tab[ndx] = bucket;
6593 }
6594 }
6595
6596 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6597 hash->dth_tab = new_tab;
6598 hash->dth_size = new_size;
6599 hash->dth_mask = new_mask;
6600}
6601
6602static void
6603dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6604{
6605 int hashval = DTRACE_HASHSTR(hash, new);
6606 int ndx = hashval & hash->dth_mask;
6607 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6608 dtrace_probe_t **nextp, **prevp;
6609
6610 for (; bucket != NULL; bucket = bucket->dthb_next) {
6611 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6612 goto add;
6613 }
6614
6615 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6616 dtrace_hash_resize(hash);
6617 dtrace_hash_add(hash, new);
6618 return;
6619 }
6620
6621 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6622 bucket->dthb_next = hash->dth_tab[ndx];
6623 hash->dth_tab[ndx] = bucket;
6624 hash->dth_nbuckets++;
6625
6626add:
6627 nextp = DTRACE_HASHNEXT(hash, new);
6628 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6629 *nextp = bucket->dthb_chain;
6630
6631 if (bucket->dthb_chain != NULL) {
6632 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6633 ASSERT(*prevp == NULL);
6634 *prevp = new;
6635 }
6636
6637 bucket->dthb_chain = new;
6638 bucket->dthb_len++;
6639}
6640
6641static dtrace_probe_t *
6642dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6643{
6644 int hashval = DTRACE_HASHSTR(hash, template);
6645 int ndx = hashval & hash->dth_mask;
6646 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6647
6648 for (; bucket != NULL; bucket = bucket->dthb_next) {
6649 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6650 return (bucket->dthb_chain);
6651 }
6652
6653 return (NULL);
6654}
6655
6656static int
6657dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6658{
6659 int hashval = DTRACE_HASHSTR(hash, template);
6660 int ndx = hashval & hash->dth_mask;
6661 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6662
6663 for (; bucket != NULL; bucket = bucket->dthb_next) {
6664 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6665 return (bucket->dthb_len);
6666 }
6667
6668 return (NULL);
6669}
6670
6671static void
6672dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6673{
6674 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6675 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6676
6677 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6678 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6679
6680 /*
6681 * Find the bucket that we're removing this probe from.
6682 */
6683 for (; bucket != NULL; bucket = bucket->dthb_next) {
6684 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6685 break;
6686 }
6687
6688 ASSERT(bucket != NULL);
6689
6690 if (*prevp == NULL) {
6691 if (*nextp == NULL) {
6692 /*
6693 * The removed probe was the only probe on this
6694 * bucket; we need to remove the bucket.
6695 */
6696 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6697
6698 ASSERT(bucket->dthb_chain == probe);
6699 ASSERT(b != NULL);
6700
6701 if (b == bucket) {
6702 hash->dth_tab[ndx] = bucket->dthb_next;
6703 } else {
6704 while (b->dthb_next != bucket)
6705 b = b->dthb_next;
6706 b->dthb_next = bucket->dthb_next;
6707 }
6708
6709 ASSERT(hash->dth_nbuckets > 0);
6710 hash->dth_nbuckets--;
6711 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6712 return;
6713 }
6714
6715 bucket->dthb_chain = *nextp;
6716 } else {
6717 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6718 }
6719
6720 if (*nextp != NULL)
6721 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6722}
6723
6724/*
6725 * DTrace Utility Functions
6726 *
6727 * These are random utility functions that are _not_ called from probe context.
6728 */
6729static int
6730dtrace_badattr(const dtrace_attribute_t *a)
6731{
6732 return (a->dtat_name > DTRACE_STABILITY_MAX ||
6733 a->dtat_data > DTRACE_STABILITY_MAX ||
6734 a->dtat_class > DTRACE_CLASS_MAX);
6735}
6736
6737/*
6738 * Return a duplicate copy of a string. If the specified string is NULL,
6739 * this function returns a zero-length string.
6740 */
6741static char *
6742dtrace_strdup(const char *str)
6743{
6744 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6745
6746 if (str != NULL)
6747 (void) strcpy(new, str);
6748
6749 return (new);
6750}
6751
6752#define DTRACE_ISALPHA(c) \
6753 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6754
6755static int
6756dtrace_badname(const char *s)
6757{
6758 char c;
6759
6760 if (s == NULL || (c = *s++) == '\0')
6761 return (0);
6762
6763 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6764 return (1);
6765
6766 while ((c = *s++) != '\0') {
6767 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6768 c != '-' && c != '_' && c != '.' && c != '`')
6769 return (1);
6770 }
6771
6772 return (0);
6773}
6774
6775static void
6776dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6777{
6778 uint32_t priv;
6779
6780 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6781 /*
6782 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6783 */
6784 priv = DTRACE_PRIV_ALL;
6785#ifdef VBOX
6786 *uidp = UINT32_MAX;
6787 *zoneidp = 0;
6788#endif
6789 } else {
6790 *uidp = crgetuid(cr);
6791 *zoneidp = crgetzoneid(cr);
6792
6793 priv = 0;
6794 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6795 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6796 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6797 priv |= DTRACE_PRIV_USER;
6798 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6799 priv |= DTRACE_PRIV_PROC;
6800 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6801 priv |= DTRACE_PRIV_OWNER;
6802 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6803 priv |= DTRACE_PRIV_ZONEOWNER;
6804 }
6805
6806 *privp = priv;
6807}
6808
6809#ifdef DTRACE_ERRDEBUG
6810static void
6811dtrace_errdebug(const char *str)
6812{
6813 int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6814 int occupied = 0;
6815
6816 mutex_enter(&dtrace_errlock);
6817 dtrace_errlast = str;
6818 dtrace_errthread = curthread;
6819
6820 while (occupied++ < DTRACE_ERRHASHSZ) {
6821 if (dtrace_errhash[hval].dter_msg == str) {
6822 dtrace_errhash[hval].dter_count++;
6823 goto out;
6824 }
6825
6826 if (dtrace_errhash[hval].dter_msg != NULL) {
6827 hval = (hval + 1) % DTRACE_ERRHASHSZ;
6828 continue;
6829 }
6830
6831 dtrace_errhash[hval].dter_msg = str;
6832 dtrace_errhash[hval].dter_count = 1;
6833 goto out;
6834 }
6835
6836 panic("dtrace: undersized error hash");
6837out:
6838 mutex_exit(&dtrace_errlock);
6839}
6840#endif
6841
6842/*
6843 * DTrace Matching Functions
6844 *
6845 * These functions are used to match groups of probes, given some elements of
6846 * a probe tuple, or some globbed expressions for elements of a probe tuple.
6847 */
6848static int
6849dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6850 zoneid_t zoneid)
6851{
6852 if (priv != DTRACE_PRIV_ALL) {
6853 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6854 uint32_t match = priv & ppriv;
6855
6856 /*
6857 * No PRIV_DTRACE_* privileges...
6858 */
6859 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6860 DTRACE_PRIV_KERNEL)) == 0)
6861 return (0);
6862
6863 /*
6864 * No matching bits, but there were bits to match...
6865 */
6866 if (match == 0 && ppriv != 0)
6867 return (0);
6868
6869 /*
6870 * Need to have permissions to the process, but don't...
6871 */
6872 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6873 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6874 return (0);
6875 }
6876
6877 /*
6878 * Need to be in the same zone unless we possess the
6879 * privilege to examine all zones.
6880 */
6881 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6882 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6883 return (0);
6884 }
6885 }
6886
6887 return (1);
6888}
6889
6890/*
6891 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6892 * consists of input pattern strings and an ops-vector to evaluate them.
6893 * This function returns >0 for match, 0 for no match, and <0 for error.
6894 */
6895static int
6896dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6897 uint32_t priv, uid_t uid, zoneid_t zoneid)
6898{
6899 dtrace_provider_t *pvp = prp->dtpr_provider;
6900 int rv;
6901
6902 if (pvp->dtpv_defunct)
6903 return (0);
6904
6905 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6906 return (rv);
6907
6908 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6909 return (rv);
6910
6911 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6912 return (rv);
6913
6914 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6915 return (rv);
6916
6917 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6918 return (0);
6919
6920 return (rv);
6921}
6922
6923/*
6924 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6925 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
6926 * libc's version, the kernel version only applies to 8-bit ASCII strings.
6927 * In addition, all of the recursion cases except for '*' matching have been
6928 * unwound. For '*', we still implement recursive evaluation, but a depth
6929 * counter is maintained and matching is aborted if we recurse too deep.
6930 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6931 */
6932static int
6933dtrace_match_glob(const char *s, const char *p, int depth)
6934{
6935 const char *olds;
6936 char s1, c;
6937 int gs;
6938
6939 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6940 return (-1);
6941
6942 if (s == NULL)
6943 s = ""; /* treat NULL as empty string */
6944
6945top:
6946 olds = s;
6947 s1 = *s++;
6948
6949 if (p == NULL)
6950 return (0);
6951
6952 if ((c = *p++) == '\0')
6953 return (s1 == '\0');
6954
6955 switch (c) {
6956 case '[': {
6957 int ok = 0, notflag = 0;
6958 char lc = '\0';
6959
6960 if (s1 == '\0')
6961 return (0);
6962
6963 if (*p == '!') {
6964 notflag = 1;
6965 p++;
6966 }
6967
6968 if ((c = *p++) == '\0')
6969 return (0);
6970
6971 do {
6972 if (c == '-' && lc != '\0' && *p != ']') {
6973 if ((c = *p++) == '\0')
6974 return (0);
6975 if (c == '\\' && (c = *p++) == '\0')
6976 return (0);
6977
6978 if (notflag) {
6979 if (s1 < lc || s1 > c)
6980 ok++;
6981 else
6982 return (0);
6983 } else if (lc <= s1 && s1 <= c)
6984 ok++;
6985
6986 } else if (c == '\\' && (c = *p++) == '\0')
6987 return (0);
6988
6989 lc = c; /* save left-hand 'c' for next iteration */
6990
6991 if (notflag) {
6992 if (s1 != c)
6993 ok++;
6994 else
6995 return (0);
6996 } else if (s1 == c)
6997 ok++;
6998
6999 if ((c = *p++) == '\0')
7000 return (0);
7001
7002 } while (c != ']');
7003
7004 if (ok)
7005 goto top;
7006
7007 return (0);
7008 }
7009
7010 case '\\':
7011 if ((c = *p++) == '\0')
7012 return (0);
7013 /*FALLTHRU*/
7014
7015 default:
7016 if (c != s1)
7017 return (0);
7018 /*FALLTHRU*/
7019
7020 case '?':
7021 if (s1 != '\0')
7022 goto top;
7023 return (0);
7024
7025 case '*':
7026 while (*p == '*')
7027 p++; /* consecutive *'s are identical to a single one */
7028
7029 if (*p == '\0')
7030 return (1);
7031
7032 for (s = olds; *s != '\0'; s++) {
7033 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7034 return (gs);
7035 }
7036
7037 return (0);
7038 }
7039}
7040
7041/*ARGSUSED*/
7042static int
7043dtrace_match_string(const char *s, const char *p, int depth)
7044{
7045 RT_NOREF_PV(depth);
7046 return (s != NULL && strcmp(s, p) == 0);
7047}
7048
7049/*ARGSUSED*/
7050static int
7051dtrace_match_nul(const char *s, const char *p, int depth)
7052{
7053 RT_NOREF_PV(s); RT_NOREF_PV(p); RT_NOREF_PV(depth);
7054 return (1); /* always match the empty pattern */
7055}
7056
7057/*ARGSUSED*/
7058static int
7059dtrace_match_nonzero(const char *s, const char *p, int depth)
7060{
7061 RT_NOREF_PV(p); RT_NOREF_PV(depth);
7062 return (s != NULL && s[0] != '\0');
7063}
7064
7065static int
7066dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7067 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7068{
7069 dtrace_probe_t template, *probe;
7070 dtrace_hash_t *hash = NULL;
7071 int len, rc, best = INT_MAX, nmatched = 0;
7072 dtrace_id_t i;
7073
7074 ASSERT(MUTEX_HELD(&dtrace_lock));
7075
7076 /*
7077 * If the probe ID is specified in the key, just lookup by ID and
7078 * invoke the match callback once if a matching probe is found.
7079 */
7080 if (pkp->dtpk_id != DTRACE_IDNONE) {
7081 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7082 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7083 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7084 return (DTRACE_MATCH_FAIL);
7085 nmatched++;
7086 }
7087 return (nmatched);
7088 }
7089
7090 template.dtpr_mod = (char *)pkp->dtpk_mod;
7091 template.dtpr_func = (char *)pkp->dtpk_func;
7092 template.dtpr_name = (char *)pkp->dtpk_name;
7093
7094 /*
7095 * We want to find the most distinct of the module name, function
7096 * name, and name. So for each one that is not a glob pattern or
7097 * empty string, we perform a lookup in the corresponding hash and
7098 * use the hash table with the fewest collisions to do our search.
7099 */
7100 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7101 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7102 best = len;
7103 hash = dtrace_bymod;
7104 }
7105
7106 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7107 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7108 best = len;
7109 hash = dtrace_byfunc;
7110 }
7111
7112 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7113 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7114 best = len;
7115 hash = dtrace_byname;
7116 }
7117
7118 /*
7119 * If we did not select a hash table, iterate over every probe and
7120 * invoke our callback for each one that matches our input probe key.
7121 */
7122 if (hash == NULL) {
7123 for (i = 0; i < VBDTCAST(dtrace_id_t)dtrace_nprobes; i++) {
7124 if ((probe = dtrace_probes[i]) == NULL ||
7125 dtrace_match_probe(probe, pkp, priv, uid,
7126 zoneid) <= 0)
7127 continue;
7128
7129 nmatched++;
7130
7131 if ((rc = (*matched)(probe, arg)) !=
7132 DTRACE_MATCH_NEXT) {
7133 if (rc == DTRACE_MATCH_FAIL)
7134 return (DTRACE_MATCH_FAIL);
7135 break;
7136 }
7137 }
7138
7139 return (nmatched);
7140 }
7141
7142 /*
7143 * If we selected a hash table, iterate over each probe of the same key
7144 * name and invoke the callback for every probe that matches the other
7145 * attributes of our input probe key.
7146 */
7147 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7148 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7149
7150 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7151 continue;
7152
7153 nmatched++;
7154
7155 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7156 if (rc == DTRACE_MATCH_FAIL)
7157 return (DTRACE_MATCH_FAIL);
7158 break;
7159 }
7160 }
7161
7162 return (nmatched);
7163}
7164
7165/*
7166 * Return the function pointer dtrace_probecmp() should use to compare the
7167 * specified pattern with a string. For NULL or empty patterns, we select
7168 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7169 * For non-empty non-glob strings, we use dtrace_match_string().
7170 */
7171static dtrace_probekey_f *
7172dtrace_probekey_func(const char *p)
7173{
7174 char c;
7175
7176 if (p == NULL || *p == '\0')
7177 return (&dtrace_match_nul);
7178
7179 while ((c = *p++) != '\0') {
7180 if (c == '[' || c == '?' || c == '*' || c == '\\')
7181 return (&dtrace_match_glob);
7182 }
7183
7184 return (&dtrace_match_string);
7185}
7186
7187/*
7188 * Build a probe comparison key for use with dtrace_match_probe() from the
7189 * given probe description. By convention, a null key only matches anchored
7190 * probes: if each field is the empty string, reset dtpk_fmatch to
7191 * dtrace_match_nonzero().
7192 */
7193static void
7194dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7195{
7196 pkp->dtpk_prov = pdp->dtpd_provider;
7197 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7198
7199 pkp->dtpk_mod = pdp->dtpd_mod;
7200 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7201
7202 pkp->dtpk_func = pdp->dtpd_func;
7203 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7204
7205 pkp->dtpk_name = pdp->dtpd_name;
7206 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7207
7208 pkp->dtpk_id = pdp->dtpd_id;
7209
7210 if (pkp->dtpk_id == DTRACE_IDNONE &&
7211 pkp->dtpk_pmatch == &dtrace_match_nul &&
7212 pkp->dtpk_mmatch == &dtrace_match_nul &&
7213 pkp->dtpk_fmatch == &dtrace_match_nul &&
7214 pkp->dtpk_nmatch == &dtrace_match_nul)
7215 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7216}
7217
7218/*
7219 * DTrace Provider-to-Framework API Functions
7220 *
7221 * These functions implement much of the Provider-to-Framework API, as
7222 * described in <sys/dtrace.h>. The parts of the API not in this section are
7223 * the functions in the API for probe management (found below), and
7224 * dtrace_probe() itself (found above).
7225 */
7226
7227/*
7228 * Register the calling provider with the DTrace framework. This should
7229 * generally be called by DTrace providers in their attach(9E) entry point.
7230 */
7231int
7232dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7233 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7234{
7235 dtrace_provider_t *provider;
7236
7237 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7238 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7239 "arguments", name ? name : "<NULL>");
7240 return (EINVAL);
7241 }
7242
7243 if (name[0] == '\0' || dtrace_badname(name)) {
7244 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7245 "provider name", name);
7246 return (EINVAL);
7247 }
7248
7249 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7250 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7251 pops->dtps_destroy == NULL ||
7252 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7253 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7254 "provider ops", name);
7255 return (EINVAL);
7256 }
7257
7258 if (dtrace_badattr(&pap->dtpa_provider) ||
7259 dtrace_badattr(&pap->dtpa_mod) ||
7260 dtrace_badattr(&pap->dtpa_func) ||
7261 dtrace_badattr(&pap->dtpa_name) ||
7262 dtrace_badattr(&pap->dtpa_args)) {
7263 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7264 "provider attributes", name);
7265 return (EINVAL);
7266 }
7267
7268 if (priv & ~DTRACE_PRIV_ALL) {
7269 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7270 "privilege attributes", name);
7271 return (EINVAL);
7272 }
7273
7274 if ((priv & DTRACE_PRIV_KERNEL) &&
7275 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7276 pops->dtps_usermode == NULL) {
7277 cmn_err(CE_WARN, "failed to register provider '%s': need "
7278 "dtps_usermode() op for given privilege attributes", name);
7279 return (EINVAL);
7280 }
7281
7282 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7283 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7284 (void) strcpy(provider->dtpv_name, name);
7285
7286 provider->dtpv_attr = *pap;
7287 provider->dtpv_priv.dtpp_flags = priv;
7288 if (cr != NULL) {
7289 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7290 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7291 }
7292 provider->dtpv_pops = *pops;
7293
7294 if (pops->dtps_provide == NULL) {
7295 ASSERT(pops->dtps_provide_module != NULL);
7296 provider->dtpv_pops.dtps_provide =
7297 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7298 }
7299
7300 if (pops->dtps_provide_module == NULL) {
7301 ASSERT(pops->dtps_provide != NULL);
7302 provider->dtpv_pops.dtps_provide_module =
7303 (void (*)(void *, struct modctl *))dtrace_nullop;
7304 }
7305
7306 if (pops->dtps_suspend == NULL) {
7307 ASSERT(pops->dtps_resume == NULL);
7308 provider->dtpv_pops.dtps_suspend =
7309 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7310 provider->dtpv_pops.dtps_resume =
7311 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7312 }
7313
7314 provider->dtpv_arg = arg;
7315 *idp = (dtrace_provider_id_t)provider;
7316
7317 if (pops == &dtrace_provider_ops) {
7318 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7319 ASSERT(MUTEX_HELD(&dtrace_lock));
7320 ASSERT(dtrace_anon.dta_enabling == NULL);
7321
7322 /*
7323 * We make sure that the DTrace provider is at the head of
7324 * the provider chain.
7325 */
7326 provider->dtpv_next = dtrace_provider;
7327 dtrace_provider = provider;
7328 return (0);
7329 }
7330
7331 mutex_enter(&dtrace_provider_lock);
7332 mutex_enter(&dtrace_lock);
7333
7334 /*
7335 * If there is at least one provider registered, we'll add this
7336 * provider after the first provider.
7337 */
7338 if (dtrace_provider != NULL) {
7339 provider->dtpv_next = dtrace_provider->dtpv_next;
7340 dtrace_provider->dtpv_next = provider;
7341 } else {
7342 dtrace_provider = provider;
7343 }
7344
7345 if (dtrace_retained != NULL) {
7346 dtrace_enabling_provide(provider);
7347
7348 /*
7349 * Now we need to call dtrace_enabling_matchall() -- which
7350 * will acquire cpu_lock and dtrace_lock. We therefore need
7351 * to drop all of our locks before calling into it...
7352 */
7353 mutex_exit(&dtrace_lock);
7354 mutex_exit(&dtrace_provider_lock);
7355 dtrace_enabling_matchall();
7356
7357 return (0);
7358 }
7359
7360 mutex_exit(&dtrace_lock);
7361 mutex_exit(&dtrace_provider_lock);
7362
7363 return (0);
7364}
7365
7366/*
7367 * Unregister the specified provider from the DTrace framework. This should
7368 * generally be called by DTrace providers in their detach(9E) entry point.
7369 */
7370int
7371dtrace_unregister(dtrace_provider_id_t id)
7372{
7373 dtrace_provider_t *old = (dtrace_provider_t *)id;
7374 dtrace_provider_t *prev = NULL;
7375 VBDTTYPE(uint32_t,int) i, self = 0;
7376 dtrace_probe_t *probe, *first = NULL;
7377
7378 if (old->dtpv_pops.dtps_enable ==
7379 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7380 /*
7381 * If DTrace itself is the provider, we're called with locks
7382 * already held.
7383 */
7384 ASSERT(old == dtrace_provider);
7385#ifndef VBOX
7386 ASSERT(dtrace_devi != NULL);
7387#endif
7388 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7389 ASSERT(MUTEX_HELD(&dtrace_lock));
7390 self = 1;
7391
7392 if (dtrace_provider->dtpv_next != NULL) {
7393 /*
7394 * There's another provider here; return failure.
7395 */
7396 return (EBUSY);
7397 }
7398 } else {
7399 mutex_enter(&dtrace_provider_lock);
7400 mutex_enter(&mod_lock);
7401 mutex_enter(&dtrace_lock);
7402 }
7403
7404 /*
7405 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7406 * probes, we refuse to let providers slither away, unless this
7407 * provider has already been explicitly invalidated.
7408 */
7409 if (!old->dtpv_defunct &&
7410 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7411 dtrace_anon.dta_state->dts_necbs > 0))) {
7412 if (!self) {
7413 mutex_exit(&dtrace_lock);
7414 mutex_exit(&mod_lock);
7415 mutex_exit(&dtrace_provider_lock);
7416 }
7417 return (EBUSY);
7418 }
7419
7420 /*
7421 * Attempt to destroy the probes associated with this provider.
7422 */
7423 for (i = 0; i < dtrace_nprobes; i++) {
7424 if ((probe = dtrace_probes[i]) == NULL)
7425 continue;
7426
7427 if (probe->dtpr_provider != old)
7428 continue;
7429
7430 if (probe->dtpr_ecb == NULL)
7431 continue;
7432
7433 /*
7434 * We have at least one ECB; we can't remove this provider.
7435 */
7436 if (!self) {
7437 mutex_exit(&dtrace_lock);
7438 mutex_exit(&mod_lock);
7439 mutex_exit(&dtrace_provider_lock);
7440 }
7441 return (EBUSY);
7442 }
7443
7444 /*
7445 * All of the probes for this provider are disabled; we can safely
7446 * remove all of them from their hash chains and from the probe array.
7447 */
7448 for (i = 0; i < dtrace_nprobes; i++) {
7449 if ((probe = dtrace_probes[i]) == NULL)
7450 continue;
7451
7452 if (probe->dtpr_provider != old)
7453 continue;
7454
7455 dtrace_probes[i] = NULL;
7456
7457 dtrace_hash_remove(dtrace_bymod, probe);
7458 dtrace_hash_remove(dtrace_byfunc, probe);
7459 dtrace_hash_remove(dtrace_byname, probe);
7460
7461 if (first == NULL) {
7462 first = probe;
7463 probe->dtpr_nextmod = NULL;
7464 } else {
7465 probe->dtpr_nextmod = first;
7466 first = probe;
7467 }
7468 }
7469
7470 /*
7471 * The provider's probes have been removed from the hash chains and
7472 * from the probe array. Now issue a dtrace_sync() to be sure that
7473 * everyone has cleared out from any probe array processing.
7474 */
7475 dtrace_sync();
7476
7477 for (probe = first; probe != NULL; probe = first) {
7478 first = probe->dtpr_nextmod;
7479
7480 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7481 probe->dtpr_arg);
7482 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7483 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7484 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7485 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7486 kmem_free(probe, sizeof (dtrace_probe_t));
7487 }
7488
7489 if ((prev = dtrace_provider) == old) {
7490#ifndef VBOX
7491 ASSERT(self || dtrace_devi == NULL);
7492 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7493#endif
7494 dtrace_provider = old->dtpv_next;
7495 } else {
7496 while (prev != NULL && prev->dtpv_next != old)
7497 prev = prev->dtpv_next;
7498
7499 if (prev == NULL) {
7500 panic("attempt to unregister non-existent "
7501 "dtrace provider %p\n", (void *)id);
7502 }
7503
7504 prev->dtpv_next = old->dtpv_next;
7505 }
7506
7507 if (!self) {
7508 mutex_exit(&dtrace_lock);
7509 mutex_exit(&mod_lock);
7510 mutex_exit(&dtrace_provider_lock);
7511 }
7512
7513 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7514 kmem_free(old, sizeof (dtrace_provider_t));
7515
7516 return (0);
7517}
7518
7519/*
7520 * Invalidate the specified provider. All subsequent probe lookups for the
7521 * specified provider will fail, but its probes will not be removed.
7522 */
7523void
7524dtrace_invalidate(dtrace_provider_id_t id)
7525{
7526 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7527
7528 ASSERT(pvp->dtpv_pops.dtps_enable !=
7529 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7530
7531 mutex_enter(&dtrace_provider_lock);
7532 mutex_enter(&dtrace_lock);
7533
7534 pvp->dtpv_defunct = 1;
7535
7536 mutex_exit(&dtrace_lock);
7537 mutex_exit(&dtrace_provider_lock);
7538}
7539
7540/*
7541 * Indicate whether or not DTrace has attached.
7542 */
7543int
7544dtrace_attached(void)
7545{
7546 /*
7547 * dtrace_provider will be non-NULL iff the DTrace driver has
7548 * attached. (It's non-NULL because DTrace is always itself a
7549 * provider.)
7550 */
7551 return (dtrace_provider != NULL);
7552}
7553
7554/*
7555 * Remove all the unenabled probes for the given provider. This function is
7556 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7557 * -- just as many of its associated probes as it can.
7558 */
7559int
7560dtrace_condense(dtrace_provider_id_t id)
7561{
7562 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7563 VBDTTYPE(uint32_t,int) i;
7564 dtrace_probe_t *probe;
7565
7566 /*
7567 * Make sure this isn't the dtrace provider itself.
7568 */
7569 ASSERT(prov->dtpv_pops.dtps_enable !=
7570 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7571
7572 mutex_enter(&dtrace_provider_lock);
7573 mutex_enter(&dtrace_lock);
7574
7575 /*
7576 * Attempt to destroy the probes associated with this provider.
7577 */
7578 for (i = 0; i < dtrace_nprobes; i++) {
7579 if ((probe = dtrace_probes[i]) == NULL)
7580 continue;
7581
7582 if (probe->dtpr_provider != prov)
7583 continue;
7584
7585 if (probe->dtpr_ecb != NULL)
7586 continue;
7587
7588 dtrace_probes[i] = NULL;
7589
7590 dtrace_hash_remove(dtrace_bymod, probe);
7591 dtrace_hash_remove(dtrace_byfunc, probe);
7592 dtrace_hash_remove(dtrace_byname, probe);
7593
7594 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7595 probe->dtpr_arg);
7596 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7597 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7598 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7599 kmem_free(probe, sizeof (dtrace_probe_t));
7600 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7601 }
7602
7603 mutex_exit(&dtrace_lock);
7604 mutex_exit(&dtrace_provider_lock);
7605
7606 return (0);
7607}
7608
7609/*
7610 * DTrace Probe Management Functions
7611 *
7612 * The functions in this section perform the DTrace probe management,
7613 * including functions to create probes, look-up probes, and call into the
7614 * providers to request that probes be provided. Some of these functions are
7615 * in the Provider-to-Framework API; these functions can be identified by the
7616 * fact that they are not declared "static".
7617 */
7618
7619/*
7620 * Create a probe with the specified module name, function name, and name.
7621 */
7622dtrace_id_t
7623dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7624 const char *func, const char *name, int aframes, void *arg)
7625{
7626 dtrace_probe_t *probe, **probes;
7627 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7628 dtrace_id_t id;
7629
7630 if (provider == dtrace_provider) {
7631 ASSERT(MUTEX_HELD(&dtrace_lock));
7632 } else {
7633 mutex_enter(&dtrace_lock);
7634 }
7635
7636 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7637 VM_BESTFIT | VM_SLEEP);
7638 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7639
7640 probe->dtpr_id = id;
7641 probe->dtpr_gen = dtrace_probegen++;
7642 probe->dtpr_mod = dtrace_strdup(mod);
7643 probe->dtpr_func = dtrace_strdup(func);
7644 probe->dtpr_name = dtrace_strdup(name);
7645 probe->dtpr_arg = arg;
7646 probe->dtpr_aframes = aframes;
7647 probe->dtpr_provider = provider;
7648
7649 dtrace_hash_add(dtrace_bymod, probe);
7650 dtrace_hash_add(dtrace_byfunc, probe);
7651 dtrace_hash_add(dtrace_byname, probe);
7652
7653 if (id - 1 >= dtrace_nprobes) {
7654 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7655 size_t nsize = osize << 1;
7656
7657 if (nsize == 0) {
7658 ASSERT(osize == 0);
7659 ASSERT(dtrace_probes == NULL);
7660 nsize = sizeof (dtrace_probe_t *);
7661 }
7662
7663 probes = kmem_zalloc(nsize, KM_SLEEP);
7664
7665 if (dtrace_probes == NULL) {
7666 ASSERT(osize == 0);
7667 dtrace_probes = probes;
7668 dtrace_nprobes = 1;
7669 } else {
7670 dtrace_probe_t **oprobes = dtrace_probes;
7671
7672 bcopy(oprobes, probes, osize);
7673 dtrace_membar_producer();
7674 dtrace_probes = probes;
7675
7676 dtrace_sync();
7677
7678 /*
7679 * All CPUs are now seeing the new probes array; we can
7680 * safely free the old array.
7681 */
7682 kmem_free(oprobes, osize);
7683 dtrace_nprobes <<= 1;
7684 }
7685
7686 ASSERT(id - 1 < dtrace_nprobes);
7687 }
7688
7689 ASSERT(dtrace_probes[id - 1] == NULL);
7690 dtrace_probes[id - 1] = probe;
7691
7692 if (provider != dtrace_provider)
7693 mutex_exit(&dtrace_lock);
7694
7695 return (id);
7696}
7697
7698static dtrace_probe_t *
7699dtrace_probe_lookup_id(dtrace_id_t id)
7700{
7701 ASSERT(MUTEX_HELD(&dtrace_lock));
7702
7703 if (id == 0 || id > dtrace_nprobes)
7704 return (NULL);
7705
7706 return (dtrace_probes[id - 1]);
7707}
7708
7709static int
7710dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7711{
7712 *((dtrace_id_t *)arg) = probe->dtpr_id;
7713
7714 return (DTRACE_MATCH_DONE);
7715}
7716
7717/*
7718 * Look up a probe based on provider and one or more of module name, function
7719 * name and probe name.
7720 */
7721dtrace_id_t
7722dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7723 const char *func, const char *name)
7724{
7725 dtrace_probekey_t pkey;
7726 dtrace_id_t id;
7727 int match;
7728
7729 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7730 pkey.dtpk_pmatch = &dtrace_match_string;
7731 pkey.dtpk_mod = mod;
7732 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7733 pkey.dtpk_func = func;
7734 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7735 pkey.dtpk_name = name;
7736 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7737 pkey.dtpk_id = DTRACE_IDNONE;
7738
7739 mutex_enter(&dtrace_lock);
7740 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7741 dtrace_probe_lookup_match, &id);
7742 mutex_exit(&dtrace_lock);
7743
7744 ASSERT(match == 1 || match == 0);
7745 return (match ? id : 0);
7746}
7747
7748/*
7749 * Returns the probe argument associated with the specified probe.
7750 */
7751void *
7752dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7753{
7754 dtrace_probe_t *probe;
7755 void *rval = NULL;
7756
7757 mutex_enter(&dtrace_lock);
7758
7759 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7760 probe->dtpr_provider == (dtrace_provider_t *)id)
7761 rval = probe->dtpr_arg;
7762
7763 mutex_exit(&dtrace_lock);
7764
7765 return (rval);
7766}
7767
7768/*
7769 * Copy a probe into a probe description.
7770 */
7771static void
7772dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7773{
7774 bzero(pdp, sizeof (dtrace_probedesc_t));
7775 pdp->dtpd_id = prp->dtpr_id;
7776
7777 (void) strncpy(pdp->dtpd_provider,
7778 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7779
7780 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7781 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7782 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7783}
7784
7785/*
7786 * Called to indicate that a probe -- or probes -- should be provided by a
7787 * specfied provider. If the specified description is NULL, the provider will
7788 * be told to provide all of its probes. (This is done whenever a new
7789 * consumer comes along, or whenever a retained enabling is to be matched.) If
7790 * the specified description is non-NULL, the provider is given the
7791 * opportunity to dynamically provide the specified probe, allowing providers
7792 * to support the creation of probes on-the-fly. (So-called _autocreated_
7793 * probes.) If the provider is NULL, the operations will be applied to all
7794 * providers; if the provider is non-NULL the operations will only be applied
7795 * to the specified provider. The dtrace_provider_lock must be held, and the
7796 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7797 * will need to grab the dtrace_lock when it reenters the framework through
7798 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7799 */
7800static void
7801dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7802{
7803#ifndef VBOX
7804 struct modctl *ctl;
7805#endif
7806 int all = 0;
7807
7808 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7809
7810 if (prv == NULL) {
7811 all = 1;
7812 prv = dtrace_provider;
7813 }
7814
7815 do {
7816 /*
7817 * First, call the blanket provide operation.
7818 */
7819 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7820
7821#ifndef VBOX
7822 /*
7823 * Now call the per-module provide operation. We will grab
7824 * mod_lock to prevent the list from being modified. Note
7825 * that this also prevents the mod_busy bits from changing.
7826 * (mod_busy can only be changed with mod_lock held.)
7827 */
7828 mutex_enter(&mod_lock);
7829
7830 ctl = &modules;
7831 do {
7832 if (ctl->mod_busy || ctl->mod_mp == NULL)
7833 continue;
7834
7835 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7836
7837 } while ((ctl = ctl->mod_next) != &modules);
7838
7839 mutex_exit(&mod_lock);
7840#endif
7841 } while (all && (prv = prv->dtpv_next) != NULL);
7842}
7843
7844/*
7845 * Iterate over each probe, and call the Framework-to-Provider API function
7846 * denoted by offs.
7847 */
7848static void
7849dtrace_probe_foreach(uintptr_t offs)
7850{
7851 dtrace_provider_t *prov;
7852 void (*func)(void *, dtrace_id_t, void *);
7853 dtrace_probe_t *probe;
7854 dtrace_icookie_t cookie;
7855 VBDTTYPE(uint32_t,int) i;
7856
7857 /*
7858 * We disable interrupts to walk through the probe array. This is
7859 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7860 * won't see stale data.
7861 */
7862 cookie = dtrace_interrupt_disable();
7863
7864 for (i = 0; i < dtrace_nprobes; i++) {
7865 if ((probe = dtrace_probes[i]) == NULL)
7866 continue;
7867
7868 if (probe->dtpr_ecb == NULL) {
7869 /*
7870 * This probe isn't enabled -- don't call the function.
7871 */
7872 continue;
7873 }
7874
7875 prov = probe->dtpr_provider;
7876 func = *((void(**)(void *, dtrace_id_t, void *))
7877 ((uintptr_t)&prov->dtpv_pops + offs));
7878
7879 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7880 }
7881
7882 dtrace_interrupt_enable(cookie);
7883}
7884
7885static int
7886dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7887{
7888 dtrace_probekey_t pkey;
7889 uint32_t priv;
7890 uid_t uid;
7891 zoneid_t zoneid;
7892
7893 ASSERT(MUTEX_HELD(&dtrace_lock));
7894 dtrace_ecb_create_cache = NULL;
7895
7896 if (desc == NULL) {
7897 /*
7898 * If we're passed a NULL description, we're being asked to
7899 * create an ECB with a NULL probe.
7900 */
7901 (void) dtrace_ecb_create_enable(NULL, enab);
7902 return (0);
7903 }
7904
7905 dtrace_probekey(desc, &pkey);
7906 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7907 &priv, &uid, &zoneid);
7908
7909 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7910 enab));
7911}
7912
7913/*
7914 * DTrace Helper Provider Functions
7915 */
7916static void
7917dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7918{
7919 attr->dtat_name = DOF_ATTR_NAME(dofattr);
7920 attr->dtat_data = DOF_ATTR_DATA(dofattr);
7921 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7922}
7923
7924static void
7925dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7926 const dof_provider_t *dofprov, char *strtab)
7927{
7928 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7929 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7930 dofprov->dofpv_provattr);
7931 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7932 dofprov->dofpv_modattr);
7933 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7934 dofprov->dofpv_funcattr);
7935 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7936 dofprov->dofpv_nameattr);
7937 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7938 dofprov->dofpv_argsattr);
7939}
7940
7941static void
7942dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7943{
7944 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7945 dof_hdr_t *dof = (dof_hdr_t *)daddr;
7946 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7947 dof_provider_t *provider;
7948 dof_probe_t *probe;
7949 uint32_t *off, *enoff;
7950 uint8_t *arg;
7951 char *strtab;
7952 uint_t i, nprobes;
7953 dtrace_helper_provdesc_t dhpv;
7954 dtrace_helper_probedesc_t dhpb;
7955 dtrace_meta_t *meta = dtrace_meta_pid;
7956 dtrace_mops_t *mops = &meta->dtm_mops;
7957 void *parg;
7958
7959 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7960 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7961 provider->dofpv_strtab * dof->dofh_secsize);
7962 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7963 provider->dofpv_probes * dof->dofh_secsize);
7964 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7965 provider->dofpv_prargs * dof->dofh_secsize);
7966 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7967 provider->dofpv_proffs * dof->dofh_secsize);
7968
7969 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7970 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7971 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7972 enoff = NULL;
7973
7974 /*
7975 * See dtrace_helper_provider_validate().
7976 */
7977 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7978 provider->dofpv_prenoffs != DOF_SECT_NONE) {
7979 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7980 provider->dofpv_prenoffs * dof->dofh_secsize);
7981 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7982 }
7983
7984 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7985
7986 /*
7987 * Create the provider.
7988 */
7989 dtrace_dofprov2hprov(&dhpv, provider, strtab);
7990
7991 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7992 return;
7993
7994 meta->dtm_count++;
7995
7996 /*
7997 * Create the probes.
7998 */
7999 for (i = 0; i < nprobes; i++) {
8000 probe = (dof_probe_t *)(uintptr_t)(daddr +
8001 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8002
8003 dhpb.dthpb_mod = dhp->dofhp_mod;
8004 dhpb.dthpb_func = strtab + probe->dofpr_func;
8005 dhpb.dthpb_name = strtab + probe->dofpr_name;
8006 dhpb.dthpb_base = probe->dofpr_addr;
8007 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8008 dhpb.dthpb_noffs = probe->dofpr_noffs;
8009 if (enoff != NULL) {
8010 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8011 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8012 } else {
8013 dhpb.dthpb_enoffs = NULL;
8014 dhpb.dthpb_nenoffs = 0;
8015 }
8016 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8017 dhpb.dthpb_nargc = probe->dofpr_nargc;
8018 dhpb.dthpb_xargc = probe->dofpr_xargc;
8019 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8020 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8021
8022 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8023 }
8024}
8025
8026static void
8027dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8028{
8029 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8030 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8031 VBDTTYPE(uint32_t,int) i;
8032
8033 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8034
8035 for (i = 0; i < dof->dofh_secnum; i++) {
8036 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8037 dof->dofh_secoff + i * dof->dofh_secsize);
8038
8039 if (sec->dofs_type != DOF_SECT_PROVIDER)
8040 continue;
8041
8042 dtrace_helper_provide_one(dhp, sec, pid);
8043 }
8044
8045 /*
8046 * We may have just created probes, so we must now rematch against
8047 * any retained enablings. Note that this call will acquire both
8048 * cpu_lock and dtrace_lock; the fact that we are holding
8049 * dtrace_meta_lock now is what defines the ordering with respect to
8050 * these three locks.
8051 */
8052 dtrace_enabling_matchall();
8053}
8054
8055static void
8056dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8057{
8058 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8059 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8060 dof_sec_t *str_sec;
8061 dof_provider_t *provider;
8062 char *strtab;
8063 dtrace_helper_provdesc_t dhpv;
8064 dtrace_meta_t *meta = dtrace_meta_pid;
8065 dtrace_mops_t *mops = &meta->dtm_mops;
8066
8067 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8068 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8069 provider->dofpv_strtab * dof->dofh_secsize);
8070
8071 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8072
8073 /*
8074 * Create the provider.
8075 */
8076 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8077
8078 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8079
8080 meta->dtm_count--;
8081}
8082
8083static void
8084dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8085{
8086 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8087 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8088 VBDTTYPE(uint32_t,int) i;
8089
8090 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8091
8092 for (i = 0; i < dof->dofh_secnum; i++) {
8093 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8094 dof->dofh_secoff + i * dof->dofh_secsize);
8095
8096 if (sec->dofs_type != DOF_SECT_PROVIDER)
8097 continue;
8098
8099 dtrace_helper_provider_remove_one(dhp, sec, pid);
8100 }
8101}
8102
8103/*
8104 * DTrace Meta Provider-to-Framework API Functions
8105 *
8106 * These functions implement the Meta Provider-to-Framework API, as described
8107 * in <sys/dtrace.h>.
8108 */
8109int
8110dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8111 dtrace_meta_provider_id_t *idp)
8112{
8113 dtrace_meta_t *meta;
8114 dtrace_helpers_t *help, *next;
8115 VBDTTYPE(uint32_t,int) i;
8116
8117 *idp = DTRACE_METAPROVNONE;
8118
8119 /*
8120 * We strictly don't need the name, but we hold onto it for
8121 * debuggability. All hail error queues!
8122 */
8123 if (name == NULL) {
8124 cmn_err(CE_WARN, "failed to register meta-provider: "
8125 "invalid name");
8126 return (EINVAL);
8127 }
8128
8129 if (mops == NULL ||
8130 mops->dtms_create_probe == NULL ||
8131 mops->dtms_provide_pid == NULL ||
8132 mops->dtms_remove_pid == NULL) {
8133 cmn_err(CE_WARN, "failed to register meta-register %s: "
8134 "invalid ops", name);
8135 return (EINVAL);
8136 }
8137
8138 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8139 meta->dtm_mops = *mops;
8140 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8141 (void) strcpy(meta->dtm_name, name);
8142 meta->dtm_arg = arg;
8143
8144 mutex_enter(&dtrace_meta_lock);
8145 mutex_enter(&dtrace_lock);
8146
8147 if (dtrace_meta_pid != NULL) {
8148 mutex_exit(&dtrace_lock);
8149 mutex_exit(&dtrace_meta_lock);
8150 cmn_err(CE_WARN, "failed to register meta-register %s: "
8151 "user-land meta-provider exists", name);
8152 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8153 kmem_free(meta, sizeof (dtrace_meta_t));
8154 return (EINVAL);
8155 }
8156
8157 dtrace_meta_pid = meta;
8158 *idp = (dtrace_meta_provider_id_t)meta;
8159
8160 /*
8161 * If there are providers and probes ready to go, pass them
8162 * off to the new meta provider now.
8163 */
8164
8165 help = dtrace_deferred_pid;
8166 dtrace_deferred_pid = NULL;
8167
8168 mutex_exit(&dtrace_lock);
8169
8170 while (help != NULL) {
8171 for (i = 0; i < help->dthps_nprovs; i++) {
8172 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8173 help->dthps_pid);
8174 }
8175
8176 next = help->dthps_next;
8177 help->dthps_next = NULL;
8178 help->dthps_prev = NULL;
8179 help->dthps_deferred = 0;
8180 help = next;
8181 }
8182
8183 mutex_exit(&dtrace_meta_lock);
8184
8185 return (0);
8186}
8187
8188int
8189dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8190{
8191 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8192
8193 mutex_enter(&dtrace_meta_lock);
8194 mutex_enter(&dtrace_lock);
8195
8196 if (old == dtrace_meta_pid) {
8197 pp = &dtrace_meta_pid;
8198 } else {
8199 panic("attempt to unregister non-existent "
8200 "dtrace meta-provider %p\n", (void *)old);
8201#ifdef VBOX
8202 return EINVAL;
8203#endif
8204 }
8205
8206 if (old->dtm_count != 0) {
8207 mutex_exit(&dtrace_lock);
8208 mutex_exit(&dtrace_meta_lock);
8209 return (EBUSY);
8210 }
8211
8212 *pp = NULL;
8213
8214 mutex_exit(&dtrace_lock);
8215 mutex_exit(&dtrace_meta_lock);
8216
8217 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8218 kmem_free(old, sizeof (dtrace_meta_t));
8219
8220 return (0);
8221}
8222
8223
8224/*
8225 * DTrace DIF Object Functions
8226 */
8227static int
8228dtrace_difo_err(uint_t pc, const char *format, ...)
8229{
8230 if (dtrace_err_verbose) {
8231 va_list alist;
8232
8233 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8234 va_start(alist, format);
8235 (void) vuprintf(format, alist);
8236 va_end(alist);
8237 }
8238
8239#ifdef DTRACE_ERRDEBUG
8240 dtrace_errdebug(format);
8241#endif
8242 return (1);
8243}
8244
8245/*
8246 * Validate a DTrace DIF object by checking the IR instructions. The following
8247 * rules are currently enforced by dtrace_difo_validate():
8248 *
8249 * 1. Each instruction must have a valid opcode
8250 * 2. Each register, string, variable, or subroutine reference must be valid
8251 * 3. No instruction can modify register %r0 (must be zero)
8252 * 4. All instruction reserved bits must be set to zero
8253 * 5. The last instruction must be a "ret" instruction
8254 * 6. All branch targets must reference a valid instruction _after_ the branch
8255 */
8256static int
8257dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8258 cred_t *cr)
8259{
8260#ifndef VBOX
8261 int err = 0, i;
8262#else
8263 int err = 0;
8264 uint_t i;
8265#endif
8266 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8267 int kcheckload;
8268 uint_t pc;
8269
8270 kcheckload = cr == NULL ||
8271 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8272
8273 dp->dtdo_destructive = 0;
8274
8275 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8276 dif_instr_t instr = dp->dtdo_buf[pc];
8277
8278 uint_t r1 = DIF_INSTR_R1(instr);
8279 uint_t r2 = DIF_INSTR_R2(instr);
8280 uint_t rd = DIF_INSTR_RD(instr);
8281 uint_t rs = DIF_INSTR_RS(instr);
8282 uint_t label = DIF_INSTR_LABEL(instr);
8283 uint_t v = DIF_INSTR_VAR(instr);
8284 uint_t subr = DIF_INSTR_SUBR(instr);
8285 uint_t type = DIF_INSTR_TYPE(instr);
8286 uint_t op = DIF_INSTR_OP(instr);
8287
8288 switch (op) {
8289 case DIF_OP_OR:
8290 case DIF_OP_XOR:
8291 case DIF_OP_AND:
8292 case DIF_OP_SLL:
8293 case DIF_OP_SRL:
8294 case DIF_OP_SRA:
8295 case DIF_OP_SUB:
8296 case DIF_OP_ADD:
8297 case DIF_OP_MUL:
8298 case DIF_OP_SDIV:
8299 case DIF_OP_UDIV:
8300 case DIF_OP_SREM:
8301 case DIF_OP_UREM:
8302 case DIF_OP_COPYS:
8303 if (r1 >= nregs)
8304 err += efunc(pc, "invalid register %u\n", r1);
8305 if (r2 >= nregs)
8306 err += efunc(pc, "invalid register %u\n", r2);
8307 if (rd >= nregs)
8308 err += efunc(pc, "invalid register %u\n", rd);
8309 if (rd == 0)
8310 err += efunc(pc, "cannot write to %r0\n");
8311 break;
8312 case DIF_OP_NOT:
8313 case DIF_OP_MOV:
8314 case DIF_OP_ALLOCS:
8315 if (r1 >= nregs)
8316 err += efunc(pc, "invalid register %u\n", r1);
8317 if (r2 != 0)
8318 err += efunc(pc, "non-zero reserved bits\n");
8319 if (rd >= nregs)
8320 err += efunc(pc, "invalid register %u\n", rd);
8321 if (rd == 0)
8322 err += efunc(pc, "cannot write to %r0\n");
8323 break;
8324 case DIF_OP_LDSB:
8325 case DIF_OP_LDSH:
8326 case DIF_OP_LDSW:
8327 case DIF_OP_LDUB:
8328 case DIF_OP_LDUH:
8329 case DIF_OP_LDUW:
8330 case DIF_OP_LDX:
8331 if (r1 >= nregs)
8332 err += efunc(pc, "invalid register %u\n", r1);
8333 if (r2 != 0)
8334 err += efunc(pc, "non-zero reserved bits\n");
8335 if (rd >= nregs)
8336 err += efunc(pc, "invalid register %u\n", rd);
8337 if (rd == 0)
8338 err += efunc(pc, "cannot write to %r0\n");
8339 if (kcheckload)
8340 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8341 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8342 break;
8343 case DIF_OP_RLDSB:
8344 case DIF_OP_RLDSH:
8345 case DIF_OP_RLDSW:
8346 case DIF_OP_RLDUB:
8347 case DIF_OP_RLDUH:
8348 case DIF_OP_RLDUW:
8349 case DIF_OP_RLDX:
8350 if (r1 >= nregs)
8351 err += efunc(pc, "invalid register %u\n", r1);
8352 if (r2 != 0)
8353 err += efunc(pc, "non-zero reserved bits\n");
8354 if (rd >= nregs)
8355 err += efunc(pc, "invalid register %u\n", rd);
8356 if (rd == 0)
8357 err += efunc(pc, "cannot write to %r0\n");
8358 break;
8359 case DIF_OP_ULDSB:
8360 case DIF_OP_ULDSH:
8361 case DIF_OP_ULDSW:
8362 case DIF_OP_ULDUB:
8363 case DIF_OP_ULDUH:
8364 case DIF_OP_ULDUW:
8365 case DIF_OP_ULDX:
8366 if (r1 >= nregs)
8367 err += efunc(pc, "invalid register %u\n", r1);
8368 if (r2 != 0)
8369 err += efunc(pc, "non-zero reserved bits\n");
8370 if (rd >= nregs)
8371 err += efunc(pc, "invalid register %u\n", rd);
8372 if (rd == 0)
8373 err += efunc(pc, "cannot write to %r0\n");
8374 break;
8375 case DIF_OP_STB:
8376 case DIF_OP_STH:
8377 case DIF_OP_STW:
8378 case DIF_OP_STX:
8379 if (r1 >= nregs)
8380 err += efunc(pc, "invalid register %u\n", r1);
8381 if (r2 != 0)
8382 err += efunc(pc, "non-zero reserved bits\n");
8383 if (rd >= nregs)
8384 err += efunc(pc, "invalid register %u\n", rd);
8385 if (rd == 0)
8386 err += efunc(pc, "cannot write to 0 address\n");
8387 break;
8388 case DIF_OP_CMP:
8389 case DIF_OP_SCMP:
8390 if (r1 >= nregs)
8391 err += efunc(pc, "invalid register %u\n", r1);
8392 if (r2 >= nregs)
8393 err += efunc(pc, "invalid register %u\n", r2);
8394 if (rd != 0)
8395 err += efunc(pc, "non-zero reserved bits\n");
8396 break;
8397 case DIF_OP_TST:
8398 if (r1 >= nregs)
8399 err += efunc(pc, "invalid register %u\n", r1);
8400 if (r2 != 0 || rd != 0)
8401 err += efunc(pc, "non-zero reserved bits\n");
8402 break;
8403 case DIF_OP_BA:
8404 case DIF_OP_BE:
8405 case DIF_OP_BNE:
8406 case DIF_OP_BG:
8407 case DIF_OP_BGU:
8408 case DIF_OP_BGE:
8409 case DIF_OP_BGEU:
8410 case DIF_OP_BL:
8411 case DIF_OP_BLU:
8412 case DIF_OP_BLE:
8413 case DIF_OP_BLEU:
8414 if (label >= dp->dtdo_len) {
8415 err += efunc(pc, "invalid branch target %u\n",
8416 label);
8417 }
8418 if (label <= pc) {
8419 err += efunc(pc, "backward branch to %u\n",
8420 label);
8421 }
8422 break;
8423 case DIF_OP_RET:
8424 if (r1 != 0 || r2 != 0)
8425 err += efunc(pc, "non-zero reserved bits\n");
8426 if (rd >= nregs)
8427 err += efunc(pc, "invalid register %u\n", rd);
8428 break;
8429 case DIF_OP_NOP:
8430 case DIF_OP_POPTS:
8431 case DIF_OP_FLUSHTS:
8432 if (r1 != 0 || r2 != 0 || rd != 0)
8433 err += efunc(pc, "non-zero reserved bits\n");
8434 break;
8435 case DIF_OP_SETX:
8436 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8437 err += efunc(pc, "invalid integer ref %u\n",
8438 DIF_INSTR_INTEGER(instr));
8439 }
8440 if (rd >= nregs)
8441 err += efunc(pc, "invalid register %u\n", rd);
8442 if (rd == 0)
8443 err += efunc(pc, "cannot write to %r0\n");
8444 break;
8445 case DIF_OP_SETS:
8446 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8447 err += efunc(pc, "invalid string ref %u\n",
8448 DIF_INSTR_STRING(instr));
8449 }
8450 if (rd >= nregs)
8451 err += efunc(pc, "invalid register %u\n", rd);
8452 if (rd == 0)
8453 err += efunc(pc, "cannot write to %r0\n");
8454 break;
8455 case DIF_OP_LDGA:
8456 case DIF_OP_LDTA:
8457 if (r1 > DIF_VAR_ARRAY_MAX)
8458 err += efunc(pc, "invalid array %u\n", r1);
8459 if (r2 >= nregs)
8460 err += efunc(pc, "invalid register %u\n", r2);
8461 if (rd >= nregs)
8462 err += efunc(pc, "invalid register %u\n", rd);
8463 if (rd == 0)
8464 err += efunc(pc, "cannot write to %r0\n");
8465 break;
8466 case DIF_OP_LDGS:
8467 case DIF_OP_LDTS:
8468 case DIF_OP_LDLS:
8469 case DIF_OP_LDGAA:
8470 case DIF_OP_LDTAA:
8471 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8472 err += efunc(pc, "invalid variable %u\n", v);
8473 if (rd >= nregs)
8474 err += efunc(pc, "invalid register %u\n", rd);
8475 if (rd == 0)
8476 err += efunc(pc, "cannot write to %r0\n");
8477 break;
8478 case DIF_OP_STGS:
8479 case DIF_OP_STTS:
8480 case DIF_OP_STLS:
8481 case DIF_OP_STGAA:
8482 case DIF_OP_STTAA:
8483 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8484 err += efunc(pc, "invalid variable %u\n", v);
8485 if (rs >= nregs)
8486 err += efunc(pc, "invalid register %u\n", rd);
8487 break;
8488 case DIF_OP_CALL:
8489 if (subr > DIF_SUBR_MAX)
8490 err += efunc(pc, "invalid subr %u\n", subr);
8491 if (rd >= nregs)
8492 err += efunc(pc, "invalid register %u\n", rd);
8493 if (rd == 0)
8494 err += efunc(pc, "cannot write to %r0\n");
8495
8496 if (subr == DIF_SUBR_COPYOUT ||
8497 subr == DIF_SUBR_COPYOUTSTR) {
8498 dp->dtdo_destructive = 1;
8499 }
8500 break;
8501 case DIF_OP_PUSHTR:
8502 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8503 err += efunc(pc, "invalid ref type %u\n", type);
8504 if (r2 >= nregs)
8505 err += efunc(pc, "invalid register %u\n", r2);
8506 if (rs >= nregs)
8507 err += efunc(pc, "invalid register %u\n", rs);
8508 break;
8509 case DIF_OP_PUSHTV:
8510 if (type != DIF_TYPE_CTF)
8511 err += efunc(pc, "invalid val type %u\n", type);
8512 if (r2 >= nregs)
8513 err += efunc(pc, "invalid register %u\n", r2);
8514 if (rs >= nregs)
8515 err += efunc(pc, "invalid register %u\n", rs);
8516 break;
8517 default:
8518 err += efunc(pc, "invalid opcode %u\n",
8519 DIF_INSTR_OP(instr));
8520 }
8521 }
8522
8523 if (dp->dtdo_len != 0 &&
8524 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8525 err += efunc(dp->dtdo_len - 1,
8526 "expected 'ret' as last DIF instruction\n");
8527 }
8528
8529 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8530 /*
8531 * If we're not returning by reference, the size must be either
8532 * 0 or the size of one of the base types.
8533 */
8534 switch (dp->dtdo_rtype.dtdt_size) {
8535 case 0:
8536 case sizeof (uint8_t):
8537 case sizeof (uint16_t):
8538 case sizeof (uint32_t):
8539 case sizeof (uint64_t):
8540 break;
8541
8542 default:
8543 err += efunc(dp->dtdo_len - 1, "bad return size\n");
8544 }
8545 }
8546
8547 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8548 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8549 dtrace_diftype_t *vt, *et;
8550 uint_t id, ndx;
8551
8552 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8553 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8554 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8555 err += efunc(i, "unrecognized variable scope %d\n",
8556 v->dtdv_scope);
8557 break;
8558 }
8559
8560 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8561 v->dtdv_kind != DIFV_KIND_SCALAR) {
8562 err += efunc(i, "unrecognized variable type %d\n",
8563 v->dtdv_kind);
8564 break;
8565 }
8566
8567 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8568 err += efunc(i, "%d exceeds variable id limit\n", id);
8569 break;
8570 }
8571
8572 if (id < DIF_VAR_OTHER_UBASE)
8573 continue;
8574
8575 /*
8576 * For user-defined variables, we need to check that this
8577 * definition is identical to any previous definition that we
8578 * encountered.
8579 */
8580 ndx = id - DIF_VAR_OTHER_UBASE;
8581
8582 switch (v->dtdv_scope) {
8583 case DIFV_SCOPE_GLOBAL:
8584 if (VBDTCAST(int64_t)ndx < vstate->dtvs_nglobals) {
8585 dtrace_statvar_t *svar;
8586
8587 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8588 existing = &svar->dtsv_var;
8589 }
8590
8591 break;
8592
8593 case DIFV_SCOPE_THREAD:
8594 if (VBDTCAST(int64_t)ndx < vstate->dtvs_ntlocals)
8595 existing = &vstate->dtvs_tlocals[ndx];
8596 break;
8597
8598 case DIFV_SCOPE_LOCAL:
8599 if (VBDTCAST(int64_t)ndx < vstate->dtvs_nlocals) {
8600 dtrace_statvar_t *svar;
8601
8602 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8603 existing = &svar->dtsv_var;
8604 }
8605
8606 break;
8607 }
8608
8609 vt = &v->dtdv_type;
8610
8611 if (vt->dtdt_flags & DIF_TF_BYREF) {
8612 if (vt->dtdt_size == 0) {
8613 err += efunc(i, "zero-sized variable\n");
8614 break;
8615 }
8616
8617 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8618 vt->dtdt_size > dtrace_global_maxsize) {
8619 err += efunc(i, "oversized by-ref global\n");
8620 break;
8621 }
8622 }
8623
8624 if (existing == NULL || existing->dtdv_id == 0)
8625 continue;
8626
8627 ASSERT(existing->dtdv_id == v->dtdv_id);
8628 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8629
8630 if (existing->dtdv_kind != v->dtdv_kind)
8631 err += efunc(i, "%d changed variable kind\n", id);
8632
8633 et = &existing->dtdv_type;
8634
8635 if (vt->dtdt_flags != et->dtdt_flags) {
8636 err += efunc(i, "%d changed variable type flags\n", id);
8637 break;
8638 }
8639
8640 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8641 err += efunc(i, "%d changed variable type size\n", id);
8642 break;
8643 }
8644 }
8645
8646 return (err);
8647}
8648
8649/*
8650 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
8651 * are much more constrained than normal DIFOs. Specifically, they may
8652 * not:
8653 *
8654 * 1. Make calls to subroutines other than copyin(), copyinstr() or
8655 * miscellaneous string routines
8656 * 2. Access DTrace variables other than the args[] array, and the
8657 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8658 * 3. Have thread-local variables.
8659 * 4. Have dynamic variables.
8660 */
8661static int
8662dtrace_difo_validate_helper(dtrace_difo_t *dp)
8663{
8664 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8665 int err = 0;
8666 uint_t pc;
8667
8668 for (pc = 0; pc < dp->dtdo_len; pc++) {
8669 dif_instr_t instr = dp->dtdo_buf[pc];
8670
8671 uint_t v = DIF_INSTR_VAR(instr);
8672 uint_t subr = DIF_INSTR_SUBR(instr);
8673 uint_t op = DIF_INSTR_OP(instr);
8674
8675 switch (op) {
8676 case DIF_OP_OR:
8677 case DIF_OP_XOR:
8678 case DIF_OP_AND:
8679 case DIF_OP_SLL:
8680 case DIF_OP_SRL:
8681 case DIF_OP_SRA:
8682 case DIF_OP_SUB:
8683 case DIF_OP_ADD:
8684 case DIF_OP_MUL:
8685 case DIF_OP_SDIV:
8686 case DIF_OP_UDIV:
8687 case DIF_OP_SREM:
8688 case DIF_OP_UREM:
8689 case DIF_OP_COPYS:
8690 case DIF_OP_NOT:
8691 case DIF_OP_MOV:
8692 case DIF_OP_RLDSB:
8693 case DIF_OP_RLDSH:
8694 case DIF_OP_RLDSW:
8695 case DIF_OP_RLDUB:
8696 case DIF_OP_RLDUH:
8697 case DIF_OP_RLDUW:
8698 case DIF_OP_RLDX:
8699 case DIF_OP_ULDSB:
8700 case DIF_OP_ULDSH:
8701 case DIF_OP_ULDSW:
8702 case DIF_OP_ULDUB:
8703 case DIF_OP_ULDUH:
8704 case DIF_OP_ULDUW:
8705 case DIF_OP_ULDX:
8706 case DIF_OP_STB:
8707 case DIF_OP_STH:
8708 case DIF_OP_STW:
8709 case DIF_OP_STX:
8710 case DIF_OP_ALLOCS:
8711 case DIF_OP_CMP:
8712 case DIF_OP_SCMP:
8713 case DIF_OP_TST:
8714 case DIF_OP_BA:
8715 case DIF_OP_BE:
8716 case DIF_OP_BNE:
8717 case DIF_OP_BG:
8718 case DIF_OP_BGU:
8719 case DIF_OP_BGE:
8720 case DIF_OP_BGEU:
8721 case DIF_OP_BL:
8722 case DIF_OP_BLU:
8723 case DIF_OP_BLE:
8724 case DIF_OP_BLEU:
8725 case DIF_OP_RET:
8726 case DIF_OP_NOP:
8727 case DIF_OP_POPTS:
8728 case DIF_OP_FLUSHTS:
8729 case DIF_OP_SETX:
8730 case DIF_OP_SETS:
8731 case DIF_OP_LDGA:
8732 case DIF_OP_LDLS:
8733 case DIF_OP_STGS:
8734 case DIF_OP_STLS:
8735 case DIF_OP_PUSHTR:
8736 case DIF_OP_PUSHTV:
8737 break;
8738
8739 case DIF_OP_LDGS:
8740 if (v >= DIF_VAR_OTHER_UBASE)
8741 break;
8742
8743 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8744 break;
8745
8746 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8747 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8748 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8749 v == DIF_VAR_UID || v == DIF_VAR_GID)
8750 break;
8751
8752 err += efunc(pc, "illegal variable %u\n", v);
8753 break;
8754
8755 case DIF_OP_LDTA:
8756 case DIF_OP_LDTS:
8757 case DIF_OP_LDGAA:
8758 case DIF_OP_LDTAA:
8759 err += efunc(pc, "illegal dynamic variable load\n");
8760 break;
8761
8762 case DIF_OP_STTS:
8763 case DIF_OP_STGAA:
8764 case DIF_OP_STTAA:
8765 err += efunc(pc, "illegal dynamic variable store\n");
8766 break;
8767
8768 case DIF_OP_CALL:
8769 if (subr == DIF_SUBR_ALLOCA ||
8770 subr == DIF_SUBR_BCOPY ||
8771 subr == DIF_SUBR_COPYIN ||
8772 subr == DIF_SUBR_COPYINTO ||
8773 subr == DIF_SUBR_COPYINSTR ||
8774 subr == DIF_SUBR_INDEX ||
8775 subr == DIF_SUBR_INET_NTOA ||
8776 subr == DIF_SUBR_INET_NTOA6 ||
8777 subr == DIF_SUBR_INET_NTOP ||
8778 subr == DIF_SUBR_LLTOSTR ||
8779 subr == DIF_SUBR_RINDEX ||
8780 subr == DIF_SUBR_STRCHR ||
8781 subr == DIF_SUBR_STRJOIN ||
8782 subr == DIF_SUBR_STRRCHR ||
8783 subr == DIF_SUBR_STRSTR ||
8784 subr == DIF_SUBR_HTONS ||
8785 subr == DIF_SUBR_HTONL ||
8786 subr == DIF_SUBR_HTONLL ||
8787 subr == DIF_SUBR_NTOHS ||
8788 subr == DIF_SUBR_NTOHL ||
8789 subr == DIF_SUBR_NTOHLL)
8790 break;
8791
8792 err += efunc(pc, "invalid subr %u\n", subr);
8793 break;
8794
8795 default:
8796 err += efunc(pc, "invalid opcode %u\n",
8797 DIF_INSTR_OP(instr));
8798 }
8799 }
8800
8801 return (err);
8802}
8803
8804/*
8805 * Returns 1 if the expression in the DIF object can be cached on a per-thread
8806 * basis; 0 if not.
8807 */
8808static int
8809dtrace_difo_cacheable(dtrace_difo_t *dp)
8810{
8811 VBDTTYPE(uint_t,int) i;
8812
8813 if (dp == NULL)
8814 return (0);
8815
8816 for (i = 0; i < dp->dtdo_varlen; i++) {
8817 dtrace_difv_t *v = &dp->dtdo_vartab[i];
8818
8819 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8820 continue;
8821
8822 switch (v->dtdv_id) {
8823 case DIF_VAR_CURTHREAD:
8824 case DIF_VAR_PID:
8825 case DIF_VAR_TID:
8826 case DIF_VAR_EXECNAME:
8827 case DIF_VAR_ZONENAME:
8828 break;
8829
8830 default:
8831 return (0);
8832 }
8833 }
8834
8835 /*
8836 * This DIF object may be cacheable. Now we need to look for any
8837 * array loading instructions, any memory loading instructions, or
8838 * any stores to thread-local variables.
8839 */
8840 for (i = 0; i < dp->dtdo_len; i++) {
8841 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8842
8843 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8844 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8845 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8846 op == DIF_OP_LDGA || op == DIF_OP_STTS)
8847 return (0);
8848 }
8849
8850 return (1);
8851}
8852
8853static void
8854dtrace_difo_hold(dtrace_difo_t *dp)
8855{
8856#ifndef VBOX
8857 VBDTTYPE(uint_t,int) i;
8858#endif
8859
8860 ASSERT(MUTEX_HELD(&dtrace_lock));
8861
8862 dp->dtdo_refcnt++;
8863 ASSERT(dp->dtdo_refcnt != 0);
8864
8865#ifndef VBOX
8866 /*
8867 * We need to check this DIF object for references to the variable
8868 * DIF_VAR_VTIMESTAMP.
8869 */
8870 for (i = 0; i < dp->dtdo_varlen; i++) {
8871 dtrace_difv_t *v = &dp->dtdo_vartab[i];
8872
8873 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8874 continue;
8875
8876 if (dtrace_vtime_references++ == 0)
8877 dtrace_vtime_enable();
8878 }
8879#endif
8880}
8881
8882/*
8883 * This routine calculates the dynamic variable chunksize for a given DIF
8884 * object. The calculation is not fool-proof, and can probably be tricked by
8885 * malicious DIF -- but it works for all compiler-generated DIF. Because this
8886 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8887 * if a dynamic variable size exceeds the chunksize.
8888 */
8889static void
8890dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8891{
8892 uint64_t sval VBDTGCC(0);
8893 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8894 const dif_instr_t *text = dp->dtdo_buf;
8895 uint_t pc, srd = 0;
8896 uint_t ttop = 0;
8897 size_t size, ksize;
8898 uint_t id, i;
8899
8900 for (pc = 0; pc < dp->dtdo_len; pc++) {
8901 dif_instr_t instr = text[pc];
8902 uint_t op = DIF_INSTR_OP(instr);
8903 uint_t rd = DIF_INSTR_RD(instr);
8904 uint_t r1 = DIF_INSTR_R1(instr);
8905 uint_t nkeys = 0;
8906 uchar_t scope VBDTGCC(0);
8907
8908 dtrace_key_t *key = tupregs;
8909
8910 switch (op) {
8911 case DIF_OP_SETX:
8912 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8913 srd = rd;
8914 continue;
8915
8916 case DIF_OP_STTS:
8917 key = &tupregs[DIF_DTR_NREGS];
8918 key[0].dttk_size = 0;
8919 key[1].dttk_size = 0;
8920 nkeys = 2;
8921 scope = DIFV_SCOPE_THREAD;
8922 break;
8923
8924 case DIF_OP_STGAA:
8925 case DIF_OP_STTAA:
8926 nkeys = ttop;
8927
8928 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8929 key[nkeys++].dttk_size = 0;
8930
8931 key[nkeys++].dttk_size = 0;
8932
8933 if (op == DIF_OP_STTAA) {
8934 scope = DIFV_SCOPE_THREAD;
8935 } else {
8936 scope = DIFV_SCOPE_GLOBAL;
8937 }
8938
8939 break;
8940
8941 case DIF_OP_PUSHTR:
8942 if (ttop == DIF_DTR_NREGS)
8943 return;
8944
8945 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8946 /*
8947 * If the register for the size of the "pushtr"
8948 * is %r0 (or the value is 0) and the type is
8949 * a string, we'll use the system-wide default
8950 * string size.
8951 */
8952 tupregs[ttop++].dttk_size =
8953 dtrace_strsize_default;
8954 } else {
8955 if (srd == 0)
8956 return;
8957
8958 tupregs[ttop++].dttk_size = sval;
8959 }
8960
8961 break;
8962
8963 case DIF_OP_PUSHTV:
8964 if (ttop == DIF_DTR_NREGS)
8965 return;
8966
8967 tupregs[ttop++].dttk_size = 0;
8968 break;
8969
8970 case DIF_OP_FLUSHTS:
8971 ttop = 0;
8972 break;
8973
8974 case DIF_OP_POPTS:
8975 if (ttop != 0)
8976 ttop--;
8977 break;
8978 }
8979
8980 sval = 0;
8981 srd = 0;
8982
8983 if (nkeys == 0)
8984 continue;
8985
8986 /*
8987 * We have a dynamic variable allocation; calculate its size.
8988 */
8989 for (ksize = 0, i = 0; i < nkeys; i++)
8990 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8991
8992 size = sizeof (dtrace_dynvar_t);
8993 size += sizeof (dtrace_key_t) * (nkeys - 1);
8994 size += ksize;
8995
8996 /*
8997 * Now we need to determine the size of the stored data.
8998 */
8999 id = DIF_INSTR_VAR(instr);
9000
9001 for (i = 0; i < dp->dtdo_varlen; i++) {
9002 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9003
9004 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9005 size += v->dtdv_type.dtdt_size;
9006 break;
9007 }
9008 }
9009
9010 if (i == dp->dtdo_varlen)
9011 return;
9012
9013 /*
9014 * We have the size. If this is larger than the chunk size
9015 * for our dynamic variable state, reset the chunk size.
9016 */
9017 size = P2ROUNDUP(size, sizeof (uint64_t));
9018
9019 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9020 vstate->dtvs_dynvars.dtds_chunksize = size;
9021 }
9022}
9023
9024static void
9025dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9026{
9027#ifndef VBOX
9028 int i, oldsvars, osz, nsz, otlocals, ntlocals;
9029#else
9030 int oldsvars, osz, nsz, otlocals, ntlocals;
9031 uint_t i;
9032#endif
9033 uint_t id;
9034
9035 ASSERT(MUTEX_HELD(&dtrace_lock));
9036 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9037
9038 for (i = 0; i < dp->dtdo_varlen; i++) {
9039 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9040 dtrace_statvar_t *svar, ***svarp;
9041 size_t dsize = 0;
9042 uint8_t scope = v->dtdv_scope;
9043 int *np;
9044
9045 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9046 continue;
9047
9048 id -= DIF_VAR_OTHER_UBASE;
9049
9050 switch (scope) {
9051 case DIFV_SCOPE_THREAD:
9052 while (VBDTCAST(int64_t)id >= (otlocals = vstate->dtvs_ntlocals)) {
9053 dtrace_difv_t *tlocals;
9054
9055 if ((ntlocals = (otlocals << 1)) == 0)
9056 ntlocals = 1;
9057
9058 osz = otlocals * sizeof (dtrace_difv_t);
9059 nsz = ntlocals * sizeof (dtrace_difv_t);
9060
9061 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9062
9063 if (osz != 0) {
9064 bcopy(vstate->dtvs_tlocals,
9065 tlocals, osz);
9066 kmem_free(vstate->dtvs_tlocals, osz);
9067 }
9068
9069 vstate->dtvs_tlocals = tlocals;
9070 vstate->dtvs_ntlocals = ntlocals;
9071 }
9072
9073 vstate->dtvs_tlocals[id] = *v;
9074 continue;
9075
9076 case DIFV_SCOPE_LOCAL:
9077 np = &vstate->dtvs_nlocals;
9078 svarp = &vstate->dtvs_locals;
9079
9080 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9081 dsize = NCPU * (v->dtdv_type.dtdt_size +
9082 sizeof (uint64_t));
9083 else
9084 dsize = NCPU * sizeof (uint64_t);
9085
9086 break;
9087
9088 case DIFV_SCOPE_GLOBAL:
9089 np = &vstate->dtvs_nglobals;
9090 svarp = &vstate->dtvs_globals;
9091
9092 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9093 dsize = v->dtdv_type.dtdt_size +
9094 sizeof (uint64_t);
9095
9096 break;
9097
9098 default:
9099#ifndef VBOX
9100 ASSERT(0);
9101#else
9102 AssertFatalMsgFailed(("%d\n", scope));
9103#endif
9104 }
9105
9106 while (VBDTCAST(int64_t)id >= (oldsvars = *np)) {
9107 dtrace_statvar_t **statics;
9108 int newsvars, oldsize, newsize;
9109
9110 if ((newsvars = (oldsvars << 1)) == 0)
9111 newsvars = 1;
9112
9113 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9114 newsize = newsvars * sizeof (dtrace_statvar_t *);
9115
9116 statics = kmem_zalloc(newsize, KM_SLEEP);
9117
9118 if (oldsize != 0) {
9119 bcopy(*svarp, statics, oldsize);
9120 kmem_free(*svarp, oldsize);
9121 }
9122
9123 *svarp = statics;
9124 *np = newsvars;
9125 }
9126
9127 if ((svar = (*svarp)[id]) == NULL) {
9128 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9129 svar->dtsv_var = *v;
9130
9131 if ((svar->dtsv_size = dsize) != 0) {
9132 svar->dtsv_data = (uint64_t)(uintptr_t)
9133 kmem_zalloc(dsize, KM_SLEEP);
9134 }
9135
9136 (*svarp)[id] = svar;
9137 }
9138
9139 svar->dtsv_refcnt++;
9140 }
9141
9142 dtrace_difo_chunksize(dp, vstate);
9143 dtrace_difo_hold(dp);
9144}
9145
9146static dtrace_difo_t *
9147dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9148{
9149 dtrace_difo_t *new;
9150 size_t sz;
9151
9152 ASSERT(dp->dtdo_buf != NULL);
9153 ASSERT(dp->dtdo_refcnt != 0);
9154
9155 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9156
9157 ASSERT(dp->dtdo_buf != NULL);
9158 sz = dp->dtdo_len * sizeof (dif_instr_t);
9159 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9160 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9161 new->dtdo_len = dp->dtdo_len;
9162
9163 if (dp->dtdo_strtab != NULL) {
9164 ASSERT(dp->dtdo_strlen != 0);
9165 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9166 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9167 new->dtdo_strlen = dp->dtdo_strlen;
9168 }
9169
9170 if (dp->dtdo_inttab != NULL) {
9171 ASSERT(dp->dtdo_intlen != 0);
9172 sz = dp->dtdo_intlen * sizeof (uint64_t);
9173 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9174 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9175 new->dtdo_intlen = dp->dtdo_intlen;
9176 }
9177
9178 if (dp->dtdo_vartab != NULL) {
9179 ASSERT(dp->dtdo_varlen != 0);
9180 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9181 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9182 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9183 new->dtdo_varlen = dp->dtdo_varlen;
9184 }
9185
9186 dtrace_difo_init(new, vstate);
9187 return (new);
9188}
9189
9190static void
9191dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9192{
9193 VBDTTYPE(uint_t,int) i;
9194
9195 ASSERT(dp->dtdo_refcnt == 0);
9196
9197 for (i = 0; i < dp->dtdo_varlen; i++) {
9198 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9199 dtrace_statvar_t *svar, **svarp;
9200 uint_t id;
9201 uint8_t scope = v->dtdv_scope;
9202 int *np;
9203
9204 switch (scope) {
9205 case DIFV_SCOPE_THREAD:
9206 continue;
9207
9208 case DIFV_SCOPE_LOCAL:
9209 np = &vstate->dtvs_nlocals;
9210 svarp = vstate->dtvs_locals;
9211 break;
9212
9213 case DIFV_SCOPE_GLOBAL:
9214 np = &vstate->dtvs_nglobals;
9215 svarp = vstate->dtvs_globals;
9216 break;
9217
9218 default:
9219#ifndef VBOX
9220 ASSERT(0);
9221#else
9222 AssertFatalMsgFailed(("%d\n", scope));
9223#endif
9224 }
9225
9226 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9227 continue;
9228
9229 id -= DIF_VAR_OTHER_UBASE;
9230 ASSERT(VBDTCAST(int64_t)id < *np);
9231
9232 svar = svarp[id];
9233 ASSERT(svar != NULL);
9234 ASSERT(svar->dtsv_refcnt > 0);
9235
9236 if (--svar->dtsv_refcnt > 0)
9237 continue;
9238
9239 if (svar->dtsv_size != 0) {
9240 ASSERT(svar->dtsv_data != NULL);
9241 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9242 svar->dtsv_size);
9243 }
9244
9245 kmem_free(svar, sizeof (dtrace_statvar_t));
9246 svarp[id] = NULL;
9247 }
9248
9249 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9250 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9251 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9252 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9253
9254 kmem_free(dp, sizeof (dtrace_difo_t));
9255}
9256
9257static void
9258dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9259{
9260#ifndef VBOX
9261 VBDTTYPE(uint_t,int) i;
9262#endif
9263
9264 ASSERT(MUTEX_HELD(&dtrace_lock));
9265 ASSERT(dp->dtdo_refcnt != 0);
9266
9267#ifndef VBOX
9268 for (i = 0; i < dp->dtdo_varlen; i++) {
9269 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9270
9271 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9272 continue;
9273
9274 ASSERT(dtrace_vtime_references > 0);
9275 if (--dtrace_vtime_references == 0)
9276 dtrace_vtime_disable();
9277 }
9278#endif
9279
9280 if (--dp->dtdo_refcnt == 0)
9281 dtrace_difo_destroy(dp, vstate);
9282}
9283
9284/*
9285 * DTrace Format Functions
9286 */
9287static uint16_t
9288dtrace_format_add(dtrace_state_t *state, char *str)
9289{
9290 char *fmt, **new;
9291 uint16_t ndx, len = VBDTCAST(uint16_t)strlen(str) + 1;
9292
9293 fmt = kmem_zalloc(len, KM_SLEEP);
9294 bcopy(str, fmt, len);
9295
9296 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9297 if (state->dts_formats[ndx] == NULL) {
9298 state->dts_formats[ndx] = fmt;
9299 return (ndx + 1);
9300 }
9301 }
9302
9303 if (state->dts_nformats == USHRT_MAX) {
9304 /*
9305 * This is only likely if a denial-of-service attack is being
9306 * attempted. As such, it's okay to fail silently here.
9307 */
9308 kmem_free(fmt, len);
9309 return (0);
9310 }
9311
9312 /*
9313 * For simplicity, we always resize the formats array to be exactly the
9314 * number of formats.
9315 */
9316 ndx = state->dts_nformats++;
9317 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9318
9319 if (state->dts_formats != NULL) {
9320 ASSERT(ndx != 0);
9321 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9322 kmem_free(state->dts_formats, ndx * sizeof (char *));
9323 }
9324
9325 state->dts_formats = new;
9326 state->dts_formats[ndx] = fmt;
9327
9328 return (ndx + 1);
9329}
9330
9331static void
9332dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9333{
9334 char *fmt;
9335
9336 ASSERT(state->dts_formats != NULL);
9337 ASSERT(format <= state->dts_nformats);
9338 ASSERT(state->dts_formats[format - 1] != NULL);
9339
9340 fmt = state->dts_formats[format - 1];
9341 kmem_free(fmt, strlen(fmt) + 1);
9342 state->dts_formats[format - 1] = NULL;
9343}
9344
9345static void
9346dtrace_format_destroy(dtrace_state_t *state)
9347{
9348 int i;
9349
9350 if (state->dts_nformats == 0) {
9351 ASSERT(state->dts_formats == NULL);
9352 return;
9353 }
9354
9355 ASSERT(state->dts_formats != NULL);
9356
9357 for (i = 0; i < state->dts_nformats; i++) {
9358 char *fmt = state->dts_formats[i];
9359
9360 if (fmt == NULL)
9361 continue;
9362
9363 kmem_free(fmt, strlen(fmt) + 1);
9364 }
9365
9366 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9367 state->dts_nformats = 0;
9368 state->dts_formats = NULL;
9369}
9370
9371/*
9372 * DTrace Predicate Functions
9373 */
9374static dtrace_predicate_t *
9375dtrace_predicate_create(dtrace_difo_t *dp)
9376{
9377 dtrace_predicate_t *pred;
9378
9379 ASSERT(MUTEX_HELD(&dtrace_lock));
9380 ASSERT(dp->dtdo_refcnt != 0);
9381
9382 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9383 pred->dtp_difo = dp;
9384 pred->dtp_refcnt = 1;
9385
9386 if (!dtrace_difo_cacheable(dp))
9387 return (pred);
9388
9389 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9390 /*
9391 * This is only theoretically possible -- we have had 2^32
9392 * cacheable predicates on this machine. We cannot allow any
9393 * more predicates to become cacheable: as unlikely as it is,
9394 * there may be a thread caching a (now stale) predicate cache
9395 * ID. (N.B.: the temptation is being successfully resisted to
9396 * have this cmn_err() "Holy shit -- we executed this code!")
9397 */
9398 return (pred);
9399 }
9400
9401 pred->dtp_cacheid = dtrace_predcache_id++;
9402
9403 return (pred);
9404}
9405
9406static void
9407dtrace_predicate_hold(dtrace_predicate_t *pred)
9408{
9409 ASSERT(MUTEX_HELD(&dtrace_lock));
9410 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9411 ASSERT(pred->dtp_refcnt > 0);
9412
9413 pred->dtp_refcnt++;
9414}
9415
9416static void
9417dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9418{
9419#ifdef VBOX_STRICT
9420 dtrace_difo_t *dp = pred->dtp_difo;
9421#endif
9422
9423 ASSERT(MUTEX_HELD(&dtrace_lock));
9424 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9425 ASSERT(pred->dtp_refcnt > 0);
9426
9427 if (--pred->dtp_refcnt == 0) {
9428 dtrace_difo_release(pred->dtp_difo, vstate);
9429 kmem_free(pred, sizeof (dtrace_predicate_t));
9430 }
9431}
9432
9433/*
9434 * DTrace Action Description Functions
9435 */
9436static dtrace_actdesc_t *
9437dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9438 uint64_t uarg, uint64_t arg)
9439{
9440 dtrace_actdesc_t *act;
9441
9442 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9443 VBDT_IS_VALID_KRNL_ADDR(arg)) || (arg == NULL && kind == DTRACEACT_PRINTA));
9444
9445 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9446 act->dtad_kind = kind;
9447 act->dtad_ntuple = ntuple;
9448 act->dtad_uarg = uarg;
9449 act->dtad_arg = arg;
9450 act->dtad_refcnt = 1;
9451
9452 return (act);
9453}
9454
9455static void
9456dtrace_actdesc_hold(dtrace_actdesc_t *act)
9457{
9458 ASSERT(act->dtad_refcnt >= 1);
9459 act->dtad_refcnt++;
9460}
9461
9462static void
9463dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9464{
9465 dtrace_actkind_t kind = act->dtad_kind;
9466 dtrace_difo_t *dp;
9467
9468 ASSERT(act->dtad_refcnt >= 1);
9469
9470 if (--act->dtad_refcnt != 0)
9471 return;
9472
9473 if ((dp = act->dtad_difo) != NULL)
9474 dtrace_difo_release(dp, vstate);
9475
9476 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9477 char *str = (char *)(uintptr_t)act->dtad_arg;
9478
9479 ASSERT((str != NULL && VBDT_IS_VALID_KRNL_ADDR((uintptr_t)str)) ||
9480 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9481
9482 if (str != NULL)
9483 kmem_free(str, strlen(str) + 1);
9484 }
9485
9486 kmem_free(act, sizeof (dtrace_actdesc_t));
9487}
9488
9489/*
9490 * DTrace ECB Functions
9491 */
9492static dtrace_ecb_t *
9493dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9494{
9495 dtrace_ecb_t *ecb;
9496 dtrace_epid_t epid;
9497
9498 ASSERT(MUTEX_HELD(&dtrace_lock));
9499
9500 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9501 ecb->dte_predicate = NULL;
9502 ecb->dte_probe = probe;
9503
9504 /*
9505 * The default size is the size of the default action: recording
9506 * the epid.
9507 */
9508 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9509 ecb->dte_alignment = sizeof (dtrace_epid_t);
9510
9511 epid = state->dts_epid++;
9512
9513 if (VBDTCAST(int64_t)epid - 1 >= state->dts_necbs) {
9514 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9515 int necbs = state->dts_necbs << 1;
9516
9517 ASSERT(epid == VBDTCAST(dtrace_epid_t)state->dts_necbs + 1);
9518
9519 if (necbs == 0) {
9520 ASSERT(oecbs == NULL);
9521 necbs = 1;
9522 }
9523
9524 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9525
9526 if (oecbs != NULL)
9527 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9528
9529 dtrace_membar_producer();
9530 state->dts_ecbs = ecbs;
9531
9532 if (oecbs != NULL) {
9533 /*
9534 * If this state is active, we must dtrace_sync()
9535 * before we can free the old dts_ecbs array: we're
9536 * coming in hot, and there may be active ring
9537 * buffer processing (which indexes into the dts_ecbs
9538 * array) on another CPU.
9539 */
9540 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9541 dtrace_sync();
9542
9543 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9544 }
9545
9546 dtrace_membar_producer();
9547 state->dts_necbs = necbs;
9548 }
9549
9550 ecb->dte_state = state;
9551
9552 ASSERT(state->dts_ecbs[epid - 1] == NULL);
9553 dtrace_membar_producer();
9554 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9555
9556 return (ecb);
9557}
9558
9559static int
9560dtrace_ecb_enable(dtrace_ecb_t *ecb)
9561{
9562 dtrace_probe_t *probe = ecb->dte_probe;
9563
9564 ASSERT(MUTEX_HELD(&cpu_lock));
9565 ASSERT(MUTEX_HELD(&dtrace_lock));
9566 ASSERT(ecb->dte_next == NULL);
9567
9568 if (probe == NULL) {
9569 /*
9570 * This is the NULL probe -- there's nothing to do.
9571 */
9572 return (0);
9573 }
9574
9575 if (probe->dtpr_ecb == NULL) {
9576 dtrace_provider_t *prov = probe->dtpr_provider;
9577
9578 /*
9579 * We're the first ECB on this probe.
9580 */
9581 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9582
9583 if (ecb->dte_predicate != NULL)
9584 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9585
9586 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9587 probe->dtpr_id, probe->dtpr_arg));
9588 } else {
9589 /*
9590 * This probe is already active. Swing the last pointer to
9591 * point to the new ECB, and issue a dtrace_sync() to assure
9592 * that all CPUs have seen the change.
9593 */
9594 ASSERT(probe->dtpr_ecb_last != NULL);
9595 probe->dtpr_ecb_last->dte_next = ecb;
9596 probe->dtpr_ecb_last = ecb;
9597 probe->dtpr_predcache = 0;
9598
9599 dtrace_sync();
9600 return (0);
9601 }
9602}
9603
9604static void
9605dtrace_ecb_resize(dtrace_ecb_t *ecb)
9606{
9607 uint32_t maxalign = sizeof (dtrace_epid_t);
9608 uint32_t align = sizeof (uint8_t), offs, diff;
9609 dtrace_action_t *act;
9610 int wastuple = 0;
9611 uint32_t aggbase = UINT32_MAX;
9612 dtrace_state_t *state = ecb->dte_state;
9613
9614 /*
9615 * If we record anything, we always record the epid. (And we always
9616 * record it first.)
9617 */
9618 offs = sizeof (dtrace_epid_t);
9619 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9620
9621 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9622 dtrace_recdesc_t *rec = &act->dta_rec;
9623
9624 if ((align = rec->dtrd_alignment) > maxalign)
9625 maxalign = align;
9626
9627 if (!wastuple && act->dta_intuple) {
9628 /*
9629 * This is the first record in a tuple. Align the
9630 * offset to be at offset 4 in an 8-byte aligned
9631 * block.
9632 */
9633 diff = offs + sizeof (dtrace_aggid_t);
9634
9635 if ((diff = (diff & (sizeof (uint64_t) - 1))))
9636 offs += sizeof (uint64_t) - diff;
9637
9638 aggbase = offs - sizeof (dtrace_aggid_t);
9639 ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9640 }
9641
9642 /*LINTED*/
9643 if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9644 /*
9645 * The current offset is not properly aligned; align it.
9646 */
9647 offs += align - diff;
9648 }
9649
9650 rec->dtrd_offset = offs;
9651
9652 if (offs + rec->dtrd_size > ecb->dte_needed) {
9653 ecb->dte_needed = offs + rec->dtrd_size;
9654
9655 if (ecb->dte_needed > state->dts_needed)
9656 state->dts_needed = ecb->dte_needed;
9657 }
9658
9659 if (DTRACEACT_ISAGG(act->dta_kind)) {
9660 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9661 dtrace_action_t *first = agg->dtag_first, *prev;
9662
9663 ASSERT(rec->dtrd_size != 0 && first != NULL);
9664 ASSERT(wastuple);
9665 ASSERT(aggbase != UINT32_MAX);
9666
9667 agg->dtag_base = aggbase;
9668
9669 while ((prev = first->dta_prev) != NULL &&
9670 DTRACEACT_ISAGG(prev->dta_kind)) {
9671 agg = (dtrace_aggregation_t *)prev;
9672 first = agg->dtag_first;
9673 }
9674
9675 if (prev != NULL) {
9676 offs = prev->dta_rec.dtrd_offset +
9677 prev->dta_rec.dtrd_size;
9678 } else {
9679 offs = sizeof (dtrace_epid_t);
9680 }
9681 wastuple = 0;
9682 } else {
9683 if (!act->dta_intuple)
9684 ecb->dte_size = offs + rec->dtrd_size;
9685
9686 offs += rec->dtrd_size;
9687 }
9688
9689 wastuple = act->dta_intuple;
9690 }
9691
9692 if ((act = ecb->dte_action) != NULL &&
9693 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9694 ecb->dte_size == sizeof (dtrace_epid_t)) {
9695 /*
9696 * If the size is still sizeof (dtrace_epid_t), then all
9697 * actions store no data; set the size to 0.
9698 */
9699 ecb->dte_alignment = maxalign;
9700 ecb->dte_size = 0;
9701
9702 /*
9703 * If the needed space is still sizeof (dtrace_epid_t), then
9704 * all actions need no additional space; set the needed
9705 * size to 0.
9706 */
9707 if (ecb->dte_needed == sizeof (dtrace_epid_t))
9708 ecb->dte_needed = 0;
9709
9710 return;
9711 }
9712
9713 /*
9714 * Set our alignment, and make sure that the dte_size and dte_needed
9715 * are aligned to the size of an EPID.
9716 */
9717 ecb->dte_alignment = maxalign;
9718 ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9719 ~(sizeof (dtrace_epid_t) - 1);
9720 ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9721 ~(sizeof (dtrace_epid_t) - 1);
9722 ASSERT(ecb->dte_size <= ecb->dte_needed);
9723}
9724
9725static dtrace_action_t *
9726dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9727{
9728 dtrace_aggregation_t *agg;
9729 size_t size = sizeof (uint64_t);
9730 int ntuple = desc->dtad_ntuple;
9731 dtrace_action_t *act;
9732 dtrace_recdesc_t *frec;
9733 dtrace_aggid_t aggid;
9734 dtrace_state_t *state = ecb->dte_state;
9735
9736 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9737 agg->dtag_ecb = ecb;
9738
9739 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9740
9741 switch (desc->dtad_kind) {
9742 case DTRACEAGG_MIN:
9743 agg->dtag_initial = INT64_MAX;
9744 agg->dtag_aggregate = dtrace_aggregate_min;
9745 break;
9746
9747 case DTRACEAGG_MAX:
9748 agg->dtag_initial = (uint64_t)INT64_MIN;
9749 agg->dtag_aggregate = dtrace_aggregate_max;
9750 break;
9751
9752 case DTRACEAGG_COUNT:
9753 agg->dtag_aggregate = dtrace_aggregate_count;
9754 break;
9755
9756 case DTRACEAGG_QUANTIZE:
9757 agg->dtag_aggregate = dtrace_aggregate_quantize;
9758 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9759 sizeof (uint64_t);
9760 break;
9761
9762 case DTRACEAGG_LQUANTIZE: {
9763 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9764 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9765
9766 agg->dtag_initial = desc->dtad_arg;
9767 agg->dtag_aggregate = dtrace_aggregate_lquantize;
9768
9769 if (step == 0 || levels == 0)
9770 goto err;
9771
9772 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9773 break;
9774 }
9775
9776 case DTRACEAGG_AVG:
9777 agg->dtag_aggregate = dtrace_aggregate_avg;
9778 size = sizeof (uint64_t) * 2;
9779 break;
9780
9781 case DTRACEAGG_STDDEV:
9782 agg->dtag_aggregate = dtrace_aggregate_stddev;
9783 size = sizeof (uint64_t) * 4;
9784 break;
9785
9786 case DTRACEAGG_SUM:
9787 agg->dtag_aggregate = dtrace_aggregate_sum;
9788 break;
9789
9790 default:
9791 goto err;
9792 }
9793
9794 agg->dtag_action.dta_rec.dtrd_size = VBDTCAST(uint32_t)size;
9795
9796 if (ntuple == 0)
9797 goto err;
9798
9799 /*
9800 * We must make sure that we have enough actions for the n-tuple.
9801 */
9802 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9803 if (DTRACEACT_ISAGG(act->dta_kind))
9804 break;
9805
9806 if (--ntuple == 0) {
9807 /*
9808 * This is the action with which our n-tuple begins.
9809 */
9810 agg->dtag_first = act;
9811 goto success;
9812 }
9813 }
9814
9815 /*
9816 * This n-tuple is short by ntuple elements. Return failure.
9817 */
9818 ASSERT(ntuple != 0);
9819err:
9820 kmem_free(agg, sizeof (dtrace_aggregation_t));
9821 return (NULL);
9822
9823success:
9824 /*
9825 * If the last action in the tuple has a size of zero, it's actually
9826 * an expression argument for the aggregating action.
9827 */
9828 ASSERT(ecb->dte_action_last != NULL);
9829 act = ecb->dte_action_last;
9830
9831 if (act->dta_kind == DTRACEACT_DIFEXPR) {
9832 ASSERT(act->dta_difo != NULL);
9833
9834 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9835 agg->dtag_hasarg = 1;
9836 }
9837
9838 /*
9839 * We need to allocate an id for this aggregation.
9840 */
9841 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9842 VM_BESTFIT | VM_SLEEP);
9843
9844 if (VBDTCAST(int64_t)aggid - 1 >= state->dts_naggregations) {
9845 dtrace_aggregation_t **oaggs = state->dts_aggregations;
9846 dtrace_aggregation_t **aggs;
9847 int naggs = state->dts_naggregations << 1;
9848 int onaggs = state->dts_naggregations;
9849
9850 ASSERT(aggid == VBDTCAST(dtrace_aggid_t)state->dts_naggregations + 1);
9851
9852 if (naggs == 0) {
9853 ASSERT(oaggs == NULL);
9854 naggs = 1;
9855 }
9856
9857 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9858
9859 if (oaggs != NULL) {
9860 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9861 kmem_free(oaggs, onaggs * sizeof (*aggs));
9862 }
9863
9864 state->dts_aggregations = aggs;
9865 state->dts_naggregations = naggs;
9866 }
9867
9868 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9869 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9870
9871 frec = &agg->dtag_first->dta_rec;
9872 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9873 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9874
9875 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9876 ASSERT(!act->dta_intuple);
9877 act->dta_intuple = 1;
9878 }
9879
9880 return (&agg->dtag_action);
9881}
9882
9883static void
9884dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9885{
9886 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9887 dtrace_state_t *state = ecb->dte_state;
9888 dtrace_aggid_t aggid = agg->dtag_id;
9889
9890 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9891 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9892
9893 ASSERT(state->dts_aggregations[aggid - 1] == agg);
9894 state->dts_aggregations[aggid - 1] = NULL;
9895
9896 kmem_free(agg, sizeof (dtrace_aggregation_t));
9897}
9898
9899static int
9900dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9901{
9902 dtrace_action_t *action, *last;
9903 dtrace_difo_t *dp = desc->dtad_difo;
9904 uint32_t size = 0, align = sizeof (uint8_t), mask;
9905 uint16_t format = 0;
9906 dtrace_recdesc_t *rec;
9907 dtrace_state_t *state = ecb->dte_state;
9908 dtrace_optval_t *opt = state->dts_options, nframes VBDTUNASS(0), strsize;
9909 uint64_t arg = desc->dtad_arg;
9910
9911 ASSERT(MUTEX_HELD(&dtrace_lock));
9912 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9913
9914 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9915 /*
9916 * If this is an aggregating action, there must be neither
9917 * a speculate nor a commit on the action chain.
9918 */
9919 dtrace_action_t *act;
9920
9921 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9922 if (act->dta_kind == DTRACEACT_COMMIT)
9923 return (EINVAL);
9924
9925 if (act->dta_kind == DTRACEACT_SPECULATE)
9926 return (EINVAL);
9927 }
9928
9929 action = dtrace_ecb_aggregation_create(ecb, desc);
9930
9931 if (action == NULL)
9932 return (EINVAL);
9933 } else {
9934 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9935 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9936 dp != NULL && dp->dtdo_destructive)) {
9937 state->dts_destructive = 1;
9938 }
9939
9940 switch (desc->dtad_kind) {
9941 case DTRACEACT_PRINTF:
9942 case DTRACEACT_PRINTA:
9943 case DTRACEACT_SYSTEM:
9944 case DTRACEACT_FREOPEN:
9945 /*
9946 * We know that our arg is a string -- turn it into a
9947 * format.
9948 */
9949 if (arg == NULL) {
9950 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9951 format = 0;
9952 } else {
9953 ASSERT(arg != NULL);
9954 ASSERT(VBDT_IS_VALID_KRNL_ADDR(arg));
9955 format = dtrace_format_add(state,
9956 (char *)(uintptr_t)arg);
9957 }
9958
9959 /*FALLTHROUGH*/
9960 case DTRACEACT_LIBACT:
9961 case DTRACEACT_DIFEXPR:
9962 if (dp == NULL)
9963 return (EINVAL);
9964
9965 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9966 break;
9967
9968 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9969 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9970 return (EINVAL);
9971
9972 size = opt[DTRACEOPT_STRSIZE];
9973 }
9974
9975 break;
9976
9977 case DTRACEACT_STACK:
9978 if ((nframes = arg) == 0) {
9979 nframes = opt[DTRACEOPT_STACKFRAMES];
9980 ASSERT(nframes > 0);
9981 arg = nframes;
9982 }
9983
9984 size = VBDTCAST(uint32_t)(nframes * sizeof (pc_t));
9985 break;
9986
9987 case DTRACEACT_JSTACK:
9988 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9989 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9990
9991 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9992 nframes = opt[DTRACEOPT_JSTACKFRAMES];
9993
9994 arg = DTRACE_USTACK_ARG(nframes, strsize);
9995
9996 /*FALLTHROUGH*/
9997 case DTRACEACT_USTACK:
9998 if (desc->dtad_kind != DTRACEACT_JSTACK &&
9999 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10000 strsize = DTRACE_USTACK_STRSIZE(arg);
10001 nframes = opt[DTRACEOPT_USTACKFRAMES];
10002 ASSERT(nframes > 0);
10003 arg = DTRACE_USTACK_ARG(nframes, strsize);
10004 }
10005
10006 /*
10007 * Save a slot for the pid.
10008 */
10009 size = VBDTCAST(uint32_t)((nframes + 1) * sizeof (uint64_t));
10010 size += DTRACE_USTACK_STRSIZE(arg);
10011 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10012
10013 break;
10014
10015 case DTRACEACT_SYM:
10016 case DTRACEACT_MOD:
10017 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10018 sizeof (uint64_t)) ||
10019 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10020 return (EINVAL);
10021 break;
10022
10023 case DTRACEACT_USYM:
10024 case DTRACEACT_UMOD:
10025 case DTRACEACT_UADDR:
10026 if (dp == NULL ||
10027 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10028 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10029 return (EINVAL);
10030
10031 /*
10032 * We have a slot for the pid, plus a slot for the
10033 * argument. To keep things simple (aligned with
10034 * bitness-neutral sizing), we store each as a 64-bit
10035 * quantity.
10036 */
10037 size = 2 * sizeof (uint64_t);
10038 break;
10039
10040 case DTRACEACT_STOP:
10041 case DTRACEACT_BREAKPOINT:
10042 case DTRACEACT_PANIC:
10043 break;
10044
10045 case DTRACEACT_CHILL:
10046 case DTRACEACT_DISCARD:
10047 case DTRACEACT_RAISE:
10048 if (dp == NULL)
10049 return (EINVAL);
10050 break;
10051
10052 case DTRACEACT_EXIT:
10053 if (dp == NULL ||
10054 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10055 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10056 return (EINVAL);
10057 break;
10058
10059 case DTRACEACT_SPECULATE:
10060 if (ecb->dte_size > sizeof (dtrace_epid_t))
10061 return (EINVAL);
10062
10063 if (dp == NULL)
10064 return (EINVAL);
10065
10066 state->dts_speculates = 1;
10067 break;
10068
10069 case DTRACEACT_COMMIT: {
10070 dtrace_action_t *act = ecb->dte_action;
10071
10072 for (; act != NULL; act = act->dta_next) {
10073 if (act->dta_kind == DTRACEACT_COMMIT)
10074 return (EINVAL);
10075 }
10076
10077 if (dp == NULL)
10078 return (EINVAL);
10079 break;
10080 }
10081
10082 default:
10083 return (EINVAL);
10084 }
10085
10086 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10087 /*
10088 * If this is a data-storing action or a speculate,
10089 * we must be sure that there isn't a commit on the
10090 * action chain.
10091 */
10092 dtrace_action_t *act = ecb->dte_action;
10093
10094 for (; act != NULL; act = act->dta_next) {
10095 if (act->dta_kind == DTRACEACT_COMMIT)
10096 return (EINVAL);
10097 }
10098 }
10099
10100 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10101 action->dta_rec.dtrd_size = size;
10102 }
10103
10104 action->dta_refcnt = 1;
10105 rec = &action->dta_rec;
10106 size = rec->dtrd_size;
10107
10108 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10109 if (!(size & mask)) {
10110 align = mask + 1;
10111 break;
10112 }
10113 }
10114
10115 action->dta_kind = desc->dtad_kind;
10116
10117 if ((action->dta_difo = dp) != NULL)
10118 dtrace_difo_hold(dp);
10119
10120 rec->dtrd_action = action->dta_kind;
10121 rec->dtrd_arg = arg;
10122 rec->dtrd_uarg = desc->dtad_uarg;
10123 rec->dtrd_alignment = (uint16_t)align;
10124 rec->dtrd_format = format;
10125
10126 if ((last = ecb->dte_action_last) != NULL) {
10127 ASSERT(ecb->dte_action != NULL);
10128 action->dta_prev = last;
10129 last->dta_next = action;
10130 } else {
10131 ASSERT(ecb->dte_action == NULL);
10132 ecb->dte_action = action;
10133 }
10134
10135 ecb->dte_action_last = action;
10136
10137 return (0);
10138}
10139
10140static void
10141dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10142{
10143 dtrace_action_t *act = ecb->dte_action, *next;
10144 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10145 dtrace_difo_t *dp;
10146 uint16_t format;
10147
10148 if (act != NULL && act->dta_refcnt > 1) {
10149 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10150 act->dta_refcnt--;
10151 } else {
10152 for (; act != NULL; act = next) {
10153 next = act->dta_next;
10154 ASSERT(next != NULL || act == ecb->dte_action_last);
10155 ASSERT(act->dta_refcnt == 1);
10156
10157 if ((format = act->dta_rec.dtrd_format) != 0)
10158 dtrace_format_remove(ecb->dte_state, format);
10159
10160 if ((dp = act->dta_difo) != NULL)
10161 dtrace_difo_release(dp, vstate);
10162
10163 if (DTRACEACT_ISAGG(act->dta_kind)) {
10164 dtrace_ecb_aggregation_destroy(ecb, act);
10165 } else {
10166 kmem_free(act, sizeof (dtrace_action_t));
10167 }
10168 }
10169 }
10170
10171 ecb->dte_action = NULL;
10172 ecb->dte_action_last = NULL;
10173 ecb->dte_size = sizeof (dtrace_epid_t);
10174}
10175
10176static void
10177dtrace_ecb_disable(dtrace_ecb_t *ecb)
10178{
10179 /*
10180 * We disable the ECB by removing it from its probe.
10181 */
10182 dtrace_ecb_t *pecb, *prev = NULL;
10183 dtrace_probe_t *probe = ecb->dte_probe;
10184
10185 ASSERT(MUTEX_HELD(&dtrace_lock));
10186
10187 if (probe == NULL) {
10188 /*
10189 * This is the NULL probe; there is nothing to disable.
10190 */
10191 return;
10192 }
10193
10194 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10195 if (pecb == ecb)
10196 break;
10197 prev = pecb;
10198 }
10199
10200 ASSERT(pecb != NULL);
10201
10202 if (prev == NULL) {
10203 probe->dtpr_ecb = ecb->dte_next;
10204 } else {
10205 prev->dte_next = ecb->dte_next;
10206 }
10207
10208 if (ecb == probe->dtpr_ecb_last) {
10209 ASSERT(ecb->dte_next == NULL);
10210 probe->dtpr_ecb_last = prev;
10211 }
10212
10213 /*
10214 * The ECB has been disconnected from the probe; now sync to assure
10215 * that all CPUs have seen the change before returning.
10216 */
10217 dtrace_sync();
10218
10219 if (probe->dtpr_ecb == NULL) {
10220 /*
10221 * That was the last ECB on the probe; clear the predicate
10222 * cache ID for the probe, disable it and sync one more time
10223 * to assure that we'll never hit it again.
10224 */
10225 dtrace_provider_t *prov = probe->dtpr_provider;
10226
10227 ASSERT(ecb->dte_next == NULL);
10228 ASSERT(probe->dtpr_ecb_last == NULL);
10229 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10230 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10231 probe->dtpr_id, probe->dtpr_arg);
10232 dtrace_sync();
10233 } else {
10234 /*
10235 * There is at least one ECB remaining on the probe. If there
10236 * is _exactly_ one, set the probe's predicate cache ID to be
10237 * the predicate cache ID of the remaining ECB.
10238 */
10239 ASSERT(probe->dtpr_ecb_last != NULL);
10240 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10241
10242 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10243 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10244
10245 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10246
10247 if (p != NULL)
10248 probe->dtpr_predcache = p->dtp_cacheid;
10249 }
10250
10251 ecb->dte_next = NULL;
10252 }
10253}
10254
10255static void
10256dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10257{
10258 dtrace_state_t *state = ecb->dte_state;
10259 dtrace_vstate_t *vstate = &state->dts_vstate;
10260 dtrace_predicate_t *pred;
10261 dtrace_epid_t epid = ecb->dte_epid;
10262
10263 ASSERT(MUTEX_HELD(&dtrace_lock));
10264 ASSERT(ecb->dte_next == NULL);
10265 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10266
10267 if ((pred = ecb->dte_predicate) != NULL)
10268 dtrace_predicate_release(pred, vstate);
10269
10270 dtrace_ecb_action_remove(ecb);
10271
10272 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10273 state->dts_ecbs[epid - 1] = NULL;
10274
10275 kmem_free(ecb, sizeof (dtrace_ecb_t));
10276}
10277
10278static dtrace_ecb_t *
10279dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10280 dtrace_enabling_t *enab)
10281{
10282 dtrace_ecb_t *ecb;
10283 dtrace_predicate_t *pred;
10284 dtrace_actdesc_t *act;
10285 dtrace_provider_t *prov;
10286 dtrace_ecbdesc_t *desc = enab->dten_current;
10287
10288 ASSERT(MUTEX_HELD(&dtrace_lock));
10289 ASSERT(state != NULL);
10290
10291 ecb = dtrace_ecb_add(state, probe);
10292 ecb->dte_uarg = desc->dted_uarg;
10293
10294 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10295 dtrace_predicate_hold(pred);
10296 ecb->dte_predicate = pred;
10297 }
10298
10299 if (probe != NULL) {
10300 /*
10301 * If the provider shows more leg than the consumer is old
10302 * enough to see, we need to enable the appropriate implicit
10303 * predicate bits to prevent the ecb from activating at
10304 * revealing times.
10305 *
10306 * Providers specifying DTRACE_PRIV_USER at register time
10307 * are stating that they need the /proc-style privilege
10308 * model to be enforced, and this is what DTRACE_COND_OWNER
10309 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10310 */
10311 prov = probe->dtpr_provider;
10312 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10313 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10314 ecb->dte_cond |= DTRACE_COND_OWNER;
10315
10316 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10317 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10318 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10319
10320 /*
10321 * If the provider shows us kernel innards and the user
10322 * is lacking sufficient privilege, enable the
10323 * DTRACE_COND_USERMODE implicit predicate.
10324 */
10325 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10326 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10327 ecb->dte_cond |= DTRACE_COND_USERMODE;
10328 }
10329
10330 if (dtrace_ecb_create_cache != NULL) {
10331 /*
10332 * If we have a cached ecb, we'll use its action list instead
10333 * of creating our own (saving both time and space).
10334 */
10335 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10336 dtrace_action_t *act2 = cached->dte_action;
10337
10338 if (act2 != NULL) {
10339 ASSERT(act2->dta_refcnt > 0);
10340 act2->dta_refcnt++;
10341 ecb->dte_action = act2;
10342 ecb->dte_action_last = cached->dte_action_last;
10343 ecb->dte_needed = cached->dte_needed;
10344 ecb->dte_size = cached->dte_size;
10345 ecb->dte_alignment = cached->dte_alignment;
10346 }
10347
10348 return (ecb);
10349 }
10350
10351 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10352 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10353 dtrace_ecb_destroy(ecb);
10354 return (NULL);
10355 }
10356 }
10357
10358 dtrace_ecb_resize(ecb);
10359
10360 return (dtrace_ecb_create_cache = ecb);
10361}
10362
10363static int
10364dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10365{
10366 dtrace_ecb_t *ecb;
10367 dtrace_enabling_t *enab = arg;
10368 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10369
10370 ASSERT(state != NULL);
10371
10372 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10373 /*
10374 * This probe was created in a generation for which this
10375 * enabling has previously created ECBs; we don't want to
10376 * enable it again, so just kick out.
10377 */
10378 return (DTRACE_MATCH_NEXT);
10379 }
10380
10381 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10382 return (DTRACE_MATCH_DONE);
10383
10384 if (dtrace_ecb_enable(ecb) < 0)
10385 return (DTRACE_MATCH_FAIL);
10386
10387 return (DTRACE_MATCH_NEXT);
10388}
10389
10390static dtrace_ecb_t *
10391dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10392{
10393 dtrace_ecb_t *ecb; NOREF(ecb);
10394
10395 ASSERT(MUTEX_HELD(&dtrace_lock));
10396
10397 if (id == 0 || VBDTCAST(int64_t)id > state->dts_necbs)
10398 return (NULL);
10399
10400 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10401 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10402
10403 return (state->dts_ecbs[id - 1]);
10404}
10405
10406static dtrace_aggregation_t *
10407dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10408{
10409 dtrace_aggregation_t *agg; NOREF(agg);
10410
10411 ASSERT(MUTEX_HELD(&dtrace_lock));
10412
10413 if (id == 0 || VBDTCAST(int64_t)id > state->dts_naggregations)
10414 return (NULL);
10415
10416 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10417 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10418 agg->dtag_id == id);
10419
10420 return (state->dts_aggregations[id - 1]);
10421}
10422
10423/*
10424 * DTrace Buffer Functions
10425 *
10426 * The following functions manipulate DTrace buffers. Most of these functions
10427 * are called in the context of establishing or processing consumer state;
10428 * exceptions are explicitly noted.
10429 */
10430
10431/*
10432 * Note: called from cross call context. This function switches the two
10433 * buffers on a given CPU. The atomicity of this operation is assured by
10434 * disabling interrupts while the actual switch takes place; the disabling of
10435 * interrupts serializes the execution with any execution of dtrace_probe() on
10436 * the same CPU.
10437 */
10438static void
10439dtrace_buffer_switch(dtrace_buffer_t *buf)
10440{
10441 caddr_t tomax = buf->dtb_tomax;
10442 caddr_t xamot = buf->dtb_xamot;
10443 dtrace_icookie_t cookie;
10444
10445 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10446 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10447
10448 cookie = dtrace_interrupt_disable();
10449 buf->dtb_tomax = xamot;
10450 buf->dtb_xamot = tomax;
10451 buf->dtb_xamot_drops = buf->dtb_drops;
10452 buf->dtb_xamot_offset = buf->dtb_offset;
10453 buf->dtb_xamot_errors = buf->dtb_errors;
10454 buf->dtb_xamot_flags = buf->dtb_flags;
10455 buf->dtb_offset = 0;
10456 buf->dtb_drops = 0;
10457 buf->dtb_errors = 0;
10458 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10459 dtrace_interrupt_enable(cookie);
10460}
10461
10462#ifdef VBOX
10463static DECLCALLBACK(void) dtrace_buffer_switch_wrapper(RTCPUID idCpu, void *pvUser1, void *pvUser2)
10464{
10465 dtrace_buffer_switch((dtrace_buffer_t *)pvUser1);
10466 NOREF(pvUser2); NOREF(idCpu);
10467}
10468#endif
10469
10470/*
10471 * Note: called from cross call context. This function activates a buffer
10472 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10473 * is guaranteed by the disabling of interrupts.
10474 */
10475static void
10476dtrace_buffer_activate(dtrace_state_t *state)
10477{
10478 dtrace_buffer_t *buf;
10479 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10480
10481 buf = &state->dts_buffer[VBDT_GET_CPUID()];
10482
10483 if (buf->dtb_tomax != NULL) {
10484 /*
10485 * We might like to assert that the buffer is marked inactive,
10486 * but this isn't necessarily true: the buffer for the CPU
10487 * that processes the BEGIN probe has its buffer activated
10488 * manually. In this case, we take the (harmless) action
10489 * re-clearing the bit INACTIVE bit.
10490 */
10491 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10492 }
10493
10494 dtrace_interrupt_enable(cookie);
10495}
10496
10497#ifdef VBOX
10498static DECLCALLBACK(void) dtrace_buffer_activate_wrapper(RTCPUID idCpu, void *pvUser1, void *pvUser2)
10499{
10500 dtrace_buffer_activate((dtrace_state_t *)pvUser1);
10501 NOREF(pvUser2); NOREF(idCpu);
10502}
10503#endif
10504
10505static int
10506dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10507 processorid_t cpu)
10508{
10509#ifndef VBOX
10510 cpu_t *cp;
10511#else
10512 RTCPUSET CpuSet;
10513 unsigned iCpu;
10514#endif
10515 dtrace_buffer_t *buf;
10516
10517 ASSERT(MUTEX_HELD(&cpu_lock));
10518 ASSERT(MUTEX_HELD(&dtrace_lock));
10519
10520 if (VBDTCAST(int64_t)size > dtrace_nonroot_maxsize
10521#ifndef VBOX
10522 && !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE)
10523#endif
10524 )
10525 return (EFBIG);
10526
10527#ifndef VBOX
10528 cp = cpu_list;
10529#else
10530 RTMpGetSet(&CpuSet);
10531#endif
10532
10533#ifndef VBOX
10534 do {
10535 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10536 continue;
10537
10538 buf = &bufs[cp->cpu_id];
10539#else
10540 for (iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++) {
10541 if ( !RTCpuSetIsMember(&CpuSet, iCpu)
10542 || (cpu != (processorid_t)DTRACE_CPUALL && cpu != iCpu))
10543 continue;
10544
10545 buf = &bufs[iCpu];
10546#endif
10547
10548 /*
10549 * If there is already a buffer allocated for this CPU, it
10550 * is only possible that this is a DR event. In this case,
10551 * the buffer size must match our specified size.
10552 */
10553 if (buf->dtb_tomax != NULL) {
10554 ASSERT(buf->dtb_size == size);
10555 continue;
10556 }
10557
10558 ASSERT(buf->dtb_xamot == NULL);
10559
10560 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10561 goto err;
10562
10563 buf->dtb_size = size;
10564 buf->dtb_flags = flags;
10565 buf->dtb_offset = 0;
10566 buf->dtb_drops = 0;
10567
10568 if (flags & DTRACEBUF_NOSWITCH)
10569 continue;
10570
10571 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10572 goto err;
10573#ifndef VBOX
10574 } while ((cp = cp->cpu_next) != cpu_list);
10575#else
10576 }
10577#endif
10578
10579 return (0);
10580
10581err:
10582#ifndef VBOX
10583 cp = cpu_list;
10584
10585 do {
10586 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10587 continue;
10588
10589 buf = &bufs[cp->cpu_id];
10590#else
10591 for (iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++) {
10592 if ( !RTCpuSetIsMember(&CpuSet, iCpu)
10593 || (cpu != (processorid_t)DTRACE_CPUALL && cpu != iCpu))
10594 continue;
10595
10596 buf = &bufs[iCpu];
10597#endif
10598
10599 if (buf->dtb_xamot != NULL) {
10600 ASSERT(buf->dtb_tomax != NULL);
10601 ASSERT(buf->dtb_size == size);
10602 kmem_free(buf->dtb_xamot, size);
10603 }
10604
10605 if (buf->dtb_tomax != NULL) {
10606 ASSERT(buf->dtb_size == size);
10607 kmem_free(buf->dtb_tomax, size);
10608 }
10609
10610 buf->dtb_tomax = NULL;
10611 buf->dtb_xamot = NULL;
10612 buf->dtb_size = 0;
10613#ifndef VBOX
10614 } while ((cp = cp->cpu_next) != cpu_list);
10615#else
10616 }
10617#endif
10618
10619 return (ENOMEM);
10620}
10621
10622/*
10623 * Note: called from probe context. This function just increments the drop
10624 * count on a buffer. It has been made a function to allow for the
10625 * possibility of understanding the source of mysterious drop counts. (A
10626 * problem for which one may be particularly disappointed that DTrace cannot
10627 * be used to understand DTrace.)
10628 */
10629static void
10630dtrace_buffer_drop(dtrace_buffer_t *buf)
10631{
10632 buf->dtb_drops++;
10633}
10634
10635/*
10636 * Note: called from probe context. This function is called to reserve space
10637 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
10638 * mstate. Returns the new offset in the buffer, or a negative value if an
10639 * error has occurred.
10640 */
10641static intptr_t
10642dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10643 dtrace_state_t *state, dtrace_mstate_t *mstate)
10644{
10645 intptr_t offs = buf->dtb_offset, soffs;
10646 intptr_t woffs;
10647 caddr_t tomax;
10648 size_t total;
10649
10650 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10651 return (-1);
10652
10653 if ((tomax = buf->dtb_tomax) == NULL) {
10654 dtrace_buffer_drop(buf);
10655 return (-1);
10656 }
10657
10658 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10659 while (offs & (align - 1)) {
10660 /*
10661 * Assert that our alignment is off by a number which
10662 * is itself sizeof (uint32_t) aligned.
10663 */
10664 ASSERT(!((align - (offs & (align - 1))) &
10665 (sizeof (uint32_t) - 1)));
10666 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10667 offs += sizeof (uint32_t);
10668 }
10669
10670 if (VBDTCAST(uintptr_t)(soffs = offs + needed) > buf->dtb_size) {
10671 dtrace_buffer_drop(buf);
10672 return (-1);
10673 }
10674
10675 if (mstate == NULL)
10676 return (offs);
10677
10678 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10679 mstate->dtms_scratch_size = buf->dtb_size - soffs;
10680 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10681
10682 return (offs);
10683 }
10684
10685 if (buf->dtb_flags & DTRACEBUF_FILL) {
10686 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10687 (buf->dtb_flags & DTRACEBUF_FULL))
10688 return (-1);
10689 goto out;
10690 }
10691
10692 total = needed + (offs & (align - 1));
10693
10694 /*
10695 * For a ring buffer, life is quite a bit more complicated. Before
10696 * we can store any padding, we need to adjust our wrapping offset.
10697 * (If we've never before wrapped or we're not about to, no adjustment
10698 * is required.)
10699 */
10700 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10701 offs + total > buf->dtb_size) {
10702 woffs = buf->dtb_xamot_offset;
10703
10704 if (offs + total > buf->dtb_size) {
10705 /*
10706 * We can't fit in the end of the buffer. First, a
10707 * sanity check that we can fit in the buffer at all.
10708 */
10709 if (total > buf->dtb_size) {
10710 dtrace_buffer_drop(buf);
10711 return (-1);
10712 }
10713
10714 /*
10715 * We're going to be storing at the top of the buffer,
10716 * so now we need to deal with the wrapped offset. We
10717 * only reset our wrapped offset to 0 if it is
10718 * currently greater than the current offset. If it
10719 * is less than the current offset, it is because a
10720 * previous allocation induced a wrap -- but the
10721 * allocation didn't subsequently take the space due
10722 * to an error or false predicate evaluation. In this
10723 * case, we'll just leave the wrapped offset alone: if
10724 * the wrapped offset hasn't been advanced far enough
10725 * for this allocation, it will be adjusted in the
10726 * lower loop.
10727 */
10728 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10729 if (woffs >= offs)
10730 woffs = 0;
10731 } else {
10732 woffs = 0;
10733 }
10734
10735 /*
10736 * Now we know that we're going to be storing to the
10737 * top of the buffer and that there is room for us
10738 * there. We need to clear the buffer from the current
10739 * offset to the end (there may be old gunk there).
10740 */
10741 while (VBDTCAST(uintptr_t)offs < buf->dtb_size)
10742 tomax[offs++] = 0;
10743
10744 /*
10745 * We need to set our offset to zero. And because we
10746 * are wrapping, we need to set the bit indicating as
10747 * much. We can also adjust our needed space back
10748 * down to the space required by the ECB -- we know
10749 * that the top of the buffer is aligned.
10750 */
10751 offs = 0;
10752 total = needed;
10753 buf->dtb_flags |= DTRACEBUF_WRAPPED;
10754 } else {
10755 /*
10756 * There is room for us in the buffer, so we simply
10757 * need to check the wrapped offset.
10758 */
10759 if (woffs < offs) {
10760 /*
10761 * The wrapped offset is less than the offset.
10762 * This can happen if we allocated buffer space
10763 * that induced a wrap, but then we didn't
10764 * subsequently take the space due to an error
10765 * or false predicate evaluation. This is
10766 * okay; we know that _this_ allocation isn't
10767 * going to induce a wrap. We still can't
10768 * reset the wrapped offset to be zero,
10769 * however: the space may have been trashed in
10770 * the previous failed probe attempt. But at
10771 * least the wrapped offset doesn't need to
10772 * be adjusted at all...
10773 */
10774 goto out;
10775 }
10776 }
10777
10778 while (VBDTCAST(uintptr_t)offs + total > VBDTCAST(uintptr_t)woffs) {
10779 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10780 size_t size;
10781
10782 if (epid == DTRACE_EPIDNONE) {
10783 size = sizeof (uint32_t);
10784 } else {
10785 ASSERT(VBDTCAST(int64_t)epid <= state->dts_necbs);
10786 ASSERT(state->dts_ecbs[epid - 1] != NULL);
10787
10788 size = state->dts_ecbs[epid - 1]->dte_size;
10789 }
10790
10791 ASSERT(woffs + size <= buf->dtb_size);
10792 ASSERT(size != 0);
10793
10794 if (woffs + size == buf->dtb_size) {
10795 /*
10796 * We've reached the end of the buffer; we want
10797 * to set the wrapped offset to 0 and break
10798 * out. However, if the offs is 0, then we're
10799 * in a strange edge-condition: the amount of
10800 * space that we want to reserve plus the size
10801 * of the record that we're overwriting is
10802 * greater than the size of the buffer. This
10803 * is problematic because if we reserve the
10804 * space but subsequently don't consume it (due
10805 * to a failed predicate or error) the wrapped
10806 * offset will be 0 -- yet the EPID at offset 0
10807 * will not be committed. This situation is
10808 * relatively easy to deal with: if we're in
10809 * this case, the buffer is indistinguishable
10810 * from one that hasn't wrapped; we need only
10811 * finish the job by clearing the wrapped bit,
10812 * explicitly setting the offset to be 0, and
10813 * zero'ing out the old data in the buffer.
10814 */
10815 if (offs == 0) {
10816 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10817 buf->dtb_offset = 0;
10818 woffs = total;
10819
10820 while (VBDTCAST(uintptr_t)woffs < buf->dtb_size)
10821 tomax[woffs++] = 0;
10822 }
10823
10824 woffs = 0;
10825 break;
10826 }
10827
10828 woffs += size;
10829 }
10830
10831 /*
10832 * We have a wrapped offset. It may be that the wrapped offset
10833 * has become zero -- that's okay.
10834 */
10835 buf->dtb_xamot_offset = woffs;
10836 }
10837
10838out:
10839 /*
10840 * Now we can plow the buffer with any necessary padding.
10841 */
10842 while (offs & (align - 1)) {
10843 /*
10844 * Assert that our alignment is off by a number which
10845 * is itself sizeof (uint32_t) aligned.
10846 */
10847 ASSERT(!((align - (offs & (align - 1))) &
10848 (sizeof (uint32_t) - 1)));
10849 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10850 offs += sizeof (uint32_t);
10851 }
10852
10853 if (buf->dtb_flags & DTRACEBUF_FILL) {
10854 if (offs + needed > buf->dtb_size - state->dts_reserve) {
10855 buf->dtb_flags |= DTRACEBUF_FULL;
10856 return (-1);
10857 }
10858 }
10859
10860 if (mstate == NULL)
10861 return (offs);
10862
10863 /*
10864 * For ring buffers and fill buffers, the scratch space is always
10865 * the inactive buffer.
10866 */
10867 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10868 mstate->dtms_scratch_size = buf->dtb_size;
10869 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10870
10871 return (offs);
10872}
10873
10874static void
10875dtrace_buffer_polish(dtrace_buffer_t *buf)
10876{
10877 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10878 ASSERT(MUTEX_HELD(&dtrace_lock));
10879
10880 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10881 return;
10882
10883 /*
10884 * We need to polish the ring buffer. There are three cases:
10885 *
10886 * - The first (and presumably most common) is that there is no gap
10887 * between the buffer offset and the wrapped offset. In this case,
10888 * there is nothing in the buffer that isn't valid data; we can
10889 * mark the buffer as polished and return.
10890 *
10891 * - The second (less common than the first but still more common
10892 * than the third) is that there is a gap between the buffer offset
10893 * and the wrapped offset, and the wrapped offset is larger than the
10894 * buffer offset. This can happen because of an alignment issue, or
10895 * can happen because of a call to dtrace_buffer_reserve() that
10896 * didn't subsequently consume the buffer space. In this case,
10897 * we need to zero the data from the buffer offset to the wrapped
10898 * offset.
10899 *
10900 * - The third (and least common) is that there is a gap between the
10901 * buffer offset and the wrapped offset, but the wrapped offset is
10902 * _less_ than the buffer offset. This can only happen because a
10903 * call to dtrace_buffer_reserve() induced a wrap, but the space
10904 * was not subsequently consumed. In this case, we need to zero the
10905 * space from the offset to the end of the buffer _and_ from the
10906 * top of the buffer to the wrapped offset.
10907 */
10908 if (buf->dtb_offset < buf->dtb_xamot_offset) {
10909 bzero(buf->dtb_tomax + buf->dtb_offset,
10910 buf->dtb_xamot_offset - buf->dtb_offset);
10911 }
10912
10913 if (buf->dtb_offset > buf->dtb_xamot_offset) {
10914 bzero(buf->dtb_tomax + buf->dtb_offset,
10915 buf->dtb_size - buf->dtb_offset);
10916 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10917 }
10918}
10919
10920static void
10921dtrace_buffer_free(dtrace_buffer_t *bufs)
10922{
10923 int i;
10924
10925 for (i = 0; i < NCPU; i++) {
10926 dtrace_buffer_t *buf = &bufs[i];
10927
10928 if (buf->dtb_tomax == NULL) {
10929 ASSERT(buf->dtb_xamot == NULL);
10930 ASSERT(buf->dtb_size == 0);
10931 continue;
10932 }
10933
10934 if (buf->dtb_xamot != NULL) {
10935 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10936 kmem_free(buf->dtb_xamot, buf->dtb_size);
10937 }
10938
10939 kmem_free(buf->dtb_tomax, buf->dtb_size);
10940 buf->dtb_size = 0;
10941 buf->dtb_tomax = NULL;
10942 buf->dtb_xamot = NULL;
10943 }
10944}
10945
10946/*
10947 * DTrace Enabling Functions
10948 */
10949static dtrace_enabling_t *
10950dtrace_enabling_create(dtrace_vstate_t *vstate)
10951{
10952 dtrace_enabling_t *enab;
10953
10954 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10955 enab->dten_vstate = vstate;
10956
10957 return (enab);
10958}
10959
10960static void
10961dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10962{
10963 dtrace_ecbdesc_t **ndesc;
10964 size_t osize, nsize;
10965
10966 /*
10967 * We can't add to enablings after we've enabled them, or after we've
10968 * retained them.
10969 */
10970 ASSERT(enab->dten_probegen == 0);
10971 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10972
10973 if (enab->dten_ndesc < enab->dten_maxdesc) {
10974 enab->dten_desc[enab->dten_ndesc++] = ecb;
10975 return;
10976 }
10977
10978 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10979
10980 if (enab->dten_maxdesc == 0) {
10981 enab->dten_maxdesc = 1;
10982 } else {
10983 enab->dten_maxdesc <<= 1;
10984 }
10985
10986 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10987
10988 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10989 ndesc = kmem_zalloc(nsize, KM_SLEEP);
10990 bcopy(enab->dten_desc, ndesc, osize);
10991 kmem_free(enab->dten_desc, osize);
10992
10993 enab->dten_desc = ndesc;
10994 enab->dten_desc[enab->dten_ndesc++] = ecb;
10995}
10996
10997static void
10998dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10999 dtrace_probedesc_t *pd)
11000{
11001 dtrace_ecbdesc_t *new;
11002 dtrace_predicate_t *pred;
11003 dtrace_actdesc_t *act;
11004
11005 /*
11006 * We're going to create a new ECB description that matches the
11007 * specified ECB in every way, but has the specified probe description.
11008 */
11009 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11010
11011 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11012 dtrace_predicate_hold(pred);
11013
11014 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11015 dtrace_actdesc_hold(act);
11016
11017 new->dted_action = ecb->dted_action;
11018 new->dted_pred = ecb->dted_pred;
11019 new->dted_probe = *pd;
11020 new->dted_uarg = ecb->dted_uarg;
11021
11022 dtrace_enabling_add(enab, new);
11023}
11024
11025static void
11026dtrace_enabling_dump(dtrace_enabling_t *enab)
11027{
11028 int i;
11029
11030 for (i = 0; i < enab->dten_ndesc; i++) {
11031 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11032
11033 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11034 desc->dtpd_provider, desc->dtpd_mod,
11035 desc->dtpd_func, desc->dtpd_name);
11036 }
11037}
11038
11039static void
11040dtrace_enabling_destroy(dtrace_enabling_t *enab)
11041{
11042 int i;
11043 dtrace_ecbdesc_t *ep;
11044 dtrace_vstate_t *vstate = enab->dten_vstate;
11045
11046 ASSERT(MUTEX_HELD(&dtrace_lock));
11047
11048 for (i = 0; i < enab->dten_ndesc; i++) {
11049 dtrace_actdesc_t *act, *next;
11050 dtrace_predicate_t *pred;
11051
11052 ep = enab->dten_desc[i];
11053
11054 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11055 dtrace_predicate_release(pred, vstate);
11056
11057 for (act = ep->dted_action; act != NULL; act = next) {
11058 next = act->dtad_next;
11059 dtrace_actdesc_release(act, vstate);
11060 }
11061
11062 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11063 }
11064
11065 kmem_free(enab->dten_desc,
11066 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11067
11068 /*
11069 * If this was a retained enabling, decrement the dts_nretained count
11070 * and take it off of the dtrace_retained list.
11071 */
11072 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11073 dtrace_retained == enab) {
11074 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11075 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11076 enab->dten_vstate->dtvs_state->dts_nretained--;
11077 dtrace_retained_gen++;
11078 }
11079
11080 if (enab->dten_prev == NULL) {
11081 if (dtrace_retained == enab) {
11082 dtrace_retained = enab->dten_next;
11083
11084 if (dtrace_retained != NULL)
11085 dtrace_retained->dten_prev = NULL;
11086 }
11087 } else {
11088 ASSERT(enab != dtrace_retained);
11089 ASSERT(dtrace_retained != NULL);
11090 enab->dten_prev->dten_next = enab->dten_next;
11091 }
11092
11093 if (enab->dten_next != NULL) {
11094 ASSERT(dtrace_retained != NULL);
11095 enab->dten_next->dten_prev = enab->dten_prev;
11096 }
11097
11098 kmem_free(enab, sizeof (dtrace_enabling_t));
11099}
11100
11101static int
11102dtrace_enabling_retain(dtrace_enabling_t *enab)
11103{
11104 dtrace_state_t *state;
11105
11106 ASSERT(MUTEX_HELD(&dtrace_lock));
11107 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11108 ASSERT(enab->dten_vstate != NULL);
11109
11110 state = enab->dten_vstate->dtvs_state;
11111 ASSERT(state != NULL);
11112
11113 /*
11114 * We only allow each state to retain dtrace_retain_max enablings.
11115 */
11116 if (state->dts_nretained >= dtrace_retain_max)
11117 return (ENOSPC);
11118
11119 state->dts_nretained++;
11120 dtrace_retained_gen++;
11121
11122 if (dtrace_retained == NULL) {
11123 dtrace_retained = enab;
11124 return (0);
11125 }
11126
11127 enab->dten_next = dtrace_retained;
11128 dtrace_retained->dten_prev = enab;
11129 dtrace_retained = enab;
11130
11131 return (0);
11132}
11133
11134static int
11135dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11136 dtrace_probedesc_t *create)
11137{
11138 dtrace_enabling_t *new, *enab;
11139 int found = 0, err = ENOENT;
11140
11141 ASSERT(MUTEX_HELD(&dtrace_lock));
11142 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11143 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11144 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11145 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11146
11147 new = dtrace_enabling_create(&state->dts_vstate);
11148
11149 /*
11150 * Iterate over all retained enablings, looking for enablings that
11151 * match the specified state.
11152 */
11153 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11154 int i;
11155
11156 /*
11157 * dtvs_state can only be NULL for helper enablings -- and
11158 * helper enablings can't be retained.
11159 */
11160 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11161
11162 if (enab->dten_vstate->dtvs_state != state)
11163 continue;
11164
11165 /*
11166 * Now iterate over each probe description; we're looking for
11167 * an exact match to the specified probe description.
11168 */
11169 for (i = 0; i < enab->dten_ndesc; i++) {
11170 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11171 dtrace_probedesc_t *pd = &ep->dted_probe;
11172
11173 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11174 continue;
11175
11176 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11177 continue;
11178
11179 if (strcmp(pd->dtpd_func, match->dtpd_func))
11180 continue;
11181
11182 if (strcmp(pd->dtpd_name, match->dtpd_name))
11183 continue;
11184
11185 /*
11186 * We have a winning probe! Add it to our growing
11187 * enabling.
11188 */
11189 found = 1;
11190 dtrace_enabling_addlike(new, ep, create);
11191 }
11192 }
11193
11194 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11195 dtrace_enabling_destroy(new);
11196 return (err);
11197 }
11198
11199 return (0);
11200}
11201
11202static void
11203dtrace_enabling_retract(dtrace_state_t *state)
11204{
11205 dtrace_enabling_t *enab, *next;
11206
11207 ASSERT(MUTEX_HELD(&dtrace_lock));
11208
11209 /*
11210 * Iterate over all retained enablings, destroy the enablings retained
11211 * for the specified state.
11212 */
11213 for (enab = dtrace_retained; enab != NULL; enab = next) {
11214 next = enab->dten_next;
11215
11216 /*
11217 * dtvs_state can only be NULL for helper enablings -- and
11218 * helper enablings can't be retained.
11219 */
11220 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11221
11222 if (enab->dten_vstate->dtvs_state == state) {
11223 ASSERT(state->dts_nretained > 0);
11224 dtrace_enabling_destroy(enab);
11225 }
11226 }
11227
11228 ASSERT(state->dts_nretained == 0);
11229}
11230
11231static int
11232dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11233{
11234 int i = 0;
11235 int total_matched = 0, matched = 0;
11236
11237 ASSERT(MUTEX_HELD(&cpu_lock));
11238 ASSERT(MUTEX_HELD(&dtrace_lock));
11239
11240 for (i = 0; i < enab->dten_ndesc; i++) {
11241 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11242
11243 enab->dten_current = ep;
11244 enab->dten_error = 0;
11245
11246 /*
11247 * If a provider failed to enable a probe then get out and
11248 * let the consumer know we failed.
11249 */
11250 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11251 return (EBUSY);
11252
11253 total_matched += matched;
11254
11255 if (enab->dten_error != 0) {
11256 /*
11257 * If we get an error half-way through enabling the
11258 * probes, we kick out -- perhaps with some number of
11259 * them enabled. Leaving enabled probes enabled may
11260 * be slightly confusing for user-level, but we expect
11261 * that no one will attempt to actually drive on in
11262 * the face of such errors. If this is an anonymous
11263 * enabling (indicated with a NULL nmatched pointer),
11264 * we cmn_err() a message. We aren't expecting to
11265 * get such an error -- such as it can exist at all,
11266 * it would be a result of corrupted DOF in the driver
11267 * properties.
11268 */
11269 if (nmatched == NULL) {
11270 cmn_err(CE_WARN, "dtrace_enabling_match() "
11271 "error on %p: %d", (void *)ep,
11272 enab->dten_error);
11273 }
11274
11275 return (enab->dten_error);
11276 }
11277 }
11278
11279 enab->dten_probegen = dtrace_probegen;
11280 if (nmatched != NULL)
11281 *nmatched = total_matched;
11282
11283 return (0);
11284}
11285
11286static void
11287dtrace_enabling_matchall(void)
11288{
11289 dtrace_enabling_t *enab;
11290
11291 mutex_enter(&cpu_lock);
11292 mutex_enter(&dtrace_lock);
11293
11294 /*
11295 * Iterate over all retained enablings to see if any probes match
11296 * against them. We only perform this operation on enablings for which
11297 * we have sufficient permissions by virtue of being in the global zone
11298 * or in the same zone as the DTrace client. Because we can be called
11299 * after dtrace_detach() has been called, we cannot assert that there
11300 * are retained enablings. We can safely load from dtrace_retained,
11301 * however: the taskq_destroy() at the end of dtrace_detach() will
11302 * block pending our completion.
11303 */
11304 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11305#ifndef VBOX
11306 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11307
11308 if (INGLOBALZONE(curproc) ||
11309 cr != NULL && getzoneid() == crgetzoneid(cr))
11310#endif
11311 (void) dtrace_enabling_match(enab, NULL);
11312 }
11313
11314 mutex_exit(&dtrace_lock);
11315 mutex_exit(&cpu_lock);
11316}
11317
11318/*
11319 * If an enabling is to be enabled without having matched probes (that is, if
11320 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11321 * enabling must be _primed_ by creating an ECB for every ECB description.
11322 * This must be done to assure that we know the number of speculations, the
11323 * number of aggregations, the minimum buffer size needed, etc. before we
11324 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11325 * enabling any probes, we create ECBs for every ECB decription, but with a
11326 * NULL probe -- which is exactly what this function does.
11327 */
11328static void
11329dtrace_enabling_prime(dtrace_state_t *state)
11330{
11331 dtrace_enabling_t *enab;
11332 int i;
11333
11334 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11335 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11336
11337 if (enab->dten_vstate->dtvs_state != state)
11338 continue;
11339
11340 /*
11341 * We don't want to prime an enabling more than once, lest
11342 * we allow a malicious user to induce resource exhaustion.
11343 * (The ECBs that result from priming an enabling aren't
11344 * leaked -- but they also aren't deallocated until the
11345 * consumer state is destroyed.)
11346 */
11347 if (enab->dten_primed)
11348 continue;
11349
11350 for (i = 0; i < enab->dten_ndesc; i++) {
11351 enab->dten_current = enab->dten_desc[i];
11352 (void) dtrace_probe_enable(NULL, enab);
11353 }
11354
11355 enab->dten_primed = 1;
11356 }
11357}
11358
11359/*
11360 * Called to indicate that probes should be provided due to retained
11361 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11362 * must take an initial lap through the enabling calling the dtps_provide()
11363 * entry point explicitly to allow for autocreated probes.
11364 */
11365static void
11366dtrace_enabling_provide(dtrace_provider_t *prv)
11367{
11368 int i, all = 0;
11369 dtrace_probedesc_t desc;
11370 dtrace_genid_t gen;
11371
11372 ASSERT(MUTEX_HELD(&dtrace_lock));
11373 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11374
11375 if (prv == NULL) {
11376 all = 1;
11377 prv = dtrace_provider;
11378 }
11379
11380 do {
11381 dtrace_enabling_t *enab;
11382 void *parg = prv->dtpv_arg;
11383
11384retry:
11385 gen = dtrace_retained_gen;
11386 for (enab = dtrace_retained; enab != NULL;
11387 enab = enab->dten_next) {
11388 for (i = 0; i < enab->dten_ndesc; i++) {
11389 desc = enab->dten_desc[i]->dted_probe;
11390 mutex_exit(&dtrace_lock);
11391 prv->dtpv_pops.dtps_provide(parg, &desc);
11392 mutex_enter(&dtrace_lock);
11393 /*
11394 * Process the retained enablings again if
11395 * they have changed while we weren't holding
11396 * dtrace_lock.
11397 */
11398 if (gen != dtrace_retained_gen)
11399 goto retry;
11400 }
11401 }
11402 } while (all && (prv = prv->dtpv_next) != NULL);
11403
11404 mutex_exit(&dtrace_lock);
11405 dtrace_probe_provide(NULL, all ? NULL : prv);
11406 mutex_enter(&dtrace_lock);
11407}
11408
11409/*
11410 * DTrace DOF Functions
11411 */
11412/*ARGSUSED*/
11413static void
11414dtrace_dof_error(dof_hdr_t *dof, const char *str)
11415{
11416 RT_NOREF_PV(dof);
11417
11418 if (dtrace_err_verbose)
11419 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11420
11421#ifdef DTRACE_ERRDEBUG
11422 dtrace_errdebug(str);
11423#endif
11424}
11425
11426/*
11427 * Create DOF out of a currently enabled state. Right now, we only create
11428 * DOF containing the run-time options -- but this could be expanded to create
11429 * complete DOF representing the enabled state.
11430 */
11431static dof_hdr_t *
11432dtrace_dof_create(dtrace_state_t *state)
11433{
11434 dof_hdr_t *dof;
11435 dof_sec_t *sec;
11436 dof_optdesc_t *opt;
11437 int i, len = sizeof (dof_hdr_t) +
11438 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11439 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11440
11441 ASSERT(MUTEX_HELD(&dtrace_lock));
11442
11443 dof = kmem_zalloc(len, KM_SLEEP);
11444 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11445 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11446 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11447 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11448
11449 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11450 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11451 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11452 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11453 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11454 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11455
11456 dof->dofh_flags = 0;
11457 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11458 dof->dofh_secsize = sizeof (dof_sec_t);
11459 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11460 dof->dofh_secoff = sizeof (dof_hdr_t);
11461 dof->dofh_loadsz = len;
11462 dof->dofh_filesz = len;
11463 dof->dofh_pad = 0;
11464
11465 /*
11466 * Fill in the option section header...
11467 */
11468 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11469 sec->dofs_type = DOF_SECT_OPTDESC;
11470 sec->dofs_align = sizeof (uint64_t);
11471 sec->dofs_flags = DOF_SECF_LOAD;
11472 sec->dofs_entsize = sizeof (dof_optdesc_t);
11473
11474 opt = (dof_optdesc_t *)((uintptr_t)sec +
11475 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11476
11477 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11478 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11479
11480 for (i = 0; i < DTRACEOPT_MAX; i++) {
11481 opt[i].dofo_option = i;
11482 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11483 opt[i].dofo_value = state->dts_options[i];
11484 }
11485
11486 return (dof);
11487}
11488
11489static dof_hdr_t *
11490dtrace_dof_copyin(uintptr_t uarg, int *errp)
11491{
11492 dof_hdr_t hdr, *dof;
11493
11494 ASSERT(!MUTEX_HELD(&dtrace_lock));
11495
11496 /*
11497 * First, we're going to copyin() the sizeof (dof_hdr_t).
11498 */
11499 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11500 dtrace_dof_error(NULL, "failed to copyin DOF header");
11501 *errp = EFAULT;
11502 return (NULL);
11503 }
11504
11505 /*
11506 * Now we'll allocate the entire DOF and copy it in -- provided
11507 * that the length isn't outrageous.
11508 */
11509 if (hdr.dofh_loadsz >= VBDTCAST(uint64_t)dtrace_dof_maxsize) {
11510 dtrace_dof_error(&hdr, "load size exceeds maximum");
11511 *errp = E2BIG;
11512 return (NULL);
11513 }
11514
11515 if (hdr.dofh_loadsz < sizeof (hdr)) {
11516 dtrace_dof_error(&hdr, "invalid load size");
11517 *errp = EINVAL;
11518 return (NULL);
11519 }
11520
11521 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11522
11523 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
11524 dof->dofh_loadsz != hdr.dofh_loadsz) {
11525 kmem_free(dof, hdr.dofh_loadsz);
11526 *errp = EFAULT;
11527 return (NULL);
11528 }
11529
11530 return (dof);
11531}
11532
11533static dof_hdr_t *
11534dtrace_dof_property(const char *name)
11535{
11536#ifndef VBOX
11537 uchar_t *buf;
11538 uint64_t loadsz;
11539 unsigned int len, i;
11540 dof_hdr_t *dof;
11541
11542 /*
11543 * Unfortunately, array of values in .conf files are always (and
11544 * only) interpreted to be integer arrays. We must read our DOF
11545 * as an integer array, and then squeeze it into a byte array.
11546 */
11547 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11548 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11549 return (NULL);
11550
11551 for (i = 0; i < len; i++)
11552 buf[i] = (uchar_t)(((int *)buf)[i]);
11553
11554 if (len < sizeof (dof_hdr_t)) {
11555 ddi_prop_free(buf);
11556 dtrace_dof_error(NULL, "truncated header");
11557 return (NULL);
11558 }
11559
11560 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11561 ddi_prop_free(buf);
11562 dtrace_dof_error(NULL, "truncated DOF");
11563 return (NULL);
11564 }
11565
11566 if (loadsz >= dtrace_dof_maxsize) {
11567 ddi_prop_free(buf);
11568 dtrace_dof_error(NULL, "oversized DOF");
11569 return (NULL);
11570 }
11571
11572 dof = kmem_alloc(loadsz, KM_SLEEP);
11573 bcopy(buf, dof, loadsz);
11574 ddi_prop_free(buf);
11575
11576 return (dof);
11577#else /* VBOX */
11578 RT_NOREF_PV(name);
11579 return (NULL);
11580#endif /* VBOX */
11581}
11582
11583static void
11584dtrace_dof_destroy(dof_hdr_t *dof)
11585{
11586 kmem_free(dof, dof->dofh_loadsz);
11587}
11588
11589/*
11590 * Return the dof_sec_t pointer corresponding to a given section index. If the
11591 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
11592 * a type other than DOF_SECT_NONE is specified, the header is checked against
11593 * this type and NULL is returned if the types do not match.
11594 */
11595static dof_sec_t *
11596dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11597{
11598 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11599 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11600
11601 if (i >= dof->dofh_secnum) {
11602 dtrace_dof_error(dof, "referenced section index is invalid");
11603 return (NULL);
11604 }
11605
11606 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11607 dtrace_dof_error(dof, "referenced section is not loadable");
11608 return (NULL);
11609 }
11610
11611 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11612 dtrace_dof_error(dof, "referenced section is the wrong type");
11613 return (NULL);
11614 }
11615
11616 return (sec);
11617}
11618
11619static dtrace_probedesc_t *
11620dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11621{
11622 dof_probedesc_t *probe;
11623 dof_sec_t *strtab;
11624 uintptr_t daddr = (uintptr_t)dof;
11625 uintptr_t str;
11626 size_t size;
11627
11628 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11629 dtrace_dof_error(dof, "invalid probe section");
11630 return (NULL);
11631 }
11632
11633 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11634 dtrace_dof_error(dof, "bad alignment in probe description");
11635 return (NULL);
11636 }
11637
11638 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11639 dtrace_dof_error(dof, "truncated probe description");
11640 return (NULL);
11641 }
11642
11643 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11644 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11645
11646 if (strtab == NULL)
11647 return (NULL);
11648
11649 str = daddr + strtab->dofs_offset;
11650 size = strtab->dofs_size;
11651
11652 if (probe->dofp_provider >= strtab->dofs_size) {
11653 dtrace_dof_error(dof, "corrupt probe provider");
11654 return (NULL);
11655 }
11656
11657 (void) strncpy(desc->dtpd_provider,
11658 (char *)(str + probe->dofp_provider),
11659 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11660
11661 if (probe->dofp_mod >= strtab->dofs_size) {
11662 dtrace_dof_error(dof, "corrupt probe module");
11663 return (NULL);
11664 }
11665
11666 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11667 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11668
11669 if (probe->dofp_func >= strtab->dofs_size) {
11670 dtrace_dof_error(dof, "corrupt probe function");
11671 return (NULL);
11672 }
11673
11674 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11675 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11676
11677 if (probe->dofp_name >= strtab->dofs_size) {
11678 dtrace_dof_error(dof, "corrupt probe name");
11679 return (NULL);
11680 }
11681
11682 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11683 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11684
11685 return (desc);
11686}
11687
11688static dtrace_difo_t *
11689dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11690 cred_t *cr)
11691{
11692 dtrace_difo_t *dp;
11693 size_t ttl = 0;
11694 dof_difohdr_t *dofd;
11695 uintptr_t daddr = (uintptr_t)dof;
11696 size_t max = dtrace_difo_maxsize;
11697 int i, l, n;
11698
11699 static const struct {
11700 int section;
11701 int bufoffs;
11702 int lenoffs;
11703 int entsize;
11704 int align;
11705 const char *msg;
11706 } difo[] = {
11707 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11708 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11709 sizeof (dif_instr_t), "multiple DIF sections" },
11710
11711 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11712 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11713 sizeof (uint64_t), "multiple integer tables" },
11714
11715 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11716 offsetof(dtrace_difo_t, dtdo_strlen), 0,
11717 sizeof (char), "multiple string tables" },
11718
11719 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11720 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11721 sizeof (uint_t), "multiple variable tables" },
11722
11723 { DOF_SECT_NONE, 0, 0, 0, NULL }
11724 };
11725
11726 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11727 dtrace_dof_error(dof, "invalid DIFO header section");
11728 return (NULL);
11729 }
11730
11731 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11732 dtrace_dof_error(dof, "bad alignment in DIFO header");
11733 return (NULL);
11734 }
11735
11736 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11737 sec->dofs_size % sizeof (dof_secidx_t)) {
11738 dtrace_dof_error(dof, "bad size in DIFO header");
11739 return (NULL);
11740 }
11741
11742 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11743 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11744
11745 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11746 dp->dtdo_rtype = dofd->dofd_rtype;
11747
11748 for (l = 0; l < n; l++) {
11749 dof_sec_t *subsec;
11750 void **bufp;
11751 uint32_t *lenp;
11752
11753 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11754 dofd->dofd_links[l])) == NULL)
11755 goto err; /* invalid section link */
11756
11757 if (ttl + subsec->dofs_size > max) {
11758 dtrace_dof_error(dof, "exceeds maximum size");
11759 goto err;
11760 }
11761
11762 ttl += subsec->dofs_size;
11763
11764 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11765 if (subsec->dofs_type != VBDTCAST(uint32_t)difo[i].section)
11766 continue;
11767
11768 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11769 dtrace_dof_error(dof, "section not loaded");
11770 goto err;
11771 }
11772
11773 if (subsec->dofs_align != VBDTCAST(uint32_t)difo[i].align) {
11774 dtrace_dof_error(dof, "bad alignment");
11775 goto err;
11776 }
11777
11778 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11779 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11780
11781 if (*bufp != NULL) {
11782 dtrace_dof_error(dof, difo[i].msg);
11783 goto err;
11784 }
11785
11786 if (VBDTCAST(uint32_t)difo[i].entsize != subsec->dofs_entsize) {
11787 dtrace_dof_error(dof, "entry size mismatch");
11788 goto err;
11789 }
11790
11791 if (subsec->dofs_entsize != 0 &&
11792 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11793 dtrace_dof_error(dof, "corrupt entry size");
11794 goto err;
11795 }
11796
11797 *lenp = subsec->dofs_size;
11798 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11799 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11800 *bufp, subsec->dofs_size);
11801
11802 if (subsec->dofs_entsize != 0)
11803 *lenp /= subsec->dofs_entsize;
11804
11805 break;
11806 }
11807
11808 /*
11809 * If we encounter a loadable DIFO sub-section that is not
11810 * known to us, assume this is a broken program and fail.
11811 */
11812 if (difo[i].section == DOF_SECT_NONE &&
11813 (subsec->dofs_flags & DOF_SECF_LOAD)) {
11814 dtrace_dof_error(dof, "unrecognized DIFO subsection");
11815 goto err;
11816 }
11817 }
11818
11819 if (dp->dtdo_buf == NULL) {
11820 /*
11821 * We can't have a DIF object without DIF text.
11822 */
11823 dtrace_dof_error(dof, "missing DIF text");
11824 goto err;
11825 }
11826
11827 /*
11828 * Before we validate the DIF object, run through the variable table
11829 * looking for the strings -- if any of their size are under, we'll set
11830 * their size to be the system-wide default string size. Note that
11831 * this should _not_ happen if the "strsize" option has been set --
11832 * in this case, the compiler should have set the size to reflect the
11833 * setting of the option.
11834 */
11835 for (i = 0; VBDTCAST(unsigned)i < dp->dtdo_varlen; i++) {
11836 dtrace_difv_t *v = &dp->dtdo_vartab[i];
11837 dtrace_diftype_t *t = &v->dtdv_type;
11838
11839 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11840 continue;
11841
11842 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11843 t->dtdt_size = VBDTCAST(uint32_t)dtrace_strsize_default;
11844 }
11845
11846 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11847 goto err;
11848
11849 dtrace_difo_init(dp, vstate);
11850 return (dp);
11851
11852err:
11853 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11854 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11855 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11856 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11857
11858 kmem_free(dp, sizeof (dtrace_difo_t));
11859 return (NULL);
11860}
11861
11862static dtrace_predicate_t *
11863dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11864 cred_t *cr)
11865{
11866 dtrace_difo_t *dp;
11867
11868 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11869 return (NULL);
11870
11871 return (dtrace_predicate_create(dp));
11872}
11873
11874static dtrace_actdesc_t *
11875dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11876 cred_t *cr)
11877{
11878 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11879 dof_actdesc_t *desc;
11880 dof_sec_t *difosec;
11881 size_t offs;
11882 uintptr_t daddr = (uintptr_t)dof;
11883 uint64_t arg;
11884 dtrace_actkind_t kind;
11885
11886 if (sec->dofs_type != DOF_SECT_ACTDESC) {
11887 dtrace_dof_error(dof, "invalid action section");
11888 return (NULL);
11889 }
11890
11891 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11892 dtrace_dof_error(dof, "truncated action description");
11893 return (NULL);
11894 }
11895
11896 if (sec->dofs_align != sizeof (uint64_t)) {
11897 dtrace_dof_error(dof, "bad alignment in action description");
11898 return (NULL);
11899 }
11900
11901 if (sec->dofs_size < sec->dofs_entsize) {
11902 dtrace_dof_error(dof, "section entry size exceeds total size");
11903 return (NULL);
11904 }
11905
11906 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11907 dtrace_dof_error(dof, "bad entry size in action description");
11908 return (NULL);
11909 }
11910
11911 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11912 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11913 return (NULL);
11914 }
11915
11916 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11917 desc = (dof_actdesc_t *)(daddr +
11918 (uintptr_t)sec->dofs_offset + offs);
11919 kind = (dtrace_actkind_t)desc->dofa_kind;
11920
11921 if (DTRACEACT_ISPRINTFLIKE(kind) &&
11922 (kind != DTRACEACT_PRINTA ||
11923 desc->dofa_strtab != DOF_SECIDX_NONE)) {
11924 dof_sec_t *strtab;
11925 char *str, *fmt;
11926 uint64_t i;
11927
11928 /*
11929 * printf()-like actions must have a format string.
11930 */
11931 if ((strtab = dtrace_dof_sect(dof,
11932 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11933 goto err;
11934
11935 str = (char *)((uintptr_t)dof +
11936 (uintptr_t)strtab->dofs_offset);
11937
11938 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11939 if (str[i] == '\0')
11940 break;
11941 }
11942
11943 if (i >= strtab->dofs_size) {
11944 dtrace_dof_error(dof, "bogus format string");
11945 goto err;
11946 }
11947
11948 if (i == desc->dofa_arg) {
11949 dtrace_dof_error(dof, "empty format string");
11950 goto err;
11951 }
11952
11953 i -= desc->dofa_arg;
11954 fmt = kmem_alloc(i + 1, KM_SLEEP);
11955 bcopy(&str[desc->dofa_arg], fmt, i + 1);
11956 arg = (uint64_t)(uintptr_t)fmt;
11957 } else {
11958 if (kind == DTRACEACT_PRINTA) {
11959 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11960 arg = 0;
11961 } else {
11962 arg = desc->dofa_arg;
11963 }
11964 }
11965
11966 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11967 desc->dofa_uarg, arg);
11968
11969 if (last != NULL) {
11970 last->dtad_next = act;
11971 } else {
11972 first = act;
11973 }
11974
11975 last = act;
11976
11977 if (desc->dofa_difo == DOF_SECIDX_NONE)
11978 continue;
11979
11980 if ((difosec = dtrace_dof_sect(dof,
11981 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11982 goto err;
11983
11984 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11985
11986 if (act->dtad_difo == NULL)
11987 goto err;
11988 }
11989
11990 ASSERT(first != NULL);
11991 return (first);
11992
11993err:
11994 for (act = first; act != NULL; act = next) {
11995 next = act->dtad_next;
11996 dtrace_actdesc_release(act, vstate);
11997 }
11998
11999 return (NULL);
12000}
12001
12002static dtrace_ecbdesc_t *
12003dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12004 cred_t *cr)
12005{
12006 dtrace_ecbdesc_t *ep;
12007 dof_ecbdesc_t *ecb;
12008 dtrace_probedesc_t *desc;
12009 dtrace_predicate_t *pred = NULL;
12010
12011 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12012 dtrace_dof_error(dof, "truncated ECB description");
12013 return (NULL);
12014 }
12015
12016 if (sec->dofs_align != sizeof (uint64_t)) {
12017 dtrace_dof_error(dof, "bad alignment in ECB description");
12018 return (NULL);
12019 }
12020
12021 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12022 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12023
12024 if (sec == NULL)
12025 return (NULL);
12026
12027 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12028 ep->dted_uarg = ecb->dofe_uarg;
12029 desc = &ep->dted_probe;
12030
12031 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12032 goto err;
12033
12034 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12035 if ((sec = dtrace_dof_sect(dof,
12036 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12037 goto err;
12038
12039 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12040 goto err;
12041
12042 ep->dted_pred.dtpdd_predicate = pred;
12043 }
12044
12045 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12046 if ((sec = dtrace_dof_sect(dof,
12047 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12048 goto err;
12049
12050 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12051
12052 if (ep->dted_action == NULL)
12053 goto err;
12054 }
12055
12056 return (ep);
12057
12058err:
12059 if (pred != NULL)
12060 dtrace_predicate_release(pred, vstate);
12061 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12062 return (NULL);
12063}
12064
12065/*
12066 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12067 * specified DOF. At present, this amounts to simply adding 'ubase' to the
12068 * site of any user SETX relocations to account for load object base address.
12069 * In the future, if we need other relocations, this function can be extended.
12070 */
12071static int
12072dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12073{
12074 uintptr_t daddr = (uintptr_t)dof;
12075 dof_relohdr_t *dofr =
12076 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12077 dof_sec_t *ss, *rs, *ts;
12078 dof_relodesc_t *r;
12079 uint_t i, n;
12080
12081 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12082 sec->dofs_align != sizeof (dof_secidx_t)) {
12083 dtrace_dof_error(dof, "invalid relocation header");
12084 return (-1);
12085 }
12086
12087 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12088 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12089 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12090
12091 if (ss == NULL || rs == NULL || ts == NULL)
12092 return (-1); /* dtrace_dof_error() has been called already */
12093
12094 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12095 rs->dofs_align != sizeof (uint64_t)) {
12096 dtrace_dof_error(dof, "invalid relocation section");
12097 return (-1);
12098 }
12099
12100 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12101 n = rs->dofs_size / rs->dofs_entsize;
12102
12103 for (i = 0; i < n; i++) {
12104 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12105
12106 switch (r->dofr_type) {
12107 case DOF_RELO_NONE:
12108 break;
12109 case DOF_RELO_SETX:
12110 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12111 sizeof (uint64_t) > ts->dofs_size) {
12112 dtrace_dof_error(dof, "bad relocation offset");
12113 return (-1);
12114 }
12115
12116 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12117 dtrace_dof_error(dof, "misaligned setx relo");
12118 return (-1);
12119 }
12120
12121 *(uint64_t *)taddr += ubase;
12122 break;
12123 default:
12124 dtrace_dof_error(dof, "invalid relocation type");
12125 return (-1);
12126 }
12127
12128 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12129 }
12130
12131 return (0);
12132}
12133
12134/*
12135 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12136 * header: it should be at the front of a memory region that is at least
12137 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12138 * size. It need not be validated in any other way.
12139 */
12140static int
12141dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12142 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12143{
12144 uint64_t len = dof->dofh_loadsz, seclen;
12145 uintptr_t daddr = (uintptr_t)dof;
12146 dtrace_ecbdesc_t *ep;
12147 dtrace_enabling_t *enab;
12148 uint_t i;
12149
12150 ASSERT(MUTEX_HELD(&dtrace_lock));
12151 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12152
12153 /*
12154 * Check the DOF header identification bytes. In addition to checking
12155 * valid settings, we also verify that unused bits/bytes are zeroed so
12156 * we can use them later without fear of regressing existing binaries.
12157 */
12158 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12159 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12160 dtrace_dof_error(dof, "DOF magic string mismatch");
12161 return (-1);
12162 }
12163
12164 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12165 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12166 dtrace_dof_error(dof, "DOF has invalid data model");
12167 return (-1);
12168 }
12169
12170 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12171 dtrace_dof_error(dof, "DOF encoding mismatch");
12172 return (-1);
12173 }
12174
12175 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12176 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12177 dtrace_dof_error(dof, "DOF version mismatch");
12178 return (-1);
12179 }
12180
12181 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12182 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12183 return (-1);
12184 }
12185
12186 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12187 dtrace_dof_error(dof, "DOF uses too many integer registers");
12188 return (-1);
12189 }
12190
12191 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12192 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12193 return (-1);
12194 }
12195
12196 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12197 if (dof->dofh_ident[i] != 0) {
12198 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12199 return (-1);
12200 }
12201 }
12202
12203 if (dof->dofh_flags & ~DOF_FL_VALID) {
12204 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12205 return (-1);
12206 }
12207
12208 if (dof->dofh_secsize == 0) {
12209 dtrace_dof_error(dof, "zero section header size");
12210 return (-1);
12211 }
12212
12213 /*
12214 * Check that the section headers don't exceed the amount of DOF
12215 * data. Note that we cast the section size and number of sections
12216 * to uint64_t's to prevent possible overflow in the multiplication.
12217 */
12218 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12219
12220 if (dof->dofh_secoff > len || seclen > len ||
12221 dof->dofh_secoff + seclen > len) {
12222 dtrace_dof_error(dof, "truncated section headers");
12223 return (-1);
12224 }
12225
12226 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12227 dtrace_dof_error(dof, "misaligned section headers");
12228 return (-1);
12229 }
12230
12231 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12232 dtrace_dof_error(dof, "misaligned section size");
12233 return (-1);
12234 }
12235
12236 /*
12237 * Take an initial pass through the section headers to be sure that
12238 * the headers don't have stray offsets. If the 'noprobes' flag is
12239 * set, do not permit sections relating to providers, probes, or args.
12240 */
12241 for (i = 0; i < dof->dofh_secnum; i++) {
12242 dof_sec_t *sec = (dof_sec_t *)(daddr +
12243 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12244
12245 if (noprobes) {
12246 switch (sec->dofs_type) {
12247 case DOF_SECT_PROVIDER:
12248 case DOF_SECT_PROBES:
12249 case DOF_SECT_PRARGS:
12250 case DOF_SECT_PROFFS:
12251 dtrace_dof_error(dof, "illegal sections "
12252 "for enabling");
12253 return (-1);
12254 }
12255 }
12256
12257 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
12258 !(sec->dofs_flags & DOF_SECF_LOAD)) {
12259 dtrace_dof_error(dof, "loadable section with load "
12260 "flag unset");
12261 return (-1);
12262 }
12263
12264 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12265 continue; /* just ignore non-loadable sections */
12266
12267 if (sec->dofs_align & (sec->dofs_align - 1)) {
12268 dtrace_dof_error(dof, "bad section alignment");
12269 return (-1);
12270 }
12271
12272 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12273 dtrace_dof_error(dof, "misaligned section");
12274 return (-1);
12275 }
12276
12277 if (sec->dofs_offset > len || sec->dofs_size > len ||
12278 sec->dofs_offset + sec->dofs_size > len) {
12279 dtrace_dof_error(dof, "corrupt section header");
12280 return (-1);
12281 }
12282
12283 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12284 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12285 dtrace_dof_error(dof, "non-terminating string table");
12286 return (-1);
12287 }
12288 }
12289
12290 /*
12291 * Take a second pass through the sections and locate and perform any
12292 * relocations that are present. We do this after the first pass to
12293 * be sure that all sections have had their headers validated.
12294 */
12295 for (i = 0; i < dof->dofh_secnum; i++) {
12296 dof_sec_t *sec = (dof_sec_t *)(daddr +
12297 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12298
12299 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12300 continue; /* skip sections that are not loadable */
12301
12302 switch (sec->dofs_type) {
12303 case DOF_SECT_URELHDR:
12304 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12305 return (-1);
12306 break;
12307 }
12308 }
12309
12310 if ((enab = *enabp) == NULL)
12311 enab = *enabp = dtrace_enabling_create(vstate);
12312
12313 for (i = 0; i < dof->dofh_secnum; i++) {
12314 dof_sec_t *sec = (dof_sec_t *)(daddr +
12315 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12316
12317 if (sec->dofs_type != DOF_SECT_ECBDESC)
12318 continue;
12319
12320 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12321 dtrace_enabling_destroy(enab);
12322 *enabp = NULL;
12323 return (-1);
12324 }
12325
12326 dtrace_enabling_add(enab, ep);
12327 }
12328
12329 return (0);
12330}
12331
12332/*
12333 * Process DOF for any options. This routine assumes that the DOF has been
12334 * at least processed by dtrace_dof_slurp().
12335 */
12336static int
12337dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12338{
12339 int i, rval;
12340 uint32_t entsize;
12341 size_t offs;
12342 dof_optdesc_t *desc;
12343
12344 for (i = 0; VBDTCAST(unsigned)i < dof->dofh_secnum; i++) {
12345 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12346 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12347
12348 if (sec->dofs_type != DOF_SECT_OPTDESC)
12349 continue;
12350
12351 if (sec->dofs_align != sizeof (uint64_t)) {
12352 dtrace_dof_error(dof, "bad alignment in "
12353 "option description");
12354 return (EINVAL);
12355 }
12356
12357 if ((entsize = sec->dofs_entsize) == 0) {
12358 dtrace_dof_error(dof, "zeroed option entry size");
12359 return (EINVAL);
12360 }
12361
12362 if (entsize < sizeof (dof_optdesc_t)) {
12363 dtrace_dof_error(dof, "bad option entry size");
12364 return (EINVAL);
12365 }
12366
12367 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12368 desc = (dof_optdesc_t *)((uintptr_t)dof +
12369 (uintptr_t)sec->dofs_offset + offs);
12370
12371 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12372 dtrace_dof_error(dof, "non-zero option string");
12373 return (EINVAL);
12374 }
12375
12376 if (desc->dofo_value == VBDTCAST(uint64_t)DTRACEOPT_UNSET) {
12377 dtrace_dof_error(dof, "unset option");
12378 return (EINVAL);
12379 }
12380
12381 if ((rval = dtrace_state_option(state,
12382 desc->dofo_option, desc->dofo_value)) != 0) {
12383 dtrace_dof_error(dof, "rejected option");
12384 return (rval);
12385 }
12386 }
12387 }
12388
12389 return (0);
12390}
12391
12392/*
12393 * DTrace Consumer State Functions
12394 */
12395VBDTSTATIC int
12396dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12397{
12398 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12399 void *base;
12400 uintptr_t limit;
12401 dtrace_dynvar_t *dvar, *next, *start;
12402 VBDTTYPE(size_t,int) i;
12403
12404 ASSERT(MUTEX_HELD(&dtrace_lock));
12405 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12406
12407 bzero(dstate, sizeof (dtrace_dstate_t));
12408
12409 if ((dstate->dtds_chunksize = chunksize) == 0)
12410 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12411
12412 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12413 size = min;
12414
12415 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12416 return (ENOMEM);
12417
12418 dstate->dtds_size = size;
12419 dstate->dtds_base = base;
12420 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12421 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12422
12423 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12424
12425 if (hashsize != 1 && (hashsize & 1))
12426 hashsize--;
12427
12428 dstate->dtds_hashsize = hashsize;
12429 dstate->dtds_hash = dstate->dtds_base;
12430
12431 /*
12432 * Set all of our hash buckets to point to the single sink, and (if
12433 * it hasn't already been set), set the sink's hash value to be the
12434 * sink sentinel value. The sink is needed for dynamic variable
12435 * lookups to know that they have iterated over an entire, valid hash
12436 * chain.
12437 */
12438 for (i = 0; i < hashsize; i++)
12439 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12440
12441 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12442 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12443
12444 /*
12445 * Determine number of active CPUs. Divide free list evenly among
12446 * active CPUs.
12447 */
12448 start = (dtrace_dynvar_t *)
12449 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12450 limit = (uintptr_t)base + size;
12451
12452 maxper = (limit - (uintptr_t)start) / NCPU;
12453 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12454
12455 for (i = 0; i < NCPU; i++) {
12456 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12457
12458 /*
12459 * If we don't even have enough chunks to make it once through
12460 * NCPUs, we're just going to allocate everything to the first
12461 * CPU. And if we're on the last CPU, we're going to allocate
12462 * whatever is left over. In either case, we set the limit to
12463 * be the limit of the dynamic variable space.
12464 */
12465 if (maxper == 0 || i == NCPU - 1) {
12466 limit = (uintptr_t)base + size;
12467 start = NULL;
12468 } else {
12469 limit = (uintptr_t)start + maxper;
12470 start = (dtrace_dynvar_t *)limit;
12471 }
12472
12473 ASSERT(limit <= (uintptr_t)base + size);
12474
12475 for (;;) {
12476 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12477 dstate->dtds_chunksize);
12478
12479 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12480 break;
12481
12482 dvar->dtdv_next = next;
12483 dvar = next;
12484 }
12485
12486 if (maxper == 0)
12487 break;
12488 }
12489
12490 return (0);
12491}
12492
12493VBDTSTATIC void
12494dtrace_dstate_fini(dtrace_dstate_t *dstate)
12495{
12496 ASSERT(MUTEX_HELD(&cpu_lock));
12497
12498 if (dstate->dtds_base == NULL)
12499 return;
12500
12501 kmem_free(dstate->dtds_base, dstate->dtds_size);
12502 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12503}
12504
12505static void
12506dtrace_vstate_fini(dtrace_vstate_t *vstate)
12507{
12508 /*
12509 * Logical XOR, where are you?
12510 */
12511 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12512
12513 if (vstate->dtvs_nglobals > 0) {
12514 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12515 sizeof (dtrace_statvar_t *));
12516 }
12517
12518 if (vstate->dtvs_ntlocals > 0) {
12519 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12520 sizeof (dtrace_difv_t));
12521 }
12522
12523 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12524
12525 if (vstate->dtvs_nlocals > 0) {
12526 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12527 sizeof (dtrace_statvar_t *));
12528 }
12529}
12530
12531static void
12532dtrace_state_clean(dtrace_state_t *state)
12533{
12534 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12535 return;
12536
12537 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12538 dtrace_speculation_clean(state);
12539}
12540#ifdef VBOX
12541static DECLCALLBACK(void) dtrace_state_clean_timer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
12542{
12543 dtrace_state_clean((dtrace_state_t *)pvUser);
12544 NOREF(pTimer); NOREF(iTick);
12545}
12546#endif
12547
12548static void
12549dtrace_state_deadman(dtrace_state_t *state)
12550{
12551 hrtime_t now;
12552
12553 dtrace_sync();
12554
12555 now = dtrace_gethrtime();
12556
12557 if (state != dtrace_anon.dta_state &&
12558 now - state->dts_laststatus >= dtrace_deadman_user)
12559 return;
12560
12561 /*
12562 * We must be sure that dts_alive never appears to be less than the
12563 * value upon entry to dtrace_state_deadman(), and because we lack a
12564 * dtrace_cas64(), we cannot store to it atomically. We thus instead
12565 * store INT64_MAX to it, followed by a memory barrier, followed by
12566 * the new value. This assures that dts_alive never appears to be
12567 * less than its true value, regardless of the order in which the
12568 * stores to the underlying storage are issued.
12569 */
12570 state->dts_alive = INT64_MAX;
12571 dtrace_membar_producer();
12572 state->dts_alive = now;
12573}
12574
12575#ifdef VBOX
12576static DECLCALLBACK(void) dtrace_state_deadman_timer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
12577{
12578 dtrace_state_deadman((dtrace_state_t *)pvUser);
12579 NOREF(pTimer); NOREF(iTick);
12580}
12581#endif
12582
12583VBDTSTATIC dtrace_state_t *
12584#ifdef VBOX
12585dtrace_state_create(cred_t *cr)
12586#else
12587dtrace_state_create(dev_t *devp, cred_t *cr)
12588#endif
12589{
12590#ifndef VBOX
12591 minor_t minor;
12592 major_t major;
12593#endif
12594 char c[30];
12595 dtrace_state_t *state;
12596 dtrace_optval_t *opt;
12597 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
12598
12599 ASSERT(MUTEX_HELD(&dtrace_lock));
12600 ASSERT(MUTEX_HELD(&cpu_lock));
12601
12602#ifndef VBOX
12603 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12604 VM_BESTFIT | VM_SLEEP);
12605
12606 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12607 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12608 return (NULL);
12609 }
12610
12611 state = ddi_get_soft_state(dtrace_softstate, minor);
12612#else
12613 state = kmem_zalloc(sizeof (*state), KM_SLEEP);
12614 if (!state) {
12615 return (NULL);
12616 }
12617#endif
12618 state->dts_epid = DTRACE_EPIDNONE + 1;
12619
12620#ifndef VBOX
12621 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12622#else
12623 (void) snprintf(c, sizeof (c), "dtrace_aggid_%p", state);
12624#endif
12625#ifndef VBOX /* Avoid idProbe = UINT32_MAX as it is used as invalid value by VTG. */
12626 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12627 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12628#else
12629 state->dts_aggid_arena = vmem_create(c, (void *)(uintptr_t)1, _1G, 1,
12630 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12631#endif
12632
12633#ifndef VBOX
12634 if (devp != NULL) {
12635 major = getemajor(*devp);
12636 } else {
12637 major = ddi_driver_major(dtrace_devi);
12638 }
12639
12640 state->dts_dev = makedevice(major, minor);
12641
12642 if (devp != NULL)
12643 *devp = state->dts_dev;
12644#endif
12645
12646 /*
12647 * We allocate NCPU buffers. On the one hand, this can be quite
12648 * a bit of memory per instance (nearly 36K on a Starcat). On the
12649 * other hand, it saves an additional memory reference in the probe
12650 * path.
12651 */
12652 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12653 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12654 state->dts_cleaner = CYCLIC_NONE;
12655 state->dts_deadman = CYCLIC_NONE;
12656 state->dts_vstate.dtvs_state = state;
12657
12658 for (i = 0; i < DTRACEOPT_MAX; i++)
12659 state->dts_options[i] = DTRACEOPT_UNSET;
12660
12661 /*
12662 * Set the default options.
12663 */
12664 opt = state->dts_options;
12665 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12666 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12667 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12668 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12669 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12670 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12671 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12672 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12673 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12674 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12675 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12676 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12677 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12678 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12679
12680 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12681
12682 /*
12683 * Depending on the user credentials, we set flag bits which alter probe
12684 * visibility or the amount of destructiveness allowed. In the case of
12685 * actual anonymous tracing, or the possession of all privileges, all of
12686 * the normal checks are bypassed.
12687 */
12688 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12689 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12690 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12691 } else {
12692 /*
12693 * Set up the credentials for this instantiation. We take a
12694 * hold on the credential to prevent it from disappearing on
12695 * us; this in turn prevents the zone_t referenced by this
12696 * credential from disappearing. This means that we can
12697 * examine the credential and the zone from probe context.
12698 */
12699 crhold(cr);
12700 state->dts_cred.dcr_cred = cr;
12701
12702 /*
12703 * CRA_PROC means "we have *some* privilege for dtrace" and
12704 * unlocks the use of variables like pid, zonename, etc.
12705 */
12706 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12707 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12708 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12709 }
12710
12711 /*
12712 * dtrace_user allows use of syscall and profile providers.
12713 * If the user also has proc_owner and/or proc_zone, we
12714 * extend the scope to include additional visibility and
12715 * destructive power.
12716 */
12717 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12718 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12719 state->dts_cred.dcr_visible |=
12720 DTRACE_CRV_ALLPROC;
12721
12722 state->dts_cred.dcr_action |=
12723 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12724 }
12725
12726 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12727 state->dts_cred.dcr_visible |=
12728 DTRACE_CRV_ALLZONE;
12729
12730 state->dts_cred.dcr_action |=
12731 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12732 }
12733
12734 /*
12735 * If we have all privs in whatever zone this is,
12736 * we can do destructive things to processes which
12737 * have altered credentials.
12738 */
12739 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12740 cr->cr_zone->zone_privset)) {
12741 state->dts_cred.dcr_action |=
12742 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12743 }
12744 }
12745
12746 /*
12747 * Holding the dtrace_kernel privilege also implies that
12748 * the user has the dtrace_user privilege from a visibility
12749 * perspective. But without further privileges, some
12750 * destructive actions are not available.
12751 */
12752 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12753 /*
12754 * Make all probes in all zones visible. However,
12755 * this doesn't mean that all actions become available
12756 * to all zones.
12757 */
12758 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12759 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12760
12761 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12762 DTRACE_CRA_PROC;
12763 /*
12764 * Holding proc_owner means that destructive actions
12765 * for *this* zone are allowed.
12766 */
12767 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12768 state->dts_cred.dcr_action |=
12769 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12770
12771 /*
12772 * Holding proc_zone means that destructive actions
12773 * for this user/group ID in all zones is allowed.
12774 */
12775 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12776 state->dts_cred.dcr_action |=
12777 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12778
12779 /*
12780 * If we have all privs in whatever zone this is,
12781 * we can do destructive things to processes which
12782 * have altered credentials.
12783 */
12784 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12785 cr->cr_zone->zone_privset)) {
12786 state->dts_cred.dcr_action |=
12787 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12788 }
12789 }
12790
12791 /*
12792 * Holding the dtrace_proc privilege gives control over fasttrap
12793 * and pid providers. We need to grant wider destructive
12794 * privileges in the event that the user has proc_owner and/or
12795 * proc_zone.
12796 */
12797 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12798 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12799 state->dts_cred.dcr_action |=
12800 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12801
12802 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12803 state->dts_cred.dcr_action |=
12804 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12805 }
12806 }
12807
12808 return (state);
12809}
12810
12811static int
12812dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12813{
12814 dtrace_optval_t *opt = state->dts_options, size;
12815 processorid_t cpu VBDTUNASS((processorid_t)DTRACE_CPUALL);
12816 int flags = 0, rval;
12817
12818 ASSERT(MUTEX_HELD(&dtrace_lock));
12819 ASSERT(MUTEX_HELD(&cpu_lock));
12820 ASSERT(which < DTRACEOPT_MAX);
12821 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12822 (state == dtrace_anon.dta_state &&
12823 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12824
12825 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12826 return (0);
12827
12828 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12829 cpu = opt[DTRACEOPT_CPU];
12830
12831 if (which == DTRACEOPT_SPECSIZE)
12832 flags |= DTRACEBUF_NOSWITCH;
12833
12834 if (which == DTRACEOPT_BUFSIZE) {
12835 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12836 flags |= DTRACEBUF_RING;
12837
12838 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12839 flags |= DTRACEBUF_FILL;
12840
12841 if (state != dtrace_anon.dta_state ||
12842 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12843 flags |= DTRACEBUF_INACTIVE;
12844 }
12845
12846 for (size = opt[which]; size >= VBDTCAST(dtrace_optval_t)sizeof (uint64_t); size >>= 1) {
12847 /*
12848 * The size must be 8-byte aligned. If the size is not 8-byte
12849 * aligned, drop it down by the difference.
12850 */
12851 if (size & (sizeof (uint64_t) - 1))
12852 size -= size & (sizeof (uint64_t) - 1);
12853
12854 if (size < state->dts_reserve) {
12855 /*
12856 * Buffers always must be large enough to accommodate
12857 * their prereserved space. We return E2BIG instead
12858 * of ENOMEM in this case to allow for user-level
12859 * software to differentiate the cases.
12860 */
12861 return (E2BIG);
12862 }
12863
12864 rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12865
12866 if (rval != ENOMEM) {
12867 opt[which] = size;
12868 return (rval);
12869 }
12870
12871 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12872 return (rval);
12873 }
12874
12875 return (ENOMEM);
12876}
12877
12878static int
12879dtrace_state_buffers(dtrace_state_t *state)
12880{
12881 dtrace_speculation_t *spec = state->dts_speculations;
12882 int rval, i;
12883
12884 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12885 DTRACEOPT_BUFSIZE)) != 0)
12886 return (rval);
12887
12888 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12889 DTRACEOPT_AGGSIZE)) != 0)
12890 return (rval);
12891
12892 for (i = 0; i < state->dts_nspeculations; i++) {
12893 if ((rval = dtrace_state_buffer(state,
12894 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12895 return (rval);
12896 }
12897
12898 return (0);
12899}
12900
12901static void
12902dtrace_state_prereserve(dtrace_state_t *state)
12903{
12904 dtrace_ecb_t *ecb;
12905 dtrace_probe_t *probe;
12906
12907 state->dts_reserve = 0;
12908
12909 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12910 return;
12911
12912 /*
12913 * If our buffer policy is a "fill" buffer policy, we need to set the
12914 * prereserved space to be the space required by the END probes.
12915 */
12916 probe = dtrace_probes[dtrace_probeid_end - 1];
12917 ASSERT(probe != NULL);
12918
12919 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12920 if (ecb->dte_state != state)
12921 continue;
12922
12923 state->dts_reserve += VBDTCAST(uint32_t)ecb->dte_needed + ecb->dte_alignment;
12924 }
12925}
12926
12927static int
12928dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12929{
12930 dtrace_optval_t *opt = state->dts_options, sz, nspec;
12931 dtrace_speculation_t *spec;
12932 dtrace_buffer_t *buf;
12933#ifndef VBOX
12934 cyc_handler_t hdlr;
12935 cyc_time_t when;
12936#endif
12937 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12938 dtrace_icookie_t cookie;
12939
12940 mutex_enter(&cpu_lock);
12941 mutex_enter(&dtrace_lock);
12942
12943 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12944 rval = EBUSY;
12945 goto out;
12946 }
12947
12948 /*
12949 * Before we can perform any checks, we must prime all of the
12950 * retained enablings that correspond to this state.
12951 */
12952 dtrace_enabling_prime(state);
12953
12954 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12955 rval = EACCES;
12956 goto out;
12957 }
12958
12959 dtrace_state_prereserve(state);
12960
12961 /*
12962 * Now we want to do is try to allocate our speculations.
12963 * We do not automatically resize the number of speculations; if
12964 * this fails, we will fail the operation.
12965 */
12966 nspec = opt[DTRACEOPT_NSPEC];
12967 ASSERT(nspec != DTRACEOPT_UNSET);
12968
12969 if (nspec > INT_MAX) {
12970 rval = ENOMEM;
12971 goto out;
12972 }
12973
12974 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12975
12976 if (spec == NULL) {
12977 rval = ENOMEM;
12978 goto out;
12979 }
12980
12981 state->dts_speculations = spec;
12982 state->dts_nspeculations = (int)nspec;
12983
12984 for (i = 0; i < nspec; i++) {
12985 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12986 rval = ENOMEM;
12987 goto err;
12988 }
12989
12990 spec[i].dtsp_buffer = buf;
12991 }
12992
12993 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12994 if (dtrace_anon.dta_state == NULL) {
12995 rval = ENOENT;
12996 goto out;
12997 }
12998
12999 if (state->dts_necbs != 0) {
13000 rval = EALREADY;
13001 goto out;
13002 }
13003
13004 state->dts_anon = dtrace_anon_grab();
13005 ASSERT(state->dts_anon != NULL);
13006 state = state->dts_anon;
13007
13008 /*
13009 * We want "grabanon" to be set in the grabbed state, so we'll
13010 * copy that option value from the grabbing state into the
13011 * grabbed state.
13012 */
13013 state->dts_options[DTRACEOPT_GRABANON] =
13014 opt[DTRACEOPT_GRABANON];
13015
13016 *cpu = dtrace_anon.dta_beganon;
13017
13018 /*
13019 * If the anonymous state is active (as it almost certainly
13020 * is if the anonymous enabling ultimately matched anything),
13021 * we don't allow any further option processing -- but we
13022 * don't return failure.
13023 */
13024 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13025 goto out;
13026 }
13027
13028 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13029 opt[DTRACEOPT_AGGSIZE] != 0) {
13030 if (state->dts_aggregations == NULL) {
13031 /*
13032 * We're not going to create an aggregation buffer
13033 * because we don't have any ECBs that contain
13034 * aggregations -- set this option to 0.
13035 */
13036 opt[DTRACEOPT_AGGSIZE] = 0;
13037 } else {
13038 /*
13039 * If we have an aggregation buffer, we must also have
13040 * a buffer to use as scratch.
13041 */
13042 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13043 opt[DTRACEOPT_BUFSIZE] < VBDTCAST(dtrace_optval_t)state->dts_needed) {
13044 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13045 }
13046 }
13047 }
13048
13049 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13050 opt[DTRACEOPT_SPECSIZE] != 0) {
13051 if (!state->dts_speculates) {
13052 /*
13053 * We're not going to create speculation buffers
13054 * because we don't have any ECBs that actually
13055 * speculate -- set the speculation size to 0.
13056 */
13057 opt[DTRACEOPT_SPECSIZE] = 0;
13058 }
13059 }
13060
13061 /*
13062 * The bare minimum size for any buffer that we're actually going to
13063 * do anything to is sizeof (uint64_t).
13064 */
13065 sz = sizeof (uint64_t);
13066
13067 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13068 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13069 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13070 /*
13071 * A buffer size has been explicitly set to 0 (or to a size
13072 * that will be adjusted to 0) and we need the space -- we
13073 * need to return failure. We return ENOSPC to differentiate
13074 * it from failing to allocate a buffer due to failure to meet
13075 * the reserve (for which we return E2BIG).
13076 */
13077 rval = ENOSPC;
13078 goto out;
13079 }
13080
13081 if ((rval = dtrace_state_buffers(state)) != 0)
13082 goto err;
13083
13084 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13085 sz = dtrace_dstate_defsize;
13086
13087 do {
13088 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13089
13090 if (rval == 0)
13091 break;
13092
13093 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13094 goto err;
13095 } while (sz >>= 1);
13096
13097 opt[DTRACEOPT_DYNVARSIZE] = sz;
13098
13099 if (rval != 0)
13100 goto err;
13101
13102 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13103 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13104
13105 if (opt[DTRACEOPT_CLEANRATE] == 0)
13106 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13107
13108 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13109 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13110
13111 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13112 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13113
13114#ifndef VBOX
13115 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13116 hdlr.cyh_arg = state;
13117 hdlr.cyh_level = CY_LOW_LEVEL;
13118
13119 when.cyt_when = 0;
13120 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13121
13122 state->dts_cleaner = cyclic_add(&hdlr, &when);
13123
13124 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13125 hdlr.cyh_arg = state;
13126 hdlr.cyh_level = CY_LOW_LEVEL;
13127
13128 when.cyt_when = 0;
13129 when.cyt_interval = dtrace_deadman_interval;
13130
13131 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13132 state->dts_deadman = cyclic_add(&hdlr, &when);
13133#else /* VBOX */
13134
13135 rval = RTTimerCreateEx(&state->dts_cleaner, opt[DTRACEOPT_CLEANRATE],
13136 RTTIMER_FLAGS_CPU_ANY, dtrace_state_clean_timer, state);
13137 if (RT_FAILURE(rval)) {
13138 rval = RTErrConvertToErrno(rval);
13139 goto err;
13140 }
13141
13142 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13143 rval = RTTimerCreateEx(&state->dts_deadman, dtrace_deadman_interval,
13144 RTTIMER_FLAGS_CPU_ANY, dtrace_state_deadman_timer, state);
13145 if (RT_FAILURE(rval)) {
13146 RTTimerDestroy(state->dts_cleaner);
13147 state->dts_cleaner = CYCLIC_NONE;
13148 state->dts_deadman = CYCLIC_NONE;
13149 rval = RTErrConvertToErrno(rval);
13150 goto err;
13151 }
13152
13153 rval = RTTimerStart(state->dts_cleaner, 0);
13154 if (RT_SUCCESS(rval))
13155 rval = RTTimerStart(state->dts_deadman, 0);
13156 if (RT_FAILURE(rval)) {
13157 rval = RTErrConvertToErrno(rval);
13158 goto err;
13159 }
13160#endif /* VBOX */
13161
13162 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13163
13164 /*
13165 * Now it's time to actually fire the BEGIN probe. We need to disable
13166 * interrupts here both to record the CPU on which we fired the BEGIN
13167 * probe (the data from this CPU will be processed first at user
13168 * level) and to manually activate the buffer for this CPU.
13169 */
13170 cookie = dtrace_interrupt_disable();
13171 *cpu = VBDT_GET_CPUID();
13172 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13173 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13174
13175 dtrace_probe(dtrace_probeid_begin,
13176 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13177 dtrace_interrupt_enable(cookie);
13178 /*
13179 * We may have had an exit action from a BEGIN probe; only change our
13180 * state to ACTIVE if we're still in WARMUP.
13181 */
13182 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13183 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13184
13185 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13186 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13187
13188 /*
13189 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13190 * want each CPU to transition its principal buffer out of the
13191 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13192 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13193 * atomically transition from processing none of a state's ECBs to
13194 * processing all of them.
13195 */
13196#ifndef VBOX
13197 dtrace_xcall(DTRACE_CPUALL,
13198 (dtrace_xcall_t)dtrace_buffer_activate, state);
13199#else
13200 RTMpOnAll(dtrace_buffer_activate_wrapper, state, NULL);
13201#endif
13202 goto out;
13203
13204err:
13205 dtrace_buffer_free(state->dts_buffer);
13206 dtrace_buffer_free(state->dts_aggbuffer);
13207
13208 if ((nspec = state->dts_nspeculations) == 0) {
13209 ASSERT(state->dts_speculations == NULL);
13210 goto out;
13211 }
13212
13213 spec = state->dts_speculations;
13214 ASSERT(spec != NULL);
13215
13216 for (i = 0; i < state->dts_nspeculations; i++) {
13217 if ((buf = spec[i].dtsp_buffer) == NULL)
13218 break;
13219
13220 dtrace_buffer_free(buf);
13221 kmem_free(buf, bufsize);
13222 }
13223
13224 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13225 state->dts_nspeculations = 0;
13226 state->dts_speculations = NULL;
13227
13228out:
13229 mutex_exit(&dtrace_lock);
13230 mutex_exit(&cpu_lock);
13231
13232 return (rval);
13233}
13234
13235static int
13236dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13237{
13238 dtrace_icookie_t cookie;
13239
13240 ASSERT(MUTEX_HELD(&dtrace_lock));
13241
13242 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13243 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13244 return (EINVAL);
13245
13246 /*
13247 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13248 * to be sure that every CPU has seen it. See below for the details
13249 * on why this is done.
13250 */
13251 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13252 dtrace_sync();
13253
13254 /*
13255 * By this point, it is impossible for any CPU to be still processing
13256 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13257 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13258 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13259 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13260 * iff we're in the END probe.
13261 */
13262 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13263 dtrace_sync();
13264 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13265
13266 /*
13267 * Finally, we can release the reserve and call the END probe. We
13268 * disable interrupts across calling the END probe to allow us to
13269 * return the CPU on which we actually called the END probe. This
13270 * allows user-land to be sure that this CPU's principal buffer is
13271 * processed last.
13272 */
13273 state->dts_reserve = 0;
13274
13275 cookie = dtrace_interrupt_disable();
13276 *cpu = VBDT_GET_CPUID();
13277 dtrace_probe(dtrace_probeid_end,
13278 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13279 dtrace_interrupt_enable(cookie);
13280
13281 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13282 dtrace_sync();
13283
13284 return (0);
13285}
13286
13287static int
13288dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13289 dtrace_optval_t val)
13290{
13291 ASSERT(MUTEX_HELD(&dtrace_lock));
13292
13293 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13294 return (EBUSY);
13295
13296 if (option >= DTRACEOPT_MAX)
13297 return (EINVAL);
13298
13299 if (option != DTRACEOPT_CPU && val < 0)
13300 return (EINVAL);
13301
13302 switch (option) {
13303 case DTRACEOPT_DESTRUCTIVE:
13304 if (dtrace_destructive_disallow)
13305 return (EACCES);
13306
13307 state->dts_cred.dcr_destructive = 1;
13308 break;
13309
13310 case DTRACEOPT_BUFSIZE:
13311 case DTRACEOPT_DYNVARSIZE:
13312 case DTRACEOPT_AGGSIZE:
13313 case DTRACEOPT_SPECSIZE:
13314 case DTRACEOPT_STRSIZE:
13315 if (val < 0)
13316 return (EINVAL);
13317
13318 if (val >= LONG_MAX) {
13319 /*
13320 * If this is an otherwise negative value, set it to
13321 * the highest multiple of 128m less than LONG_MAX.
13322 * Technically, we're adjusting the size without
13323 * regard to the buffer resizing policy, but in fact,
13324 * this has no effect -- if we set the buffer size to
13325 * ~LONG_MAX and the buffer policy is ultimately set to
13326 * be "manual", the buffer allocation is guaranteed to
13327 * fail, if only because the allocation requires two
13328 * buffers. (We set the the size to the highest
13329 * multiple of 128m because it ensures that the size
13330 * will remain a multiple of a megabyte when
13331 * repeatedly halved -- all the way down to 15m.)
13332 */
13333 val = LONG_MAX - (1 << 27) + 1;
13334 }
13335 }
13336
13337 state->dts_options[option] = val;
13338
13339 return (0);
13340}
13341
13342static void
13343dtrace_state_destroy(dtrace_state_t *state)
13344{
13345 dtrace_ecb_t *ecb;
13346 dtrace_vstate_t *vstate = &state->dts_vstate;
13347#ifndef VBOX
13348 minor_t minor = getminor(state->dts_dev);
13349#endif
13350 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13351 dtrace_speculation_t *spec = state->dts_speculations;
13352 int nspec = state->dts_nspeculations;
13353 uint32_t match;
13354
13355 ASSERT(MUTEX_HELD(&dtrace_lock));
13356 ASSERT(MUTEX_HELD(&cpu_lock));
13357
13358 /*
13359 * First, retract any retained enablings for this state.
13360 */
13361 dtrace_enabling_retract(state);
13362 ASSERT(state->dts_nretained == 0);
13363
13364 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13365 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13366 /*
13367 * We have managed to come into dtrace_state_destroy() on a
13368 * hot enabling -- almost certainly because of a disorderly
13369 * shutdown of a consumer. (That is, a consumer that is
13370 * exiting without having called dtrace_stop().) In this case,
13371 * we're going to set our activity to be KILLED, and then
13372 * issue a sync to be sure that everyone is out of probe
13373 * context before we start blowing away ECBs.
13374 */
13375 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13376 dtrace_sync();
13377 }
13378
13379 /*
13380 * Release the credential hold we took in dtrace_state_create().
13381 */
13382 if (state->dts_cred.dcr_cred != NULL)
13383 crfree(state->dts_cred.dcr_cred);
13384
13385 /*
13386 * Now we can safely disable and destroy any enabled probes. Because
13387 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13388 * (especially if they're all enabled), we take two passes through the
13389 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13390 * in the second we disable whatever is left over.
13391 */
13392 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13393 for (i = 0; i < state->dts_necbs; i++) {
13394 if ((ecb = state->dts_ecbs[i]) == NULL)
13395 continue;
13396
13397 if (match && ecb->dte_probe != NULL) {
13398 dtrace_probe_t *probe = ecb->dte_probe;
13399 dtrace_provider_t *prov = probe->dtpr_provider;
13400
13401 if (!(prov->dtpv_priv.dtpp_flags & match))
13402 continue;
13403 }
13404
13405 dtrace_ecb_disable(ecb);
13406 dtrace_ecb_destroy(ecb);
13407 }
13408
13409 if (!match)
13410 break;
13411 }
13412
13413 /*
13414 * Before we free the buffers, perform one more sync to assure that
13415 * every CPU is out of probe context.
13416 */
13417 dtrace_sync();
13418
13419 dtrace_buffer_free(state->dts_buffer);
13420 dtrace_buffer_free(state->dts_aggbuffer);
13421
13422 for (i = 0; i < nspec; i++)
13423 dtrace_buffer_free(spec[i].dtsp_buffer);
13424
13425 if (state->dts_cleaner != CYCLIC_NONE)
13426 cyclic_remove(state->dts_cleaner);
13427
13428 if (state->dts_deadman != CYCLIC_NONE)
13429 cyclic_remove(state->dts_deadman);
13430
13431 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13432 dtrace_vstate_fini(vstate);
13433 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13434
13435 if (state->dts_aggregations != NULL) {
13436#ifdef DEBUG
13437 for (i = 0; i < state->dts_naggregations; i++)
13438 ASSERT(state->dts_aggregations[i] == NULL);
13439#endif
13440 ASSERT(state->dts_naggregations > 0);
13441 kmem_free(state->dts_aggregations,
13442 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13443 }
13444
13445 kmem_free(state->dts_buffer, bufsize);
13446 kmem_free(state->dts_aggbuffer, bufsize);
13447
13448 for (i = 0; i < nspec; i++)
13449 kmem_free(spec[i].dtsp_buffer, bufsize);
13450
13451 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13452
13453 dtrace_format_destroy(state);
13454
13455 vmem_destroy(state->dts_aggid_arena);
13456#ifndef VBOX
13457 ddi_soft_state_free(dtrace_softstate, minor);
13458 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13459#else
13460 kmem_free(state, sizeof (*state));
13461#endif
13462}
13463
13464/*
13465 * DTrace Anonymous Enabling Functions
13466 */
13467static dtrace_state_t *
13468dtrace_anon_grab(void)
13469{
13470 dtrace_state_t *state;
13471
13472 ASSERT(MUTEX_HELD(&dtrace_lock));
13473
13474 if ((state = dtrace_anon.dta_state) == NULL) {
13475 ASSERT(dtrace_anon.dta_enabling == NULL);
13476 return (NULL);
13477 }
13478
13479 ASSERT(dtrace_anon.dta_enabling != NULL);
13480 ASSERT(dtrace_retained != NULL);
13481
13482 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13483 dtrace_anon.dta_enabling = NULL;
13484 dtrace_anon.dta_state = NULL;
13485
13486 return (state);
13487}
13488
13489#ifndef VBOX
13490static void
13491dtrace_anon_property(void)
13492{
13493 int i, rv;
13494 dtrace_state_t *state;
13495 dof_hdr_t *dof;
13496 char c[32]; /* enough for "dof-data-" + digits */
13497
13498 ASSERT(MUTEX_HELD(&dtrace_lock));
13499 ASSERT(MUTEX_HELD(&cpu_lock));
13500
13501 for (i = 0; ; i++) {
13502 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
13503
13504 dtrace_err_verbose = 1;
13505
13506 if ((dof = dtrace_dof_property(c)) == NULL) {
13507 dtrace_err_verbose = 0;
13508 break;
13509 }
13510
13511#ifndef VBOX
13512 /*
13513 * We want to create anonymous state, so we need to transition
13514 * the kernel debugger to indicate that DTrace is active. If
13515 * this fails (e.g. because the debugger has modified text in
13516 * some way), we won't continue with the processing.
13517 */
13518 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13519 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13520 "enabling ignored.");
13521 dtrace_dof_destroy(dof);
13522 break;
13523 }
13524#endif
13525
13526 /*
13527 * If we haven't allocated an anonymous state, we'll do so now.
13528 */
13529 if ((state = dtrace_anon.dta_state) == NULL) {
13530 state = dtrace_state_create(NULL, NULL);
13531 dtrace_anon.dta_state = state;
13532
13533 if (state == NULL) {
13534 /*
13535 * This basically shouldn't happen: the only
13536 * failure mode from dtrace_state_create() is a
13537 * failure of ddi_soft_state_zalloc() that
13538 * itself should never happen. Still, the
13539 * interface allows for a failure mode, and
13540 * we want to fail as gracefully as possible:
13541 * we'll emit an error message and cease
13542 * processing anonymous state in this case.
13543 */
13544 cmn_err(CE_WARN, "failed to create "
13545 "anonymous state");
13546 dtrace_dof_destroy(dof);
13547 break;
13548 }
13549 }
13550
13551 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13552 &dtrace_anon.dta_enabling, 0, B_TRUE);
13553
13554 if (rv == 0)
13555 rv = dtrace_dof_options(dof, state);
13556
13557 dtrace_err_verbose = 0;
13558 dtrace_dof_destroy(dof);
13559
13560 if (rv != 0) {
13561 /*
13562 * This is malformed DOF; chuck any anonymous state
13563 * that we created.
13564 */
13565 ASSERT(dtrace_anon.dta_enabling == NULL);
13566 dtrace_state_destroy(state);
13567 dtrace_anon.dta_state = NULL;
13568 break;
13569 }
13570
13571 ASSERT(dtrace_anon.dta_enabling != NULL);
13572 }
13573
13574 if (dtrace_anon.dta_enabling != NULL) {
13575 int rval;
13576
13577 /*
13578 * dtrace_enabling_retain() can only fail because we are
13579 * trying to retain more enablings than are allowed -- but
13580 * we only have one anonymous enabling, and we are guaranteed
13581 * to be allowed at least one retained enabling; we assert
13582 * that dtrace_enabling_retain() returns success.
13583 */
13584 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13585 ASSERT(rval == 0);
13586
13587 dtrace_enabling_dump(dtrace_anon.dta_enabling);
13588 }
13589}
13590#endif /* !VBOX */
13591
13592/*
13593 * DTrace Helper Functions
13594 */
13595#ifndef VBOX /* No helper stuff */
13596static void
13597dtrace_helper_trace(dtrace_helper_action_t *helper,
13598 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13599{
13600 uint32_t size, next, nnext, i;
13601 dtrace_helptrace_t *ent;
13602 uint16_t flags = cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
13603
13604 if (!dtrace_helptrace_enabled)
13605 return;
13606
13607 ASSERT(vstate->dtvs_nlocals <= VBDTCAST(int32_t)dtrace_helptrace_nlocals);
13608
13609 /*
13610 * What would a tracing framework be without its own tracing
13611 * framework? (Well, a hell of a lot simpler, for starters...)
13612 */
13613 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13614 sizeof (uint64_t) - sizeof (uint64_t);
13615
13616 /*
13617 * Iterate until we can allocate a slot in the trace buffer.
13618 */
13619 do {
13620 next = dtrace_helptrace_next;
13621
13622 if (next + size < VBDTCAST(unsigned)dtrace_helptrace_bufsize) {
13623 nnext = next + size;
13624 } else {
13625 nnext = size;
13626 }
13627 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13628
13629 /*
13630 * We have our slot; fill it in.
13631 */
13632 if (nnext == size)
13633 next = 0;
13634
13635 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13636 ent->dtht_helper = helper;
13637 ent->dtht_where = where;
13638 ent->dtht_nlocals = vstate->dtvs_nlocals;
13639
13640 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13641 mstate->dtms_fltoffs : -1;
13642 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13643 ent->dtht_illval = cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_illval;
13644
13645 for (i = 0; VBDTCAST(int32_t)i < vstate->dtvs_nlocals; i++) {
13646 dtrace_statvar_t *svar;
13647
13648 if ((svar = vstate->dtvs_locals[i]) == NULL)
13649 continue;
13650
13651 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
13652 ent->dtht_locals[i] =
13653 ((uint64_t *)(uintptr_t)svar->dtsv_data)[VBDT_GET_CPUID()];
13654 }
13655}
13656
13657static uint64_t
13658dtrace_helper(int which, dtrace_mstate_t *mstate,
13659 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13660{
13661 VBDTTYPE(uint16_t volatile *, uint16_t *)flags = &cpu_core[VBDT_GET_CPUID()].cpuc_dtrace_flags;
13662 uint64_t sarg0 = mstate->dtms_arg[0];
13663 uint64_t sarg1 = mstate->dtms_arg[1];
13664 uint64_t rval VBDTUNASS(666);
13665 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13666 dtrace_helper_action_t *helper;
13667 dtrace_vstate_t *vstate;
13668 dtrace_difo_t *pred;
13669 int i, trace = dtrace_helptrace_enabled;
13670
13671 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13672
13673 if (helpers == NULL)
13674 return (0);
13675
13676 if ((helper = helpers->dthps_actions[which]) == NULL)
13677 return (0);
13678
13679 vstate = &helpers->dthps_vstate;
13680 mstate->dtms_arg[0] = arg0;
13681 mstate->dtms_arg[1] = arg1;
13682
13683 /*
13684 * Now iterate over each helper. If its predicate evaluates to 'true',
13685 * we'll call the corresponding actions. Note that the below calls
13686 * to dtrace_dif_emulate() may set faults in machine state. This is
13687 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
13688 * the stored DIF offset with its own (which is the desired behavior).
13689 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13690 * from machine state; this is okay, too.
13691 */
13692 for (; helper != NULL; helper = helper->dtha_next) {
13693 if ((pred = helper->dtha_predicate) != NULL) {
13694 if (trace)
13695 dtrace_helper_trace(helper, mstate, vstate, 0);
13696
13697 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13698 goto next;
13699
13700 if (*flags & CPU_DTRACE_FAULT)
13701 goto err;
13702 }
13703
13704 for (i = 0; i < helper->dtha_nactions; i++) {
13705 if (trace)
13706 dtrace_helper_trace(helper,
13707 mstate, vstate, i + 1);
13708
13709 rval = dtrace_dif_emulate(helper->dtha_actions[i],
13710 mstate, vstate, state);
13711
13712 if (*flags & CPU_DTRACE_FAULT)
13713 goto err;
13714 }
13715
13716next:
13717 if (trace)
13718 dtrace_helper_trace(helper, mstate, vstate,
13719 DTRACE_HELPTRACE_NEXT);
13720 }
13721
13722 if (trace)
13723 dtrace_helper_trace(helper, mstate, vstate,
13724 DTRACE_HELPTRACE_DONE);
13725
13726 /*
13727 * Restore the arg0 that we saved upon entry.
13728 */
13729 mstate->dtms_arg[0] = sarg0;
13730 mstate->dtms_arg[1] = sarg1;
13731
13732 return (rval);
13733
13734err:
13735 if (trace)
13736 dtrace_helper_trace(helper, mstate, vstate,
13737 DTRACE_HELPTRACE_ERR);
13738
13739 /*
13740 * Restore the arg0 that we saved upon entry.
13741 */
13742 mstate->dtms_arg[0] = sarg0;
13743 mstate->dtms_arg[1] = sarg1;
13744
13745 return (NULL);
13746}
13747
13748static void
13749dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13750 dtrace_vstate_t *vstate)
13751{
13752 int i;
13753
13754 if (helper->dtha_predicate != NULL)
13755 dtrace_difo_release(helper->dtha_predicate, vstate);
13756
13757 for (i = 0; i < helper->dtha_nactions; i++) {
13758 ASSERT(helper->dtha_actions[i] != NULL);
13759 dtrace_difo_release(helper->dtha_actions[i], vstate);
13760 }
13761
13762 kmem_free(helper->dtha_actions,
13763 helper->dtha_nactions * sizeof (dtrace_difo_t *));
13764 kmem_free(helper, sizeof (dtrace_helper_action_t));
13765}
13766
13767static int
13768dtrace_helper_destroygen(int gen)
13769{
13770 proc_t *p = curproc;
13771 dtrace_helpers_t *help = p->p_dtrace_helpers;
13772 dtrace_vstate_t *vstate;
13773 VBDTTYPE(uint_t,int) i;
13774
13775 ASSERT(MUTEX_HELD(&dtrace_lock));
13776
13777 if (help == NULL || gen > help->dthps_generation)
13778 return (EINVAL);
13779
13780 vstate = &help->dthps_vstate;
13781
13782 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13783 dtrace_helper_action_t *last = NULL, *h, *next;
13784
13785 for (h = help->dthps_actions[i]; h != NULL; h = next) {
13786 next = h->dtha_next;
13787
13788 if (h->dtha_generation == gen) {
13789 if (last != NULL) {
13790 last->dtha_next = next;
13791 } else {
13792 help->dthps_actions[i] = next;
13793 }
13794
13795 dtrace_helper_action_destroy(h, vstate);
13796 } else {
13797 last = h;
13798 }
13799 }
13800 }
13801
13802 /*
13803 * Interate until we've cleared out all helper providers with the
13804 * given generation number.
13805 */
13806 for (;;) {
13807 dtrace_helper_provider_t *prov VBDTGCC(NULL);
13808
13809 /*
13810 * Look for a helper provider with the right generation. We
13811 * have to start back at the beginning of the list each time
13812 * because we drop dtrace_lock. It's unlikely that we'll make
13813 * more than two passes.
13814 */
13815 for (i = 0; i < help->dthps_nprovs; i++) {
13816 prov = help->dthps_provs[i];
13817
13818 if (prov->dthp_generation == gen)
13819 break;
13820 }
13821
13822 /*
13823 * If there were no matches, we're done.
13824 */
13825 if (i == help->dthps_nprovs)
13826 break;
13827
13828 /*
13829 * Move the last helper provider into this slot.
13830 */
13831 help->dthps_nprovs--;
13832 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13833 help->dthps_provs[help->dthps_nprovs] = NULL;
13834
13835 mutex_exit(&dtrace_lock);
13836
13837 /*
13838 * If we have a meta provider, remove this helper provider.
13839 */
13840 mutex_enter(&dtrace_meta_lock);
13841 if (dtrace_meta_pid != NULL) {
13842 ASSERT(dtrace_deferred_pid == NULL);
13843 dtrace_helper_provider_remove(&prov->dthp_prov,
13844 p->p_pid);
13845 }
13846 mutex_exit(&dtrace_meta_lock);
13847
13848 dtrace_helper_provider_destroy(prov);
13849
13850 mutex_enter(&dtrace_lock);
13851 }
13852
13853 return (0);
13854}
13855
13856static int
13857dtrace_helper_validate(dtrace_helper_action_t *helper)
13858{
13859 int err = 0, i;
13860 dtrace_difo_t *dp;
13861
13862 if ((dp = helper->dtha_predicate) != NULL)
13863 err += dtrace_difo_validate_helper(dp);
13864
13865 for (i = 0; i < helper->dtha_nactions; i++)
13866 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13867
13868 return (err == 0);
13869}
13870
13871static int
13872dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13873{
13874 dtrace_helpers_t *help;
13875 dtrace_helper_action_t *helper, *last;
13876 dtrace_actdesc_t *act;
13877 dtrace_vstate_t *vstate;
13878 dtrace_predicate_t *pred;
13879 int count = 0, nactions = 0, i;
13880
13881 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13882 return (EINVAL);
13883
13884 help = curproc->p_dtrace_helpers;
13885 last = help->dthps_actions[which];
13886 vstate = &help->dthps_vstate;
13887
13888 for (count = 0; last != NULL; last = last->dtha_next) {
13889 count++;
13890 if (last->dtha_next == NULL)
13891 break;
13892 }
13893
13894 /*
13895 * If we already have dtrace_helper_actions_max helper actions for this
13896 * helper action type, we'll refuse to add a new one.
13897 */
13898 if (count >= dtrace_helper_actions_max)
13899 return (ENOSPC);
13900
13901 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13902 helper->dtha_generation = help->dthps_generation;
13903
13904 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13905 ASSERT(pred->dtp_difo != NULL);
13906 dtrace_difo_hold(pred->dtp_difo);
13907 helper->dtha_predicate = pred->dtp_difo;
13908 }
13909
13910 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13911 if (act->dtad_kind != DTRACEACT_DIFEXPR)
13912 goto err;
13913
13914 if (act->dtad_difo == NULL)
13915 goto err;
13916
13917 nactions++;
13918 }
13919
13920 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13921 (helper->dtha_nactions = nactions), KM_SLEEP);
13922
13923 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13924 dtrace_difo_hold(act->dtad_difo);
13925 helper->dtha_actions[i++] = act->dtad_difo;
13926 }
13927
13928 if (!dtrace_helper_validate(helper))
13929 goto err;
13930
13931 if (last == NULL) {
13932 help->dthps_actions[which] = helper;
13933 } else {
13934 last->dtha_next = helper;
13935 }
13936
13937 if (vstate->dtvs_nlocals > VBDTCAST(int32_t)dtrace_helptrace_nlocals) {
13938 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13939 dtrace_helptrace_next = 0;
13940 }
13941
13942 return (0);
13943err:
13944 dtrace_helper_action_destroy(helper, vstate);
13945 return (EINVAL);
13946}
13947
13948static void
13949dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13950 dof_helper_t *dofhp)
13951{
13952 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13953
13954 mutex_enter(&dtrace_meta_lock);
13955 mutex_enter(&dtrace_lock);
13956
13957 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13958 /*
13959 * If the dtrace module is loaded but not attached, or if
13960 * there aren't isn't a meta provider registered to deal with
13961 * these provider descriptions, we need to postpone creating
13962 * the actual providers until later.
13963 */
13964
13965 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13966 dtrace_deferred_pid != help) {
13967 help->dthps_deferred = 1;
13968 help->dthps_pid = p->p_pid;
13969 help->dthps_next = dtrace_deferred_pid;
13970 help->dthps_prev = NULL;
13971 if (dtrace_deferred_pid != NULL)
13972 dtrace_deferred_pid->dthps_prev = help;
13973 dtrace_deferred_pid = help;
13974 }
13975
13976 mutex_exit(&dtrace_lock);
13977
13978 } else if (dofhp != NULL) {
13979 /*
13980 * If the dtrace module is loaded and we have a particular
13981 * helper provider description, pass that off to the
13982 * meta provider.
13983 */
13984
13985 mutex_exit(&dtrace_lock);
13986
13987 dtrace_helper_provide(dofhp, p->p_pid);
13988
13989 } else {
13990 /*
13991 * Otherwise, just pass all the helper provider descriptions
13992 * off to the meta provider.
13993 */
13994
13995 VBDTTYPE(uint_t,int) i;
13996 mutex_exit(&dtrace_lock);
13997
13998 for (i = 0; i < help->dthps_nprovs; i++) {
13999 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14000 p->p_pid);
14001 }
14002 }
14003
14004 mutex_exit(&dtrace_meta_lock);
14005}
14006
14007static int
14008dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14009{
14010 dtrace_helpers_t *help;
14011 dtrace_helper_provider_t *hprov, **tmp_provs;
14012 uint_t tmp_maxprovs, i;
14013
14014 ASSERT(MUTEX_HELD(&dtrace_lock));
14015
14016 help = curproc->p_dtrace_helpers;
14017 ASSERT(help != NULL);
14018
14019 /*
14020 * If we already have dtrace_helper_providers_max helper providers,
14021 * we're refuse to add a new one.
14022 */
14023 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14024 return (ENOSPC);
14025
14026 /*
14027 * Check to make sure this isn't a duplicate.
14028 */
14029 for (i = 0; i < help->dthps_nprovs; i++) {
14030 if (dofhp->dofhp_addr ==
14031 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14032 return (EALREADY);
14033 }
14034
14035 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14036 hprov->dthp_prov = *dofhp;
14037 hprov->dthp_ref = 1;
14038 hprov->dthp_generation = gen;
14039
14040 /*
14041 * Allocate a bigger table for helper providers if it's already full.
14042 */
14043 if (help->dthps_maxprovs == help->dthps_nprovs) {
14044 tmp_maxprovs = help->dthps_maxprovs;
14045 tmp_provs = help->dthps_provs;
14046
14047 if (help->dthps_maxprovs == 0)
14048 help->dthps_maxprovs = 2;
14049 else
14050 help->dthps_maxprovs *= 2;
14051 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14052 help->dthps_maxprovs = dtrace_helper_providers_max;
14053
14054 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14055
14056 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14057 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14058
14059 if (tmp_provs != NULL) {
14060 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14061 sizeof (dtrace_helper_provider_t *));
14062 kmem_free(tmp_provs, tmp_maxprovs *
14063 sizeof (dtrace_helper_provider_t *));
14064 }
14065 }
14066
14067 help->dthps_provs[help->dthps_nprovs] = hprov;
14068 help->dthps_nprovs++;
14069
14070 return (0);
14071}
14072
14073static void
14074dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14075{
14076 mutex_enter(&dtrace_lock);
14077
14078 if (--hprov->dthp_ref == 0) {
14079 dof_hdr_t *dof;
14080 mutex_exit(&dtrace_lock);
14081 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14082 dtrace_dof_destroy(dof);
14083 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14084 } else {
14085 mutex_exit(&dtrace_lock);
14086 }
14087}
14088
14089static int
14090dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14091{
14092 uintptr_t daddr = (uintptr_t)dof;
14093 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14094 dof_provider_t *provider;
14095 dof_probe_t *probe;
14096 uint8_t *arg;
14097 char *strtab, *typestr;
14098 dof_stridx_t typeidx;
14099 size_t typesz;
14100 uint_t nprobes, j, k;
14101
14102 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14103
14104 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14105 dtrace_dof_error(dof, "misaligned section offset");
14106 return (-1);
14107 }
14108
14109 /*
14110 * The section needs to be large enough to contain the DOF provider
14111 * structure appropriate for the given version.
14112 */
14113 if (sec->dofs_size <
14114 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14115 offsetof(dof_provider_t, dofpv_prenoffs) :
14116 sizeof (dof_provider_t))) {
14117 dtrace_dof_error(dof, "provider section too small");
14118 return (-1);
14119 }
14120
14121 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14122 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14123 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14124 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14125 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14126
14127 if (str_sec == NULL || prb_sec == NULL ||
14128 arg_sec == NULL || off_sec == NULL)
14129 return (-1);
14130
14131 enoff_sec = NULL;
14132
14133 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14134 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14135 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14136 provider->dofpv_prenoffs)) == NULL)
14137 return (-1);
14138
14139 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14140
14141 if (provider->dofpv_name >= str_sec->dofs_size ||
14142 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14143 dtrace_dof_error(dof, "invalid provider name");
14144 return (-1);
14145 }
14146
14147 if (prb_sec->dofs_entsize == 0 ||
14148 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14149 dtrace_dof_error(dof, "invalid entry size");
14150 return (-1);
14151 }
14152
14153 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14154 dtrace_dof_error(dof, "misaligned entry size");
14155 return (-1);
14156 }
14157
14158 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14159 dtrace_dof_error(dof, "invalid entry size");
14160 return (-1);
14161 }
14162
14163 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14164 dtrace_dof_error(dof, "misaligned section offset");
14165 return (-1);
14166 }
14167
14168 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14169 dtrace_dof_error(dof, "invalid entry size");
14170 return (-1);
14171 }
14172
14173 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14174
14175 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14176
14177 /*
14178 * Take a pass through the probes to check for errors.
14179 */
14180 for (j = 0; j < nprobes; j++) {
14181 probe = (dof_probe_t *)(uintptr_t)(daddr +
14182 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14183
14184 if (probe->dofpr_func >= str_sec->dofs_size) {
14185 dtrace_dof_error(dof, "invalid function name");
14186 return (-1);
14187 }
14188
14189 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14190 dtrace_dof_error(dof, "function name too long");
14191 return (-1);
14192 }
14193
14194 if (probe->dofpr_name >= str_sec->dofs_size ||
14195 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14196 dtrace_dof_error(dof, "invalid probe name");
14197 return (-1);
14198 }
14199
14200 /*
14201 * The offset count must not wrap the index, and the offsets
14202 * must also not overflow the section's data.
14203 */
14204 if (probe->dofpr_offidx + probe->dofpr_noffs <
14205 probe->dofpr_offidx ||
14206 (probe->dofpr_offidx + probe->dofpr_noffs) *
14207 off_sec->dofs_entsize > off_sec->dofs_size) {
14208 dtrace_dof_error(dof, "invalid probe offset");
14209 return (-1);
14210 }
14211
14212 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14213 /*
14214 * If there's no is-enabled offset section, make sure
14215 * there aren't any is-enabled offsets. Otherwise
14216 * perform the same checks as for probe offsets
14217 * (immediately above).
14218 */
14219 if (enoff_sec == NULL) {
14220 if (probe->dofpr_enoffidx != 0 ||
14221 probe->dofpr_nenoffs != 0) {
14222 dtrace_dof_error(dof, "is-enabled "
14223 "offsets with null section");
14224 return (-1);
14225 }
14226 } else if (probe->dofpr_enoffidx +
14227 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14228 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14229 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14230 dtrace_dof_error(dof, "invalid is-enabled "
14231 "offset");
14232 return (-1);
14233 }
14234
14235 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14236 dtrace_dof_error(dof, "zero probe and "
14237 "is-enabled offsets");
14238 return (-1);
14239 }
14240 } else if (probe->dofpr_noffs == 0) {
14241 dtrace_dof_error(dof, "zero probe offsets");
14242 return (-1);
14243 }
14244
14245 if (probe->dofpr_argidx + probe->dofpr_xargc <
14246 probe->dofpr_argidx ||
14247 (probe->dofpr_argidx + probe->dofpr_xargc) *
14248 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14249 dtrace_dof_error(dof, "invalid args");
14250 return (-1);
14251 }
14252
14253 typeidx = probe->dofpr_nargv;
14254 typestr = strtab + probe->dofpr_nargv;
14255 for (k = 0; k < probe->dofpr_nargc; k++) {
14256 if (typeidx >= str_sec->dofs_size) {
14257 dtrace_dof_error(dof, "bad "
14258 "native argument type");
14259 return (-1);
14260 }
14261
14262 typesz = strlen(typestr) + 1;
14263 if (typesz > DTRACE_ARGTYPELEN) {
14264 dtrace_dof_error(dof, "native "
14265 "argument type too long");
14266 return (-1);
14267 }
14268 typeidx += VBDTCAST(dof_stridx_t)typesz;
14269 typestr += typesz;
14270 }
14271
14272 typeidx = probe->dofpr_xargv;
14273 typestr = strtab + probe->dofpr_xargv;
14274 for (k = 0; k < probe->dofpr_xargc; k++) {
14275 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14276 dtrace_dof_error(dof, "bad "
14277 "native argument index");
14278 return (-1);
14279 }
14280
14281 if (typeidx >= str_sec->dofs_size) {
14282 dtrace_dof_error(dof, "bad "
14283 "translated argument type");
14284 return (-1);
14285 }
14286
14287 typesz = strlen(typestr) + 1;
14288 if (typesz > DTRACE_ARGTYPELEN) {
14289 dtrace_dof_error(dof, "translated argument "
14290 "type too long");
14291 return (-1);
14292 }
14293
14294 typeidx += VBDTCAST(dof_stridx_t)typesz;
14295 typestr += typesz;
14296 }
14297 }
14298
14299 return (0);
14300}
14301
14302static int
14303dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14304{
14305 dtrace_helpers_t *help;
14306 dtrace_vstate_t *vstate;
14307 dtrace_enabling_t *enab = NULL;
14308 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14309 uintptr_t daddr = (uintptr_t)dof;
14310
14311 ASSERT(MUTEX_HELD(&dtrace_lock));
14312
14313 if ((help = curproc->p_dtrace_helpers) == NULL)
14314 help = dtrace_helpers_create(curproc);
14315
14316 vstate = &help->dthps_vstate;
14317
14318 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14319 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14320 dtrace_dof_destroy(dof);
14321 return (rv);
14322 }
14323
14324 /*
14325 * Look for helper providers and validate their descriptions.
14326 */
14327 if (dhp != NULL) {
14328 for (i = 0; i < VBDTCAST(int)dof->dofh_secnum; i++) {
14329 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14330 dof->dofh_secoff + i * dof->dofh_secsize);
14331
14332 if (sec->dofs_type != DOF_SECT_PROVIDER)
14333 continue;
14334
14335 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14336 dtrace_enabling_destroy(enab);
14337 dtrace_dof_destroy(dof);
14338 return (-1);
14339 }
14340
14341 nprovs++;
14342 }
14343 }
14344
14345 /*
14346 * Now we need to walk through the ECB descriptions in the enabling.
14347 */
14348 for (i = 0; i < enab->dten_ndesc; i++) {
14349 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14350 dtrace_probedesc_t *desc = &ep->dted_probe;
14351
14352 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14353 continue;
14354
14355 if (strcmp(desc->dtpd_mod, "helper") != 0)
14356 continue;
14357
14358 if (strcmp(desc->dtpd_func, "ustack") != 0)
14359 continue;
14360
14361 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14362 ep)) != 0) {
14363 /*
14364 * Adding this helper action failed -- we are now going
14365 * to rip out the entire generation and return failure.
14366 */
14367 (void) dtrace_helper_destroygen(help->dthps_generation);
14368 dtrace_enabling_destroy(enab);
14369 dtrace_dof_destroy(dof);
14370 return (-1);
14371 }
14372
14373 nhelpers++;
14374 }
14375
14376 if (nhelpers < enab->dten_ndesc)
14377 dtrace_dof_error(dof, "unmatched helpers");
14378
14379 gen = help->dthps_generation++;
14380 dtrace_enabling_destroy(enab);
14381
14382 if (dhp != NULL && nprovs > 0) {
14383 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14384 if (dtrace_helper_provider_add(dhp, gen) == 0) {
14385 mutex_exit(&dtrace_lock);
14386 dtrace_helper_provider_register(curproc, help, dhp);
14387 mutex_enter(&dtrace_lock);
14388
14389 destroy = 0;
14390 }
14391 }
14392
14393 if (destroy)
14394 dtrace_dof_destroy(dof);
14395
14396 return (gen);
14397}
14398
14399static dtrace_helpers_t *
14400dtrace_helpers_create(proc_t *p)
14401{
14402 dtrace_helpers_t *help;
14403
14404 ASSERT(MUTEX_HELD(&dtrace_lock));
14405 ASSERT(p->p_dtrace_helpers == NULL);
14406
14407 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14408 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14409 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14410
14411 p->p_dtrace_helpers = help;
14412 dtrace_helpers++;
14413
14414 return (help);
14415}
14416
14417static void
14418dtrace_helpers_destroy(void)
14419{
14420 dtrace_helpers_t *help;
14421 dtrace_vstate_t *vstate;
14422 proc_t *p = curproc;
14423 VBDTTYPE(uint_t, int) i;
14424
14425 mutex_enter(&dtrace_lock);
14426
14427 ASSERT(p->p_dtrace_helpers != NULL);
14428 ASSERT(dtrace_helpers > 0);
14429
14430 help = p->p_dtrace_helpers;
14431 vstate = &help->dthps_vstate;
14432
14433 /*
14434 * We're now going to lose the help from this process.
14435 */
14436 p->p_dtrace_helpers = NULL;
14437 dtrace_sync();
14438
14439 /*
14440 * Destory the helper actions.
14441 */
14442 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14443 dtrace_helper_action_t *h, *next;
14444
14445 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14446 next = h->dtha_next;
14447 dtrace_helper_action_destroy(h, vstate);
14448 h = next;
14449 }
14450 }
14451
14452 mutex_exit(&dtrace_lock);
14453
14454 /*
14455 * Destroy the helper providers.
14456 */
14457 if (help->dthps_maxprovs > 0) {
14458 mutex_enter(&dtrace_meta_lock);
14459 if (dtrace_meta_pid != NULL) {
14460 ASSERT(dtrace_deferred_pid == NULL);
14461
14462 for (i = 0; i < help->dthps_nprovs; i++) {
14463 dtrace_helper_provider_remove(
14464 &help->dthps_provs[i]->dthp_prov, p->p_pid);
14465 }
14466 } else {
14467 mutex_enter(&dtrace_lock);
14468 ASSERT(help->dthps_deferred == 0 ||
14469 help->dthps_next != NULL ||
14470 help->dthps_prev != NULL ||
14471 help == dtrace_deferred_pid);
14472
14473 /*
14474 * Remove the helper from the deferred list.
14475 */
14476 if (help->dthps_next != NULL)
14477 help->dthps_next->dthps_prev = help->dthps_prev;
14478 if (help->dthps_prev != NULL)
14479 help->dthps_prev->dthps_next = help->dthps_next;
14480 if (dtrace_deferred_pid == help) {
14481 dtrace_deferred_pid = help->dthps_next;
14482 ASSERT(help->dthps_prev == NULL);
14483 }
14484
14485 mutex_exit(&dtrace_lock);
14486 }
14487
14488 mutex_exit(&dtrace_meta_lock);
14489
14490 for (i = 0; i < help->dthps_nprovs; i++) {
14491 dtrace_helper_provider_destroy(help->dthps_provs[i]);
14492 }
14493
14494 kmem_free(help->dthps_provs, help->dthps_maxprovs *
14495 sizeof (dtrace_helper_provider_t *));
14496 }
14497
14498 mutex_enter(&dtrace_lock);
14499
14500 dtrace_vstate_fini(&help->dthps_vstate);
14501 kmem_free(help->dthps_actions,
14502 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
14503 kmem_free(help, sizeof (dtrace_helpers_t));
14504
14505 --dtrace_helpers;
14506 mutex_exit(&dtrace_lock);
14507}
14508
14509static void
14510dtrace_helpers_duplicate(proc_t *from, proc_t *to)
14511{
14512 dtrace_helpers_t *help, *newhelp;
14513 dtrace_helper_action_t *helper, *new, *last;
14514 dtrace_difo_t *dp;
14515 dtrace_vstate_t *vstate;
14516 int i, j, sz, hasprovs = 0;
14517
14518 mutex_enter(&dtrace_lock);
14519 ASSERT(from->p_dtrace_helpers != NULL);
14520 ASSERT(dtrace_helpers > 0);
14521
14522 help = from->p_dtrace_helpers;
14523 newhelp = dtrace_helpers_create(to);
14524 ASSERT(to->p_dtrace_helpers != NULL);
14525
14526 newhelp->dthps_generation = help->dthps_generation;
14527 vstate = &newhelp->dthps_vstate;
14528
14529 /*
14530 * Duplicate the helper actions.
14531 */
14532 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14533 if ((helper = help->dthps_actions[i]) == NULL)
14534 continue;
14535
14536 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
14537 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
14538 KM_SLEEP);
14539 new->dtha_generation = helper->dtha_generation;
14540
14541 if ((dp = helper->dtha_predicate) != NULL) {
14542 dp = dtrace_difo_duplicate(dp, vstate);
14543 new->dtha_predicate = dp;
14544 }
14545
14546 new->dtha_nactions = helper->dtha_nactions;
14547 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
14548 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
14549
14550 for (j = 0; j < new->dtha_nactions; j++) {
14551 dtrace_difo_t *dp2 = helper->dtha_actions[j];
14552
14553 ASSERT(dp2 != NULL);
14554 dp2 = dtrace_difo_duplicate(dp2, vstate);
14555 new->dtha_actions[j] = dp2;
14556 }
14557
14558 if (last != NULL) {
14559 last->dtha_next = new;
14560 } else {
14561 newhelp->dthps_actions[i] = new;
14562 }
14563
14564 last = new;
14565 }
14566 }
14567
14568 /*
14569 * Duplicate the helper providers and register them with the
14570 * DTrace framework.
14571 */
14572 if (help->dthps_nprovs > 0) {
14573 newhelp->dthps_nprovs = help->dthps_nprovs;
14574 newhelp->dthps_maxprovs = help->dthps_nprovs;
14575 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
14576 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14577 for (i = 0; i < VBDTCAST(int)newhelp->dthps_nprovs; i++) {
14578 newhelp->dthps_provs[i] = help->dthps_provs[i];
14579 newhelp->dthps_provs[i]->dthp_ref++;
14580 }
14581
14582 hasprovs = 1;
14583 }
14584
14585 mutex_exit(&dtrace_lock);
14586
14587 if (hasprovs)
14588 dtrace_helper_provider_register(to, newhelp, NULL);
14589}
14590
14591/*
14592 * DTrace Hook Functions
14593 */
14594static void
14595dtrace_module_loaded(struct modctl *ctl)
14596{
14597 dtrace_provider_t *prv;
14598
14599 mutex_enter(&dtrace_provider_lock);
14600 mutex_enter(&mod_lock);
14601
14602 ASSERT(ctl->mod_busy);
14603
14604 /*
14605 * We're going to call each providers per-module provide operation
14606 * specifying only this module.
14607 */
14608 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
14609 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
14610
14611 mutex_exit(&mod_lock);
14612 mutex_exit(&dtrace_provider_lock);
14613
14614 /*
14615 * If we have any retained enablings, we need to match against them.
14616 * Enabling probes requires that cpu_lock be held, and we cannot hold
14617 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
14618 * module. (In particular, this happens when loading scheduling
14619 * classes.) So if we have any retained enablings, we need to dispatch
14620 * our task queue to do the match for us.
14621 */
14622 mutex_enter(&dtrace_lock);
14623
14624 if (dtrace_retained == NULL) {
14625 mutex_exit(&dtrace_lock);
14626 return;
14627 }
14628
14629 (void) taskq_dispatch(dtrace_taskq,
14630 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
14631
14632 mutex_exit(&dtrace_lock);
14633
14634 /*
14635 * And now, for a little heuristic sleaze: in general, we want to
14636 * match modules as soon as they load. However, we cannot guarantee
14637 * this, because it would lead us to the lock ordering violation
14638 * outlined above. The common case, of course, is that cpu_lock is
14639 * _not_ held -- so we delay here for a clock tick, hoping that that's
14640 * long enough for the task queue to do its work. If it's not, it's
14641 * not a serious problem -- it just means that the module that we
14642 * just loaded may not be immediately instrumentable.
14643 */
14644 delay(1);
14645}
14646
14647static void
14648dtrace_module_unloaded(struct modctl *ctl)
14649{
14650 dtrace_probe_t template, *probe, *first, *next;
14651 dtrace_provider_t *prov;
14652
14653 template.dtpr_mod = ctl->mod_modname;
14654
14655 mutex_enter(&dtrace_provider_lock);
14656 mutex_enter(&mod_lock);
14657 mutex_enter(&dtrace_lock);
14658
14659 if (dtrace_bymod == NULL) {
14660 /*
14661 * The DTrace module is loaded (obviously) but not attached;
14662 * we don't have any work to do.
14663 */
14664 mutex_exit(&dtrace_provider_lock);
14665 mutex_exit(&mod_lock);
14666 mutex_exit(&dtrace_lock);
14667 return;
14668 }
14669
14670 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
14671 probe != NULL; probe = probe->dtpr_nextmod) {
14672 if (probe->dtpr_ecb != NULL) {
14673 mutex_exit(&dtrace_provider_lock);
14674 mutex_exit(&mod_lock);
14675 mutex_exit(&dtrace_lock);
14676
14677 /*
14678 * This shouldn't _actually_ be possible -- we're
14679 * unloading a module that has an enabled probe in it.
14680 * (It's normally up to the provider to make sure that
14681 * this can't happen.) However, because dtps_enable()
14682 * doesn't have a failure mode, there can be an
14683 * enable/unload race. Upshot: we don't want to
14684 * assert, but we're not going to disable the
14685 * probe, either.
14686 */
14687 if (dtrace_err_verbose) {
14688 cmn_err(CE_WARN, "unloaded module '%s' had "
14689 "enabled probes", ctl->mod_modname);
14690 }
14691
14692 return;
14693 }
14694 }
14695
14696 probe = first;
14697
14698 for (first = NULL; probe != NULL; probe = next) {
14699 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
14700
14701 dtrace_probes[probe->dtpr_id - 1] = NULL;
14702
14703 next = probe->dtpr_nextmod;
14704 dtrace_hash_remove(dtrace_bymod, probe);
14705 dtrace_hash_remove(dtrace_byfunc, probe);
14706 dtrace_hash_remove(dtrace_byname, probe);
14707
14708 if (first == NULL) {
14709 first = probe;
14710 probe->dtpr_nextmod = NULL;
14711 } else {
14712 probe->dtpr_nextmod = first;
14713 first = probe;
14714 }
14715 }
14716
14717 /*
14718 * We've removed all of the module's probes from the hash chains and
14719 * from the probe array. Now issue a dtrace_sync() to be sure that
14720 * everyone has cleared out from any probe array processing.
14721 */
14722 dtrace_sync();
14723
14724 for (probe = first; probe != NULL; probe = first) {
14725 first = probe->dtpr_nextmod;
14726 prov = probe->dtpr_provider;
14727 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
14728 probe->dtpr_arg);
14729 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
14730 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
14731 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
14732 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
14733 kmem_free(probe, sizeof (dtrace_probe_t));
14734 }
14735
14736 mutex_exit(&dtrace_lock);
14737 mutex_exit(&mod_lock);
14738 mutex_exit(&dtrace_provider_lock);
14739}
14740
14741#endif /* !VBOX */
14742
14743VBDTSTATIC void
14744dtrace_suspend(void)
14745{
14746 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14747}
14748
14749VBDTSTATIC void
14750dtrace_resume(void)
14751{
14752 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14753}
14754
14755#ifdef VBOX
14756typedef enum {
14757 CPU_INVALID,
14758 CPU_CONFIG,
14759 CPU_UNCONFIG
14760} cpu_setup_t;
14761#endif
14762
14763
14764static int
14765dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14766{
14767 ASSERT(MUTEX_HELD(&cpu_lock));
14768 mutex_enter(&dtrace_lock);
14769
14770 switch (what) {
14771 case CPU_CONFIG: {
14772 dtrace_state_t *state;
14773 dtrace_optval_t *opt, rs, c;
14774
14775 /*
14776 * For now, we only allocate a new buffer for anonymous state.
14777 */
14778 if ((state = dtrace_anon.dta_state) == NULL)
14779 break;
14780
14781 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14782 break;
14783
14784 opt = state->dts_options;
14785 c = opt[DTRACEOPT_CPU];
14786
14787 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14788 break;
14789
14790 /*
14791 * Regardless of what the actual policy is, we're going to
14792 * temporarily set our resize policy to be manual. We're
14793 * also going to temporarily set our CPU option to denote
14794 * the newly configured CPU.
14795 */
14796 rs = opt[DTRACEOPT_BUFRESIZE];
14797 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14798 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14799
14800 (void) dtrace_state_buffers(state);
14801
14802 opt[DTRACEOPT_BUFRESIZE] = rs;
14803 opt[DTRACEOPT_CPU] = c;
14804
14805 break;
14806 }
14807
14808 case CPU_UNCONFIG:
14809 /*
14810 * We don't free the buffer in the CPU_UNCONFIG case. (The
14811 * buffer will be freed when the consumer exits.)
14812 */
14813 break;
14814
14815 default:
14816 break;
14817 }
14818
14819 mutex_exit(&dtrace_lock);
14820 return (0);
14821}
14822
14823#ifndef VBOX
14824static void
14825dtrace_cpu_setup_initial(processorid_t cpu)
14826{
14827 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14828}
14829#endif /* !VBOX */
14830
14831static void
14832dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14833{
14834 if (dtrace_toxranges >= dtrace_toxranges_max) {
14835 int osize, nsize;
14836 dtrace_toxrange_t *range;
14837
14838 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14839
14840 if (osize == 0) {
14841 ASSERT(dtrace_toxrange == NULL);
14842 ASSERT(dtrace_toxranges_max == 0);
14843 dtrace_toxranges_max = 1;
14844 } else {
14845 dtrace_toxranges_max <<= 1;
14846 }
14847
14848 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14849 range = kmem_zalloc(nsize, KM_SLEEP);
14850
14851 if (dtrace_toxrange != NULL) {
14852 ASSERT(osize != 0);
14853 bcopy(dtrace_toxrange, range, osize);
14854 kmem_free(dtrace_toxrange, osize);
14855 }
14856
14857 dtrace_toxrange = range;
14858 }
14859
14860 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14861 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14862
14863 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14864 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14865 dtrace_toxranges++;
14866}
14867
14868/*
14869 * DTrace Driver Cookbook Functions
14870 */
14871#ifdef VBOX
14872int dtrace_attach(void)
14873#else
14874/*ARGSUSED*/
14875static int
14876dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14877#endif
14878{
14879 dtrace_provider_id_t id;
14880 dtrace_state_t *state = NULL;
14881 dtrace_enabling_t *enab;
14882
14883#ifdef VBOX
14884 if ( VBoxDtMutexInit(&dtrace_lock)
14885 || VBoxDtMutexInit(&dtrace_provider_lock)
14886 || VBoxDtMutexInit(&dtrace_meta_lock)
14887# ifdef DEBUG
14888 || VBoxDtMutexInit(&dtrace_errlock)
14889# endif
14890 )
14891 return (DDI_FAILURE);
14892#endif
14893
14894 mutex_enter(&cpu_lock);
14895 mutex_enter(&dtrace_provider_lock);
14896 mutex_enter(&dtrace_lock);
14897
14898#ifndef VBOX
14899 if (ddi_soft_state_init(&dtrace_softstate,
14900 sizeof (dtrace_state_t), 0) != 0) {
14901 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14902 mutex_exit(&cpu_lock);
14903 mutex_exit(&dtrace_provider_lock);
14904 mutex_exit(&dtrace_lock);
14905 return (DDI_FAILURE);
14906 }
14907
14908 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14909 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14910 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14911 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14912 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14913 ddi_remove_minor_node(devi, NULL);
14914 ddi_soft_state_fini(&dtrace_softstate);
14915 mutex_exit(&cpu_lock);
14916 mutex_exit(&dtrace_provider_lock);
14917 mutex_exit(&dtrace_lock);
14918 return (DDI_FAILURE);
14919 }
14920
14921 ddi_report_dev(devi);
14922 dtrace_devi = devi;
14923
14924 dtrace_modload = dtrace_module_loaded;
14925 dtrace_modunload = dtrace_module_unloaded;
14926 dtrace_cpu_init = dtrace_cpu_setup_initial;
14927 dtrace_helpers_cleanup = dtrace_helpers_destroy;
14928 dtrace_helpers_fork = dtrace_helpers_duplicate;
14929 dtrace_cpustart_init = dtrace_suspend;
14930 dtrace_cpustart_fini = dtrace_resume;
14931 dtrace_debugger_init = dtrace_suspend;
14932 dtrace_debugger_fini = dtrace_resume;
14933
14934 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14935#else
14936 /** @todo some of these hooks needs checking out! */
14937#endif
14938
14939 ASSERT(MUTEX_HELD(&cpu_lock));
14940
14941#ifndef VBOX /* Reduce the area a bit just to be sure our vmem fake doesn't blow up. */
14942 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14943 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14944#else
14945 dtrace_arena = vmem_create("dtrace", (void *)(uintptr_t)1, UINT32_MAX - 16, 1,
14946 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14947#endif
14948#ifndef VBOX
14949 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14950 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14951 VM_SLEEP | VMC_IDENTIFIER);
14952 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14953 1, INT_MAX, 0);
14954#endif
14955
14956 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14957 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14958 NULL, NULL, NULL, NULL, NULL, 0);
14959
14960 ASSERT(MUTEX_HELD(&cpu_lock));
14961 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14962 offsetof(dtrace_probe_t, dtpr_nextmod),
14963 offsetof(dtrace_probe_t, dtpr_prevmod));
14964
14965 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14966 offsetof(dtrace_probe_t, dtpr_nextfunc),
14967 offsetof(dtrace_probe_t, dtpr_prevfunc));
14968
14969 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14970 offsetof(dtrace_probe_t, dtpr_nextname),
14971 offsetof(dtrace_probe_t, dtpr_prevname));
14972
14973 if (dtrace_retain_max < 1) {
14974 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14975 "setting to 1", dtrace_retain_max);
14976 dtrace_retain_max = 1;
14977 }
14978
14979 /*
14980 * Now discover our toxic ranges.
14981 */
14982 dtrace_toxic_ranges(dtrace_toxrange_add);
14983
14984 /*
14985 * Before we register ourselves as a provider to our own framework,
14986 * we would like to assert that dtrace_provider is NULL -- but that's
14987 * not true if we were loaded as a dependency of a DTrace provider.
14988 * Once we've registered, we can assert that dtrace_provider is our
14989 * pseudo provider.
14990 */
14991 (void) dtrace_register("dtrace", &dtrace_provider_attr,
14992 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14993
14994 ASSERT(dtrace_provider != NULL);
14995 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14996
14997 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14998 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14999 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15000 dtrace_provider, NULL, NULL, "END", 0, NULL);
15001 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15002 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15003
15004#ifndef VBOX
15005 dtrace_anon_property();
15006#endif
15007 mutex_exit(&cpu_lock);
15008
15009 /*
15010 * If DTrace helper tracing is enabled, we need to allocate the
15011 * trace buffer and initialize the values.
15012 */
15013 if (dtrace_helptrace_enabled) {
15014 ASSERT(dtrace_helptrace_buffer == NULL);
15015 dtrace_helptrace_buffer =
15016 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15017 dtrace_helptrace_next = 0;
15018 }
15019
15020 /*
15021 * If there are already providers, we must ask them to provide their
15022 * probes, and then match any anonymous enabling against them. Note
15023 * that there should be no other retained enablings at this time:
15024 * the only retained enablings at this time should be the anonymous
15025 * enabling.
15026 */
15027 if (dtrace_anon.dta_enabling != NULL) {
15028 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15029
15030 dtrace_enabling_provide(NULL);
15031 state = dtrace_anon.dta_state;
15032
15033 /*
15034 * We couldn't hold cpu_lock across the above call to
15035 * dtrace_enabling_provide(), but we must hold it to actually
15036 * enable the probes. We have to drop all of our locks, pick
15037 * up cpu_lock, and regain our locks before matching the
15038 * retained anonymous enabling.
15039 */
15040 mutex_exit(&dtrace_lock);
15041 mutex_exit(&dtrace_provider_lock);
15042
15043 mutex_enter(&cpu_lock);
15044 mutex_enter(&dtrace_provider_lock);
15045 mutex_enter(&dtrace_lock);
15046
15047 if ((enab = dtrace_anon.dta_enabling) != NULL)
15048 (void) dtrace_enabling_match(enab, NULL);
15049
15050 mutex_exit(&cpu_lock);
15051 }
15052
15053 mutex_exit(&dtrace_lock);
15054 mutex_exit(&dtrace_provider_lock);
15055
15056 if (state != NULL) {
15057 /*
15058 * If we created any anonymous state, set it going now.
15059 */
15060 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15061 }
15062
15063 return (DDI_SUCCESS);
15064}
15065
15066#ifdef VBOX
15067int dtrace_open(dtrace_state_t **ppState, cred_t *cred_p)
15068#else
15069/*ARGSUSED*/
15070static int
15071dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15072#endif
15073{
15074 dtrace_state_t *state;
15075 uint32_t priv;
15076 uid_t uid;
15077 zoneid_t zoneid;
15078
15079#ifndef VBOX
15080 if (getminor(*devp) == DTRACEMNRN_HELPER)
15081 return (0);
15082
15083 /*
15084 * If this wasn't an open with the "helper" minor, then it must be
15085 * the "dtrace" minor.
15086 */
15087 if (getminor(*devp) != DTRACEMNRN_DTRACE)
15088 return (ENXIO);
15089#endif /* !VBOX */
15090
15091 /*
15092 * If no DTRACE_PRIV_* bits are set in the credential, then the
15093 * caller lacks sufficient permission to do anything with DTrace.
15094 */
15095 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15096 if (priv == DTRACE_PRIV_NONE)
15097 return (EACCES);
15098
15099 /*
15100 * Ask all providers to provide all their probes.
15101 */
15102 mutex_enter(&dtrace_provider_lock);
15103 dtrace_probe_provide(NULL, NULL);
15104 mutex_exit(&dtrace_provider_lock);
15105
15106 mutex_enter(&cpu_lock);
15107 mutex_enter(&dtrace_lock);
15108 dtrace_opens++;
15109 dtrace_membar_producer();
15110
15111#ifndef VBOX
15112 /*
15113 * If the kernel debugger is active (that is, if the kernel debugger
15114 * modified text in some way), we won't allow the open.
15115 */
15116 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15117 dtrace_opens--;
15118 mutex_exit(&cpu_lock);
15119 mutex_exit(&dtrace_lock);
15120 return (EBUSY);
15121 }
15122#endif
15123
15124#ifndef VBOX
15125 state = dtrace_state_create(devp, cred_p);
15126#else
15127 state = dtrace_state_create(cred_p);
15128#endif
15129 mutex_exit(&cpu_lock);
15130
15131 if (state == NULL) {
15132#ifndef VBOX
15133 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15134 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15135#else
15136 dtrace_opens--;
15137#endif
15138 mutex_exit(&dtrace_lock);
15139 return (EAGAIN);
15140 }
15141
15142 mutex_exit(&dtrace_lock);
15143
15144#ifdef VBOX
15145 *ppState = state;
15146#endif
15147 return (0);
15148}
15149
15150#ifdef VBOX
15151int dtrace_close(dtrace_state_t *state)
15152#else
15153/*ARGSUSED*/
15154static int
15155dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15156#endif
15157{
15158#ifndef VBOX
15159 minor_t minor = getminor(dev);
15160 dtrace_state_t *state;
15161
15162 if (minor == DTRACEMNRN_HELPER)
15163 return (0);
15164
15165 state = ddi_get_soft_state(dtrace_softstate, minor);
15166#endif
15167
15168 mutex_enter(&cpu_lock);
15169 mutex_enter(&dtrace_lock);
15170
15171 if (state->dts_anon) {
15172 /*
15173 * There is anonymous state. Destroy that first.
15174 */
15175 ASSERT(dtrace_anon.dta_state == NULL);
15176 dtrace_state_destroy(state->dts_anon);
15177 }
15178
15179 dtrace_state_destroy(state);
15180 ASSERT(dtrace_opens > 0);
15181
15182#ifndef VBOX
15183 /*
15184 * Only relinquish control of the kernel debugger interface when there
15185 * are no consumers and no anonymous enablings.
15186 */
15187 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15188 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15189#else
15190 dtrace_opens--;
15191#endif
15192
15193 mutex_exit(&dtrace_lock);
15194 mutex_exit(&cpu_lock);
15195
15196 return (0);
15197}
15198
15199#ifndef VBOX
15200/*ARGSUSED*/
15201static int
15202dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15203{
15204 int rval;
15205 dof_helper_t help, *dhp = NULL;
15206
15207 switch (cmd) {
15208 case DTRACEHIOC_ADDDOF:
15209 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15210 dtrace_dof_error(NULL, "failed to copyin DOF helper");
15211 return (EFAULT);
15212 }
15213
15214 dhp = &help;
15215 arg = (intptr_t)help.dofhp_dof;
15216 /*FALLTHROUGH*/
15217
15218 case DTRACEHIOC_ADD: {
15219 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15220
15221 if (dof == NULL)
15222 return (rval);
15223
15224 mutex_enter(&dtrace_lock);
15225
15226 /*
15227 * dtrace_helper_slurp() takes responsibility for the dof --
15228 * it may free it now or it may save it and free it later.
15229 */
15230 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15231 *rv = rval;
15232 rval = 0;
15233 } else {
15234 rval = EINVAL;
15235 }
15236
15237 mutex_exit(&dtrace_lock);
15238 return (rval);
15239 }
15240
15241 case DTRACEHIOC_REMOVE: {
15242 mutex_enter(&dtrace_lock);
15243 rval = dtrace_helper_destroygen(arg);
15244 mutex_exit(&dtrace_lock);
15245
15246 return (rval);
15247 }
15248
15249 default:
15250 break;
15251 }
15252
15253 return (ENOTTY);
15254}
15255#endif /* !VBOX */
15256
15257#ifdef VBOX
15258int dtrace_ioctl(dtrace_state_t *state, int cmd, intptr_t arg, int32_t *rv)
15259#else
15260/*ARGSUSED*/
15261static int
15262dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15263#endif
15264{
15265#ifndef VBOX
15266 minor_t minor = getminor(dev);
15267 dtrace_state_t *state;
15268#endif
15269 int rval;
15270
15271#ifndef VBOX
15272 if (minor == DTRACEMNRN_HELPER)
15273 return (dtrace_ioctl_helper(cmd, arg, rv));
15274
15275 state = ddi_get_soft_state(dtrace_softstate, minor);
15276#endif
15277
15278 if (state->dts_anon) {
15279 ASSERT(dtrace_anon.dta_state == NULL);
15280 state = state->dts_anon;
15281 }
15282
15283 switch (cmd) {
15284 case DTRACEIOC_PROVIDER: {
15285 dtrace_providerdesc_t pvd;
15286 dtrace_provider_t *pvp;
15287
15288 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15289 return (EFAULT);
15290
15291 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15292 mutex_enter(&dtrace_provider_lock);
15293
15294 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15295 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15296 break;
15297 }
15298
15299 mutex_exit(&dtrace_provider_lock);
15300
15301 if (pvp == NULL)
15302 return (ESRCH);
15303
15304 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15305 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15306 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15307 return (EFAULT);
15308
15309 return (0);
15310 }
15311
15312 case DTRACEIOC_EPROBE: {
15313 dtrace_eprobedesc_t epdesc;
15314 dtrace_ecb_t *ecb;
15315 dtrace_action_t *act;
15316 void *buf;
15317 size_t size;
15318 uintptr_t dest;
15319 int nrecs;
15320
15321 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15322 return (EFAULT);
15323
15324 mutex_enter(&dtrace_lock);
15325
15326 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15327 mutex_exit(&dtrace_lock);
15328 return (EINVAL);
15329 }
15330
15331 if (ecb->dte_probe == NULL) {
15332 mutex_exit(&dtrace_lock);
15333 return (EINVAL);
15334 }
15335
15336 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15337 epdesc.dtepd_uarg = ecb->dte_uarg;
15338 epdesc.dtepd_size = VBDTCAST(uint32_t)ecb->dte_size;
15339
15340 nrecs = epdesc.dtepd_nrecs;
15341 epdesc.dtepd_nrecs = 0;
15342 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15343 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15344 continue;
15345
15346 epdesc.dtepd_nrecs++;
15347 }
15348
15349 /*
15350 * Now that we have the size, we need to allocate a temporary
15351 * buffer in which to store the complete description. We need
15352 * the temporary buffer to be able to drop dtrace_lock()
15353 * across the copyout(), below.
15354 */
15355 size = sizeof (dtrace_eprobedesc_t) +
15356 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15357
15358 buf = kmem_alloc(size, KM_SLEEP);
15359 dest = (uintptr_t)buf;
15360
15361 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
15362 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
15363
15364 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15365 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15366 continue;
15367
15368 if (nrecs-- == 0)
15369 break;
15370
15371 bcopy(&act->dta_rec, (void *)dest,
15372 sizeof (dtrace_recdesc_t));
15373 dest += sizeof (dtrace_recdesc_t);
15374 }
15375
15376 mutex_exit(&dtrace_lock);
15377
15378 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15379 kmem_free(buf, size);
15380 return (EFAULT);
15381 }
15382
15383 kmem_free(buf, size);
15384 return (0);
15385 }
15386
15387 case DTRACEIOC_AGGDESC: {
15388 dtrace_aggdesc_t aggdesc;
15389 dtrace_action_t *act;
15390 dtrace_aggregation_t *agg;
15391 int nrecs;
15392 uint32_t offs;
15393 dtrace_recdesc_t *lrec;
15394 void *buf;
15395 size_t size;
15396 uintptr_t dest;
15397
15398 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
15399 return (EFAULT);
15400
15401 mutex_enter(&dtrace_lock);
15402
15403 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
15404 mutex_exit(&dtrace_lock);
15405 return (EINVAL);
15406 }
15407
15408 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
15409
15410 nrecs = aggdesc.dtagd_nrecs;
15411 aggdesc.dtagd_nrecs = 0;
15412
15413 offs = agg->dtag_base;
15414 lrec = &agg->dtag_action.dta_rec;
15415 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
15416
15417 for (act = agg->dtag_first; ; act = act->dta_next) {
15418 ASSERT(act->dta_intuple ||
15419 DTRACEACT_ISAGG(act->dta_kind));
15420
15421 /*
15422 * If this action has a record size of zero, it
15423 * denotes an argument to the aggregating action.
15424 * Because the presence of this record doesn't (or
15425 * shouldn't) affect the way the data is interpreted,
15426 * we don't copy it out to save user-level the
15427 * confusion of dealing with a zero-length record.
15428 */
15429 if (act->dta_rec.dtrd_size == 0) {
15430 ASSERT(agg->dtag_hasarg);
15431 continue;
15432 }
15433
15434 aggdesc.dtagd_nrecs++;
15435
15436 if (act == &agg->dtag_action)
15437 break;
15438 }
15439
15440 /*
15441 * Now that we have the size, we need to allocate a temporary
15442 * buffer in which to store the complete description. We need
15443 * the temporary buffer to be able to drop dtrace_lock()
15444 * across the copyout(), below.
15445 */
15446 size = sizeof (dtrace_aggdesc_t) +
15447 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
15448
15449 buf = kmem_alloc(size, KM_SLEEP);
15450 dest = (uintptr_t)buf;
15451
15452 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
15453 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
15454
15455 for (act = agg->dtag_first; ; act = act->dta_next) {
15456 dtrace_recdesc_t rec = act->dta_rec;
15457
15458 /*
15459 * See the comment in the above loop for why we pass
15460 * over zero-length records.
15461 */
15462 if (rec.dtrd_size == 0) {
15463 ASSERT(agg->dtag_hasarg);
15464 continue;
15465 }
15466
15467 if (nrecs-- == 0)
15468 break;
15469
15470 rec.dtrd_offset -= offs;
15471 bcopy(&rec, (void *)dest, sizeof (rec));
15472 dest += sizeof (dtrace_recdesc_t);
15473
15474 if (act == &agg->dtag_action)
15475 break;
15476 }
15477
15478 mutex_exit(&dtrace_lock);
15479
15480 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15481 kmem_free(buf, size);
15482 return (EFAULT);
15483 }
15484
15485 kmem_free(buf, size);
15486 return (0);
15487 }
15488
15489 case DTRACEIOC_ENABLE: {
15490 dof_hdr_t *dof;
15491 dtrace_enabling_t *enab = NULL;
15492 dtrace_vstate_t *vstate;
15493 int err = 0;
15494#ifdef VBOX
15495 cred_t *cr = CRED();
15496#endif
15497
15498 *rv = 0;
15499
15500 /*
15501 * If a NULL argument has been passed, we take this as our
15502 * cue to reevaluate our enablings.
15503 */
15504 if (arg == NULL) {
15505 dtrace_enabling_matchall();
15506
15507 return (0);
15508 }
15509
15510 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
15511 return (rval);
15512
15513 mutex_enter(&cpu_lock);
15514 mutex_enter(&dtrace_lock);
15515 vstate = &state->dts_vstate;
15516
15517 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
15518 mutex_exit(&dtrace_lock);
15519 mutex_exit(&cpu_lock);
15520 dtrace_dof_destroy(dof);
15521 return (EBUSY);
15522 }
15523
15524 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
15525 mutex_exit(&dtrace_lock);
15526 mutex_exit(&cpu_lock);
15527 dtrace_dof_destroy(dof);
15528 return (EINVAL);
15529 }
15530
15531 if ((rval = dtrace_dof_options(dof, state)) != 0) {
15532 dtrace_enabling_destroy(enab);
15533 mutex_exit(&dtrace_lock);
15534 mutex_exit(&cpu_lock);
15535 dtrace_dof_destroy(dof);
15536 return (rval);
15537 }
15538
15539 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
15540 err = dtrace_enabling_retain(enab);
15541 } else {
15542 dtrace_enabling_destroy(enab);
15543 }
15544
15545 mutex_exit(&cpu_lock);
15546 mutex_exit(&dtrace_lock);
15547 dtrace_dof_destroy(dof);
15548
15549 return (err);
15550 }
15551
15552 case DTRACEIOC_REPLICATE: {
15553 dtrace_repldesc_t desc;
15554 dtrace_probedesc_t *match = &desc.dtrpd_match;
15555 dtrace_probedesc_t *create = &desc.dtrpd_create;
15556 int err;
15557
15558 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15559 return (EFAULT);
15560
15561 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15562 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15563 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15564 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15565
15566 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15567 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15568 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15569 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15570
15571 mutex_enter(&dtrace_lock);
15572 err = dtrace_enabling_replicate(state, match, create);
15573 mutex_exit(&dtrace_lock);
15574
15575 return (err);
15576 }
15577
15578 case DTRACEIOC_PROBEMATCH:
15579 case DTRACEIOC_PROBES: {
15580 dtrace_probe_t *probe = NULL;
15581 dtrace_probedesc_t desc;
15582 dtrace_probekey_t pkey;
15583 dtrace_id_t i;
15584 int m = 0;
15585 uint32_t priv;
15586 uid_t uid;
15587 zoneid_t zoneid;
15588#ifdef VBOX
15589 cred_t *cr = CRED();
15590#endif
15591
15592 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15593 return (EFAULT);
15594
15595 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15596 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15597 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15598 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15599
15600 /*
15601 * Before we attempt to match this probe, we want to give
15602 * all providers the opportunity to provide it.
15603 */
15604 if (desc.dtpd_id == DTRACE_IDNONE) {
15605 mutex_enter(&dtrace_provider_lock);
15606 dtrace_probe_provide(&desc, NULL);
15607 mutex_exit(&dtrace_provider_lock);
15608 desc.dtpd_id++;
15609 }
15610
15611 if (cmd == DTRACEIOC_PROBEMATCH) {
15612 dtrace_probekey(&desc, &pkey);
15613 pkey.dtpk_id = DTRACE_IDNONE;
15614 }
15615
15616 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
15617
15618 mutex_enter(&dtrace_lock);
15619
15620 if (cmd == DTRACEIOC_PROBEMATCH) {
15621 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15622 if ((probe = dtrace_probes[i - 1]) != NULL &&
15623 (m = dtrace_match_probe(probe, &pkey,
15624 priv, uid, zoneid)) != 0)
15625 break;
15626 }
15627
15628 if (m < 0) {
15629 mutex_exit(&dtrace_lock);
15630 return (EINVAL);
15631 }
15632
15633 } else {
15634 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15635 if ((probe = dtrace_probes[i - 1]) != NULL &&
15636 dtrace_match_priv(probe, priv, uid, zoneid))
15637 break;
15638 }
15639 }
15640
15641 if (probe == NULL) {
15642 mutex_exit(&dtrace_lock);
15643 return (ESRCH);
15644 }
15645
15646 dtrace_probe_description(probe, &desc);
15647 mutex_exit(&dtrace_lock);
15648
15649 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15650 return (EFAULT);
15651
15652 return (0);
15653 }
15654
15655 case DTRACEIOC_PROBEARG: {
15656 dtrace_argdesc_t desc;
15657 dtrace_probe_t *probe;
15658 dtrace_provider_t *prov;
15659
15660 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15661 return (EFAULT);
15662
15663 if (desc.dtargd_id == DTRACE_IDNONE)
15664 return (EINVAL);
15665
15666 if (desc.dtargd_ndx == DTRACE_ARGNONE)
15667 return (EINVAL);
15668
15669 mutex_enter(&dtrace_provider_lock);
15670 mutex_enter(&mod_lock);
15671 mutex_enter(&dtrace_lock);
15672
15673 if (desc.dtargd_id > dtrace_nprobes) {
15674 mutex_exit(&dtrace_lock);
15675 mutex_exit(&mod_lock);
15676 mutex_exit(&dtrace_provider_lock);
15677 return (EINVAL);
15678 }
15679
15680 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
15681 mutex_exit(&dtrace_lock);
15682 mutex_exit(&mod_lock);
15683 mutex_exit(&dtrace_provider_lock);
15684 return (EINVAL);
15685 }
15686
15687 mutex_exit(&dtrace_lock);
15688
15689 prov = probe->dtpr_provider;
15690
15691 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
15692 /*
15693 * There isn't any typed information for this probe.
15694 * Set the argument number to DTRACE_ARGNONE.
15695 */
15696 desc.dtargd_ndx = DTRACE_ARGNONE;
15697 } else {
15698 desc.dtargd_native[0] = '\0';
15699 desc.dtargd_xlate[0] = '\0';
15700 desc.dtargd_mapping = desc.dtargd_ndx;
15701
15702 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
15703 probe->dtpr_id, probe->dtpr_arg, &desc);
15704 }
15705
15706 mutex_exit(&mod_lock);
15707 mutex_exit(&dtrace_provider_lock);
15708
15709 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15710 return (EFAULT);
15711
15712 return (0);
15713 }
15714
15715 case DTRACEIOC_GO: {
15716 processorid_t cpuid;
15717 rval = dtrace_state_go(state, &cpuid);
15718
15719 if (rval != 0)
15720 return (rval);
15721
15722 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15723 return (EFAULT);
15724
15725 return (0);
15726 }
15727
15728 case DTRACEIOC_STOP: {
15729 processorid_t cpuid;
15730
15731 mutex_enter(&dtrace_lock);
15732 rval = dtrace_state_stop(state, &cpuid);
15733 mutex_exit(&dtrace_lock);
15734
15735 if (rval != 0)
15736 return (rval);
15737
15738 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15739 return (EFAULT);
15740
15741 return (0);
15742 }
15743
15744 case DTRACEIOC_DOFGET: {
15745 dof_hdr_t hdr, *dof;
15746 uint64_t len;
15747
15748 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
15749 return (EFAULT);
15750
15751 mutex_enter(&dtrace_lock);
15752 dof = dtrace_dof_create(state);
15753 mutex_exit(&dtrace_lock);
15754
15755 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
15756 rval = copyout(dof, (void *)arg, len);
15757 dtrace_dof_destroy(dof);
15758
15759 return (rval == 0 ? 0 : EFAULT);
15760 }
15761
15762 case DTRACEIOC_AGGSNAP:
15763 case DTRACEIOC_BUFSNAP: {
15764 dtrace_bufdesc_t desc;
15765 caddr_t cached;
15766 dtrace_buffer_t *buf;
15767
15768 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15769 return (EFAULT);
15770
15771 if (/*VBox value is is unsigned: desc.dtbd_cpu < 0 ||*/ desc.dtbd_cpu >= NCPU)
15772 return (EINVAL);
15773
15774 mutex_enter(&dtrace_lock);
15775
15776 if (cmd == DTRACEIOC_BUFSNAP) {
15777 buf = &state->dts_buffer[desc.dtbd_cpu];
15778 } else {
15779 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
15780 }
15781
15782 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
15783 size_t sz = buf->dtb_offset;
15784
15785 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
15786 mutex_exit(&dtrace_lock);
15787 return (EBUSY);
15788 }
15789
15790 /*
15791 * If this buffer has already been consumed, we're
15792 * going to indicate that there's nothing left here
15793 * to consume.
15794 */
15795 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
15796 mutex_exit(&dtrace_lock);
15797
15798 desc.dtbd_size = 0;
15799 desc.dtbd_drops = 0;
15800 desc.dtbd_errors = 0;
15801 desc.dtbd_oldest = 0;
15802 sz = sizeof (desc);
15803
15804 if (copyout(&desc, (void *)arg, sz) != 0)
15805 return (EFAULT);
15806
15807 return (0);
15808 }
15809
15810 /*
15811 * If this is a ring buffer that has wrapped, we want
15812 * to copy the whole thing out.
15813 */
15814 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
15815 dtrace_buffer_polish(buf);
15816 sz = buf->dtb_size;
15817 }
15818
15819 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
15820 mutex_exit(&dtrace_lock);
15821 return (EFAULT);
15822 }
15823
15824 desc.dtbd_size = sz;
15825 desc.dtbd_drops = buf->dtb_drops;
15826 desc.dtbd_errors = buf->dtb_errors;
15827 desc.dtbd_oldest = buf->dtb_xamot_offset;
15828
15829 mutex_exit(&dtrace_lock);
15830
15831 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15832 return (EFAULT);
15833
15834 buf->dtb_flags |= DTRACEBUF_CONSUMED;
15835
15836 return (0);
15837 }
15838
15839 if (buf->dtb_tomax == NULL) {
15840 ASSERT(buf->dtb_xamot == NULL);
15841 mutex_exit(&dtrace_lock);
15842 return (ENOENT);
15843 }
15844
15845 cached = buf->dtb_tomax;
15846 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15847
15848#ifndef VBOX
15849 dtrace_xcall(desc.dtbd_cpu,
15850 (dtrace_xcall_t)dtrace_buffer_switch, buf);
15851#else
15852 if ((int32_t)desc.dtbd_cpu == DTRACE_CPUALL)
15853 RTMpOnAll(dtrace_buffer_switch_wrapper, buf, NULL);
15854 else
15855 RTMpOnSpecific(desc.dtbd_cpu, dtrace_buffer_switch_wrapper, buf, NULL);
15856#endif
15857
15858 state->dts_errors += buf->dtb_xamot_errors;
15859
15860 /*
15861 * If the buffers did not actually switch, then the cross call
15862 * did not take place -- presumably because the given CPU is
15863 * not in the ready set. If this is the case, we'll return
15864 * ENOENT.
15865 */
15866 if (buf->dtb_tomax == cached) {
15867 ASSERT(buf->dtb_xamot != cached);
15868 mutex_exit(&dtrace_lock);
15869 return (ENOENT);
15870 }
15871
15872 ASSERT(cached == buf->dtb_xamot);
15873
15874 /*
15875 * We have our snapshot; now copy it out.
15876 */
15877 if (copyout(buf->dtb_xamot, desc.dtbd_data,
15878 buf->dtb_xamot_offset) != 0) {
15879 mutex_exit(&dtrace_lock);
15880 return (EFAULT);
15881 }
15882
15883 desc.dtbd_size = buf->dtb_xamot_offset;
15884 desc.dtbd_drops = buf->dtb_xamot_drops;
15885 desc.dtbd_errors = buf->dtb_xamot_errors;
15886 desc.dtbd_oldest = 0;
15887
15888 mutex_exit(&dtrace_lock);
15889
15890 /*
15891 * Finally, copy out the buffer description.
15892 */
15893 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15894 return (EFAULT);
15895
15896 return (0);
15897 }
15898
15899 case DTRACEIOC_CONF: {
15900 dtrace_conf_t conf;
15901
15902 bzero(&conf, sizeof (conf));
15903 conf.dtc_difversion = DIF_VERSION;
15904 conf.dtc_difintregs = DIF_DIR_NREGS;
15905 conf.dtc_diftupregs = DIF_DTR_NREGS;
15906 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15907
15908 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15909 return (EFAULT);
15910
15911 return (0);
15912 }
15913
15914 case DTRACEIOC_STATUS: {
15915 dtrace_status_t stat;
15916 dtrace_dstate_t *dstate;
15917 int i, j;
15918 uint64_t nerrs;
15919
15920 /*
15921 * See the comment in dtrace_state_deadman() for the reason
15922 * for setting dts_laststatus to INT64_MAX before setting
15923 * it to the correct value.
15924 */
15925 state->dts_laststatus = INT64_MAX;
15926 dtrace_membar_producer();
15927 state->dts_laststatus = dtrace_gethrtime();
15928
15929 bzero(&stat, sizeof (stat));
15930
15931 mutex_enter(&dtrace_lock);
15932
15933 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15934 mutex_exit(&dtrace_lock);
15935 return (ENOENT);
15936 }
15937
15938 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15939 stat.dtst_exiting = 1;
15940
15941 nerrs = state->dts_errors;
15942 dstate = &state->dts_vstate.dtvs_dynvars;
15943
15944 for (i = 0; i < NCPU; i++) {
15945 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15946
15947 stat.dtst_dyndrops += dcpu->dtdsc_drops;
15948 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15949 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15950
15951 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15952 stat.dtst_filled++;
15953
15954 nerrs += state->dts_buffer[i].dtb_errors;
15955
15956 for (j = 0; j < state->dts_nspeculations; j++) {
15957 dtrace_speculation_t *spec;
15958 dtrace_buffer_t *buf;
15959
15960 spec = &state->dts_speculations[j];
15961 buf = &spec->dtsp_buffer[i];
15962 stat.dtst_specdrops += buf->dtb_xamot_drops;
15963 }
15964 }
15965
15966 stat.dtst_specdrops_busy = state->dts_speculations_busy;
15967 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15968 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15969 stat.dtst_dblerrors = state->dts_dblerrors;
15970 stat.dtst_killed =
15971 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15972 stat.dtst_errors = nerrs;
15973
15974 mutex_exit(&dtrace_lock);
15975
15976 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15977 return (EFAULT);
15978
15979 return (0);
15980 }
15981
15982 case DTRACEIOC_FORMAT: {
15983 dtrace_fmtdesc_t fmt;
15984 char *str;
15985 int len;
15986
15987 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15988 return (EFAULT);
15989
15990 mutex_enter(&dtrace_lock);
15991
15992 if (fmt.dtfd_format == 0 ||
15993 fmt.dtfd_format > state->dts_nformats) {
15994 mutex_exit(&dtrace_lock);
15995 return (EINVAL);
15996 }
15997
15998 /*
15999 * Format strings are allocated contiguously and they are
16000 * never freed; if a format index is less than the number
16001 * of formats, we can assert that the format map is non-NULL
16002 * and that the format for the specified index is non-NULL.
16003 */
16004 ASSERT(state->dts_formats != NULL);
16005 str = state->dts_formats[fmt.dtfd_format - 1];
16006 ASSERT(str != NULL);
16007
16008 len = VBDTCAST(int)strlen(str) + 1;
16009
16010 if (len > fmt.dtfd_length) {
16011 fmt.dtfd_length = len;
16012
16013 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16014 mutex_exit(&dtrace_lock);
16015 return (EINVAL);
16016 }
16017 } else {
16018 if (copyout(str, fmt.dtfd_string, len) != 0) {
16019 mutex_exit(&dtrace_lock);
16020 return (EINVAL);
16021 }
16022 }
16023
16024 mutex_exit(&dtrace_lock);
16025 return (0);
16026 }
16027
16028 default:
16029 break;
16030 }
16031
16032 return (ENOTTY);
16033}
16034
16035#ifdef VBOX
16036int dtrace_detach(void)
16037#else
16038/*ARGSUSED*/
16039static int
16040dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16041#endif
16042{
16043 dtrace_state_t *state;
16044
16045#ifndef VBOX
16046 switch (cmd) {
16047 case DDI_DETACH:
16048 break;
16049
16050 case DDI_SUSPEND:
16051 return (DDI_SUCCESS);
16052
16053 default:
16054 return (DDI_FAILURE);
16055 }
16056#endif
16057
16058 mutex_enter(&cpu_lock);
16059 mutex_enter(&dtrace_provider_lock);
16060 mutex_enter(&dtrace_lock);
16061
16062 ASSERT(dtrace_opens == 0);
16063
16064 if (dtrace_helpers > 0) {
16065 mutex_exit(&dtrace_provider_lock);
16066 mutex_exit(&dtrace_lock);
16067 mutex_exit(&cpu_lock);
16068 return (DDI_FAILURE);
16069 }
16070
16071 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16072 mutex_exit(&dtrace_provider_lock);
16073 mutex_exit(&dtrace_lock);
16074 mutex_exit(&cpu_lock);
16075 return (DDI_FAILURE);
16076 }
16077
16078 dtrace_provider = NULL;
16079
16080 if ((state = dtrace_anon_grab()) != NULL) {
16081 /*
16082 * If there were ECBs on this state, the provider should
16083 * have not been allowed to detach; assert that there is
16084 * none.
16085 */
16086 ASSERT(state->dts_necbs == 0);
16087 dtrace_state_destroy(state);
16088
16089#ifndef VBOX
16090 /*
16091 * If we're being detached with anonymous state, we need to
16092 * indicate to the kernel debugger that DTrace is now inactive.
16093 */
16094 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16095#endif
16096 }
16097
16098 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16099#ifndef VBOX /** @todo CPU hooks */
16100 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16101 dtrace_cpu_init = NULL;
16102 dtrace_helpers_cleanup = NULL;
16103 dtrace_helpers_fork = NULL;
16104 dtrace_cpustart_init = NULL;
16105 dtrace_cpustart_fini = NULL;
16106 dtrace_debugger_init = NULL;
16107 dtrace_debugger_fini = NULL;
16108 dtrace_modload = NULL;
16109 dtrace_modunload = NULL;
16110#endif
16111
16112 mutex_exit(&cpu_lock);
16113
16114 if (dtrace_helptrace_enabled) {
16115 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16116 dtrace_helptrace_buffer = NULL;
16117 }
16118
16119 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16120 dtrace_probes = NULL;
16121 dtrace_nprobes = 0;
16122
16123 dtrace_hash_destroy(dtrace_bymod);
16124 dtrace_hash_destroy(dtrace_byfunc);
16125 dtrace_hash_destroy(dtrace_byname);
16126 dtrace_bymod = NULL;
16127 dtrace_byfunc = NULL;
16128 dtrace_byname = NULL;
16129
16130 kmem_cache_destroy(dtrace_state_cache);
16131#ifndef VBOX
16132 vmem_destroy(dtrace_minor);
16133#endif
16134 vmem_destroy(dtrace_arena);
16135
16136 if (dtrace_toxrange != NULL) {
16137 kmem_free(dtrace_toxrange,
16138 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16139 dtrace_toxrange = NULL;
16140 dtrace_toxranges = 0;
16141 dtrace_toxranges_max = 0;
16142 }
16143
16144#ifndef VBOX
16145 ddi_remove_minor_node(dtrace_devi, NULL);
16146 dtrace_devi = NULL;
16147
16148 ddi_soft_state_fini(&dtrace_softstate);
16149#endif
16150
16151 ASSERT(dtrace_vtime_references == 0);
16152 ASSERT(dtrace_opens == 0);
16153 ASSERT(dtrace_retained == NULL);
16154
16155 mutex_exit(&dtrace_lock);
16156 mutex_exit(&dtrace_provider_lock);
16157#ifdef VBOX
16158 VBoxDtMutexDelete(&dtrace_lock);
16159 VBoxDtMutexDelete(&dtrace_provider_lock);
16160 VBoxDtMutexDelete(&dtrace_meta_lock);
16161# ifdef DEBUG
16162 VBoxDtMutexDelete(&dtrace_errlock);
16163# endif
16164#endif
16165
16166 /*
16167 * We don't destroy the task queue until after we have dropped our
16168 * locks (taskq_destroy() may block on running tasks). To prevent
16169 * attempting to do work after we have effectively detached but before
16170 * the task queue has been destroyed, all tasks dispatched via the
16171 * task queue must check that DTrace is still attached before
16172 * performing any operation.
16173 */
16174#ifndef VBOX
16175 taskq_destroy(dtrace_taskq);
16176 dtrace_taskq = NULL;
16177#endif
16178
16179 return (DDI_SUCCESS);
16180}
16181
16182#ifndef VBOX
16183/*ARGSUSED*/
16184static int
16185dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16186{
16187 int error;
16188
16189 switch (infocmd) {
16190 case DDI_INFO_DEVT2DEVINFO:
16191 *result = (void *)dtrace_devi;
16192 error = DDI_SUCCESS;
16193 break;
16194 case DDI_INFO_DEVT2INSTANCE:
16195 *result = (void *)0;
16196 error = DDI_SUCCESS;
16197 break;
16198 default:
16199 error = DDI_FAILURE;
16200 }
16201 return (error);
16202}
16203
16204static struct cb_ops dtrace_cb_ops = {
16205 dtrace_open, /* open */
16206 dtrace_close, /* close */
16207 nulldev, /* strategy */
16208 nulldev, /* print */
16209 nodev, /* dump */
16210 nodev, /* read */
16211 nodev, /* write */
16212 dtrace_ioctl, /* ioctl */
16213 nodev, /* devmap */
16214 nodev, /* mmap */
16215 nodev, /* segmap */
16216 nochpoll, /* poll */
16217 ddi_prop_op, /* cb_prop_op */
16218 0, /* streamtab */
16219 D_NEW | D_MP /* Driver compatibility flag */
16220};
16221
16222static struct dev_ops dtrace_ops = {
16223 DEVO_REV, /* devo_rev */
16224 0, /* refcnt */
16225 dtrace_info, /* get_dev_info */
16226 nulldev, /* identify */
16227 nulldev, /* probe */
16228 dtrace_attach, /* attach */
16229 dtrace_detach, /* detach */
16230 nodev, /* reset */
16231 &dtrace_cb_ops, /* driver operations */
16232 NULL, /* bus operations */
16233 nodev, /* dev power */
16234 ddi_quiesce_not_needed, /* quiesce */
16235};
16236
16237static struct modldrv modldrv = {
16238 &mod_driverops, /* module type (this is a pseudo driver) */
16239 "Dynamic Tracing", /* name of module */
16240 &dtrace_ops, /* driver ops */
16241};
16242
16243static struct modlinkage modlinkage = {
16244 MODREV_1,
16245 (void *)&modldrv,
16246 NULL
16247};
16248
16249int
16250_init(void)
16251{
16252 return (mod_install(&modlinkage));
16253}
16254
16255int
16256_info(struct modinfo *modinfop)
16257{
16258 return (mod_info(&modlinkage, modinfop));
16259}
16260
16261int
16262_fini(void)
16263{
16264 return (mod_remove(&modlinkage));
16265}
16266
16267#endif /* !VBOX */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette